Add Markdown editor, server statistics and content navigation

This commit is contained in:
SantaSpeen committed 2026-12-02 15:32:14 +03:00
1 parent 03c590e172
commit 1819f35f91
52 files changed
+7190 -28

No files matched your search

+2
View File
@@ -23,3 +23,5 @@ Dock утверждён пользователем 30.11.2026 и являетс
Оформление не занимает отдельный пункт подменю: светлая/тёмная тема переключаются компактными кнопками солнце/луна внизу меню аккаунта, без навигации. По просьбе пользователя промежуточные правки выполняются без тестовых прогонов; полный набор проверок отложен на финальный этап.
На мобильных Dock снизу с четырьмя иконками: текущий раздел, предыдущий, полное меню, аккаунт. Левого rail на мобильных нет. Полное меню открывается вверх, при выборе закрывается; предыдущий пункт недоступен до первого перехода. Повтор текущей страницы историю не меняет, переход к предыдущей меняет их местами. История сбрасывается при выходе/смене аккаунта/контекста панели; недоступные пункты удаляются. Desktop сохраняет прежний Dock. Общий контроллер — components/mobile-dock.js, стили — mobile-dock.css.
Расширение 02.12.2026: Markdown, минимальный редактор, breadcrumbs, графики и mini-log — отдельные контроллеры в components, публичный API в runtime/index.js, контракт docs/CONTENT-WORKSPACES.md. content-demo.js и patterns/demo-{documents,statistics}.js — только примеры. Не превращайте их в backend-контракт. Зависимости Marked/DOMPurify/Highlight.js функционально нужны для разбора, очистки и подсветки; runtime использует локальный vendor/text. Полная проверка отложена именно до утверждения состава пользователем, включая новые модули, мобильный Dock и предыдущие промежуточные правки.
+2
View File
@@ -5,3 +5,5 @@ The Anidev code, icons and instructions are private project materials. No open-s
The optional terminal runtime is third-party software distributed under its own MIT licenses: `vendor/xterm/xterm.LICENSE`, `vendor/xterm/addon-fit.LICENSE`, `vendor/xterm/addon-search.LICENSE`. Exact versions are recorded in `vendor/xterm/manifest.json`.
Fonts are system fonts; font files and external skill implementations are not distributed. Anidev's own Skill contains project-specific instructions and resources written for this repository.
Optional Markdown and editing modules bundle Marked (MIT), DOMPurify (Apache-2.0 OR MPL-2.0), and Highlight.js (BSD-3-Clause). Their original license texts are included in vendor/text; pinned versions and included languages are listed in vendor/text/manifest.json. These runtimes are served locally and do not require a CDN. Native SVG charts and the mini-log component are Anidev code.
+6
View File
@@ -82,3 +82,9 @@ npm run test:release
Suite использует Edge на Windows или PLAYWRIGHT_EXECUTABLE_PATH. Для другого порта задайте BASE_URL. [QA](references/QA.md), [проверки утверждённого Dock](references/approved-dock/README.md).
[Исследование и лицензии](references/RESEARCH.md) содержит историю выбора; другие концепции не включены в активные компоненты и токены. [Промпт SSO](prompts/SSO.md) — контекст будущей интеграции. Установка универсального Skill описана в [SKILL.md](SKILL.md).
## Документы и статистика сервера
Добавлены Markdown-просмотр с очисткой HTML, редактор с подсветкой и номерами строк, виртуальные папки и кликабельные хлебные крошки. Экран статистики содержит CPU, память, сеть, диски, HTTP-запросы, 5xx, распределение места и индикатор CPU; рядом — мини-логи с цветом всей строки по уровню. Графики поддерживают line/area/bar/stacked/donut/gauge/sparkline. Все показатели тестовые.
[Контракт компонентов и данных](docs/CONTENT-WORKSPACES.md). Быстрый просмотр: `/?page=statistics&panel=admin` и `/?page=documents&path=/some/fee/foo/README.md`. Новые модули включены в runtime, starter, переносимый пакет и экспорт галереи. Версия остаётся предварительной; проверки новых правок будут после утверждения состава пользователем.
+4
View File
@@ -85,3 +85,7 @@ Dock revision 02: постоянная панель иконок, переклю
Revision 04: отдельной иконки раскрытия Dock нет. Hover всей панели открывает меню; бренд-кнопка `a/` сохраняет aria-expanded/aria-controls, Enter/Space и touch. Личный кабинет и статусы Identity описаны в `patterns/IDENTITY.md`. Фото использует одинаковое object-fit: cover во всех представлениях. Смена состояния аккаунта закрывает открытый приватный диалог и скрывает прежний контент.
30.11.2026: утверждён только Dock. Строки таблиц, сервисов, событий, сеансов, настроек, приложений и токенов получают color.row-hover при наведении и focus-within; нажатие/выбор используют color.row-active. Курсор pointer не добавляется строке без действия. Текст остаётся читаемым на обоих состояниях. Root scrollbar-gutter: stable сохраняет ширину при блокировке фоновой прокрутки; native scrollbar оформлен через цвета темы, CSS scrollbar-color/width и WebKit fallback.
## Содержимое и серверная статистика
Markdown — через Marked + DOMPurify и локальную подсветку; редактор — textarea с номерами строк, без исполнения кода. Разрешения/сохранение/запросы остаются у приложения. Хлебные крошки используют реальные ссылки на родителей. Графики имеют единицы, период, значения при наведении и числовое представление. Мини-логи окрашивают всю строку по уровню, сохраняя текст уровня. Детальные контракты: [CONTENT-WORKSPACES.md](../docs/CONTENT-WORKSPACES.md). Новые элементы 02.12.2026 ожидают утверждения и итоговых проверок.
+55
View File
@@ -0,0 +1,55 @@
import { escapeText } from "./text-runtime.js";
export function breadcrumbsMarkup({ items = [], t = (ru) => ru } = {}) {
if (!Array.isArray(items) || items.length > 32)
throw new TypeError("Breadcrumbs support up to 32 entries");
return `<nav class="breadcrumbs" aria-label="${t("Хлебные крошки", "Breadcrumbs")}"><ol>${items
.map((item, index) => {
const label = escapeText(item.label),
current = index === items.length - 1;
let href = item.href;
if (href) {
try {
if (
!["http:", "https:"].includes(
new URL(
href,
globalThis.location?.href || "https://anidev.invalid/",
).protocol,
)
)
href = null;
} catch {
href = null;
}
}
return `<li>${index ? '<span class="breadcrumb-separator" aria-hidden="true">/</span>' : ""}${!current && href ? `<a href="${escapeText(href)}">${label}</a>` : `<span ${current ? 'aria-current="page"' : ""}>${label}</span>`}</li>`;
})
.join("")}</ol></nav>`;
}
export function mountBreadcrumbs(root, { onNavigate } = {}) {
const abort = new AbortController();
root.addEventListener(
"click",
(event) => {
const link = event.target.closest("a[href]");
if (
!onNavigate ||
!link ||
event.defaultPrevented ||
event.button !== 0 ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
event.altKey ||
link.target === "_blank"
)
return;
const url = new URL(link.href, location.href);
if (url.origin !== location.origin) return;
event.preventDefault();
onNavigate(url);
},
{ signal: abort.signal },
);
return () => abort.abort();
}
+324
View File
@@ -0,0 +1,324 @@
import { escapeText } from "./text-runtime.js";
const types = new Set([
"line",
"area",
"bar",
"stacked",
"donut",
"gauge",
"sparkline",
]);
const format = (value, unit = "") =>
value == null
? "—"
: `${new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value)}${unit ? " " + unit : ""}`;
export function mountChart(root, initial) {
const abort = new AbortController(),
{ signal } = abort;
let model,
active = -1,
disposed = false;
root.classList.add("metric-chart");
function normalize(options) {
const type = options.type || "line";
if (!types.has(type)) throw new TypeError("Unknown chart type");
const series = (options.series || []).slice(0, 8).map((item) => ({
name: String(item.name || ""),
values: (item.values || [])
.slice(0, 120)
.map((value) => (value == null ? null : Number(value))),
}));
if (
series.some((item) =>
item.values.some((value) => value !== null && !Number.isFinite(value)),
)
)
throw new TypeError("Chart data must be finite numbers or null");
if (
["stacked", "donut", "gauge"].includes(type) &&
series.some((item) =>
item.values.some((value) => value !== null && value < 0),
)
)
throw new TypeError("This chart needs non-negative data");
const count = Math.max(0, ...series.map((item) => item.values.length)),
labels = Array.from({ length: count }, (_, index) =>
String(options.labels?.[index] ?? index + 1),
);
const values = series
.flatMap((item) => item.values)
.filter((value) => value !== null);
let min = options.min ?? Math.min(0, ...values),
max = options.max ?? Math.max(1, ...values);
if (type === "stacked")
max =
options.max ??
Math.max(
1,
...labels.map((_, index) =>
series.reduce((sum, item) => sum + (item.values[index] || 0), 0),
),
);
if (!Number.isFinite(min) || !Number.isFinite(max) || max <= min) {
min = 0;
max = 1;
}
return {
...options,
type,
series,
labels,
count,
min,
max,
unit: String(options.unit || ""),
t: options.t || ((ru) => ru),
};
}
const x = (index) =>
["bar", "stacked"].includes(model.type)
? 12 + ((index + 0.5) * 616) / Math.max(1, model.count)
: model.count < 2
? 320
: 12 + (index / (model.count - 1)) * 616,
y = (value) => 164 - ((value - model.min) / (model.max - model.min)) * 152;
function paths() {
const { type, series, count } = model;
if (["donut", "gauge"].includes(type)) {
const radius = 66,
circumference = 2 * Math.PI * radius;
let total = series.reduce((sum, item) => sum + (item.values[0] || 0), 0),
offset = 0;
const base = `<circle class="chart-ring-track" cx="120" cy="90" r="${radius}" ${type === "gauge" ? `stroke-dasharray="${circumference * 0.75} ${circumference}" transform="rotate(135 120 90)"` : ""}/>`;
if (type === "gauge") {
const value = series[0]?.values[0] || 0,
ratio = Math.max(0, Math.min(1, value / model.max));
return (
base +
`<circle class="chart-ring series-0" cx="120" cy="90" r="${radius}" stroke-dasharray="${ratio * circumference * 0.75} ${circumference}" transform="rotate(135 120 90)" data-chart-slice="0"/>`
);
}
return (
base +
series
.map((item, index) => {
const length = total
? ((item.values[0] || 0) / total) * circumference
: 0,
result = `<circle class="chart-ring series-${index}" cx="120" cy="90" r="${radius}" stroke-dasharray="${length} ${circumference}" stroke-dashoffset="${-offset}" transform="rotate(-90 120 90)" data-chart-slice="${index}"/>`;
offset += length;
return result;
})
.join("")
);
}
let output = [12, 88, 164]
.map(
(value) =>
`<line class="chart-grid" x1="0" x2="640" y1="${value}" y2="${value}"/>`,
)
.join("");
if (type === "bar" || type === "stacked") {
const group = 616 / Math.max(1, count),
width = Math.max(
1,
(group * 0.72) /
(type === "stacked" ? 1 : Math.max(1, series.length)),
);
for (let index = 0; index < count; index++) {
let sum = 0;
series.forEach((item, s) => {
const value = item.values[index];
if (value == null) return;
const from = type === "stacked" ? sum : 0,
to = from + value;
output += `<rect class="chart-bar series-${s}" x="${12 + index * group + (type === "stacked" ? group * 0.14 : group * 0.14 + s * width)}" y="${Math.min(y(from), y(to))}" width="${width}" height="${Math.max(1, Math.abs(y(to) - y(from)))}" rx="2"/>`;
sum += value;
});
}
} else {
series.forEach((item, s) => {
const runs = [];
let run = [];
item.values.forEach((value, index) => {
if (value == null) {
if (run.length) runs.push(run);
run = [];
} else run.push([x(index), y(value)]);
});
if (run.length) runs.push(run);
for (const points of runs) {
const d = points
.map(([px, py], index) => `${index ? "L" : "M"}${px},${py}`)
.join(" ");
if (type === "area")
output += `<path class="chart-area series-${s}" d="${d} L${points.at(-1)[0]},${y(0)} L${points[0][0]},${y(0)} Z"/>`;
output += `<path class="chart-line series-${s}" d="${d}"/>`;
}
});
}
return (
output +
'<line class="chart-crosshair" x1="0" x2="0" y1="0" y2="180" hidden/>'
);
}
function render() {
active = -1;
const {
title = "",
description = "",
type,
series,
labels,
t,
unit,
count,
} = model,
round = ["donut", "gauge"].includes(type),
empty =
!count ||
!series.some((item) => item.values.some((value) => value !== null));
const total =
type === "gauge"
? series[0]?.values[0] || 0
: series.reduce((sum, item) => sum + (item.values[0] || 0), 0);
root.dataset.chartType = type;
root.dataset.chartTone = ["danger", "warning"].includes(model.tone)
? model.tone
: "default";
root.innerHTML = `${title ? `<div class="chart-heading"><h3>${escapeText(title)}</h3>${description ? `<p>${escapeText(description)}</p>` : ""}</div>` : ""}${empty ? `<div class="chart-empty">${t("Нет данных за выбранный период.", "No data for this period.")}</div>` : `<div class="chart-plot ${round ? "chart-round" : ""}" tabindex="0" role="group" aria-label="${escapeText(title)}. ${t("Стрелки для просмотра значений", "Use arrow keys to inspect values")}"><svg viewBox="0 0 ${round ? "240 180" : "640 180"}" preserveAspectRatio="${round ? "xMidYMid meet" : "none"}" aria-hidden="true">${paths()}</svg>${round ? `<div class="chart-center"><strong>${escapeText(format(total, unit))}</strong><span>${type === "gauge" ? t("текущее значение", "current value") : t("всего", "total")}</span></div>` : ""}<div class="chart-tooltip" hidden role="status" aria-live="off"></div></div>${!round && type !== "sparkline" ? `<div class="chart-axis"><span>${escapeText(labels[0])}</span><span>${escapeText(labels[Math.floor((count - 1) / 2)])}</span><span>${escapeText(labels.at(-1))}</span></div><div class="chart-scale">${escapeText(format(model.min, unit))} — ${escapeText(format(model.max, unit))}</div>` : ""}<div class="chart-legend">${series.map((item, index) => `<span><i class="series-${index}" aria-hidden="true"></i>${escapeText(item.name)}</span>`).join("")}</div>${type !== "sparkline" ? `<details class="chart-data"><summary>${t("Числовые данные", "Numerical data")}</summary><div class="table-wrap"><table><thead><tr><th>${round ? t("Показатель", "Metric") : t("Период", "Period")}</th>${round ? `<th>${escapeText(unit || t("Значение", "Value"))}</th>` : series.map((item) => `<th>${escapeText(item.name)}${unit ? ` (${escapeText(unit)})` : ""}</th>`).join("")}</tr></thead><tbody>${round ? series.map((item) => `<tr><th>${escapeText(item.name)}</th><td>${escapeText(format(item.values[0], unit))}</td></tr>`).join("") : labels.map((label, index) => `<tr><th>${escapeText(label)}</th>${series.map((item) => `<td>${escapeText(format(item.values[index], unit))}</td>`).join("")}</tr>`).join("")}</tbody></table></div></details>` : ""}`}`;
}
function show(index, keyboard = false) {
const plot = root.querySelector(".chart-plot"),
tooltip = root.querySelector(".chart-tooltip");
if (!plot || !tooltip) return;
const round = ["donut", "gauge"].includes(model.type),
size = round ? model.series.length : model.count;
active = Math.max(0, Math.min(size - 1, index));
tooltip.replaceChildren();
const title = document.createElement("strong");
title.textContent = round
? model.series[active]?.name
: model.labels[active];
tooltip.append(title);
for (const item of round ? [model.series[active]] : model.series) {
if (!item) continue;
const line = document.createElement("span");
line.textContent =
(round ? "" : item.name + ": ") +
format(item.values[round ? 0 : active], model.unit);
tooltip.append(line);
}
tooltip.hidden = false;
tooltip.setAttribute("aria-live", keyboard ? "polite" : "off");
const width = plot.clientWidth,
px = round
? width / 2
: (model.count < 2 ? 0.5 : active / (model.count - 1)) * width;
tooltip.style.left =
Math.max(
6,
Math.min(px - tooltip.offsetWidth / 2, width - tooltip.offsetWidth - 6),
) + "px";
const cross = root.querySelector(".chart-crosshair");
if (cross) {
cross.removeAttribute("hidden");
cross.setAttribute("x1", x(active));
cross.setAttribute("x2", x(active));
}
}
function hide() {
root.querySelector(".chart-tooltip")?.setAttribute("hidden", "");
root.querySelector(".chart-crosshair")?.setAttribute("hidden", "");
}
root.addEventListener(
"pointermove",
(event) => {
const plot = event.target.closest(".chart-plot");
if (!plot) return;
if (["donut", "gauge"].includes(model.type)) {
const slice = event.target.closest("[data-chart-slice]");
if (slice) show(Number(slice.dataset.chartSlice));
} else {
const ratio =
(event.clientX - plot.getBoundingClientRect().left) /
Math.max(1, plot.clientWidth);
show(
["bar", "stacked"].includes(model.type)
? Math.floor(ratio * model.count)
: Math.round(ratio * (model.count - 1)),
);
}
},
{ signal },
);
root.addEventListener(
"pointerleave",
() => {
if (!root.contains(document.activeElement)) hide();
},
{ signal },
);
root.addEventListener(
"focusin",
(event) => {
if (event.target.matches(".chart-plot")) show(Math.max(0, active), true);
},
{ signal },
);
root.addEventListener(
"focusout",
(event) => {
if (!root.contains(event.relatedTarget)) hide();
},
{ signal },
);
root.addEventListener(
"keydown",
(event) => {
if (
!event.target.matches(".chart-plot") ||
event.ctrlKey ||
event.metaKey ||
event.altKey
)
return;
if (
["ArrowLeft", "ArrowRight", "Home", "End", "Escape"].includes(event.key)
) {
event.preventDefault();
event.stopPropagation();
if (event.key === "Escape") {
hide();
return;
}
const size = ["donut", "gauge"].includes(model.type)
? model.series.length
: model.count;
show(
event.key === "Home"
? 0
: event.key === "End"
? size - 1
: Math.max(0, active) + (event.key === "ArrowRight" ? 1 : -1),
true,
);
}
},
{ signal },
);
function update(options) {
if (disposed) return;
model = normalize({ ...model, ...options });
render();
}
update(initial);
return {
update,
dispose() {
disposed = true;
abort.abort();
hide();
},
};
}
+227
View File
@@ -0,0 +1,227 @@
import { iconSvg } from "../icons/icons.js";
import {
escapeText,
highlightedCode,
codeLanguages,
normalizeLanguage,
} from "./text-runtime.js";
let sequence = 0;
export function mountCodeEditor(
root,
{
value = "",
language = "plaintext",
label = "editor.txt",
readOnly = false,
onChange = () => {},
onSave,
notify,
t = (ru) => ru,
} = {},
) {
const id = `code-editor-${++sequence}`,
abort = new AbortController(),
{ signal } = abort;
let disposed = false,
timer,
revision = 0,
captureTab = true,
accepted = "";
const valid = (text) =>
text.length <= 131072 && text.split("\n").length <= 4000;
if (!valid(String(value)))
throw new RangeError(
"Editor supports up to 131072 characters and 4000 lines",
);
root.classList.add("code-editor");
root.innerHTML = `<div class="code-editor-toolbar"><label for="${id}">${escapeText(label)}</label><div><select aria-label="${t("Язык кода", "Code language")}">${codeLanguages.map((name) => `<option value="${name}">${name === "plaintext" ? t("Текст", "Plain text") : name}</option>`).join("")}</select><button type="button" data-code-copy aria-label="${t("Копировать код", "Copy code")}" title="${t("Копировать код", "Copy code")}">${iconSvg("copy", { size: 16 })}</button></div></div><div class="code-editor-viewport"><div class="code-editor-gutter" aria-hidden="true"><pre></pre></div><div class="code-editor-layer"><pre aria-hidden="true"><code></code></pre><textarea id="${id}" aria-label="${escapeText(label)}" spellcheck="false" autocapitalize="off" autocomplete="off" autocorrect="off" wrap="off" maxlength="131072" ${readOnly ? "readonly" : ""}></textarea></div></div><div class="code-editor-status"><span data-code-position></span><button type="button" data-code-tab aria-pressed="true" title="Ctrl M">${t("Tab: отступ", "Tab: indent")}</button><span data-code-message role="status"></span></div>`;
const input = root.querySelector("textarea"),
pre = root.querySelector(".code-editor-layer pre"),
code = pre.querySelector("code"),
lines = root.querySelector(".code-editor-gutter pre"),
select = root.querySelector("select"),
position = root.querySelector("[data-code-position]"),
message = root.querySelector("[data-code-message]"),
tab = root.querySelector("[data-code-tab]");
input.value = accepted = String(value);
select.value = codeLanguages.includes(normalizeLanguage(language))
? normalizeLanguage(language)
: "plaintext";
function locate() {
const before = input.value.slice(0, input.selectionStart).split("\n");
position.textContent = t(
`Строка ${before.length}, столбец ${before.at(-1).length + 1}`,
`Line ${before.length}, column ${before.at(-1).length + 1}`,
);
}
function syncScroll() {
pre.scrollTop = input.scrollTop;
pre.scrollLeft = input.scrollLeft;
lines.style.transform = `translateY(${-input.scrollTop}px)`;
}
async function paint() {
const ticket = ++revision,
text = input.value + (input.value.endsWith("\n") ? " " : "");
code.textContent = text;
lines.textContent = Array.from(
{ length: input.value.split("\n").length },
(_, index) => index + 1,
).join("\n");
locate();
syncScroll();
try {
const html = await highlightedCode(text, select.value);
if (!disposed && ticket === revision) {
code.innerHTML = html;
syncScroll();
}
} catch {
if (!disposed && ticket === revision) code.textContent = text;
}
}
function changed() {
if (!valid(input.value)) {
input.value = accepted;
message.textContent = t(
"Превышен размер редактора.",
"Editor size limit exceeded.",
);
return;
}
accepted = input.value;
revision++;
clearTimeout(timer);
code.textContent = input.value;
lines.textContent = Array.from(
{ length: input.value.split("\n").length },
(_, index) => index + 1,
).join("\n");
locate();
syncScroll();
onChange(input.value);
timer = setTimeout(paint, 70);
}
function insert(text) {
input.focus();
const start = input.selectionStart,
end = input.selectionEnd;
if (!document.execCommand("insertText", false, text)) {
input.setRangeText(text, start, end, "end");
changed();
}
}
function toggleTab() {
captureTab = !captureTab;
tab.setAttribute("aria-pressed", String(captureTab));
tab.textContent = captureTab
? t("Tab: отступ", "Tab: indent")
: t("Tab: переход", "Tab: focus");
}
input.addEventListener("input", changed, { signal });
input.addEventListener("scroll", syncScroll, { signal });
input.addEventListener("click", locate, { signal });
input.addEventListener("keyup", locate, { signal });
input.addEventListener(
"keydown",
(event) => {
if (event.isComposing) return;
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "m") {
event.preventDefault();
event.stopPropagation();
toggleTab();
return;
}
if (
(event.ctrlKey || event.metaKey) &&
event.key.toLowerCase() === "s" &&
onSave
) {
event.preventDefault();
event.stopPropagation();
onSave(input.value);
return;
}
if (readOnly) return;
if (event.key === "Tab" && captureTab) {
event.preventDefault();
event.stopPropagation();
const start = input.selectionStart,
end = input.selectionEnd;
if (start === end && !event.shiftKey) {
insert(" ");
return;
}
const first = input.value.lastIndexOf("\n", start - 1) + 1,
last = input.value.indexOf("\n", Math.max(start, end - 1)),
finish = last < 0 ? input.value.length : last;
const selected = input.value
.slice(first, finish)
.split("\n")
.map((line) =>
event.shiftKey ? line.replace(/^( {1,2}|\t)/, "") : " " + line,
)
.join("\n");
input.setSelectionRange(first, finish);
insert(selected);
input.setSelectionRange(first, first + selected.length);
return;
}
if (
event.key === "Enter" &&
!event.ctrlKey &&
!event.metaKey &&
!event.altKey
) {
event.preventDefault();
const before = input.value
.slice(0, input.selectionStart)
.split("\n")
.at(-1),
indent = /^[ \t]*/.exec(before)[0];
insert("\n" + indent + (/[\[{]\s*$/.test(before) ? " " : ""));
}
},
{ signal },
);
select.addEventListener("change", paint, { signal });
tab.addEventListener("click", toggleTab, { signal });
root.querySelector("[data-code-copy]").addEventListener(
"click",
async () => {
try {
await navigator.clipboard.writeText(input.value);
if (!disposed) {
message.textContent = t("Скопировано", "Copied");
notify?.(t("Код скопирован.", "Code copied."), { type: "success" });
}
} catch {
if (!disposed)
message.textContent = t("Не удалось скопировать.", "Could not copy.");
}
},
{ signal },
);
paint();
return {
getValue: () => input.value,
setValue(text, { emit = false } = {}) {
text = String(text);
if (!valid(text)) throw new RangeError("Editor limit exceeded");
input.value = accepted = text;
paint();
if (emit) onChange(text);
},
setLanguage(name) {
select.value = codeLanguages.includes(normalizeLanguage(name))
? normalizeLanguage(name)
: "plaintext";
paint();
},
dispose() {
disposed = true;
revision++;
clearTimeout(timer);
abort.abort();
},
};
}
+183
View File
@@ -0,0 +1,183 @@
import { statisticsMarkup, mountStatistics } from "./server-statistics.js";
import { mountDocuments, normalizeDocumentPath } from "./documents.js";
import { errorPageMarkup, mountErrorPage } from "./error-page.js";
import { escapeText } from "./text-runtime.js";
import {
demoServers,
createDemoStatistics,
} from "../patterns/demo-statistics.js";
import { createDemoDocuments } from "../patterns/demo-documents.js";
export { createDemoDocuments };
export const contentDemoPages = Object.freeze([
"documents",
"servers",
"server",
"statistics",
]);
export function contentHref({ page, server, path, panel } = {}) {
const url = new URL(location.href);
url.searchParams.set("page", page);
if (server) url.searchParams.set("server", server);
else url.searchParams.delete("server");
if (page === "documents" && path) url.searchParams.set("path", path);
else url.searchParams.delete("path");
if (panel) url.searchParams.set("panel", panel);
url.hash = "";
return url.pathname + url.search;
}
export function contentBreadcrumbs(
page,
{
server = "edge-01",
path = "/",
rootPage = "dashboard",
t = (ru) => ru,
} = {},
) {
const items = [{ label: "anidev", href: contentHref({ page: rootPage }) }];
if (page === "documents") {
items.push({
label: t("Документы", "Documents"),
href: contentHref({ page, path: "/" }),
});
const parts = (normalizeDocumentPath(path) || "/")
.split("/")
.filter(Boolean);
parts.forEach((label, index) =>
items.push({
label,
href: contentHref({
page,
path: "/" + parts.slice(0, index + 1).join("/"),
}),
}),
);
} else {
items.push({
label: t("Серверы", "Servers"),
href: contentHref({ page: "servers" }),
});
if (page !== "servers")
items.push({
label: server,
href: contentHref({ page: "server", server }),
});
if (page === "statistics")
items.push({ label: t("Статистика", "Statistics") });
}
return items;
}
export function contentDemoMarkup(
page,
{
server = "edge-01",
path = "/",
heading = (title, description) =>
`<h1>${escapeText(title)}</h1><p>${escapeText(description)}</p>`,
t = (ru) => ru,
} = {},
) {
const record = demoServers.find((item) => item.id === server),
demo = t(
"Демонстрационные данные · API сервера пока не подключено.",
"Sample data · no server API is connected.",
);
if (page === "documents")
return (
heading(
t("Документы и код", "Documents and code"),
t(
"Markdown-просмотр и компактный редактор с подсветкой.",
"Markdown preview and a compact syntax editor.",
),
) + `<div data-content-demo data-documents-host></div>`
);
if (page === "servers")
return (
heading(t("Серверы", "Servers"), demo) +
`<div data-content-demo><div class="document-file-list">${demoServers.map((item) => `<a data-content-link href="${escapeText(contentHref({ page: "server", server: item.id }))}"><strong>${escapeText(item.name)}</strong><span>${escapeText(item.os)}</span><small>${escapeText(item.region)}</small></a>`).join("")}</div></div>`
);
if (!record)
return `<div data-content-demo>${errorPageMarkup({ status: 404, t })}</div>`;
if (page === "server")
return (
heading(record.name, demo) +
`<div data-content-demo><dl class="server-details">${[
[t("Система", "System"), record.os],
[t("Регион", "Region"), record.region],
["CPU", `${record.cpu} vCPU`],
[t("Память", "Memory"), `${record.memory} ${t("ГБ", "GB")}`],
]
.map(
([label, value]) =>
`<div><dt>${escapeText(label)}</dt><dd>${escapeText(value)}</dd></div>`,
)
.join(
"",
)}</dl><div class="component-row"><a class="content-action" data-content-link href="${escapeText(contentHref({ page: "statistics", server }))}">${t("Статистика сервера", "Server statistics")}</a><a class="content-action" data-content-link href="${escapeText(contentHref({ page: "documents", path: "/server-guide.md" }))}">${t("Руководство .md", "Markdown guide")}</a></div></div>`
);
return (
heading(`${t("Статистика", "Statistics")} · ${record.name}`, demo) +
`<div data-content-demo>${statisticsMarkup({ title: t("Показатели сервера", "Server metrics"), t })}</div>`
);
}
export function mountContentDemo(
root,
{
page,
server = "edge-01",
path = "/",
files = createDemoDocuments(),
onNavigate,
notify,
t = (ru) => ru,
} = {},
) {
const abort = new AbortController();
let controller, cleanup;
const go = (route) =>
onNavigate?.(new URL(contentHref(route), location.href));
root.addEventListener(
"click",
(event) => {
const link = event.target.closest("[data-content-link]");
if (
!link ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
event.altKey ||
!onNavigate
)
return;
event.preventDefault();
onNavigate(new URL(link.href, location.href));
},
{ signal: abort.signal },
);
if (page === "documents")
controller = mountDocuments(root, {
files,
path,
onNavigate: (next) => go({ page: "documents", path: next }),
hrefForPath: (next) => contentHref({ page: "documents", path: next }),
notify,
t,
});
else if (root.querySelector("[data-error-status]"))
cleanup = mountErrorPage(root, { onHome: () => go({ page: "servers" }) });
else if (page === "statistics") {
controller = mountStatistics(root.querySelector(".server-statistics"), {
data: createDemoStatistics("1h", server),
t,
onRangeChange: (range) =>
controller.update(createDemoStatistics(range, server)),
onOpenLogs: () => go({ page: "logs", server }),
});
}
return () => {
abort.abort();
controller?.dispose();
cleanup?.();
};
}
+814
View File
@@ -0,0 +1,814 @@
.breadcrumbs {
min-width: 0;
max-width: 100%;
overflow-x: auto;
scrollbar-width: thin;
font-size: 13px;
}
.breadcrumbs ol {
display: flex;
align-items: center;
gap: 8px;
list-style: none;
margin: 0;
padding: 2px 0;
white-space: nowrap;
}
.breadcrumbs li {
display: flex;
align-items: center;
gap: 8px;
}
.breadcrumbs a {
color: var(--color-muted);
text-decoration: none;
padding: 4px 2px;
border-radius: 4px;
}
.breadcrumbs a:hover {
color: var(--color-accent);
text-decoration: underline;
}
.breadcrumbs [aria-current="page"] {
color: var(--color-text);
}
.breadcrumb-separator {
color: var(--color-muted);
opacity: 0.6;
}
.demo-label {
font-size: 12px;
color: var(--color-muted);
}
.markdown-body {
line-height: 1.75;
min-width: 0;
overflow-wrap: anywhere;
}
.markdown-body :is(h1, h2, h3, h4, h5, h6) {
margin: 1.4em 0 0.6em;
line-height: 1.3;
scroll-margin-top: 24px;
}
.markdown-body > :first-child {
margin-top: 0;
}
.markdown-body p {
margin-bottom: 1em;
}
.markdown-body blockquote {
margin: 1em 0;
padding: 10px 18px;
border-left: 3px solid var(--color-accent);
background: var(--color-row-hover);
border-radius: 0 10px 10px 0;
}
.markdown-body blockquote > :last-child {
margin-bottom: 0;
}
.markdown-body pre {
max-width: 100%;
overflow: auto;
padding: 16px;
background: var(--color-bg);
border: 1px solid var(--color-border);
border-radius: 10px;
line-height: 1.6;
}
.markdown-body code {
font:
13px/1.6 ui-monospace,
Consolas,
monospace;
}
.markdown-body :not(pre) > code {
padding: 2px 5px;
background: var(--color-row-hover);
border-radius: 4px;
}
.markdown-body table {
display: block;
width: max-content;
max-width: 100%;
overflow: auto;
border-collapse: collapse;
}
.markdown-body :is(th, td) {
padding: 8px 12px;
border: 1px solid var(--color-border);
}
.markdown-body img {
max-width: 100%;
height: auto;
border-radius: 8px;
}
.markdown-body li > input[type="checkbox"] {
vertical-align: middle;
margin-right: 6px;
}
.markdown-body hr {
border: 0;
border-top: 1px solid var(--color-border);
margin: 24px 0;
}
.hljs-comment,
.hljs-quote {
color: var(--color-muted);
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-attribute,
.hljs-meta,
.hljs-title,
.hljs-section,
.hljs-built_in {
color: var(--color-accent);
}
.hljs-string,
.hljs-regexp,
.hljs-addition {
color: var(--color-success);
}
.hljs-number,
.hljs-literal,
.hljs-symbol,
.hljs-bullet {
color: var(--color-warning);
}
.hljs-deletion {
color: var(--color-danger);
}
.code-editor {
min-width: 0;
overflow: hidden;
border: 1px solid var(--color-border);
border-radius: 12px;
background: var(--color-surface);
}
.code-editor:focus-within {
border-color: var(--color-accent);
}
.code-editor-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 12px;
border-bottom: 1px solid var(--color-border);
}
.code-editor-toolbar > label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font:
12px ui-monospace,
monospace;
}
.code-editor-toolbar > div {
display: flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
}
.code-editor-toolbar :is(select, button) {
min-height: 30px;
padding: 5px 7px;
font-size: 11px;
}
.code-editor-viewport {
position: relative;
display: grid;
grid-template-columns: 44px minmax(0, 1fr);
height: var(--editor-height, 320px);
overflow: hidden;
}
.code-editor-gutter {
position: relative;
overflow: hidden;
color: var(--color-muted);
background: var(--color-bg);
border-right: 1px solid var(--color-border);
user-select: none;
}
.code-editor-gutter pre {
margin: 0;
padding: 12px 8px;
text-align: right;
font:
13px/22px ui-monospace,
Consolas,
monospace;
white-space: pre;
}
.code-editor-layer {
position: relative;
min-width: 0;
overflow: hidden;
}
.code-editor-layer :is(pre, textarea) {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
padding: 12px;
margin: 0;
border: 0;
border-radius: 0;
font:
13px/22px ui-monospace,
Consolas,
monospace;
letter-spacing: normal;
tab-size: 2;
white-space: pre;
overflow: auto;
}
.code-editor-layer pre {
pointer-events: none;
scrollbar-width: none;
color: var(--color-text);
background: transparent;
}
.code-editor-layer pre::-webkit-scrollbar {
display: none;
}
.code-editor-layer code {
font: inherit;
white-space: inherit;
}
.code-editor-layer textarea {
background: transparent;
color: transparent;
caret-color: var(--color-text);
resize: none;
outline: none;
cursor: text;
-webkit-text-fill-color: transparent;
}
.code-editor-layer textarea:focus-visible {
outline: none;
}
.code-editor-layer textarea::selection {
background: color-mix(in srgb, var(--color-accent) 24%, transparent);
}
.code-editor-status {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
padding: 6px 12px;
border-top: 1px solid var(--color-border);
font-size: 11px;
color: var(--color-muted);
}
.code-editor-status button {
min-height: 24px;
font-size: 11px;
padding: 2px 6px;
border: 0;
background: transparent;
color: var(--color-muted);
}
.code-editor-status [role="status"] {
margin-left: auto;
}
.documents-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 16px;
}
.documents-toolbar .demo-label {
margin-right: auto;
}
.documents-toolbar > button,
.document-open {
display: inline-flex;
align-items: center;
gap: 8px;
}
.document-open {
position: relative;
padding: 8px 12px;
border: 1px solid var(--color-border);
border-radius: var(--radius-control);
cursor: pointer;
font-size: 13px;
background: var(--color-surface);
}
.document-open:focus-within {
outline: 2px solid var(--color-accent);
outline-offset: 2px;
}
.document-open input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
padding: 0;
min-height: 0;
}
.document-panes {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 20px;
}
.document-split {
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: start;
}
.document-preview {
min-width: 0;
padding: 20px;
border: 1px solid var(--color-border);
border-radius: 12px;
background: var(--color-surface);
}
.document-preview > h2 {
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--color-muted);
margin-bottom: 20px;
}
.document-file-list {
max-width: 900px;
border-top: 1px solid var(--color-border);
}
.document-file-list > a {
display: flex;
align-items: center;
gap: 12px;
padding: 15px 12px;
border-bottom: 1px solid var(--color-border);
color: var(--color-text);
text-decoration: none;
}
.document-file-list > a:hover {
background: var(--color-row-hover);
}
.document-file-list small {
margin-left: auto;
}
.mini-log {
min-width: 0;
margin-top: 20px;
border: 1px solid var(--color-border);
border-radius: 12px;
overflow: hidden;
background: var(--color-surface);
}
.mini-log-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 14px;
}
.mini-log-heading h3 {
margin: 0;
font-size: 14px;
}
.mini-log-heading button {
min-height: 28px;
padding: 4px 8px;
font-size: 12px;
}
.mini-log-lines {
max-height: 280px;
overflow: auto;
scrollbar-gutter: stable;
}
.mini-log-line {
display: grid;
grid-template-columns: 70px 48px minmax(0, 1fr);
gap: 10px;
padding: 10px 14px;
border-top: 1px solid color-mix(in srgb, var(--color-border) 50%, transparent);
font:
12px/1.6 ui-monospace,
Consolas,
monospace;
}
.mini-log-line time {
color: var(--color-muted);
}
.mini-log-message {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.mini-log-level {
font-size: 10px;
font-weight: 600;
padding-top: 2px;
}
.mini-log-line[data-level="DEBUG"] {
background: color-mix(in srgb, var(--color-muted) 6%, var(--color-surface));
color: var(--color-muted);
}
.mini-log-line[data-level="INFO"] {
background: color-mix(in srgb, var(--color-accent) 7%, var(--color-surface));
}
.mini-log-line[data-level="WARN"] {
background: color-mix(
in srgb,
var(--color-warning) 12%,
var(--color-surface)
);
}
.mini-log-line[data-level="WARN"] .mini-log-level {
color: var(--color-warning);
}
.mini-log-line[data-level="ERROR"] {
background: color-mix(in srgb, var(--color-danger) 12%, var(--color-surface));
}
.mini-log-line[data-level="ERROR"] .mini-log-level {
color: var(--color-danger);
}
.mini-log-empty {
padding: 12px 14px;
color: var(--color-muted);
font-size: 13px;
}
.statistics-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 20px;
}
.statistics-toolbar h2 {
margin-bottom: 4px;
}
.statistics-toolbar p {
margin: 0;
font-size: 13px;
}
.statistics-toolbar label {
display: grid;
gap: 4px;
font-size: 12px;
flex-shrink: 0;
}
.statistics-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 18px;
}
.statistics-panel {
min-width: 0;
border: 1px solid var(--color-border);
border-radius: 12px;
padding: 18px;
background: var(--color-surface);
}
.statistics-kpis {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 18px;
margin-bottom: 18px;
}
.statistics-kpi {
min-width: 0;
padding: 16px 18px;
border: 1px solid var(--color-border);
border-radius: 12px;
background: var(--color-surface);
}
.statistics-kpi > span {
display: block;
font-size: 12px;
color: var(--color-muted);
}
.statistics-kpi > strong {
display: block;
font-size: 24px;
margin: 4px 0 8px;
font-weight: 600;
}
.chart-heading h3 {
font-size: 14px;
margin: 0 0 5px;
}
.chart-heading p {
font-size: 12px;
color: var(--color-muted);
margin: 0 0 12px;
}
.chart-plot {
position: relative;
height: 180px;
margin-top: 16px;
min-width: 0;
border-radius: 6px;
}
.chart-plot > svg {
display: block;
width: 100%;
height: 100%;
overflow: hidden;
}
.chart-grid {
stroke: var(--color-border);
stroke-width: 1;
stroke-dasharray: 4 5;
vector-effect: non-scaling-stroke;
}
.series-0 {
--series-color: var(--color-accent);
}
.series-1 {
--series-color: var(--color-warning);
}
.series-2 {
--series-color: var(--color-success);
}
.series-3 {
--series-color: var(--color-danger);
}
.series-4 {
--series-color: color-mix(
in srgb,
var(--color-accent) 50%,
var(--color-text)
);
}
.series-5 {
--series-color: var(--color-muted);
}
.series-6 {
--series-color: color-mix(
in srgb,
var(--color-warning) 65%,
var(--color-text)
);
}
.series-7 {
--series-color: color-mix(
in srgb,
var(--color-success) 65%,
var(--color-text)
);
}
.chart-line {
stroke: var(--series-color);
fill: none;
stroke-width: 2;
vector-effect: non-scaling-stroke;
stroke-linejoin: round;
}
.chart-area {
fill: var(--series-color);
opacity: 0.13;
stroke: none;
}
.chart-bar {
fill: var(--series-color);
opacity: 0.85;
}
.chart-crosshair {
stroke: var(--color-muted);
stroke-width: 1;
stroke-dasharray: 3 3;
vector-effect: non-scaling-stroke;
}
.chart-crosshair[hidden] {
display: none;
}
.chart-axis {
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 8px;
font:
10px ui-monospace,
monospace;
color: var(--color-muted);
}
.chart-scale {
font-size: 10px;
color: var(--color-muted);
margin-top: 6px;
}
.chart-legend {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
margin-top: 12px;
font-size: 11px;
color: var(--color-muted);
}
.chart-legend > span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.chart-legend i {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--series-color);
}
.chart-data {
margin-top: 14px;
border: 0;
}
.chart-data summary {
font-size: 11px;
color: var(--color-muted);
padding: 4px 0;
cursor: pointer;
}
.chart-data table {
font-size: 11px;
margin-top: 8px;
}
.metric-chart .chart-tooltip {
position: absolute;
top: 6px;
z-index: 5;
display: grid;
gap: 4px;
width: max-content;
max-width: calc(100% - 12px);
padding: 9px 11px;
border: 1px solid var(--color-border);
border-radius: 9px;
background: var(--color-surface);
box-shadow: 0 8px 24px #07181f30;
font-size: 11px;
pointer-events: none;
overflow-wrap: anywhere;
}
.metric-chart .chart-tooltip[hidden] {
display: none;
}
.metric-chart .chart-tooltip strong {
font-weight: 600;
}
.chart-round {
max-width: 280px;
height: 180px;
margin-inline: auto;
}
.chart-ring-track {
fill: none;
stroke: var(--color-border);
stroke-width: 20;
}
.chart-ring {
fill: none;
stroke: var(--series-color);
stroke-width: 20;
}
.chart-center {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
pointer-events: none;
}
.chart-center strong {
font-size: 22px;
font-weight: 600;
}
.chart-center span {
font-size: 10px;
color: var(--color-muted);
}
.chart-empty {
min-height: 180px;
display: grid;
place-items: center;
font-size: 13px;
color: var(--color-muted);
}
.metric-chart[data-chart-type="sparkline"] .chart-plot {
height: 46px;
margin: 0;
}
.metric-chart[data-chart-type="sparkline"] .chart-heading {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
}
.metric-chart[data-chart-type="sparkline"] .chart-legend {
display: none;
}
@media (max-width: 900px) {
.document-split {
grid-template-columns: minmax(0, 1fr);
}
.statistics-kpis {
gap: 10px;
}
.statistics-kpi {
padding: 14px;
}
.statistics-kpi > strong {
font-size: 20px;
}
}
@media (max-width: 600px) {
.statistics-grid {
grid-template-columns: minmax(0, 1fr);
}
.statistics-kpis {
grid-template-columns: minmax(0, 1fr);
}
.statistics-kpi {
display: grid;
grid-template-columns: minmax(0, 1fr) 100px;
column-gap: 12px;
}
.statistics-kpi > [data-stat-spark] {
grid-column: 2;
grid-row: 1/3;
align-self: center;
}
.statistics-kpi > strong {
margin: 4px 0;
}
.statistics-toolbar {
align-items: flex-start;
}
.statistics-panel {
padding: 14px;
}
.mini-log-line {
grid-template-columns: 58px 40px minmax(0, 1fr);
gap: 7px;
padding: 9px 10px;
font-size: 11px;
}
.code-editor-toolbar {
padding: 8px;
}
.code-editor-toolbar select {
max-width: 110px;
}
.document-preview {
padding: 14px;
}
.breadcrumbs {
font-size: 12px;
}
}
.content-action {
display: inline-flex;
align-items: center;
padding: 9px 13px;
border: 1px solid var(--color-border);
border-radius: var(--radius-control);
text-decoration: none;
background: var(--color-surface);
}
.app-header > .breadcrumbs {
flex: 1;
min-width: 0;
}
.metric-chart[data-chart-tone="danger"] .series-0 {
--series-color: var(--color-danger);
}
.metric-chart[data-chart-tone="warning"] .series-0 {
--series-color: var(--color-warning);
}
.server-details {
max-width: 720px;
margin: 0 0 24px;
}
.server-details > div {
display: grid;
grid-template-columns: 140px minmax(0, 1fr);
gap: 20px;
padding: 14px 0;
border-bottom: 1px solid var(--color-border);
}
.server-details dt {
color: var(--color-muted);
}
.server-details dd {
margin: 0;
}
.document-file-list > a {
flex-wrap: wrap;
}
.document-file-list > a > span {
min-width: 0;
overflow-wrap: anywhere;
flex: 1;
}
.statistics-grid[hidden],
.statistics-kpis[hidden],
.statistics-empty[hidden] {
display: none;
}
+199
View File
@@ -0,0 +1,199 @@
import { iconSvg } from "../icons/icons.js";
import { mountMarkdown } from "./markdown.js";
import { mountCodeEditor } from "./code-editor.js";
import { escapeText } from "./text-runtime.js";
export function normalizeDocumentPath(value = "/") {
const parts = String(value).split("/").filter(Boolean);
if (
parts.length > 20 ||
parts.some((part) => part === ".." || part === "." || part.length > 128)
)
return null;
return "/" + parts.join("/");
}
export function mountDocuments(
root,
{ files, path = "/", onNavigate, hrefForPath, notify, t = (ru) => ru } = {},
) {
if (!(files instanceof Map))
throw new TypeError("Documents need a Map of path to file");
const abort = new AbortController(),
{ signal } = abort;
let editor,
markdown,
timer,
disposed = false;
path = normalizeDocumentPath(path);
const item = path && files.get(path),
name = path?.split("/").at(-1) || t("Документы", "Documents");
function download(value) {
const blob = new Blob([value], { type: "text/plain;charset=utf-8" }),
url = URL.createObjectURL(blob),
link = document.createElement("a");
link.href = url;
link.download = name;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 30000);
}
function error(message) {
notify?.(message, { type: "error" });
}
root.classList.add("documents-workspace");
const toolbar = `<div class="documents-toolbar"><span class="demo-label">${t("Тестовые документы · изменения в текущей вкладке", "Sample documents · changes stay in this tab")}</span><label class="document-open">${iconSvg("upload", { size: 16 })}<span>${t("Открыть .md", "Open .md")}</span><input type="file" accept=".md,.markdown,.txt" data-document-open></label>${item ? `<button type="button" data-document-download>${iconSvg("download", { size: 16 })}<span>${t("Скачать", "Download")}</span></button>` : ""}</div>`;
if (item) {
const isMarkdown = ["markdown", "md"].includes(item.language);
root.innerHTML =
toolbar +
`<div class="document-panes ${isMarkdown ? "document-split" : ""}"><div data-document-editor></div>${isMarkdown ? `<section class="document-preview"><h2>${t("Просмотр Markdown", "Markdown preview")}</h2><div data-markdown-preview></div></section>` : ""}</div>`;
if (isMarkdown) {
markdown = mountMarkdown(root.querySelector("[data-markdown-preview]"), {
source: item.content,
t,
});
markdown.ready.catch(() =>
error(t("Не удалось загрузить просмотр.", "Could not load preview.")),
);
}
editor = mountCodeEditor(root.querySelector("[data-document-editor]"), {
value: item.content,
language: item.language,
label: name,
t,
notify,
onSave: download,
onChange: (value) => {
item.content = value;
clearTimeout(timer);
if (markdown)
timer = setTimeout(
() =>
markdown
.setSource(value)
.catch(() =>
error(
t(
"Не удалось обновить просмотр.",
"Could not refresh preview.",
),
),
),
120,
);
},
});
root
.querySelector("[data-document-download]")
.addEventListener("click", () => download(editor.getValue()), { signal });
root.querySelector("[data-markdown-preview]")?.addEventListener(
"click",
(event) => {
const link = event.target.closest("a[href]");
if (
!link ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
event.altKey ||
link.target === "_blank"
)
return;
const raw = link.getAttribute("href");
if (!raw || raw.startsWith("#") || /^[a-z][a-z\d+.-]*:/i.test(raw))
return;
const next = normalizeDocumentPath(
decodeURIComponent(
new URL(raw, "https://documents.invalid" + path).pathname,
),
);
if (next && files.has(next) && onNavigate) {
event.preventDefault();
onNavigate(next);
}
},
{ signal },
);
} else {
const prefix = path === "/" ? "/" : path + "/",
children = new Map();
if (path)
for (const [file] of files) {
if (file.startsWith(prefix)) {
const rest = file.slice(prefix.length),
segment = rest.split("/")[0];
if (segment)
children.set(segment, {
folder: rest.includes("/"),
path: prefix + segment,
});
}
}
root.innerHTML =
toolbar +
`<div class="document-file-list">${
children.size
? [...children]
.sort(([a], [b]) => a.localeCompare(b))
.map(
([label, entry]) =>
`<a href="${escapeText(hrefForPath?.(entry.path) || "#")}" data-document-path="${escapeText(entry.path)}">${iconSvg(entry.folder ? "folder" : "document", { size: 20 })}<span>${escapeText(label)}</span><small>${entry.folder ? t("Папка", "Folder") : ""}</small></a>`,
)
.join("")
: `<div class="empty-state"><h2>${t("Папка не найдена", "Folder not found")}</h2><p>${t("Вернитесь к документам через хлебные крошки.", "Return to documents using the breadcrumbs.")}</p></div>`
}</div>`;
root.querySelectorAll("[data-document-path]").forEach((link) =>
link.addEventListener(
"click",
(event) => {
if (
onNavigate &&
!event.ctrlKey &&
!event.metaKey &&
!event.shiftKey &&
!event.altKey
) {
event.preventDefault();
onNavigate(link.dataset.documentPath);
}
},
{ signal },
),
);
}
root.querySelector("[data-document-open]").addEventListener(
"change",
async (event) => {
const file = event.target.files?.[0];
if (!file) return;
if (file.size > 131072) {
error(
t(
"Для этого редактора выберите файл до 128 КБ.",
"Choose a file up to 128 KB for this editor.",
),
);
return;
}
try {
const content = await file.text();
if (disposed) return;
if (content.split("\n").length > 4000) throw new RangeError();
const next = "/imports/" + file.name.replace(/[\\/]/g, "_");
files.set(next, { language: "markdown", content });
onNavigate?.(next);
} catch {
if (!disposed)
error(t("Не удалось открыть файл.", "Could not open the file."));
}
},
{ signal },
);
return {
dispose() {
disposed = true;
clearTimeout(timer);
abort.abort();
editor?.dispose();
markdown?.dispose();
},
};
}
+35
View File
@@ -105,6 +105,41 @@ export async function exportSystem(
"icons/anidev-dock-icons.zip",
...iconNames.map((name) => `icons/svg/${name}.svg`),
"components/system.css",
"components/content-workspaces.css",
"components/text-runtime.js",
"components/markdown.js",
"components/code-editor.js",
"components/charts.js",
"components/mini-log.js",
"components/breadcrumbs.js",
"components/documents.js",
"components/server-statistics.js",
"components/content-demo.js",
"patterns/demo-statistics.js",
"patterns/demo-documents.js",
"vendor/text/marked.js",
"vendor/text/marked.LICENSE",
"vendor/text/purify.js",
"vendor/text/dompurify.LICENSE",
"vendor/text/dompurify.MPL.LICENSE",
"vendor/text/highlight/core.js",
"vendor/text/highlight.LICENSE",
"vendor/text/manifest.json",
...[
"xml",
"javascript",
"typescript",
"json",
"yaml",
"bash",
"python",
"css",
"ini",
"nginx",
"sql",
"markdown",
].map((name) => `vendor/text/highlight/languages/${name}.js`),
"docs/CONTENT-WORKSPACES.md",
"components/toast.js",
"components/copy-field.js",
"components/error-page.js",
+166
View File
@@ -0,0 +1,166 @@
import {
loadTextRuntime,
highlightedCode,
normalizeLanguage,
} from "./text-runtime.js";
const versions = new WeakMap();
let sequence = 0;
export function mountMarkdown(
root,
{ source = "", headingPrefix, t = (ru) => ru } = {},
) {
const prefix = headingPrefix || `anidev-md-${++sequence}`;
let disposed = false;
root.classList.add("markdown-body");
async function setSource(value) {
const text = String(value);
if (text.length > 262144)
throw new RangeError("Markdown exceeds 262144 characters");
const ticket = {};
versions.set(root, ticket);
root.setAttribute("aria-busy", "true");
try {
const { marked, purify } = await loadTextRuntime();
const fragment = purify.sanitize(
marked.parse(text.replace(/^\uFEFF/, ""), {
gfm: true,
breaks: false,
async: false,
}),
{
RETURN_DOM_FRAGMENT: true,
ALLOWED_TAGS: [
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"p",
"br",
"hr",
"strong",
"em",
"del",
"blockquote",
"ul",
"ol",
"li",
"pre",
"code",
"a",
"table",
"thead",
"tbody",
"tr",
"th",
"td",
"img",
"input",
"details",
"summary",
"kbd",
"s",
"sup",
"sub",
],
ALLOWED_ATTR: [
"href",
"title",
"alt",
"src",
"class",
"start",
"type",
"checked",
"disabled",
"align",
],
},
);
const ids = new Map();
fragment.querySelectorAll("h1,h2,h3,h4,h5,h6").forEach((heading) => {
const slug =
heading.textContent
.trim()
.toLowerCase()
.replace(/[^\p{L}\p{N}\s-]/gu, "")
.replace(/\s+/g, "-") || "section";
const count = ids.get(slug) || 0;
ids.set(slug, count + 1);
heading.id = `${prefix}-${slug}${count ? "-" + count : ""}`;
});
fragment.querySelectorAll("a").forEach((link) => {
const href = link.getAttribute("href") || "";
if (href.startsWith("#")) {
let slug;
try {
slug = decodeURIComponent(href.slice(1));
} catch {
slug = href.slice(1);
}
if (ids.has(slug)) link.href = `#${prefix}-${slug}`;
} else {
let url;
try {
url = new URL(href, location.href);
} catch {
link.removeAttribute("href");
return;
}
if (!["http:", "https:", "mailto:", "tel:"].includes(url.protocol))
link.removeAttribute("href");
else if (
["http:", "https:"].includes(url.protocol) &&
url.origin !== location.origin
) {
link.target = "_blank";
link.rel = "noopener noreferrer";
}
}
});
fragment.querySelectorAll("img").forEach((img) => {
img.loading = "lazy";
img.decoding = "async";
});
fragment.querySelectorAll("input").forEach((input) => {
if (input.type !== "checkbox") input.remove();
else input.disabled = true;
});
await Promise.all(
[...fragment.querySelectorAll("pre > code")].map(async (code) => {
const match = [...code.classList].find((name) =>
name.startsWith("language-"),
);
const language = normalizeLanguage(match?.slice(9) || "plaintext");
code.innerHTML = await highlightedCode(code.textContent, language);
code.className = `hljs language-${language.replace(/[^\w-]/g, "")}`;
}),
);
if (disposed || versions.get(root) !== ticket) return;
root.replaceChildren(fragment);
} catch (error) {
if (!disposed && versions.get(root) === ticket) {
root.textContent = t(
"Не удалось отобразить документ.",
"Could not render the document.",
);
throw error;
}
} finally {
if (!disposed && versions.get(root) === ticket)
root.setAttribute("aria-busy", "false");
}
}
root.textContent = t("Загрузка документа…", "Loading document…");
const ready = setSource(source);
return {
ready,
setSource,
dispose() {
disposed = true;
versions.delete(root);
root.removeAttribute("aria-busy");
},
};
}
+66
View File
@@ -0,0 +1,66 @@
import { escapeText } from "./text-runtime.js";
const levelOf = (value) => {
const level = String(value || "INFO").toUpperCase();
return (
{ TRACE: "DEBUG", WARNING: "WARN", FATAL: "ERROR" }[level] ||
(["DEBUG", "INFO", "WARN", "ERROR"].includes(level) ? level : "INFO")
);
};
export function mountMiniLog(
root,
{ entries = [], limit = 8, title = "", onOpenFull, t = (ru) => ru } = {},
) {
const abort = new AbortController();
let disposed = false,
records = [];
limit = Math.max(1, Math.min(50, Math.trunc(limit) || 8));
root.classList.add("mini-log");
root.innerHTML = `<div class="mini-log-heading"><h3>${escapeText(title || t("Последние события", "Recent events"))}</h3>${onOpenFull ? `<button type="button" data-mini-full>${t("Все логи", "All logs")}</button>` : ""}</div><div class="mini-log-lines" role="list" aria-label="${t("Строки журнала", "Log entries")}"></div><p class="mini-log-empty" hidden>${t("Событий пока нет.", "No events yet.")}</p>`;
const lines = root.querySelector(".mini-log-lines"),
empty = root.querySelector(".mini-log-empty");
function render() {
if (disposed) return;
lines.replaceChildren();
empty.hidden = records.length > 0;
for (const entry of records.slice(-limit)) {
const row = document.createElement("div"),
time = document.createElement("time"),
level = document.createElement("span"),
message = document.createElement("span");
row.className = "mini-log-line";
row.dataset.level = levelOf(entry.level);
row.setAttribute("role", "listitem");
time.textContent = String(entry.time || entry.timestamp || "—");
level.className = "mini-log-level";
level.textContent = row.dataset.level;
message.className = "mini-log-message";
message.textContent =
(entry.source ? `${entry.source} · ` : "") +
String(entry.message ?? "");
row.append(time, level, message);
lines.append(row);
}
}
function update(next) {
if (!Array.isArray(next))
throw new TypeError("Log entries must be an array");
records = next.slice(-100);
render();
}
root
.querySelector("[data-mini-full]")
?.addEventListener("click", onOpenFull, { signal: abort.signal });
update(entries);
return {
update,
append(entry) {
records.push(entry);
records = records.slice(-100);
render();
},
dispose() {
disposed = true;
abort.abort();
},
};
}
+162
View File
@@ -0,0 +1,162 @@
import { mountChart } from "./charts.js";
import { mountMiniLog } from "./mini-log.js";
import { escapeText } from "./text-runtime.js";
export function statisticsMarkup({ title = "", t = (ru) => ru } = {}) {
return `<section class="server-statistics"><div class="statistics-toolbar"><div><h2>${escapeText(title || t("Статистика сервера", "Server statistics"))}</h2><p class="muted">${t("Показатели и события за выбранный период.", "Metrics and events for the selected period.")}</p></div><label>${t("Период", "Period")}<select data-statistics-range><option value="15m">${t("15 минут", "15 minutes")}</option><option value="1h" selected>${t("1 час", "1 hour")}</option><option value="24h">${t("24 часа", "24 hours")}</option></select></label></div><p class="statistics-empty muted" hidden></p><div class="statistics-kpis">${["cpu", "memory", "network"].map((key) => `<div class="statistics-kpi" data-kpi="${key}"><span></span><strong></strong><div data-stat-spark="${key}"></div></div>`).join("")}</div><div class="statistics-grid">${["cpu", "memory", "network", "disk", "requests", "errors", "storage", "gauge"].map((key) => `<div class="statistics-panel" data-stat-chart="${key}"></div>`).join("")}</div><div data-stat-mini-log></div></section>`;
}
export function mountStatistics(
root,
{ data, t = (ru) => ru, onRangeChange, onOpenLogs } = {},
) {
const abort = new AbortController();
let disposed = false,
charts = [],
logs;
function update(next) {
if (disposed) return;
charts.forEach((chart) => chart.dispose());
charts = [];
logs?.dispose();
const empty = root.querySelector(".statistics-empty");
empty.hidden = Boolean(next);
empty.textContent = next ? "" : t("Нет данных.", "No data.");
root.querySelector(".statistics-grid").hidden = !next;
root.querySelector(".statistics-kpis").hidden = !next;
root.querySelector("[data-stat-mini-log]").hidden = !next;
if (!next) return;
const labels = next.labels || [],
series = (name, values) => [{ name, values: values || [] }],
last = (values) => values?.at(-1) ?? 0;
root.querySelector("[data-statistics-range]").value = next.range || "1h";
const definitions = {
cpu: {
type: "area",
title: t("Загрузка CPU", "CPU utilization"),
unit: "%",
max: 100,
series: series("CPU", next.cpu),
},
memory: {
type: "line",
title: t("Оперативная память", "Memory"),
unit: t("ГБ", "GB"),
max: next.memoryTotal || 16,
series: series(t("Используется", "Used"), next.memory),
},
network: {
type: "line",
title: t("Сетевой трафик", "Network traffic"),
unit: t("МБ/с", "MB/s"),
series: [
{ name: t("Входящий", "Inbound"), values: next.networkIn || [] },
{ name: t("Исходящий", "Outbound"), values: next.networkOut || [] },
],
},
disk: {
type: "stacked",
title: t("Дисковые операции", "Disk I/O"),
unit: t("МБ/с", "MB/s"),
series: [
{ name: t("Чтение", "Read"), values: next.diskRead || [] },
{ name: t("Запись", "Write"), values: next.diskWrite || [] },
],
},
requests: {
type: "bar",
title: t("Запросы", "Requests"),
unit: t("запр./с", "req/s"),
series: series("HTTP", next.requests),
},
errors: {
type: "bar",
tone: "danger",
title: t("Ошибки сервиса", "Service errors"),
description: t(
"Количество 5xx в каждом интервале",
"5xx count per interval",
),
unit: t("шт.", "count"),
series: series("5xx", next.errors),
},
storage: {
type: "donut",
title: t("Дисковое пространство", "Storage allocation"),
unit: t("ГБ", "GB"),
series: (next.storage || []).map((item) => ({
name: item.name,
values: [item.value],
})),
},
gauge: {
type: "gauge",
title: t("CPU сейчас", "Current CPU"),
unit: "%",
max: 100,
series: series("CPU", [last(next.cpu)]),
},
};
for (const [key, options] of Object.entries(definitions))
charts.push(
mountChart(root.querySelector(`[data-stat-chart="${key}"]`), {
...options,
labels,
t,
}),
);
const kpis = {
cpu: {
label: t("CPU сейчас", "CPU now"),
value: `${last(next.cpu).toFixed(1)} %`,
values: next.cpu,
},
memory: {
label: t("Память сейчас", "Memory now"),
value: `${last(next.memory).toFixed(1)} / ${next.memoryTotal || 16} ${t("ГБ", "GB")}`,
values: next.memory,
},
network: {
label: t("Входящий трафик", "Inbound traffic"),
value: `${last(next.networkIn).toFixed(1)} ${t("МБ/с", "MB/s")}`,
values: next.networkIn,
},
};
for (const [key, item] of Object.entries(kpis)) {
const card = root.querySelector(`[data-kpi="${key}"]`);
card.querySelector("span").textContent = item.label;
card.querySelector("strong").textContent = item.value;
charts.push(
mountChart(card.querySelector("[data-stat-spark]"), {
type: "sparkline",
title: item.label,
series: series(item.label, item.values),
labels,
t,
}),
);
}
logs = mountMiniLog(root.querySelector("[data-stat-mini-log]"), {
entries: next.logs || [],
limit: 6,
title: t("Последние события сервера", "Recent server events"),
onOpenFull: onOpenLogs,
t,
});
}
root
.querySelector("[data-statistics-range]")
.addEventListener(
"change",
(event) => onRangeChange?.(event.target.value),
{ signal: abort.signal },
);
update(data);
return {
update,
dispose() {
disposed = true;
abort.abort();
charts.forEach((chart) => chart.dispose());
logs?.dispose();
},
};
}
+1
View File
@@ -1,5 +1,6 @@
@import url("./workspaces.css");
@import url("./mobile-dock.css");
@import url("./content-workspaces.css");
* {
box-sizing: border-box;
}
+78
View File
@@ -0,0 +1,78 @@
export const escapeText = (value) =>
String(value).replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
c
],
);
export const codeLanguages = Object.freeze([
"plaintext",
"markdown",
"yaml",
"json",
"javascript",
"typescript",
"python",
"bash",
"nginx",
"ini",
"xml",
"css",
"sql",
]);
export const normalizeLanguage = (value) =>
({
text: "plaintext",
txt: "plaintext",
md: "markdown",
yml: "yaml",
js: "javascript",
ts: "typescript",
sh: "bash",
html: "xml",
})[String(value).toLowerCase()] || String(value).toLowerCase();
let runtime;
export function loadTextRuntime() {
runtime ||= Promise.all([
import("../vendor/text/marked.js"),
import("../vendor/text/purify.js"),
import("../vendor/text/highlight/core.js"),
])
.then(async ([marked, purify, highlight]) => {
const hljs = highlight.default;
const languages = codeLanguages.filter(
(language) => language !== "plaintext",
);
const grammars = await Promise.all(
languages.map(
(language) =>
import(`../vendor/text/highlight/languages/${language}.js`),
),
);
languages.forEach((language, index) =>
hljs.registerLanguage(language, grammars[index].default),
);
return { marked: marked.marked, purify: purify.default, hljs };
})
.catch((error) => {
runtime = null;
throw error;
});
return runtime;
}
export async function highlightedCode(value, language = "plaintext") {
const text = String(value),
name = normalizeLanguage(language);
if (
name === "plaintext" ||
!codeLanguages.includes(name) ||
text.length > 65536
)
return escapeText(text);
const { hljs, purify } = await loadTextRuntime();
return purify.sanitize(
hljs.highlight(text, { language: name, ignoreIllegals: true }).value,
{ ALLOWED_TAGS: ["span"], ALLOWED_ATTR: ["class"] },
);
}
+4
View File
@@ -153,3 +153,7 @@ title/description/label/value — строки; rows — массив. Это п
## Проверка до подключения
`npm run test:package` после сборки проверяет изолированную копию фронта на тестовом HTTP-сервере. `npm run test:system-pages` при работающей галерее проверяет страницы ошибок в обеих темах и RU/EN. Для просмотра: dist/starter/?page=account, ?page=account-settings, ?page=error-404, ?page=error-500, ?page=error-502, ?page=account-banned. Последняя ссылка — только демонстрация; реальное состояние задаётся ответом сервера.
## Метрики и документы
[Модель статистики и компонентов содержимого](CONTENT-WORKSPACES.md) описывает следующий этап интеграции: backend отдаёт разрешённые вкладки, метрики выбранного сервера, документы и события, а frontend адаптирует ответ для отдельных контроллеров. Сейчас endpoints метрик/документов отсутствуют; галерея и starter используют явно обозначенные fixtures. Не выдавайте эти показатели за реальное наблюдение и не используйте демо-редактор как серверное хранилище.
+144
View File
@@ -0,0 +1,144 @@
# Документы, редактор и статистика
Предварительное расширение состава 1.0. Добавлено 02.12.2026; проверки отложены до утверждения пользователем. Данные галереи и starter — примеры, API сервера пока нет.
## Подключение
Подключите `components/system.css` и импортируйте нужные функции из `runtime/index.js` (или корня собранного пакета). Компоненты не выполняют API-запросы и не владеют маршрутизатором. При уходе со страницы вызывайте `dispose()` каждого контроллера. Демонстрационная сборка `components/content-demo.js` подключается отдельно и не является контрактом backend.
## Markdown
```js
import { mountMarkdown } from "./runtime/index.js";
const viewer = mountMarkdown(document.querySelector("#readme"), {
source: "# Сервер\n\nДокументация **Anidev**.",
});
await viewer.ready;
await viewer.setSource(nextMarkdown);
// При удалении экрана:
viewer.dispose();
```
Поддерживаются заголовки, ссылки, таблицы, списки, задачи, цитаты и блоки кода. Marked разбирает текст, DOMPurify очищает HTML по списку разрешённых элементов. Скрипты, формы, iframe и обработчики событий не входят в разрешённую разметку. Задачи отображаются выключенными чекбоксами. Ссылки ограничены HTTP(S), mailto, tel и относительными адресами. Ссылки на изображения могут обращаться к сети: политику разрешённых ресурсов задаёт приложение, например через CSP `img-src`. Не используйте HTML Markdown как доверенную разметку вне этого контроллера.
Предел — 262144 символа на документ; ошибки загрузки/рендера возвращаются через `ready`/`setSource`. Библиотеки хранятся локально в `vendor/text`; runtime не требует CDN. Обновление: `npm ci`, затем `npm run text:vendor`. Источники и лицензии — [Marked](https://marked.js.org/), [DOMPurify](https://github.com/cure53/DOMPurify), [Highlight.js](https://highlightjs.org/usage), `NOTICE.md` и `vendor/text/manifest.json`.
## Минималистичный редактор
```js
import { mountCodeEditor } from "./runtime/index.js";
const editor = mountCodeEditor(document.querySelector("#editor"), {
value: "server:\n port: 8080",
language: "yaml",
label: "gateway.yaml",
readOnly: false,
onChange(value) {
draft = value;
},
onSave(value) {
saveDraft(value);
},
notify(message, options) {
showToast(message, options);
},
});
editor.getValue();
editor.setValue(nextText);
editor.setLanguage("json");
editor.dispose();
```
Редактор содержит номера строк, подсветку, выбор языка, копирование и позицию курсора. Языки: plain text, HTML/XML, JavaScript, TypeScript, JSON, YAML, Bash, Python, CSS, INI, Nginx, SQL, Markdown. Tab/Shift+Tab меняют отступ, Enter сохраняет отступ, Ctrl/Cmd+S вызывает `onSave`. Ctrl/Cmd+M переключает захват Tab; есть такая же кнопка для выхода из режима отступов. Обычные copy/paste/undo остаются у текстового поля. Пределы: 131072 символа, 4000 строк; для текста свыше 65536 символов подсветка уступает место обычному тексту. Это редактор текста без исполнения кода, LSP и терминальных команд.
## Документы и хлебные крошки
`mountDocuments(root, { files, path, onNavigate, hrefForPath, notify, t })` принимает `Map`, где ключ — нормализованный абсолютный виртуальный путь, значение — `{ language, content }`. Возвращает `{ dispose }`. Дерево папок выводится из ключей. Markdown открывается рядом с редактором; YAML/JSON — в редакторе. Изменения обновляют переданную Map. Демопример позволяет открыть локальный `.md`/`.markdown`/`.txt` до 128 КБ и скачать результат. Сохранение на сервер не выполняется; смена аккаунта очищает демочерновики.
`normalizeDocumentPath(path)` возвращает нормализованный путь или `null`: до 20 сегментов, до 128 символов в сегменте, без `.`/`..`. Относительные ссылки внутри Markdown разрешаются относительно файла; переход к существующему виртуальному файлу передаётся `onNavigate`.
```js
import { breadcrumbsMarkup, mountBreadcrumbs } from "./runtime/index.js";
root.innerHTML = breadcrumbsMarkup({
items: [
{ label: "anidev", href: "/" },
{ label: "some", href: "/some" },
{ label: "fee", href: "/some/fee" },
{ label: "foo" },
],
});
const dispose = mountBreadcrumbs(root, {
onNavigate(url) {
router.navigate(url.pathname + url.search);
},
});
```
Родительские элементы — ссылки; последний — текущая страница. Контроллер перехватывает только обычные переходы в пределах origin и сохраняет браузерные модификаторы. История и маршруты принадлежат приложению. В демо работают вложенные документы и `anidev / Серверы / edge-01 / Статистика` через query-параметры `page`, `path`, `server`.
## Графики
```js
import { mountChart } from "./runtime/index.js";
const chart = mountChart(root, {
type: "line",
title: "CPU",
unit: "%",
max: 100,
labels: ["12:00", "12:05", "12:10"],
series: [{ name: "CPU", values: [18, 32, 24] }],
});
chart.update({ series: [{ name: "CPU", values: [20, 35, 29] }] });
chart.dispose();
```
Варианты: `line`, `area`, `bar`, `stacked`, `donut`, `gauge`, `sparkline`. Дополнительные параметры: `description`, `tone` (`danger`/`warning`), `t`. Значения выводятся при наведении; стрелки, Home/End перемещают указатель, Escape скрывает подсказку. Кроме sparkline доступна таблица числовых данных. Пределы: 8 рядов, 120 точек; значения — конечные числа или `null` для пропуска. Для stacked/donut/gauge значения неотрицательные. Для donut каждый ряд содержит одно значение. Это SVG без отдельной chart-библиотеки, не замена хранилищу временных рядов: агрегация длинных периодов должна происходить в приложении/API.
## Мини-логи
```js
import { mountMiniLog } from "./runtime/index.js";
const log = mountMiniLog(root, {
title: "События",
limit: 6,
entries: [
{ time: "12:10:03", level: "WARN", source: "disk", message: "Мало места" },
],
onOpenFull() {
router.navigate("/logs");
},
});
log.append({ time: "12:11:00", level: "INFO", message: "Ротация завершена" });
log.update(nextEntries);
log.dispose();
```
Вся строка получает цвет своего уровня; рядом остаётся текст DEBUG/INFO/WARN/ERROR. TRACE → DEBUG, WARNING → WARN, FATAL → ERROR. `limit` — от 1 до 50, внутри сохраняется не более 100 записей. Нет подключения к потоку, фильтров или таймера. Для поиска и большого потока используйте полный log-reader.
## Шаблон статистики сервера и будущий API
`statisticsMarkup({ title, t })` создаёт разметку. `mountStatistics(root, { data, onRangeChange, onOpenLogs, t })` возвращает `{ update, dispose }`. В `root` должна находиться созданная разметка `.server-statistics`.
```js
const data = {
range: "1h",
labels: ["12:00", "12:05"],
cpu: [25, 30],
memory: [3.1, 3.2],
memoryTotal: 8,
networkIn: [2, 3],
networkOut: [1, 1.5],
diskRead: [4, 6],
diskWrite: [1, 2],
requests: [100, 120],
errors: [0, 1],
storage: [
{ name: "Использовано", value: 30 },
{ name: "Свободно", value: 70 },
],
logs: [{ time: "12:05:00", level: "INFO", message: "Сервер доступен" }],
};
```
Единицы фиксированы шаблоном: CPU — %, память/диск — ГБ, сеть/дисковые операции — МБ/с, запросы — запросов/с, errors — число 5xx за интервал. Массивы согласованы с `labels`; `range` — `15m`, `1h` или `24h`. Шаблон показывает 8 графиков и 3 KPI со sparkline. Демо содержит два сервера и воспроизводимые тестовые показатели, а не наблюдение за текущей машиной.
Когда появится backend, frontend получает разрешённое меню по существующему контракту панели и запрашивает метрики выбранного сервера отдельно. Имя endpoint не закреплено: например, приложение может адаптировать ответ `GET /servers/{id}/statistics?range=1h` к модели выше. `onRangeChange` должен отменить прошлый запрос, показать загрузку и применить только актуальный ответ. Ответы без доступа/ошибки/недоступность отображаются существующими системными состояниями; `update(null)` означает отсутствие данных, не ошибку сервера. Backend проверяет сессию и доступ к серверу на каждом запросе. Документы, редактор и логи используют собственные endpoints; разрешения, маршрутизация, сохранение, CSP и управление соединениями остаются у приложения.
+4
View File
@@ -47,3 +47,7 @@ CSS применяется глобально и не поддерживает
## Операционные модули
Отдельные импорты `components/ssh-console.js` и `components/log-reader.js` (npm subpaths `/ssh`, `/logs`) — дополнительные модули, вне основного barrel. Их текущие экраны и demo PTY предназначены для интеграционного примера; backend не реализован. [WORKSPACES](../patterns/WORKSPACES.md) описывает transport, ограничения клавиш и cleanup. Подключение реального SSO, SSH и логов принадлежит конкретному продукту.
## Документы, редактор, графики и мини-логи
Публичные экспорты: `breadcrumbsMarkup`, `mountBreadcrumbs`, `mountMarkdown`, `mountCodeEditor`, `mountChart`, `mountMiniLog`, `statisticsMarkup`, `mountStatistics`, `mountDocuments`, `normalizeDocumentPath`. Контракты, единицы измерения, ограничения и примеры — [CONTENT-WORKSPACES.md](CONTENT-WORKSPACES.md). Демонстрационная сборка экранов доступна отдельно через `@anidev/design-system/content-demo`; основной runtime не импортирует тестовые документы/метрики.
+15
View File
@@ -12,6 +12,11 @@
"id": "projects",
"label": "Проекты",
"icon": "applications"
},
{
"id": "documents",
"label": "Документы",
"icon": "document"
}
]
},
@@ -37,8 +42,18 @@
"id": "logs",
"label": "Логи",
"icon": "document"
},
{
"id": "statistics",
"label": "Статистика сервера",
"icon": "server"
}
]
},
{
"id": "documents",
"label": "Документы",
"icon": "document"
}
]
}
+3 -1
View File
@@ -83,6 +83,8 @@ body.dock-open .nav-empty {
flex-wrap: wrap;
}
.breadcrumb {
display: none;
display: block;
min-width: 0;
flex: 1 1 200px;
}
}
+103 -3
View File
@@ -1,5 +1,7 @@
import {
applyTheme,
breadcrumbsMarkup,
mountBreadcrumbs,
iconSvg,
createNotifier,
mountCopyField,
@@ -12,6 +14,14 @@ import {
searchSelectMarkup,
mountSearchSelect,
} from "./anidev/runtime/index.js";
import {
contentDemoPages,
contentDemoMarkup,
mountContentDemo,
contentBreadcrumbs,
contentHref,
createDemoDocuments,
} from "./anidev/components/content-demo.js";
const $ = (selector) => document.querySelector(selector),
t = (ru) => ru;
@@ -21,7 +31,10 @@ const abort = new AbortController(),
const notify = createNotifier($("#project-toast"), { t });
const cleanups = [];
let syncAccountTheme = () => {};
const pageIds = new Set(["overview", "projects", "logs"]);
const pageIds = new Set(["overview", "projects", "logs", ...contentDemoPages]);
const documentFiles = createDemoDocuments();
let contentCleanup = () => {},
breadcrumbCleanup = () => {};
let allowedIds = new Set(),
serviceHome = null;
let mobilePages = new Map();
@@ -93,6 +106,13 @@ function urlFor(id, push = false) {
}
let sessionCleanup = () => {};
function showSession(error = { status: 401 }) {
contentCleanup();
contentCleanup = () => {};
breadcrumbCleanup();
breadcrumbCleanup = () => {};
documentFiles.clear();
for (const [path, file] of createDemoDocuments())
documentFiles.set(path, file);
pageRequest?.abort();
pageRequest = undefined;
menuRequest?.abort();
@@ -238,6 +258,8 @@ async function showPage(id) {
return;
}
pageRequest?.abort();
contentCleanup();
contentCleanup = () => {};
errorCleanup();
errorCleanup = () => {};
const request = (pageRequest = new AbortController()),
@@ -247,6 +269,7 @@ async function showPage(id) {
$(".page-heading").hidden = false;
$(".integration-form").hidden = true;
accountMenu.setActive(id);
renderBreadcrumbs(id);
mobileDock.update(id, `${identity.panel}:${identity.id || "account"}`);
if (["account", "account-settings"].includes(id)) {
renderAccount(id);
@@ -321,10 +344,51 @@ async function showPage(id) {
displayError(404);
return;
}
if (!allowedIds.has(id)) {
if (
!allowedIds.has(id) &&
!(["server", "servers"].includes(id) && allowedIds.has("statistics"))
) {
displayError(403);
return;
}
if (contentDemoPages.includes(id)) {
$(".page-heading").hidden = true;
const url = new URL(location.href),
server = url.searchParams.get("server") || "edge-01",
path = url.searchParams.get("path") || "/";
container.innerHTML = contentDemoMarkup(id, {
server,
path,
t,
heading: (title, description) =>
`<div class="page-heading"><div><h1></h1><p></p></div></div>`,
});
const heading = container.querySelector(".page-heading");
if (heading) {
const names = {
documents: "Документы и код",
servers: "Серверы",
server,
statistics: `Статистика · ${server}`,
};
heading.querySelector("h1").textContent = names[id];
heading.querySelector("p").textContent =
"Демонстрационные данные · API пока не подключено.";
}
contentCleanup = mountContentDemo(
container.querySelector("[data-content-demo]"),
{
page: id,
server,
path,
files: documentFiles,
onNavigate: visitContentURL,
notify,
t,
},
);
return;
}
container.setAttribute("aria-busy", "true");
try {
const data = await get(`pages/${id}.json`, request.signal);
@@ -425,7 +489,12 @@ const mobileDock = mountMobileDock($(".navigation"), {
if (personal[id])
return { id, label: personal[id][0], icon: personal[id][1] };
if (preview(id)) return { id, label: "Состояние", icon: "warning" };
return mobilePages.get(id) || null;
return (
mobilePages.get(id) ||
(["servers", "server"].includes(id) && mobilePages.has("statistics")
? { id, label: id === "servers" ? "Серверы" : "Сервер", icon: "server" }
: null)
);
},
});
const navigation = mountNavigation($(".nav-links"), {
@@ -456,6 +525,35 @@ function go(id, push = true) {
urlFor(id, push);
showPage(id);
}
function renderBreadcrumbs(id) {
breadcrumbCleanup();
const url = new URL(location.href);
const personalNames = {
account: "Управление",
"account-security": "Безопасность",
"account-sessions": "Устройства и сеансы",
"account-settings": "Настройки",
};
const items = contentDemoPages.includes(id)
? contentBreadcrumbs(id, {
server: url.searchParams.get("server") || "edge-01",
path: url.searchParams.get("path") || "/",
rootPage: "overview",
t,
})
: [
{ label: "anidev", href: contentHref({ page: "overview" }) },
{ label: personalNames[id] || mobilePages.get(id)?.label || "Панель" },
];
$(".breadcrumb").innerHTML = breadcrumbsMarkup({ items, t });
breadcrumbCleanup = mountBreadcrumbs($(".breadcrumbs"), {
onNavigate: visitContentURL,
});
}
function visitContentURL(url) {
history.pushState({}, "", url);
go(url.searchParams.get("page") || "overview", false);
}
async function loadAccount() {
accountRequest?.abort();
const request = (accountRequest = new AbortController());
@@ -658,6 +756,8 @@ function dispose() {
accountRequest?.abort();
errorCleanup();
sessionCleanup();
contentCleanup();
breadcrumbCleanup();
abort.abort();
cleanups.forEach((cleanup) => cleanup());
navigation.dispose();
+59 -2
View File
@@ -8,14 +8,34 @@
"name": "anidev-design-system",
"version": "0.2.0",
"dependencies": {
"@highlightjs/cdn-assets": "11.12.0",
"@xterm/addon-fit": "0.11.0",
"@xterm/addon-search": "0.16.0",
"@xterm/xterm": "6.0.0"
"@xterm/xterm": "6.0.0",
"dompurify": "3.5.1",
"marked": "18.4.0"
},
"devDependencies": {
"playwright": "^1.58.0"
"playwright": "^1.58.0",
"prettier": "3.10.1"
}
},
"node_modules/@highlightjs/cdn-assets": {
"version": "11.12.0",
"resolved": "https://registry.npmjs.org/@highlightjs/cdn-assets/-/cdn-assets-11.12.0.tgz",
"integrity": "sha512-KvOKXODaiFmId9xaq3xc5xCL66wVLUuOngDbO9B/kewbFTqdGbn2nJxNhN3H5R1cgDTVj6R8vH0zgiNDEGjpDw==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT",
"optional": true
},
"node_modules/@xterm/addon-fit": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",
@@ -37,6 +57,27 @@
"addons/*"
]
},
"node_modules/dompurify": {
"version": "3.5.1",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.5.1.tgz",
"integrity": "sha512-9fRTM0QJhaSDzR2y4Ym59AW3J3wvNIsQrFQmDilCsExEA/Daks2t5UXh75tE38PB7v8S2/3+JP1UT89Zo9YvEg==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
},
"node_modules/marked": {
"version": "18.4.0",
"resolved": "https://registry.npmjs.org/marked/-/marked-18.4.0.tgz",
"integrity": "sha512-evbvoaiBPFO2lk2kSkIbrwjPMuX/HjKyefPdZbtwccsJWY91xlLF/SzB5hRsAOwStztmKC09i+IGsUcTYMt//A==",
"license": "MIT",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 20"
}
},
"node_modules/playwright": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
@@ -65,6 +106,22 @@
"engines": {
"node": ">=20"
}
},
"node_modules/prettier": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.10.1.tgz",
"integrity": "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
}
}
}
+7 -2
View File
@@ -4,6 +4,7 @@
"private": true,
"type": "module",
"scripts": {
"text:vendor": "node scripts/vendor-text.mjs",
"build:package": "node scripts/check.mjs && node scripts/build-package.mjs",
"package:archives": "python scripts/package-release.py",
"test:package": "node tests/package.mjs",
@@ -26,11 +27,15 @@
"test:feedback": "node tests/navigation-feedback.mjs"
},
"devDependencies": {
"playwright": "^1.58.0"
"playwright": "^1.58.0",
"prettier": "3.10.1"
},
"dependencies": {
"@highlightjs/cdn-assets": "11.12.0",
"@xterm/addon-fit": "0.11.0",
"@xterm/addon-search": "0.16.0",
"@xterm/xterm": "6.0.0"
"@xterm/xterm": "6.0.0",
"dompurify": "3.5.1",
"marked": "18.4.0"
}
}
+36
View File
@@ -0,0 +1,36 @@
export function createDemoDocuments() {
return new Map([
[
"/server-guide.md",
{
language: "markdown",
content:
"# Руководство сервера\n\nДокумент в формате **Markdown**. Это тестовый пример для Anidev.\n\n## Мониторинг\n\n- CPU и память\n- Входящий и исходящий трафик\n- Диски и журнал событий\n\n> Перед изменением конфигурации сохраните текущую версию.\n\n| Параметр | Значение |\n| --- | --- |\n| Регион | eu-central-1 |\n| Проверка | Каждые 60 секунд |\n\n## Проверка состояния\n\n```bash\nsystemctl status anidev-gateway\njournalctl -u anidev-gateway -n 50\n```\n\n### Чеклист\n\n- [x] Сервис запущен\n- [x] Логи доступны\n- [ ] Подключить реальное API\n",
},
],
[
"/some/fee/foo/README.md",
{
language: "markdown",
content:
"# anidev / some / fee / foo\n\nКаждый родитель в **хлебных крошках** можно открыть.\n\n## Конфигурация\n\nВ этой папке лежат `gateway.yaml` и этот документ.\n\n```yaml\nserver:\n name: edge-01\n region: eu-central-1\n monitoring: true\n```\n\n## Возможности редактора\n\n1. Номера строк и подсветка.\n2. Отступ по Tab и автоматический перенос с отступом.\n3. Ctrl+M переключает Tab между отступом и переходом к следующему элементу.\n\n[К конфигурации](./gateway.yaml)\n\nИзменения этого примера остаются в текущей вкладке.\n",
},
],
[
"/some/fee/foo/gateway.yaml",
{
language: "yaml",
content:
"# Anidev gateway — демонстрационная конфигурация\nserver:\n name: edge-01\n region: eu-central-1\n port: 8443\n\nmonitoring:\n enabled: true\n interval: 60\n logs:\n level: info\n retention_days: 30\n",
},
],
[
"/some/fee/metrics.json",
{
language: "json",
content:
'{\n "server": "edge-01",\n "metrics": ["cpu", "memory", "network", "disk"],\n "intervalSeconds": 60\n}\n',
},
],
]);
}
+90
View File
@@ -0,0 +1,90 @@
export const demoServers = [
{
id: "edge-01",
name: "edge-01",
region: "eu-central-1",
os: "Ubuntu 24.04 LTS",
cpu: 8,
memory: 16,
},
{
id: "worker-02",
name: "worker-02",
region: "eu-central-1",
os: "Debian 12",
cpu: 4,
memory: 8,
},
];
export function createDemoStatistics(range = "1h", server = "edge-01") {
const minutes = { "15m": 15, "1h": 60, "24h": 1440 }[range] || 60,
phase = server === "worker-02" ? 1.7 : 0;
const labels = Array.from({ length: 24 }, (_, index) => {
const total = Math.round((index * minutes) / 23);
return `${String(Math.floor(total / 60)).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`;
});
const values = (base, amplitude, offset = 0) =>
labels.map(
(_, index) =>
Math.round(
(base +
Math.sin(index * 0.65 + offset + phase) * amplitude +
Math.cos(index * 1.3 + offset) * amplitude * 0.2) *
100,
) / 100,
);
return {
range,
server,
labels,
memoryTotal: server === "worker-02" ? 8 : 16,
cpu: values(48, 18),
memory: values(
server === "worker-02" ? 5.1 : 10.2,
server === "worker-02" ? 0.65 : 1.3,
),
networkIn: values(24, 12),
networkOut: values(9, 5, 1.2),
diskRead: values(42, 22, 0.5),
diskWrite: values(16, 8, 2),
requests: values(320, 130).map(Math.round),
errors: values(2, 2).map((value) => Math.max(0, Math.round(value))),
storage: [
{ name: "Система", value: 28 },
{ name: "Данные", value: 94 },
{ name: "Свободно", value: 78 },
],
logs: [
{
time: "12:14:08",
level: "DEBUG",
source: "scheduler",
message: "Проверка очереди задач",
},
{
time: "12:14:10",
level: "INFO",
source: "gateway",
message: "Соединение с upstream восстановлено",
},
{
time: "12:14:12",
level: "WARN",
source: "disk",
message: "Задержка записи выше обычной: 48 мс",
},
{
time: "12:14:14",
level: "ERROR",
source: "worker",
message: "Задача завершилась по таймауту; запланирован повтор",
},
{
time: "12:14:16",
level: "INFO",
source: "worker",
message: "Повторная обработка завершена",
},
],
};
}
+154 -13
View File
@@ -5,6 +5,18 @@ import {
} from "../components/search-select.js";
import { createNotifier } from "../components/toast.js";
import { mountCopyField } from "../components/copy-field.js";
import {
breadcrumbsMarkup,
mountBreadcrumbs,
} from "../components/breadcrumbs.js";
import {
contentDemoPages,
contentDemoMarkup,
mountContentDemo,
contentBreadcrumbs,
contentHref,
createDemoDocuments,
} from "../components/content-demo.js";
import {
mountMobileDock,
createMobileHistory,
@@ -38,6 +50,8 @@ import {
import { exportSystem } from "../components/export-system.js";
const identityAdapter = createDemoIdentityAdapter();
const mobileHistory = createMobileHistory();
const documentFiles = createDemoDocuments();
let documentOwner = null;
let preferences = {};
try {
preferences =
@@ -192,6 +206,10 @@ let page = [
"ssh",
"logs",
"errors",
"documents",
"servers",
"server",
"statistics",
...accountPageIds,
].includes(params.get("page"))
? params.get("page")
@@ -209,6 +227,10 @@ let query = "",
tab = "general",
chartRange = "24h";
const pageNames = {
documents: t("Документы", "Documents"),
servers: t("Серверы", "Servers"),
server: t("Сервер", "Server"),
statistics: t("Статистика сервера", "Server statistics"),
errors: t("Страницы ошибок", "Error pages"),
ssh: t("SSH-консоль", "SSH console"),
logs: t("Журнал событий", "Log reader"),
@@ -232,6 +254,10 @@ const icon = (id) =>
logs: "document",
administration: "server",
errors: "warning",
documents: "document",
statistics: "server",
servers: "server",
server: "server",
}[id] || id,
{
className: "nav-icon",
@@ -262,11 +288,12 @@ function accountInitials() {
}
function navigationPages() {
return panel === "user"
? ["dashboard"]
? ["dashboard", "documents"]
: [
"dashboard",
"users",
"settings",
"documents",
"administration",
"components",
"tokens",
@@ -302,13 +329,21 @@ ${currentIdentity()?.roles.some((r) => ["Master Admin", "SSO Admin"].includes(r)
<button class="account-separator" data-identity="logout">${icon("logout")}<span>${t("Выйти из SSO", "Sign out of SSO")}</span></button>${themeControlMarkup({ theme, t })}</div>
<button class="dock-account" popovertarget="account-menu" aria-label="${escape(t("Меню аккаунта ", "Account menu ") + accountName())}"><span class="avatar">${currentIdentity()?.avatar ? `<img src="${escape(currentIdentity().avatar)}" alt="">` : escape(accountInitials())}</span><span class="account-identity"><b>${escape(accountName())}</b><small>${escape(currentIdentity()?.username || "Anidev Identity")}</small></span><span class="account-more" aria-hidden="true">···</span></button></div>`;
}
let administrationOpen = ["ssh", "logs"].includes(page);
let administrationOpen = [
"ssh",
"logs",
"statistics",
"servers",
"server",
].includes(page);
function navPage(id, label = pageNames[id]) {
return `<button data-page="${id}" ${page === id ? 'aria-current="page"' : ""} title="${label}" aria-label="${label}">${icon(id)}<span>${label}</span></button>`;
}
function administrationNav() {
const active = ["ssh", "logs"].includes(page);
return `<div class="nav-group" data-nav-group="administration"><button type="button" class="nav-group-toggle" data-action="administration-toggle" aria-expanded="false" aria-controls="administration-submenu" data-active="${active}" title="${t("Администрирование", "Administration")}" aria-label="${t("Администрирование", "Administration")}">${icon("administration")}<span class="nav-group-label">${t("Администрирование", "Administration")}${iconSvg("chevron-down", { size: 16, className: "nav-chevron" })}</span></button><div class="nav-submenu-container" id="administration-submenu" aria-hidden="true" inert><div class="nav-submenu-clip"><div class="nav-submenu-list">${navPage("ssh")}${navPage("logs", t("Логи", "Logs"))}</div></div></div></div>`;
const active = ["ssh", "logs", "statistics", "servers", "server"].includes(
page,
);
return `<div class="nav-group" data-nav-group="administration"><button type="button" class="nav-group-toggle" data-action="administration-toggle" aria-expanded="false" aria-controls="administration-submenu" data-active="${active}" title="${t("Администрирование", "Administration")}" aria-label="${t("Администрирование", "Administration")}">${icon("administration")}<span class="nav-group-label">${t("Администрирование", "Administration")}${iconSvg("chevron-down", { size: 16, className: "nav-chevron" })}</span></button><div class="nav-submenu-container" id="administration-submenu" aria-hidden="true" inert><div class="nav-submenu-clip"><div class="nav-submenu-list">${navPage("ssh")}${navPage("logs", t("Логи", "Logs"))}${navPage("statistics")}</div></div></div></div>`;
}
function syncAdministration() {
const group = $("[data-nav-group=administration]");
@@ -345,7 +380,40 @@ const commandShortcut = /Mac|iPhone|iPad/.test(navigator.platform)
? "⌘ K"
: "Ctrl K";
function header() {
return `<header class="app-header"><button class="mobile-menu" data-action="mobile-menu" aria-label="${t("Открыть навигацию", "Open navigation")}" aria-expanded="false">☰</button><div class="breadcrumb">Anidev <span aria-hidden="true">/</span> ${accountPageIds.includes(page) ? t("Личный кабинет", "My account") : "Production"} <span aria-hidden="true">/</span> ${pageNames[page]}</div><div class="header-actions"><button class="command-trigger" data-action="command" data-shortcut="${commandShortcut}" aria-label="${t("Найти команду", "Find a command")} (${commandShortcut})">${t("Найти команду", "Find a command")} <kbd>${commandShortcut}</kbd></button><button class="avatar" data-action="profile" aria-label="${escape(accountName())}">${escape(accountInitials())}</button></div></header>`;
const route = new URL(location.href),
personal = panel === "user",
root = {
label: "anidev",
href: contentHref({
page: "dashboard",
panel: personal ? "user" : "admin",
}),
};
const items = contentDemoPages.includes(page)
? contentBreadcrumbs(page, {
server: route.searchParams.get("server") || "edge-01",
path: route.searchParams.get("path") || "/",
t,
})
: [
root,
...(page !== "dashboard" && page !== "profile"
? [
{
label: personal
? t("Аккаунт", "Account")
: t("Панель управления", "Control panel"),
href: contentHref({
page: personal ? "profile" : "dashboard",
panel,
}),
},
]
: []),
{ label: pageNames[page] },
];
const breadcrumb = breadcrumbsMarkup({ items, t });
return `<header class="app-header"><button class="mobile-menu" data-action="mobile-menu" aria-label="${t("Открыть навигацию", "Open navigation")}" aria-expanded="false">☰</button>${breadcrumb}<div class="header-actions"><button class="command-trigger" data-action="command" data-shortcut="${commandShortcut}" aria-label="${t("Найти команду", "Find a command")} (${commandShortcut})">${t("Найти команду", "Find a command")} <kbd>${commandShortcut}</kbd></button><button class="avatar" data-action="profile" aria-label="${escape(accountName())}">${escape(accountInitials())}</button></div></header>`;
}
const heading = (title, desc, actions = "") =>
`<div class="page-heading"><div><div class="overline">ANIDEV://PRODUCTION/${page.toUpperCase()}</div><h1>${title}</h1><p>${desc}</p></div><div class="heading-actions">${actions}</div></div>`;
@@ -431,6 +499,13 @@ function render({ preserveDock = false } = {}) {
workspaceCleanup = () => {};
const workspaceVersion = ++workspaceRender;
const signedIn = identityAdapter.snapshot().status === "authenticated";
const owner = signedIn ? currentIdentity()?.sub : null;
if (owner !== documentOwner) {
documentFiles.clear();
for (const [path, file] of createDemoDocuments())
documentFiles.set(path, file);
documentOwner = owner;
}
if (
accountPageIds.includes(page) ||
!currentIdentity()?.roles.some((role) =>
@@ -473,7 +548,15 @@ function render({ preserveDock = false } = {}) {
: identityAdapter.snapshot().status !== "authenticated" &&
!["components", "tokens", "auth", "errors"].includes(page)
? accountUI.gate()
: ["users", "settings", "ssh", "logs"].includes(page) &&
: [
"users",
"settings",
"ssh",
"logs",
"statistics",
"servers",
"server",
].includes(page) &&
!currentIdentity()?.roles.some((r) =>
["Master Admin", "SSO Admin"].includes(r),
)
@@ -484,6 +567,24 @@ function render({ preserveDock = false } = {}) {
dashboard: panel === "admin" ? dashboard : userOverview,
users: userScreen,
settings: settingsScreen,
documents: () => contentDemoMarkup("documents", { heading, t }),
servers: () => contentDemoMarkup("servers", { heading, t }),
server: () =>
contentDemoMarkup("server", {
heading,
t,
server:
new URL(location.href).searchParams.get("server") ||
"edge-01",
}),
statistics: () =>
contentDemoMarkup("statistics", {
heading,
t,
server:
new URL(location.href).searchParams.get("server") ||
"edge-01",
}),
components: componentScreen,
errors: errorScreen,
tokens: tokenScreen,
@@ -499,6 +600,20 @@ function render({ preserveDock = false } = {}) {
bindDockHover();
if (dockWasOpen) setDockOpen(true, false);
bindCharts();
if ($(".breadcrumbs"))
selectCleanups.push(
mountBreadcrumbs($(".breadcrumbs"), { onNavigate: visitContentURL }),
);
if (contentDemoPages.includes(page) && $("[data-content-demo]"))
workspaceCleanup = mountContentDemo($("[data-content-demo]"), {
page,
server: new URL(location.href).searchParams.get("server") || "edge-01",
path: new URL(location.href).searchParams.get("path") || "/",
files: documentFiles,
onNavigate: visitContentURL,
notify: toast,
t,
});
if ($(".navigation")) {
const mobile = mountMobileDock($(".navigation"), {
trigger: $(".dock-brand"),
@@ -507,19 +622,37 @@ function render({ preserveDock = false } = {}) {
getPage: (id) => {
const allowed = [
"dashboard",
"documents",
...accountPageIds,
"components",
"tokens",
"errors",
...(panel === "admin" ? ["users", "settings", "ssh", "logs"] : []),
...(panel === "admin"
? [
"users",
"settings",
"ssh",
"logs",
"statistics",
"servers",
"server",
]
: []),
];
return allowed.includes(id) && pageNames[id]
? {
id,
label: pageNames[id],
icon:
{ ssh: "terminal", logs: "document", errors: "warning" }[id] ||
id,
{
ssh: "terminal",
logs: "document",
errors: "warning",
documents: "document",
statistics: "server",
servers: "server",
server: "server",
}[id] || id,
}
: null;
},
@@ -838,6 +971,11 @@ function settingsScreen() {
function auth() {
return `<main id="content" class="auth-layout" style="max-width:none;padding:0"><section class="auth-brand">${wordmark}<div class="auth-statement">${t("Ваша инфраструктура.<br>Под вашим контролем.", "Your infrastructure.<br>Under your control.")}</div><small>ANIDEV IDENTITY / ${t("ДЕМОНСТРАЦИЯ", "DEMONSTRATION")}</small></section><section class="auth-main"><form id="auth-form" class="auth-form"><h1>${t("Вход в Anidev", "Sign in to Anidev")}</h1><p>${t("Продолжите работу с вашим пространством.", "Continue to your workspace.")}</p><label class="field">${t("Username или email", "Username or email")}<input name="email" type="text" autocomplete="username" placeholder="anna.volkova" required></label><label class="field">${t("Пароль", "Password")}<input name="password" type="password" autocomplete="current-password" minlength="8" required aria-describedby="password-hint"><small id="password-hint">${t("Демо: anna.volkova или mikhail.orlov; пароль от 8 символов.", "Demo: anna.volkova or mikhail.orlov; password of 8+ characters.")}</small></label><div class="form-row"><input id="remember" type="checkbox"><label for="remember">${t("Запомнить меня", "Remember me")}</label><button class="row-action" type="button" data-action="recover">${t("Забыли пароль?", "Forgot password?")}</button></div><p class="error-text" id="auth-error" role="alert"></p><button class="primary" type="submit">${t("Войти", "Sign in")}</button><div class="auth-divider">${t("или корпоративный аккаунт", "or your company account")}</div><button type="button" class="sso" data-action="sso">${t("Войти через SSO", "Continue with SSO")}</button><div class="auth-foot"><span>© Anidev 2026</span><button class="row-action" type="button" data-page="dashboard">${t("Вернуться к обзору", "Back to overview")}</button></div></form></section></main>`;
}
function visitContentURL(url) {
history.pushState({}, "", url);
dispatchEvent(new PopStateEvent("popstate"));
$("#content")?.focus({ preventScroll: true });
}
function userOverview() {
return (
heading(
@@ -893,7 +1031,7 @@ function componentScreen() {
)
.join("")}</div></section>
<section class="specimen status-specimen"><h2>${t("Статусы", "Status indicators")}</h2><div class="component-row status-examples"><span class="status-badge status-badge--success">${iconSvg("check", { size: 16 })}${t("Работает", "Operational")}</span><span class="status-badge status-badge--danger">${iconSvg("close", { size: 16 })}${t("Недоступен", "Unavailable")}</span><span class="status-badge status-badge--pending">${iconSvg("more-horizontal", { size: 16 })}${t("Ожидает", "Pending")}</span></div><p class="muted" style="font-size:13px">${t("Состояние выражено текстом, а не только цветом.", "Status uses text as well as color.")}</p></section>
<section class="specimen"><h2>${t("Рабочие области", "Workspaces")}</h2><p class="muted">${t("SSH-терминал и ридер логов в стиле Dock.", "SSH terminal and log reader in Dock style.")}</p><div class="component-row"><button data-page="ssh">${t("SSH-консоль", "SSH console")}</button><button data-page="logs">${t("Log-ридер", "Log reader")}</button></div></section>
<section class="specimen"><h2>${t("Рабочие области", "Workspaces")}</h2><p class="muted">${t("SSH-терминал и ридер логов в стиле Dock.", "SSH terminal and log reader in Dock style.")}</p><div class="component-row"><button data-page="ssh">${t("SSH-консоль", "SSH console")}</button><button data-page="logs">${t("Log-ридер", "Log reader")}</button><button data-page="statistics">${t("Статистика сервера", "Server statistics")}</button><button data-page="documents">${t("Markdown и редактор", "Markdown and editor")}</button></div></section>
<section class="specimen"><h2>${t("Иконки Anidev", "Anidev icons")}</h2><div class="component-row icon-specimen">${["profile", "security", "sessions", "applications", "settings", "copy", "key", "bell"].map(icon).join("")}</div><p class="muted">${t("64 SVG · сетка 24×24 · контур 1.5px", "64 SVGs · 24×24 grid · 1.5px stroke")}</p><a href="${new URL("../icons/", import.meta.url).pathname}" data-icon-catalog>${t("Открыть пак иконок →", "Open icon pack →")}</a></section>
<section class="specimen"><h2>Chart</h2>${chart()}</section></div><p class="compact-note">${t("Таблицы, пагинация и фильтры — на экране «Пользователи»; вкладки — в настройках; форма входа — в авторизации.", "Tables, pagination and filters: Users. Tabs: Settings. Sign-in form: Authentication.")}</p></div>`;
}
@@ -1115,7 +1253,8 @@ document.addEventListener("click", async (e) => {
return;
}
page = pageButton.dataset.page;
if (["ssh", "logs"].includes(page)) administrationOpen = true;
if (["ssh", "logs", "statistics", "servers", "server"].includes(page))
administrationOpen = true;
$("#dialog").close();
render({ preserveDock: fromDock && !matchMedia(mobileDockQuery).matches });
if (fromDock && document.body.classList.contains("dock-open")) {
@@ -1552,7 +1691,8 @@ addEventListener("storage", (e) => {
});
function navigate(next) {
page = next;
if (["ssh", "logs"].includes(page)) administrationOpen = true;
if (["ssh", "logs", "statistics", "servers", "server"].includes(page))
administrationOpen = true;
$("#dialog").close();
render();
$("#content")?.focus();
@@ -1590,7 +1730,8 @@ addEventListener("popstate", () => {
page = Object.keys(pageNames).includes(route.searchParams.get("page"))
? route.searchParams.get("page")
: "dashboard";
if (["ssh", "logs"].includes(page)) administrationOpen = true;
if (["ssh", "logs", "statistics", "servers", "server"].includes(page))
administrationOpen = true;
theme = route.searchParams.get("theme") === "dark" ? "dark" : "light";
tokens = tokensFor("dock", theme, rawAccent || undefined, density);
document.documentElement.style.cssText = cssVars(tokens);
+4 -7
View File
@@ -67,7 +67,6 @@
Core 50/50, Dock 10/10, Identity 94/94, TOTP geometry 4/4, feedback/scroll 24/24, standalone site 31/31 — всего 213 проверок, ошибок JavaScript нет. Последняя suite проверяет hover/focus для Пользователей, Настроек, Компонентов и Токенов в обеих темах на desktop/mobile, current-page, Back/Forward, reload, совместимость старых URL, тему и отсутствие сдвигов. Выбранный Обзор выделен отдельно. Экспорт 23 файла, CRC проверен. Актуальные скриншоты: [site](site/README.md).
## Dock / исправления по скриншотам, 30.11.2026
Удалены запасное меню и выбор интерфейса через concept в URL. Корневой HTML сразу отмечен как Dock; версии CSS/JS и no-store у обоих серверов предотвращают загрузку старой оболочки. Python fallback использует scripts/serve.py. По пользовательскому адресу 4173 подтверждены HTTP 200 и Cache-Control: no-store.
@@ -76,7 +75,6 @@ Core 50/50, standalone site 35/35 (включая четыре старые сс
Дополнительно 36 целевых проверок в Edge: геометрия переключателя в обоих состояниях, двух темах и desktop/mobile; скругление/анимация меню и reduced motion; значения и границы подсказки графика, клавиатура и семидневный диапазон; касание в мобильном контексте; тост в верхнем слое при открытом диалоге. Скриншоты меню, переключателя, графика и тоста проверены визуально. Это не полный аудит доступности.
## Dock / навигация и отступы, 30.11.2026
У выбранного пункта нет дополнительной hover-подсветки. Переход по пунктам не удаляет dock-open; сохраняются затемнение, inert основной области и способ открытия. Повторный клик выбранного раздела не пересоздаёт экран. Клавиатурный фокус остаётся в меню.
@@ -87,7 +85,6 @@ Standalone site 35/35 и Dock 10/10 повторены успешно. В site
Меню аккаунта сокращено до Аккаунта, Панели управления (по роли), Сменить аккаунт и Выйти из SSO. В обеих темах проверены отсутствие трёх удалённых пунктов и сохранение оставшихся действий.
## Dock Icons и общая полировка / 30.11.2026
Созданы 64 SVG в восьми категориях: единые сетка 24, stroke 1.5, caps/joins round. Проверены XML всех файлов, границы рисунков, размеры 16/20/24/32/48, manifest/sprite, поиск и копирование в каталоге. У иконок и подложек общая ось; устранено смещение от старых 21px SVG и padding. Логотип и аватар выровнены по ней, раскрытие не меняет положение значков. Внутренний focus-ring не обрезается мобильным Dock, pressed не сдвигает пункты. Закрытие диалогов использует SVG с проверенным центром.
@@ -98,14 +95,12 @@ Core 50/50, Dock 10/10, standalone 35/35, feedback/scroll 24/24, Identity 94/94,
SVG ZIP содержит 70 файлов. Экспорт системы содержит 97 файлов, включая модуль, каталог, 64 SVG и вложенный бинарный ZIP. Проверены CRC обоих архивов. Распакованный экспорт запущен на отдельном loopback-сервере, профиль и каталог 64 иконок открываются автономно; QA-сервер остановлен после проверки.
## Бейджи состояний / 01.12.2026
В образце Status indicators вместо трёх разрозненных цветных подписей — компактные бейджи с иконками check/close/more-horizontal, мягкой заливкой и семантической рамкой. Состояние передаётся символом и текстом; декоративные SVG скрыты от скринридера. Стиль вынесен в отдельный status-badge и не меняет служебные текстовые сообщения статуса.
Проверены 12 сочетаний: light/dark, RU/EN, ширины 1440/768/390. Контраст текста на фактическом смешанном фоне >=4.5:1, высота >=28px, центры SVG совпадают с центрами меток, горизонтального переполнения и ошибок JavaScript нет. Скриншоты обеих тем desktop/tablet/mobile просмотрены: references/status-badges. npm run check проходит.
## SSH-консоль и log-ридер / 01.12.2026
Добавлены собственные страницы ssh/logs, пункты Dock и образец Workspaces в компонентах. SSH использует xterm.js 6.0.0, addon-fit 0.11.0, addon-search 0.16.0, локальные ESM-дистрибутивы и MIT-лицензии в vendor/xterm. Это frontend-демо с локальной PTY, не настоящая SSH-сессия; реализация транспорта вынесена в контракт. Фон #000 проверен в обеих темах. После корректировки padding renderer полностью помещается в viewport терминала.
@@ -120,7 +115,6 @@ Log reader: фильтры уровня/сервиса/текста, подсв
Экспорт 110 файлов: CRC всех записей и вложенного SVG ZIP проверены; присутствуют оба компонента, CSS, PTY fixture, xterm runtime и лицензии. Распакованный экспорт запущен на отдельном loopback-сервере: ввод в SSH, чёрный фон и фильтры логов работают без репозитория/CDN, ошибок JavaScript нет. QA-сервер закрыт после проверки.
## Подменю, выбор, readonly и тосты / 01.12.2026
В Dock добавлена disclosure-группа «Администрирование» с SSH-консолью и логами. Проверены текущая страница/активный раздел, сохранение раскрытия после переходов, повторный клик, Right/Left/Up/Down/Escape, aria-expanded/controls и inert закрытого подменю. На коротком экране навигация прокручивается, аккаунт остаётся видимым. Подпись группы не сталкивается с шевроном.
@@ -133,7 +127,6 @@ Log reader: фильтры уровня/сервиса/текста, подсв
Массовый прогон выявил отказы подключения локального Python preview при параллельной загрузке модулей: контрольный запуск дал 17/24 успешных запроса. Очередь увеличена до 128, в Windows включён SO_EXCLUSIVEADDRUSE, чтобы порт не делили два процесса; успешные запросы больше не засоряют консоль. После перезапуска — 3×24/24 запросов, затем весь браузерный проход 470/470. Временный Node QA-сервер на 4174 остановлен; основной preview 4173 оставлен для просмотра.
## Общая капсула чекбоксов / 01.12.2026
В компоненты добавлен образец «Группы чекбоксов»: по три связанных checkbox в одной общей поверхности, горизонтально и вертикально. У пунктов нет собственных пузырьков; разделители не участвуют в расчёте геометрии, поэтому контролы и подписи остаются на одной оси. Яркая прямоугольная рамка фокуса убрана по уточнению пользователя; клавиатурный фокус обозначается фоном.
@@ -179,3 +172,7 @@ Log reader: фильтры уровня/сервиса/текста, подсв
Набор проверок: Browser 50, Dock 10, Approved 24, Site 35, Identity 94, TOTP 4, Icons 91, Workspaces 83, Navigation/feedback 79, Search-select 6, Package 31, System pages 183, Panel navigation 14 — суммарно 704 успешных сценария, без ошибок JavaScript. Финальные изменения аккаунта повторно проверены Package 31 / Panel navigation 14 / Browser 50; check и штатный Skill validator проходят. Скриншоты references/panel-navigation просмотрены в light/dark на 1440/768/390; signed-out просмотрен отдельно. Архивы пересобраны, ZIP CRC проверен.
Во время общего запуска был единичный Windows-сбой записи PNG и зависимый от нагрузки результат терминального теста после фиксированной паузы 80 мс. Identity и Workspaces отдельно повторены успешно (94/94 и 83/83). Это наблюдение о воспроизводимости QA, не полный аудит доступности. Настоящие API/SSO не подключались; контракт и fixtures обновлены под новую схему.
## 02.12.2026 — новые рабочие области, ожидание утверждения
Добавлены Markdown/очистка HTML, минимальный редактор, виртуальные документы, breadcrumbs, 7 вариантов графиков, шаблон серверной статистики и мини-логи. Интегрированы в галерею, starter, runtime, browser export и сборку пакета. Выполнены только форматирование и сборка копированием. По прямой просьбе пользователя тесты, проверки, browser QA и аудит зависимостей не запускались. Предыдущие результаты выше не распространяются на эти изменения и новые зависимости. После утверждения нужны полный проход обеих тем/RU/EN/desktop/mobile, клавиатура и фокус, поведение редактора/Markdown и очистка опасной разметки, tooltip/таблицы графиков, логи, вложенные маршруты/back-forward, экспорт и запуск переносимого starter; затем существующие release suites.
+16
View File
@@ -1,4 +1,20 @@
export { iconSvg, iconNames } from "../icons/icons.js";
export {
breadcrumbsMarkup,
mountBreadcrumbs,
} from "../components/breadcrumbs.js";
export { mountMarkdown } from "../components/markdown.js";
export { mountCodeEditor } from "../components/code-editor.js";
export { mountChart } from "../components/charts.js";
export { mountMiniLog } from "../components/mini-log.js";
export {
statisticsMarkup,
mountStatistics,
} from "../components/server-statistics.js";
export {
mountDocuments,
normalizeDocumentPath,
} from "../components/documents.js";
export { createNotifier } from "../components/toast.js";
export {
searchSelectMarkup,
+18
View File
@@ -41,6 +41,16 @@ async function copy(from, to) {
for (const file of [
"runtime/index.js",
"components/system.css",
"components/content-workspaces.css",
"components/text-runtime.js",
"components/markdown.js",
"components/code-editor.js",
"components/charts.js",
"components/mini-log.js",
"components/breadcrumbs.js",
"components/documents.js",
"components/server-statistics.js",
"components/content-demo.js",
"components/workspaces.css",
"components/toast.js",
"components/search-select.js",
@@ -56,6 +66,9 @@ for (const file of [
"components/ssh-console.js",
"components/log-reader.js",
"patterns/demo-pty.js",
"patterns/demo-statistics.js",
"patterns/demo-documents.js",
"vendor/text",
"concepts/registry.js",
"tokens/dock",
"tokens/schema.json",
@@ -96,6 +109,10 @@ await writeFile(
.replaceAll("(../patterns/", "(patterns/"),
);
await copy("docs/PANEL-API.md", path.join(pkg, "docs/PANEL-API.md"));
await copy(
"docs/CONTENT-WORKSPACES.md",
path.join(pkg, "docs/CONTENT-WORKSPACES.md"),
);
await copy(
"docs/BACKEND-INTEGRATION.md",
path.join(pkg, "docs/BACKEND-INTEGRATION.md"),
@@ -120,6 +137,7 @@ await writeFile(
"./tokens/dark.json": "./tokens/dock/dark.json",
"./ssh": "./components/ssh-console.js",
"./logs": "./components/log-reader.js",
"./content-demo": "./components/content-demo.js",
},
},
null,
+59
View File
@@ -0,0 +1,59 @@
import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
const root = new URL("../", import.meta.url),
output = new URL("vendor/text/", root);
await mkdir(output, { recursive: true });
const files = {
"marked/lib/marked.esm.js": "marked.js",
"marked/LICENSE": "marked.LICENSE",
"dompurify/dist/purify.es.mjs": "purify.js",
"dompurify/LICENSE": "dompurify.LICENSE",
"dompurify/LICENSE-MPL": "dompurify.MPL.LICENSE",
"@highlightjs/cdn-assets/es/core.min.js": "highlight/core.js",
"@highlightjs/cdn-assets/LICENSE": "highlight.LICENSE",
};
const languages = [
"xml",
"javascript",
"typescript",
"json",
"yaml",
"bash",
"python",
"css",
"ini",
"nginx",
"sql",
"markdown",
];
for (const language of languages)
files[`@highlightjs/cdn-assets/es/languages/${language}.min.js`] =
`highlight/languages/${language}.js`;
for (const [source, target] of Object.entries(files)) {
const to = new URL(target, output);
await mkdir(fileURLToPath(new URL("./", to)), { recursive: true });
await cp(new URL(`node_modules/${source}`, root), to);
if (target.endsWith(".js"))
await writeFile(
to,
(await readFile(to, "utf8")).replace(/^\/\/# sourceMappingURL=.*$/gm, ""),
);
}
const versions = {};
for (const name of ["marked", "dompurify", "@highlightjs/cdn-assets"])
versions[name] = JSON.parse(
await readFile(new URL(`node_modules/${name}/package.json`, root), "utf8"),
).version;
await writeFile(
new URL("manifest.json", output),
JSON.stringify(
{
versions,
languages,
distribution: "Local browser ES modules; no CDN requests",
},
null,
2,
) + "\n",
);
console.log("Vendored Markdown, HTML sanitizer and syntax languages.");
+4
View File
@@ -38,3 +38,7 @@ On mobile, use a bottom Dock with exactly four icon slots: current section, prev
Appearance is a compact light/dark icon control at the bottom of the account menu, not a separate flyout item. Switching it preserves the route and keeps the menu open. When working in this source project, follow the user's current instruction to defer intermediate test runs to the final validation stage.
Verify the changed flows in both themes and desktop/mobile, with keyboard, long Russian labels, empty/error data and any affected modal or popover. Confirm that dynamic menu changes preserve an available active section and provide a sensible fallback when it disappears. Dispose controllers, listeners and requests on unmount. Review the rendered result; automated checks alone are not an accessibility audit. Report the actual checks and remaining integration limits.
## Документы и серверная статистика
В assets/anidev/docs/CONTENT-WORKSPACES.md описаны mountMarkdown, mountCodeEditor, breadcrumbs, mountChart, mountMiniLog, mountDocuments и mountStatistics. Используйте отдельные контроллеры из runtime; запросы, разрешения, маршрутизация и сохранение принадлежат приложению. content-demo и demo-documents/demo-statistics содержат только fixtures. Все зависимости Markdown/подсветки локальны в vendor/text, сохраняйте лицензии. Новые модули и мобильный Dock ожидают итоговой проверки после утверждения пользователем.
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+373
View File
@@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+29
View File
@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2006, Ivan Sagalaev.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+305
View File
@@ -0,0 +1,305 @@
/*!
Highlight.js v11.12.0 (git: f7f7d3803b)
(c) 2006-2026 Josh Goebel <hello@joshgoebel.com> and other contributors
License: BSD-3-Clause
*/
function e(t){return t instanceof Map?t.clear=t.delete=t.set=()=>{
throw Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=()=>{
throw Error("set is read-only")
}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{
const i=t[n],s=typeof i;"object"!==s&&"function"!==s||Object.isFrozen(i)||e(i)
}),t}class t{constructor(e){
void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}
ignoreMatch(){this.isMatchIgnored=!0}}function n(e){
return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")
}function i(e,...t){const n=Object.create(null);for(const t in e)n[t]=e[t]
;return t.forEach(e=>{for(const t in e)n[t]=e[t]}),n}const s=e=>!!e.scope
;class r{constructor(e,t){
this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){
this.buffer+=n(e)}openNode(e){if(!s(e))return;const t=((e,{prefix:t})=>{
if(e.startsWith("language:"))return e.replace("language:","language-")
;if(e.includes(".")){const n=e.split(".")
;return[`${t}${n.shift()}`,...n.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}
return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){
s(e)&&(this.buffer+="</span>")}value(){return this.buffer}span(e){
this.buffer+=`<span class="${e}">`}}const o=(e={})=>{const t={children:[]}
;return Object.assign(t,e),t};class a{constructor(){
this.rootNode=o(),this.stack=[this.rootNode]}get top(){
return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){
this.top.children.push(e)}openNode(e){const t=o({scope:e})
;this.add(t),this.stack.push(t)}closeNode(){
if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){
for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}
walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){
return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t),
t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(e){
"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{
a._collapse(e)}))}}class c extends a{constructor(e){super(),this.options=e}
addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){
this.closeNode()}__addSublanguage(e,t){const n=e.root
;t&&(n.scope="language:"+t),this.add(n)}toHTML(){
return new r(this,this.options).value()}finalize(){
return this.closeAllNodes(),!0}}function l(e){
return e?"string"==typeof e?e:e.source:null}function g(e){return h("(?=",e,")")}
function u(e){return h("(?:",e,")*")}function d(e){return h("(?:",e,")?")}
function h(...e){return e.map(e=>l(e)).join("")}function f(...e){const t=(e=>{
const t=e[e.length-1]
;return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}
})(e);return"("+(t.capture?"":"?:")+e.map(e=>l(e)).join("|")+")"}function p(e){
return RegExp(e.toString()+"|").exec("").length-1}
const b=RegExp(f(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./))
;function m(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;const t=n
;let i=l(e),s="";for(;i.length>0;){const e=b.exec(i);if(!e){s+=i;break}
s+=i.substring(0,e.index),
i=i.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?s+="\\"+(Number(e[1])+t):(s+=e[0],
("("===e[0]||/^\(\?[<']/.test(e[0]))&&n++)}return s}).map(e=>`(${e})`).join(t)}
const E="[a-zA-Z]\\w*",x="[a-zA-Z_]\\w*",_="\\b\\d+(\\.\\d+)?",y="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",w="\\b(0b[01]+)",O={
begin:"\\\\[\\s\\S]",relevance:0},k={scope:"string",begin:"'",end:"'",
illegal:"\\n",contains:[O]},N={scope:"string",begin:'"',end:'"',illegal:"\\n",
contains:[O]},S=(e,t,n={})=>{const s=i({scope:"comment",begin:e,end:t,
contains:[]},n);s.contains.push({scope:"doctag",
begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",
end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0})
;const r=f("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/)
;return s.contains.push({begin:h(/[ ]+/,"(",r,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),s
},v=S("//","$"),M=S("/\\*","\\*/"),R=S("#","$");var A=Object.freeze({
__proto__:null,APOS_STRING_MODE:k,BACKSLASH_ESCAPE:O,BINARY_NUMBER_MODE:{
scope:"number",begin:w,relevance:0},BINARY_NUMBER_RE:w,COMMENT:S,
C_BLOCK_COMMENT_MODE:M,C_LINE_COMMENT_MODE:v,C_NUMBER_MODE:{scope:"number",
begin:y,relevance:0},C_NUMBER_RE:y,END_SAME_AS_BEGIN:e=>Object.assign(e,{
"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{
t.data._beginMatch!==e[1]&&t.ignoreMatch()}}),HASH_COMMENT_MODE:R,IDENT_RE:E,
MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:{begin:"\\.\\s*"+x,relevance:0},
NUMBER_MODE:{scope:"number",begin:_,relevance:0},NUMBER_RE:_,
PHRASAL_WORDS_MODE:{
begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
},QUOTE_STRING_MODE:N,REGEXP_MODE:{scope:"regexp",begin:/\/(?=[^/\n]*\/)/,
end:/\/[gimuy]*/,contains:[O,{begin:/\[/,end:/\]/,relevance:0,contains:[O]}]},
RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",
SHEBANG:(e={})=>{const t=/^#![ ]*\//
;return e.binary&&(e.begin=h(t,/.*\b/,e.binary,/\b.*/)),i({scope:"meta",begin:t,
end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},
TITLE_MODE:{scope:"title",begin:E,relevance:0},UNDERSCORE_IDENT_RE:x,
UNDERSCORE_TITLE_MODE:{scope:"title",begin:x,relevance:0}});function j(e,t){
"."===e.input[e.index-1]&&t.ignoreMatch()}function I(e,t){
void 0!==e.className&&(e.scope=e.className,delete e.className)}function T(e,t){
t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",
e.__beforeBegin=j,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,
void 0===e.relevance&&(e.relevance=0))}function L(e,t){
Array.isArray(e.illegal)&&(e.illegal=f(...e.illegal))}function B(e,t){
if(e.match){
if(e.begin||e.end)throw Error("begin & end are not supported with match")
;e.begin=e.match,delete e.match}}function P(e,t){
void 0===e.relevance&&(e.relevance=1)}const D=(e,t)=>{if(!e.beforeMatch)return
;if(e.starts)throw Error("beforeMatch cannot be used with starts")
;const n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]
}),e.keywords=n.keywords,e.begin=h(n.beforeMatch,g(n.begin)),e.starts={
relevance:0,contains:[Object.assign(n,{endsParent:!0})]
},e.relevance=0,delete n.beforeMatch
},H=["of","and","for","in","not","or","if","then","parent","list","value"]
;function C(e,t,n="keyword"){const i=Object.create(null)
;return"string"==typeof e?s(n,e.split(" ")):Array.isArray(e)?s(n,e):Object.keys(e).forEach(n=>{
Object.assign(i,C(e[n],t,n))}),i;function s(e,n){
t&&(n=n.map(e=>e.toLowerCase())),n.forEach(t=>{const n=t.split("|")
;i[n[0]]=[e,$(n[0],n[1])]})}}function $(e,t){
return t?Number(t):(e=>H.includes(e.toLowerCase()))(e)?0:1}const U={},z=e=>{
console.error(e)},W=(e,...t)=>{console.log("WARN: "+e,...t)},X=(e,t)=>{
U[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),U[`${e}/${t}`]=!0)
},G=Error();function K(e,t,{key:n}){let i=0;const s=e[n],r={},o={}
;for(let e=1;e<=t.length;e++)o[e+i]=s[e],r[e+i]=!0,i+=p(t[e-1])
;e[n]=o,e[n]._emit=r,e[n]._multi=!0}function F(e){(e=>{
e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,
delete e.scope)})(e),"string"==typeof e.beginScope&&(e.beginScope={
_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope
}),(e=>{if(Array.isArray(e.begin)){
if(e.skip||e.excludeBegin||e.returnBegin)throw z("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),
G
;if("object"!=typeof e.beginScope||null===e.beginScope)throw z("beginScope must be object"),
G;K(e,e.begin,{key:"beginScope"}),e.begin=m(e.begin,{joinWith:""})}})(e),(e=>{
if(Array.isArray(e.end)){
if(e.skip||e.excludeEnd||e.returnEnd)throw z("skip, excludeEnd, returnEnd not compatible with endScope: {}"),
G
;if("object"!=typeof e.endScope||null===e.endScope)throw z("endScope must be object"),
G;K(e,e.end,{key:"endScope"}),e.end=m(e.end,{joinWith:""})}})(e)}function Z(e){
function t(t,n){
return RegExp(l(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":""))
}class n{constructor(){
this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}
addRule(e,t){
t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),
this.matchAt+=p(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null)
;const e=this.regexes.map(e=>e[1]);this.matcherRe=t(m(e,{joinWith:"|"
}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex
;const t=this.matcherRe.exec(e);if(!t)return null
;const n=t.findIndex((e,t)=>t>0&&void 0!==e),i=this.matchIndexes[n]
;return t.splice(0,n),Object.assign(t,i)}}class s{constructor(){
this.rules=[],this.multiRegexes=[],
this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){
if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n
;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),
t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){
return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){
this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){
const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex
;let n=t.exec(e)
;if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else{
const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}
return n&&(this.regexIndex+=n.position+1,
this.regexIndex===this.count&&this.considerAll()),n}}
if(e.compilerExtensions||(e.compilerExtensions=[]),
e.contains&&e.contains.includes("self"))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.")
;return e.classNameAliases=i(e.classNameAliases||{}),function n(r,o){const a=r
;if(r.isCompiled)return a
;[I,B,F,D].forEach(e=>e(r,o)),e.compilerExtensions.forEach(e=>e(r,o)),
r.__beforeBegin=null,[T,L,P].forEach(e=>e(r,o)),r.isCompiled=!0;let c=null
;return"object"==typeof r.keywords&&r.keywords.$pattern&&(r.keywords=Object.assign({},r.keywords),
c=r.keywords.$pattern,
delete r.keywords.$pattern),c=c||/\w+/,r.keywords&&(r.keywords=C(r.keywords,e.case_insensitive)),
a.keywordPatternRe=t(c,!0),
o&&(r.begin||(r.begin=/\B|\b/),a.beginRe=t(a.begin),r.end||r.endsWithParent||(r.end=/\B|\b/),
r.end&&(a.endRe=t(a.end)),
a.terminatorEnd=l(a.end)||"",r.endsWithParent&&o.terminatorEnd&&(a.terminatorEnd+=(r.end?"|":"")+o.terminatorEnd)),
r.illegal&&(a.illegalRe=t(r.illegal)),
r.contains||(r.contains=[]),r.contains=[].concat(...r.contains.map(e=>(e=>(e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(t=>i(e,{
variants:null},t))),e.cachedVariants?e.cachedVariants:V(e)?i(e,{
starts:e.starts?i(e.starts):null
}):Object.isFrozen(e)?i(e):e))("self"===e?r:e))),r.contains.forEach(e=>{n(e,a)
}),r.starts&&n(r.starts,o),a.matcher=(e=>{const t=new s
;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"
})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"
}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t})(a),a}(e)}function V(e){
return!!e&&(e.endsWithParent||V(e.starts))}class q extends Error{
constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}}
const J=n,Y=i,Q=Symbol("nomatch"),ee=n=>{
const i=Object.create(null),s=Object.create(null),r=[];let o=!0
;const a="Could not find the language '{}', did you forget to load/include a language module?",l={
disableAutodetect:!0,name:"Plain text",contains:[]};let p={
ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,
languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",
cssSelector:"pre code",languages:null,__emitter:c};function b(e){
return p.noHighlightRe.test(e)}function m(e,t,n){let i="",s=""
;"object"==typeof t?(i=e,
n=t.ignoreIllegals,s=t.language):(X("10.7.0","highlight(lang, code, ...args) has been deprecated."),
X("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),
s=e,i=t),void 0===n&&(n=!0);const r={code:i,language:s};S("before:highlight",r)
;const o=r.result?r.result:E(r.language,r.code,n)
;return o.code=r.code,S("after:highlight",o),o}function E(e,n,s,r){
const c=Object.create(null);function l(e,t){return e.keywords[t]}function g(){
if(!v.keywords)return void R.addText(A);let e=0;v.keywordPatternRe.lastIndex=0
;let t=v.keywordPatternRe.exec(A),n="";for(;t;){n+=A.substring(e,t.index)
;const i=k.case_insensitive?t[0].toLowerCase():t[0],s=l(v,i);if(s){const[e,r]=s
;if(R.addText(n),
n="",c[i]=(c[i]||0)+1,c[i]<=7&&(j+=r),e.startsWith("_"))n+=t[0];else{
const n=k.classNameAliases[e]||e;d(t[0],n)}}else n+=t[0]
;e=v.keywordPatternRe.lastIndex,t=v.keywordPatternRe.exec(A)}
n+=A.substring(e),R.addText(n)}function u(){null!=v.subLanguage?(()=>{
if(""===A)return;let e=null;if("string"==typeof v.subLanguage){
if(!i[v.subLanguage])return void R.addText(A)
;e=E(v.subLanguage,A,!0,M[v.subLanguage]),M[v.subLanguage]=e._top
}else e=x(A,v.subLanguage.length?v.subLanguage:null)
;v.relevance>0&&(j+=e.relevance),R.__addSublanguage(e._emitter,e.language)
})():g(),A=""}function d(e,t){
""!==e&&(R.startScope(t),R.addText(e),R.endScope())}function h(e,t){let n=1
;const i=t.length-1;for(;n<=i;){if(!e._emit[n]){n++;continue}
const i=k.classNameAliases[e[n]]||e[n],s=t[n];i?d(s,i):(A=s,g(),A=""),n++}}
function f(e,t){
return e.scope&&"string"==typeof e.scope&&R.openNode(k.classNameAliases[e.scope]||e.scope),
e.beginScope&&(e.beginScope._wrap?(d(A,k.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),
A=""):e.beginScope._multi&&(h(e.beginScope,t),A="")),v=Object.create(e,{parent:{
value:v}}),v}function b(e,n,i){let s=((e,t)=>{const n=e&&e.exec(t)
;return n&&0===n.index})(e.endRe,i);if(s){if(e["on:end"]){const i=new t(e)
;e["on:end"](n,i),i.isMatchIgnored&&(s=!1)}if(s){
for(;e.endsParent&&e.parent;)e=e.parent;return e}}
if(e.endsWithParent)return b(e.parent,n,i)}function m(e){
return 0===v.matcher.regexIndex?(A+=e[0],1):(L=!0,0)}function _(e){
const t=e[0],i=n.substring(e.index),s=b(v,e,i);if(!s)return Q;const r=v
;v.endScope&&v.endScope._wrap?(u(),
d(t,v.endScope._wrap)):v.endScope&&v.endScope._multi?(u(),
h(v.endScope,e)):r.skip?A+=t:(r.returnEnd||r.excludeEnd||(A+=t),
u(),r.excludeEnd&&(A=t));do{
v.scope&&R.closeNode(),v.skip||v.subLanguage||(j+=v.relevance),v=v.parent
}while(v!==s.parent);return s.starts&&f(s.starts,e),r.returnEnd?0:t.length}
let y={};function w(i,r){const a=r&&r[0];if(A+=i,null==a)return u(),0
;if("begin"===y.type&&"end"===r.type&&y.index===r.index&&""===a){
if(A+=n.slice(r.index,r.index+1),!o){const t=Error(`0 width match regex (${e})`)
;throw t.languageName=e,t.badRule=y.rule,t}return 1}
if(y=r,"begin"===r.type)return(e=>{
const n=e[0],i=e.rule,s=new t(i),r=[i.__beforeBegin,i["on:begin"]]
;for(const t of r)if(t&&(t(e,s),s.isMatchIgnored))return m(n)
;return i.skip?A+=n:(i.excludeBegin&&(A+=n),
u(),i.returnBegin||i.excludeBegin||(A=n)),f(i,e),i.returnBegin?0:n.length})(r)
;if("illegal"===r.type&&!s){
const e=Error('Illegal lexeme "'+a+'" for mode "'+(v.scope||"<unnamed>")+'"')
;throw e.mode=v,e}if("end"===r.type){const e=_(r);if(e!==Q)return e}
if("illegal"===r.type&&""===a)return r.index===n.length||(A+="\n"),1
;if(T>1e5&&T>3*r.index)throw Error("potential infinite loop, way more iterations than matches")
;return A+=a,a.length}const k=O(e)
;if(!k)throw z(a.replace("{}",e)),Error('Unknown language: "'+e+'"')
;const N=Z(k);let S="",v=r||N;const M={},R=new p.__emitter(p);(()=>{const e=[]
;for(let t=v;t!==k;t=t.parent)t.scope&&e.unshift(t.scope)
;e.forEach(e=>R.openNode(e))})();let A="",j=0,I=0,T=0,L=!1;try{
if(k.__emitTokens)k.__emitTokens(n,R);else{for(v.matcher.considerAll();;){
T++,L?L=!1:v.matcher.considerAll(),v.matcher.lastIndex=I
;const e=v.matcher.exec(n);if(!e)break;const t=w(n.substring(I,e.index),e)
;I=e.index+t}w(n.substring(I))}return R.finalize(),S=R.toHTML(),{language:e,
value:S,relevance:j,illegal:!1,_emitter:R,_top:v}}catch(t){
if(t.message&&t.message.includes("Illegal"))return{language:e,value:J(n),
illegal:!0,relevance:0,_illegalBy:{message:t.message,index:I,
context:n.slice(I-100,I+100),mode:t.mode,resultSoFar:S},_emitter:R};if(o)return{
language:e,value:J(n),illegal:!1,relevance:0,errorRaised:t,_emitter:R,_top:v}
;throw t}}function x(e,t){t=t||p.languages||Object.keys(i);const n=(e=>{
const t={value:J(e),illegal:!1,relevance:0,_top:l,_emitter:new p.__emitter(p)}
;return t._emitter.addText(e),t})(e),s=t.filter(O).filter(N).map(t=>E(t,e,!1))
;s.unshift(n);const r=s.sort((e,t)=>{
if(e.relevance!==t.relevance)return t.relevance-e.relevance
;if(e.language&&t.language){if(O(e.language).supersetOf===t.language)return 1
;if(O(t.language).supersetOf===e.language)return-1}return 0}),[o,a]=r,c=o
;return c.secondBest=a,c}function _(e){let t=null;const n=(e=>{
let t=e.className+" ";t+=e.parentNode?e.parentNode.className:""
;const n=p.languageDetectRe.exec(t);if(n){const t=O(n[1])
;return t||(W(a.replace("{}",n[1])),
W("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}
return t.split(/\s+/).find(e=>b(e)||O(e))})(e);if(b(n))return
;if(S("before:highlightElement",{el:e,language:n
}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e)
;if(e.children.length>0&&(p.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),
console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),
console.warn("The element with unescaped HTML:"),
console.warn(e)),p.throwUnescapedHTML))throw new q("One of your code blocks includes unescaped HTML.",e.innerHTML)
;t=e;const i=t.textContent,r=n?m(i,{language:n,ignoreIllegals:!0}):x(i)
;e.innerHTML=r.value,e.dataset.highlighted="yes",((e,t,n)=>{const i=t&&s[t]||n
;e.classList.add("hljs"),e.classList.add("language-"+i)
})(e,n,r.language),e.result={language:r.language,re:r.relevance,
relevance:r.relevance},r.secondBest&&(e.secondBest={
language:r.secondBest.language,relevance:r.secondBest.relevance
}),S("after:highlightElement",{el:e,result:r,text:i})}let y=!1;function w(){
if("loading"===document.readyState)return y||window.addEventListener("DOMContentLoaded",()=>{
w()},!1),void(y=!0);document.querySelectorAll(p.cssSelector).forEach(_)}
function O(e){return e=(e||"").toLowerCase(),i[e]||i[s[e]]}
function k(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{
s[e.toLowerCase()]=t})}function N(e){const t=O(e);return t&&!t.disableAutodetect
}function S(e,t){const n=e;r.forEach(e=>{e[n]&&e[n](t)})}Object.assign(n,{
highlight:m,highlightAuto:x,highlightAll:w,highlightElement:_,
highlightBlock:e=>(X("10.7.0","highlightBlock will be removed entirely in v12.0"),
X("10.7.0","Please use highlightElement now."),_(e)),configure:e=>{p=Y(p,e)},
initHighlighting:()=>{
w(),X("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")},
initHighlightingOnLoad:()=>{
w(),X("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")
},registerLanguage:(e,t)=>{let s=null;try{s=t(n)}catch(t){
if(z("Language definition for '{}' could not be registered.".replace("{}",e)),
!o)throw t;z(t),s=l}
s.name||(s.name=e),i[e]=s,s.rawDefinition=t.bind(null,n),s.aliases&&k(s.aliases,{
languageName:e})},unregisterLanguage:e=>{delete i[e]
;for(const t of Object.keys(s))s[t]===e&&delete s[t]},
listLanguages:()=>Object.keys(i),getLanguage:O,registerAliases:k,
autoDetection:N,inherit:Y,addPlugin:e=>{(e=>{
e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{
e["before:highlightBlock"](Object.assign({block:t.el},t))
}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{
e["after:highlightBlock"](Object.assign({block:t.el},t))})})(e),r.push(e)},
removePlugin:e=>{const t=r.indexOf(e);-1!==t&&r.splice(t,1)}}),n.debugMode=()=>{
o=!1},n.safeMode=()=>{o=!0},n.versionString="11.12.0",n.regex={concat:h,
lookahead:g,either:f,optional:d,anyNumberOfTimes:u}
;for(const t in A)"object"==typeof A[t]&&e(A[t]);return Object.assign(n,A),n
},te=ee({});te.newInstance=()=>ee({});export{te as default};
+21
View File
@@ -0,0 +1,21 @@
/*! `bash` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict";return e=>{const s=e.regex,t={},a={
begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[t]}]}
;Object.assign(t,{className:"variable",variants:[{
begin:s.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},a]});const n={
className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]
},c=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),i={
begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,
end:/(\w+)/,className:"string"})]}},o={className:"string",begin:/"/,end:/"/,
contains:[e.BACKSLASH_ESCAPE,t,n]};n.contains.push(o);const r={begin:/\$?\(\(/,
end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,t]
},l=e.SHEBANG({binary:"(fish|bash|zsh|sh|csh|ksh|tcsh|dash|scsh)",relevance:10
}),m={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,
contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{
name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,
keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],
literal:["true","false"],
built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"]
},contains:[l,e.SHEBANG(),m,r,c,i,{match:/(\/[a-z._-]+)+/},o,{match:/\\"/},{
className:"string",begin:/'/,end:/'/},{match:/\\'/},t]}}})()
;export default hljsGrammar;
+33
View File
@@ -0,0 +1,33 @@
/*! `css` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict"
;const e=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],t=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),i=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),o=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),r=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contaiLine truncated
;return n=>{const a=n.regex,l=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},
BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",
begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{
scope:"number",
begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},
FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},
ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",
contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{
scope:"number",
begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",
relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}
}))(n),s=[n.APOS_STRING_MODE,n.QUOTE_STRING_MODE];return{name:"CSS",
case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},
classNameAliases:{keyframePosition:"selector-tag"},contains:[l.BLOCK_COMMENT,{
begin:/-(webkit|moz|ms|o)-(?=[a-z])/},l.CSS_NUMBER_MODE,{
className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{
className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0
},l.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{
begin:":("+i.join("|")+")"},{begin:":(:)?("+o.join("|")+")"}]},l.CSS_VARIABLE,{
className:"attribute",begin:"\\b("+r.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,
contains:[l.BLOCK_COMMENT,l.HEXCOLOR,l.IMPORTANT,l.CSS_NUMBER_MODE,l.UNICODE_RANGE,...s,{
begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"
},contains:[...s,{className:"string",begin:/[^)]/,endsWithParent:!0,
excludeEnd:!0}]},l.FUNCTION_DISPATCH]},{begin:a.lookahead(/@/),end:"[{;]",
relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/
},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{
$pattern:/[a-z-]+/,keyword:"and or not only",attribute:t.join(" ")},contains:[{
begin:/[a-z-]+(?=:)/,className:"attribute"},...s,l.CSS_NUMBER_MODE]}]},{
className:"selector-tag",begin:"\\b("+e.join("|")+")\\b"}]}}})()
;export default hljsGrammar;
+16
View File
@@ -0,0 +1,16 @@
/*! `ini` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict";return e=>{const n=e.regex,a={
className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{
begin:e.NUMBER_RE}]},s=e.COMMENT();s.variants=[{begin:/;/,end:/$/},{begin:/#/,
end:/$/}];const i={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{
begin:/\$\{(.*?)\}/}]},r={className:"literal",
begin:/\bon|off|true|false|yes|no\b/},t={className:"string",
contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{
begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]
},l={begin:/\[/,end:/\]/,contains:[s,r,i,t,a,"self"],relevance:0
},c=n.either(/[A-Za-z0-9_-]+/,/"(\\"|[^"])*"/,/'[^']*'/);return{
name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,
contains:[s,{className:"section",begin:/\[+/,end:/\]+/},{
begin:n.concat(c,"(\\s*\\.\\s*",c,")*",n.lookahead(/\s*=\s*[^#\s]/)),
className:"attr",starts:{end:/$/,contains:[s,l,r,i,t,a]}}]}}})()
;export default hljsGrammar;
+81
View File
@@ -0,0 +1,81 @@
/*! `javascript` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict"
;const e="[A-Za-z$_][0-9A-Za-z$_]*",n=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],a=["true","false","null","undefined","NaN","Infinity"],t=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],s=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],r=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],c=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],i=[].concat(r,t,s)
;return o=>{const l=o.regex,d=e,b={begin:/<[A-Za-z0-9\\._:-]+/,
end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,n)=>{
const a=e[0].length+e.index,t=e.input[a]
;if("<"===t||","===t)return void n.ignoreMatch();let s
;">"===t&&(((e,{after:n})=>{const a="</"+e[0].slice(1)
;return-1!==e.input.indexOf(a,n)})(e,{after:a})||n.ignoreMatch())
;const r=e.input.substring(a)
;((s=r.match(/^\s*=/))||(s=r.match(/^\s+extends\s+/))&&0===s.index)&&n.ignoreMatch()
}},g={$pattern:e,keyword:n,literal:a,built_in:i,"variable.language":c
},u="[0-9](_?[0-9])*",m=`\\.(${u})`,E="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",A={
className:"number",variants:[{
begin:`(\\b(${E})((${m})|\\.)?|(${m}))[eE][+-]?(${u})\\b`},{
begin:`\\b(${E})\\b((${m})\\b|\\.)?|(${m})\\b`},{
begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{
begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{
begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{
begin:"\\b0[0-7]+n?\\b"}],relevance:0},y={className:"subst",begin:"\\$\\{",
end:"\\}",keywords:g,contains:[]},h={begin:".?html`",end:"",starts:{end:"`",
returnEnd:!1,contains:[o.BACKSLASH_ESCAPE,y],subLanguage:"xml"}},_={
begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,
contains:[o.BACKSLASH_ESCAPE,y],subLanguage:"css"}},N={begin:".?gql`",end:"",
starts:{end:"`",returnEnd:!1,contains:[o.BACKSLASH_ESCAPE,y],
subLanguage:"graphql"}},f={className:"string",begin:"`",end:"`",
contains:[o.BACKSLASH_ESCAPE,y]},p={className:"comment",
variants:[o.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{
begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",
begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,
excludeBegin:!0,relevance:0},{className:"variable",begin:d+"(?=\\s*(-)|$)",
endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]
}),o.C_BLOCK_COMMENT_MODE,o.C_LINE_COMMENT_MODE]
},v=[o.APOS_STRING_MODE,o.QUOTE_STRING_MODE,h,_,N,f,{match:/\$\d+/},A]
;y.contains=v.concat({begin:/\{/,end:/\}/,keywords:g,contains:["self"].concat(v)
});const S=[].concat(p,y.contains),w=S.concat([{begin:/(\s*)\(/,end:/\)/,
keywords:g,contains:["self"].concat(S)}]),R={className:"params",begin:/(\s*)\(/,
end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:g,contains:w},O={variants:[{
match:[/class/,/\s+/,d,/\s+/,/extends/,/\s+/,l.concat(d,"(",l.concat(/\./,d),")*")],
scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{
match:[/class/,/\s+/,d],scope:{1:"keyword",3:"title.class"}}]},k={relevance:0,
match:l.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),
className:"title.class",keywords:{_:[...t,...s]}},I={variants:[{
match:[/function/,/\s+/,d,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],
className:{1:"keyword",3:"title.function"},label:"func.def",contains:[R],
illegal:/%/},x={
match:l.concat(/\b/,(T=[...r,"super","import","await"].map(e=>e+"\\s*\\("),
l.concat("(?!",T.join("|"),")")),d,l.lookahead(/\s*\(/)),
className:"title.function",relevance:0};var T;const C={
begin:l.concat(/\./,l.lookahead(l.concat(d,/(?![0-9A-Za-z$_(])/))),end:d,
excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},M={
match:[/get|set/,/\s+/,d,/(?=\()/],className:{1:"keyword",3:"title.function"},
contains:[{begin:/\(\)/},R]
},B="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+o.UNDERSCORE_IDENT_RE+")\\s*=>",Z={
match:[/const|var|let/,/\s+/,d,/\s*/,/=\s*/,/(async\s*)?/,l.lookahead(B)],
keywords:"async",className:{1:"keyword",3:"title.function"},contains:[R]}
;return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:g,exports:{
PARAMS_CONTAINS:w,CLASS_REFERENCE:k},illegal:/#(?![$_A-Za-z])/,
contains:[o.SHEBANG({label:"shebang",binary:"node",relevance:5}),{
label:"use_strict",className:"meta",relevance:10,
begin:/^\s*['"]use (strict|asm)['"]/
},o.APOS_STRING_MODE,o.QUOTE_STRING_MODE,h,_,N,f,p,{match:/\$\d+/},A,k,{
scope:"attr",match:d+l.lookahead(":"),relevance:0},Z,{
begin:"("+o.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",
keywords:"return throw case",relevance:0,contains:[p,o.REGEXP_MODE,{
className:"function",begin:B,returnBegin:!0,end:"\\s*=>",contains:[{
className:"params",variants:[{begin:o.UNDERSCORE_IDENT_RE,relevance:0},{
className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,
excludeBegin:!0,excludeEnd:!0,keywords:g,contains:w}]}]},{begin:/,/,relevance:0
},{match:/\s+/,relevance:0},{variants:[{begin:"<>",end:"</>"},{
match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:b.begin,
"on:begin":b.isTrulyOpeningTag,end:b.end}],subLanguage:"xml",contains:[{
begin:b.begin,end:b.end,skip:!0,contains:["self"]}]}]},I,{
beginKeywords:"while if switch catch for"},{
begin:"\\b(?!function)"+o.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
returnBegin:!0,label:"func.def",contains:[R,o.inherit(o.TITLE_MODE,{begin:d,
className:"title.function"})]},{match:/\.\.\./,relevance:0},C,{match:"\\$"+d,
relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},
contains:[R]},x,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,
className:"variable.constant"},O,M,{match:/\$[(.]/}]}}})()
;export default hljsGrammar;
+10
View File
@@ -0,0 +1,10 @@
/*! `json` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict";const e={scope:"number",
match:"([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity",
relevance:0};return a=>{const n=["true","false","null"],r={scope:"literal",
beginKeywords:n.join(" ")};return{name:"JSON",aliases:["jsonc","json5"],
keywords:{literal:n},contains:[{className:"attr",
begin:/(("(\\.|[^\\"\r\n])*")|('(\\.|[^\\'\r\n])*'))(?=\s*:)/,relevance:1.01},{
match:/[{}[\],:]/,className:"punctuation",relevance:0
},a.APOS_STRING_MODE,a.QUOTE_STRING_MODE,r,e,a.C_LINE_COMMENT_MODE,a.C_BLOCK_COMMENT_MODE],
illegal:"\\S"}}})();export default hljsGrammar;
+33
View File
@@ -0,0 +1,33 @@
/*! `markdown` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict";return e=>{const n={begin:/<\/?[A-Za-z_]/,
end:">",subLanguage:"xml",relevance:0},a={variants:[{begin:/\[.+?\]\[.*?\]/,
relevance:0},{
begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,
relevance:2},{
begin:e.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/),
relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{
begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/
},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,
returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",
excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",
end:"\\]",excludeBegin:!0,excludeEnd:!0}]},i={className:"strong",contains:[],
variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]
},s={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{
begin:/_(?![_\s])/,end:/_/,relevance:0}]},c=e.inherit(i,{contains:[]
}),t=e.inherit(s,{contains:[]});i.contains.push(t),s.contains.push(c)
;let l=[n,a];return[i,s,c,t].forEach(e=>{e.contains=e.contains.concat(l)
}),l=l.concat(i,s),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{
className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:l},{
begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",
contains:l}]}]},n,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)",
end:"\\s+",excludeEnd:!0},{match:/^ {0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/},i,s,{
className:"quote",begin:"^>\\s+",contains:l,end:"$"},{className:"code",
variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{
begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{
begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",
contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},a,{
begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,
end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,
excludeBegin:!0}]},{scope:"literal",
match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}})()
;export default hljsGrammar;
+21
View File
@@ -0,0 +1,21 @@
/*! `nginx` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict";return e=>{const n=e.regex,a={
className:"variable",variants:[{begin:/\$\d+/},{begin:/\$\{\w+\}/},{
begin:n.concat(/[$@]/,e.UNDERSCORE_IDENT_RE)}]},s={endsWithParent:!0,keywords:{
$pattern:/[a-z_]{2,}|\/dev\/poll/,
literal:["on","off","yes","no","true","false","none","blocked","debug","info","notice","warn","error","crit","select","break","last","permanent","redirect","kqueue","rtsig","epoll","poll","/dev/poll"]
},relevance:0,illegal:"=>",contains:[e.HASH_COMMENT_MODE,{className:"string",
contains:[e.BACKSLASH_ESCAPE,a],variants:[{begin:/"/,end:/"/},{begin:/'/,end:/'/
}]},{begin:"([a-z]+):/",end:"\\s",endsWithParent:!0,excludeEnd:!0,contains:[a]
},{className:"regexp",contains:[e.BACKSLASH_ESCAPE,a],variants:[{begin:"\\s\\^",
end:"\\s|\\{|;",returnEnd:!0},{begin:"~\\*?\\s+",end:"\\s|\\{|;",returnEnd:!0},{
begin:"\\*(\\.[a-z\\-]+)+"},{begin:"([a-z\\-]+\\.)+\\*"}]},{className:"number",
begin:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{
className:"number",begin:"\\b\\d+[kKmMgGdshdwy]?\\b",relevance:0},a]};return{
name:"Nginx config",aliases:["nginxconf"],contains:[e.HASH_COMMENT_MODE,{
beginKeywords:"upstream location",end:/;|\{/,contains:s.contains,keywords:{
section:"upstream location"}},{className:"section",
begin:n.concat(e.UNDERSCORE_IDENT_RE+n.lookahead(/\s+\{/)),relevance:0},{
begin:n.lookahead(e.UNDERSCORE_IDENT_RE+"\\s"),end:";|\\{",contains:[{
className:"attribute",begin:e.UNDERSCORE_IDENT_RE,starts:s}],relevance:0}],
illegal:"[^\\s\\}\\{]"}}})();export default hljsGrammar;
+43
View File
@@ -0,0 +1,43 @@
/*! `python` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict";return e=>{
const n=e.regex,a=/[\p{XID_Start}_]\p{XID_Continue}*/u,t=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","lazy","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],s={
$pattern:/[A-Za-z]\w+|__\w+__/,keyword:t,
built_in:["__import__","abs","aiter","all","anext","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozendict","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","sentinel","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],
literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],
type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]
},i={className:"meta",begin:/^(>>>|\.\.\.) /},r={className:"subst",begin:/\{/,
end:/\}/,keywords:s,illegal:/#/},l={begin:/\{\{/,relevance:0},o={
className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{
begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,
contains:[e.BACKSLASH_ESCAPE,i],relevance:10},{
begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,
contains:[e.BACKSLASH_ESCAPE,i],relevance:10},{
begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'''/,end:/'''/,
contains:[e.BACKSLASH_ESCAPE,i,l,r]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"""/,
end:/"""/,contains:[e.BACKSLASH_ESCAPE,i,l,r]},{begin:/([uU]|[rR])'/,end:/'/,
relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{
begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,
end:/"/},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'/,end:/'/,
contains:[e.BACKSLASH_ESCAPE,l,r]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"/,
end:/"/,contains:[e.BACKSLASH_ESCAPE,l,r]
},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]
},b="[0-9](_?[0-9])*",c=`(\\b(${b}))?\\.(${b})|\\b(${b})\\.`,d="\\b|"+t.join("|"),m={
className:"number",relevance:0,variants:[{
begin:`(\\b(${b})|(${c}))[eE][+-]?(${b})[jJ]?(?=${d})`},{begin:`(${c})[jJ]?`},{
begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${d})`},{
begin:`\\b0[bB](_?[01])+[lL]?(?=${d})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${d})`
},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${d})`},{begin:`\\b(${b})[jJ](?=${d})`
}]},g={className:"comment",begin:n.lookahead(/# type:/),end:/$/,keywords:s,
contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},p={
className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,
end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,
contains:["self",i,m,o,e.HASH_COMMENT_MODE]}]};return r.contains=[o,m,i],{
name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:s,
illegal:/(<\/|\?)|=>/,contains:[i,m,{scope:"variable.language",match:/\bself\b/
},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"
},o,g,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,a],scope:{1:"keyword",
3:"title.function"},contains:[p]},{variants:[{
match:[/\bclass/,/\s+/,a,/\s*/,/\(\s*/,a,/\s*\)/]},{match:[/\bclass/,/\s+/,a]}],
scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{
className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[m,p,o]}]}}})()
;export default hljsGrammar;
+21
View File
@@ -0,0 +1,21 @@
/*! `sql` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict";return e=>{
const r=e.regex,t=e.COMMENT("--","$"),a=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],n=a,s=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(e=>!a.includes(e)),i={
match:r.concat(/\b/,r.either(...n),/\s*\(/),relevance:0,keywords:{built_in:n}}
;function o(e){
return r.concat(/\b/,r.either(...e.map(e=>e.replace(/\s+/,"\\s+"))),/\b/)}
const c={scope:"keyword",
match:o(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]),
relevance:0};return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{
$pattern:/\b[\w\.]+/,keyword:((e,{exceptions:r,when:t}={})=>{const a=t
;return r=r||[],e.map(e=>e.match(/\|\d+$/)||r.includes(e)?e:a(e)?e+"|0":e)})(s,{
when:e=>e.length<3}),literal:["true","false","unknown"],
type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],
built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"]
},contains:[{scope:"type",
match:o(["double precision","large object","with timezone","without timezone"])
},c,i,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{
begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{
match:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,t,{scope:"operator",
match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}}})()
;export default hljsGrammar;
+99
View File
@@ -0,0 +1,99 @@
/*! `typescript` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict"
;const e="[A-Za-z$_][0-9A-Za-z$_]*",n=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],a=["true","false","null","undefined","NaN","Infinity"],t=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],s=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],r=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],c=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],i=[].concat(r,t,s)
;function o(o){const l=o.regex,d=e,b={begin:/<[A-Za-z0-9\\._:-]+/,
end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,n)=>{
const a=e[0].length+e.index,t=e.input[a]
;if("<"===t||","===t)return void n.ignoreMatch();let s
;">"===t&&(((e,{after:n})=>{const a="</"+e[0].slice(1)
;return-1!==e.input.indexOf(a,n)})(e,{after:a})||n.ignoreMatch())
;const r=e.input.substring(a)
;((s=r.match(/^\s*=/))||(s=r.match(/^\s+extends\s+/))&&0===s.index)&&n.ignoreMatch()
}},g={$pattern:e,keyword:n,literal:a,built_in:i,"variable.language":c
},u="[0-9](_?[0-9])*",m=`\\.(${u})`,E="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",A={
className:"number",variants:[{
begin:`(\\b(${E})((${m})|\\.)?|(${m}))[eE][+-]?(${u})\\b`},{
begin:`\\b(${E})\\b((${m})\\b|\\.)?|(${m})\\b`},{
begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{
begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{
begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{
begin:"\\b0[0-7]+n?\\b"}],relevance:0},y={className:"subst",begin:"\\$\\{",
end:"\\}",keywords:g,contains:[]},p={begin:".?html`",end:"",starts:{end:"`",
returnEnd:!1,contains:[o.BACKSLASH_ESCAPE,y],subLanguage:"xml"}},f={
begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,
contains:[o.BACKSLASH_ESCAPE,y],subLanguage:"css"}},N={begin:".?gql`",end:"",
starts:{end:"`",returnEnd:!1,contains:[o.BACKSLASH_ESCAPE,y],
subLanguage:"graphql"}},h={className:"string",begin:"`",end:"`",
contains:[o.BACKSLASH_ESCAPE,y]},_={className:"comment",
variants:[o.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{
begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",
begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,
excludeBegin:!0,relevance:0},{className:"variable",begin:d+"(?=\\s*(-)|$)",
endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]
}),o.C_BLOCK_COMMENT_MODE,o.C_LINE_COMMENT_MODE]
},S=[o.APOS_STRING_MODE,o.QUOTE_STRING_MODE,p,f,N,h,{match:/\$\d+/},A]
;y.contains=S.concat({begin:/\{/,end:/\}/,keywords:g,contains:["self"].concat(S)
});const v=[].concat(_,y.contains),w=v.concat([{begin:/(\s*)\(/,end:/\)/,
keywords:g,contains:["self"].concat(v)}]),R={className:"params",begin:/(\s*)\(/,
end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:g,contains:w},x={variants:[{
match:[/class/,/\s+/,d,/\s+/,/extends/,/\s+/,l.concat(d,"(",l.concat(/\./,d),")*")],
scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{
match:[/class/,/\s+/,d],scope:{1:"keyword",3:"title.class"}}]},k={relevance:0,
match:l.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),
className:"title.class",keywords:{_:[...t,...s]}},O={variants:[{
match:[/function/,/\s+/,d,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],
className:{1:"keyword",3:"title.function"},label:"func.def",contains:[R],
illegal:/%/},I={
match:l.concat(/\b/,(C=[...r,"super","import","await"].map(e=>e+"\\s*\\("),
l.concat("(?!",C.join("|"),")")),d,l.lookahead(/\s*\(/)),
className:"title.function",relevance:0};var C;const T={
begin:l.concat(/\./,l.lookahead(l.concat(d,/(?![0-9A-Za-z$_(])/))),end:d,
excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},M={
match:[/get|set/,/\s+/,d,/(?=\()/],className:{1:"keyword",3:"title.function"},
contains:[{begin:/\(\)/},R]
},B="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+o.UNDERSCORE_IDENT_RE+")\\s*=>",$={
match:[/const|var|let/,/\s+/,d,/\s*/,/=\s*/,/(async\s*)?/,l.lookahead(B)],
keywords:"async",className:{1:"keyword",3:"title.function"},contains:[R]}
;return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:g,exports:{
PARAMS_CONTAINS:w,CLASS_REFERENCE:k},illegal:/#(?![$_A-Za-z])/,
contains:[o.SHEBANG({label:"shebang",binary:"node",relevance:5}),{
label:"use_strict",className:"meta",relevance:10,
begin:/^\s*['"]use (strict|asm)['"]/
},o.APOS_STRING_MODE,o.QUOTE_STRING_MODE,p,f,N,h,_,{match:/\$\d+/},A,k,{
scope:"attr",match:d+l.lookahead(":"),relevance:0},$,{
begin:"("+o.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",
keywords:"return throw case",relevance:0,contains:[_,o.REGEXP_MODE,{
className:"function",begin:B,returnBegin:!0,end:"\\s*=>",contains:[{
className:"params",variants:[{begin:o.UNDERSCORE_IDENT_RE,relevance:0},{
className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,
excludeBegin:!0,excludeEnd:!0,keywords:g,contains:w}]}]},{begin:/,/,relevance:0
},{match:/\s+/,relevance:0},{variants:[{begin:"<>",end:"</>"},{
match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:b.begin,
"on:begin":b.isTrulyOpeningTag,end:b.end}],subLanguage:"xml",contains:[{
begin:b.begin,end:b.end,skip:!0,contains:["self"]}]}]},O,{
beginKeywords:"while if switch catch for"},{
begin:"\\b(?!function)"+o.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
returnBegin:!0,label:"func.def",contains:[R,o.inherit(o.TITLE_MODE,{begin:d,
className:"title.function"})]},{match:/\.\.\./,relevance:0},T,{match:"\\$"+d,
relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},
contains:[R]},I,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,
className:"variable.constant"},x,M,{match:/\$[(.]/}]}}return t=>{
const s=t.regex,r=o(t),l=e,d=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],b={
begin:[/namespace/,/\s+/,t.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}
},g={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{
keyword:"interface extends",built_in:d},contains:[r.exports.CLASS_REFERENCE]
},u={$pattern:e,
keyword:n.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),
literal:a,built_in:i.concat(d),"variable.language":c},m={className:"meta",
begin:"@"+l},E=(e,n,a)=>{const t=e.contains.findIndex(e=>e.label===n)
;if(-1===t)throw Error("can not find mode to replace");e.contains.splice(t,1,a)}
;Object.assign(r.keywords,u),r.exports.PARAMS_CONTAINS.push(m)
;const A=r.contains.find(e=>"attr"===e.scope),y=Object.assign({},A,{
match:s.concat(l,s.lookahead(/\s*\?:/))})
;return r.exports.PARAMS_CONTAINS.push([r.exports.CLASS_REFERENCE,A,y]),
r.contains=r.contains.concat([m,b,g,y]),
E(r,"shebang",t.SHEBANG()),E(r,"use_strict",{className:"meta",relevance:10,
begin:/^\s*['"]use strict['"]/
}),r.contains.find(e=>"func.def"===e.label).relevance=0,Object.assign(r,{
name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),r}})()
;export default hljsGrammar;
+29
View File
@@ -0,0 +1,29 @@
/*! `xml` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict";return e=>{
const a=e.regex,n=a.concat(/[\p{L}_]/u,a.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),s={
className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},t={begin:/\s/,
contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]
},i=e.inherit(t,{begin:/\(/,end:/\)/}),c=e.inherit(e.APOS_STRING_MODE,{
className:"string"}),r=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),l={
endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",
begin:/[\p{L}0-9._:-]+/u,relevance:0},{begin:/=\s*/,relevance:0,contains:[{
className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[s]},{
begin:/'/,end:/'/,contains:[s]},{begin:/[^\s"'=<>`]+/}]}]}]};return{
name:"HTML, XML",
aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],
case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,
end:/>/,relevance:10,contains:[t,r,c,i,{begin:/\[/,end:/\]/,contains:[{
className:"meta",begin:/<![a-z]/,end:/>/,contains:[t,i,r,c]}]}]
},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,
relevance:10},s,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,
relevance:10,contains:[r]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",
begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[l],starts:{
end:/<\/style>/,returnEnd:!0,subLanguage:"css"}},{className:"tag",
begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[l],starts:{
end:/<\/script>/,returnEnd:!0,subLanguage:"javascript"}},{className:"tag",
begin:/<>|<\/>/},{className:"tag",
begin:a.concat(/</,a.lookahead(a.concat(n,a.either(/\/>/,/>/,/\s/)))),
end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:l}]},{
className:"tag",begin:a.concat(/<\//,a.lookahead(a.concat(n,/>/))),contains:[{
className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}
})();export default hljsGrammar;
+28
View File
@@ -0,0 +1,28 @@
/*! `yaml` grammar compiled for Highlight.js 11.12.0 */
var hljsGrammar=(()=>{"use strict";return e=>{
const n="true false yes no null",a="[\\w#;/?:@&=+$,.~*'()[\\]]+",s={
className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],
contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{
begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},i=e.inherit(s,{variants:[{
begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{
begin:/[^\s,{}[\]]+/}]}),l={end:",",endsWithParent:!0,excludeEnd:!0,keywords:n,
relevance:0},t={begin:/\{/,end:/\}/,contains:[l],illegal:"\\n",relevance:0},c={
begin:"\\[",end:"\\]",contains:[l],illegal:"\\n",relevance:0},r=[{
className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{
begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{
begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta",
begin:"^---\\s*$",relevance:10},{className:"string",
begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{
begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,
relevance:0},{className:"type",begin:"!\\w+!"+a},{className:"type",
begin:"!<"+a+">"},{className:"type",begin:"!"+a},{className:"type",begin:"!!"+a
},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",
begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",
relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:n,keywords:{literal:n}},{
className:"number",
begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"
},{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},t,c,{
className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,
scope:"char.escape",relevance:0}]},s],b=[...r]
;return b.pop(),b.push(i),l.contains=b,{name:"YAML",case_insensitive:!0,
aliases:["yml"],contains:r}}})();export default hljsGrammar;
+22
View File
@@ -0,0 +1,22 @@
{
"versions": {
"marked": "18.4.0",
"dompurify": "3.5.1",
"@highlightjs/cdn-assets": "11.12.0"
},
"languages": [
"xml",
"javascript",
"typescript",
"json",
"yaml",
"bash",
"python",
"css",
"ini",
"nginx",
"sql",
"markdown"
],
"distribution": "Local browser ES modules; no CDN requests"
}
+44
View File
@@ -0,0 +1,44 @@
# License information
## Contribution License Agreement
If you contribute code to this project, you are implicitly allowing your code
to be distributed under the MIT license. You are also implicitly verifying that
all code is your original work. `</legalese>`
## Marked
Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/)
Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## Markdown
Copyright © 2004, John Gruber
http://daringfireball.net/
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
+90
View File
@@ -0,0 +1,90 @@
/**
* marked v18.4.0 - a markdown parser
* Copyright (c) 2018-2026, MarkedJS. (MIT License)
* Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License)
* https://github.com/markedjs/marked
*/
/**
* DO NOT EDIT THIS FILE
* The code in this file is generated from files in ./src/
*/
function G(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var $=G();function ge(l){$=l}var N={exec:()=>null};function j(l){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),r=e[n];return r||(r=l(n),e[n]=r),r}}function h(l,e=""){let t=typeof l=="string"?l:l.source,n={replace:(r,s)=>{let o=typeof s=="string"?s:s.source;return o=o.replace(b.caret,"$1"),t=t.replace(r,o),n},getRegex:()=>new RegExp(t,e)};return n}var ze=((l="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l)}catch{return!1}})(),Me="^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)",b={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,listInterruptsParagraph:/^ {0,3}(?:[*+-]|0{0,8}1[.)])[ \t]+[^ \t\n]/,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^( {1,3})(?:`{3}|~{3})/,beginningSpace:/^[ \t]{1,3}/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,multipleSpaceTabGlobal:/[ \t\r\n]+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,textIndentedContinuation:/^(?:\n(?: {4}| {0,3}\t)[ \t]*[^ \t\n][^\n]*)+/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+)[ \t]*)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,blockquoteMarkerWhitespace:/^( {0,3}>)(\t[ \t]*)/gm,blockquoteFenceOpen:/^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/,blockquoteFenceClose:/^ {0,3}(`{3,}|~{3,})[ \t]*$/,blockquoteListItemStart:/^ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|$)/,nestedBlockMarker:/^ {0,3}(?:(?:[*+-]|\d{1,9}[.)])(?: |$)|> ?)/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\][ \t]+\S/,listReplaceTask:/^\[[ xX]\][ \t]+/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableHeader:new RegExp(Me+"(?:\\n|$)"),tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:j(l=>new RegExp(`^ {0,${l}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:j(l=>new RegExp(`^ {0,${l}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:j(l=>new RegExp(`^ {0,${l}}(?:\`{3,}(?=[^\`\\n]*(?:\\n|$))|~~~)`)),headingBeginRegex:j(l=>new RegExp(`^ {0,${l}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:j(l=>new RegExp(`^ {0,${l}}#`)),htmlBeginRegex:j(l=>new RegExp(`^ {0,${l}}(?:</?(?:${me})(?:[ \\t]+|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,"i")),blockquoteBeginRegex:j(l=>new RegExp(`^ {0,${l}}>`)),nestedContainerMarkers:/^(?: {0,3}(?:(?:[*+-]|\d{1,9}[.)])[ \t]+|>[ \t]?))+/},Ye=/^(?:[ \t]*(?:\n|$))+/,et=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,tt=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}(?:(?=`)\1`*|(?=~)\1~*)[ \t]*(?=\n|$)|$)/,ee=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,nt=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,fe=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,me="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",te=h(" {0,3}(?:</?(?:tag)(?:[ \\t]+|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",me).getRegex(),Be=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?![ \t]*\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+)[ \t]*(?:\n+|$)/,De=h(Be).replace(/bull/g,fe).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}(?=[^`\n]*(?:\n|$))|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/\|table/Line truncated
]`).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").replace("lheading",De).getRegex()},gt=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,kt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,He=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,ft=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,E=/[\p{P}\p{S}]/u,Q=/[\s\p{P}\p{S}]/u,ne=/[^\s\p{P}\p{S}]/u,mt=h(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Q).getRegex(),xt=/[\p{Pi}\p{Ps}"']/u,ve=/(?!~)[\p{P}\p{S}]/u,bt=/(?!~)[\s\p{P}\p{S}]/u,Rt=/(?:[^\s\p{P}\p{S}]|~)/u,Ot=h(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",ze?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ze=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Tt=h(Ze,"u").replace(/punct/g,E).getRegex(),wt=h(Ze,"u").replace(/punct/g,ve).getRegex(),Pt=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,yt=h(Pt,"u").replace(/openQuote/g,xt).replace(/punct/g,E).getRegex(),je="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",St=h(je,"gu").replace(/notPunctSpace/g,ne).replace(/punctSpace/g,Q).replace(/punct/g,E).getRegex(),_t=h(je,"gu").replace(/notPunctSpace/g,Rt).replace(/punctSpace/g,bt).replace(/punct/g,ve).getRegex(),$t="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Ct=h($t,"gu").replace(/notPunctSpace/g,ne).replace(/punctSpace/g,Q).replace(/punct/g,E).getRegex(),It=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ne).replace(/punctSpace/g,Q).replace(/punct/g,E).getRegex(),Lt="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",At=h(Lt,"gu").replace(/notPunctSpace/g,ne).replace(/punctSpace/g,Q).replace(/punct/g,E).getRegex(),Et=h(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,E).getRegex(),zt="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Mt=h(zt,"gu").replace(/notPunctSpace/g,ne).replace(/punctSpace/g,Q).replace(/punct/g,E).getRegex(),Bt=h(/\\(punct)/,"gu").replace(/punct/g,E).getRegex(),Dt=h(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,E).getRegex(),qt=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ht=h(Re).replace("(?:-->|$)","-->").getRegex(),vt=h("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Ht).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ne=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,le=h(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",Ne).getRegex(),ue=/\\[^ \t\n\x00-\x1f]|\\(?=[ \t\n])|[^ \t\n\x00-\x1f\\()]/,Zt=h(/\((?:char)*\)/).replace("char",ue).getRegex(),jt=h(/\((?:char|p1)*\)/).replace("char",ue).replace("p1",Zt).getRegex(),Nt=h(/\((?:char|p2)*\)/).replace("char",ue).replace("p2",jt).getRegex(),Ft=h(/(?!<)(?:char|p3)+/).replace("char",ue).replace("p3",Nt).getRegex(),Gt=h(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",le).replace("href",h(/<(?:\\.|[^\n<>\\])*>|bareHref|(?=\))/).replace("bareHref",Ft).getRegex()).replace("title",/"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\((?:\\[\s\S]|[^)\\])*\)/).getRegex(),Qt=h(/^!?\[(label)\]\[(ref)\]/).replace("label",le).replace("ref",be).getRegex(),Wt=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",be).getRegex(),Ae=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Ut=h(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/Line truncated
`),t=e.length-1;for(;t>=0&&b.blankLine.test(e[t]);)t--;return e.length-t<=2?l:e.slice(0,t+1).join(`
`)}function K(l,e=!1){let t=e?b.multipleSpaceGlobal:b.multipleSpaceTabGlobal;return l.trim().replace(t," ").toLowerCase().toUpperCase().toLowerCase()}function ye(l,e){if(l.indexOf(e[0])===-1&&l.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l.length;n++)if(l[n]==="\\")n++;else if(l[n]===e[0])t++;else if(l[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}var U=new WeakMap;function Se(l){let e={"*":-1,_:-1},t=-1,n=l.length;for(let r=0;r<n;r++){let s=l[r];if(s!=="*"&&s!=="_"&&s!=="~")continue;let o=r===0?`
`:l[r-1],i=r+1;for(;i<n&&l[i]===s;)i++;o!==" "&&o!==" "&&o!==`
`&&o!=="\r"&&o!=="\f"&&(s==="~"?t=r:e[s]=r),r=i-1}return{maskedSrc:l,lastPossibleEmStrongCloserIndex:e,lastPossibleDelCloserIndex:t}}function We(l,e){let t=Se(e),n=U.get(l);n?n.push(t):U.set(l,[t])}function Ue(l){let e=U.get(l);e&&(e.pop(),e.length===0&&U.delete(l))}function ce(l,e,t){let n=U.get(l)?.at(-1);return n&&n.maskedSrc===e?n.lastPossibleEmStrongCloserIndex[t]:Se(e).lastPossibleEmStrongCloserIndex[t]}function he(l,e){let t=U.get(l)?.at(-1);return t&&t.maskedSrc===e?t.lastPossibleDelCloserIndex:Se(e).lastPossibleDelCloserIndex}function X(l,e=0){let t=e,n="";for(let r of l)if(r===" "){let s=4-t%4;n+=" ".repeat(s),t+=s}else n+=r,t++;return n}function Ke(l){let e,t=!1;return l.map(n=>{if(t)return n;let{depth:r,expanded:s,keptIndent:o,content:i}=tn(n,e?.depth??1/0);if(e?.depth!==r&&(e=void 0),e){let p=b.blockquoteFenceClose.exec(i)?.[1];return!p||p[0]!==e.marker[0]||p.length<e.marker.length?o:(e=void 0,s)}if(t=b.blockquoteListItemStart.test(i),t)return n;let a=b.blockquoteFenceOpen.exec(i)?.[1];return a&&(e={marker:a,depth:r}),s}).join(`
`)}function tn(l,e){let t=0,n=0,r=0,s=0,o="";for(;r<e;){let u=t,d=n;for(;l[u]===" "||l[u]===" ";)d+=Ge(l[u],d),u++;if(l[u]!==">"||d-s>3)break;o+=" ".repeat(d-n)+">",r++,t=u+1,n=d+1,s=l[t]===" "||l[t]===" "?n+1:n}if(r===0)return{depth:r,expanded:l,keptIndent:l,content:l};let i="",a="";for(;(l[t]===" "||l[t]===" ")&&n<s+4;){let u=Ge(l[t],n);i+=" ".repeat(u),a+=n<s&&u>1?" ".repeat(u):l[t],n+=u,t++}let p=l.slice(t);return{depth:r,expanded:o+i+p,keptIndent:o+a+p,content:" ".repeat(Math.max(0,n-s))+p}}function Ge(l,e){return l===" "?4-e%4:1}function nn(l,e){let t="";for(let n=0;n<l.length;n++){if(l[n]==="`"){let r=e.inline.code.exec(l.slice(n));if(r){t+=r[0],n+=r[0].length-1;continue}}if(l[n]==="\\"&&(l[n+1]==="["||l[n+1]==="]")){t+=l[n+1],n++;continue}t+=l[n]}return t}function Xe(l,e,t,n,r){let s=e.href,o=e.title||null,i=nn(l[1],r),a=l[0].charAt(0)==="!",p=n.state.inLink,u=n.state.linkEmitted,d=n.state.inRawBlock;n.state.inLink=!0,n.state.linkEmitted=!1;let k=n.inlineTokens(i),g=n.state.linkEmitted;if(n.state.linkEmitted=u,n.state.inLink=p,!a){if(g){n.state.inRawBlock=d;return}n.state.linkEmitted=!0}return{type:a?"image":"link",raw:t,href:s,title:o,text:i,tokens:k}}function rn(l,e,t,n){let r=l.match(t.other.indentCodeCompensation);if(r===null)return e;let s=r[1].length;return e.split(`
`).map(o=>{let i=o.match(t.other.beginningSpace);if(i===null)return o;let[a]=i,p=a.indexOf(" ");if(p!==-1&&p<s){if(n)return" ".repeat(4-s)+o.slice(p+1);if(l[s]==="~")return o}return o.slice(Math.min(a.length,s))}).join(`
`)}function Ve(l,e,t,n){if(!e.includes("<"))return!1;for(let r=0;r<e.length;r++){if(e[r]==="\\"){r++;continue}if(e[r]==="`"){let i=n.inline.code.exec(e.slice(r));if(i){r+=i[0].length-1;continue}}if(e[r]!=="<")continue;let s=l.slice(t+r),o=n.inline.tag.exec(s)||n.inline.autolink.exec(s);if(o){if(o[0].length>e.length-r)return!0;r+=o[0].length-1}}return!1}var C=class{options;rules;lexer;constructor(e){this.options=e||$}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:Pe(t[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=rn(n,t[3]||"",this.rules,this.lexer.state.top&&!this.lexer.state.inBlockquote);t[3]!==void 0&&(r===""||r.endsWith(`
`))&&(r+=`
`);let s=t[2];if(s){let o=0,i=s.length;for(;o<i&&(s[o]===" "||s[o]===" ");)o++;for(;i>o&&(s[i-1]===" "||s[i-1]===" ");)i--;s=s.slice(o,i).replace(this.rules.inline.anyPunctuation,"$1")}return{type:"code",raw:n,lang:s,text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=z(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceTabChar.test(r))&&(n=r.trim())}return{type:"heading",raw:z(t[0],`
`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:z(t[0],`
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=z(t[0],`
`).split(`
`),r="",s="",o=[];for(;n.length>0;){let i=!1,a=[],p;for(p=0;p<n.length;p++)if(this.rules.other.blockquoteStart.test(n[p]))a.push(n[p]),i=!0;else if(!i)a.push(n[p]);else break;n=n.slice(p);let u=a.join(`
`),k=(this.lexer.state.top&&!this.lexer.state.inBlockquote&&u.includes(" ")?Ke(a):u).replace(this.rules.other.blockquoteMarkerWhitespace,(w,f,m)=>m.startsWith(" ")?f+" "+m.slice(1):f+X(m,f.length)).replace(this.rules.other.blockquoteSetextReplace,`
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
${u}`:u,s=s?`${s}
${k}`:k;let g=this.lexer.state.top,c=this.lexer.state.inBlockquote,R=this.lexer.state.lastToken;if(this.lexer.state.top=!0,this.lexer.state.inBlockquote=!0,this.lexer.blockTokens(k,o,!0),this.lexer.state.top=g,this.lexer.state.inBlockquote=c,n.length===0)break;let x=o.at(-1);if(x?.type==="code"||x?.type==="heading"||x?.type==="hr"||x?.type==="html"||x?.type==="table")break;if(x?.type==="blockquote"){let w=x,f=n.join(`
`),m=w.raw+`
`+f.replace(this.rules.other.blockquoteSetextReplace2,"");this.lexer.state.inBlockquote=!0,this.lexer.state.lastToken=o.at(-2);let _=this.blockquote(m);this.lexer.state.inBlockquote=c,this.lexer.state.lastToken=R,o[o.length-1]=_;let T=m.substring(_.raw.length).replace(/^\n/,""),H=T?T.split(`
`).length:0,D=H?n.slice(0,-H):n;if(D.length>0&&(r=`${r}
${D.join(`
`)}`),s=s.substring(0,s.length-w.text.length)+_.text,n=n.slice(D.length),n.length>0&&this.rules.other.blockquoteStart.test(n[0]))continue;break}else if(x?.type==="list"){let w=x,f=w.raw+`
`+n.join(`
`);this.lexer.state.inBlockquote=!0,this.lexer.state.lastToken=o.at(-2);let m=this.list(f);this.lexer.state.top=g,this.lexer.state.inBlockquote=c,this.lexer.state.lastToken=R,o[o.length-1]=m;let _=m.raw.length>w.raw.length?f.slice(w.raw.length+1,m.raw.length).split(`
`).length:0;if(_>0){let T=n.slice(0,_).join(`
`);r=`${r}
${T}`,s=`${s}
${T}`}if(n=n.slice(_),n.length>0&&!this.rules.other.blockquoteStart.test(n[0]))break;continue}}return{type:"blockquote",raw:r,tokens:o,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){if(!this.options.pedantic&&this.lexer.state.lastToken?.type==="text"&&!this.rules.other.listInterruptsParagraph.test(e))return;let n=e,r=()=>n.length-e.length,s=t[1].trim(),o=s.length>1,i={type:"list",raw:"",ordered:o,start:o?+s.slice(0,-1):"",loose:!1,items:[]};s=o?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=o?s:"[*+-]");let a=this.rules.other.listItemRegex(s),p=!1;for(;e;){let g=!1,c="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;let R=r();e=e.substring(t[0].length);let x=t[2].split(`
`,1)[0],w=t[1].length,f=this.options.pedantic?X(x,w):x.replace(this.rules.other.leadingSpaceTab,D=>X(D,w)),m=e.split(`
`,1)[0],_=!f.trim(),T=0;if(this.options.pedantic?(T=2,c=f.trimStart()):_?T=w+1:(T=f.search(this.rules.other.nonSpaceChar),T=T>4?1:T,c=f.slice(T),f=c,T+=w),_&&this.rules.other.blankLine.test(m)&&(e=e.substring(m.length+1),g=!0),!g){let D=this.rules.other.nextBulletRegex(T),V=this.rules.other.hrRegex(T),ie=this.rules.other.fencesBeginRegex(T),Z=this.options.pedantic?this.rules.other.pedanticHeadingBeginRegex(T):this.rules.other.headingBeginRegex(T),J=this.rules.other.htmlBeginRegex(T),oe=this.rules.other.blockquoteBeginRegex(T),ae=!1;for(;e;){let $e=e.split(`
`,1)[0],L;if(m=$e,this.options.pedantic?(m=m.replace(this.rules.other.listReplaceNesting," "),L=m):L=m.replace(this.rules.other.leadingSpaceTab,I=>X(I)),ie.test(m)||Z.test(m)||J.test(m)||oe.test(m)||D.test(m)||V.test(m))break;if(L.search(this.rules.other.nonSpaceChar)>=T||!m.trim())c+=`
`+L.slice(T),ae=!1;else{if(_)break;let I=f;if(!this.options.pedantic&&!c.includes(`
`)&&!f.includes(" ")){let A;for(;!V.test(I)&&(A=this.rules.other.nestedBlockMarker.exec(I));)I=I.slice(A[0].length);if(!I.trim())break}if(I.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ie.test(I)||Z.test(I)||J.test(I)||V.test(I))break;if(!this.options.pedantic&&!ae){let A=f.replace(this.rules.other.nestedContainerMarkers,"");if(this.rules.block.fences.test(A)||this.rules.block.heading.test(A)||this.rules.block.hr.test(A))break}let Ce=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(m)&&this.rules.block.lheading.test(`${f}
${m}`)?` ${L.replace(/^ {0,3}/,"")}`:m,de=!this.options.pedantic&&!ae&&L.startsWith(" ")?this.rules.block.list.exec(f):null;if(de?.[2]){let A=de[1].length,Ie=de[2].replace(this.rules.other.leadingSpaceTab,Je=>X(Je,A)),Y=Ie.search(this.rules.other.nonSpaceChar);Y>0&&Y<=4&&!this.rules.other.nestedBlockMarker.test(Ie.slice(Y))&&L.search(this.rules.other.nonSpaceChar)>=A+Y&&this.rules.other.listInterruptsParagraph.test(L.slice(A+Y))&&(Ce=` ${L}`)}c+=`
`+Ce,ae=!0}_=!m.trim(),e=e.substring($e.length+1),f=L.slice(T)}}let H=n.slice(R,r());i.loose||(p?i.loose=!0:this.rules.other.doubleBlankLine.test(H)&&(p=!0)),i.items.push({type:"list_item",raw:H,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]})}let u=i.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;i.raw=n.slice(0,r()).trimEnd();let d=[],k=this.lexer.state.top;for(let g of i.items)if(this.lexer.state.top=!1,d.push(this.lexer.inlineQueue.length),g.tokens=this.lexer.blockTokens(g.text,[]),!i.loose){let c=g.tokens.filter(x=>x.type==="space"),R=c.length>0&&c.some(x=>this.rules.other.anyLine.test(x.raw));i.loose=R}this.lexer.state.top=k;for(let g=0;g<i.items.length;g++){let c=i.items[g],R=c.tokens[0];if(c.task&&(R?.type==="text"||R?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),R.raw=R.raw.replace(this.rules.other.listReplaceTask,""),R.text=R.text.replace(this.rules.other.listReplaceTask,"");let x=this.lexer.inlineQueue;for(let f=d[g];f<x.length;f++)if(x[f].tokens===R.tokens){x[f].src=x[f].src.replace(this.rules.other.listReplaceTask,"");break}let w=this.rules.other.listTaskCheckbox.exec(c.raw);if(w){let f={type:"checkbox",raw:w[0]+" ",checked:w[0]!=="[ ]"};c.checked=f.checked,i.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=f.raw+c.tokens[0].raw,c.tokens[0].text=f.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(f)):c.tokens.unshift({type:"paragraph",raw:f.raw,text:f.raw,tokens:[f]}):c.tokens.unshift(f)}}else c.task&&(c.task=!1)}if(i.loose)for(let g of i.items){g.loose=!0;for(let c of g.tokens)c.type==="text"&&(c.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){if(this.lexer.state.lastToken?.type==="paragraph"&&!this.rules.other.htmlBeginRegex(4).test(e))return;let n=Pe(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&ye(t[2],"()")!==-1)return;let n=K(t[1],this.options.pedantic),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:z(t[0],`
`),href:r,title:s}}}table(e){let t,n;if(this.options.gfm&&!this.options.pedantic){let i=this.rules.other.tableHeader.exec(e);if(!i||!this.rules.other.tableDelimiter.test(i[2])||(t=pe(i[1]),n=i[2].replace(this.rules.other.tableAlignChars,"").split("|"),t.length!==n.length))return}let r=this.rules.block.table.exec(e);if(!r||!this.rules.other.tableDelimiter.test(r[2]))return;t??=pe(r[1]),n??=r[2].replace(this.rules.other.tableAlignChars,"").split("|");let s=r[3]?.trim()?r[3].replace(this.rules.other.tableRowBlankLine,"").split(`
`):[],o={type:"table",raw:z(r[0],`
`),header:[],align:[],rows:[]};if(t.length===n.length){for(let i of n)this.rules.other.tableAlignRight.test(i)?o.align.push("right"):this.rules.other.tableAlignCenter.test(i)?o.align.push("center"):this.rules.other.tableAlignLeft.test(i)?o.align.push("left"):o.align.push(null);for(let i=0;i<t.length;i++)o.header.push({text:t[i],tokens:this.lexer.inline(t[i]),header:!0,align:o.align[i]});for(let i of s)o.rows.push(pe(i,o.header.length).map((a,p)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[p]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:z(t[0],`
`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t){let n=t[0],r=t[0],s=this.rules.other.textIndentedContinuation.exec(e.slice(n.length));return s&&(n+=s[0],r+=s[0].replace(this.rules.other.codeRemoveIndent,"")),{type:"text",raw:n,text:r,tokens:this.lexer.inline(r)}}}escape(e){if(e.charCodeAt(0)!==92)return;let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){if(e.charCodeAt(0)!==60)return;let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){if(this.lexer.state.linkParenPossible===!1)return;let t=e.charCodeAt(0);if(t!==91&&t!==33)return;let n=this.rules.inline.link.exec(e);if(n){let r=n[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&Ve(e,n[1],r,this.rules))return;let s=n[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let p=z(s.slice(0,-1),"\\");if((s.length-p.length)%2===0)return}else{let p=ye(n[2],"()");if(p===-2)return;if(p>-1){let d=(n[0].indexOf("!")===0?5:4)+n[1].length+p;n[2]=n[2].substring(0,p),n[0]=n[0].substring(0,d).trim(),n[3]=""}}let o=z(n[0].slice(0,-1),"\\");if((n[0].length-o.length)%2===0)return;let i=n[2],a="";if(this.options.pedantic){let p=this.rules.other.pedanticHrefTitle.exec(i);p&&(i=p[1],a=p[3])}else a=n[3]?n[3].slice(1,-1):"";return this.options.pedantic&&(i=i.trim()),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?i=i.slice(1):i=i.slice(1,-1)),Xe(n,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},n[0],this.lexer,this.rules)}}reflink(e,t){let n=e.charCodeAt(0);if(n!==91&&n!==33)return;let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let s=r[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&Ve(e,r[1],s,this.rules))return;let o=t[K(r[2]||r[1],this.options.pedantic)];if(!o){let i=r[0].charAt(0);return{type:"text",raw:i,text:i}}return Xe(r,o,r[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||!r[1]&&!r[2]&&!r[3]&&!r[4])return;let s=r[0][0],o=n===s,i=t.length-e.length,a=i;for(;!this.options.pedantic&&a>0&&t[a-1]===s;)a--;let p=[...t.slice(Math.max(0,a-2),a)].at(-1)??"",u=p==="*"||p==="_"||!!this.rules.inline.punctuation.exec(p);a<i&&(n=p);let d=a<i?u:n==="*"||n==="_"||!!this.rules.inline.punctuation.exec(n);if(r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;let k=r[1]||r[3]||"";if(!k||!n||d){let g=[...r[0]].length-1,c,R,x=g,w=0,f=i-a+g,m=!this.options.pedantic&&!!p.trim()&&(!!k||s==="*"&&!u);if(s!=="*"&&s!=="_")return;let _=s==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd,T=ce(this,t,s),H=t.length-e.length+g;if(T<H)return;t=t.slice(-1*e.length+g);let D=T-H;for(_.lastIndex=0;(r=_.exec(t))!==null&&!(r.index>D);){if(c=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!c)continue;R=[...c].length;let V=R>x-g;if(r[3]||r[4]){x+=R;continue}else if((r[5]||r[6]||m&&V)&&f%3&&!((f+R)%3)){if(o&&(r[5]||r[6]))break;w+=R;continue}if(x-=R,x>0)continue;R=Math.min(R,R+x+w);let ie=[...r[0]][0].length,Z=e.slice(0,g+r.index+ie+R);if(Math.min(g,R)%2){let oe=Z.slice(1,-1);return{type:"em",raw:Z,text:oe,tokens:this.lexer.inlineTokens(oe)}}let J=Z.slice(2,-2);return{type:"strong",raw:Z,text:J,tokens:this.lexer.inlineTokens(J)}}}}codespan(e){if(e.charCodeAt(0)!==96)return;let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=e.charCodeAt(0);if(t!==32&&t!==92&&t!==10)return;let n=this.rules.inline.br.exec(e);if(n)return{type:"br",raw:n[0]}}del(e,t,n=""){if(e.charCodeAt(0)!==126)return;let r=this.rules.inline.delLDelim.exec(e);if(!r)return;if(!(r[1]||"")||!n||this.rules.inline.punctuation.exec(n)){let o=[...r[0]].length-1,i,a,p=o,u=this.rules.inline.delRDelim,d=he(this,t),k=t.length-e.length+o;if(d<k)return;t=t.slice(-1*e.length+o);let g=d-k;for(u.lastIndex=0;(r=u.exec(t))!==null&&!(r.index>g);){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==o))continue;if(r[3]||r[4]){p+=a;continue}if(p-=a,p>0)continue;a=Math.min(a,a+p);let c=[...r[0]][0].length,R=e.slice(0,o+r.index+c+a),x=R.slice(o Line truncated
`)),n.inlineTokens(e)}lex(e){e=e.replace(b.carriageReturn,`
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.state.inRawBlock=!1,this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this;let r=this.state.lastToken;this.options.pedantic&&(e=e.replace(b.tabCharGlobal," ").replace(b.spaceLine,""));let s=1/0,o,i=this.options.gfm&&!this.options.pedantic&&this.tokenizer.paragraph===C.prototype.paragraph;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}this.state.lastToken=t.at(-1);let a;if(this.options.extensions?.block?.some(u=>(a=u.call({lexer:this},e,t))?(e=e.substring(a.raw.length),t.push(a),!0):!1))continue;if(a=this.tokenizer.space(e)){e=e.substring(a.raw.length);let u=t.at(-1);a.raw.length===1&&u!==void 0?u.raw+=`
`:t.push(a);continue}if(a=this.tokenizer.code(e)){e=e.substring(a.raw.length);let u=t.at(-1);u?.type==="paragraph"||u?.type==="text"?(u.raw+=(u.raw.endsWith(`
`)?"":`
`)+a.raw,u.text+=`
`+a.text,this.inlineQueue.at(-1).src=u.text):t.push(a);continue}if(a=this.tokenizer.fences(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.heading(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.hr(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.blockquote(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.list(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.html(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.def(e)){e=e.substring(a.raw.length);let u=t.at(-1);u?.type==="paragraph"||u?.type==="text"?(u.raw+=(u.raw.endsWith(`
`)?"":`
`)+a.raw,u.text+=`
`+a.raw,this.inlineQueue.at(-1).src=u.text):(this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title}),t.push(a));continue}if(a=this.tokenizer.table(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.lheading(e)){e=e.substring(a.raw.length),t.push(a);continue}let p=e;if(this.options.extensions?.startBlock){let u=1/0,d=e.slice(1),k;this.options.extensions.startBlock.forEach(g=>{k=g.call({lexer:this},d),typeof k=="number"&&k>=0&&(u=Math.min(u,k))}),u<1/0&&u>=0&&(p=e.substring(0,u+1))}if(this.state.top&&(a=this.tokenizer.paragraph(p))){let u=t.at(-1);(n||u===o&&i)&&u?.type==="paragraph"?(u.raw+=(u.raw.endsWith(`
`)?"":`
`)+a.raw,u.text+=`
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text,o=u):(t.push(a),o=a),n=p.length!==e.length,e=e.substring(a.raw.length);continue}if(a=this.tokenizer.text(e)){e=e.substring(a.raw.length);let u=t.at(-1);u?.type==="text"?(u.raw+=(u.raw.endsWith(`
`)?"":`
`)+a.raw,u.text+=`
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):t.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,this.state.lastToken=r,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!=="!")return!0;for(let n of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let r=n[0],s=r.lastIndexOf("[");if(!(r.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,K(r.slice(s+1,-1),this.options.pedantic)))&&!(s>1&&this.linkInText(r.slice(1,s-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=e.includes(")");try{return this.#t(e,t)}finally{this.state.linkParenPossible=n}}#t(e,t){let n=e.includes("*")||e.includes("_")||e.includes("~"),r=n||this.options.hooks?.emStrongMask||this.tokenizer.emStrong!==C.prototype.emStrong||this.tokenizer.del!==C.prototype.del?this.#r(e):e;if(!n)return this.#e(e,r,t);We(this.tokenizer,r);try{return this.#e(e,r,t)}finally{Ue(this.tokenizer)}}#e(e,t,n){let r=!1,s="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}r||(s=""),r=!1;let i;if(this.options.extensions?.inline?.some(u=>(i=u.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length);let u=n.at(-1);i.type==="text"&&u?.type==="text"?(u.raw+=i.raw,u.text+=i.text):n.push(i);continue}let a=e[0];if(a==="*"||a==="_"){let u=t.length-e.length;if(ce(this.tokenizer,t,a)<=u){let k=1;for(;k<e.length&&e.charCodeAt(k)===a.charCodeAt(0);)k++;let g=e.substring(0,k),c=n.at(-1);c?.type==="text"&&!c.escaped?(c.raw+=g,c.text+=g):n.push({type:"text",raw:g,text:g,escaped:!1}),e=e.substring(k),s=a,r=!0;continue}}else if(a==="~"){let u=t.length-e.length;if(he(this.tokenizer,t)<=u){let k=1;for(;k<e.length&&e.charCodeAt(k)===126;)k++;let g=e.substring(0,k),c=n.at(-1);c?.type==="text"&&!c.escaped?(c.raw+=g,c.text+=g):n.push({type:"text",raw:g,text:g,escaped:!1}),e=e.substring(k),s=a,r=!0;continue}}if(i=this.tokenizer.emStrong(e,t,s)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.del(e,t,s)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.autolink(e)){e=e.substring(i.raw.length),n.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e))){e=e.substring(i.raw.length),n.push(i);continue}let p=e;if(this.options.extensions?.startInline){let u=1/0,d=e.slice(1),k;this.options.extensions.startInline.forEach(g=>{k=g.call({lexer:this},d),typeof k=="number"&&k>=0&&(u=Math.min(u,k))}),u<1/0&&u>=0&&(p=e.substring(0,u+1))}if(i=this.tokenizer.inlineText(p)){e=e.substring(i.raw.length),i.raw.slice(-1)!=="_"&&(s=i.raw.slice(-1)),r=!0;let u=n.at(-1);u?.type==="text"?(u.raw+=i.raw,u.text+=i.text):n.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}#n(e){let{blockSkip:t,tag:n,autolink:r}=this.tokenizer.rules.inline,s="",o=0,i;for(t.lastIndex=0;i=t.exec(e);){let a=i.index+(i[2]?i[2].length:0),p=i.index+i[0].length;if(e.charAt(a)==="<"){let u=e.slice(a),d=n.exec(u)||r.exec(u);if(!d){t.lastIndex=a+1;continue}p=a+d[0].length,t.lastIndex=p}s+=e.slice(o,a)+"["+"a".repeat(p-a-2)+"]",o=p}return s+e.slice(o)}#r(e){let t=e;if(this.tokens.links&&e.includes("[")){let n=this.tokenizer.rules.inline.reflinkSearch,r=s=>{let o=s.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,K(s.slice(o+1,-1),this.options.pedantic)))return s;if(o>1&&s.charAt(0)!=="!"){let i=s.slice(1,o-1);if(this.linkInText(i))return"["+i.replace(n,r)+"]["+"a".repeat(s.length-o-2)+"]"}return"["+"a".repeat(s.length-2)+"]"};t=t.replace(n,r)}return t=t.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(n,r,s)=>s?"+".repeat(n.length):r?r+n.slice(r.length,-r.length).replace(/`/g,"+")+r:n),t=this.#n(t),t=this.options.hooks?.emStrongMask?.call({lexer:this},t)??t,t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}};function _e(l,e=!1){let t;for(let n=0;n<l.length;n++){let r=l[n],s=r;if(r.type==="codespan"||r.type==="escape"||e&&r.type==="text"){let o=P(r.text,!0);o!==r.text&&(s={...r,text:o})}else if(r.type==="link"&&r.autolink){let o=P(r.text,!0),i=r.tokens,a=i&&(i.length===1&&i[0].type==="text"&&i[0].text===r.text?o!==r.text?[{...i[0],text:o}]:i:_e(i,!0));(o!==r.text||a!==i)&&(s=a!==i?{...r,text:o,tokens:a}:{...r,text:o})}else if("tLine truncated
`:"";return r?'<pre><code class="language-'+P(r)+'">'+(n?s:P(s,!0))+`</code></pre>
`:"<pre><code>"+(n?s:P(s,!0))+`</code></pre>
`}blockquote({tokens:e}){return`<blockquote>
${this.parser.parse(e)}</blockquote>
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
`}hr(e){return`<hr>
`}list(e){let t=e.ordered,n=e.start,r="";for(let i=0;i<e.items.length;i++){let a=e.items[i];r+=this.listitem(a)}let s=t?"ol":"ul",o=t&&n!==1?' start="'+n+'"':"";return"<"+s+o+`>
`+r+"</"+s+`>
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
`}table(e){let t="",n="";for(let s=0;s<e.header.length;s++)n+=this.tablecell(e.header[s]);t+=this.tablerow({text:n});let r="";for(let s=0;s<e.rows.length;s++){let o=e.rows[s];n="";for(let i=0;i<o.length;i++)n+=this.tablecell(o[i]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
<thead>
`+t+`</thead>
`+r+`</table>
`}tablerow({text:e}){return`<tr>
${e}</tr>
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${P(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:r,autolink:s}){let o=s?P(n,!0):this.parser.parseInline(r),i=we(e);if(i===null)return o;e=P(i,s);let a='<a href="'+e+'"';return t&&(a+=' title="'+P(t)+'"'),a+=">"+o+"</a>",a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(_e(r),this.parser.textRenderer));let s=we(e);if(s===null)return P(n);e=s;let o=`<img src="${P(e)}" alt="${P(n)}"`;return t&&(o+=` title="${P(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:P(e.text)}};var q=class{parser;strong({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}em({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}codespan({text:e}){return e}del({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}html({text:e}){return e}text({text:e}){return e}link({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}image({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}br(){return`
`}checkbox({raw:e}){return e}};var S=class l{options;renderer;textRenderer;constructor(e){this.options=e||$,this.options.renderer=this.options.renderer||new M,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new q,this.textRenderer.parser=this}static parse(e,t){return new l(t).parse(e)}static parseInline(e,t){return new l(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let r=e[n],s=this.options.extensions?.renderers;if(s&&Object.hasOwn(s,r.type)&&s[r.type]){let i=r,a=s[i.type].call({parser:this},i);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(i.type)){t+=a===!1?"":a??"";continue}}let o=r;switch(o.type){case"space":{t+=this.renderer.space(o);break}case"hr":{t+=this.renderer.hr(o);break}case"heading":{t+=this.renderer.heading(o);break}case"code":{t+=this.renderer.code(o);break}case"table":{t+=this.renderer.table(o);break}case"blockquote":{t+=this.renderer.blockquote(o);break}case"list":{t+=this.renderer.list(o);break}case"checkbox":{t+=this.renderer.checkbox(o);break}case"html":{t+=this.renderer.html(o);break}case"def":{t+=this.renderer.def(o);break}case"paragraph":{t+=this.renderer.paragraph(o);break}case"text":{t+=this.renderer.text(o);break}default:{let i='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let s=e[r],o=this.options.extensions?.renderers;if(o&&Object.hasOwn(o,s.type)&&o[s.type]){let a=o[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(s.type)){n+=a===!1?"":a??"";continue}}let i=s;switch(i.type){case"escape":{n+=t.text(i);break}case"html":{n+=t.html(i);break}case"link":{n+=t.link(i);break}case"image":{n+=t.image(i);break}case"checkbox":{n+=t.checkbox(i);break}case"strong":{n+=t.strong(i);break}case"em":{n+=t.em(i);break}case"codespan":{n+=t.codespan(i);break}case"br":{n+=t.br(i);break}case"del":{n+=t.del(i);break}case"text":{n+=t.text(i);break}default:{let a='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}};var B=class{options;block;constructor(e){this.options=e||$}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?y.lex:y.lexInline}provideParser(e=this.block){return e?S.parse:S.parseInline}};function v(l,e){if(Array.isArray(e))for(let t=0;t<e.length;t++)l.push(e[t]);else l.push(e)}var se=class{defaults=G();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=S;Renderer=M;TextRenderer=q;Lexer=y;Tokenizer=C;Hooks=B;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(v(n,t.call(this,r)),r.type){case"table":{let s=r;for(let o of s.header)v(n,this.walkTokens(o.tokens,t));for(let o of s.rows)for(let i of o)v(n,this.walkTokens(i.tokens,t));break}case"list":{let s=r;v(n,this.walkTokens(s.items,t));break}default:{let s=r;this.defaults.extensions?.childTokens?.[s.type]?this.defaults.extensions.childTokens[s.type].forEach(o=>{if(s[o]){let i=s[o].flat(1/0);v(n,this.walkTokens(i,t))}}):s.tokens&&v(n,this.walkTokens(s.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:Object.create(null),childTokens:Object.create(null)};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s&&s.renderer){let o=s.renderer,i=t.renderers[s.name];i?t.renderers[s.name]=function(...a){let p=o.apply(this,a);return p===!1&&(p=i.apply(this,a)),p}:t.renderers[s.name]=o}if("tokenizer"in s&&s.tokenizer){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[s.level];o?o.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level==="block"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level==="inline"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),r.extensions=t),n.renderer){let s=this.defaults.renderer||new M(this.defaults);for(let o in n.renderer){if(!(o in s))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let i=o,a=n.renderer[i];if(a===void 0)continue;let p=s[i];s[i]=(...u)=>{let d=a.apply(s,u);return d===!1&&(d=p.apply(s,u)),d===!1?"":d??""}}r.renderer=s}if(n.tokenizer){let s=this.defaults.toke Line truncated
Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+P(r.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(r);throw r}}};var F=new se;function O(l,e){return F.parse(l,e)}function sn(l,e){return F.parseInline(l,e)}O.options=O.setOptions=function(l){return F.setOptions(l),O.defaults=F.defaults,ge(O.defaults),O};O.getDefaults=G;O.defaults=$;function on(...l){return F.use(...l),O.defaults=F.defaults,ge(O.defaults),O}O.use=on;O.walkTokens=function(l,e){return F.walkTokens(l,e)};O.parseInline=sn;O.Parser=S;O.parser=S.parse;O.Renderer=M;O.TextRenderer=q;O.Lexer=y;O.lexer=y.lex;O.Tokenizer=C;O.Hooks=B;O.parse=O;var Xn=O.options,Vn=O.setOptions,Jn=O.walkTokens,Yn=O.parseInline,er=O,tr=S.parse,nr=y.lex;export{B as Hooks,y as Lexer,se as Marked,S as Parser,M as Renderer,q as TextRenderer,C as Tokenizer,$ as defaults,G as getDefaults,nr as lexer,O as marked,Xn as options,er as parse,Yn as parseInline,tr as parser,Vn as setOptions,on as use,Jn as walkTokens};
+2646
View File
File diff suppressed because it is too large. Load diff