(() => {
var chart_default = `<html lang="en">
<head>
<title>Ample Chart</title>
</head>
<body>
<div class="chart-container">
<canvas id="chart"></canvas>
</div>
<script>(() => {
var __defProp = Object.defineProperty;
var __export = (target, all2) => {
for (var name in all2)
__defProp(target, name, { get: all2[name], enumerable: !0 });
};
// common-utils/embed-ui.js
function showEmbedLoader() {
let overlay = document.createElement("div");
overlay.id = "embed-loader-overlay", overlay.style.cssText = \`
position: fixed;
top: 0;
left: 0;
width: 100%;
/*height: 100%;*/
background-color: rgba(0, 0, 0, 0.5);
z-index: 9998;
animation: fadeIn 0.3s ease-in-out;
\`;
let loader = document.createElement("div");
loader.id = "embed-loader", loader.style.cssText = \`
position: fixed;
left: 50%;
transform: translate(-50%, 0%);
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
z-index: 9999;
\`;
let keyframes = document.createElement("style");
keyframes.textContent = \`
@keyframes spin {
0% { transform: translate(-50%, -50%) rotate(0deg); }
100% { transform: translate(-50%, -50%) rotate(360deg); }
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
\`, document.head.appendChild(keyframes), document.body.appendChild(overlay), document.body.appendChild(loader), overlay.style.display = "none", loader.style.display = "none", setTimeout(() => {
document.getElementById("embed-loader") && (loader.style.display = "block"), document.getElementById("embed-loader-overlay") && (overlay.style.display = "block");
}, 240);
}
function hideEmbedLoader() {
let loader = document.getElementById("embed-loader"), overlay = document.getElementById("embed-loader-overlay");
loader && loader.remove(), overlay && overlay.remove();
}
// node_modules/@ungap/structured-clone/esm/deserialize.js
var env = typeof self == "object" ? self : globalThis, deserializer = ($2, _) => {
let as = (out, index2) => ($2.set(index2, out), out), unpair = (index2) => {
if ($2.has(index2))
return $2.get(index2);
let [type, value] = _[index2];
switch (type) {
case 0:
case -1:
return as(value, index2);
case 1: {
let arr = as([], index2);
for (let index3 of value)
arr.push(unpair(index3));
return arr;
}
case 2: {
let object = as({}, index2);
for (let [key, index3] of value)
object[unpair(key)] = unpair(index3);
return object;
}
case 3:
return as(new Date(value), index2);
case 4: {
let { source, flags } = value;
return as(new RegExp(source, flags), index2);
}
case 5: {
let map4 = as(/* @__PURE__ */ new Map(), index2);
for (let [key, index3] of value)
map4.set(unpair(key), unpair(index3));
return map4;
}
case 6: {
let set = as(/* @__PURE__ */ new Set(), index2);
for (let index3 of value)
set.add(unpair(index3));
return set;
}
case 7: {
let { name, message } = value;
return as(new env[name](message), index2);
}
case 8:
return as(BigInt(value), index2);
case "BigInt":
return as(Object(BigInt(value)), index2);
}
return as(new env[type](value), index2);
};
return unpair;
}, deserialize = (serialized) => deserializer(/* @__PURE__ */ new Map(), serialized)(0);
// node_modules/@ungap/structured-clone/esm/serialize.js
var EMPTY = "", { toString } = {}, { keys } = Object, typeOf = (value) => {
let type = typeof value;
if (type !== "object" || !value)
return [0, type];
let asString = toString.call(value).slice(8, -1);
switch (asString) {
case "Array":
return [1, EMPTY];
case "Object":
return [2, EMPTY];
case "Date":
return [3, EMPTY];
case "RegExp":
return [4, EMPTY];
case "Map":
return [5, EMPTY];
case "Set":
return [6, EMPTY];
}
return asString.includes("Array") ? [1, asString] : asString.includes("Error") ? [7, asString] : [2, asString];
}, shouldSkip = ([TYPE, type]) => TYPE === 0 && (type === "function" || type === "symbol"), serializer = (strict, json, $2, _) => {
let as = (out, value) => {
let index2 = _.push(out) - 1;
return $2.set(value, index2), index2;
}, pair = (value) => {
if ($2.has(value))
return $2.get(value);
let [TYPE, type] = typeOf(value);
switch (TYPE) {
case 0: {
let entry = value;
switch (type) {
case "bigint":
TYPE = 8, entry = value.toString();
break;
case "function":
case "symbol":
if (strict)
throw new TypeError("unable to serialize " + type);
entry = null;
break;
case "undefined":
return as([-1], value);
}
return as([TYPE, entry], value);
}
case 1: {
if (type)
return as([type, [...value]], value);
let arr = [], index2 = as([TYPE, arr], value);
for (let entry of value)
arr.push(pair(entry));
return index2;
}
case 2: {
if (type)
switch (type) {
case "BigInt":
return as([type, value.toString()], value);
case "Boolean":
case "Number":
case "String":
return as([type, value.valueOf()], value);
}
if (json && "toJSON" in value)
return pair(value.toJSON());
let entries = [], index2 = as([TYPE, entries], value);
for (let key of keys(value))
(strict || !shouldSkip(typeOf(value[key]))) && entries.push([pair(key), pair(value[key])]);
return index2;
}
case 3:
return as([TYPE, value.toISOString()], value);
case 4: {
let { source, flags } = value;
return as([TYPE, { source, flags }], value);
}
case 5: {
let entries = [], index2 = as([TYPE, entries], value);
for (let [key, entry] of value)
(strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry)))) && entries.push([pair(key), pair(entry)]);
return index2;
}
case 6: {
let entries = [], index2 = as([TYPE, entries], value);
for (let entry of value)
(strict || !shouldSkip(typeOf(entry))) && entries.push(pair(entry));
return index2;
}
}
let { message } = value;
return as([TYPE, { name: type, message }], value);
};
return pair;
}, serialize = (value, { json, lossy } = {}) => {
let _ = [];
return serializer(!(json || lossy), !!json, /* @__PURE__ */ new Map(), _)(value), _;
};
// node_modules/@ungap/structured-clone/esm/index.js
var esm_default = typeof structuredClone == "function" ? (
/* c8 ignore start */
(any, options) => options && ("json" in options || "lossy" in options) ? deserialize(serialize(any, options)) : structuredClone(any)
) : (any, options) => deserialize(serialize(any, options));
// node_modules/bail/index.js
function bail(error) {
if (error)
throw error;
}
// node_modules/is-plain-obj/index.js
function isPlainObject(value) {
if (typeof value != "object" || value === null)
return !1;
let prototype = Object.getPrototypeOf(value);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
}
// node_modules/trough/lib/index.js
function trough() {
let fns = [], pipeline = { run, use };
return pipeline;
function run(...values) {
let middlewareIndex = -1, callback = values.pop();
if (typeof callback != "function")
throw new TypeError("Expected function as last argument, not " + callback);
next(null, ...values);
function next(error, ...output) {
let fn = fns[++middlewareIndex], index2 = -1;
if (error) {
callback(error);
return;
}
for (; ++index2 < values.length; )
(output[index2] === null || output[index2] === void 0) && (output[index2] = values[index2]);
values = output, fn ? wrap(fn, next)(...output) : callback(null, ...output);
}
}
function use(middelware) {
if (typeof middelware != "function")
throw new TypeError(
"Expected \`middelware\` to be a function, not " + middelware
);
return fns.push(middelware), pipeline;
}
}
function wrap(middleware, callback) {
let called;
return wrapped;
function wrapped(...parameters) {
let fnExpectsCallback = middleware.length > parameters.length, result;
fnExpectsCallback && parameters.push(done);
try {
result = middleware.apply(this, parameters);
} catch (error) {
let exception = (
/** @type {Error} */
error
);
if (fnExpectsCallback && called)
throw exception;
return done(exception);
}
fnExpectsCallback || (result && result.then && typeof result.then == "function" ? result.then(then, done) : result instanceof Error ? done(result) : then(result));
}
function done(error, ...output) {
called || (called = !0, callback(error, ...output));
}
function then(value) {
done(null, value);
}
}
// node_modules/unist-util-stringify-position/lib/index.js
function stringifyPosition(value) {
return !value || typeof value != "object" ? "" : "position" in value || "type" in value ? position(value.position) : "start" in value || "end" in value ? position(value) : "line" in value || "column" in value ? point(value) : "";
}
function point(point3) {
return index(point3 && point3.line) + ":" + index(point3 && point3.column);
}
function position(pos) {
return point(pos && pos.start) + "-" + point(pos && pos.end);
}
function index(value) {
return value && typeof value == "number" ? value : 1;
}
// node_modules/vfile-message/lib/index.js
var VFileMessage = class extends Error {
/**
* Create a message for \`reason\`.
*
* > \u{1FAA6} **Note**: also has obsolete signatures.
*
* @overload
* @param {string} reason
* @param {Options | null | undefined} [options]
* @returns
*
* @overload
* @param {string} reason
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {string} reason
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {string} reason
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns
*
* @overload
* @param {Error | VFileMessage} cause
* @param {string | null | undefined} [origin]
* @returns
*
* @param {Error | VFileMessage | string} causeOrReason
* Reason for message, should use markdown.
* @param {Node | NodeLike | Options | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
* Configuration (optional).
* @param {string | null | undefined} [origin]
* Place in code where the message originates (example:
* \`'my-package:my-rule'\` or \`'my-rule'\`).
* @returns
* Instance of \`VFileMessage\`.
*/
// eslint-disable-next-line complexity
constructor(causeOrReason, optionsOrParentOrPlace, origin) {
super(), typeof optionsOrParentOrPlace == "string" && (origin = optionsOrParentOrPlace, optionsOrParentOrPlace = void 0);
let reason = "", options = {}, legacyCause = !1;
if (optionsOrParentOrPlace && ("line" in optionsOrParentOrPlace && "column" in optionsOrParentOrPlace ? options = { place: optionsOrParentOrPlace } : "start" in optionsOrParentOrPlace && "end" in optionsOrParentOrPlace ? options = { place: optionsOrParentOrPlace } : "type" in optionsOrParentOrPlace ? options = {
ancestors: [optionsOrParentOrPlace],
place: optionsOrParentOrPlace.position
} : options = { ...optionsOrParentOrPlace }), typeof causeOrReason == "string" ? reason = causeOrReason : !options.cause && causeOrReason && (legacyCause = !0, reason = causeOrReason.message, options.cause = causeOrReason), !options.ruleId && !options.source && typeof origin == "string") {
let index2 = origin.indexOf(":");
index2 === -1 ? options.ruleId = origin : (options.source = origin.slice(0, index2), options.ruleId = origin.slice(index2 + 1));
}
if (!options.place && options.ancestors && options.ancestors) {
let parent = options.ancestors[options.ancestors.length - 1];
parent && (options.place = parent.position);
}
let start = options.place && "start" in options.place ? options.place.start : options.place;
this.ancestors = options.ancestors || void 0, this.cause = options.cause || void 0, this.column = start ? start.column : void 0, this.fatal = void 0, this.file, this.message = reason, this.line = start ? start.line : void 0, this.name = stringifyPosition(options.place) || "1:1", this.place = options.place || void 0, this.reason = this.message, this.ruleId = options.ruleId || void 0, this.source = options.source || void 0, this.stack = legacyCause && options.cause && typeof options.cause.stack == "string" ? options.cause.stack : "", this.actual, this.expected, this.note, this.url;
}
};
VFileMessage.prototype.file = "";
VFileMessage.prototype.name = "";
VFileMessage.prototype.reason = "";
VFileMessage.prototype.message = "";
VFileMessage.prototype.stack = "";
VFileMessage.prototype.column = void 0;
VFileMessage.prototype.line = void 0;
VFileMessage.prototype.ancestors = void 0;
VFileMessage.prototype.cause = void 0;
VFileMessage.prototype.fatal = void 0;
VFileMessage.prototype.place = void 0;
VFileMessage.prototype.ruleId = void 0;
VFileMessage.prototype.source = void 0;
// node_modules/vfile/lib/minpath.browser.js
var minpath = { basename, dirname, extname, join, sep: "/" };
function basename(path2, extname2) {
if (extname2 !== void 0 && typeof extname2 != "string")
throw new TypeError('"ext" argument must be a string');
assertPath(path2);
let start = 0, end = -1, index2 = path2.length, seenNonSlash;
if (extname2 === void 0 || extname2.length === 0 || extname2.length > path2.length) {
for (; index2--; )
if (path2.codePointAt(index2) === 47) {
if (seenNonSlash) {
start = index2 + 1;
break;
}
} else end < 0 && (seenNonSlash = !0, end = index2 + 1);
return end < 0 ? "" : path2.slice(start, end);
}
if (extname2 === path2)
return "";
let firstNonSlashEnd = -1, extnameIndex = extname2.length - 1;
for (; index2--; )
if (path2.codePointAt(index2) === 47) {
if (seenNonSlash) {
start = index2 + 1;
break;
}
} else
firstNonSlashEnd < 0 && (seenNonSlash = !0, firstNonSlashEnd = index2 + 1), extnameIndex > -1 && (path2.codePointAt(index2) === extname2.codePointAt(extnameIndex--) ? extnameIndex < 0 && (end = index2) : (extnameIndex = -1, end = firstNonSlashEnd));
return start === end ? end = firstNonSlashEnd : end < 0 && (end = path2.length), path2.slice(start, end);
}
function dirname(path2) {
if (assertPath(path2), path2.length === 0)
return ".";
let end = -1, index2 = path2.length, unmatchedSlash;
for (; --index2; )
if (path2.codePointAt(index2) === 47) {
if (unmatchedSlash) {
end = index2;
break;
}
} else unmatchedSlash || (unmatchedSlash = !0);
return end < 0 ? path2.codePointAt(0) === 47 ? "/" : "." : end === 1 && path2.codePointAt(0) === 47 ? "//" : path2.slice(0, end);
}
function extname(path2) {
assertPath(path2);
let index2 = path2.length, end = -1, startPart = 0, startDot = -1, preDotState = 0, unmatchedSlash;
for (; index2--; ) {
let code3 = path2.codePointAt(index2);
if (code3 === 47) {
if (unmatchedSlash) {
startPart = index2 + 1;
break;
}
continue;
}
end < 0 && (unmatchedSlash = !0, end = index2 + 1), code3 === 46 ? startDot < 0 ? startDot = index2 : preDotState !== 1 && (preDotState = 1) : startDot > -1 && (preDotState = -1);
}
return startDot < 0 || end < 0 || // We saw a non-dot character immediately before the dot.
preDotState === 0 || // The (right-most) trimmed path component is exactly \`..\`.
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1 ? "" : path2.slice(startDot, end);
}
function join(...segments) {
let index2 = -1, joined;
for (; ++index2 < segments.length; )
assertPath(segments[index2]), segments[index2] && (joined = joined === void 0 ? segments[index2] : joined + "/" + segments[index2]);
return joined === void 0 ? "." : normalize(joined);
}
function normalize(path2) {
assertPath(path2);
let absolute = path2.codePointAt(0) === 47, value = normalizeString(path2, !absolute);
return value.length === 0 && !absolute && (value = "."), value.length > 0 && path2.codePointAt(path2.length - 1) === 47 && (value += "/"), absolute ? "/" + value : value;
}
function normalizeString(path2, allowAboveRoot) {
let result = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, index2 = -1, code3, lastSlashIndex;
for (; ++index2 <= path2.length; ) {
if (index2 < path2.length)
code3 = path2.codePointAt(index2);
else {
if (code3 === 47)
break;
code3 = 47;
}
if (code3 === 47) {
if (!(lastSlash === index2 - 1 || dots === 1))
if (lastSlash !== index2 - 1 && dots === 2) {
if (result.length < 2 || lastSegmentLength !== 2 || result.codePointAt(result.length - 1) !== 46 || result.codePointAt(result.length - 2) !== 46) {
if (result.length > 2) {
if (lastSlashIndex = result.lastIndexOf("/"), lastSlashIndex !== result.length - 1) {
lastSlashIndex < 0 ? (result = "", lastSegmentLength = 0) : (result = result.slice(0, lastSlashIndex), lastSegmentLength = result.length - 1 - result.lastIndexOf("/")), lastSlash = index2, dots = 0;
continue;
}
} else if (result.length > 0) {
result = "", lastSegmentLength = 0, lastSlash = index2, dots = 0;
continue;
}
}
allowAboveRoot && (result = result.length > 0 ? result + "/.." : "..", lastSegmentLength = 2);
} else
result.length > 0 ? result += "/" + path2.slice(lastSlash + 1, index2) : result = path2.slice(lastSlash + 1, index2), lastSegmentLength = index2 - lastSlash - 1;
lastSlash = index2, dots = 0;
} else code3 === 46 && dots > -1 ? dots++ : dots = -1;
}
return result;
}
function assertPath(path2) {
if (typeof path2 != "string")
throw new TypeError(
"Path must be a string. Received " + JSON.stringify(path2)
);
}
// node_modules/vfile/lib/minproc.browser.js
var minproc = { cwd };
function cwd() {
return "/";
}
// node_modules/vfile/lib/minurl.shared.js
function isUrl(fileUrlOrPath) {
return !!(fileUrlOrPath !== null && typeof fileUrlOrPath == "object" && "href" in fileUrlOrPath && fileUrlOrPath.href && "protocol" in fileUrlOrPath && fileUrlOrPath.protocol && // @ts-expect-error: indexing is fine.
fileUrlOrPath.auth === void 0);
}
// node_modules/vfile/lib/minurl.browser.js
function urlToPath(path2) {
if (typeof path2 == "string")
path2 = new URL(path2);
else if (!isUrl(path2)) {
let error = new TypeError(
'The "path" argument must be of type string or an instance of URL. Received \`' + path2 + "\`"
);
throw error.code = "ERR_INVALID_ARG_TYPE", error;
}
if (path2.protocol !== "file:") {
let error = new TypeError("The URL must be of scheme file");
throw error.code = "ERR_INVALID_URL_SCHEME", error;
}
return getPathFromURLPosix(path2);
}
function getPathFromURLPosix(url) {
if (url.hostname !== "") {
let error = new TypeError(
'File URL host must be "localhost" or empty on darwin'
);
throw error.code = "ERR_INVALID_FILE_URL_HOST", error;
}
let pathname = url.pathname, index2 = -1;
for (; ++index2 < pathname.length; )
if (pathname.codePointAt(index2) === 37 && pathname.codePointAt(index2 + 1) === 50) {
let third = pathname.codePointAt(index2 + 2);
if (third === 70 || third === 102) {
let error = new TypeError(
"File URL path must not include encoded / characters"
);
throw error.code = "ERR_INVALID_FILE_URL_PATH", error;
}
}
return decodeURIComponent(pathname);
}
// node_modules/vfile/lib/index.js
var order = (
/** @type {const} */
[
"history",
"path",
"basename",
"stem",
"extname",
"dirname"
]
), VFile = class {
/**
* Create a new virtual file.
*
* \`options\` is treated as:
*
* * \`string\` or \`Uint8Array\` \u2014 \`{value: options}\`
* * \`URL\` \u2014 \`{path: options}\`
* * \`VFile\` \u2014 shallow copies its data over to the new file
* * \`object\` \u2014 all fields are shallow copied over to the new file
*
* Path related fields are set in the following order (least specific to
* most specific): \`history\`, \`path\`, \`basename\`, \`stem\`, \`extname\`,
* \`dirname\`.
*
* You cannot set \`dirname\` or \`extname\` without setting either \`history\`,
* \`path\`, \`basename\`, or \`stem\` too.
*
* @param {Compatible | null | undefined} [value]
* File value.
* @returns
* New instance.
*/
constructor(value) {
let options;
value ? isUrl(value) ? options = { path: value } : typeof value == "string" || isUint8Array(value) ? options = { value } : options = value : options = {}, this.cwd = "cwd" in options ? "" : minproc.cwd(), this.data = {}, this.history = [], this.messages = [], this.value, this.map, this.result, this.stored;
let index2 = -1;
for (; ++index2 < order.length; ) {
let field2 = order[index2];
field2 in options && options[field2] !== void 0 && options[field2] !== null && (this[field2] = field2 === "history" ? [...options[field2]] : options[field2]);
}
let field;
for (field in options)
order.includes(field) || (this[field] = options[field]);
}
/**
* Get the basename (including extname) (example: \`'index.min.js'\`).
*
* @returns {string | undefined}
* Basename.
*/
get basename() {
return typeof this.path == "string" ? minpath.basename(this.path) : void 0;
}
/**
* Set basename (including extname) (\`'index.min.js'\`).
*
* Cannot contain path separators (\`'/'\` on unix, macOS, and browsers, \`'\\'\`
* on windows).
* Cannot be nullified (use \`file.path = file.dirname\` instead).
*
* @param {string} basename
* Basename.
* @returns {undefined}
* Nothing.
*/
set basename(basename2) {
assertNonEmpty(basename2, "basename"), assertPart(basename2, "basename"), this.path = minpath.join(this.dirname || "", basename2);
}
/**
* Get the parent path (example: \`'~'\`).
*
* @returns {string | undefined}
* Dirname.
*/
get dirname() {
return typeof this.path == "string" ? minpath.dirname(this.path) : void 0;
}
/**
* Set the parent path (example: \`'~'\`).
*
* Cannot be set if there\u2019s no \`path\` yet.
*
* @param {string | undefined} dirname
* Dirname.
* @returns {undefined}
* Nothing.
*/
set dirname(dirname2) {
assertPath2(this.basename, "dirname"), this.path = minpath.join(dirname2 || "", this.basename);
}
/**
* Get the extname (including dot) (example: \`'.js'\`).
*
* @returns {string | undefined}
* Extname.
*/
get extname() {
return typeof this.path == "string" ? minpath.extname(this.path) : void 0;
}
/**
* Set the extname (including dot) (example: \`'.js'\`).
*
* Cannot contain path separators (\`'/'\` on unix, macOS, and browsers, \`'\\'\`
* on windows).
* Cannot be set if there\u2019s no \`path\` yet.
*
* @param {string | undefined} extname
* Extname.
* @returns {undefined}
* Nothing.
*/
set extname(extname2) {
if (assertPart(extname2, "extname"), assertPath2(this.dirname, "extname"), extname2) {
if (extname2.codePointAt(0) !== 46)
throw new Error("\`extname\` must start with \`.\`");
if (extname2.includes(".", 1))
throw new Error("\`extname\` cannot contain multiple dots");
}
this.path = minpath.join(this.dirname, this.stem + (extname2 || ""));
}
/**
* Get the full path (example: \`'~/index.min.js'\`).
*
* @returns {string}
* Path.
*/
get path() {
return this.history[this.history.length - 1];
}
/**
* Set the full path (example: \`'~/index.min.js'\`).
*
* Cannot be nullified.
* You can set a file URL (a \`URL\` object with a \`file:\` protocol) which will
* be turned into a path with \`url.fileURLToPath\`.
*
* @param {URL | string} path
* Path.
* @returns {undefined}
* Nothing.
*/
set path(path2) {
isUrl(path2) && (path2 = urlToPath(path2)), assertNonEmpty(path2, "path"), this.path !== path2 && this.history.push(path2);
}
/**
* Get the stem (basename w/o extname) (example: \`'index.min'\`).
*
* @returns {string | undefined}
* Stem.
*/
get stem() {
return typeof this.path == "string" ? minpath.basename(this.path, this.extname) : void 0;
}
/**
* Set the stem (basename w/o extname) (example: \`'index.min'\`).
*
* Cannot contain path separators (\`'/'\` on unix, macOS, and browsers, \`'\\'\`
* on windows).
* Cannot be nullified (use \`file.path = file.dirname\` instead).
*
* @param {string} stem
* Stem.
* @returns {undefined}
* Nothing.
*/
set stem(stem) {
assertNonEmpty(stem, "stem"), assertPart(stem, "stem"), this.path = minpath.join(this.dirname || "", stem + (this.extname || ""));
}
// Normal prototypal methods.
/**
* Create a fatal message for \`reason\` associated with the file.
*
* The \`fatal\` field of the message is set to \`true\` (error; file not usable)
* and the \`file\` field is set to the current file path.
* The message is added to the \`messages\` field on \`file\`.
*
* > \u{1FAA6} **Note**: also has obsolete signatures.
*
* @overload
* @param {string} reason
* @param {MessageOptions | null | undefined} [options]
* @returns {never}
*
* @overload
* @param {string} reason
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {string} reason
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {string} reason
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {string | null | undefined} [origin]
* @returns {never}
*
* @param {Error | VFileMessage | string} causeOrReason
* Reason for message, should use markdown.
* @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
* Configuration (optional).
* @param {string | null | undefined} [origin]
* Place in code where the message originates (example:
* \`'my-package:my-rule'\` or \`'my-rule'\`).
* @returns {never}
* Never.
* @throws {VFileMessage}
* Message.
*/
fail(causeOrReason, optionsOrParentOrPlace, origin) {
let message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
throw message.fatal = !0, message;
}
/**
* Create an info message for \`reason\` associated with the file.
*
* The \`fatal\` field of the message is set to \`undefined\` (info; change
* likely not needed) and the \`file\` field is set to the current file path.
* The message is added to the \`messages\` field on \`file\`.
*
* > \u{1FAA6} **Note**: also has obsolete signatures.
*
* @overload
* @param {string} reason
* @param {MessageOptions | null | undefined} [options]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @param {Error | VFileMessage | string} causeOrReason
* Reason for message, should use markdown.
* @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
* Configuration (optional).
* @param {string | null | undefined} [origin]
* Place in code where the message originates (example:
* \`'my-package:my-rule'\` or \`'my-rule'\`).
* @returns {VFileMessage}
* Message.
*/
info(causeOrReason, optionsOrParentOrPlace, origin) {
let message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
return message.fatal = void 0, message;
}
/**
* Create a message for \`reason\` associated with the file.
*
* The \`fatal\` field of the message is set to \`false\` (warning; change may be
* needed) and the \`file\` field is set to the current file path.
* The message is added to the \`messages\` field on \`file\`.
*
* > \u{1FAA6} **Note**: also has obsolete signatures.
*
* @overload
* @param {string} reason
* @param {MessageOptions | null | undefined} [options]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {string} reason
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Node | NodeLike | null | undefined} parent
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {Point | Position | null | undefined} place
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @overload
* @param {Error | VFileMessage} cause
* @param {string | null | undefined} [origin]
* @returns {VFileMessage}
*
* @param {Error | VFileMessage | string} causeOrReason
* Reason for message, should use markdown.
* @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
* Configuration (optional).
* @param {string | null | undefined} [origin]
* Place in code where the message originates (example:
* \`'my-package:my-rule'\` or \`'my-rule'\`).
* @returns {VFileMessage}
* Message.
*/
message(causeOrReason, optionsOrParentOrPlace, origin) {
let message = new VFileMessage(
// @ts-expect-error: the overloads are fine.
causeOrReason,
optionsOrParentOrPlace,
origin
);
return this.path && (message.name = this.path + ":" + message.name, message.file = this.path), message.fatal = !1, this.messages.push(message), message;
}
/**
* Serialize the file.
*
* > **Note**: which encodings are supported depends on the engine.
* > For info on Node.js, see:
* > <https://nodejs.org/api/util.html#whatwg-supported-encodings>.
*
* @param {string | null | undefined} [encoding='utf8']
* Character encoding to understand \`value\` as when it\u2019s a \`Uint8Array\`
* (default: \`'utf-8'\`).
* @returns {string}
* Serialized file.
*/
toString(encoding) {
return this.value === void 0 ? "" : typeof this.value == "string" ? this.value : new TextDecoder(encoding || void 0).decode(this.value);
}
};
function assertPart(part, name) {
if (part && part.includes(minpath.sep))
throw new Error(
"\`" + name + "\` cannot be a path: did not expect \`" + minpath.sep + "\`"
);
}
function assertNonEmpty(part, name) {
if (!part)
throw new Error("\`" + name + "\` cannot be empty");
}
function assertPath2(path2, name) {
if (!path2)
throw new Error("Setting \`" + name + "\` requires \`path\` to be set too");
}
function isUint8Array(value) {
return !!(value && typeof value == "object" && "byteLength" in value && "byteOffset" in value);
}
// node_modules/unified/lib/callable-instance.js
var CallableInstance = (
/**
* @type {new <Parameters extends Array<unknown>, Result>(property: string | symbol) => (...parameters: Parameters) => Result}
*/
/** @type {unknown} */
/**
* @this {Function}
* @param {string | symbol} property
* @returns {(...parameters: Array<unknown>) => unknown}
*/
function(property) {
let proto = (
/** @type {Record<string | symbol, Function>} */
// Prototypes do exist.
// type-coverage:ignore-next-line
this.constructor.prototype
), func = proto[property], apply = function() {
return func.apply(apply, arguments);
};
Object.setPrototypeOf(apply, proto);
let names = Object.getOwnPropertyNames(func);
for (let p2 of names) {
let descriptor = Object.getOwnPropertyDescriptor(func, p2);
descriptor && Object.defineProperty(apply, p2, descriptor);
}
return apply;
}
);
// node_modules/unified/lib/index.js
var own = {}.hasOwnProperty, Processor = class _Processor extends CallableInstance {
/**
* Create a processor.
*/
constructor() {
super("copy"), this.Compiler = void 0, this.Parser = void 0, this.attachers = [], this.compiler = void 0, this.freezeIndex = -1, this.frozen = void 0, this.namespace = {}, this.parser = void 0, this.transformers = trough();
}
/**
* Copy a processor.
*
* @deprecated
* This is a private internal method and should not be used.
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
* New *unfrozen* processor ({@link Processor \`Processor\`}) that is
* configured to work the same as its ancestor.
* When the descendant processor is configured in the future it does not
* affect the ancestral processor.
*/
copy() {
let destination = (
/** @type {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>} */
new _Processor()
), index2 = -1;
for (; ++index2 < this.attachers.length; ) {
let attacher = this.attachers[index2];
destination.use(...attacher);
}
return destination.data(esm_default(this.namespace)), destination;
}
/**
* Configure the processor with info available to all plugins.
* Information is stored in an object.
*
* Typically, options can be given to a specific plugin, but sometimes it
* makes sense to have information shared with several plugins.
* For example, a list of HTML elements that are self-closing, which is
* needed during all phases.
*
* > \u{1F449} **Note**: setting information cannot occur on *frozen* processors.
* > Call the processor first to create a new unfrozen processor.
*
* > \u{1F449} **Note**: to register custom data in TypeScript, augment the
* > {@link Data \`Data\`} interface.
*
* @example
* This example show how to get and set info:
*
* \`\`\`js
* import {unified} from 'unified'
*
* const processor = unified().data('alpha', 'bravo')
*
* processor.data('alpha') // => 'bravo'
*
* processor.data() // => {alpha: 'bravo'}
*
* processor.data({charlie: 'delta'})
*
* processor.data() // => {charlie: 'delta'}
* \`\`\`
*
* @template {keyof Data} Key
*
* @overload
* @returns {Data}
*
* @overload
* @param {Data} dataset
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
*
* @overload
* @param {Key} key
* @returns {Data[Key]}
*
* @overload
* @param {Key} key
* @param {Data[Key]} value
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
*
* @param {Data | Key} [key]
* Key to get or set, or entire dataset to set, or nothing to get the
* entire dataset (optional).
* @param {Data[Key]} [value]
* Value to set (optional).
* @returns {unknown}
* The current processor when setting, the value at \`key\` when getting, or
* the entire dataset when getting without key.
*/
data(key, value) {
return typeof key == "string" ? arguments.length === 2 ? (assertUnfrozen("data", this.frozen), this.namespace[key] = value, this) : own.call(this.namespace, key) && this.namespace[key] || void 0 : key ? (assertUnfrozen("data", this.frozen), this.namespace = key, this) : this.namespace;
}
/**
* Freeze a processor.
*
* Frozen processors are meant to be extended and not to be configured
* directly.
*
* When a processor is frozen it cannot be unfrozen.
* New processors working the same way can be created by calling the
* processor.
*
* It\u2019s possible to freeze processors explicitly by calling \`.freeze()\`.
* Processors freeze automatically when \`.parse()\`, \`.run()\`, \`.runSync()\`,
* \`.stringify()\`, \`.process()\`, or \`.processSync()\` are called.
*
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
* The current processor.
*/
freeze() {
if (this.frozen)
return this;
let self2 = (
/** @type {Processor} */
/** @type {unknown} */
this
);
for (; ++this.freezeIndex < this.attachers.length; ) {
let [attacher, ...options] = this.attachers[this.freezeIndex];
if (options[0] === !1)
continue;
options[0] === !0 && (options[0] = void 0);
let transformer = attacher.call(self2, ...options);
typeof transformer == "function" && this.transformers.use(transformer);
}
return this.frozen = !0, this.freezeIndex = Number.POSITIVE_INFINITY, this;
}
/**
* Parse text to a syntax tree.
*
* > \u{1F449} **Note**: \`parse\` freezes the processor if not already *frozen*.
*
* > \u{1F449} **Note**: \`parse\` performs the parse phase, not the run phase or other
* > phases.
*
* @param {Compatible | undefined} [file]
* file to parse (optional); typically \`string\` or \`VFile\`; any value
* accepted as \`x\` in \`new VFile(x)\`.
* @returns {ParseTree extends undefined ? Node : ParseTree}
* Syntax tree representing \`file\`.
*/
parse(file) {
this.freeze();
let realFile = vfile(file), parser = this.parser || this.Parser;
return assertParser("parse", parser), parser(String(realFile), realFile);
}
/**
* Process the given file as configured on the processor.
*
* > \u{1F449} **Note**: \`process\` freezes the processor if not already *frozen*.
*
* > \u{1F449} **Note**: \`process\` performs the parse, run, and stringify phases.
*
* @overload
* @param {Compatible | undefined} file
* @param {ProcessCallback<VFileWithOutput<CompileResult>>} done
* @returns {undefined}
*
* @overload
* @param {Compatible | undefined} [file]
* @returns {Promise<VFileWithOutput<CompileResult>>}
*
* @param {Compatible | undefined} [file]
* File (optional); typically \`string\` or \`VFile\`]; any value accepted as
* \`x\` in \`new VFile(x)\`.
* @param {ProcessCallback<VFileWithOutput<CompileResult>> | undefined} [done]
* Callback (optional).
* @returns {Promise<VFile> | undefined}
* Nothing if \`done\` is given.
* Otherwise a promise, rejected with a fatal error or resolved with the
* processed file.
*
* The parsed, transformed, and compiled value is available at
* \`file.value\` (see note).
*
* > \u{1F449} **Note**: unified typically compiles by serializing: most
* > compilers return \`string\` (or \`Uint8Array\`).
* > Some compilers, such as the one configured with
* > [\`rehype-react\`][rehype-react], return other values (in this case, a
* > React tree).
* > If you\u2019re using a compiler that doesn\u2019t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@link CompileResultMap \`CompileResultMap\`}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
*/
process(file, done) {
let self2 = this;
return this.freeze(), assertParser("process", this.parser || this.Parser), assertCompiler("process", this.compiler || this.Compiler), done ? executor(void 0, done) : new Promise(executor);
function executor(resolve, reject) {
let realFile = vfile(file), parseTree = (
/** @type {HeadTree extends undefined ? Node : HeadTree} */
/** @type {unknown} */
self2.parse(realFile)
);
self2.run(parseTree, realFile, function(error, tree, file2) {
if (error || !tree || !file2)
return realDone(error);
let compileTree = (
/** @type {CompileTree extends undefined ? Node : CompileTree} */
/** @type {unknown} */
tree
), compileResult = self2.stringify(compileTree, file2);
looksLikeAValue(compileResult) ? file2.value = compileResult : file2.result = compileResult, realDone(
error,
/** @type {VFileWithOutput<CompileResult>} */
file2
);
});
function realDone(error, file2) {
error || !file2 ? reject(error) : resolve ? resolve(file2) : done(void 0, file2);
}
}
}
/**
* Process the given file as configured on the processor.
*
* An error is thrown if asynchronous transforms are configured.
*
* > \u{1F449} **Note**: \`processSync\` freezes the processor if not already *frozen*.
*
* > \u{1F449} **Note**: \`processSync\` performs the parse, run, and stringify phases.
*
* @param {Compatible | undefined} [file]
* File (optional); typically \`string\` or \`VFile\`; any value accepted as
* \`x\` in \`new VFile(x)\`.
* @returns {VFileWithOutput<CompileResult>}
* The processed file.
*
* The parsed, transformed, and compiled value is available at
* \`file.value\` (see note).
*
* > \u{1F449} **Note**: unified typically compiles by serializing: most
* > compilers return \`string\` (or \`Uint8Array\`).
* > Some compilers, such as the one configured with
* > [\`rehype-react\`][rehype-react], return other values (in this case, a
* > React tree).
* > If you\u2019re using a compiler that doesn\u2019t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@link CompileResultMap \`CompileResultMap\`}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
*/
processSync(file) {
let complete = !1, result;
return this.freeze(), assertParser("processSync", this.parser || this.Parser), assertCompiler("processSync", this.compiler || this.Compiler), this.process(file, realDone), assertDone("processSync", "process", complete), result;
function realDone(error, file2) {
complete = !0, bail(error), result = file2;
}
}
/**
* Run *transformers* on a syntax tree.
*
* > \u{1F449} **Note**: \`run\` freezes the processor if not already *frozen*.
*
* > \u{1F449} **Note**: \`run\` performs the run phase, not other phases.
*
* @overload
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
* @returns {undefined}
*
* @overload
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* @param {Compatible | undefined} file
* @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
* @returns {undefined}
*
* @overload
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* @param {Compatible | undefined} [file]
* @returns {Promise<TailTree extends undefined ? Node : TailTree>}
*
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* Tree to transform and inspect.
* @param {(
* RunCallback<TailTree extends undefined ? Node : TailTree> |
* Compatible
* )} [file]
* File associated with \`node\` (optional); any value accepted as \`x\` in
* \`new VFile(x)\`.
* @param {RunCallback<TailTree extends undefined ? Node : TailTree>} [done]
* Callback (optional).
* @returns {Promise<TailTree extends undefined ? Node : TailTree> | undefined}
* Nothing if \`done\` is given.
* Otherwise, a promise rejected with a fatal error or resolved with the
* transformed tree.
*/
run(tree, file, done) {
assertNode(tree), this.freeze();
let transformers = this.transformers;
return !done && typeof file == "function" && (done = file, file = void 0), done ? executor(void 0, done) : new Promise(executor);
function executor(resolve, reject) {
let realFile = vfile(file);
transformers.run(tree, realFile, realDone);
function realDone(error, outputTree, file2) {
let resultingTree = (
/** @type {TailTree extends undefined ? Node : TailTree} */
outputTree || tree
);
error ? reject(error) : resolve ? resolve(resultingTree) : done(void 0, resultingTree, file2);
}
}
}
/**
* Run *transformers* on a syntax tree.
*
* An error is thrown if asynchronous transforms are configured.
*
* > \u{1F449} **Note**: \`runSync\` freezes the processor if not already *frozen*.
*
* > \u{1F449} **Note**: \`runSync\` performs the run phase, not other phases.
*
* @param {HeadTree extends undefined ? Node : HeadTree} tree
* Tree to transform and inspect.
* @param {Compatible | undefined} [file]
* File associated with \`node\` (optional); any value accepted as \`x\` in
* \`new VFile(x)\`.
* @returns {TailTree extends undefined ? Node : TailTree}
* Transformed tree.
*/
runSync(tree, file) {
let complete = !1, result;
return this.run(tree, file, realDone), assertDone("runSync", "run", complete), result;
function realDone(error, tree2) {
bail(error), result = tree2, complete = !0;
}
}
/**
* Compile a syntax tree.
*
* > \u{1F449} **Note**: \`stringify\` freezes the processor if not already *frozen*.
*
* > \u{1F449} **Note**: \`stringify\` performs the stringify phase, not the run phase
* > or other phases.
*
* @param {CompileTree extends undefined ? Node : CompileTree} tree
* Tree to compile.
* @param {Compatible | undefined} [file]
* File associated with \`node\` (optional); any value accepted as \`x\` in
* \`new VFile(x)\`.
* @returns {CompileResult extends undefined ? Value : CompileResult}
* Textual representation of the tree (see note).
*
* > \u{1F449} **Note**: unified typically compiles by serializing: most compilers
* > return \`string\` (or \`Uint8Array\`).
* > Some compilers, such as the one configured with
* > [\`rehype-react\`][rehype-react], return other values (in this case, a
* > React tree).
* > If you\u2019re using a compiler that doesn\u2019t serialize, expect different
* > result values.
* >
* > To register custom results in TypeScript, add them to
* > {@link CompileResultMap \`CompileResultMap\`}.
*
* [rehype-react]: https://github.com/rehypejs/rehype-react
*/
stringify(tree, file) {
this.freeze();
let realFile = vfile(file), compiler2 = this.compiler || this.Compiler;
return assertCompiler("stringify", compiler2), assertNode(tree), compiler2(tree, realFile);
}
/**
* Configure the processor to use a plugin, a list of usable values, or a
* preset.
*
* If the processor is already using a plugin, the previous plugin
* configuration is changed based on the options that are passed in.
* In other words, the plugin is not added a second time.
*
* > \u{1F449} **Note**: \`use\` cannot be called on *frozen* processors.
* > Call the processor first to create a new unfrozen processor.
*
* @example
* There are many ways to pass plugins to \`.use()\`.
* This example gives an overview:
*
* \`\`\`js
* import {unified} from 'unified'
*
* unified()
* // Plugin with options:
* .use(pluginA, {x: true, y: true})
* // Passing the same plugin again merges configuration (to \`{x: true, y: false, z: true}\`):
* .use(pluginA, {y: false, z: true})
* // Plugins:
* .use([pluginB, pluginC])
* // Two plugins, the second with options:
* .use([pluginD, [pluginE, {}]])
* // Preset with plugins and settings:
* .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})
* // Settings only:
* .use({settings: {position: false}})
* \`\`\`
*
* @template {Array<unknown>} [Parameters=[]]
* @template {Node | string | undefined} [Input=undefined]
* @template [Output=Input]
*
* @overload
* @param {Preset | null | undefined} [preset]
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
*
* @overload
* @param {PluggableList} list
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
*
* @overload
* @param {Plugin<Parameters, Input, Output>} plugin
* @param {...(Parameters | [boolean])} parameters
* @returns {UsePlugin<ParseTree, HeadTree, TailTree, CompileTree, CompileResult, Input, Output>}
*
* @param {PluggableList | Plugin | Preset | null | undefined} value
* Usable value.
* @param {...unknown} parameters
* Parameters, when a plugin is given as a usable value.
* @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
* Current processor.
*/
use(value, ...parameters) {
let attachers = this.attachers, namespace = this.namespace;
if (assertUnfrozen("use", this.frozen), value != null)
if (typeof value == "function")
addPlugin(value, parameters);
else if (typeof value == "object")
Array.isArray(value) ? addList(value) : addPreset(value);
else
throw new TypeError("Expected usable value, not \`" + value + "\`");
return this;
function add(value2) {
if (typeof value2 == "function")
addPlugin(value2, []);
else if (typeof value2 == "object")
if (Array.isArray(value2)) {
let [plugin, ...parameters2] = (
/** @type {PluginTuple<Array<unknown>>} */
value2
);
addPlugin(plugin, parameters2);
} else
addPreset(value2);
else
throw new TypeError("Expected usable value, not \`" + value2 + "\`");
}
function addPreset(result) {
if (!("plugins" in result) && !("settings" in result))
throw new Error(
"Expected usable value but received an empty preset, which is probably a mistake: presets typically come with \`plugins\` and sometimes with \`settings\`, but this has neither"
);
addList(result.plugins), result.settings && (namespace.settings = {
...namespace.settings,
...esm_default(result.settings)
});
}
function addList(plugins) {
let index2 = -1;
if (plugins != null)
if (Array.isArray(plugins))
for (; ++index2 < plugins.length; ) {
let thing = plugins[index2];
add(thing);
}
else
throw new TypeError("Expected a list of plugins, not \`" + plugins + "\`");
}
function addPlugin(plugin, parameters2) {
let index2 = -1, entryIndex = -1;
for (; ++index2 < attachers.length; )
if (attachers[index2][0] === plugin) {
entryIndex = index2;
break;
}
if (entryIndex === -1)
attachers.push([plugin, ...parameters2]);
else if (parameters2.length > 0) {
let [primary, ...rest] = parameters2, currentPrimary = attachers[entryIndex][1];
isPlainObject(currentPrimary) && isPlainObject(primary) && (primary = esm_default({ ...currentPrimary, ...primary })), attachers[entryIndex] = [plugin, primary, ...rest];
}
}
}
}, unified = new Processor().freeze();
function assertParser(name, value) {
if (typeof value != "function")
throw new TypeError("Cannot \`" + name + "\` without \`parser\`");
}
function assertCompiler(name, value) {
if (typeof value != "function")
throw new TypeError("Cannot \`" + name + "\` without \`compiler\`");
}
function assertUnfrozen(name, frozen) {
if (frozen)
throw new Error(
"Cannot call \`" + name + "\` on a frozen processor.\\nCreate a new processor first, by calling it: use \`processor()\` instead of \`processor\`."
);
}
function assertNode(node2) {
if (!isPlainObject(node2) || typeof node2.type != "string")
throw new TypeError("Expected node, got \`" + node2 + "\`");
}
function assertDone(name, asyncName, complete) {
if (!complete)
throw new Error(
"\`" + name + "\` finished async. Use \`" + asyncName + "\` instead"
);
}
function vfile(value) {
return looksLikeAVFile(value) ? value : new VFile(value);
}
function looksLikeAVFile(value) {
return !!(value && typeof value == "object" && "message" in value && "messages" in value);
}
function looksLikeAValue(value) {
return typeof value == "string" || isUint8Array2(value);
}
function isUint8Array2(value) {
return !!(value && typeof value == "object" && "byteLength" in value && "byteOffset" in value);
}
// node_modules/mdast-util-to-string/lib/index.js
var emptyOptions = {};
function toString2(value, options) {
let settings = options || emptyOptions, includeImageAlt = typeof settings.includeImageAlt == "boolean" ? settings.includeImageAlt : !0, includeHtml = typeof settings.includeHtml == "boolean" ? settings.includeHtml : !0;
return one(value, includeImageAlt, includeHtml);
}
function one(value, includeImageAlt, includeHtml) {
if (node(value)) {
if ("value" in value)
return value.type === "html" && !includeHtml ? "" : value.value;
if (includeImageAlt && "alt" in value && value.alt)
return value.alt;
if ("children" in value)
return all(value.children, includeImageAlt, includeHtml);
}
return Array.isArray(value) ? all(value, includeImageAlt, includeHtml) : "";
}
function all(values, includeImageAlt, includeHtml) {
let result = [], index2 = -1;
for (; ++index2 < values.length; )
result[index2] = one(values[index2], includeImageAlt, includeHtml);
return result.join("");
}
function node(value) {
return !!(value && typeof value == "object");
}
// node_modules/decode-named-character-reference/index.dom.js
var element = document.createElement("i");
function decodeNamedCharacterReference(value) {
let characterReference2 = "&" + value + ";";
element.innerHTML = characterReference2;
let char = element.textContent;
return char.charCodeAt(char.length - 1) === 59 && value !== "semi" || char === characterReference2 ? !1 : char;
}
// node_modules/micromark-util-chunked/index.js
function splice(list3, start, remove, items) {
let end = list3.length, chunkStart = 0, parameters;
if (start < 0 ? start = -start > end ? 0 : end + start : start = start > end ? end : start, remove = remove > 0 ? remove : 0, items.length < 1e4)
parameters = Array.from(items), parameters.unshift(start, remove), list3.splice(...parameters);
else
for (remove && list3.splice(start, remove); chunkStart < items.length; )
parameters = items.slice(chunkStart, chunkStart + 1e4), parameters.unshift(start, 0), list3.splice(...parameters), chunkStart += 1e4, start += 1e4;
}
function push(list3, items) {
return list3.length > 0 ? (splice(list3, list3.length, 0, items), list3) : items;
}
// node_modules/micromark-util-combine-extensions/index.js
var hasOwnProperty = {}.hasOwnProperty;
function combineExtensions(extensions) {
let all2 = {}, index2 = -1;
for (; ++index2 < extensions.length; )
syntaxExtension(all2, extensions[index2]);
return all2;
}
function syntaxExtension(all2, extension2) {
let hook;
for (hook in extension2) {
let left = (hasOwnProperty.call(all2, hook) ? all2[hook] : void 0) || (all2[hook] = {}), right = extension2[hook], code3;
if (right)
for (code3 in right) {
hasOwnProperty.call(left, code3) || (left[code3] = []);
let value = right[code3];
constructs(
// @ts-expect-error Looks like a list.
left[code3],
Array.isArray(value) ? value : value ? [value] : []
);
}
}
}
function constructs(existing, list3) {
let index2 = -1, before = [];
for (; ++index2 < list3.length; )
(list3[index2].add === "after" ? existing : before).push(list3[index2]);
splice(existing, 0, 0, before);
}
// node_modules/micromark-util-decode-numeric-character-reference/index.js
function decodeNumericCharacterReference(value, base) {
let code3 = Number.parseInt(value, base);
return (
// C0 except for HT, LF, FF, CR, space.
code3 < 9 || code3 === 11 || code3 > 13 && code3 < 32 || // Control character (DEL) of C0, and C1 controls.
code3 > 126 && code3 < 160 || // Lone high surrogates and low surrogates.
code3 > 55295 && code3 < 57344 || // Noncharacters.
code3 > 64975 && code3 < 65008 || /* eslint-disable no-bitwise */
(code3 & 65535) === 65535 || (code3 & 65535) === 65534 || /* eslint-enable no-bitwise */
// Out of range
code3 > 1114111 ? "\\uFFFD" : String.fromCodePoint(code3)
);
}
// node_modules/micromark-util-normalize-identifier/index.js
function normalizeIdentifier(value) {
return value.replace(/[\\t\\n\\r ]+/g, " ").replace(/^ | $/g, "").toLowerCase().toUpperCase();
}
// node_modules/micromark-util-character/index.js
var asciiAlpha = regexCheck(/[A-Za-z]/), asciiAlphanumeric = regexCheck(/[\\dA-Za-z]/), asciiAtext = regexCheck(/[#-'*+\\--9=?A-Z^-~]/);
function asciiControl(code3) {
return (
// Special whitespace codes (which have negative values), C0 and Control
// character DEL
code3 !== null && (code3 < 32 || code3 === 127)
);
}
var asciiDigit = regexCheck(/\\d/), asciiHexDigit = regexCheck(/[\\dA-Fa-f]/), asciiPunctuation = regexCheck(/[!-/:-@[-\`{-~]/);
function markdownLineEnding(code3) {
return code3 !== null && code3 < -2;
}
function markdownLineEndingOrSpace(code3) {
return code3 !== null && (code3 < 0 || code3 === 32);
}
function markdownSpace(code3) {
return code3 === -2 || code3 === -1 || code3 === 32;
}
var unicodePunctuation = regexCheck(/\\p{P}|\\p{S}/u), unicodeWhitespace = regexCheck(/\\s/);
function regexCheck(regex) {
return check;
function check(code3) {
return code3 !== null && code3 > -1 && regex.test(String.fromCharCode(code3));
}
}
// node_modules/micromark-factory-space/index.js
function factorySpace(effects, ok2, type, max) {
let limit = max ? max - 1 : Number.POSITIVE_INFINITY, size = 0;
return start;
function start(code3) {
return markdownSpace(code3) ? (effects.enter(type), prefix(code3)) : ok2(code3);
}
function prefix(code3) {
return markdownSpace(code3) && size++ < limit ? (effects.consume(code3), prefix) : (effects.exit(type), ok2(code3));
}
}
// node_modules/micromark/lib/initialize/content.js
var content = {
tokenize: initializeContent
};
function initializeContent(effects) {
let contentStart = effects.attempt(
this.parser.constructs.contentInitial,
afterContentStartConstruct,
paragraphInitial
), previous3;
return contentStart;
function afterContentStartConstruct(code3) {
if (code3 === null) {
effects.consume(code3);
return;
}
return effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), factorySpace(effects, contentStart, "linePrefix");
}
function paragraphInitial(code3) {
return effects.enter("paragraph"), lineStart(code3);
}
function lineStart(code3) {
let token = effects.enter("chunkText", {
contentType: "text",
previous: previous3
});
return previous3 && (previous3.next = token), previous3 = token, data(code3);
}
function data(code3) {
if (code3 === null) {
effects.exit("chunkText"), effects.exit("paragraph"), effects.consume(code3);
return;
}
return markdownLineEnding(code3) ? (effects.consume(code3), effects.exit("chunkText"), lineStart) : (effects.consume(code3), data);
}
}
// node_modules/micromark/lib/initialize/document.js
var document2 = {
tokenize: initializeDocument
}, containerConstruct = {
tokenize: tokenizeContainer
};
function initializeDocument(effects) {
let self2 = this, stack = [], continued = 0, childFlow, childToken, lineStartOffset;
return start;
function start(code3) {
if (continued < stack.length) {
let item = stack[continued];
return self2.containerState = item[1], effects.attempt(
item[0].continuation,
documentContinue,
checkNewContainers
)(code3);
}
return checkNewContainers(code3);
}
function documentContinue(code3) {
if (continued++, self2.containerState._closeFlow) {
self2.containerState._closeFlow = void 0, childFlow && closeFlow();
let indexBeforeExits = self2.events.length, indexBeforeFlow = indexBeforeExits, point3;
for (; indexBeforeFlow--; )
if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === "chunkFlow") {
point3 = self2.events[indexBeforeFlow][1].end;
break;
}
exitContainers(continued);
let index2 = indexBeforeExits;
for (; index2 < self2.events.length; )
self2.events[index2][1].end = Object.assign({}, point3), index2++;
return splice(
self2.events,
indexBeforeFlow + 1,
0,
self2.events.slice(indexBeforeExits)
), self2.events.length = index2, checkNewContainers(code3);
}
return start(code3);
}
function checkNewContainers(code3) {
if (continued === stack.length) {
if (!childFlow)
return documentContinued(code3);
if (childFlow.currentConstruct && childFlow.currentConstruct.concrete)
return flowStart(code3);
self2.interrupt = !!(childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack);
}
return self2.containerState = {}, effects.check(
containerConstruct,
thereIsANewContainer,
thereIsNoNewContainer
)(code3);
}
function thereIsANewContainer(code3) {
return childFlow && closeFlow(), exitContainers(continued), documentContinued(code3);
}
function thereIsNoNewContainer(code3) {
return self2.parser.lazy[self2.now().line] = continued !== stack.length, lineStartOffset = self2.now().offset, flowStart(code3);
}
function documentContinued(code3) {
return self2.containerState = {}, effects.attempt(
containerConstruct,
containerContinue,
flowStart
)(code3);
}
function containerContinue(code3) {
return continued++, stack.push([self2.currentConstruct, self2.containerState]), documentContinued(code3);
}
function flowStart(code3) {
if (code3 === null) {
childFlow && closeFlow(), exitContainers(0), effects.consume(code3);
return;
}
return childFlow = childFlow || self2.parser.flow(self2.now()), effects.enter("chunkFlow", {
contentType: "flow",
previous: childToken,
_tokenizer: childFlow
}), flowContinue(code3);
}
function flowContinue(code3) {
if (code3 === null) {
writeToChild(effects.exit("chunkFlow"), !0), exitContainers(0), effects.consume(code3);
return;
}
return markdownLineEnding(code3) ? (effects.consume(code3), writeToChild(effects.exit("chunkFlow")), continued = 0, self2.interrupt = void 0, start) : (effects.consume(code3), flowContinue);
}
function writeToChild(token, eof) {
let stream = self2.sliceStream(token);
if (eof && stream.push(null), token.previous = childToken, childToken && (childToken.next = token), childToken = token, childFlow.defineSkip(token.start), childFlow.write(stream), self2.parser.lazy[token.start.line]) {
let index2 = childFlow.events.length;
for (; index2--; )
if (
// The token starts before the line ending\u2026
childFlow.events[index2][1].start.offset < lineStartOffset && // \u2026and either is not ended yet\u2026
(!childFlow.events[index2][1].end || // \u2026or ends after it.
childFlow.events[index2][1].end.offset > lineStartOffset)
)
return;
let indexBeforeExits = self2.events.length, indexBeforeFlow = indexBeforeExits, seen, point3;
for (; indexBeforeFlow--; )
if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === "chunkFlow") {
if (seen) {
point3 = self2.events[indexBeforeFlow][1].end;
break;
}
seen = !0;
}
for (exitContainers(continued), index2 = indexBeforeExits; index2 < self2.events.length; )
self2.events[index2][1].end = Object.assign({}, point3), index2++;
splice(
self2.events,
indexBeforeFlow + 1,
0,
self2.events.slice(indexBeforeExits)
), self2.events.length = index2;
}
}
function exitContainers(size) {
let index2 = stack.length;
for (; index2-- > size; ) {
let entry = stack[index2];
self2.containerState = entry[1], entry[0].exit.call(self2, effects);
}
stack.length = size;
}
function closeFlow() {
childFlow.write([null]), childToken = void 0, childFlow = void 0, self2.containerState._closeFlow = void 0;
}
}
function tokenizeContainer(effects, ok2, nok) {
return factorySpace(
effects,
effects.attempt(this.parser.constructs.document, ok2, nok),
"linePrefix",
this.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4
);
}
// node_modules/micromark-util-classify-character/index.js
function classifyCharacter(code3) {
if (code3 === null || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3))
return 1;
if (unicodePunctuation(code3))
return 2;
}
// node_modules/micromark-util-resolve-all/index.js
function resolveAll(constructs2, events, context) {
let called = [], index2 = -1;
for (; ++index2 < constructs2.length; ) {
let resolve = constructs2[index2].resolveAll;
resolve && !called.includes(resolve) && (events = resolve(events, context), called.push(resolve));
}
return events;
}
// node_modules/micromark-core-commonmark/lib/attention.js
var attention = {
name: "attention",
tokenize: tokenizeAttention,
resolveAll: resolveAllAttention
};
function resolveAllAttention(events, context) {
let index2 = -1, open, group, text5, openingSequence, closingSequence, use, nextEvents, offset;
for (; ++index2 < events.length; )
if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
for (open = index2; open--; )
if (events[open][0] === "exit" && events[open][1].type === "attentionSequence" && events[open][1]._open && // If the markers are the same:
context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
if ((events[open][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3))
continue;
use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
let start = Object.assign({}, events[open][1].end), end = Object.assign({}, events[index2][1].start);
movePoint(start, -use), movePoint(end, use), openingSequence = {
type: use > 1 ? "strongSequence" : "emphasisSequence",
start,
end: Object.assign({}, events[open][1].end)
}, closingSequence = {
type: use > 1 ? "strongSequence" : "emphasisSequence",
start: Object.assign({}, events[index2][1].start),
end
}, text5 = {
type: use > 1 ? "strongText" : "emphasisText",
start: Object.assign({}, events[open][1].end),
end: Object.assign({}, events[index2][1].start)
}, group = {
type: use > 1 ? "strong" : "emphasis",
start: Object.assign({}, openingSequence.start),
end: Object.assign({}, closingSequence.end)
}, events[open][1].end = Object.assign({}, openingSequence.start), events[index2][1].start = Object.assign({}, closingSequence.end), nextEvents = [], events[open][1].end.offset - events[open][1].start.offset && (nextEvents = push(nextEvents, [["enter", events[open][1], context], ["exit", events[open][1], context]])), nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text5, context]]), nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + 1, index2), context)), nextEvents = push(nextEvents, [["exit", text5, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]), events[index2][1].end.offset - events[index2][1].start.offset ? (offset = 2, nextEvents = push(nextEvents, [["enter", events[index2][1], context], ["exit", events[index2][1], context]])) : offset = 0, splice(events, open - 1, index2 - open + 3, nextEvents), index2 = open + nextEvents.length - offset - 2;
break;
}
}
for (index2 = -1; ++index2 < events.length; )
events[index2][1].type === "attentionSequence" && (events[index2][1].type = "data");
return events;
}
function tokenizeAttention(effects, ok2) {
let attentionMarkers2 = this.parser.constructs.attentionMarkers.null, previous3 = this.previous, before = classifyCharacter(previous3), marker;
return start;
function start(code3) {
return marker = code3, effects.enter("attentionSequence"), inside(code3);
}
function inside(code3) {
if (code3 === marker)
return effects.consume(code3), inside;
let token = effects.exit("attentionSequence"), after = classifyCharacter(code3), open = !after || after === 2 && before || attentionMarkers2.includes(code3), close = !before || before === 2 && after || attentionMarkers2.includes(previous3);
return token._open = !!(marker === 42 ? open : open && (before || !close)), token._close = !!(marker === 42 ? close : close && (after || !open)), ok2(code3);
}
}
function movePoint(point3, offset) {
point3.column += offset, point3.offset += offset, point3._bufferIndex += offset;
}
// node_modules/micromark-core-commonmark/lib/autolink.js
var autolink = {
name: "autolink",
tokenize: tokenizeAutolink
};
function tokenizeAutolink(effects, ok2, nok) {
let size = 0;
return start;
function start(code3) {
return effects.enter("autolink"), effects.enter("autolinkMarker"), effects.consume(code3), effects.exit("autolinkMarker"), effects.enter("autolinkProtocol"), open;
}
function open(code3) {
return asciiAlpha(code3) ? (effects.consume(code3), schemeOrEmailAtext) : code3 === 64 ? nok(code3) : emailAtext(code3);
}
function schemeOrEmailAtext(code3) {
return code3 === 43 || code3 === 45 || code3 === 46 || asciiAlphanumeric(code3) ? (size = 1, schemeInsideOrEmailAtext(code3)) : emailAtext(code3);
}
function schemeInsideOrEmailAtext(code3) {
return code3 === 58 ? (effects.consume(code3), size = 0, urlInside) : (code3 === 43 || code3 === 45 || code3 === 46 || asciiAlphanumeric(code3)) && size++ < 32 ? (effects.consume(code3), schemeInsideOrEmailAtext) : (size = 0, emailAtext(code3));
}
function urlInside(code3) {
return code3 === 62 ? (effects.exit("autolinkProtocol"), effects.enter("autolinkMarker"), effects.consume(code3), effects.exit("autolinkMarker"), effects.exit("autolink"), ok2) : code3 === null || code3 === 32 || code3 === 60 || asciiControl(code3) ? nok(code3) : (effects.consume(code3), urlInside);
}
function emailAtext(code3) {
return code3 === 64 ? (effects.consume(code3), emailAtSignOrDot) : asciiAtext(code3) ? (effects.consume(code3), emailAtext) : nok(code3);
}
function emailAtSignOrDot(code3) {
return asciiAlphanumeric(code3) ? emailLabel(code3) : nok(code3);
}
function emailLabel(code3) {
return code3 === 46 ? (effects.consume(code3), size = 0, emailAtSignOrDot) : code3 === 62 ? (effects.exit("autolinkProtocol").type = "autolinkEmail", effects.enter("autolinkMarker"), effects.consume(code3), effects.exit("autolinkMarker"), effects.exit("autolink"), ok2) : emailValue(code3);
}
function emailValue(code3) {
if ((code3 === 45 || asciiAlphanumeric(code3)) && size++ < 63) {
let next = code3 === 45 ? emailValue : emailLabel;
return effects.consume(code3), next;
}
return nok(code3);
}
}
// node_modules/micromark-core-commonmark/lib/blank-line.js
var blankLine = {
tokenize: tokenizeBlankLine,
partial: !0
};
function tokenizeBlankLine(effects, ok2, nok) {
return start;
function start(code3) {
return markdownSpace(code3) ? factorySpace(effects, after, "linePrefix")(code3) : after(code3);
}
function after(code3) {
return code3 === null || markdownLineEnding(code3) ? ok2(code3) : nok(code3);
}
}
// node_modules/micromark-core-commonmark/lib/block-quote.js
var blockQuote = {
name: "blockQuote",
tokenize: tokenizeBlockQuoteStart,
continuation: {
tokenize: tokenizeBlockQuoteContinuation
},
exit
};
function tokenizeBlockQuoteStart(effects, ok2, nok) {
let self2 = this;
return start;
function start(code3) {
if (code3 === 62) {
let state = self2.containerState;
return state.open || (effects.enter("blockQuote", {
_container: !0
}), state.open = !0), effects.enter("blockQuotePrefix"), effects.enter("blockQuoteMarker"), effects.consume(code3), effects.exit("blockQuoteMarker"), after;
}
return nok(code3);
}
function after(code3) {
return markdownSpace(code3) ? (effects.enter("blockQuotePrefixWhitespace"), effects.consume(code3), effects.exit("blockQuotePrefixWhitespace"), effects.exit("blockQuotePrefix"), ok2) : (effects.exit("blockQuotePrefix"), ok2(code3));
}
}
function tokenizeBlockQuoteContinuation(effects, ok2, nok) {
let self2 = this;
return contStart;
function contStart(code3) {
return markdownSpace(code3) ? factorySpace(effects, contBefore, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code3) : contBefore(code3);
}
function contBefore(code3) {
return effects.attempt(blockQuote, ok2, nok)(code3);
}
}
function exit(effects) {
effects.exit("blockQuote");
}
// node_modules/micromark-core-commonmark/lib/character-escape.js
var characterEscape = {
name: "characterEscape",
tokenize: tokenizeCharacterEscape
};
function tokenizeCharacterEscape(effects, ok2, nok) {
return start;
function start(code3) {
return effects.enter("characterEscape"), effects.enter("escapeMarker"), effects.consume(code3), effects.exit("escapeMarker"), inside;
}
function inside(code3) {
return asciiPunctuation(code3) ? (effects.enter("characterEscapeValue"), effects.consume(code3), effects.exit("characterEscapeValue"), effects.exit("characterEscape"), ok2) : nok(code3);
}
}
// node_modules/micromark-core-commonmark/lib/character-reference.js
var characterReference = {
name: "characterReference",
tokenize: tokenizeCharacterReference
};
function tokenizeCharacterReference(effects, ok2, nok) {
let self2 = this, size = 0, max, test;
return start;
function start(code3) {
return effects.enter("characterReference"), effects.enter("characterReferenceMarker"), effects.consume(code3), effects.exit("characterReferenceMarker"), open;
}
function open(code3) {
return code3 === 35 ? (effects.enter("characterReferenceMarkerNumeric"), effects.consume(code3), effects.exit("characterReferenceMarkerNumeric"), numeric) : (effects.enter("characterReferenceValue"), max = 31, test = asciiAlphanumeric, value(code3));
}
function numeric(code3) {
return code3 === 88 || code3 === 120 ? (effects.enter("characterReferenceMarkerHexadecimal"), effects.consume(code3), effects.exit("characterReferenceMarkerHexadecimal"), effects.enter("characterReferenceValue"), max = 6, test = asciiHexDigit, value) : (effects.enter("characterReferenceValue"), max = 7, test = asciiDigit, value(code3));
}
function value(code3) {
if (code3 === 59 && size) {
let token = effects.exit("characterReferenceValue");
return test === asciiAlphanumeric && !decodeNamedCharacterReference(self2.sliceSerialize(token)) ? nok(code3) : (effects.enter("characterReferenceMarker"), effects.consume(code3), effects.exit("characterReferenceMarker"), effects.exit("characterReference"), ok2);
}
return test(code3) && size++ < max ? (effects.consume(code3), value) : nok(code3);
}
}
// node_modules/micromark-core-commonmark/lib/code-fenced.js
var nonLazyContinuation = {
tokenize: tokenizeNonLazyContinuation,
partial: !0
}, codeFenced = {
name: "codeFenced",
tokenize: tokenizeCodeFenced,
concrete: !0
};
function tokenizeCodeFenced(effects, ok2, nok) {
let self2 = this, closeStart = {
tokenize: tokenizeCloseStart,
partial: !0
}, initialPrefix = 0, sizeOpen = 0, marker;
return start;
function start(code3) {
return beforeSequenceOpen(code3);
}
function beforeSequenceOpen(code3) {
let tail = self2.events[self2.events.length - 1];
return initialPrefix = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], !0).length : 0, marker = code3, effects.enter("codeFenced"), effects.enter("codeFencedFence"), effects.enter("codeFencedFenceSequence"), sequenceOpen(code3);
}
function sequenceOpen(code3) {
return code3 === marker ? (sizeOpen++, effects.consume(code3), sequenceOpen) : sizeOpen < 3 ? nok(code3) : (effects.exit("codeFencedFenceSequence"), markdownSpace(code3) ? factorySpace(effects, infoBefore, "whitespace")(code3) : infoBefore(code3));
}
function infoBefore(code3) {
return code3 === null || markdownLineEnding(code3) ? (effects.exit("codeFencedFence"), self2.interrupt ? ok2(code3) : effects.check(nonLazyContinuation, atNonLazyBreak, after)(code3)) : (effects.enter("codeFencedFenceInfo"), effects.enter("chunkString", {
contentType: "string"
}), info(code3));
}
function info(code3) {
return code3 === null || markdownLineEnding(code3) ? (effects.exit("chunkString"), effects.exit("codeFencedFenceInfo"), infoBefore(code3)) : markdownSpace(code3) ? (effects.exit("chunkString"), effects.exit("codeFencedFenceInfo"), factorySpace(effects, metaBefore, "whitespace")(code3)) : code3 === 96 && code3 === marker ? nok(code3) : (effects.consume(code3), info);
}
function metaBefore(code3) {
return code3 === null || markdownLineEnding(code3) ? infoBefore(code3) : (effects.enter("codeFencedFenceMeta"), effects.enter("chunkString", {
contentType: "string"
}), meta(code3));
}
function meta(code3) {
return code3 === null || markdownLineEnding(code3) ? (effects.exit("chunkString"), effects.exit("codeFencedFenceMeta"), infoBefore(code3)) : code3 === 96 && code3 === marker ? nok(code3) : (effects.consume(code3), meta);
}
function atNonLazyBreak(code3) {
return effects.attempt(closeStart, after, contentBefore)(code3);
}
function contentBefore(code3) {
return effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), contentStart;
}
function contentStart(code3) {
return initialPrefix > 0 && markdownSpace(code3) ? factorySpace(effects, beforeContentChunk, "linePrefix", initialPrefix + 1)(code3) : beforeContentChunk(code3);
}
function beforeContentChunk(code3) {
return code3 === null || markdownLineEnding(code3) ? effects.check(nonLazyContinuation, atNonLazyBreak, after)(code3) : (effects.enter("codeFlowValue"), contentChunk(code3));
}
function contentChunk(code3) {
return code3 === null || markdownLineEnding(code3) ? (effects.exit("codeFlowValue"), beforeContentChunk(code3)) : (effects.consume(code3), contentChunk);
}
function after(code3) {
return effects.exit("codeFenced"), ok2(code3);
}
function tokenizeCloseStart(effects2, ok3, nok2) {
let size = 0;
return startBefore;
function startBefore(code3) {
return effects2.enter("lineEnding"), effects2.consume(code3), effects2.exit("lineEnding"), start2;
}
function start2(code3) {
return effects2.enter("codeFencedFence"), markdownSpace(code3) ? factorySpace(effects2, beforeSequenceClose, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code3) : beforeSequenceClose(code3);
}
function beforeSequenceClose(code3) {
return code3 === marker ? (effects2.enter("codeFencedFenceSequence"), sequenceClose(code3)) : nok2(code3);
}
function sequenceClose(code3) {
return code3 === marker ? (size++, effects2.consume(code3), sequenceClose) : size >= sizeOpen ? (effects2.exit("codeFencedFenceSequence"), markdownSpace(code3) ? factorySpace(effects2, sequenceCloseAfter, "whitespace")(code3) : sequenceCloseAfter(code3)) : nok2(code3);
}
function sequenceCloseAfter(code3) {
return code3 === null || markdownLineEnding(code3) ? (effects2.exit("codeFencedFence"), ok3(code3)) : nok2(code3);
}
}
}
function tokenizeNonLazyContinuation(effects, ok2, nok) {
let self2 = this;
return start;
function start(code3) {
return code3 === null ? nok(code3) : (effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), lineStart);
}
function lineStart(code3) {
return self2.parser.lazy[self2.now().line] ? nok(code3) : ok2(code3);
}
}
// node_modules/micromark-core-commonmark/lib/code-indented.js
var codeIndented = {
name: "codeIndented",
tokenize: tokenizeCodeIndented
}, furtherStart = {
tokenize: tokenizeFurtherStart,
partial: !0
};
function tokenizeCodeIndented(effects, ok2, nok) {
let self2 = this;
return start;
function start(code3) {
return effects.enter("codeIndented"), factorySpace(effects, afterPrefix, "linePrefix", 5)(code3);
}
function afterPrefix(code3) {
let tail = self2.events[self2.events.length - 1];
return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], !0).length >= 4 ? atBreak(code3) : nok(code3);
}
function atBreak(code3) {
return code3 === null ? after(code3) : markdownLineEnding(code3) ? effects.attempt(furtherStart, atBreak, after)(code3) : (effects.enter("codeFlowValue"), inside(code3));
}
function inside(code3) {
return code3 === null || markdownLineEnding(code3) ? (effects.exit("codeFlowValue"), atBreak(code3)) : (effects.consume(code3), inside);
}
function after(code3) {
return effects.exit("codeIndented"), ok2(code3);
}
}
function tokenizeFurtherStart(effects, ok2, nok) {
let self2 = this;
return furtherStart2;
function furtherStart2(code3) {
return self2.parser.lazy[self2.now().line] ? nok(code3) : markdownLineEnding(code3) ? (effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), furtherStart2) : factorySpace(effects, afterPrefix, "linePrefix", 5)(code3);
}
function afterPrefix(code3) {
let tail = self2.events[self2.events.length - 1];
return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], !0).length >= 4 ? ok2(code3) : markdownLineEnding(code3) ? furtherStart2(code3) : nok(code3);
}
}
// node_modules/micromark-core-commonmark/lib/code-text.js
var codeText = {
name: "codeText",
tokenize: tokenizeCodeText,
resolve: resolveCodeText,
previous
};
function resolveCodeText(events) {
let tailExitIndex = events.length - 4, headEnterIndex = 3, index2, enter;
if ((events[headEnterIndex][1].type === "lineEnding" || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === "lineEnding" || events[tailExitIndex][1].type === "space")) {
for (index2 = headEnterIndex; ++index2 < tailExitIndex; )
if (events[index2][1].type === "codeTextData") {
events[headEnterIndex][1].type = "codeTextPadding", events[tailExitIndex][1].type = "codeTextPadding", headEnterIndex += 2, tailExitIndex -= 2;
break;
}
}
for (index2 = headEnterIndex - 1, tailExitIndex++; ++index2 <= tailExitIndex; )
enter === void 0 ? index2 !== tailExitIndex && events[index2][1].type !== "lineEnding" && (enter = index2) : (index2 === tailExitIndex || events[index2][1].type === "lineEnding") && (events[enter][1].type = "codeTextData", index2 !== enter + 2 && (events[enter][1].end = events[index2 - 1][1].end, events.splice(enter + 2, index2 - enter - 2), tailExitIndex -= index2 - enter - 2, index2 = enter + 2), enter = void 0);
return events;
}
function previous(code3) {
return code3 !== 96 || this.events[this.events.length - 1][1].type === "characterEscape";
}
function tokenizeCodeText(effects, ok2, nok) {
let self2 = this, sizeOpen = 0, size, token;
return start;
function start(code3) {
return effects.enter("codeText"), effects.enter("codeTextSequence"), sequenceOpen(code3);
}
function sequenceOpen(code3) {
return code3 === 96 ? (effects.consume(code3), sizeOpen++, sequenceOpen) : (effects.exit("codeTextSequence"), between(code3));
}
function between(code3) {
return code3 === null ? nok(code3) : code3 === 32 ? (effects.enter("space"), effects.consume(code3), effects.exit("space"), between) : code3 === 96 ? (token = effects.enter("codeTextSequence"), size = 0, sequenceClose(code3)) : markdownLineEnding(code3) ? (effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), between) : (effects.enter("codeTextData"), data(code3));
}
function data(code3) {
return code3 === null || code3 === 32 || code3 === 96 || markdownLineEnding(code3) ? (effects.exit("codeTextData"), between(code3)) : (effects.consume(code3), data);
}
function sequenceClose(code3) {
return code3 === 96 ? (effects.consume(code3), size++, sequenceClose) : size === sizeOpen ? (effects.exit("codeTextSequence"), effects.exit("codeText"), ok2(code3)) : (token.type = "codeTextData", data(code3));
}
}
// node_modules/micromark-util-subtokenize/lib/splice-buffer.js
var SpliceBuffer = class {
/**
* @param {ReadonlyArray<T> | null | undefined} [initial]
* Initial items (optional).
* @returns
* Splice buffer.
*/
constructor(initial) {
this.left = initial ? [...initial] : [], this.right = [];
}
/**
* Array access;
* does not move the cursor.
*
* @param {number} index
* Index.
* @return {T}
* Item.
*/
get(index2) {
if (index2 < 0 || index2 >= this.left.length + this.right.length)
throw new RangeError("Cannot access index \`" + index2 + "\` in a splice buffer of size \`" + (this.left.length + this.right.length) + "\`");
return index2 < this.left.length ? this.left[index2] : this.right[this.right.length - index2 + this.left.length - 1];
}
/**
* The length of the splice buffer, one greater than the largest index in the
* array.
*/
get length() {
return this.left.length + this.right.length;
}
/**
* Remove and return \`list[0]\`;
* moves the cursor to \`0\`.
*
* @returns {T | undefined}
* Item, optional.
*/
shift() {
return this.setCursor(0), this.right.pop();
}
/**
* Slice the buffer to get an array;
* does not move the cursor.
*
* @param {number} start
* Start.
* @param {number | null | undefined} [end]
* End (optional).
* @returns {Array<T>}
* Array of items.
*/
slice(start, end) {
let stop = end == null ? Number.POSITIVE_INFINITY : end;
return stop < this.left.length ? this.left.slice(start, stop) : start > this.left.length ? this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse() : this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse());
}
/**
* Mimics the behavior of Array.prototype.splice() except for the change of
* interface necessary to avoid segfaults when patching in very large arrays.
*
* This operation moves cursor is moved to \`start\` and results in the cursor
* placed after any inserted items.
*
* @param {number} start
* Start;
* zero-based index at which to start changing the array;
* negative numbers count backwards from the end of the array and values
* that are out-of bounds are clamped to the appropriate end of the array.
* @param {number | null | undefined} [deleteCount=0]
* Delete count (default: \`0\`);
* maximum number of elements to delete, starting from start.
* @param {Array<T> | null | undefined} [items=[]]
* Items to include in place of the deleted items (default: \`[]\`).
* @return {Array<T>}
* Any removed items.
*/
splice(start, deleteCount, items) {
let count = deleteCount || 0;
this.setCursor(Math.trunc(start));
let removed = this.right.splice(this.right.length - count, Number.POSITIVE_INFINITY);
return items && chunkedPush(this.left, items), removed.reverse();
}
/**
* Remove and return the highest-numbered item in the array, so
* \`list[list.length - 1]\`;
* Moves the cursor to \`length\`.
*
* @returns {T | undefined}
* Item, optional.
*/
pop() {
return this.setCursor(Number.POSITIVE_INFINITY), this.left.pop();
}
/**
* Inserts a single item to the high-numbered side of the array;
* moves the cursor to \`length\`.
*
* @param {T} item
* Item.
* @returns {undefined}
* Nothing.
*/
push(item) {
this.setCursor(Number.POSITIVE_INFINITY), this.left.push(item);
}
/**
* Inserts many items to the high-numbered side of the array.
* Moves the cursor to \`length\`.
*
* @param {Array<T>} items
* Items.
* @returns {undefined}
* Nothing.
*/
pushMany(items) {
this.setCursor(Number.POSITIVE_INFINITY), chunkedPush(this.left, items);
}
/**
* Inserts a single item to the low-numbered side of the array;
* Moves the cursor to \`0\`.
*
* @param {T} item
* Item.
* @returns {undefined}
* Nothing.
*/
unshift(item) {
this.setCursor(0), this.right.push(item);
}
/**
* Inserts many items to the low-numbered side of the array;
* moves the cursor to \`0\`.
*
* @param {Array<T>} items
* Items.
* @returns {undefined}
* Nothing.
*/
unshiftMany(items) {
this.setCursor(0), chunkedPush(this.right, items.reverse());
}
/**
* Move the cursor to a specific position in the array. Requires
* time proportional to the distance moved.
*
* If \`n < 0\`, the cursor will end up at the beginning.
* If \`n > length\`, the cursor will end up at the end.
*
* @param {number} n
* Position.
* @return {undefined}
* Nothing.
*/
setCursor(n2) {
if (!(n2 === this.left.length || n2 > this.left.length && this.right.length === 0 || n2 < 0 && this.left.length === 0))
if (n2 < this.left.length) {
let removed = this.left.splice(n2, Number.POSITIVE_INFINITY);
chunkedPush(this.right, removed.reverse());
} else {
let removed = this.right.splice(this.left.length + this.right.length - n2, Number.POSITIVE_INFINITY);
chunkedPush(this.left, removed.reverse());
}
}
};
function chunkedPush(list3, right) {
let chunkStart = 0;
if (right.length < 1e4)
list3.push(...right);
else
for (; chunkStart < right.length; )
list3.push(...right.slice(chunkStart, chunkStart + 1e4)), chunkStart += 1e4;
}
// node_modules/micromark-util-subtokenize/index.js
function subtokenize(eventsArray) {
let jumps = {}, index2 = -1, event, lineIndex, otherIndex, otherEvent, parameters, subevents, more, events = new SpliceBuffer(eventsArray);
for (; ++index2 < events.length; ) {
for (; index2 in jumps; )
index2 = jumps[index2];
if (event = events.get(index2), index2 && event[1].type === "chunkFlow" && events.get(index2 - 1)[1].type === "listItemPrefix" && (subevents = event[1]._tokenizer.events, otherIndex = 0, otherIndex < subevents.length && subevents[otherIndex][1].type === "lineEndingBlank" && (otherIndex += 2), otherIndex < subevents.length && subevents[otherIndex][1].type === "content"))
for (; ++otherIndex < subevents.length && subevents[otherIndex][1].type !== "content"; )
subevents[otherIndex][1].type === "chunkText" && (subevents[otherIndex][1]._isInFirstContentOfListItem = !0, otherIndex++);
if (event[0] === "enter")
event[1].contentType && (Object.assign(jumps, subcontent(events, index2)), index2 = jumps[index2], more = !0);
else if (event[1]._container) {
for (otherIndex = index2, lineIndex = void 0; otherIndex-- && (otherEvent = events.get(otherIndex), otherEvent[1].type === "lineEnding" || otherEvent[1].type === "lineEndingBlank"); )
otherEvent[0] === "enter" && (lineIndex && (events.get(lineIndex)[1].type = "lineEndingBlank"), otherEvent[1].type = "lineEnding", lineIndex = otherIndex);
lineIndex && (event[1].end = Object.assign({}, events.get(lineIndex)[1].start), parameters = events.slice(lineIndex, index2), parameters.unshift(event), events.splice(lineIndex, index2 - lineIndex + 1, parameters));
}
}
return splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0)), !more;
}
function subcontent(events, eventIndex) {
let token = events.get(eventIndex)[1], context = events.get(eventIndex)[2], startPosition = eventIndex - 1, startPositions = [], tokenizer = token._tokenizer || context.parser[token.contentType](token.start), childEvents = tokenizer.events, jumps = [], gaps = {}, stream, previous3, index2 = -1, current = token, adjust = 0, start = 0, breaks = [start];
for (; current; ) {
for (; events.get(++startPosition)[1] !== current; )
;
startPositions.push(startPosition), current._tokenizer || (stream = context.sliceStream(current), current.next || stream.push(null), previous3 && tokenizer.defineSkip(current.start), current._isInFirstContentOfListItem && (tokenizer._gfmTasklistFirstContentOfListItem = !0), tokenizer.write(stream), current._isInFirstContentOfListItem && (tokenizer._gfmTasklistFirstContentOfListItem = void 0)), previous3 = current, current = current.next;
}
for (current = token; ++index2 < childEvents.length; )
// Find a void token that includes a break.
childEvents[index2][0] === "exit" && childEvents[index2 - 1][0] === "enter" && childEvents[index2][1].type === childEvents[index2 - 1][1].type && childEvents[index2][1].start.line !== childEvents[index2][1].end.line && (start = index2 + 1, breaks.push(start), current._tokenizer = void 0, current.previous = void 0, current = current.next);
for (tokenizer.events = [], current ? (current._tokenizer = void 0, current.previous = void 0) : breaks.pop(), index2 = breaks.length; index2--; ) {
let slice = childEvents.slice(breaks[index2], breaks[index2 + 1]), start2 = startPositions.pop();
jumps.push([start2, start2 + slice.length - 1]), events.splice(start2, 2, slice);
}
for (jumps.reverse(), index2 = -1; ++index2 < jumps.length; )
gaps[adjust + jumps[index2][0]] = adjust + jumps[index2][1], adjust += jumps[index2][1] - jumps[index2][0] - 1;
return gaps;
}
// node_modules/micromark-core-commonmark/lib/content.js
var content2 = {
tokenize: tokenizeContent,
resolve: resolveContent
}, continuationConstruct = {
tokenize: tokenizeContinuation,
partial: !0
};
function resolveContent(events) {
return subtokenize(events), events;
}
function tokenizeContent(effects, ok2) {
let previous3;
return chunkStart;
function chunkStart(code3) {
return effects.enter("content"), previous3 = effects.enter("chunkContent", {
contentType: "content"
}), chunkInside(code3);
}
function chunkInside(code3) {
return code3 === null ? contentEnd(code3) : markdownLineEnding(code3) ? effects.check(continuationConstruct, contentContinue, contentEnd)(code3) : (effects.consume(code3), chunkInside);
}
function contentEnd(code3) {
return effects.exit("chunkContent"), effects.exit("content"), ok2(code3);
}
function contentContinue(code3) {
return effects.consume(code3), effects.exit("chunkContent"), previous3.next = effects.enter("chunkContent", {
contentType: "content",
previous: previous3
}), previous3 = previous3.next, chunkInside;
}
}
function tokenizeContinuation(effects, ok2, nok) {
let self2 = this;
return startLookahead;
function startLookahead(code3) {
return effects.exit("chunkContent"), effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), factorySpace(effects, prefixed, "linePrefix");
}
function prefixed(code3) {
if (code3 === null || markdownLineEnding(code3))
return nok(code3);
let tail = self2.events[self2.events.length - 1];
return !self2.parser.constructs.disable.null.includes("codeIndented") && tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], !0).length >= 4 ? ok2(code3) : effects.interrupt(self2.parser.constructs.flow, nok, ok2)(code3);
}
}
// node_modules/micromark-factory-destination/index.js
function factoryDestination(effects, ok2, nok, type, literalType2, literalMarkerType, rawType, stringType2, max) {
let limit = max || Number.POSITIVE_INFINITY, balance = 0;
return start;
function start(code3) {
return code3 === 60 ? (effects.enter(type), effects.enter(literalType2), effects.enter(literalMarkerType), effects.consume(code3), effects.exit(literalMarkerType), enclosedBefore) : code3 === null || code3 === 32 || code3 === 41 || asciiControl(code3) ? nok(code3) : (effects.enter(type), effects.enter(rawType), effects.enter(stringType2), effects.enter("chunkString", {
contentType: "string"
}), raw(code3));
}
function enclosedBefore(code3) {
return code3 === 62 ? (effects.enter(literalMarkerType), effects.consume(code3), effects.exit(literalMarkerType), effects.exit(literalType2), effects.exit(type), ok2) : (effects.enter(stringType2), effects.enter("chunkString", {
contentType: "string"
}), enclosed(code3));
}
function enclosed(code3) {
return code3 === 62 ? (effects.exit("chunkString"), effects.exit(stringType2), enclosedBefore(code3)) : code3 === null || code3 === 60 || markdownLineEnding(code3) ? nok(code3) : (effects.consume(code3), code3 === 92 ? enclosedEscape : enclosed);
}
function enclosedEscape(code3) {
return code3 === 60 || code3 === 62 || code3 === 92 ? (effects.consume(code3), enclosed) : enclosed(code3);
}
function raw(code3) {
return !balance && (code3 === null || code3 === 41 || markdownLineEndingOrSpace(code3)) ? (effects.exit("chunkString"), effects.exit(stringType2), effects.exit(rawType), effects.exit(type), ok2(code3)) : balance < limit && code3 === 40 ? (effects.consume(code3), balance++, raw) : code3 === 41 ? (effects.consume(code3), balance--, raw) : code3 === null || code3 === 32 || code3 === 40 || asciiControl(code3) ? nok(code3) : (effects.consume(code3), code3 === 92 ? rawEscape : raw);
}
function rawEscape(code3) {
return code3 === 40 || code3 === 41 || code3 === 92 ? (effects.consume(code3), raw) : raw(code3);
}
}
// node_modules/micromark-factory-label/index.js
function factoryLabel(effects, ok2, nok, type, markerType, stringType2) {
let self2 = this, size = 0, seen;
return start;
function start(code3) {
return effects.enter(type), effects.enter(markerType), effects.consume(code3), effects.exit(markerType), effects.enter(stringType2), atBreak;
}
function atBreak(code3) {
return size > 999 || code3 === null || code3 === 91 || code3 === 93 && !seen || // To do: remove in the future once we\u2019ve switched from
// \`micromark-extension-footnote\` to \`micromark-extension-gfm-footnote\`,
// which doesn\u2019t need this.
// Hidden footnotes hook.
/* c8 ignore next 3 */
code3 === 94 && !size && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code3) : code3 === 93 ? (effects.exit(stringType2), effects.enter(markerType), effects.consume(code3), effects.exit(markerType), effects.exit(type), ok2) : markdownLineEnding(code3) ? (effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), atBreak) : (effects.enter("chunkString", {
contentType: "string"
}), labelInside(code3));
}
function labelInside(code3) {
return code3 === null || code3 === 91 || code3 === 93 || markdownLineEnding(code3) || size++ > 999 ? (effects.exit("chunkString"), atBreak(code3)) : (effects.consume(code3), seen || (seen = !markdownSpace(code3)), code3 === 92 ? labelEscape : labelInside);
}
function labelEscape(code3) {
return code3 === 91 || code3 === 92 || code3 === 93 ? (effects.consume(code3), size++, labelInside) : labelInside(code3);
}
}
// node_modules/micromark-factory-title/index.js
function factoryTitle(effects, ok2, nok, type, markerType, stringType2) {
let marker;
return start;
function start(code3) {
return code3 === 34 || code3 === 39 || code3 === 40 ? (effects.enter(type), effects.enter(markerType), effects.consume(code3), effects.exit(markerType), marker = code3 === 40 ? 41 : code3, begin) : nok(code3);
}
function begin(code3) {
return code3 === marker ? (effects.enter(markerType), effects.consume(code3), effects.exit(markerType), effects.exit(type), ok2) : (effects.enter(stringType2), atBreak(code3));
}
function atBreak(code3) {
return code3 === marker ? (effects.exit(stringType2), begin(marker)) : code3 === null ? nok(code3) : markdownLineEnding(code3) ? (effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), factorySpace(effects, atBreak, "linePrefix")) : (effects.enter("chunkString", {
contentType: "string"
}), inside(code3));
}
function inside(code3) {
return code3 === marker || code3 === null || markdownLineEnding(code3) ? (effects.exit("chunkString"), atBreak(code3)) : (effects.consume(code3), code3 === 92 ? escape : inside);
}
function escape(code3) {
return code3 === marker || code3 === 92 ? (effects.consume(code3), inside) : inside(code3);
}
}
// node_modules/micromark-factory-whitespace/index.js
function factoryWhitespace(effects, ok2) {
let seen;
return start;
function start(code3) {
return markdownLineEnding(code3) ? (effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), seen = !0, start) : markdownSpace(code3) ? factorySpace(
effects,
start,
seen ? "linePrefix" : "lineSuffix"
)(code3) : ok2(code3);
}
}
// node_modules/micromark-core-commonmark/lib/definition.js
var definition = {
name: "definition",
tokenize: tokenizeDefinition
}, titleBefore = {
tokenize: tokenizeTitleBefore,
partial: !0
};
function tokenizeDefinition(effects, ok2, nok) {
let self2 = this, identifier;
return start;
function start(code3) {
return effects.enter("definition"), before(code3);
}
function before(code3) {
return factoryLabel.call(
self2,
effects,
labelAfter,
// Note: we don\u2019t need to reset the way \`markdown-rs\` does.
nok,
"definitionLabel",
"definitionLabelMarker",
"definitionLabelString"
)(code3);
}
function labelAfter(code3) {
return identifier = normalizeIdentifier(self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1)), code3 === 58 ? (effects.enter("definitionMarker"), effects.consume(code3), effects.exit("definitionMarker"), markerAfter) : nok(code3);
}
function markerAfter(code3) {
return markdownLineEndingOrSpace(code3) ? factoryWhitespace(effects, destinationBefore)(code3) : destinationBefore(code3);
}
function destinationBefore(code3) {
return factoryDestination(
effects,
destinationAfter,
// Note: we don\u2019t need to reset the way \`markdown-rs\` does.
nok,
"definitionDestination",
"definitionDestinationLiteral",
"definitionDestinationLiteralMarker",
"definitionDestinationRaw",
"definitionDestinationString"
)(code3);
}
function destinationAfter(code3) {
return effects.attempt(titleBefore, after, after)(code3);
}
function after(code3) {
return markdownSpace(code3) ? factorySpace(effects, afterWhitespace, "whitespace")(code3) : afterWhitespace(code3);
}
function afterWhitespace(code3) {
return code3 === null || markdownLineEnding(code3) ? (effects.exit("definition"), self2.parser.defined.push(identifier), ok2(code3)) : nok(code3);
}
}
function tokenizeTitleBefore(effects, ok2, nok) {
return titleBefore2;
function titleBefore2(code3) {
return markdownLineEndingOrSpace(code3) ? factoryWhitespace(effects, beforeMarker)(code3) : nok(code3);
}
function beforeMarker(code3) {
return factoryTitle(effects, titleAfter, nok, "definitionTitle", "definitionTitleMarker", "definitionTitleString")(code3);
}
function titleAfter(code3) {
return markdownSpace(code3) ? factorySpace(effects, titleAfterOptionalWhitespace, "whitespace")(code3) : titleAfterOptionalWhitespace(code3);
}
function titleAfterOptionalWhitespace(code3) {
return code3 === null || markdownLineEnding(code3) ? ok2(code3) : nok(code3);
}
}
// node_modules/micromark-core-commonmark/lib/hard-break-escape.js
var hardBreakEscape = {
name: "hardBreakEscape",
tokenize: tokenizeHardBreakEscape
};
function tokenizeHardBreakEscape(effects, ok2, nok) {
return start;
function start(code3) {
return effects.enter("hardBreakEscape"), effects.consume(code3), after;
}
function after(code3) {
return markdownLineEnding(code3) ? (effects.exit("hardBreakEscape"), ok2(code3)) : nok(code3);
}
}
// node_modules/micromark-core-commonmark/lib/heading-atx.js
var headingAtx = {
name: "headingAtx",
tokenize: tokenizeHeadingAtx,
resolve: resolveHeadingAtx
};
function resolveHeadingAtx(events, context) {
let contentEnd = events.length - 2, contentStart = 3, content3, text5;
return events[contentStart][1].type === "whitespace" && (contentStart += 2), contentEnd - 2 > contentStart && events[contentEnd][1].type === "whitespace" && (contentEnd -= 2), events[contentEnd][1].type === "atxHeadingSequence" && (contentStart === contentEnd - 1 || contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === "whitespace") && (contentEnd -= contentStart + 1 === contentEnd ? 2 : 4), contentEnd > contentStart && (content3 = {
type: "atxHeadingText",
start: events[contentStart][1].start,
end: events[contentEnd][1].end
}, text5 = {
type: "chunkText",
start: events[contentStart][1].start,
end: events[contentEnd][1].end,
contentType: "text"
}, splice(events, contentStart, contentEnd - contentStart + 1, [["enter", content3, context], ["enter", text5, context], ["exit", text5, context], ["exit", content3, context]])), events;
}
function tokenizeHeadingAtx(effects, ok2, nok) {
let size = 0;
return start;
function start(code3) {
return effects.enter("atxHeading"), before(code3);
}
function before(code3) {
return effects.enter("atxHeadingSequence"), sequenceOpen(code3);
}
function sequenceOpen(code3) {
return code3 === 35 && size++ < 6 ? (effects.consume(code3), sequenceOpen) : code3 === null || markdownLineEndingOrSpace(code3) ? (effects.exit("atxHeadingSequence"), atBreak(code3)) : nok(code3);
}
function atBreak(code3) {
return code3 === 35 ? (effects.enter("atxHeadingSequence"), sequenceFurther(code3)) : code3 === null || markdownLineEnding(code3) ? (effects.exit("atxHeading"), ok2(code3)) : markdownSpace(code3) ? factorySpace(effects, atBreak, "whitespace")(code3) : (effects.enter("atxHeadingText"), data(code3));
}
function sequenceFurther(code3) {
return code3 === 35 ? (effects.consume(code3), sequenceFurther) : (effects.exit("atxHeadingSequence"), atBreak(code3));
}
function data(code3) {
return code3 === null || code3 === 35 || markdownLineEndingOrSpace(code3) ? (effects.exit("atxHeadingText"), atBreak(code3)) : (effects.consume(code3), data);
}
}
// node_modules/micromark-util-html-tag-name/index.js
var htmlBlockNames = [
"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",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"head",
"header",
"hr",
"html",
"iframe",
"legend",
"li",
"link",
"main",
"menu",
"menuitem",
"nav",
"noframes",
"ol",
"optgroup",
"option",
"p",
"param",
"search",
"section",
"summary",
"table",
"tbody",
"td",
"tfoot",
"th",
"thead",
"title",
"tr",
"track",
"ul"
], htmlRawNames = ["pre", "script", "style", "textarea"];
// node_modules/micromark-core-commonmark/lib/html-flow.js
var htmlFlow = {
name: "htmlFlow",
tokenize: tokenizeHtmlFlow,
resolveTo: resolveToHtmlFlow,
concrete: !0
}, blankLineBefore = {
tokenize: tokenizeBlankLineBefore,
partial: !0
}, nonLazyContinuationStart = {
tokenize: tokenizeNonLazyContinuationStart,
partial: !0
};
function resolveToHtmlFlow(events) {
let index2 = events.length;
for (; index2-- && !(events[index2][0] === "enter" && events[index2][1].type === "htmlFlow"); )
;
return index2 > 1 && events[index2 - 2][1].type === "linePrefix" && (events[index2][1].start = events[index2 - 2][1].start, events[index2 + 1][1].start = events[index2 - 2][1].start, events.splice(index2 - 2, 2)), events;
}
function tokenizeHtmlFlow(effects, ok2, nok) {
let self2 = this, marker, closingTag, buffer, index2, markerB;
return start;
function start(code3) {
return before(code3);
}
function before(code3) {
return effects.enter("htmlFlow"), effects.enter("htmlFlowData"), effects.consume(code3), open;
}
function open(code3) {
return code3 === 33 ? (effects.consume(code3), declarationOpen) : code3 === 47 ? (effects.consume(code3), closingTag = !0, tagCloseStart) : code3 === 63 ? (effects.consume(code3), marker = 3, self2.interrupt ? ok2 : continuationDeclarationInside) : asciiAlpha(code3) ? (effects.consume(code3), buffer = String.fromCharCode(code3), tagName) : nok(code3);
}
function declarationOpen(code3) {
return code3 === 45 ? (effects.consume(code3), marker = 2, commentOpenInside) : code3 === 91 ? (effects.consume(code3), marker = 5, index2 = 0, cdataOpenInside) : asciiAlpha(code3) ? (effects.consume(code3), marker = 4, self2.interrupt ? ok2 : continuationDeclarationInside) : nok(code3);
}
function commentOpenInside(code3) {
return code3 === 45 ? (effects.consume(code3), self2.interrupt ? ok2 : continuationDeclarationInside) : nok(code3);
}
function cdataOpenInside(code3) {
let value = "CDATA[";
return code3 === value.charCodeAt(index2++) ? (effects.consume(code3), index2 === value.length ? self2.interrupt ? ok2 : continuation : cdataOpenInside) : nok(code3);
}
function tagCloseStart(code3) {
return asciiAlpha(code3) ? (effects.consume(code3), buffer = String.fromCharCode(code3), tagName) : nok(code3);
}
function tagName(code3) {
if (code3 === null || code3 === 47 || code3 === 62 || markdownLineEndingOrSpace(code3)) {
let slash = code3 === 47, name = buffer.toLowerCase();
return !slash && !closingTag && htmlRawNames.includes(name) ? (marker = 1, self2.interrupt ? ok2(code3) : continuation(code3)) : htmlBlockNames.includes(buffer.toLowerCase()) ? (marker = 6, slash ? (effects.consume(code3), basicSelfClosing) : self2.interrupt ? ok2(code3) : continuation(code3)) : (marker = 7, self2.interrupt && !self2.parser.lazy[self2.now().line] ? nok(code3) : closingTag ? completeClosingTagAfter(code3) : completeAttributeNameBefore(code3));
}
return code3 === 45 || asciiAlphanumeric(code3) ? (effects.consume(code3), buffer += String.fromCharCode(code3), tagName) : nok(code3);
}
function basicSelfClosing(code3) {
return code3 === 62 ? (effects.consume(code3), self2.interrupt ? ok2 : continuation) : nok(code3);
}
function completeClosingTagAfter(code3) {
return markdownSpace(code3) ? (effects.consume(code3), completeClosingTagAfter) : completeEnd(code3);
}
function completeAttributeNameBefore(code3) {
return code3 === 47 ? (effects.consume(code3), completeEnd) : code3 === 58 || code3 === 95 || asciiAlpha(code3) ? (effects.consume(code3), completeAttributeName) : markdownSpace(code3) ? (effects.consume(code3), completeAttributeNameBefore) : completeEnd(code3);
}
function completeAttributeName(code3) {
return code3 === 45 || code3 === 46 || code3 === 58 || code3 === 95 || asciiAlphanumeric(code3) ? (effects.consume(code3), completeAttributeName) : completeAttributeNameAfter(code3);
}
function completeAttributeNameAfter(code3) {
return code3 === 61 ? (effects.consume(code3), completeAttributeValueBefore) : markdownSpace(code3) ? (effects.consume(code3), completeAttributeNameAfter) : completeAttributeNameBefore(code3);
}
function completeAttributeValueBefore(code3) {
return code3 === null || code3 === 60 || code3 === 61 || code3 === 62 || code3 === 96 ? nok(code3) : code3 === 34 || code3 === 39 ? (effects.consume(code3), markerB = code3, completeAttributeValueQuoted) : markdownSpace(code3) ? (effects.consume(code3), completeAttributeValueBefore) : completeAttributeValueUnquoted(code3);
}
function completeAttributeValueQuoted(code3) {
return code3 === markerB ? (effects.consume(code3), markerB = null, completeAttributeValueQuotedAfter) : code3 === null || markdownLineEnding(code3) ? nok(code3) : (effects.consume(code3), completeAttributeValueQuoted);
}
function completeAttributeValueUnquoted(code3) {
return code3 === null || code3 === 34 || code3 === 39 || code3 === 47 || code3 === 60 || code3 === 61 || code3 === 62 || code3 === 96 || markdownLineEndingOrSpace(code3) ? completeAttributeNameAfter(code3) : (effects.consume(code3), completeAttributeValueUnquoted);
}
function completeAttributeValueQuotedAfter(code3) {
return code3 === 47 || code3 === 62 || markdownSpace(code3) ? completeAttributeNameBefore(code3) : nok(code3);
}
function completeEnd(code3) {
return code3 === 62 ? (effects.consume(code3), completeAfter) : nok(code3);
}
function completeAfter(code3) {
return code3 === null || markdownLineEnding(code3) ? continuation(code3) : markdownSpace(code3) ? (effects.consume(code3), completeAfter) : nok(code3);
}
function continuation(code3) {
return code3 === 45 && marker === 2 ? (effects.consume(code3), continuationCommentInside) : code3 === 60 && marker === 1 ? (effects.consume(code3), continuationRawTagOpen) : code3 === 62 && marker === 4 ? (effects.consume(code3), continuationClose) : code3 === 63 && marker === 3 ? (effects.consume(code3), continuationDeclarationInside) : code3 === 93 && marker === 5 ? (effects.consume(code3), continuationCdataInside) : markdownLineEnding(code3) && (marker === 6 || marker === 7) ? (effects.exit("htmlFlowData"), effects.check(blankLineBefore, continuationAfter, continuationStart)(code3)) : code3 === null || markdownLineEnding(code3) ? (effects.exit("htmlFlowData"), continuationStart(code3)) : (effects.consume(code3), continuation);
}
function continuationStart(code3) {
return effects.check(nonLazyContinuationStart, continuationStartNonLazy, continuationAfter)(code3);
}
function continuationStartNonLazy(code3) {
return effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), continuationBefore;
}
function continuationBefore(code3) {
return code3 === null || markdownLineEnding(code3) ? continuationStart(code3) : (effects.enter("htmlFlowData"), continuation(code3));
}
function continuationCommentInside(code3) {
return code3 === 45 ? (effects.consume(code3), continuationDeclarationInside) : continuation(code3);
}
function continuationRawTagOpen(code3) {
return code3 === 47 ? (effects.consume(code3), buffer = "", continuationRawEndTag) : continuation(code3);
}
function continuationRawEndTag(code3) {
if (code3 === 62) {
let name = buffer.toLowerCase();
return htmlRawNames.includes(name) ? (effects.consume(code3), continuationClose) : continuation(code3);
}
return asciiAlpha(code3) && buffer.length < 8 ? (effects.consume(code3), buffer += String.fromCharCode(code3), continuationRawEndTag) : continuation(code3);
}
function continuationCdataInside(code3) {
return code3 === 93 ? (effects.consume(code3), continuationDeclarationInside) : continuation(code3);
}
function continuationDeclarationInside(code3) {
return code3 === 62 ? (effects.consume(code3), continuationClose) : code3 === 45 && marker === 2 ? (effects.consume(code3), continuationDeclarationInside) : continuation(code3);
}
function continuationClose(code3) {
return code3 === null || markdownLineEnding(code3) ? (effects.exit("htmlFlowData"), continuationAfter(code3)) : (effects.consume(code3), continuationClose);
}
function continuationAfter(code3) {
return effects.exit("htmlFlow"), ok2(code3);
}
}
function tokenizeNonLazyContinuationStart(effects, ok2, nok) {
let self2 = this;
return start;
function start(code3) {
return markdownLineEnding(code3) ? (effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), after) : nok(code3);
}
function after(code3) {
return self2.parser.lazy[self2.now().line] ? nok(code3) : ok2(code3);
}
}
function tokenizeBlankLineBefore(effects, ok2, nok) {
return start;
function start(code3) {
return effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), effects.attempt(blankLine, ok2, nok);
}
}
// node_modules/micromark-core-commonmark/lib/html-text.js
var htmlText = {
name: "htmlText",
tokenize: tokenizeHtmlText
};
function tokenizeHtmlText(effects, ok2, nok) {
let self2 = this, marker, index2, returnState;
return start;
function start(code3) {
return effects.enter("htmlText"), effects.enter("htmlTextData"), effects.consume(code3), open;
}
function open(code3) {
return code3 === 33 ? (effects.consume(code3), declarationOpen) : code3 === 47 ? (effects.consume(code3), tagCloseStart) : code3 === 63 ? (effects.consume(code3), instruction) : asciiAlpha(code3) ? (effects.consume(code3), tagOpen) : nok(code3);
}
function declarationOpen(code3) {
return code3 === 45 ? (effects.consume(code3), commentOpenInside) : code3 === 91 ? (effects.consume(code3), index2 = 0, cdataOpenInside) : asciiAlpha(code3) ? (effects.consume(code3), declaration) : nok(code3);
}
function commentOpenInside(code3) {
return code3 === 45 ? (effects.consume(code3), commentEnd) : nok(code3);
}
function comment(code3) {
return code3 === null ? nok(code3) : code3 === 45 ? (effects.consume(code3), commentClose) : markdownLineEnding(code3) ? (returnState = comment, lineEndingBefore(code3)) : (effects.consume(code3), comment);
}
function commentClose(code3) {
return code3 === 45 ? (effects.consume(code3), commentEnd) : comment(code3);
}
function commentEnd(code3) {
return code3 === 62 ? end(code3) : code3 === 45 ? commentClose(code3) : comment(code3);
}
function cdataOpenInside(code3) {
let value = "CDATA[";
return code3 === value.charCodeAt(index2++) ? (effects.consume(code3), index2 === value.length ? cdata : cdataOpenInside) : nok(code3);
}
function cdata(code3) {
return code3 === null ? nok(code3) : code3 === 93 ? (effects.consume(code3), cdataClose) : markdownLineEnding(code3) ? (returnState = cdata, lineEndingBefore(code3)) : (effects.consume(code3), cdata);
}
function cdataClose(code3) {
return code3 === 93 ? (effects.consume(code3), cdataEnd) : cdata(code3);
}
function cdataEnd(code3) {
return code3 === 62 ? end(code3) : code3 === 93 ? (effects.consume(code3), cdataEnd) : cdata(code3);
}
function declaration(code3) {
return code3 === null || code3 === 62 ? end(code3) : markdownLineEnding(code3) ? (returnState = declaration, lineEndingBefore(code3)) : (effects.consume(code3), declaration);
}
function instruction(code3) {
return code3 === null ? nok(code3) : code3 === 63 ? (effects.consume(code3), instructionClose) : markdownLineEnding(code3) ? (returnState = instruction, lineEndingBefore(code3)) : (effects.consume(code3), instruction);
}
function instructionClose(code3) {
return code3 === 62 ? end(code3) : instruction(code3);
}
function tagCloseStart(code3) {
return asciiAlpha(code3) ? (effects.consume(code3), tagClose) : nok(code3);
}
function tagClose(code3) {
return code3 === 45 || asciiAlphanumeric(code3) ? (effects.consume(code3), tagClose) : tagCloseBetween(code3);
}
function tagCloseBetween(code3) {
return markdownLineEnding(code3) ? (returnState = tagCloseBetween, lineEndingBefore(code3)) : markdownSpace(code3) ? (effects.consume(code3), tagCloseBetween) : end(code3);
}
function tagOpen(code3) {
return code3 === 45 || asciiAlphanumeric(code3) ? (effects.consume(code3), tagOpen) : code3 === 47 || code3 === 62 || markdownLineEndingOrSpace(code3) ? tagOpenBetween(code3) : nok(code3);
}
function tagOpenBetween(code3) {
return code3 === 47 ? (effects.consume(code3), end) : code3 === 58 || code3 === 95 || asciiAlpha(code3) ? (effects.consume(code3), tagOpenAttributeName) : markdownLineEnding(code3) ? (returnState = tagOpenBetween, lineEndingBefore(code3)) : markdownSpace(code3) ? (effects.consume(code3), tagOpenBetween) : end(code3);
}
function tagOpenAttributeName(code3) {
return code3 === 45 || code3 === 46 || code3 === 58 || code3 === 95 || asciiAlphanumeric(code3) ? (effects.consume(code3), tagOpenAttributeName) : tagOpenAttributeNameAfter(code3);
}
function tagOpenAttributeNameAfter(code3) {
return code3 === 61 ? (effects.consume(code3), tagOpenAttributeValueBefore) : markdownLineEnding(code3) ? (returnState = tagOpenAttributeNameAfter, lineEndingBefore(code3)) : markdownSpace(code3) ? (effects.consume(code3), tagOpenAttributeNameAfter) : tagOpenBetween(code3);
}
function tagOpenAttributeValueBefore(code3) {
return code3 === null || code3 === 60 || code3 === 61 || code3 === 62 || code3 === 96 ? nok(code3) : code3 === 34 || code3 === 39 ? (effects.consume(code3), marker = code3, tagOpenAttributeValueQuoted) : markdownLineEnding(code3) ? (returnState = tagOpenAttributeValueBefore, lineEndingBefore(code3)) : markdownSpace(code3) ? (effects.consume(code3), tagOpenAttributeValueBefore) : (effects.consume(code3), tagOpenAttributeValueUnquoted);
}
function tagOpenAttributeValueQuoted(code3) {
return code3 === marker ? (effects.consume(code3), marker = void 0, tagOpenAttributeValueQuotedAfter) : code3 === null ? nok(code3) : markdownLineEnding(code3) ? (returnState = tagOpenAttributeValueQuoted, lineEndingBefore(code3)) : (effects.consume(code3), tagOpenAttributeValueQuoted);
}
function tagOpenAttributeValueUnquoted(code3) {
return code3 === null || code3 === 34 || code3 === 39 || code3 === 60 || code3 === 61 || code3 === 96 ? nok(code3) : code3 === 47 || code3 === 62 || markdownLineEndingOrSpace(code3) ? tagOpenBetween(code3) : (effects.consume(code3), tagOpenAttributeValueUnquoted);
}
function tagOpenAttributeValueQuotedAfter(code3) {
return code3 === 47 || code3 === 62 || markdownLineEndingOrSpace(code3) ? tagOpenBetween(code3) : nok(code3);
}
function end(code3) {
return code3 === 62 ? (effects.consume(code3), effects.exit("htmlTextData"), effects.exit("htmlText"), ok2) : nok(code3);
}
function lineEndingBefore(code3) {
return effects.exit("htmlTextData"), effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), lineEndingAfter;
}
function lineEndingAfter(code3) {
return markdownSpace(code3) ? factorySpace(effects, lineEndingAfterPrefix, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code3) : lineEndingAfterPrefix(code3);
}
function lineEndingAfterPrefix(code3) {
return effects.enter("htmlTextData"), returnState(code3);
}
}
// node_modules/micromark-core-commonmark/lib/label-end.js
var labelEnd = {
name: "labelEnd",
tokenize: tokenizeLabelEnd,
resolveTo: resolveToLabelEnd,
resolveAll: resolveAllLabelEnd
}, resourceConstruct = {
tokenize: tokenizeResource
}, referenceFullConstruct = {
tokenize: tokenizeReferenceFull
}, referenceCollapsedConstruct = {
tokenize: tokenizeReferenceCollapsed
};
function resolveAllLabelEnd(events) {
let index2 = -1;
for (; ++index2 < events.length; ) {
let token = events[index2][1];
(token.type === "labelImage" || token.type === "labelLink" || token.type === "labelEnd") && (events.splice(index2 + 1, token.type === "labelImage" ? 4 : 2), token.type = "data", index2++);
}
return events;
}
function resolveToLabelEnd(events, context) {
let index2 = events.length, offset = 0, token, open, close, media;
for (; index2--; )
if (token = events[index2][1], open) {
if (token.type === "link" || token.type === "labelLink" && token._inactive)
break;
events[index2][0] === "enter" && token.type === "labelLink" && (token._inactive = !0);
} else if (close) {
if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced && (open = index2, token.type !== "labelLink")) {
offset = 2;
break;
}
} else token.type === "labelEnd" && (close = index2);
let group = {
type: events[open][1].type === "labelLink" ? "link" : "image",
start: Object.assign({}, events[open][1].start),
end: Object.assign({}, events[events.length - 1][1].end)
}, label = {
type: "label",
start: Object.assign({}, events[open][1].start),
end: Object.assign({}, events[close][1].end)
}, text5 = {
type: "labelText",
start: Object.assign({}, events[open + offset + 2][1].end),
end: Object.assign({}, events[close - 2][1].start)
};
return media = [["enter", group, context], ["enter", label, context]], media = push(media, events.slice(open + 1, open + offset + 3)), media = push(media, [["enter", text5, context]]), media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context)), media = push(media, [["exit", text5, context], events[close - 2], events[close - 1], ["exit", label, context]]), media = push(media, events.slice(close + 1)), media = push(media, [["exit", group, context]]), splice(events, open, events.length, media), events;
}
function tokenizeLabelEnd(effects, ok2, nok) {
let self2 = this, index2 = self2.events.length, labelStart, defined;
for (; index2--; )
if ((self2.events[index2][1].type === "labelImage" || self2.events[index2][1].type === "labelLink") && !self2.events[index2][1]._balanced) {
labelStart = self2.events[index2][1];
break;
}
return start;
function start(code3) {
return labelStart ? labelStart._inactive ? labelEndNok(code3) : (defined = self2.parser.defined.includes(normalizeIdentifier(self2.sliceSerialize({
start: labelStart.end,
end: self2.now()
}))), effects.enter("labelEnd"), effects.enter("labelMarker"), effects.consume(code3), effects.exit("labelMarker"), effects.exit("labelEnd"), after) : nok(code3);
}
function after(code3) {
return code3 === 40 ? effects.attempt(resourceConstruct, labelEndOk, defined ? labelEndOk : labelEndNok)(code3) : code3 === 91 ? effects.attempt(referenceFullConstruct, labelEndOk, defined ? referenceNotFull : labelEndNok)(code3) : defined ? labelEndOk(code3) : labelEndNok(code3);
}
function referenceNotFull(code3) {
return effects.attempt(referenceCollapsedConstruct, labelEndOk, labelEndNok)(code3);
}
function labelEndOk(code3) {
return ok2(code3);
}
function labelEndNok(code3) {
return labelStart._balanced = !0, nok(code3);
}
}
function tokenizeResource(effects, ok2, nok) {
return resourceStart;
function resourceStart(code3) {
return effects.enter("resource"), effects.enter("resourceMarker"), effects.consume(code3), effects.exit("resourceMarker"), resourceBefore;
}
function resourceBefore(code3) {
return markdownLineEndingOrSpace(code3) ? factoryWhitespace(effects, resourceOpen)(code3) : resourceOpen(code3);
}
function resourceOpen(code3) {
return code3 === 41 ? resourceEnd(code3) : factoryDestination(effects, resourceDestinationAfter, resourceDestinationMissing, "resourceDestination", "resourceDestinationLiteral", "resourceDestinationLiteralMarker", "resourceDestinationRaw", "resourceDestinationString", 32)(code3);
}
function resourceDestinationAfter(code3) {
return markdownLineEndingOrSpace(code3) ? factoryWhitespace(effects, resourceBetween)(code3) : resourceEnd(code3);
}
function resourceDestinationMissing(code3) {
return nok(code3);
}
function resourceBetween(code3) {
return code3 === 34 || code3 === 39 || code3 === 40 ? factoryTitle(effects, resourceTitleAfter, nok, "resourceTitle", "resourceTitleMarker", "resourceTitleString")(code3) : resourceEnd(code3);
}
function resourceTitleAfter(code3) {
return markdownLineEndingOrSpace(code3) ? factoryWhitespace(effects, resourceEnd)(code3) : resourceEnd(code3);
}
function resourceEnd(code3) {
return code3 === 41 ? (effects.enter("resourceMarker"), effects.consume(code3), effects.exit("resourceMarker"), effects.exit("resource"), ok2) : nok(code3);
}
}
function tokenizeReferenceFull(effects, ok2, nok) {
let self2 = this;
return referenceFull;
function referenceFull(code3) {
return factoryLabel.call(self2, effects, referenceFullAfter, referenceFullMissing, "reference", "referenceMarker", "referenceString")(code3);
}
function referenceFullAfter(code3) {
return self2.parser.defined.includes(normalizeIdentifier(self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1))) ? ok2(code3) : nok(code3);
}
function referenceFullMissing(code3) {
return nok(code3);
}
}
function tokenizeReferenceCollapsed(effects, ok2, nok) {
return referenceCollapsedStart;
function referenceCollapsedStart(code3) {
return effects.enter("reference"), effects.enter("referenceMarker"), effects.consume(code3), effects.exit("referenceMarker"), referenceCollapsedOpen;
}
function referenceCollapsedOpen(code3) {
return code3 === 93 ? (effects.enter("referenceMarker"), effects.consume(code3), effects.exit("referenceMarker"), effects.exit("reference"), ok2) : nok(code3);
}
}
// node_modules/micromark-core-commonmark/lib/label-start-image.js
var labelStartImage = {
name: "labelStartImage",
tokenize: tokenizeLabelStartImage,
resolveAll: labelEnd.resolveAll
};
function tokenizeLabelStartImage(effects, ok2, nok) {
let self2 = this;
return start;
function start(code3) {
return effects.enter("labelImage"), effects.enter("labelImageMarker"), effects.consume(code3), effects.exit("labelImageMarker"), open;
}
function open(code3) {
return code3 === 91 ? (effects.enter("labelMarker"), effects.consume(code3), effects.exit("labelMarker"), effects.exit("labelImage"), after) : nok(code3);
}
function after(code3) {
return code3 === 94 && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code3) : ok2(code3);
}
}
// node_modules/micromark-core-commonmark/lib/label-start-link.js
var labelStartLink = {
name: "labelStartLink",
tokenize: tokenizeLabelStartLink,
resolveAll: labelEnd.resolveAll
};
function tokenizeLabelStartLink(effects, ok2, nok) {
let self2 = this;
return start;
function start(code3) {
return effects.enter("labelLink"), effects.enter("labelMarker"), effects.consume(code3), effects.exit("labelMarker"), effects.exit("labelLink"), after;
}
function after(code3) {
return code3 === 94 && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code3) : ok2(code3);
}
}
// node_modules/micromark-core-commonmark/lib/line-ending.js
var lineEnding = {
name: "lineEnding",
tokenize: tokenizeLineEnding
};
function tokenizeLineEnding(effects, ok2) {
return start;
function start(code3) {
return effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), factorySpace(effects, ok2, "linePrefix");
}
}
// node_modules/micromark-core-commonmark/lib/thematic-break.js
var thematicBreak = {
name: "thematicBreak",
tokenize: tokenizeThematicBreak
};
function tokenizeThematicBreak(effects, ok2, nok) {
let size = 0, marker;
return start;
function start(code3) {
return effects.enter("thematicBreak"), before(code3);
}
function before(code3) {
return marker = code3, atBreak(code3);
}
function atBreak(code3) {
return code3 === marker ? (effects.enter("thematicBreakSequence"), sequence(code3)) : size >= 3 && (code3 === null || markdownLineEnding(code3)) ? (effects.exit("thematicBreak"), ok2(code3)) : nok(code3);
}
function sequence(code3) {
return code3 === marker ? (effects.consume(code3), size++, sequence) : (effects.exit("thematicBreakSequence"), markdownSpace(code3) ? factorySpace(effects, atBreak, "whitespace")(code3) : atBreak(code3));
}
}
// node_modules/micromark-core-commonmark/lib/list.js
var list = {
name: "list",
tokenize: tokenizeListStart,
continuation: {
tokenize: tokenizeListContinuation
},
exit: tokenizeListEnd
}, listItemPrefixWhitespaceConstruct = {
tokenize: tokenizeListItemPrefixWhitespace,
partial: !0
}, indentConstruct = {
tokenize: tokenizeIndent,
partial: !0
};
function tokenizeListStart(effects, ok2, nok) {
let self2 = this, tail = self2.events[self2.events.length - 1], initialSize = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], !0).length : 0, size = 0;
return start;
function start(code3) {
let kind = self2.containerState.type || (code3 === 42 || code3 === 43 || code3 === 45 ? "listUnordered" : "listOrdered");
if (kind === "listUnordered" ? !self2.containerState.marker || code3 === self2.containerState.marker : asciiDigit(code3)) {
if (self2.containerState.type || (self2.containerState.type = kind, effects.enter(kind, {
_container: !0
})), kind === "listUnordered")
return effects.enter("listItemPrefix"), code3 === 42 || code3 === 45 ? effects.check(thematicBreak, nok, atMarker)(code3) : atMarker(code3);
if (!self2.interrupt || code3 === 49)
return effects.enter("listItemPrefix"), effects.enter("listItemValue"), inside(code3);
}
return nok(code3);
}
function inside(code3) {
return asciiDigit(code3) && ++size < 10 ? (effects.consume(code3), inside) : (!self2.interrupt || size < 2) && (self2.containerState.marker ? code3 === self2.containerState.marker : code3 === 41 || code3 === 46) ? (effects.exit("listItemValue"), atMarker(code3)) : nok(code3);
}
function atMarker(code3) {
return effects.enter("listItemMarker"), effects.consume(code3), effects.exit("listItemMarker"), self2.containerState.marker = self2.containerState.marker || code3, effects.check(
blankLine,
// Can\u2019t be empty when interrupting.
self2.interrupt ? nok : onBlank,
effects.attempt(listItemPrefixWhitespaceConstruct, endOfPrefix, otherPrefix)
);
}
function onBlank(code3) {
return self2.containerState.initialBlankLine = !0, initialSize++, endOfPrefix(code3);
}
function otherPrefix(code3) {
return markdownSpace(code3) ? (effects.enter("listItemPrefixWhitespace"), effects.consume(code3), effects.exit("listItemPrefixWhitespace"), endOfPrefix) : nok(code3);
}
function endOfPrefix(code3) {
return self2.containerState.size = initialSize + self2.sliceSerialize(effects.exit("listItemPrefix"), !0).length, ok2(code3);
}
}
function tokenizeListContinuation(effects, ok2, nok) {
let self2 = this;
return self2.containerState._closeFlow = void 0, effects.check(blankLine, onBlank, notBlank);
function onBlank(code3) {
return self2.containerState.furtherBlankLines = self2.containerState.furtherBlankLines || self2.containerState.initialBlankLine, factorySpace(effects, ok2, "listItemIndent", self2.containerState.size + 1)(code3);
}
function notBlank(code3) {
return self2.containerState.furtherBlankLines || !markdownSpace(code3) ? (self2.containerState.furtherBlankLines = void 0, self2.containerState.initialBlankLine = void 0, notInCurrentItem(code3)) : (self2.containerState.furtherBlankLines = void 0, self2.containerState.initialBlankLine = void 0, effects.attempt(indentConstruct, ok2, notInCurrentItem)(code3));
}
function notInCurrentItem(code3) {
return self2.containerState._closeFlow = !0, self2.interrupt = void 0, factorySpace(effects, effects.attempt(list, ok2, nok), "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code3);
}
}
function tokenizeIndent(effects, ok2, nok) {
let self2 = this;
return factorySpace(effects, afterPrefix, "listItemIndent", self2.containerState.size + 1);
function afterPrefix(code3) {
let tail = self2.events[self2.events.length - 1];
return tail && tail[1].type === "listItemIndent" && tail[2].sliceSerialize(tail[1], !0).length === self2.containerState.size ? ok2(code3) : nok(code3);
}
}
function tokenizeListEnd(effects) {
effects.exit(this.containerState.type);
}
function tokenizeListItemPrefixWhitespace(effects, ok2, nok) {
let self2 = this;
return factorySpace(effects, afterPrefix, "listItemPrefixWhitespace", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 5);
function afterPrefix(code3) {
let tail = self2.events[self2.events.length - 1];
return !markdownSpace(code3) && tail && tail[1].type === "listItemPrefixWhitespace" ? ok2(code3) : nok(code3);
}
}
// node_modules/micromark-core-commonmark/lib/setext-underline.js
var setextUnderline = {
name: "setextUnderline",
tokenize: tokenizeSetextUnderline,
resolveTo: resolveToSetextUnderline
};
function resolveToSetextUnderline(events, context) {
let index2 = events.length, content3, text5, definition3;
for (; index2--; )
if (events[index2][0] === "enter") {
if (events[index2][1].type === "content") {
content3 = index2;
break;
}
events[index2][1].type === "paragraph" && (text5 = index2);
} else
events[index2][1].type === "content" && events.splice(index2, 1), !definition3 && events[index2][1].type === "definition" && (definition3 = index2);
let heading2 = {
type: "setextHeading",
start: Object.assign({}, events[text5][1].start),
end: Object.assign({}, events[events.length - 1][1].end)
};
return events[text5][1].type = "setextHeadingText", definition3 ? (events.splice(text5, 0, ["enter", heading2, context]), events.splice(definition3 + 1, 0, ["exit", events[content3][1], context]), events[content3][1].end = Object.assign({}, events[definition3][1].end)) : events[content3][1] = heading2, events.push(["exit", heading2, context]), events;
}
function tokenizeSetextUnderline(effects, ok2, nok) {
let self2 = this, marker;
return start;
function start(code3) {
let index2 = self2.events.length, paragraph2;
for (; index2--; )
if (self2.events[index2][1].type !== "lineEnding" && self2.events[index2][1].type !== "linePrefix" && self2.events[index2][1].type !== "content") {
paragraph2 = self2.events[index2][1].type === "paragraph";
break;
}
return !self2.parser.lazy[self2.now().line] && (self2.interrupt || paragraph2) ? (effects.enter("setextHeadingLine"), marker = code3, before(code3)) : nok(code3);
}
function before(code3) {
return effects.enter("setextHeadingLineSequence"), inside(code3);
}
function inside(code3) {
return code3 === marker ? (effects.consume(code3), inside) : (effects.exit("setextHeadingLineSequence"), markdownSpace(code3) ? factorySpace(effects, after, "lineSuffix")(code3) : after(code3));
}
function after(code3) {
return code3 === null || markdownLineEnding(code3) ? (effects.exit("setextHeadingLine"), ok2(code3)) : nok(code3);
}
}
// node_modules/micromark/lib/initialize/flow.js
var flow = {
tokenize: initializeFlow
};
function initializeFlow(effects) {
let self2 = this, initial = effects.attempt(
// Try to parse a blank line.
blankLine,
atBlankEnding,
// Try to parse initial flow (essentially, only code).
effects.attempt(
this.parser.constructs.flowInitial,
afterConstruct,
factorySpace(
effects,
effects.attempt(
this.parser.constructs.flow,
afterConstruct,
effects.attempt(content2, afterConstruct)
),
"linePrefix"
)
)
);
return initial;
function atBlankEnding(code3) {
if (code3 === null) {
effects.consume(code3);
return;
}
return effects.enter("lineEndingBlank"), effects.consume(code3), effects.exit("lineEndingBlank"), self2.currentConstruct = void 0, initial;
}
function afterConstruct(code3) {
if (code3 === null) {
effects.consume(code3);
return;
}
return effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), self2.currentConstruct = void 0, initial;
}
}
// node_modules/micromark/lib/initialize/text.js
var resolver = {
resolveAll: createResolver()
}, string = initializeFactory("string"), text = initializeFactory("text");
function initializeFactory(field) {
return {
tokenize: initializeText,
resolveAll: createResolver(
field === "text" ? resolveAllLineSuffixes : void 0
)
};
function initializeText(effects) {
let self2 = this, constructs2 = this.parser.constructs[field], text5 = effects.attempt(constructs2, start, notText);
return start;
function start(code3) {
return atBreak(code3) ? text5(code3) : notText(code3);
}
function notText(code3) {
if (code3 === null) {
effects.consume(code3);
return;
}
return effects.enter("data"), effects.consume(code3), data;
}
function data(code3) {
return atBreak(code3) ? (effects.exit("data"), text5(code3)) : (effects.consume(code3), data);
}
function atBreak(code3) {
if (code3 === null)
return !0;
let list3 = constructs2[code3], index2 = -1;
if (list3)
for (; ++index2 < list3.length; ) {
let item = list3[index2];
if (!item.previous || item.previous.call(self2, self2.previous))
return !0;
}
return !1;
}
}
}
function createResolver(extraResolver) {
return resolveAllText;
function resolveAllText(events, context) {
let index2 = -1, enter;
for (; ++index2 <= events.length; )
enter === void 0 ? events[index2] && events[index2][1].type === "data" && (enter = index2, index2++) : (!events[index2] || events[index2][1].type !== "data") && (index2 !== enter + 2 && (events[enter][1].end = events[index2 - 1][1].end, events.splice(enter + 2, index2 - enter - 2), index2 = enter + 2), enter = void 0);
return extraResolver ? extraResolver(events, context) : events;
}
}
function resolveAllLineSuffixes(events, context) {
let eventIndex = 0;
for (; ++eventIndex <= events.length; )
if ((eventIndex === events.length || events[eventIndex][1].type === "lineEnding") && events[eventIndex - 1][1].type === "data") {
let data = events[eventIndex - 1][1], chunks = context.sliceStream(data), index2 = chunks.length, bufferIndex = -1, size = 0, tabs;
for (; index2--; ) {
let chunk = chunks[index2];
if (typeof chunk == "string") {
for (bufferIndex = chunk.length; chunk.charCodeAt(bufferIndex - 1) === 32; )
size++, bufferIndex--;
if (bufferIndex) break;
bufferIndex = -1;
} else if (chunk === -2)
tabs = !0, size++;
else if (chunk !== -1) {
index2++;
break;
}
}
if (size) {
let token = {
type: eventIndex === events.length || tabs || size < 2 ? "lineSuffix" : "hardBreakTrailing",
start: {
line: data.end.line,
column: data.end.column - size,
offset: data.end.offset - size,
_index: data.start._index + index2,
_bufferIndex: index2 ? bufferIndex : data.start._bufferIndex + bufferIndex
},
end: Object.assign({}, data.end)
};
data.end = Object.assign({}, token.start), data.start.offset === data.end.offset ? Object.assign(data, token) : (events.splice(
eventIndex,
0,
["enter", token, context],
["exit", token, context]
), eventIndex += 2);
}
eventIndex++;
}
return events;
}
// node_modules/micromark/lib/create-tokenizer.js
function createTokenizer(parser, initialize, from) {
let point3 = Object.assign(
from ? Object.assign({}, from) : {
line: 1,
column: 1,
offset: 0
},
{
_index: 0,
_bufferIndex: -1
}
), columnStart = {}, resolveAllConstructs = [], chunks = [], stack = [], consumed = !0, effects = {
consume,
enter,
exit: exit3,
attempt: constructFactory(onsuccessfulconstruct),
check: constructFactory(onsuccessfulcheck),
interrupt: constructFactory(onsuccessfulcheck, {
interrupt: !0
})
}, context = {
previous: null,
code: null,
containerState: {},
events: [],
parser,
sliceStream,
sliceSerialize,
now,
defineSkip,
write
}, state = initialize.tokenize.call(context, effects), expectedCode;
return initialize.resolveAll && resolveAllConstructs.push(initialize), context;
function write(slice) {
return chunks = push(chunks, slice), main(), chunks[chunks.length - 1] !== null ? [] : (addResult(initialize, 0), context.events = resolveAll(resolveAllConstructs, context.events, context), context.events);
}
function sliceSerialize(token, expandTabs) {
return serializeChunks(sliceStream(token), expandTabs);
}
function sliceStream(token) {
return sliceChunks(chunks, token);
}
function now() {
let { line, column, offset, _index, _bufferIndex } = point3;
return {
line,
column,
offset,
_index,
_bufferIndex
};
}
function defineSkip(value) {
columnStart[value.line] = value.column, accountForPotentialSkip();
}
function main() {
let chunkIndex;
for (; point3._index < chunks.length; ) {
let chunk = chunks[point3._index];
if (typeof chunk == "string")
for (chunkIndex = point3._index, point3._bufferIndex < 0 && (point3._bufferIndex = 0); point3._index === chunkIndex && point3._bufferIndex < chunk.length; )
go(chunk.charCodeAt(point3._bufferIndex));
else
go(chunk);
}
}
function go(code3) {
consumed = void 0, expectedCode = code3, state = state(code3);
}
function consume(code3) {
markdownLineEnding(code3) ? (point3.line++, point3.column = 1, point3.offset += code3 === -3 ? 2 : 1, accountForPotentialSkip()) : code3 !== -1 && (point3.column++, point3.offset++), point3._bufferIndex < 0 ? point3._index++ : (point3._bufferIndex++, point3._bufferIndex === chunks[point3._index].length && (point3._bufferIndex = -1, point3._index++)), context.previous = code3, consumed = !0;
}
function enter(type, fields) {
let token = fields || {};
return token.type = type, token.start = now(), context.events.push(["enter", token, context]), stack.push(token), token;
}
function exit3(type) {
let token = stack.pop();
return token.end = now(), context.events.push(["exit", token, context]), token;
}
function onsuccessfulconstruct(construct, info) {
addResult(construct, info.from);
}
function onsuccessfulcheck(_, info) {
info.restore();
}
function constructFactory(onreturn, fields) {
return hook;
function hook(constructs2, returnState, bogusState) {
let listOfConstructs, constructIndex, currentConstruct, info;
return Array.isArray(constructs2) ? handleListOfConstructs(constructs2) : "tokenize" in constructs2 ? (
// @ts-expect-error Looks like a construct.
handleListOfConstructs([constructs2])
) : handleMapOfConstructs(constructs2);
function handleMapOfConstructs(map4) {
return start;
function start(code3) {
let def = code3 !== null && map4[code3], all2 = code3 !== null && map4.null, list3 = [
// To do: add more extension tests.
/* c8 ignore next 2 */
...Array.isArray(def) ? def : def ? [def] : [],
...Array.isArray(all2) ? all2 : all2 ? [all2] : []
];
return handleListOfConstructs(list3)(code3);
}
}
function handleListOfConstructs(list3) {
return listOfConstructs = list3, constructIndex = 0, list3.length === 0 ? bogusState : handleConstruct(list3[constructIndex]);
}
function handleConstruct(construct) {
return start;
function start(code3) {
return info = store(), currentConstruct = construct, construct.partial || (context.currentConstruct = construct), construct.name && context.parser.constructs.disable.null.includes(construct.name) ? nok(code3) : construct.tokenize.call(
// If we do have fields, create an object w/ \`context\` as its
// prototype.
// This allows a \u201Clive binding\u201D, which is needed for \`interrupt\`.
fields ? Object.assign(Object.create(context), fields) : context,
effects,
ok2,
nok
)(code3);
}
}
function ok2(code3) {
return consumed = !0, onreturn(currentConstruct, info), returnState;
}
function nok(code3) {
return consumed = !0, info.restore(), ++constructIndex < listOfConstructs.length ? handleConstruct(listOfConstructs[constructIndex]) : bogusState;
}
}
}
function addResult(construct, from2) {
construct.resolveAll && !resolveAllConstructs.includes(construct) && resolveAllConstructs.push(construct), construct.resolve && splice(
context.events,
from2,
context.events.length - from2,
construct.resolve(context.events.slice(from2), context)
), construct.resolveTo && (context.events = construct.resolveTo(context.events, context));
}
function store() {
let startPoint = now(), startPrevious = context.previous, startCurrentConstruct = context.currentConstruct, startEventsIndex = context.events.length, startStack = Array.from(stack);
return {
restore,
from: startEventsIndex
};
function restore() {
point3 = startPoint, context.previous = startPrevious, context.currentConstruct = startCurrentConstruct, context.events.length = startEventsIndex, stack = startStack, accountForPotentialSkip();
}
}
function accountForPotentialSkip() {
point3.line in columnStart && point3.column < 2 && (point3.column = columnStart[point3.line], point3.offset += columnStart[point3.line] - 1);
}
}
function sliceChunks(chunks, token) {
let startIndex = token.start._index, startBufferIndex = token.start._bufferIndex, endIndex = token.end._index, endBufferIndex = token.end._bufferIndex, view;
if (startIndex === endIndex)
view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)];
else {
if (view = chunks.slice(startIndex, endIndex), startBufferIndex > -1) {
let head = view[0];
typeof head == "string" ? view[0] = head.slice(startBufferIndex) : view.shift();
}
endBufferIndex > 0 && view.push(chunks[endIndex].slice(0, endBufferIndex));
}
return view;
}
function serializeChunks(chunks, expandTabs) {
let index2 = -1, result = [], atTab;
for (; ++index2 < chunks.length; ) {
let chunk = chunks[index2], value;
if (typeof chunk == "string")
value = chunk;
else
switch (chunk) {
case -5: {
value = "\\r";
break;
}
case -4: {
value = \`
\`;
break;
}
case -3: {
value = \`\\r
\`;
break;
}
case -2: {
value = expandTabs ? " " : " ";
break;
}
case -1: {
if (!expandTabs && atTab) continue;
value = " ";
break;
}
default:
value = String.fromCharCode(chunk);
}
atTab = chunk === -2, result.push(value);
}
return result.join("");
}
// node_modules/micromark/lib/constructs.js
var constructs_exports = {};
__export(constructs_exports, {
attentionMarkers: () => attentionMarkers,
contentInitial: () => contentInitial,
disable: () => disable,
document: () => document3,
flow: () => flow2,
flowInitial: () => flowInitial,
insideSpan: () => insideSpan,
string: () => string2,
text: () => text2
});
var document3 = {
42: list,
43: list,
45: list,
48: list,
49: list,
50: list,
51: list,
52: list,
53: list,
54: list,
55: list,
56: list,
57: list,
62: blockQuote
}, contentInitial = {
91: definition
}, flowInitial = {
[-2]: codeIndented,
[-1]: codeIndented,
32: codeIndented
}, flow2 = {
35: headingAtx,
42: thematicBreak,
45: [setextUnderline, thematicBreak],
60: htmlFlow,
61: setextUnderline,
95: thematicBreak,
96: codeFenced,
126: codeFenced
}, string2 = {
38: characterReference,
92: characterEscape
}, text2 = {
[-5]: lineEnding,
[-4]: lineEnding,
[-3]: lineEnding,
33: labelStartImage,
38: characterReference,
42: attention,
60: [autolink, htmlText],
91: labelStartLink,
92: [hardBreakEscape, characterEscape],
93: labelEnd,
95: attention,
96: codeText
}, insideSpan = {
null: [attention, resolver]
}, attentionMarkers = {
null: [42, 95]
}, disable = {
null: []
};
// node_modules/micromark/lib/parse.js
function parse(options) {
let constructs2 = (
/** @type {FullNormalizedExtension} */
combineExtensions([constructs_exports, ...(options || {}).extensions || []])
), parser = {
defined: [],
lazy: {},
constructs: constructs2,
content: create(content),
document: create(document2),
flow: create(flow),
string: create(string),
text: create(text)
};
return parser;
function create(initial) {
return creator;
function creator(from) {
return createTokenizer(parser, initial, from);
}
}
}
// node_modules/micromark/lib/postprocess.js
function postprocess(events) {
for (; !subtokenize(events); )
;
return events;
}
// node_modules/micromark/lib/preprocess.js
var search = /[\\0\\t\\n\\r]/g;
function preprocess() {
let column = 1, buffer = "", start = !0, atCarriageReturn;
return preprocessor;
function preprocessor(value, encoding, end) {
let chunks = [], match, next, startPosition, endPosition, code3;
for (value = buffer + (typeof value == "string" ? value.toString() : new TextDecoder(encoding || void 0).decode(value)), startPosition = 0, buffer = "", start && (value.charCodeAt(0) === 65279 && startPosition++, start = void 0); startPosition < value.length; ) {
if (search.lastIndex = startPosition, match = search.exec(value), endPosition = match && match.index !== void 0 ? match.index : value.length, code3 = value.charCodeAt(endPosition), !match) {
buffer = value.slice(startPosition);
break;
}
if (code3 === 10 && startPosition === endPosition && atCarriageReturn)
chunks.push(-3), atCarriageReturn = void 0;
else
switch (atCarriageReturn && (chunks.push(-5), atCarriageReturn = void 0), startPosition < endPosition && (chunks.push(value.slice(startPosition, endPosition)), column += endPosition - startPosition), code3) {
case 0: {
chunks.push(65533), column++;
break;
}
case 9: {
for (next = Math.ceil(column / 4) * 4, chunks.push(-2); column++ < next; ) chunks.push(-1);
break;
}
case 10: {
chunks.push(-4), column = 1;
break;
}
default:
atCarriageReturn = !0, column = 1;
}
startPosition = endPosition + 1;
}
return end && (atCarriageReturn && chunks.push(-5), buffer && chunks.push(buffer), chunks.push(null)), chunks;
}
}
// node_modules/micromark-util-decode-string/index.js
var characterEscapeOrReference = /\\\\([!-/:-@[-\`{-~])|&(#(?:\\d{1,7}|x[\\da-f]{1,6})|[\\da-z]{1,31});/gi;
function decodeString(value) {
return value.replace(characterEscapeOrReference, decode);
}
function decode($0, $1, $2) {
if ($1)
return $1;
if ($2.charCodeAt(0) === 35) {
let head2 = $2.charCodeAt(1), hex = head2 === 120 || head2 === 88;
return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10);
}
return decodeNamedCharacterReference($2) || $0;
}
// node_modules/mdast-util-from-markdown/lib/index.js
var own2 = {}.hasOwnProperty;
function fromMarkdown(value, encoding, options) {
return typeof encoding != "string" && (options = encoding, encoding = void 0), compiler(options)(postprocess(parse(options).document().write(preprocess()(value, encoding, !0))));
}
function compiler(options) {
let config = {
transforms: [],
canContainEols: ["emphasis", "fragment", "heading", "paragraph", "strong"],
enter: {
autolink: opener(link2),
autolinkProtocol: onenterdata,
autolinkEmail: onenterdata,
atxHeading: opener(heading2),
blockQuote: opener(blockQuote2),
characterEscape: onenterdata,
characterReference: onenterdata,
codeFenced: opener(codeFlow),
codeFencedFenceInfo: buffer,
codeFencedFenceMeta: buffer,
codeIndented: opener(codeFlow, buffer),
codeText: opener(codeText2, buffer),
codeTextData: onenterdata,
data: onenterdata,
codeFlowValue: onenterdata,
definition: opener(definition3),
definitionDestinationString: buffer,
definitionLabelString: buffer,
definitionTitleString: buffer,
emphasis: opener(emphasis2),
hardBreakEscape: opener(hardBreak2),
hardBreakTrailing: opener(hardBreak2),
htmlFlow: opener(html2, buffer),
htmlFlowData: onenterdata,
htmlText: opener(html2, buffer),
htmlTextData: onenterdata,
image: opener(image2),
label: buffer,
link: opener(link2),
listItem: opener(listItem2),
listItemValue: onenterlistitemvalue,
listOrdered: opener(list3, onenterlistordered),
listUnordered: opener(list3),
paragraph: opener(paragraph2),
reference: onenterreference,
referenceString: buffer,
resourceDestinationString: buffer,
resourceTitleString: buffer,
setextHeading: opener(heading2),
strong: opener(strong2),
thematicBreak: opener(thematicBreak3)
},
exit: {
atxHeading: closer(),
atxHeadingSequence: onexitatxheadingsequence,
autolink: closer(),
autolinkEmail: onexitautolinkemail,
autolinkProtocol: onexitautolinkprotocol,
blockQuote: closer(),
characterEscapeValue: onexitdata,
characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker,
characterReferenceMarkerNumeric: onexitcharacterreferencemarker,
characterReferenceValue: onexitcharacterreferencevalue,
characterReference: onexitcharacterreference,
codeFenced: closer(onexitcodefenced),
codeFencedFence: onexitcodefencedfence,
codeFencedFenceInfo: onexitcodefencedfenceinfo,
codeFencedFenceMeta: onexitcodefencedfencemeta,
codeFlowValue: onexitdata,
codeIndented: closer(onexitcodeindented),
codeText: closer(onexitcodetext),
codeTextData: onexitdata,
data: onexitdata,
definition: closer(),
definitionDestinationString: onexitdefinitiondestinationstring,
definitionLabelString: onexitdefinitionlabelstring,
definitionTitleString: onexitdefinitiontitlestring,
emphasis: closer(),
hardBreakEscape: closer(onexithardbreak),
hardBreakTrailing: closer(onexithardbreak),
htmlFlow: closer(onexithtmlflow),
htmlFlowData: onexitdata,
htmlText: closer(onexithtmltext),
htmlTextData: onexitdata,
image: closer(onexitimage),
label: onexitlabel,
labelText: onexitlabeltext,
lineEnding: onexitlineending,
link: closer(onexitlink),
listItem: closer(),
listOrdered: closer(),
listUnordered: closer(),
paragraph: closer(),
referenceString: onexitreferencestring,
resourceDestinationString: onexitresourcedestinationstring,
resourceTitleString: onexitresourcetitlestring,
resource: onexitresource,
setextHeading: closer(onexitsetextheading),
setextHeadingLineSequence: onexitsetextheadinglinesequence,
setextHeadingText: onexitsetextheadingtext,
strong: closer(),
thematicBreak: closer()
}
};
configure(config, (options || {}).mdastExtensions || []);
let data = {};
return compile;
function compile(events) {
let tree = {
type: "root",
children: []
}, context = {
stack: [tree],
tokenStack: [],
config,
enter,
exit: exit3,
buffer,
resume,
data
}, listStack = [], index2 = -1;
for (; ++index2 < events.length; )
if (events[index2][1].type === "listOrdered" || events[index2][1].type === "listUnordered")
if (events[index2][0] === "enter")
listStack.push(index2);
else {
let tail = listStack.pop();
index2 = prepareList(events, tail, index2);
}
for (index2 = -1; ++index2 < events.length; ) {
let handler = config[events[index2][0]];
own2.call(handler, events[index2][1].type) && handler[events[index2][1].type].call(Object.assign({
sliceSerialize: events[index2][2].sliceSerialize
}, context), events[index2][1]);
}
if (context.tokenStack.length > 0) {
let tail = context.tokenStack[context.tokenStack.length - 1];
(tail[1] || defaultOnError).call(context, void 0, tail[0]);
}
for (tree.position = {
start: point2(events.length > 0 ? events[0][1].start : {
line: 1,
column: 1,
offset: 0
}),
end: point2(events.length > 0 ? events[events.length - 2][1].end : {
line: 1,
column: 1,
offset: 0
})
}, index2 = -1; ++index2 < config.transforms.length; )
tree = config.transforms[index2](tree) || tree;
return tree;
}
function prepareList(events, start, length) {
let index2 = start - 1, containerBalance = -1, listSpread = !1, listItem3, lineIndex, firstBlankLineIndex, atMarker;
for (; ++index2 <= length; ) {
let event = events[index2];
switch (event[1].type) {
case "listUnordered":
case "listOrdered":
case "blockQuote": {
event[0] === "enter" ? containerBalance++ : containerBalance--, atMarker = void 0;
break;
}
case "lineEndingBlank": {
event[0] === "enter" && (listItem3 && !atMarker && !containerBalance && !firstBlankLineIndex && (firstBlankLineIndex = index2), atMarker = void 0);
break;
}
case "linePrefix":
case "listItemValue":
case "listItemMarker":
case "listItemPrefix":
case "listItemPrefixWhitespace":
break;
default:
atMarker = void 0;
}
if (!containerBalance && event[0] === "enter" && event[1].type === "listItemPrefix" || containerBalance === -1 && event[0] === "exit" && (event[1].type === "listUnordered" || event[1].type === "listOrdered")) {
if (listItem3) {
let tailIndex = index2;
for (lineIndex = void 0; tailIndex--; ) {
let tailEvent = events[tailIndex];
if (tailEvent[1].type === "lineEnding" || tailEvent[1].type === "lineEndingBlank") {
if (tailEvent[0] === "exit") continue;
lineIndex && (events[lineIndex][1].type = "lineEndingBlank", listSpread = !0), tailEvent[1].type = "lineEnding", lineIndex = tailIndex;
} else if (!(tailEvent[1].type === "linePrefix" || tailEvent[1].type === "blockQuotePrefix" || tailEvent[1].type === "blockQuotePrefixWhitespace" || tailEvent[1].type === "blockQuoteMarker" || tailEvent[1].type === "listItemIndent"))
break;
}
firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex) && (listItem3._spread = !0), listItem3.end = Object.assign({}, lineIndex ? events[lineIndex][1].start : event[1].end), events.splice(lineIndex || index2, 0, ["exit", listItem3, event[2]]), index2++, length++;
}
if (event[1].type === "listItemPrefix") {
let item = {
type: "listItem",
_spread: !1,
start: Object.assign({}, event[1].start),
// @ts-expect-error: we\u2019ll add \`end\` in a second.
end: void 0
};
listItem3 = item, events.splice(index2, 0, ["enter", item, event[2]]), index2++, length++, firstBlankLineIndex = void 0, atMarker = !0;
}
}
}
return events[start][1]._spread = listSpread, length;
}
function opener(create, and) {
return open;
function open(token) {
enter.call(this, create(token), token), and && and.call(this, token);
}
}
function buffer() {
this.stack.push({
type: "fragment",
children: []
});
}
function enter(node2, token, errorHandler) {
this.stack[this.stack.length - 1].children.push(node2), this.stack.push(node2), this.tokenStack.push([token, errorHandler]), node2.position = {
start: point2(token.start),
// @ts-expect-error: \`end\` will be patched later.
end: void 0
};
}
function closer(and) {
return close;
function close(token) {
and && and.call(this, token), exit3.call(this, token);
}
}
function exit3(token, onExitError) {
let node2 = this.stack.pop(), open = this.tokenStack.pop();
if (open)
open[0].type !== token.type && (onExitError ? onExitError.call(this, token, open[0]) : (open[1] || defaultOnError).call(this, token, open[0]));
else throw new Error("Cannot close \`" + token.type + "\` (" + stringifyPosition({
start: token.start,
end: token.end
}) + "): it\\u2019s not open");
node2.position.end = point2(token.end);
}
function resume() {
return toString2(this.stack.pop());
}
function onenterlistordered() {
this.data.expectingFirstListItemValue = !0;
}
function onenterlistitemvalue(token) {
if (this.data.expectingFirstListItemValue) {
let ancestor = this.stack[this.stack.length - 2];
ancestor.start = Number.parseInt(this.sliceSerialize(token), 10), this.data.expectingFirstListItemValue = void 0;
}
}
function onexitcodefencedfenceinfo() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.lang = data2;
}
function onexitcodefencedfencemeta() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.meta = data2;
}
function onexitcodefencedfence() {
this.data.flowCodeInside || (this.buffer(), this.data.flowCodeInside = !0);
}
function onexitcodefenced() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.value = data2.replace(/^(\\r?\\n|\\r)|(\\r?\\n|\\r)$/g, ""), this.data.flowCodeInside = void 0;
}
function onexitcodeindented() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.value = data2.replace(/(\\r?\\n|\\r)$/g, "");
}
function onexitdefinitionlabelstring(token) {
let label = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.label = label, node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();
}
function onexitdefinitiontitlestring() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.title = data2;
}
function onexitdefinitiondestinationstring() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.url = data2;
}
function onexitatxheadingsequence(token) {
let node2 = this.stack[this.stack.length - 1];
if (!node2.depth) {
let depth = this.sliceSerialize(token).length;
node2.depth = depth;
}
}
function onexitsetextheadingtext() {
this.data.setextHeadingSlurpLineEnding = !0;
}
function onexitsetextheadinglinesequence(token) {
let node2 = this.stack[this.stack.length - 1];
node2.depth = this.sliceSerialize(token).codePointAt(0) === 61 ? 1 : 2;
}
function onexitsetextheading() {
this.data.setextHeadingSlurpLineEnding = void 0;
}
function onenterdata(token) {
let siblings = this.stack[this.stack.length - 1].children, tail = siblings[siblings.length - 1];
(!tail || tail.type !== "text") && (tail = text5(), tail.position = {
start: point2(token.start),
// @ts-expect-error: we\u2019ll add \`end\` later.
end: void 0
}, siblings.push(tail)), this.stack.push(tail);
}
function onexitdata(token) {
let tail = this.stack.pop();
tail.value += this.sliceSerialize(token), tail.position.end = point2(token.end);
}
function onexitlineending(token) {
let context = this.stack[this.stack.length - 1];
if (this.data.atHardBreak) {
let tail = context.children[context.children.length - 1];
tail.position.end = point2(token.end), this.data.atHardBreak = void 0;
return;
}
!this.data.setextHeadingSlurpLineEnding && config.canContainEols.includes(context.type) && (onenterdata.call(this, token), onexitdata.call(this, token));
}
function onexithardbreak() {
this.data.atHardBreak = !0;
}
function onexithtmlflow() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.value = data2;
}
function onexithtmltext() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.value = data2;
}
function onexitcodetext() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.value = data2;
}
function onexitlink() {
let node2 = this.stack[this.stack.length - 1];
if (this.data.inReference) {
let referenceType = this.data.referenceType || "shortcut";
node2.type += "Reference", node2.referenceType = referenceType, delete node2.url, delete node2.title;
} else
delete node2.identifier, delete node2.label;
this.data.referenceType = void 0;
}
function onexitimage() {
let node2 = this.stack[this.stack.length - 1];
if (this.data.inReference) {
let referenceType = this.data.referenceType || "shortcut";
node2.type += "Reference", node2.referenceType = referenceType, delete node2.url, delete node2.title;
} else
delete node2.identifier, delete node2.label;
this.data.referenceType = void 0;
}
function onexitlabeltext(token) {
let string3 = this.sliceSerialize(token), ancestor = this.stack[this.stack.length - 2];
ancestor.label = decodeString(string3), ancestor.identifier = normalizeIdentifier(string3).toLowerCase();
}
function onexitlabel() {
let fragment = this.stack[this.stack.length - 1], value = this.resume(), node2 = this.stack[this.stack.length - 1];
if (this.data.inReference = !0, node2.type === "link") {
let children = fragment.children;
node2.children = children;
} else
node2.alt = value;
}
function onexitresourcedestinationstring() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.url = data2;
}
function onexitresourcetitlestring() {
let data2 = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.title = data2;
}
function onexitresource() {
this.data.inReference = void 0;
}
function onenterreference() {
this.data.referenceType = "collapsed";
}
function onexitreferencestring(token) {
let label = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.label = label, node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase(), this.data.referenceType = "full";
}
function onexitcharacterreferencemarker(token) {
this.data.characterReferenceType = token.type;
}
function onexitcharacterreferencevalue(token) {
let data2 = this.sliceSerialize(token), type = this.data.characterReferenceType, value;
type ? (value = decodeNumericCharacterReference(data2, type === "characterReferenceMarkerNumeric" ? 10 : 16), this.data.characterReferenceType = void 0) : value = decodeNamedCharacterReference(data2);
let tail = this.stack[this.stack.length - 1];
tail.value += value;
}
function onexitcharacterreference(token) {
let tail = this.stack.pop();
tail.position.end = point2(token.end);
}
function onexitautolinkprotocol(token) {
onexitdata.call(this, token);
let node2 = this.stack[this.stack.length - 1];
node2.url = this.sliceSerialize(token);
}
function onexitautolinkemail(token) {
onexitdata.call(this, token);
let node2 = this.stack[this.stack.length - 1];
node2.url = "mailto:" + this.sliceSerialize(token);
}
function blockQuote2() {
return {
type: "blockquote",
children: []
};
}
function codeFlow() {
return {
type: "code",
lang: null,
meta: null,
value: ""
};
}
function codeText2() {
return {
type: "inlineCode",
value: ""
};
}
function definition3() {
return {
type: "definition",
identifier: "",
label: null,
title: null,
url: ""
};
}
function emphasis2() {
return {
type: "emphasis",
children: []
};
}
function heading2() {
return {
type: "heading",
// @ts-expect-error \`depth\` will be set later.
depth: 0,
children: []
};
}
function hardBreak2() {
return {
type: "break"
};
}
function html2() {
return {
type: "html",
value: ""
};
}
function image2() {
return {
type: "image",
title: null,
url: "",
alt: null
};
}
function link2() {
return {
type: "link",
title: null,
url: "",
children: []
};
}
function list3(token) {
return {
type: "list",
ordered: token.type === "listOrdered",
start: null,
spread: token._spread,
children: []
};
}
function listItem2(token) {
return {
type: "listItem",
spread: token._spread,
checked: null,
children: []
};
}
function paragraph2() {
return {
type: "paragraph",
children: []
};
}
function strong2() {
return {
type: "strong",
children: []
};
}
function text5() {
return {
type: "text",
value: ""
};
}
function thematicBreak3() {
return {
type: "thematicBreak"
};
}
}
function point2(d2) {
return {
line: d2.line,
column: d2.column,
offset: d2.offset
};
}
function configure(combined, extensions) {
let index2 = -1;
for (; ++index2 < extensions.length; ) {
let value = extensions[index2];
Array.isArray(value) ? configure(combined, value) : extension(combined, value);
}
}
function extension(combined, extension2) {
let key;
for (key in extension2)
if (own2.call(extension2, key))
switch (key) {
case "canContainEols": {
let right = extension2[key];
right && combined[key].push(...right);
break;
}
case "transforms": {
let right = extension2[key];
right && combined[key].push(...right);
break;
}
case "enter":
case "exit": {
let right = extension2[key];
right && Object.assign(combined[key], right);
break;
}
}
}
function defaultOnError(left, right) {
throw left ? new Error("Cannot close \`" + left.type + "\` (" + stringifyPosition({
start: left.start,
end: left.end
}) + "): a different token (\`" + right.type + "\`, " + stringifyPosition({
start: right.start,
end: right.end
}) + ") is open") : new Error("Cannot close document, a token (\`" + right.type + "\`, " + stringifyPosition({
start: right.start,
end: right.end
}) + ") is still open");
}
// node_modules/remark-parse/lib/index.js
function remarkParse(options) {
let self2 = this;
self2.parser = parser;
function parser(doc) {
return fromMarkdown(doc, {
...self2.data("settings"),
...options,
// Note: these options are not in the readme.
// The goal is for them to be set by plugins on \`data\` instead of being
// passed by users.
extensions: self2.data("micromarkExtensions") || [],
mdastExtensions: self2.data("fromMarkdownExtensions") || []
});
}
}
// node_modules/unist-util-is/lib/index.js
var convert = (
// Note: overloads in JSDoc can\u2019t yet use different \`@template\`s.
/**
* @type {(
* (<Condition extends string>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &
* (<Condition extends Props>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &
* (<Condition extends TestFunction>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &
* ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &
* ((test?: Test) => Check)
* )}
*/
/**
* @param {Test} [test]
* @returns {Check}
*/
function(test) {
if (test == null)
return ok;
if (typeof test == "function")
return castFactory(test);
if (typeof test == "object")
return Array.isArray(test) ? anyFactory(test) : propsFactory(test);
if (typeof test == "string")
return typeFactory(test);
throw new Error("Expected function, string, or object as test");
}
);
function anyFactory(tests) {
let checks = [], index2 = -1;
for (; ++index2 < tests.length; )
checks[index2] = convert(tests[index2]);
return castFactory(any);
function any(...parameters) {
let index3 = -1;
for (; ++index3 < checks.length; )
if (checks[index3].apply(this, parameters)) return !0;
return !1;
}
}
function propsFactory(check) {
let checkAsRecord = (
/** @type {Record<string, unknown>} */
check
);
return castFactory(all2);
function all2(node2) {
let nodeAsRecord = (
/** @type {Record<string, unknown>} */
/** @type {unknown} */
node2
), key;
for (key in check)
if (nodeAsRecord[key] !== checkAsRecord[key]) return !1;
return !0;
}
}
function typeFactory(check) {
return castFactory(type);
function type(node2) {
return node2 && node2.type === check;
}
}
function castFactory(testFunction) {
return check;
function check(value, index2, parent) {
return !!(looksLikeANode(value) && testFunction.call(
this,
value,
typeof index2 == "number" ? index2 : void 0,
parent || void 0
));
}
}
function ok() {
return !0;
}
function looksLikeANode(value) {
return value !== null && typeof value == "object" && "type" in value;
}
// node_modules/unist-util-visit-parents/lib/index.js
var empty = [], CONTINUE = !0, EXIT = !1, SKIP = "skip";
function visitParents(tree, test, visitor, reverse) {
let check;
typeof test == "function" && typeof visitor != "function" ? (reverse = visitor, visitor = test) : check = test;
let is2 = convert(check), step = reverse ? -1 : 1;
factory(tree, void 0, [])();
function factory(node2, index2, parents) {
let value = (
/** @type {Record<string, unknown>} */
node2 && typeof node2 == "object" ? node2 : {}
);
if (typeof value.type == "string") {
let name = (
// \`hast\`
typeof value.tagName == "string" ? value.tagName : (
// \`xast\`
typeof value.name == "string" ? value.name : void 0
)
);
Object.defineProperty(visit2, "name", {
value: "node (" + (node2.type + (name ? "<" + name + ">" : "")) + ")"
});
}
return visit2;
function visit2() {
let result = empty, subresult, offset, grandparents;
if ((!test || is2(node2, index2, parents[parents.length - 1] || void 0)) && (result = toResult(visitor(node2, parents)), result[0] === EXIT))
return result;
if ("children" in node2 && node2.children) {
let nodeAsParent = (
/** @type {UnistParent} */
node2
);
if (nodeAsParent.children && result[0] !== SKIP)
for (offset = (reverse ? nodeAsParent.children.length : -1) + step, grandparents = parents.concat(nodeAsParent); offset > -1 && offset < nodeAsParent.children.length; ) {
let child = nodeAsParent.children[offset];
if (subresult = factory(child, offset, grandparents)(), subresult[0] === EXIT)
return subresult;
offset = typeof subresult[1] == "number" ? subresult[1] : offset + step;
}
}
return result;
}
}
}
function toResult(value) {
return Array.isArray(value) ? value : typeof value == "number" ? [CONTINUE, value] : value == null ? empty : [value];
}
// node_modules/unist-util-visit/lib/index.js
function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
let reverse, test, visitor;
typeof testOrVisitor == "function" && typeof visitorOrReverse != "function" ? (test = void 0, visitor = testOrVisitor, reverse = visitorOrReverse) : (test = testOrVisitor, visitor = visitorOrReverse, reverse = maybeReverse), visitParents(tree, test, overload, reverse);
function overload(node2, parents) {
let parent = parents[parents.length - 1], index2 = parent ? parent.children.indexOf(node2) : void 0;
return visitor(node2, index2, parent);
}
}
// node_modules/ccount/index.js
function ccount(value, character) {
let source = String(value);
if (typeof character != "string")
throw new TypeError("Expected character");
let count = 0, index2 = source.indexOf(character);
for (; index2 !== -1; )
count++, index2 = source.indexOf(character, index2 + character.length);
return count;
}
// node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp/index.js
function escapeStringRegexp(string3) {
if (typeof string3 != "string")
throw new TypeError("Expected a string");
return string3.replace(/[|\\\\{}()[\\]^$+*?.]/g, "\\\\$&").replace(/-/g, "\\\\x2d");
}
// node_modules/mdast-util-find-and-replace/lib/index.js
function findAndReplace(tree, list3, options) {
let ignored = convert((options || {}).ignore || []), pairs = toPairs(list3), pairIndex = -1;
for (; ++pairIndex < pairs.length; )
visitParents(tree, "text", visitor);
function visitor(node2, parents) {
let index2 = -1, grandparent;
for (; ++index2 < parents.length; ) {
let parent = parents[index2], siblings = grandparent ? grandparent.children : void 0;
if (ignored(
parent,
siblings ? siblings.indexOf(parent) : void 0,
grandparent
))
return;
grandparent = parent;
}
if (grandparent)
return handler(node2, parents);
}
function handler(node2, parents) {
let parent = parents[parents.length - 1], find = pairs[pairIndex][0], replace2 = pairs[pairIndex][1], start = 0, index2 = parent.children.indexOf(node2), change = !1, nodes = [];
find.lastIndex = 0;
let match = find.exec(node2.value);
for (; match; ) {
let position2 = match.index, matchObject = {
index: match.index,
input: match.input,
stack: [...parents, node2]
}, value = replace2(...match, matchObject);
if (typeof value == "string" && (value = value.length > 0 ? { type: "text", value } : void 0), value === !1 ? find.lastIndex = position2 + 1 : (start !== position2 && nodes.push({
type: "text",
value: node2.value.slice(start, position2)
}), Array.isArray(value) ? nodes.push(...value) : value && nodes.push(value), start = position2 + match[0].length, change = !0), !find.global)
break;
match = find.exec(node2.value);
}
return change ? (start < node2.value.length && nodes.push({ type: "text", value: node2.value.slice(start) }), parent.children.splice(index2, 1, ...nodes)) : nodes = [node2], index2 + nodes.length;
}
}
function toPairs(tupleOrList) {
let result = [];
if (!Array.isArray(tupleOrList))
throw new TypeError("Expected find and replace tuple or list of tuples");
let list3 = !tupleOrList[0] || Array.isArray(tupleOrList[0]) ? tupleOrList : [tupleOrList], index2 = -1;
for (; ++index2 < list3.length; ) {
let tuple = list3[index2];
result.push([toExpression(tuple[0]), toFunction(tuple[1])]);
}
return result;
}
function toExpression(find) {
return typeof find == "string" ? new RegExp(escapeStringRegexp(find), "g") : find;
}
function toFunction(replace2) {
return typeof replace2 == "function" ? replace2 : function() {
return replace2;
};
}
// node_modules/mdast-util-gfm-autolink-literal/lib/index.js
var inConstruct = "phrasing", notInConstruct = ["autolink", "link", "image", "label"];
function gfmAutolinkLiteralFromMarkdown() {
return {
transforms: [transformGfmAutolinkLiterals],
enter: {
literalAutolink: enterLiteralAutolink,
literalAutolinkEmail: enterLiteralAutolinkValue,
literalAutolinkHttp: enterLiteralAutolinkValue,
literalAutolinkWww: enterLiteralAutolinkValue
},
exit: {
literalAutolink: exitLiteralAutolink,
literalAutolinkEmail: exitLiteralAutolinkEmail,
literalAutolinkHttp: exitLiteralAutolinkHttp,
literalAutolinkWww: exitLiteralAutolinkWww
}
};
}
function gfmAutolinkLiteralToMarkdown() {
return {
unsafe: [
{
character: "@",
before: "[+\\\\-.\\\\w]",
after: "[\\\\-.\\\\w]",
inConstruct,
notInConstruct
},
{
character: ".",
before: "[Ww]",
after: "[\\\\-.\\\\w]",
inConstruct,
notInConstruct
},
{
character: ":",
before: "[ps]",
after: "\\\\/",
inConstruct,
notInConstruct
}
]
};
}
function enterLiteralAutolink(token) {
this.enter({ type: "link", title: null, url: "", children: [] }, token);
}
function enterLiteralAutolinkValue(token) {
this.config.enter.autolinkProtocol.call(this, token);
}
function exitLiteralAutolinkHttp(token) {
this.config.exit.autolinkProtocol.call(this, token);
}
function exitLiteralAutolinkWww(token) {
this.config.exit.data.call(this, token);
let node2 = this.stack[this.stack.length - 1];
node2.type, node2.url = "http://" + this.sliceSerialize(token);
}
function exitLiteralAutolinkEmail(token) {
this.config.exit.autolinkEmail.call(this, token);
}
function exitLiteralAutolink(token) {
this.exit(token);
}
function transformGfmAutolinkLiterals(tree) {
findAndReplace(
tree,
[
[/(https?:\\/\\/|www(?=\\.))([-.\\w]+)([^ \\t\\r\\n]*)/gi, findUrl],
[/([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)/g, findEmail]
],
{ ignore: ["link", "linkReference"] }
);
}
function findUrl(_, protocol, domain2, path2, match) {
let prefix = "";
if (!previous2(match) || (/^w/i.test(protocol) && (domain2 = protocol + domain2, protocol = "", prefix = "http://"), !isCorrectDomain(domain2)))
return !1;
let parts = splitUrl(domain2 + path2);
if (!parts[0]) return !1;
let result = {
type: "link",
title: null,
url: prefix + protocol + parts[0],
children: [{ type: "text", value: protocol + parts[0] }]
};
return parts[1] ? [result, { type: "text", value: parts[1] }] : result;
}
function findEmail(_, atext, label, match) {
return (
// Not an expected previous character.
!previous2(match, !0) || // Label ends in not allowed character.
/[-\\d_]$/.test(label) ? !1 : {
type: "link",
title: null,
url: "mailto:" + atext + "@" + label,
children: [{ type: "text", value: atext + "@" + label }]
}
);
}
function isCorrectDomain(domain2) {
let parts = domain2.split(".");
return !(parts.length < 2 || parts[parts.length - 1] && (/_/.test(parts[parts.length - 1]) || !/[a-zA-Z\\d]/.test(parts[parts.length - 1])) || parts[parts.length - 2] && (/_/.test(parts[parts.length - 2]) || !/[a-zA-Z\\d]/.test(parts[parts.length - 2])));
}
function splitUrl(url) {
let trailExec = /[!"&'),.:;<>?\\]}]+$/.exec(url);
if (!trailExec)
return [url, void 0];
url = url.slice(0, trailExec.index);
let trail2 = trailExec[0], closingParenIndex = trail2.indexOf(")"), openingParens = ccount(url, "("), closingParens = ccount(url, ")");
for (; closingParenIndex !== -1 && openingParens > closingParens; )
url += trail2.slice(0, closingParenIndex + 1), trail2 = trail2.slice(closingParenIndex + 1), closingParenIndex = trail2.indexOf(")"), closingParens++;
return [url, trail2];
}
function previous2(match, email) {
let code3 = match.input.charCodeAt(match.index - 1);
return (match.index === 0 || unicodeWhitespace(code3) || unicodePunctuation(code3)) && (!email || code3 !== 47);
}
// node_modules/mdast-util-gfm-footnote/lib/index.js
footnoteReference.peek = footnoteReferencePeek;
function gfmFootnoteFromMarkdown() {
return {
enter: {
gfmFootnoteDefinition: enterFootnoteDefinition,
gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString,
gfmFootnoteCall: enterFootnoteCall,
gfmFootnoteCallString: enterFootnoteCallString
},
exit: {
gfmFootnoteDefinition: exitFootnoteDefinition,
gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString,
gfmFootnoteCall: exitFootnoteCall,
gfmFootnoteCallString: exitFootnoteCallString
}
};
}
function gfmFootnoteToMarkdown() {
return {
// This is on by default already.
unsafe: [{ character: "[", inConstruct: ["phrasing", "label", "reference"] }],
handlers: { footnoteDefinition, footnoteReference }
};
}
function enterFootnoteDefinition(token) {
this.enter(
{ type: "footnoteDefinition", identifier: "", label: "", children: [] },
token
);
}
function enterFootnoteDefinitionLabelString() {
this.buffer();
}
function exitFootnoteDefinitionLabelString(token) {
let label = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.type, node2.label = label, node2.identifier = normalizeIdentifier(
this.sliceSerialize(token)
).toLowerCase();
}
function exitFootnoteDefinition(token) {
this.exit(token);
}
function enterFootnoteCall(token) {
this.enter({ type: "footnoteReference", identifier: "", label: "" }, token);
}
function enterFootnoteCallString() {
this.buffer();
}
function exitFootnoteCallString(token) {
let label = this.resume(), node2 = this.stack[this.stack.length - 1];
node2.type, node2.label = label, node2.identifier = normalizeIdentifier(
this.sliceSerialize(token)
).toLowerCase();
}
function exitFootnoteCall(token) {
this.exit(token);
}
function footnoteReference(node2, _, state, info) {
let tracker = state.createTracker(info), value = tracker.move("[^"), exit3 = state.enter("footnoteReference"), subexit = state.enter("reference");
return value += tracker.move(
state.safe(state.associationId(node2), {
...tracker.current(),
before: value,
after: "]"
})
), subexit(), exit3(), value += tracker.move("]"), value;
}
function footnoteReferencePeek() {
return "[";
}
function footnoteDefinition(node2, _, state, info) {
let tracker = state.createTracker(info), value = tracker.move("[^"), exit3 = state.enter("footnoteDefinition"), subexit = state.enter("label");
return value += tracker.move(
state.safe(state.associationId(node2), {
...tracker.current(),
before: value,
after: "]"
})
), subexit(), value += tracker.move(
"]:" + (node2.children && node2.children.length > 0 ? " " : "")
), tracker.shift(4), value += tracker.move(
state.indentLines(state.containerFlow(node2, tracker.current()), map)
), exit3(), value;
}
function map(line, index2, blank) {
return index2 === 0 ? line : (blank ? "" : " ") + line;
}
// node_modules/mdast-util-gfm-strikethrough/lib/index.js
var constructsWithoutStrikethrough = [
"autolink",
"destinationLiteral",
"destinationRaw",
"reference",
"titleQuote",
"titleApostrophe"
];
handleDelete.peek = peekDelete;
function gfmStrikethroughFromMarkdown() {
return {
canContainEols: ["delete"],
enter: { strikethrough: enterStrikethrough },
exit: { strikethrough: exitStrikethrough }
};
}
function gfmStrikethroughToMarkdown() {
return {
unsafe: [
{
character: "~",
inConstruct: "phrasing",
notInConstruct: constructsWithoutStrikethrough
}
],
handlers: { delete: handleDelete }
};
}
function enterStrikethrough(token) {
this.enter({ type: "delete", children: [] }, token);
}
function exitStrikethrough(token) {
this.exit(token);
}
function handleDelete(node2, _, state, info) {
let tracker = state.createTracker(info), exit3 = state.enter("strikethrough"), value = tracker.move("~~");
return value += state.containerPhrasing(node2, {
...tracker.current(),
before: value,
after: "~"
}), value += tracker.move("~~"), exit3(), value;
}
function peekDelete() {
return "~";
}
// node_modules/markdown-table/index.js
function markdownTable(table, options = {}) {
let align = (options.align || []).concat(), stringLength = options.stringLength || defaultStringLength, alignments = [], cellMatrix = [], sizeMatrix = [], longestCellByColumn = [], mostCellsPerRow = 0, rowIndex = -1;
for (; ++rowIndex < table.length; ) {
let row2 = [], sizes2 = [], columnIndex2 = -1;
for (table[rowIndex].length > mostCellsPerRow && (mostCellsPerRow = table[rowIndex].length); ++columnIndex2 < table[rowIndex].length; ) {
let cell = serialize2(table[rowIndex][columnIndex2]);
if (options.alignDelimiters !== !1) {
let size = stringLength(cell);
sizes2[columnIndex2] = size, (longestCellByColumn[columnIndex2] === void 0 || size > longestCellByColumn[columnIndex2]) && (longestCellByColumn[columnIndex2] = size);
}
row2.push(cell);
}
cellMatrix[rowIndex] = row2, sizeMatrix[rowIndex] = sizes2;
}
let columnIndex = -1;
if (typeof align == "object" && "length" in align)
for (; ++columnIndex < mostCellsPerRow; )
alignments[columnIndex] = toAlignment(align[columnIndex]);
else {
let code3 = toAlignment(align);
for (; ++columnIndex < mostCellsPerRow; )
alignments[columnIndex] = code3;
}
columnIndex = -1;
let row = [], sizes = [];
for (; ++columnIndex < mostCellsPerRow; ) {
let code3 = alignments[columnIndex], before = "", after = "";
code3 === 99 ? (before = ":", after = ":") : code3 === 108 ? before = ":" : code3 === 114 && (after = ":");
let size = options.alignDelimiters === !1 ? 1 : Math.max(
1,
longestCellByColumn[columnIndex] - before.length - after.length
), cell = before + "-".repeat(size) + after;
options.alignDelimiters !== !1 && (size = before.length + size + after.length, size > longestCellByColumn[columnIndex] && (longestCellByColumn[columnIndex] = size), sizes[columnIndex] = size), row[columnIndex] = cell;
}
cellMatrix.splice(1, 0, row), sizeMatrix.splice(1, 0, sizes), rowIndex = -1;
let lines = [];
for (; ++rowIndex < cellMatrix.length; ) {
let row2 = cellMatrix[rowIndex], sizes2 = sizeMatrix[rowIndex];
columnIndex = -1;
let line = [];
for (; ++columnIndex < mostCellsPerRow; ) {
let cell = row2[columnIndex] || "", before = "", after = "";
if (options.alignDelimiters !== !1) {
let size = longestCellByColumn[columnIndex] - (sizes2[columnIndex] || 0), code3 = alignments[columnIndex];
code3 === 114 ? before = " ".repeat(size) : code3 === 99 ? size % 2 ? (before = " ".repeat(size / 2 + 0.5), after = " ".repeat(size / 2 - 0.5)) : (before = " ".repeat(size / 2), after = before) : after = " ".repeat(size);
}
options.delimiterStart !== !1 && !columnIndex && line.push("|"), options.padding !== !1 && // Don\u2019t add the opening space if we\u2019re not aligning and the cell is
// empty: there will be a closing space.
!(options.alignDelimiters === !1 && cell === "") && (options.delimiterStart !== !1 || columnIndex) && line.push(" "), options.alignDelimiters !== !1 && line.push(before), line.push(cell), options.alignDelimiters !== !1 && line.push(after), options.padding !== !1 && line.push(" "), (options.delimiterEnd !== !1 || columnIndex !== mostCellsPerRow - 1) && line.push("|");
}
lines.push(
options.delimiterEnd === !1 ? line.join("").replace(/ +$/, "") : line.join("")
);
}
return lines.join(\`
\`);
}
function serialize2(value) {
return value == null ? "" : String(value);
}
function defaultStringLength(value) {
return value.length;
}
function toAlignment(value) {
let code3 = typeof value == "string" ? value.codePointAt(0) : 0;
return code3 === 67 || code3 === 99 ? 99 : code3 === 76 || code3 === 108 ? 108 : code3 === 82 || code3 === 114 ? 114 : 0;
}
// node_modules/mdast-util-to-markdown/lib/handle/blockquote.js
function blockquote(node2, _, state, info) {
let exit3 = state.enter("blockquote"), tracker = state.createTracker(info);
tracker.move("> "), tracker.shift(2);
let value = state.indentLines(
state.containerFlow(node2, tracker.current()),
map2
);
return exit3(), value;
}
function map2(line, _, blank) {
return ">" + (blank ? "" : " ") + line;
}
// node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js
function patternInScope(stack, pattern) {
return listInScope(stack, pattern.inConstruct, !0) && !listInScope(stack, pattern.notInConstruct, !1);
}
function listInScope(stack, list3, none) {
if (typeof list3 == "string" && (list3 = [list3]), !list3 || list3.length === 0)
return none;
let index2 = -1;
for (; ++index2 < list3.length; )
if (stack.includes(list3[index2]))
return !0;
return !1;
}
// node_modules/mdast-util-to-markdown/lib/handle/break.js
function hardBreak(_, _1, state, info) {
let index2 = -1;
for (; ++index2 < state.unsafe.length; )
if (state.unsafe[index2].character === \`
\` && patternInScope(state.stack, state.unsafe[index2]))
return /[ \\t]/.test(info.before) ? "" : " ";
return \`\\\\
\`;
}
// node_modules/longest-streak/index.js
function longestStreak(value, substring) {
let source = String(value), index2 = source.indexOf(substring), expected = index2, count = 0, max = 0;
if (typeof substring != "string")
throw new TypeError("Expected substring");
for (; index2 !== -1; )
index2 === expected ? ++count > max && (max = count) : count = 1, expected = index2 + substring.length, index2 = source.indexOf(substring, expected);
return max;
}
// node_modules/mdast-util-to-markdown/lib/util/format-code-as-indented.js
function formatCodeAsIndented(node2, state) {
return !!(state.options.fences === !1 && node2.value && // If there\u2019s no info\u2026
!node2.lang && // And there\u2019s a non-whitespace character\u2026
/[^ \\r\\n]/.test(node2.value) && // And the value doesn\u2019t start or end in a blank\u2026
!/^[\\t ]*(?:[\\r\\n]|$)|(?:^|[\\r\\n])[\\t ]*$/.test(node2.value));
}
// node_modules/mdast-util-to-markdown/lib/util/check-fence.js
function checkFence(state) {
let marker = state.options.fence || "\`";
if (marker !== "\`" && marker !== "~")
throw new Error(
"Cannot serialize code with \`" + marker + "\` for \`options.fence\`, expected \`\` \` \`\` or \`~\`"
);
return marker;
}
// node_modules/mdast-util-to-markdown/lib/handle/code.js
function code(node2, _, state, info) {
let marker = checkFence(state), raw = node2.value || "", suffix = marker === "\`" ? "GraveAccent" : "Tilde";
if (formatCodeAsIndented(node2, state)) {
let exit4 = state.enter("codeIndented"), value2 = state.indentLines(raw, map3);
return exit4(), value2;
}
let tracker = state.createTracker(info), sequence = marker.repeat(Math.max(longestStreak(raw, marker) + 1, 3)), exit3 = state.enter("codeFenced"), value = tracker.move(sequence);
if (node2.lang) {
let subexit = state.enter(\`codeFencedLang\${suffix}\`);
value += tracker.move(
state.safe(node2.lang, {
before: value,
after: " ",
encode: ["\`"],
...tracker.current()
})
), subexit();
}
if (node2.lang && node2.meta) {
let subexit = state.enter(\`codeFencedMeta\${suffix}\`);
value += tracker.move(" "), value += tracker.move(
state.safe(node2.meta, {
before: value,
after: \`
\`,
encode: ["\`"],
...tracker.current()
})
), subexit();
}
return value += tracker.move(\`
\`), raw && (value += tracker.move(raw + \`
\`)), value += tracker.move(sequence), exit3(), value;
}
function map3(line, _, blank) {
return (blank ? "" : " ") + line;
}
// node_modules/mdast-util-to-markdown/lib/util/check-quote.js
function checkQuote(state) {
let marker = state.options.quote || '"';
if (marker !== '"' && marker !== "'")
throw new Error(
"Cannot serialize title with \`" + marker + "\` for \`options.quote\`, expected \`\\"\`, or \`'\`"
);
return marker;
}
// node_modules/mdast-util-to-markdown/lib/handle/definition.js
function definition2(node2, _, state, info) {
let quote = checkQuote(state), suffix = quote === '"' ? "Quote" : "Apostrophe", exit3 = state.enter("definition"), subexit = state.enter("label"), tracker = state.createTracker(info), value = tracker.move("[");
return value += tracker.move(
state.safe(state.associationId(node2), {
before: value,
after: "]",
...tracker.current()
})
), value += tracker.move("]: "), subexit(), // If there\u2019s no url, or\u2026
!node2.url || // If there are control characters or whitespace.
/[\\0- \\u007F]/.test(node2.url) ? (subexit = state.enter("destinationLiteral"), value += tracker.move("<"), value += tracker.move(
state.safe(node2.url, { before: value, after: ">", ...tracker.current() })
), value += tracker.move(">")) : (subexit = state.enter("destinationRaw"), value += tracker.move(
state.safe(node2.url, {
before: value,
after: node2.title ? " " : \`
\`,
...tracker.current()
})
)), subexit(), node2.title && (subexit = state.enter(\`title\${suffix}\`), value += tracker.move(" " + quote), value += tracker.move(
state.safe(node2.title, {
before: value,
after: quote,
...tracker.current()
})
), value += tracker.move(quote), subexit()), exit3(), value;
}
// node_modules/mdast-util-to-markdown/lib/util/check-emphasis.js
function checkEmphasis(state) {
let marker = state.options.emphasis || "*";
if (marker !== "*" && marker !== "_")
throw new Error(
"Cannot serialize emphasis with \`" + marker + "\` for \`options.emphasis\`, expected \`*\`, or \`_\`"
);
return marker;
}
// node_modules/mdast-util-to-markdown/lib/handle/emphasis.js
emphasis.peek = emphasisPeek;
function emphasis(node2, _, state, info) {
let marker = checkEmphasis(state), exit3 = state.enter("emphasis"), tracker = state.createTracker(info), value = tracker.move(marker);
return value += tracker.move(
state.containerPhrasing(node2, {
before: value,
after: marker,
...tracker.current()
})
), value += tracker.move(marker), exit3(), value;
}
function emphasisPeek(_, _1, state) {
return state.options.emphasis || "*";
}
// node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
function formatHeadingAsSetext(node2, state) {
let literalWithBreak = !1;
return visit(node2, function(node3) {
if ("value" in node3 && /\\r?\\n|\\r/.test(node3.value) || node3.type === "break")
return literalWithBreak = !0, EXIT;
}), !!((!node2.depth || node2.depth < 3) && toString2(node2) && (state.options.setext || literalWithBreak));
}
// node_modules/mdast-util-to-markdown/lib/handle/heading.js
function heading(node2, _, state, info) {
let rank = Math.max(Math.min(6, node2.depth || 1), 1), tracker = state.createTracker(info);
if (formatHeadingAsSetext(node2, state)) {
let exit4 = state.enter("headingSetext"), subexit2 = state.enter("phrasing"), value2 = state.containerPhrasing(node2, {
...tracker.current(),
before: \`
\`,
after: \`
\`
});
return subexit2(), exit4(), value2 + \`
\` + (rank === 1 ? "=" : "-").repeat(
// The whole size\u2026
value2.length - // Minus the position of the character after the last EOL (or
// 0 if there is none)\u2026
(Math.max(value2.lastIndexOf("\\r"), value2.lastIndexOf(\`
\`)) + 1)
);
}
let sequence = "#".repeat(rank), exit3 = state.enter("headingAtx"), subexit = state.enter("phrasing");
tracker.move(sequence + " ");
let value = state.containerPhrasing(node2, {
before: "# ",
after: \`
\`,
...tracker.current()
});
return /^[\\t ]/.test(value) && (value = "&#x" + value.charCodeAt(0).toString(16).toUpperCase() + ";" + value.slice(1)), value = value ? sequence + " " + value : sequence, state.options.closeAtx && (value += " " + sequence), subexit(), exit3(), value;
}
// node_modules/mdast-util-to-markdown/lib/handle/html.js
html.peek = htmlPeek;
function html(node2) {
return node2.value || "";
}
function htmlPeek() {
return "<";
}
// node_modules/mdast-util-to-markdown/lib/handle/image.js
image.peek = imagePeek;
function image(node2, _, state, info) {
let quote = checkQuote(state), suffix = quote === '"' ? "Quote" : "Apostrophe", exit3 = state.enter("image"), subexit = state.enter("label"), tracker = state.createTracker(info), value = tracker.move("![");
return value += tracker.move(
state.safe(node2.alt, { before: value, after: "]", ...tracker.current() })
), value += tracker.move("]("), subexit(), // If there\u2019s no url but there is a title\u2026
!node2.url && node2.title || // If there are control characters or whitespace.
/[\\0- \\u007F]/.test(node2.url) ? (subexit = state.enter("destinationLiteral"), value += tracker.move("<"), value += tracker.move(
state.safe(node2.url, { before: value, after: ">", ...tracker.current() })
), value += tracker.move(">")) : (subexit = state.enter("destinationRaw"), value += tracker.move(
state.safe(node2.url, {
before: value,
after: node2.title ? " " : ")",
...tracker.current()
})
)), subexit(), node2.title && (subexit = state.enter(\`title\${suffix}\`), value += tracker.move(" " + quote), value += tracker.move(
state.safe(node2.title, {
before: value,
after: quote,
...tracker.current()
})
), value += tracker.move(quote), subexit()), value += tracker.move(")"), exit3(), value;
}
function imagePeek() {
return "!";
}
// node_modules/mdast-util-to-markdown/lib/handle/image-reference.js
imageReference.peek = imageReferencePeek;
function imageReference(node2, _, state, info) {
let type = node2.referenceType, exit3 = state.enter("imageReference"), subexit = state.enter("label"), tracker = state.createTracker(info), value = tracker.move("!["), alt = state.safe(node2.alt, {
before: value,
after: "]",
...tracker.current()
});
value += tracker.move(alt + "]["), subexit();
let stack = state.stack;
state.stack = [], subexit = state.enter("reference");
let reference = state.safe(state.associationId(node2), {
before: value,
after: "]",
...tracker.current()
});
return subexit(), state.stack = stack, exit3(), type === "full" || !alt || alt !== reference ? value += tracker.move(reference + "]") : type === "shortcut" ? value = value.slice(0, -1) : value += tracker.move("]"), value;
}
function imageReferencePeek() {
return "!";
}
// node_modules/mdast-util-to-markdown/lib/handle/inline-code.js
inlineCode.peek = inlineCodePeek;
function inlineCode(node2, _, state) {
let value = node2.value || "", sequence = "\`", index2 = -1;
for (; new RegExp("(^|[^\`])" + sequence + "([^\`]|$)").test(value); )
sequence += "\`";
for (/[^ \\r\\n]/.test(value) && (/^[ \\r\\n]/.test(value) && /[ \\r\\n]$/.test(value) || /^\`|\`$/.test(value)) && (value = " " + value + " "); ++index2 < state.unsafe.length; ) {
let pattern = state.unsafe[index2], expression = state.compilePattern(pattern), match;
if (pattern.atBreak)
for (; match = expression.exec(value); ) {
let position2 = match.index;
value.charCodeAt(position2) === 10 && value.charCodeAt(position2 - 1) === 13 && position2--, value = value.slice(0, position2) + " " + value.slice(match.index + 1);
}
}
return sequence + value + sequence;
}
function inlineCodePeek() {
return "\`";
}
// node_modules/mdast-util-to-markdown/lib/util/format-link-as-autolink.js
function formatLinkAsAutolink(node2, state) {
let raw = toString2(node2);
return !!(!state.options.resourceLink && // If there\u2019s a url\u2026
node2.url && // And there\u2019s a no title\u2026
!node2.title && // And the content of \`node\` is a single text node\u2026
node2.children && node2.children.length === 1 && node2.children[0].type === "text" && // And if the url is the same as the content\u2026
(raw === node2.url || "mailto:" + raw === node2.url) && // And that starts w/ a protocol\u2026
/^[a-z][a-z+.-]+:/i.test(node2.url) && // And that doesn\u2019t contain ASCII control codes (character escapes and
// references don\u2019t work), space, or angle brackets\u2026
!/[\\0- <>\\u007F]/.test(node2.url));
}
// node_modules/mdast-util-to-markdown/lib/handle/link.js
link.peek = linkPeek;
function link(node2, _, state, info) {
let quote = checkQuote(state), suffix = quote === '"' ? "Quote" : "Apostrophe", tracker = state.createTracker(info), exit3, subexit;
if (formatLinkAsAutolink(node2, state)) {
let stack = state.stack;
state.stack = [], exit3 = state.enter("autolink");
let value2 = tracker.move("<");
return value2 += tracker.move(
state.containerPhrasing(node2, {
before: value2,
after: ">",
...tracker.current()
})
), value2 += tracker.move(">"), exit3(), state.stack = stack, value2;
}
exit3 = state.enter("link"), subexit = state.enter("label");
let value = tracker.move("[");
return value += tracker.move(
state.containerPhrasing(node2, {
before: value,
after: "](",
...tracker.current()
})
), value += tracker.move("]("), subexit(), // If there\u2019s no url but there is a title\u2026
!node2.url && node2.title || // If there are control characters or whitespace.
/[\\0- \\u007F]/.test(node2.url) ? (subexit = state.enter("destinationLiteral"), value += tracker.move("<"), value += tracker.move(
state.safe(node2.url, { before: value, after: ">", ...tracker.current() })
), value += tracker.move(">")) : (subexit = state.enter("destinationRaw"), value += tracker.move(
state.safe(node2.url, {
before: value,
after: node2.title ? " " : ")",
...tracker.current()
})
)), subexit(), node2.title && (subexit = state.enter(\`title\${suffix}\`), value += tracker.move(" " + quote), value += tracker.move(
state.safe(node2.title, {
before: value,
after: quote,
...tracker.current()
})
), value += tracker.move(quote), subexit()), value += tracker.move(")"), exit3(), value;
}
function linkPeek(node2, _, state) {
return formatLinkAsAutolink(node2, state) ? "<" : "[";
}
// node_modules/mdast-util-to-markdown/lib/handle/link-reference.js
linkReference.peek = linkReferencePeek;
function linkReference(node2, _, state, info) {
let type = node2.referenceType, exit3 = state.enter("linkReference"), subexit = state.enter("label"), tracker = state.createTracker(info), value = tracker.move("["), text5 = state.containerPhrasing(node2, {
before: value,
after: "]",
...tracker.current()
});
value += tracker.move(text5 + "]["), subexit();
let stack = state.stack;
state.stack = [], subexit = state.enter("reference");
let reference = state.safe(state.associationId(node2), {
before: value,
after: "]",
...tracker.current()
});
return subexit(), state.stack = stack, exit3(), type === "full" || !text5 || text5 !== reference ? value += tracker.move(reference + "]") : type === "shortcut" ? value = value.slice(0, -1) : value += tracker.move("]"), value;
}
function linkReferencePeek() {
return "[";
}
// node_modules/mdast-util-to-markdown/lib/util/check-bullet.js
function checkBullet(state) {
let marker = state.options.bullet || "*";
if (marker !== "*" && marker !== "+" && marker !== "-")
throw new Error(
"Cannot serialize items with \`" + marker + "\` for \`options.bullet\`, expected \`*\`, \`+\`, or \`-\`"
);
return marker;
}
// node_modules/mdast-util-to-markdown/lib/util/check-bullet-other.js
function checkBulletOther(state) {
let bullet = checkBullet(state), bulletOther = state.options.bulletOther;
if (!bulletOther)
return bullet === "*" ? "-" : "*";
if (bulletOther !== "*" && bulletOther !== "+" && bulletOther !== "-")
throw new Error(
"Cannot serialize items with \`" + bulletOther + "\` for \`options.bulletOther\`, expected \`*\`, \`+\`, or \`-\`"
);
if (bulletOther === bullet)
throw new Error(
"Expected \`bullet\` (\`" + bullet + "\`) and \`bulletOther\` (\`" + bulletOther + "\`) to be different"
);
return bulletOther;
}
// node_modules/mdast-util-to-markdown/lib/util/check-bullet-ordered.js
function checkBulletOrdered(state) {
let marker = state.options.bulletOrdered || ".";
if (marker !== "." && marker !== ")")
throw new Error(
"Cannot serialize items with \`" + marker + "\` for \`options.bulletOrdered\`, expected \`.\` or \`)\`"
);
return marker;
}
// node_modules/mdast-util-to-markdown/lib/util/check-rule.js
function checkRule(state) {
let marker = state.options.rule || "*";
if (marker !== "*" && marker !== "-" && marker !== "_")
throw new Error(
"Cannot serialize rules with \`" + marker + "\` for \`options.rule\`, expected \`*\`, \`-\`, or \`_\`"
);
return marker;
}
// node_modules/mdast-util-to-markdown/lib/handle/list.js
function list2(node2, parent, state, info) {
let exit3 = state.enter("list"), bulletCurrent = state.bulletCurrent, bullet = node2.ordered ? checkBulletOrdered(state) : checkBullet(state), bulletOther = node2.ordered ? bullet === "." ? ")" : "." : checkBulletOther(state), useDifferentMarker = parent && state.bulletLastUsed ? bullet === state.bulletLastUsed : !1;
if (!node2.ordered) {
let firstListItem = node2.children ? node2.children[0] : void 0;
if (
// Bullet could be used as a thematic break marker:
(bullet === "*" || bullet === "-") && // Empty first list item:
firstListItem && (!firstListItem.children || !firstListItem.children[0]) && // Directly in two other list items:
state.stack[state.stack.length - 1] === "list" && state.stack[state.stack.length - 2] === "listItem" && state.stack[state.stack.length - 3] === "list" && state.stack[state.stack.length - 4] === "listItem" && // That are each the first child.
state.indexStack[state.indexStack.length - 1] === 0 && state.indexStack[state.indexStack.length - 2] === 0 && state.indexStack[state.indexStack.length - 3] === 0 && (useDifferentMarker = !0), checkRule(state) === bullet && firstListItem
) {
let index2 = -1;
for (; ++index2 < node2.children.length; ) {
let item = node2.children[index2];
if (item && item.type === "listItem" && item.children && item.children[0] && item.children[0].type === "thematicBreak") {
useDifferentMarker = !0;
break;
}
}
}
}
useDifferentMarker && (bullet = bulletOther), state.bulletCurrent = bullet;
let value = state.containerFlow(node2, info);
return state.bulletLastUsed = bullet, state.bulletCurrent = bulletCurrent, exit3(), value;
}
// node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js
function checkListItemIndent(state) {
let style = state.options.listItemIndent || "one";
if (style !== "tab" && style !== "one" && style !== "mixed")
throw new Error(
"Cannot serialize items with \`" + style + "\` for \`options.listItemIndent\`, expected \`tab\`, \`one\`, or \`mixed\`"
);
return style;
}
// node_modules/mdast-util-to-markdown/lib/handle/list-item.js
function listItem(node2, parent, state, info) {
let listItemIndent = checkListItemIndent(state), bullet = state.bulletCurrent || checkBullet(state);
parent && parent.type === "list" && parent.ordered && (bullet = (typeof parent.start == "number" && parent.start > -1 ? parent.start : 1) + (state.options.incrementListMarker === !1 ? 0 : parent.children.indexOf(node2)) + bullet);
let size = bullet.length + 1;
(listItemIndent === "tab" || listItemIndent === "mixed" && (parent && parent.type === "list" && parent.spread || node2.spread)) && (size = Math.ceil(size / 4) * 4);
let tracker = state.createTracker(info);
tracker.move(bullet + " ".repeat(size - bullet.length)), tracker.shift(size);
let exit3 = state.enter("listItem"), value = state.indentLines(
state.containerFlow(node2, tracker.current()),
map4
);
return exit3(), value;
function map4(line, index2, blank) {
return index2 ? (blank ? "" : " ".repeat(size)) + line : (blank ? bullet : bullet + " ".repeat(size - bullet.length)) + line;
}
}
// node_modules/mdast-util-to-markdown/lib/handle/paragraph.js
function paragraph(node2, _, state, info) {
let exit3 = state.enter("paragraph"), subexit = state.enter("phrasing"), value = state.containerPhrasing(node2, info);
return subexit(), exit3(), value;
}
// node_modules/mdast-util-phrasing/lib/index.js
var phrasing = (
/** @type {(node?: unknown) => node is Exclude<PhrasingContent, Html>} */
convert([
"break",
"delete",
"emphasis",
// To do: next major: removed since footnotes were added to GFM.
"footnote",
"footnoteReference",
"image",
"imageReference",
"inlineCode",
// Enabled by \`mdast-util-math\`:
"inlineMath",
"link",
"linkReference",
// Enabled by \`mdast-util-mdx\`:
"mdxJsxTextElement",
// Enabled by \`mdast-util-mdx\`:
"mdxTextExpression",
"strong",
"text",
// Enabled by \`mdast-util-directive\`:
"textDirective"
])
);
// node_modules/mdast-util-to-markdown/lib/handle/root.js
function root(node2, _, state, info) {
return (node2.children.some(function(d2) {
return phrasing(d2);
}) ? state.containerPhrasing : state.containerFlow).call(state, node2, info);
}
// node_modules/mdast-util-to-markdown/lib/util/check-strong.js
function checkStrong(state) {
let marker = state.options.strong || "*";
if (marker !== "*" && marker !== "_")
throw new Error(
"Cannot serialize strong with \`" + marker + "\` for \`options.strong\`, expected \`*\`, or \`_\`"
);
return marker;
}
// node_modules/mdast-util-to-markdown/lib/handle/strong.js
strong.peek = strongPeek;
function strong(node2, _, state, info) {
let marker = checkStrong(state), exit3 = state.enter("strong"), tracker = state.createTracker(info), value = tracker.move(marker + marker);
return value += tracker.move(
state.containerPhrasing(node2, {
before: value,
after: marker,
...tracker.current()
})
), value += tracker.move(marker + marker), exit3(), value;
}
function strongPeek(_, _1, state) {
return state.options.strong || "*";
}
// node_modules/mdast-util-to-markdown/lib/handle/text.js
function text3(node2, _, state, info) {
return state.safe(node2.value, info);
}
// node_modules/mdast-util-to-markdown/lib/util/check-rule-repetition.js
function checkRuleRepetition(state) {
let repetition = state.options.ruleRepetition || 3;
if (repetition < 3)
throw new Error(
"Cannot serialize rules with repetition \`" + repetition + "\` for \`options.ruleRepetition\`, expected \`3\` or more"
);
return repetition;
}
// node_modules/mdast-util-to-markdown/lib/handle/thematic-break.js
function thematicBreak2(_, _1, state) {
let value = (checkRule(state) + (state.options.ruleSpaces ? " " : "")).repeat(checkRuleRepetition(state));
return state.options.ruleSpaces ? value.slice(0, -1) : value;
}
// node_modules/mdast-util-to-markdown/lib/handle/index.js
var handle = {
blockquote,
break: hardBreak,
code,
definition: definition2,
emphasis,
hardBreak,
heading,
html,
image,
imageReference,
inlineCode,
link,
linkReference,
list: list2,
listItem,
paragraph,
root,
strong,
text: text3,
thematicBreak: thematicBreak2
};
// node_modules/mdast-util-gfm-table/lib/index.js
function gfmTableFromMarkdown() {
return {
enter: {
table: enterTable,
tableData: enterCell,
tableHeader: enterCell,
tableRow: enterRow
},
exit: {
codeText: exitCodeText,
table: exitTable,
tableData: exit2,
tableHeader: exit2,
tableRow: exit2
}
};
}
function enterTable(token) {
let align = token._align;
this.enter(
{
type: "table",
align: align.map(function(d2) {
return d2 === "none" ? null : d2;
}),
children: []
},
token
), this.data.inTable = !0;
}
function exitTable(token) {
this.exit(token), this.data.inTable = void 0;
}
function enterRow(token) {
this.enter({ type: "tableRow", children: [] }, token);
}
function exit2(token) {
this.exit(token);
}
function enterCell(token) {
this.enter({ type: "tableCell", children: [] }, token);
}
function exitCodeText(token) {
let value = this.resume();
this.data.inTable && (value = value.replace(/\\\\([\\\\|])/g, replace));
let node2 = this.stack[this.stack.length - 1];
node2.type, node2.value = value, this.exit(token);
}
function replace($0, $1) {
return $1 === "|" ? $1 : $0;
}
function gfmTableToMarkdown(options) {
let settings = options || {}, padding = settings.tableCellPadding, alignDelimiters = settings.tablePipeAlign, stringLength = settings.stringLength, around = padding ? " " : "|";
return {
unsafe: [
{ character: "\\r", inConstruct: "tableCell" },
{ character: \`
\`, inConstruct: "tableCell" },
// A pipe, when followed by a tab or space (padding), or a dash or colon
// (unpadded delimiter row), could result in a table.
{ atBreak: !0, character: "|", after: "[ :-]" },
// A pipe in a cell must be encoded.
{ character: "|", inConstruct: "tableCell" },
// A colon must be followed by a dash, in which case it could start a
// delimiter row.
{ atBreak: !0, character: ":", after: "-" },
// A delimiter row can also start with a dash, when followed by more
// dashes, a colon, or a pipe.
// This is a stricter version than the built in check for lists, thematic
// breaks, and setex heading underlines though:
// <https://github.com/syntax-tree/mdast-util-to-markdown/blob/51a2038/lib/unsafe.js#L57>
{ atBreak: !0, character: "-", after: "[:|-]" }
],
handlers: {
inlineCode: inlineCodeWithTable,
table: handleTable,
tableCell: handleTableCell,
tableRow: handleTableRow
}
};
function handleTable(node2, _, state, info) {
return serializeData(handleTableAsData(node2, state, info), node2.align);
}
function handleTableRow(node2, _, state, info) {
let row = handleTableRowAsData(node2, state, info), value = serializeData([row]);
return value.slice(0, value.indexOf(\`
\`));
}
function handleTableCell(node2, _, state, info) {
let exit3 = state.enter("tableCell"), subexit = state.enter("phrasing"), value = state.containerPhrasing(node2, {
...info,
before: around,
after: around
});
return subexit(), exit3(), value;
}
function serializeData(matrix, align) {
return markdownTable(matrix, {
align,
// @ts-expect-error: \`markdown-table\` types should support \`null\`.
alignDelimiters,
// @ts-expect-error: \`markdown-table\` types should support \`null\`.
padding,
// @ts-expect-error: \`markdown-table\` types should support \`null\`.
stringLength
});
}
function handleTableAsData(node2, state, info) {
let children = node2.children, index2 = -1, result = [], subexit = state.enter("table");
for (; ++index2 < children.length; )
result[index2] = handleTableRowAsData(children[index2], state, info);
return subexit(), result;
}
function handleTableRowAsData(node2, state, info) {
let children = node2.children, index2 = -1, result = [], subexit = state.enter("tableRow");
for (; ++index2 < children.length; )
result[index2] = handleTableCell(children[index2], node2, state, info);
return subexit(), result;
}
function inlineCodeWithTable(node2, parent, state) {
let value = handle.inlineCode(node2, parent, state);
return state.stack.includes("tableCell") && (value = value.replace(/\\|/g, "\\\\$&")), value;
}
}
// node_modules/mdast-util-gfm-task-list-item/lib/index.js
function gfmTaskListItemFromMarkdown() {
return {
exit: {
taskListCheckValueChecked: exitCheck,
taskListCheckValueUnchecked: exitCheck,
paragraph: exitParagraphWithTaskListItem
}
};
}
function gfmTaskListItemToMarkdown() {
return {
unsafe: [{ atBreak: !0, character: "-", after: "[:|-]" }],
handlers: { listItem: listItemWithTaskListItem }
};
}
function exitCheck(token) {
let node2 = this.stack[this.stack.length - 2];
node2.type, node2.checked = token.type === "taskListCheckValueChecked";
}
function exitParagraphWithTaskListItem(token) {
let parent = this.stack[this.stack.length - 2];
if (parent && parent.type === "listItem" && typeof parent.checked == "boolean") {
let node2 = this.stack[this.stack.length - 1];
node2.type;
let head = node2.children[0];
if (head && head.type === "text") {
let siblings = parent.children, index2 = -1, firstParaghraph;
for (; ++index2 < siblings.length; ) {
let sibling = siblings[index2];
if (sibling.type === "paragraph") {
firstParaghraph = sibling;
break;
}
}
firstParaghraph === node2 && (head.value = head.value.slice(1), head.value.length === 0 ? node2.children.shift() : node2.position && head.position && typeof head.position.start.offset == "number" && (head.position.start.column++, head.position.start.offset++, node2.position.start = Object.assign({}, head.position.start)));
}
}
this.exit(token);
}
function listItemWithTaskListItem(node2, parent, state, info) {
let head = node2.children[0], checkable = typeof node2.checked == "boolean" && head && head.type === "paragraph", checkbox = "[" + (node2.checked ? "x" : " ") + "] ", tracker = state.createTracker(info);
checkable && tracker.move(checkbox);
let value = handle.listItem(node2, parent, state, {
...info,
...tracker.current()
});
return checkable && (value = value.replace(/^(?:[*+-]|\\d+\\.)([\\r\\n]| {1,3})/, check)), value;
function check($0) {
return $0 + checkbox;
}
}
// node_modules/mdast-util-gfm/lib/index.js
function gfmFromMarkdown() {
return [
gfmAutolinkLiteralFromMarkdown(),
gfmFootnoteFromMarkdown(),
gfmStrikethroughFromMarkdown(),
gfmTableFromMarkdown(),
gfmTaskListItemFromMarkdown()
];
}
function gfmToMarkdown(options) {
return {
extensions: [
gfmAutolinkLiteralToMarkdown(),
gfmFootnoteToMarkdown(),
gfmStrikethroughToMarkdown(),
gfmTableToMarkdown(options),
gfmTaskListItemToMarkdown()
]
};
}
// node_modules/micromark-extension-gfm-autolink-literal/lib/syntax.js
var wwwPrefix = {
tokenize: tokenizeWwwPrefix,
partial: !0
}, domain = {
tokenize: tokenizeDomain,
partial: !0
}, path = {
tokenize: tokenizePath,
partial: !0
}, trail = {
tokenize: tokenizeTrail,
partial: !0
}, emailDomainDotTrail = {
tokenize: tokenizeEmailDomainDotTrail,
partial: !0
}, wwwAutolink = {
name: "wwwAutolink",
tokenize: tokenizeWwwAutolink,
previous: previousWww
}, protocolAutolink = {
name: "protocolAutolink",
tokenize: tokenizeProtocolAutolink,
previous: previousProtocol
}, emailAutolink = {
name: "emailAutolink",
tokenize: tokenizeEmailAutolink,
previous: previousEmail
}, text4 = {};
function gfmAutolinkLiteral() {
return {
text: text4
};
}
var code2 = 48;
for (; code2 < 123; )
text4[code2] = emailAutolink, code2++, code2 === 58 ? code2 = 65 : code2 === 91 && (code2 = 97);
text4[43] = emailAutolink;
text4[45] = emailAutolink;
text4[46] = emailAutolink;
text4[95] = emailAutolink;
text4[72] = [emailAutolink, protocolAutolink];
text4[104] = [emailAutolink, protocolAutolink];
text4[87] = [emailAutolink, wwwAutolink];
text4[119] = [emailAutolink, wwwAutolink];
function tokenizeEmailAutolink(effects, ok2, nok) {
let self2 = this, dot, data;
return start;
function start(code3) {
return !gfmAtext(code3) || !previousEmail.call(self2, self2.previous) || previousUnbalanced(self2.events) ? nok(code3) : (effects.enter("literalAutolink"), effects.enter("literalAutolinkEmail"), atext(code3));
}
function atext(code3) {
return gfmAtext(code3) ? (effects.consume(code3), atext) : code3 === 64 ? (effects.consume(code3), emailDomain) : nok(code3);
}
function emailDomain(code3) {
return code3 === 46 ? effects.check(emailDomainDotTrail, emailDomainAfter, emailDomainDot)(code3) : code3 === 45 || code3 === 95 || asciiAlphanumeric(code3) ? (data = !0, effects.consume(code3), emailDomain) : emailDomainAfter(code3);
}
function emailDomainDot(code3) {
return effects.consume(code3), dot = !0, emailDomain;
}
function emailDomainAfter(code3) {
return data && dot && asciiAlpha(self2.previous) ? (effects.exit("literalAutolinkEmail"), effects.exit("literalAutolink"), ok2(code3)) : nok(code3);
}
}
function tokenizeWwwAutolink(effects, ok2, nok) {
let self2 = this;
return wwwStart;
function wwwStart(code3) {
return code3 !== 87 && code3 !== 119 || !previousWww.call(self2, self2.previous) || previousUnbalanced(self2.events) ? nok(code3) : (effects.enter("literalAutolink"), effects.enter("literalAutolinkWww"), effects.check(wwwPrefix, effects.attempt(domain, effects.attempt(path, wwwAfter), nok), nok)(code3));
}
function wwwAfter(code3) {
return effects.exit("literalAutolinkWww"), effects.exit("literalAutolink"), ok2(code3);
}
}
function tokenizeProtocolAutolink(effects, ok2, nok) {
let self2 = this, buffer = "", seen = !1;
return protocolStart;
function protocolStart(code3) {
return (code3 === 72 || code3 === 104) && previousProtocol.call(self2, self2.previous) && !previousUnbalanced(self2.events) ? (effects.enter("literalAutolink"), effects.enter("literalAutolinkHttp"), buffer += String.fromCodePoint(code3), effects.consume(code3), protocolPrefixInside) : nok(code3);
}
function protocolPrefixInside(code3) {
if (asciiAlpha(code3) && buffer.length < 5)
return buffer += String.fromCodePoint(code3), effects.consume(code3), protocolPrefixInside;
if (code3 === 58) {
let protocol = buffer.toLowerCase();
if (protocol === "http" || protocol === "https")
return effects.consume(code3), protocolSlashesInside;
}
return nok(code3);
}
function protocolSlashesInside(code3) {
return code3 === 47 ? (effects.consume(code3), seen ? afterProtocol : (seen = !0, protocolSlashesInside)) : nok(code3);
}
function afterProtocol(code3) {
return code3 === null || asciiControl(code3) || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3) || unicodePunctuation(code3) ? nok(code3) : effects.attempt(domain, effects.attempt(path, protocolAfter), nok)(code3);
}
function protocolAfter(code3) {
return effects.exit("literalAutolinkHttp"), effects.exit("literalAutolink"), ok2(code3);
}
}
function tokenizeWwwPrefix(effects, ok2, nok) {
let size = 0;
return wwwPrefixInside;
function wwwPrefixInside(code3) {
return (code3 === 87 || code3 === 119) && size < 3 ? (size++, effects.consume(code3), wwwPrefixInside) : code3 === 46 && size === 3 ? (effects.consume(code3), wwwPrefixAfter) : nok(code3);
}
function wwwPrefixAfter(code3) {
return code3 === null ? nok(code3) : ok2(code3);
}
}
function tokenizeDomain(effects, ok2, nok) {
let underscoreInLastSegment, underscoreInLastLastSegment, seen;
return domainInside;
function domainInside(code3) {
return code3 === 46 || code3 === 95 ? effects.check(trail, domainAfter, domainAtPunctuation)(code3) : code3 === null || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3) || code3 !== 45 && unicodePunctuation(code3) ? domainAfter(code3) : (seen = !0, effects.consume(code3), domainInside);
}
function domainAtPunctuation(code3) {
return code3 === 95 ? underscoreInLastSegment = !0 : (underscoreInLastLastSegment = underscoreInLastSegment, underscoreInLastSegment = void 0), effects.consume(code3), domainInside;
}
function domainAfter(code3) {
return underscoreInLastLastSegment || underscoreInLastSegment || !seen ? nok(code3) : ok2(code3);
}
}
function tokenizePath(effects, ok2) {
let sizeOpen = 0, sizeClose = 0;
return pathInside;
function pathInside(code3) {
return code3 === 40 ? (sizeOpen++, effects.consume(code3), pathInside) : code3 === 41 && sizeClose < sizeOpen ? pathAtPunctuation(code3) : code3 === 33 || code3 === 34 || code3 === 38 || code3 === 39 || code3 === 41 || code3 === 42 || code3 === 44 || code3 === 46 || code3 === 58 || code3 === 59 || code3 === 60 || code3 === 63 || code3 === 93 || code3 === 95 || code3 === 126 ? effects.check(trail, ok2, pathAtPunctuation)(code3) : code3 === null || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3) ? ok2(code3) : (effects.consume(code3), pathInside);
}
function pathAtPunctuation(code3) {
return code3 === 41 && sizeClose++, effects.consume(code3), pathInside;
}
}
function tokenizeTrail(effects, ok2, nok) {
return trail2;
function trail2(code3) {
return code3 === 33 || code3 === 34 || code3 === 39 || code3 === 41 || code3 === 42 || code3 === 44 || code3 === 46 || code3 === 58 || code3 === 59 || code3 === 63 || code3 === 95 || code3 === 126 ? (effects.consume(code3), trail2) : code3 === 38 ? (effects.consume(code3), trailCharacterReferenceStart) : code3 === 93 ? (effects.consume(code3), trailBracketAfter) : (
// \`<\` is an end.
code3 === 60 || // So is whitespace.
code3 === null || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3) ? ok2(code3) : nok(code3)
);
}
function trailBracketAfter(code3) {
return code3 === null || code3 === 40 || code3 === 91 || markdownLineEndingOrSpace(code3) || unicodeWhitespace(code3) ? ok2(code3) : trail2(code3);
}
function trailCharacterReferenceStart(code3) {
return asciiAlpha(code3) ? trailCharacterReferenceInside(code3) : nok(code3);
}
function trailCharacterReferenceInside(code3) {
return code3 === 59 ? (effects.consume(code3), trail2) : asciiAlpha(code3) ? (effects.consume(code3), trailCharacterReferenceInside) : nok(code3);
}
}
function tokenizeEmailDomainDotTrail(effects, ok2, nok) {
return start;
function start(code3) {
return effects.consume(code3), after;
}
function after(code3) {
return asciiAlphanumeric(code3) ? nok(code3) : ok2(code3);
}
}
function previousWww(code3) {
return code3 === null || code3 === 40 || code3 === 42 || code3 === 95 || code3 === 91 || code3 === 93 || code3 === 126 || markdownLineEndingOrSpace(code3);
}
function previousProtocol(code3) {
return !asciiAlpha(code3);
}
function previousEmail(code3) {
return !(code3 === 47 || gfmAtext(code3));
}
function gfmAtext(code3) {
return code3 === 43 || code3 === 45 || code3 === 46 || code3 === 95 || asciiAlphanumeric(code3);
}
function previousUnbalanced(events) {
let index2 = events.length, result = !1;
for (; index2--; ) {
let token = events[index2][1];
if ((token.type === "labelLink" || token.type === "labelImage") && !token._balanced) {
result = !0;
break;
}
if (token._gfmAutolinkLiteralWalkedInto) {
result = !1;
break;
}
}
return events.length > 0 && !result && (events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = !0), result;
}
// node_modules/micromark-extension-gfm-footnote/lib/syntax.js
var indent = {
tokenize: tokenizeIndent2,
partial: !0
};
function gfmFootnote() {
return {
document: {
91: {
name: "gfmFootnoteDefinition",
tokenize: tokenizeDefinitionStart,
continuation: {
tokenize: tokenizeDefinitionContinuation
},
exit: gfmFootnoteDefinitionEnd
}
},
text: {
91: {
name: "gfmFootnoteCall",
tokenize: tokenizeGfmFootnoteCall
},
93: {
name: "gfmPotentialFootnoteCall",
add: "after",
tokenize: tokenizePotentialGfmFootnoteCall,
resolveTo: resolveToPotentialGfmFootnoteCall
}
}
};
}
function tokenizePotentialGfmFootnoteCall(effects, ok2, nok) {
let self2 = this, index2 = self2.events.length, defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []), labelStart;
for (; index2--; ) {
let token = self2.events[index2][1];
if (token.type === "labelImage") {
labelStart = token;
break;
}
if (token.type === "gfmFootnoteCall" || token.type === "labelLink" || token.type === "label" || token.type === "image" || token.type === "link")
break;
}
return start;
function start(code3) {
if (!labelStart || !labelStart._balanced)
return nok(code3);
let id = normalizeIdentifier(self2.sliceSerialize({
start: labelStart.end,
end: self2.now()
}));
return id.codePointAt(0) !== 94 || !defined.includes(id.slice(1)) ? nok(code3) : (effects.enter("gfmFootnoteCallLabelMarker"), effects.consume(code3), effects.exit("gfmFootnoteCallLabelMarker"), ok2(code3));
}
}
function resolveToPotentialGfmFootnoteCall(events, context) {
let index2 = events.length, labelStart;
for (; index2--; )
if (events[index2][1].type === "labelImage" && events[index2][0] === "enter") {
labelStart = events[index2][1];
break;
}
events[index2 + 1][1].type = "data", events[index2 + 3][1].type = "gfmFootnoteCallLabelMarker";
let call = {
type: "gfmFootnoteCall",
start: Object.assign({}, events[index2 + 3][1].start),
end: Object.assign({}, events[events.length - 1][1].end)
}, marker = {
type: "gfmFootnoteCallMarker",
start: Object.assign({}, events[index2 + 3][1].end),
end: Object.assign({}, events[index2 + 3][1].end)
};
marker.end.column++, marker.end.offset++, marker.end._bufferIndex++;
let string3 = {
type: "gfmFootnoteCallString",
start: Object.assign({}, marker.end),
end: Object.assign({}, events[events.length - 1][1].start)
}, chunk = {
type: "chunkString",
contentType: "string",
start: Object.assign({}, string3.start),
end: Object.assign({}, string3.end)
}, replacement = [
// Take the \`labelImageMarker\` (now \`data\`, the \`!\`)
events[index2 + 1],
events[index2 + 2],
["enter", call, context],
// The \`[\`
events[index2 + 3],
events[index2 + 4],
// The \`^\`.
["enter", marker, context],
["exit", marker, context],
// Everything in between.
["enter", string3, context],
["enter", chunk, context],
["exit", chunk, context],
["exit", string3, context],
// The ending (\`]\`, properly parsed and labelled).
events[events.length - 2],
events[events.length - 1],
["exit", call, context]
];
return events.splice(index2, events.length - index2 + 1, ...replacement), events;
}
function tokenizeGfmFootnoteCall(effects, ok2, nok) {
let self2 = this, defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []), size = 0, data;
return start;
function start(code3) {
return effects.enter("gfmFootnoteCall"), effects.enter("gfmFootnoteCallLabelMarker"), effects.consume(code3), effects.exit("gfmFootnoteCallLabelMarker"), callStart;
}
function callStart(code3) {
return code3 !== 94 ? nok(code3) : (effects.enter("gfmFootnoteCallMarker"), effects.consume(code3), effects.exit("gfmFootnoteCallMarker"), effects.enter("gfmFootnoteCallString"), effects.enter("chunkString").contentType = "string", callData);
}
function callData(code3) {
if (
// Too long.
size > 999 || // Closing brace with nothing.
code3 === 93 && !data || // Space or tab is not supported by GFM for some reason.
// \`\\n\` and \`[\` not being supported makes sense.
code3 === null || code3 === 91 || markdownLineEndingOrSpace(code3)
)
return nok(code3);
if (code3 === 93) {
effects.exit("chunkString");
let token = effects.exit("gfmFootnoteCallString");
return defined.includes(normalizeIdentifier(self2.sliceSerialize(token))) ? (effects.enter("gfmFootnoteCallLabelMarker"), effects.consume(code3), effects.exit("gfmFootnoteCallLabelMarker"), effects.exit("gfmFootnoteCall"), ok2) : nok(code3);
}
return markdownLineEndingOrSpace(code3) || (data = !0), size++, effects.consume(code3), code3 === 92 ? callEscape : callData;
}
function callEscape(code3) {
return code3 === 91 || code3 === 92 || code3 === 93 ? (effects.consume(code3), size++, callData) : callData(code3);
}
}
function tokenizeDefinitionStart(effects, ok2, nok) {
let self2 = this, defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []), identifier, size = 0, data;
return start;
function start(code3) {
return effects.enter("gfmFootnoteDefinition")._container = !0, effects.enter("gfmFootnoteDefinitionLabel"), effects.enter("gfmFootnoteDefinitionLabelMarker"), effects.consume(code3), effects.exit("gfmFootnoteDefinitionLabelMarker"), labelAtMarker;
}
function labelAtMarker(code3) {
return code3 === 94 ? (effects.enter("gfmFootnoteDefinitionMarker"), effects.consume(code3), effects.exit("gfmFootnoteDefinitionMarker"), effects.enter("gfmFootnoteDefinitionLabelString"), effects.enter("chunkString").contentType = "string", labelInside) : nok(code3);
}
function labelInside(code3) {
if (
// Too long.
size > 999 || // Closing brace with nothing.
code3 === 93 && !data || // Space or tab is not supported by GFM for some reason.
// \`\\n\` and \`[\` not being supported makes sense.
code3 === null || code3 === 91 || markdownLineEndingOrSpace(code3)
)
return nok(code3);
if (code3 === 93) {
effects.exit("chunkString");
let token = effects.exit("gfmFootnoteDefinitionLabelString");
return identifier = normalizeIdentifier(self2.sliceSerialize(token)), effects.enter("gfmFootnoteDefinitionLabelMarker"), effects.consume(code3), effects.exit("gfmFootnoteDefinitionLabelMarker"), effects.exit("gfmFootnoteDefinitionLabel"), labelAfter;
}
return markdownLineEndingOrSpace(code3) || (data = !0), size++, effects.consume(code3), code3 === 92 ? labelEscape : labelInside;
}
function labelEscape(code3) {
return code3 === 91 || code3 === 92 || code3 === 93 ? (effects.consume(code3), size++, labelInside) : labelInside(code3);
}
function labelAfter(code3) {
return code3 === 58 ? (effects.enter("definitionMarker"), effects.consume(code3), effects.exit("definitionMarker"), defined.includes(identifier) || defined.push(identifier), factorySpace(effects, whitespaceAfter, "gfmFootnoteDefinitionWhitespace")) : nok(code3);
}
function whitespaceAfter(code3) {
return ok2(code3);
}
}
function tokenizeDefinitionContinuation(effects, ok2, nok) {
return effects.check(blankLine, ok2, effects.attempt(indent, ok2, nok));
}
function gfmFootnoteDefinitionEnd(effects) {
effects.exit("gfmFootnoteDefinition");
}
function tokenizeIndent2(effects, ok2, nok) {
let self2 = this;
return factorySpace(effects, afterPrefix, "gfmFootnoteDefinitionIndent", 5);
function afterPrefix(code3) {
let tail = self2.events[self2.events.length - 1];
return tail && tail[1].type === "gfmFootnoteDefinitionIndent" && tail[2].sliceSerialize(tail[1], !0).length === 4 ? ok2(code3) : nok(code3);
}
}
// node_modules/micromark-extension-gfm-strikethrough/lib/syntax.js
function gfmStrikethrough(options) {
let single = (options || {}).singleTilde, tokenizer = {
name: "strikethrough",
tokenize: tokenizeStrikethrough,
resolveAll: resolveAllStrikethrough
};
return single == null && (single = !0), {
text: {
126: tokenizer
},
insideSpan: {
null: [tokenizer]
},
attentionMarkers: {
null: [126]
}
};
function resolveAllStrikethrough(events, context) {
let index2 = -1;
for (; ++index2 < events.length; )
if (events[index2][0] === "enter" && events[index2][1].type === "strikethroughSequenceTemporary" && events[index2][1]._close) {
let open = index2;
for (; open--; )
if (events[open][0] === "exit" && events[open][1].type === "strikethroughSequenceTemporary" && events[open][1]._open && // If the sizes are the same:
events[index2][1].end.offset - events[index2][1].start.offset === events[open][1].end.offset - events[open][1].start.offset) {
events[index2][1].type = "strikethroughSequence", events[open][1].type = "strikethroughSequence";
let strikethrough = {
type: "strikethrough",
start: Object.assign({}, events[open][1].start),
end: Object.assign({}, events[index2][1].end)
}, text5 = {
type: "strikethroughText",
start: Object.assign({}, events[open][1].end),
end: Object.assign({}, events[index2][1].start)
}, nextEvents = [["enter", strikethrough, context], ["enter", events[open][1], context], ["exit", events[open][1], context], ["enter", text5, context]], insideSpan2 = context.parser.constructs.insideSpan.null;
insideSpan2 && splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan2, events.slice(open + 1, index2), context)), splice(nextEvents, nextEvents.length, 0, [["exit", text5, context], ["enter", events[index2][1], context], ["exit", events[index2][1], context], ["exit", strikethrough, context]]), splice(events, open - 1, index2 - open + 3, nextEvents), index2 = open + nextEvents.length - 2;
break;
}
}
for (index2 = -1; ++index2 < events.length; )
events[index2][1].type === "strikethroughSequenceTemporary" && (events[index2][1].type = "data");
return events;
}
function tokenizeStrikethrough(effects, ok2, nok) {
let previous3 = this.previous, events = this.events, size = 0;
return start;
function start(code3) {
return previous3 === 126 && events[events.length - 1][1].type !== "characterEscape" ? nok(code3) : (effects.enter("strikethroughSequenceTemporary"), more(code3));
}
function more(code3) {
let before = classifyCharacter(previous3);
if (code3 === 126)
return size > 1 ? nok(code3) : (effects.consume(code3), size++, more);
if (size < 2 && !single) return nok(code3);
let token = effects.exit("strikethroughSequenceTemporary"), after = classifyCharacter(code3);
return token._open = !after || after === 2 && !!before, token._close = !before || before === 2 && !!after, ok2(code3);
}
}
}
// node_modules/micromark-extension-gfm-table/lib/edit-map.js
var EditMap = class {
/**
* Create a new edit map.
*/
constructor() {
this.map = [];
}
/**
* Create an edit: a remove and/or add at a certain place.
*
* @param {number} index
* @param {number} remove
* @param {Array<Event>} add
* @returns {undefined}
*/
add(index2, remove, add) {
addImplementation(this, index2, remove, add);
}
// To do: add this when moving to \`micromark\`.
// /**
// * Create an edit: but insert \`add\` before existing additions.
// *
// * @param {number} index
// * @param {number} remove
// * @param {Array<Event>} add
// * @returns {undefined}
// */
// addBefore(index, remove, add) {
// addImplementation(this, index, remove, add, true)
// }
/**
* Done, change the events.
*
* @param {Array<Event>} events
* @returns {undefined}
*/
consume(events) {
if (this.map.sort(function(a, b2) {
return a[0] - b2[0];
}), this.map.length === 0)
return;
let index2 = this.map.length, vecs = [];
for (; index2 > 0; )
index2 -= 1, vecs.push(events.slice(this.map[index2][0] + this.map[index2][1]), this.map[index2][2]), events.length = this.map[index2][0];
vecs.push([...events]), events.length = 0;
let slice = vecs.pop();
for (; slice; )
events.push(...slice), slice = vecs.pop();
this.map.length = 0;
}
};
function addImplementation(editMap, at, remove, add) {
let index2 = 0;
if (!(remove === 0 && add.length === 0)) {
for (; index2 < editMap.map.length; ) {
if (editMap.map[index2][0] === at) {
editMap.map[index2][1] += remove, editMap.map[index2][2].push(...add);
return;
}
index2 += 1;
}
editMap.map.push([at, remove, add]);
}
}
// node_modules/micromark-extension-gfm-table/lib/infer.js
function gfmTableAlign(events, index2) {
let inDelimiterRow = !1, align = [];
for (; index2 < events.length; ) {
let event = events[index2];
if (inDelimiterRow) {
if (event[0] === "enter")
event[1].type === "tableContent" && align.push(events[index2 + 1][1].type === "tableDelimiterMarker" ? "left" : "none");
else if (event[1].type === "tableContent") {
if (events[index2 - 1][1].type === "tableDelimiterMarker") {
let alignIndex = align.length - 1;
align[alignIndex] = align[alignIndex] === "left" ? "center" : "right";
}
} else if (event[1].type === "tableDelimiterRow")
break;
} else event[0] === "enter" && event[1].type === "tableDelimiterRow" && (inDelimiterRow = !0);
index2 += 1;
}
return align;
}
// node_modules/micromark-extension-gfm-table/lib/syntax.js
function gfmTable() {
return {
flow: {
null: {
name: "table",
tokenize: tokenizeTable,
resolveAll: resolveTable
}
}
};
}
function tokenizeTable(effects, ok2, nok) {
let self2 = this, size = 0, sizeB = 0, seen;
return start;
function start(code3) {
let index2 = self2.events.length - 1;
for (; index2 > -1; ) {
let type = self2.events[index2][1].type;
if (type === "lineEnding" || // Note: markdown-rs uses \`whitespace\` instead of \`linePrefix\`
type === "linePrefix") index2--;
else break;
}
let tail = index2 > -1 ? self2.events[index2][1].type : null, next = tail === "tableHead" || tail === "tableRow" ? bodyRowStart : headRowBefore;
return next === bodyRowStart && self2.parser.lazy[self2.now().line] ? nok(code3) : next(code3);
}
function headRowBefore(code3) {
return effects.enter("tableHead"), effects.enter("tableRow"), headRowStart(code3);
}
function headRowStart(code3) {
return code3 === 124 || (seen = !0, sizeB += 1), headRowBreak(code3);
}
function headRowBreak(code3) {
return code3 === null ? nok(code3) : markdownLineEnding(code3) ? sizeB > 1 ? (sizeB = 0, self2.interrupt = !0, effects.exit("tableRow"), effects.enter("lineEnding"), effects.consume(code3), effects.exit("lineEnding"), headDelimiterStart) : nok(code3) : markdownSpace(code3) ? factorySpace(effects, headRowBreak, "whitespace")(code3) : (sizeB += 1, seen && (seen = !1, size += 1), code3 === 124 ? (effects.enter("tableCellDivider"), effects.consume(code3), effects.exit("tableCellDivider"), seen = !0, headRowBreak) : (effects.enter("data"), headRowData(code3)));
}
function headRowData(code3) {
return code3 === null || code3 === 124 || markdownLineEndingOrSpace(code3) ? (effects.exit("data"), headRowBreak(code3)) : (effects.consume(code3), code3 === 92 ? headRowEscape : headRowData);
}
function headRowEscape(code3) {
return code3 === 92 || code3 === 124 ? (effects.consume(code3), headRowData) : headRowData(code3);
}
function headDelimiterStart(code3) {
return self2.interrupt = !1, self2.parser.lazy[self2.now().line] ? nok(code3) : (effects.enter("tableDelimiterRow"), seen = !1, markdownSpace(code3) ? factorySpace(effects, headDelimiterBefore, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code3) : headDelimiterBefore(code3));
}
function headDelimiterBefore(code3) {
return code3 === 45 || code3 === 58 ? headDelimiterValueBefore(code3) : code3 === 124 ? (seen = !0, effects.enter("tableCellDivider"), effects.consume(code3), effects.exit("tableCellDivider"), headDelimiterCellBefore) : headDelimiterNok(code3);
}
function headDelimiterCellBefore(code3) {
return markdownSpace(code3) ? factorySpace(effects, headDelimiterValueBefore, "whitespace")(code3) : headDelimiterValueBefore(code3);
}
function headDelimiterValueBefore(code3) {
return code3 === 58 ? (sizeB += 1, seen = !0, effects.enter("tableDelimiterMarker"), effects.consume(code3), effects.exit("tableDelimiterMarker"), headDelimiterLeftAlignmentAfter) : code3 === 45 ? (sizeB += 1, headDelimiterLeftAlignmentAfter(code3)) : code3 === null || markdownLineEnding(code3) ? headDelimiterCellAfter(code3) : headDelimiterNok(code3);
}
function headDelimiterLeftAlignmentAfter(code3) {
return code3 === 45 ? (effects.enter("tableDelimiterFiller"), headDelimiterFiller(code3)) : headDelimiterNok(code3);
}
function headDelimiterFiller(code3) {
return code3 === 45 ? (effects.consume(code3), headDelimiterFiller) : code3 === 58 ? (seen = !0, effects.exit("tableDelimiterFiller"), effects.enter("tableDelimiterMarker"), effects.consume(code3), effects.exit("tableDelimiterMarker"), headDelimiterRightAlignmentAfter) : (effects.exit("tableDelimiterFiller"), headDelimiterRightAlignmentAfter(code3));
}
function headDelimiterRightAlignmentAfter(code3) {
return markdownSpace(code3) ? factorySpace(effects, headDelimiterCellAfter, "whitespace")(code3) : headDelimiterCellAfter(code3);
}
function headDelimiterCellAfter(code3) {
return code3 === 124 ? headDelimiterBefore(code3) : code3 === null || markdownLineEnding(code3) ? !seen || size !== sizeB ? headDelimiterNok(code3) : (effects.exit("tableDelimiterRow"), effects.exit("tableHead"), ok2(code3)) : headDelimiterNok(code3);
}
function headDelimiterNok(code3) {
return nok(code3);
}
function bodyRowStart(code3) {
return effects.enter("tableRow"), bodyRowBreak(code3);
}
function bodyRowBreak(code3) {
return code3 === 124 ? (effects.enter("tableCellDivider"), effects.consume(code3), effects.exit("tableCellDivider"), bodyRowBreak) : code3 === null || markdownLineEnding(code3) ? (effects.exit("tableRow"), ok2(code3)) : markdownSpace(code3) ? factorySpace(effects, bodyRowBreak, "whitespace")(code3) : (effects.enter("data"), bodyRowData(code3));
}
function bodyRowData(code3) {
return code3 === null || code3 === 124 || markdownLineEndingOrSpace(code3) ? (effects.exit("data"), bodyRowBreak(code3)) : (effects.consume(code3), code3 === 92 ? bodyRowEscape : bodyRowData);
}
function bodyRowEscape(code3) {
return code3 === 92 || code3 === 124 ? (effects.consume(code3), bodyRowData) : bodyRowData(code3);
}
}
function resolveTable(events, context) {
let index2 = -1, inFirstCellAwaitingPipe = !0, rowKind = 0, lastCell = [0, 0, 0, 0], cell = [0, 0, 0, 0], afterHeadAwaitingFirstBodyRow = !1, lastTableEnd = 0, currentTable, currentBody, currentCell, map4 = new EditMap();
for (; ++index2 < events.length; ) {
let event = events[index2], token = event[1];
event[0] === "enter" ? token.type === "tableHead" ? (afterHeadAwaitingFirstBodyRow = !1, lastTableEnd !== 0 && (flushTableEnd(map4, context, lastTableEnd, currentTable, currentBody), currentBody = void 0, lastTableEnd = 0), currentTable = {
type: "table",
start: Object.assign({}, token.start),
// Note: correct end is set later.
end: Object.assign({}, token.end)
}, map4.add(index2, 0, [["enter", currentTable, context]])) : token.type === "tableRow" || token.type === "tableDelimiterRow" ? (inFirstCellAwaitingPipe = !0, currentCell = void 0, lastCell = [0, 0, 0, 0], cell = [0, index2 + 1, 0, 0], afterHeadAwaitingFirstBodyRow && (afterHeadAwaitingFirstBodyRow = !1, currentBody = {
type: "tableBody",
start: Object.assign({}, token.start),
// Note: correct end is set later.
end: Object.assign({}, token.end)
}, map4.add(index2, 0, [["enter", currentBody, context]])), rowKind = token.type === "tableDelimiterRow" ? 2 : currentBody ? 3 : 1) : rowKind && (token.type === "data" || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller") ? (inFirstCellAwaitingPipe = !1, cell[2] === 0 && (lastCell[1] !== 0 && (cell[0] = cell[1], currentCell = flushCell(map4, context, lastCell, rowKind, void 0, currentCell), lastCell = [0, 0, 0, 0]), cell[2] = index2)) : token.type === "tableCellDivider" && (inFirstCellAwaitingPipe ? inFirstCellAwaitingPipe = !1 : (lastCell[1] !== 0 && (cell[0] = cell[1], currentCell = flushCell(map4, context, lastCell, rowKind, void 0, currentCell)), lastCell = cell, cell = [lastCell[1], index2, 0, 0])) : token.type === "tableHead" ? (afterHeadAwaitingFirstBodyRow = !0, lastTableEnd = index2) : token.type === "tableRow" || token.type === "tableDelimiterRow" ? (lastTableEnd = index2, lastCell[1] !== 0 ? (cell[0] = cell[1], currentCell = flushCell(map4, context, lastCell, rowKind, index2, currentCell)) : cell[1] !== 0 && (currentCell = flushCell(map4, context, cell, rowKind, index2, currentCell)), rowKind = 0) : rowKind && (token.type === "data" || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller") && (cell[3] = index2);
}
for (lastTableEnd !== 0 && flushTableEnd(map4, context, lastTableEnd, currentTable, currentBody), map4.consume(context.events), index2 = -1; ++index2 < context.events.length; ) {
let event = context.events[index2];
event[0] === "enter" && event[1].type === "table" && (event[1]._align = gfmTableAlign(context.events, index2));
}
return events;
}
function flushCell(map4, context, range, rowKind, rowEnd, previousCell) {
let groupName = rowKind === 1 ? "tableHeader" : rowKind === 2 ? "tableDelimiter" : "tableData", valueName = "tableContent";
range[0] !== 0 && (previousCell.end = Object.assign({}, getPoint(context.events, range[0])), map4.add(range[0], 0, [["exit", previousCell, context]]));
let now = getPoint(context.events, range[1]);
if (previousCell = {
type: groupName,
start: Object.assign({}, now),
// Note: correct end is set later.
end: Object.assign({}, now)
}, map4.add(range[1], 0, [["enter", previousCell, context]]), range[2] !== 0) {
let relatedStart = getPoint(context.events, range[2]), relatedEnd = getPoint(context.events, range[3]), valueToken = {
type: valueName,
start: Object.assign({}, relatedStart),
end: Object.assign({}, relatedEnd)
};
if (map4.add(range[2], 0, [["enter", valueToken, context]]), rowKind !== 2) {
let start = context.events[range[2]], end = context.events[range[3]];
if (start[1].end = Object.assign({}, end[1].end), start[1].type = "chunkText", start[1].contentType = "text", range[3] > range[2] + 1) {
let a = range[2] + 1, b2 = range[3] - range[2] - 1;
map4.add(a, b2, []);
}
}
map4.add(range[3] + 1, 0, [["exit", valueToken, context]]);
}
return rowEnd !== void 0 && (previousCell.end = Object.assign({}, getPoint(context.events, rowEnd)), map4.add(rowEnd, 0, [["exit", previousCell, context]]), previousCell = void 0), previousCell;
}
function flushTableEnd(map4, context, index2, table, tableBody) {
let exits = [], related = getPoint(context.events, index2);
tableBody && (tableBody.end = Object.assign({}, related), exits.push(["exit", tableBody, context])), table.end = Object.assign({}, related), exits.push(["exit", table, context]), map4.add(index2 + 1, 0, exits);
}
function getPoint(events, index2) {
let event = events[index2], side = event[0] === "enter" ? "start" : "end";
return event[1][side];
}
// node_modules/micromark-extension-gfm-task-list-item/lib/syntax.js
var tasklistCheck = {
name: "tasklistCheck",
tokenize: tokenizeTasklistCheck
};
function gfmTaskListItem() {
return {
text: {
91: tasklistCheck
}
};
}
function tokenizeTasklistCheck(effects, ok2, nok) {
let self2 = this;
return open;
function open(code3) {
return (
// Exit if there\u2019s stuff before.
self2.previous !== null || // Exit if not in the first content that is the first child of a list
// item.
!self2._gfmTasklistFirstContentOfListItem ? nok(code3) : (effects.enter("taskListCheck"), effects.enter("taskListCheckMarker"), effects.consume(code3), effects.exit("taskListCheckMarker"), inside)
);
}
function inside(code3) {
return markdownLineEndingOrSpace(code3) ? (effects.enter("taskListCheckValueUnchecked"), effects.consume(code3), effects.exit("taskListCheckValueUnchecked"), close) : code3 === 88 || code3 === 120 ? (effects.enter("taskListCheckValueChecked"), effects.consume(code3), effects.exit("taskListCheckValueChecked"), close) : nok(code3);
}
function close(code3) {
return code3 === 93 ? (effects.enter("taskListCheckMarker"), effects.consume(code3), effects.exit("taskListCheckMarker"), effects.exit("taskListCheck"), after) : nok(code3);
}
function after(code3) {
return markdownLineEnding(code3) ? ok2(code3) : markdownSpace(code3) ? effects.check({
tokenize: spaceThenNonSpace
}, ok2, nok)(code3) : nok(code3);
}
}
function spaceThenNonSpace(effects, ok2, nok) {
return factorySpace(effects, after, "whitespace");
function after(code3) {
return code3 === null ? nok(code3) : ok2(code3);
}
}
// node_modules/micromark-extension-gfm/index.js
function gfm(options) {
return combineExtensions([
gfmAutolinkLiteral(),
gfmFootnote(),
gfmStrikethrough(options),
gfmTable(),
gfmTaskListItem()
]);
}
// node_modules/remark-gfm/lib/index.js
var emptyOptions2 = {};
function remarkGfm(options) {
let self2 = (
/** @type {Processor} */
this
), settings = options || emptyOptions2, data = self2.data(), micromarkExtensions = data.micromarkExtensions || (data.micromarkExtensions = []), fromMarkdownExtensions = data.fromMarkdownExtensions || (data.fromMarkdownExtensions = []), toMarkdownExtensions = data.toMarkdownExtensions || (data.toMarkdownExtensions = []);
micromarkExtensions.push(gfm(settings)), fromMarkdownExtensions.push(gfmFromMarkdown()), toMarkdownExtensions.push(gfmToMarkdown(settings));
}
// src-charts/markdown/getMarkdownTableByIdx.js
function getMarkdownTableByIdx(markdownText, idx = 0) {
let tableCount = 0, targetTable = null, tree = unified().use(remarkParse).use(remarkGfm).parse(markdownText);
if (visit(tree, "table", (node2) => {
if (tableCount === idx)
return targetTable = node2, !1;
tableCount++;
}), !targetTable || !targetTable.position)
return null;
let { start, end } = targetTable.position;
return markdownText[end.offset - 2] === \`
\` && markdownText[end.offset - 1] === "\\\\" ? markdownText.substring(start.offset, end.offset - 2) : markdownText.substring(start.offset, end.offset);
}
// src-charts/markdown/parseMarkdownTable.js
function parseMarkdownTable(markdownText) {
let result = [], tree = unified().use(remarkParse).use(remarkGfm).parse(markdownText);
return visit(tree, "table", (node2) => (node2.children.forEach((row) => {
let rowData = [];
row.children.forEach((cell) => {
let cellText = "";
visit(cell, "text", (textNode) => {
cellText += textNode.value;
}), rowData.push(cellText.trim());
}), result.push(rowData);
}), !1)), result.filter((row) => !row.every((cell) => cell.trim() === ""));
}
// node_modules/lodash-es/_freeGlobal.js
var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis, freeGlobal_default = freeGlobal;
// node_modules/lodash-es/_root.js
var freeSelf = typeof self == "object" && self && self.Object === Object && self, root2 = freeGlobal_default || freeSelf || Function("return this")(), root_default = root2;
// node_modules/lodash-es/_Symbol.js
var Symbol2 = root_default.Symbol, Symbol_default = Symbol2;
// node_modules/lodash-es/_getRawTag.js
var objectProto = Object.prototype, hasOwnProperty2 = objectProto.hasOwnProperty, nativeObjectToString = objectProto.toString, symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty2.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = !0;
} catch {
}
var result = nativeObjectToString.call(value);
return unmasked && (isOwn ? value[symToStringTag] = tag : delete value[symToStringTag]), result;
}
var getRawTag_default = getRawTag;
// node_modules/lodash-es/_objectToString.js
var objectProto2 = Object.prototype, nativeObjectToString2 = objectProto2.toString;
function objectToString(value) {
return nativeObjectToString2.call(value);
}
var objectToString_default = objectToString;
// node_modules/lodash-es/_baseGetTag.js
var nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
function baseGetTag(value) {
return value == null ? value === void 0 ? undefinedTag : nullTag : symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
}
var baseGetTag_default = baseGetTag;
// node_modules/lodash-es/isObjectLike.js
function isObjectLike(value) {
return value != null && typeof value == "object";
}
var isObjectLike_default = isObjectLike;
// node_modules/lodash-es/isArray.js
var isArray = Array.isArray, isArray_default = isArray;
// node_modules/lodash-es/isObject.js
function isObject(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
var isObject_default = isObject;
// node_modules/lodash-es/isFunction.js
var asyncTag = "[object AsyncFunction]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
function isFunction(value) {
if (!isObject_default(value))
return !1;
var tag = baseGetTag_default(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_default = isFunction;
// node_modules/lodash-es/_coreJsData.js
var coreJsData = root_default["__core-js_shared__"], coreJsData_default = coreJsData;
// node_modules/lodash-es/_isMasked.js
var maskSrcKey = function() {
var uid = /[^.]+$/.exec(coreJsData_default && coreJsData_default.keys && coreJsData_default.keys.IE_PROTO || "");
return uid ? "Symbol(src)_1." + uid : "";
}();
function isMasked(func) {
return !!maskSrcKey && maskSrcKey in func;
}
var isMasked_default = isMasked;
// node_modules/lodash-es/_toSource.js
var funcProto = Function.prototype, funcToString = funcProto.toString;
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch {
}
try {
return func + "";
} catch {
}
}
return "";
}
var toSource_default = toSource;
// node_modules/lodash-es/_baseIsNative.js
var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g, reIsHostCtor = /^\\[object .+?Constructor\\]$/, funcProto2 = Function.prototype, objectProto3 = Object.prototype, funcToString2 = funcProto2.toString, hasOwnProperty3 = objectProto3.hasOwnProperty, reIsNative = RegExp(
"^" + funcToString2.call(hasOwnProperty3).replace(reRegExpChar, "\\\\$&").replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, "$1.*?") + "$"
);
function baseIsNative(value) {
if (!isObject_default(value) || isMasked_default(value))
return !1;
var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource_default(value));
}
var baseIsNative_default = baseIsNative;
// node_modules/lodash-es/_getValue.js
function getValue(object, key) {
return object == null ? void 0 : object[key];
}
var getValue_default = getValue;
// node_modules/lodash-es/_getNative.js
function getNative(object, key) {
var value = getValue_default(object, key);
return baseIsNative_default(value) ? value : void 0;
}
var getNative_default = getNative;
// node_modules/lodash-es/_WeakMap.js
var WeakMap2 = getNative_default(root_default, "WeakMap"), WeakMap_default = WeakMap2;
// node_modules/lodash-es/_baseCreate.js
var objectCreate = Object.create, baseCreate = /* @__PURE__ */ function() {
function object() {
}
return function(proto) {
if (!isObject_default(proto))
return {};
if (objectCreate)
return objectCreate(proto);
object.prototype = proto;
var result = new object();
return object.prototype = void 0, result;
};
}(), baseCreate_default = baseCreate;
// node_modules/lodash-es/_copyArray.js
function copyArray(source, array) {
var index2 = -1, length = source.length;
for (array || (array = Array(length)); ++index2 < length; )
array[index2] = source[index2];
return array;
}
var copyArray_default = copyArray;
// node_modules/lodash-es/_defineProperty.js
var defineProperty = function() {
try {
var func = getNative_default(Object, "defineProperty");
return func({}, "", {}), func;
} catch {
}
}(), defineProperty_default = defineProperty;
// node_modules/lodash-es/_arrayEach.js
function arrayEach(array, iteratee) {
for (var index2 = -1, length = array == null ? 0 : array.length; ++index2 < length && iteratee(array[index2], index2, array) !== !1; )
;
return array;
}
var arrayEach_default = arrayEach;
// node_modules/lodash-es/_isIndex.js
var MAX_SAFE_INTEGER = 9007199254740991, reIsUint = /^(?:0|[1-9]\\d*)$/;
function isIndex(value, length) {
var type = typeof value;
return length = length == null ? MAX_SAFE_INTEGER : length, !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}
var isIndex_default = isIndex;
// node_modules/lodash-es/_baseAssignValue.js
function baseAssignValue(object, key, value) {
key == "__proto__" && defineProperty_default ? defineProperty_default(object, key, {
configurable: !0,
enumerable: !0,
value,
writable: !0
}) : object[key] = value;
}
var baseAssignValue_default = baseAssignValue;
// node_modules/lodash-es/eq.js
function eq(value, other) {
return value === other || value !== value && other !== other;
}
var eq_default = eq;
// node_modules/lodash-es/_assignValue.js
var objectProto4 = Object.prototype, hasOwnProperty4 = objectProto4.hasOwnProperty;
function assignValue(object, key, value) {
var objValue = object[key];
(!(hasOwnProperty4.call(object, key) && eq_default(objValue, value)) || value === void 0 && !(key in object)) && baseAssignValue_default(object, key, value);
}
var assignValue_default = assignValue;
// node_modules/lodash-es/_copyObject.js
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
for (var index2 = -1, length = props.length; ++index2 < length; ) {
var key = props[index2], newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
newValue === void 0 && (newValue = source[key]), isNew ? baseAssignValue_default(object, key, newValue) : assignValue_default(object, key, newValue);
}
return object;
}
var copyObject_default = copyObject;
// node_modules/lodash-es/isLength.js
var MAX_SAFE_INTEGER2 = 9007199254740991;
function isLength(value) {
return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
}
var isLength_default = isLength;
// node_modules/lodash-es/isArrayLike.js
function isArrayLike(value) {
return value != null && isLength_default(value.length) && !isFunction_default(value);
}
var isArrayLike_default = isArrayLike;
// node_modules/lodash-es/_isPrototype.js
var objectProto5 = Object.prototype;
function isPrototype(value) {
var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto5;
return value === proto;
}
var isPrototype_default = isPrototype;
// node_modules/lodash-es/_baseTimes.js
function baseTimes(n2, iteratee) {
for (var index2 = -1, result = Array(n2); ++index2 < n2; )
result[index2] = iteratee(index2);
return result;
}
var baseTimes_default = baseTimes;
// node_modules/lodash-es/_baseIsArguments.js
var argsTag = "[object Arguments]";
function baseIsArguments(value) {
return isObjectLike_default(value) && baseGetTag_default(value) == argsTag;
}
var baseIsArguments_default = baseIsArguments;
// node_modules/lodash-es/isArguments.js
var objectProto6 = Object.prototype, hasOwnProperty5 = objectProto6.hasOwnProperty, propertyIsEnumerable = objectProto6.propertyIsEnumerable, isArguments = baseIsArguments_default(/* @__PURE__ */ function() {
return arguments;
}()) ? baseIsArguments_default : function(value) {
return isObjectLike_default(value) && hasOwnProperty5.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
}, isArguments_default = isArguments;
// node_modules/lodash-es/stubFalse.js
function stubFalse() {
return !1;
}
var stubFalse_default = stubFalse;
// node_modules/lodash-es/isBuffer.js
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports, Buffer2 = moduleExports ? root_default.Buffer : void 0, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0, isBuffer = nativeIsBuffer || stubFalse_default, isBuffer_default = isBuffer;
// node_modules/lodash-es/_baseIsTypedArray.js
var argsTag2 = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag2 = "[object Function]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", weakMapTag = "[object WeakMap]", arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]", typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = !0;
typedArrayTags[argsTag2] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag2] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = !1;
function baseIsTypedArray(value) {
return isObjectLike_default(value) && isLength_default(value.length) && !!typedArrayTags[baseGetTag_default(value)];
}
var baseIsTypedArray_default = baseIsTypedArray;
// node_modules/lodash-es/_baseUnary.js
function baseUnary(func) {
return function(value) {
return func(value);
};
}
var baseUnary_default = baseUnary;
// node_modules/lodash-es/_nodeUtil.js
var freeExports2 = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule2 = freeExports2 && typeof module == "object" && module && !module.nodeType && module, moduleExports2 = freeModule2 && freeModule2.exports === freeExports2, freeProcess = moduleExports2 && freeGlobal_default.process, nodeUtil = function() {
try {
var types = freeModule2 && freeModule2.require && freeModule2.require("util").types;
return types || freeProcess && freeProcess.binding && freeProcess.binding("util");
} catch {
}
}(), nodeUtil_default = nodeUtil;
// node_modules/lodash-es/isTypedArray.js
var nodeIsTypedArray = nodeUtil_default && nodeUtil_default.isTypedArray, isTypedArray = nodeIsTypedArray ? baseUnary_default(nodeIsTypedArray) : baseIsTypedArray_default, isTypedArray_default = isTypedArray;
// node_modules/lodash-es/_arrayLikeKeys.js
var objectProto7 = Object.prototype, hasOwnProperty6 = objectProto7.hasOwnProperty;
function arrayLikeKeys(value, inherited) {
var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes_default(value.length, String) : [], length = result.length;
for (var key in value)
(inherited || hasOwnProperty6.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable \`arguments.length\` in strict mode.
(key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
isIndex_default(key, length))) && result.push(key);
return result;
}
var arrayLikeKeys_default = arrayLikeKeys;
// node_modules/lodash-es/_overArg.js
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
var overArg_default = overArg;
// node_modules/lodash-es/_nativeKeys.js
var nativeKeys = overArg_default(Object.keys, Object), nativeKeys_default = nativeKeys;
// node_modules/lodash-es/_baseKeys.js
var objectProto8 = Object.prototype, hasOwnProperty7 = objectProto8.hasOwnProperty;
function baseKeys(object) {
if (!isPrototype_default(object))
return nativeKeys_default(object);
var result = [];
for (var key in Object(object))
hasOwnProperty7.call(object, key) && key != "constructor" && result.push(key);
return result;
}
var baseKeys_default = baseKeys;
// node_modules/lodash-es/keys.js
function keys2(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object) : baseKeys_default(object);
}
var keys_default = keys2;
// node_modules/lodash-es/_nativeKeysIn.js
function nativeKeysIn(object) {
var result = [];
if (object != null)
for (var key in Object(object))
result.push(key);
return result;
}
var nativeKeysIn_default = nativeKeysIn;
// node_modules/lodash-es/_baseKeysIn.js
var objectProto9 = Object.prototype, hasOwnProperty8 = objectProto9.hasOwnProperty;
function baseKeysIn(object) {
if (!isObject_default(object))
return nativeKeysIn_default(object);
var isProto = isPrototype_default(object), result = [];
for (var key in object)
key == "constructor" && (isProto || !hasOwnProperty8.call(object, key)) || result.push(key);
return result;
}
var baseKeysIn_default = baseKeysIn;
// node_modules/lodash-es/keysIn.js
function keysIn(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object, !0) : baseKeysIn_default(object);
}
var keysIn_default = keysIn;
// node_modules/lodash-es/_nativeCreate.js
var nativeCreate = getNative_default(Object, "create"), nativeCreate_default = nativeCreate;
// node_modules/lodash-es/_hashClear.js
function hashClear() {
this.__data__ = nativeCreate_default ? nativeCreate_default(null) : {}, this.size = 0;
}
var hashClear_default = hashClear;
// node_modules/lodash-es/_hashDelete.js
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
return this.size -= result ? 1 : 0, result;
}
var hashDelete_default = hashDelete;
// node_modules/lodash-es/_hashGet.js
var HASH_UNDEFINED = "__lodash_hash_undefined__", objectProto10 = Object.prototype, hasOwnProperty9 = objectProto10.hasOwnProperty;
function hashGet(key) {
var data = this.__data__;
if (nativeCreate_default) {
var result = data[key];
return result === HASH_UNDEFINED ? void 0 : result;
}
return hasOwnProperty9.call(data, key) ? data[key] : void 0;
}
var hashGet_default = hashGet;
// node_modules/lodash-es/_hashHas.js
var objectProto11 = Object.prototype, hasOwnProperty10 = objectProto11.hasOwnProperty;
function hashHas(key) {
var data = this.__data__;
return nativeCreate_default ? data[key] !== void 0 : hasOwnProperty10.call(data, key);
}
var hashHas_default = hashHas;
// node_modules/lodash-es/_hashSet.js
var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
function hashSet(key, value) {
var data = this.__data__;
return this.size += this.has(key) ? 0 : 1, data[key] = nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value, this;
}
var hashSet_default = hashSet;
// node_modules/lodash-es/_Hash.js
function Hash(entries) {
var index2 = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index2 < length; ) {
var entry = entries[index2];
this.set(entry[0], entry[1]);
}
}
Hash.prototype.clear = hashClear_default;
Hash.prototype.delete = hashDelete_default;
Hash.prototype.get = hashGet_default;
Hash.prototype.has = hashHas_default;
Hash.prototype.set = hashSet_default;
var Hash_default = Hash;
// node_modules/lodash-es/_listCacheClear.js
function listCacheClear() {
this.__data__ = [], this.size = 0;
}
var listCacheClear_default = listCacheClear;
// node_modules/lodash-es/_assocIndexOf.js
function assocIndexOf(array, key) {
for (var length = array.length; length--; )
if (eq_default(array[length][0], key))
return length;
return -1;
}
var assocIndexOf_default = assocIndexOf;
// node_modules/lodash-es/_listCacheDelete.js
var arrayProto = Array.prototype, splice2 = arrayProto.splice;
function listCacheDelete(key) {
var data = this.__data__, index2 = assocIndexOf_default(data, key);
if (index2 < 0)
return !1;
var lastIndex = data.length - 1;
return index2 == lastIndex ? data.pop() : splice2.call(data, index2, 1), --this.size, !0;
}
var listCacheDelete_default = listCacheDelete;
// node_modules/lodash-es/_listCacheGet.js
function listCacheGet(key) {
var data = this.__data__, index2 = assocIndexOf_default(data, key);
return index2 < 0 ? void 0 : data[index2][1];
}
var listCacheGet_default = listCacheGet;
// node_modules/lodash-es/_listCacheHas.js
function listCacheHas(key) {
return assocIndexOf_default(this.__data__, key) > -1;
}
var listCacheHas_default = listCacheHas;
// node_modules/lodash-es/_listCacheSet.js
function listCacheSet(key, value) {
var data = this.__data__, index2 = assocIndexOf_default(data, key);
return index2 < 0 ? (++this.size, data.push([key, value])) : data[index2][1] = value, this;
}
var listCacheSet_default = listCacheSet;
// node_modules/lodash-es/_ListCache.js
function ListCache(entries) {
var index2 = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index2 < length; ) {
var entry = entries[index2];
this.set(entry[0], entry[1]);
}
}
ListCache.prototype.clear = listCacheClear_default;
ListCache.prototype.delete = listCacheDelete_default;
ListCache.prototype.get = listCacheGet_default;
ListCache.prototype.has = listCacheHas_default;
ListCache.prototype.set = listCacheSet_default;
var ListCache_default = ListCache;
// node_modules/lodash-es/_Map.js
var Map2 = getNative_default(root_default, "Map"), Map_default = Map2;
// node_modules/lodash-es/_mapCacheClear.js
function mapCacheClear() {
this.size = 0, this.__data__ = {
hash: new Hash_default(),
map: new (Map_default || ListCache_default)(),
string: new Hash_default()
};
}
var mapCacheClear_default = mapCacheClear;
// node_modules/lodash-es/_isKeyable.js
function isKeyable(value) {
var type = typeof value;
return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
var isKeyable_default = isKeyable;
// node_modules/lodash-es/_getMapData.js
function getMapData(map4, key) {
var data = map4.__data__;
return isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
var getMapData_default = getMapData;
// node_modules/lodash-es/_mapCacheDelete.js
function mapCacheDelete(key) {
var result = getMapData_default(this, key).delete(key);
return this.size -= result ? 1 : 0, result;
}
var mapCacheDelete_default = mapCacheDelete;
// node_modules/lodash-es/_mapCacheGet.js
function mapCacheGet(key) {
return getMapData_default(this, key).get(key);
}
var mapCacheGet_default = mapCacheGet;
// node_modules/lodash-es/_mapCacheHas.js
function mapCacheHas(key) {
return getMapData_default(this, key).has(key);
}
var mapCacheHas_default = mapCacheHas;
// node_modules/lodash-es/_mapCacheSet.js
function mapCacheSet(key, value) {
var data = getMapData_default(this, key), size = data.size;
return data.set(key, value), this.size += data.size == size ? 0 : 1, this;
}
var mapCacheSet_default = mapCacheSet;
// node_modules/lodash-es/_MapCache.js
function MapCache(entries) {
var index2 = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index2 < length; ) {
var entry = entries[index2];
this.set(entry[0], entry[1]);
}
}
MapCache.prototype.clear = mapCacheClear_default;
MapCache.prototype.delete = mapCacheDelete_default;
MapCache.prototype.get = mapCacheGet_default;
MapCache.prototype.has = mapCacheHas_default;
MapCache.prototype.set = mapCacheSet_default;
var MapCache_default = MapCache;
// node_modules/lodash-es/_arrayPush.js
function arrayPush(array, values) {
for (var index2 = -1, length = values.length, offset = array.length; ++index2 < length; )
array[offset + index2] = values[index2];
return array;
}
var arrayPush_default = arrayPush;
// node_modules/lodash-es/_getPrototype.js
var getPrototype = overArg_default(Object.getPrototypeOf, Object), getPrototype_default = getPrototype;
// node_modules/lodash-es/_stackClear.js
function stackClear() {
this.__data__ = new ListCache_default(), this.size = 0;
}
var stackClear_default = stackClear;
// node_modules/lodash-es/_stackDelete.js
function stackDelete(key) {
var data = this.__data__, result = data.delete(key);
return this.size = data.size, result;
}
var stackDelete_default = stackDelete;
// node_modules/lodash-es/_stackGet.js
function stackGet(key) {
return this.__data__.get(key);
}
var stackGet_default = stackGet;
// node_modules/lodash-es/_stackHas.js
function stackHas(key) {
return this.__data__.has(key);
}
var stackHas_default = stackHas;
// node_modules/lodash-es/_stackSet.js
var LARGE_ARRAY_SIZE = 200;
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache_default) {
var pairs = data.__data__;
if (!Map_default || pairs.length < LARGE_ARRAY_SIZE - 1)
return pairs.push([key, value]), this.size = ++data.size, this;
data = this.__data__ = new MapCache_default(pairs);
}
return data.set(key, value), this.size = data.size, this;
}
var stackSet_default = stackSet;
// node_modules/lodash-es/_Stack.js
function Stack(entries) {
var data = this.__data__ = new ListCache_default(entries);
this.size = data.size;
}
Stack.prototype.clear = stackClear_default;
Stack.prototype.delete = stackDelete_default;
Stack.prototype.get = stackGet_default;
Stack.prototype.has = stackHas_default;
Stack.prototype.set = stackSet_default;
var Stack_default = Stack;
// node_modules/lodash-es/_baseAssign.js
function baseAssign(object, source) {
return object && copyObject_default(source, keys_default(source), object);
}
var baseAssign_default = baseAssign;
// node_modules/lodash-es/_baseAssignIn.js
function baseAssignIn(object, source) {
return object && copyObject_default(source, keysIn_default(source), object);
}
var baseAssignIn_default = baseAssignIn;
// node_modules/lodash-es/_cloneBuffer.js
var freeExports3 = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule3 = freeExports3 && typeof module == "object" && module && !module.nodeType && module, moduleExports3 = freeModule3 && freeModule3.exports === freeExports3, Buffer3 = moduleExports3 ? root_default.Buffer : void 0, allocUnsafe = Buffer3 ? Buffer3.allocUnsafe : void 0;
function cloneBuffer(buffer, isDeep) {
if (isDeep)
return buffer.slice();
var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
return buffer.copy(result), result;
}
var cloneBuffer_default = cloneBuffer;
// node_modules/lodash-es/_arrayFilter.js
function arrayFilter(array, predicate) {
for (var index2 = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; ++index2 < length; ) {
var value = array[index2];
predicate(value, index2, array) && (result[resIndex++] = value);
}
return result;
}
var arrayFilter_default = arrayFilter;
// node_modules/lodash-es/stubArray.js
function stubArray() {
return [];
}
var stubArray_default = stubArray;
// node_modules/lodash-es/_getSymbols.js
var objectProto12 = Object.prototype, propertyIsEnumerable2 = objectProto12.propertyIsEnumerable, nativeGetSymbols = Object.getOwnPropertySymbols, getSymbols = nativeGetSymbols ? function(object) {
return object == null ? [] : (object = Object(object), arrayFilter_default(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable2.call(object, symbol);
}));
} : stubArray_default, getSymbols_default = getSymbols;
// node_modules/lodash-es/_copySymbols.js
function copySymbols(source, object) {
return copyObject_default(source, getSymbols_default(source), object);
}
var copySymbols_default = copySymbols;
// node_modules/lodash-es/_getSymbolsIn.js
var nativeGetSymbols2 = Object.getOwnPropertySymbols, getSymbolsIn = nativeGetSymbols2 ? function(object) {
for (var result = []; object; )
arrayPush_default(result, getSymbols_default(object)), object = getPrototype_default(object);
return result;
} : stubArray_default, getSymbolsIn_default = getSymbolsIn;
// node_modules/lodash-es/_copySymbolsIn.js
function copySymbolsIn(source, object) {
return copyObject_default(source, getSymbolsIn_default(source), object);
}
var copySymbolsIn_default = copySymbolsIn;
// node_modules/lodash-es/_baseGetAllKeys.js
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray_default(object) ? result : arrayPush_default(result, symbolsFunc(object));
}
var baseGetAllKeys_default = baseGetAllKeys;
// node_modules/lodash-es/_getAllKeys.js
function getAllKeys(object) {
return baseGetAllKeys_default(object, keys_default, getSymbols_default);
}
var getAllKeys_default = getAllKeys;
// node_modules/lodash-es/_getAllKeysIn.js
function getAllKeysIn(object) {
return baseGetAllKeys_default(object, keysIn_default, getSymbolsIn_default);
}
var getAllKeysIn_default = getAllKeysIn;
// node_modules/lodash-es/_DataView.js
var DataView = getNative_default(root_default, "DataView"), DataView_default = DataView;
// node_modules/lodash-es/_Promise.js
var Promise2 = getNative_default(root_default, "Promise"), Promise_default = Promise2;
// node_modules/lodash-es/_Set.js
var Set2 = getNative_default(root_default, "Set"), Set_default = Set2;
// node_modules/lodash-es/_getTag.js
var mapTag2 = "[object Map]", objectTag2 = "[object Object]", promiseTag = "[object Promise]", setTag2 = "[object Set]", weakMapTag2 = "[object WeakMap]", dataViewTag2 = "[object DataView]", dataViewCtorString = toSource_default(DataView_default), mapCtorString = toSource_default(Map_default), promiseCtorString = toSource_default(Promise_default), setCtorString = toSource_default(Set_default), weakMapCtorString = toSource_default(WeakMap_default), getTag = baseGetTag_default;
(DataView_default && getTag(new DataView_default(new ArrayBuffer(1))) != dataViewTag2 || Map_default && getTag(new Map_default()) != mapTag2 || Promise_default && getTag(Promise_default.resolve()) != promiseTag || Set_default && getTag(new Set_default()) != setTag2 || WeakMap_default && getTag(new WeakMap_default()) != weakMapTag2) && (getTag = function(value) {
var result = baseGetTag_default(value), Ctor = result == objectTag2 ? value.constructor : void 0, ctorString = Ctor ? toSource_default(Ctor) : "";
if (ctorString)
switch (ctorString) {
case dataViewCtorString:
return dataViewTag2;
case mapCtorString:
return mapTag2;
case promiseCtorString:
return promiseTag;
case setCtorString:
return setTag2;
case weakMapCtorString:
return weakMapTag2;
}
return result;
});
var getTag_default = getTag;
// node_modules/lodash-es/_initCloneArray.js
var objectProto13 = Object.prototype, hasOwnProperty11 = objectProto13.hasOwnProperty;
function initCloneArray(array) {
var length = array.length, result = new array.constructor(length);
return length && typeof array[0] == "string" && hasOwnProperty11.call(array, "index") && (result.index = array.index, result.input = array.input), result;
}
var initCloneArray_default = initCloneArray;
// node_modules/lodash-es/_Uint8Array.js
var Uint8Array2 = root_default.Uint8Array, Uint8Array_default = Uint8Array2;
// node_modules/lodash-es/_cloneArrayBuffer.js
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
return new Uint8Array_default(result).set(new Uint8Array_default(arrayBuffer)), result;
}
var cloneArrayBuffer_default = cloneArrayBuffer;
// node_modules/lodash-es/_cloneDataView.js
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var cloneDataView_default = cloneDataView;
// node_modules/lodash-es/_cloneRegExp.js
var reFlags = /\\w*$/;
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
return result.lastIndex = regexp.lastIndex, result;
}
var cloneRegExp_default = cloneRegExp;
// node_modules/lodash-es/_cloneSymbol.js
var symbolProto = Symbol_default ? Symbol_default.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
var cloneSymbol_default = cloneSymbol;
// node_modules/lodash-es/_cloneTypedArray.js
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
var cloneTypedArray_default = cloneTypedArray;
// node_modules/lodash-es/_initCloneByTag.js
var boolTag2 = "[object Boolean]", dateTag2 = "[object Date]", mapTag3 = "[object Map]", numberTag2 = "[object Number]", regexpTag2 = "[object RegExp]", setTag3 = "[object Set]", stringTag2 = "[object String]", symbolTag = "[object Symbol]", arrayBufferTag2 = "[object ArrayBuffer]", dataViewTag3 = "[object DataView]", float32Tag2 = "[object Float32Array]", float64Tag2 = "[object Float64Array]", int8Tag2 = "[object Int8Array]", int16Tag2 = "[object Int16Array]", int32Tag2 = "[object Int32Array]", uint8Tag2 = "[object Uint8Array]", uint8ClampedTag2 = "[object Uint8ClampedArray]", uint16Tag2 = "[object Uint16Array]", uint32Tag2 = "[object Uint32Array]";
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag2:
return cloneArrayBuffer_default(object);
case boolTag2:
case dateTag2:
return new Ctor(+object);
case dataViewTag3:
return cloneDataView_default(object, isDeep);
case float32Tag2:
case float64Tag2:
case int8Tag2:
case int16Tag2:
case int32Tag2:
case uint8Tag2:
case uint8ClampedTag2:
case uint16Tag2:
case uint32Tag2:
return cloneTypedArray_default(object, isDeep);
case mapTag3:
return new Ctor();
case numberTag2:
case stringTag2:
return new Ctor(object);
case regexpTag2:
return cloneRegExp_default(object);
case setTag3:
return new Ctor();
case symbolTag:
return cloneSymbol_default(object);
}
}
var initCloneByTag_default = initCloneByTag;
// node_modules/lodash-es/_initCloneObject.js
function initCloneObject(object) {
return typeof object.constructor == "function" && !isPrototype_default(object) ? baseCreate_default(getPrototype_default(object)) : {};
}
var initCloneObject_default = initCloneObject;
// node_modules/lodash-es/_baseIsMap.js
var mapTag4 = "[object Map]";
function baseIsMap(value) {
return isObjectLike_default(value) && getTag_default(value) == mapTag4;
}
var baseIsMap_default = baseIsMap;
// node_modules/lodash-es/isMap.js
var nodeIsMap = nodeUtil_default && nodeUtil_default.isMap, isMap = nodeIsMap ? baseUnary_default(nodeIsMap) : baseIsMap_default, isMap_default = isMap;
// node_modules/lodash-es/_baseIsSet.js
var setTag4 = "[object Set]";
function baseIsSet(value) {
return isObjectLike_default(value) && getTag_default(value) == setTag4;
}
var baseIsSet_default = baseIsSet;
// node_modules/lodash-es/isSet.js
var nodeIsSet = nodeUtil_default && nodeUtil_default.isSet, isSet = nodeIsSet ? baseUnary_default(nodeIsSet) : baseIsSet_default, isSet_default = isSet;
// node_modules/lodash-es/_baseClone.js
var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4, argsTag3 = "[object Arguments]", arrayTag2 = "[object Array]", boolTag3 = "[object Boolean]", dateTag3 = "[object Date]", errorTag2 = "[object Error]", funcTag3 = "[object Function]", genTag2 = "[object GeneratorFunction]", mapTag5 = "[object Map]", numberTag3 = "[object Number]", objectTag3 = "[object Object]", regexpTag3 = "[object RegExp]", setTag5 = "[object Set]", stringTag3 = "[object String]", symbolTag2 = "[object Symbol]", weakMapTag3 = "[object WeakMap]", arrayBufferTag3 = "[object ArrayBuffer]", dataViewTag4 = "[object DataView]", float32Tag3 = "[object Float32Array]", float64Tag3 = "[object Float64Array]", int8Tag3 = "[object Int8Array]", int16Tag3 = "[object Int16Array]", int32Tag3 = "[object Int32Array]", uint8Tag3 = "[object Uint8Array]", uint8ClampedTag3 = "[object Uint8ClampedArray]", uint16Tag3 = "[object Uint16Array]", uint32Tag3 = "[object Uint32Array]", cloneableTags = {};
cloneableTags[argsTag3] = cloneableTags[arrayTag2] = cloneableTags[arrayBufferTag3] = cloneableTags[dataViewTag4] = cloneableTags[boolTag3] = cloneableTags[dateTag3] = cloneableTags[float32Tag3] = cloneableTags[float64Tag3] = cloneableTags[int8Tag3] = cloneableTags[int16Tag3] = cloneableTags[int32Tag3] = cloneableTags[mapTag5] = cloneableTags[numberTag3] = cloneableTags[objectTag3] = cloneableTags[regexpTag3] = cloneableTags[setTag5] = cloneableTags[stringTag3] = cloneableTags[symbolTag2] = cloneableTags[uint8Tag3] = cloneableTags[uint8ClampedTag3] = cloneableTags[uint16Tag3] = cloneableTags[uint32Tag3] = !0;
cloneableTags[errorTag2] = cloneableTags[funcTag3] = cloneableTags[weakMapTag3] = !1;
function baseClone(value, bitmask, customizer, key, object, stack) {
var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer && (result = object ? customizer(value, key, object, stack) : customizer(value)), result !== void 0)
return result;
if (!isObject_default(value))
return value;
var isArr = isArray_default(value);
if (isArr) {
if (result = initCloneArray_default(value), !isDeep)
return copyArray_default(value, result);
} else {
var tag = getTag_default(value), isFunc = tag == funcTag3 || tag == genTag2;
if (isBuffer_default(value))
return cloneBuffer_default(value, isDeep);
if (tag == objectTag3 || tag == argsTag3 || isFunc && !object) {
if (result = isFlat || isFunc ? {} : initCloneObject_default(value), !isDeep)
return isFlat ? copySymbolsIn_default(value, baseAssignIn_default(result, value)) : copySymbols_default(value, baseAssign_default(result, value));
} else {
if (!cloneableTags[tag])
return object ? value : {};
result = initCloneByTag_default(value, tag, isDeep);
}
}
stack || (stack = new Stack_default());
var stacked = stack.get(value);
if (stacked)
return stacked;
stack.set(value, result), isSet_default(value) ? value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
}) : isMap_default(value) && value.forEach(function(subValue, key2) {
result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
});
var keysFunc = isFull ? isFlat ? getAllKeysIn_default : getAllKeys_default : isFlat ? keysIn_default : keys_default, props = isArr ? void 0 : keysFunc(value);
return arrayEach_default(props || value, function(subValue, key2) {
props && (key2 = subValue, subValue = value[key2]), assignValue_default(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
}), result;
}
var baseClone_default = baseClone;
// node_modules/lodash-es/cloneDeep.js
var CLONE_DEEP_FLAG2 = 1, CLONE_SYMBOLS_FLAG2 = 4;
function cloneDeep(value) {
return baseClone_default(value, CLONE_DEEP_FLAG2 | CLONE_SYMBOLS_FLAG2);
}
var cloneDeep_default = cloneDeep;
// src-charts/chart/getChartDataFrom2DArray.js
function getChartDataFrom2DArray(table2DArray, categoryDirection = "row") {
table2DArray = parse2DArrayElementsAsNumberIfPossible(cloneDeep_default(table2DArray));
let data = categoryDirection.toLowerCase() === "column" ? transposeArray(table2DArray) : table2DArray, dataCopy = cloneDeep_default(data), firstRowNumeric = isRowMostlyNumeric(data[0]), lastRowNumeric = isRowMostlyNumeric(data[data.length - 1]), categoryPosition;
firstRowNumeric ? categoryPosition = "last" : categoryPosition = "first";
let firstColNumeric = isColumnMostlyNumeric(data, 0), lastColNumeric = isColumnMostlyNumeric(data, data[0].length - 1), seriesPosition;
firstColNumeric ? seriesPosition = "last" : lastColNumeric ? seriesPosition = "first" : seriesPosition = null;
let labels;
seriesPosition === "first" ? labels = categoryPosition === "first" ? data[0].slice(1) : data[data.length - 1].slice(1) : seriesPosition === "last" ? labels = categoryPosition === "first" ? data[0].slice(0, -1) : data[data.length - 1].slice(0, -1) : labels = categoryPosition === "first" ? data[0] : data[data.length - 1], data = categoryPosition === "first" ? data.slice(1) : data.slice(0, -1);
let datasets = [], seriesIndex = seriesPosition === "first" ? 0 : seriesPosition === "last" && data[0] ? data[0].length - 1 : null;
for (let i = 0; i < data.length; i++) {
let row = data[i];
if (seriesIndex === null && data.length === 1)
datasets.push({ data: row });
else {
seriesIndex = seriesIndex === null ? 0 : seriesIndex;
let seriesLabel = row[seriesIndex], seriesData = seriesPosition === "first" ? row.slice(1) : row.slice(0, -1);
datasets.push({
label: seriesLabel,
data: seriesData
});
}
}
return dataCopy.length === 1 && !isNaN(parseFloat(dataCopy[0][0])) && isFinite(dataCopy[0][0]) ? (labels = [dataCopy[0][dataCopy[0].length - 1]], datasets.push({ data: dataCopy[0].slice(0, -1) })) : dataCopy.length === 1 && !isNaN(parseFloat(dataCopy[0][dataCopy[0].length - 1])) && isFinite(dataCopy[0].length - 1) && (labels = [dataCopy[0][0]], datasets.push({ data: dataCopy[0].slice(1) })), { labels, datasets };
}
function transposeArray(array) {
return array[0].map((_, colIndex) => array.map((row) => row[colIndex]));
}
function isRowMostlyNumeric(row) {
return row.slice(1).filter((item) => !isNaN(parseFloat(item)) && isFinite(item)).length > row.length / 2;
}
function isColumnMostlyNumeric(data, colIndex) {
return data.filter((row) => !isNaN(parseFloat(row[colIndex])) && isFinite(row[colIndex])).length > data.length / 2;
}
function parse2DArrayElementsAsNumberIfPossible(data) {
return data.map((row) => row.map((cell) => !isNaN(parseFloat(cell)) && isFinite(cell) ? parseFloat(cell) : cell));
}
// node_modules/fparser/dist/fparser.js
var $ = Object.defineProperty, O = (l, i, e) => i in l ? $(l, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : l[i] = e, n = (l, i, e) => (O(l, typeof i != "symbol" ? i + "" : i, e), e), g = {
PI: Math.PI,
E: Math.E,
LN2: Math.LN2,
LN10: Math.LN10,
LOG2E: Math.LOG2E,
LOG10E: Math.LOG10E,
SQRT1_2: Math.SQRT1_2,
SQRT2: Math.SQRT2
}, p = class {
static throwIfNotNumber(i) {
if (typeof i == "string")
throw new Error("Strings are not allowed in math operations");
}
}, V = class {
static throwIfNotNumber(i) {
if (typeof i == "string")
throw new Error("Strings are not allowed in math operations");
}
}, h = class {
static createOperatorExpression(i, e, t) {
if (i === "^")
return new b(e, t);
if (["*", "/"].includes(i))
return new x(i, e, t);
if (["+", "-"].includes(i))
return new E(i, e, t);
if (["<", ">", "<=", ">=", "=", "!="].includes(i))
return new d(i, e, t);
throw new Error(\`Unknown operator: \${i}\`);
}
evaluate(i = {}) {
throw new Error("Empty Expression - Must be defined in child classes");
}
toString() {
return "";
}
}, S = class extends h {
constructor(e) {
if (super(), n(this, "innerExpression"), this.innerExpression = e, !(this.innerExpression instanceof h))
throw new Error("No inner expression given for bracket expression");
}
evaluate(e = {}) {
return this.innerExpression.evaluate(e);
}
toString() {
return \`(\${this.innerExpression.toString()})\`;
}
}, w = class extends h {
constructor(e, t = "number") {
switch (super(), n(this, "value"), n(this, "type"), this.value = Number(e), t) {
case "number":
if (this.value = Number(e), isNaN(this.value))
throw new Error("Cannot parse number: " + e);
break;
case "string":
this.value = String(e);
break;
default:
throw new Error("Invalid value type: " + t);
}
this.type = t;
}
evaluate() {
return this.value;
}
toString() {
switch (this.type) {
case "number":
return String(this.value);
case "string":
return '"' + this.value + '"';
default:
throw new Error("Invalid type");
}
}
}, E = class extends h {
constructor(e, t, r) {
if (super(), n(this, "operator"), n(this, "left"), n(this, "right"), !["+", "-"].includes(e))
throw new Error(\`Operator not allowed in Plus/Minus expression: \${e}\`);
this.operator = e, this.left = t, this.right = r;
}
evaluate(e = {}) {
let t = this.left.evaluate(e), r = this.right.evaluate(e);
if (p.throwIfNotNumber(t), p.throwIfNotNumber(r), this.operator === "+")
return Number(t) + Number(r);
if (this.operator === "-")
return Number(t) - Number(r);
throw new Error("Unknown operator for PlusMinus expression");
}
toString() {
return \`\${this.left.toString()} \${this.operator} \${this.right.toString()}\`;
}
}, x = class extends h {
constructor(e, t, r) {
if (super(), n(this, "operator"), n(this, "left"), n(this, "right"), !["*", "/"].includes(e))
throw new Error(\`Operator not allowed in Multiply/Division expression: \${e}\`);
this.operator = e, this.left = t, this.right = r;
}
evaluate(e = {}) {
let t = this.left.evaluate(e), r = this.right.evaluate(e);
if (p.throwIfNotNumber(t), p.throwIfNotNumber(r), this.operator === "*")
return Number(t) * Number(r);
if (this.operator === "/")
return Number(t) / Number(r);
throw new Error("Unknown operator for MultDiv expression");
}
toString() {
return \`\${this.left.toString()} \${this.operator} \${this.right.toString()}\`;
}
}, b = class extends h {
constructor(e, t) {
super(), n(this, "base"), n(this, "exponent"), this.base = e, this.exponent = t;
}
evaluate(e = {}) {
let t = this.base.evaluate(e), r = this.exponent.evaluate(e);
return p.throwIfNotNumber(t), p.throwIfNotNumber(r), Math.pow(Number(t), Number(r));
}
toString() {
return \`\${this.base.toString()}^\${this.exponent.toString()}\`;
}
}, d = class extends h {
constructor(e, t, r) {
if (super(), n(this, "operator"), n(this, "left"), n(this, "right"), !["<", ">", "<=", ">=", "=", "!="].includes(e))
throw new Error(\`Operator not allowed in Logical expression: \${e}\`);
this.operator = e, this.left = t, this.right = r;
}
evaluate(e = {}) {
let t = this.left.evaluate(e), r = this.right.evaluate(e);
switch (this.operator) {
case "<":
return t < r ? 1 : 0;
case ">":
return t > r ? 1 : 0;
case "<=":
return t <= r ? 1 : 0;
case ">=":
return t >= r ? 1 : 0;
case "=":
return t === r ? 1 : 0;
case "!=":
return t !== r ? 1 : 0;
}
throw new Error("Unknown operator for Logical expression");
}
toString() {
return \`\${this.left.toString()} \${this.operator} \${this.right.toString()}\`;
}
}, k = class extends h {
constructor(e, t, r = null) {
super(), n(this, "fn"), n(this, "varPath"), n(this, "argumentExpressions"), n(this, "formulaObject"), n(this, "blacklisted"), this.fn = e != null ? e : "", this.varPath = this.fn.split("."), this.argumentExpressions = t || [], this.formulaObject = r, this.blacklisted = void 0;
}
evaluate(e = {}) {
var a;
e = e || {};
let t = this.argumentExpressions.map((s) => s.evaluate(e));
try {
let s = m(e, this.varPath, this.fn);
if (s instanceof Function)
return s.apply(this, t);
} catch {
}
let r;
try {
r = m((a = this.formulaObject) != null ? a : {}, this.varPath, this.fn);
} catch {
}
if (this.formulaObject && r instanceof Function) {
if (this.isBlacklisted())
throw new Error("Blacklisted function called: " + this.fn);
return r.apply(this.formulaObject, t);
}
try {
let s = m(Math, this.varPath, this.fn);
if (s instanceof Function)
return t.forEach((o) => {
V.throwIfNotNumber(o);
}), s.apply(this, t);
} catch {
}
throw new Error("Function not found: " + this.fn);
}
toString() {
return \`\${this.fn}(\${this.argumentExpressions.map((e) => e.toString()).join(", ")})\`;
}
isBlacklisted() {
return this.blacklisted === void 0 && (this.blacklisted = N.functionBlacklist.includes(
this.formulaObject ? this.formulaObject[this.fn] : null
)), this.blacklisted;
}
};
function m(l, i, e) {
let t = l;
for (let r of i) {
if (typeof t != "object")
throw new Error(\`Cannot evaluate \${r}, property not found (from path \${e})\`);
if (t[r] === void 0)
throw new Error(\`Cannot evaluate \${r}, property not found (from path \${e})\`);
t = t[r];
}
if (typeof t == "object")
throw new Error("Invalid value");
return t;
}
var y = class extends h {
constructor(e, t = null) {
super(), n(this, "fullPath"), n(this, "varPath"), n(this, "formulaObject"), this.formulaObject = t, this.fullPath = e, this.varPath = e.split(".");
}
evaluate(e = {}) {
var r;
let t;
try {
t = m(e, this.varPath, this.fullPath);
} catch {
}
if (t === void 0 && (t = m((r = this.formulaObject) != null ? r : {}, this.varPath, this.fullPath)), typeof t == "function" || typeof t == "object")
throw new Error(\`Cannot use \${this.fullPath} as value: It contains a non-numerical value.\`);
return t;
}
toString() {
return \`\${this.varPath.join(".")}\`;
}
}, u = class u2 {
/**
* Creates a new Formula instance
*
* Optional configuration can be set in the options object:
*
* - memoization (bool): If true, results are stored and re-used when evaluate() is called with the same parameters
*
* @param {String} fStr The formula string, e.g. 'sin(x)/cos(y)'
* @param {Object} options An options object. Supported options:
* - memoization (bool): If true, results are stored and re-used when evaluate() is called with the same parameters
* @param {Formula} parentFormula Internally used to build a Formula AST
*/
constructor(i, e = {}) {
n(this, "formulaExpression"), n(this, "options"), n(this, "formulaStr"), n(this, "_variables"), n(this, "_memory"), this.formulaExpression = null, this.options = { memoization: !1, ...e }, this.formulaStr = "", this._variables = [], this._memory = {}, this.setFormula(i);
}
/**
* Re-sets the given String and parses it to a formula expression. Can be used after initialization,
* to re-use the Formula object.
*
* @param {String} formulaString The formula string to set/parse
* @return {this} The Formula object (this)
*/
setFormula(i) {
return i && (this.formulaExpression = null, this._variables = [], this._memory = {}, this.formulaStr = i, this.formulaExpression = this.parse(i)), this;
}
/**
* Enable memoization: An expression is only evaluated once for the same input.
* Further evaluations with the same input will return the in-memory stored result.
*/
enableMemoization() {
this.options.memoization = !0;
}
/**
* Disable in-memory memoization: each call to evaluate() is executed from scratch.
*/
disableMemoization() {
this.options.memoization = !1, this._memory = {};
}
/**
* Splits the given string by ',', makes sure the ',' is not within
* a sub-expression
* e.g.: str = "x,pow(3,4)" returns 2 elements: x and pow(3,4).
*/
splitFunctionParams(i) {
let e = 0, t = "", r = [];
for (let a of i.split(""))
if (a === "," && e === 0)
r.push(t), t = "";
else if (a === "(")
e++, t += a;
else if (a === ")") {
if (e--, t += a, e < 0)
throw new Error("ERROR: Too many closing parentheses!");
} else
t += a;
if (e !== 0)
throw new Error("ERROR: Too many opening parentheses!");
return t.length > 0 && r.push(t), r;
}
/**
* Cleans the input string from unnecessary whitespace,
* and replaces some known constants:
*/
cleanupInputFormula(i) {
let e = [];
return i.split('"').forEach((r, a) => {
a % 2 === 0 && (r = r.replace(/[\\s]+/g, ""), Object.keys(g).forEach((s) => {
r = r.replace(new RegExp(\`\\\\b\${s}\\\\b\`, "g"), \`[\${s}]\`);
})), e.push(r);
}), e.join('"');
}
/**
* Parses the given formula string by using a state machine into a single Expression object,
* which represents an expression tree (aka AST).
*
* First, we split the string into 'expression': An expression can be:
* - a number, e.g. '3.45'
* - an unknown variable, e.g. 'x'
* - a single char operator, such as '*','+' etc...
* - a named variable, in [], e.g. [myvar]
* - a function, such as sin(x)
* - a parenthessed expression, containing other expressions
*
* We want to create an expression tree out of the string. This is done in 2 stages:
* 1. form single expressions from the string: parse the string into known expression objects:
* - numbers/[variables]/"strings"
* - operators
* - braces (with a sub-expression)
* - functions (with sub-expressions (aka argument expressions))
* This will lead to an array of expressions.
* As an example:
* "2 + 3 * (4 + 3 ^ 5) * sin(PI * x)" forms an array of the following expressions:
* \`[2, +, 3, *, bracketExpr(4,+,3,^,5), * , functionExpr(PI,*,x)]\`
* 2. From the raw expression array we form an expression tree by evaluating the expressions in the correct order:
* e.g.:
* the expression array \`[2, +, 3, *, bracketExpr(4,+,3,^,5), * , functionExpr(PI,*,x)]\` will be transformed into the expression tree:
* \`\`\`
* root expr: (+)
* / \\
* 2 (*)
* / \\
* (*) functionExpr(...)
* / \\
* 3 (bracket(..))
* \`\`\`
*
* In the end, we have a single root expression node, which then can be evaluated in the evaluate() function.
*
* @param {String} str The formula string, e.g. '3*sin(PI/x)'
* @returns {Expression} An expression object, representing the expression tree
*/
parse(i) {
return i = this.cleanupInputFormula(i), this._do_parse(i);
}
/**
* @see parse(): this is the recursive parse function, without the clean string part.
* @param {String} str
* @returns {Expression} An expression object, representing the expression tree
*/
_do_parse(i) {
let e = i.length - 1, t = 0, r = "initial", a = [], s = "", o = "", v = null, f = 0, c = "";
for (; t <= e; ) {
switch (r) {
case "initial":
if (s = i.charAt(t), s.match(/[0-9.]/))
r = "within-nr", o = "", t--;
else if (this.isOperator(s)) {
if (s === "-" && (a.length === 0 || this.isOperatorExpr(a[a.length - 1]))) {
r = "within-nr", o = "-";
break;
}
if (t === e || this.isOperatorExpr(a[a.length - 1])) {
r = "invalid";
break;
} else
a.push(
h.createOperatorExpression(s, new h(), new h())
), r = "initial";
} else if ([">", "<", "=", "!"].includes(s))
if (t === e) {
r = "invalid";
break;
} else
r = "within-logical-operator", o = s;
else
s === "(" ? (r = "within-parentheses", o = "", f = 0) : s === "[" ? (r = "within-named-var", o = "") : s.match(/["']/) ? (r = "within-string", c = s, o = "") : s.match(/[a-zA-Z]/) && (t < e && i.charAt(t + 1).match(/[a-zA-Z0-9_.]/) ? (o = s, r = "within-func") : (a.length > 0 && a[a.length - 1] instanceof w && a.push(
h.createOperatorExpression("*", new h(), new h())
), a.push(new y(s, this)), this.registerVariable(s), r = "initial", o = ""));
break;
case "within-nr":
s = i.charAt(t), s.match(/[0-9.]/) ? (o += s, t === e && (a.push(new w(o)), r = "initial")) : (o === "-" && (o = "-1"), a.push(new w(o)), o = "", r = "initial", t--);
break;
case "within-func":
if (s = i.charAt(t), s.match(/[a-zA-Z0-9_.]/))
o += s;
else if (s === "(")
v = o, o = "", f = 0, r = "within-func-parentheses";
else
throw new Error("Wrong character for function at position " + t);
break;
case "within-named-var":
if (s = i.charAt(t), s === "]")
a.push(new y(o, this)), this.registerVariable(o), o = "", r = "initial";
else if (s.match(/[a-zA-Z0-9_.]/))
o += s;
else
throw new Error("Character not allowed within named variable: " + s);
break;
case "within-string":
s = i.charAt(t), s === c ? (a.push(new w(o, "string")), o = "", r = "initial", c = "") : o += s;
break;
case "within-parentheses":
case "within-func-parentheses":
if (s = i.charAt(t), c)
s === c && (c = ""), o += s;
else if (s === ")")
if (f <= 0) {
if (r === "within-parentheses")
a.push(new S(this._do_parse(o)));
else if (r === "within-func-parentheses") {
let M = this.splitFunctionParams(o).map((P) => this._do_parse(P));
a.push(new k(v, M, this)), v = null;
}
r = "initial";
} else
f--, o += s;
else
s === "(" ? (f++, o += s) : (s.match(/["']/) && (c = s), o += s);
break;
case "within-logical-operator":
s = i.charAt(t), s === "=" && (o += s, t++), a.push(h.createOperatorExpression(o, new h(), new h())), o = "", r = "initial", t--;
break;
}
t++;
}
if (r !== "initial")
throw new Error("Could not parse formula: Syntax error.");
return this.buildExpressionTree(a);
}
/**
* @see parse(): Builds an expression tree from the given expression array.
* Builds a tree with a single root expression in the correct order of operator precedence.
*
* Note that the given expression objects are modified and linked.
*
* @param {*} expressions
* @return {Expression} The root Expression of the built expression tree
*/
buildExpressionTree(i) {
if (i.length < 1)
throw new Error("No expression given!");
let e = [...i], t = 0, r = null;
for (; t < e.length; )
if (r = e[t], r instanceof b) {
if (t === 0 || t === e.length - 1)
throw new Error("Wrong operator position!");
r.base = e[t - 1], r.exponent = e[t + 1], e[t - 1] = r, e.splice(t, 2);
} else
t++;
for (t = 0, r = null; t < e.length; )
if (r = e[t], r instanceof x) {
if (t === 0 || t === e.length - 1)
throw new Error("Wrong operator position!");
r.left = e[t - 1], r.right = e[t + 1], e[t - 1] = r, e.splice(t, 2);
} else
t++;
for (t = 0, r = null; t < e.length; )
if (r = e[t], r instanceof E) {
if (t === 0 || t === e.length - 1)
throw new Error("Wrong operator position!");
r.left = e[t - 1], r.right = e[t + 1], e[t - 1] = r, e.splice(t, 2);
} else
t++;
for (t = 0, r = null; t < e.length; )
if (r = e[t], r instanceof d) {
if (t === 0 || t === e.length - 1)
throw new Error("Wrong operator position!");
r.left = e[t - 1], r.right = e[t + 1], e[t - 1] = r, e.splice(t, 2);
} else
t++;
if (e.length !== 1)
throw new Error("Could not parse formula: incorrect syntax?");
return e[0];
}
isOperator(i) {
return typeof i == "string" && i.match(/[+\\-*/^]/);
}
isOperatorExpr(i) {
return i instanceof E || i instanceof x || i instanceof b || i instanceof d;
}
registerVariable(i) {
this._variables.indexOf(i) < 0 && this._variables.push(i);
}
getVariables() {
return this._variables;
}
/**
* Evaluates a Formula by delivering values for the Formula's variables.
* E.g. if the formula is '3*x^2 + 2*x + 4', you should call \`evaulate\` as follows:
*
* evaluate({x:2}) --> Result: 20
*
* @param {ValueObject|Array<ValueObject>} valueObj An object containing values for variables and (unknown) functions,
* or an array of such objects: If an array is given, all objects are evaluated and the results
* also returned as array.
* @return {Number|String|(Number|String)[]} The evaluated result, or an array with results
*/
evaluate(i) {
if (i instanceof Array)
return i.map((t) => this.evaluate(t));
let e = this.getExpression();
if (!(e instanceof h))
throw new Error("No expression set: Did you init the object with a Formula?");
if (this.options.memoization) {
let t = this.resultFromMemory(i);
return t !== null || (t = e.evaluate({ ...g, ...i }), this.storeInMemory(i, t)), t;
}
return e.evaluate({ ...g, ...i });
}
hashValues(i) {
return JSON.stringify(i);
}
resultFromMemory(i) {
let e = this.hashValues(i), t = this._memory[e];
return t !== void 0 ? t : null;
}
storeInMemory(i, e) {
this._memory[this.hashValues(i)] = e;
}
getExpression() {
return this.formulaExpression;
}
getExpressionString() {
return this.formulaExpression ? this.formulaExpression.toString() : "";
}
static calc(i, e = null, t = {}) {
return e = e != null ? e : {}, new u2(i, t).evaluate(e);
}
};
n(u, "Expression", h), n(u, "BracketExpression", S), n(u, "PowerExpression", b), n(u, "MultDivExpression", x), n(u, "PlusMinusExpression", E), n(u, "LogicalExpression", d), n(u, "ValueExpression", w), n(u, "VariableExpression", y), n(u, "FunctionExpression", k), n(u, "MATH_CONSTANTS", g), // Create a function blacklist:
n(u, "functionBlacklist", Object.getOwnPropertyNames(u.prototype).filter((i) => u.prototype[i] instanceof Function).map((i) => u.prototype[i]));
var N = u;
// package.json
var package_default = {
name: "amplenote-plugin-dev-env",
author: "debajandhar12",
version: "1.0.0",
type: "module",
repository: "https://github.com/debanjandhar12/my-amplenote-plugins-v2",
dependencies: {
"@debanjandhar12/markmap-lib": "0.17.0-mod.3",
"@debanjandhar12/markmap-toolbar": "0.17.0-mod.3",
"@debanjandhar12/markmap-view": "0.17.0-mod.3",
"date-fns": "^3.6.0",
"lodash-es": "^4.17.21",
luxon: "^3.4.4",
"markdown-escape": "^2.0.0",
"@omnivore-app/api": "^1.0.4",
"markdown-it": "^14.1.0",
"remark-gfm": "4.0.0",
"remark-parse": "11.0.0",
unified: "11.0.0",
"unist-util-visit": "^5.0.0",
"unist-util-visit-parents": "6.0.1",
"d3-svg-to-png": "^0.3.1",
"chart.js": "^4.4.3",
fparser: "^3.1.0",
nanoid: "^5.0.7",
zod: "^3.23.8"
},
devDependencies: {
"@types/jest": "^29.5.0",
cors: "^2.8.5",
"cross-fetch": "^4.0.0",
dotenv: "^16.0.3",
esbuild: "0.23.1",
"esbuild-jest2": "0.6.7",
"esbuild-plugins-node-modules-polyfill": "1.6.6",
express: "^4.19.2",
"isomorphic-fetch": "^3.0.0",
jest: "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
jsdom: "^24.1.0",
"make-synchronous": "^1.0.0",
playwright: "^1.47.2",
"core-js": "^3.38.1"
},
scripts: {
test: "jest --testPathPattern=src-charts",
"test:watch": "jest --testPathPattern=src-charts --watch",
"build:prod": "NODE_ENV=production node esbuild.js $(pwd)/src-charts",
"build:dev": "node esbuild.js $(pwd)/src-charts --watch --server"
}
};
// common-utils/dynamic-import-esm.js
var dynamicImportESM = async (pkg, pkgVersion = null) => {
if (0) {
try {
} catch (e) {
}
try {
} catch (e) {
}
}
let cdnList = ["https://esm.sh/", "https://esm.run/"], resolvedVersion = resolvePackageVersion(pkg, pkgVersion), importCompleted = !1, importPromises = cdnList.map(async (cdn) => {
let url = buildCDNUrl(cdn, pkg, resolvedVersion);
if (cdn !== "https://esm.sh/" && await new Promise((resolve) => setTimeout(resolve, 600)), importCompleted)
throw new Error(\`Terminating as \${pkg} has already been imported\`);
return import(url).then((module2) => ({ module: module2, url })).catch((e) => {
throw console.warn(\`Failed to import \${pkg} from \${cdn}: \${e.message}\`), e;
});
});
try {
let result = await Promise.any(importPromises);
return importCompleted = !0, console.log(\`Imported \${pkg}@\${resolvedVersion} from \${result.url}\`), result.module;
} catch {
throw new Error(\`Failed to import \${pkg} from all available CDNs\`);
}
throw new Error(\`Failed to import \${pkg} from all available CDNs\`);
};
function getBasePackage(pkg) {
if (pkg.startsWith("@")) {
let [scope, name] = pkg.split("/");
return \`\${scope}/\${name}\`;
}
return pkg.split("/")[0];
}
function resolvePackageVersion(pkg, pkgVersion) {
let basePkg = getBasePackage(pkg), version = pkgVersion || package_default.dependencies[basePkg] || package_default.devDependencies[basePkg] || "latest";
return version.startsWith("^") || version.startsWith("~") ? version.substring(1) : version;
}
function buildCDNUrl(cdn, pkg, version) {
let folders = [];
pkg.startsWith("@") ? [, , ...folders] = pkg.split("/") : [, ...folders] = pkg.split("/");
let basePkg = getBasePackage(pkg), versionString = version !== "latest" ? \`@\${version}\` : "", folderString = folders && folders.length > 0 ? \`/\${folders.join("/")}\` : "", url = \`\${cdn}\${basePkg}\${versionString}\${folderString}\`;
return ["https://esm.sh/"].includes(cdn) ? url + "?bundle-deps" : url;
}
var dynamic_import_esm_default = dynamicImportESM;
// node_modules/zod/lib/index.mjs
var util;
(function(util2) {
util2.assertEqual = (val) => val;
function assertIs(_arg) {
}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util2.assertNever = assertNever, util2.arrayToEnum = (items) => {
let obj = {};
for (let item of items)
obj[item] = item;
return obj;
}, util2.getValidEnumValues = (obj) => {
let validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] != "number"), filtered = {};
for (let k2 of validKeys)
filtered[k2] = obj[k2];
return util2.objectValues(filtered);
}, util2.objectValues = (obj) => util2.objectKeys(obj).map(function(e) {
return obj[e];
}), util2.objectKeys = typeof Object.keys == "function" ? (obj) => Object.keys(obj) : (object) => {
let keys3 = [];
for (let key in object)
Object.prototype.hasOwnProperty.call(object, key) && keys3.push(key);
return keys3;
}, util2.find = (arr, checker) => {
for (let item of arr)
if (checker(item))
return item;
}, util2.isInteger = typeof Number.isInteger == "function" ? (val) => Number.isInteger(val) : (val) => typeof val == "number" && isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val == "string" ? \`'\${val}'\` : val).join(separator);
}
util2.joinValues = joinValues, util2.jsonStringifyReplacer = (_, value) => typeof value == "bigint" ? value.toString() : value;
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => ({
...first,
...second
// second overwrites first
});
})(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"
]), getParsedType = (data) => {
switch (typeof data) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
return Array.isArray(data) ? ZodParsedType.array : data === null ? ZodParsedType.null : data.then && typeof data.then == "function" && data.catch && typeof data.catch == "function" ? ZodParsedType.promise : typeof Map != "undefined" && data instanceof Map ? ZodParsedType.map : typeof Set != "undefined" && data instanceof Set ? ZodParsedType.set : typeof Date != "undefined" && data instanceof Date ? ZodParsedType.date : ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
}, ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]), quotelessJson = (obj) => JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:"), ZodError = class _ZodError extends Error {
constructor(issues) {
super(), this.issues = [], this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
}, this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
let actualProto = new.target.prototype;
Object.setPrototypeOf ? Object.setPrototypeOf(this, actualProto) : this.__proto__ = actualProto, this.name = "ZodError", this.issues = issues;
}
get errors() {
return this.issues;
}
format(_mapper) {
let mapper = _mapper || function(issue) {
return issue.message;
}, fieldErrors = { _errors: [] }, processError = (error) => {
for (let 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, i = 0;
for (; i < issue.path.length; ) {
let el = issue.path[i];
i === issue.path.length - 1 ? (curr[el] = curr[el] || { _errors: [] }, curr[el]._errors.push(mapper(issue))) : curr[el] = curr[el] || { _errors: [] }, curr = curr[el], i++;
}
}
};
return processError(this), 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) {
let fieldErrors = {}, formErrors = [];
for (let sub of this.issues)
sub.path.length > 0 ? (fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [], fieldErrors[sub.path[0]].push(mapper(sub))) : formErrors.push(mapper(sub));
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => new ZodError(issues);
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
issue.received === ZodParsedType.undefined ? message = "Required" : 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:
typeof issue.validation == "object" ? "includes" in issue.validation ? (message = \`Invalid input: must include "\${issue.validation.includes}"\`, typeof issue.validation.position == "number" && (message = \`\${message} at one or more positions greater than or equal to \${issue.validation.position}\`)) : "startsWith" in issue.validation ? message = \`Invalid input: must start with "\${issue.validation.startsWith}"\` : "endsWith" in issue.validation ? message = \`Invalid input: must end with "\${issue.validation.endsWith}"\` : util.assertNever(issue.validation) : issue.validation !== "regex" ? message = \`Invalid \${issue.validation}\` : message = "Invalid";
break;
case ZodIssueCode.too_small:
issue.type === "array" ? message = \`Array must contain \${issue.exact ? "exactly" : issue.inclusive ? "at least" : "more than"} \${issue.minimum} element(s)\` : issue.type === "string" ? message = \`String must contain \${issue.exact ? "exactly" : issue.inclusive ? "at least" : "over"} \${issue.minimum} character(s)\` : issue.type === "number" ? message = \`Number must be \${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}\${issue.minimum}\` : 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))}\` : message = "Invalid input";
break;
case ZodIssueCode.too_big:
issue.type === "array" ? message = \`Array must contain \${issue.exact ? "exactly" : issue.inclusive ? "at most" : "less than"} \${issue.maximum} element(s)\` : issue.type === "string" ? message = \`String must contain \${issue.exact ? "exactly" : issue.inclusive ? "at most" : "under"} \${issue.maximum} character(s)\` : issue.type === "number" ? message = \`Number must be \${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} \${issue.maximum}\` : issue.type === "bigint" ? message = \`BigInt must be \${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} \${issue.maximum}\` : issue.type === "date" ? message = \`Date must be \${issue.exact ? "exactly" : issue.inclusive ? "smaller than or equal to" : "smaller than"} \${new Date(Number(issue.maximum))}\` : message = "Invalid input";
break;
case ZodIssueCode.custom:
message = "Invalid input";
break;
case ZodIssueCode.invalid_intersection_types:
message = "Intersection results could not be merged";
break;
case ZodIssueCode.not_multiple_of:
message = \`Number must be a multiple of \${issue.multipleOf}\`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError, util.assertNever(issue);
}
return { message };
}, overrideErrorMap = errorMap;
function setErrorMap(map4) {
overrideErrorMap = map4;
}
function getErrorMap() {
return overrideErrorMap;
}
var makeIssue = (params) => {
let { data, path: path2, errorMaps, issueData } = params, fullPath = [...path2, ...issueData.path || []], fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== void 0)
return {
...issueData,
path: fullPath,
message: issueData.message
};
let errorMessage = "", maps = errorMaps.filter((m2) => !!m2).slice().reverse();
for (let map4 of maps)
errorMessage = map4(fullIssue, { data, defaultError: errorMessage }).message;
return {
...issueData,
path: fullPath,
message: errorMessage
};
}, EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
let overrideMap = getErrorMap(), issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === errorMap ? void 0 : errorMap
// then global default map
].filter((x2) => !!x2)
});
ctx.common.issues.push(issue);
}
var ParseStatus = class _ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
this.value === "valid" && (this.value = "dirty");
}
abort() {
this.value !== "aborted" && (this.value = "aborted");
}
static mergeArray(status, results) {
let arrayValue = [];
for (let s of results) {
if (s.status === "aborted")
return INVALID;
s.status === "dirty" && status.dirty(), arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
let syncPairs = [];
for (let pair of pairs) {
let key = await pair.key, value = await pair.value;
syncPairs.push({
key,
value
});
}
return _ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
let finalObject = {};
for (let pair of pairs) {
let { key, value } = pair;
if (key.status === "aborted" || value.status === "aborted")
return INVALID;
key.status === "dirty" && status.dirty(), value.status === "dirty" && status.dirty(), key.value !== "__proto__" && (typeof value.value != "undefined" || pair.alwaysSet) && (finalObject[key.value] = value.value);
}
return { status: status.value, value: finalObject };
}
}, INVALID = Object.freeze({
status: "aborted"
}), DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x2) => x2.status === "aborted", isDirty = (x2) => x2.status === "dirty", isValid = (x2) => x2.status === "valid", isAsync = (x2) => typeof Promise != "undefined" && x2 instanceof Promise;
function __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);
}
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;
}
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message == "string" ? { message } : message || {}, errorUtil2.toString = (message) => typeof message == "string" ? message : message == null ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache, _ZodNativeEnum_cache, ParseInputLazyPath = class {
constructor(parent, value, path2, key) {
this._cachedPath = [], this.parent = parent, this.data = value, this._path = path2, this._key = key;
}
get path() {
return this._cachedPath.length || (this._key instanceof Array ? this._cachedPath.push(...this._path, ...this._key) : this._cachedPath.push(...this._path, this._key)), this._cachedPath;
}
}, handleResult = (ctx, result) => {
if (isValid(result))
return { success: !0, data: result.value };
if (!ctx.common.issues.length)
throw new Error("Validation failed but no issues detected.");
return {
success: !1,
get error() {
if (this._error)
return this._error;
let error = new ZodError(ctx.common.issues);
return this._error = error, this._error;
}
};
};
function processCreateParams(params) {
if (!params)
return {};
let { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error))
throw new Error(\`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.\`);
return errorMap2 ? { errorMap: errorMap2, description } : { errorMap: (iss, ctx) => {
var _a, _b;
let { message } = params;
return iss.code === "invalid_enum_value" ? { message: message != null ? message : ctx.defaultError } : typeof ctx.data == "undefined" ? { message: (_a = message != null ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError } : iss.code !== "invalid_type" ? { message: ctx.defaultError } : { message: (_b = message != null ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
}, description };
}
var ZodType = class {
constructor(def) {
this.spa = this.safeParseAsync, this._def = def, this.parse = this.parse.bind(this), this.safeParse = this.safeParse.bind(this), this.parseAsync = this.parseAsync.bind(this), this.safeParseAsync = this.safeParseAsync.bind(this), this.spa = this.spa.bind(this), this.refine = this.refine.bind(this), this.refinement = this.refinement.bind(this), this.superRefine = this.superRefine.bind(this), this.optional = this.optional.bind(this), this.nullable = this.nullable.bind(this), this.nullish = this.nullish.bind(this), this.array = this.array.bind(this), this.promise = this.promise.bind(this), this.or = this.or.bind(this), this.and = this.and.bind(this), this.transform = this.transform.bind(this), this.brand = this.brand.bind(this), this.default = this.default.bind(this), this.catch = this.catch.bind(this), this.describe = this.describe.bind(this), this.pipe = this.pipe.bind(this), this.readonly = this.readonly.bind(this), this.isNullable = this.isNullable.bind(this), this.isOptional = this.isOptional.bind(this);
}
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
let result = this._parse(input);
if (isAsync(result))
throw new Error("Synchronous parse encountered promise.");
return result;
}
_parseAsync(input) {
let result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
let result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
var _a;
let ctx = {
common: {
issues: [],
async: (_a = params == null ? void 0 : params.async) !== null && _a !== void 0 ? _a : !1,
contextualErrorMap: params == null ? void 0 : params.errorMap
},
path: (params == null ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
}, result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
async parseAsync(data, params) {
let result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
let ctx = {
common: {
issues: [],
contextualErrorMap: params == null ? void 0 : params.errorMap,
async: !0
},
path: (params == null ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
}, maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }), result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
let getIssueProperties = (val) => typeof message == "string" || typeof message == "undefined" ? { message } : typeof message == "function" ? message(val) : message;
return this._refinement((val, ctx) => {
let result = check(val), setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
return typeof Promise != "undefined" && result instanceof Promise ? result.then((data) => data ? !0 : (setError(), !1)) : result ? !0 : (setError(), !1);
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => check(val) ? !0 : (ctx.addIssue(typeof refinementData == "function" ? refinementData(val, ctx) : refinementData), !1));
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this, this._def);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
default(def) {
let 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) {
let catchValueFunc = typeof def == "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
let 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;
}
}, cuidRegex = /^c[^\\s-]{8,}$/i, cuid2Regex = /^[0-9a-z]+$/, ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/, uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i, nanoidRegex = /^[a-z0-9_-]{21}$/i, 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)?)??$/, emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i, _emojiRegex = "^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$", emojiRegex, 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])$/, ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, 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])))", dateRegex = new RegExp(\`^\${dateRegexSource}$\`);
function timeRegexSource(args) {
let regex = "([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d";
return args.precision ? regex = \`\${regex}\\\\.\\\\d{\${args.precision}}\` : args.precision == null && (regex = \`\${regex}(\\\\.\\\\d+)?\`), regex;
}
function timeRegex(args) {
return new RegExp(\`^\${timeRegexSource(args)}$\`);
}
function datetimeRegex(args) {
let regex = \`\${dateRegexSource}T\${timeRegexSource(args)}\`, opts = [];
return opts.push(args.local ? "Z?" : "Z"), args.offset && opts.push("([+-]\\\\d{2}:?\\\\d{2})"), regex = \`\${regex}(\${opts.join("|")})\`, new RegExp(\`^\${regex}$\`);
}
function isValidIP(ip, version) {
return !!((version === "v4" || !version) && ipv4Regex.test(ip) || (version === "v6" || !version) && ipv6Regex.test(ip));
}
var ZodString = class _ZodString extends ZodType {
_parse(input) {
if (this._def.coerce && (input.data = String(input.data)), this._getType(input) !== ZodParsedType.string) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
}), INVALID;
}
let status = new ParseStatus(), ctx;
for (let check of this._def.checks)
if (check.kind === "min")
input.data.length < check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: !0,
exact: !1,
message: check.message
}), status.dirty());
else if (check.kind === "max")
input.data.length > check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: !0,
exact: !1,
message: check.message
}), status.dirty());
else if (check.kind === "length") {
let tooBig = input.data.length > check.value, tooSmall = input.data.length < check.value;
(tooBig || tooSmall) && (ctx = this._getOrReturnCtx(input, ctx), tooBig ? addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: !0,
exact: !0,
message: check.message
}) : tooSmall && addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: !0,
exact: !0,
message: check.message
}), status.dirty());
} else if (check.kind === "email")
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")
emojiRegex || (emojiRegex = new RegExp(_emojiRegex, "u")), emojiRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty());
else if (check.kind === "uuid")
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")
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")
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")
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")
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 check.kind === "regex" ? (check.regex.lastIndex = 0, check.regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty())) : check.kind === "trim" ? input.data = input.data.trim() : check.kind === "includes" ? 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()) : check.kind === "toLowerCase" ? input.data = input.data.toLowerCase() : check.kind === "toUpperCase" ? input.data = input.data.toUpperCase() : check.kind === "startsWith" ? 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()) : check.kind === "endsWith" ? 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()) : check.kind === "datetime" ? datetimeRegex(check).test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
}), status.dirty()) : check.kind === "date" ? dateRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
}), status.dirty()) : check.kind === "time" ? timeRegex(check).test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
}), status.dirty()) : check.kind === "duration" ? durationRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty()) : check.kind === "ip" ? isValidIP(input.data, check.version) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty()) : check.kind === "base64" ? base64Regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty()) : 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) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
datetime(options) {
var _a, _b;
return typeof options == "string" ? this._addCheck({
kind: "datetime",
precision: null,
offset: !1,
local: !1,
message: options
}) : this._addCheck({
kind: "datetime",
precision: typeof (options == null ? void 0 : options.precision) == "undefined" ? null : options == null ? void 0 : options.precision,
offset: (_a = options == null ? void 0 : options.offset) !== null && _a !== void 0 ? _a : !1,
local: (_b = options == null ? void 0 : options.local) !== null && _b !== void 0 ? _b : !1,
...errorUtil.errToObj(options == null ? void 0 : options.message)
});
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
return typeof options == "string" ? this._addCheck({
kind: "time",
precision: null,
message: options
}) : this._addCheck({
kind: "time",
precision: typeof (options == null ? void 0 : options.precision) == "undefined" ? null : options == null ? void 0 : options.precision,
...errorUtil.errToObj(options == null ? void 0 : 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 == null ? void 0 : options.position,
...errorUtil.errToObj(options == null ? void 0 : options.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
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 isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get minLength() {
let min = null;
for (let ch of this._def.checks)
ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value);
return min;
}
get maxLength() {
let max = null;
for (let ch of this._def.checks)
ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
return max;
}
};
ZodString.create = (params) => {
var _a;
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: (_a = params == null ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : !1,
...processCreateParams(params)
});
};
function floatSafeRemainder(val, step) {
let valDecCount = (val.toString().split(".")[1] || "").length, stepDecCount = (step.toString().split(".")[1] || "").length, decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount, valInt = parseInt(val.toFixed(decCount).replace(".", "")), stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / Math.pow(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)), this._getType(input) !== ZodParsedType.number) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
}), INVALID;
}
let ctx, status = new ParseStatus();
for (let check of this._def.checks)
check.kind === "int" ? util.isInteger(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
}), status.dirty()) : check.kind === "min" ? (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: !1,
message: check.message
}), status.dirty()) : check.kind === "max" ? (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: !1,
message: check.message
}), status.dirty()) : check.kind === "multipleOf" ? 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()) : check.kind === "finite" ? Number.isFinite(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
}), status.dirty()) : util.assertNever(check);
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, !0, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, !1, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, !0, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, !1, 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: !1,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: !1,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: !0,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: !0,
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: !0,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: !0,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (let ch of this._def.checks)
ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value);
return min;
}
get maxValue() {
let max = null;
for (let ch of this._def.checks)
ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null, min = null;
for (let ch of this._def.checks) {
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf")
return !0;
ch.kind === "min" ? (min === null || ch.value > min) && (min = ch.value) : ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: (params == null ? void 0 : params.coerce) || !1,
...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 && (input.data = BigInt(input.data)), this._getType(input) !== ZodParsedType.bigint) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx2.parsedType
}), INVALID;
}
let ctx, status = new ParseStatus();
for (let check of this._def.checks)
check.kind === "min" ? (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()) : check.kind === "max" ? (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()) : check.kind === "multipleOf" ? 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()) : util.assertNever(check);
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, !0, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, !1, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, !0, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, !1, 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: !1,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: !1,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: !0,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: !0,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (let ch of this._def.checks)
ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value);
return min;
}
get maxValue() {
let max = null;
for (let ch of this._def.checks)
ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
return max;
}
};
ZodBigInt.create = (params) => {
var _a;
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: (_a = params == null ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : !1,
...processCreateParams(params)
});
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce && (input.data = !!input.data), this._getType(input) !== ZodParsedType.boolean) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: (params == null ? void 0 : params.coerce) || !1,
...processCreateParams(params)
});
var ZodDate = class _ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce && (input.data = new Date(input.data)), this._getType(input) !== ZodParsedType.date) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
}), INVALID;
}
if (isNaN(input.data.getTime())) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
}), INVALID;
}
let status = new ParseStatus(), ctx;
for (let check of this._def.checks)
check.kind === "min" ? input.data.getTime() < check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: !0,
exact: !1,
minimum: check.value,
type: "date"
}), status.dirty()) : check.kind === "max" ? input.data.getTime() > check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: !0,
exact: !1,
maximum: check.value,
type: "date"
}), status.dirty()) : 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 (let ch of this._def.checks)
ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value);
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (let ch of this._def.checks)
ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => new ZodDate({
checks: [],
coerce: (params == null ? void 0 : params.coerce) || !1,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
var ZodSymbol = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.symbol) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
var ZodUndefined = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.undefined) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
var ZodNull = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.null) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
var ZodAny = class extends ZodType {
constructor() {
super(...arguments), this._any = !0;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
var ZodUnknown = class extends ZodType {
constructor() {
super(...arguments), this._unknown = !0;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
var ZodNever = class extends ZodType {
_parse(input) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
}), INVALID;
}
};
ZodNever.create = (params) => new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
var ZodVoid = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.undefined) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
var ZodArray = class _ZodArray extends ZodType {
_parse(input) {
let { ctx, status } = this._processInputParams(input), def = this._def;
if (ctx.parsedType !== ZodParsedType.array)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
}), INVALID;
if (def.exactLength !== null) {
let tooBig = ctx.data.length > def.exactLength.value, tooSmall = ctx.data.length < def.exactLength.value;
(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: !0,
exact: !0,
message: def.exactLength.message
}), status.dirty());
}
if (def.minLength !== null && ctx.data.length < def.minLength.value && (addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: !0,
exact: !1,
message: def.minLength.message
}), status.dirty()), def.maxLength !== null && ctx.data.length > def.maxLength.value && (addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: !0,
exact: !1,
message: def.maxLength.message
}), status.dirty()), ctx.common.async)
return Promise.all([...ctx.data].map((item, i) => def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)))).then((result2) => ParseStatus.mergeArray(status, result2));
let result = [...ctx.data].map((item, i) => 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) => new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
let newShape = {};
for (let key in schema.shape) {
let fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: () => newShape
});
} else return schema instanceof ZodArray ? new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
}) : schema instanceof ZodOptional ? ZodOptional.create(deepPartialify(schema.unwrap())) : schema instanceof ZodNullable ? ZodNullable.create(deepPartialify(schema.unwrap())) : schema instanceof ZodTuple ? ZodTuple.create(schema.items.map((item) => deepPartialify(item))) : schema;
}
var ZodObject = class _ZodObject extends ZodType {
constructor() {
super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
let shape = this._def.shape(), keys3 = util.objectKeys(shape);
return this._cached = { shape, keys: keys3 };
}
_parse(input) {
if (this._getType(input) !== ZodParsedType.object) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
}), INVALID;
}
let { status, ctx } = this._processInputParams(input), { shape, keys: shapeKeys } = this._getCached(), extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip"))
for (let key in ctx.data)
shapeKeys.includes(key) || extraKeys.push(key);
let pairs = [];
for (let key of shapeKeys) {
let keyValidator = shape[key], 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) {
let unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough")
for (let key of extraKeys)
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] }
});
else if (unknownKeys === "strict")
extraKeys.length > 0 && (addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
}), status.dirty());
else if (unknownKeys !== "strip") throw new Error("Internal ZodObject error: invalid unknownKeys value.");
} else {
let catchall = this._def.catchall;
for (let key of extraKeys) {
let value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(
new ParseInputLazyPath(ctx, value, ctx.path, key)
//, ctx.child(key), value, getParsedType(value)
),
alwaysSet: key in ctx.data
});
}
}
return ctx.common.async ? Promise.resolve().then(async () => {
let syncPairs = [];
for (let pair of pairs) {
let key = await pair.key, value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => ParseStatus.mergeObjectSync(status, syncPairs)) : ParseStatus.mergeObjectSync(status, pairs);
}
get shape() {
return this._def.shape();
}
strict(message) {
return errorUtil.errToObj, new _ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? {
errorMap: (issue, ctx) => {
var _a, _b, _c, _d;
let defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
return issue.code === "unrecognized_keys" ? {
message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
} : {
message: defaultError
};
}
} : {}
});
}
strip() {
return new _ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new _ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
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
});
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema) {
return this.augment({ [key]: schema });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index2) {
return new _ZodObject({
...this._def,
catchall: index2
});
}
pick(mask) {
let shape = {};
return util.objectKeys(mask).forEach((key) => {
mask[key] && this.shape[key] && (shape[key] = this.shape[key]);
}), new _ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
let shape = {};
return util.objectKeys(this.shape).forEach((key) => {
mask[key] || (shape[key] = this.shape[key]);
}), new _ZodObject({
...this._def,
shape: () => shape
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
let newShape = {};
return util.objectKeys(this.shape).forEach((key) => {
let fieldSchema = this.shape[key];
mask && !mask[key] ? newShape[key] = fieldSchema : newShape[key] = fieldSchema.optional();
}), new _ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
let newShape = {};
return util.objectKeys(this.shape).forEach((key) => {
if (mask && !mask[key])
newShape[key] = this.shape[key];
else {
let newField = this.shape[key];
for (; newField instanceof ZodOptional; )
newField = newField._def.innerType;
newShape[key] = newField;
}
}), new _ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
ZodObject.strictCreate = (shape, params) => new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
ZodObject.lazycreate = (shape, params) => new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
var ZodUnion = class extends ZodType {
_parse(input) {
let { ctx } = this._processInputParams(input), options = this._def.options;
function handleResults(results) {
for (let result of results)
if (result.result.status === "valid")
return result.result;
for (let result of results)
if (result.result.status === "dirty")
return ctx.common.issues.push(...result.ctx.common.issues), result.result;
let unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
}), INVALID;
}
if (ctx.common.async)
return Promise.all(options.map(async (option) => {
let 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);
{
let dirty, issues = [];
for (let option of options) {
let childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
}, result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid")
return result;
result.status === "dirty" && !dirty && (dirty = { result, ctx: childCtx }), childCtx.common.issues.length && issues.push(childCtx.common.issues);
}
if (dirty)
return ctx.common.issues.push(...dirty.ctx.common.issues), dirty.result;
let unionErrors = issues.map((issues2) => new ZodError(issues2));
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
}), INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types, params) => new ZodUnion({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
var getDiscriminator = (type) => type instanceof ZodLazy ? getDiscriminator(type.schema) : type instanceof ZodEffects ? getDiscriminator(type.innerType()) : type instanceof ZodLiteral ? [type.value] : type instanceof ZodEnum ? type.options : type instanceof ZodNativeEnum ? util.objectValues(type.enum) : type instanceof ZodDefault ? getDiscriminator(type._def.innerType) : type instanceof ZodUndefined ? [void 0] : type instanceof ZodNull ? [null] : type instanceof ZodOptional ? [void 0, ...getDiscriminator(type.unwrap())] : type instanceof ZodNullable ? [null, ...getDiscriminator(type.unwrap())] : type instanceof ZodBranded || type instanceof ZodReadonly ? getDiscriminator(type.unwrap()) : type instanceof ZodCatch ? getDiscriminator(type._def.innerType) : [], ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
_parse(input) {
let { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
}), INVALID;
let discriminator = this.discriminator, discriminatorValue = ctx.data[discriminator], option = this.optionsMap.get(discriminatorValue);
return option ? ctx.common.async ? option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}) : option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}) : (addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
}), INVALID);
}
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) {
let optionsMap = /* @__PURE__ */ new Map();
for (let type of options) {
let 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 (let 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, b2) {
let aType = getParsedType(a), bType = getParsedType(b2);
if (a === b2)
return { valid: !0, data: a };
if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
let bKeys = util.objectKeys(b2), sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1), newObj = { ...a, ...b2 };
for (let key of sharedKeys) {
let sharedValue = mergeValues(a[key], b2[key]);
if (!sharedValue.valid)
return { valid: !1 };
newObj[key] = sharedValue.data;
}
return { valid: !0, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b2.length)
return { valid: !1 };
let newArray = [];
for (let index2 = 0; index2 < a.length; index2++) {
let itemA = a[index2], itemB = b2[index2], sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid)
return { valid: !1 };
newArray.push(sharedValue.data);
}
return { valid: !0, data: newArray };
} else return aType === ZodParsedType.date && bType === ZodParsedType.date && +a == +b2 ? { valid: !0, data: a } : { valid: !1 };
}
var ZodIntersection = class extends ZodType {
_parse(input) {
let { status, ctx } = this._processInputParams(input), handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight))
return INVALID;
let merged = mergeValues(parsedLeft.value, parsedRight.value);
return merged.valid ? ((isDirty(parsedLeft) || isDirty(parsedRight)) && status.dirty(), { status: status.value, value: merged.data }) : (addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
}), INVALID);
};
return ctx.common.async ? 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)) : 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) => new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
var ZodTuple = class _ZodTuple extends ZodType {
_parse(input) {
let { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
}), INVALID;
if (ctx.data.length < this._def.items.length)
return addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: !0,
exact: !1,
type: "array"
}), INVALID;
!this._def.rest && ctx.data.length > this._def.items.length && (addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: !0,
exact: !1,
type: "array"
}), status.dirty());
let items = [...ctx.data].map((item, itemIndex) => {
let schema = this._def.items[itemIndex] || this._def.rest;
return schema ? schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)) : null;
}).filter((x2) => !!x2);
return ctx.common.async ? Promise.all(items).then((results) => ParseStatus.mergeArray(status, results)) : 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) {
let { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
}), INVALID;
let pairs = [], keyType = this._def.keyType, valueType = this._def.valueType;
for (let 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
});
return ctx.common.async ? ParseStatus.mergeObjectAsync(status, pairs) : ParseStatus.mergeObjectSync(status, pairs);
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
return second instanceof ZodType ? new _ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
}) : new _ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
}, ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
let { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
}), INVALID;
let keyType = this._def.keyType, valueType = this._def.valueType, pairs = [...ctx.data.entries()].map(([key, value], index2) => ({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
}));
if (ctx.common.async) {
let finalMap = /* @__PURE__ */ new Map();
return Promise.resolve().then(async () => {
for (let pair of pairs) {
let key = await pair.key, value = await pair.value;
if (key.status === "aborted" || value.status === "aborted")
return INVALID;
(key.status === "dirty" || value.status === "dirty") && status.dirty(), finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
});
} else {
let finalMap = /* @__PURE__ */ new Map();
for (let pair of pairs) {
let key = pair.key, value = pair.value;
if (key.status === "aborted" || value.status === "aborted")
return INVALID;
(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) => new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
var ZodSet = class _ZodSet extends ZodType {
_parse(input) {
let { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
}), INVALID;
let def = this._def;
def.minSize !== null && ctx.data.size < def.minSize.value && (addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: !0,
exact: !1,
message: def.minSize.message
}), status.dirty()), def.maxSize !== null && ctx.data.size > def.maxSize.value && (addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: !0,
exact: !1,
message: def.maxSize.message
}), status.dirty());
let valueType = this._def.valueType;
function finalizeSet(elements2) {
let parsedSet = /* @__PURE__ */ new Set();
for (let element2 of elements2) {
if (element2.status === "aborted")
return INVALID;
element2.status === "dirty" && status.dirty(), parsedSet.add(element2.value);
}
return { status: status.value, value: parsedSet };
}
let elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
return ctx.common.async ? Promise.all(elements).then((elements2) => finalizeSet(elements2)) : 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) => 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) {
let { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
}), INVALID;
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x2) => !!x2),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x2) => !!x2),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
let params = { errorMap: ctx.common.contextualErrorMap }, fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
let me = this;
return OK(async function(...args) {
let error = new ZodError([]), parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
throw error.addIssue(makeArgsIssue(args, e)), error;
}), result = await Reflect.apply(fn, this, parsedArgs);
return await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
throw error.addIssue(makeReturnsIssue(result, e)), error;
});
});
} else {
let me = this;
return OK(function(...args) {
let parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success)
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
let result = Reflect.apply(fn, this, parsedArgs.data), 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 || ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
}, ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
let { ctx } = this._processInputParams(input);
return this._def.getter()._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
};
ZodLazy.create = (getter, params) => new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
var ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
}), INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => 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 {
constructor() {
super(...arguments), _ZodEnum_cache.set(this, void 0);
}
_parse(input) {
if (typeof input.data != "string") {
let ctx = this._getOrReturnCtx(input), expectedValues = this._def.values;
return addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
}), INVALID;
}
if (__classPrivateFieldGet(this, _ZodEnum_cache, "f") || __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"), !__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
let ctx = this._getOrReturnCtx(input), expectedValues = this._def.values;
return addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
}), INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
let enumValues = {};
for (let val of this._def.values)
enumValues[val] = val;
return enumValues;
}
get Values() {
let enumValues = {};
for (let val of this._def.values)
enumValues[val] = val;
return enumValues;
}
get Enum() {
let enumValues = {};
for (let 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_cache = /* @__PURE__ */ new WeakMap();
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
constructor() {
super(...arguments), _ZodNativeEnum_cache.set(this, void 0);
}
_parse(input) {
let nativeEnumValues = util.getValidEnumValues(this._def.values), ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
let expectedValues = util.objectValues(nativeEnumValues);
return addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
}), INVALID;
}
if (__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f") || __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f"), !__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
let expectedValues = util.objectValues(nativeEnumValues);
return addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
}), INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
_ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap();
ZodNativeEnum.create = (values, params) => new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
var ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
let { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === !1)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
}), INVALID;
let promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
})));
}
};
ZodPromise.create = (schema, params) => 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) {
let { status, ctx } = this._processInputParams(input), effect = this._def.effect || null, checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg), arg.fatal ? status.abort() : status.dirty();
},
get path() {
return ctx.path;
}
};
if (checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx), effect.type === "preprocess") {
let processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async)
return Promise.resolve(processed).then(async (processed2) => {
if (status.value === "aborted")
return INVALID;
let result = await this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
return result.status === "aborted" ? INVALID : result.status === "dirty" || status.value === "dirty" ? DIRTY(result.value) : result;
});
{
if (status.value === "aborted")
return INVALID;
let result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
return result.status === "aborted" ? INVALID : result.status === "dirty" || status.value === "dirty" ? DIRTY(result.value) : result;
}
}
if (effect.type === "refinement") {
let executeRefinement = (acc) => {
let 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 === !1) {
let inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
return inner.status === "aborted" ? INVALID : (inner.status === "dirty" && status.dirty(), executeRefinement(inner.value), { status: status.value, value: inner.value });
} else
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => inner.status === "aborted" ? INVALID : (inner.status === "dirty" && status.dirty(), executeRefinement(inner.value).then(() => ({ status: status.value, value: inner.value }))));
}
if (effect.type === "transform")
if (ctx.common.async === !1) {
let base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base))
return base;
let 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) => isValid(base) ? Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })) : base);
util.assertNever(effect);
}
};
ZodEffects.create = (schema, effect, params) => new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
ZodEffects.createWithPreprocess = (preprocess2, schema, params) => new ZodEffects({
schema,
effect: { type: "preprocess", transform: preprocess2 },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
var ZodOptional = class extends ZodType {
_parse(input) {
return this._getType(input) === ZodParsedType.undefined ? OK(void 0) : this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
var ZodNullable = class extends ZodType {
_parse(input) {
return this._getType(input) === ZodParsedType.null ? OK(null) : this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
var ZodDefault = class extends ZodType {
_parse(input) {
let { ctx } = this._processInputParams(input), data = ctx.data;
return ctx.parsedType === ZodParsedType.undefined && (data = this._def.defaultValue()), this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type, params) => 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) {
let { ctx } = this._processInputParams(input), newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
}, result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
return isAsync(result) ? result.then((result2) => ({
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
})) : {
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) => 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) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
}), INVALID;
}
return { status: "valid", value: input.data };
}
};
ZodNaN.create = (params) => new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
var BRAND = Symbol("zod_brand"), ZodBranded = class extends ZodType {
_parse(input) {
let { ctx } = this._processInputParams(input), data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
}, ZodPipeline = class _ZodPipeline extends ZodType {
_parse(input) {
let { status, ctx } = this._processInputParams(input);
if (ctx.common.async)
return (async () => {
let inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
return inResult.status === "aborted" ? INVALID : inResult.status === "dirty" ? (status.dirty(), DIRTY(inResult.value)) : this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
})();
{
let inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
return inResult.status === "aborted" ? INVALID : inResult.status === "dirty" ? (status.dirty(), {
status: "dirty",
value: inResult.value
}) : this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
static create(a, b2) {
return new _ZodPipeline({
in: a,
out: b2,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
}, ZodReadonly = class extends ZodType {
_parse(input) {
let result = this._def.innerType._parse(input), freeze = (data) => (isValid(data) && (data.value = Object.freeze(data.value)), data);
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
};
ZodReadonly.create = (type, params) => new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
function custom(check, params = {}, fatal) {
return check ? ZodAny.create().superRefine((data, ctx) => {
var _a, _b;
if (!check(data)) {
let p2 = typeof params == "function" ? params(data) : typeof params == "string" ? { message: params } : params, _fatal = (_b = (_a = p2.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : !0, p22 = typeof p2 == "string" ? { message: p2 } : p2;
ctx.addIssue({ code: "custom", ...p22, fatal: _fatal });
}
}) : ZodAny.create();
}
var late = {
object: ZodObject.lazycreate
}, ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2.ZodString = "ZodString", ZodFirstPartyTypeKind2.ZodNumber = "ZodNumber", ZodFirstPartyTypeKind2.ZodNaN = "ZodNaN", ZodFirstPartyTypeKind2.ZodBigInt = "ZodBigInt", ZodFirstPartyTypeKind2.ZodBoolean = "ZodBoolean", ZodFirstPartyTypeKind2.ZodDate = "ZodDate", ZodFirstPartyTypeKind2.ZodSymbol = "ZodSymbol", ZodFirstPartyTypeKind2.ZodUndefined = "ZodUndefined", ZodFirstPartyTypeKind2.ZodNull = "ZodNull", ZodFirstPartyTypeKind2.ZodAny = "ZodAny", ZodFirstPartyTypeKind2.ZodUnknown = "ZodUnknown", ZodFirstPartyTypeKind2.ZodNever = "ZodNever", ZodFirstPartyTypeKind2.ZodVoid = "ZodVoid", ZodFirstPartyTypeKind2.ZodArray = "ZodArray", ZodFirstPartyTypeKind2.ZodObject = "ZodObject", ZodFirstPartyTypeKind2.ZodUnion = "ZodUnion", ZodFirstPartyTypeKind2.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", ZodFirstPartyTypeKind2.ZodIntersection = "ZodIntersection", ZodFirstPartyTypeKind2.ZodTuple = "ZodTuple", ZodFirstPartyTypeKind2.ZodRecord = "ZodRecord", ZodFirstPartyTypeKind2.ZodMap = "ZodMap", ZodFirstPartyTypeKind2.ZodSet = "ZodSet", ZodFirstPartyTypeKind2.ZodFunction = "ZodFunction", ZodFirstPartyTypeKind2.ZodLazy = "ZodLazy", ZodFirstPartyTypeKind2.ZodLiteral = "ZodLiteral", ZodFirstPartyTypeKind2.ZodEnum = "ZodEnum", ZodFirstPartyTypeKind2.ZodEffects = "ZodEffects", ZodFirstPartyTypeKind2.ZodNativeEnum = "ZodNativeEnum", ZodFirstPartyTypeKind2.ZodOptional = "ZodOptional", ZodFirstPartyTypeKind2.ZodNullable = "ZodNullable", ZodFirstPartyTypeKind2.ZodDefault = "ZodDefault", ZodFirstPartyTypeKind2.ZodCatch = "ZodCatch", ZodFirstPartyTypeKind2.ZodPromise = "ZodPromise", ZodFirstPartyTypeKind2.ZodBranded = "ZodBranded", ZodFirstPartyTypeKind2.ZodPipeline = "ZodPipeline", ZodFirstPartyTypeKind2.ZodReadonly = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
message: \`Input not instance of \${cls.name}\`
}) => custom((data) => data instanceof cls, params), stringType = ZodString.create, numberType = ZodNumber.create, nanType = ZodNaN.create, bigIntType = ZodBigInt.create, booleanType = ZodBoolean.create, dateType = ZodDate.create, symbolType = ZodSymbol.create, undefinedType = ZodUndefined.create, nullType = ZodNull.create, anyType = ZodAny.create, unknownType = ZodUnknown.create, neverType = ZodNever.create, voidType = ZodVoid.create, arrayType = ZodArray.create, objectType = ZodObject.create, strictObjectType = ZodObject.strictCreate, unionType = ZodUnion.create, discriminatedUnionType = ZodDiscriminatedUnion.create, intersectionType = ZodIntersection.create, tupleType = ZodTuple.create, recordType = ZodRecord.create, mapType = ZodMap.create, setType = ZodSet.create, functionType = ZodFunction.create, lazyType = ZodLazy.create, literalType = ZodLiteral.create, enumType = ZodEnum.create, nativeEnumType = ZodNativeEnum.create, promiseType = ZodPromise.create, effectsType = ZodEffects.create, optionalType = ZodOptional.create, nullableType = ZodNullable.create, preprocessType = ZodEffects.createWithPreprocess, pipelineType = ZodPipeline.create, ostring = () => stringType().optional(), onumber = () => numberType().optional(), oboolean = () => booleanType().optional(), coerce = {
string: (arg) => ZodString.create({ ...arg, coerce: !0 }),
number: (arg) => ZodNumber.create({ ...arg, coerce: !0 }),
boolean: (arg) => ZodBoolean.create({
...arg,
coerce: !0
}),
bigint: (arg) => ZodBigInt.create({ ...arg, coerce: !0 }),
date: (arg) => ZodDate.create({ ...arg, coerce: !0 })
}, NEVER = INVALID, z = /* @__PURE__ */ Object.freeze({
__proto__: null,
defaultErrorMap: errorMap,
setErrorMap,
getErrorMap,
makeIssue,
EMPTY_PATH,
addIssueToContext,
ParseStatus,
INVALID,
DIRTY,
OK,
isAborted,
isDirty,
isValid,
isAsync,
get util() {
return util;
},
get objectUtil() {
return objectUtil;
},
ZodParsedType,
getParsedType,
ZodType,
datetimeRegex,
ZodString,
ZodNumber,
ZodBigInt,
ZodBoolean,
ZodDate,
ZodSymbol,
ZodUndefined,
ZodNull,
ZodAny,
ZodUnknown,
ZodNever,
ZodVoid,
ZodArray,
ZodObject,
ZodUnion,
ZodDiscriminatedUnion,
ZodIntersection,
ZodTuple,
ZodRecord,
ZodMap,
ZodSet,
ZodFunction,
ZodLazy,
ZodLiteral,
ZodEnum,
ZodNativeEnum,
ZodPromise,
ZodEffects,
ZodTransformer: ZodEffects,
ZodOptional,
ZodNullable,
ZodDefault,
ZodCatch,
ZodNaN,
BRAND,
ZodBranded,
ZodPipeline,
ZodReadonly,
custom,
Schema: ZodType,
ZodSchema: ZodType,
late,
get ZodFirstPartyTypeKind() {
return ZodFirstPartyTypeKind;
},
coerce,
any: anyType,
array: arrayType,
bigint: bigIntType,
boolean: booleanType,
date: dateType,
discriminatedUnion: discriminatedUnionType,
effect: effectsType,
enum: enumType,
function: functionType,
instanceof: instanceOfType,
intersection: intersectionType,
lazy: lazyType,
literal: literalType,
map: mapType,
nan: nanType,
nativeEnum: nativeEnumType,
never: neverType,
null: nullType,
nullable: nullableType,
number: numberType,
object: objectType,
oboolean,
onumber,
optional: optionalType,
ostring,
pipeline: pipelineType,
preprocess: preprocessType,
promise: promiseType,
record: recordType,
set: setType,
strictObject: strictObjectType,
string: stringType,
symbol: symbolType,
transformer: effectsType,
tuple: tupleType,
undefined: undefinedType,
union: unionType,
unknown: unknownType,
void: voidType,
NEVER,
ZodIssueCode,
quotelessJson,
ZodError
});
// src-charts/constants.js
var chartTypeSchema = z.enum(["bar", "line", "area", "pie", "doughnut", "polarArea"]), formulaChartTypeSchema = z.enum(["line", "area"]), baseChartSchema = z.object({
RANDOM_UUID: z.string(),
DATA_SOURCE: z.enum(["note", "formula"]),
CHART_TITLE: z.string(),
CHART_ASPECT_RATIO_SIZE: z.string().refine((val) => !isNaN(val) && !isNaN(parseFloat(val)), {
message: "Chart size must be a number"
})
}), noteChartSchema = baseChartSchema.extend({
CHART_TYPE: chartTypeSchema,
DATA_SOURCE_NOTE_UUID: z.string(),
TABLE_INDEX_IN_NOTE: z.string().refine((val) => {
let parsed = parseInt(val, 10);
return !isNaN(parsed) && Number.isInteger(parsed) && parsed >= 0 && parsed <= 100;
}, {
message: "Table Index must be an integer between 0 and 100 (inclusive)"
}),
HORIZONTAL_AXIS_LABEL_DIRECTION: z.enum(["column", "row"]),
START_FROM_ZERO: z.boolean()
}), ADDITIONAL_MATH_CONSTANTS = {
pi: Math.PI,
e: Math.E,
ln2: Math.LN2,
ln10: Math.LN10,
log2e: Math.LOG2E,
log10e: Math.LOG10E
}, formulaChartSchema = baseChartSchema.extend({
CHART_TYPE: formulaChartTypeSchema,
DATA_SOURCE_FORMULA_F: z.string().refine((val) => {
try {
return new N(val).evaluate({ x: 1, ...ADDITIONAL_MATH_CONSTANTS }), !0;
} catch {
return !1;
}
}, "Invalid formula"),
MIN_X: z.string().refine((val) => !isNaN(val) && !isNaN(parseFloat(val)), {
message: "minX must be a number"
}),
MAX_X: z.string().refine((val) => !isNaN(val) && !isNaN(parseFloat(val)), {
message: "maxX must be a number"
}),
STEP_X: z.string().refine((val) => !isNaN(val) && !isNaN(parseFloat(val)), {
message: "stepX must be a number"
})
});
// src-charts/embed/renderer.js
var chart;
async function initChart() {
let ctx = document.getElementById("chart").getContext("2d"), getNoteDataSourceLabelsDataSetsObj = async () => {
let noteContent = await appConnector.getNoteContentByUUID(window.chartData.DATA_SOURCE_NOTE_UUID);
console.log("noteContent", noteContent);
let tableAtIndex = getMarkdownTableByIdx(noteContent, parseInt(window.chartData.TABLE_INDEX_IN_NOTE));
if (!tableAtIndex)
throw new Error(\`Table not found at index \${window.chartData.TABLE_INDEX_IN_NOTE} in note \${window.chartData.DATA_SOURCE_NOTE_UUID}\`);
console.log("tableAtIndex", tableAtIndex);
let table2DArray = parseMarkdownTable(tableAtIndex);
console.log("table2DArray", table2DArray);
let chartDataFrom2DArray = getChartDataFrom2DArray(table2DArray, window.chartData.HORIZONTAL_AXIS_LABEL_DIRECTION);
return console.log("chartDataFrom2DArray", chartDataFrom2DArray), chartDataFrom2DArray;
}, getFormulaDataSourceLabelsDataSetsObj = async () => {
let labels = [], datasets = [{
label: "f(x)",
data: []
}], formula = new N(window.chartData.DATA_SOURCE_FORMULA_F);
for (let x2 = parseFloat(window.chartData.MIN_X); x2 <= parseFloat(window.chartData.MAX_X); x2 += parseFloat(window.chartData.STEP_X)) {
labels.push(x2.toString());
let y2 = await formula.evaluate({ x: x2, ...ADDITIONAL_MATH_CONSTANTS });
datasets[0].data.push(y2);
}
return console.log("formula", labels, datasets), { labels, datasets };
};
try {
let chartDataSetArray = window.chartData.DATA_SOURCE === "note" ? await getNoteDataSourceLabelsDataSetsObj() : await getFormulaDataSourceLabelsDataSetsObj(), Chart = (await dynamic_import_esm_default("chart.js/auto")).default;
window.Chart = Chart, chart = new Chart(ctx, getChartJSParamObject(chartDataSetArray));
} catch (e) {
let oldFillStyle = ctx.fillStyle, oldFont = ctx.font;
ctx.font = "16px Arial", ctx.fillStyle = "white", ctx.fillText("Error: " + e, 10, 50), ctx.font = oldFont, ctx.fillStyle = oldFillStyle, console.error(e);
}
}
async function reloadChart() {
chart.destroy(), await initChart();
}
function getChartJSParamObject(chartDataSetArray) {
let chartJSParamObjOptions = {};
window.chartData.CHART_TITLE && (chartJSParamObjOptions.plugins = {
title: {
display: !0,
text: window.chartData.CHART_TITLE
}
}), window.chartData.START_FROM_ZERO && (chartJSParamObjOptions.scales = {
y: {
beginAtZero: !0
}
}), window.chartData.CHART_TYPE === "area" && chartDataSetArray.datasets.forEach((dataset) => {
dataset.fill = !0;
});
let customCanvasBackgroundColorPlugin = {
id: "customCanvasBackgroundColor",
beforeDraw: (chart2, args, options) => {
let { ctx } = chart2;
ctx.save(), ctx.globalCompositeOperation = "destination-over", ctx.fillStyle = "#192025", ctx.fillRect(0, 0, chart2.width, chart2.height), ctx.restore();
}
};
return {
type: window.chartData.CHART_TYPE !== "area" ? window.chartData.CHART_TYPE : "line",
// area is implemented as line with fill
responsive: !0,
maintainAspectRatio: !0,
aspectRatio: window.chartData.CHART_ASPECT_RATIO_SIZE,
data: chartDataSetArray,
options: chartJSParamObjOptions,
plugins: [customCanvasBackgroundColorPlugin]
};
}
// src-charts/embed/toolbar.js
async function addToolbar() {
let style = document.createElement("style");
style.textContent = \`
body {
background-color: #192025;
color: rgb(249, 251, 252);
height: 100vh;
margin: 0;
}
.chart-container {
position: relative;
width: 100%;
height: 100%;
margin: 0px;
display: flex;
justify-content: center;
align-items: center;
}
.toolbar-brand {
display: none;
}
.toolbar-item:hover {
cursor: pointer;
color: #007bff;
}
.toolbar-item svg {
pointer-events: none;
}
\`, document.head.append(style);
let container = document.createElement("div");
container.style.position = "absolute", container.style.top = "0.5rem", container.style.right = "0.5rem", document.body.append(container);
let reloadToolbarItem = document.createElement("div");
reloadToolbarItem.title = "Reload Chart", reloadToolbarItem.className = "toolbar-item", reloadToolbarItem.onclick = () => reloadChart(), reloadToolbarItem.innerHTML = '<svg width="20" height="20" viewBox="0 0 768 1204"><path fill="currentColor" d="M655.461 473.469c11.875 81.719-13.062 167.781-76.812 230.594-94.188 92.938-239.5 104.375-346.375 34.562l74.875-73L31.96 627.25 70.367 896l84.031-80.5c150.907 111.25 364.938 100.75 502.063-34.562 79.5-78.438 115.75-182.562 111.25-285.312L655.461 473.469zM189.46 320.062c94.156-92.938 239.438-104.438 346.313-34.562l-75 72.969 275.188 38.406L697.586 128l-83.938 80.688C462.711 97.34400000000005 248.742 107.96900000000005 111.585 243.25 32.085 321.656-4.133 425.781 0.335 528.5l112.25 22.125C100.71 468.875 125.71 382.906 189.46 320.062z"/></svg>', window.chartData.DATA_SOURCE !== "formula" && container.append(reloadToolbarItem);
let optionsToolbarItem = document.createElement("div");
optionsToolbarItem.title = "Options", optionsToolbarItem.className = "toolbar-item", optionsToolbarItem.onclick = () => handleOptionsToolbarItem(), optionsToolbarItem.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="-2 -4 28 28" width="20px" fill="currentColor"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z"/></svg>', container.append(optionsToolbarItem);
let settingsToolbarItem = document.createElement("div");
settingsToolbarItem.title = "Settings", settingsToolbarItem.className = "toolbar-item", settingsToolbarItem.onclick = async () => {
let newChartData = await appConnector.updateChartData(window.chartData);
newChartData && (window.chartData = newChartData, await reloadChart());
}, settingsToolbarItem.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="0 -6 28 28" width="24px" fill="currentColor"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M19.43 12.98c.04-.32.07-.64.07-.98 0-.34-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.09-.16-.26-.25-.44-.25-.06 0-.12.01-.17.03l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.06-.02-.12-.03-.18-.03-.17 0-.34.09-.43.25l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98 0 .33.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.09.16.26.25.44.25.06 0 .12-.01.17-.03l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.06.02.12.03.18.03.17 0 .34-.09.43-.25l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zm-1.98-1.71c.04.31.05.52.05.73 0 .21-.02.43-.05.73l-.14 1.13.89.7 1.08.84-.7 1.21-1.27-.51-1.04-.42-.9.68c-.43.32-.84.56-1.25.73l-1.06.43-.16 1.13-.2 1.35h-1.4l-.19-1.35-.16-1.13-1.06-.43c-.43-.18-.83-.41-1.23-.71l-.91-.7-1.06.43-1.27.51-.7-1.21 1.08-.84.89-.7-.14-1.13c-.03-.31-.05-.54-.05-.74s.02-.43.05-.73l.14-1.13-.89-.7-1.08-.84.7-1.21 1.27.51 1.04.42.9-.68c.43-.32.84-.56 1.25-.73l1.06-.43.16-1.13.2-1.35h1.39l.19 1.35.16 1.13 1.06.43c.43.18.83.41 1.23.71l.91.7 1.06-.43 1.27-.51.7 1.21-1.07.85-.89.7.14 1.13zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/></svg>', container.append(settingsToolbarItem);
}
async function handleOptionsToolbarItem() {
switch (await appConnector.prompt("", {
inputs: [
{
label: "Select an option",
type: "select",
options: [
{ label: "Save as png image", value: "Save as png image" }
],
value: "Save as png image"
}
]
})) {
case "Save as png image":
let dataURL = document.getElementById("chart").toDataURL("image/png");
await appConnector.saveFile({ data: dataURL, name: "chart.png" });
break;
}
}
// common-utils/embed-comunication.js
function createCallAmplenotePluginMock(embedCommandsMock) {
return async (commandName, ...args) => {
if (commandName in embedCommandsMock)
return await embedCommandsMock[commandName](...args);
throw new Error(\`Unknown command: \${commandName}\`);
};
}
function deserializeWithFunctions(str) {
return JSON.parse(str, (key, value) => {
if (typeof value == "string" && value.startsWith("__FUNCTION:")) {
let functionBody = value.slice(11);
return new Function(\`return \${functionBody}\`)();
}
return value;
});
}
// src-charts/embed/chart.js
window.INJECTED_EMBED_COMMANDS_MOCK && (window.callAmplenotePlugin = createCallAmplenotePluginMock(deserializeWithFunctions(window.INJECTED_EMBED_COMMANDS_MOCK))), window.INJECTED_CHART_DATA_MOCK && (window.chartData = deserializeWithFunctions(window.INJECTED_CHART_DATA_MOCK));
window.appConnector = new Proxy({}, {
get: function(target, prop, receiver) {
return prop in target ? target[prop] : async function(...args) {
return await window.callAmplenotePlugin(prop, ...args);
};
}
});
window.appSettings = window.appSettings || {};
(async () => (showEmbedLoader(), await initChart(), hideEmbedLoader(), await addToolbar()))();
return plugin;
})()
<\/script>
</body>
</html>`;
var util;
(function(util2) {
util2.assertEqual = (val) => val;
function assertIs(_arg) {
}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util2.assertNever = assertNever, util2.arrayToEnum = (items) => {
let obj = {};
for (let item of items)
obj[item] = item;
return obj;
}, util2.getValidEnumValues = (obj) => {
let validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] != "number"), filtered = {};
for (let k2 of validKeys)
filtered[k2] = obj[k2];
return util2.objectValues(filtered);
}, util2.objectValues = (obj) => util2.objectKeys(obj).map(function(e) {
return obj[e];
}), util2.objectKeys = typeof Object.keys == "function" ? (obj) => Object.keys(obj) : (object) => {
let keys2 = [];
for (let key in object)
Object.prototype.hasOwnProperty.call(object, key) && keys2.push(key);
return keys2;
}, util2.find = (arr, checker) => {
for (let item of arr)
if (checker(item))
return item;
}, util2.isInteger = typeof Number.isInteger == "function" ? (val) => Number.isInteger(val) : (val) => typeof val == "number" && isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val == "string" ? `'${val}'` : val).join(separator);
}
util2.joinValues = joinValues, util2.jsonStringifyReplacer = (_, value) => typeof value == "bigint" ? value.toString() : value;
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => ({
...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"
]), getParsedType = (data) => {
switch (typeof data) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
return Array.isArray(data) ? ZodParsedType.array : data === null ? ZodParsedType.null : data.then && typeof data.then == "function" && data.catch && typeof data.catch == "function" ? ZodParsedType.promise : typeof Map != "undefined" && data instanceof Map ? ZodParsedType.map : typeof Set != "undefined" && data instanceof Set ? ZodParsedType.set : typeof Date != "undefined" && data instanceof Date ? ZodParsedType.date : ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
}, ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]), quotelessJson = (obj) => JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:"), ZodError = class _ZodError extends Error {
constructor(issues) {
super(), this.issues = [], this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
}, this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
let actualProto = new.target.prototype;
Object.setPrototypeOf ? Object.setPrototypeOf(this, actualProto) : this.__proto__ = actualProto, this.name = "ZodError", this.issues = issues;
}
get errors() {
return this.issues;
}
format(_mapper) {
let mapper = _mapper || function(issue) {
return issue.message;
}, fieldErrors = { _errors: [] }, processError = (error) => {
for (let 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, i = 0;
for (; i < issue.path.length; ) {
let el = issue.path[i];
i === issue.path.length - 1 ? (curr[el] = curr[el] || { _errors: [] }, curr[el]._errors.push(mapper(issue))) : curr[el] = curr[el] || { _errors: [] }, curr = curr[el], i++;
}
}
};
return processError(this), 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) {
let fieldErrors = {}, formErrors = [];
for (let sub of this.issues)
sub.path.length > 0 ? (fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [], fieldErrors[sub.path[0]].push(mapper(sub))) : formErrors.push(mapper(sub));
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => new ZodError(issues);
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
issue.received === ZodParsedType.undefined ? message = "Required" : 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:
typeof issue.validation == "object" ? "includes" in issue.validation ? (message = `Invalid input: must include "${issue.validation.includes}"`, typeof issue.validation.position == "number" && (message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`)) : "startsWith" in issue.validation ? message = `Invalid input: must start with "${issue.validation.startsWith}"` : "endsWith" in issue.validation ? message = `Invalid input: must end with "${issue.validation.endsWith}"` : util.assertNever(issue.validation) : issue.validation !== "regex" ? message = `Invalid ${issue.validation}` : message = "Invalid";
break;
case ZodIssueCode.too_small:
issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "more than"} ${issue.minimum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "over"} ${issue.minimum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : 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))}` : message = "Invalid input";
break;
case ZodIssueCode.too_big:
issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "less than"} ${issue.maximum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "under"} ${issue.maximum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : issue.type === "bigint" ? message = `BigInt must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : issue.type === "date" ? message = `Date must be ${issue.exact ? "exactly" : issue.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(issue.maximum))}` : message = "Invalid input";
break;
case ZodIssueCode.custom:
message = "Invalid input";
break;
case ZodIssueCode.invalid_intersection_types:
message = "Intersection results could not be merged";
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError, util.assertNever(issue);
}
return { message };
}, overrideErrorMap = errorMap;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
var makeIssue = (params) => {
let { data, path, errorMaps, issueData } = params, fullPath = [...path, ...issueData.path || []], fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== void 0)
return {
...issueData,
path: fullPath,
message: issueData.message
};
let errorMessage = "", maps = errorMaps.filter((m2) => !!m2).slice().reverse();
for (let map of maps)
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
return {
...issueData,
path: fullPath,
message: errorMessage
};
}, EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
let overrideMap = getErrorMap(), issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === errorMap ? void 0 : errorMap
].filter((x2) => !!x2)
});
ctx.common.issues.push(issue);
}
var ParseStatus = class _ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
this.value === "valid" && (this.value = "dirty");
}
abort() {
this.value !== "aborted" && (this.value = "aborted");
}
static mergeArray(status, results) {
let arrayValue = [];
for (let s of results) {
if (s.status === "aborted")
return INVALID;
s.status === "dirty" && status.dirty(), arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
let syncPairs = [];
for (let pair of pairs) {
let key = await pair.key, value = await pair.value;
syncPairs.push({
key,
value
});
}
return _ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
let finalObject = {};
for (let pair of pairs) {
let { key, value } = pair;
if (key.status === "aborted" || value.status === "aborted")
return INVALID;
key.status === "dirty" && status.dirty(), value.status === "dirty" && status.dirty(), key.value !== "__proto__" && (typeof value.value != "undefined" || pair.alwaysSet) && (finalObject[key.value] = value.value);
}
return { status: status.value, value: finalObject };
}
}, INVALID = Object.freeze({
status: "aborted"
}), DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x2) => x2.status === "aborted", isDirty = (x2) => x2.status === "dirty", isValid = (x2) => x2.status === "valid", isAsync = (x2) => typeof Promise != "undefined" && x2 instanceof Promise;
function __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);
}
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;
}
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message == "string" ? { message } : message || {}, errorUtil2.toString = (message) => typeof message == "string" ? message : message == null ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache, _ZodNativeEnum_cache, ParseInputLazyPath = class {
constructor(parent, value, path, key) {
this._cachedPath = [], this.parent = parent, this.data = value, this._path = path, this._key = key;
}
get path() {
return this._cachedPath.length || (this._key instanceof Array ? this._cachedPath.push(...this._path, ...this._key) : this._cachedPath.push(...this._path, this._key)), this._cachedPath;
}
}, handleResult = (ctx, result) => {
if (isValid(result))
return { success: !0, data: result.value };
if (!ctx.common.issues.length)
throw new Error("Validation failed but no issues detected.");
return {
success: !1,
get error() {
if (this._error)
return this._error;
let error = new ZodError(ctx.common.issues);
return this._error = error, this._error;
}
};
};
function processCreateParams(params) {
if (!params)
return {};
let { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error))
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
return errorMap2 ? { errorMap: errorMap2, description } : { errorMap: (iss, ctx) => {
var _a, _b;
let { message } = params;
return iss.code === "invalid_enum_value" ? { message: message != null ? message : ctx.defaultError } : typeof ctx.data == "undefined" ? { message: (_a = message != null ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError } : iss.code !== "invalid_type" ? { message: ctx.defaultError } : { message: (_b = message != null ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
}, description };
}
var ZodType = class {
constructor(def) {
this.spa = this.safeParseAsync, this._def = def, this.parse = this.parse.bind(this), this.safeParse = this.safeParse.bind(this), this.parseAsync = this.parseAsync.bind(this), this.safeParseAsync = this.safeParseAsync.bind(this), this.spa = this.spa.bind(this), this.refine = this.refine.bind(this), this.refinement = this.refinement.bind(this), this.superRefine = this.superRefine.bind(this), this.optional = this.optional.bind(this), this.nullable = this.nullable.bind(this), this.nullish = this.nullish.bind(this), this.array = this.array.bind(this), this.promise = this.promise.bind(this), this.or = this.or.bind(this), this.and = this.and.bind(this), this.transform = this.transform.bind(this), this.brand = this.brand.bind(this), this.default = this.default.bind(this), this.catch = this.catch.bind(this), this.describe = this.describe.bind(this), this.pipe = this.pipe.bind(this), this.readonly = this.readonly.bind(this), this.isNullable = this.isNullable.bind(this), this.isOptional = this.isOptional.bind(this);
}
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
let result = this._parse(input);
if (isAsync(result))
throw new Error("Synchronous parse encountered promise.");
return result;
}
_parseAsync(input) {
let result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
let result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
var _a;
let ctx = {
common: {
issues: [],
async: (_a = params == null ? void 0 : params.async) !== null && _a !== void 0 ? _a : !1,
contextualErrorMap: params == null ? void 0 : params.errorMap
},
path: (params == null ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
}, result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
async parseAsync(data, params) {
let result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
let ctx = {
common: {
issues: [],
contextualErrorMap: params == null ? void 0 : params.errorMap,
async: !0
},
path: (params == null ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
}, maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }), result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
let getIssueProperties = (val) => typeof message == "string" || typeof message == "undefined" ? { message } : typeof message == "function" ? message(val) : message;
return this._refinement((val, ctx) => {
let result = check(val), setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
return typeof Promise != "undefined" && result instanceof Promise ? result.then((data) => data ? !0 : (setError(), !1)) : result ? !0 : (setError(), !1);
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => check(val) ? !0 : (ctx.addIssue(typeof refinementData == "function" ? refinementData(val, ctx) : refinementData), !1));
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this, this._def);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
default(def) {
let 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) {
let catchValueFunc = typeof def == "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
let 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;
}
}, cuidRegex = /^c[^\s-]{8,}$/i, cuid2Regex = /^[0-9a-z]+$/, ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/, uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i, nanoidRegex = /^[a-z0-9_-]{21}$/i, 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)?)??$/, emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i, _emojiRegex = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", emojiRegex, 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])$/, ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, 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])))", dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let regex = "([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";
return args.precision ? regex = `${regex}\\.\\d{${args.precision}}` : args.precision == null && (regex = `${regex}(\\.\\d+)?`), regex;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`, opts = [];
return opts.push(args.local ? "Z?" : "Z"), args.offset && opts.push("([+-]\\d{2}:?\\d{2})"), regex = `${regex}(${opts.join("|")})`, new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
return !!((version === "v4" || !version) && ipv4Regex.test(ip) || (version === "v6" || !version) && ipv6Regex.test(ip));
}
var ZodString = class _ZodString extends ZodType {
_parse(input) {
if (this._def.coerce && (input.data = String(input.data)), this._getType(input) !== ZodParsedType.string) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
}), INVALID;
}
let status = new ParseStatus(), ctx;
for (let check of this._def.checks)
if (check.kind === "min")
input.data.length < check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: !0,
exact: !1,
message: check.message
}), status.dirty());
else if (check.kind === "max")
input.data.length > check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: !0,
exact: !1,
message: check.message
}), status.dirty());
else if (check.kind === "length") {
let tooBig = input.data.length > check.value, tooSmall = input.data.length < check.value;
(tooBig || tooSmall) && (ctx = this._getOrReturnCtx(input, ctx), tooBig ? addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: !0,
exact: !0,
message: check.message
}) : tooSmall && addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: !0,
exact: !0,
message: check.message
}), status.dirty());
} else if (check.kind === "email")
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")
emojiRegex || (emojiRegex = new RegExp(_emojiRegex, "u")), emojiRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty());
else if (check.kind === "uuid")
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")
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")
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")
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")
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 check.kind === "regex" ? (check.regex.lastIndex = 0, check.regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty())) : check.kind === "trim" ? input.data = input.data.trim() : check.kind === "includes" ? 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()) : check.kind === "toLowerCase" ? input.data = input.data.toLowerCase() : check.kind === "toUpperCase" ? input.data = input.data.toUpperCase() : check.kind === "startsWith" ? 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()) : check.kind === "endsWith" ? 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()) : check.kind === "datetime" ? datetimeRegex(check).test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
}), status.dirty()) : check.kind === "date" ? dateRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
}), status.dirty()) : check.kind === "time" ? timeRegex(check).test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
}), status.dirty()) : check.kind === "duration" ? durationRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty()) : check.kind === "ip" ? isValidIP(input.data, check.version) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty()) : check.kind === "base64" ? base64Regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
}), status.dirty()) : 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) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
datetime(options) {
var _a, _b;
return typeof options == "string" ? this._addCheck({
kind: "datetime",
precision: null,
offset: !1,
local: !1,
message: options
}) : this._addCheck({
kind: "datetime",
precision: typeof (options == null ? void 0 : options.precision) == "undefined" ? null : options == null ? void 0 : options.precision,
offset: (_a = options == null ? void 0 : options.offset) !== null && _a !== void 0 ? _a : !1,
local: (_b = options == null ? void 0 : options.local) !== null && _b !== void 0 ? _b : !1,
...errorUtil.errToObj(options == null ? void 0 : options.message)
});
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
return typeof options == "string" ? this._addCheck({
kind: "time",
precision: null,
message: options
}) : this._addCheck({
kind: "time",
precision: typeof (options == null ? void 0 : options.precision) == "undefined" ? null : options == null ? void 0 : options.precision,
...errorUtil.errToObj(options == null ? void 0 : 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 == null ? void 0 : options.position,
...errorUtil.errToObj(options == null ? void 0 : options.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get 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 isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get minLength() {
let min = null;
for (let ch of this._def.checks)
ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value);
return min;
}
get maxLength() {
let max = null;
for (let ch of this._def.checks)
ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
return max;
}
};
ZodString.create = (params) => {
var _a;
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: (_a = params == null ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : !1,
...processCreateParams(params)
});
};
function floatSafeRemainder(val, step) {
let valDecCount = (val.toString().split(".")[1] || "").length, stepDecCount = (step.toString().split(".")[1] || "").length, decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount, valInt = parseInt(val.toFixed(decCount).replace(".", "")), stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / Math.pow(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)), this._getType(input) !== ZodParsedType.number) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
}), INVALID;
}
let ctx, status = new ParseStatus();
for (let check of this._def.checks)
check.kind === "int" ? util.isInteger(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
}), status.dirty()) : check.kind === "min" ? (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: !1,
message: check.message
}), status.dirty()) : check.kind === "max" ? (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: !1,
message: check.message
}), status.dirty()) : check.kind === "multipleOf" ? 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()) : check.kind === "finite" ? Number.isFinite(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
}), status.dirty()) : util.assertNever(check);
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, !0, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, !1, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, !0, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, !1, 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: !1,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: !1,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: !0,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: !0,
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: !0,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: !0,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (let ch of this._def.checks)
ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value);
return min;
}
get maxValue() {
let max = null;
for (let ch of this._def.checks)
ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null, min = null;
for (let ch of this._def.checks) {
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf")
return !0;
ch.kind === "min" ? (min === null || ch.value > min) && (min = ch.value) : ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: (params == null ? void 0 : params.coerce) || !1,
...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 && (input.data = BigInt(input.data)), this._getType(input) !== ZodParsedType.bigint) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx2.parsedType
}), INVALID;
}
let ctx, status = new ParseStatus();
for (let check of this._def.checks)
check.kind === "min" ? (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()) : check.kind === "max" ? (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()) : check.kind === "multipleOf" ? 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()) : util.assertNever(check);
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, !0, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, !1, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, !0, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, !1, 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: !1,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: !1,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: !0,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: !0,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (let ch of this._def.checks)
ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value);
return min;
}
get maxValue() {
let max = null;
for (let ch of this._def.checks)
ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
return max;
}
};
ZodBigInt.create = (params) => {
var _a;
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: (_a = params == null ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : !1,
...processCreateParams(params)
});
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce && (input.data = !!input.data), this._getType(input) !== ZodParsedType.boolean) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: (params == null ? void 0 : params.coerce) || !1,
...processCreateParams(params)
});
var ZodDate = class _ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce && (input.data = new Date(input.data)), this._getType(input) !== ZodParsedType.date) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
}), INVALID;
}
if (isNaN(input.data.getTime())) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
}), INVALID;
}
let status = new ParseStatus(), ctx;
for (let check of this._def.checks)
check.kind === "min" ? input.data.getTime() < check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: !0,
exact: !1,
minimum: check.value,
type: "date"
}), status.dirty()) : check.kind === "max" ? input.data.getTime() > check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: !0,
exact: !1,
maximum: check.value,
type: "date"
}), status.dirty()) : 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 (let ch of this._def.checks)
ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value);
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (let ch of this._def.checks)
ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value);
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => new ZodDate({
checks: [],
coerce: (params == null ? void 0 : params.coerce) || !1,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
var ZodSymbol = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.symbol) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
var ZodUndefined = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.undefined) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
var ZodNull = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.null) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
var ZodAny = class extends ZodType {
constructor() {
super(...arguments), this._any = !0;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
var ZodUnknown = class extends ZodType {
constructor() {
super(...arguments), this._unknown = !0;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
var ZodNever = class extends ZodType {
_parse(input) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
}), INVALID;
}
};
ZodNever.create = (params) => new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
var ZodVoid = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.undefined) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
}), INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
var ZodArray = class _ZodArray extends ZodType {
_parse(input) {
let { ctx, status } = this._processInputParams(input), def = this._def;
if (ctx.parsedType !== ZodParsedType.array)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
}), INVALID;
if (def.exactLength !== null) {
let tooBig = ctx.data.length > def.exactLength.value, tooSmall = ctx.data.length < def.exactLength.value;
(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: !0,
exact: !0,
message: def.exactLength.message
}), status.dirty());
}
if (def.minLength !== null && ctx.data.length < def.minLength.value && (addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: !0,
exact: !1,
message: def.minLength.message
}), status.dirty()), def.maxLength !== null && ctx.data.length > def.maxLength.value && (addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: !0,
exact: !1,
message: def.maxLength.message
}), status.dirty()), ctx.common.async)
return Promise.all([...ctx.data].map((item, i) => def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)))).then((result2) => ParseStatus.mergeArray(status, result2));
let result = [...ctx.data].map((item, i) => 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) => new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
let newShape = {};
for (let key in schema.shape) {
let fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: () => newShape
});
} else return schema instanceof ZodArray ? new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
}) : schema instanceof ZodOptional ? ZodOptional.create(deepPartialify(schema.unwrap())) : schema instanceof ZodNullable ? ZodNullable.create(deepPartialify(schema.unwrap())) : schema instanceof ZodTuple ? ZodTuple.create(schema.items.map((item) => deepPartialify(item))) : schema;
}
var ZodObject = class _ZodObject extends ZodType {
constructor() {
super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
let shape = this._def.shape(), keys2 = util.objectKeys(shape);
return this._cached = { shape, keys: keys2 };
}
_parse(input) {
if (this._getType(input) !== ZodParsedType.object) {
let ctx2 = this._getOrReturnCtx(input);
return addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
}), INVALID;
}
let { status, ctx } = this._processInputParams(input), { shape, keys: shapeKeys } = this._getCached(), extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip"))
for (let key in ctx.data)
shapeKeys.includes(key) || extraKeys.push(key);
let pairs = [];
for (let key of shapeKeys) {
let keyValidator = shape[key], 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) {
let unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough")
for (let key of extraKeys)
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] }
});
else if (unknownKeys === "strict")
extraKeys.length > 0 && (addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
}), status.dirty());
else if (unknownKeys !== "strip") throw new Error("Internal ZodObject error: invalid unknownKeys value.");
} else {
let catchall = this._def.catchall;
for (let key of extraKeys) {
let 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
});
}
}
return ctx.common.async ? Promise.resolve().then(async () => {
let syncPairs = [];
for (let pair of pairs) {
let key = await pair.key, value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => ParseStatus.mergeObjectSync(status, syncPairs)) : ParseStatus.mergeObjectSync(status, pairs);
}
get shape() {
return this._def.shape();
}
strict(message) {
return errorUtil.errToObj, new _ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? {
errorMap: (issue, ctx) => {
var _a, _b, _c, _d;
let defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
return issue.code === "unrecognized_keys" ? {
message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
} : {
message: defaultError
};
}
} : {}
});
}
strip() {
return new _ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new _ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
extend(augmentation) {
return new _ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
merge(merging) {
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) {
let shape = {};
return util.objectKeys(mask).forEach((key) => {
mask[key] && this.shape[key] && (shape[key] = this.shape[key]);
}), new _ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
let shape = {};
return util.objectKeys(this.shape).forEach((key) => {
mask[key] || (shape[key] = this.shape[key]);
}), new _ZodObject({
...this._def,
shape: () => shape
});
}
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
let newShape = {};
return util.objectKeys(this.shape).forEach((key) => {
let fieldSchema = this.shape[key];
mask && !mask[key] ? newShape[key] = fieldSchema : newShape[key] = fieldSchema.optional();
}), new _ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
let newShape = {};
return util.objectKeys(this.shape).forEach((key) => {
if (mask && !mask[key])
newShape[key] = this.shape[key];
else {
let newField = this.shape[key];
for (; newField instanceof ZodOptional; )
newField = newField._def.innerType;
newShape[key] = newField;
}
}), new _ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
ZodObject.strictCreate = (shape, params) => new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
ZodObject.lazycreate = (shape, params) => new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
var ZodUnion = class extends ZodType {
_parse(input) {
let { ctx } = this._processInputParams(input), options = this._def.options;
function handleResults(results) {
for (let result of results)
if (result.result.status === "valid")
return result.result;
for (let result of results)
if (result.result.status === "dirty")
return ctx.common.issues.push(...result.ctx.common.issues), result.result;
let unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
}), INVALID;
}
if (ctx.common.async)
return Promise.all(options.map(async (option) => {
let 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);
{
let dirty, issues = [];
for (let option of options) {
let childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
}, result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid")
return result;
result.status === "dirty" && !dirty && (dirty = { result, ctx: childCtx }), childCtx.common.issues.length && issues.push(childCtx.common.issues);
}
if (dirty)
return ctx.common.issues.push(...dirty.ctx.common.issues), dirty.result;
let unionErrors = issues.map((issues2) => new ZodError(issues2));
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
}), INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types, params) => new ZodUnion({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
var getDiscriminator = (type) => type instanceof ZodLazy ? getDiscriminator(type.schema) : type instanceof ZodEffects ? getDiscriminator(type.innerType()) : type instanceof ZodLiteral ? [type.value] : type instanceof ZodEnum ? type.options : type instanceof ZodNativeEnum ? util.objectValues(type.enum) : type instanceof ZodDefault ? getDiscriminator(type._def.innerType) : type instanceof ZodUndefined ? [void 0] : type instanceof ZodNull ? [null] : type instanceof ZodOptional ? [void 0, ...getDiscriminator(type.unwrap())] : type instanceof ZodNullable ? [null, ...getDiscriminator(type.unwrap())] : type instanceof ZodBranded || type instanceof ZodReadonly ? getDiscriminator(type.unwrap()) : type instanceof ZodCatch ? getDiscriminator(type._def.innerType) : [], ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
_parse(input) {
let { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
}), INVALID;
let discriminator = this.discriminator, discriminatorValue = ctx.data[discriminator], option = this.optionsMap.get(discriminatorValue);
return option ? ctx.common.async ? option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}) : option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}) : (addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
}), INVALID);
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
static create(discriminator, options, params) {
let optionsMap = new Map();
for (let type of options) {
let 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 (let 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, b2) {
let aType = getParsedType(a), bType = getParsedType(b2);
if (a === b2)
return { valid: !0, data: a };
if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
let bKeys = util.objectKeys(b2), sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1), newObj = { ...a, ...b2 };
for (let key of sharedKeys) {
let sharedValue = mergeValues(a[key], b2[key]);
if (!sharedValue.valid)
return { valid: !1 };
newObj[key] = sharedValue.data;
}
return { valid: !0, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b2.length)
return { valid: !1 };
let newArray = [];
for (let index = 0; index < a.length; index++) {
let itemA = a[index], itemB = b2[index], sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid)
return { valid: !1 };
newArray.push(sharedValue.data);
}
return { valid: !0, data: newArray };
} else return aType === ZodParsedType.date && bType === ZodParsedType.date && +a == +b2 ? { valid: !0, data: a } : { valid: !1 };
}
var ZodIntersection = class extends ZodType {
_parse(input) {
let { status, ctx } = this._processInputParams(input), handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight))
return INVALID;
let merged = mergeValues(parsedLeft.value, parsedRight.value);
return merged.valid ? ((isDirty(parsedLeft) || isDirty(parsedRight)) && status.dirty(), { status: status.value, value: merged.data }) : (addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
}), INVALID);
};
return ctx.common.async ? 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)) : 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) => new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
var ZodTuple = class _ZodTuple extends ZodType {
_parse(input) {
let { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
}), INVALID;
if (ctx.data.length < this._def.items.length)
return addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: !0,
exact: !1,
type: "array"
}), INVALID;
!this._def.rest && ctx.data.length > this._def.items.length && (addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: !0,
exact: !1,
type: "array"
}), status.dirty());
let items = [...ctx.data].map((item, itemIndex) => {
let schema = this._def.items[itemIndex] || this._def.rest;
return schema ? schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)) : null;
}).filter((x2) => !!x2);
return ctx.common.async ? Promise.all(items).then((results) => ParseStatus.mergeArray(status, results)) : 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) {
let { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
}), INVALID;
let pairs = [], keyType = this._def.keyType, valueType = this._def.valueType;
for (let 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
});
return ctx.common.async ? ParseStatus.mergeObjectAsync(status, pairs) : ParseStatus.mergeObjectSync(status, pairs);
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
return second instanceof ZodType ? new _ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
}) : new _ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
}, ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
let { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
}), INVALID;
let keyType = this._def.keyType, valueType = this._def.valueType, pairs = [...ctx.data.entries()].map(([key, value], index) => ({
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) {
let finalMap = new Map();
return Promise.resolve().then(async () => {
for (let pair of pairs) {
let key = await pair.key, value = await pair.value;
if (key.status === "aborted" || value.status === "aborted")
return INVALID;
(key.status === "dirty" || value.status === "dirty") && status.dirty(), finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
});
} else {
let finalMap = new Map();
for (let pair of pairs) {
let key = pair.key, value = pair.value;
if (key.status === "aborted" || value.status === "aborted")
return INVALID;
(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) => new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
var ZodSet = class _ZodSet extends ZodType {
_parse(input) {
let { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
}), INVALID;
let def = this._def;
def.minSize !== null && ctx.data.size < def.minSize.value && (addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: !0,
exact: !1,
message: def.minSize.message
}), status.dirty()), def.maxSize !== null && ctx.data.size > def.maxSize.value && (addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: !0,
exact: !1,
message: def.maxSize.message
}), status.dirty());
let valueType = this._def.valueType;
function finalizeSet(elements2) {
let parsedSet = new Set();
for (let element of elements2) {
if (element.status === "aborted")
return INVALID;
element.status === "dirty" && status.dirty(), parsedSet.add(element.value);
}
return { status: status.value, value: parsedSet };
}
let elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
return ctx.common.async ? Promise.all(elements).then((elements2) => finalizeSet(elements2)) : 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) => 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) {
let { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
}), INVALID;
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x2) => !!x2),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x2) => !!x2),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
let params = { errorMap: ctx.common.contextualErrorMap }, fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
let me = this;
return OK(async function(...args) {
let error = new ZodError([]), parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
throw error.addIssue(makeArgsIssue(args, e)), error;
}), result = await Reflect.apply(fn, this, parsedArgs);
return await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
throw error.addIssue(makeReturnsIssue(result, e)), error;
});
});
} else {
let me = this;
return OK(function(...args) {
let parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success)
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
let result = Reflect.apply(fn, this, parsedArgs.data), 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 || ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
}, ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
let { ctx } = this._processInputParams(input);
return this._def.getter()._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
};
ZodLazy.create = (getter, params) => new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
var ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
}), INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => 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 {
constructor() {
super(...arguments), _ZodEnum_cache.set(this, void 0);
}
_parse(input) {
if (typeof input.data != "string") {
let ctx = this._getOrReturnCtx(input), expectedValues = this._def.values;
return addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
}), INVALID;
}
if (__classPrivateFieldGet(this, _ZodEnum_cache, "f") || __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"), !__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
let ctx = this._getOrReturnCtx(input), expectedValues = this._def.values;
return addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
}), INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
let enumValues = {};
for (let val of this._def.values)
enumValues[val] = val;
return enumValues;
}
get Values() {
let enumValues = {};
for (let val of this._def.values)
enumValues[val] = val;
return enumValues;
}
get Enum() {
let enumValues = {};
for (let 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_cache = new WeakMap();
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
constructor() {
super(...arguments), _ZodNativeEnum_cache.set(this, void 0);
}
_parse(input) {
let nativeEnumValues = util.getValidEnumValues(this._def.values), ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
let expectedValues = util.objectValues(nativeEnumValues);
return addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
}), INVALID;
}
if (__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f") || __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f"), !__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
let expectedValues = util.objectValues(nativeEnumValues);
return addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
}), INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
_ZodNativeEnum_cache = new WeakMap();
ZodNativeEnum.create = (values, params) => new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
var ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
let { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === !1)
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
}), INVALID;
let promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
})));
}
};
ZodPromise.create = (schema, params) => 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) {
let { status, ctx } = this._processInputParams(input), effect = this._def.effect || null, checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg), arg.fatal ? status.abort() : status.dirty();
},
get path() {
return ctx.path;
}
};
if (checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx), effect.type === "preprocess") {
let processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async)
return Promise.resolve(processed).then(async (processed2) => {
if (status.value === "aborted")
return INVALID;
let result = await this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
return result.status === "aborted" ? INVALID : result.status === "dirty" || status.value === "dirty" ? DIRTY(result.value) : result;
});
{
if (status.value === "aborted")
return INVALID;
let result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
return result.status === "aborted" ? INVALID : result.status === "dirty" || status.value === "dirty" ? DIRTY(result.value) : result;
}
}
if (effect.type === "refinement") {
let executeRefinement = (acc) => {
let 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 === !1) {
let inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
return inner.status === "aborted" ? INVALID : (inner.status === "dirty" && status.dirty(), executeRefinement(inner.value), { status: status.value, value: inner.value });
} else
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => inner.status === "aborted" ? INVALID : (inner.status === "dirty" && status.dirty(), executeRefinement(inner.value).then(() => ({ status: status.value, value: inner.value }))));
}
if (effect.type === "transform")
if (ctx.common.async === !1) {
let base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base))
return base;
let 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) => isValid(base) ? Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })) : base);
util.assertNever(effect);
}
};
ZodEffects.create = (schema, effect, params) => new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
ZodEffects.createWithPreprocess = (preprocess, schema, params) => new ZodEffects({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
var ZodOptional = class extends ZodType {
_parse(input) {
return this._getType(input) === ZodParsedType.undefined ? OK(void 0) : this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
var ZodNullable = class extends ZodType {
_parse(input) {
return this._getType(input) === ZodParsedType.null ? OK(null) : this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
var ZodDefault = class extends ZodType {
_parse(input) {
let { ctx } = this._processInputParams(input), data = ctx.data;
return ctx.parsedType === ZodParsedType.undefined && (data = this._def.defaultValue()), this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type, params) => 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) {
let { ctx } = this._processInputParams(input), newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
}, result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
return isAsync(result) ? result.then((result2) => ({
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
})) : {
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) => 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) {
let ctx = this._getOrReturnCtx(input);
return addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
}), INVALID;
}
return { status: "valid", value: input.data };
}
};
ZodNaN.create = (params) => new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
var BRAND = Symbol("zod_brand"), ZodBranded = class extends ZodType {
_parse(input) {
let { ctx } = this._processInputParams(input), data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
}, ZodPipeline = class _ZodPipeline extends ZodType {
_parse(input) {
let { status, ctx } = this._processInputParams(input);
if (ctx.common.async)
return (async () => {
let inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
return inResult.status === "aborted" ? INVALID : inResult.status === "dirty" ? (status.dirty(), DIRTY(inResult.value)) : this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
})();
{
let inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
return inResult.status === "aborted" ? INVALID : inResult.status === "dirty" ? (status.dirty(), {
status: "dirty",
value: inResult.value
}) : this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
static create(a, b2) {
return new _ZodPipeline({
in: a,
out: b2,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
}, ZodReadonly = class extends ZodType {
_parse(input) {
let result = this._def.innerType._parse(input), freeze = (data) => (isValid(data) && (data.value = Object.freeze(data.value)), data);
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
};
ZodReadonly.create = (type, params) => new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
function custom(check, params = {}, fatal) {
return check ? ZodAny.create().superRefine((data, ctx) => {
var _a, _b;
if (!check(data)) {
let p2 = typeof params == "function" ? params(data) : typeof params == "string" ? { message: params } : params, _fatal = (_b = (_a = p2.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : !0, p22 = typeof p2 == "string" ? { message: p2 } : p2;
ctx.addIssue({ code: "custom", ...p22, fatal: _fatal });
}
}) : ZodAny.create();
}
var late = {
object: ZodObject.lazycreate
}, ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2.ZodString = "ZodString", ZodFirstPartyTypeKind2.ZodNumber = "ZodNumber", ZodFirstPartyTypeKind2.ZodNaN = "ZodNaN", ZodFirstPartyTypeKind2.ZodBigInt = "ZodBigInt", ZodFirstPartyTypeKind2.ZodBoolean = "ZodBoolean", ZodFirstPartyTypeKind2.ZodDate = "ZodDate", ZodFirstPartyTypeKind2.ZodSymbol = "ZodSymbol", ZodFirstPartyTypeKind2.ZodUndefined = "ZodUndefined", ZodFirstPartyTypeKind2.ZodNull = "ZodNull", ZodFirstPartyTypeKind2.ZodAny = "ZodAny", ZodFirstPartyTypeKind2.ZodUnknown = "ZodUnknown", ZodFirstPartyTypeKind2.ZodNever = "ZodNever", ZodFirstPartyTypeKind2.ZodVoid = "ZodVoid", ZodFirstPartyTypeKind2.ZodArray = "ZodArray", ZodFirstPartyTypeKind2.ZodObject = "ZodObject", ZodFirstPartyTypeKind2.ZodUnion = "ZodUnion", ZodFirstPartyTypeKind2.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", ZodFirstPartyTypeKind2.ZodIntersection = "ZodIntersection", ZodFirstPartyTypeKind2.ZodTuple = "ZodTuple", ZodFirstPartyTypeKind2.ZodRecord = "ZodRecord", ZodFirstPartyTypeKind2.ZodMap = "ZodMap", ZodFirstPartyTypeKind2.ZodSet = "ZodSet", ZodFirstPartyTypeKind2.ZodFunction = "ZodFunction", ZodFirstPartyTypeKind2.ZodLazy = "ZodLazy", ZodFirstPartyTypeKind2.ZodLiteral = "ZodLiteral", ZodFirstPartyTypeKind2.ZodEnum = "ZodEnum", ZodFirstPartyTypeKind2.ZodEffects = "ZodEffects", ZodFirstPartyTypeKind2.ZodNativeEnum = "ZodNativeEnum", ZodFirstPartyTypeKind2.ZodOptional = "ZodOptional", ZodFirstPartyTypeKind2.ZodNullable = "ZodNullable", ZodFirstPartyTypeKind2.ZodDefault = "ZodDefault", ZodFirstPartyTypeKind2.ZodCatch = "ZodCatch", ZodFirstPartyTypeKind2.ZodPromise = "ZodPromise", ZodFirstPartyTypeKind2.ZodBranded = "ZodBranded", ZodFirstPartyTypeKind2.ZodPipeline = "ZodPipeline", ZodFirstPartyTypeKind2.ZodReadonly = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params), stringType = ZodString.create, numberType = ZodNumber.create, nanType = ZodNaN.create, bigIntType = ZodBigInt.create, booleanType = ZodBoolean.create, dateType = ZodDate.create, symbolType = ZodSymbol.create, undefinedType = ZodUndefined.create, nullType = ZodNull.create, anyType = ZodAny.create, unknownType = ZodUnknown.create, neverType = ZodNever.create, voidType = ZodVoid.create, arrayType = ZodArray.create, objectType = ZodObject.create, strictObjectType = ZodObject.strictCreate, unionType = ZodUnion.create, discriminatedUnionType = ZodDiscriminatedUnion.create, intersectionType = ZodIntersection.create, tupleType = ZodTuple.create, recordType = ZodRecord.create, mapType = ZodMap.create, setType = ZodSet.create, functionType = ZodFunction.create, lazyType = ZodLazy.create, literalType = ZodLiteral.create, enumType = ZodEnum.create, nativeEnumType = ZodNativeEnum.create, promiseType = ZodPromise.create, effectsType = ZodEffects.create, optionalType = ZodOptional.create, nullableType = ZodNullable.create, preprocessType = ZodEffects.createWithPreprocess, pipelineType = ZodPipeline.create, ostring = () => stringType().optional(), onumber = () => numberType().optional(), oboolean = () => booleanType().optional(), coerce = {
string: (arg) => ZodString.create({ ...arg, coerce: !0 }),
number: (arg) => ZodNumber.create({ ...arg, coerce: !0 }),
boolean: (arg) => ZodBoolean.create({
...arg,
coerce: !0
}),
bigint: (arg) => ZodBigInt.create({ ...arg, coerce: !0 }),
date: (arg) => ZodDate.create({ ...arg, coerce: !0 })
}, NEVER = INVALID, z = Object.freeze({
__proto__: null,
defaultErrorMap: errorMap,
setErrorMap,
getErrorMap,
makeIssue,
EMPTY_PATH,
addIssueToContext,
ParseStatus,
INVALID,
DIRTY,
OK,
isAborted,
isDirty,
isValid,
isAsync,
get util() {
return util;
},
get objectUtil() {
return objectUtil;
},
ZodParsedType,
getParsedType,
ZodType,
datetimeRegex,
ZodString,
ZodNumber,
ZodBigInt,
ZodBoolean,
ZodDate,
ZodSymbol,
ZodUndefined,
ZodNull,
ZodAny,
ZodUnknown,
ZodNever,
ZodVoid,
ZodArray,
ZodObject,
ZodUnion,
ZodDiscriminatedUnion,
ZodIntersection,
ZodTuple,
ZodRecord,
ZodMap,
ZodSet,
ZodFunction,
ZodLazy,
ZodLiteral,
ZodEnum,
ZodNativeEnum,
ZodPromise,
ZodEffects,
ZodTransformer: ZodEffects,
ZodOptional,
ZodNullable,
ZodDefault,
ZodCatch,
ZodNaN,
BRAND,
ZodBranded,
ZodPipeline,
ZodReadonly,
custom,
Schema: ZodType,
ZodSchema: ZodType,
late,
get ZodFirstPartyTypeKind() {
return ZodFirstPartyTypeKind;
},
coerce,
any: anyType,
array: arrayType,
bigint: bigIntType,
boolean: booleanType,
date: dateType,
discriminatedUnion: discriminatedUnionType,
effect: effectsType,
enum: enumType,
function: functionType,
instanceof: instanceOfType,
intersection: intersectionType,
lazy: lazyType,
literal: literalType,
map: mapType,
nan: nanType,
nativeEnum: nativeEnumType,
never: neverType,
null: nullType,
nullable: nullableType,
number: numberType,
object: objectType,
oboolean,
onumber,
optional: optionalType,
ostring,
pipeline: pipelineType,
preprocess: preprocessType,
promise: promiseType,
record: recordType,
set: setType,
strictObject: strictObjectType,
string: stringType,
symbol: symbolType,
transformer: effectsType,
tuple: tupleType,
undefined: undefinedType,
union: unionType,
unknown: unknownType,
void: voidType,
NEVER,
ZodIssueCode,
quotelessJson,
ZodError
});
var $ = Object.defineProperty, O = (l, i, e) => i in l ? $(l, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : l[i] = e, n = (l, i, e) => (O(l, typeof i != "symbol" ? i + "" : i, e), e), g = {
PI: Math.PI,
E: Math.E,
LN2: Math.LN2,
LN10: Math.LN10,
LOG2E: Math.LOG2E,
LOG10E: Math.LOG10E,
SQRT1_2: Math.SQRT1_2,
SQRT2: Math.SQRT2
}, p = class {
static throwIfNotNumber(i) {
if (typeof i == "string")
throw new Error("Strings are not allowed in math operations");
}
}, V = class {
static throwIfNotNumber(i) {
if (typeof i == "string")
throw new Error("Strings are not allowed in math operations");
}
}, h = class {
static createOperatorExpression(i, e, t) {
if (i === "^")
return new b(e, t);
if (["*", "/"].includes(i))
return new x(i, e, t);
if (["+", "-"].includes(i))
return new E(i, e, t);
if (["<", ">", "<=", ">=", "=", "!="].includes(i))
return new d(i, e, t);
throw new Error(`Unknown operator: ${i}`);
}
evaluate(i = {}) {
throw new Error("Empty Expression - Must be defined in child classes");
}
toString() {
return "";
}
}, S = class extends h {
constructor(e) {
if (super(), n(this, "innerExpression"), this.innerExpression = e, !(this.innerExpression instanceof h))
throw new Error("No inner expression given for bracket expression");
}
evaluate(e = {}) {
return this.innerExpression.evaluate(e);
}
toString() {
return `(${this.innerExpression.toString()})`;
}
}, w = class extends h {
constructor(e, t = "number") {
switch (super(), n(this, "value"), n(this, "type"), this.value = Number(e), t) {
case "number":
if (this.value = Number(e), isNaN(this.value))
throw new Error("Cannot parse number: " + e);
break;
case "string":
this.value = String(e);
break;
default:
throw new Error("Invalid value type: " + t);
}
this.type = t;
}
evaluate() {
return this.value;
}
toString() {
switch (this.type) {
case "number":
return String(this.value);
case "string":
return '"' + this.value + '"';
default:
throw new Error("Invalid type");
}
}
}, E = class extends h {
constructor(e, t, r) {
if (super(), n(this, "operator"), n(this, "left"), n(this, "right"), !["+", "-"].includes(e))
throw new Error(`Operator not allowed in Plus/Minus expression: ${e}`);
this.operator = e, this.left = t, this.right = r;
}
evaluate(e = {}) {
let t = this.left.evaluate(e), r = this.right.evaluate(e);
if (p.throwIfNotNumber(t), p.throwIfNotNumber(r), this.operator === "+")
return Number(t) + Number(r);
if (this.operator === "-")
return Number(t) - Number(r);
throw new Error("Unknown operator for PlusMinus expression");
}
toString() {
return `${this.left.toString()} ${this.operator} ${this.right.toString()}`;
}
}, x = class extends h {
constructor(e, t, r) {
if (super(), n(this, "operator"), n(this, "left"), n(this, "right"), !["*", "/"].includes(e))
throw new Error(`Operator not allowed in Multiply/Division expression: ${e}`);
this.operator = e, this.left = t, this.right = r;
}
evaluate(e = {}) {
let t = this.left.evaluate(e), r = this.right.evaluate(e);
if (p.throwIfNotNumber(t), p.throwIfNotNumber(r), this.operator === "*")
return Number(t) * Number(r);
if (this.operator === "/")
return Number(t) / Number(r);
throw new Error("Unknown operator for MultDiv expression");
}
toString() {
return `${this.left.toString()} ${this.operator} ${this.right.toString()}`;
}
}, b = class extends h {
constructor(e, t) {
super(), n(this, "base"), n(this, "exponent"), this.base = e, this.exponent = t;
}
evaluate(e = {}) {
let t = this.base.evaluate(e), r = this.exponent.evaluate(e);
return p.throwIfNotNumber(t), p.throwIfNotNumber(r), Math.pow(Number(t), Number(r));
}
toString() {
return `${this.base.toString()}^${this.exponent.toString()}`;
}
}, d = class extends h {
constructor(e, t, r) {
if (super(), n(this, "operator"), n(this, "left"), n(this, "right"), !["<", ">", "<=", ">=", "=", "!="].includes(e))
throw new Error(`Operator not allowed in Logical expression: ${e}`);
this.operator = e, this.left = t, this.right = r;
}
evaluate(e = {}) {
let t = this.left.evaluate(e), r = this.right.evaluate(e);
switch (this.operator) {
case "<":
return t < r ? 1 : 0;
case ">":
return t > r ? 1 : 0;
case "<=":
return t <= r ? 1 : 0;
case ">=":
return t >= r ? 1 : 0;
case "=":
return t === r ? 1 : 0;
case "!=":
return t !== r ? 1 : 0;
}
throw new Error("Unknown operator for Logical expression");
}
toString() {
return `${this.left.toString()} ${this.operator} ${this.right.toString()}`;
}
}, k = class extends h {
constructor(e, t, r = null) {
super(), n(this, "fn"), n(this, "varPath"), n(this, "argumentExpressions"), n(this, "formulaObject"), n(this, "blacklisted"), this.fn = e != null ? e : "", this.varPath = this.fn.split("."), this.argumentExpressions = t || [], this.formulaObject = r, this.blacklisted = void 0;
}
evaluate(e = {}) {
var a;
e = e || {};
let t = this.argumentExpressions.map((s) => s.evaluate(e));
try {
let s = m(e, this.varPath, this.fn);
if (s instanceof Function)
return s.apply(this, t);
} catch {
}
let r;
try {
r = m((a = this.formulaObject) != null ? a : {}, this.varPath, this.fn);
} catch {
}
if (this.formulaObject && r instanceof Function) {
if (this.isBlacklisted())
throw new Error("Blacklisted function called: " + this.fn);
return r.apply(this.formulaObject, t);
}
try {
let s = m(Math, this.varPath, this.fn);
if (s instanceof Function)
return t.forEach((o) => {
V.throwIfNotNumber(o);
}), s.apply(this, t);
} catch {
}
throw new Error("Function not found: " + this.fn);
}
toString() {
return `${this.fn}(${this.argumentExpressions.map((e) => e.toString()).join(", ")})`;
}
isBlacklisted() {
return this.blacklisted === void 0 && (this.blacklisted = N.functionBlacklist.includes(
this.formulaObject ? this.formulaObject[this.fn] : null
)), this.blacklisted;
}
};
function m(l, i, e) {
let t = l;
for (let r of i) {
if (typeof t != "object")
throw new Error(`Cannot evaluate ${r}, property not found (from path ${e})`);
if (t[r] === void 0)
throw new Error(`Cannot evaluate ${r}, property not found (from path ${e})`);
t = t[r];
}
if (typeof t == "object")
throw new Error("Invalid value");
return t;
}
var y = class extends h {
constructor(e, t = null) {
super(), n(this, "fullPath"), n(this, "varPath"), n(this, "formulaObject"), this.formulaObject = t, this.fullPath = e, this.varPath = e.split(".");
}
evaluate(e = {}) {
var r;
let t;
try {
t = m(e, this.varPath, this.fullPath);
} catch {
}
if (t === void 0 && (t = m((r = this.formulaObject) != null ? r : {}, this.varPath, this.fullPath)), typeof t == "function" || typeof t == "object")
throw new Error(`Cannot use ${this.fullPath} as value: It contains a non-numerical value.`);
return t;
}
toString() {
return `${this.varPath.join(".")}`;
}
}, u = class u2 {
constructor(i, e = {}) {
n(this, "formulaExpression"), n(this, "options"), n(this, "formulaStr"), n(this, "_variables"), n(this, "_memory"), this.formulaExpression = null, this.options = { memoization: !1, ...e }, this.formulaStr = "", this._variables = [], this._memory = {}, this.setFormula(i);
}
setFormula(i) {
return i && (this.formulaExpression = null, this._variables = [], this._memory = {}, this.formulaStr = i, this.formulaExpression = this.parse(i)), this;
}
enableMemoization() {
this.options.memoization = !0;
}
disableMemoization() {
this.options.memoization = !1, this._memory = {};
}
splitFunctionParams(i) {
let e = 0, t = "", r = [];
for (let a of i.split(""))
if (a === "," && e === 0)
r.push(t), t = "";
else if (a === "(")
e++, t += a;
else if (a === ")") {
if (e--, t += a, e < 0)
throw new Error("ERROR: Too many closing parentheses!");
} else
t += a;
if (e !== 0)
throw new Error("ERROR: Too many opening parentheses!");
return t.length > 0 && r.push(t), r;
}
cleanupInputFormula(i) {
let e = [];
return i.split('"').forEach((r, a) => {
a % 2 === 0 && (r = r.replace(/[\s]+/g, ""), Object.keys(g).forEach((s) => {
r = r.replace(new RegExp(`\\b${s}\\b`, "g"), `[${s}]`);
})), e.push(r);
}), e.join('"');
}
parse(i) {
return i = this.cleanupInputFormula(i), this._do_parse(i);
}
_do_parse(i) {
let e = i.length - 1, t = 0, r = "initial", a = [], s = "", o = "", v = null, f = 0, c = "";
for (; t <= e; ) {
switch (r) {
case "initial":
if (s = i.charAt(t), s.match(/[0-9.]/))
r = "within-nr", o = "", t--;
else if (this.isOperator(s)) {
if (s === "-" && (a.length === 0 || this.isOperatorExpr(a[a.length - 1]))) {
r = "within-nr", o = "-";
break;
}
if (t === e || this.isOperatorExpr(a[a.length - 1])) {
r = "invalid";
break;
} else
a.push(
h.createOperatorExpression(s, new h(), new h())
), r = "initial";
} else if ([">", "<", "=", "!"].includes(s))
if (t === e) {
r = "invalid";
break;
} else
r = "within-logical-operator", o = s;
else
s === "(" ? (r = "within-parentheses", o = "", f = 0) : s === "[" ? (r = "within-named-var", o = "") : s.match(/["']/) ? (r = "within-string", c = s, o = "") : s.match(/[a-zA-Z]/) && (t < e && i.charAt(t + 1).match(/[a-zA-Z0-9_.]/) ? (o = s, r = "within-func") : (a.length > 0 && a[a.length - 1] instanceof w && a.push(
h.createOperatorExpression("*", new h(), new h())
), a.push(new y(s, this)), this.registerVariable(s), r = "initial", o = ""));
break;
case "within-nr":
s = i.charAt(t), s.match(/[0-9.]/) ? (o += s, t === e && (a.push(new w(o)), r = "initial")) : (o === "-" && (o = "-1"), a.push(new w(o)), o = "", r = "initial", t--);
break;
case "within-func":
if (s = i.charAt(t), s.match(/[a-zA-Z0-9_.]/))
o += s;
else if (s === "(")
v = o, o = "", f = 0, r = "within-func-parentheses";
else
throw new Error("Wrong character for function at position " + t);
break;
case "within-named-var":
if (s = i.charAt(t), s === "]")
a.push(new y(o, this)), this.registerVariable(o), o = "", r = "initial";
else if (s.match(/[a-zA-Z0-9_.]/))
o += s;
else
throw new Error("Character not allowed within named variable: " + s);
break;
case "within-string":
s = i.charAt(t), s === c ? (a.push(new w(o, "string")), o = "", r = "initial", c = "") : o += s;
break;
case "within-parentheses":
case "within-func-parentheses":
if (s = i.charAt(t), c)
s === c && (c = ""), o += s;
else if (s === ")")
if (f <= 0) {
if (r === "within-parentheses")
a.push(new S(this._do_parse(o)));
else if (r === "within-func-parentheses") {
let M = this.splitFunctionParams(o).map((P) => this._do_parse(P));
a.push(new k(v, M, this)), v = null;
}
r = "initial";
} else
f--, o += s;
else
s === "(" ? (f++, o += s) : (s.match(/["']/) && (c = s), o += s);
break;
case "within-logical-operator":
s = i.charAt(t), s === "=" && (o += s, t++), a.push(h.createOperatorExpression(o, new h(), new h())), o = "", r = "initial", t--;
break;
}
t++;
}
if (r !== "initial")
throw new Error("Could not parse formula: Syntax error.");
return this.buildExpressionTree(a);
}
buildExpressionTree(i) {
if (i.length < 1)
throw new Error("No expression given!");
let e = [...i], t = 0, r = null;
for (; t < e.length; )
if (r = e[t], r instanceof b) {
if (t === 0 || t === e.length - 1)
throw new Error("Wrong operator position!");
r.base = e[t - 1], r.exponent = e[t + 1], e[t - 1] = r, e.splice(t, 2);
} else
t++;
for (t = 0, r = null; t < e.length; )
if (r = e[t], r instanceof x) {
if (t === 0 || t === e.length - 1)
throw new Error("Wrong operator position!");
r.left = e[t - 1], r.right = e[t + 1], e[t - 1] = r, e.splice(t, 2);
} else
t++;
for (t = 0, r = null; t < e.length; )
if (r = e[t], r instanceof E) {
if (t === 0 || t === e.length - 1)
throw new Error("Wrong operator position!");
r.left = e[t - 1], r.right = e[t + 1], e[t - 1] = r, e.splice(t, 2);
} else
t++;
for (t = 0, r = null; t < e.length; )
if (r = e[t], r instanceof d) {
if (t === 0 || t === e.length - 1)
throw new Error("Wrong operator position!");
r.left = e[t - 1], r.right = e[t + 1], e[t - 1] = r, e.splice(t, 2);
} else
t++;
if (e.length !== 1)
throw new Error("Could not parse formula: incorrect syntax?");
return e[0];
}
isOperator(i) {
return typeof i == "string" && i.match(/[+\-*/^]/);
}
isOperatorExpr(i) {
return i instanceof E || i instanceof x || i instanceof b || i instanceof d;
}
registerVariable(i) {
this._variables.indexOf(i) < 0 && this._variables.push(i);
}
getVariables() {
return this._variables;
}
evaluate(i) {
if (i instanceof Array)
return i.map((t) => this.evaluate(t));
let e = this.getExpression();
if (!(e instanceof h))
throw new Error("No expression set: Did you init the object with a Formula?");
if (this.options.memoization) {
let t = this.resultFromMemory(i);
return t !== null || (t = e.evaluate({ ...g, ...i }), this.storeInMemory(i, t)), t;
}
return e.evaluate({ ...g, ...i });
}
hashValues(i) {
return JSON.stringify(i);
}
resultFromMemory(i) {
let e = this.hashValues(i), t = this._memory[e];
return t !== void 0 ? t : null;
}
storeInMemory(i, e) {
this._memory[this.hashValues(i)] = e;
}
getExpression() {
return this.formulaExpression;
}
getExpressionString() {
return this.formulaExpression ? this.formulaExpression.toString() : "";
}
static calc(i, e = null, t = {}) {
return e = e != null ? e : {}, new u2(i, t).evaluate(e);
}
};
n(u, "Expression", h), n(u, "BracketExpression", S), n(u, "PowerExpression", b), n(u, "MultDivExpression", x), n(u, "PlusMinusExpression", E), n(u, "LogicalExpression", d), n(u, "ValueExpression", w), n(u, "VariableExpression", y), n(u, "FunctionExpression", k), n(u, "MATH_CONSTANTS", g),
n(u, "functionBlacklist", Object.getOwnPropertyNames(u.prototype).filter((i) => u.prototype[i] instanceof Function).map((i) => u.prototype[i]));
var N = u;
var TABLE_CHART_CONFIG_DIALOG = ["Enter chart type to create:", {
inputs: [
{
label: "Chart type",
type: "select",
options: [
{ label: "Bar", value: "bar" },
{ label: "Line", value: "line" },
{ label: "Area", value: "area" },
{ label: "Pie", value: "pie" },
{ label: "Doughnut", value: "doughnut" },
{ label: "Polar Area", value: "polarArea" }
],
value: "bar"
},
{
label: "Data Source",
type: "note",
value: ""
},
{
label: "Chart Title (optional)",
type: "text",
value: ""
},
{
label: "Table Index in Note",
type: "text",
value: "0"
},
{
label: "Horizontal (category) axis labels direction",
type: "select",
options: [
{ label: "Column", value: "column" },
{ label: "Row", value: "row" }
],
value: "row"
},
{
label: "Start from zero?",
type: "checkbox",
value: !1
},
{
label: "Chart aspect ratio size",
type: "select",
options: [
{ label: "1 (not recommended)", value: "1" },
{ label: "2", value: "2" },
{ label: "3", value: "3" }
],
value: "2"
}
]
}], FORMULA_CHART_CONFIG_DIALOG = ["Enter chart type to create:", {
inputs: [
{
label: "Chart type",
type: "select",
options: [
{ label: "Line", value: "line" },
{ label: "Area", value: "area" }
],
value: "line"
},
{
label: "Chart Title (optional)",
type: "text",
value: ""
},
{
label: "Formula f(x)=",
type: "text",
value: "2x + 1"
},
{
label: "minX",
type: "text",
value: "1"
},
{
label: "maxX",
type: "text",
value: "20"
},
{
label: "stepX",
type: "text",
value: "1"
},
{
label: "Chart aspect ratio size",
type: "select",
options: [
{ label: "1 (not recommended)", value: "1" },
{ label: "2", value: "2" },
{ label: "3", value: "3" }
],
value: "2"
}
]
}], chartTypeSchema = z.enum(["bar", "line", "area", "pie", "doughnut", "polarArea"]), formulaChartTypeSchema = z.enum(["line", "area"]), baseChartSchema = z.object({
RANDOM_UUID: z.string(),
DATA_SOURCE: z.enum(["note", "formula"]),
CHART_TITLE: z.string(),
CHART_ASPECT_RATIO_SIZE: z.string().refine((val) => !isNaN(val) && !isNaN(parseFloat(val)), {
message: "Chart size must be a number"
})
}), noteChartSchema = baseChartSchema.extend({
CHART_TYPE: chartTypeSchema,
DATA_SOURCE_NOTE_UUID: z.string(),
TABLE_INDEX_IN_NOTE: z.string().refine((val) => {
let parsed = parseInt(val, 10);
return !isNaN(parsed) && Number.isInteger(parsed) && parsed >= 0 && parsed <= 100;
}, {
message: "Table Index must be an integer between 0 and 100 (inclusive)"
}),
HORIZONTAL_AXIS_LABEL_DIRECTION: z.enum(["column", "row"]),
START_FROM_ZERO: z.boolean()
}), ADDITIONAL_MATH_CONSTANTS = {
pi: Math.PI,
e: Math.E,
ln2: Math.LN2,
ln10: Math.LN10,
log2e: Math.LOG2E,
log10e: Math.LOG10E
}, formulaChartSchema = baseChartSchema.extend({
CHART_TYPE: formulaChartTypeSchema,
DATA_SOURCE_FORMULA_F: z.string().refine((val) => {
try {
return new N(val).evaluate({ x: 1, ...ADDITIONAL_MATH_CONSTANTS }), !0;
} catch {
return !1;
}
}, "Invalid formula"),
MIN_X: z.string().refine((val) => !isNaN(val) && !isNaN(parseFloat(val)), {
message: "minX must be a number"
}),
MAX_X: z.string().refine((val) => !isNaN(val) && !isNaN(parseFloat(val)), {
message: "maxX must be a number"
}),
STEP_X: z.string().refine((val) => !isNaN(val) && !isNaN(parseFloat(val)), {
message: "stepX must be a number"
})
});
var addScriptToHtmlString = (htmlString, scriptContent) => {
let doc = new DOMParser().parseFromString(htmlString, "text/html"), script = doc.createElement("script");
script.textContent = scriptContent;
let head = doc.head;
return head.firstChild ? head.insertBefore(script, head.firstChild) : head.appendChild(script), doc.documentElement.outerHTML.replaceAll("\\x3Cscript>", () => "<script>");
}, addWindowVariableToHtmlString = (htmlString, variableName, variableValue) => {
let scriptContent = `window.${variableName} = ${JSON.stringify(variableValue)};`;
return addScriptToHtmlString(htmlString, scriptContent);
};
var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis, freeGlobal_default = freeGlobal;
var freeSelf = typeof self == "object" && self && self.Object === Object && self, root = freeGlobal_default || freeSelf || Function("return this")(), root_default = root;
var Symbol2 = root_default.Symbol, Symbol_default = Symbol2;
var objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, nativeObjectToString = objectProto.toString, symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = !0;
} catch {
}
var result = nativeObjectToString.call(value);
return unmasked && (isOwn ? value[symToStringTag] = tag : delete value[symToStringTag]), result;
}
var getRawTag_default = getRawTag;
var objectProto2 = Object.prototype, nativeObjectToString2 = objectProto2.toString;
function objectToString(value) {
return nativeObjectToString2.call(value);
}
var objectToString_default = objectToString;
var nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
function baseGetTag(value) {
return value == null ? value === void 0 ? undefinedTag : nullTag : symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
}
var baseGetTag_default = baseGetTag;
function isObjectLike(value) {
return value != null && typeof value == "object";
}
var isObjectLike_default = isObjectLike;
var isArray = Array.isArray, isArray_default = isArray;
function isObject(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
var isObject_default = isObject;
var asyncTag = "[object AsyncFunction]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
function isFunction(value) {
if (!isObject_default(value))
return !1;
var tag = baseGetTag_default(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_default = isFunction;
var coreJsData = root_default["__core-js_shared__"], coreJsData_default = coreJsData;
var maskSrcKey = function() {
var uid = /[^.]+$/.exec(coreJsData_default && coreJsData_default.keys && coreJsData_default.keys.IE_PROTO || "");
return uid ? "Symbol(src)_1." + uid : "";
}();
function isMasked(func) {
return !!maskSrcKey && maskSrcKey in func;
}
var isMasked_default = isMasked;
var funcProto = Function.prototype, funcToString = funcProto.toString;
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch {
}
try {
return func + "";
} catch {
}
}
return "";
}
var toSource_default = toSource;
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reIsHostCtor = /^\[object .+?Constructor\]$/, funcProto2 = Function.prototype, objectProto3 = Object.prototype, funcToString2 = funcProto2.toString, hasOwnProperty2 = objectProto3.hasOwnProperty, reIsNative = RegExp(
"^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
);
function baseIsNative(value) {
if (!isObject_default(value) || isMasked_default(value))
return !1;
var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource_default(value));
}
var baseIsNative_default = baseIsNative;
function getValue(object, key) {
return object == null ? void 0 : object[key];
}
var getValue_default = getValue;
function getNative(object, key) {
var value = getValue_default(object, key);
return baseIsNative_default(value) ? value : void 0;
}
var getNative_default = getNative;
var WeakMap2 = getNative_default(root_default, "WeakMap"), WeakMap_default = WeakMap2;
var objectCreate = Object.create, baseCreate = function() {
function object() {
}
return function(proto) {
if (!isObject_default(proto))
return {};
if (objectCreate)
return objectCreate(proto);
object.prototype = proto;
var result = new object();
return object.prototype = void 0, result;
};
}(), baseCreate_default = baseCreate;
function copyArray(source, array) {
var index = -1, length = source.length;
for (array || (array = Array(length)); ++index < length; )
array[index] = source[index];
return array;
}
var copyArray_default = copyArray;
var defineProperty = function() {
try {
var func = getNative_default(Object, "defineProperty");
return func({}, "", {}), func;
} catch {
}
}(), defineProperty_default = defineProperty;
function arrayEach(array, iteratee) {
for (var index = -1, length = array == null ? 0 : array.length; ++index < length && iteratee(array[index], index, array) !== !1; )
;
return array;
}
var arrayEach_default = arrayEach;
var MAX_SAFE_INTEGER = 9007199254740991, reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length) {
var type = typeof value;
return length = length == null ? MAX_SAFE_INTEGER : length, !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}
var isIndex_default = isIndex;
function baseAssignValue(object, key, value) {
key == "__proto__" && defineProperty_default ? defineProperty_default(object, key, {
configurable: !0,
enumerable: !0,
value,
writable: !0
}) : object[key] = value;
}
var baseAssignValue_default = baseAssignValue;
function eq(value, other) {
return value === other || value !== value && other !== other;
}
var eq_default = eq;
var objectProto4 = Object.prototype, hasOwnProperty3 = objectProto4.hasOwnProperty;
function assignValue(object, key, value) {
var objValue = object[key];
(!(hasOwnProperty3.call(object, key) && eq_default(objValue, value)) || value === void 0 && !(key in object)) && baseAssignValue_default(object, key, value);
}
var assignValue_default = assignValue;
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
for (var index = -1, length = props.length; ++index < length; ) {
var key = props[index], newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
newValue === void 0 && (newValue = source[key]), isNew ? baseAssignValue_default(object, key, newValue) : assignValue_default(object, key, newValue);
}
return object;
}
var copyObject_default = copyObject;
var MAX_SAFE_INTEGER2 = 9007199254740991;
function isLength(value) {
return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
}
var isLength_default = isLength;
function isArrayLike(value) {
return value != null && isLength_default(value.length) && !isFunction_default(value);
}
var isArrayLike_default = isArrayLike;
var objectProto5 = Object.prototype;
function isPrototype(value) {
var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto5;
return value === proto;
}
var isPrototype_default = isPrototype;
function baseTimes(n2, iteratee) {
for (var index = -1, result = Array(n2); ++index < n2; )
result[index] = iteratee(index);
return result;
}
var baseTimes_default = baseTimes;
var argsTag = "[object Arguments]";
function baseIsArguments(value) {
return isObjectLike_default(value) && baseGetTag_default(value) == argsTag;
}
var baseIsArguments_default = baseIsArguments;
var objectProto6 = Object.prototype, hasOwnProperty4 = objectProto6.hasOwnProperty, propertyIsEnumerable = objectProto6.propertyIsEnumerable, isArguments = baseIsArguments_default( function() {
return arguments;
}()) ? baseIsArguments_default : function(value) {
return isObjectLike_default(value) && hasOwnProperty4.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
}, isArguments_default = isArguments;
function stubFalse() {
return !1;
}
var stubFalse_default = stubFalse;
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports, Buffer = moduleExports ? root_default.Buffer : void 0, nativeIsBuffer = Buffer ? Buffer.isBuffer : void 0, isBuffer = nativeIsBuffer || stubFalse_default, isBuffer_default = isBuffer;
var argsTag2 = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag2 = "[object Function]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", weakMapTag = "[object WeakMap]", arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]", typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = !0;
typedArrayTags[argsTag2] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag2] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = !1;
function baseIsTypedArray(value) {
return isObjectLike_default(value) && isLength_default(value.length) && !!typedArrayTags[baseGetTag_default(value)];
}
var baseIsTypedArray_default = baseIsTypedArray;
function baseUnary(func) {
return function(value) {
return func(value);
};
}
var baseUnary_default = baseUnary;
var freeExports2 = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule2 = freeExports2 && typeof module == "object" && module && !module.nodeType && module, moduleExports2 = freeModule2 && freeModule2.exports === freeExports2, freeProcess = moduleExports2 && freeGlobal_default.process, nodeUtil = function() {
try {
var types = freeModule2 && freeModule2.require && freeModule2.require("util").types;
return types || freeProcess && freeProcess.binding && freeProcess.binding("util");
} catch {
}
}(), nodeUtil_default = nodeUtil;
var nodeIsTypedArray = nodeUtil_default && nodeUtil_default.isTypedArray, isTypedArray = nodeIsTypedArray ? baseUnary_default(nodeIsTypedArray) : baseIsTypedArray_default, isTypedArray_default = isTypedArray;
var objectProto7 = Object.prototype, hasOwnProperty5 = objectProto7.hasOwnProperty;
function arrayLikeKeys(value, inherited) {
var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes_default(value.length, String) : [], length = result.length;
for (var key in value)
(inherited || hasOwnProperty5.call(value, key)) && !(skipIndexes &&
(key == "length" ||
isBuff && (key == "offset" || key == "parent") ||
isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") ||
isIndex_default(key, length))) && result.push(key);
return result;
}
var arrayLikeKeys_default = arrayLikeKeys;
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
var overArg_default = overArg;
var nativeKeys = overArg_default(Object.keys, Object), nativeKeys_default = nativeKeys;
var objectProto8 = Object.prototype, hasOwnProperty6 = objectProto8.hasOwnProperty;
function baseKeys(object) {
if (!isPrototype_default(object))
return nativeKeys_default(object);
var result = [];
for (var key in Object(object))
hasOwnProperty6.call(object, key) && key != "constructor" && result.push(key);
return result;
}
var baseKeys_default = baseKeys;
function keys(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object) : baseKeys_default(object);
}
var keys_default = keys;
function nativeKeysIn(object) {
var result = [];
if (object != null)
for (var key in Object(object))
result.push(key);
return result;
}
var nativeKeysIn_default = nativeKeysIn;
var objectProto9 = Object.prototype, hasOwnProperty7 = objectProto9.hasOwnProperty;
function baseKeysIn(object) {
if (!isObject_default(object))
return nativeKeysIn_default(object);
var isProto = isPrototype_default(object), result = [];
for (var key in object)
key == "constructor" && (isProto || !hasOwnProperty7.call(object, key)) || result.push(key);
return result;
}
var baseKeysIn_default = baseKeysIn;
function keysIn(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object, !0) : baseKeysIn_default(object);
}
var keysIn_default = keysIn;
var nativeCreate = getNative_default(Object, "create"), nativeCreate_default = nativeCreate;
function hashClear() {
this.__data__ = nativeCreate_default ? nativeCreate_default(null) : {}, this.size = 0;
}
var hashClear_default = hashClear;
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
return this.size -= result ? 1 : 0, result;
}
var hashDelete_default = hashDelete;
var HASH_UNDEFINED = "__lodash_hash_undefined__", objectProto10 = Object.prototype, hasOwnProperty8 = objectProto10.hasOwnProperty;
function hashGet(key) {
var data = this.__data__;
if (nativeCreate_default) {
var result = data[key];
return result === HASH_UNDEFINED ? void 0 : result;
}
return hasOwnProperty8.call(data, key) ? data[key] : void 0;
}
var hashGet_default = hashGet;
var objectProto11 = Object.prototype, hasOwnProperty9 = objectProto11.hasOwnProperty;
function hashHas(key) {
var data = this.__data__;
return nativeCreate_default ? data[key] !== void 0 : hasOwnProperty9.call(data, key);
}
var hashHas_default = hashHas;
var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
function hashSet(key, value) {
var data = this.__data__;
return this.size += this.has(key) ? 0 : 1, data[key] = nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value, this;
}
var hashSet_default = hashSet;
function Hash(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index < length; ) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
Hash.prototype.clear = hashClear_default;
Hash.prototype.delete = hashDelete_default;
Hash.prototype.get = hashGet_default;
Hash.prototype.has = hashHas_default;
Hash.prototype.set = hashSet_default;
var Hash_default = Hash;
function listCacheClear() {
this.__data__ = [], this.size = 0;
}
var listCacheClear_default = listCacheClear;
function assocIndexOf(array, key) {
for (var length = array.length; length--; )
if (eq_default(array[length][0], key))
return length;
return -1;
}
var assocIndexOf_default = assocIndexOf;
var arrayProto = Array.prototype, splice = arrayProto.splice;
function listCacheDelete(key) {
var data = this.__data__, index = assocIndexOf_default(data, key);
if (index < 0)
return !1;
var lastIndex = data.length - 1;
return index == lastIndex ? data.pop() : splice.call(data, index, 1), --this.size, !0;
}
var listCacheDelete_default = listCacheDelete;
function listCacheGet(key) {
var data = this.__data__, index = assocIndexOf_default(data, key);
return index < 0 ? void 0 : data[index][1];
}
var listCacheGet_default = listCacheGet;
function listCacheHas(key) {
return assocIndexOf_default(this.__data__, key) > -1;
}
var listCacheHas_default = listCacheHas;
function listCacheSet(key, value) {
var data = this.__data__, index = assocIndexOf_default(data, key);
return index < 0 ? (++this.size, data.push([key, value])) : data[index][1] = value, this;
}
var listCacheSet_default = listCacheSet;
function ListCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index < length; ) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
ListCache.prototype.clear = listCacheClear_default;
ListCache.prototype.delete = listCacheDelete_default;
ListCache.prototype.get = listCacheGet_default;
ListCache.prototype.has = listCacheHas_default;
ListCache.prototype.set = listCacheSet_default;
var ListCache_default = ListCache;
var Map2 = getNative_default(root_default, "Map"), Map_default = Map2;
function mapCacheClear() {
this.size = 0, this.__data__ = {
hash: new Hash_default(),
map: new (Map_default || ListCache_default)(),
string: new Hash_default()
};
}
var mapCacheClear_default = mapCacheClear;
function isKeyable(value) {
var type = typeof value;
return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
var isKeyable_default = isKeyable;
function getMapData(map, key) {
var data = map.__data__;
return isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
var getMapData_default = getMapData;
function mapCacheDelete(key) {
var result = getMapData_default(this, key).delete(key);
return this.size -= result ? 1 : 0, result;
}
var mapCacheDelete_default = mapCacheDelete;
function mapCacheGet(key) {
return getMapData_default(this, key).get(key);
}
var mapCacheGet_default = mapCacheGet;
function mapCacheHas(key) {
return getMapData_default(this, key).has(key);
}
var mapCacheHas_default = mapCacheHas;
function mapCacheSet(key, value) {
var data = getMapData_default(this, key), size = data.size;
return data.set(key, value), this.size += data.size == size ? 0 : 1, this;
}
var mapCacheSet_default = mapCacheSet;
function MapCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
for (this.clear(); ++index < length; ) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
MapCache.prototype.clear = mapCacheClear_default;
MapCache.prototype.delete = mapCacheDelete_default;
MapCache.prototype.get = mapCacheGet_default;
MapCache.prototype.has = mapCacheHas_default;
MapCache.prototype.set = mapCacheSet_default;
var MapCache_default = MapCache;
function arrayPush(array, values) {
for (var index = -1, length = values.length, offset = array.length; ++index < length; )
array[offset + index] = values[index];
return array;
}
var arrayPush_default = arrayPush;
var getPrototype = overArg_default(Object.getPrototypeOf, Object), getPrototype_default = getPrototype;
function stackClear() {
this.__data__ = new ListCache_default(), this.size = 0;
}
var stackClear_default = stackClear;
function stackDelete(key) {
var data = this.__data__, result = data.delete(key);
return this.size = data.size, result;
}
var stackDelete_default = stackDelete;
function stackGet(key) {
return this.__data__.get(key);
}
var stackGet_default = stackGet;
function stackHas(key) {
return this.__data__.has(key);
}
var stackHas_default = stackHas;
var LARGE_ARRAY_SIZE = 200;
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache_default) {
var pairs = data.__data__;
if (!Map_default || pairs.length < LARGE_ARRAY_SIZE - 1)
return pairs.push([key, value]), this.size = ++data.size, this;
data = this.__data__ = new MapCache_default(pairs);
}
return data.set(key, value), this.size = data.size, this;
}
var stackSet_default = stackSet;
function Stack(entries) {
var data = this.__data__ = new ListCache_default(entries);
this.size = data.size;
}
Stack.prototype.clear = stackClear_default;
Stack.prototype.delete = stackDelete_default;
Stack.prototype.get = stackGet_default;
Stack.prototype.has = stackHas_default;
Stack.prototype.set = stackSet_default;
var Stack_default = Stack;
function baseAssign(object, source) {
return object && copyObject_default(source, keys_default(source), object);
}
var baseAssign_default = baseAssign;
function baseAssignIn(object, source) {
return object && copyObject_default(source, keysIn_default(source), object);
}
var baseAssignIn_default = baseAssignIn;
var freeExports3 = typeof exports == "object" && exports && !exports.nodeType && exports, freeModule3 = freeExports3 && typeof module == "object" && module && !module.nodeType && module, moduleExports3 = freeModule3 && freeModule3.exports === freeExports3, Buffer2 = moduleExports3 ? root_default.Buffer : void 0, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : void 0;
function cloneBuffer(buffer, isDeep) {
if (isDeep)
return buffer.slice();
var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
return buffer.copy(result), result;
}
var cloneBuffer_default = cloneBuffer;
function arrayFilter(array, predicate) {
for (var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; ++index < length; ) {
var value = array[index];
predicate(value, index, array) && (result[resIndex++] = value);
}
return result;
}
var arrayFilter_default = arrayFilter;
function stubArray() {
return [];
}
var stubArray_default = stubArray;
var objectProto12 = Object.prototype, propertyIsEnumerable2 = objectProto12.propertyIsEnumerable, nativeGetSymbols = Object.getOwnPropertySymbols, getSymbols = nativeGetSymbols ? function(object) {
return object == null ? [] : (object = Object(object), arrayFilter_default(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable2.call(object, symbol);
}));
} : stubArray_default, getSymbols_default = getSymbols;
function copySymbols(source, object) {
return copyObject_default(source, getSymbols_default(source), object);
}
var copySymbols_default = copySymbols;
var nativeGetSymbols2 = Object.getOwnPropertySymbols, getSymbolsIn = nativeGetSymbols2 ? function(object) {
for (var result = []; object; )
arrayPush_default(result, getSymbols_default(object)), object = getPrototype_default(object);
return result;
} : stubArray_default, getSymbolsIn_default = getSymbolsIn;
function copySymbolsIn(source, object) {
return copyObject_default(source, getSymbolsIn_default(source), object);
}
var copySymbolsIn_default = copySymbolsIn;
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray_default(object) ? result : arrayPush_default(result, symbolsFunc(object));
}
var baseGetAllKeys_default = baseGetAllKeys;
function getAllKeys(object) {
return baseGetAllKeys_default(object, keys_default, getSymbols_default);
}
var getAllKeys_default = getAllKeys;
function getAllKeysIn(object) {
return baseGetAllKeys_default(object, keysIn_default, getSymbolsIn_default);
}
var getAllKeysIn_default = getAllKeysIn;
var DataView = getNative_default(root_default, "DataView"), DataView_default = DataView;
var Promise2 = getNative_default(root_default, "Promise"), Promise_default = Promise2;
var Set2 = getNative_default(root_default, "Set"), Set_default = Set2;
var mapTag2 = "[object Map]", objectTag2 = "[object Object]", promiseTag = "[object Promise]", setTag2 = "[object Set]", weakMapTag2 = "[object WeakMap]", dataViewTag2 = "[object DataView]", dataViewCtorString = toSource_default(DataView_default), mapCtorString = toSource_default(Map_default), promiseCtorString = toSource_default(Promise_default), setCtorString = toSource_default(Set_default), weakMapCtorString = toSource_default(WeakMap_default), getTag = baseGetTag_default;
(DataView_default && getTag(new DataView_default(new ArrayBuffer(1))) != dataViewTag2 || Map_default && getTag(new Map_default()) != mapTag2 || Promise_default && getTag(Promise_default.resolve()) != promiseTag || Set_default && getTag(new Set_default()) != setTag2 || WeakMap_default && getTag(new WeakMap_default()) != weakMapTag2) && (getTag = function(value) {
var result = baseGetTag_default(value), Ctor = result == objectTag2 ? value.constructor : void 0, ctorString = Ctor ? toSource_default(Ctor) : "";
if (ctorString)
switch (ctorString) {
case dataViewCtorString:
return dataViewTag2;
case mapCtorString:
return mapTag2;
case promiseCtorString:
return promiseTag;
case setCtorString:
return setTag2;
case weakMapCtorString:
return weakMapTag2;
}
return result;
});
var getTag_default = getTag;
var objectProto13 = Object.prototype, hasOwnProperty10 = objectProto13.hasOwnProperty;
function initCloneArray(array) {
var length = array.length, result = new array.constructor(length);
return length && typeof array[0] == "string" && hasOwnProperty10.call(array, "index") && (result.index = array.index, result.input = array.input), result;
}
var initCloneArray_default = initCloneArray;
var Uint8Array = root_default.Uint8Array, Uint8Array_default = Uint8Array;
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
return new Uint8Array_default(result).set(new Uint8Array_default(arrayBuffer)), result;
}
var cloneArrayBuffer_default = cloneArrayBuffer;
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var cloneDataView_default = cloneDataView;
var reFlags = /\w*$/;
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
return result.lastIndex = regexp.lastIndex, result;
}
var cloneRegExp_default = cloneRegExp;
var symbolProto = Symbol_default ? Symbol_default.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
var cloneSymbol_default = cloneSymbol;
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
var cloneTypedArray_default = cloneTypedArray;
var boolTag2 = "[object Boolean]", dateTag2 = "[object Date]", mapTag3 = "[object Map]", numberTag2 = "[object Number]", regexpTag2 = "[object RegExp]", setTag3 = "[object Set]", stringTag2 = "[object String]", symbolTag = "[object Symbol]", arrayBufferTag2 = "[object ArrayBuffer]", dataViewTag3 = "[object DataView]", float32Tag2 = "[object Float32Array]", float64Tag2 = "[object Float64Array]", int8Tag2 = "[object Int8Array]", int16Tag2 = "[object Int16Array]", int32Tag2 = "[object Int32Array]", uint8Tag2 = "[object Uint8Array]", uint8ClampedTag2 = "[object Uint8ClampedArray]", uint16Tag2 = "[object Uint16Array]", uint32Tag2 = "[object Uint32Array]";
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag2:
return cloneArrayBuffer_default(object);
case boolTag2:
case dateTag2:
return new Ctor(+object);
case dataViewTag3:
return cloneDataView_default(object, isDeep);
case float32Tag2:
case float64Tag2:
case int8Tag2:
case int16Tag2:
case int32Tag2:
case uint8Tag2:
case uint8ClampedTag2:
case uint16Tag2:
case uint32Tag2:
return cloneTypedArray_default(object, isDeep);
case mapTag3:
return new Ctor();
case numberTag2:
case stringTag2:
return new Ctor(object);
case regexpTag2:
return cloneRegExp_default(object);
case setTag3:
return new Ctor();
case symbolTag:
return cloneSymbol_default(object);
}
}
var initCloneByTag_default = initCloneByTag;
function initCloneObject(object) {
return typeof object.constructor == "function" && !isPrototype_default(object) ? baseCreate_default(getPrototype_default(object)) : {};
}
var initCloneObject_default = initCloneObject;
var mapTag4 = "[object Map]";
function baseIsMap(value) {
return isObjectLike_default(value) && getTag_default(value) == mapTag4;
}
var baseIsMap_default = baseIsMap;
var nodeIsMap = nodeUtil_default && nodeUtil_default.isMap, isMap = nodeIsMap ? baseUnary_default(nodeIsMap) : baseIsMap_default, isMap_default = isMap;
var setTag4 = "[object Set]";
function baseIsSet(value) {
return isObjectLike_default(value) && getTag_default(value) == setTag4;
}
var baseIsSet_default = baseIsSet;
var nodeIsSet = nodeUtil_default && nodeUtil_default.isSet, isSet = nodeIsSet ? baseUnary_default(nodeIsSet) : baseIsSet_default, isSet_default = isSet;
var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4, argsTag3 = "[object Arguments]", arrayTag2 = "[object Array]", boolTag3 = "[object Boolean]", dateTag3 = "[object Date]", errorTag2 = "[object Error]", funcTag3 = "[object Function]", genTag2 = "[object GeneratorFunction]", mapTag5 = "[object Map]", numberTag3 = "[object Number]", objectTag3 = "[object Object]", regexpTag3 = "[object RegExp]", setTag5 = "[object Set]", stringTag3 = "[object String]", symbolTag2 = "[object Symbol]", weakMapTag3 = "[object WeakMap]", arrayBufferTag3 = "[object ArrayBuffer]", dataViewTag4 = "[object DataView]", float32Tag3 = "[object Float32Array]", float64Tag3 = "[object Float64Array]", int8Tag3 = "[object Int8Array]", int16Tag3 = "[object Int16Array]", int32Tag3 = "[object Int32Array]", uint8Tag3 = "[object Uint8Array]", uint8ClampedTag3 = "[object Uint8ClampedArray]", uint16Tag3 = "[object Uint16Array]", uint32Tag3 = "[object Uint32Array]", cloneableTags = {};
cloneableTags[argsTag3] = cloneableTags[arrayTag2] = cloneableTags[arrayBufferTag3] = cloneableTags[dataViewTag4] = cloneableTags[boolTag3] = cloneableTags[dateTag3] = cloneableTags[float32Tag3] = cloneableTags[float64Tag3] = cloneableTags[int8Tag3] = cloneableTags[int16Tag3] = cloneableTags[int32Tag3] = cloneableTags[mapTag5] = cloneableTags[numberTag3] = cloneableTags[objectTag3] = cloneableTags[regexpTag3] = cloneableTags[setTag5] = cloneableTags[stringTag3] = cloneableTags[symbolTag2] = cloneableTags[uint8Tag3] = cloneableTags[uint8ClampedTag3] = cloneableTags[uint16Tag3] = cloneableTags[uint32Tag3] = !0;
cloneableTags[errorTag2] = cloneableTags[funcTag3] = cloneableTags[weakMapTag3] = !1;
function baseClone(value, bitmask, customizer, key, object, stack) {
var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer && (result = object ? customizer(value, key, object, stack) : customizer(value)), result !== void 0)
return result;
if (!isObject_default(value))
return value;
var isArr = isArray_default(value);
if (isArr) {
if (result = initCloneArray_default(value), !isDeep)
return copyArray_default(value, result);
} else {
var tag = getTag_default(value), isFunc = tag == funcTag3 || tag == genTag2;
if (isBuffer_default(value))
return cloneBuffer_default(value, isDeep);
if (tag == objectTag3 || tag == argsTag3 || isFunc && !object) {
if (result = isFlat || isFunc ? {} : initCloneObject_default(value), !isDeep)
return isFlat ? copySymbolsIn_default(value, baseAssignIn_default(result, value)) : copySymbols_default(value, baseAssign_default(result, value));
} else {
if (!cloneableTags[tag])
return object ? value : {};
result = initCloneByTag_default(value, tag, isDeep);
}
}
stack || (stack = new Stack_default());
var stacked = stack.get(value);
if (stacked)
return stacked;
stack.set(value, result), isSet_default(value) ? value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
}) : isMap_default(value) && value.forEach(function(subValue, key2) {
result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
});
var keysFunc = isFull ? isFlat ? getAllKeysIn_default : getAllKeys_default : isFlat ? keysIn_default : keys_default, props = isArr ? void 0 : keysFunc(value);
return arrayEach_default(props || value, function(subValue, key2) {
props && (key2 = subValue, subValue = value[key2]), assignValue_default(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
}), result;
}
var baseClone_default = baseClone;
var CLONE_DEEP_FLAG2 = 1, CLONE_SYMBOLS_FLAG2 = 4;
function cloneDeep(value) {
return baseClone_default(value, CLONE_DEEP_FLAG2 | CLONE_SYMBOLS_FLAG2);
}
var cloneDeep_default = cloneDeep;
var COMMON_EMBED_COMMANDS = {
navigate: async (app, url) => !!(app.navigate(url) || window.open(url, "_blank")),
prompt: async (app, ...args) => await app.prompt(...args),
getSettings: async (app) => app.settings,
setSetting: async (app, key, value) => app.setSetting(key, value),
getNoteTitleByUUID: async (app, noteUUID) => (await app.notes.find(noteUUID)).name,
getNoteContentByUUID: async (app, noteUUID) => await app.getNoteContent({ uuid: noteUUID }),
getNoteSections: async (app, ...args) => await app.getNoteSections(...args),
saveFile: async (app, ...args) => {
try {
let { name, data } = args[0];
return data.startsWith("data:") && (data = await (await fetch(data)).blob()), await app.saveFile(data, name);
} catch (e) {
throw e.message;
}
}
};
function createOnEmbedCallHandler(embedCommands = {}) {
return async function(app, commandName, ...args) {
console.log("onEmbedCall", commandName, args);
try {
if (commandName in embedCommands)
return await embedCommands[commandName](app, ...args);
} catch (e) {
throw app.alert("Error:", e.message || e), console.error(e), e;
}
throw new Error(`Unknown command: ${commandName}`);
};
}
var plugin = {
insertText: {
"Create from table": async function(app) {
try {
let dialog = cloneDeep_default(TABLE_CHART_CONFIG_DIALOG);
app.context.noteUUID && (dialog[1].inputs[1].value = app.context.noteUUID);
let promptResult = await app.prompt(...dialog);
if (!promptResult) return;
let [
CHART_TYPE,
DATA_SOURCE_NOTE_UUID,
CHART_TITLE,
TABLE_INDEX_IN_NOTE,
HORIZONTAL_AXIS_LABEL_DIRECTION,
START_FROM_ZERO,
CHART_ASPECT_RATIO_SIZE
] = promptResult;
DATA_SOURCE_NOTE_UUID && DATA_SOURCE_NOTE_UUID.uuid && (DATA_SOURCE_NOTE_UUID = DATA_SOURCE_NOTE_UUID.uuid);
let chartData = {
RANDOM_UUID: Math.random().toString(36).substring(7),
RENDERING_NOTE_UUID: app.context.noteUUID,
DATA_SOURCE: "note",
CHART_TYPE,
DATA_SOURCE_NOTE_UUID,
DATA_SOURCE_HEADER_FILTER: "",
CUMULATIVE: !1,
CHART_TITLE,
TABLE_INDEX_IN_NOTE,
HORIZONTAL_AXIS_LABEL_DIRECTION,
START_FROM_ZERO,
CHART_ASPECT_RATIO_SIZE
};
return await plugin._validateChartConfig(chartData), await app.context.replaceSelection(`<object data="plugin://${app.context.pluginUUID}?${encodeURIComponent(JSON.stringify(chartData))}" data-aspect-ratio="${chartData.CHART_ASPECT_RATIO_SIZE}" />`), null;
} catch (e) {
console.error(e), await app.alert(e);
}
},
"Create from formula": async function(app) {
try {
let dialog = cloneDeep_default(FORMULA_CHART_CONFIG_DIALOG), promptResult = await app.prompt(...dialog);
if (!promptResult) return;
let [
CHART_TYPE,
CHART_TITLE,
DATA_SOURCE_FORMULA_F,
MIN_X,
MAX_X,
STEP_X,
CHART_ASPECT_RATIO_SIZE
] = promptResult, chartData = {
RANDOM_UUID: Math.random().toString(36).substring(7),
RENDERING_NOTE_UUID: app.context.noteUUID,
DATA_SOURCE: "formula",
CHART_TYPE,
CHART_TITLE,
DATA_SOURCE_FORMULA_F,
DATA_SOURCE_FORMULA_G: "",
DATA_SOURCE_FORMULA_H: "",
MIN_X,
MAX_X,
STEP_X,
START_FROM_ZERO: !1,
CHART_ASPECT_RATIO_SIZE
};
return await plugin._validateChartConfig(chartData), await app.context.replaceSelection(`<object data="plugin://${app.context.pluginUUID}?${encodeURIComponent(JSON.stringify(chartData))}" data-aspect-ratio="${chartData.CHART_ASPECT_RATIO_SIZE}" />`), null;
} catch (e) {
console.error(e), await app.alert(e);
}
}
},
renderEmbed(app, args, source = "embed") {
try {
let decodedChartData = JSON.parse(decodeURIComponent(args));
return addWindowVariableToHtmlString(chart_default, "chartData", decodedChartData);
} catch (e) {
return console.error(e), "Error parsing object tag";
}
},
onEmbedCall: createOnEmbedCallHandler({
...COMMON_EMBED_COMMANDS,
updateChartData: async (app, chartDataOld) => {
try {
let chartDataNew = {};
if (chartDataOld.DATA_SOURCE === "note") {
let dialog = cloneDeep_default(TABLE_CHART_CONFIG_DIALOG);
dialog[1].inputs[0].value = chartDataOld.CHART_TYPE, dialog[1].inputs[1].value = chartDataOld.DATA_SOURCE_NOTE_UUID, dialog[1].inputs[1].type = "text", dialog[1].inputs[2].value = chartDataOld.CHART_TITLE, dialog[1].inputs[3].value = chartDataOld.TABLE_INDEX_IN_NOTE, dialog[1].inputs[4].value = chartDataOld.HORIZONTAL_AXIS_LABEL_DIRECTION, dialog[1].inputs[5].value = chartDataOld.START_FROM_ZERO, dialog[1].inputs[6].value = chartDataOld.CHART_ASPECT_RATIO_SIZE;
let promptResult = await app.prompt(...dialog);
if (!promptResult) return;
let [
CHART_TYPE,
DATA_SOURCE_NOTE_UUID,
CHART_TITLE,
TABLE_INDEX_IN_NOTE,
HORIZONTAL_AXIS_LABEL_DIRECTION,
START_FROM_ZERO,
CHART_ASPECT_RATIO_SIZE
] = promptResult;
DATA_SOURCE_NOTE_UUID && (DATA_SOURCE_NOTE_UUID = await app.findNote({ uuid: DATA_SOURCE_NOTE_UUID }), DATA_SOURCE_NOTE_UUID = DATA_SOURCE_NOTE_UUID.uuid), chartDataNew = {
...chartDataOld,
CHART_TYPE,
DATA_SOURCE_NOTE_UUID,
CHART_TITLE,
TABLE_INDEX_IN_NOTE,
HORIZONTAL_AXIS_LABEL_DIRECTION,
START_FROM_ZERO,
CHART_ASPECT_RATIO_SIZE
};
} else if (chartDataOld.DATA_SOURCE === "formula") {
let dialog = cloneDeep_default(FORMULA_CHART_CONFIG_DIALOG);
dialog[1].inputs[0].value = chartDataOld.CHART_TYPE, dialog[1].inputs[1].value = chartDataOld.CHART_TITLE, dialog[1].inputs[2].value = chartDataOld.DATA_SOURCE_FORMULA_F, dialog[1].inputs[3].value = chartDataOld.MIN_X, dialog[1].inputs[4].value = chartDataOld.MAX_X, dialog[1].inputs[5].value = chartDataOld.STEP_X, dialog[1].inputs[6].value = chartDataOld.CHART_ASPECT_RATIO_SIZE;
let promptResult = await app.prompt(...dialog);
if (!promptResult) return;
let [
CHART_TYPE,
CHART_TITLE,
DATA_SOURCE_FORMULA_F,
MIN_X,
MAX_X,
STEP_X,
CHART_ASPECT_RATIO_SIZE
] = promptResult;
chartDataNew = {
...chartDataOld,
CHART_TYPE,
CHART_TITLE,
DATA_SOURCE_FORMULA_F,
MIN_X,
MAX_X,
STEP_X,
CHART_ASPECT_RATIO_SIZE
};
}
await plugin._validateChartConfig(chartDataNew), console.log("ok", chartDataNew);
let originalNoteContent = await app.getNoteContent({ uuid: chartDataOld.RENDERING_NOTE_UUID }), originalEmbedTag = `<object data="plugin://${app.context.pluginUUID}?${encodeURIComponent(JSON.stringify(chartDataOld))}" data-aspect-ratio="${chartDataOld.CHART_ASPECT_RATIO_SIZE}" />`;
if (!originalNoteContent.includes(originalEmbedTag))
throw new Error("Original chart not found in note");
let newEmbedTag = `<object data="plugin://${app.context.pluginUUID}?${encodeURIComponent(JSON.stringify(chartDataNew))}" data-aspect-ratio="${chartDataNew.CHART_ASPECT_RATIO_SIZE}" />`, newNoteContent = originalNoteContent.replace(originalEmbedTag, newEmbedTag);
return await app.replaceNoteContent({ uuid: chartDataNew.RENDERING_NOTE_UUID }, newNoteContent), chartDataNew;
} catch (e) {
throw console.error(e), await app.alert(e), e;
}
}
}),
async _validateChartConfig(chartData) {
try {
if (chartData.DATA_SOURCE === "note")
noteChartSchema.parse(chartData);
else if (chartData.DATA_SOURCE === "formula")
formulaChartSchema.parse(chartData);
else
throw new Error("Invalid data source");
} catch (e) {
throw new Error(e.errors.map((err) => err.message).join(", "));
}
return !0;
}
}, plugin_default = plugin;
return plugin;
})()