window.__ModuleLoader__.load({ id: "dsh-better-chat", factory: (require) => { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); // \0rolldown/runtime.js var __defProp = Object.defineProperty; var __exportAll = (all, flags) => { let target = Object.setPrototypeOf({}, null); for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" }); return flags & 2 ? target : Object.preventExtensions(target); }; let _deepseek_ai_dsh_client_store = require("@deepseek-ai/dsh-client-store"); let react = require("react"); let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives"); let react_jsx_runtime = require("react/jsx-runtime"); // src/client/chat/bindings.ts const DEFAULT_BINDINGS = { allow: { key: "Enter", primary: false, shift: false, alt: false }, always: { key: "Enter", primary: true, shift: false, alt: false }, reject: { key: "Escape", primary: false, shift: false, alt: false } }; /** 设置页保存快捷键后派发的窗口事件;提示与判定都靠实时 getter,无需重启。 */ const BINDINGS_CHANGED_EVENT = "better-chat:bindings-changed"; /** 每个动作允许的基础键:允许类只能用 Enter,拒绝只能用 Esc。 */ function baseKeyFor(action) { return action === "reject" ? "Escape" : "Enter"; } /** 展示用键帽文案,例如 Enter / Ctrl+Enter / Shift+Alt+Enter / Esc。 */ function bindingKeycap(binding, mac) { const parts = []; if (binding.primary) parts.push(mac ? "Cmd" : "Ctrl"); if (binding.shift) parts.push("Shift"); if (binding.alt) parts.push("Alt"); parts.push(binding.key === "Escape" ? "Esc" : binding.key); return parts.join("+"); } /** 纯判定:按键事件是否命中这条绑定(修饰键必须完全一致)。 */ function bindingMatches(binding, event) { const primary = Boolean(event.ctrlKey) || Boolean(event.metaKey); return event.key === binding.key && primary === binding.primary && Boolean(event.shiftKey) === binding.shift && Boolean(event.altKey) === binding.alt; } /** 是否是不带任何修饰键的裸键(Enter / Esc)。 */ function isPlainBinding(binding) { return Boolean(binding) && !binding.primary && !binding.shift && !binding.alt; } /** 两条绑定是否相同。 */ function bindingsEqual(left, right) { if (!left || !right) return left === right; return left.key === right.key && left.primary === right.primary && left.shift === right.shift && left.alt === right.alt; } function booleanOrFalse(value) { return value === true; } /** 校验并收敛一条绑定;形状不对时返回 undefined。 */ function normalizeBinding(value) { if (!value || typeof value !== "object") return void 0; const record = value; if (record.key !== "Enter" && record.key !== "Escape") return void 0; return { key: record.key, primary: booleanOrFalse(record.primary), shift: booleanOrFalse(record.shift), alt: booleanOrFalse(record.alt) }; } /** * 把持久化快照收敛成合法绑定;`{ bindings: ... }` 或内层对象都接受。 * 缺失/非法/冲突的项回落到默认值,保证任何旧快照都能用。 */ function normalizeBindings(value) { const inner = value && typeof value === "object" && "bindings" in value ? value.bindings : value; const record = inner && typeof inner === "object" ? inner : {}; const allowRaw = normalizeBinding(record.allow); const rejectRaw = normalizeBinding(record.reject); const allow = allowRaw && allowRaw.key === "Enter" ? allowRaw : { ...DEFAULT_BINDINGS.allow }; const reject = rejectRaw && rejectRaw.key === "Escape" ? rejectRaw : { ...DEFAULT_BINDINGS.reject }; const alwaysRaw = "always" in record ? record.always : DEFAULT_BINDINGS.always; const alwaysParsed = alwaysRaw === null ? null : normalizeBinding(alwaysRaw); const out = { allow, always: alwaysParsed && alwaysParsed.key === "Enter" ? alwaysParsed : alwaysRaw === null ? null : { ...DEFAULT_BINDINGS.always }, reject }; if (out.always && (!hasModifier(out.always) || bindingsEqual(out.allow, out.always))) { out.allow = { ...DEFAULT_BINDINGS.allow }; out.always = { ...DEFAULT_BINDINGS.always }; } if (out.always && bindingsEqual(out.reject, out.always)) out.reject = { ...DEFAULT_BINDINGS.reject }; if (bindingsEqual(out.allow, out.reject)) { out.allow = { ...DEFAULT_BINDINGS.allow }; out.reject = { ...DEFAULT_BINDINGS.reject }; } return out; } function hasModifier(binding) { return binding.primary || binding.shift || binding.alt; } /** * 保存前的校验:基础键是否匹配动作、始终允许是否有修饰键、是否与其他动作冲突。 */ function validateBinding(action, binding, current) { if (binding.key !== baseKeyFor(action)) return "key"; if (action === "always" && !hasModifier(binding)) return "modifier"; const others = []; if (action !== "allow") others.push(current.allow); if (action !== "always" && current.always) others.push(current.always); if (action !== "reject") others.push(current.reject); if (others.some((other) => bindingsEqual(other, binding))) return "conflict"; return "ok"; } // src/client/chat/approval-keys.ts /** * 功能一:审批卡片的回车批准 / Esc 拒绝(自动送入焦点 + 全局兜底路由)。 * * 背景(@deepseek-ai/dsh-client-ui-approval):官方审批卡自带键盘处理 * —— Enter 批准(单次)、Esc 拒绝 —— 但 keydown 挂在卡片根节点上,且 * 要求焦点先落在卡片内。审批弹出时焦点往往还在对话区,按回车毫无反应。 * * 本模块补两件事,不改官方任何逻辑: * 1. 审批卡出现时,若用户没有正在别处输入,把焦点送进卡片详情区。 * 2. 焦点不在卡片内时兜底路由:document 捕获阶段拦 keydown,点击卡片 * 操作行里的按钮 —— 回车点「允许(单次)」,Esc 点「拒绝」。 */ const CARD_SELECTOR$1 = "[data-approval-key]"; const SCROLL_SELECTOR = "[data-approval-scroll]"; const EDITABLE_SELECTOR = "input, textarea, select, [contenteditable=\"true\"], [contenteditable=\"\"]"; /** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */ function actionButtons(card) { return [...card.querySelectorAll("button")].filter((button) => !button.closest(SCROLL_SELECTOR)); } /** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */ function findPendingCard(doc) { for (const card of doc.querySelectorAll(CARD_SELECTOR$1)) { if (card.getAttribute("aria-busy") === "true") continue; const buttons = actionButtons(card); if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card; } return null; } /** * 纯判定:这次 keydown 是否应该路由到审批卡。 * * 默认绑定:Enter → 允许(单次)、Ctrl/Cmd+Enter → 始终允许、Esc → 拒绝; * 绑定可由设置页改写(见 bindings.ts),基础键固定 Enter/Escape,只调修饰键。 * 官方卡片本身对带修饰键的按键不作答,所以带修饰键的绑定即使在卡内也由 * 本插件处理;裸 Enter/Esc 在卡内交给官方。 * * @returns 'allow' | 'reject' | 'always' | null */ function decideKeyAction(input) { const { repeat, isComposing, keyCode, defaultPrevented, target, activeElement, card, hasAlways } = input; if (!card) return null; if (defaultPrevented) return null; if (repeat || isComposing || keyCode === 229) return null; if (target && typeof target.closest === "function" && target.closest(EDITABLE_SELECTOR) !== null) return null; const bindings = input.bindings ?? DEFAULT_BINDINGS; const candidates = [ ["allow", bindings.allow], ["always", hasAlways ? bindings.always : null], ["reject", bindings.reject] ]; for (const [action, binding] of candidates) { if (!binding || !bindingMatches(binding, input)) continue; if (isPlainBinding(binding)) { if (activeElement && card.contains(activeElement)) return null; if (binding.key === "Enter" && target && typeof target.closest === "function" && target.closest("button, a[href], [role=\"button\"]") !== null) return null; } return action; } return null; } /** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */ function shouldAutoFocus(activeElement, card) { if (!activeElement) return true; if (activeElement === card.ownerDocument?.body) return true; if (card.contains(activeElement)) return false; if (typeof activeElement.closest === "function" && activeElement.closest(EDITABLE_SELECTOR) !== null) return false; return true; } /** 安装审批键盘增强,返回卸载函数。 */ function install(doc, getBindings) { const focusedCards = /* @__PURE__ */ new WeakSet(); const tryAutoFocus = () => { const card = findPendingCard(doc); if (!card || focusedCards.has(card)) return; focusedCards.add(card); if (!shouldAutoFocus(doc.activeElement, card)) return; const region = card.querySelector(SCROLL_SELECTOR); if (region && typeof region.focus === "function") region.focus(); }; const observer = new MutationObserver(tryAutoFocus); observer.observe(doc.documentElement, { childList: true, subtree: true }); tryAutoFocus(); const onKeyDown = (event) => { const card = findPendingCard(doc); if (!card) return; const buttons = actionButtons(card); const hasAlways = buttons.length >= 3 && !buttons[2].disabled; const action = decideKeyAction({ key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, repeat: event.repeat, isComposing: event.isComposing, keyCode: event.keyCode, defaultPrevented: event.defaultPrevented, target: event.target, activeElement: doc.activeElement, card, hasAlways, bindings: getBindings?.() ?? DEFAULT_BINDINGS }); if (!action) return; const button = action === "allow" ? buttons[1] : action === "always" ? buttons[2] : buttons[0]; if (!button || button.disabled) return; event.preventDefault(); event.stopPropagation(); button.click(); }; doc.addEventListener("keydown", onKeyDown, true); return () => { observer.disconnect(); doc.removeEventListener("keydown", onKeyDown, true); }; } // src/client/chat/bindings-store.ts /** * 聊天增强的持久化设置:审批卡快捷键。存储键 `dsh.better-chat.v1`,由宿主 * 客户端 store 的 persist 机制写入配置,重启后仍在。 */ const CHAT_PREFS_KEY = "dsh.better-chat.v1"; function createChatStore() { return (0, _deepseek_ai_dsh_client_store.defineStore)({ init: () => ({ bindings: normalizeBindings(void 0) }), persist: CHAT_PREFS_KEY, actions: { setApprovalBinding: (draft, action, binding) => { draft.bindings = normalizeBindings({ ...draft.bindings, [action]: binding }); }, resetApprovalBindings: (draft) => { draft.bindings = normalizeBindings(void 0); } } }); } /** 从设置实例读取当前绑定;旧快照/非法值自动回落默认。 */ function currentBindings(prefs) { try { return normalizeBindings(prefs?.getSnapshot()); } catch { return normalizeBindings(void 0); } } // src/client/chat/key-hint.ts /** * 审批卡键盘提示:在操作行左侧显示「Enter 允许(单次) · Ctrl+Enter * 始终允许 · Esc 拒绝」的键帽提示,文案直接取卡片按钮的实际文字。 * * 提示只是说明,不参与点击:pointer-events: none、aria-hidden,且只挂在 * 卡片操作行里(详情滚动区之外)。React 重渲染把提示冲掉时,MutationObserver * 会按按钮文案的签名重新挂回去;卡片作答后(aria-busy)立即移除。 */ const HINT_ATTR = "data-better-chat-keyhint"; const CARD_SELECTOR = "[data-approval-key]"; const SEPARATOR = "·"; /** 纯判定:当前平台是否用 Cmd 代替 Ctrl(只影响提示文案)。 */ function isMacPlatform(platform) { return typeof platform === "string" && /Mac|iPhone|iPad|iPod/.test(platform); } /** * 纯函数:根据卡片上实际存在的按钮文案与当前绑定,生成提示的分段。 * 「始终允许」被关掉(binding 为 null)时就不显示这一段。 */ function hintParts(labels, mac, bindings = DEFAULT_BINDINGS) { const parts = []; if (labels.allow) parts.push({ key: bindingKeycap(bindings.allow, mac), label: labels.allow }); if (labels.always && bindings.always) parts.push({ key: bindingKeycap(bindings.always, mac), label: labels.always }); if (labels.reject) parts.push({ key: bindingKeycap(bindings.reject, mac), label: labels.reject }); return parts; } /** 纯函数:提示内容的签名,用于判断是否需要重建。 */ function hintSignature(parts) { return parts.map((part) => `${part.key}=${part.label}`).join("|"); } const HINT_CSS = [ "margin-right:auto", "display:inline-flex", "flex-wrap:wrap", "align-items:center", "gap:6px", "font-size:12px", "line-height:18px", "color:var(--dsw-alias-label-tertiary,#8b919b)", "user-select:none", "pointer-events:none" ].join(";"); const KEYCAP_CSS = [ "display:inline-flex", "align-items:center", "justify-content:center", "height:18px", "padding:0 5px", "border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35))", "border-bottom-width:2px", "border-radius:5px", "background:var(--dsw-alias-bg-module-platform,rgba(127,127,127,.08))", "font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace)", "font-size:11px", "line-height:1", "letter-spacing:.2px" ].join(";"); const PAIR_CSS = "display:inline-flex;align-items:center;gap:5px"; const SEPARATOR_CSS = "opacity:.45;margin:0 2px"; function labelOf(button) { if (!button) return void 0; const text = button.textContent?.trim(); return text ? text : void 0; } function buildHint(doc, parts) { const hint = doc.createElement("div"); hint.setAttribute(HINT_ATTR, ""); hint.setAttribute("role", "note"); hint.setAttribute("aria-hidden", "true"); hint.style.cssText = HINT_CSS; parts.forEach((part, index) => { if (index > 0) { const separator = doc.createElement("span"); separator.textContent = SEPARATOR; separator.style.cssText = SEPARATOR_CSS; hint.append(separator); } const pair = doc.createElement("span"); pair.style.cssText = PAIR_CSS; const keycap = doc.createElement("span"); keycap.textContent = part.key; keycap.style.cssText = KEYCAP_CSS; const label = doc.createElement("span"); label.textContent = part.label; pair.append(keycap, label); hint.append(pair); }); return hint; } function removeHints(doc) { for (const hint of doc.querySelectorAll(`[${HINT_ATTR}]`)) hint.remove(); } /** 安装审批卡键盘提示,返回卸载函数。 */ function installKeyHints(doc, options = {}) { const mac = isMacPlatform(options.platform ?? doc.defaultView?.navigator?.platform); const getBindings = options.getBindings ?? (() => DEFAULT_BINDINGS); let disposed = false; const syncCard = (card) => { const buttons = actionButtons(card); const existing = card.querySelector(`[${HINT_ATTR}]`); if (card.getAttribute("aria-busy") === "true" || buttons.length < 2 || buttons[0].disabled || buttons[1].disabled) { existing?.remove(); return; } const always = buttons.length >= 3 && !buttons[2].disabled ? buttons[2] : void 0; const parts = hintParts({ allow: labelOf(buttons[1]), always: labelOf(always), reject: labelOf(buttons[0]) }, mac, getBindings()); if (parts.length === 0) { existing?.remove(); return; } const signature = hintSignature(parts); if (existing && existing.getAttribute("data-signature") === signature) return; existing?.remove(); const row = buttons[0].parentElement; if (!row) return; const hint = buildHint(doc, parts); hint.setAttribute("data-signature", signature); row.insertBefore(hint, row.firstChild); }; const sync = () => { if (disposed) return; const cards = doc.querySelectorAll(CARD_SELECTOR); if (cards.length === 0) { removeHints(doc); return; } for (const card of cards) syncCard(card); }; const observer = new MutationObserver(sync); observer.observe(doc.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ["aria-busy", "disabled"] }); const view = doc.defaultView; view?.addEventListener?.(BINDINGS_CHANGED_EVENT, sync); sync(); return () => { disposed = true; observer.disconnect(); view?.removeEventListener?.(BINDINGS_CHANGED_EVENT, sync); removeHints(doc); }; } // src/client/chat/permission-policy.ts /** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */ const FULL_ACCESS_LABELS = ["完全权限", "Full access"]; /** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */ function isFullAccessLabel(text) { if (typeof text !== "string") return false; const trimmed = text.trim(); return FULL_ACCESS_LABELS.some((label) => trimmed === label || trimmed.startsWith(label)); } /** * 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出 * 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。 * @returns 摘掉的个数 */ function pruneFullAccess(doc) { let removed = 0; for (const option of doc.querySelectorAll("option")) if (isFullAccessLabel(option.textContent)) { option.remove(); removed++; } for (const item of doc.querySelectorAll("[role=\"listbox\"] [role=\"option\"], [role=\"menu\"] [role=\"menuitem\"]")) if (isFullAccessLabel(item.textContent)) { item.remove(); removed++; } return removed; } /** * 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。 * 不接收 getSessions,也不启动任何会话轮询。 * @returns 卸载函数 */ function installPermissionPolicy(doc, _getSessions, timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }) { let disposed = false; let scanTimer = 0; const scheduleScan = () => { if (disposed || scanTimer) return; scanTimer = timers.setTimeout(() => { scanTimer = 0; if (!disposed) pruneFullAccess(doc); }, 120); }; const observer = new MutationObserver(scheduleScan); if (doc.body) observer.observe(doc.body, { childList: true, subtree: true }); pruneFullAccess(doc); return () => { disposed = true; observer.disconnect(); if (scanTimer) timers.clearTimeout(scanTimer); }; } // src/client/chat/store-update.ts /** * 功能三:插件商店「更新」按钮。 * * DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有「有新版本」 * 标签、没有按钮。这里补一个真按钮:数据与动作都走宿主自己的远程服务 * ——pluginMarket 查索引和安装状态,pluginManager.installBundle 按索引 * 给出的精确 spec 覆盖安装——与官方安装流程同一套接口,不模拟点击、 * 不动官方状态。 * * 服务经子插件声明 inject 取用:主插件保持自己的 inject,商店功能不 * 依赖这些服务;未启用实验性插件索引时子插件不生效,本功能静默关闭。 */ const UPDATE_LABELS = ["有新版本", "Update available"]; /** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */ function localizedTitle(title, lang) { if (typeof title === "string") return title; if (!title || typeof title !== "object") return ""; const record = title; const chain = [ lang, lang && lang.split("-")[0], "zh-CN", "en" ]; for (const key of chain) if (key && typeof record[key] === "string" && record[key]) return record[key]; const values = Object.values(record); return typeof values[0] === "string" ? values[0] : ""; } /** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */ function pickUpdates(searchResults, lang) { const updates = []; for (const result of searchResults ?? []) { const entries = result?.value?.entries ?? result?.entries ?? []; for (const entry of entries) { if (entry?.installation?.status !== "update-available") continue; const versions = entry.versions ?? []; const version = versions.find((candidate) => candidate.version === entry.defaultVersion) ?? versions[0]; const spec = version?.install?.spec; if (!entry.name || !version?.version || !spec) continue; updates.push({ name: entry.name, title: localizedTitle(entry.title, lang) || entry.name, installedVersion: entry.installation.installedVersion ?? "", version: version.version, spec, registry: version.install.registry }); } } return updates; } /** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */ async function runUpdate(remote, update, makeRequestId) { const requestId = makeRequestId ? makeRequestId() : "better-chat-update-" + Date.now(); return remote.pluginManager.installBundle(update.spec, { enabled: true, requestId, ...update.registry ? { registry: update.registry } : {} }); } /** * 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个 * 同时包含插件标题、且文本总量还像一行的祖先。 */ function findUpdateRow(doc, title) { for (const element of doc.querySelectorAll("button")) { if (!UPDATE_LABELS.includes(element.textContent?.trim() ?? "")) continue; let node = element; for (let depth = 0; depth < 6 && node; depth++) { node = node.parentElement; if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node; } } return null; } /** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */ function makeUpdateClickHandler(doc, getRemote, update, button) { return async (event) => { event?.preventDefault?.(); event?.stopPropagation?.(); const view = doc.defaultView; const ask = view?.confirm ?? globalThis.confirm; const message = "更新「" + update.title + "」" + (update.installedVersion ? " " + update.installedVersion : "") + " → " + update.version + "?\n会直接覆盖安装新版,插件数据保留。"; if (ask && !ask.call(view ?? globalThis, message)) return; button.disabled = true; button.textContent = "更新中…"; try { const result = await runUpdate(getRemote(), update, () => globalThis.crypto?.randomUUID?.() ?? void 0); if (result?.value?.application === "applied") button.textContent = "已更新,重启 DSH 后生效"; else { console.error("[dsh-better-chat] update failed for", update.name, result?.value?.error ?? result); button.disabled = false; button.textContent = "更新失败,点此重试"; } } catch (error) { console.error("[dsh-better-chat] update failed for", update.name, error); button.disabled = false; button.textContent = "更新失败,点此重试"; } }; } /** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */ function installStoreUpdateButtons(doc, getRemote, timers = { setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (id) => clearInterval(id) }) { let disposed = false; let updates = []; const decorate = () => { for (const update of updates) { const row = findUpdateRow(doc, update.title); if (!row || row.querySelector("[data-better-chat-update]")) continue; const button = doc.createElement("button"); button.type = "button"; button.setAttribute("data-better-chat-update", update.name); button.textContent = "更新到 " + update.version; button.style.cssText = "flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer"; button.addEventListener("click", makeUpdateClickHandler(doc, getRemote, update, button)); row.appendChild(button); } }; const refresh = async () => { try { const remote = getRemote(); if (!remote?.pluginMarket || !remote?.pluginManager) return; const indexes = await remote.pluginMarket.listIndexes(); const urls = (indexes?.value ?? indexes ?? []).map((entry) => entry?.url).filter(Boolean); const results = []; for (const url of urls) results.push(await remote.pluginMarket.search(url, { sort: { kind: "index" }, offset: 0, limit: 100 })); if (disposed) return; updates = pickUpdates(results, doc.documentElement?.lang || "zh-CN"); decorate(); } catch {} }; const observer = new MutationObserver(() => decorate()); observer.observe(doc.documentElement, { childList: true, subtree: true }); const timer = timers.setInterval(() => { refresh(); }, 3e4); refresh(); return () => { disposed = true; observer.disconnect(); timers.clearInterval(timer); }; } /** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */ const storeUpdatePlugin = { name: "dsh-better-chat-store-update", inject: [ "remote", "remote.pluginMarket", "remote.pluginManager" ], apply(childCtx) { childCtx.effect(() => installStoreUpdateButtons(document, () => childCtx.remote), "dsh-better-chat: store update buttons"); } }; // node_modules/@deepseek-ai/dsh-util-workspace-path/lib/index.js /** * The `dsh-resource://file/…` address grammar: how a file is named across the * Sidebar and the resource model, built and parsed without touching a * filesystem. * @module */ /** The scheme and type every file address opens with. */ const FILE_ADDRESS_PREFIX = "dsh-resource://file/"; /** Component-encode one id or path segment, keeping `:` literal for drive letters. */ function encodeSegment$1(segment) { return encodeURIComponent(segment).replace(/%3A/gi, ":"); } /** Encode a `/`-separated path segment by segment. */ function encodePath$1(path) { return path.split("/").map(encodeSegment$1).join("/"); } /** * Build the address of a file read through one Session. * @param sessionId - the Session whose Host workspace resolves the path. * @param path - absolute or workspace-relative path; backslashes are normalized to `/`, and leading `./` prefixes are dropped. * @returns the `dsh-resource://file/session//` address. */ function sessionFileAddress(sessionId, path) { const normalized = path.replace(/\\/g, "/").replace(/^(?:\.\/)+/, ""); return `${FILE_ADDRESS_PREFIX}session/${encodeSegment$1(sessionId)}/${encodePath$1(normalized)}`; } /** * Browser-safe Workspace path and display helpers. * @module @deepseek-ai/dsh-util-workspace-path */ /** Whether a path uses a Windows drive or UNC prefix. */ function isWindowsStylePath(value) { return /^[A-Za-z]:[/\\]/.test(value) || value.startsWith("\\\\"); } /** * Whether a path is absolute in either spelling the Host accepts: POSIX (`/a/b`) or Windows drive or UNC. * @param path - the path to classify. * @returns `true` for an absolute path; `false` for a Workspace-relative one. */ function isAbsoluteWorkspacePath$1(path) { return path.startsWith("/") || isWindowsStylePath(path); } /** * Resolve a Workspace-relative path into the Host-facing spelling used by path operations. * @param cwd - Session Workspace root, when known. * @param path - Absolute or Workspace-relative path. * @returns an absolute path when a Workspace root is available, otherwise the original path. */ function resolveWorkspacePath(cwd, path) { if (isAbsoluteWorkspacePath$1(path)) return path; if (cwd === void 0 || cwd === "") return path; const separator = isWindowsStylePath(cwd) && cwd.includes("\\") ? "\\" : "/"; return `${cwd.replace(/[/\\]+$/, "")}${separator}${path.replace(/^[/\\]+/, "")}`; } /** * Abbreviate a POSIX home directory for display. * @param path - Absolute or already-short display path. * @param home - Host account home; absent skips abbreviation. * @returns `~` or `~/…` for the POSIX home and its descendants, otherwise `path`. */ function abbreviateHomePath(path, home) { if (home === void 0 || home === "") return path; if (isWindowsStylePath(path) || isWindowsStylePath(home)) return path; const root = home.replace(/\/+$/, ""); if (root === "" || root === "/") return path; if (path.replace(/\/+$/, "") === root) return "~"; if (path.startsWith(`${root}/`)) return `~${path.slice(root.length)}`; return path; } /** * The address for a path as a caller holds it: a relative path, or an absolute * path inside the Session's workspace, becomes a `session`-scoped address; an * absolute path outside it, or one whose workspace root is unknown, keeps its * absolute path in that Session's address. * @param sessionId - the Session the path is read in. * @param cwd - that Session's workspace root, when known. * @param path - absolute or workspace-relative path, in either separator spelling. * @returns the `dsh-resource://file/…` address. */ function fileAddressFor$1(sessionId, cwd, path) { const normalized = path.replace(/\\/g, "/"); if (!isAbsoluteWorkspacePath$1(normalized)) return sessionFileAddress(sessionId, normalized); const root = cwd === void 0 ? "" : cwd.replace(/\\/g, "/").replace(/\/+$/, ""); if (root !== "" && normalized === root) return sessionFileAddress(sessionId, ""); if (root !== "" && normalized.startsWith(`${root}/`)) return sessionFileAddress(sessionId, normalized.slice(root.length + 1)); return sessionFileAddress(sessionId, normalized); } // src/client/rewind-cut.ts function asRecord$1(value) { return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0; } function safeSeq(value) { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0; } /** The command payload of a `command` chat node, when it is structurally readable. */ function commandOf(node) { if (node.kind !== "command") return void 0; return asRecord$1(node.data); } /** * The engine names an executed rewind command node can carry. The plugin * registers its command as `rewind-plugin` (`ENGINE_COMMANDS = new * Set(['rewind-plugin', 'rewind'])` in dsh-rewind-plugin's * `src/client/hidden.ts`), and that is the name the client projection actually * publishes — the session log's `command/run.name` is not what the Reader sees. * `rewind` stays accepted because older logs and the bili-side proxy record the * shorter spelling. */ const REWIND_COMMANDS = /* @__PURE__ */ new Set(["rewind-plugin", "rewind"]); /** True when a command payload is the rewind engine command, in either spelling. */ function isRewindCommand(command) { return typeof command.name === "string" && REWIND_COMMANDS.has(command.name); } /** * The render POSITION a row is anchored at: the view node's `anchorSeq`, else * its payload seq. * * This is deliberately NOT integer-only. The host anchors synthetic rows at * fractional offsets off a real seq (`CHAT_SYNTHETIC_SEQ_OFFSETS` in the * official ChatView: `turn-process` at `controlAnchorSeq - 0.1`, `turn-tail` at * `seq + 0.1`, an interrupted assistant step at `seq - 0.9`). An integer-only * read made those rows invisible to the cut, so the last `turn-process` of a * withdrawn turn survived on its own. Log seqs (marker, target) stay integer: * see `safeSeq`. */ function anchorSeqOf(node) { const raw = node.anchorSeq ?? asRecord$1(node.data)?.seq; return typeof raw === "number" && Number.isFinite(raw) && raw >= 0 ? raw : void 0; } /** * Extract the rewind target seq from a `/rewind` command's structured `args` * (e.g. `@5 chat`, `preview @5 both`). Locale-independent: it never parses the * host's human outcome copy. */ function rewindTargetOfArgs(args) { if (typeof args !== "string") return void 0; const match = args.match(/@(\d+)/); return match === null ? void 0 : Number(match[1]); } /** True for the internal candidate-list probe (`/rewind __candidates`). */ function isCandidateCommand(command) { return typeof command.args === "string" && command.args.includes("__candidates"); } /** True for an impact preview (`/rewind preview @5 both`). */ function isPreviewCommand(command) { return typeof command.args === "string" && command.args.includes("preview"); } /** * Merge overlapping or touching shadow ranges. * * Spans are kept SEPARATE unless they genuinely overlap: collapsing every cut * to `[min target, max marker]` would hide a still-on-surface gap of new traffic * between an earlier marker and a later target. */ function coalesceCutSpans(spans) { if (spans.length < 2) return [...spans]; const sorted = [...spans].sort((left, right) => left.start - right.start || left.end - right.end); const merged = []; for (const span of sorted) { const last = merged.at(-1); if (last !== void 0 && span.start <= last.end) { if (span.end > last.end) last.end = span.end; continue; } merged.push({ start: span.start, end: span.end }); } return merged; } /** * True when a row anchored at `seq` falls inside one of the cut spans. * * A cut runs from the target seq through the marker's own log seq, inclusive * (`target <= anchorSeq && anchorSeq <= marker`), the same comparison * `dsh-rewind-plugin`'s `RewindVisibilityBuilder` uses. The upper bound stops * at the marker. Extending it to the next integer hides the following turn's * process row, which the host anchors at `startSeq - 0.1` and therefore in * `[marker, marker + 1)`. Fractional anchors inside the closed range still * match: `anchorSeqOf` keeps them. A process or tail row parked outside the * range is handled by `summaryTurns`, not by widening the cut. Spans stay * disjoint, so new traffic between two rewinds survives. */ function cutContains(cuts, seq) { let low = 0; let high = cuts.length - 1; let found = -1; while (low <= high) { const middle = low + high >> 1; const cut = cuts[middle]; if (cut === void 0) return false; if (seq < cut.start) high = middle - 1; else { found = middle; low = middle + 1; } } const span = found < 0 ? void 0 : cuts[found]; return span !== void 0 && seq <= span.end; } /** The turn id a node belongs to (absent outside a turn). */ function turnIdOf(node) { const turn = asRecord$1(asRecord$1(node.location)?.turn); if (turn === void 0 || !Object.hasOwn(turn, "turn")) return void 0; return turn.turn; } /** * Node kinds that SUMMARIZE a turn instead of carrying its content, so the host * anchors them at the turn's edges rather than at an event inside it. */ const TURN_SUMMARY_KINDS = /* @__PURE__ */ new Set(["turn-process", "turn-tail"]); /** * True for a rewind command row the transcript should not keep. * * Probes (`preview`, `__candidates`) exist only to feed the popover. An * executed rewind — success plus a marker seq — is the command that performed * the cut, and the plugin hides that row even when its anchor sits outside * the numeric range. A failed or still-running command stays visible. */ function commandHidden(node) { const command = commandOf(node); if (command === void 0 || !isRewindCommand(command)) return false; if (isPreviewCommand(command) || isCandidateCommand(command)) return true; const outcome = asRecord$1(command.outcome); return outcome?.kind === "success" && safeSeq(outcome.sourceEventSeq) !== void 0; } /** True when the row's own anchor falls in a cut, or the row is a rewind command to hide. */ function anchorWithdrawn(node, cuts) { if (commandHidden(node)) return true; const seq = anchorSeqOf(node); return seq !== void 0 && cutContains(cuts, seq); } /** * Turns whose process and tail rows must leave. * * The host opens a turn before its user message is logged and anchors * `turn-process` at `controlAnchorSeq - 0.1`, below the first withdrawn * event, and `turn-tail` at `turn.end.seq + 0.1`, which can sit past the * marker. Containment therefore misses those two rows, and the transcript * kept announcing `执行过程 / 本轮已停止,已生成的内容仍保留。` * * A summary leaves only when every content row of its turn is already * withdrawn — the same rule as the plugin's `deriveTurnProcess`. One content * row before the target (a mid-turn steering rewind) keeps the summary and * that earlier message. A turn with no content rows is left alone. */ function summaryTurns(chat, cuts) { const stays = /* @__PURE__ */ new Map(); for (const key of chat.order) { const node = chat.nodes.get(key); if (node === void 0 || TURN_SUMMARY_KINDS.has(node.kind ?? "")) continue; const id = turnIdOf(node); if (id === void 0) continue; const visible = node.visibility !== "hidden" && !anchorWithdrawn(node, cuts); stays.set(id, (stays.get(id) ?? false) || visible); } const withdrawn = /* @__PURE__ */ new Set(); for (const [id, visible] of stays) if (!visible) withdrawn.add(id); return withdrawn; } /** True when this row is a summary of a turn whose content is fully withdrawn. */ function summaryWithdrawn(node, summaries) { if (!TURN_SUMMARY_KINDS.has(node.kind ?? "")) return false; const id = turnIdOf(node); return id !== void 0 && summaries.has(id); } /** * The shadow ranges a session's executed rewinds produced, newest state last. * An executed rewind cuts `[target, marker]` — the target itself is included, * because a rewind restores the state *before* that message was sent (its text * goes back to the composer). */ function rewindCutSpans(chat) { if (chat === void 0) return []; const spans = []; for (const key of chat.order) { const node = chat.nodes.get(key); if (node === void 0) continue; const command = commandOf(node); if (command === void 0 || !isRewindCommand(command)) continue; if (isPreviewCommand(command) || isCandidateCommand(command)) continue; const outcome = asRecord$1(command.outcome); if (outcome?.kind !== "success") continue; const marker = safeSeq(outcome.sourceEventSeq); if (marker === void 0) continue; const target = rewindTargetOfArgs(command.args); if (target === void 0 || target > marker) continue; spans.push({ start: target, end: marker }); } return coalesceCutSpans(spans); } /** * The chat keys the Reader should render, in snapshot order: withdrawn rows and * rows the host itself marked hidden are dropped, everything else keeps its * position. Returns the snapshot's own `order` array when nothing is filtered, * so React selectors see a stable reference. */ function visibleChatKeys(chat) { const cuts = rewindCutSpans(chat); const summaries = summaryTurns(chat, cuts); const visible = []; for (const key of chat.order) { const node = chat.nodes.get(key); if (node === void 0) continue; if (node.visibility === "hidden") continue; if (anchorWithdrawn(node, cuts) || summaryWithdrawn(node, summaries)) continue; visible.push(key); } return visible.length === chat.order.length ? chat.order : visible; } /** * A comparable signal for the visible row set, built for * `useSyncExternalStore`-style subscription: the host re-runs a chat selector * on every publish and compares the RESULT by `Object.is`, and a rewind * publishes an in-place upsert of an existing command row. The snapshot's * `order` array and node store are therefore both reference-stable across a * rewind, so a selector on them never re-renders; a string does change exactly * when the visible set does. Never return the array itself from a selector — * a fresh array fails the `Object.is` check on every publish. */ function visibleChatSignature(chat) { return visibleChatKeys(chat).join("\0"); } // src/client/tool-activity.ts /** * callId of a tool-call chat node. Drafts for a call whose node was cut must * not be reintroduced after `group.keys` has already dropped that node. */ function toolCallId(node) { const callId = node.data?.root?.callId; return typeof callId === "string" && callId.length > 0 ? callId : void 0; } /** callIds whose tool-call node sits inside a rewind cut. */ function cutToolCallIds(order, get, spans) { const ids = /* @__PURE__ */ new Set(); for (const key of order) { const node = get(key); if (node?.kind !== "tool-call") continue; const seq = anchorSeqOf(node); if (seq === void 0 || !cutContains(spans, seq)) continue; const callId = toolCallId(node); if (callId !== void 0) ids.add(callId); } return ids; } /** * Public Step data includes tool-only model output before a chat node exists. * * `sourceOrder` is the unfiltered chat order. Drafts that belong to a cut step, * or to a call whose tool-call node was cut, are not put back. A draft that * still has no tool-call node, on a step outside the cut, stays — that is the * in-flight call the host has not published a node for yet. */ function readerFlow(group, turn, get, sourceOrder) { const flow = []; const calls = /* @__PURE__ */ new Map(); const assistantOrder = /* @__PURE__ */ new Map(); const spans = sourceOrder === void 0 ? [] : rewindCutSpans({ order: sourceOrder, nodes: { get } }); const cutCalls = spans.length === 0 || sourceOrder === void 0 ? void 0 : cutToolCallIds(sourceOrder, get, spans); for (const key of group.keys) { const node = get(key); if (!node || node.visibility === "hidden") continue; const step = node.location.kind === "step" ? node.location.step.step : 0; if (node.kind === "tool-call") { const block = node.data.root; calls.set(block.callId, { kind: "tool", key: `reader-tool:${block.callId}`, callId: block.callId, step, block, order: node.anchorSeq }); } else { flow.push({ kind: "node", key, nodeKey: key, order: node.anchorSeq }); if (node.kind === "assistant-step") assistantOrder.set(step, node.anchorSeq); } } for (const step of turn?.steps ?? []) { const data = step.data.get("assistant-step"); const stepSeq = step.start?.seq; const stepCut = typeof stepSeq === "number" && spans.length > 0 && cutContains(spans, stepSeq); let index = 0; for (const draft of data?.blocks ?? []) { if (draft.kind !== "tool-call" || !draft.callId) continue; const previous = calls.get(draft.callId); if (!previous && (stepCut || cutCalls?.has(draft.callId) === true)) continue; calls.set(draft.callId, previous ? { ...previous, draft } : { kind: "tool", key: `reader-tool:${draft.callId}`, callId: draft.callId, step: step.step, draft, order: (assistantOrder.get(step.step) ?? step.start?.seq ?? 0) + .01 + index++ / 1e4 }); } } flow.push(...calls.values()); return flow.sort((left, right) => left.order - right.order); } function objectValue(value) { return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null; } function stringValue(record, ...keys) { for (const key of keys) if (typeof record?.[key] === "string" && record[key]) return record[key]; } /** Read only top-level JSON string values, including an unfinished final string. * This never executes input or mistakes escaped/nested content for a path field. */ function parseInputFields(raw) { try { return { kind: "complete", fields: objectValue(JSON.parse(raw)) ?? {} }; } catch {} const fields = Object.create(null); const prefix = raw.slice(0, 262144); let depth = 0; let key; for (let index = 0; index < prefix.length; index++) { const char = prefix[index]; if (char === "{" || char === "[") { depth++; continue; } if (char === "}" || char === "]") { depth--; continue; } if (char !== "\"") continue; const start = index; let closed = false; for (index++; index < prefix.length; index++) { if (prefix[index] === "\\") { index++; continue; } if (prefix[index] === "\"") { closed = true; break; } } if (depth !== 1) continue; const token = prefix.slice(start, closed ? index + 1 : prefix.length); let value; try { value = JSON.parse(token); } catch { if (closed) continue; let body = token.slice(1); const unicode = /(?= 0 && body[end] === "\\"; end--) slashes++; if (slashes % 2) body = body.slice(0, -1); try { value = JSON.parse(`"${body}"`); } catch { continue; } } if (closed && /^\s*:/.test(prefix.slice(index + 1))) key = value; else if (key !== void 0) { fields[key] = value; key = void 0; } } return { kind: "partial", fields }; } function inputFields(raw) { return parseInputFields(raw).fields; } /** Name and raw arguments of any call block, whether it has landed or is pending. */ function toolIdentity(entry) { const block = entry.block; return { name: block ? "kind" in block ? block.call?.name ?? entry.draft?.name ?? "工具调用" : block.name : entry.draft?.name ?? "工具调用", raw: block ? "kind" in block ? block.call?.argsRaw ?? entry.draft?.argsRaw ?? "" : "argsRaw" in block ? block.argsRaw : entry.draft?.argsRaw ?? "" : entry.draft?.argsRaw ?? "" }; } /** Name and raw arguments of any call block, whether it has landed or is pending. */ function childIdentity(block) { if (!block || !("kind" in block)) return { name: block?.name, raw: block && "argsRaw" in block ? block.argsRaw : "" }; return { name: block.call?.name, raw: block.call?.argsRaw ?? "" }; } function executionFacts(block) { if (!block || !("kind" in block)) return {}; const meta = objectValue(block.meta); const code = meta?.exitCode ?? meta?.exit_code; const text = block.content.length === 1 && block.content[0]?.type === "text" ? block.content[0].text : ""; const exit = /\n\[exit code: (\d+)\]$/.exec(text); const signal = /\n\[killed by signal: ([^\]\n]+)\]$/.exec(text); const parsedCode = exit?.[1] === void 0 ? void 0 : Number(exit[1]); return { exitCode: typeof code === "number" && Number.isFinite(code) ? code : parsedCode, signal: stringValue(meta, "signal") ?? signal?.[1] }; } /** Line counts of one text side; a trailing newline does not start a line. */ function lineCount(text) { if (text === null) return 0; const body = text.endsWith("\n") ? text.slice(0, -1) : text; return body === "" ? 0 : body.split("\n").length; } /** Argument fields that carry the text a call is about to write. */ const NEW_TEXT_FIELDS = [ "content", "new_string", "new_str", "newText", "file_text" ]; /** Argument fields that carry the text a call is about to replace. */ const OLD_TEXT_FIELDS = [ "old_string", "old_str", "oldText" ]; /** Argument fields that name the file a mutation call targets. */ const PATH_FIELDS = [ "file_path", "path", "filePath" ]; function firstString(source, fields) { if (!source) return null; for (const field of fields) { const value = source[field]; if (typeof value === "string" && value !== "") return value; } return null; } const MUTATION_TOOLS = /* @__PURE__ */ new Set([ "write", "edit", "str_replace_editor" ]); function callDiffHunks(block, args, name) { const nested = block && "kind" in block && Array.isArray(block.subCalls) ? block.subCalls.flatMap((child) => { try { return callDiffHunks(child, inputFields(childIdentity(child).raw), childIdentity(child).name); } catch { return []; } }) : []; if (block && "kind" in block) { const diffs = objectValue(block.meta)?.diffs; if (Array.isArray(diffs) && diffs.length > 0) { const hunks = []; for (const raw of diffs) { const entry = objectValue(raw); if (!entry) continue; const oldText = typeof entry.oldText === "string" ? entry.oldText : null; const newText = typeof entry.newText === "string" ? entry.newText : ""; if (!lineCount(newText) && !lineCount(oldText)) continue; hunks.push({ path: firstString(entry, PATH_FIELDS) ?? "", oldText, newText }); } if (hunks.length) return [...hunks, ...nested]; } } if (!name || !MUTATION_TOOLS.has(name)) return nested; const path = firstString(args, PATH_FIELDS); if (!path) return nested; const oldText = firstString(args, OLD_TEXT_FIELDS); const newText = firstString(args, NEW_TEXT_FIELDS) ?? ""; if (!lineCount(newText) && !lineCount(oldText)) return nested; return [{ path, oldText, newText }, ...nested]; } /** Added/removed line counts for one call, or null when there is nothing to show. */ function diffTotals$1(block, args, name) { const hunks = callDiffHunks(block, args, name); if (!hunks.length) return null; return diffLineTotals(hunks); } /** Counts the lines on each side, under the same rule the official block uses. */ function diffLineTotals(hunks) { return hunks.reduce((total, hunk) => ({ added: total.added + lineCount(hunk.newText), removed: total.removed + lineCount(hunk.oldText) }), { added: 0, removed: 0 }); } /** Every changed file across a folded run of steps, in the order they ran. */ function foldDiffHunks(steps) { const hunks = []; for (const step of steps) { if (step.kind !== "tool" || !step.entry) continue; const model = activitySummary(step.entry); hunks.push(...callDiffHunks(step.entry.block, model.args, model.name)); } return hunks; } function activityPhase(entry, turnClosed = false) { if (!entry.block) return turnClosed ? "interrupted" : "preparing"; if (!("kind" in entry.block)) return turnClosed ? "interrupted" : entry.block.phase === "preparing" ? "preparing" : "running"; if (entry.block.error?.code === "ABORTED" || entry.block.error?.code === "interrupted") return "interrupted"; const facts = executionFacts(entry.block); if (entry.block.isError || facts.signal || facts.exitCode !== void 0 && facts.exitCode !== 0 || entry.block.subCalls.some((block) => activityPhase({ block }, turnClosed) === "failed")) return "failed"; if (facts.exitCode === 0) return "succeeded"; return "returned"; } /** * First-seen time for calls the host has not stamped yet. A draft that * precedes a landed call carries no timestamp, so without this memory the * running clock would restart at zero on every remount — e.g. switching to * another conversation and back while the call is still preparing. Keyed by * call id, dropped when the call leaves the running phases. */ const clockFirstSeen = /* @__PURE__ */ new Map(); const CLOCK_FIRST_SEEN_LIMIT = 512; /** * Session-stamped start of a call, or null while only a draft exists. * A settled result carries `callTime`, the paired tool/call event's time; a * still-running call head stamps the same instant in its own `time` field. */ function callStartTime(entry) { const block = entry.block; if (!block) return null; return "kind" in block ? block.callTime : block.time; } /** * The instant a still-running call's elapsed clock counts from. The stamped * time wins so a remounted view keeps counting from the real start; an * un-stamped draft falls back to when this view first saw that call id, which * survives remounts for the same reason. */ function runningClockBase(callId, block, now = Date.now()) { const stamped = callStartTime({ block }); if (stamped != null) return stamped; const seen = clockFirstSeen.get(callId); if (seen !== void 0) return seen; if (clockFirstSeen.size >= CLOCK_FIRST_SEEN_LIMIT) clockFirstSeen.delete(clockFirstSeen.keys().next().value); clockFirstSeen.set(callId, now); return now; } /** Forget a call's first-seen time once its clock is no longer live. */ function forgetCallClock(callId) { clockFirstSeen.delete(callId); } function activitySummary(entry) { const { name, raw } = toolIdentity(entry); const parsed = parseInputFields(raw); const args = parsed.fields; const target = stringValue(args, "file_path", "path", "filename", "filePath"); const command = stringValue(args, "command", "cmd", "script"); const description = stringValue(args, "description"); const file = target?.split(/[/\\]/).at(-1); const category = /^(write|edit|apply_patch|patch|str_replace_editor)$/.test(name) ? "write" : /^(read|read_file)$/.test(name) ? "read" : /^(bash|shell|terminal|terminal_send|exec_command|pwsh)$/.test(name) ? "terminal" : /^(grep|glob|find|search)$/.test(name) ? "search" : /^(web_search|web_fetch|web_open)$/.test(name) ? "web" : /^(run_code|execute_code|code_interpreter|python|node|eval|repl)$/.test(name) ? "code" : "other"; const title = category === "write" ? `${name === "write" ? "写入" : "修改"}${file ? ` ${file}` : name === "apply_patch" ? "代码补丁" : "文件"}` : category === "read" ? `读取${file ? ` ${file}` : "文件"}` : category === "terminal" ? description || "运行命令" : category === "search" ? name === "glob" ? "查找文件" : "搜索内容" : category === "web" ? name === "web_search" ? "搜索网页" : "读取网页" : category === "code" ? description || "运行代码" : name; return { name, raw, args, argsState: parsed.kind, category, title, target: target ?? command ?? stringValue(args, "query", "pattern", "url"), command, cwd: stringValue(args, "workdir", "cwd"), content: stringValue(args, "content", "new_string", "newText", "file_text") }; } function preparingLabel(name) { return /^(write|edit|apply_patch)$/.test(name) ? "正在生成文件内容" : /^(bash|shell|exec_command|pwsh)$/.test(name) ? "正在准备命令" : "正在准备工具输入"; } // src/client/deliverables.ts /** Extract standard filename without directory components. */ function basename(path) { const normalized = path.replace(/[/\\]+$/, ""); const at = Math.max(normalized.lastIndexOf("/"), normalized.lastIndexOf("\\")); return at === -1 ? normalized : normalized.slice(at + 1); } /** Extract parent directory of a path (or '.' if top-level). */ function dirname(path) { const normalized = path.replace(/[/\\]+$/, ""); const at = Math.max(normalized.lastIndexOf("/"), normalized.lastIndexOf("\\")); if (at === 0 || at === 2 && /^[A-Za-z]:/.test(normalized)) return normalized.slice(0, at + 1); return at === -1 ? "." : normalized.slice(0, at) || "."; } /** * The produced-files chip row waits for turn close. Live writes still * accumulate, but the row must not interrupt an in-progress process. */ function showDeliverablesRow(status, paths) { return status === "closed" && paths.length > 0; } /** * Extract all unique file paths produced/modified in one turn. * Respects official deliverables data when available, and falls back to * inspecting successful write/edit tool invocations in the turn flow. */ function getTurnDeliverables(turn, flow) { const paths = []; const seen = /* @__PURE__ */ new Set(); const deliverables = (turn?.data)?.get("deliverables"); if (deliverables?.produced && Array.isArray(deliverables.produced)) { for (const item of deliverables.produced) if (typeof item?.path === "string" && item.path.trim().length > 0) { const clean = item.path.trim(); if (!seen.has(clean)) { seen.add(clean); paths.push(clean); } } } if (paths.length > 0) return paths; if (flow) for (const item of flow) { if (item.kind !== "tool" || !item.block) continue; if ("isError" in item.block && item.block.isError) continue; const { name, raw } = toolIdentity(item); const toolName = name !== "工具调用" ? name : item.block.name || item.block.call?.name; const toolRaw = raw || item.block.argsRaw || item.block.call?.argsRaw || ""; if (toolName === "write" || toolName === "edit" || toolName === "apply_patch") { const target = stringValue(inputFields(toolRaw), "file_path", "path", "filename", "filePath"); if (target && !seen.has(target)) { seen.add(target); paths.push(target); } } else if (toolName === "str_replace_editor") { const args = inputFields(toolRaw); const cmd = stringValue(args, "command"); if (cmd === "create" || cmd === "str_replace" || cmd === "insert") { const target = stringValue(args, "path"); if (target && !seen.has(target)) { seen.add(target); paths.push(target); } } } } return paths; } /** The single produced path whose basename is exactly value, or undefined. */ function onlyPathWithBasename(paths, value) { const matches = paths.filter((path) => basename(path) === value); return matches.length === 1 ? matches[0] : void 0; } /** * File-mention resolver: converts inline-code tokens matching produced paths * into clickable file references that open the corresponding file on the host. */ function createProducedFileMentions(paths, openFile) { return { resolve(value) { if (!value || value.includes("\n")) return void 0; const clean = value.trim(); const path = paths.includes(clean) ? clean : onlyPathWithBasename(paths, clean); if (path === void 0) return void 0; return { open: () => { openFile(path); }, label: `打开 ${path}`, title: path }; } }; } // src/workspace-path.ts /** Absolute paths accepted by both POSIX and Windows hosts. */ function isAbsoluteWorkspacePath(path) { return /^(?:\/|[A-Za-z]:[/\\]|\\\\)/.test(path); } // src/client/styles.ts const plugin = "dsh-better-display"; const styles$1 = /* @__PURE__ */ new Map(); /** Retain injected CSS across host cleanup and restore it before Reader paints. */ function ensureStyles() { if (typeof document === "undefined") return; const live = /* @__PURE__ */ new Set(); for (const tag of document.querySelectorAll(`style[data-plugin="${plugin}"][data-plugin-css]`)) { const id = tag.dataset.pluginCss; if (id === void 0) continue; styles$1.set(id, tag.textContent ?? ""); live.add(id); } for (const [id, text] of styles$1) { if (live.has(id)) continue; const tag = document.createElement("style"); tag.dataset.plugin = plugin; tag.dataset.pluginCss = id; tag.textContent = text; document.head.appendChild(tag); } } // src/client/mcp-app.ts /** * Core pure functions for SEP-1865 / MCP Apps integration. * Free of CSS module imports so it can be cleanly tested in Node test environments. */ function getHostTheme() { if (typeof document === "undefined") return "light"; if (document.body?.hasAttribute("data-ds-dark-theme")) return "dark"; const colorScheme = document.documentElement?.style.colorScheme; if (colorScheme === "dark" || colorScheme === "light") return colorScheme; const dataTheme = document.documentElement?.getAttribute("data-theme") || document.body?.getAttribute("data-theme"); if (dataTheme === "dark" || dataTheme === "light") return dataTheme; if (document.body?.classList.contains("dark") || document.documentElement?.classList.contains("dark")) return "dark"; return typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light"; } function getCssTokens(theme) { const isDark = theme === "dark"; return { "--background": isDark ? "#0f172a" : "#ffffff", "--card": isDark ? "#1e293b" : "#f8fafc", "--foreground": isDark ? "#f8fafc" : "#0f172a", "--muted-foreground": isDark ? "#94a3b8" : "#64748b", "--primary": "#2563eb", "--primary-foreground": "#ffffff", "--border": isDark ? "#334155" : "#e2e8f0", "--hover": isDark ? "rgba(148, 163, 184, 0.15)" : "rgba(148, 163, 184, 0.12)" }; } /** * Extracts a title from the HTML document's tag. */ function extractHtmlTitle(html) { return /<title[^>]*>([^<]+)<\/title>/i.exec(html)?.[1]?.trim(); } /** * Normalizes user/model generated HTML to ensure a valid HTML5 structure * and embeds a dynamic theme listener so dark/light mode switches take effect immediately. */ function ensureHtmlDocument(rawHtml, initialTheme = "light") { const isDark = initialTheme === "dark"; const trimmed = rawHtml.trim(); const themeScript = `<script> (function() { function applyTheme(theme) { if (!theme) return; document.documentElement.setAttribute('data-theme', theme); document.documentElement.style.colorScheme = theme; if (theme === 'dark') { document.documentElement.classList.add('dark'); if (document.body) document.body.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); if (document.body) document.body.classList.remove('dark'); } } applyTheme(${JSON.stringify(initialTheme)}); // Precise content-bottom measurement to avoid scrollHeight latching to iframe outer height function reportHeight() { var body = document.body; if (!body) return; var children = body.children; var maxBottom = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || el.tagName === 'LINK') continue; var style = window.getComputedStyle(el); if (style.display === 'none' || style.position === 'fixed') continue; var marginBottom = parseFloat(style.marginBottom) || 0; var bottom = el.offsetTop + el.offsetHeight + marginBottom; if (bottom > maxBottom) maxBottom = bottom; } var bodyStyle = window.getComputedStyle(body); var bodyPaddingBottom = parseFloat(bodyStyle.paddingBottom) || 0; var h = maxBottom > 0 ? Math.ceil(maxBottom + bodyPaddingBottom) : body.scrollHeight; if (h > 40) { window.parent.postMessage({ jsonrpc: '2.0', method: 'ui/resize', params: { height: h } }, '*'); } } if (typeof ResizeObserver !== 'undefined') { var ro = new ResizeObserver(function() { reportHeight(); }); if (document.body) { ro.observe(document.body); } else { document.addEventListener('DOMContentLoaded', function() { if (document.body) ro.observe(document.body); }); } } window.addEventListener('load', reportHeight); setTimeout(reportHeight, 50); setTimeout(reportHeight, 250); setTimeout(reportHeight, 600); window.addEventListener('message', function(e) { var msg = e.data; if (!msg || typeof msg !== 'object') return; var theme = (msg.params && msg.params.theme) || (msg.result && msg.result.hostContext && msg.result.hostContext.theme); if (theme) applyTheme(theme); }); })(); <\/script>`; if (/^<!DOCTYPE/i.test(trimmed) || /<html[\s>]/i.test(trimmed)) { if (/<head[\s>]/i.test(trimmed)) return trimmed.replace(/<head([^>]*)>/i, `<head$1>\n ${themeScript}`); return trimmed; } return `<!DOCTYPE html> <html lang="zh-CN" data-theme="${initialTheme}" class="${isDark ? "dark" : ""}"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> ${themeScript} <style> :root { --background: #ffffff; --card: #f8fafc; --border: #e2e8f0; --foreground: #0f172a; --muted-foreground: #64748b; --primary: #2563eb; --primary-foreground: #ffffff; } :root[data-theme='dark'], html.dark { --background: #0f172a; --card: #1e293b; --border: #334155; --foreground: #f8fafc; --muted-foreground: #94a3b8; } @media (prefers-color-scheme: dark) { :root:not([data-theme='light']) { --background: #0f172a; --card: #1e293b; --border: #334155; --foreground: #f8fafc; --muted-foreground: #94a3b8; } } * { box-sizing: border-box; margin: 0; padding: 0; } body { background: transparent; color: var(--foreground); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 12px; } </style> </head> <body class="${isDark ? "dark" : ""}"> ${trimmed} </body> </html>`; } /** * Determines whether a markdown code block represents an MCP App. */ function isMcpAppCodeBlock(lang, meta, value) { const l = (lang ?? "").toLowerCase().trim(); const m = (meta ?? "").toLowerCase().trim(); if (l === "mcp-app" || l === "mcpapp" || l === "mcp-ui" || l === "mcp" || l.startsWith("mcp-app:") || l === "html:mcp-app" || l === "html:mcp") return true; if (m.includes("mcp-app") || m.includes("mcpapp") || m.includes("sep-1865") || m.includes("mcp-ui")) return true; if (l === "html" && (value.includes("ui/submit") || value.includes("ui/initialize") || value.includes("SEP-1865") || value.includes("mcp-app"))) return true; return false; } /** * Extracts a title from code block meta or HTML content. */ function extractMcpAppTitle(meta, value) { if (meta) { const titleMatch = /title=["']([^"']+)["']/i.exec(meta) || /title=([^\s]+)/i.exec(meta); if (titleMatch?.[1]) return titleMatch[1]; } const htmlTitle = extractHtmlTitle(value); if (htmlTitle) return htmlTitle; } /** * Extracts an explicit height budget from code block meta (e.g. height=600 or height="500px"). */ function extractMcpAppHeight(meta) { if (!meta) return void 0; const match = /height=["']?(\d+)(?:px)?["']?/i.exec(meta); if (match?.[1]) { const n = parseInt(match[1], 10); if (Number.isFinite(n) && n >= 100 && n <= 3e3) return n; } } /** * Formats a user-submitted MCP App event into a concise, natural language conversational prompt. * Avoids raw multiline JSON and excessive whitespace. */ function formatReceiptPrompt(params, title) { if (typeof params.choice === "string") { const desc = typeof params.desc === "string" ? `(${params.desc})` : ""; return `我在${title ? `「${title}」` : "组件"}中选择了:${params.choice}${desc}。请根据我的选择继续。`; } if (typeof params.selectedVariant === "string") { const score = typeof params.score === "number" ? `,得分:${params.score}` : ""; return `我在方案评测中选择了:${params.selectedVariant}${score}。请根据该方案继续分析。`; } if (typeof params.action === "string") { const payloadStr = params.payload ? typeof params.payload === "string" ? params.payload : JSON.stringify(params.payload) : ""; return `[${title ?? "组件操作"}] 已完成 ${params.action}${payloadStr ? `: ${payloadStr}` : ""}`; } const keys = Object.keys(params); if (keys.length === 1 && typeof params[keys[0]] === "string") return `[${title ?? "组件回执"}] ${keys[0]}: ${params[keys[0]]}`; return `[${title ?? "组件回执"}] ${JSON.stringify(params)}`; } /** * DOM fallback for composer fill: types into the Lexical contenteditable * surface (`[data-composer-input]`) via execCommand insertText so the editor * adopts the change as a genuine user edit. Returns true when accepted. */ function fillComposerDom(text, doc) { const d = doc ?? (typeof document !== "undefined" ? document : void 0); if (!d) return false; try { const surfaces = Array.from(d.querySelectorAll("[data-composer-input]")); const target = surfaces.find((el) => el.getAttribute("contenteditable") === "true") ?? surfaces[0]; if (!target) return false; target.focus(); if (typeof d.execCommand === "function") try { if (d.execCommand("insertText", false, text)) return true; } catch {} const selection = d.getSelection?.(); if (selection) { selection.selectAllChildren(target); if (typeof d.execCommand === "function") try { if (d.execCommand("insertText", false, text)) return true; } catch {} } } catch {} return false; } // \0dshx-css-module:src/client/McpAppFrame.module.css.mjs const css$7 = ".YE487q_card{border:1px solid var(--dsw-alias-border-l2,#00000014);background:var(--dsw-alias-bg-module-platform,transparent);border-radius:14px;margin:16px 0;transition:border-color .2s cubic-bezier(.22,1,.36,1),box-shadow .2s cubic-bezier(.22,1,.36,1);position:relative;overflow:hidden}.YE487q_card:hover{border-color:var(--dsw-alias-border-l1,#00000029);box-shadow:0 2px 10px -2px #0000000a}.YE487q_header{border-bottom:1px solid var(--dsw-alias-border-l2,#0000000f);background:var(--dsw-alias-interactive-bg-hover,#00000004);-webkit-user-select:none;user-select:none;justify-content:space-between;align-items:center;height:36px;padding:0 14px;display:flex}.YE487q_titleArea{align-items:center;gap:7px;min-width:0;display:flex}.YE487q_icon{color:var(--dsw-alias-label-tertiary,#94a3b8);flex-shrink:0;justify-content:center;align-items:center;display:flex}.YE487q_title{color:var(--dsw-alias-label-secondary,#64748b);letter-spacing:-.01em;text-overflow:ellipsis;white-space:nowrap;font-size:12px;font-weight:500;overflow:hidden}.YE487q_actions{align-items:center;gap:4px;display:flex}.YE487q_iconBtn{width:24px;height:24px;color:var(--dsw-alias-label-tertiary,#94a3b8);cursor:pointer;background:0 0;border:none;border-radius:6px;justify-content:center;align-items:center;padding:0;transition:all .15s;display:inline-flex}.YE487q_iconBtn:hover{background:var(--dsw-alias-interactive-bg-hover,#0000000f);color:var(--dsw-alias-label-primary,#0f172a)}.YE487q_iconBtn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#2563eb);outline-offset:1px}.YE487q_iframeWrapper{background:0 0;width:100%;transition:height .25s cubic-bezier(.22,1,.36,1);position:relative}.YE487q_iframe{background:0 0;border:none;width:100%;height:100%;display:block}.YE487q_receipt{background:var(--dsw-alias-interactive-bg-hover,#22c55e0d);border-top:1px solid var(--dsw-alias-border-l2,#0000000f);color:var(--dsw-alias-label-primary,#0f172a);flex-wrap:wrap;justify-content:space-between;align-items:center;gap:6px 12px;padding:8px 14px;font-size:12px;line-height:18px;animation:.2s cubic-bezier(.22,1,.36,1) YE487q_slideUp;display:flex}.YE487q_receiptPrompt{color:var(--dsw-alias-label-secondary,#64748b);background:var(--dsw-alias-bg-base,#00000008);border:1px solid var(--dsw-alias-border-l2,#0000000f);-webkit-user-select:text;user-select:text;cursor:text;overflow-wrap:anywhere;border-radius:6px;flex:100%;padding:6px 10px;font-size:12px;line-height:18px}@keyframes YE487q_slideUp{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.YE487q_receiptSummary{color:var(--dsw-alias-state-business-primary,#16a34a);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;font-weight:500;display:flex;overflow:hidden}.YE487q_receiptHint{align-items:center;gap:6px;display:flex}.YE487q_sendKbd{color:var(--dsw-alias-label-tertiary,#94a3b8);background:var(--dsw-alias-bg-base,#0000000a);border:1px solid var(--dsw-alias-border-l2,#00000014);cursor:pointer;border-radius:5px;align-items:center;gap:4px;padding:2px 8px;font-family:inherit;font-size:11px;transition:all .15s;display:inline-flex}.YE487q_sendKbd:hover{background:var(--dsw-alias-interactive-bg-hover,#00000014);color:var(--dsw-alias-label-primary,#0f172a)}.YE487q_sendKbd:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#2563eb);outline-offset:1px}.YE487q_streamingPlaceholder{border:1px dashed var(--dsw-alias-border-l2,#0000001f);background:var(--dsw-alias-interactive-bg-hover,#00000004);color:var(--dsw-alias-label-secondary,#64748b);border-radius:14px;align-items:center;gap:10px;margin:16px 0;padding:16px 18px;font-size:13px;display:flex}.YE487q_pulseDot{background:var(--dsw-alias-state-business-primary,#2563eb);border-radius:50%;width:7px;height:7px;animation:1.5s ease-in-out infinite YE487q_pulse}@keyframes YE487q_pulse{0%,to{opacity:.35;transform:scale(.9)}50%{opacity:1;transform:scale(1.15)}}"; const tagId$7 = "dsh-better-chat/McpAppFrame.module.css"; if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$7) + "]") === null) { const tag = document.createElement("style"); tag.dataset.plugin = "dsh-better-chat"; tag.dataset.pluginCss = tagId$7; tag.textContent = css$7; document.head.appendChild(tag); } var McpAppFrame_module_css_default = { "actions": "YE487q_actions", "card": "YE487q_card", "header": "YE487q_header", "icon": "YE487q_icon", "iconBtn": "YE487q_iconBtn", "iframe": "YE487q_iframe", "iframeWrapper": "YE487q_iframeWrapper", "pulse": "YE487q_pulse", "pulseDot": "YE487q_pulseDot", "receipt": "YE487q_receipt", "receiptHint": "YE487q_receiptHint", "receiptPrompt": "YE487q_receiptPrompt", "receiptSummary": "YE487q_receiptSummary", "sendKbd": "YE487q_sendKbd", "slideUp": "YE487q_slideUp", "streamingPlaceholder": "YE487q_streamingPlaceholder", "title": "YE487q_title", "titleArea": "YE487q_titleArea" }; // src/client/McpAppFrame.tsx const ComposerFillContext = (0, react.createContext)(void 0); function useComposerFill() { return (0, react.useContext)(ComposerFillContext); } const McpAppFrame = (0, react.memo)(function McpAppFrame({ html, title: initialTitle, initialHeight = 240, fillComposer: fillComposerProp }) { const fillComposerFromContext = useComposerFill(); const writeComposer = (0, react.useMemo)(() => fillComposerProp ?? fillComposerFromContext ?? fillComposerDom, [fillComposerProp, fillComposerFromContext]); const iframeRef = (0, react.useRef)(null); const lastParamsRef = (0, react.useRef)({}); const [height, setHeight] = (0, react.useState)(() => Math.max(60, Math.min(2400, initialHeight))); const [receipt, setReceipt] = (0, react.useState)(null); const [lastPrompt, setLastPrompt] = (0, react.useState)(null); const [reloadNonce, setReloadNonce] = (0, react.useState)(0); const frameId = (0, react.useId)(); const title = (0, react.useMemo)(() => { return initialTitle || extractHtmlTitle(html) || "交互式 MCP App"; }, [initialTitle, html]); const [initialTheme] = (0, react.useState)(getHostTheme); const preparedHtml = (0, react.useMemo)(() => ensureHtmlDocument(html, initialTheme), [html, initialTheme]); const fillComposer = (0, react.useCallback)((params) => { const prompt = formatReceiptPrompt(params, title); setLastPrompt(prompt); try { if (writeComposer(prompt)) return true; try { navigator.clipboard?.writeText(prompt); } catch {} } catch {} return false; }, [title, writeComposer]); const handleUserSubmit = (0, react.useCallback)((params) => { lastParamsRef.current = params; let summary; if (typeof params.choice === "string") { const desc = typeof params.desc === "string" ? ` (${params.desc})` : ""; summary = `选择: ${params.choice}${desc}`; } else if (typeof params.action === "string") summary = `操作: ${params.action}${params.payload ? ` (${JSON.stringify(params.payload)})` : ""}`; else if (typeof params.selectedVariant === "string") summary = `方案: ${params.selectedVariant}`; else summary = JSON.stringify(params); setReceipt(summary); fillComposer(params); }, [fillComposer]); (0, react.useEffect)(() => { const handleMessage = (event) => { const iframe = iframeRef.current; if (!iframe || event.source !== iframe.contentWindow) return; const data = event.data; if (!data || typeof data !== "object") return; const currentTheme = getHostTheme(); const cssTokens = getCssTokens(currentTheme); if (data.method === "ui/initialize") { const response = { jsonrpc: "2.0", id: data.id, result: { protocolVersion: "2026-01-26", hostContext: { theme: currentTheme, locale: "zh-CN", styles: { variables: cssTokens } } } }; iframe.contentWindow?.postMessage(response, "*"); return; } if (data.method === "ui/ready" || data.method === "ui/notifications/initialized") return; if (data.method === "ui/resize" && data.params?.height) { const h = Number(data.params.height); if (Number.isFinite(h) && h > 0) setHeight(Math.max(60, Math.min(2400, Math.round(h)))); return; } if (data.method === "ui/submit" || data.method === "ui/update-model-context") { const params = data.params || {}; handleUserSubmit(params); return; } }; window.addEventListener("message", handleMessage); const broadcastTheme = () => { const newTheme = getHostTheme(); const tokens = getCssTokens(newTheme); iframeRef.current?.contentWindow?.postMessage({ jsonrpc: "2.0", method: "ui/notifications/host-context-changed", params: { theme: newTheme, styles: { variables: tokens } } }, "*"); }; let observer = null; if (typeof MutationObserver !== "undefined" && typeof document !== "undefined") { observer = new MutationObserver(broadcastTheme); if (document.body) observer.observe(document.body, { attributes: true, attributeFilter: [ "data-ds-dark-theme", "class", "style", "data-theme" ] }); if (document.documentElement) observer.observe(document.documentElement, { attributes: true, attributeFilter: [ "data-theme", "class", "style" ] }); } const media = typeof window !== "undefined" && window.matchMedia ? window.matchMedia("(prefers-color-scheme: dark)") : null; media?.addEventListener?.("change", broadcastTheme); return () => { window.removeEventListener("message", handleMessage); observer?.disconnect(); media?.removeEventListener?.("change", broadcastTheme); }; }, [handleUserSubmit]); const handleFrameLoad = (0, react.useCallback)(() => { const iframe = iframeRef.current; if (!iframe) return; const currentTheme = getHostTheme(); const cssTokens = getCssTokens(currentTheme); iframe.contentWindow?.postMessage({ jsonrpc: "2.0", method: "ui/initialize", params: { theme: currentTheme, locale: "zh-CN", styles: { variables: cssTokens } } }, "*"); }, []); const handleReload = (0, react.useCallback)(() => { setReloadNonce((n) => n + 1); setReceipt(null); }, []); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: McpAppFrame_module_css_default.card, "data-mcp-app-card": true, "data-testid": "mcp-app-card", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: McpAppFrame_module_css_default.header, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: McpAppFrame_module_css_default.titleArea, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: McpAppFrame_module_css_default.icon, "aria-hidden": "true", children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { width: "13", height: "13", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", { width: "18", height: "18", x: "3", y: "3", rx: "2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 9h18" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M9 21V9" }) ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: McpAppFrame_module_css_default.title, title, children: title })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: McpAppFrame_module_css_default.actions, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: McpAppFrame_module_css_default.iconBtn, onClick: handleReload, title: "重置组件状态", "aria-label": "重置组件状态", children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { width: "13", height: "13", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 3v5h5" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M16 16h5v5" }) ] }) }) })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: McpAppFrame_module_css_default.iframeWrapper, style: { height: `${height}px` }, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("iframe", { ref: iframeRef, className: McpAppFrame_module_css_default.iframe, title, srcDoc: preparedHtml, sandbox: "allow-scripts allow-forms", referrerPolicy: "no-referrer", onLoad: handleFrameLoad }, `${frameId}-${reloadNonce}`) }), receipt && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: McpAppFrame_module_css_default.receipt, "data-testid": "mcp-app-receipt", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: McpAppFrame_module_css_default.receiptSummary, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { width: "13", height: "13", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("polyline", { points: "20 6 9 17 4 12" }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: ["已就绪:", receipt] })] }), lastPrompt && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: McpAppFrame_module_css_default.receiptPrompt, title: lastPrompt, children: lastPrompt }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: McpAppFrame_module_css_default.receiptHint, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { type: "button", className: McpAppFrame_module_css_default.sendKbd, title: "把这条结果重新填入输入框,然后回车发送", onClick: () => { fillComposer(lastParamsRef.current); }, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "填入输入框" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("kbd", { children: "↵" })] }) }) ] }) ] }); }); /** * Markdown code-fence mount point: picks the session composer writer from * React context (provided by Blocks) without changing the markdown * pipeline's signatures. */ function McpAppCodeBlock({ html, title, initialHeight }) { const fillComposer = useComposerFill(); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(McpAppFrame, { html, title, initialHeight, fillComposer }); } function StreamingMcpAppPlaceholder({ title }) { return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: McpAppFrame_module_css_default.streamingPlaceholder, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: McpAppFrame_module_css_default.pulseDot, "aria-hidden": "true" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [ "正在生成交互组件", title ? `(${title})` : "", "..." ] })] }); } // src/client/message-chrome.ts /** Local clock and run-duration labels for reader message chrome. */ function pad2(n) { return String(n).padStart(2, "0"); } /** * Elapsed wall time, matching official Chat `duration.minutes` / `duration.seconds`. * @param ms - Elapsed milliseconds (negatives clamp to zero). */ function formatRunDuration(ms) { const total = Math.max(0, Math.floor(ms / 1e3)); const minutes = Math.floor(total / 60); const seconds = total % 60; return minutes > 0 ? `${minutes}分${pad2(seconds)}秒` : `${seconds}秒`; } /** * Settled-turn duration pill, matching official `message.ranFor`. * @param ms - Elapsed milliseconds. */ function formatRanFor(ms) { return `用时 ${formatRunDuration(ms)}`; } /** * Compact local timestamp. Same calendar day → `HH:mm`; earlier this year → * `M月D日 HH:mm`; other years → `YYYY年M月D日 HH:mm`. * @param time - Unix epoch ms from the source session event. * @param now - Reference instant for the day/year cut. */ function formatMessageClock(time, now = Date.now()) { const d = new Date(time); const n = new Date(now); const clock = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`; if (d.getFullYear() === n.getFullYear() && d.getMonth() === n.getMonth() && d.getDate() === n.getDate()) return clock; if (d.getFullYear() === n.getFullYear()) return `${d.getMonth() + 1}月${d.getDate()}日 ${clock}`; return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 ${clock}`; } // src/client/primitive-labels.ts const markdownLabels = { code: { copyLabel: "复制", copiedLabel: "已复制" }, footnotes: "脚注" }; const readBlockLabels = { codeLabel: "代码", wrapLabel: "自动换行", unwrapLabel: "不换行", window: (shown, total) => `显示 ${shown} / ${total} 行`, copy: "复制", copied: "已复制", collapseAria: "收起文件内容", expandAria: (hidden) => `展开其余 ${hidden} 行`, collapse: "收起", expand: (hidden) => `展开其余 ${hidden} 行` }; const terminalBlockLabels = { commandLine: (line) => `命令第 ${line} 行`, signal: (signal) => `信号 ${signal}`, exitCode: (code) => `退出码 ${code}`, noExitCode: "无退出码", running: "执行中", failed: "失败", done: "已完成", copy: "复制", copied: "已复制", noOutput: "没有输出", collapseAria: "收起命令输出", collapse: "收起", expandAria: (hidden) => `展开其余 ${hidden} 行`, expand: (hidden) => `展开其余 ${hidden} 行` }; const diffBlockLabels = { codeLabel: "代码", wrapLabel: "自动换行", unwrapLabel: "不换行", copy: "复制", copied: "已复制", collapseAria: "收起差异", collapse: "收起", expandAria: (hidden) => `展开其余 ${hidden} 行`, expand: (hidden) => `展开其余 ${hidden} 行` }; const searchBlockLabels = { pathsSummary: (shown, total, truncated) => `${shown} / ${total} 个路径${truncated ? "(结果已截断)" : ""}`, matchesSummary: (shown, total, files, truncated) => `${shown} / ${total} 处匹配 · ${files} 个文件${truncated ? "(结果已截断)" : ""}`, copy: "复制", copied: "已复制", noResults: "没有结果", collapseAria: "收起搜索结果", collapse: "收起", expandAria: (hidden) => `展开其余 ${hidden} 行`, expand: (hidden) => `展开其余 ${hidden} 行` }; const webBlockLabels = { noResults: "没有结果", sourcesTruncated: "来源已截断", http: "HTTP", contentTruncated: "内容已截断", markdown: markdownLabels }; const jsonTreeLabels = { copyValue: "复制值", copyJson: "复制 JSON", copyPath: "复制路径", copyPrettyJson: "复制格式化 JSON", copyCompactJson: "复制紧凑 JSON", copied: "已复制", copyFailed: "复制失败", collapseNode: "收起节点", expandNode: "展开节点", copyButtonTitle: (action) => action }; const truncatedJsonLabel = (total) => `内容过长,已截断(共 ${total} 个字符)`; // src/client/stream-buffer.ts /** Presentation only. The original session string remains the source of truth. */ const STREAM_TIMING = { catchUpMs: 520, maxQueuedMs: 600, finishMs: 96, revealMs: 350, minimumRate: 260, /** Weight of the newest arrival sample in the smoothed source rate. */ rateWeight: .35, /** A longer gap is a pause between runs, not a slow model: keep the estimate. */ rateGapMs: 250 }; const graphemes = new Intl.Segmenter(void 0, { granularity: "grapheme" }); function atOrAfter(values, target) { let low = 0; let high = values.length - 1; while (low < high) { const middle = low + high >>> 1; if (values[middle] < target) low = middle + 1; else high = middle; } return low; } var StreamBuffer = class { target; visible; revision = 0; boundaries = [0]; arrivals = []; lastAt = null; credit = 0; finishAt = null; rateEwma = 0; lastArrival = null; constructor(initial = "") { this.target = initial; this.visible = initial; this.segment(0); } get pending() { return this.visible.length < this.target.length; } segment(from) { const index = atOrAfter(this.boundaries, from); this.boundaries.length = index; for (const part of graphemes.segment(this.target.slice(from))) this.boundaries.push(from + part.index); if (this.boundaries.at(-1) !== this.target.length) this.boundaries.push(this.target.length); } /** Non-append updates, cancellations and hidden/reduced views never replay. */ update(text, now, options = {}) { if (options.immediate || !text.startsWith(this.target)) { if (text !== this.target) this.revision++; this.target = text; this.flush(); this.boundaries = [0]; this.segment(0); return; } if (text !== this.target) { const wasPending = this.pending; const grew = text.length - this.target.length; const from = this.boundaries.at(-2) ?? 0; this.observe(grew, now); this.target = text; this.segment(from); this.arrivals.push({ end: text.length, at: now }); if (!wasPending) { this.lastAt = now; this.credit = 0; } } if (options.finished && this.finishAt === null) this.finishAt = now + STREAM_TIMING.finishMs; if (!options.finished) this.finishAt = null; if (this.target.length - this.visible.length > 8192) { this.revision++; this.flush(); } } /** Smoothed source rate, so one jittery transport chunk cannot set the pace. */ observe(grew, now) { const previous = this.lastArrival; this.lastArrival = now; if (previous === null || grew <= 0) return; const elapsed = now - previous; if (elapsed <= 0 || elapsed > STREAM_TIMING.rateGapMs) return; const sample = grew * 1e3 / elapsed; this.rateEwma = this.rateEwma === 0 ? sample : this.rateEwma * (1 - STREAM_TIMING.rateWeight) + sample * STREAM_TIMING.rateWeight; } flush() { this.visible = this.target; this.arrivals = []; this.credit = 0; this.lastAt = null; this.lastArrival = null; this.finishAt = null; } advance(now) { if (!this.pending) return false; const before = this.visible.length; const index = atOrAfter(this.boundaries, before); const remaining = this.boundaries.length - index - 1; const delta = Math.max(0, now - (this.lastAt ?? now)); this.lastAt = now; const windowMs = this.finishAt === null ? STREAM_TIMING.catchUpMs : Math.max(16, Math.min(STREAM_TIMING.catchUpMs, this.finishAt - now)); const rate = Math.max(STREAM_TIMING.minimumRate, this.rateEwma + remaining * 1e3 / windowMs); this.credit += rate * delta / 1e3; const count = Math.floor(this.credit); this.credit -= count; let end = this.boundaries[Math.min(this.boundaries.length - 1, index + count)]; for (const item of this.arrivals) { if (now - item.at < STREAM_TIMING.maxQueuedMs) break; end = Math.max(end, this.boundaries[atOrAfter(this.boundaries, item.end)]); } if (this.finishAt !== null && now >= this.finishAt) end = this.target.length; if (end && /[\uD800-\uDBFF]/.test(this.target[end - 1]) && this.finishAt === null) end--; end = Math.max(before, end); this.visible = this.target.slice(0, end); this.arrivals = this.arrivals.filter((item) => item.end > end); if (!this.pending) { this.credit = 0; this.lastAt = null; } return end !== before; } }; // src/client/word-timeline.ts /** Motion parameters from the public transitions.dev streaming-text recipe. */ const WORD_MOTION = { duration: 350, gap: 60, blur: 1, easing: "cubic-bezier(0.22, 1, 0.36, 1)", maxDelay: 240, /** Floor for the per-word cadence once a batch is compressed. */ minGap: 3, /** One paint's words should land inside this window, however many arrive. */ batchMs: 90 }; const segmenter = new Intl.Segmenter(void 0, { granularity: "word" }); const closingPunctuation = /^[\p{Pe}\p{Pf},.!?:;,。!?、;:%‰…·]+$/u; const openingPunctuation = /^[\p{Ps}\p{Pi}]+$/u; /** Source-offset identity survives reparsing, frozen blocks, and final formatting. */ var WordTimeline = class { generation = 0; hasLiveText = false; source = null; enabled = false; revision = 0; floor = 0; lastBirth = -1e400; births = []; begin(source, enabled, revision, now) { if (this.source === source && this.enabled === enabled && this.revision === revision) return; if (revision !== this.revision || this.source !== null && !source.startsWith(this.source) || !enabled) { this.births.length = 0; this.lastBirth = -1e400; this.generation++; this.floor = source.length; } else if (this.source === null) this.floor = source.length; else { const from = this.source.length; const added = source.slice(from); let arriving = 0; for (const part of segmenter.segment(added)) if (part.segment.trim()) arriving++; const gap = arriving > 1 ? Math.max(WORD_MOTION.minGap, Math.min(WORD_MOTION.gap, WORD_MOTION.batchMs / arriving)) : WORD_MOTION.gap; for (const part of segmenter.segment(added)) { let born = Number.isFinite(this.lastBirth) ? this.lastBirth : null; if (part.segment.trim()) { born = Math.min(now + WORD_MOTION.batchMs, Math.max(now, this.lastBirth + gap)); this.lastBirth = born; } const end = from + part.index + part.segment.length; const previous = this.births.at(-1); if (previous && previous.born === born) previous.end = end; else this.births.push({ end, born }); } } this.source = source; this.enabled = enabled; this.revision = revision; this.hasLiveText = enabled && this.births.length > 0; } bornAt(offset) { if (!this.enabled || offset < this.floor || this.births.length === 0) return null; let low = 0; let high = this.births.length - 1; while (low < high) { const middle = low + high >>> 1; if (this.births[middle].end <= offset) low = middle + 1; else high = middle; } return this.births[low].born; } words(value, offset) { const prefixLength = Math.min(value.length, Math.max(0, this.floor - offset)); const prefix = prefixLength > 0 ? [{ key: offset, text: value.slice(0, prefixLength), born: null }] : []; const parts = []; for (const segment of segmenter.segment(value.slice(prefixLength))) { const part = { index: prefixLength + segment.index, segment: segment.segment }; const previous = parts.at(-1); if (previous?.segment.trim() && (closingPunctuation.test(part.segment) || openingPunctuation.test(previous.segment))) previous.segment += part.segment; else parts.push({ index: part.index, segment: part.segment }); } return prefix.concat(parts.map((part) => { const key = offset + part.index; return { key, text: part.segment, born: this.bornAt(key) }; })); } }; // src/client/streaming.tsx const StreamMotionContext = (0, react.createContext)({ enabled: false, activatedAt: 0 }); function useStreamingText(source, streaming, options) { const { enabled, activatedAt, paused = false, resumed = false } = (0, react.useContext)(StreamMotionContext); const fresh = resumed || (options.startedAt ?? 0) >= activatedAt; const buffer = (0, react.useRef)(); if (!buffer.current) buffer.current = new StreamBuffer(enabled && (streaming || resumed) && fresh ? "" : source); const [display, setDisplay] = (0, react.useState)(() => ({ text: buffer.current.visible, revision: 0 })); const [finalizing, setFinalizing] = (0, react.useState)(streaming); const frame = (0, react.useRef)(0); const immediate = !enabled || options.interrupted || options.selected; const publish = () => { const current = buffer.current; setDisplay((previous) => previous.text === current.visible && previous.revision === current.revision ? previous : { text: current.visible, revision: current.revision }); }; const handoff = (0, react.useRef)(resumed); const presentationClock = (0, react.useRef)(performance.now()); (0, react.useLayoutEffect)(() => { cancelAnimationFrame(frame.current); const current = buffer.current; if (paused && !immediate && !document.hidden) { current.update(source, performance.now(), { immediate: false, finished: !streaming }); publish(); return; } let previous = performance.now(); current.update(source, handoff.current ? presentationClock.current : previous, { immediate: immediate || document.hidden, finished: !streaming && !resumed }); publish(); const tick = (now) => { presentationClock.current += Math.min(32, Math.max(0, now - previous)); previous = now; if (document.hidden) current.flush(); else current.advance(handoff.current ? presentationClock.current : now); publish(); if (current.pending) frame.current = requestAnimationFrame(tick); else handoff.current = false; }; if (current.pending) frame.current = requestAnimationFrame(tick); return () => cancelAnimationFrame(frame.current); }, [ source, streaming, immediate, paused, resumed ]); (0, react.useEffect)(() => { const hidden = () => { if (!document.hidden) return; cancelAnimationFrame(frame.current); buffer.current.flush(); publish(); setFinalizing(false); }; document.addEventListener("visibilitychange", hidden); return () => document.removeEventListener("visibilitychange", hidden); }, []); const pending = display.text !== source; (0, react.useEffect)(() => { if (streaming || pending) { setFinalizing(true); return; } if (immediate || document.hidden) { setFinalizing(false); return; } const timer = setTimeout(() => setFinalizing(false), WORD_MOTION.duration + WORD_MOTION.maxDelay); return () => clearTimeout(timer); }, [ streaming, pending, immediate ]); return { text: immediate ? source : display.text, pending: !immediate && pending, revision: display.revision, formatStreaming: streaming || !immediate && (pending || finalizing), reveal: enabled && !options.interrupted && !options.selected }; } // src/client/markdown/incremental.ts /** * Trailing blocks kept unstable. Appended text reshapes at most the last * block; the second-to-last is retained as safety margin so a freeze decision * never has to reason about the parse frontier. */ const UNSTABLE_TAIL_BLOCKS = 2; /** * A block's render key: its absolute source start offset. A position-less * node (a grammar is free to omit positions) falls back to a negative * list-index key — unique within one update's tail, which is the only place * the fallback can occur: freezing requires the cut block's position, so a * position-less parse keeps every block in the tail (real grammars always * stamp positions and never take this path). */ function blockKey(node, base, index) { const offset = node.position?.start.offset; return offset === void 0 ? -(index + 1) : base + offset; } /** * Append-only incremental parser over a caller-supplied grammar. One instance * accumulates one streaming document; non-append input resets it. */ var IncrementalMarkdownParser = class { parse; prevText = ""; tailStart = 0; frozen = []; generation = 0; cached = null; /** @param parse - Grammar shared with whatever renders the blocks, so boundaries agree. */ constructor(parse) { this.parse = parse; } /** * Fold the current accumulated text and return the frozen/tail split. * Idempotent for identical input (the previous result is returned as-is), * so callers may invoke it from render paths that re-execute. * @param text - The full accumulated markdown source. * @returns Frozen and tail blocks with stream-stable render keys. */ update(text) { if (this.cached !== null && text === this.prevText) return this.cached; if (!text.startsWith(this.prevText)) { this.prevText = ""; this.tailStart = 0; this.frozen = []; this.generation += 1; } this.prevText = text; const base = this.tailStart; const blocks = this.parse(text.slice(base)).children; let firstUnstable = Math.max(0, blocks.length - UNSTABLE_TAIL_BLOCKS); if (firstUnstable > 0) { const cutEnd = blocks[firstUnstable - 1]?.position?.end.offset; if (cutEnd === void 0) firstUnstable = 0; else { for (const node of blocks.slice(0, firstUnstable)) this.frozen.push({ node, key: blockKey(node, base, this.frozen.length) }); this.tailStart = base + cutEnd; } } const tail = blocks.slice(firstUnstable).map((node, index) => ({ node, key: blockKey(node, base, index) })); this.cached = { frozen: [...this.frozen], tail, generation: this.generation }; return this.cached; } }; // node_modules/mdast-util-to-string/lib/index.js /** * @typedef {import('mdast').Nodes} Nodes * * @typedef Options * Configuration (optional). * @property {boolean | null | undefined} [includeImageAlt=true] * Whether to use `alt` for `image`s (default: `true`). * @property {boolean | null | undefined} [includeHtml=true] * Whether to use `value` of HTML (default: `true`). */ /** @type {Options} */ const emptyOptions = {}; /** * Get the text content of a node or list of nodes. * * Prefers the node’s plain-text fields, otherwise serializes its children, * and if the given value is an array, serialize the nodes in it. * * @param {unknown} [value] * Thing to serialize, typically `Node`. * @param {Options | null | undefined} [options] * Configuration (optional). * @returns {string} * Serialized `value`. */ function toString(value, options) { const settings = options || emptyOptions; return one(value, typeof settings.includeImageAlt === "boolean" ? settings.includeImageAlt : true, typeof settings.includeHtml === "boolean" ? settings.includeHtml : true); } /** * One node or several nodes. * * @param {unknown} value * Thing to serialize. * @param {boolean} includeImageAlt * Include image `alt`s. * @param {boolean} includeHtml * Include HTML. * @returns {string} * Serialized node. */ function one(value, includeImageAlt, includeHtml) { if (node(value)) { if ("value" in value) return value.type === "html" && !includeHtml ? "" : value.value; if (includeImageAlt && "alt" in value && value.alt) return value.alt; if ("children" in value) return all(value.children, includeImageAlt, includeHtml); } if (Array.isArray(value)) return all(value, includeImageAlt, includeHtml); return ""; } /** * Serialize a list of nodes. * * @param {Array<unknown>} values * Thing to serialize. * @param {boolean} includeImageAlt * Include image `alt`s. * @param {boolean} includeHtml * Include HTML. * @returns {string} * Serialized nodes. */ function all(values, includeImageAlt, includeHtml) { /** @type {Array<string>} */ const result = []; let index = -1; while (++index < values.length) result[index] = one(values[index], includeImageAlt, includeHtml); return result.join(""); } /** * Check if `value` looks like a node. * * @param {unknown} value * Thing. * @returns {value is Nodes} * Whether `value` is a node. */ function node(value) { return Boolean(value && typeof value === "object"); } // node_modules/character-entities/index.js /** * Map of named character references. * * @type {Record<string, string>} */ const characterEntities = { AElig: "Æ", AMP: "&", Aacute: "Á", Abreve: "Ă", Acirc: "Â", Acy: "А", Afr: "𝔄", Agrave: "À", Alpha: "Α", Amacr: "Ā", And: "⩓", Aogon: "Ą", Aopf: "𝔸", ApplyFunction: "⁡", Aring: "Å", Ascr: "𝒜", Assign: "≔", Atilde: "Ã", Auml: "Ä", Backslash: "∖", Barv: "⫧", Barwed: "⌆", Bcy: "Б", Because: "∵", Bernoullis: "ℬ", Beta: "Β", Bfr: "𝔅", Bopf: "𝔹", Breve: "˘", Bscr: "ℬ", Bumpeq: "≎", CHcy: "Ч", COPY: "©", Cacute: "Ć", Cap: "⋒", CapitalDifferentialD: "ⅅ", Cayleys: "ℭ", Ccaron: "Č", Ccedil: "Ç", Ccirc: "Ĉ", Cconint: "∰", Cdot: "Ċ", Cedilla: "¸", CenterDot: "·", Cfr: "ℭ", Chi: "Χ", CircleDot: "⊙", CircleMinus: "⊖", CirclePlus: "⊕", CircleTimes: "⊗", ClockwiseContourIntegral: "∲", CloseCurlyDoubleQuote: "”", CloseCurlyQuote: "’", Colon: "∷", Colone: "⩴", Congruent: "≡", Conint: "∯", ContourIntegral: "∮", Copf: "ℂ", Coproduct: "∐", CounterClockwiseContourIntegral: "∳", Cross: "⨯", Cscr: "𝒞", Cup: "⋓", CupCap: "≍", DD: "ⅅ", DDotrahd: "⤑", DJcy: "Ђ", DScy: "Ѕ", DZcy: "Џ", Dagger: "‡", Darr: "↡", Dashv: "⫤", Dcaron: "Ď", Dcy: "Д", Del: "∇", Delta: "Δ", Dfr: "𝔇", DiacriticalAcute: "´", DiacriticalDot: "˙", DiacriticalDoubleAcute: "˝", DiacriticalGrave: "`", DiacriticalTilde: "˜", Diamond: "⋄", DifferentialD: "ⅆ", Dopf: "𝔻", Dot: "¨", DotDot: "⃜", DotEqual: "≐", DoubleContourIntegral: "∯", DoubleDot: "¨", DoubleDownArrow: "⇓", DoubleLeftArrow: "⇐", DoubleLeftRightArrow: "⇔", DoubleLeftTee: "⫤", DoubleLongLeftArrow: "⟸", DoubleLongLeftRightArrow: "⟺", DoubleLongRightArrow: "⟹", DoubleRightArrow: "⇒", DoubleRightTee: "⊨", DoubleUpArrow: "⇑", DoubleUpDownArrow: "⇕", DoubleVerticalBar: "∥", DownArrow: "↓", DownArrowBar: "⤓", DownArrowUpArrow: "⇵", DownBreve: "̑", DownLeftRightVector: "⥐", DownLeftTeeVector: "⥞", DownLeftVector: "↽", DownLeftVectorBar: "⥖", DownRightTeeVector: "⥟", DownRightVector: "⇁", DownRightVectorBar: "⥗", DownTee: "⊤", DownTeeArrow: "↧", Downarrow: "⇓", Dscr: "𝒟", Dstrok: "Đ", ENG: "Ŋ", ETH: "Ð", Eacute: "É", Ecaron: "Ě", Ecirc: "Ê", Ecy: "Э", Edot: "Ė", Efr: "𝔈", Egrave: "È", Element: "∈", Emacr: "Ē", EmptySmallSquare: "◻", EmptyVerySmallSquare: "▫", Eogon: "Ę", Eopf: "𝔼", Epsilon: "Ε", Equal: "⩵", EqualTilde: "≂", Equilibrium: "⇌", Escr: "ℰ", Esim: "⩳", Eta: "Η", Euml: "Ë", Exists: "∃", ExponentialE: "ⅇ", Fcy: "Ф", Ffr: "𝔉", FilledSmallSquare: "◼", FilledVerySmallSquare: "▪", Fopf: "𝔽", ForAll: "∀", Fouriertrf: "ℱ", Fscr: "ℱ", GJcy: "Ѓ", GT: ">", Gamma: "Γ", Gammad: "Ϝ", Gbreve: "Ğ", Gcedil: "Ģ", Gcirc: "Ĝ", Gcy: "Г", Gdot: "Ġ", Gfr: "𝔊", Gg: "⋙", Gopf: "𝔾", GreaterEqual: "≥", GreaterEqualLess: "⋛", GreaterFullEqual: "≧", GreaterGreater: "⪢", GreaterLess: "≷", GreaterSlantEqual: "⩾", GreaterTilde: "≳", Gscr: "𝒢", Gt: "≫", HARDcy: "Ъ", Hacek: "ˇ", Hat: "^", Hcirc: "Ĥ", Hfr: "ℌ", HilbertSpace: "ℋ", Hopf: "ℍ", HorizontalLine: "─", Hscr: "ℋ", Hstrok: "Ħ", HumpDownHump: "≎", HumpEqual: "≏", IEcy: "Е", IJlig: "IJ", IOcy: "Ё", Iacute: "Í", Icirc: "Î", Icy: "И", Idot: "İ", Ifr: "ℑ", Igrave: "Ì", Im: "ℑ", Imacr: "Ī", ImaginaryI: "ⅈ", Implies: "⇒", Int: "∬", Integral: "∫", Intersection: "⋂", InvisibleComma: "⁣", InvisibleTimes: "⁢", Iogon: "Į", Iopf: "𝕀", Iota: "Ι", Iscr: "ℐ", Itilde: "Ĩ", Iukcy: "І", Iuml: "Ï", Jcirc: "Ĵ", Jcy: "Й", Jfr: "𝔍", Jopf: "𝕁", Jscr: "𝒥", Jsercy: "Ј", Jukcy: "Є", KHcy: "Х", KJcy: "Ќ", Kappa: "Κ", Kcedil: "Ķ", Kcy: "К", Kfr: "𝔎", Kopf: "𝕂", Kscr: "𝒦", LJcy: "Љ", LT: "<", Lacute: "Ĺ", Lambda: "Λ", Lang: "⟪", Laplacetrf: "ℒ", Larr: "↞", Lcaron: "Ľ", Lcedil: "Ļ", Lcy: "Л", LeftAngleBracket: "⟨", LeftArrow: "←", LeftArrowBar: "⇤", LeftArrowRightArrow: "⇆", LeftCeiling: "⌈", LeftDoubleBracket: "⟦", LeftDownTeeVector: "⥡", LeftDownVector: "⇃", LeftDownVectorBar: "⥙", LeftFloor: "⌊", LeftRightArrow: "↔", LeftRightVector: "⥎", LeftTee: "⊣", LeftTeeArrow: "↤", LeftTeeVector: "⥚", LeftTriangle: "⊲", LeftTriangleBar: "⧏", LeftTriangleEqual: "⊴", LeftUpDownVector: "⥑", LeftUpTeeVector: "⥠", LeftUpVector: "↿", LeftUpVectorBar: "⥘", LeftVector: "↼", LeftVectorBar: "⥒", Leftarrow: "⇐", Leftrightarrow: "⇔", LessEqualGreater: "⋚", LessFullEqual: "≦", LessGreater: "≶", LessLess: "⪡", LessSlantEqual: "⩽", LessTilde: "≲", Lfr: "𝔏", Ll: "⋘", Lleftarrow: "⇚", Lmidot: "Ŀ", LongLeftArrow: "⟵", LongLeftRightArrow: "⟷", LongRightArrow: "⟶", Longleftarrow: "⟸", Longleftrightarrow: "⟺", Longrightarrow: "⟹", Lopf: "𝕃", LowerLeftArrow: "↙", LowerRightArrow: "↘", Lscr: "ℒ", Lsh: "↰", Lstrok: "Ł", Lt: "≪", Map: "⤅", Mcy: "М", MediumSpace: " ", Mellintrf: "ℳ", Mfr: "𝔐", MinusPlus: "∓", Mopf: "𝕄", Mscr: "ℳ", Mu: "Μ", NJcy: "Њ", Nacute: "Ń", Ncaron: "Ň", Ncedil: "Ņ", Ncy: "Н", NegativeMediumSpace: "​", NegativeThickSpace: "​", NegativeThinSpace: "​", NegativeVeryThinSpace: "​", NestedGreaterGreater: "≫", NestedLessLess: "≪", NewLine: "\n", Nfr: "𝔑", NoBreak: "⁠", NonBreakingSpace: "\xA0", Nopf: "ℕ", Not: "⫬", NotCongruent: "≢", NotCupCap: "≭", NotDoubleVerticalBar: "∦", NotElement: "∉", NotEqual: "≠", NotEqualTilde: "≂̸", NotExists: "∄", NotGreater: "≯", NotGreaterEqual: "≱", NotGreaterFullEqual: "≧̸", NotGreaterGreater: "≫̸", NotGreaterLess: "≹", NotGreaterSlantEqual: "⩾̸", NotGreaterTilde: "≵", NotHumpDownHump: "≎̸", NotHumpEqual: "≏̸", NotLeftTriangle: "⋪", NotLeftTriangleBar: "⧏̸", NotLeftTriangleEqual: "⋬", NotLess: "≮", NotLessEqual: "≰", NotLessGreater: "≸", NotLessLess: "≪̸", NotLessSlantEqual: "⩽̸", NotLessTilde: "≴", NotNestedGreaterGreater: "⪢̸", NotNestedLessLess: "⪡̸", NotPrecedes: "⊀", NotPrecedesEqual: "⪯̸", NotPrecedesSlantEqual: "⋠", NotReverseElement: "∌", NotRightTriangle: "⋫", NotRightTriangleBar: "⧐̸", NotRightTriangleEqual: "⋭", NotSquareSubset: "⊏̸", NotSquareSubsetEqual: "⋢", NotSquareSuperset: "⊐̸", NotSquareSupersetEqual: "⋣", NotSubset: "⊂⃒", NotSubsetEqual: "⊈", NotSucceeds: "⊁", NotSucceedsEqual: "⪰̸", NotSucceedsSlantEqual: "⋡", NotSucceedsTilde: "≿̸", NotSuperset: "⊃⃒", NotSupersetEqual: "⊉", NotTilde: "≁", NotTildeEqual: "≄", NotTildeFullEqual: "≇", NotTildeTilde: "≉", NotVerticalBar: "∤", Nscr: "𝒩", Ntilde: "Ñ", Nu: "Ν", OElig: "Œ", Oacute: "Ó", Ocirc: "Ô", Ocy: "О", Odblac: "Ő", Ofr: "𝔒", Ograve: "Ò", Omacr: "Ō", Omega: "Ω", Omicron: "Ο", Oopf: "𝕆", OpenCurlyDoubleQuote: "“", OpenCurlyQuote: "‘", Or: "⩔", Oscr: "𝒪", Oslash: "Ø", Otilde: "Õ", Otimes: "⨷", Ouml: "Ö", OverBar: "‾", OverBrace: "⏞", OverBracket: "⎴", OverParenthesis: "⏜", PartialD: "∂", Pcy: "П", Pfr: "𝔓", Phi: "Φ", Pi: "Π", PlusMinus: "±", Poincareplane: "ℌ", Popf: "ℙ", Pr: "⪻", Precedes: "≺", PrecedesEqual: "⪯", PrecedesSlantEqual: "≼", PrecedesTilde: "≾", Prime: "″", Product: "∏", Proportion: "∷", Proportional: "∝", Pscr: "𝒫", Psi: "Ψ", QUOT: "\"", Qfr: "𝔔", Qopf: "ℚ", Qscr: "𝒬", RBarr: "⤐", REG: "®", Racute: "Ŕ", Rang: "⟫", Rarr: "↠", Rarrtl: "⤖", Rcaron: "Ř", Rcedil: "Ŗ", Rcy: "Р", Re: "ℜ", ReverseElement: "∋", ReverseEquilibrium: "⇋", ReverseUpEquilibrium: "⥯", Rfr: "ℜ", Rho: "Ρ", RightAngleBracket: "⟩", RightArrow: "→", RightArrowBar: "⇥", RightArrowLeftArrow: "⇄", RightCeiling: "⌉", RightDoubleBracket: "⟧", RightDownTeeVector: "⥝", RightDownVector: "⇂", RightDownVectorBar: "⥕", RightFloor: "⌋", RightTee: "⊢", RightTeeArrow: "↦", RightTeeVector: "⥛", RightTriangle: "⊳", RightTriangleBar: "⧐", RightTriangleEqual: "⊵", RightUpDownVector: "⥏", RightUpTeeVector: "⥜", RightUpVector: "↾", RightUpVectorBar: "⥔", RightVector: "⇀", RightVectorBar: "⥓", Rightarrow: "⇒", Ropf: "ℝ", RoundImplies: "⥰", Rrightarrow: "⇛", Rscr: "ℛ", Rsh: "↱", RuleDelayed: "⧴", SHCHcy: "Щ", SHcy: "Ш", SOFTcy: "Ь", Sacute: "Ś", Sc: "⪼", Scaron: "Š", Scedil: "Ş", Scirc: "Ŝ", Scy: "С", Sfr: "𝔖", ShortDownArrow: "↓", ShortLeftArrow: "←", ShortRightArrow: "→", ShortUpArrow: "↑", Sigma: "Σ", SmallCircle: "∘", Sopf: "𝕊", Sqrt: "√", Square: "□", SquareIntersection: "⊓", SquareSubset: "⊏", SquareSubsetEqual: "⊑", SquareSuperset: "⊐", SquareSupersetEqual: "⊒", SquareUnion: "⊔", Sscr: "𝒮", Star: "⋆", Sub: "⋐", Subset: "⋐", SubsetEqual: "⊆", Succeeds: "≻", SucceedsEqual: "⪰", SucceedsSlantEqual: "≽", SucceedsTilde: "≿", SuchThat: "∋", Sum: "∑", Sup: "⋑", Superset: "⊃", SupersetEqual: "⊇", Supset: "⋑", THORN: "Þ", TRADE: "™", TSHcy: "Ћ", TScy: "Ц", Tab: " ", Tau: "Τ", Tcaron: "Ť", Tcedil: "Ţ", Tcy: "Т", Tfr: "𝔗", Therefore: "∴", Theta: "Θ", ThickSpace: "  ", ThinSpace: " ", Tilde: "∼", TildeEqual: "≃", TildeFullEqual: "≅", TildeTilde: "≈", Topf: "𝕋", TripleDot: "⃛", Tscr: "𝒯", Tstrok: "Ŧ", Uacute: "Ú", Uarr: "↟", Uarrocir: "⥉", Ubrcy: "Ў", Ubreve: "Ŭ", Ucirc: "Û", Ucy: "У", Udblac: "Ű", Ufr: "𝔘", Ugrave: "Ù", Umacr: "Ū", UnderBar: "_", UnderBrace: "⏟", UnderBracket: "⎵", UnderParenthesis: "⏝", Union: "⋃", UnionPlus: "⊎", Uogon: "Ų", Uopf: "𝕌", UpArrow: "↑", UpArrowBar: "⤒", UpArrowDownArrow: "⇅", UpDownArrow: "↕", UpEquilibrium: "⥮", UpTee: "⊥", UpTeeArrow: "↥", Uparrow: "⇑", Updownarrow: "⇕", UpperLeftArrow: "↖", UpperRightArrow: "↗", Upsi: "ϒ", Upsilon: "Υ", Uring: "Ů", Uscr: "𝒰", Utilde: "Ũ", Uuml: "Ü", VDash: "⊫", Vbar: "⫫", Vcy: "В", Vdash: "⊩", Vdashl: "⫦", Vee: "⋁", Verbar: "‖", Vert: "‖", VerticalBar: "∣", VerticalLine: "|", VerticalSeparator: "❘", VerticalTilde: "≀", VeryThinSpace: " ", Vfr: "𝔙", Vopf: "𝕍", Vscr: "𝒱", Vvdash: "⊪", Wcirc: "Ŵ", Wedge: "⋀", Wfr: "𝔚", Wopf: "𝕎", Wscr: "𝒲", Xfr: "𝔛", Xi: "Ξ", Xopf: "𝕏", Xscr: "𝒳", YAcy: "Я", YIcy: "Ї", YUcy: "Ю", Yacute: "Ý", Ycirc: "Ŷ", Ycy: "Ы", Yfr: "𝔜", Yopf: "𝕐", Yscr: "𝒴", Yuml: "Ÿ", ZHcy: "Ж", Zacute: "Ź", Zcaron: "Ž", Zcy: "З", Zdot: "Ż", ZeroWidthSpace: "​", Zeta: "Ζ", Zfr: "ℨ", Zopf: "ℤ", Zscr: "𝒵", aacute: "á", abreve: "ă", ac: "∾", acE: "∾̳", acd: "∿", acirc: "â", acute: "´", acy: "а", aelig: "æ", af: "⁡", afr: "𝔞", agrave: "à", alefsym: "ℵ", aleph: "ℵ", alpha: "α", amacr: "ā", amalg: "⨿", amp: "&", and: "∧", andand: "⩕", andd: "⩜", andslope: "⩘", andv: "⩚", ang: "∠", ange: "⦤", angle: "∠", angmsd: "∡", angmsdaa: "⦨", angmsdab: "⦩", angmsdac: "⦪", angmsdad: "⦫", angmsdae: "⦬", angmsdaf: "⦭", angmsdag: "⦮", angmsdah: "⦯", angrt: "∟", angrtvb: "⊾", angrtvbd: "⦝", angsph: "∢", angst: "Å", angzarr: "⍼", aogon: "ą", aopf: "𝕒", ap: "≈", apE: "⩰", apacir: "⩯", ape: "≊", apid: "≋", apos: "'", approx: "≈", approxeq: "≊", aring: "å", ascr: "𝒶", ast: "*", asymp: "≈", asympeq: "≍", atilde: "ã", auml: "ä", awconint: "∳", awint: "⨑", bNot: "⫭", backcong: "≌", backepsilon: "϶", backprime: "‵", backsim: "∽", backsimeq: "⋍", barvee: "⊽", barwed: "⌅", barwedge: "⌅", bbrk: "⎵", bbrktbrk: "⎶", bcong: "≌", bcy: "б", bdquo: "„", becaus: "∵", because: "∵", bemptyv: "⦰", bepsi: "϶", bernou: "ℬ", beta: "β", beth: "ℶ", between: "≬", bfr: "𝔟", bigcap: "⋂", bigcirc: "◯", bigcup: "⋃", bigodot: "⨀", bigoplus: "⨁", bigotimes: "⨂", bigsqcup: "⨆", bigstar: "★", bigtriangledown: "▽", bigtriangleup: "△", biguplus: "⨄", bigvee: "⋁", bigwedge: "⋀", bkarow: "⤍", blacklozenge: "⧫", blacksquare: "▪", blacktriangle: "▴", blacktriangledown: "▾", blacktriangleleft: "◂", blacktriangleright: "▸", blank: "␣", blk12: "▒", blk14: "░", blk34: "▓", block: "█", bne: "=⃥", bnequiv: "≡⃥", bnot: "⌐", bopf: "𝕓", bot: "⊥", bottom: "⊥", bowtie: "⋈", boxDL: "╗", boxDR: "╔", boxDl: "╖", boxDr: "╓", boxH: "═", boxHD: "╦", boxHU: "╩", boxHd: "╤", boxHu: "╧", boxUL: "╝", boxUR: "╚", boxUl: "╜", boxUr: "╙", boxV: "║", boxVH: "╬", boxVL: "╣", boxVR: "╠", boxVh: "╫", boxVl: "╢", boxVr: "╟", boxbox: "⧉", boxdL: "╕", boxdR: "╒", boxdl: "┐", boxdr: "┌", boxh: "─", boxhD: "╥", boxhU: "╨", boxhd: "┬", boxhu: "┴", boxminus: "⊟", boxplus: "⊞", boxtimes: "⊠", boxuL: "╛", boxuR: "╘", boxul: "┘", boxur: "└", boxv: "│", boxvH: "╪", boxvL: "╡", boxvR: "╞", boxvh: "┼", boxvl: "┤", boxvr: "├", bprime: "‵", breve: "˘", brvbar: "¦", bscr: "𝒷", bsemi: "⁏", bsim: "∽", bsime: "⋍", bsol: "\\", bsolb: "⧅", bsolhsub: "⟈", bull: "•", bullet: "•", bump: "≎", bumpE: "⪮", bumpe: "≏", bumpeq: "≏", cacute: "ć", cap: "∩", capand: "⩄", capbrcup: "⩉", capcap: "⩋", capcup: "⩇", capdot: "⩀", caps: "∩︀", caret: "⁁", caron: "ˇ", ccaps: "⩍", ccaron: "č", ccedil: "ç", ccirc: "ĉ", ccups: "⩌", ccupssm: "⩐", cdot: "ċ", cedil: "¸", cemptyv: "⦲", cent: "¢", centerdot: "·", cfr: "𝔠", chcy: "ч", check: "✓", checkmark: "✓", chi: "χ", cir: "○", cirE: "⧃", circ: "ˆ", circeq: "≗", circlearrowleft: "↺", circlearrowright: "↻", circledR: "®", circledS: "Ⓢ", circledast: "⊛", circledcirc: "⊚", circleddash: "⊝", cire: "≗", cirfnint: "⨐", cirmid: "⫯", cirscir: "⧂", clubs: "♣", clubsuit: "♣", colon: ":", colone: "≔", coloneq: "≔", comma: ",", commat: "@", comp: "∁", compfn: "∘", complement: "∁", complexes: "ℂ", cong: "≅", congdot: "⩭", conint: "∮", copf: "𝕔", coprod: "∐", copy: "©", copysr: "℗", crarr: "↵", cross: "✗", cscr: "𝒸", csub: "⫏", csube: "⫑", csup: "⫐", csupe: "⫒", ctdot: "⋯", cudarrl: "⤸", cudarrr: "⤵", cuepr: "⋞", cuesc: "⋟", cularr: "↶", cularrp: "⤽", cup: "∪", cupbrcap: "⩈", cupcap: "⩆", cupcup: "⩊", cupdot: "⊍", cupor: "⩅", cups: "∪︀", curarr: "↷", curarrm: "⤼", curlyeqprec: "⋞", curlyeqsucc: "⋟", curlyvee: "⋎", curlywedge: "⋏", curren: "¤", curvearrowleft: "↶", curvearrowright: "↷", cuvee: "⋎", cuwed: "⋏", cwconint: "∲", cwint: "∱", cylcty: "⌭", dArr: "⇓", dHar: "⥥", dagger: "†", daleth: "ℸ", darr: "↓", dash: "‐", dashv: "⊣", dbkarow: "⤏", dblac: "˝", dcaron: "ď", dcy: "д", dd: "ⅆ", ddagger: "‡", ddarr: "⇊", ddotseq: "⩷", deg: "°", delta: "δ", demptyv: "⦱", dfisht: "⥿", dfr: "𝔡", dharl: "⇃", dharr: "⇂", diam: "⋄", diamond: "⋄", diamondsuit: "♦", diams: "♦", die: "¨", digamma: "ϝ", disin: "⋲", div: "÷", divide: "÷", divideontimes: "⋇", divonx: "⋇", djcy: "ђ", dlcorn: "⌞", dlcrop: "⌍", dollar: "$", dopf: "𝕕", dot: "˙", doteq: "≐", doteqdot: "≑", dotminus: "∸", dotplus: "∔", dotsquare: "⊡", doublebarwedge: "⌆", downarrow: "↓", downdownarrows: "⇊", downharpoonleft: "⇃", downharpoonright: "⇂", drbkarow: "⤐", drcorn: "⌟", drcrop: "⌌", dscr: "𝒹", dscy: "ѕ", dsol: "⧶", dstrok: "đ", dtdot: "⋱", dtri: "▿", dtrif: "▾", duarr: "⇵", duhar: "⥯", dwangle: "⦦", dzcy: "џ", dzigrarr: "⟿", eDDot: "⩷", eDot: "≑", eacute: "é", easter: "⩮", ecaron: "ě", ecir: "≖", ecirc: "ê", ecolon: "≕", ecy: "э", edot: "ė", ee: "ⅇ", efDot: "≒", efr: "𝔢", eg: "⪚", egrave: "è", egs: "⪖", egsdot: "⪘", el: "⪙", elinters: "⏧", ell: "ℓ", els: "⪕", elsdot: "⪗", emacr: "ē", empty: "∅", emptyset: "∅", emptyv: "∅", emsp13: " ", emsp14: " ", emsp: " ", eng: "ŋ", ensp: " ", eogon: "ę", eopf: "𝕖", epar: "⋕", eparsl: "⧣", eplus: "⩱", epsi: "ε", epsilon: "ε", epsiv: "ϵ", eqcirc: "≖", eqcolon: "≕", eqsim: "≂", eqslantgtr: "⪖", eqslantless: "⪕", equals: "=", equest: "≟", equiv: "≡", equivDD: "⩸", eqvparsl: "⧥", erDot: "≓", erarr: "⥱", escr: "ℯ", esdot: "≐", esim: "≂", eta: "η", eth: "ð", euml: "ë", euro: "€", excl: "!", exist: "∃", expectation: "ℰ", exponentiale: "ⅇ", fallingdotseq: "≒", fcy: "ф", female: "♀", ffilig: "ffi", fflig: "ff", ffllig: "ffl", ffr: "𝔣", filig: "fi", fjlig: "fj", flat: "♭", fllig: "fl", fltns: "▱", fnof: "ƒ", fopf: "𝕗", forall: "∀", fork: "⋔", forkv: "⫙", fpartint: "⨍", frac12: "½", frac13: "⅓", frac14: "¼", frac15: "⅕", frac16: "⅙", frac18: "⅛", frac23: "⅔", frac25: "⅖", frac34: "¾", frac35: "⅗", frac38: "⅜", frac45: "⅘", frac56: "⅚", frac58: "⅝", frac78: "⅞", frasl: "⁄", frown: "⌢", fscr: "𝒻", gE: "≧", gEl: "⪌", gacute: "ǵ", gamma: "γ", gammad: "ϝ", gap: "⪆", gbreve: "ğ", gcirc: "ĝ", gcy: "г", gdot: "ġ", ge: "≥", gel: "⋛", geq: "≥", geqq: "≧", geqslant: "⩾", ges: "⩾", gescc: "⪩", gesdot: "⪀", gesdoto: "⪂", gesdotol: "⪄", gesl: "⋛︀", gesles: "⪔", gfr: "𝔤", gg: "≫", ggg: "⋙", gimel: "ℷ", gjcy: "ѓ", gl: "≷", glE: "⪒", gla: "⪥", glj: "⪤", gnE: "≩", gnap: "⪊", gnapprox: "⪊", gne: "⪈", gneq: "⪈", gneqq: "≩", gnsim: "⋧", gopf: "𝕘", grave: "`", gscr: "ℊ", gsim: "≳", gsime: "⪎", gsiml: "⪐", gt: ">", gtcc: "⪧", gtcir: "⩺", gtdot: "⋗", gtlPar: "⦕", gtquest: "⩼", gtrapprox: "⪆", gtrarr: "⥸", gtrdot: "⋗", gtreqless: "⋛", gtreqqless: "⪌", gtrless: "≷", gtrsim: "≳", gvertneqq: "≩︀", gvnE: "≩︀", hArr: "⇔", hairsp: " ", half: "½", hamilt: "ℋ", hardcy: "ъ", harr: "↔", harrcir: "⥈", harrw: "↭", hbar: "ℏ", hcirc: "ĥ", hearts: "♥", heartsuit: "♥", hellip: "…", hercon: "⊹", hfr: "𝔥", hksearow: "⤥", hkswarow: "⤦", hoarr: "⇿", homtht: "∻", hookleftarrow: "↩", hookrightarrow: "↪", hopf: "𝕙", horbar: "―", hscr: "𝒽", hslash: "ℏ", hstrok: "ħ", hybull: "⁃", hyphen: "‐", iacute: "í", ic: "⁣", icirc: "î", icy: "и", iecy: "е", iexcl: "¡", iff: "⇔", ifr: "𝔦", igrave: "ì", ii: "ⅈ", iiiint: "⨌", iiint: "∭", iinfin: "⧜", iiota: "℩", ijlig: "ij", imacr: "ī", image: "ℑ", imagline: "ℐ", imagpart: "ℑ", imath: "ı", imof: "⊷", imped: "Ƶ", in: "∈", incare: "℅", infin: "∞", infintie: "⧝", inodot: "ı", int: "∫", intcal: "⊺", integers: "ℤ", intercal: "⊺", intlarhk: "⨗", intprod: "⨼", iocy: "ё", iogon: "į", iopf: "𝕚", iota: "ι", iprod: "⨼", iquest: "¿", iscr: "𝒾", isin: "∈", isinE: "⋹", isindot: "⋵", isins: "⋴", isinsv: "⋳", isinv: "∈", it: "⁢", itilde: "ĩ", iukcy: "і", iuml: "ï", jcirc: "ĵ", jcy: "й", jfr: "𝔧", jmath: "ȷ", jopf: "𝕛", jscr: "𝒿", jsercy: "ј", jukcy: "є", kappa: "κ", kappav: "ϰ", kcedil: "ķ", kcy: "к", kfr: "𝔨", kgreen: "ĸ", khcy: "х", kjcy: "ќ", kopf: "𝕜", kscr: "𝓀", lAarr: "⇚", lArr: "⇐", lAtail: "⤛", lBarr: "⤎", lE: "≦", lEg: "⪋", lHar: "⥢", lacute: "ĺ", laemptyv: "⦴", lagran: "ℒ", lambda: "λ", lang: "⟨", langd: "⦑", langle: "⟨", lap: "⪅", laquo: "«", larr: "←", larrb: "⇤", larrbfs: "⤟", larrfs: "⤝", larrhk: "↩", larrlp: "↫", larrpl: "⤹", larrsim: "⥳", larrtl: "↢", lat: "⪫", latail: "⤙", late: "⪭", lates: "⪭︀", lbarr: "⤌", lbbrk: "❲", lbrace: "{", lbrack: "[", lbrke: "⦋", lbrksld: "⦏", lbrkslu: "⦍", lcaron: "ľ", lcedil: "ļ", lceil: "⌈", lcub: "{", lcy: "л", ldca: "⤶", ldquo: "“", ldquor: "„", ldrdhar: "⥧", ldrushar: "⥋", ldsh: "↲", le: "≤", leftarrow: "←", leftarrowtail: "↢", leftharpoondown: "↽", leftharpoonup: "↼", leftleftarrows: "⇇", leftrightarrow: "↔", leftrightarrows: "⇆", leftrightharpoons: "⇋", leftrightsquigarrow: "↭", leftthreetimes: "⋋", leg: "⋚", leq: "≤", leqq: "≦", leqslant: "⩽", les: "⩽", lescc: "⪨", lesdot: "⩿", lesdoto: "⪁", lesdotor: "⪃", lesg: "⋚︀", lesges: "⪓", lessapprox: "⪅", lessdot: "⋖", lesseqgtr: "⋚", lesseqqgtr: "⪋", lessgtr: "≶", lesssim: "≲", lfisht: "⥼", lfloor: "⌊", lfr: "𝔩", lg: "≶", lgE: "⪑", lhard: "↽", lharu: "↼", lharul: "⥪", lhblk: "▄", ljcy: "љ", ll: "≪", llarr: "⇇", llcorner: "⌞", llhard: "⥫", lltri: "◺", lmidot: "ŀ", lmoust: "⎰", lmoustache: "⎰", lnE: "≨", lnap: "⪉", lnapprox: "⪉", lne: "⪇", lneq: "⪇", lneqq: "≨", lnsim: "⋦", loang: "⟬", loarr: "⇽", lobrk: "⟦", longleftarrow: "⟵", longleftrightarrow: "⟷", longmapsto: "⟼", longrightarrow: "⟶", looparrowleft: "↫", looparrowright: "↬", lopar: "⦅", lopf: "𝕝", loplus: "⨭", lotimes: "⨴", lowast: "∗", lowbar: "_", loz: "◊", lozenge: "◊", lozf: "⧫", lpar: "(", lparlt: "⦓", lrarr: "⇆", lrcorner: "⌟", lrhar: "⇋", lrhard: "⥭", lrm: "‎", lrtri: "⊿", lsaquo: "‹", lscr: "𝓁", lsh: "↰", lsim: "≲", lsime: "⪍", lsimg: "⪏", lsqb: "[", lsquo: "‘", lsquor: "‚", lstrok: "ł", lt: "<", ltcc: "⪦", ltcir: "⩹", ltdot: "⋖", lthree: "⋋", ltimes: "⋉", ltlarr: "⥶", ltquest: "⩻", ltrPar: "⦖", ltri: "◃", ltrie: "⊴", ltrif: "◂", lurdshar: "⥊", luruhar: "⥦", lvertneqq: "≨︀", lvnE: "≨︀", mDDot: "∺", macr: "¯", male: "♂", malt: "✠", maltese: "✠", map: "↦", mapsto: "↦", mapstodown: "↧", mapstoleft: "↤", mapstoup: "↥", marker: "▮", mcomma: "⨩", mcy: "м", mdash: "—", measuredangle: "∡", mfr: "𝔪", mho: "℧", micro: "µ", mid: "∣", midast: "*", midcir: "⫰", middot: "·", minus: "−", minusb: "⊟", minusd: "∸", minusdu: "⨪", mlcp: "⫛", mldr: "…", mnplus: "∓", models: "⊧", mopf: "𝕞", mp: "∓", mscr: "𝓂", mstpos: "∾", mu: "μ", multimap: "⊸", mumap: "⊸", nGg: "⋙̸", nGt: "≫⃒", nGtv: "≫̸", nLeftarrow: "⇍", nLeftrightarrow: "⇎", nLl: "⋘̸", nLt: "≪⃒", nLtv: "≪̸", nRightarrow: "⇏", nVDash: "⊯", nVdash: "⊮", nabla: "∇", nacute: "ń", nang: "∠⃒", nap: "≉", napE: "⩰̸", napid: "≋̸", napos: "ʼn", napprox: "≉", natur: "♮", natural: "♮", naturals: "ℕ", nbsp: "\xA0", nbump: "≎̸", nbumpe: "≏̸", ncap: "⩃", ncaron: "ň", ncedil: "ņ", ncong: "≇", ncongdot: "⩭̸", ncup: "⩂", ncy: "н", ndash: "–", ne: "≠", neArr: "⇗", nearhk: "⤤", nearr: "↗", nearrow: "↗", nedot: "≐̸", nequiv: "≢", nesear: "⤨", nesim: "≂̸", nexist: "∄", nexists: "∄", nfr: "𝔫", ngE: "≧̸", nge: "≱", ngeq: "≱", ngeqq: "≧̸", ngeqslant: "⩾̸", nges: "⩾̸", ngsim: "≵", ngt: "≯", ngtr: "≯", nhArr: "⇎", nharr: "↮", nhpar: "⫲", ni: "∋", nis: "⋼", nisd: "⋺", niv: "∋", njcy: "њ", nlArr: "⇍", nlE: "≦̸", nlarr: "↚", nldr: "‥", nle: "≰", nleftarrow: "↚", nleftrightarrow: "↮", nleq: "≰", nleqq: "≦̸", nleqslant: "⩽̸", nles: "⩽̸", nless: "≮", nlsim: "≴", nlt: "≮", nltri: "⋪", nltrie: "⋬", nmid: "∤", nopf: "𝕟", not: "¬", notin: "∉", notinE: "⋹̸", notindot: "⋵̸", notinva: "∉", notinvb: "⋷", notinvc: "⋶", notni: "∌", notniva: "∌", notnivb: "⋾", notnivc: "⋽", npar: "∦", nparallel: "∦", nparsl: "⫽⃥", npart: "∂̸", npolint: "⨔", npr: "⊀", nprcue: "⋠", npre: "⪯̸", nprec: "⊀", npreceq: "⪯̸", nrArr: "⇏", nrarr: "↛", nrarrc: "⤳̸", nrarrw: "↝̸", nrightarrow: "↛", nrtri: "⋫", nrtrie: "⋭", nsc: "⊁", nsccue: "⋡", nsce: "⪰̸", nscr: "𝓃", nshortmid: "∤", nshortparallel: "∦", nsim: "≁", nsime: "≄", nsimeq: "≄", nsmid: "∤", nspar: "∦", nsqsube: "⋢", nsqsupe: "⋣", nsub: "⊄", nsubE: "⫅̸", nsube: "⊈", nsubset: "⊂⃒", nsubseteq: "⊈", nsubseteqq: "⫅̸", nsucc: "⊁", nsucceq: "⪰̸", nsup: "⊅", nsupE: "⫆̸", nsupe: "⊉", nsupset: "⊃⃒", nsupseteq: "⊉", nsupseteqq: "⫆̸", ntgl: "≹", ntilde: "ñ", ntlg: "≸", ntriangleleft: "⋪", ntrianglelefteq: "⋬", ntriangleright: "⋫", ntrianglerighteq: "⋭", nu: "ν", num: "#", numero: "№", numsp: " ", nvDash: "⊭", nvHarr: "⤄", nvap: "≍⃒", nvdash: "⊬", nvge: "≥⃒", nvgt: ">⃒", nvinfin: "⧞", nvlArr: "⤂", nvle: "≤⃒", nvlt: "<⃒", nvltrie: "⊴⃒", nvrArr: "⤃", nvrtrie: "⊵⃒", nvsim: "∼⃒", nwArr: "⇖", nwarhk: "⤣", nwarr: "↖", nwarrow: "↖", nwnear: "⤧", oS: "Ⓢ", oacute: "ó", oast: "⊛", ocir: "⊚", ocirc: "ô", ocy: "о", odash: "⊝", odblac: "ő", odiv: "⨸", odot: "⊙", odsold: "⦼", oelig: "œ", ofcir: "⦿", ofr: "𝔬", ogon: "˛", ograve: "ò", ogt: "⧁", ohbar: "⦵", ohm: "Ω", oint: "∮", olarr: "↺", olcir: "⦾", olcross: "⦻", oline: "‾", olt: "⧀", omacr: "ō", omega: "ω", omicron: "ο", omid: "⦶", ominus: "⊖", oopf: "𝕠", opar: "⦷", operp: "⦹", oplus: "⊕", or: "∨", orarr: "↻", ord: "⩝", order: "ℴ", orderof: "ℴ", ordf: "ª", ordm: "º", origof: "⊶", oror: "⩖", orslope: "⩗", orv: "⩛", oscr: "ℴ", oslash: "ø", osol: "⊘", otilde: "õ", otimes: "⊗", otimesas: "⨶", ouml: "ö", ovbar: "⌽", par: "∥", para: "¶", parallel: "∥", parsim: "⫳", parsl: "⫽", part: "∂", pcy: "п", percnt: "%", period: ".", permil: "‰", perp: "⊥", pertenk: "‱", pfr: "𝔭", phi: "φ", phiv: "ϕ", phmmat: "ℳ", phone: "☎", pi: "π", pitchfork: "⋔", piv: "ϖ", planck: "ℏ", planckh: "ℎ", plankv: "ℏ", plus: "+", plusacir: "⨣", plusb: "⊞", pluscir: "⨢", plusdo: "∔", plusdu: "⨥", pluse: "⩲", plusmn: "±", plussim: "⨦", plustwo: "⨧", pm: "±", pointint: "⨕", popf: "𝕡", pound: "£", pr: "≺", prE: "⪳", prap: "⪷", prcue: "≼", pre: "⪯", prec: "≺", precapprox: "⪷", preccurlyeq: "≼", preceq: "⪯", precnapprox: "⪹", precneqq: "⪵", precnsim: "⋨", precsim: "≾", prime: "′", primes: "ℙ", prnE: "⪵", prnap: "⪹", prnsim: "⋨", prod: "∏", profalar: "⌮", profline: "⌒", profsurf: "⌓", prop: "∝", propto: "∝", prsim: "≾", prurel: "⊰", pscr: "𝓅", psi: "ψ", puncsp: " ", qfr: "𝔮", qint: "⨌", qopf: "𝕢", qprime: "⁗", qscr: "𝓆", quaternions: "ℍ", quatint: "⨖", quest: "?", questeq: "≟", quot: "\"", rAarr: "⇛", rArr: "⇒", rAtail: "⤜", rBarr: "⤏", rHar: "⥤", race: "∽̱", racute: "ŕ", radic: "√", raemptyv: "⦳", rang: "⟩", rangd: "⦒", range: "⦥", rangle: "⟩", raquo: "»", rarr: "→", rarrap: "⥵", rarrb: "⇥", rarrbfs: "⤠", rarrc: "⤳", rarrfs: "⤞", rarrhk: "↪", rarrlp: "↬", rarrpl: "⥅", rarrsim: "⥴", rarrtl: "↣", rarrw: "↝", ratail: "⤚", ratio: "∶", rationals: "ℚ", rbarr: "⤍", rbbrk: "❳", rbrace: "}", rbrack: "]", rbrke: "⦌", rbrksld: "⦎", rbrkslu: "⦐", rcaron: "ř", rcedil: "ŗ", rceil: "⌉", rcub: "}", rcy: "р", rdca: "⤷", rdldhar: "⥩", rdquo: "”", rdquor: "”", rdsh: "↳", real: "ℜ", realine: "ℛ", realpart: "ℜ", reals: "ℝ", rect: "▭", reg: "®", rfisht: "⥽", rfloor: "⌋", rfr: "𝔯", rhard: "⇁", rharu: "⇀", rharul: "⥬", rho: "ρ", rhov: "ϱ", rightarrow: "→", rightarrowtail: "↣", rightharpoondown: "⇁", rightharpoonup: "⇀", rightleftarrows: "⇄", rightleftharpoons: "⇌", rightrightarrows: "⇉", rightsquigarrow: "↝", rightthreetimes: "⋌", ring: "˚", risingdotseq: "≓", rlarr: "⇄", rlhar: "⇌", rlm: "‏", rmoust: "⎱", rmoustache: "⎱", rnmid: "⫮", roang: "⟭", roarr: "⇾", robrk: "⟧", ropar: "⦆", ropf: "𝕣", roplus: "⨮", rotimes: "⨵", rpar: ")", rpargt: "⦔", rppolint: "⨒", rrarr: "⇉", rsaquo: "›", rscr: "𝓇", rsh: "↱", rsqb: "]", rsquo: "’", rsquor: "’", rthree: "⋌", rtimes: "⋊", rtri: "▹", rtrie: "⊵", rtrif: "▸", rtriltri: "⧎", ruluhar: "⥨", rx: "℞", sacute: "ś", sbquo: "‚", sc: "≻", scE: "⪴", scap: "⪸", scaron: "š", sccue: "≽", sce: "⪰", scedil: "ş", scirc: "ŝ", scnE: "⪶", scnap: "⪺", scnsim: "⋩", scpolint: "⨓", scsim: "≿", scy: "с", sdot: "⋅", sdotb: "⊡", sdote: "⩦", seArr: "⇘", searhk: "⤥", searr: "↘", searrow: "↘", sect: "§", semi: ";", seswar: "⤩", setminus: "∖", setmn: "∖", sext: "✶", sfr: "𝔰", sfrown: "⌢", sharp: "♯", shchcy: "щ", shcy: "ш", shortmid: "∣", shortparallel: "∥", shy: "­", sigma: "σ", sigmaf: "ς", sigmav: "ς", sim: "∼", simdot: "⩪", sime: "≃", simeq: "≃", simg: "⪞", simgE: "⪠", siml: "⪝", simlE: "⪟", simne: "≆", simplus: "⨤", simrarr: "⥲", slarr: "←", smallsetminus: "∖", smashp: "⨳", smeparsl: "⧤", smid: "∣", smile: "⌣", smt: "⪪", smte: "⪬", smtes: "⪬︀", softcy: "ь", sol: "/", solb: "⧄", solbar: "⌿", sopf: "𝕤", spades: "♠", spadesuit: "♠", spar: "∥", sqcap: "⊓", sqcaps: "⊓︀", sqcup: "⊔", sqcups: "⊔︀", sqsub: "⊏", sqsube: "⊑", sqsubset: "⊏", sqsubseteq: "⊑", sqsup: "⊐", sqsupe: "⊒", sqsupset: "⊐", sqsupseteq: "⊒", squ: "□", square: "□", squarf: "▪", squf: "▪", srarr: "→", sscr: "𝓈", ssetmn: "∖", ssmile: "⌣", sstarf: "⋆", star: "☆", starf: "★", straightepsilon: "ϵ", straightphi: "ϕ", strns: "¯", sub: "⊂", subE: "⫅", subdot: "⪽", sube: "⊆", subedot: "⫃", submult: "⫁", subnE: "⫋", subne: "⊊", subplus: "⪿", subrarr: "⥹", subset: "⊂", subseteq: "⊆", subseteqq: "⫅", subsetneq: "⊊", subsetneqq: "⫋", subsim: "⫇", subsub: "⫕", subsup: "⫓", succ: "≻", succapprox: "⪸", succcurlyeq: "≽", succeq: "⪰", succnapprox: "⪺", succneqq: "⪶", succnsim: "⋩", succsim: "≿", sum: "∑", sung: "♪", sup1: "¹", sup2: "²", sup3: "³", sup: "⊃", supE: "⫆", supdot: "⪾", supdsub: "⫘", supe: "⊇", supedot: "⫄", suphsol: "⟉", suphsub: "⫗", suplarr: "⥻", supmult: "⫂", supnE: "⫌", supne: "⊋", supplus: "⫀", supset: "⊃", supseteq: "⊇", supseteqq: "⫆", supsetneq: "⊋", supsetneqq: "⫌", supsim: "⫈", supsub: "⫔", supsup: "⫖", swArr: "⇙", swarhk: "⤦", swarr: "↙", swarrow: "↙", swnwar: "⤪", szlig: "ß", target: "⌖", tau: "τ", tbrk: "⎴", tcaron: "ť", tcedil: "ţ", tcy: "т", tdot: "⃛", telrec: "⌕", tfr: "𝔱", there4: "∴", therefore: "∴", theta: "θ", thetasym: "ϑ", thetav: "ϑ", thickapprox: "≈", thicksim: "∼", thinsp: " ", thkap: "≈", thksim: "∼", thorn: "þ", tilde: "˜", times: "×", timesb: "⊠", timesbar: "⨱", timesd: "⨰", tint: "∭", toea: "⤨", top: "⊤", topbot: "⌶", topcir: "⫱", topf: "𝕥", topfork: "⫚", tosa: "⤩", tprime: "‴", trade: "™", triangle: "▵", triangledown: "▿", triangleleft: "◃", trianglelefteq: "⊴", triangleq: "≜", triangleright: "▹", trianglerighteq: "⊵", tridot: "◬", trie: "≜", triminus: "⨺", triplus: "⨹", trisb: "⧍", tritime: "⨻", trpezium: "⏢", tscr: "𝓉", tscy: "ц", tshcy: "ћ", tstrok: "ŧ", twixt: "≬", twoheadleftarrow: "↞", twoheadrightarrow: "↠", uArr: "⇑", uHar: "⥣", uacute: "ú", uarr: "↑", ubrcy: "ў", ubreve: "ŭ", ucirc: "û", ucy: "у", udarr: "⇅", udblac: "ű", udhar: "⥮", ufisht: "⥾", ufr: "𝔲", ugrave: "ù", uharl: "↿", uharr: "↾", uhblk: "▀", ulcorn: "⌜", ulcorner: "⌜", ulcrop: "⌏", ultri: "◸", umacr: "ū", uml: "¨", uogon: "ų", uopf: "𝕦", uparrow: "↑", updownarrow: "↕", upharpoonleft: "↿", upharpoonright: "↾", uplus: "⊎", upsi: "υ", upsih: "ϒ", upsilon: "υ", upuparrows: "⇈", urcorn: "⌝", urcorner: "⌝", urcrop: "⌎", uring: "ů", urtri: "◹", uscr: "𝓊", utdot: "⋰", utilde: "ũ", utri: "▵", utrif: "▴", uuarr: "⇈", uuml: "ü", uwangle: "⦧", vArr: "⇕", vBar: "⫨", vBarv: "⫩", vDash: "⊨", vangrt: "⦜", varepsilon: "ϵ", varkappa: "ϰ", varnothing: "∅", varphi: "ϕ", varpi: "ϖ", varpropto: "∝", varr: "↕", varrho: "ϱ", varsigma: "ς", varsubsetneq: "⊊︀", varsubsetneqq: "⫋︀", varsupsetneq: "⊋︀", varsupsetneqq: "⫌︀", vartheta: "ϑ", vartriangleleft: "⊲", vartriangleright: "⊳", vcy: "в", vdash: "⊢", vee: "∨", veebar: "⊻", veeeq: "≚", vellip: "⋮", verbar: "|", vert: "|", vfr: "𝔳", vltri: "⊲", vnsub: "⊂⃒", vnsup: "⊃⃒", vopf: "𝕧", vprop: "∝", vrtri: "⊳", vscr: "𝓋", vsubnE: "⫋︀", vsubne: "⊊︀", vsupnE: "⫌︀", vsupne: "⊋︀", vzigzag: "⦚", wcirc: "ŵ", wedbar: "⩟", wedge: "∧", wedgeq: "≙", weierp: "℘", wfr: "𝔴", wopf: "𝕨", wp: "℘", wr: "≀", wreath: "≀", wscr: "𝓌", xcap: "⋂", xcirc: "◯", xcup: "⋃", xdtri: "▽", xfr: "𝔵", xhArr: "⟺", xharr: "⟷", xi: "ξ", xlArr: "⟸", xlarr: "⟵", xmap: "⟼", xnis: "⋻", xodot: "⨀", xopf: "𝕩", xoplus: "⨁", xotime: "⨂", xrArr: "⟹", xrarr: "⟶", xscr: "𝓍", xsqcup: "⨆", xuplus: "⨄", xutri: "△", xvee: "⋁", xwedge: "⋀", yacute: "ý", yacy: "я", ycirc: "ŷ", ycy: "ы", yen: "¥", yfr: "𝔶", yicy: "ї", yopf: "𝕪", yscr: "𝓎", yucy: "ю", yuml: "ÿ", zacute: "ź", zcaron: "ž", zcy: "з", zdot: "ż", zeetrf: "ℨ", zeta: "ζ", zfr: "𝔷", zhcy: "ж", zigrarr: "⇝", zopf: "𝕫", zscr: "𝓏", zwj: "‍", zwnj: "‌" }; // node_modules/decode-named-character-reference/index.js const own$1 = {}.hasOwnProperty; /** * Decode a single character reference (without the `&` or `;`). * You probably only need this when you’re building parsers yourself that follow * different rules compared to HTML. * This is optimized to be tiny in browsers. * * @param {string} value * `notin` (named), `#123` (deci), `#x123` (hexa). * @returns {string|false} * Decoded reference. */ function decodeNamedCharacterReference(value) { return own$1.call(characterEntities, value) ? characterEntities[value] : false; } // node_modules/micromark-util-chunked/index.js /** * Like `Array#splice`, but smarter for giant arrays. * * `Array#splice` takes all items to be inserted as individual argument which * causes a stack overflow in V8 when trying to insert 100k items for instance. * * Otherwise, this does not return the removed items, and takes `items` as an * array instead of rest parameters. * * @template {unknown} T * Item type. * @param {Array<T>} list * List to operate on. * @param {number} start * Index to remove/insert at (can be negative). * @param {number} remove * Number of items to remove. * @param {Array<T>} items * Items to inject into `list`. * @returns {undefined} * Nothing. */ function splice(list, start, remove, items) { const end = list.length; let chunkStart = 0; /** @type {Array<unknown>} */ let parameters; if (start < 0) start = -start > end ? 0 : end + start; else start = start > end ? end : start; remove = remove > 0 ? remove : 0; if (items.length < 1e4) { parameters = Array.from(items); parameters.unshift(start, remove); list.splice(...parameters); } else { if (remove) list.splice(start, remove); while (chunkStart < items.length) { parameters = items.slice(chunkStart, chunkStart + 1e4); parameters.unshift(start, 0); list.splice(...parameters); chunkStart += 1e4; start += 1e4; } } } /** * Append `items` (an array) at the end of `list` (another array). * When `list` was empty, returns `items` instead. * * This prevents a potentially expensive operation when `list` is empty, * and adds items in batches to prevent V8 from hanging. * * @template {unknown} T * Item type. * @param {Array<T>} list * List to operate on. * @param {Array<T>} items * Items to add to `list`. * @returns {Array<T>} * Either `list` or `items`. */ function push(list, items) { if (list.length > 0) { splice(list, list.length, 0, items); return list; } return items; } // node_modules/micromark-util-combine-extensions/index.js /** * @import { * Extension, * Handles, * HtmlExtension, * NormalizedExtension * } from 'micromark-util-types' */ const hasOwnProperty = {}.hasOwnProperty; /** * Combine multiple syntax extensions into one. * * @param {ReadonlyArray<Extension>} extensions * List of syntax extensions. * @returns {NormalizedExtension} * A single combined extension. */ function combineExtensions(extensions) { /** @type {NormalizedExtension} */ const all = {}; let index = -1; while (++index < extensions.length) syntaxExtension(all, extensions[index]); return all; } /** * Merge `extension` into `all`. * * @param {NormalizedExtension} all * Extension to merge into. * @param {Extension} extension * Extension to merge. * @returns {undefined} * Nothing. */ function syntaxExtension(all, extension) { /** @type {keyof Extension} */ let hook; for (hook in extension) { /** @type {Record<string, unknown>} */ const left = (hasOwnProperty.call(all, hook) ? all[hook] : void 0) || (all[hook] = {}); /** @type {Record<string, unknown> | undefined} */ const right = extension[hook]; /** @type {string} */ let code; if (right) for (code in right) { if (!hasOwnProperty.call(left, code)) left[code] = []; const value = right[code]; constructs(left[code], Array.isArray(value) ? value : value ? [value] : []); } } } /** * Merge `list` into `existing` (both lists of constructs). * Mutates `existing`. * * @param {Array<unknown>} existing * List of constructs to merge into. * @param {Array<unknown>} list * List of constructs to merge. * @returns {undefined} * Nothing. */ function constructs(existing, list) { let index = -1; /** @type {Array<unknown>} */ const before = []; while (++index < list.length) (list[index].add === "after" ? existing : before).push(list[index]); splice(existing, 0, 0, before); } // node_modules/micromark-util-decode-numeric-character-reference/index.js /** * Turn the number (in string form as either hexa- or plain decimal) coming from * a numeric character reference into a character. * * Sort of like `String.fromCodePoint(Number.parseInt(value, base))`, but makes * non-characters and control characters safe. * * @param {string} value * Value to decode. * @param {number} base * Numeric base. * @returns {string} * Character. */ function decodeNumericCharacterReference(value, base) { const code = Number.parseInt(value, base); if (code < 9 || code === 11 || code > 13 && code < 32 || code > 126 && code < 160 || code > 55295 && code < 57344 || code > 64975 && code < 65008 || (code & 65535) === 65535 || (code & 65535) === 65534 || code > 1114111) return "�"; return String.fromCodePoint(code); } // node_modules/micromark-util-normalize-identifier/index.js /** * Normalize an identifier (as found in references, definitions). * * Collapses markdown whitespace, trim, and then lower- and uppercase. * * Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their * lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different * uppercase character (U+0398 (`Θ`)). * So, to get a canonical form, we perform both lower- and uppercase. * * Using uppercase last makes sure keys will never interact with default * prototypal values (such as `constructor`): nothing in the prototype of * `Object` is uppercase. * * @param {string} value * Identifier to normalize. * @returns {string} * Normalized identifier. */ function normalizeIdentifier(value) { return value.replace(/[\t\n\r ]+/g, " ").replace(/^ | $/g, "").toLowerCase().toUpperCase(); } // node_modules/micromark-util-character/index.js /** * @import {Code} from 'micromark-util-types' */ /** * Check whether the character code represents an ASCII alpha (`a` through `z`, * case insensitive). * * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha. * * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`) * to U+005A (`Z`). * * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`) * to U+007A (`z`). * * @param code * Code. * @returns {boolean} * Whether it matches. */ const asciiAlpha = regexCheck(/[A-Za-z]/); /** * Check whether the character code represents an ASCII alphanumeric (`a` * through `z`, case insensitive, or `0` through `9`). * * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha * (see `asciiAlpha`). * * @param code * Code. * @returns {boolean} * Whether it matches. */ const asciiAlphanumeric = regexCheck(/[\dA-Za-z]/); /** * Check whether the character code represents an ASCII atext. * * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`), * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE * (`{`) to U+007E TILDE (`~`). * * See: * **\[RFC5322]**: * [Internet Message Format](https://tools.ietf.org/html/rfc5322). * P. Resnick. * IETF. * * @param code * Code. * @returns {boolean} * Whether it matches. */ const asciiAtext = regexCheck(/[#-'*+\--9=?A-Z^-~]/); /** * Check whether a character code is an ASCII control character. * * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL) * to U+001F (US), or U+007F (DEL). * * @param {Code} code * Code. * @returns {boolean} * Whether it matches. */ function asciiControl(code) { return code !== null && (code < 32 || code === 127); } /** * Check whether the character code represents an ASCII digit (`0` through `9`). * * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to * U+0039 (`9`). * * @param code * Code. * @returns {boolean} * Whether it matches. */ const asciiDigit = regexCheck(/\d/); /** * Check whether the character code represents an ASCII hex digit (`a` through * `f`, case insensitive, or `0` through `9`). * * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex * digit, or an ASCII lower hex digit. * * An **ASCII upper hex digit** is a character in the inclusive range U+0041 * (`A`) to U+0046 (`F`). * * An **ASCII lower hex digit** is a character in the inclusive range U+0061 * (`a`) to U+0066 (`f`). * * @param code * Code. * @returns {boolean} * Whether it matches. */ const asciiHexDigit = regexCheck(/[\dA-Fa-f]/); /** * Check whether the character code represents ASCII punctuation. * * An **ASCII punctuation** is a character in the inclusive ranges U+0021 * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`). * * @param code * Code. * @returns {boolean} * Whether it matches. */ const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/); /** * Check whether a character code is a markdown line ending. * * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR). * * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE * RETURN (CR) are replaced by these virtual characters depending on whether * they occurred together. * * @param {Code} code * Code. * @returns {boolean} * Whether it matches. */ function markdownLineEnding(code) { return code !== null && code < -2; } /** * Check whether a character code is a markdown line ending (see * `markdownLineEnding`) or markdown space (see `markdownSpace`). * * @param {Code} code * Code. * @returns {boolean} * Whether it matches. */ function markdownLineEndingOrSpace(code) { return code !== null && (code < 0 || code === 32); } /** * Check whether a character code is a markdown space. * * A **markdown space** is the concrete character U+0020 SPACE (SP) and the * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT). * * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL * SPACE (VS) characters, depending on the column at which the tab occurred. * * @param {Code} code * Code. * @returns {boolean} * Whether it matches. */ function markdownSpace(code) { return code === -2 || code === -1 || code === 32; } /** * Check whether the character code represents Unicode punctuation. * * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation, * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf` * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po` * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII * punctuation (see `asciiPunctuation`). * * See: * **\[UNICODE]**: * [The Unicode Standard](https://www.unicode.org/versions/). * Unicode Consortium. * * @param code * Code. * @returns * Whether it matches. */ const unicodePunctuation = regexCheck(/\p{P}|\p{S}/u); /** * Check whether the character code represents Unicode whitespace. * * Note that this does handle micromark specific markdown whitespace characters. * See `markdownLineEndingOrSpace` to check that. * * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator, * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF), * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\[UNICODE]**). * * See: * **\[UNICODE]**: * [The Unicode Standard](https://www.unicode.org/versions/). * Unicode Consortium. * * @param code * Code. * @returns * Whether it matches. */ const unicodeWhitespace = regexCheck(/\s/); /** * Create a code check from a regex. * * @param {RegExp} regex * Expression. * @returns {(code: Code) => boolean} * Check. */ function regexCheck(regex) { return check; /** * Check whether a code matches the bound regex. * * @param {Code} code * Character code. * @returns {boolean} * Whether the character code matches the bound regex. */ function check(code) { return code !== null && code > -1 && regex.test(String.fromCharCode(code)); } } // node_modules/micromark-util-sanitize-uri/index.js /** * Normalize a URL. * * Encode unsafe characters with percent-encoding, skipping already encoded * sequences. * * @param {string} value * URI to normalize. * @returns {string} * Normalized URI. */ function normalizeUri(value) { /** @type {Array<string>} */ const result = []; let index = -1; let start = 0; let skip = 0; while (++index < value.length) { const code = value.charCodeAt(index); /** @type {string} */ let replace = ""; if (code === 37 && asciiAlphanumeric(value.charCodeAt(index + 1)) && asciiAlphanumeric(value.charCodeAt(index + 2))) skip = 2; else if (code < 128) { if (!/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(code))) replace = String.fromCharCode(code); } else if (code > 55295 && code < 57344) { const next = value.charCodeAt(index + 1); if (code < 56320 && next > 56319 && next < 57344) { replace = String.fromCharCode(code, next); skip = 1; } else replace = "�"; } else replace = String.fromCharCode(code); if (replace) { result.push(value.slice(start, index), encodeURIComponent(replace)); start = index + skip + 1; replace = ""; } if (skip) { index += skip; skip = 0; } } return result.join("") + value.slice(start); } // node_modules/micromark-factory-space/index.js /** * @import {Effects, State, TokenType} from 'micromark-util-types' */ /** * Parse spaces and tabs. * * There is no `nok` parameter: * * * spaces in markdown are often optional, in which case this factory can be * used and `ok` will be switched to whether spaces were found or not * * one line ending or space can be detected with `markdownSpace(code)` right * before using `factorySpace` * * ###### Examples * * Where `␉` represents a tab (plus how much it expands) and `␠` represents a * single space. * * ```markdown * ␉ * ␠␠␠␠ * ␉␠ * ``` * * @param {Effects} effects * Context. * @param {State} ok * State switched to when successful. * @param {TokenType} type * Type of the whole whitespace. * @param {number | undefined} [max=Infinity] * Max (exclusive). * @returns {State} * Start state. */ function factorySpace(effects, ok, type, max) { const limit = max ? max - 1 : 1e400; let size = 0; return start; /** @type {State} */ function start(code) { if (markdownSpace(code)) { effects.enter(type); return prefix(code); } return ok(code); } /** @type {State} */ function prefix(code) { if (markdownSpace(code) && size++ < limit) { effects.consume(code); return prefix; } effects.exit(type); return ok(code); } } /** * Parse spaces and tabs, with a required minimum and maximum, matching * `markdown-rs`’s `space_or_tab_min_max`. * * Unlike `factorySpace`, this can fail: `nok` is used when fewer than * `min` spaces or tabs are found. * * @param {Effects} effects * Context. * @param {State} ok * State switched to when successful. * @param {State} nok * State switched to when unsuccessful. * @param {TokenType} type * Type of the whole whitespace. * @param {number} min * Minimum allowed characters (inclusive). * @param {number} max * Maximum allowed characters (inclusive). * @returns {State} * Start state. */ function factorySpaceMinMax(effects, ok, nok, type, min, max) { let size = 0; return start; /** @type {State} */ function start(code) { if (max > 0 && markdownSpace(code)) { effects.enter(type); return prefix(code); } return after(code); } /** @type {State} */ function prefix(code) { if (markdownSpace(code) && size < max) { effects.consume(code); size++; return prefix; } effects.exit(type); return after(code); } /** @type {State} */ function after(code) { return size >= min ? ok(code) : nok(code); } } // node_modules/micromark/lib/initialize/content.js /** * @import { * InitialConstruct, * Initializer, * State, * TokenizeContext, * Token * } from 'micromark-util-types' */ /** @type {InitialConstruct} */ const content$1 = { tokenize: initializeContent }; /** * @this {TokenizeContext} * Context. * @type {Initializer} * Content. */ function initializeContent(effects) { const contentStart = effects.attempt(this.parser.constructs.contentInitial, afterContentStartConstruct, paragraphInitial); /** @type {Token} */ let previous; return contentStart; /** @type {State} */ function afterContentStartConstruct(code) { if (code === null) { effects.consume(code); return; } effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return factorySpace(effects, contentStart, "linePrefix"); } /** @type {State} */ function paragraphInitial(code) { effects.enter("paragraph"); return lineStart(code); } /** @type {State} */ function lineStart(code) { const token = effects.enter("chunkText", { contentType: "text", previous }); if (previous) previous.next = token; previous = token; return data(code); } /** @type {State} */ function data(code) { if (code === null) { effects.exit("chunkText"); effects.exit("paragraph"); effects.consume(code); return; } if (markdownLineEnding(code)) { effects.consume(code); effects.exit("chunkText"); return lineStart; } effects.consume(code); return data; } } // node_modules/micromark-util-edit-map/index.js /** * @import {Event} from 'micromark-util-types' */ /** * @typedef {[number, number, Array<Event>]} Change * @typedef {[number, number, number]} Jump */ /** * Tracks a bunch of edits. * * Port of `edit_map.rs` from `markdown-rs`: * <https://github.com/wooorm/markdown-rs/blob/1506572f/src/util/edit_map.rs>. * * Deal with several changes in events, batching them together. * * Preferably, changes should be kept to a minimum. * Sometimes, it’s needed to change the list of events, because parsing can be * messy, and it helps to expose a cleaner interface of events to the compiler * and other users. * It can also help to merge many adjacent similar events. * And, in other cases, it’s needed to parse subcontent: pass some events * through another tokenizer and inject the result. */ var EditMap$1 = class { /** * Create a new edit map. * * @returns * New instance. */ constructor() { /** * Changes by index, so `add` does not need to scan `map` (which is * quadratic for documents with many edits at different places). * * @type {Map<number, Change>} */ this.index = /* @__PURE__ */ new Map(); /** * Record of changes. * * @type {Array<Change>} */ this.map = []; } /** * Create an edit: a remove and/or add at a certain place. * * @param {number} index * Index at which to apply the edit. * @param {number} remove * Count of items to remove at the index. * @param {Array<Event>} add * Items to add at the index. * @returns {undefined} * Nothing. */ add(index, remove, add) { addImplementation$1(this, index, remove, add, false); } /** * Create an edit: but insert `add` before existing additions, instead of * after them. * * @param {number} index * Index at which to apply the edit. * @param {number} remove * Count of items to remove at the index. * @param {Array<Event>} add * Items to add at the index. * @returns {undefined} * Nothing. */ addBefore(index, remove, add) { addImplementation$1(this, index, remove, add, true); } /** * Done, change the events. * * @param {Array<Event>} events * List of events to apply the edits to. * @returns {undefined} * Nothing. */ consume(events) { this.map.sort(function(a, b) { return a[0] - b[0]; }); if (this.map.length === 0) return; let index = this.map.length; /** @type {Array<Array<Event>>} */ const vecs = []; while (index > 0) { index -= 1; vecs.push(events.slice(this.map[index][0] + this.map[index][1]), this.map[index][2]); events.length = this.map[index][0]; } vecs.push(events.slice()); events.length = 0; let slice = vecs.pop(); while (slice) { for (const element of slice) events.push(element); slice = vecs.pop(); } this.map.length = 0; this.index.clear(); } }; /** * Create an edit. * * @param {EditMap} editMap * Edit map to apply to. * @param {number} at * Index at which to apply the edit. * @param {number} remove * Count of items to remove at the index. * @param {Array<Event>} add * Items to add at the index. * @param {boolean} before * Insert `add` before existing additions at `at`, instead of after them. * @returns {undefined} * Nothing. */ function addImplementation$1(editMap, at, remove, add, before) { if (remove === 0 && add.length === 0) return; const existing = editMap.index.get(at); if (existing) { existing[1] += remove; if (before) { add.push(...existing[2]); existing[2] = add; } else existing[2].push(...add); return; } /** @type {Change} */ const change = [ at, remove, add ]; editMap.map.push(change); editMap.index.set(at, change); } // node_modules/micromark/lib/initialize/document.js /** * @import { * Construct, * ContainerState, * InitialConstruct, * Initializer, * Point, * State, * TokenizeContext, * Tokenizer, * Token * } from 'micromark-util-types' */ /** * @typedef {[Construct, ContainerState]} StackItem * Construct and its state. */ /** @type {InitialConstruct} */ const document$2 = { tokenize: initializeDocument }; /** @type {Construct} */ const containerConstruct = { tokenize: tokenizeContainer }; /** * @this {TokenizeContext} * Self. * @type {Initializer} * Initializer. */ function initializeDocument(effects) { const self = this; /** @type {Array<StackItem>} */ const stack = []; let continued = 0; /** @type {TokenizeContext | undefined} */ let childFlow; /** @type {Token | undefined} */ let childToken; /** @type {number} */ let lineStartOffset; return start; /** @type {State} */ function start(code) { if (continued < stack.length) { const item = stack[continued]; self.containerState = item[1]; return effects.attempt(item[0].continuation, documentContinue, checkNewContainers)(code); } return checkNewContainers(code); } /** @type {State} */ function documentContinue(code) { continued++; if (self.containerState._closeFlow) { self.containerState._closeFlow = void 0; if (childFlow) closeFlow(); const indexBeforeExits = self.events.length; let indexBeforeFlow = indexBeforeExits; /** @type {Point | undefined} */ let point; while (indexBeforeFlow--) if (self.events[indexBeforeFlow][0] === "exit" && self.events[indexBeforeFlow][1].type === "chunkFlow") { point = self.events[indexBeforeFlow][1].end; break; } exitContainers(continued); let index = indexBeforeExits; while (index < self.events.length) { self.events[index][1].end = { ...point }; index++; } const editMap = new EditMap$1(); editMap.add(indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits)); editMap.add(indexBeforeExits, index - indexBeforeExits, []); editMap.consume(self.events); return checkNewContainers(code); } return start(code); } /** @type {State} */ function checkNewContainers(code) { if (continued === stack.length) { if (!childFlow) return documentContinued(code); if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) return flowStart(code); self.interrupt = Boolean(childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack); } self.containerState = {}; return effects.check(containerConstruct, thereIsANewContainer, thereIsNoNewContainer)(code); } /** @type {State} */ function thereIsANewContainer(code) { if (childFlow) closeFlow(); exitContainers(continued); return documentContinued(code); } /** @type {State} */ function thereIsNoNewContainer(code) { self.parser.lazy[self.now().line] = continued !== stack.length; lineStartOffset = self.now().offset; return flowStart(code); } /** @type {State} */ function documentContinued(code) { self.containerState = {}; return effects.attempt(containerConstruct, containerContinue, flowStart)(code); } /** @type {State} */ function containerContinue(code) { continued++; stack.push([self.currentConstruct, self.containerState]); return documentContinued(code); } /** @type {State} */ function flowStart(code) { if (code === null) { if (childFlow) closeFlow(); exitContainers(0); effects.consume(code); return; } childFlow = childFlow || self.parser.flow(self.now()); effects.enter("chunkFlow", { _tokenizer: childFlow, contentType: "flow", previous: childToken }); return flowContinue(code); } /** @type {State} */ function flowContinue(code) { if (code === null) { writeToChild(effects.exit("chunkFlow"), true); exitContainers(0); effects.consume(code); return; } if (markdownLineEnding(code)) { effects.consume(code); writeToChild(effects.exit("chunkFlow")); continued = 0; self.interrupt = void 0; return start; } effects.consume(code); return flowContinue; } /** * @param {Token} token * Token. * @param {boolean | undefined} [endOfFile] * Whether the token is at the end of the file (default: `false`). * @returns {undefined} * Nothing. */ function writeToChild(token, endOfFile) { const stream = self.sliceStream(token); if (endOfFile) stream.push(null); token.previous = childToken; if (childToken) childToken.next = token; childToken = token; childFlow.defineSkip(token.start); childFlow.write(stream); if (self.parser.lazy[token.start.line]) { let index = childFlow.events.length; while (index--) if (childFlow.events[index][1].start.offset < lineStartOffset && (!childFlow.events[index][1].end || childFlow.events[index][1].end.offset > lineStartOffset)) return; const indexBeforeExits = self.events.length; let indexBeforeFlow = indexBeforeExits; /** @type {boolean | undefined} */ let seen; /** @type {Point | undefined} */ let point; while (indexBeforeFlow--) if (self.events[indexBeforeFlow][0] === "exit" && self.events[indexBeforeFlow][1].type === "chunkFlow") { if (seen) { point = self.events[indexBeforeFlow][1].end; break; } seen = true; } exitContainers(continued); index = indexBeforeExits; while (index < self.events.length) { self.events[index][1].end = { ...point }; index++; } const editMap = new EditMap$1(); editMap.add(indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits)); editMap.add(indexBeforeExits, index - indexBeforeExits, []); editMap.consume(self.events); } } /** * @param {number} size * Size. * @returns {undefined} * Nothing. */ function exitContainers(size) { let index = stack.length; while (index-- > size) { const entry = stack[index]; self.containerState = entry[1]; entry[0].exit.call(self, effects); } stack.length = size; } function closeFlow() { childFlow.write([null]); childToken = void 0; childFlow = void 0; self.containerState._closeFlow = void 0; } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} * Tokenizer. */ function tokenizeContainer(effects, ok, nok) { return factorySpace(effects, effects.attempt(this.parser.constructs.document, ok, nok), "linePrefix", this.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4); } // node_modules/micromark-util-classify-character/index.js /** * @import {Code} from 'micromark-util-types' */ /** * Classify whether a code represents whitespace, punctuation, or something * else. * * Used for attention (emphasis, strong), whose sequences can open or close * based on the class of surrounding characters. * * > 👉 **Note**: eof (`null`) is seen as whitespace. * * @param {Code} code * Code. * @returns {typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined} * Group. */ function classifyCharacter(code) { if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) return 1; if (unicodePunctuation(code)) return 2; } // node_modules/micromark-util-resolve-all/index.js /** * @import {Event, Resolver, TokenizeContext} from 'micromark-util-types' */ /** * Call all `resolveAll`s. * * @param {ReadonlyArray<{resolveAll?: Resolver | undefined}>} constructs * List of constructs, optionally with `resolveAll`s. * @param {Array<Event>} events * List of events. * @param {TokenizeContext} context * Context used by `tokenize`. * @returns {Array<Event>} * Changed events. */ function resolveAll(constructs, events, context) { /** @type {Array<Resolver>} */ const called = []; let index = -1; while (++index < constructs.length) { const resolve = constructs[index].resolveAll; if (resolve && !called.includes(resolve)) { events = resolve(events, context); called.push(resolve); } } return events; } // node_modules/micromark-core-commonmark/lib/attention.js /** * @import { * Code, * Construct, * Event, * Point, * Resolver, * State, * TokenizeContext, * Tokenizer, * Token * } from 'micromark-util-types' */ /** @type {Construct} */ const attention = { name: "attention", resolveAll: resolveAllAttention, tokenize: tokenizeAttention }; /** * Take all events and resolve attention to emphasis or strong. * * @type {Resolver} */ function resolveAllAttention(events, context) { let index = -1; /** @type {Array<Event>} */ let nextEvents; while (++index < events.length) if (events[index][0] === "enter" && events[index][1].type === "attentionSequence" && events[index][1]._close) { let open = index; while (open--) if (events[open][0] === "exit" && events[open][1].type === "attentionSequence" && events[open][1]._open && context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index][1]).charCodeAt(0)) { if ((events[open][1]._close || events[index][1]._open) && (events[index][1].end.offset - events[index][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index][1].end.offset - events[index][1].start.offset) % 3)) continue; const use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index][1].end.offset - events[index][1].start.offset > 1 ? 2 : 1; const start = { ...events[open][1].end }; const end = { ...events[index][1].start }; movePoint(start, -use); movePoint(end, use); const openingSequence = { type: use > 1 ? "strongSequence" : "emphasisSequence", start, end: { ...events[open][1].end } }; const closingSequence = { type: use > 1 ? "strongSequence" : "emphasisSequence", start: { ...events[index][1].start }, end }; const text = { type: use > 1 ? "strongText" : "emphasisText", start: { ...events[open][1].end }, end: { ...events[index][1].start } }; const group = { type: use > 1 ? "strong" : "emphasis", start: { ...openingSequence.start }, end: { ...closingSequence.end } }; events[open][1].end = { ...openingSequence.start }; events[index][1].start = { ...closingSequence.end }; nextEvents = []; if (events[open][1].end.offset - events[open][1].start.offset) nextEvents = push(nextEvents, [[ "enter", events[open][1], context ], [ "exit", events[open][1], context ]]); nextEvents = push(nextEvents, [ [ "enter", group, context ], [ "enter", openingSequence, context ], [ "exit", openingSequence, context ], [ "enter", text, context ] ]); nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + 1, index), context)); nextEvents = push(nextEvents, [ [ "exit", text, context ], [ "enter", closingSequence, context ], [ "exit", closingSequence, context ], [ "exit", group, context ] ]); /** @type {number} */ let offset = 0; if (events[index][1].end.offset - events[index][1].start.offset) { offset = 2; nextEvents = push(nextEvents, [[ "enter", events[index][1], context ], [ "exit", events[index][1], context ]]); } splice(events, open - 1, index - open + 3, nextEvents); index = open + nextEvents.length - offset - 2; break; } } index = -1; while (++index < events.length) if (events[index][1].type === "attentionSequence") events[index][1].type = "data"; return events; } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeAttention(effects, ok) { const attentionMarkers = this.parser.constructs.attentionMarkers.null; const previous = this.previous; const before = classifyCharacter(previous); /** @type {NonNullable<Code>} */ let marker; return start; /** * Before a sequence. * * ```markdown * > | ** * ^ * ``` * * @type {State} */ function start(code) { marker = code; effects.enter("attentionSequence"); return inside(code); } /** * In a sequence. * * ```markdown * > | ** * ^^ * ``` * * @type {State} */ function inside(code) { if (code === marker) { effects.consume(code); return inside; } const token = effects.exit("attentionSequence"); const after = classifyCharacter(code); const open = !after || after === 2 && before || attentionMarkers.includes(code) && code !== 42 && code !== 95; const close = !before || before === 2 && after || attentionMarkers.includes(previous) && previous !== 42 && previous !== 95; token._open = Boolean(marker === 42 ? open : open && (before || !close)); token._close = Boolean(marker === 42 ? close : close && (after || !open)); return ok(code); } } /** * Move a point a bit. * * Note: `move` only works inside lines! It’s not possible to move past other * chunks (replacement characters, tabs, or line endings). * * @param {Point} point * Point. * @param {number} offset * Amount to move. * @returns {undefined} * Nothing. */ function movePoint(point, offset) { point.column += offset; point.offset += offset; point._bufferIndex += offset; } // node_modules/micromark-core-commonmark/lib/autolink.js /** * @import { * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const autolink = { name: "autolink", tokenize: tokenizeAutolink }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeAutolink(effects, ok, nok) { let size = 0; return start; /** * Start of an autolink. * * ```markdown * > | a<https://example.com>b * ^ * > | a<user@example.com>b * ^ * ``` * * @type {State} */ function start(code) { effects.enter("autolink"); effects.enter("autolinkMarker"); effects.consume(code); effects.exit("autolinkMarker"); effects.enter("autolinkProtocol"); return open; } /** * After `<`, at protocol or atext. * * ```markdown * > | a<https://example.com>b * ^ * > | a<user@example.com>b * ^ * ``` * * @type {State} */ function open(code) { if (asciiAlpha(code)) { effects.consume(code); return schemeOrEmailAtext; } if (code === 64) return nok(code); return emailAtext(code); } /** * At second byte of protocol or atext. * * ```markdown * > | a<https://example.com>b * ^ * > | a<user@example.com>b * ^ * ``` * * @type {State} */ function schemeOrEmailAtext(code) { if (code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) { size = 1; return schemeInsideOrEmailAtext(code); } return emailAtext(code); } /** * In ambiguous protocol or atext. * * ```markdown * > | a<https://example.com>b * ^ * > | a<user@example.com>b * ^ * ``` * * @type {State} */ function schemeInsideOrEmailAtext(code) { if (code === 58) { effects.consume(code); size = 0; return urlInside; } if ((code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) && size++ < 32) { effects.consume(code); return schemeInsideOrEmailAtext; } size = 0; return emailAtext(code); } /** * After protocol, in URL. * * ```markdown * > | a<https://example.com>b * ^ * ``` * * @type {State} */ function urlInside(code) { if (code === 62) { effects.exit("autolinkProtocol"); effects.enter("autolinkMarker"); effects.consume(code); effects.exit("autolinkMarker"); effects.exit("autolink"); return ok; } if (code === null || code === 32 || code === 60 || asciiControl(code)) return nok(code); effects.consume(code); return urlInside; } /** * In email atext. * * ```markdown * > | a<user.name@example.com>b * ^ * ``` * * @type {State} */ function emailAtext(code) { if (code === 64) { effects.consume(code); return emailAtSignOrDot; } if (asciiAtext(code)) { effects.consume(code); return emailAtext; } return nok(code); } /** * In label, after at-sign or dot. * * ```markdown * > | a<user.name@example.com>b * ^ ^ * ``` * * @type {State} */ function emailAtSignOrDot(code) { return asciiAlphanumeric(code) ? emailLabel(code) : nok(code); } /** * In label, where `.` and `>` are allowed. * * ```markdown * > | a<user.name@example.com>b * ^ * ``` * * @type {State} */ function emailLabel(code) { if (code === 46) { effects.consume(code); size = 0; return emailAtSignOrDot; } if (code === 62) { effects.exit("autolinkProtocol").type = "autolinkEmail"; effects.enter("autolinkMarker"); effects.consume(code); effects.exit("autolinkMarker"); effects.exit("autolink"); return ok; } return emailValue(code); } /** * In label, where `.` and `>` are *not* allowed. * * Though, this is also used in `emailLabel` to parse other values. * * ```markdown * > | a<user.name@ex-ample.com>b * ^ * ``` * * @type {State} */ function emailValue(code) { if ((code === 45 || asciiAlphanumeric(code)) && size++ < 63) { const next = code === 45 ? emailValue : emailLabel; effects.consume(code); return next; } return nok(code); } } // node_modules/micromark-core-commonmark/lib/blank-line.js /** * @import { * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const blankLine = { partial: true, tokenize: tokenizeBlankLine }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeBlankLine(effects, ok, nok) { return start; /** * Start of blank line. * * > 👉 **Note**: `␠` represents a space character. * * ```markdown * > | ␠␠␊ * ^ * > | ␊ * ^ * ``` * * @type {State} */ function start(code) { return markdownSpace(code) ? factorySpace(effects, after, "linePrefix")(code) : after(code); } /** * At eof/eol, after optional whitespace. * * > 👉 **Note**: `␠` represents a space character. * * ```markdown * > | ␠␠␊ * ^ * > | ␊ * ^ * ``` * * @type {State} */ function after(code) { return code === null || markdownLineEnding(code) ? ok(code) : nok(code); } } // node_modules/micromark-core-commonmark/lib/block-quote.js /** * @import { * Construct, * Exiter, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const blockQuote = { continuation: { tokenize: tokenizeBlockQuoteContinuation }, exit: exit$1, name: "blockQuote", tokenize: tokenizeBlockQuoteStart }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeBlockQuoteStart(effects, ok, nok) { const self = this; return start; /** * Start of block quote. * * ```markdown * > | > a * ^ * ``` * * @type {State} */ function start(code) { if (code === 62) { const state = self.containerState; if (!state.open) { effects.enter("blockQuote", { _container: true }); state.open = true; } effects.enter("blockQuotePrefix"); effects.enter("blockQuoteMarker"); effects.consume(code); effects.exit("blockQuoteMarker"); return after; } return nok(code); } /** * After `>`, before optional whitespace. * * ```markdown * > | > a * ^ * ``` * * @type {State} */ function after(code) { if (markdownSpace(code)) { effects.enter("blockQuotePrefixWhitespace"); effects.consume(code); effects.exit("blockQuotePrefixWhitespace"); effects.exit("blockQuotePrefix"); return ok; } effects.exit("blockQuotePrefix"); return ok(code); } } /** * Start of block quote continuation. * * ```markdown * | > a * > | > b * ^ * ``` * * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeBlockQuoteContinuation(effects, ok, nok) { const self = this; return contStart; /** * Start of block quote continuation. * * Also used to parse the first block quote opening. * * ```markdown * | > a * > | > b * ^ * ``` * * @type {State} */ function contStart(code) { if (markdownSpace(code)) return factorySpace(effects, contBefore, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code); return contBefore(code); } /** * At `>`, after optional whitespace. * * Also used to parse the first block quote opening. * * ```markdown * | > a * > | > b * ^ * ``` * * @type {State} */ function contBefore(code) { return effects.attempt(blockQuote, ok, nok)(code); } } /** @type {Exiter} */ function exit$1(effects) { effects.exit("blockQuote"); } // node_modules/micromark-core-commonmark/lib/character-escape.js /** * @import { * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const characterEscape = { name: "characterEscape", tokenize: tokenizeCharacterEscape }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeCharacterEscape(effects, ok, nok) { return start; /** * Start of character escape. * * ```markdown * > | a\*b * ^ * ``` * * @type {State} */ function start(code) { effects.enter("characterEscape"); effects.enter("escapeMarker"); effects.consume(code); effects.exit("escapeMarker"); return inside; } /** * After `\`, at punctuation. * * ```markdown * > | a\*b * ^ * ``` * * @type {State} */ function inside(code) { if (asciiPunctuation(code)) { effects.enter("characterEscapeValue"); effects.consume(code); effects.exit("characterEscapeValue"); effects.exit("characterEscape"); return ok; } return nok(code); } } // node_modules/micromark-core-commonmark/lib/character-reference.js /** * @import { * Code, * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const characterReference = { name: "characterReference", tokenize: tokenizeCharacterReference }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeCharacterReference(effects, ok, nok) { const self = this; let size = 0; /** @type {number} */ let max; /** @type {(code: Code) => boolean} */ let test; return start; /** * Start of character reference. * * ```markdown * > | a&b * ^ * > | a{b * ^ * > | a b * ^ * ``` * * @type {State} */ function start(code) { effects.enter("characterReference"); effects.enter("characterReferenceMarker"); effects.consume(code); effects.exit("characterReferenceMarker"); return open; } /** * After `&`, at `#` for numeric references or alphanumeric for named * references. * * ```markdown * > | a&b * ^ * > | a{b * ^ * > | a b * ^ * ``` * * @type {State} */ function open(code) { if (code === 35) { effects.enter("characterReferenceMarkerNumeric"); effects.consume(code); effects.exit("characterReferenceMarkerNumeric"); return numeric; } effects.enter("characterReferenceValue"); max = 31; test = asciiAlphanumeric; return value(code); } /** * After `#`, at `x` for hexadecimals or digit for decimals. * * ```markdown * > | a{b * ^ * > | a b * ^ * ``` * * @type {State} */ function numeric(code) { if (code === 88 || code === 120) { effects.enter("characterReferenceMarkerHexadecimal"); effects.consume(code); effects.exit("characterReferenceMarkerHexadecimal"); effects.enter("characterReferenceValue"); max = 6; test = asciiHexDigit; return value; } effects.enter("characterReferenceValue"); max = 7; test = asciiDigit; return value(code); } /** * After markers (`&#x`, `&#`, or `&`), in value, before `;`. * * The character reference kind defines what and how many characters are * allowed. * * ```markdown * > | a&b * ^^^ * > | a{b * ^^^ * > | a b * ^ * ``` * * @type {State} */ function value(code) { if (code === 59 && size) { const token = effects.exit("characterReferenceValue"); if (test === asciiAlphanumeric && !decodeNamedCharacterReference(self.sliceSerialize(token))) return nok(code); effects.enter("characterReferenceMarker"); effects.consume(code); effects.exit("characterReferenceMarker"); effects.exit("characterReference"); return ok; } if (test(code) && size++ < max) { effects.consume(code); return value; } return nok(code); } } // node_modules/micromark-core-commonmark/lib/partial-non-lazy-continuation.js /** @type {Construct} */ const nonLazyContinuation$2 = { partial: true, tokenize: tokenizeNonLazyContinuation$2 }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeNonLazyContinuation$2(effects, ok, nok) { const self = this; return start; /** * At eol, before continuation. * * ```markdown * > | * ```js * ^ * | b * ``` * * @type {State} */ function start(code) { if (code === null) return nok(code); effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return after; } /** * A continuation. * * ```markdown * | * ```js * > | b * ^ * ``` * * @type {State} */ function after(code) { return self.parser.lazy[self.now().line] ? nok(code) : ok(code); } } // node_modules/micromark-core-commonmark/lib/code-fenced.js /** * @import { * Code, * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const codeFenced = { concrete: true, name: "codeFenced", tokenize: tokenizeCodeFenced }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeCodeFenced(effects, ok, nok) { const self = this; /** @type {Construct} */ const closeStart = { partial: true, tokenize: tokenizeCloseStart }; let initialPrefix = 0; let sizeOpen = 0; /** @type {NonNullable<Code>} */ let marker; return start; /** * Start of code. * * ```markdown * > | ~~~js * ^ * | alert(1) * | ~~~ * ``` * * @type {State} */ function start(code) { return beforeSequenceOpen(code); } /** * In opening fence, after prefix, at sequence. * * ```markdown * > | ~~~js * ^ * | alert(1) * | ~~~ * ``` * * @type {State} */ function beforeSequenceOpen(code) { const tail = self.events[self.events.length - 1]; initialPrefix = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0; marker = code; effects.enter("codeFenced"); effects.enter("codeFencedFence"); effects.enter("codeFencedFenceSequence"); return sequenceOpen(code); } /** * In opening fence sequence. * * ```markdown * > | ~~~js * ^ * | alert(1) * | ~~~ * ``` * * @type {State} */ function sequenceOpen(code) { if (code === marker) { sizeOpen++; effects.consume(code); return sequenceOpen; } if (sizeOpen < 3) return nok(code); effects.exit("codeFencedFenceSequence"); return markdownSpace(code) ? factorySpace(effects, infoBefore, "whitespace")(code) : infoBefore(code); } /** * In opening fence, after the sequence (and optional whitespace), before info. * * ```markdown * > | ~~~js * ^ * | alert(1) * | ~~~ * ``` * * @type {State} */ function infoBefore(code) { if (code === null || markdownLineEnding(code)) { effects.exit("codeFencedFence"); return self.interrupt ? ok(code) : effects.check(nonLazyContinuation$2, atNonLazyBreak, after)(code); } effects.enter("codeFencedFenceInfo"); effects.enter("chunkString", { contentType: "string" }); return info(code); } /** * In info. * * ```markdown * > | ~~~js * ^ * | alert(1) * | ~~~ * ``` * * @type {State} */ function info(code) { if (code === null || markdownLineEnding(code)) { effects.exit("chunkString"); effects.exit("codeFencedFenceInfo"); return infoBefore(code); } if (markdownSpace(code)) { effects.exit("chunkString"); effects.exit("codeFencedFenceInfo"); return factorySpace(effects, metaBefore, "whitespace")(code); } if (code === 96 && code === marker) return nok(code); effects.consume(code); return info; } /** * In opening fence, after info and whitespace, before meta. * * ```markdown * > | ~~~js eval * ^ * | alert(1) * | ~~~ * ``` * * @type {State} */ function metaBefore(code) { if (code === null || markdownLineEnding(code)) return infoBefore(code); effects.enter("codeFencedFenceMeta"); effects.enter("chunkString", { contentType: "string" }); return meta(code); } /** * In meta. * * ```markdown * > | ~~~js eval * ^ * | alert(1) * | ~~~ * ``` * * @type {State} */ function meta(code) { if (code === null || markdownLineEnding(code)) { effects.exit("chunkString"); effects.exit("codeFencedFenceMeta"); return infoBefore(code); } if (code === 96 && code === marker) return nok(code); effects.consume(code); return meta; } /** * At eol/eof in code, before a non-lazy closing fence or content. * * ```markdown * > | ~~~js * ^ * > | alert(1) * ^ * | ~~~ * ``` * * @type {State} */ function atNonLazyBreak(code) { return effects.attempt(closeStart, after, contentBefore)(code); } /** * Before code content, not a closing fence, at eol. * * ```markdown * | ~~~js * > | alert(1) * ^ * | ~~~ * ``` * * @type {State} */ function contentBefore(code) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return contentStart; } /** * Before code content, not a closing fence. * * ```markdown * | ~~~js * > | alert(1) * ^ * | ~~~ * ``` * * @type {State} */ function contentStart(code) { return initialPrefix > 0 && markdownSpace(code) ? factorySpace(effects, beforeContentChunk, "linePrefix", initialPrefix + 1)(code) : beforeContentChunk(code); } /** * Before code content, after optional prefix. * * ```markdown * | ~~~js * > | alert(1) * ^ * | ~~~ * ``` * * @type {State} */ function beforeContentChunk(code) { if (code === null || markdownLineEnding(code)) return effects.check(nonLazyContinuation$2, atNonLazyBreak, after)(code); effects.enter("codeFlowValue"); return contentChunk(code); } /** * In code content. * * ```markdown * | ~~~js * > | alert(1) * ^^^^^^^^ * | ~~~ * ``` * * @type {State} */ function contentChunk(code) { if (code === null || markdownLineEnding(code)) { effects.exit("codeFlowValue"); return beforeContentChunk(code); } effects.consume(code); return contentChunk; } /** * After code. * * ```markdown * | ~~~js * | alert(1) * > | ~~~ * ^ * ``` * * @type {State} */ function after(code) { effects.exit("codeFenced"); return ok(code); } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeCloseStart(effects, ok, nok) { let size = 0; return startBefore; /** * * * @type {State} */ function startBefore(code) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return start; } /** * Before closing fence, at optional whitespace. * * ```markdown * | ~~~js * | alert(1) * > | ~~~ * ^ * ``` * * @type {State} */ function start(code) { effects.enter("codeFencedFence"); return markdownSpace(code) ? factorySpace(effects, beforeSequenceClose, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code) : beforeSequenceClose(code); } /** * In closing fence, after optional whitespace, at sequence. * * ```markdown * | ~~~js * | alert(1) * > | ~~~ * ^ * ``` * * @type {State} */ function beforeSequenceClose(code) { if (code === marker) { effects.enter("codeFencedFenceSequence"); return sequenceClose(code); } return nok(code); } /** * In closing fence sequence. * * ```markdown * | ~~~js * | alert(1) * > | ~~~ * ^ * ``` * * @type {State} */ function sequenceClose(code) { if (code === marker) { size++; effects.consume(code); return sequenceClose; } if (size >= sizeOpen) { effects.exit("codeFencedFenceSequence"); return markdownSpace(code) ? factorySpace(effects, sequenceCloseAfter, "whitespace")(code) : sequenceCloseAfter(code); } return nok(code); } /** * After closing fence sequence, after optional whitespace. * * ```markdown * | ~~~js * | alert(1) * > | ~~~ * ^ * ``` * * @type {State} */ function sequenceCloseAfter(code) { if (code === null || markdownLineEnding(code)) { effects.exit("codeFencedFence"); return ok(code); } return nok(code); } } } // node_modules/micromark-core-commonmark/lib/code-indented.js /** * @import { * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const codeIndented = { name: "codeIndented", tokenize: tokenizeCodeIndented }; /** @type {Construct} */ const furtherStart = { partial: true, tokenize: tokenizeFurtherStart }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeCodeIndented(effects, ok, nok) { return start; /** * Start of code (indented). * * > **Parsing note**: it is not needed to check if this first line is a * > filled line (that it has a non-whitespace character), because blank lines * > are parsed already, so we never run into that. * * ```markdown * > | aaa * ^ * ``` * * @type {State} */ function start(code) { effects.enter("codeIndented"); return factorySpaceMinMax(effects, atBreak, nok, "linePrefix", 4, 4)(code); } /** * At a break. * * ```markdown * > | aaa * ^ ^ * ``` * * @type {State} */ function atBreak(code) { if (code === null) return after(code); if (markdownLineEnding(code)) return effects.attempt(furtherStart, atBreak, after)(code); effects.enter("codeFlowValue"); return inside(code); } /** * In code content. * * ```markdown * > | aaa * ^^^^ * ``` * * @type {State} */ function inside(code) { if (code === null || markdownLineEnding(code)) { effects.exit("codeFlowValue"); return atBreak(code); } effects.consume(code); return inside; } /** @type {State} */ function after(code) { effects.exit("codeIndented"); return ok(code); } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeFurtherStart(effects, ok, nok) { const self = this; return furtherStart; /** * At eol, trying to parse another indent. * * ```markdown * > | aaa * ^ * | bbb * ``` * * @type {State} */ function furtherStart(code) { if (self.parser.lazy[self.now().line]) return nok(code); if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return furtherStart; } return factorySpaceMinMax(effects, ok, onNotEnoughPrefix, "linePrefix", 4, 4)(code); } /** * After not enough of a prefix. * * A following line ending is another (potentially blank) line to try, * anything else means this isn’t a continuation. * * ```markdown * > | aaa * * | bbb * ``` * * @type {State} */ function onNotEnoughPrefix(code) { return markdownLineEnding(code) ? furtherStart(code) : nok(code); } } // node_modules/micromark-core-commonmark/lib/code-text.js /** * @import { * Construct, * Previous, * Resolver, * State, * TokenizeContext, * Tokenizer, * Token * } from 'micromark-util-types' */ /** @type {Construct} */ const codeText = { name: "codeText", previous: previous$2, resolve: resolveCodeText, tokenize: tokenizeCodeText }; /** @type {Resolver} */ function resolveCodeText(events) { let tailExitIndex = events.length - 4; let headEnterIndex = 3; /** @type {number} */ let index; /** @type {number | undefined} */ let enter; if ((events[headEnterIndex][1].type === "lineEnding" || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === "lineEnding" || events[tailExitIndex][1].type === "space")) { index = headEnterIndex; while (++index < tailExitIndex) if (events[index][1].type === "codeTextData") { events[headEnterIndex][1].type = "codeTextPadding"; events[tailExitIndex][1].type = "codeTextPadding"; headEnterIndex += 2; tailExitIndex -= 2; break; } } index = headEnterIndex - 1; tailExitIndex++; while (++index <= tailExitIndex) if (enter === void 0) { if (index !== tailExitIndex && events[index][1].type !== "lineEnding") enter = index; } else if (index === tailExitIndex || events[index][1].type === "lineEnding") { events[enter][1].type = "codeTextData"; if (index !== enter + 2) { events[enter][1].end = events[index - 1][1].end; events.splice(enter + 2, index - enter - 2); tailExitIndex -= index - enter - 2; index = enter + 2; } enter = void 0; } return events; } /** * @this {TokenizeContext} * Context. * @type {Previous} */ function previous$2(code) { return code !== 96 || this.events[this.events.length - 1][1].type === "characterEscape"; } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeCodeText(effects, ok, nok) { let sizeOpen = 0; /** @type {number} */ let size; /** @type {Token} */ let token; return start; /** * Start of code (text). * * ```markdown * > | `a` * ^ * > | \`a` * ^ * ``` * * @type {State} */ function start(code) { effects.enter("codeText"); effects.enter("codeTextSequence"); return sequenceOpen(code); } /** * In opening sequence. * * ```markdown * > | `a` * ^ * ``` * * @type {State} */ function sequenceOpen(code) { if (code === 96) { effects.consume(code); sizeOpen++; return sequenceOpen; } effects.exit("codeTextSequence"); return between(code); } /** * Between something and something else. * * ```markdown * > | `a` * ^^ * ``` * * @type {State} */ function between(code) { if (code === null) return nok(code); if (code === 32) { effects.enter("space"); effects.consume(code); effects.exit("space"); return between; } if (code === 96) { token = effects.enter("codeTextSequence"); size = 0; return sequenceClose(code); } if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return between; } effects.enter("codeTextData"); return data(code); } /** * In data. * * ```markdown * > | `a` * ^ * ``` * * @type {State} */ function data(code) { if (code === null || code === 32 || code === 96 || markdownLineEnding(code)) { effects.exit("codeTextData"); return between(code); } effects.consume(code); return data; } /** * In closing sequence. * * ```markdown * > | `a` * ^ * ``` * * @type {State} */ function sequenceClose(code) { if (code === 96) { effects.consume(code); size++; return sequenceClose; } if (size === sizeOpen) { effects.exit("codeTextSequence"); effects.exit("codeText"); return ok(code); } token.type = "codeTextData"; return data(code); } } // node_modules/micromark-util-subtokenize/lib/splice-buffer.js /** * Some of the internal operations of micromark do lots of editing * operations on very large arrays. This runs into problems with two * properties of most circa-2020 JavaScript interpreters: * * - Array-length modifications at the high end of an array (push/pop) are * expected to be common and are implemented in (amortized) time * proportional to the number of elements added or removed, whereas * other operations (shift/unshift and splice) are much less efficient. * - Function arguments are passed on the stack, so adding tens of thousands * of elements to an array with `arr.push(...newElements)` will frequently * cause stack overflows. (see <https://stackoverflow.com/questions/22123769/rangeerror-maximum-call-stack-size-exceeded-why>) * * SpliceBuffers are an implementation of gap buffers, which are a * generalization of the "queue made of two stacks" idea. The splice buffer * maintains a cursor, and moving the cursor has cost proportional to the * distance the cursor moves, but inserting, deleting, or splicing in * new information at the cursor is as efficient as the push/pop operation. * This allows for an efficient sequence of splices (or pushes, pops, shifts, * or unshifts) as long such edits happen at the same part of the array or * generally sweep through the array from the beginning to the end. * * The interface for splice buffers also supports large numbers of inputs by * passing a single array argument rather passing multiple arguments on the * function call stack. * * @template T * Item type. */ var SpliceBuffer = class { /** * @param {ReadonlyArray<T> | null | undefined} [initial] * Initial items (optional). * @returns * Splice buffer. */ constructor(initial) { /** @type {Array<T>} */ this.left = initial ? [...initial] : []; /** @type {Array<T>} */ this.right = []; } /** * Array access; * does not move the cursor. * * @param {number} index * Index. * @return {T} * Item. */ get(index) { if (index < 0 || index >= this.left.length + this.right.length) throw new RangeError("Cannot access index `" + index + "` in a splice buffer of size `" + (this.left.length + this.right.length) + "`"); if (index < this.left.length) return this.left[index]; return this.right[this.right.length - index + this.left.length - 1]; } /** * The length of the splice buffer, one greater than the largest index in the * array. */ get length() { return this.left.length + this.right.length; } /** * Remove and return `list[0]`; * moves the cursor to `0`. * * @returns {T | undefined} * Item, optional. */ shift() { this.setCursor(0); return this.right.pop(); } /** * Slice the buffer to get an array; * does not move the cursor. * * @param {number} start * Start. * @param {number | null | undefined} [end] * End (optional). * @returns {Array<T>} * Array of items. */ slice(start, end) { /** @type {number} */ const stop = end === null || end === void 0 ? Number.POSITIVE_INFINITY : end; if (stop < this.left.length) return this.left.slice(start, stop); if (start > this.left.length) return this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse(); return this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse()); } /** * Mimics the behavior of Array.prototype.splice() except for the change of * interface necessary to avoid segfaults when patching in very large arrays. * * This operation moves cursor is moved to `start` and results in the cursor * placed after any inserted items. * * @param {number} start * Start; * zero-based index at which to start changing the array; * negative numbers count backwards from the end of the array and values * that are out-of bounds are clamped to the appropriate end of the array. * @param {number | null | undefined} [deleteCount=0] * Delete count (default: `0`); * maximum number of elements to delete, starting from start. * @param {Array<T> | null | undefined} [items=[]] * Items to include in place of the deleted items (default: `[]`). * @return {Array<T>} * Any removed items. */ splice(start, deleteCount, items) { /** @type {number} */ const count = deleteCount || 0; this.setCursor(Math.trunc(start)); const removed = this.right.splice(this.right.length - count, Number.POSITIVE_INFINITY); if (items) chunkedPush(this.left, items); return removed.reverse(); } /** * Remove and return the highest-numbered item in the array, so * `list[list.length - 1]`; * Moves the cursor to `length`. * * @returns {T | undefined} * Item, optional. */ pop() { this.setCursor(Number.POSITIVE_INFINITY); return this.left.pop(); } /** * Inserts a single item to the high-numbered side of the array; * moves the cursor to `length`. * * @param {T} item * Item. * @returns {undefined} * Nothing. */ push(item) { this.setCursor(Number.POSITIVE_INFINITY); this.left.push(item); } /** * Inserts many items to the high-numbered side of the array. * Moves the cursor to `length`. * * @param {Array<T>} items * Items. * @returns {undefined} * Nothing. */ pushMany(items) { this.setCursor(Number.POSITIVE_INFINITY); chunkedPush(this.left, items); } /** * Inserts a single item to the low-numbered side of the array; * Moves the cursor to `0`. * * @param {T} item * Item. * @returns {undefined} * Nothing. */ unshift(item) { this.setCursor(0); this.right.push(item); } /** * Inserts many items to the low-numbered side of the array; * moves the cursor to `0`. * * @param {Array<T>} items * Items. * @returns {undefined} * Nothing. */ unshiftMany(items) { this.setCursor(0); chunkedPush(this.right, items.reverse()); } /** * Move the cursor to a specific position in the array. Requires * time proportional to the distance moved. * * If `n < 0`, the cursor will end up at the beginning. * If `n > length`, the cursor will end up at the end. * * @param {number} n * Position. * @return {undefined} * Nothing. */ setCursor(n) { if (n === this.left.length || n > this.left.length && this.right.length === 0 || n < 0 && this.left.length === 0) return; if (n < this.left.length) { const removed = this.left.splice(n, Number.POSITIVE_INFINITY); chunkedPush(this.right, removed.reverse()); } else { const removed = this.right.splice(this.left.length + this.right.length - n, Number.POSITIVE_INFINITY); chunkedPush(this.left, removed.reverse()); } } }; /** * Avoid stack overflow by pushing items onto the stack in segments * * @template T * Item type. * @param {Array<T>} list * List to inject into. * @param {ReadonlyArray<T>} right * Items to inject. * @return {undefined} * Nothing. */ function chunkedPush(list, right) { /** @type {number} */ let chunkStart = 0; if (right.length < 1e4) list.push(...right); else while (chunkStart < right.length) { list.push(...right.slice(chunkStart, chunkStart + 1e4)); chunkStart += 1e4; } } // node_modules/micromark-util-subtokenize/index.js /** * @import {Chunk, Event, Token} from 'micromark-util-types' */ /** * Tokenize subcontent. * * @param {Array<Event>} eventsArray * List of events. * @returns {boolean} * Whether subtokens were found. */ function subtokenize(eventsArray) { /** @type {Record<string, number>} */ const jumps = {}; let index = -1; /** @type {Event} */ let event; /** @type {number | undefined} */ let lineIndex; /** @type {number} */ let otherIndex; /** @type {Event} */ let otherEvent; /** @type {Array<Event>} */ let parameters; /** @type {Array<Event>} */ let subevents; /** @type {boolean | undefined} */ let more; const events = new SpliceBuffer(eventsArray); while (++index < events.length) { while (index in jumps) index = jumps[index]; event = events.get(index); if (index && event[1].type === "chunkFlow" && events.get(index - 1)[1].type === "listItemPrefix") { subevents = event[1]._tokenizer.events; otherIndex = 0; if (otherIndex < subevents.length && subevents[otherIndex][1].type === "lineEndingBlank") otherIndex += 2; if (otherIndex < subevents.length && subevents[otherIndex][1].type === "content") while (++otherIndex < subevents.length) { if (subevents[otherIndex][1].type === "content") break; if (subevents[otherIndex][1].type === "chunkText") { subevents[otherIndex][1]._isInFirstContentOfListItem = true; otherIndex++; } } } if (event[0] === "enter") { if (event[1].contentType) { Object.assign(jumps, subcontent(events, index)); index = jumps[index]; more = true; } } else if (event[1]._container) { otherIndex = index; lineIndex = void 0; while (otherIndex--) { otherEvent = events.get(otherIndex); if (otherEvent[1].type === "lineEnding" || otherEvent[1].type === "lineEndingBlank") { if (otherEvent[0] === "enter") { if (lineIndex) events.get(lineIndex)[1].type = "lineEndingBlank"; otherEvent[1].type = "lineEnding"; lineIndex = otherIndex; } } else if (otherEvent[1].type === "linePrefix" || otherEvent[1].type === "listItemIndent") {} else break; } if (lineIndex) { event[1].end = { ...events.get(lineIndex)[1].start }; parameters = events.slice(lineIndex, index); parameters.unshift(event); events.splice(lineIndex, index - lineIndex + 1, parameters); } } } splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0)); return !more; } /** * Tokenize embedded tokens. * * @param {SpliceBuffer<Event>} events * Events. * @param {number} eventIndex * Index. * @returns {Record<string, number>} * Gaps. */ function subcontent(events, eventIndex) { const token = events.get(eventIndex)[1]; const context = events.get(eventIndex)[2]; let startPosition = eventIndex - 1; /** @type {Array<number>} */ const startPositions = []; let tokenizer = token._tokenizer; if (!tokenizer) { tokenizer = context.parser[token.contentType](token.start); if (token._contentTypeTextTrailing) tokenizer._contentTypeTextTrailing = true; } const childEvents = tokenizer.events; /** @type {Array<[number, number]>} */ const jumps = []; /** @type {Record<string, number>} */ const gaps = {}; /** @type {Array<Chunk>} */ let stream; /** @type {Token | undefined} */ let previous; let index = -1; /** @type {Token | undefined} */ let current = token; let adjust = 0; let start = 0; const breaks = [start]; while (current) { while (events.get(++startPosition)[1] !== current); startPositions.push(startPosition); if (!current._tokenizer) { stream = context.sliceStream(current); if (!current.next) stream.push(null); if (previous) tokenizer.defineSkip(current.start); if (current._isInFirstContentOfListItem) tokenizer._gfmTasklistFirstContentOfListItem = true; tokenizer.write(stream); if (current._isInFirstContentOfListItem) tokenizer._gfmTasklistFirstContentOfListItem = void 0; } previous = current; current = current.next; } current = token; while (++index < childEvents.length) if (childEvents[index][0] === "exit" && childEvents[index - 1][0] === "enter" && childEvents[index][1].type === childEvents[index - 1][1].type && childEvents[index][1].start.line !== childEvents[index][1].end.line) { start = index + 1; breaks.push(start); current._tokenizer = void 0; current.previous = void 0; current = current.next; } tokenizer.events = []; if (current) { current._tokenizer = void 0; current.previous = void 0; } else breaks.pop(); index = breaks.length; while (index--) { const slice = childEvents.slice(breaks[index], breaks[index + 1]); const start = startPositions.pop(); jumps.push([start, start + slice.length - 1]); events.splice(start, 2, slice); } jumps.reverse(); index = -1; while (++index < jumps.length) { gaps[adjust + jumps[index][0]] = adjust + jumps[index][1]; adjust += jumps[index][1] - jumps[index][0] - 1; } return gaps; } // node_modules/micromark-core-commonmark/lib/content.js /** * @import { * Construct, * Resolver, * State, * TokenizeContext, * Tokenizer, * Token * } from 'micromark-util-types' */ /** * No name because it must not be turned off. * @type {Construct} */ const content = { resolve: resolveContent, tokenize: tokenizeContent }; /** @type {Construct} */ const continuationConstruct = { partial: true, tokenize: tokenizeContinuation }; /** * Content is transparent: it’s parsed right now. That way, definitions are also * parsed right now: before text in paragraphs (specifically, media) are parsed. * * @type {Resolver} */ function resolveContent(events) { subtokenize(events); return events; } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeContent(effects, ok) { /** @type {Token | undefined} */ let previous; return chunkStart; /** * Before a content chunk. * * ```markdown * > | abc * ^ * ``` * * @type {State} */ function chunkStart(code) { effects.enter("content"); previous = effects.enter("chunkContent", { contentType: "content" }); return chunkInside(code); } /** * In a content chunk. * * ```markdown * > | abc * ^^^ * ``` * * @type {State} */ function chunkInside(code) { if (code === null) return contentEnd(code); if (markdownLineEnding(code)) return effects.check(continuationConstruct, contentContinue, contentEnd)(code); effects.consume(code); return chunkInside; } /** * * * @type {State} */ function contentEnd(code) { effects.exit("chunkContent"); effects.exit("content"); return ok(code); } /** * * * @type {State} */ function contentContinue(code) { effects.consume(code); effects.exit("chunkContent"); previous.next = effects.enter("chunkContent", { contentType: "content", previous }); previous = previous.next; return chunkInside; } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeContinuation(effects, ok, nok) { const self = this; return startLookahead; /** * * * @type {State} */ function startLookahead(code) { effects.exit("chunkContent"); effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return factorySpace(effects, prefixed, "linePrefix"); } /** * * * @type {State} */ function prefixed(code) { if (code === null || markdownLineEnding(code)) return nok(code); const tail = self.events[self.events.length - 1]; if (!self.parser.constructs.disable.null.includes("codeIndented") && tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4) return ok(code); return effects.interrupt(self.parser.constructs.flow, nok, ok)(code); } } // node_modules/micromark-factory-destination/index.js /** * @import {Effects, State, TokenType} from 'micromark-util-types' */ /** * Parse destinations. * * ###### Examples * * ```markdown * <a> * <a\>b> * <a b> * <a)> * a * a\)b * a(b)c * a(b) * ``` * * @param {Effects} effects * Context. * @param {State} ok * State switched to when successful. * @param {State} nok * State switched to when unsuccessful. * @param {TokenType} type * Type for whole (`<a>` or `b`). * @param {TokenType} literalType * Type when enclosed (`<a>`). * @param {TokenType} literalMarkerType * Type for enclosing (`<` and `>`). * @param {TokenType} rawType * Type when not enclosed (`b`). * @param {TokenType} stringType * Type for the value (`a` or `b`). * @param {number | undefined} [max=Infinity] * Depth of nested parens (inclusive). * @returns {State} * Start state. */ function factoryDestination(effects, ok, nok, type, literalType, literalMarkerType, rawType, stringType, max) { const limit = max || Number.POSITIVE_INFINITY; let balance = 0; return start; /** * Start of destination. * * ```markdown * > | <aa> * ^ * > | aa * ^ * ``` * * @type {State} */ function start(code) { if (code === 60) { effects.enter(type); effects.enter(literalType); effects.enter(literalMarkerType); effects.consume(code); effects.exit(literalMarkerType); return enclosedBefore; } if (code === null || code === 32 || code === 41 || asciiControl(code)) return nok(code); effects.enter(type); effects.enter(rawType); effects.enter(stringType); effects.enter("chunkString", { contentType: "string" }); return raw(code); } /** * After `<`, at an enclosed destination. * * ```markdown * > | <aa> * ^ * ``` * * @type {State} */ function enclosedBefore(code) { if (code === 62) { effects.enter(literalMarkerType); effects.consume(code); effects.exit(literalMarkerType); effects.exit(literalType); effects.exit(type); return ok; } effects.enter(stringType); effects.enter("chunkString", { contentType: "string" }); return enclosed(code); } /** * In enclosed destination. * * ```markdown * > | <aa> * ^ * ``` * * @type {State} */ function enclosed(code) { if (code === 62) { effects.exit("chunkString"); effects.exit(stringType); return enclosedBefore(code); } if (code === null || code === 60 || markdownLineEnding(code)) return nok(code); effects.consume(code); return code === 92 ? enclosedEscape : enclosed; } /** * After `\`, at a special character. * * ```markdown * > | <a\*a> * ^ * ``` * * @type {State} */ function enclosedEscape(code) { if (code === 60 || code === 62 || code === 92) { effects.consume(code); return enclosed; } return enclosed(code); } /** * In raw destination. * * ```markdown * > | aa * ^ * ``` * * @type {State} */ function raw(code) { if (!balance && (code === null || code === 41 || markdownLineEndingOrSpace(code))) { effects.exit("chunkString"); effects.exit(stringType); effects.exit(rawType); effects.exit(type); return ok(code); } if (balance < limit && code === 40) { effects.consume(code); balance++; return raw; } if (code === 41) { effects.consume(code); balance--; return raw; } if (code === null || code === 32 || code === 40 || asciiControl(code)) return nok(code); effects.consume(code); return code === 92 ? rawEscape : raw; } /** * After `\`, at special character. * * ```markdown * > | a\*a * ^ * ``` * * @type {State} */ function rawEscape(code) { if (code === 40 || code === 41 || code === 92) { effects.consume(code); return raw; } return raw(code); } } // node_modules/micromark-factory-label/index.js /** * @import { * Effects, * State, * TokenizeContext, * TokenType * } from 'micromark-util-types' */ /** * Parse labels. * * > 👉 **Note**: labels in markdown are capped at 999 characters in the string. * * ###### Examples * * ```markdown * [a] * [a * b] * [a\]b] * ``` * * @this {TokenizeContext} * Tokenize context. * @param {Effects} effects * Context. * @param {State} ok * State switched to when successful. * @param {State} nok * State switched to when unsuccessful. * @param {TokenType} type * Type of the whole label (`[a]`). * @param {TokenType} markerType * Type for the markers (`[` and `]`). * @param {TokenType} stringType * Type for the identifier (`a`). * @returns {State} * Start state. */ function factoryLabel(effects, ok, nok, type, markerType, stringType) { const self = this; let size = 0; /** @type {boolean} */ let seen; return start; /** * Start of label. * * ```markdown * > | [a] * ^ * ``` * * @type {State} */ function start(code) { effects.enter(type); effects.enter(markerType); effects.consume(code); effects.exit(markerType); effects.enter(stringType); return atBreak; } /** * In label, at something, before something else. * * ```markdown * > | [a] * ^ * ``` * * @type {State} */ function atBreak(code) { if (size > 999 || code === null || code === 91 || code === 93 && !seen || /* c8 ignore next 3 */ code === 94 && !size && "_hiddenFootnoteSupport" in self.parser.constructs) return nok(code); if (code === 93) { effects.exit(stringType); effects.enter(markerType); effects.consume(code); effects.exit(markerType); effects.exit(type); return ok; } if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return atBreak; } effects.enter("chunkString", { contentType: "string" }); return labelInside(code); } /** * In label, in text. * * ```markdown * > | [a] * ^ * ``` * * @type {State} */ function labelInside(code) { if (code === null || code === 91 || code === 93 || markdownLineEnding(code) || size++ > 999) { effects.exit("chunkString"); return atBreak(code); } effects.consume(code); if (!seen) seen = !markdownSpace(code); return code === 92 ? labelEscape : labelInside; } /** * After `\`, at a special character. * * ```markdown * > | [a\*a] * ^ * ``` * * @type {State} */ function labelEscape(code) { if (code === 91 || code === 92 || code === 93) { effects.consume(code); size++; return labelInside; } return labelInside(code); } } // node_modules/micromark-factory-title/index.js /** * @import { * Code, * Effects, * State, * TokenType * } from 'micromark-util-types' */ /** * Parse titles. * * ###### Examples * * ```markdown * "a" * 'b' * (c) * "a * b" * 'a * b' * (a\)b) * ``` * * @param {Effects} effects * Context. * @param {State} ok * State switched to when successful. * @param {State} nok * State switched to when unsuccessful. * @param {TokenType} type * Type of the whole title (`"a"`, `'b'`, `(c)`). * @param {TokenType} markerType * Type for the markers (`"`, `'`, `(`, and `)`). * @param {TokenType} stringType * Type for the value (`a`). * @returns {State} * Start state. */ function factoryTitle(effects, ok, nok, type, markerType, stringType) { /** @type {NonNullable<Code>} */ let marker; return start; /** * Start of title. * * ```markdown * > | "a" * ^ * ``` * * @type {State} */ function start(code) { if (code === 34 || code === 39 || code === 40) { effects.enter(type); effects.enter(markerType); effects.consume(code); effects.exit(markerType); marker = code === 40 ? 41 : code; return begin; } return nok(code); } /** * After opening marker. * * This is also used at the closing marker. * * ```markdown * > | "a" * ^ * ``` * * @type {State} */ function begin(code) { if (code === marker) { effects.enter(markerType); effects.consume(code); effects.exit(markerType); effects.exit(type); return ok; } effects.enter(stringType); return atBreak(code); } /** * At something, before something else. * * ```markdown * > | "a" * ^ * ``` * * @type {State} */ function atBreak(code) { if (code === marker) { effects.exit(stringType); return begin(marker); } if (code === null) return nok(code); if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return factorySpace(effects, atBreak, "linePrefix"); } effects.enter("chunkString", { contentType: "string" }); return inside(code); } /** * * * @type {State} */ function inside(code) { if (code === marker || code === null || markdownLineEnding(code)) { effects.exit("chunkString"); return atBreak(code); } effects.consume(code); return code === 92 ? escape : inside; } /** * After `\`, at a special character. * * ```markdown * > | "a\*b" * ^ * ``` * * @type {State} */ function escape(code) { if (code === marker || code === 92) { effects.consume(code); return inside; } return inside(code); } } // node_modules/micromark-factory-whitespace/index.js /** * @import {Effects, State} from 'micromark-util-types' */ /** * Parse spaces and tabs. * * There is no `nok` parameter: * * * line endings or spaces in markdown are often optional, in which case this * factory can be used and `ok` will be switched to whether spaces were found * or not * * one line ending or space can be detected with * `markdownLineEndingOrSpace(code)` right before using `factoryWhitespace` * * @param {Effects} effects * Context. * @param {State} ok * State switched to when successful. * @returns {State} * Start state. */ function factoryWhitespace(effects, ok) { /** @type {boolean} */ let seen; return start; /** @type {State} */ function start(code) { if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); seen = true; return start; } if (markdownSpace(code)) return factorySpace(effects, start, seen ? "linePrefix" : "lineSuffix")(code); return ok(code); } } // node_modules/micromark-core-commonmark/lib/definition.js /** * @import { * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const definition = { name: "definition", tokenize: tokenizeDefinition }; /** @type {Construct} */ const titleBefore = { partial: true, tokenize: tokenizeTitleBefore }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeDefinition(effects, ok, nok) { const self = this; /** @type {string} */ let identifier; return start; /** * At start of a definition. * * ```markdown * > | [a]: b "c" * ^ * ``` * * @type {State} */ function start(code) { effects.enter("definition"); return before(code); } /** * After optional whitespace, at `[`. * * ```markdown * > | [a]: b "c" * ^ * ``` * * @type {State} */ function before(code) { return factoryLabel.call(self, effects, labelAfter, nok, "definitionLabel", "definitionLabelMarker", "definitionLabelString")(code); } /** * After label. * * ```markdown * > | [a]: b "c" * ^ * ``` * * @type {State} */ function labelAfter(code) { identifier = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1)); if (code === 58) { effects.enter("definitionMarker"); effects.consume(code); effects.exit("definitionMarker"); return markerAfter; } return nok(code); } /** * After marker. * * ```markdown * > | [a]: b "c" * ^ * ``` * * @type {State} */ function markerAfter(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, destinationBefore)(code) : destinationBefore(code); } /** * Before destination. * * ```markdown * > | [a]: b "c" * ^ * ``` * * @type {State} */ function destinationBefore(code) { return factoryDestination(effects, destinationAfter, nok, "definitionDestination", "definitionDestinationLiteral", "definitionDestinationLiteralMarker", "definitionDestinationRaw", "definitionDestinationString")(code); } /** * After destination. * * ```markdown * > | [a]: b "c" * ^ * ``` * * @type {State} */ function destinationAfter(code) { return effects.attempt(titleBefore, after, after)(code); } /** * After definition. * * ```markdown * > | [a]: b * ^ * > | [a]: b "c" * ^ * ``` * * @type {State} */ function after(code) { return markdownSpace(code) ? factorySpace(effects, afterWhitespace, "whitespace")(code) : afterWhitespace(code); } /** * After definition, after optional whitespace. * * ```markdown * > | [a]: b * ^ * > | [a]: b "c" * ^ * ``` * * @type {State} */ function afterWhitespace(code) { if (code === null || markdownLineEnding(code)) { effects.exit("definition"); self.parser.defined.push(identifier); return ok(code); } return nok(code); } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeTitleBefore(effects, ok, nok) { return titleBefore; /** * After destination, at whitespace. * * ```markdown * > | [a]: b * ^ * > | [a]: b "c" * ^ * ``` * * @type {State} */ function titleBefore(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, beforeMarker)(code) : nok(code); } /** * At title. * * ```markdown * | [a]: b * > | "c" * ^ * ``` * * @type {State} */ function beforeMarker(code) { return factoryTitle(effects, titleAfter, nok, "definitionTitle", "definitionTitleMarker", "definitionTitleString")(code); } /** * After title. * * ```markdown * > | [a]: b "c" * ^ * ``` * * @type {State} */ function titleAfter(code) { return markdownSpace(code) ? factorySpace(effects, titleAfterOptionalWhitespace, "whitespace")(code) : titleAfterOptionalWhitespace(code); } /** * After title, after optional whitespace. * * ```markdown * > | [a]: b "c" * ^ * ``` * * @type {State} */ function titleAfterOptionalWhitespace(code) { return code === null || markdownLineEnding(code) ? ok(code) : nok(code); } } // node_modules/micromark-core-commonmark/lib/hard-break-escape.js /** * @import { * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const hardBreakEscape = { name: "hardBreakEscape", tokenize: tokenizeHardBreakEscape }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeHardBreakEscape(effects, ok, nok) { return start; /** * Start of a hard break (escape). * * ```markdown * > | a\ * ^ * | b * ``` * * @type {State} */ function start(code) { effects.enter("hardBreakEscape"); effects.consume(code); return after; } /** * After `\`, at eol. * * ```markdown * > | a\ * ^ * | b * ``` * * @type {State} */ function after(code) { if (markdownLineEnding(code)) { effects.exit("hardBreakEscape"); return ok(code); } return nok(code); } } // node_modules/micromark-core-commonmark/lib/heading-atx.js /** * @import { * Construct, * Resolver, * State, * TokenizeContext, * Tokenizer, * Token * } from 'micromark-util-types' */ /** @type {Construct} */ const headingAtx = { name: "headingAtx", resolve: resolveHeadingAtx, tokenize: tokenizeHeadingAtx }; /** @type {Resolver} */ function resolveHeadingAtx(events, context) { let contentEnd = events.length - 2; let contentStart = 3; if (events[contentStart][1].type === "whitespace") contentStart += 2; if (contentEnd - 2 > contentStart && events[contentEnd][1].type === "whitespace") contentEnd -= 2; if (events[contentEnd][1].type === "atxHeadingSequence" && (contentStart === contentEnd - 1 || contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === "whitespace")) contentEnd -= contentStart + 1 === contentEnd ? 2 : 4; if (contentEnd > contentStart) { const content = { type: "atxHeadingText", start: events[contentStart][1].start, end: events[contentEnd][1].end }; const text = { type: "chunkText", start: events[contentStart][1].start, end: events[contentEnd][1].end, contentType: "text" }; splice(events, contentStart, contentEnd - contentStart + 1, [ [ "enter", content, context ], [ "enter", text, context ], [ "exit", text, context ], [ "exit", content, context ] ]); } return events; } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeHeadingAtx(effects, ok, nok) { let size = 0; return start; /** * Start of a heading (atx). * * ```markdown * > | ## aa * ^ * ``` * * @type {State} */ function start(code) { effects.enter("atxHeading"); return before(code); } /** * After optional whitespace, at `#`. * * ```markdown * > | ## aa * ^ * ``` * * @type {State} */ function before(code) { effects.enter("atxHeadingSequence"); return sequenceOpen(code); } /** * In opening sequence. * * ```markdown * > | ## aa * ^ * ``` * * @type {State} */ function sequenceOpen(code) { if (code === 35 && size++ < 6) { effects.consume(code); return sequenceOpen; } if (code === null || markdownLineEndingOrSpace(code)) { effects.exit("atxHeadingSequence"); return atBreak(code); } return nok(code); } /** * After something, before something else. * * ```markdown * > | ## aa * ^ * ``` * * @type {State} */ function atBreak(code) { if (code === 35) { effects.enter("atxHeadingSequence"); return sequenceFurther(code); } if (code === null || markdownLineEnding(code)) { effects.exit("atxHeading"); return ok(code); } if (markdownSpace(code)) return factorySpace(effects, atBreak, "whitespace")(code); effects.enter("atxHeadingText"); return data(code); } /** * In further sequence (after whitespace). * * Could be normal “visible” hashes in the heading or a final sequence. * * ```markdown * > | ## aa ## * ^ * ``` * * @type {State} */ function sequenceFurther(code) { if (code === 35) { effects.consume(code); return sequenceFurther; } effects.exit("atxHeadingSequence"); return atBreak(code); } /** * In text. * * ```markdown * > | ## aa * ^ * ``` * * @type {State} */ function data(code) { if (code === null || code === 35 || markdownLineEndingOrSpace(code)) { effects.exit("atxHeadingText"); return atBreak(code); } effects.consume(code); return data; } } // node_modules/micromark-util-html-tag-name/index.js /** * List of lowercase HTML “block” tag names. * * The list, when parsing HTML (flow), results in more relaxed rules (condition * 6). * Because they are known blocks, the HTML-like syntax doesn’t have to be * strictly parsed. * For tag names not in this list, a more strict algorithm (condition 7) is used * to detect whether the HTML-like syntax is seen as HTML (flow) or not. * * This is copied from: * <https://spec.commonmark.org/0.30/#html-blocks>. * * > 👉 **Note**: `search` was added in `CommonMark@0.31`. */ const htmlBlockNames = [ "address", "article", "aside", "base", "basefont", "blockquote", "body", "caption", "center", "col", "colgroup", "dd", "details", "dialog", "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hr", "html", "iframe", "legend", "li", "link", "main", "menu", "menuitem", "nav", "noframes", "ol", "optgroup", "option", "p", "param", "search", "section", "summary", "table", "tbody", "td", "tfoot", "th", "thead", "title", "tr", "track", "ul" ]; /** * List of lowercase HTML “raw” tag names. * * The list, when parsing HTML (flow), results in HTML that can include lines * without exiting, until a closing tag also in this list is found (condition * 1). * * This module is copied from: * <https://spec.commonmark.org/0.30/#html-blocks>. * * > 👉 **Note**: `textarea` was added in `CommonMark@0.30`. */ const htmlRawNames = [ "pre", "script", "style", "textarea" ]; // node_modules/micromark-core-commonmark/lib/html-flow.js /** * @import { * Code, * Construct, * Resolver, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const htmlFlow = { concrete: true, name: "htmlFlow", resolveTo: resolveToHtmlFlow, tokenize: tokenizeHtmlFlow }; /** @type {Construct} */ const blankLineBefore = { partial: true, tokenize: tokenizeBlankLineBefore }; /** @type {Resolver} */ function resolveToHtmlFlow(events) { let index = events.length; while (index--) if (events[index][0] === "enter" && events[index][1].type === "htmlFlow") break; if (index > 1 && events[index - 2][1].type === "linePrefix") { events[index][1].start = events[index - 2][1].start; events[index + 1][1].start = events[index - 2][1].start; events.splice(index - 2, 2); } return events; } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeHtmlFlow(effects, ok, nok) { const self = this; /** @type {number} */ let marker; /** @type {boolean} */ let closingTag; /** @type {string} */ let buffer; /** @type {number} */ let index; /** @type {Code} */ let markerB; return start; /** * Start of HTML (flow). * * ```markdown * > | <x /> * ^ * ``` * * @type {State} */ function start(code) { return before(code); } /** * At `<`, after optional whitespace. * * ```markdown * > | <x /> * ^ * ``` * * @type {State} */ function before(code) { effects.enter("htmlFlow"); effects.enter("htmlFlowData"); effects.consume(code); return open; } /** * After `<`, at tag name or other stuff. * * ```markdown * > | <x /> * ^ * > | <!doctype> * ^ * > | <!--xxx--> * ^ * ``` * * @type {State} */ function open(code) { if (code === 33) { effects.consume(code); return declarationOpen; } if (code === 47) { effects.consume(code); closingTag = true; return tagCloseStart; } if (code === 63) { effects.consume(code); marker = 3; return self.interrupt ? ok : continuationDeclarationInside; } if (asciiAlpha(code)) { effects.consume(code); buffer = String.fromCharCode(code); return tagName; } return nok(code); } /** * After `<!`, at declaration, comment, or CDATA. * * ```markdown * > | <!doctype> * ^ * > | <!--xxx--> * ^ * > | <![CDATA[>&<]]> * ^ * ``` * * @type {State} */ function declarationOpen(code) { if (code === 45) { effects.consume(code); marker = 2; return commentOpenInside; } if (code === 91) { effects.consume(code); marker = 5; index = 0; return cdataOpenInside; } if (asciiAlpha(code)) { effects.consume(code); marker = 4; return self.interrupt ? ok : continuationDeclarationInside; } return nok(code); } /** * After `<!-`, inside a comment, at another `-`. * * ```markdown * > | <!--xxx--> * ^ * ``` * * @type {State} */ function commentOpenInside(code) { if (code === 45) { effects.consume(code); return self.interrupt ? ok : continuationDeclarationInside; } return nok(code); } /** * After `<![`, inside CDATA, expecting `CDATA[`. * * ```markdown * > | <![CDATA[>&<]]> * ^^^^^^ * ``` * * @type {State} */ function cdataOpenInside(code) { if (code === "CDATA[".charCodeAt(index++)) { effects.consume(code); if (index === 6) return self.interrupt ? ok : continuation; return cdataOpenInside; } return nok(code); } /** * After `</`, in closing tag, at tag name. * * ```markdown * > | </x> * ^ * ``` * * @type {State} */ function tagCloseStart(code) { if (asciiAlpha(code)) { effects.consume(code); buffer = String.fromCharCode(code); return tagName; } return nok(code); } /** * In tag name. * * ```markdown * > | <ab> * ^^ * > | </ab> * ^^ * ``` * * @type {State} */ function tagName(code) { if (code === null || code === 47 || code === 62 || markdownLineEndingOrSpace(code)) { const slash = code === 47; const name = buffer.toLowerCase(); if (!slash && !closingTag && htmlRawNames.includes(name)) { marker = 1; return self.interrupt ? ok(code) : continuation(code); } if (htmlBlockNames.includes(buffer.toLowerCase())) { marker = 6; if (slash) { effects.consume(code); return basicSelfClosing; } return self.interrupt ? ok(code) : continuation(code); } marker = 7; return self.interrupt && !self.parser.lazy[self.now().line] ? nok(code) : closingTag ? completeClosingTagAfter(code) : completeAttributeNameBefore(code); } if (code === 45 || asciiAlphanumeric(code)) { effects.consume(code); buffer += String.fromCharCode(code); return tagName; } return nok(code); } /** * After closing slash of a basic tag name. * * ```markdown * > | <div/> * ^ * ``` * * @type {State} */ function basicSelfClosing(code) { if (code === 62) { effects.consume(code); return self.interrupt ? ok : continuation; } return nok(code); } /** * After closing slash of a complete tag name. * * ```markdown * > | <x/> * ^ * ``` * * @type {State} */ function completeClosingTagAfter(code) { if (markdownSpace(code)) { effects.consume(code); return completeClosingTagAfter; } return completeEnd(code); } /** * At an attribute name. * * At first, this state is used after a complete tag name, after whitespace, * where it expects optional attributes or the end of the tag. * It is also reused after attributes, when expecting more optional * attributes. * * ```markdown * > | <a /> * ^ * > | <a :b> * ^ * > | <a _b> * ^ * > | <a b> * ^ * > | <a > * ^ * ``` * * @type {State} */ function completeAttributeNameBefore(code) { if (code === 47) { effects.consume(code); return completeEnd; } if (code === 58 || code === 95 || asciiAlpha(code)) { effects.consume(code); return completeAttributeName; } if (markdownSpace(code)) { effects.consume(code); return completeAttributeNameBefore; } return completeEnd(code); } /** * In attribute name. * * ```markdown * > | <a :b> * ^ * > | <a _b> * ^ * > | <a b> * ^ * ``` * * @type {State} */ function completeAttributeName(code) { if (code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code)) { effects.consume(code); return completeAttributeName; } return completeAttributeNameAfter(code); } /** * After attribute name, at an optional initializer, the end of the tag, or * whitespace. * * ```markdown * > | <a b> * ^ * > | <a b=c> * ^ * ``` * * @type {State} */ function completeAttributeNameAfter(code) { if (code === 61) { effects.consume(code); return completeAttributeValueBefore; } if (markdownSpace(code)) { effects.consume(code); return completeAttributeNameAfter; } return completeAttributeNameBefore(code); } /** * Before unquoted, double quoted, or single quoted attribute value, allowing * whitespace. * * ```markdown * > | <a b=c> * ^ * > | <a b="c"> * ^ * ``` * * @type {State} */ function completeAttributeValueBefore(code) { if (code === null || code === 60 || code === 61 || code === 62 || code === 96) return nok(code); if (code === 34 || code === 39) { effects.consume(code); markerB = code; return completeAttributeValueQuoted; } if (markdownSpace(code)) { effects.consume(code); return completeAttributeValueBefore; } return completeAttributeValueUnquoted(code); } /** * In double or single quoted attribute value. * * ```markdown * > | <a b="c"> * ^ * > | <a b='c'> * ^ * ``` * * @type {State} */ function completeAttributeValueQuoted(code) { if (code === markerB) { effects.consume(code); markerB = null; return completeAttributeValueQuotedAfter; } if (code === null || markdownLineEnding(code)) return nok(code); effects.consume(code); return completeAttributeValueQuoted; } /** * In unquoted attribute value. * * ```markdown * > | <a b=c> * ^ * ``` * * @type {State} */ function completeAttributeValueUnquoted(code) { if (code === null || code === 34 || code === 39 || code === 47 || code === 60 || code === 61 || code === 62 || code === 96 || markdownLineEndingOrSpace(code)) return completeAttributeNameAfter(code); effects.consume(code); return completeAttributeValueUnquoted; } /** * After double or single quoted attribute value, before whitespace or the * end of the tag. * * ```markdown * > | <a b="c"> * ^ * ``` * * @type {State} */ function completeAttributeValueQuotedAfter(code) { if (code === 47 || code === 62 || markdownSpace(code)) return completeAttributeNameBefore(code); return nok(code); } /** * In certain circumstances of a complete tag where only an `>` is allowed. * * ```markdown * > | <a b="c"> * ^ * ``` * * @type {State} */ function completeEnd(code) { if (code === 62) { effects.consume(code); return completeAfter; } return nok(code); } /** * After `>` in a complete tag. * * ```markdown * > | <x> * ^ * ``` * * @type {State} */ function completeAfter(code) { if (code === null || markdownLineEnding(code)) return continuation(code); if (markdownSpace(code)) { effects.consume(code); return completeAfter; } return nok(code); } /** * In continuation of any HTML kind. * * ```markdown * > | <!--xxx--> * ^ * ``` * * @type {State} */ function continuation(code) { if (code === 45 && marker === 2) { effects.consume(code); return continuationCommentInside; } if (code === 60 && marker === 1) { effects.consume(code); return continuationRawTagOpen; } if (code === 62 && marker === 4) { effects.consume(code); return continuationClose; } if (code === 63 && marker === 3) { effects.consume(code); return continuationDeclarationInside; } if (code === 93 && marker === 5) { effects.consume(code); return continuationCdataInside; } if (markdownLineEnding(code) && (marker === 6 || marker === 7)) { effects.exit("htmlFlowData"); return effects.check(blankLineBefore, continuationAfter, continuationStart)(code); } if (code === null || markdownLineEnding(code)) { effects.exit("htmlFlowData"); return continuationStart(code); } effects.consume(code); return continuation; } /** * In continuation, at eol. * * ```markdown * > | <x> * ^ * | asd * ``` * * @type {State} */ function continuationStart(code) { return effects.check(nonLazyContinuation$2, continuationStartNonLazy, continuationAfter)(code); } /** * In continuation, at eol, before non-lazy content. * * ```markdown * > | <x> * ^ * | asd * ``` * * @type {State} */ function continuationStartNonLazy(code) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return continuationBefore; } /** * In continuation, before non-lazy content. * * ```markdown * | <x> * > | asd * ^ * ``` * * @type {State} */ function continuationBefore(code) { if (code === null || markdownLineEnding(code)) return continuationStart(code); effects.enter("htmlFlowData"); return continuation(code); } /** * In comment continuation, after one `-`, expecting another. * * ```markdown * > | <!--xxx--> * ^ * ``` * * @type {State} */ function continuationCommentInside(code) { if (code === 45) { effects.consume(code); return continuationDeclarationInside; } return continuation(code); } /** * In raw continuation, after `<`, at `/`. * * ```markdown * > | <script>console.log(1)<\/script> * ^ * ``` * * @type {State} */ function continuationRawTagOpen(code) { if (code === 47) { effects.consume(code); buffer = ""; return continuationRawEndTag; } return continuation(code); } /** * In raw continuation, after `</`, in a raw tag name. * * ```markdown * > | <script>console.log(1)<\/script> * ^^^^^^ * ``` * * @type {State} */ function continuationRawEndTag(code) { if (code === 62) { const name = buffer.toLowerCase(); if (htmlRawNames.includes(name)) { effects.consume(code); return continuationClose; } return continuation(code); } if (asciiAlpha(code) && buffer.length < 8) { effects.consume(code); buffer += String.fromCharCode(code); return continuationRawEndTag; } return continuation(code); } /** * In cdata continuation, after `]`, expecting `]>`. * * ```markdown * > | <![CDATA[>&<]]> * ^ * ``` * * @type {State} */ function continuationCdataInside(code) { if (code === 93) { effects.consume(code); return continuationDeclarationInside; } return continuation(code); } /** * In declaration or instruction continuation, at `>`. * * ```markdown * > | <!--> * ^ * > | <?> * ^ * > | <!q> * ^ * > | <!--ab--> * ^ * > | <![CDATA[>&<]]> * ^ * ``` * * @type {State} */ function continuationDeclarationInside(code) { if (code === 62) { effects.consume(code); return continuationClose; } if (code === 45 && marker === 2) { effects.consume(code); return continuationDeclarationInside; } return continuation(code); } /** * In closed continuation: everything we get until the eol/eof is part of it. * * ```markdown * > | <!doctype> * ^ * ``` * * @type {State} */ function continuationClose(code) { if (code === null || markdownLineEnding(code)) { effects.exit("htmlFlowData"); return continuationAfter(code); } effects.consume(code); return continuationClose; } /** * Done. * * ```markdown * > | <!doctype> * ^ * ``` * * @type {State} */ function continuationAfter(code) { effects.exit("htmlFlow"); return ok(code); } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeBlankLineBefore(effects, ok, nok) { return start; /** * Before eol, expecting blank line. * * ```markdown * > | <div> * ^ * | * ``` * * @type {State} */ function start(code) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return effects.attempt(blankLine, ok, nok); } } // node_modules/micromark-core-commonmark/lib/html-text.js /** * @import { * Code, * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const htmlText = { name: "htmlText", tokenize: tokenizeHtmlText }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeHtmlText(effects, ok, nok) { const self = this; /** @type {NonNullable<Code> | undefined} */ let marker; /** @type {number} */ let index; /** @type {State} */ let returnState; return start; /** * Start of HTML (text). * * ```markdown * > | a <b> c * ^ * ``` * * @type {State} */ function start(code) { effects.enter("htmlText"); effects.enter("htmlTextData"); effects.consume(code); return open; } /** * After `<`, at tag name or other stuff. * * ```markdown * > | a <b> c * ^ * > | a <!doctype> c * ^ * > | a <!--b--> c * ^ * ``` * * @type {State} */ function open(code) { if (code === 33) { effects.consume(code); return declarationOpen; } if (code === 47) { effects.consume(code); return tagCloseStart; } if (code === 63) { effects.consume(code); return instruction; } if (asciiAlpha(code)) { effects.consume(code); return tagOpen; } return nok(code); } /** * After `<!`, at declaration, comment, or CDATA. * * ```markdown * > | a <!doctype> c * ^ * > | a <!--b--> c * ^ * > | a <![CDATA[>&<]]> c * ^ * ``` * * @type {State} */ function declarationOpen(code) { if (code === 45) { effects.consume(code); return commentOpenInside; } if (code === 91) { effects.consume(code); index = 0; return cdataOpenInside; } if (asciiAlpha(code)) { effects.consume(code); return declaration; } return nok(code); } /** * In a comment, after `<!-`, at another `-`. * * ```markdown * > | a <!--b--> c * ^ * ``` * * @type {State} */ function commentOpenInside(code) { if (code === 45) { effects.consume(code); return commentEnd; } return nok(code); } /** * In comment. * * ```markdown * > | a <!--b--> c * ^ * ``` * * @type {State} */ function comment(code) { if (code === null) return nok(code); if (code === 45) { effects.consume(code); return commentClose; } if (markdownLineEnding(code)) { returnState = comment; return lineEndingBefore(code); } effects.consume(code); return comment; } /** * In comment, after `-`. * * ```markdown * > | a <!--b--> c * ^ * ``` * * @type {State} */ function commentClose(code) { if (code === 45) { effects.consume(code); return commentEnd; } return comment(code); } /** * In comment, after `--`. * * ```markdown * > | a <!--b--> c * ^ * ``` * * @type {State} */ function commentEnd(code) { return code === 62 ? end(code) : code === 45 ? commentClose(code) : comment(code); } /** * After `<![`, in CDATA, expecting `CDATA[`. * * ```markdown * > | a <![CDATA[>&<]]> b * ^^^^^^ * ``` * * @type {State} */ function cdataOpenInside(code) { if (code === "CDATA[".charCodeAt(index++)) { effects.consume(code); return index === 6 ? cdata : cdataOpenInside; } return nok(code); } /** * In CDATA. * * ```markdown * > | a <![CDATA[>&<]]> b * ^^^ * ``` * * @type {State} */ function cdata(code) { if (code === null) return nok(code); if (code === 93) { effects.consume(code); return cdataClose; } if (markdownLineEnding(code)) { returnState = cdata; return lineEndingBefore(code); } effects.consume(code); return cdata; } /** * In CDATA, after `]`, at another `]`. * * ```markdown * > | a <![CDATA[>&<]]> b * ^ * ``` * * @type {State} */ function cdataClose(code) { if (code === 93) { effects.consume(code); return cdataEnd; } return cdata(code); } /** * In CDATA, after `]]`, at `>`. * * ```markdown * > | a <![CDATA[>&<]]> b * ^ * ``` * * @type {State} */ function cdataEnd(code) { if (code === 62) return end(code); if (code === 93) { effects.consume(code); return cdataEnd; } return cdata(code); } /** * In declaration. * * ```markdown * > | a <!b> c * ^ * ``` * * @type {State} */ function declaration(code) { if (code === null || code === 62) return end(code); if (markdownLineEnding(code)) { returnState = declaration; return lineEndingBefore(code); } effects.consume(code); return declaration; } /** * In instruction. * * ```markdown * > | a <?b?> c * ^ * ``` * * @type {State} */ function instruction(code) { if (code === null) return nok(code); if (code === 63) { effects.consume(code); return instructionClose; } if (markdownLineEnding(code)) { returnState = instruction; return lineEndingBefore(code); } effects.consume(code); return instruction; } /** * In instruction, after `?`, at `>`. * * ```markdown * > | a <?b?> c * ^ * ``` * * @type {State} */ function instructionClose(code) { return code === 62 ? end(code) : instruction(code); } /** * After `</`, in closing tag, at tag name. * * ```markdown * > | a </b> c * ^ * ``` * * @type {State} */ function tagCloseStart(code) { if (asciiAlpha(code)) { effects.consume(code); return tagClose; } return nok(code); } /** * After `</x`, in a tag name. * * ```markdown * > | a </b> c * ^ * ``` * * @type {State} */ function tagClose(code) { if (code === 45 || asciiAlphanumeric(code)) { effects.consume(code); return tagClose; } return tagCloseBetween(code); } /** * In closing tag, after tag name. * * ```markdown * > | a </b> c * ^ * ``` * * @type {State} */ function tagCloseBetween(code) { if (markdownLineEnding(code)) { returnState = tagCloseBetween; return lineEndingBefore(code); } if (markdownSpace(code)) { effects.consume(code); return tagCloseBetween; } return end(code); } /** * After `<x`, in opening tag name. * * ```markdown * > | a <b> c * ^ * ``` * * @type {State} */ function tagOpen(code) { if (code === 45 || asciiAlphanumeric(code)) { effects.consume(code); return tagOpen; } if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) return tagOpenBetween(code); return nok(code); } /** * In opening tag, after tag name. * * ```markdown * > | a <b> c * ^ * ``` * * @type {State} */ function tagOpenBetween(code) { if (code === 47) { effects.consume(code); return end; } if (code === 58 || code === 95 || asciiAlpha(code)) { effects.consume(code); return tagOpenAttributeName; } if (markdownLineEnding(code)) { returnState = tagOpenBetween; return lineEndingBefore(code); } if (markdownSpace(code)) { effects.consume(code); return tagOpenBetween; } return end(code); } /** * In attribute name. * * ```markdown * > | a <b c> d * ^ * ``` * * @type {State} */ function tagOpenAttributeName(code) { if (code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code)) { effects.consume(code); return tagOpenAttributeName; } return tagOpenAttributeNameAfter(code); } /** * After attribute name, before initializer, the end of the tag, or * whitespace. * * ```markdown * > | a <b c> d * ^ * ``` * * @type {State} */ function tagOpenAttributeNameAfter(code) { if (code === 61) { effects.consume(code); return tagOpenAttributeValueBefore; } if (markdownLineEnding(code)) { returnState = tagOpenAttributeNameAfter; return lineEndingBefore(code); } if (markdownSpace(code)) { effects.consume(code); return tagOpenAttributeNameAfter; } return tagOpenBetween(code); } /** * Before unquoted, double quoted, or single quoted attribute value, allowing * whitespace. * * ```markdown * > | a <b c=d> e * ^ * ``` * * @type {State} */ function tagOpenAttributeValueBefore(code) { if (code === null || code === 60 || code === 61 || code === 62 || code === 96) return nok(code); if (code === 34 || code === 39) { effects.consume(code); marker = code; return tagOpenAttributeValueQuoted; } if (markdownLineEnding(code)) { returnState = tagOpenAttributeValueBefore; return lineEndingBefore(code); } if (markdownSpace(code)) { effects.consume(code); return tagOpenAttributeValueBefore; } effects.consume(code); return tagOpenAttributeValueUnquoted; } /** * In double or single quoted attribute value. * * ```markdown * > | a <b c="d"> e * ^ * ``` * * @type {State} */ function tagOpenAttributeValueQuoted(code) { if (code === marker) { effects.consume(code); marker = void 0; return tagOpenAttributeValueQuotedAfter; } if (code === null) return nok(code); if (markdownLineEnding(code)) { returnState = tagOpenAttributeValueQuoted; return lineEndingBefore(code); } effects.consume(code); return tagOpenAttributeValueQuoted; } /** * In unquoted attribute value. * * ```markdown * > | a <b c=d> e * ^ * ``` * * @type {State} */ function tagOpenAttributeValueUnquoted(code) { if (code === null || code === 34 || code === 39 || code === 60 || code === 61 || code === 96) return nok(code); if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) return tagOpenBetween(code); effects.consume(code); return tagOpenAttributeValueUnquoted; } /** * After double or single quoted attribute value, before whitespace or the end * of the tag. * * ```markdown * > | a <b c="d"> e * ^ * ``` * * @type {State} */ function tagOpenAttributeValueQuotedAfter(code) { if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) return tagOpenBetween(code); return nok(code); } /** * In certain circumstances of a tag where only an `>` is allowed. * * ```markdown * > | a <b c="d"> e * ^ * ``` * * @type {State} */ function end(code) { if (code === 62) { effects.consume(code); effects.exit("htmlTextData"); effects.exit("htmlText"); return ok; } return nok(code); } /** * At eol. * * > 👉 **Note**: we can’t have blank lines in text, so no need to worry about * > empty tokens. * * ```markdown * > | a <!--a * ^ * | b--> * ``` * * @type {State} */ function lineEndingBefore(code) { effects.exit("htmlTextData"); effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return lineEndingAfter; } /** * After eol, at optional whitespace. * * > 👉 **Note**: we can’t have blank lines in text, so no need to worry about * > empty tokens. * * ```markdown * | a <!--a * > | b--> * ^ * ``` * * @type {State} */ function lineEndingAfter(code) { return markdownSpace(code) ? factorySpace(effects, lineEndingAfterPrefix, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code) : lineEndingAfterPrefix(code); } /** * After eol, after optional whitespace. * * > 👉 **Note**: we can’t have blank lines in text, so no need to worry about * > empty tokens. * * ```markdown * | a <!--a * > | b--> * ^ * ``` * * @type {State} */ function lineEndingAfterPrefix(code) { effects.enter("htmlTextData"); return returnState(code); } } // node_modules/micromark-core-commonmark/lib/label-end.js /** * @import { * Construct, * Event, * Resolver, * State, * TokenizeContext, * Tokenizer, * Token * } from 'micromark-util-types' */ /** @type {Construct} */ const labelEnd = { name: "labelEnd", resolveAll: resolveAllLabelEnd, resolveTo: resolveToLabelEnd, tokenize: tokenizeLabelEnd }; /** @type {Construct} */ const resourceConstruct = { tokenize: tokenizeResource }; /** @type {Construct} */ const referenceFullConstruct = { tokenize: tokenizeReferenceFull }; /** @type {Construct} */ const referenceCollapsedConstruct = { tokenize: tokenizeReferenceCollapsed }; /** @type {Resolver} */ function resolveAllLabelEnd(events) { let index = -1; /** @type {Array<Event>} */ const newEvents = []; while (++index < events.length) { const token = events[index][1]; newEvents.push(events[index]); if (token.type === "labelImage" || token.type === "labelLink" || token.type === "labelEnd") { const offset = token.type === "labelImage" ? 4 : 2; token.type = "data"; index += offset; } } if (events.length !== newEvents.length) splice(events, 0, events.length, newEvents); return events; } /** @type {Resolver} */ function resolveToLabelEnd(events, context) { let index = events.length; let offset = 0; /** @type {number | undefined} */ let open; /** @type {number | undefined} */ let close; /** @type {Array<Event>} */ let media; while (index--) { const token = events[index][1]; if (open) { if (token.type === "link" || token.type === "labelLink" && token._inactive) break; if (events[index][0] === "enter" && token.type === "labelLink") token._inactive = true; } else if (close) { if (events[index][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) { open = index; if (token.type !== "labelLink") { offset = 2; break; } } } else if (token.type === "labelEnd") close = index; } const group = { type: events[open][1].type === "labelLink" ? "link" : "image", start: { ...events[open][1].start }, end: { ...events[events.length - 1][1].end } }; const label = { type: "label", start: { ...events[open][1].start }, end: { ...events[close][1].end } }; const text = { type: "labelText", start: { ...events[open + offset + 2][1].end }, end: { ...events[close - 2][1].start } }; media = [[ "enter", group, context ], [ "enter", label, context ]]; media = push(media, events.slice(open + 1, open + offset + 3)); media = push(media, [[ "enter", text, context ]]); media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context)); media = push(media, [ [ "exit", text, context ], events[close - 2], events[close - 1], [ "exit", label, context ] ]); media = push(media, events.slice(close + 1)); media = push(media, [[ "exit", group, context ]]); splice(events, open, events.length, media); return events; } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeLabelEnd(effects, ok, nok) { const self = this; const labelStarts = self._labelStarts; /** @type {Token} */ let labelStart; /** @type {boolean} */ let defined; if (labelStarts) { while (labelStarts.length > 0 && labelStarts[labelStarts.length - 1]._balanced) labelStarts.pop(); labelStart = labelStarts[labelStarts.length - 1]; } return start; /** * Start of label end. * * ```markdown * > | [a](b) c * ^ * > | [a][b] c * ^ * > | [a][] b * ^ * > | [a] b * ``` * * @type {State} */ function start(code) { if (!labelStart) return nok(code); if (labelStart._inactive) return labelEndNok(code); defined = self.parser.defined.includes(normalizeIdentifier(self.sliceSerialize({ start: labelStart.end, end: self.now() }))); effects.enter("labelEnd"); effects.enter("labelMarker"); effects.consume(code); effects.exit("labelMarker"); effects.exit("labelEnd"); return after; } /** * After `]`. * * ```markdown * > | [a](b) c * ^ * > | [a][b] c * ^ * > | [a][] b * ^ * > | [a] b * ^ * ``` * * @type {State} */ function after(code) { if (code === 40) return effects.attempt(resourceConstruct, labelEndOk, defined ? labelEndOk : labelEndNok)(code); if (code === 91) return effects.attempt(referenceFullConstruct, labelEndOk, defined ? referenceNotFull : labelEndNok)(code); return defined ? labelEndOk(code) : labelEndNok(code); } /** * After `]`, at `[`, but not at a full reference. * * > 👉 **Note**: we only get here if the label is defined. * * ```markdown * > | [a][] b * ^ * > | [a] b * ^ * ``` * * @type {State} */ function referenceNotFull(code) { return effects.attempt(referenceCollapsedConstruct, labelEndOk, labelEndNok)(code); } /** * Done, we found something. * * ```markdown * > | [a](b) c * ^ * > | [a][b] c * ^ * > | [a][] b * ^ * > | [a] b * ^ * ``` * * @type {State} */ function labelEndOk(code) { labelStarts.pop(); return ok(code); } /** * Done, it’s nothing. * * There was an okay opening, but we didn’t match anything. * * ```markdown * > | [a](b c * ^ * > | [a][b c * ^ * > | [a] b * ^ * ``` * * @type {State} */ function labelEndNok(code) { labelStart._balanced = true; return nok(code); } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeResource(effects, ok, nok) { return resourceStart; /** * At a resource. * * ```markdown * > | [a](b) c * ^ * ``` * * @type {State} */ function resourceStart(code) { effects.enter("resource"); effects.enter("resourceMarker"); effects.consume(code); effects.exit("resourceMarker"); return resourceBefore; } /** * In resource, after `(`, at optional whitespace. * * ```markdown * > | [a](b) c * ^ * ``` * * @type {State} */ function resourceBefore(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceOpen)(code) : resourceOpen(code); } /** * In resource, after optional whitespace, at `)` or a destination. * * ```markdown * > | [a](b) c * ^ * ``` * * @type {State} */ function resourceOpen(code) { if (code === 41) return resourceEnd(code); return factoryDestination(effects, resourceDestinationAfter, resourceDestinationMissing, "resourceDestination", "resourceDestinationLiteral", "resourceDestinationLiteralMarker", "resourceDestinationRaw", "resourceDestinationString", 32)(code); } /** * In resource, after destination, at optional whitespace. * * ```markdown * > | [a](b) c * ^ * ``` * * @type {State} */ function resourceDestinationAfter(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceBetween)(code) : resourceEnd(code); } /** * At invalid destination. * * ```markdown * > | [a](<<) b * ^ * ``` * * @type {State} */ function resourceDestinationMissing(code) { return nok(code); } /** * In resource, after destination and whitespace, at `(` or title. * * ```markdown * > | [a](b ) c * ^ * ``` * * @type {State} */ function resourceBetween(code) { if (code === 34 || code === 39 || code === 40) return factoryTitle(effects, resourceTitleAfter, nok, "resourceTitle", "resourceTitleMarker", "resourceTitleString")(code); return resourceEnd(code); } /** * In resource, after title, at optional whitespace. * * ```markdown * > | [a](b "c") d * ^ * ``` * * @type {State} */ function resourceTitleAfter(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceEnd)(code) : resourceEnd(code); } /** * In resource, at `)`. * * ```markdown * > | [a](b) d * ^ * ``` * * @type {State} */ function resourceEnd(code) { if (code === 41) { effects.enter("resourceMarker"); effects.consume(code); effects.exit("resourceMarker"); effects.exit("resource"); return ok; } return nok(code); } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeReferenceFull(effects, ok, nok) { const self = this; return referenceFull; /** * In a reference (full), at the `[`. * * ```markdown * > | [a][b] d * ^ * ``` * * @type {State} */ function referenceFull(code) { return factoryLabel.call(self, effects, referenceFullAfter, referenceFullMissing, "reference", "referenceMarker", "referenceString")(code); } /** * In a reference (full), after `]`. * * ```markdown * > | [a][b] d * ^ * ``` * * @type {State} */ function referenceFullAfter(code) { return self.parser.defined.includes(normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1))) ? ok(code) : nok(code); } /** * In reference (full) that was missing. * * ```markdown * > | [a][b d * ^ * ``` * * @type {State} */ function referenceFullMissing(code) { return nok(code); } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeReferenceCollapsed(effects, ok, nok) { return referenceCollapsedStart; /** * In reference (collapsed), at `[`. * * > 👉 **Note**: we only get here if the label is defined. * * ```markdown * > | [a][] d * ^ * ``` * * @type {State} */ function referenceCollapsedStart(code) { effects.enter("reference"); effects.enter("referenceMarker"); effects.consume(code); effects.exit("referenceMarker"); return referenceCollapsedOpen; } /** * In reference (collapsed), at `]`. * * > 👉 **Note**: we only get here if the label is defined. * * ```markdown * > | [a][] d * ^ * ``` * * @type {State} */ function referenceCollapsedOpen(code) { if (code === 93) { effects.enter("referenceMarker"); effects.consume(code); effects.exit("referenceMarker"); effects.exit("reference"); return ok; } return nok(code); } } // node_modules/micromark-core-commonmark/lib/label-start-image.js /** * @import { * Construct, * State, * Token, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const labelStartImage = { name: "labelStartImage", resolveAll: labelEnd.resolveAll, tokenize: tokenizeLabelStartImage }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeLabelStartImage(effects, ok, nok) { const self = this; /** @type {Token} */ let labelImage; return start; /** * Start of label (image) start. * * ```markdown * > | a ![b] c * ^ * ``` * * @type {State} */ function start(code) { effects.enter("labelImage"); effects.enter("labelImageMarker"); effects.consume(code); effects.exit("labelImageMarker"); return open; } /** * After `!`, at `[`. * * ```markdown * > | a ![b] c * ^ * ``` * * @type {State} */ function open(code) { if (code === 91) { effects.enter("labelMarker"); effects.consume(code); effects.exit("labelMarker"); labelImage = effects.exit("labelImage"); return after; } return nok(code); } /** * After `![`. * * ```markdown * > | a ![b] c * ^ * ``` * * This is needed in because, when GFM footnotes are enabled, images never * form when started with a `^`. * Instead, links form: * * ```markdown * ![^a](b) * * ![^a][b] * * [b]: c * ``` * * ```html * <p>!<a href=\"b\">^a</a></p> * <p>!<a href=\"c\">^a</a></p> * ``` * * @type {State} */ function after(code) { /* c8 ignore next 6 */ if (code === 94 && "_hiddenFootnoteSupport" in self.parser.constructs) return nok(code); self._labelStarts = self._labelStarts || []; self._labelStarts.push(labelImage); return ok(code); } } // node_modules/micromark-core-commonmark/lib/label-start-link.js /** * @import { * Construct, * State, * Token, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const labelStartLink = { name: "labelStartLink", resolveAll: labelEnd.resolveAll, tokenize: tokenizeLabelStartLink }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeLabelStartLink(effects, ok, nok) { const self = this; /** @type {Token} */ let labelLink; return start; /** * Start of label (link) start. * * ```markdown * > | a [b] c * ^ * ``` * * @type {State} */ function start(code) { effects.enter("labelLink"); effects.enter("labelMarker"); effects.consume(code); effects.exit("labelMarker"); labelLink = effects.exit("labelLink"); return after; } /** @type {State} */ function after(code) { /* c8 ignore next 6 */ if (code === 94 && "_hiddenFootnoteSupport" in self.parser.constructs) return nok(code); self._labelStarts = self._labelStarts || []; self._labelStarts.push(labelLink); return ok(code); } } // node_modules/micromark-core-commonmark/lib/line-ending.js /** * @import { * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const lineEnding = { name: "lineEnding", tokenize: tokenizeLineEnding }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeLineEnding(effects, ok) { return start; /** @type {State} */ function start(code) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return factorySpace(effects, ok, "linePrefix"); } } // node_modules/micromark-core-commonmark/lib/thematic-break.js /** * @import { * Code, * Construct, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const thematicBreak = { name: "thematicBreak", tokenize: tokenizeThematicBreak }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeThematicBreak(effects, ok, nok) { let size = 0; /** @type {NonNullable<Code>} */ let marker; return start; /** * Start of thematic break. * * ```markdown * > | *** * ^ * ``` * * @type {State} */ function start(code) { effects.enter("thematicBreak"); return before(code); } /** * After optional whitespace, at marker. * * ```markdown * > | *** * ^ * ``` * * @type {State} */ function before(code) { marker = code; return atBreak(code); } /** * After something, before something else. * * ```markdown * > | *** * ^ * ``` * * @type {State} */ function atBreak(code) { if (code === marker) { effects.enter("thematicBreakSequence"); return sequence(code); } if (size >= 3 && (code === null || markdownLineEnding(code))) { effects.exit("thematicBreak"); return ok(code); } return nok(code); } /** * In sequence. * * ```markdown * > | *** * ^ * ``` * * @type {State} */ function sequence(code) { if (code === marker) { effects.consume(code); size++; return sequence; } effects.exit("thematicBreakSequence"); return markdownSpace(code) ? factorySpace(effects, atBreak, "whitespace")(code) : atBreak(code); } } // node_modules/micromark-core-commonmark/lib/list.js /** * @import { * Code, * Construct, * Exiter, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const list = { continuation: { tokenize: tokenizeListContinuation }, exit: tokenizeListEnd, name: "list", tokenize: tokenizeListStart }; /** @type {Construct} */ const listItemPrefixWhitespaceConstruct = { partial: true, tokenize: tokenizeListItemPrefixWhitespace }; /** @type {Construct} */ const indentConstruct = { partial: true, tokenize: tokenizeIndent$1 }; /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeListStart(effects, ok, nok) { const self = this; const tail = self.events[self.events.length - 1]; let initialSize = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0; let size = 0; return start; /** @type {State} */ function start(code) { const kind = self.containerState.type || (code === 42 || code === 43 || code === 45 ? "listUnordered" : "listOrdered"); if (kind === "listUnordered" ? !self.containerState.marker || code === self.containerState.marker : asciiDigit(code)) { if (!self.containerState.type) { self.containerState.type = kind; effects.enter(kind, { _container: true }); } if (kind === "listUnordered") { effects.enter("listItemPrefix"); return code === 42 || code === 45 ? effects.check(thematicBreak, nok, atMarker)(code) : atMarker(code); } if (!self.interrupt || code === 49) { effects.enter("listItemPrefix"); effects.enter("listItemValue"); return inside(code); } } return nok(code); } /** @type {State} */ function inside(code) { if (asciiDigit(code) && ++size < 10) { effects.consume(code); return inside; } if ((!self.interrupt || size < 2) && (self.containerState.marker ? code === self.containerState.marker : code === 41 || code === 46)) { effects.exit("listItemValue"); return atMarker(code); } return nok(code); } /** * @type {State} **/ function atMarker(code) { effects.enter("listItemMarker"); effects.consume(code); effects.exit("listItemMarker"); self.containerState.marker = self.containerState.marker || code; return effects.check(blankLine, self.interrupt ? nok : onBlank, effects.attempt(listItemPrefixWhitespaceConstruct, endOfPrefix, otherPrefix)); } /** @type {State} */ function onBlank(code) { self.containerState.initialBlankLine = true; initialSize++; return endOfPrefix(code); } /** @type {State} */ function otherPrefix(code) { if (markdownSpace(code)) { effects.enter("listItemPrefixWhitespace"); effects.consume(code); effects.exit("listItemPrefixWhitespace"); return endOfPrefix; } return nok(code); } /** @type {State} */ function endOfPrefix(code) { self.containerState.size = initialSize + self.sliceSerialize(effects.exit("listItemPrefix"), true).length; return ok(code); } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeListContinuation(effects, ok, nok) { const self = this; self.containerState._closeFlow = void 0; return effects.check(blankLine, onBlank, notBlank); /** @type {State} */ function onBlank(code) { self.containerState.furtherBlankLines = self.containerState.furtherBlankLines || self.containerState.initialBlankLine; return factorySpace(effects, ok, "listItemIndent", self.containerState.size + 1)(code); } /** @type {State} */ function notBlank(code) { if (self.containerState.furtherBlankLines || !markdownSpace(code)) { self.containerState.furtherBlankLines = void 0; self.containerState.initialBlankLine = void 0; return notInCurrentItem(code); } self.containerState.furtherBlankLines = void 0; self.containerState.initialBlankLine = void 0; return effects.attempt(indentConstruct, ok, notInCurrentItem)(code); } /** @type {State} */ function notInCurrentItem(code) { self.containerState._closeFlow = true; self.interrupt = void 0; return factorySpace(effects, effects.attempt(list, ok, nok), "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code); } } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeIndent$1(effects, ok, nok) { const self = this; return factorySpace(effects, afterPrefix, "listItemIndent", self.containerState.size + 1); /** @type {State} */ function afterPrefix(code) { const tail = self.events[self.events.length - 1]; return tail && tail[1].type === "listItemIndent" && tail[2].sliceSerialize(tail[1], true).length === self.containerState.size ? ok(code) : nok(code); } } /** * @this {TokenizeContext} * Context. * @type {Exiter} */ function tokenizeListEnd(effects) { effects.exit(this.containerState.type); } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeListItemPrefixWhitespace(effects, ok, nok) { const self = this; return factorySpace(effects, afterPrefix, "listItemPrefixWhitespace", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 5); /** @type {State} */ function afterPrefix(code) { const tail = self.events[self.events.length - 1]; return !markdownSpace(code) && tail && tail[1].type === "listItemPrefixWhitespace" ? ok(code) : nok(code); } } // node_modules/micromark-core-commonmark/lib/setext-underline.js /** * @import { * Code, * Construct, * Resolver, * State, * TokenizeContext, * Tokenizer * } from 'micromark-util-types' */ /** @type {Construct} */ const setextUnderline = { name: "setextUnderline", resolveTo: resolveToSetextUnderline, tokenize: tokenizeSetextUnderline }; /** @type {Resolver} */ function resolveToSetextUnderline(events, context) { const editMap = new EditMap$1(); let index = events.length; /** @type {number | undefined} */ let content; /** @type {number | undefined} */ let text; /** @type {number | undefined} */ let definition; while (index--) if (events[index][0] === "enter") { if (events[index][1].type === "content") { content = index; break; } if (events[index][1].type === "paragraph") text = index; } else { if (events[index][1].type === "content") editMap.add(index, 1, []); if (!definition && events[index][1].type === "definition") definition = index; } const heading = { type: "setextHeading", start: { ...events[content][1].start }, end: { ...events[events.length - 1][1].end } }; events[text][1].type = "setextHeadingText"; if (definition) { editMap.add(text, 0, [[ "enter", heading, context ]]); editMap.add(definition + 1, 0, [[ "exit", events[content][1], context ]]); events[content][1].end = { ...events[definition][1].end }; } else events[content][1] = heading; editMap.add(events.length, 0, [[ "exit", heading, context ]]); editMap.consume(events); return events; } /** * @this {TokenizeContext} * Context. * @type {Tokenizer} */ function tokenizeSetextUnderline(effects, ok, nok) { const self = this; /** @type {NonNullable<Code>} */ let marker; return start; /** * At start of heading (setext) underline. * * ```markdown * | aa * > | == * ^ * ``` * * @type {State} */ function start(code) { let index = self.events.length; /** @type {boolean | undefined} */ let paragraph; while (index--) if (self.events[index][1].type !== "lineEnding" && self.events[index][1].type !== "linePrefix" && self.events[index][1].type !== "content") { paragraph = self.events[index][1].type === "paragraph"; break; } if (!self.parser.lazy[self.now().line] && (self.interrupt || paragraph)) { effects.enter("setextHeadingLine"); marker = code; return before(code); } return nok(code); } /** * After optional whitespace, at `-` or `=`. * * ```markdown * | aa * > | == * ^ * ``` * * @type {State} */ function before(code) { effects.enter("setextHeadingLineSequence"); return inside(code); } /** * In sequence. * * ```markdown * | aa * > | == * ^ * ``` * * @type {State} */ function inside(code) { if (code === marker) { effects.consume(code); return inside; } effects.exit("setextHeadingLineSequence"); return markdownSpace(code) ? factorySpace(effects, after, "lineSuffix")(code) : after(code); } /** * After sequence, after optional whitespace. * * ```markdown * | aa * > | == * ^ * ``` * * @type {State} */ function after(code) { if (code === null || markdownLineEnding(code)) { effects.exit("setextHeadingLine"); return ok(code); } return nok(code); } } // node_modules/micromark/lib/initialize/flow.js /** * @import { * InitialConstruct, * Initializer, * State, * TokenizeContext * } from 'micromark-util-types' */ /** @type {InitialConstruct} */ const flow$1 = { tokenize: initializeFlow }; /** * @this {TokenizeContext} * Self. * @type {Initializer} * Initializer. */ function initializeFlow(effects) { const self = this; const initial = effects.attempt(blankLine, atBlankEnding, effects.attempt(this.parser.constructs.flowInitial, afterConstruct, factorySpace(effects, effects.attempt(this.parser.constructs.flow, afterConstruct, effects.attempt(content, afterConstruct)), "linePrefix"))); return initial; /** @type {State} */ function atBlankEnding(code) { if (code === null) { effects.consume(code); return; } effects.enter("lineEndingBlank"); effects.consume(code); effects.exit("lineEndingBlank"); self.currentConstruct = void 0; return initial; } /** @type {State} */ function afterConstruct(code) { if (code === null) { effects.consume(code); return; } effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); self.currentConstruct = void 0; return initial; } } // node_modules/micromark/lib/initialize/text.js /** * @import { * Code, * InitialConstruct, * Initializer, * Resolver, * State, * TokenizeContext * } from 'micromark-util-types' */ const resolver = { resolveAll: createResolver() }; const string$1 = initializeFactory("string"); const text$5 = initializeFactory("text"); /** * @param {'string' | 'text'} field * Field. * @returns {InitialConstruct} * Construct. */ function initializeFactory(field) { return { resolveAll: createResolver(field === "text" ? resolveAllLineSuffixes : void 0), tokenize: initializeText }; /** * @this {TokenizeContext} * Context. * @type {Initializer} */ function initializeText(effects) { const self = this; const constructs = this.parser.constructs[field]; const text = effects.attempt(constructs, start, notText); return start; /** @type {State} */ function start(code) { return atBreak(code) ? text(code) : notText(code); } /** @type {State} */ function notText(code) { if (code === null) { effects.consume(code); return; } effects.enter("data"); effects.consume(code); return data; } /** @type {State} */ function data(code) { if (atBreak(code)) { effects.exit("data"); return text(code); } effects.consume(code); return data; } /** * @param {Code} code * Code. * @returns {boolean} * Whether the code is a break. */ function atBreak(code) { if (code === null) return true; const list = constructs[code]; let index = -1; if (list) while (++index < list.length) { const item = list[index]; if (!item.previous || item.previous.call(self, self.previous)) return true; } return false; } } } /** * @param {Resolver | undefined} [extraResolver] * Resolver. * @returns {Resolver} * Resolver. */ function createResolver(extraResolver) { return resolveAllText; /** @type {Resolver} */ function resolveAllText(events, context) { let index = -1; /** @type {number | undefined} */ let enter; while (++index <= events.length) if (enter === void 0) { if (events[index] && events[index][1].type === "data") { enter = index; index++; } } else if (!events[index] || events[index][1].type !== "data") { if (index !== enter + 2) { events[enter][1].end = events[index - 1][1].end; events.splice(enter + 2, index - enter - 2); index = enter + 2; } enter = void 0; } return extraResolver ? extraResolver(events, context) : events; } } /** * A rather ugly set of instructions which again looks at chunks in the input * stream. * The reason to do this here is that it is *much* faster to parse in reverse. * And that we can’t hook into `null` to split the line suffix before an EOF. * To do: figure out if we can make this into a clean utility, or even in core. * As it will be useful for GFMs literal autolink extension (and maybe even * tables?) * * @type {Resolver} */ function resolveAllLineSuffixes(events, context) { const editMap = new EditMap$1(); let eventIndex = 0; while (++eventIndex <= events.length) if ((eventIndex === events.length || events[eventIndex][1].type === "lineEnding") && events[eventIndex - 1][1].type === "data") { const data = events[eventIndex - 1][1]; const chunks = context.sliceStream(data); let index = chunks.length; let bufferIndex = -1; let size = 0; /** @type {boolean | undefined} */ let tabs; while (index--) { const chunk = chunks[index]; if (typeof chunk === "string") { bufferIndex = chunk.length; while (chunk.charCodeAt(bufferIndex - 1) === 32) { size++; bufferIndex--; } if (bufferIndex) break; bufferIndex = -1; } else if (chunk === -2) { tabs = true; size++; } else if (chunk === -1) {} else { index++; break; } } if (context._contentTypeTextTrailing && eventIndex === events.length) size = 0; if (size) { const token = { type: eventIndex === events.length || tabs || size < 2 ? "lineSuffix" : "hardBreakTrailing", start: { _bufferIndex: index ? bufferIndex : data.start._bufferIndex + bufferIndex, _index: data.start._index + index, line: data.end.line, column: data.end.column - size, offset: data.end.offset - size }, end: { ...data.end } }; data.end = { ...token.start }; if (data.start.offset === data.end.offset) Object.assign(data, token); else editMap.add(eventIndex, 0, [[ "enter", token, context ], [ "exit", token, context ]]); } eventIndex++; } editMap.consume(events); return events; } // node_modules/micromark/lib/constructs.js /** * @import {Extension} from 'micromark-util-types' */ var constructs_exports = /* @__PURE__ */ __exportAll({ attentionMarkers: () => attentionMarkers, contentInitial: () => contentInitial, disable: () => disable, document: () => document$1, flow: () => flow, flowInitial: () => flowInitial, insideSpan: () => insideSpan, string: () => string, text: () => text$4 }); /** @satisfies {Extension['document']} */ const document$1 = { [42]: list, [43]: list, [45]: list, [48]: list, [49]: list, [50]: list, [51]: list, [52]: list, [53]: list, [54]: list, [55]: list, [56]: list, [57]: list, [62]: blockQuote }; /** @satisfies {Extension['contentInitial']} */ const contentInitial = { [91]: definition }; /** @satisfies {Extension['flowInitial']} */ const flowInitial = { [-2]: codeIndented, [-1]: codeIndented, [32]: codeIndented }; /** @satisfies {Extension['flow']} */ const flow = { [35]: headingAtx, [42]: thematicBreak, [45]: [setextUnderline, thematicBreak], [60]: htmlFlow, [61]: setextUnderline, [95]: thematicBreak, [96]: codeFenced, [126]: codeFenced }; /** @satisfies {Extension['string']} */ const string = { [38]: characterReference, [92]: characterEscape }; /** @satisfies {Extension['text']} */ const text$4 = { [-5]: lineEnding, [-4]: lineEnding, [-3]: lineEnding, [33]: labelStartImage, [38]: characterReference, [42]: attention, [60]: [autolink, htmlText], [91]: labelStartLink, [92]: [hardBreakEscape, characterEscape], [93]: labelEnd, [95]: attention, [96]: codeText }; /** @satisfies {Extension['insideSpan']} */ const insideSpan = { null: [attention, resolver] }; /** @satisfies {Extension['attentionMarkers']} */ const attentionMarkers = { null: [42, 95] }; /** @satisfies {Extension['disable']} */ const disable = { null: [] }; // node_modules/micromark/lib/create-tokenizer.js /** * @import { * Chunk, * Code, * ConstructRecord, * Construct, * Effects, * InitialConstruct, * ParseContext, * Point, * State, * TokenizeContext, * Token * } from 'micromark-util-types' */ /** * @callback Restore * Restore the state. * @returns {undefined} * Nothing. * * @typedef Info * Info. * @property {Restore} restore * Restore. * @property {number} from * From. * * @callback ReturnHandle * Handle a successful run. * @param {Construct} construct * Construct. * @param {Info} info * Info. * @returns {undefined} * Nothing. */ /** * Create a tokenizer. * Tokenizers deal with one type of data (e.g., containers, flow, text). * The parser is the object dealing with it all. * `initialize` works like other constructs, except that only its `tokenize` * function is used, in which case it doesn’t receive an `ok` or `nok`. * `from` can be given to set the point before the first character, although * when further lines are indented, they must be set with `defineSkip`. * * @param {ParseContext} parser * Parser. * @param {InitialConstruct} initialize * Construct. * @param {Omit<Point, '_bufferIndex' | '_index'> | undefined} [from] * Point (optional). * @returns {TokenizeContext} * Context. */ function createTokenizer(parser, initialize, from) { /** @type {Point} */ let point = { _bufferIndex: -1, _index: 0, line: from && from.line || 1, column: from && from.column || 1, offset: from && from.offset || 0 }; /** @type {Record<string, number>} */ const columnStart = {}; /** @type {Array<Construct>} */ const resolveAllConstructs = []; /** @type {Array<Chunk>} */ let chunks = []; /** @type {Array<Token>} */ let stack = []; /** * Tools used for tokenizing. * * @type {Effects} */ const effects = { attempt: constructFactory(onsuccessfulconstruct), check: constructFactory(onsuccessfulcheck), consume, enter, exit, interrupt: constructFactory(onsuccessfulcheck, { interrupt: true }) }; /** * State and tools for resolving and serializing. * * @type {TokenizeContext} */ const context = { code: null, containerState: {}, defineSkip, events: [], now, parser, previous: null, sliceSerialize, sliceStream, write }; /** * The state function. * * @type {State | undefined} */ let state = initialize.tokenize.call(context, effects); if (initialize.resolveAll) resolveAllConstructs.push(initialize); return context; /** @type {TokenizeContext['write']} */ function write(slice) { chunks = push(chunks, slice); main(); if (chunks[chunks.length - 1] !== null) return []; addResult(initialize, 0); context.events = resolveAll(resolveAllConstructs, context.events, context); return context.events; } /** @type {TokenizeContext['sliceSerialize']} */ function sliceSerialize(token, expandTabs) { return serializeChunks(sliceStream(token), expandTabs); } /** @type {TokenizeContext['sliceStream']} */ function sliceStream(token) { return sliceChunks(chunks, token); } /** @type {TokenizeContext['now']} */ function now() { const { _bufferIndex, _index, line, column, offset } = point; return { _bufferIndex, _index, line, column, offset }; } /** @type {TokenizeContext['defineSkip']} */ function defineSkip(value) { columnStart[value.line] = value.column; accountForPotentialSkip(); } /** * Main loop (note that `_index` and `_bufferIndex` in `point` are modified by * `consume`). * Here is where we walk through the chunks, which either include strings of * several characters, or numerical character codes. * The reason to do this in a loop instead of a call is so the stack can * drain. * * @returns {undefined} * Nothing. */ function main() { while (point._index < chunks.length) { const chunk = chunks[point._index]; if (typeof chunk === "string") { const chunkIndex = point._index; if (point._bufferIndex < 0) point._bufferIndex = 0; while (point._index === chunkIndex && point._bufferIndex < chunk.length) go(chunk.charCodeAt(point._bufferIndex)); } else go(chunk); } } /** * Deal with one code. * * @param {Code} code * Code. * @returns {undefined} * Nothing. */ function go(code) { state = state(code); } /** @type {Effects['consume']} */ function consume(code) { if (markdownLineEnding(code)) { point.line++; point.column = 1; point.offset += code === -3 ? 2 : 1; accountForPotentialSkip(); } else if (code !== -1) { point.column++; point.offset++; } if (point._bufferIndex < 0) point._index++; else { point._bufferIndex++; if (point._bufferIndex === chunks[point._index].length) { point._bufferIndex = -1; point._index++; } } context.previous = code; } /** @type {Effects['enter']} */ function enter(type, fields) { /** @type {Token} */ const token = fields || {}; token.type = type; token.start = now(); context.events.push([ "enter", token, context ]); stack.push(token); return token; } /** @type {Effects['exit']} */ function exit(type) { const token = stack.pop(); token.end = now(); context.events.push([ "exit", token, context ]); return token; } /** * Use results. * * @type {ReturnHandle} */ function onsuccessfulconstruct(construct, info) { addResult(construct, info.from); } /** * Discard results. * * @type {ReturnHandle} */ function onsuccessfulcheck(_, info) { info.restore(); } /** * Factory to attempt/check/interrupt. * * @param {ReturnHandle} onreturn * Callback. * @param {{interrupt?: boolean | undefined} | undefined} [fields] * Fields. */ function constructFactory(onreturn, fields) { return hook; /** * Handle either an object mapping codes to constructs, a list of * constructs, or a single construct. * * @param {Array<Construct> | ConstructRecord | Construct} constructs * Constructs. * @param {State} returnState * State. * @param {State | undefined} [bogusState] * State. * @returns {State} * State. */ function hook(constructs, returnState, bogusState) { /** @type {ReadonlyArray<Construct>} */ let listOfConstructs; /** @type {number} */ let constructIndex; /** @type {Construct} */ let currentConstruct; /** @type {Info} */ let info; return Array.isArray(constructs) ? handleListOfConstructs(constructs) : "tokenize" in constructs ? handleListOfConstructs([constructs]) : handleMapOfConstructs(constructs); /** * Handle a list of construct. * * @param {ConstructRecord} map * Constructs. * @returns {State} * State. */ function handleMapOfConstructs(map) { return start; /** @type {State} */ function start(code) { const left = code !== null && map[code]; const all = code !== null && map.null; return handleListOfConstructs([...Array.isArray(left) ? left : left ? [left] : [], ...Array.isArray(all) ? all : all ? [all] : []])(code); } } /** * Handle a list of construct. * * @param {ReadonlyArray<Construct>} list * Constructs. * @returns {State} * State. */ function handleListOfConstructs(list) { listOfConstructs = list; constructIndex = 0; if (list.length === 0) return bogusState; return handleConstruct(list[constructIndex]); } /** * Handle a single construct. * * @param {Construct} construct * Construct. * @returns {State} * State. */ function handleConstruct(construct) { return start; /** @type {State} */ function start(code) { info = store(); currentConstruct = construct; if (!construct.partial) context.currentConstruct = construct; if (construct.name && context.parser.constructs.disable.null.includes(construct.name)) return nok(code); return construct.tokenize.call(fields ? Object.assign(Object.create(context), fields) : context, effects, ok, nok)(code); } } /** @type {State} */ function ok(code) { onreturn(currentConstruct, info); return returnState; } /** @type {State} */ function nok(code) { info.restore(); if (++constructIndex < listOfConstructs.length) return handleConstruct(listOfConstructs[constructIndex]); return bogusState; } } } /** * @param {Construct} construct * Construct. * @param {number} from * From. * @returns {undefined} * Nothing. */ function addResult(construct, from) { if (construct.resolveAll && !resolveAllConstructs.includes(construct)) resolveAllConstructs.push(construct); if (construct.resolve) splice(context.events, from, context.events.length - from, construct.resolve(context.events.slice(from), context)); if (construct.resolveTo) context.events = construct.resolveTo(context.events, context); } /** * Store state. * * @returns {Info} * Info. */ function store() { const startPoint = now(); const startPrevious = context.previous; const startCurrentConstruct = context.currentConstruct; const startEventsIndex = context.events.length; const startStack = Array.from(stack); return { from: startEventsIndex, restore }; /** * Restore state. * * @returns {undefined} * Nothing. */ function restore() { point = startPoint; context.previous = startPrevious; context.currentConstruct = startCurrentConstruct; context.events.length = startEventsIndex; stack = startStack; accountForPotentialSkip(); } } /** * Move the current point a bit forward in the line when it’s on a column * skip. * * @returns {undefined} * Nothing. */ function accountForPotentialSkip() { if (point.line in columnStart && point.column < 2) { point.column = columnStart[point.line]; point.offset += columnStart[point.line] - 1; } } } /** * Get the chunks from a slice of chunks in the range of a token. * * @param {ReadonlyArray<Chunk>} chunks * Chunks. * @param {Pick<Token, 'end' | 'start'>} token * Token. * @returns {Array<Chunk>} * Chunks. */ function sliceChunks(chunks, token) { const startIndex = token.start._index; const startBufferIndex = token.start._bufferIndex; const endIndex = token.end._index; const endBufferIndex = token.end._bufferIndex; /** @type {Array<Chunk>} */ let view; if (startIndex === endIndex) view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)]; else { view = chunks.slice(startIndex, endIndex); if (startBufferIndex > -1) { const head = view[0]; if (typeof head === "string") view[0] = head.slice(startBufferIndex); else view.shift(); } if (endBufferIndex > 0) view.push(chunks[endIndex].slice(0, endBufferIndex)); } return view; } /** * Get the string value of a slice of chunks. * * @param {ReadonlyArray<Chunk>} chunks * Chunks. * @param {boolean | undefined} [expandTabs=false] * Whether to expand tabs (default: `false`). * @returns {string} * Result. */ function serializeChunks(chunks, expandTabs) { let index = -1; /** @type {Array<string>} */ const result = []; /** @type {boolean | undefined} */ let atTab; while (++index < chunks.length) { const chunk = chunks[index]; /** @type {string} */ let value; if (typeof chunk === "string") value = chunk; else switch (chunk) { case -5: value = "\r"; break; case -4: value = "\n"; break; case -3: value = "\r\n"; break; case -2: value = expandTabs ? " " : " "; break; case -1: if (!expandTabs && atTab) continue; value = " "; break; default: value = String.fromCharCode(chunk); } atTab = chunk === -2; result.push(value); } return result.join(""); } // node_modules/micromark/lib/parse.js /** * @import { * Create, * FullNormalizedExtension, * InitialConstruct, * ParseContext, * ParseOptions * } from 'micromark-util-types' */ /** * @param {ParseOptions | null | undefined} [options] * Configuration (optional). * @returns {ParseContext} * Parser. */ function parse(options) { /** @type {ParseContext} */ const parser = { constructs: combineExtensions([constructs_exports, ...(options || {}).extensions || []]), content: create(content$1), defined: [], document: create(document$2), flow: create(flow$1), lazy: {}, string: create(string$1), text: create(text$5) }; return parser; /** * @param {InitialConstruct} initial * Construct to start with. * @returns {Create} * Create a tokenizer. */ function create(initial) { return creator; /** @type {Create} */ function creator(from) { return createTokenizer(parser, initial, from); } } } // node_modules/micromark/lib/postprocess.js /** * @import {Event} from 'micromark-util-types' */ /** * @param {Array<Event>} events * Events. * @returns {Array<Event>} * Events. */ function postprocess(events) { while (!subtokenize(events)); return events; } // node_modules/micromark/lib/preprocess.js /** * @import {Chunk, Code, Encoding, Value} from 'micromark-util-types' */ /** * @callback Preprocessor * Preprocess a value. * @param {Value} value * Value. * @param {Encoding | null | undefined} [encoding] * Encoding when `value` is a typed array (optional). * @param {boolean | null | undefined} [end=false] * Whether this is the last chunk (default: `false`). * @returns {Array<Chunk>} * Chunks. */ const search = /[\0\t\n\r]/g; /** * @returns {Preprocessor} * Preprocess a value. */ function preprocess() { let column = 1; let buffer = ""; /** @type {boolean | undefined} */ let start = true; /** @type {boolean | undefined} */ let atCarriageReturn; return preprocessor; /** @type {Preprocessor} */ function preprocessor(value, encoding, end) { value = buffer + (typeof value === "string" ? value.toString() : new TextDecoder(encoding || void 0).decode(value)); /** @type {Array<Chunk>} */ const chunks = []; let startPosition = 0; buffer = ""; if (start) { if (value.charCodeAt(0) === 65279) startPosition++; start = void 0; } while (startPosition < value.length) { search.lastIndex = startPosition; const match = search.exec(value); const endPosition = match && match.index !== void 0 ? match.index : value.length; const code = value.charCodeAt(endPosition); if (!match) { buffer = value.slice(startPosition); break; } if (code === 10 && startPosition === endPosition && atCarriageReturn) { chunks.push(-3); atCarriageReturn = void 0; } else { if (atCarriageReturn) { chunks.push(-5); atCarriageReturn = void 0; } if (startPosition < endPosition) { chunks.push(value.slice(startPosition, endPosition)); column += endPosition - startPosition; } switch (code) { case 0: chunks.push(65533); column++; break; case 9: { const next = Math.ceil(column / 4) * 4; chunks.push(-2); while (column++ < next) chunks.push(-1); break; } case 10: chunks.push(-4); column = 1; break; default: atCarriageReturn = true; column = 1; } } startPosition = endPosition + 1; } if (end) { if (atCarriageReturn) chunks.push(-5); if (buffer) chunks.push(buffer); chunks.push(null); } return chunks; } } // node_modules/micromark-util-decode-string/index.js const characterEscapeOrReference = /\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi; /** * Decode markdown strings (which occur in places such as fenced code info * strings, destinations, labels, and titles). * * The “string” content type allows character escapes and -references. * This decodes those. * * @param {string} value * Value to decode. * @returns {string} * Decoded value. */ function decodeString(value) { return value.replace(characterEscapeOrReference, decode); } /** * @param {string} $0 * Match. * @param {string} $1 * Character escape. * @param {string} $2 * Character reference. * @returns {string} * Decoded value */ function decode($0, $1, $2) { if ($1) return $1; if ($2.charCodeAt(0) === 35) { const head = $2.charCodeAt(1); const hex = head === 120 || head === 88; return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10); } return decodeNamedCharacterReference($2) || $0; } // node_modules/unist-util-stringify-position/lib/index.js /** * @typedef {import('unist').Node} Node * @typedef {import('unist').Point} Point * @typedef {import('unist').Position} Position */ /** * @typedef NodeLike * @property {string} type * @property {PositionLike | null | undefined} [position] * * @typedef PointLike * @property {number | null | undefined} [line] * @property {number | null | undefined} [column] * @property {number | null | undefined} [offset] * * @typedef PositionLike * @property {PointLike | null | undefined} [start] * @property {PointLike | null | undefined} [end] */ /** * Serialize the positional info of a point, position (start and end points), * or node. * * @param {Node | NodeLike | Point | PointLike | Position | PositionLike | null | undefined} [value] * Node, position, or point. * @returns {string} * Pretty printed positional info of a node (`string`). * * In the format of a range `ls:cs-le:ce` (when given `node` or `position`) * or a point `l:c` (when given `point`), where `l` stands for line, `c` for * column, `s` for `start`, and `e` for end. * An empty string (`''`) is returned if the given value is neither `node`, * `position`, nor `point`. */ function stringifyPosition(value) { if (!value || typeof value !== "object") return ""; if ("position" in value || "type" in value) return position(value.position); if ("start" in value || "end" in value) return position(value); if ("line" in value || "column" in value) return point$1(value); return ""; } /** * @param {Point | PointLike | null | undefined} point * @returns {string} */ function point$1(point) { return index(point && point.line) + ":" + index(point && point.column); } /** * @param {Position | PositionLike | null | undefined} pos * @returns {string} */ function position(pos) { return point$1(pos && pos.start) + "-" + point$1(pos && pos.end); } /** * @param {number | null | undefined} value * @returns {number} */ function index(value) { return value && typeof value === "number" ? value : 1; } // node_modules/mdast-util-from-markdown/lib/index.js /** * @import { * Break, * Blockquote, * Code, * Definition, * Emphasis, * Heading, * Html, * Image, * InlineCode, * Link, * ListItem, * List, * Nodes, * Paragraph, * PhrasingContent, * ReferenceType, * Root, * Strong, * Text, * ThematicBreak * } from 'mdast' * @import { * Encoding, * Event, * Token, * Value * } from 'micromark-util-types' * @import {Point} from 'unist' * @import { * CompileContext, * CompileData, * Config, * Extension, * Handle, * OnEnterError, * Options * } from './types.js' */ const own = {}.hasOwnProperty; /** * Turn markdown into a syntax tree. * * @overload * @param {Value} value * @param {Encoding | null | undefined} [encoding] * @param {Options | null | undefined} [options] * @returns {Root} * * @overload * @param {Value} value * @param {Options | null | undefined} [options] * @returns {Root} * * @param {Value} value * Markdown to parse. * @param {Encoding | Options | null | undefined} [encoding] * Character encoding for when `value` is `Buffer`. * @param {Options | null | undefined} [options] * Configuration. * @returns {Root} * mdast tree. */ function fromMarkdown(value, encoding, options) { if (encoding && typeof encoding === "object") { options = encoding; encoding = void 0; } return compiler(options)(postprocess(parse(options).document().write(preprocess()(value, encoding, true)))); } /** * Note this compiler only understand complete buffering, not streaming. * * @param {Options | null | undefined} [options] */ function compiler(options) { /** @type {Config} */ const config = { afterExit: [], beforeEnter: [], transforms: [], canContainEols: [ "emphasis", "fragment", "heading", "paragraph", "strong" ], enter: { autolink: opener(link), autolinkProtocol: onenterdata, autolinkEmail: onenterdata, atxHeading: opener(heading), blockQuote: opener(blockQuote), characterEscape: onenterdata, characterReference: onenterdata, codeFenced: opener(codeFlow), codeFencedFenceInfo: buffer, codeFencedFenceMeta: buffer, codeIndented: opener(codeFlow, buffer), codeText: opener(codeText, buffer), codeTextData: onenterdata, data: onenterdata, codeFlowValue: onenterdata, definition: opener(definition), definitionDestinationString: buffer, definitionLabelString: buffer, definitionTitleString: buffer, emphasis: opener(emphasis), hardBreakEscape: opener(hardBreak), hardBreakTrailing: opener(hardBreak), htmlFlow: opener(html, buffer), htmlFlowData: onenterdata, htmlText: opener(html, buffer), htmlTextData: onenterdata, image: opener(image), label: buffer, link: opener(link), listItem: opener(listItem), listItemValue: onenterlistitemvalue, listOrdered: opener(list, onenterlistordered), listUnordered: opener(list), paragraph: opener(paragraph), reference: onenterreference, referenceString: buffer, resourceDestinationString: buffer, resourceTitleString: buffer, setextHeading: opener(heading), strong: opener(strong), thematicBreak: opener(thematicBreak) }, exit: { atxHeading: closer(), atxHeadingSequence: onexitatxheadingsequence, autolink: closer(), autolinkEmail: onexitautolinkemail, autolinkProtocol: onexitautolinkprotocol, blockQuote: closer(), characterEscapeValue: onexitdata, characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker, characterReferenceMarkerNumeric: onexitcharacterreferencemarker, characterReferenceValue: onexitcharacterreferencevalue, characterReference: onexitcharacterreference, codeFenced: closer(onexitcodefenced), codeFencedFence: onexitcodefencedfence, codeFencedFenceInfo: onexitcodefencedfenceinfo, codeFencedFenceMeta: onexitcodefencedfencemeta, codeFlowValue: onexitdata, codeIndented: closer(onexitcodeindented), codeText: closer(onexitcodetext), codeTextData: onexitdata, data: onexitdata, definition: closer(), definitionDestinationString: onexitdefinitiondestinationstring, definitionLabelString: onexitdefinitionlabelstring, definitionTitleString: onexitdefinitiontitlestring, emphasis: closer(), hardBreakEscape: closer(onexithardbreak), hardBreakTrailing: closer(onexithardbreak), htmlFlow: closer(onexithtmlflow), htmlFlowData: onexitdata, htmlText: closer(onexithtmltext), htmlTextData: onexitdata, image: closer(onexitimage), label: onexitlabel, labelText: onexitlabeltext, lineEnding: onexitlineending, link: closer(onexitlink), listItem: closer(), listOrdered: closer(), listUnordered: closer(), paragraph: closer(), referenceString: onexitreferencestring, resourceDestinationString: onexitresourcedestinationstring, resourceTitleString: onexitresourcetitlestring, resource: onexitresource, setextHeading: closer(onexitsetextheading), setextHeadingLineSequence: onexitsetextheadinglinesequence, setextHeadingText: onexitsetextheadingtext, strong: closer(), thematicBreak: closer() } }; configure(config, (options || {}).mdastExtensions || []); /** @type {CompileData} */ const data = {}; return compile; /** * Turn micromark events into an mdast tree. * * @param {Array<Event>} events * Events. * @returns {Root} * mdast tree. */ function compile(events) { /** @type {Root} */ let tree = { type: "root", children: [], position: void 0 }; /** @type {Omit<CompileContext, 'sliceSerialize'>} */ const context = { stack: [tree], tokenStack: [], config, enter, exit, buffer, resume, data }; /** @type {Array<number>} */ const listStack = []; /** @type {Array<Event>} */ const prepared = []; let index = -1; while (++index < events.length) { prepared.push(events[index]); if (events[index][1].type === "listOrdered" || events[index][1].type === "listUnordered") { if (events[index][0] === "enter") listStack.push(prepared.length - 1); else prepareList(prepared, listStack.pop()); } } events = prepared; index = -1; while (++index < events.length) { const handler = config[events[index][0]]; if (events[index][0] === "enter" && config.beforeEnter.length > 0) callListeners(config.beforeEnter, { ...context, sliceSerialize: events[index][2].sliceSerialize }, events[index][1]); if (own.call(handler, events[index][1].type)) handler[events[index][1].type].call({ ...context, sliceSerialize: events[index][2].sliceSerialize }, events[index][1]); if (events[index][0] === "exit" && config.afterExit.length > 0) callListeners(config.afterExit, { ...context, sliceSerialize: events[index][2].sliceSerialize }, events[index][1]); } if (context.tokenStack.length > 0) { const tail = context.tokenStack[context.tokenStack.length - 1]; (tail[1] || defaultOnError).call(context, void 0, tail[0]); } tree.position = { start: point(events.length > 0 ? events[0][1].start : { line: 1, column: 1, offset: 0 }), end: point(events.length > 0 ? events[events.length - 2][1].end : { line: 1, column: 1, offset: 0 }) }; index = -1; while (++index < config.transforms.length) tree = config.transforms[index](tree) || tree; return tree; } /** * @param {Array<Handle>} listeners * Listeners. * @param {CompileContext} context * Context. * @param {Token} token * Token. * @returns {undefined} * Nothing. */ function callListeners(listeners, context, token) { let index = -1; while (++index < listeners.length) listeners[index].call(context, token); } /** * @param {Array<Event>} events * Events, ending with the list to prepare. * @param {number} start * Index of the list enter. * @returns {undefined} */ function prepareList(events, start) { const end = events.length - 1; let index = start - 1; let containerBalance = -1; let listSpread = false; /** @type {Token | undefined} */ let listItem; /** @type {number | undefined} */ let lineIndex; /** @type {number | undefined} */ let firstBlankLineIndex; /** @type {boolean | undefined} */ let atMarker; /** * `listItem` events to insert before the event at `at`, in walk order. * Merged in after the walk, as inserting while walking would shift the * rest of the list once per item. * @type {Array<{at: number, event: Event}>} */ const insertions = []; while (++index <= end) { const event = events[index]; switch (event[1].type) { case "listUnordered": case "listOrdered": case "blockQuote": if (event[0] === "enter") containerBalance++; else containerBalance--; atMarker = void 0; break; case "lineEndingBlank": if (event[0] === "enter") { if (listItem && !atMarker && !containerBalance && !firstBlankLineIndex) firstBlankLineIndex = index; atMarker = void 0; } break; case "linePrefix": case "listItemValue": case "listItemMarker": case "listItemPrefix": case "listItemPrefixWhitespace": break; default: atMarker = void 0; } if (!containerBalance && event[0] === "enter" && event[1].type === "listItemPrefix" || containerBalance === -1 && event[0] === "exit" && (event[1].type === "listUnordered" || event[1].type === "listOrdered")) { if (listItem) { let tailIndex = index; lineIndex = void 0; while (tailIndex--) { const tailEvent = events[tailIndex]; if (tailEvent[1].type === "lineEnding" || tailEvent[1].type === "lineEndingBlank") { if (tailEvent[0] === "exit") continue; if (lineIndex) { events[lineIndex][1].type = "lineEndingBlank"; listSpread = true; } tailEvent[1].type = "lineEnding"; lineIndex = tailIndex; } else if (tailEvent[1].type === "linePrefix" || tailEvent[1].type === "blockQuotePrefix" || tailEvent[1].type === "blockQuotePrefixWhitespace" || tailEvent[1].type === "blockQuoteMarker" || tailEvent[1].type === "listItemIndent") {} else break; } if (firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex)) listItem._spread = true; listItem.end = Object.assign({}, lineIndex ? events[lineIndex][1].start : event[1].end); insertions.push({ at: lineIndex || index, event: [ "exit", listItem, event[2] ] }); } if (event[1].type === "listItemPrefix") { /** @type {Token} */ const item = { type: "listItem", _spread: false, start: Object.assign({}, event[1].start), end: void 0 }; listItem = item; insertions.push({ at: index, event: [ "enter", item, event[2] ] }); firstBlankLineIndex = void 0; atMarker = true; } } } const listEvents = events.splice(start); let insertion = 0; index = -1; while (++index < listEvents.length) { while (insertion < insertions.length && insertions[insertion].at === start + index) events.push(insertions[insertion++].event); events.push(listEvents[index]); } events[start][1]._spread = listSpread; } /** * Create an opener handle. * * @param {(token: Token) => Nodes} create * Create a node. * @param {Handle | undefined} [and] * Optional function to also run. * @returns {Handle} * Handle. */ function opener(create, and) { return open; /** * @this {CompileContext} * @param {Token} token * @returns {undefined} */ function open(token) { enter.call(this, create(token), token); if (and) and.call(this, token); } } /** * @type {CompileContext['buffer']} */ function buffer() { this.stack.push({ type: "fragment", children: [] }); } /** * @type {CompileContext['enter']} */ function enter(node, token, errorHandler) { this.stack[this.stack.length - 1].children.push(node); this.stack.push(node); this.tokenStack.push([token, errorHandler || void 0]); node.position = { start: point(token.start), end: void 0 }; } /** * Create a closer handle. * * @param {Handle | undefined} [and] * Optional function to also run. * @returns {Handle} * Handle. */ function closer(and) { return close; /** * @this {CompileContext} * @param {Token} token * @returns {undefined} */ function close(token) { if (and) and.call(this, token); exit.call(this, token); } } /** * @type {CompileContext['exit']} */ function exit(token, onExitError) { const node = this.stack.pop(); const open = this.tokenStack.pop(); if (!open) throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({ start: token.start, end: token.end }) + "): it’s not open"); if (open[0].type !== token.type) { if (onExitError) onExitError.call(this, token, open[0]); else (open[1] || defaultOnError).call(this, token, open[0]); } node.position.end = point(token.end); } /** * @type {CompileContext['resume']} */ function resume() { return toString(this.stack.pop()); } /** * @this {CompileContext} * @type {Handle} */ function onenterlistordered() { this.data.expectingFirstListItemValue = true; } /** * @this {CompileContext} * @type {Handle} */ function onenterlistitemvalue(token) { if (this.data.expectingFirstListItemValue) { const ancestor = this.stack[this.stack.length - 2]; ancestor.start = Number.parseInt(this.sliceSerialize(token), 10); this.data.expectingFirstListItemValue = void 0; } } /** * @this {CompileContext} * @type {Handle} */ function onexitcodefencedfenceinfo() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.lang = data; } /** * @this {CompileContext} * @type {Handle} */ function onexitcodefencedfencemeta() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.meta = data; } /** * @this {CompileContext} * @type {Handle} */ function onexitcodefencedfence() { if (this.data.flowCodeInside) return; this.buffer(); this.data.flowCodeInside = true; } /** * @this {CompileContext} * @type {Handle} */ function onexitcodefenced() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.value = data.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, ""); this.data.flowCodeInside = void 0; } /** * @this {CompileContext} * @type {Handle} */ function onexitcodeindented() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.value = data.replace(/(\r?\n|\r)$/g, ""); } /** * @this {CompileContext} * @type {Handle} */ function onexitdefinitionlabelstring(token) { const label = this.resume(); const node = this.stack[this.stack.length - 1]; node.label = label; node.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase(); } /** * @this {CompileContext} * @type {Handle} */ function onexitdefinitiontitlestring() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.title = data; } /** * @this {CompileContext} * @type {Handle} */ function onexitdefinitiondestinationstring() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.url = data; } /** * @this {CompileContext} * @type {Handle} */ function onexitatxheadingsequence(token) { const node = this.stack[this.stack.length - 1]; if (!node.depth) node.depth = this.sliceSerialize(token).length; } /** * @this {CompileContext} * @type {Handle} */ function onexitsetextheadingtext() { this.data.setextHeadingSlurpLineEnding = true; } /** * @this {CompileContext} * @type {Handle} */ function onexitsetextheadinglinesequence(token) { const node = this.stack[this.stack.length - 1]; node.depth = this.sliceSerialize(token).codePointAt(0) === 61 ? 1 : 2; } /** * @this {CompileContext} * @type {Handle} */ function onexitsetextheading() { this.data.setextHeadingSlurpLineEnding = void 0; } /** * @this {CompileContext} * @type {Handle} */ function onenterdata(token) { /** @type {Array<Nodes>} */ const siblings = this.stack[this.stack.length - 1].children; let tail = siblings[siblings.length - 1]; if (!tail || tail.type !== "text") { tail = text(); tail.position = { start: point(token.start), end: void 0 }; siblings.push(tail); } this.stack.push(tail); } /** * @this {CompileContext} * @type {Handle} */ function onexitdata(token) { const tail = this.stack.pop(); tail.value += this.sliceSerialize(token); tail.position.end = point(token.end); } /** * @this {CompileContext} * @type {Handle} */ function onexitlineending(token) { const context = this.stack[this.stack.length - 1]; if (this.data.atHardBreak) { const tail = context.children[context.children.length - 1]; tail.position.end = point(token.end); this.data.atHardBreak = void 0; return; } if (!this.data.setextHeadingSlurpLineEnding && config.canContainEols.includes(context.type)) { onenterdata.call(this, token); onexitdata.call(this, token); } } /** * @this {CompileContext} * @type {Handle} */ function onexithardbreak() { this.data.atHardBreak = true; } /** * @this {CompileContext} * @type {Handle} */ function onexithtmlflow() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.value = data; } /** * @this {CompileContext} * @type {Handle} */ function onexithtmltext() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.value = data; } /** * @this {CompileContext} * @type {Handle} */ function onexitcodetext() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.value = data; } /** * @this {CompileContext} * @type {Handle} */ function onexitlink() { const node = this.stack[this.stack.length - 1]; if (this.data.inReference) { /** @type {ReferenceType} */ const referenceType = this.data.referenceType || "shortcut"; node.type += "Reference"; node.referenceType = referenceType; delete node.url; delete node.title; } else { delete node.identifier; delete node.label; } this.data.referenceType = void 0; } /** * @this {CompileContext} * @type {Handle} */ function onexitimage() { const node = this.stack[this.stack.length - 1]; if (this.data.inReference) { /** @type {ReferenceType} */ const referenceType = this.data.referenceType || "shortcut"; node.type += "Reference"; node.referenceType = referenceType; delete node.url; delete node.title; } else { delete node.identifier; delete node.label; } this.data.referenceType = void 0; } /** * @this {CompileContext} * @type {Handle} */ function onexitlabeltext(token) { const string = this.sliceSerialize(token); const ancestor = this.stack[this.stack.length - 2]; ancestor.label = decodeString(string); ancestor.identifier = normalizeIdentifier(string).toLowerCase(); } /** * @this {CompileContext} * @type {Handle} */ function onexitlabel() { const fragment = this.stack[this.stack.length - 1]; const value = this.resume(); const node = this.stack[this.stack.length - 1]; this.data.inReference = true; if (node.type === "link") node.children = fragment.children; else node.alt = value; } /** * @this {CompileContext} * @type {Handle} */ function onexitresourcedestinationstring() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.url = data; } /** * @this {CompileContext} * @type {Handle} */ function onexitresourcetitlestring() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.title = data; } /** * @this {CompileContext} * @type {Handle} */ function onexitresource() { this.data.inReference = void 0; } /** * @this {CompileContext} * @type {Handle} */ function onenterreference() { this.data.referenceType = "collapsed"; } /** * @this {CompileContext} * @type {Handle} */ function onexitreferencestring(token) { const label = this.resume(); const node = this.stack[this.stack.length - 1]; node.label = label; node.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase(); this.data.referenceType = "full"; } /** * @this {CompileContext} * @type {Handle} */ function onexitcharacterreferencemarker(token) { this.data.characterReferenceType = token.type; } /** * @this {CompileContext} * @type {Handle} */ function onexitcharacterreferencevalue(token) { const data = this.sliceSerialize(token); const type = this.data.characterReferenceType; /** @type {string} */ let value; if (type) { value = decodeNumericCharacterReference(data, type === "characterReferenceMarkerNumeric" ? 10 : 16); this.data.characterReferenceType = void 0; } else value = decodeNamedCharacterReference(data); const tail = this.stack[this.stack.length - 1]; tail.value += value; } /** * @this {CompileContext} * @type {Handle} */ function onexitcharacterreference(token) { const tail = this.stack.pop(); tail.position.end = point(token.end); } /** * @this {CompileContext} * @type {Handle} */ function onexitautolinkprotocol(token) { onexitdata.call(this, token); const node = this.stack[this.stack.length - 1]; node.url = this.sliceSerialize(token); } /** * @this {CompileContext} * @type {Handle} */ function onexitautolinkemail(token) { onexitdata.call(this, token); const node = this.stack[this.stack.length - 1]; node.url = "mailto:" + this.sliceSerialize(token); } /** @returns {Blockquote} */ function blockQuote() { return { type: "blockquote", children: [], position: void 0 }; } /** @returns {Code} */ function codeFlow() { return { type: "code", lang: null, meta: null, value: "", position: void 0 }; } /** @returns {InlineCode} */ function codeText() { return { type: "inlineCode", value: "", position: void 0 }; } /** @returns {Definition} */ function definition() { return { type: "definition", identifier: "", label: null, title: null, url: "", position: void 0 }; } /** @returns {Emphasis} */ function emphasis() { return { type: "emphasis", children: [], position: void 0 }; } /** @returns {Heading} */ function heading() { return { type: "heading", depth: 0, children: [], position: void 0 }; } /** @returns {Break} */ function hardBreak() { return { type: "break", position: void 0 }; } /** @returns {Html} */ function html() { return { type: "html", value: "", position: void 0 }; } /** @returns {Image} */ function image() { return { type: "image", title: null, url: "", alt: null, position: void 0 }; } /** @returns {Link} */ function link() { return { type: "link", title: null, url: "", children: [], position: void 0 }; } /** * @param {Token} token * @returns {List} */ function list(token) { return { type: "list", ordered: token.type === "listOrdered", start: null, spread: token._spread, children: [], position: void 0 }; } /** * @param {Token} token * @returns {ListItem} */ function listItem(token) { return { type: "listItem", spread: token._spread, checked: null, children: [], position: void 0 }; } /** @returns {Paragraph} */ function paragraph() { return { type: "paragraph", children: [], position: void 0 }; } /** @returns {Strong} */ function strong() { return { type: "strong", children: [], position: void 0 }; } /** @returns {Text} */ function text() { return { type: "text", value: "", position: void 0 }; } /** @returns {ThematicBreak} */ function thematicBreak() { return { type: "thematicBreak", position: void 0 }; } } /** * Copy a point-like value. * * @param {Point} d * Point-like value. * @returns {Point} * unist point. */ function point(d) { return { line: d.line, column: d.column, offset: d.offset }; } /** * @param {Config} combined * @param {Array<Array<Extension> | Extension>} extensions * @returns {undefined} */ function configure(combined, extensions) { let index = -1; while (++index < extensions.length) { const value = extensions[index]; if (Array.isArray(value)) configure(combined, value); else extension(combined, value); } } /** * @param {Config} combined * @param {Extension} extension * @returns {undefined} */ function extension(combined, extension) { /** @type {keyof Extension} */ let key; for (key in extension) if (own.call(extension, key)) switch (key) { case "canContainEols": { const right = extension[key]; if (right) combined[key].push(...right); break; } case "transforms": { const right = extension[key]; if (right) combined[key].push(...right); break; } case "afterExit": case "beforeEnter": { const right = extension[key]; if (right) combined[key].push(right); break; } case "enter": case "exit": { const right = extension[key]; if (right) Object.assign(combined[key], right); break; } } } /** @type {OnEnterError} */ function defaultOnError(left, right) { if (left) throw new Error("Cannot close `" + left.type + "` (" + stringifyPosition({ start: left.start, end: left.end }) + "): a different token (`" + right.type + "`, " + stringifyPosition({ start: right.start, end: right.end }) + ") is open"); throw new Error("Cannot close document, a token (`" + right.type + "`, " + stringifyPosition({ start: right.start, end: right.end }) + ") is still open"); } // node_modules/ccount/index.js /** * Count how often a character (or substring) is used in a string. * * @param {string} value * Value to search in. * @param {string} character * Character (or substring) to look for. * @return {number} * Number of times `character` occurred in `value`. */ function ccount(value, character) { const source = String(value); if (typeof character !== "string") throw new TypeError("Expected character"); let count = 0; let index = source.indexOf(character); while (index !== -1) { count++; index = source.indexOf(character, index + character.length); } return count; } // node_modules/escape-string-regexp/index.js function escapeStringRegexp(string) { if (typeof string !== "string") throw new TypeError("Expected a string"); return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d"); } // node_modules/unist-util-is/lib/index.js /** * Generate an assertion from a test. * * Useful if you’re going to test many nodes, for example when creating a * utility where something else passes a compatible test. * * The created function is a bit faster because it expects valid input only: * a `node`, `index`, and `parent`. * * @param {Test} test * * when nullish, checks if `node` is a `Node`. * * when `string`, works like passing `(node) => node.type === test`. * * when `function` checks if function passed the node is true. * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values. * * when `array`, checks if any one of the subtests pass. * @returns {Check} * An assertion. */ const convert = ( /** * @param {Test} [test] * @returns {Check} */ function(test) { if (test === null || test === void 0) return ok; if (typeof test === "function") return castFactory(test); if (typeof test === "object") return Array.isArray(test) ? anyFactory(test) : propertiesFactory(test); if (typeof test === "string") return typeFactory(test); throw new Error("Expected function, string, or object as test"); }); /** * @param {Array<Props | TestFunction | string>} tests * @returns {Check} */ function anyFactory(tests) { /** @type {Array<Check>} */ const checks = []; let index = -1; while (++index < tests.length) checks[index] = convert(tests[index]); return castFactory(any); /** * @this {unknown} * @type {TestFunction} */ function any(...parameters) { let index = -1; while (++index < checks.length) if (checks[index].apply(this, parameters)) return true; return false; } } /** * Turn an object into a test for a node with a certain fields. * * @param {Props} check * @returns {Check} */ function propertiesFactory(check) { const checkAsRecord = check; return castFactory(all); /** * @param {Node} node * @returns {boolean} */ function all(node) { const nodeAsRecord = node; /** @type {string} */ let key; for (key in check) if (nodeAsRecord[key] !== checkAsRecord[key]) return false; return true; } } /** * Turn a string into a test for a node with a certain type. * * @param {string} check * @returns {Check} */ function typeFactory(check) { return castFactory(type); /** * @param {Node} node */ function type(node) { return node && node.type === check; } } /** * Turn a custom test into a test for a node that passes that test. * * @param {TestFunction} testFunction * @returns {Check} */ function castFactory(testFunction) { return check; /** * @this {unknown} * @type {Check} */ function check(value, index, parent) { return Boolean(looksLikeANode(value) && testFunction.call(this, value, typeof index === "number" ? index : void 0, parent || void 0)); } } function ok() { return true; } /** * @param {unknown} value * @returns {value is Node} */ function looksLikeANode(value) { return value !== null && typeof value === "object" && "type" in value; } // node_modules/unist-util-visit-parents/lib/color.node.js /** * Color a string. * * @param {string} d * Value. * @returns {string} * Colored value. */ function color(d) { return "\x1B[33m" + d + "\x1B[39m"; } // node_modules/unist-util-visit-parents/lib/index.js /** * @import {Node as UnistNode, Parent as UnistParent} from 'unist' */ /** * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test * Test from `unist-util-is`. * * Note: we have remove and add `undefined`, because otherwise when generating * automatic `.d.ts` files, TS tries to flatten paths from a local perspective, * which doesn’t work when publishing on npm. */ /** * @typedef {( * Fn extends (value: any) => value is infer Thing * ? Thing * : Fallback * )} Predicate * Get the value of a type guard `Fn`. * @template Fn * Value; typically function that is a type guard (such as `(x): x is Y`). * @template Fallback * Value to yield if `Fn` is not a type guard. */ /** * @typedef {( * Check extends null | undefined // No test. * ? Value * : Value extends {type: Check} // String (type) test. * ? Value * : Value extends Check // Partial test. * ? Value * : Check extends Function // Function test. * ? Predicate<Check, Value> extends Value * ? Predicate<Check, Value> * : never * : never // Some other test? * )} MatchesOne * Check whether a node matches a primitive check in the type system. * @template Value * Value; typically unist `Node`. * @template Check * Value; typically `unist-util-is`-compatible test, but not arrays. */ /** * @typedef {( * Check extends ReadonlyArray<infer T> * ? MatchesOne<Value, T> * : Check extends Array<infer T> * ? MatchesOne<Value, T> * : MatchesOne<Value, Check> * )} Matches * Check whether a node matches a check in the type system. * @template Value * Value; typically unist `Node`. * @template Check * Value; typically `unist-util-is`-compatible test. */ /** * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint * Number; capped reasonably. */ /** * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment * Increment a number in the type system. * @template {Uint} [I=0] * Index. */ /** * @typedef {( * Node extends UnistParent * ? Node extends {children: Array<infer Children>} * ? Child extends Children ? Node : never * : never * : never * )} InternalParent * Collect nodes that can be parents of `Child`. * @template {UnistNode} Node * All node types in a tree. * @template {UnistNode} Child * Node to search for. */ /** * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent * Collect nodes in `Tree` that can be parents of `Child`. * @template {UnistNode} Tree * All node types in a tree. * @template {UnistNode} Child * Node to search for. */ /** * @typedef {( * Depth extends Max * ? never * : * | InternalParent<Node, Child> * | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>> * )} InternalAncestor * Collect nodes in `Tree` that can be ancestors of `Child`. * @template {UnistNode} Node * All node types in a tree. * @template {UnistNode} Child * Node to search for. * @template {Uint} [Max=10] * Max; searches up to this depth. * @template {Uint} [Depth=0] * Current depth. */ /** * @typedef {InternalAncestor<InclusiveDescendant<Tree>, Child>} Ancestor * Collect nodes in `Tree` that can be ancestors of `Child`. * @template {UnistNode} Tree * All node types in a tree. * @template {UnistNode} Child * Node to search for. */ /** * @typedef {( * Tree extends UnistParent * ? Depth extends Max * ? Tree * : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>> * : Tree * )} InclusiveDescendant * Collect all (inclusive) descendants of `Tree`. * * > 👉 **Note**: for performance reasons, this seems to be the fastest way to * > recurse without actually running into an infinite loop, which the * > previous version did. * > * > Practically, a max of `2` is typically enough assuming a `Root` is * > passed, but it doesn’t improve performance. * > It gets higher with `List > ListItem > Table > TableRow > TableCell`. * > Using up to `10` doesn’t hurt or help either. * @template {UnistNode} Tree * Tree type. * @template {Uint} [Max=10] * Max; searches up to this depth. * @template {Uint} [Depth=0] * Current depth. */ /** * @typedef {'skip' | boolean} Action * Union of the action types. * * @typedef {number} Index * Move to the sibling at `index` next (after node itself is completely * traversed). * * Useful if mutating the tree, such as removing the node the visitor is * currently on, or any of its previous siblings. * Results less than 0 or greater than or equal to `children.length` stop * traversing the parent. * * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple * List with one or two values, the first an action, the second an index. * * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult * Any value that can be returned from an enter visitor. * * Like `VisitorResultExit`, * but `SKIP` can also be returned, * to not walk the children of the node, * and `ActionTuple` can be used to combine an action with an index. * * @typedef {Index | boolean | null | undefined | void} VisitorResultExit * Any value that can be returned from an exit visitor. */ /** * @callback Visitor * Handle a node (matching `test`, if given) before its children. * * Changes inside `node` are walked next. * Replacing or removing it is easier in `exit`. * When replacing or removing it here, * return `SKIP` (as otherwise its old children are walked), * or `[SKIP, index]` to continue with the node now at `index`. * Changing next siblings (in walk order) is fine; * changing previous siblings needs a new `Index`. * Removing an ancestor or changing its previous siblings is not supported. * @param {Visited} node * Found node. * @param {Array<VisitedParents>} ancestors * Ancestors of `node`. * @param {number | undefined} index * Index of `node` in its parent (the last of `ancestors`), * or `undefined` for the tree itself. * @returns {VisitorResult} * What to do next. * * Like `VisitorExit`, * but `SKIP` can also be returned, * to not walk the children of `node`. * Passing a tuple back (`ActionTuple`) only makes sense as `[SKIP, Index]`. * @template {UnistNode} [Visited=UnistNode] * Visited node type. * @template {UnistParent} [VisitedParents=UnistParent] * Ancestor type. */ /** * @callback VisitorExit * Handle a node (matching `test`, if given) after its children. * * Changes inside `node` are not walked, * which makes this a good place to change `node` based on its children, * or to replace or remove it. * When removing `node` or changing previous siblings (in walk order), * return a new `Index`. * Removing an ancestor or changing its previous siblings is not supported. * @param {Visited} node * Found node. * @param {Array<VisitedParents>} ancestors * Ancestors of `node`. * @param {number | undefined} index * Index of `node` in its parent (the last of `ancestors`), * or `undefined` for the tree itself. * @returns {VisitorResultExit} * What to do next. * * `CONTINUE` (`true`, nothing) continues as normal, * `EXIT` (`false`) stops traversing, * and `Index` continues at that sibling. * @template {UnistNode} [Visited=UnistNode] * Visited node type. * @template {UnistParent} [VisitedParents=UnistParent] * Ancestor type. */ /** * @template {UnistNode} [Visited=UnistNode] * Visited node type. * @template {UnistParent} [VisitedParents=UnistParent] * Ancestor type. * @typedef Visitors * Handle nodes when entering and exiting them. * The `enter` visitor is optional while `exit` is required. * * Pass an `enter` visitor directly to only handle nodes when entering them. * * `enter` is called before children (if any) are walked and `exit` after that. * `exit` is still called when `enter` returns `SKIP`. * Both `enter` and `exit` are only called for nodes that match an optional `test`. * @property {Visitor<Visited, VisitedParents> | null | undefined} [enter] * Handle a node before its children (optional). * @property {VisitorExit<Visited, VisitedParents>} exit * Handle a node after its children. */ /** * @typedef {Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitor * Build a typed `Visitor` function from a tree and a test. * * It will infer which values are passed as `node` and which as `parents`. * @template {UnistNode} [Tree=UnistNode] * Tree type. * @template {Test} [Check=Test] * Test type. */ /** * @typedef {Visitors<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitors * Build typed `Visitors` from a tree and a test. * * It will infer which values are passed as `node` and which as `parents`. * @template {UnistNode} [Tree=UnistNode] * Tree type. * @template {Test} [Check=Test] * Test type. */ /** @type {Readonly<ActionTuple>} */ const empty = []; /** * Do not traverse this node’s children. * Only works when entering a node. */ const SKIP = "skip"; /** * Visit nodes, with ancestral information. * * This algorithm performs *depth-first* *tree traversal* in *preorder* * (**NLR**) or if `reverse` is given, * in *reverse preorder* (**NRL**). * An `exit` visitor is called in *postorder* (**LRN**) * or if `reverse` is given, in *reverse postorder* (**RLN**). * * You can choose which nodes are visited by passing a `test`. * For complex tests, you should test yourself in a visitor, as it will be * faster and will have improved type information. * * Walking the tree is an intensive task. * Make use of the return values of the visitor when possible. * Instead of walking a tree multiple times, walk it once, use `unist-util-is` * to check if a node matches, and then perform different operations. * * You can change the tree. * Changes inside a node made when entering it are walked, * changes made when exiting it are not. * See `Visitor` and `VisitorExit` for more info. * * @overload * @param {Tree} tree * Tree to traverse. * @param {Check} check * `unist-util-is`-compatible test. * @param {BuildVisitor<Tree, Check>} enter * Handle each node when entering it. * @param {boolean | null | undefined} [reverse] * Walk children from last to first; * for `enter`, reverse preorder (NRL) instead of preorder (NLR); * for `exit`, reverse postorder (RLN) instead of postorder (LRN). * @returns {undefined} * Nothing. * * @overload * @param {Tree} tree * Tree to traverse. * @param {Check} check * `unist-util-is`-compatible test. * @param {BuildVisitors<Tree, Check>} visitors * Handle each node when exiting it, and optionally when entering it. * @param {boolean | null | undefined} [reverse] * Walk children from last to first; * for `enter`, reverse preorder (NRL) instead of preorder (NLR); * for `exit`, reverse postorder (RLN) instead of postorder (LRN). * @returns {undefined} * Nothing. * * @overload * @param {Tree} tree * Tree to traverse. * @param {BuildVisitor<Tree>} enter * Handle each node when entering it. * @param {boolean | null | undefined} [reverse] * Walk children from last to first; * for `enter`, reverse preorder (NRL) instead of preorder (NLR); * for `exit`, reverse postorder (RLN) instead of postorder (LRN). * @returns {undefined} * Nothing. * * @overload * @param {Tree} tree * Tree to traverse. * @param {BuildVisitors<Tree>} visitors * Handle each node when exiting it, and optionally when entering it. * @param {boolean | null | undefined} [reverse] * Walk children from last to first; * for `enter`, reverse preorder (NRL) instead of preorder (NLR); * for `exit`, reverse postorder (RLN) instead of postorder (LRN). * @returns {undefined} * Nothing. * * @param {UnistNode} tree * Tree to traverse. * @param {Visitor | Visitors | Test} testOrEnterOrVisitors * `unist-util-is`-compatible test, `enter`, or `visitors`. * @param {Visitor | Visitors | boolean | null | undefined} [enterOrVisitorsOrReverse] * `enter`, `visitors`, or `reverse` after a test. * @param {boolean | null | undefined} [reverse] * Walk children from last to first; * for `enter`, reverse preorder (NRL) instead of preorder (NLR); * for `exit`, reverse postorder (RLN) instead of postorder (LRN). * @returns {undefined} * Nothing. * * @template {UnistNode} Tree * Node type. * @template {Test} Check * `unist-util-is`-compatible test. */ function visitParents(tree, testOrEnterOrVisitors, enterOrVisitorsOrReverse, reverse) { if (!tree || typeof tree !== "object") throw new Error("Unexpected value `" + tree + "` for `tree`, expected node"); let preorder = true; /** @type {Test} */ let check; /** @type {Visitors | Visitor} */ let visitors; /** @type {Visitor | null | undefined} */ let enter; /** @type {VisitorExit | null | undefined} */ let exit; if (typeof enterOrVisitorsOrReverse === "function" || enterOrVisitorsOrReverse && typeof enterOrVisitorsOrReverse === "object") { check = testOrEnterOrVisitors; visitors = enterOrVisitorsOrReverse; if (reverse) preorder = false; } else { visitors = testOrEnterOrVisitors; if (enterOrVisitorsOrReverse) preorder = false; } if (typeof visitors === "function") enter = visitors; else if (visitors && typeof visitors === "object") { if (visitors.enter === null || visitors.enter === void 0) {} else if (typeof visitors.enter === "function") enter = visitors.enter; else throw new Error("Unexpected value `" + visitors.enter + "` for `visitors.enter`, expected optional visitor"); if (typeof visitors.exit === "function") exit = visitors.exit; else throw new Error("Unexpected value `" + visitors.exit + "` for `visitors.exit`, expected visitor (pass a visitor directly if you only want an enter visitor)"); } else throw new Error("Unexpected value `" + visitors + "` for `enter` or `visitors`, expected visitor or object with visitors"); const is = convert(check); const step = preorder ? 1 : -1; factory(tree, void 0, [])(); /** * Create a function to visit a node. * * @param {UnistNode} node * Node to visit. * @param {number | undefined} index * Index of `node` in its parent. * @param {Array<UnistParent>} parents * Ancestors of `node`. * @returns {() => Readonly<ActionTuple>} * Visit `node`. */ function factory(node, index, parents) { const value = node && typeof node === "object" ? node : {}; if (typeof value.type === "string") { const name = typeof value.tagName === "string" ? value.tagName : typeof value.name === "string" ? value.name : void 0; Object.defineProperty(visit, "name", { value: "node (" + color(node.type + (name ? "<" + name + ">" : "")) + ")" }); } return visit; function visit() { const matches = !check || is(node, index, parents[parents.length - 1] || void 0); /** @type {Readonly<ActionTuple>} */ let result = empty; if (enter && matches) { result = toResult(enter(node, parents, index)); if (result[0] === false) return result; } if ("children" in node && node.children) { const nodeAsParent = node; if (nodeAsParent.children && result[0] !== "skip") { let offset = (preorder ? -1 : nodeAsParent.children.length) + step; const grandparents = [...parents, nodeAsParent]; while (offset > -1 && offset < nodeAsParent.children.length) { const child = nodeAsParent.children[offset]; const subresult = factory(child, offset, grandparents)(); if (subresult[0] === false) return subresult; offset = typeof subresult[1] === "number" ? subresult[1] : offset + step; } } } if (exit && matches) { const exitResult = toResult(exit(node, parents, index)); if (exitResult[0] === "skip") throw new Error("Unexpected value `" + exitResult[0] + "` from `exit`, expected `CONTINUE`, `EXIT`, index, or nothing"); if (exitResult[0] === false || typeof exitResult[1] === "number") return exitResult; } return result; } } } /** * Turn a return value into a clean result. * * @param {VisitorResult} value * Valid return values from visitors. * @returns {Readonly<ActionTuple>} * Clean result. */ function toResult(value) { if (Array.isArray(value)) return value; if (typeof value === "number") return [true, value]; return value === null || value === void 0 ? empty : [value]; } // node_modules/mdast-util-find-and-replace/lib/index.js /** * @import {Nodes, Parents, PhrasingContent, Root, Text} from 'mdast' * @import {BuildVisitor, Test, VisitorResult} from 'unist-util-visit-parents' */ /** * @typedef RegExpMatchObject * Info on the match. * @property {number} index * The index of the search at which the result was found. * @property {string} input * A copy of the search string in the text node. * @property {[...Array<Parents>, Text]} stack * All ancestors of the text node, where the last node is the text itself. * * @typedef {RegExp | string} Find * Pattern to find. * * Strings are escaped and then turned into global expressions. * * @typedef {Array<FindAndReplaceTuple>} FindAndReplaceList * Several find and replaces, in array form. * * @typedef {[Find, Replace?]} FindAndReplaceTuple * Find and replace in tuple form. * * @typedef {ReplaceFunction | string | null | undefined} Replace * Thing to replace with. * * @callback ReplaceFunction * Callback called when a search matches. * @param {...any} parameters * The parameters are the result of corresponding search expression: * * * `value` (`string`) — whole match * * `...capture` (`Array<string>`) — matches from regex capture groups * * `match` (`RegExpMatchObject`) — info on the match * @returns {Array<PhrasingContent> | PhrasingContent | string | false | null | undefined} * Thing to replace with. * * * when `null`, `undefined`, `''`, remove the match * * …or when `false`, do not replace at all * * …or when `string`, replace with a text node of that value * * …or when `Node` or `Array<Node>`, replace with those nodes * * @typedef {[RegExp, ReplaceFunction]} Pair * Normalized find and replace. * * @typedef {Array<Pair>} Pairs * All find and replaced. * * @typedef Options * Configuration. * @property {Test | null | undefined} [ignore] * Test for which nodes to ignore (optional). */ /** * Find patterns in a tree and replace them. * * The algorithm searches the tree in *preorder* for complete values in `Text` * nodes. * Partial matches are not supported. * * @param {Nodes} tree * Tree to change. * @param {FindAndReplaceList | FindAndReplaceTuple} list * Patterns to find. * @param {Options | null | undefined} [options] * Configuration (optional). * @returns {undefined} * Nothing. */ function findAndReplace(tree, list, options) { const ignored = convert((options || {}).ignore || []); const pairs = toPairs(list); let pairIndex = -1; while (++pairIndex < pairs.length) visitParents(tree, visitor); /** * Handle text nodes and skip ignored nodes. * * @type {BuildVisitor<Root>} */ function visitor(node, parents, index) { if (node.type === "text" && typeof index === "number") return handler(node, parents, index); if (ignored(node, index, parents[parents.length - 1])) return SKIP; } /** * Handle a text node which is not in an ignored parent. * * @param {Text} node * Text node to search in. * @param {Array<Parents>} parents * Ancestors of `node`. * @param {number} index * Index of `node` in its parent. * @returns {VisitorResult} * Where to continue visiting. */ function handler(node, parents, index) { const parent = parents[parents.length - 1]; const find = pairs[pairIndex][0]; const replace = pairs[pairIndex][1]; let start = 0; let change = false; /** @type {Array<PhrasingContent>} */ let nodes = []; find.lastIndex = 0; let match = find.exec(node.value); while (match) { const position = match.index; /** @type {RegExpMatchObject} */ const matchObject = { index: match.index, input: match.input, stack: [...parents, node] }; let value = replace(...match, matchObject); if (typeof value === "string") value = value.length > 0 ? { type: "text", value } : void 0; if (value === false) find.lastIndex = position + 1; else { if (start !== position) add({ type: "text", value: node.value.slice(start, position) }); if (Array.isArray(value)) for (const child of value) add(child); else if (value) add(value); start = position + match[0].length; change = true; } if (!find.global) break; match = find.exec(node.value); } if (change) { if (start < node.value.length) add({ type: "text", value: node.value.slice(start) }); parent.children.splice(index, 1, ...nodes); } else nodes = [node]; return index + nodes.length; /** * Add a node. * * @param {PhrasingContent} child * Node to add. * @returns {undefined} * Nothing. */ function add(child) { const previous = nodes[nodes.length - 1]; if (previous && previous.type === "text" && child.type === "text") previous.value += child.value; else nodes.push(child); } } } /** * Turn a tuple or a list of tuples into pairs. * * @param {FindAndReplaceList | FindAndReplaceTuple} tupleOrList * Schema. * @returns {Pairs} * Clean pairs. */ function toPairs(tupleOrList) { if (!Array.isArray(tupleOrList)) throw new TypeError("Expected find and replace tuple or list of tuples"); /** @type {Pairs} */ const result = []; const list = !tupleOrList[0] || Array.isArray(tupleOrList[0]) ? tupleOrList : [tupleOrList]; let index = -1; while (++index < list.length) { const tuple = list[index]; result.push([toExpression(tuple[0]), toFunction(tuple[1])]); } return result; } /** * Turn a find into an expression. * * @param {Find} find * Pattern to find. * @returns {RegExp} * Global expression. */ function toExpression(find) { return typeof find === "string" ? new RegExp(escapeStringRegexp(find), "g") : find; } /** * Turn a replace into a function. * * @param {Replace} replace * Thing to replace with. * @returns {ReplaceFunction} * Function that returns that thing. */ function toFunction(replace) { return typeof replace === "function" ? replace : function() { return replace; }; } // node_modules/mdast-util-gfm-autolink-literal/lib/index.js /** * @import {RegExpMatchObject, ReplaceFunction} from 'mdast-util-find-and-replace' * @import {CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle, Transform as FromMarkdownTransform} from 'mdast-util-from-markdown' * @import {ConstructName, Options as ToMarkdownExtension} from 'mdast-util-to-markdown' * @import {Link, PhrasingContent} from 'mdast' */ /** * Create an extension for `mdast-util-from-markdown` to enable GFM autolink * literals in markdown. * * @returns {FromMarkdownExtension} * Extension for `mdast-util-to-markdown` to enable GFM autolink literals. */ function gfmAutolinkLiteralFromMarkdown() { return { transforms: [transformGfmAutolinkLiterals], enter: { literalAutolink: enterLiteralAutolink, literalAutolinkEmail: enterLiteralAutolinkValue, literalAutolinkHttp: enterLiteralAutolinkValue, literalAutolinkWww: enterLiteralAutolinkValue }, exit: { literalAutolink: exitLiteralAutolink, literalAutolinkEmail: exitLiteralAutolinkEmail, literalAutolinkHttp: exitLiteralAutolinkHttp, literalAutolinkWww: exitLiteralAutolinkWww } }; } /** * Handle the start of an autolink literal. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterLiteralAutolink(token) { this.enter({ type: "link", title: null, url: "", children: [], position: void 0 }, token); } /** * Handle the start of an autolink literal value. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterLiteralAutolinkValue(token) { this.config.enter.autolinkProtocol.call(this, token); } /** * Handle the end of an HTTP autolink literal value. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitLiteralAutolinkHttp(token) { this.config.exit.autolinkProtocol.call(this, token); } /** * Handle the end of a `www` autolink literal value. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitLiteralAutolinkWww(token) { this.config.exit.data.call(this, token); const node = this.stack[this.stack.length - 1]; node.type; node.url = "http://" + this.sliceSerialize(token); } /** * Handle the end of an email autolink literal value. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitLiteralAutolinkEmail(token) { this.config.exit.autolinkEmail.call(this, token); } /** * Handle the end of an autolink literal. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitLiteralAutolink(token) { this.exit(token); } /** * Find autolink literals in text and turn them into links. * * @type {FromMarkdownTransform} */ function transformGfmAutolinkLiterals(tree) { findAndReplace(tree, [ [/(?<![\da-z])(https?:\/\/|www(?=\.))([\w-]*\.[\w\-.]*)([^\t\n\r ]*)/gi, findUrl], [/(?<![\w+\-.@])xmpp:([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)(\/(?:[\w\-/]|\.(?=[\dA-Za-z]))*)?/g, findXmpp], [/(?<![\w+\-.@])mailto:([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)/g, findMailto], [/(?<![\w+\-.]|(?:^|[^\d@A-Za-z])(?:mailto|xmpp):)([\w+\-.]+)@([\w-]+(?:\.[\w-]+)+)/g, findEmail] ], { ignore: ["link", "linkReference"] }); } /** * Turn a URL match into a link. * * @type {ReplaceFunction} * @param {string} _ * Whole match. * @param {string} protocol * Protocol (`http://`, `https://`) or `www`. * @param {string} domain * Host name, up to the path. * @param {string} path * Path, query, and fragment. * @param {RegExpMatchObject} match * Match object. * @returns {Array<PhrasingContent> | Link | false} * Link, link and trailing text, or `false` if not a URL. */ function findUrl(_, protocol, domain, path, match) { if (!previous$1(match)) return false; let prefix = ""; if (/^w/i.test(protocol)) { domain = protocol + domain; protocol = ""; prefix = "http://"; } if (unicodePunctuation(domain.charCodeAt(0)) || !isCorrectDomain(domain)) return false; const parts = splitUrl(domain + path); /** @type {Link} */ const result = { type: "link", title: null, url: prefix + protocol + parts[0], children: [{ type: "text", value: protocol + parts[0], position: void 0 }], position: void 0 }; if (parts[1]) return [result, { type: "text", value: parts[1], position: void 0 }]; return result; } /** * Turn an email match into a link. * * @type {ReplaceFunction} * @param {string} _ * Whole match. * @param {string} atext * Local part. * @param {string} label * Domain. * @returns {Link | false} * Link, or `false` if not an email. */ function findEmail(_, atext, label) { if (/[\d\-_]$/.test(label)) return false; return { type: "link", title: null, url: "mailto:" + atext + "@" + label, children: [{ type: "text", value: atext + "@" + label, position: void 0 }], position: void 0 }; } /** * Turn a `mailto:` email match into a link. * * @type {ReplaceFunction} * @param {string} _ * Whole match. * @param {string} atext * Local part. * @param {string} label * Domain. * @returns {Link | false} * Link, or `false` if not an email. */ function findMailto(_, atext, label) { if (/[\d\-_]$/.test(label)) return false; const value = "mailto:" + atext + "@" + label; return { type: "link", title: null, url: value, children: [{ type: "text", value, position: void 0 }], position: void 0 }; } /** * Turn an `xmpp:` address match into a link. * * @type {ReplaceFunction} * @param {string} matchValue * Whole match. * @param {string} atext * Local part. * @param {string} label * Domain. * @param {string | undefined} resource * Resource (`/` and more), if any. * @param {RegExpMatchObject} match * Match object. * @returns {Link | false} * Link, or `false` if not an address. */ function findXmpp(matchValue, atext, label, resource, match) { if (/[\d\-_]$/.test(label) || resource && (!/[A-Za-z]$/.test(resource) || match.input.charAt(match.index + matchValue.length) === "@")) return false; const value = "xmpp:" + atext + "@" + label + (resource || ""); return { type: "link", title: null, url: value, children: [{ type: "text", value, position: void 0 }], position: void 0 }; } /** * Check if a domain is valid. * * @param {string} domain * Host name to check. * @returns {boolean} * Whether the domain is valid. */ function isCorrectDomain(domain) { const parts = domain.split("."); if (parts.length < 2 || parts[parts.length - 1] && (/_/.test(parts[parts.length - 1]) || !/[\dA-Za-z]/.test(parts[parts.length - 1])) || parts[parts.length - 2] && (/_/.test(parts[parts.length - 2]) || !/[\dA-Za-z]/.test(parts[parts.length - 2]))) return false; return true; } /** * Split trailing punctuation off a URL. * * @param {string} url * Value to split. * @returns {[string, string | undefined]} * URL and trailing punctuation, if any. */ function splitUrl(url) { let index = url.length; while (index > 0) { const code = url.charCodeAt(index - 1); if (code === 33 || code === 34 || code === 38 || code === 39 || code === 41 || code === 44 || code === 46 || code === 58 || code === 59 || code === 60 || code === 62 || code === 63 || code === 93 || code === 125) index--; else break; } if (index === url.length) return [url, void 0]; let trail = url.slice(index); url = url.slice(0, index); let closingParenIndex = trail.indexOf(")"); const openingParens = ccount(url, "("); let closingParens = ccount(url, ")"); while (closingParenIndex !== -1 && openingParens > closingParens) { url += trail.slice(0, closingParenIndex + 1); trail = trail.slice(closingParenIndex + 1); closingParenIndex = trail.indexOf(")"); closingParens++; } return [url, trail]; } /** * Check if the character before a match is allowed. * * @param {RegExpMatchObject} match * Match object. * @returns {boolean} * Whether the previous character is allowed. */ function previous$1(match) { const code = match.input.charCodeAt(match.index - 1); return match.index === 0 || unicodeWhitespace(code) || unicodePunctuation(code); } // node_modules/mdast-util-gfm-footnote/lib/index.js /** * @import { * CompileContext, * Extension as FromMarkdownExtension, * Handle as FromMarkdownHandle * } from 'mdast-util-from-markdown' * @import {ToMarkdownOptions} from 'mdast-util-gfm-footnote' * @import { * Handle as ToMarkdownHandle, * Map, * Options as ToMarkdownExtension * } from 'mdast-util-to-markdown' * @import {FootnoteDefinition, FootnoteReference} from 'mdast' */ footnoteReference.peek = footnoteReferencePeek; /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterFootnoteCallString() { this.buffer(); } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterFootnoteCall(token) { this.enter({ type: "footnoteReference", identifier: "", label: "" }, token); } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterFootnoteDefinitionLabelString() { this.buffer(); } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterFootnoteDefinition(token) { this.enter({ type: "footnoteDefinition", identifier: "", label: "", children: [] }, token); } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitFootnoteCallString(token) { const label = this.resume(); const node = this.stack[this.stack.length - 1]; node.type; node.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase(); node.label = label; } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitFootnoteCall(token) { this.exit(token); } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitFootnoteDefinitionLabelString(token) { const label = this.resume(); const node = this.stack[this.stack.length - 1]; node.type; node.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase(); node.label = label; } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitFootnoteDefinition(token) { this.exit(token); } /** @type {ToMarkdownHandle} */ function footnoteReferencePeek() { return "["; } /** * @type {ToMarkdownHandle} * @param {FootnoteReference} node */ function footnoteReference(node, _, state, info) { const tracker = state.createTracker(info); let value = tracker.move("[^"); const exit = state.enter("footnoteReference"); const subexit = state.enter("reference"); value += tracker.move(state.safe(state.associationId(node), { after: "]", before: value })); subexit(); exit(); value += tracker.move("]"); return value; } /** * Create an extension for `mdast-util-from-markdown` to enable GFM footnotes * in markdown. * * @returns {FromMarkdownExtension} * Extension for `mdast-util-from-markdown`. */ function gfmFootnoteFromMarkdown() { return { enter: { gfmFootnoteCallString: enterFootnoteCallString, gfmFootnoteCall: enterFootnoteCall, gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString, gfmFootnoteDefinition: enterFootnoteDefinition }, exit: { gfmFootnoteCallString: exitFootnoteCallString, gfmFootnoteCall: exitFootnoteCall, gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString, gfmFootnoteDefinition: exitFootnoteDefinition } }; } // node_modules/mdast-util-gfm-strikethrough/lib/index.js handleDelete.attention = attentionDelete; handleDelete.peek = peekDelete; /** * Create an extension for `mdast-util-from-markdown` to enable GFM * strikethrough in markdown. * * @returns {FromMarkdownExtension} * Extension for `mdast-util-from-markdown` to enable GFM strikethrough. */ function gfmStrikethroughFromMarkdown() { return { canContainEols: ["delete"], enter: { strikethrough: enterStrikethrough }, exit: { strikethrough: exitStrikethrough } }; } /** * Enter strikethrough. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterStrikethrough(token) { this.enter({ type: "delete", children: [], position: void 0 }, token); } /** * Exit strikethrough. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitStrikethrough(token) { this.exit(token); } /** * Serialize a delete node. * * @type {ToMarkdownHandle} * @param {Delete} node * Node to serialize. */ function handleDelete(node, _, state, info) { const tracker = state.createTracker(info); const sequence = state.stack.includes("strikethrough") ? "~" : "~~"; const exit = state.enter("strikethrough"); let value = tracker.move(sequence); value += state.containerPhrasing(node, { ...tracker.current(), before: value, after: "~" }); value += tracker.move(sequence); exit(); return value; } /** * Serialize a delete node as attention. * * @type {Attention} */ function attentionDelete() { return { construct: "strikethrough", markers: ["~"], sizes: [2, 1] }; } /** * Peek the first character of a delete node. * * @type {ToMarkdownHandle} */ function peekDelete() { return "~"; } // node_modules/mdast-util-gfm-table/lib/index.js /** * @import {Heading, InlineCode, Table, TableCell, TableRow} from 'mdast' * @import {Options as MarkdownTableOptions} from 'markdown-table' * @import { * CompileContext, * Extension as FromMarkdownExtension, * Handle as FromMarkdownHandle, * } from 'mdast-util-from-markdown' * @import { * Options as ToMarkdownExtension, * Handle as ToMarkdownHandle, * Info, * Join, * State * } from 'mdast-util-to-markdown' */ /** * @typedef Options * Configuration. * @property {boolean | null | undefined} [tableCellPadding=true] * Whether to add a space of padding between delimiters and cells (default: * `true`). * @property {boolean | null | undefined} [tablePipeAlign=true] * Whether to align the delimiters (default: `true`). * @property {MarkdownTableOptions['stringLength'] | null | undefined} [stringLength] * Function to detect the length of table cell content, used when aligning * the delimiters between cells (optional). */ /** * Create an extension for `mdast-util-from-markdown` to enable GFM tables in * markdown. * * @returns {FromMarkdownExtension} * Extension for `mdast-util-from-markdown` to enable GFM tables. */ function gfmTableFromMarkdown() { return { enter: { table: enterTable, tableData: enterCell, tableHeader: enterCell, tableRow: enterRow }, exit: { codeText: exitCodeText, table: exitTable, tableData: exit, tableHeader: exit, tableRow: exit } }; } /** * Enter a table. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterTable(token) { const align = token._align; this.enter({ type: "table", align: align.map(function(d) { return d === "none" ? null : d; }), children: [], position: void 0 }, token); this.data.inTable = true; } /** * Exit a table. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitTable(token) { this.exit(token); this.data.inTable = void 0; } /** * Enter a row. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterRow(token) { this.enter({ type: "tableRow", children: [], position: void 0 }, token); } /** * Exit a row or cell. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exit(token) { this.exit(token); } /** * Enter a cell. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterCell(token) { this.enter({ type: "tableCell", children: [], position: void 0 }, token); } /** * Exit code (text). * * Overwrites the default code text data handler to unescape escaped pipes * when they are in tables. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitCodeText(token) { let value = this.resume(); if (this.data.inTable) value = value.replace(/\\([\\|])/g, replace); const node = this.stack[this.stack.length - 1]; node.type; node.value = value; this.exit(token); } /** * Unescape an escaped pipe. * * @param {string} $0 * Whole match. * @param {string} $1 * Escaped character. * @returns {string} * Replacement. */ function replace($0, $1) { return $1 === "|" ? $1 : $0; } // node_modules/mdast-util-gfm-task-list-item/lib/index.js /** * @import {ListItem, Paragraph, Parents} from 'mdast' * @import { * CompileContext, * Extension as FromMarkdownExtension, * Handle as FromMarkdownHandle * } from 'mdast-util-from-markdown' * @import { * Handle as ToMarkdownHandle, * Join as ToMarkdownJoin, * Options as ToMarkdownExtension * } from 'mdast-util-to-markdown' */ /** * Create an extension for `mdast-util-from-markdown` to enable GFM task * list items in markdown. * * @returns {FromMarkdownExtension} * Extension for `mdast-util-from-markdown` to enable GFM task list items. */ function gfmTaskListItemFromMarkdown() { return { exit: { taskListCheckValueChecked: exitCheck, taskListCheckValueUnchecked: exitCheck, paragraph: exitParagraphWithTaskListItem } }; } /** * Exit a check. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitCheck(token) { const node = this.stack[this.stack.length - 2]; node.type; node.checked = token.type === "taskListCheckValueChecked"; } /** * Exit a paragraph, removing the whitespace after a check. * * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitParagraphWithTaskListItem(token) { const parent = this.stack[this.stack.length - 2]; if (parent && parent.type === "listItem" && typeof parent.checked === "boolean") { const node = this.stack[this.stack.length - 1]; node.type; const head = node.children[0]; if (head && head.type === "text") { const siblings = parent.children; let index = -1; /** @type {Paragraph | undefined} */ let firstParagraph; while (++index < siblings.length) { const sibling = siblings[index]; if (sibling.type === "paragraph") { firstParagraph = sibling; break; } } if (firstParagraph === node) { head.value = head.value.slice(1); if (head.value.length === 0) node.children.shift(); else if (node.position && head.position && typeof head.position.start.offset === "number") { head.position.start.column++; head.position.start.offset++; node.position.start = { ...head.position.start }; } } } } this.exit(token); } // node_modules/mdast-util-gfm/lib/index.js /** * @import {Extension as FromMarkdownExtension} from 'mdast-util-from-markdown' * @import {Options} from 'mdast-util-gfm' * @import {Options as ToMarkdownExtension} from 'mdast-util-to-markdown' */ /** * Create an extension for `mdast-util-from-markdown` to enable GFM (autolink * literals, footnotes, strikethrough, tables, tasklists). * * @returns {Array<FromMarkdownExtension>} * Extension for `mdast-util-from-markdown` to enable GFM (autolink literals, * footnotes, strikethrough, tables, tasklists). */ function gfmFromMarkdown() { return [ gfmAutolinkLiteralFromMarkdown(), gfmFootnoteFromMarkdown(), gfmStrikethroughFromMarkdown(), gfmTableFromMarkdown(), gfmTaskListItemFromMarkdown() ]; } // node_modules/mdast-util-math/lib/index.js /** * @typedef {import('hast').Element} HastElement * @typedef {import('hast').ElementContent} HastElementContent * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension * @typedef {import('../index.js').InlineMath} InlineMath * @typedef {import('../index.js').Math} Math * * @typedef ToOptions * Configuration. * @property {boolean | null | undefined} [singleDollarTextMath=true] * Whether to support math (text) with a single dollar (default: `true`). * * Single dollars work in Pandoc and many other places, but often interfere * with “normal” dollars in text. * If you turn this off, you can still use two or more dollars for text math. */ /** * Create an extension for `mdast-util-from-markdown`. * * @returns {FromMarkdownExtension} * Extension for `mdast-util-from-markdown`. */ function mathFromMarkdown() { return { enter: { mathFlow: enterMathFlow, mathFlowFenceMeta: enterMathFlowMeta, mathText: enterMathText }, exit: { mathFlow: exitMathFlow, mathFlowFence: exitMathFlowFence, mathFlowFenceMeta: exitMathFlowMeta, mathFlowValue: exitMathData, mathText: exitMathText, mathTextData: exitMathData } }; /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterMathFlow(token) { this.enter({ type: "math", meta: null, value: "", data: { hName: "pre", hChildren: [{ type: "element", tagName: "code", properties: { className: ["language-math", "math-display"] }, children: [] }] } }, token); } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterMathFlowMeta() { this.buffer(); } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitMathFlowMeta() { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.type; node.meta = data; } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitMathFlowFence() { if (this.data.mathFlowInside) return; this.buffer(); this.data.mathFlowInside = true; } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitMathFlow(token) { const data = this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, ""); const node = this.stack[this.stack.length - 1]; node.type; this.exit(token); node.value = data; const code = node.data.hChildren[0]; code.type; code.tagName; code.children.push({ type: "text", value: data }); this.data.mathFlowInside = void 0; } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function enterMathText(token) { this.enter({ type: "inlineMath", value: "", data: { hName: "code", hProperties: { className: ["language-math", "math-inline"] }, hChildren: [] } }, token); this.buffer(); } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitMathText(token) { const data = this.resume(); const node = this.stack[this.stack.length - 1]; node.type; this.exit(token); node.value = data; node.data.hChildren.push({ type: "text", value: data }); } /** * @this {CompileContext} * @type {FromMarkdownHandle} */ function exitMathData(token) { this.config.enter.data.call(this, token); this.config.exit.data.call(this, token); } } // node_modules/micromark-extension-gfm-autolink-literal/lib/syntax.js /** * @import {Code, ConstructRecord, Event, Extension, Previous, State, TokenizeContext, Tokenizer} from 'micromark-util-types' */ const wwwPrefix = { tokenize: tokenizeWwwPrefix, partial: true }; const domain = { tokenize: tokenizeDomain, partial: true }; const path$1 = { tokenize: tokenizePath, partial: true }; const trail = { tokenize: tokenizeTrail, partial: true }; const emailDomainDotTrail = { tokenize: tokenizeEmailDomainDotTrail, partial: true }; const wwwAutolink = { name: "wwwAutolink", tokenize: tokenizeWwwAutolink, previous: previousWww }; const protocolAutolink = { name: "protocolAutolink", tokenize: tokenizeProtocolAutolink, previous: previousProtocol }; const emailAutolink = { name: "emailAutolink", tokenize: tokenizeEmailAutolink, previous: previousEmail }; /** @type {ConstructRecord} */ const text$3 = {}; /** * Create an extension for `micromark` to support GitHub autolink literal * syntax. * * @returns {Extension} * Extension for `micromark` that can be passed in `extensions` to enable GFM * autolink literal syntax. */ function gfmAutolinkLiteral() { return { text: text$3 }; } /** @type {Code} */ let code = 48; while (code < 123) { text$3[code] = emailAutolink; code++; if (code === 58) code = 65; else if (code === 91) code = 97; } text$3[43] = emailAutolink; text$3[45] = emailAutolink; text$3[46] = emailAutolink; text$3[95] = emailAutolink; text$3[72] = [emailAutolink, protocolAutolink]; text$3[104] = [emailAutolink, protocolAutolink]; text$3[87] = [emailAutolink, wwwAutolink]; text$3[119] = [emailAutolink, wwwAutolink]; /** * Email autolink literal. * * ```markdown * > | a contact@example.org b * ^^^^^^^^^^^^^^^^^^^ * ``` * * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeEmailAutolink(effects, ok, nok) { const self = this; /** @type {boolean | undefined} */ let dot; /** @type {boolean} */ let data; return start; /** * Start of email autolink literal. * * ```markdown * > | a contact@example.org b * ^ * ``` * * @type {State} */ function start(code) { if (!gfmAtext(code) || !previousEmail.call(self, self.previous) || previousUnbalanced(self.events)) return nok(code); effects.enter("literalAutolink"); effects.enter("literalAutolinkEmail"); return atext(code); } /** * In email atext. * * ```markdown * > | a contact@example.org b * ^ * ``` * * @type {State} */ function atext(code) { if (gfmAtext(code)) { effects.consume(code); return atext; } if (code === 64) { effects.consume(code); return emailDomain; } return nok(code); } /** * In email domain. * * The reference code is a bit overly complex as it handles the `@`, of which * there may be just one. * Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L318> * * ```markdown * > | a contact@example.org b * ^ * ``` * * @type {State} */ function emailDomain(code) { if (code === 46) return effects.check(emailDomainDotTrail, emailDomainAfter, emailDomainDot)(code); if (code === 45 || code === 95 || asciiAlphanumeric(code)) { data = true; effects.consume(code); return emailDomain; } return emailDomainAfter(code); } /** * In email domain, on dot that is not a trail. * * ```markdown * > | a contact@example.org b * ^ * ``` * * @type {State} */ function emailDomainDot(code) { effects.consume(code); dot = true; return emailDomain; } /** * After email domain. * * ```markdown * > | a contact@example.org b * ^ * ``` * * @type {State} */ function emailDomainAfter(code) { if (data && dot && asciiAlpha(self.previous)) { effects.exit("literalAutolinkEmail"); effects.exit("literalAutolink"); return ok(code); } return nok(code); } } /** * `www` autolink literal. * * ```markdown * > | a www.example.org b * ^^^^^^^^^^^^^^^ * ``` * * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeWwwAutolink(effects, ok, nok) { const self = this; return wwwStart; /** * Start of www autolink literal. * * ```markdown * > | www.example.com/a?b#c * ^ * ``` * * @type {State} */ function wwwStart(code) { if (code !== 87 && code !== 119 || !previousWww.call(self, self.previous) || previousUnbalanced(self.events)) return nok(code); effects.enter("literalAutolink"); effects.enter("literalAutolinkWww"); return effects.check(wwwPrefix, effects.attempt(domain, effects.attempt(path$1, wwwAfter), nok), nok)(code); } /** * After a www autolink literal. * * ```markdown * > | www.example.com/a?b#c * ^ * ``` * * @type {State} */ function wwwAfter(code) { effects.exit("literalAutolinkWww"); effects.exit("literalAutolink"); return ok(code); } } /** * Protocol autolink literal. * * ```markdown * > | a https://example.org b * ^^^^^^^^^^^^^^^^^^^ * ``` * * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeProtocolAutolink(effects, ok, nok) { const self = this; let buffer = ""; let seen = false; return protocolStart; /** * Start of protocol autolink literal. * * ```markdown * > | https://example.com/a?b#c * ^ * ``` * * @type {State} */ function protocolStart(code) { if ((code === 72 || code === 104) && previousProtocol.call(self, self.previous) && !previousUnbalanced(self.events)) { effects.enter("literalAutolink"); effects.enter("literalAutolinkHttp"); buffer += String.fromCodePoint(code); effects.consume(code); return protocolPrefixInside; } return nok(code); } /** * In protocol. * * ```markdown * > | https://example.com/a?b#c * ^^^^^ * ``` * * @type {State} */ function protocolPrefixInside(code) { if (asciiAlpha(code) && buffer.length < 5) { buffer += String.fromCodePoint(code); effects.consume(code); return protocolPrefixInside; } if (code === 58) { const protocol = buffer.toLowerCase(); if (protocol === "http" || protocol === "https") { effects.consume(code); return protocolSlashesInside; } } return nok(code); } /** * In slashes. * * ```markdown * > | https://example.com/a?b#c * ^^ * ``` * * @type {State} */ function protocolSlashesInside(code) { if (code === 47) { effects.consume(code); if (seen) return afterProtocol; seen = true; return protocolSlashesInside; } return nok(code); } /** * After protocol, before domain. * * ```markdown * > | https://example.com/a?b#c * ^ * ``` * * @type {State} */ function afterProtocol(code) { return code === null || asciiControl(code) || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || unicodePunctuation(code) ? nok(code) : effects.attempt(domain, effects.attempt(path$1, protocolAfter), nok)(code); } /** * After a protocol autolink literal. * * ```markdown * > | https://example.com/a?b#c * ^ * ``` * * @type {State} */ function protocolAfter(code) { effects.exit("literalAutolinkHttp"); effects.exit("literalAutolink"); return ok(code); } } /** * `www` prefix. * * ```markdown * > | a www.example.org b * ^^^^ * ``` * * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeWwwPrefix(effects, ok, nok) { let size = 0; return wwwPrefixInside; /** * In www prefix. * * ```markdown * > | www.example.com * ^^^^ * ``` * * @type {State} */ function wwwPrefixInside(code) { if ((code === 87 || code === 119) && size < 3) { size++; effects.consume(code); return wwwPrefixInside; } if (code === 46 && size === 3) { effects.consume(code); return wwwPrefixAfter; } return nok(code); } /** * After www prefix. * * ```markdown * > | www.example.com * ^ * ``` * * @type {State} */ function wwwPrefixAfter(code) { return code === null ? nok(code) : ok(code); } } /** * Domain. * * ```markdown * > | a https://example.org b * ^^^^^^^^^^^ * ``` * * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeDomain(effects, ok, nok) { /** @type {boolean | undefined} */ let underscoreInLastSegment; /** @type {boolean | undefined} */ let underscoreInLastLastSegment; /** @type {boolean | undefined} */ let seen; return domainInside; /** * In domain. * * ```markdown * > | https://example.com/a * ^^^^^^^^^^^ * ``` * * @type {State} */ function domainInside(code) { if (code === 46 || code === 95) return effects.check(trail, domainAfter, domainAtPunctuation)(code); if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || code !== 45 && unicodePunctuation(code)) return domainAfter(code); seen = true; effects.consume(code); return domainInside; } /** * In domain, at potential trailing punctuation, that was not trailing. * * ```markdown * > | https://example.com * ^ * ``` * * @type {State} */ function domainAtPunctuation(code) { if (code === 95) underscoreInLastSegment = true; else { underscoreInLastLastSegment = underscoreInLastSegment; underscoreInLastSegment = void 0; } effects.consume(code); return domainInside; } /** * After domain. * * ```markdown * > | https://example.com/a * ^ * ``` * * @type {State} */ function domainAfter(code) { if (underscoreInLastLastSegment || underscoreInLastSegment || !seen) return nok(code); return ok(code); } } /** * Path. * * ```markdown * > | a https://example.org/stuff b * ^^^^^^ * ``` * * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizePath(effects, ok) { let sizeOpen = 0; let sizeClose = 0; return pathInside; /** * In path. * * ```markdown * > | https://example.com/a * ^^ * ``` * * @type {State} */ function pathInside(code) { if (code === 40) { sizeOpen++; effects.consume(code); return pathInside; } if (code === 41 && sizeClose < sizeOpen) return pathAtPunctuation(code); if (code === 33 || code === 34 || code === 38 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 60 || code === 63 || code === 93 || code === 95 || code === 126) return effects.check(trail, ok, pathAtPunctuation)(code); if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) return ok(code); effects.consume(code); return pathInside; } /** * In path, at potential trailing punctuation, that was not trailing. * * ```markdown * > | https://example.com/a"b * ^ * ``` * * @type {State} */ function pathAtPunctuation(code) { if (code === 41) sizeClose++; effects.consume(code); return pathInside; } } /** * Trail. * * This calls `ok` if this *is* the trail, followed by an end, which means * the entire trail is not part of the link. * It calls `nok` if this *is* part of the link. * * ```markdown * > | https://example.com"). * ^^^ * ``` * * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeTrail(effects, ok, nok) { return trail; /** * In trail of domain or path. * * ```markdown * > | https://example.com"). * ^ * ``` * * @type {State} */ function trail(code) { if (code === 33 || code === 34 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 63 || code === 95 || code === 126) { effects.consume(code); return trail; } if (code === 38) { effects.consume(code); return trailCharacterReferenceStart; } if (code === 93) { effects.consume(code); return trailBracketAfter; } if (code === 60 || code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) return ok(code); return nok(code); } /** * In trail, after `]`. * * > 👉 **Note**: this deviates from `cmark-gfm` to fix a bug. * > See end of <https://github.com/github/cmark-gfm/issues/278> for more. * * ```markdown * > | https://example.com]( * ^ * ``` * * @type {State} */ function trailBracketAfter(code) { if (code === null || code === 40 || code === 91 || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) return ok(code); return trail(code); } /** * In character-reference like trail, after `&`. * * ```markdown * > | https://example.com&). * ^ * ``` * * @type {State} */ function trailCharacterReferenceStart(code) { return asciiAlpha(code) ? trailCharacterReferenceInside(code) : nok(code); } /** * In character-reference like trail. * * ```markdown * > | https://example.com&). * ^ * ``` * * @type {State} */ function trailCharacterReferenceInside(code) { if (code === 59) { effects.consume(code); return trail; } if (asciiAlpha(code)) { effects.consume(code); return trailCharacterReferenceInside; } return nok(code); } } /** * Dot in email domain trail. * * This calls `ok` if this *is* the trail, followed by an end, which means * the trail is not part of the link. * It calls `nok` if this *is* part of the link. * * ```markdown * > | contact@example.org. * ^ * ``` * * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeEmailDomainDotTrail(effects, ok, nok) { return start; /** * Dot. * * ```markdown * > | contact@example.org. * ^ ^ * ``` * * @type {State} */ function start(code) { effects.consume(code); return after; } /** * After dot. * * ```markdown * > | contact@example.org. * ^ ^ * ``` * * @type {State} */ function after(code) { return asciiAlphanumeric(code) ? nok(code) : ok(code); } } /** * See: * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L156>. * * @type {Previous} */ function previousWww(code) { return code === null || code === 40 || code === 42 || code === 95 || code === 91 || code === 93 || code === 126 || markdownLineEndingOrSpace(code); } /** * See: * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L214>. * * @type {Previous} */ function previousProtocol(code) { return !asciiAlpha(code); } /** * @this {TokenizeContext} * @type {Previous} */ function previousEmail(code) { return !(code === 47 || gfmAtext(code)); } /** * @param {Code} code * @returns {boolean} */ function gfmAtext(code) { return code === 43 || code === 45 || code === 46 || code === 95 || asciiAlphanumeric(code); } /** * @param {Array<Event>} events * @returns {boolean} */ function previousUnbalanced(events) { let index = events.length; let result = false; while (index--) { const token = events[index][1]; if ((token.type === "labelLink" || token.type === "labelImage") && !token._balanced) { result = true; break; } if (token._gfmAutolinkLiteralWalkedInto) { result = false; break; } } if (events.length > 0 && !result) events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true; return result; } // node_modules/micromark-extension-gfm-footnote/lib/syntax.js /** * @import {Event, Exiter, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types' */ const indent = { tokenize: tokenizeIndent, partial: true }; /** * Create an extension for `micromark` to enable GFM footnote syntax. * * @returns {Extension} * Extension for `micromark` that can be passed in `extensions` to * enable GFM footnote syntax. */ function gfmFootnote() { /** @type {Extension} */ return { document: { [91]: { name: "gfmFootnoteDefinition", tokenize: tokenizeDefinitionStart, continuation: { tokenize: tokenizeDefinitionContinuation }, exit: gfmFootnoteDefinitionEnd } }, text: { [91]: { name: "gfmFootnoteCall", tokenize: tokenizeGfmFootnoteCall }, [93]: { name: "gfmPotentialFootnoteCall", add: "after", tokenize: tokenizePotentialGfmFootnoteCall, resolveTo: resolveToPotentialGfmFootnoteCall } } }; } /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizePotentialGfmFootnoteCall(effects, ok, nok) { const self = this; let index = self.events.length; const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []); /** @type {Token} */ let labelStart; while (index--) { const token = self.events[index][1]; if (token.type === "labelImage") { labelStart = token; break; } if (token.type === "gfmFootnoteCall" || token.type === "labelLink" || token.type === "label" || token.type === "image" || token.type === "link") break; } return start; /** * @type {State} */ function start(code) { if (!labelStart || !labelStart._balanced) return nok(code); const id = normalizeIdentifier(self.sliceSerialize({ start: labelStart.end, end: self.now() })); if (id.codePointAt(0) !== 94 || !defined.includes(id.slice(1))) return nok(code); effects.enter("gfmFootnoteCallLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteCallLabelMarker"); return ok(code); } } /** @type {Resolver} */ function resolveToPotentialGfmFootnoteCall(events, context) { let index = events.length; while (index--) if (events[index][1].type === "labelImage" && events[index][0] === "enter") { events[index][1]; break; } events[index + 1][1].type = "data"; events[index + 3][1].type = "gfmFootnoteCallLabelMarker"; /** @type {Token} */ const call = { type: "gfmFootnoteCall", start: Object.assign({}, events[index + 3][1].start), end: Object.assign({}, events[events.length - 1][1].end) }; /** @type {Token} */ const marker = { type: "gfmFootnoteCallMarker", start: Object.assign({}, events[index + 3][1].end), end: Object.assign({}, events[index + 3][1].end) }; marker.end.column++; marker.end.offset++; marker.end._bufferIndex++; /** @type {Token} */ const string = { type: "gfmFootnoteCallString", start: Object.assign({}, marker.end), end: Object.assign({}, events[events.length - 1][1].start) }; /** @type {Token} */ const chunk = { type: "chunkString", contentType: "string", start: Object.assign({}, string.start), end: Object.assign({}, string.end) }; /** @type {Array<Event>} */ const replacement = [ events[index + 1], events[index + 2], [ "enter", call, context ], events[index + 3], events[index + 4], [ "enter", marker, context ], [ "exit", marker, context ], [ "enter", string, context ], [ "enter", chunk, context ], [ "exit", chunk, context ], [ "exit", string, context ], events[events.length - 2], events[events.length - 1], [ "exit", call, context ] ]; events.splice(index, events.length - index + 1, ...replacement); return events; } /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeGfmFootnoteCall(effects, ok, nok) { const self = this; const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []); let size = 0; /** @type {boolean} */ let data; return start; /** * Start of footnote label. * * ```markdown * > | a [^b] c * ^ * ``` * * @type {State} */ function start(code) { effects.enter("gfmFootnoteCall"); effects.enter("gfmFootnoteCallLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteCallLabelMarker"); return callStart; } /** * After `[`, at `^`. * * ```markdown * > | a [^b] c * ^ * ``` * * @type {State} */ function callStart(code) { if (code !== 94) return nok(code); effects.enter("gfmFootnoteCallMarker"); effects.consume(code); effects.exit("gfmFootnoteCallMarker"); effects.enter("gfmFootnoteCallString"); effects.enter("chunkString").contentType = "string"; return callData; } /** * In label. * * ```markdown * > | a [^b] c * ^ * ``` * * @type {State} */ function callData(code) { if (size > 999 || code === 93 && !data || code === null || code === 91 || markdownLineEndingOrSpace(code)) return nok(code); if (code === 93) { effects.exit("chunkString"); const token = effects.exit("gfmFootnoteCallString"); if (!defined.includes(normalizeIdentifier(self.sliceSerialize(token)))) return nok(code); effects.enter("gfmFootnoteCallLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteCallLabelMarker"); effects.exit("gfmFootnoteCall"); return ok; } if (!markdownLineEndingOrSpace(code)) data = true; size++; effects.consume(code); return code === 92 ? callEscape : callData; } /** * On character after escape. * * ```markdown * > | a [^b\c] d * ^ * ``` * * @type {State} */ function callEscape(code) { if (code === 91 || code === 92 || code === 93) { effects.consume(code); size++; return callData; } return callData(code); } } /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeDefinitionStart(effects, ok, nok) { const self = this; const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []); /** @type {string} */ let identifier; let size = 0; /** @type {boolean | undefined} */ let data; return start; /** * Start of GFM footnote definition. * * ```markdown * > | [^a]: b * ^ * ``` * * @type {State} */ function start(code) { effects.enter("gfmFootnoteDefinition")._container = true; effects.enter("gfmFootnoteDefinitionLabel"); effects.enter("gfmFootnoteDefinitionLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteDefinitionLabelMarker"); return labelAtMarker; } /** * In label, at caret. * * ```markdown * > | [^a]: b * ^ * ``` * * @type {State} */ function labelAtMarker(code) { if (code === 94) { effects.enter("gfmFootnoteDefinitionMarker"); effects.consume(code); effects.exit("gfmFootnoteDefinitionMarker"); effects.enter("gfmFootnoteDefinitionLabelString"); effects.enter("chunkString").contentType = "string"; return labelInside; } return nok(code); } /** * In label. * * > 👉 **Note**: `cmark-gfm` prevents whitespace from occurring in footnote * > definition labels. * * ```markdown * > | [^a]: b * ^ * ``` * * @type {State} */ function labelInside(code) { if (size > 999 || code === 93 && !data || code === null || code === 91 || markdownLineEndingOrSpace(code)) return nok(code); if (code === 93) { effects.exit("chunkString"); const token = effects.exit("gfmFootnoteDefinitionLabelString"); identifier = normalizeIdentifier(self.sliceSerialize(token)); effects.enter("gfmFootnoteDefinitionLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteDefinitionLabelMarker"); effects.exit("gfmFootnoteDefinitionLabel"); return labelAfter; } if (!markdownLineEndingOrSpace(code)) data = true; size++; effects.consume(code); return code === 92 ? labelEscape : labelInside; } /** * After `\`, at a special character. * * > 👉 **Note**: `cmark-gfm` currently does not support escaped brackets: * > <https://github.com/github/cmark-gfm/issues/240> * * ```markdown * > | [^a\*b]: c * ^ * ``` * * @type {State} */ function labelEscape(code) { if (code === 91 || code === 92 || code === 93) { effects.consume(code); size++; return labelInside; } return labelInside(code); } /** * After definition label. * * ```markdown * > | [^a]: b * ^ * ``` * * @type {State} */ function labelAfter(code) { if (code === 58) { effects.enter("definitionMarker"); effects.consume(code); effects.exit("definitionMarker"); if (!defined.includes(identifier)) defined.push(identifier); return factorySpace(effects, whitespaceAfter, "gfmFootnoteDefinitionWhitespace"); } return nok(code); } /** * After definition prefix. * * ```markdown * > | [^a]: b * ^ * ``` * * @type {State} */ function whitespaceAfter(code) { return ok(code); } } /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeDefinitionContinuation(effects, ok, nok) { return effects.check(blankLine, ok, effects.attempt(indent, ok, nok)); } /** @type {Exiter} */ function gfmFootnoteDefinitionEnd(effects) { effects.exit("gfmFootnoteDefinition"); } /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeIndent(effects, ok, nok) { const self = this; return factorySpace(effects, afterPrefix, "gfmFootnoteDefinitionIndent", 5); /** * @type {State} */ function afterPrefix(code) { const tail = self.events[self.events.length - 1]; return tail && tail[1].type === "gfmFootnoteDefinitionIndent" && tail[2].sliceSerialize(tail[1], true).length === 4 ? ok(code) : nok(code); } } // node_modules/micromark-extension-gfm-strikethrough/lib/syntax.js /** * @import {Options} from 'micromark-extension-gfm-strikethrough' * @import {Event, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types' */ /** * Create an extension for `micromark` to enable GFM strikethrough syntax. * * @param {Options | null | undefined} [options={}] * Configuration. * @returns {Extension} * Extension for `micromark` that can be passed in `extensions`, to * enable GFM strikethrough syntax. */ function gfmStrikethrough(options) { let single = (options || {}).singleTilde; const tokenizer = { name: "strikethrough", tokenize: tokenizeStrikethrough, resolveAll: resolveAllStrikethrough }; if (single === null || single === void 0) single = true; return { text: { [126]: tokenizer }, insideSpan: { null: [tokenizer] }, attentionMarkers: { null: [126] } }; /** * Take events and resolve strikethrough. * * @type {Resolver} */ function resolveAllStrikethrough(events, context) { let index = -1; while (++index < events.length) if (events[index][0] === "enter" && events[index][1].type === "strikethroughSequenceTemporary" && events[index][1]._close) { let open = index; while (open--) if (events[open][0] === "exit" && events[open][1].type === "strikethroughSequenceTemporary" && events[open][1]._open && events[index][1].end.offset - events[index][1].start.offset === events[open][1].end.offset - events[open][1].start.offset) { events[index][1].type = "strikethroughSequence"; events[open][1].type = "strikethroughSequence"; /** @type {Token} */ const strikethrough = { type: "strikethrough", start: Object.assign({}, events[open][1].start), end: Object.assign({}, events[index][1].end) }; /** @type {Token} */ const text = { type: "strikethroughText", start: Object.assign({}, events[open][1].end), end: Object.assign({}, events[index][1].start) }; /** @type {Array<Event>} */ const nextEvents = [ [ "enter", strikethrough, context ], [ "enter", events[open][1], context ], [ "exit", events[open][1], context ], [ "enter", text, context ] ]; const insideSpan = context.parser.constructs.insideSpan.null; if (insideSpan) splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan, events.slice(open + 1, index), context)); splice(nextEvents, nextEvents.length, 0, [ [ "exit", text, context ], [ "enter", events[index][1], context ], [ "exit", events[index][1], context ], [ "exit", strikethrough, context ] ]); splice(events, open - 1, index - open + 3, nextEvents); index = open + nextEvents.length - 2; break; } } index = -1; while (++index < events.length) if (events[index][1].type === "strikethroughSequenceTemporary") events[index][1].type = "data"; return events; } /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeStrikethrough(effects, ok, nok) { const previous = this.previous; const events = this.events; let size = 0; return start; /** @type {State} */ function start(code) { if (previous === 126 && events[events.length - 1][1].type !== "characterEscape") return nok(code); effects.enter("strikethroughSequenceTemporary"); return more(code); } /** @type {State} */ function more(code) { const before = classifyCharacter(previous); if (code === 126) { if (size > 1) return nok(code); effects.consume(code); size++; return more; } if (size < 2 && !single) return nok(code); const token = effects.exit("strikethroughSequenceTemporary"); const after = classifyCharacter(code); token._open = !after || after === 2 && Boolean(before); token._close = !before || before === 2 && Boolean(after); return ok(code); } } } // node_modules/micromark-extension-gfm-table/lib/edit-map.js /** * @import {Event} from 'micromark-util-types' */ /** * @typedef {[number, number, Array<Event>]} Change * @typedef {[number, number, number]} Jump */ /** * Tracks a bunch of edits. */ var EditMap = class { /** * Create a new edit map. */ constructor() { /** * Record of changes. * * @type {Array<Change>} */ this.map = []; /** * Changes by index, so `add` does not scan `map` (quadratic on * table-heavy documents). * * @type {Map<number, Change>} */ this.index = /* @__PURE__ */ new Map(); } /** * Create an edit: a remove and/or add at a certain place. * * @param {number} index * Index at which to apply the edit. * @param {number} remove * Count of items to remove at the index. * @param {Array<Event>} add * Items to add at the index. * @returns {undefined} * Nothing. */ add(index, remove, add) { addImplementation(this, index, remove, add); } /** * Done, change the events. * * @param {Array<Event>} events * List of events to apply the edits to. * @returns {undefined} * Nothing. */ consume(events) { this.map.sort(function(a, b) { return a[0] - b[0]; }); /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */ if (this.map.length === 0) return; let index = this.map.length; /** @type {Array<Array<Event>>} */ const vecs = []; while (index > 0) { index -= 1; vecs.push(events.slice(this.map[index][0] + this.map[index][1]), this.map[index][2]); events.length = this.map[index][0]; } vecs.push(events.slice()); events.length = 0; let slice = vecs.pop(); while (slice) { for (const element of slice) events.push(element); slice = vecs.pop(); } this.map.length = 0; this.index.clear(); } }; /** * Create an edit. * * @param {EditMap} editMap * Edit map to apply to. * @param {number} at * Index at which to apply the edit. * @param {number} remove * Count of items to remove at the index. * @param {Array<Event>} add * Items to add at the index. * @returns {undefined} * Nothing. */ function addImplementation(editMap, at, remove, add) { /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */ if (remove === 0 && add.length === 0) return; const existing = editMap.index.get(at); if (existing) { existing[1] += remove; existing[2].push(...add); return; } /** @type {Change} */ const change = [ at, remove, add ]; editMap.map.push(change); editMap.index.set(at, change); } // node_modules/micromark-extension-gfm-table/lib/infer.js /** * @import {Event} from 'micromark-util-types' */ /** * @typedef {'center' | 'left' | 'none' | 'right'} Align */ /** * Figure out the alignment of a GFM table. * * @param {Readonly<Array<Event>>} events * List of events. * @param {number} index * Table enter event. * @returns {Array<Align>} * List of aligns. */ function gfmTableAlign(events, index) { let inDelimiterRow = false; /** @type {Array<Align>} */ const align = []; while (index < events.length) { const event = events[index]; if (inDelimiterRow) { if (event[0] === "enter") { if (event[1].type === "tableContent") align.push(events[index + 1][1].type === "tableDelimiterMarker" ? "left" : "none"); } else if (event[1].type === "tableContent") { if (events[index - 1][1].type === "tableDelimiterMarker") { const alignIndex = align.length - 1; align[alignIndex] = align[alignIndex] === "left" ? "center" : "right"; } } else if (event[1].type === "tableDelimiterRow") break; } else if (event[0] === "enter" && event[1].type === "tableDelimiterRow") inDelimiterRow = true; index += 1; } return align; } // node_modules/micromark-extension-gfm-table/lib/syntax.js /** * @import {Event, Extension, Point, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types' */ /** * @typedef {[number, number, number, number]} Range * Cell info. * * @typedef {0 | 1 | 2 | 3} RowKind * Where we are: `1` for head row, `2` for delimiter row, `3` for body row. */ /** * Create an HTML extension for `micromark` to support GitHub tables syntax. * * @returns {Extension} * Extension for `micromark` that can be passed in `extensions` to enable GFM * table syntax. */ function gfmTable() { return { flow: { null: { name: "table", tokenize: tokenizeTable, resolveAll: resolveTable } } }; } /** * Tokenizer for GFM tables. * * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeTable(effects, ok, nok) { const self = this; let size = 0; let sizeB = 0; /** @type {boolean | undefined} */ let seen; return start; /** * Start of a GFM table. * * If there is a valid table row or table head before, then we try to parse * another row. * Otherwise, we try to parse a head. * * ```markdown * > | | a | * ^ * | | - | * > | | b | * ^ * ``` * @type {State} */ function start(code) { let index = self.events.length - 1; while (index > -1) { const { type } = self.events[index][1]; if (type === "lineEnding" || type === "linePrefix") index--; else break; } const tail = index > -1 ? self.events[index][1].type : null; const next = tail === "tableHead" || tail === "tableRow" ? bodyRowStart : headRowBefore; if (next === bodyRowStart && self.parser.lazy[self.now().line]) return nok(code); return next(code); } /** * Before table head row. * * ```markdown * > | | a | * ^ * | | - | * | | b | * ``` * * @type {State} */ function headRowBefore(code) { effects.enter("tableHead"); effects.enter("tableRow"); return headRowStart(code); } /** * Before table head row, after whitespace. * * ```markdown * > | | a | * ^ * | | - | * | | b | * ``` * * @type {State} */ function headRowStart(code) { if (code === 124) return headRowBreak(code); seen = true; sizeB += 1; return headRowBreak(code); } /** * At break in table head row. * * ```markdown * > | | a | * ^ * ^ * ^ * | | - | * | | b | * ``` * * @type {State} */ function headRowBreak(code) { if (code === null) return nok(code); if (markdownLineEnding(code)) { if (sizeB > 1) { sizeB = 0; self.interrupt = true; effects.exit("tableRow"); effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return headDelimiterStart; } return nok(code); } if (markdownSpace(code)) return factorySpace(effects, headRowBreak, "whitespace")(code); sizeB += 1; if (seen) { seen = false; size += 1; } if (code === 124) { effects.enter("tableCellDivider"); effects.consume(code); effects.exit("tableCellDivider"); seen = true; return headRowBreak; } effects.enter("data"); return headRowData(code); } /** * In table head row data. * * ```markdown * > | | a | * ^ * | | - | * | | b | * ``` * * @type {State} */ function headRowData(code) { if (code === null || code === 124 || markdownLineEndingOrSpace(code)) { effects.exit("data"); return headRowBreak(code); } effects.consume(code); return code === 92 ? headRowEscape : headRowData; } /** * In table head row escape. * * ```markdown * > | | a\-b | * ^ * | | ---- | * | | c | * ``` * * @type {State} */ function headRowEscape(code) { if (code === 92 || code === 124) { effects.consume(code); return headRowData; } return headRowData(code); } /** * Before delimiter row. * * ```markdown * | | a | * > | | - | * ^ * | | b | * ``` * * @type {State} */ function headDelimiterStart(code) { self.interrupt = false; if (self.parser.lazy[self.now().line]) return nok(code); effects.enter("tableDelimiterRow"); seen = false; if (markdownSpace(code)) return factorySpace(effects, headDelimiterBefore, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code); return headDelimiterBefore(code); } /** * Before delimiter row, after optional whitespace. * * Reused when a `|` is found later, to parse another cell. * * ```markdown * | | a | * > | | - | * ^ * | | b | * ``` * * @type {State} */ function headDelimiterBefore(code) { if (code === 45 || code === 58) return headDelimiterValueBefore(code); if (code === 124) { seen = true; effects.enter("tableCellDivider"); effects.consume(code); effects.exit("tableCellDivider"); return headDelimiterCellBefore; } return headDelimiterNok(code); } /** * After `|`, before delimiter cell. * * ```markdown * | | a | * > | | - | * ^ * ``` * * @type {State} */ function headDelimiterCellBefore(code) { if (markdownSpace(code)) return factorySpace(effects, headDelimiterValueBefore, "whitespace")(code); return headDelimiterValueBefore(code); } /** * Before delimiter cell value. * * ```markdown * | | a | * > | | - | * ^ * ``` * * @type {State} */ function headDelimiterValueBefore(code) { if (code === 58) { sizeB += 1; seen = true; effects.enter("tableDelimiterMarker"); effects.consume(code); effects.exit("tableDelimiterMarker"); return headDelimiterLeftAlignmentAfter; } if (code === 45) { sizeB += 1; return headDelimiterLeftAlignmentAfter(code); } if (code === null || markdownLineEnding(code)) return headDelimiterCellAfter(code); return headDelimiterNok(code); } /** * After delimiter cell left alignment marker. * * ```markdown * | | a | * > | | :- | * ^ * ``` * * @type {State} */ function headDelimiterLeftAlignmentAfter(code) { if (code === 45) { effects.enter("tableDelimiterFiller"); return headDelimiterFiller(code); } return headDelimiterNok(code); } /** * In delimiter cell filler. * * ```markdown * | | a | * > | | - | * ^ * ``` * * @type {State} */ function headDelimiterFiller(code) { if (code === 45) { effects.consume(code); return headDelimiterFiller; } if (code === 58) { seen = true; effects.exit("tableDelimiterFiller"); effects.enter("tableDelimiterMarker"); effects.consume(code); effects.exit("tableDelimiterMarker"); return headDelimiterRightAlignmentAfter; } effects.exit("tableDelimiterFiller"); return headDelimiterRightAlignmentAfter(code); } /** * After delimiter cell right alignment marker. * * ```markdown * | | a | * > | | -: | * ^ * ``` * * @type {State} */ function headDelimiterRightAlignmentAfter(code) { if (markdownSpace(code)) return factorySpace(effects, headDelimiterCellAfter, "whitespace")(code); return headDelimiterCellAfter(code); } /** * After delimiter cell. * * ```markdown * | | a | * > | | -: | * ^ * ``` * * @type {State} */ function headDelimiterCellAfter(code) { if (code === 124) return headDelimiterBefore(code); if (code === null || markdownLineEnding(code)) { if (!seen || size !== sizeB) return headDelimiterNok(code); effects.exit("tableDelimiterRow"); effects.exit("tableHead"); return ok(code); } return headDelimiterNok(code); } /** * In delimiter row, at a disallowed byte. * * ```markdown * | | a | * > | | x | * ^ * ``` * * @type {State} */ function headDelimiterNok(code) { return nok(code); } /** * Before table body row. * * ```markdown * | | a | * | | - | * > | | b | * ^ * ``` * * @type {State} */ function bodyRowStart(code) { effects.enter("tableRow"); return bodyRowBreak(code); } /** * At break in table body row. * * ```markdown * | | a | * | | - | * > | | b | * ^ * ^ * ^ * ``` * * @type {State} */ function bodyRowBreak(code) { if (code === 124) { effects.enter("tableCellDivider"); effects.consume(code); effects.exit("tableCellDivider"); return bodyRowBreak; } if (code === null || markdownLineEnding(code)) { effects.exit("tableRow"); return ok(code); } if (markdownSpace(code)) return factorySpace(effects, bodyRowBreak, "whitespace")(code); effects.enter("data"); return bodyRowData(code); } /** * In table body row data. * * ```markdown * | | a | * | | - | * > | | b | * ^ * ``` * * @type {State} */ function bodyRowData(code) { if (code === null || code === 124 || markdownLineEndingOrSpace(code)) { effects.exit("data"); return bodyRowBreak(code); } effects.consume(code); return code === 92 ? bodyRowEscape : bodyRowData; } /** * In table body row escape. * * ```markdown * | | a | * | | ---- | * > | | b\-c | * ^ * ``` * * @type {State} */ function bodyRowEscape(code) { if (code === 92 || code === 124) { effects.consume(code); return bodyRowData; } return bodyRowData(code); } } /** @type {Resolver} */ function resolveTable(events, context) { let index = -1; let inFirstCellAwaitingPipe = true; /** @type {RowKind} */ let rowKind = 0; /** @type {Range} */ let lastCell = [ 0, 0, 0, 0 ]; /** @type {Range} */ let cell = [ 0, 0, 0, 0 ]; let afterHeadAwaitingFirstBodyRow = false; let lastTableEnd = 0; /** @type {Token | undefined} */ let currentTable; /** @type {Token | undefined} */ let currentBody; /** @type {Token | undefined} */ let currentCell; const map = new EditMap(); while (++index < events.length) { const event = events[index]; const token = event[1]; if (event[0] === "enter") { if (token.type === "tableHead") { afterHeadAwaitingFirstBodyRow = false; if (lastTableEnd !== 0) { flushTableEnd(map, context, lastTableEnd, currentTable, currentBody); currentBody = void 0; lastTableEnd = 0; } currentTable = { type: "table", start: Object.assign({}, token.start), end: Object.assign({}, token.end) }; map.add(index, 0, [[ "enter", currentTable, context ]]); } else if (token.type === "tableRow" || token.type === "tableDelimiterRow") { inFirstCellAwaitingPipe = true; currentCell = void 0; lastCell = [ 0, 0, 0, 0 ]; cell = [ 0, index + 1, 0, 0 ]; if (afterHeadAwaitingFirstBodyRow) { afterHeadAwaitingFirstBodyRow = false; currentBody = { type: "tableBody", start: Object.assign({}, token.start), end: Object.assign({}, token.end) }; map.add(index, 0, [[ "enter", currentBody, context ]]); } rowKind = token.type === "tableDelimiterRow" ? 2 : currentBody ? 3 : 1; } else if (rowKind && (token.type === "data" || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) { inFirstCellAwaitingPipe = false; if (cell[2] === 0) { if (lastCell[1] !== 0) { cell[0] = cell[1]; currentCell = flushCell(map, context, lastCell, rowKind, void 0, currentCell); lastCell = [ 0, 0, 0, 0 ]; } cell[2] = index; } } else if (token.type === "tableCellDivider") { if (inFirstCellAwaitingPipe) inFirstCellAwaitingPipe = false; else { if (lastCell[1] !== 0) { cell[0] = cell[1]; currentCell = flushCell(map, context, lastCell, rowKind, void 0, currentCell); } lastCell = cell; cell = [ lastCell[1], index, 0, 0 ]; } } } else if (token.type === "tableHead") { afterHeadAwaitingFirstBodyRow = true; lastTableEnd = index; } else if (token.type === "tableRow" || token.type === "tableDelimiterRow") { lastTableEnd = index; if (lastCell[1] !== 0) { cell[0] = cell[1]; currentCell = flushCell(map, context, lastCell, rowKind, index, currentCell); } else if (cell[1] !== 0) currentCell = flushCell(map, context, cell, rowKind, index, currentCell); rowKind = 0; } else if (rowKind && (token.type === "data" || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) cell[3] = index; } if (lastTableEnd !== 0) flushTableEnd(map, context, lastTableEnd, currentTable, currentBody); map.consume(context.events); index = -1; while (++index < context.events.length) { const event = context.events[index]; if (event[0] === "enter" && event[1].type === "table") event[1]._align = gfmTableAlign(context.events, index); } return events; } /** * Generate a cell. * * @param {EditMap} map * Edit map to apply to. * @param {Readonly<TokenizeContext>} context * Tokenize context. * @param {Readonly<Range>} range * Range of the cell within events. * @param {RowKind} rowKind * Type of row. * @param {number | undefined} rowEnd * Index of the end of the row, if known. * @param {Token | undefined} previousCell * Previous cell token, if any. * @returns {Token | undefined} * Current cell token after flushing, if any. */ function flushCell(map, context, range, rowKind, rowEnd, previousCell) { const groupName = rowKind === 1 ? "tableHeader" : rowKind === 2 ? "tableDelimiter" : "tableData"; const valueName = "tableContent"; if (range[0] !== 0) { previousCell.end = Object.assign({}, getPoint(context.events, range[0])); map.add(range[0], 0, [[ "exit", previousCell, context ]]); } const now = getPoint(context.events, range[1]); previousCell = { type: groupName, start: Object.assign({}, now), end: Object.assign({}, now) }; map.add(range[1], 0, [[ "enter", previousCell, context ]]); if (range[2] !== 0) { const relatedStart = getPoint(context.events, range[2]); const relatedEnd = getPoint(context.events, range[3]); /** @type {Token} */ const valueToken = { type: valueName, start: Object.assign({}, relatedStart), end: Object.assign({}, relatedEnd) }; map.add(range[2], 0, [[ "enter", valueToken, context ]]); if (rowKind !== 2) { const start = context.events[range[2]]; const end = context.events[range[3]]; start[1].end = Object.assign({}, end[1].end); start[1].type = "chunkText"; start[1].contentType = "text"; if (range[3] > range[2] + 1) { const a = range[2] + 1; const b = range[3] - range[2] - 1; map.add(a, b, []); } } map.add(range[3] + 1, 0, [[ "exit", valueToken, context ]]); } if (rowEnd !== void 0) { previousCell.end = Object.assign({}, getPoint(context.events, rowEnd)); map.add(rowEnd, 0, [[ "exit", previousCell, context ]]); previousCell = void 0; } return previousCell; } /** * Generate table end (and table body end). * * @param {Readonly<EditMap>} map * Edit map to apply to. * @param {Readonly<TokenizeContext>} context * Tokenize context. * @param {number} index * Index within the events where the table end should be inserted. * @param {Token} table * Table token. * @param {Token | undefined} tableBody * Table body token, if any. * @returns {undefined} * Nothing. */ function flushTableEnd(map, context, index, table, tableBody) { /** @type {Array<Event>} */ const exits = []; const related = getPoint(context.events, index); if (tableBody) { tableBody.end = Object.assign({}, related); exits.push([ "exit", tableBody, context ]); } table.end = Object.assign({}, related); exits.push([ "exit", table, context ]); map.add(index + 1, 0, exits); } /** * Get the point (start or end) for a given event in the list of events. * * @param {Readonly<Array<Event>>} events * List of events. * @param {number} index * Index of the event to get the point for. * @returns {Readonly<Point>} * Start point for enter and end point for exit. */ function getPoint(events, index) { const event = events[index]; const side = event[0] === "enter" ? "start" : "end"; return event[1][side]; } // node_modules/micromark-extension-gfm-task-list-item/lib/syntax.js /** * @import {Extension, State, TokenizeContext, Tokenizer} from 'micromark-util-types' */ const tasklistCheck = { name: "tasklistCheck", tokenize: tokenizeTasklistCheck }; /** * Create an HTML extension for `micromark` to support GFM task list items * syntax. * * @returns {Extension} * Extension for `micromark` that can be passed in `htmlExtensions` to * support GFM task list items when serializing to HTML. */ function gfmTaskListItem() { return { text: { [91]: tasklistCheck } }; } /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeTasklistCheck(effects, ok, nok) { const self = this; return open; /** * At start of task list item check. * * ```markdown * > | * [x] y. * ^ * ``` * * @type {State} */ function open(code) { if (self.previous !== null || !self._gfmTasklistFirstContentOfListItem) return nok(code); effects.enter("taskListCheck"); effects.enter("taskListCheckMarker"); effects.consume(code); effects.exit("taskListCheckMarker"); return inside; } /** * In task list item check. * * ```markdown * > | * [x] y. * ^ * ``` * * @type {State} */ function inside(code) { if (markdownLineEndingOrSpace(code)) { effects.enter("taskListCheckValueUnchecked"); effects.consume(code); effects.exit("taskListCheckValueUnchecked"); return close; } if (code === 88 || code === 120) { effects.enter("taskListCheckValueChecked"); effects.consume(code); effects.exit("taskListCheckValueChecked"); return close; } return nok(code); } /** * At close of task list item check. * * ```markdown * > | * [x] y. * ^ * ``` * * @type {State} */ function close(code) { if (code === 93) { effects.enter("taskListCheckMarker"); effects.consume(code); effects.exit("taskListCheckMarker"); effects.exit("taskListCheck"); return after; } return nok(code); } /** * @type {State} */ function after(code) { if (markdownLineEnding(code)) return ok(code); if (markdownSpace(code)) return effects.check({ tokenize: spaceThenNonSpace }, ok, nok)(code); return nok(code); } } /** * @this {TokenizeContext} * @type {Tokenizer} */ function spaceThenNonSpace(effects, ok, nok) { return factorySpace(effects, after, "whitespace"); /** * After whitespace, after task list item check. * * ```markdown * > | * [x] y. * ^ * ``` * * @type {State} */ function after(code) { return code === null ? nok(code) : ok(code); } } // node_modules/micromark-extension-gfm/index.js /** * @typedef {import('micromark-extension-gfm-footnote').HtmlOptions} HtmlOptions * @typedef {import('micromark-extension-gfm-strikethrough').Options} Options * @typedef {import('micromark-util-types').Extension} Extension * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension */ /** * Create an extension for `micromark` to enable GFM syntax. * * @param {Options | null | undefined} [options] * Configuration (optional). * * Passed to `micromark-extens-gfm-strikethrough`. * @returns {Extension} * Extension for `micromark` that can be passed in `extensions` to enable GFM * syntax. */ function gfm(options) { return combineExtensions([ gfmAutolinkLiteral(), gfmFootnote(), gfmStrikethrough(options), gfmTable(), gfmTaskListItem() ]); } // node_modules/micromark-extension-math/lib/math-flow.js /** * @import {Construct, State, TokenizeContext, Tokenizer} from 'micromark-util-types' */ /** @type {Construct} */ const mathFlow = { tokenize: tokenizeMathFenced, concrete: true, name: "mathFlow" }; /** @type {Construct} */ const nonLazyContinuation$1 = { tokenize: tokenizeNonLazyContinuation$1, partial: true }; /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeMathFenced(effects, ok, nok) { const self = this; const tail = self.events[self.events.length - 1]; const initialSize = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0; let sizeOpen = 0; return start; /** * Start of math. * * ```markdown * > | $$ * ^ * | \frac{1}{2} * | $$ * ``` * * @type {State} */ function start(code) { effects.enter("mathFlow"); effects.enter("mathFlowFence"); effects.enter("mathFlowFenceSequence"); return sequenceOpen(code); } /** * In opening fence sequence. * * ```markdown * > | $$ * ^ * | \frac{1}{2} * | $$ * ``` * * @type {State} */ function sequenceOpen(code) { if (code === 36) { effects.consume(code); sizeOpen++; return sequenceOpen; } if (sizeOpen < 2) return nok(code); effects.exit("mathFlowFenceSequence"); return factorySpace(effects, metaBefore, "whitespace")(code); } /** * In opening fence, before meta. * * ```markdown * > | $$asciimath * ^ * | x < y * | $$ * ``` * * @type {State} */ function metaBefore(code) { if (code === null || markdownLineEnding(code)) return metaAfter(code); effects.enter("mathFlowFenceMeta"); effects.enter("chunkString", { contentType: "string" }); return meta(code); } /** * In meta. * * ```markdown * > | $$asciimath * ^ * | x < y * | $$ * ``` * * @type {State} */ function meta(code) { if (code === null || markdownLineEnding(code)) { effects.exit("chunkString"); effects.exit("mathFlowFenceMeta"); return metaAfter(code); } if (code === 36) return nok(code); effects.consume(code); return meta; } /** * After meta. * * ```markdown * > | $$ * ^ * | \frac{1}{2} * | $$ * ``` * * @type {State} */ function metaAfter(code) { effects.exit("mathFlowFence"); if (self.interrupt) return ok(code); return effects.attempt(nonLazyContinuation$1, beforeNonLazyContinuation, after)(code); } /** * After eol/eof in math, at a non-lazy closing fence or content. * * ```markdown * | $$ * > | \frac{1}{2} * ^ * > | $$ * ^ * ``` * * @type {State} */ function beforeNonLazyContinuation(code) { return effects.attempt({ tokenize: tokenizeClosingFence, partial: true }, after, contentStart)(code); } /** * Before math content, definitely not before a closing fence. * * ```markdown * | $$ * > | \frac{1}{2} * ^ * | $$ * ``` * * @type {State} */ function contentStart(code) { return (initialSize ? factorySpace(effects, beforeContentChunk, "linePrefix", initialSize + 1) : beforeContentChunk)(code); } /** * Before math content, after optional prefix. * * ```markdown * | $$ * > | \frac{1}{2} * ^ * | $$ * ``` * * @type {State} */ function beforeContentChunk(code) { if (code === null) return after(code); if (markdownLineEnding(code)) return effects.attempt(nonLazyContinuation$1, beforeNonLazyContinuation, after)(code); effects.enter("mathFlowValue"); return contentChunk(code); } /** * In math content. * * ```markdown * | $$ * > | \frac{1}{2} * ^ * | $$ * ``` * * @type {State} */ function contentChunk(code) { if (code === null || markdownLineEnding(code)) { effects.exit("mathFlowValue"); return beforeContentChunk(code); } effects.consume(code); return contentChunk; } /** * After math (ha!). * * ```markdown * | $$ * | \frac{1}{2} * > | $$ * ^ * ``` * * @type {State} */ function after(code) { effects.exit("mathFlow"); return ok(code); } /** @type {Tokenizer} */ function tokenizeClosingFence(effects, ok, nok) { let size = 0; /** * Before closing fence, at optional whitespace. * * ```markdown * | $$ * | \frac{1}{2} * > | $$ * ^ * ``` */ return factorySpace(effects, beforeSequenceClose, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4); /** * In closing fence, after optional whitespace, at sequence. * * ```markdown * | $$ * | \frac{1}{2} * > | $$ * ^ * ``` * * @type {State} */ function beforeSequenceClose(code) { effects.enter("mathFlowFence"); effects.enter("mathFlowFenceSequence"); return sequenceClose(code); } /** * In closing fence sequence. * * ```markdown * | $$ * | \frac{1}{2} * > | $$ * ^ * ``` * * @type {State} */ function sequenceClose(code) { if (code === 36) { size++; effects.consume(code); return sequenceClose; } if (size < sizeOpen) return nok(code); effects.exit("mathFlowFenceSequence"); return factorySpace(effects, afterSequenceClose, "whitespace")(code); } /** * After closing fence sequence, after optional whitespace. * * ```markdown * | $$ * | \frac{1}{2} * > | $$ * ^ * ``` * * @type {State} */ function afterSequenceClose(code) { if (code === null || markdownLineEnding(code)) { effects.exit("mathFlowFence"); return ok(code); } return nok(code); } } } /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeNonLazyContinuation$1(effects, ok, nok) { const self = this; return start; /** @type {State} */ function start(code) { if (code === null) return ok(code); effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return lineStart; } /** @type {State} */ function lineStart(code) { return self.parser.lazy[self.now().line] ? nok(code) : ok(code); } } // node_modules/micromark-extension-math/lib/math-text.js /** * @import {Options} from 'micromark-extension-math' * @import {Construct, Previous, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types' */ /** * @param {Options | null | undefined} [options={}] * Configuration (default: `{}`). * @returns {Construct} * Construct. */ function mathText(options) { let single = (options || {}).singleDollarTextMath; if (single === null || single === void 0) single = true; return { tokenize: tokenizeMathText, resolve: resolveMathText, previous, name: "mathText" }; /** * @this {TokenizeContext} * @type {Tokenizer} */ function tokenizeMathText(effects, ok, nok) { let sizeOpen = 0; /** @type {number} */ let size; /** @type {Token} */ let token; return start; /** * Start of math (text). * * ```markdown * > | $a$ * ^ * > | \$a$ * ^ * ``` * * @type {State} */ function start(code) { effects.enter("mathText"); effects.enter("mathTextSequence"); return sequenceOpen(code); } /** * In opening sequence. * * ```markdown * > | $a$ * ^ * ``` * * @type {State} */ function sequenceOpen(code) { if (code === 36) { effects.consume(code); sizeOpen++; return sequenceOpen; } if (sizeOpen < 2 && !single) return nok(code); effects.exit("mathTextSequence"); return between(code); } /** * Between something and something else. * * ```markdown * > | $a$ * ^^ * ``` * * @type {State} */ function between(code) { if (code === null) return nok(code); if (code === 36) { token = effects.enter("mathTextSequence"); size = 0; return sequenceClose(code); } if (code === 32) { effects.enter("space"); effects.consume(code); effects.exit("space"); return between; } if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return between; } effects.enter("mathTextData"); return data(code); } /** * In data. * * ```markdown * > | $a$ * ^ * ``` * * @type {State} */ function data(code) { if (code === null || code === 32 || code === 36 || markdownLineEnding(code)) { effects.exit("mathTextData"); return between(code); } effects.consume(code); return data; } /** * In closing sequence. * * ```markdown * > | `a` * ^ * ``` * * @type {State} */ function sequenceClose(code) { if (code === 36) { effects.consume(code); size++; return sequenceClose; } if (size === sizeOpen) { effects.exit("mathTextSequence"); effects.exit("mathText"); return ok(code); } token.type = "mathTextData"; return data(code); } } } /** @type {Resolver} */ function resolveMathText(events) { let tailExitIndex = events.length - 4; let headEnterIndex = 3; /** @type {number} */ let index; /** @type {number | undefined} */ let enter; if ((events[headEnterIndex][1].type === "lineEnding" || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === "lineEnding" || events[tailExitIndex][1].type === "space")) { index = headEnterIndex; while (++index < tailExitIndex) if (events[index][1].type === "mathTextData") { events[tailExitIndex][1].type = "mathTextPadding"; events[headEnterIndex][1].type = "mathTextPadding"; headEnterIndex += 2; tailExitIndex -= 2; break; } } index = headEnterIndex - 1; tailExitIndex++; while (++index <= tailExitIndex) if (enter === void 0) { if (index !== tailExitIndex && events[index][1].type !== "lineEnding") enter = index; } else if (index === tailExitIndex || events[index][1].type === "lineEnding") { events[enter][1].type = "mathTextData"; if (index !== enter + 2) { events[enter][1].end = events[index - 1][1].end; events.splice(enter + 2, index - enter - 2); tailExitIndex -= index - enter - 2; index = enter + 2; } enter = void 0; } return events; } /** * @this {TokenizeContext} * @type {Previous} */ function previous(code) { return code !== 36 || this.events[this.events.length - 1][1].type === "characterEscape"; } // node_modules/micromark-extension-math/lib/syntax.js /** * @import {Options} from 'micromark-extension-math' * @import {Extension} from 'micromark-util-types' */ /** * Create an extension for `micromark` to enable math syntax. * * @param {Options | null | undefined} [options={}] * Configuration (default: `{}`). * @returns {Extension} * Extension for `micromark` that can be passed in `extensions`, to * enable math syntax. */ function math$1(options) { return { flow: { [36]: mathFlow }, text: { [36]: mathText(options) } }; } // node_modules/micromark-util-symbol/lib/codes.js /** * Character codes. * * This module is compiled away! * * micromark works based on character codes. * This module contains constants for the ASCII block and the replacement * character. * A couple of them are handled in a special way, such as the line endings * (CR, LF, and CR+LF, commonly known as end-of-line: EOLs), the tab (horizontal * tab) and its expansion based on what column it’s at (virtual space), * and the end-of-file (eof) character. * As values are preprocessed before handling them, the actual characters LF, * CR, HT, and NUL (which is present as the replacement character), are * guaranteed to not exist. * * Unicode basic latin block. */ const codes = { carriageReturn: -5, lineFeed: -4, carriageReturnLineFeed: -3, horizontalTab: -2, virtualSpace: -1, eof: null, nul: 0, soh: 1, stx: 2, etx: 3, eot: 4, enq: 5, ack: 6, bel: 7, bs: 8, ht: 9, lf: 10, vt: 11, ff: 12, cr: 13, so: 14, si: 15, dle: 16, dc1: 17, dc2: 18, dc3: 19, dc4: 20, nak: 21, syn: 22, etb: 23, can: 24, em: 25, sub: 26, esc: 27, fs: 28, gs: 29, rs: 30, us: 31, space: 32, exclamationMark: 33, quotationMark: 34, numberSign: 35, dollarSign: 36, percentSign: 37, ampersand: 38, apostrophe: 39, leftParenthesis: 40, rightParenthesis: 41, asterisk: 42, plusSign: 43, comma: 44, dash: 45, dot: 46, slash: 47, digit0: 48, digit1: 49, digit2: 50, digit3: 51, digit4: 52, digit5: 53, digit6: 54, digit7: 55, digit8: 56, digit9: 57, colon: 58, semicolon: 59, lessThan: 60, equalsTo: 61, greaterThan: 62, questionMark: 63, atSign: 64, uppercaseA: 65, uppercaseB: 66, uppercaseC: 67, uppercaseD: 68, uppercaseE: 69, uppercaseF: 70, uppercaseG: 71, uppercaseH: 72, uppercaseI: 73, uppercaseJ: 74, uppercaseK: 75, uppercaseL: 76, uppercaseM: 77, uppercaseN: 78, uppercaseO: 79, uppercaseP: 80, uppercaseQ: 81, uppercaseR: 82, uppercaseS: 83, uppercaseT: 84, uppercaseU: 85, uppercaseV: 86, uppercaseW: 87, uppercaseX: 88, uppercaseY: 89, uppercaseZ: 90, leftSquareBracket: 91, backslash: 92, rightSquareBracket: 93, caret: 94, underscore: 95, graveAccent: 96, lowercaseA: 97, lowercaseB: 98, lowercaseC: 99, lowercaseD: 100, lowercaseE: 101, lowercaseF: 102, lowercaseG: 103, lowercaseH: 104, lowercaseI: 105, lowercaseJ: 106, lowercaseK: 107, lowercaseL: 108, lowercaseM: 109, lowercaseN: 110, lowercaseO: 111, lowercaseP: 112, lowercaseQ: 113, lowercaseR: 114, lowercaseS: 115, lowercaseT: 116, lowercaseU: 117, lowercaseV: 118, lowercaseW: 119, lowercaseX: 120, lowercaseY: 121, lowercaseZ: 122, leftCurlyBrace: 123, verticalBar: 124, rightCurlyBrace: 125, tilde: 126, del: 127, byteOrderMarker: 65279, replacementCharacter: 65533 }; // node_modules/micromark-util-symbol/lib/constants.js /** * This module is compiled away! * * Parsing markdown comes with a couple of constants, such as minimum or maximum * sizes of certain sequences. * Additionally, there are a couple symbols used inside micromark. * These are all defined here, but compiled away by scripts. */ const constants = { attentionSideAfter: 2, attentionSideBefore: 1, atxHeadingOpeningFenceSizeMax: 6, autolinkDomainSizeMax: 63, autolinkSchemeSizeMax: 32, cdataOpeningString: "CDATA[", characterGroupPunctuation: 2, characterGroupWhitespace: 1, characterReferenceDecimalSizeMax: 7, characterReferenceHexadecimalSizeMax: 6, characterReferenceNamedSizeMax: 31, codeFencedSequenceSizeMin: 3, contentTypeContent: "content", contentTypeDocument: "document", contentTypeFlow: "flow", contentTypeString: "string", contentTypeText: "text", hardBreakPrefixSizeMin: 2, htmlBasic: 6, htmlCdata: 5, htmlComment: 2, htmlComplete: 7, htmlDeclaration: 4, htmlInstruction: 3, htmlRawSizeMax: 8, htmlRaw: 1, linkResourceDestinationBalanceMax: 32, linkReferenceSizeMax: 999, listItemValueSizeMax: 10, numericBaseDecimal: 10, numericBaseHexadecimal: 16, tabSize: 4, thematicBreakMarkerCountMin: 3, v8MaxSafeChunkSize: 1e4 }; // node_modules/micromark-util-symbol/lib/types.js /** * This module is compiled away! * * Here is the list of all types of tokens exposed by micromark, with a short * explanation of what they include and where they are found. * In picking names, generally, the rule is to be as explicit as possible * instead of reusing names. * For example, there is a `definitionDestination` and a `resourceDestination`, * instead of one shared name. */ const types = { data: "data", whitespace: "whitespace", lineEnding: "lineEnding", lineEndingBlank: "lineEndingBlank", linePrefix: "linePrefix", lineSuffix: "lineSuffix", atxHeading: "atxHeading", atxHeadingSequence: "atxHeadingSequence", atxHeadingText: "atxHeadingText", autolink: "autolink", autolinkEmail: "autolinkEmail", autolinkMarker: "autolinkMarker", autolinkProtocol: "autolinkProtocol", characterEscape: "characterEscape", characterEscapeValue: "characterEscapeValue", characterReference: "characterReference", characterReferenceMarker: "characterReferenceMarker", characterReferenceMarkerNumeric: "characterReferenceMarkerNumeric", characterReferenceMarkerHexadecimal: "characterReferenceMarkerHexadecimal", characterReferenceValue: "characterReferenceValue", codeFenced: "codeFenced", codeFencedFence: "codeFencedFence", codeFencedFenceSequence: "codeFencedFenceSequence", codeFencedFenceInfo: "codeFencedFenceInfo", codeFencedFenceMeta: "codeFencedFenceMeta", codeFlowValue: "codeFlowValue", codeIndented: "codeIndented", codeText: "codeText", codeTextData: "codeTextData", codeTextPadding: "codeTextPadding", codeTextSequence: "codeTextSequence", content: "content", definition: "definition", definitionDestination: "definitionDestination", definitionDestinationLiteral: "definitionDestinationLiteral", definitionDestinationLiteralMarker: "definitionDestinationLiteralMarker", definitionDestinationRaw: "definitionDestinationRaw", definitionDestinationString: "definitionDestinationString", definitionLabel: "definitionLabel", definitionLabelMarker: "definitionLabelMarker", definitionLabelString: "definitionLabelString", definitionMarker: "definitionMarker", definitionTitle: "definitionTitle", definitionTitleMarker: "definitionTitleMarker", definitionTitleString: "definitionTitleString", emphasis: "emphasis", emphasisSequence: "emphasisSequence", emphasisText: "emphasisText", escapeMarker: "escapeMarker", hardBreakEscape: "hardBreakEscape", hardBreakTrailing: "hardBreakTrailing", htmlFlow: "htmlFlow", htmlFlowData: "htmlFlowData", htmlText: "htmlText", htmlTextData: "htmlTextData", image: "image", label: "label", labelText: "labelText", labelLink: "labelLink", labelImage: "labelImage", labelMarker: "labelMarker", labelImageMarker: "labelImageMarker", labelEnd: "labelEnd", link: "link", paragraph: "paragraph", reference: "reference", referenceMarker: "referenceMarker", referenceString: "referenceString", resource: "resource", resourceDestination: "resourceDestination", resourceDestinationLiteral: "resourceDestinationLiteral", resourceDestinationLiteralMarker: "resourceDestinationLiteralMarker", resourceDestinationRaw: "resourceDestinationRaw", resourceDestinationString: "resourceDestinationString", resourceMarker: "resourceMarker", resourceTitle: "resourceTitle", resourceTitleMarker: "resourceTitleMarker", resourceTitleString: "resourceTitleString", setextHeading: "setextHeading", setextHeadingText: "setextHeadingText", setextHeadingLine: "setextHeadingLine", setextHeadingLineSequence: "setextHeadingLineSequence", strong: "strong", strongSequence: "strongSequence", strongText: "strongText", thematicBreak: "thematicBreak", thematicBreakSequence: "thematicBreakSequence", blockQuote: "blockQuote", blockQuotePrefix: "blockQuotePrefix", blockQuoteMarker: "blockQuoteMarker", blockQuotePrefixWhitespace: "blockQuotePrefixWhitespace", listOrdered: "listOrdered", listUnordered: "listUnordered", listItemIndent: "listItemIndent", listItemMarker: "listItemMarker", listItemPrefix: "listItemPrefix", listItemPrefixWhitespace: "listItemPrefixWhitespace", listItemValue: "listItemValue", chunkDocument: "chunkDocument", chunkContent: "chunkContent", chunkFlow: "chunkFlow", chunkText: "chunkText", chunkString: "chunkString" }; // src/client/markdown/cjkFriendlyStrong.ts /** Let asterisk strong emphasis close after punctuation when CJK prose continues without whitespace. */ const cjkCharacter = new RegExp([ "\\p{Script_Extensions=Han}", "\\p{Script_Extensions=Hiragana}", "\\p{Script_Extensions=Katakana}", "\\p{Script_Extensions=Hangul}", "\\p{Script_Extensions=Bopomofo}" ].join("|"), "u"); function isCjkCharacter(code) { return code !== null && code >= 0 && cjkCharacter.test(String.fromCodePoint(code)); } const tokenizeCjkFriendlyAttention = function(effects, ok, nok) { const configuredAttentionMarkers = this.parser.constructs.attentionMarkers.null; if (configuredAttentionMarkers === void 0) throw new Error("micromark CommonMark attention markers are unavailable"); const attentionMarkers = configuredAttentionMarkers; const previous = this.previous; const before = classifyCharacter(previous); let marker = codes.eof; return start; function start(code) { /* v8 ignore next -- this text construct is dispatched only for an asterisk. */ if (code !== codes.asterisk) return nok(code); marker = code; effects.enter("attentionSequence"); return inside(code); } function inside(code) { if (code === marker) { effects.consume(code); return inside; } const token = effects.exit("attentionSequence"); const after = classifyCharacter(code); const open = !after || after === constants.characterGroupPunctuation && Boolean(before) || attentionMarkers.includes(code); const commonMarkClose = !before || before === constants.characterGroupPunctuation && Boolean(after) || attentionMarkers.includes(previous); const cjkStrongClose = token.end.offset - token.start.offset >= 2 && unicodePunctuation(previous) && isCjkCharacter(code); const close = commonMarkClose || cjkStrongClose; token._open = open; token._close = close; return ok(code); } }; const cjkFriendlyAttention = { name: "cjkFriendlyAttention", resolveAll: attention.resolveAll, tokenize: tokenizeCjkFriendlyAttention }; const cjkFriendlyStrongExtension = { text: { [codes.asterisk]: cjkFriendlyAttention } }; /** * Extend CommonMark asterisk strong emphasis for punctuation-delimited CJK * prose, as a micromark syntax extension for `fromMarkdown`. * @returns The micromark syntax extension. */ function cjkFriendlyStrong() { return cjkFriendlyStrongExtension; } // src/client/markdown/mathCompatibility.ts /** Extend upstream dollar-only math syntax with TeX delimiters while reusing its token vocabulary. */ const previousBackslash = function(code) { if (code !== codes.backslash) return true; const tail = this.events.at(-1); /* v8 ignore next -- a previous code necessarily has a preceding event. */ if (tail === void 0) return false; return tail[1].type === types.characterEscape; }; const tokenizeBackslashMathText = function(effects, ok, nok) { return start; function start(code) { /* v8 ignore next -- the text construct is dispatched only for a backslash. */ if (code !== codes.backslash) return nok(code); effects.enter("mathText"); effects.enter("mathTextSequence"); effects.consume(code); return open; } function open(code) { if (code !== codes.leftParenthesis) return nok(code); effects.consume(code); effects.exit("mathTextSequence"); return between; } function between(code) { if (code === codes.eof) return nok(code); if (code === codes.backslash) return effects.attempt({ partial: true, tokenize: tokenizeClose }, close, afterCloseAttempt)(code); if (markdownLineEnding(code)) { effects.enter(types.lineEnding); effects.consume(code); effects.exit(types.lineEnding); return between; } return dataStart(code); } function afterCloseAttempt(code) { return effects.check({ partial: true, tokenize: tokenizeOpen }, nok, dataStart)(code); } function dataStart(code) { effects.enter("mathTextData"); effects.consume(code); return code === codes.backslash ? afterDataBackslash : data; } function afterDataBackslash(code) { if (code === codes.backslash) { effects.consume(code); return data; } return data(code); } function data(code) { if (code === codes.eof || code === codes.backslash || markdownLineEnding(code)) { effects.exit("mathTextData"); return between(code); } effects.consume(code); return data; } function close(code) { effects.exit("mathText"); return ok(code); } function tokenizeClose(closeEffects, closeOk, closeNok) { return slash; function slash(code) { /* v8 ignore next -- this partial construct is attempted only at a backslash. */ if (code !== codes.backslash) return closeNok(code); closeEffects.enter("mathTextSequence"); closeEffects.consume(code); return parenthesis; } function parenthesis(code) { if (code !== codes.rightParenthesis) return closeNok(code); closeEffects.consume(code); closeEffects.exit("mathTextSequence"); return closeOk; } } function tokenizeOpen(openEffects, openOk, openNok) { return slash; function slash(code) { /* v8 ignore next -- the opening check follows a failed close attempt at a backslash. */ if (code !== codes.backslash) return openNok(code); openEffects.enter(types.chunkString); openEffects.consume(code); return parenthesis; } function parenthesis(code) { if (code !== codes.leftParenthesis) return openNok(code); openEffects.consume(code); openEffects.exit(types.chunkString); return openOk; } } }; function createMathFlow(marker, openMarker, closeMarker, multiline) { const tokenize = function(effects, ok, nok) { const self = this; let oddBackslashRun = false; const tail = self.events.at(-1); const initialSize = tail?.[1].type === types.linePrefix ? tail[2].sliceSerialize(tail[1], true).length : 0; return start; function start(code) { /* v8 ignore next -- the flow construct is dispatched only for its marker. */ if (code !== marker) return nok(code); effects.enter("mathFlow"); effects.enter("mathFlowFence"); effects.enter("mathFlowFenceSequence"); effects.consume(code); return open; } function open(code) { if (code !== openMarker) return nok(code); effects.consume(code); effects.exit("mathFlowFenceSequence"); effects.exit("mathFlowFence"); return marker === codes.dollarSign ? afterDollarOpen : content; } function afterDollarOpen(code) { return code === codes.dollarSign ? nok(code) : content(code); } function content(code) { if (code === codes.eof) return nok(code); if (code === marker && (marker !== codes.dollarSign || !oddBackslashRun)) return effects.attempt({ partial: true, tokenize: tokenizeClosingFence }, closed, afterClosingFenceAttempt)(code); if (markdownLineEnding(code)) return multiline ? effects.attempt(nonLazyContinuation, afterContinuation, nok)(code) : nok(code); return valueStart(code); } function afterClosingFenceAttempt(code) { return marker === codes.backslash ? effects.check({ partial: true, tokenize: tokenizeOpeningFence }, nok, markerValueStart)(code) : markerValueStart(code); } function afterContinuation(code) { return effects.attempt({ partial: true, tokenize: tokenizeClosingFence }, closed, initialSize ? factorySpace(effects, content, types.linePrefix, initialSize + 1) : content)(code); } function valueStart(code) { effects.enter("mathFlowValue"); oddBackslashRun = code === codes.backslash; effects.consume(code); return value; } function markerValueStart(code) { effects.enter("mathFlowValue"); oddBackslashRun = false; effects.consume(code); return valueAfterMarker; } function valueAfterMarker(code) { if (code === marker) { effects.consume(code); return value; } return value(code); } function value(code) { if (code === codes.eof || code === marker || markdownLineEnding(code)) { effects.exit("mathFlowValue"); return content(code); } oddBackslashRun = code === codes.backslash ? !oddBackslashRun : false; effects.consume(code); return value; } function closed(code) { effects.exit("mathFlow"); return ok(code); } function tokenizeClosingFence(closeEffects, closeOk, closeNok) { return factorySpace(closeEffects, sequenceStart, types.linePrefix, constants.tabSize); function sequenceStart(code) { if (code !== marker) return closeNok(code); closeEffects.enter("mathFlowFence"); closeEffects.enter("mathFlowFenceSequence"); closeEffects.consume(code); return sequenceEnd; } function sequenceEnd(code) { if (code !== closeMarker) return closeNok(code); closeEffects.consume(code); closeEffects.exit("mathFlowFenceSequence"); return factorySpace(closeEffects, after, types.whitespace); } function after(code) { if (code !== codes.eof && !markdownLineEnding(code)) return closeNok(code); closeEffects.exit("mathFlowFence"); return closeOk(code); } } function tokenizeOpeningFence(openEffects, openOk, openNok) { return sequenceStart; function sequenceStart(code) { /* v8 ignore next -- the opening check follows a failed close attempt at the marker. */ if (code !== marker) return openNok(code); openEffects.enter(types.chunkString); openEffects.consume(code); return sequenceEnd; } function sequenceEnd(code) { if (code !== openMarker) return openNok(code); openEffects.consume(code); openEffects.exit(types.chunkString); return openOk; } } }; return { concrete: true, name: marker === codes.dollarSign ? "sameLineDollarMathFlow" : "backslashMathFlow", tokenize }; } const tokenizeNonLazyContinuation = function(effects, ok, nok) { const self = this; return start; function start(code) { /* v8 ignore next -- continuation constructs are attempted only after a line ending. */ if (code === codes.eof) return ok(code); /* v8 ignore next -- continuation constructs are attempted only after a line ending. */ if (!markdownLineEnding(code)) return nok(code); effects.enter(types.lineEnding); effects.consume(code); effects.exit(types.lineEnding); return lineStart; } function lineStart(code) { return self.parser.lazy[self.now().line] ? nok(code) : ok(code); } }; const nonLazyContinuation = { partial: true, tokenize: tokenizeNonLazyContinuation }; const backslashMathText = { name: "backslashMathText", previous: previousBackslash, tokenize: tokenizeBackslashMathText }; const backslashMathFlow = createMathFlow(codes.backslash, codes.leftSquareBracket, codes.rightSquareBracket, true); const sameLineDollarMathFlow = createMathFlow(codes.dollarSign, codes.dollarSign, codes.dollarSign, false); const backslashMath = { flow: { [codes.backslash]: backslashMathFlow, [codes.dollarSign]: sameLineDollarMathFlow }, text: { [codes.backslash]: backslashMathText } }; /** * TeX backslash delimiters and same-line display-dollar blocks as a micromark * syntax extension reusing `micromark-extension-math`'s token vocabulary; the * caller must also register `math()` on the same parse so the emitted tokens * compile to standard math nodes. * @returns The micromark syntax extension. */ function mathCompatibility() { return backslashMath; } // src/client/markdown/parse.ts /** * Parse GFM markdown (the streaming arm's grammar: no math, so incomplete * TeX never flashes KaTeX errors mid-stream). * @param text - Markdown source. * @returns The mdast root. */ function parseGfm(text) { return fromMarkdown(text, { extensions: [gfm(), cjkFriendlyStrong()], mdastExtensions: [gfmFromMarkdown()] }); } /** * Parse GFM markdown plus TeX math with the compatibility delimiters * (the settled arm's grammar). * @param text - Markdown source. * @returns The mdast root. */ function parseGfmWithMath(text) { return fromMarkdown(text, { extensions: [ gfm(), cjkFriendlyStrong(), mathCompatibility(), math$1() ], mdastExtensions: [gfmFromMarkdown(), mathFromMarkdown()] }); } // node_modules/clsx/dist/clsx.mjs function r(e) { var t, f, n = ""; if ("string" == typeof e || "number" == typeof e) n += e; else if ("object" == typeof e) if (Array.isArray(e)) { var o = e.length; for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f); } else for (f in e) e[f] && (n && (n += " "), n += f); return n; } function clsx() { for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t); return n; } // node_modules/katex/dist/katex.mjs /** * This is the ParseError class, which is the main error thrown by KaTeX * functions when something has gone wrong. This is used to distinguish internal * errors from errors in the expression that the user provided. * * If possible, a caller should provide a Token or ParseNode with information * about where in the source string the problem occurred. */ var ParseError = class ParseError extends Error { constructor(message, token) { var error = "KaTeX parse error: " + message; var start; var end; var loc = token && token.loc; if (loc && loc.start <= loc.end) { var input = loc.lexer.input; start = loc.start; end = loc.end; if (start === input.length) error += " at end of input: "; else error += " at position " + (start + 1) + ": "; var underlined = input.slice(start, end).replace(/[^]/g, "$&̲"); var left; if (start > 15) left = "…" + input.slice(start - 15, start); else left = input.slice(0, start); var right; if (end + 15 < input.length) right = input.slice(end, end + 15) + "…"; else right = input.slice(end); error += left + underlined + right; } super(error); this.name = "ParseError"; this.position = void 0; this.length = void 0; this.rawMessage = void 0; Object.setPrototypeOf(this, ParseError.prototype); this.position = start; if (start != null && end != null) this.length = end - start; this.rawMessage = message; } }; /** * This file contains a list of utility functions which are useful in other * files. */ var uppercase = /([A-Z])/g; var hyphenate = (str) => str.replace(uppercase, "-$1").toLowerCase(); var ESCAPE_LOOKUP = { "&": "&", ">": ">", "<": "<", "\"": """, "'": "'" }; var ESCAPE_REGEX = /[&><"']/g; /** * Escapes text to prevent scripting attacks. */ var escape = (text) => String(text).replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]); /** * Sometimes we want to pull out the innermost element of a group. In most * cases, this will just be the group itself, but when ordgroups and colors have * a single element, we want to pull that out. */ var getBaseElem = (group) => { if (group.type === "ordgroup") { if (group.body.length === 1) return getBaseElem(group.body[0]); else return group; } else if (group.type === "color") { if (group.body.length === 1) return getBaseElem(group.body[0]); else return group; } else if (group.type === "font") return getBaseElem(group.body); else return group; }; var characterNodesTypes = /* @__PURE__ */ new Set([ "mathord", "textord", "atom" ]); /** * TeXbook algorithms often reference "character boxes", which are simply groups * with a single character in them. To decide if something is a character box, * we find its innermost group, and see if it is a single character. */ var isCharacterBox = (group) => characterNodesTypes.has(getBaseElem(group).type); /** * Return the protocol of a URL, or "_relative" if the URL does not specify a * protocol (and thus is relative), or `null` if URL has invalid protocol * (so should be outright rejected). */ var protocolFromUrl = (url) => { var protocol = /^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(url); if (!protocol) return "_relative"; if (protocol[2] !== ":") return null; if (!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(protocol[1])) return null; return protocol[1].toLowerCase(); }; var SETTINGS_SCHEMA = { displayMode: { type: "boolean", description: "Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.", cli: "-d, --display-mode" }, output: { type: { enum: [ "htmlAndMathml", "html", "mathml" ] }, description: "Determines the markup language of the output.", cli: "-F, --format <type>" }, leqno: { type: "boolean", description: "Render display math in leqno style (left-justified tags)." }, fleqn: { type: "boolean", description: "Render display math flush left." }, throwOnError: { type: "boolean", default: true, cli: "-t, --no-throw-on-error", cliDescription: "Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error." }, errorColor: { type: "string", default: "#cc0000", cli: "-c, --error-color <color>", cliDescription: "A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.", cliProcessor: (color) => "#" + color }, macros: { type: "object", cli: "-m, --macro <def>", cliDescription: "Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).", cliDefault: [], cliProcessor: (def, defs) => { defs.push(def); return defs; } }, minRuleThickness: { type: "number", description: "Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.", processor: (t) => Math.max(0, t), cli: "--min-rule-thickness <size>", cliProcessor: parseFloat }, colorIsTextColor: { type: "boolean", description: "Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.", cli: "-b, --color-is-text-color" }, strict: { type: [ { enum: [ "warn", "ignore", "error" ] }, "boolean", "function" ], description: "Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.", cli: "-S, --strict", cliDefault: false }, trust: { type: ["boolean", "function"], description: "Trust the input, enabling all HTML features such as \\url.", cli: "-T, --trust" }, maxSize: { type: "number", default: 1e400, description: "If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large", processor: (s) => Math.max(0, s), cli: "-s, --max-size <n>", cliProcessor: parseInt }, maxExpand: { type: "number", default: 1e3, description: "Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.", processor: (n) => Math.max(0, n), cli: "-e, --max-expand <n>", cliProcessor: (n) => n === "Infinity" ? 1e400 : parseInt(n) }, globalGroup: { type: "boolean", cli: false } }; function getImplicitDefault(type) { if (typeof type !== "string") return type.enum[0]; switch (type) { case "boolean": return false; case "string": return ""; case "number": return 0; case "object": return {}; default: throw new Error("Unexpected schema type; settings must declare an explicit default."); } } function getDefaultValue(schema) { if (Object.prototype.hasOwnProperty.call(schema, "default") && schema.default !== void 0) return schema.default; return getImplicitDefault(Array.isArray(schema.type) ? schema.type[0] : schema.type); } function applySetting(target, prop, options, schema) { var optionValue = Object.prototype.hasOwnProperty.call(options, prop) ? options[prop] : void 0; var processor = Object.prototype.hasOwnProperty.call(schema, "processor") ? schema.processor : void 0; target[prop] = optionValue !== void 0 ? processor ? processor(optionValue) : optionValue : getDefaultValue(schema); } /** * The main Settings object * * The current options stored are: * - displayMode: Whether the expression should be typeset as inline math * (false, the default), meaning that the math starts in * \textstyle and is placed in an inline-block); or as display * math (true), meaning that the math starts in \displaystyle * and is placed in a block with vertical margin. */ var Settings = class { constructor(options) { if (options === void 0) options = {}; this.displayMode = void 0; this.output = void 0; this.leqno = void 0; this.fleqn = void 0; this.throwOnError = void 0; this.errorColor = void 0; this.macros = void 0; this.minRuleThickness = void 0; this.colorIsTextColor = void 0; this.strict = void 0; this.trust = void 0; this.maxSize = void 0; this.maxExpand = void 0; this.globalGroup = void 0; options = options || {}; for (var prop of Object.keys(SETTINGS_SCHEMA)) { var schema = SETTINGS_SCHEMA[prop]; if (schema) applySetting(this, prop, options, schema); } } /** * Check whether to test potentially dangerous input, and return * `true` (trusted) or `false` (untrusted). The sole argument `context` * should be an object with `command` field specifying the relevant LaTeX * command (as a string starting with `\`), and any other arguments, etc. * If `context` has a `url` field, a `protocol` field will automatically * get added by this function (changing the specified object). */ isTrusted(context) { if ("url" in context && context.url && !context.protocol) { var protocol = protocolFromUrl(context.url); if (protocol == null) return false; context.protocol = protocol; } var trust = typeof this.trust === "function" ? this.trust(context) : this.trust; return Boolean(trust); } }; /** * This file contains information and classes for the various kinds of styles * used in TeX. It provides a generic `Style` class, which holds information * about a specific style. It then provides instances of all the different kinds * of styles possible, and provides functions to move between them and get * information about them. */ /** * The main style class. Contains a unique id for the style, a size (which is * the same for cramped and uncramped version of a style), and a cramped flag. */ var Style = class { constructor(id, size, cramped) { this.id = void 0; this.size = void 0; this.cramped = void 0; this.id = id; this.size = size; this.cramped = cramped; } /** * Get the style of a superscript given a base in the current style. */ sup() { return styles[sup[this.id]]; } /** * Get the style of a subscript given a base in the current style. */ sub() { return styles[sub[this.id]]; } /** * Get the style of a fraction numerator given the fraction in the current * style. */ fracNum() { return styles[fracNum[this.id]]; } /** * Get the style of a fraction denominator given the fraction in the current * style. */ fracDen() { return styles[fracDen[this.id]]; } /** * Get the cramped version of a style (in particular, cramping a cramped style * doesn't change the style). */ cramp() { return styles[cramp[this.id]]; } /** * Get a text or display version of this style. */ text() { return styles[text$1[this.id]]; } /** * Return true if this style is tightly spaced (scriptstyle/scriptscriptstyle) */ isTight() { return this.size >= 2; } }; var D = 0; var Dc = 1; var T = 2; var Tc = 3; var S = 4; var Sc = 5; var SS = 6; var SSc = 7; var styles = [ new Style(D, 0, false), new Style(Dc, 0, true), new Style(T, 1, false), new Style(Tc, 1, true), new Style(S, 2, false), new Style(Sc, 2, true), new Style(SS, 3, false), new Style(SSc, 3, true) ]; var sup = [ S, Sc, S, Sc, SS, SSc, SS, SSc ]; var sub = [ Sc, Sc, Sc, Sc, SSc, SSc, SSc, SSc ]; var fracNum = [ T, Tc, S, Sc, SS, SSc, SS, SSc ]; var fracDen = [ Tc, Tc, Sc, Sc, SSc, SSc, SSc, SSc ]; var cramp = [ Dc, Dc, Tc, Tc, Sc, Sc, SSc, SSc ]; var text$1 = [ D, Dc, T, Tc, T, Tc, T, Tc ]; var Style$1 = { DISPLAY: styles[D], TEXT: styles[T], SCRIPT: styles[S], SCRIPTSCRIPT: styles[SS] }; /** * Unicode block data for the families of scripts we support in \text{}. * Scripts only need to appear here if they do not have font metrics. */ var scriptData = [ { name: "latin", blocks: [[256, 591], [768, 879]] }, { name: "cyrillic", blocks: [[1024, 1279]] }, { name: "armenian", blocks: [[1328, 1423]] }, { name: "brahmic", blocks: [[2304, 4255]] }, { name: "georgian", blocks: [[4256, 4351]] }, { name: "cjk", blocks: [ [12288, 12543], [19968, 40879], [65280, 65376] ] }, { name: "hangul", blocks: [[44032, 55215]] } ]; /** * Given a codepoint, return the name of the script or script family * it is from, or null if it is not part of a known block */ function scriptFromCodepoint(codepoint) { for (var i = 0; i < scriptData.length; i++) { var script = scriptData[i]; for (var _i = 0; _i < script.blocks.length; _i++) { var block = script.blocks[_i]; if (codepoint >= block[0] && codepoint <= block[1]) return script.name; } } return null; } /** * A flattened version of all the supported blocks in a single array. * This is an optimization to make supportedCodepoint() fast. */ var allBlocks = []; scriptData.forEach((s) => s.blocks.forEach((b) => allBlocks.push(...b))); /** * Given a codepoint, return true if it falls within one of the * scripts or script families defined above and false otherwise. * * Micro benchmarks shows that this is faster than * /[\u3000-\u30FF\u4E00-\u9FAF\uFF00-\uFF60\uAC00-\uD7AF\u0900-\u109F]/.test() * in Firefox, Chrome and Node. */ function supportedCodepoint(codepoint) { for (var i = 0; i < allBlocks.length; i += 2) if (codepoint >= allBlocks[i] && codepoint <= allBlocks[i + 1]) return true; return false; } /** * This file provides support to domTree.js and delimiter.js. * It's a storehouse of path geometry for SVG images. */ var doubleBrushStroke = (svgPath) => svgPath + " " + svgPath; var hLinePad = 80; var sqrtMain = function sqrtMain(extraVinculum, hLinePad) { return "M95," + (622 + extraVinculum + hLinePad) + "\nc-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14\nc0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54\nc44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10\ns173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429\nc69,-144,104.5,-217.7,106.5,-221\nl" + extraVinculum / 2.075 + " -" + extraVinculum + "\nc5.3,-9.3,12,-14,20,-14\nH400000v" + (40 + extraVinculum) + "H845.2724\ns-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7\nc-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z\nM" + (834 + extraVinculum) + " " + hLinePad + "h400000v" + (40 + extraVinculum) + "h-400000z"; }; var sqrtSize1 = function sqrtSize1(extraVinculum, hLinePad) { return "M263," + (601 + extraVinculum + hLinePad) + "c0.7,0,18,39.7,52,119\nc34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120\nc340,-704.7,510.7,-1060.3,512,-1067\nl" + extraVinculum / 2.084 + " -" + extraVinculum + "\nc4.7,-7.3,11,-11,19,-11\nH40000v" + (40 + extraVinculum) + "H1012.3\ns-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232\nc-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1\ns-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26\nc-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z\nM" + (1001 + extraVinculum) + " " + hLinePad + "h400000v" + (40 + extraVinculum) + "h-400000z"; }; var sqrtSize2 = function sqrtSize2(extraVinculum, hLinePad) { return "M983 " + (10 + extraVinculum + hLinePad) + "\nl" + extraVinculum / 3.13 + " -" + extraVinculum + "\nc4,-6.7,10,-10,18,-10 H400000v" + (40 + extraVinculum) + "\nH1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7\ns-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744\nc-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30\nc26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722\nc56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5\nc53.7,-170.3,84.5,-266.8,92.5,-289.5z\nM" + (1001 + extraVinculum) + " " + hLinePad + "h400000v" + (40 + extraVinculum) + "h-400000z"; }; var sqrtSize3 = function sqrtSize3(extraVinculum, hLinePad) { return "M424," + (2398 + extraVinculum + hLinePad) + "\nc-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514\nc0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20\ns-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121\ns209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081\nl" + extraVinculum / 4.223 + " -" + extraVinculum + "c4,-6.7,10,-10,18,-10 H400000\nv" + (40 + extraVinculum) + "H1014.6\ns-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185\nc-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2z M" + (1001 + extraVinculum) + " " + hLinePad + "\nh400000v" + (40 + extraVinculum) + "h-400000z"; }; var sqrtSize4 = function sqrtSize4(extraVinculum, hLinePad) { return "M473," + (2713 + extraVinculum + hLinePad) + "\nc339.3,-1799.3,509.3,-2700,510,-2702 l" + extraVinculum / 5.298 + " -" + extraVinculum + "\nc3.3,-7.3,9.3,-11,18,-11 H400000v" + (40 + extraVinculum) + "H1017.7\ns-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200\nc0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26\ns76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,\n606zM" + (1001 + extraVinculum) + " " + hLinePad + "h400000v" + (40 + extraVinculum) + "H1017.7z"; }; var phasePath = function phasePath(y) { var x = y / 2; return "M400000 " + y + " H0 L" + x + " 0 l65 45 L145 " + (y - 80) + " H400000z"; }; var sqrtTall = function sqrtTall(extraVinculum, hLinePad, viewBoxHeight) { var vertSegment = viewBoxHeight - 54 - hLinePad - extraVinculum; return "M702 " + (extraVinculum + hLinePad) + "H400000" + (40 + extraVinculum) + "\nH742v" + vertSegment + "l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1\nh-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170\nc-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667\n219 661 l218 661zM702 " + hLinePad + "H400000v" + (40 + extraVinculum) + "H742z"; }; var sqrtPath = function sqrtPath(size, extraVinculum, viewBoxHeight) { extraVinculum = 1e3 * extraVinculum; var path = ""; switch (size) { case "sqrtMain": path = sqrtMain(extraVinculum, hLinePad); break; case "sqrtSize1": path = sqrtSize1(extraVinculum, hLinePad); break; case "sqrtSize2": path = sqrtSize2(extraVinculum, hLinePad); break; case "sqrtSize3": path = sqrtSize3(extraVinculum, hLinePad); break; case "sqrtSize4": path = sqrtSize4(extraVinculum, hLinePad); break; case "sqrtTall": path = sqrtTall(extraVinculum, hLinePad, viewBoxHeight); } return path; }; var innerPath = function innerPath(name, height) { switch (name) { case "⎜": return doubleBrushStroke("M291 0 H417 V" + height + " H291z"); case "∣": return doubleBrushStroke("M145 0 H188 V" + height + " H145z"); case "∥": return doubleBrushStroke("M145 0 H188 V" + height + " H145z") + doubleBrushStroke("M367 0 H410 V" + height + " H367z"); case "⎟": return doubleBrushStroke("M457 0 H583 V" + height + " H457z"); case "⎢": return doubleBrushStroke("M319 0 H403 V" + height + " H319z"); case "⎥": return doubleBrushStroke("M263 0 H347 V" + height + " H263z"); case "⎪": return doubleBrushStroke("M384 0 H504 V" + height + " H384z"); case "⏐": return doubleBrushStroke("M312 0 H355 V" + height + " H312z"); case "‖": return doubleBrushStroke("M257 0 H300 V" + height + " H257z") + doubleBrushStroke("M478 0 H521 V" + height + " H478z"); default: return ""; } }; var path = { doubleleftarrow: "M262 157\nl10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3\n 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28\n 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5\nc2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5\n 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87\n-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7\n-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z\nm8 0v40h399730v-40zm0 194v40h399730v-40z", doublerightarrow: "M399738 392l\n-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5\n 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88\n-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68\n-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18\n-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782\nc-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3\n-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z", leftarrow: "M400000 241H110l3-3c68.7-52.7 113.7-120\n 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8\n-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247\nc-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208\n 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3\n 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202\n l-3-3h399890zM100 241v40h399900v-40z", leftbrace: "M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117\n-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7\n 5-6 9-10 13-.7 1-7.3 1-20 1H6z", leftbraceunder: "M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13\n 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688\n 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7\n-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z", leftgroup: "M400000 80\nH435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0\n 435 0h399565z", leftgroupunder: "M400000 262\nH435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219\n 435 219h399565z", leftharpoon: "M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3\n-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5\n-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7\n-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z", leftharpoonplus: "M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5\n 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3\n-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7\n-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z\nm0 0v40h400000v-40z", leftharpoondown: "M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333\n 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5\n 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667\n-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z", leftharpoondownplus: "M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12\n 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7\n-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0\nv40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z", lefthook: "M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5\n-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3\n-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21\n 71.5 23h399859zM103 281v-40h399897v40z", leftlinesegment: doubleBrushStroke("M40 281 V428 H0 V94 H40 V241 H400000 v40z"), leftbracketunder: doubleBrushStroke("M0 0 h120 V290 H399995 v120 H0z"), leftbracketover: doubleBrushStroke("M0 440 h120 V150 H399995 v-120 H0z"), leftmapsto: doubleBrushStroke("M40 281 V448H0V74H40V241H400000v40z"), leftToFrom: "M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23\n-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8\nc28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3\n 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z", longequal: doubleBrushStroke("M0 50 h400000 v40H0z m0 194h40000v40H0z"), midbrace: "M200428 334\nc-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14\n-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7\n 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11\n 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z", midbraceunder: "M199572 214\nc100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14\n 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3\n 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0\n-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z", oiintSize1: "M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6\n-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z\nm368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8\n60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z", oiintSize2: "M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8\n-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z\nm502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2\nc0 110 84 276 504 276s502.4-166 502.4-276z", oiiintSize1: "M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6\n-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z\nm525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0\n85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z", oiiintSize2: "M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8\n-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z\nm770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1\nc0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z", rightarrow: "M0 241v40h399891c-47.3 35.3-84 78-110 128\n-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20\n 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7\n 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85\n-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n 151.7 139 205zm0 0v40h399900v-40z", rightbrace: "M400000 542l\n-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5\ns-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1\nc124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z", rightbraceunder: "M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3\n 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237\n-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z", rightgroup: "M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0\n 3-1 3-3v-38c-76-158-257-219-435-219H0z", rightgroupunder: "M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18\n 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z", rightharpoon: "M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3\n-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2\n-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58\n 69.2 92 94.5zm0 0v40h399900v-40z", rightharpoonplus: "M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11\n-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7\n 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z\nm0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z", rightharpoondown: "M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8\n 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5\n-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95\n-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z", rightharpoondownplus: "M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8\n 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3\n 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3\n-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z\nm0-194v40h400000v-40zm0 0v40h400000v-40z", righthook: "M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3\n 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0\n-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21\n 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z", rightlinesegment: doubleBrushStroke("M399960 241 V94 h40 V428 h-40 V281 H0 v-40z"), rightbracketunder: doubleBrushStroke("M399995 0 h-120 V290 H0 v120 H400000z"), rightbracketover: doubleBrushStroke("M399995 440 h-120 V150 H0 v-120 H399995z"), rightToFrom: "M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23\n 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32\n-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142\n-167z M100 147v40h399900v-40zM0 341v40h399900v-40z", twoheadleftarrow: "M0 167c68 40\n 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69\n-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3\n-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19\n-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101\n 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z", twoheadrightarrow: "M400000 167\nc-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3\n 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42\n 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333\n-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70\n 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z", tilde1: "M200 55.538c-77 0-168 73.953-177 73.953-3 0-7\n-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0\n 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0\n 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128\n-68.267.847-113-73.952-191-73.952z", tilde2: "M344 55.266c-142 0-300.638 81.316-311.5 86.418\n-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9\n 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114\nc1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751\n 181.476 676 181.476c-149 0-189-126.21-332-126.21z", tilde3: "M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457\n-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0\n 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697\n 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696\n -338 0-409-156.573-744-156.573z", tilde4: "M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345\n-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409\n 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9\n 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409\n -175.236-744-175.236z", vec: "M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5\n3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11\n10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63\n-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1\n-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59\nH213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359\nc-16-25.333-24-45-24-59z", widehat1: "M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22\nc-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z", widehat2: "M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z", widehat3: "M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z", widehat4: "M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z", widecheck1: "M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,\n-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z", widecheck2: "M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z", widecheck3: "M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z", widecheck4: "M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z", baraboveleftarrow: "M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202\nc4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5\nc-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130\ns-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47\n121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6\ns2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11\nc0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z\nM100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z", rightarrowabovebar: "M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32\n-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0\n13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39\n-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5\n-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z", baraboveshortleftharpoon: "M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17\nc2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21\nc-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40\nc-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z\nM0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z", rightharpoonaboveshortbar: "M0,241 l0,40c399126,0,399993,0,399993,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z", shortbaraboveleftharpoon: "M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,\n1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,\n-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z\nM93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z", shortrightharpoonabovebar: "M53,241l0,40c398570,0,399437,0,399437,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z" }; var tallDelim = function tallDelim(label, midHeight) { switch (label) { case "lbrack": return "M403 1759 V84 H666 V0 H319 V1759 v" + midHeight + " v1759 v84 h347 v-84\nH403z M403 1759 V0 H319 V1759 v" + midHeight + " v1759 v84 h84z"; case "rbrack": return "M347 1759 V0 H0 V84 H263 V1759 v" + midHeight + " v1759 H0 v84 H347z\nM347 1759 V0 H263 V1759 v" + midHeight + " v1759 h84z"; case "vert": return "M145 15 v585 v" + midHeight + " v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v" + -midHeight + " v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v" + midHeight + " v585 h43z"; case "doublevert": return "M145 15 v585 v" + midHeight + " v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v" + -midHeight + " v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v" + midHeight + " v585 h43z\nM367 15 v585 v" + midHeight + " v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v" + -midHeight + " v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M410 15 H367 v585 v" + midHeight + " v585 h43z"; case "lfloor": return "M319 602 V0 H403 V602 v" + midHeight + " v1715 h263 v84 H319z\nMM319 602 V0 H403 V602 v" + midHeight + " v1715 H319z"; case "rfloor": return "M319 602 V0 H403 V602 v" + midHeight + " v1799 H0 v-84 H319z\nMM319 602 V0 H403 V602 v" + midHeight + " v1715 H319z"; case "lceil": return "M403 1759 V84 H666 V0 H319 V1759 v" + midHeight + " v602 h84z\nM403 1759 V0 H319 V1759 v" + midHeight + " v602 h84z"; case "rceil": return "M347 1759 V0 H0 V84 H263 V1759 v" + midHeight + " v602 h84z\nM347 1759 V0 h-84 V1759 v" + midHeight + " v602 h84z"; case "lparen": return "M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1\nc-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349,\n-36,557 l0," + (midHeight + 84) + "c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210,\n949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9\nc0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5,\n-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189\nl0,-" + (midHeight + 92) + "c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3,\n-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z"; case "rparen": return "M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3,\n63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5\nc11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0," + (midHeight + 9) + "\nc-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664\nc-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11\nc0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17\nc242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558\nl0,-" + (midHeight + 144) + "c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,\n-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z"; default: throw new Error("Unknown stretchy delimiter."); } }; function isMathDomNode(node) { return "toText" in node; } /** * This node represents a document fragment, which contains elements, but when * placed into the DOM doesn't have any representation itself. It only contains * children and doesn't have any DOM node properties. */ var DocumentFragment = class { constructor(children) { this.children = void 0; this.classes = void 0; this.height = void 0; this.depth = void 0; this.maxFontSize = void 0; this.style = void 0; this.children = children; this.classes = []; this.height = 0; this.depth = 0; this.maxFontSize = 0; this.style = {}; } hasClass(className) { return this.classes.includes(className); } /** Convert the fragment into a node. */ toNode() { var frag = document.createDocumentFragment(); for (var i = 0; i < this.children.length; i++) frag.appendChild(this.children[i].toNode()); return frag; } /** Convert the fragment into HTML markup. */ toMarkup() { var markup = ""; for (var i = 0; i < this.children.length; i++) markup += this.children[i].toMarkup(); return markup; } /** * Converts the math node into a string, similar to innerText. Applies to * MathDomNode's only. */ toText() { return this.children.map((child) => { if (isMathDomNode(child)) return child.toText(); throw new Error("Expected MathDomNode with toText, got " + child.constructor.name); }).join(""); } }; /** * This file does conversion between units. In particular, it provides * calculateSize to convert other units into ems. */ var ptPerUnit = { "pt": 1, "mm": 7227 / 2540, "cm": 7227 / 254, "in": 72.27, "bp": 803 / 800, "pc": 12, "dd": 1238 / 1157, "cc": 14856 / 1157, "nd": 685 / 642, "nc": 1370 / 107, "sp": 1 / 65536, "px": 803 / 800 }; var relativeUnit = { "ex": true, "em": true, "mu": true }; /** * Determine whether the specified unit (either a string defining the unit * or a "size" parse node containing a unit field) is valid. */ var validUnit = function validUnit(unit) { if (typeof unit !== "string") unit = unit.unit; return unit in ptPerUnit || unit in relativeUnit || unit === "ex"; }; var calculateSize = function calculateSize(sizeValue, options) { var scale; if (sizeValue.unit in ptPerUnit) scale = ptPerUnit[sizeValue.unit] / options.fontMetrics().ptPerEm / options.sizeMultiplier; else if (sizeValue.unit === "mu") scale = options.fontMetrics().cssEmPerMu; else { var unitOptions; if (options.style.isTight()) unitOptions = options.havingStyle(options.style.text()); else unitOptions = options; if (sizeValue.unit === "ex") scale = unitOptions.fontMetrics().xHeight; else if (sizeValue.unit === "em") scale = unitOptions.fontMetrics().quad; else throw new ParseError("Invalid unit: '" + sizeValue.unit + "'"); if (unitOptions !== options) scale *= unitOptions.sizeMultiplier / options.sizeMultiplier; } return Math.min(sizeValue.number * scale, options.maxSize); }; /** * Round `n` to 4 decimal places, or to the nearest 1/10,000th em. See * https://github.com/KaTeX/KaTeX/pull/2460. */ var makeEm = function makeEm(n) { return +n.toFixed(4) + "em"; }; /** * These objects store the data about the DOM nodes we create, as well as some * extra data. They can then be transformed into real DOM nodes with the * `toNode` function or HTML markup using `toMarkup`. They are useful for both * storing extra properties on the nodes, as well as providing a way to easily * work with the DOM. * * Similar functions for working with MathML nodes exist in mathMLTree.js. * * TODO: refactor `span` and `anchor` into common superclass when * target environments support class inheritance */ /** * Create an HTML className based on a list of classes. In addition to joining * with spaces, we also remove empty classes. */ var createClass = function createClass(classes) { return classes.filter((cls) => cls).join(" "); }; /** * Serialize a CssStyle object into a semicolon-delimited inline-style string * (hyphenating camelCase property names). Returns "" when no property is set. */ var cssStyleToString = function cssStyleToString(style) { var styles = ""; for (var key of Object.keys(style)) { var value = style[key]; if (value !== void 0) styles += hyphenate(key) + ":" + value + ";"; } return styles; }; var initNode = function initNode(classes, options, style) { this.classes = classes || []; this.attributes = {}; this.height = 0; this.depth = 0; this.maxFontSize = 0; this.style = style || {}; if (options) { if (options.style.isTight()) this.classes.push("mtight"); var color = options.getColor(); if (color) this.style.color = color; } }; /** * Convert into an HTML node */ var toNode = function toNode(tagName) { var node = document.createElement(tagName); node.className = createClass(this.classes); Object.assign(node.style, this.style); for (var attr of Object.keys(this.attributes)) node.setAttribute(attr, this.attributes[attr]); for (var i = 0; i < this.children.length; i++) node.appendChild(this.children[i].toNode()); return node; }; /** * https://w3c.github.io/html-reference/syntax.html#syntax-attributes * * > Attribute Names must consist of one or more characters * other than the space characters, U+0000 NULL, * '"', "'", ">", "/", "=", the control characters, * and any characters that are not defined by Unicode. */ var invalidAttributeNameRegex = /[\s"'>/=\x00-\x1f]/; /** * Convert into an HTML markup string */ var toMarkup = function toMarkup(tagName) { var markup = "<" + tagName; if (this.classes.length) markup += " class=\"" + escape(createClass(this.classes)) + "\""; var styles = cssStyleToString(this.style); if (styles) markup += " style=\"" + escape(styles) + "\""; for (var attr of Object.keys(this.attributes)) { if (invalidAttributeNameRegex.test(attr)) throw new ParseError("Invalid attribute name '" + attr + "'"); markup += " " + attr + "=\"" + escape(this.attributes[attr]) + "\""; } markup += ">"; for (var i = 0; i < this.children.length; i++) markup += this.children[i].toMarkup(); markup += "</" + tagName + ">"; return markup; }; /** * This node represents a span node, with a className, a list of children, and * an inline style. It also contains information about its height, depth, and * maxFontSize. * * Represents two types with different uses: SvgSpan to wrap an SVG and DomSpan * otherwise. This typesafety is important when HTML builders access a span's * children. */ var Span = class { constructor(classes, children, options, style) { this.children = void 0; this.attributes = void 0; this.classes = void 0; this.height = void 0; this.depth = void 0; this.width = void 0; this.maxFontSize = void 0; this.style = void 0; /** * Italic correction carried over from a SymbolNode when the symbol is * wrapped in a vlist (e.g. \oiint / \oiiint). Read by supsub to adjust * subscript positioning. Only set when nonzero; use `?? 0` at read sites. */ this.italic = void 0; initNode.call(this, classes, options, style); this.children = children || []; } /** * Sets an arbitrary attribute on the span. Warning: use this wisely. Not * all browsers support attributes the same, and having too many custom * attributes is probably bad. */ setAttribute(attribute, value) { this.attributes[attribute] = value; } hasClass(className) { return this.classes.includes(className); } toNode() { return toNode.call(this, "span"); } toMarkup() { return toMarkup.call(this, "span"); } }; /** * This node represents an anchor (<a>) element with a hyperlink. See `span` * for further details. */ var Anchor = class { constructor(href, classes, children, options) { this.children = void 0; this.attributes = void 0; this.classes = void 0; this.height = void 0; this.depth = void 0; this.maxFontSize = void 0; this.style = void 0; initNode.call(this, classes, options); this.children = children || []; this.setAttribute("href", href); } setAttribute(attribute, value) { this.attributes[attribute] = value; } hasClass(className) { return this.classes.includes(className); } toNode() { return toNode.call(this, "a"); } toMarkup() { return toMarkup.call(this, "a"); } }; /** * This node represents an image embed (<img>) element. */ var Img = class { constructor(src, alt, style) { this.src = void 0; this.alt = void 0; this.classes = void 0; this.height = void 0; this.depth = void 0; this.maxFontSize = void 0; this.style = void 0; this.alt = alt; this.src = src; this.classes = ["mord"]; this.height = 0; this.depth = 0; this.maxFontSize = 0; this.style = style; } hasClass(className) { return this.classes.includes(className); } toNode() { var node = document.createElement("img"); node.src = this.src; node.alt = this.alt; node.className = "mord"; Object.assign(node.style, this.style); return node; } toMarkup() { var markup = "<img src=\"" + escape(this.src) + "\"" + (" alt=\"" + escape(this.alt) + "\""); var styles = cssStyleToString(this.style); if (styles) markup += " style=\"" + escape(styles) + "\""; markup += "'/>"; return markup; } }; var iCombinations = { "î": "ı̂", "ï": "ı̈", "í": "ı́", "ì": "ı̀" }; /** * A symbol node contains information about a single symbol. It either renders * to a single text node, or a span with a single text node in it, depending on * whether it has CSS classes, styles, or needs italic correction. */ var SymbolNode = class { constructor(text, height, depth, italic, skew, width, classes, style) { this.text = void 0; this.height = void 0; this.depth = void 0; this.italic = void 0; this.skew = void 0; this.width = void 0; this.maxFontSize = void 0; this.classes = void 0; this.style = void 0; this.text = text; this.height = height || 0; this.depth = depth || 0; this.italic = italic || 0; this.skew = skew || 0; this.width = width || 0; this.classes = classes || []; this.style = style || {}; this.maxFontSize = 0; var script = scriptFromCodepoint(this.text.charCodeAt(0)); if (script) this.classes.push(script + "_fallback"); if (/[îïíì]/.test(this.text)) this.text = iCombinations[this.text]; } hasClass(className) { return this.classes.includes(className); } /** * Creates a text node or span from a symbol node. Note that a span is only * created if it is needed. */ toNode() { var node = document.createTextNode(this.text); var span = null; if (this.italic > 0) { span = document.createElement("span"); span.style.marginRight = makeEm(this.italic); } if (this.classes.length > 0) { span = span || document.createElement("span"); span.className = createClass(this.classes); } if (Object.keys(this.style).length > 0) { span = span || document.createElement("span"); Object.assign(span.style, this.style); } if (span) { span.appendChild(node); return span; } else return node; } /** * Creates markup for a symbol node. */ toMarkup() { var needsSpan = false; var markup = "<span"; if (this.classes.length) { needsSpan = true; markup += " class=\""; markup += escape(createClass(this.classes)); markup += "\""; } var styles = ""; if (this.italic > 0) styles += "margin-right:" + makeEm(this.italic) + ";"; styles += cssStyleToString(this.style); if (styles) { needsSpan = true; markup += " style=\"" + escape(styles) + "\""; } var escaped = escape(this.text); if (needsSpan) { markup += ">"; markup += escaped; markup += "</span>"; return markup; } else return escaped; } }; /** * SVG nodes are used to render stretchy wide elements. */ var SvgNode = class { constructor(children, attributes) { this.children = void 0; this.attributes = void 0; this.children = children || []; this.attributes = attributes || {}; } toNode() { var node = document.createElementNS("http://www.w3.org/2000/svg", "svg"); for (var attr of Object.keys(this.attributes)) node.setAttribute(attr, this.attributes[attr]); for (var i = 0; i < this.children.length; i++) node.appendChild(this.children[i].toNode()); return node; } toMarkup() { var markup = "<svg xmlns=\"http://www.w3.org/2000/svg\""; for (var attr of Object.keys(this.attributes)) markup += " " + attr + "=\"" + escape(this.attributes[attr]) + "\""; markup += ">"; for (var i = 0; i < this.children.length; i++) markup += this.children[i].toMarkup(); markup += "</svg>"; return markup; } }; var PathNode = class { constructor(pathName, alternate) { this.pathName = void 0; this.alternate = void 0; this.pathName = pathName; this.alternate = alternate; } toNode() { var node = document.createElementNS("http://www.w3.org/2000/svg", "path"); if (this.alternate) node.setAttribute("d", this.alternate); else node.setAttribute("d", path[this.pathName]); return node; } toMarkup() { if (this.alternate) return "<path d=\"" + escape(this.alternate) + "\"/>"; else return "<path d=\"" + escape(path[this.pathName]) + "\"/>"; } }; var LineNode = class { constructor(attributes) { this.attributes = void 0; this.attributes = attributes || {}; } toNode() { var node = document.createElementNS("http://www.w3.org/2000/svg", "line"); for (var attr of Object.keys(this.attributes)) node.setAttribute(attr, this.attributes[attr]); return node; } toMarkup() { var markup = "<line"; for (var attr of Object.keys(this.attributes)) markup += " " + attr + "=\"" + escape(this.attributes[attr]) + "\""; markup += "/>"; return markup; } }; function assertSymbolDomNode(group) { if (group instanceof SymbolNode) return group; else throw new Error("Expected symbolNode but got " + String(group) + "."); } function assertSpan(group) { if (group instanceof Span) return group; else throw new Error("Expected span<HtmlDomNode> but got " + String(group) + "."); } /** * Whether an HtmlDomNode has HtmlDomNode children. * HtmlDomNode is a base type representing a union of * SymbolNode, SvgSpan, DomSpan, Anchor, and documentFragment. * In the last three cases, the children are HtmlDomNode[]. */ var hasHtmlDomChildren = (node) => node instanceof Span || node instanceof Anchor || node instanceof DocumentFragment; var fontMetricsData = { "AMS-Regular": { "32": [ 0, 0, 0, 0, .25 ], "65": [ 0, .68889, 0, 0, .72222 ], "66": [ 0, .68889, 0, 0, .66667 ], "67": [ 0, .68889, 0, 0, .72222 ], "68": [ 0, .68889, 0, 0, .72222 ], "69": [ 0, .68889, 0, 0, .66667 ], "70": [ 0, .68889, 0, 0, .61111 ], "71": [ 0, .68889, 0, 0, .77778 ], "72": [ 0, .68889, 0, 0, .77778 ], "73": [ 0, .68889, 0, 0, .38889 ], "74": [ .16667, .68889, 0, 0, .5 ], "75": [ 0, .68889, 0, 0, .77778 ], "76": [ 0, .68889, 0, 0, .66667 ], "77": [ 0, .68889, 0, 0, .94445 ], "78": [ 0, .68889, 0, 0, .72222 ], "79": [ .16667, .68889, 0, 0, .77778 ], "80": [ 0, .68889, 0, 0, .61111 ], "81": [ .16667, .68889, 0, 0, .77778 ], "82": [ 0, .68889, 0, 0, .72222 ], "83": [ 0, .68889, 0, 0, .55556 ], "84": [ 0, .68889, 0, 0, .66667 ], "85": [ 0, .68889, 0, 0, .72222 ], "86": [ 0, .68889, 0, 0, .72222 ], "87": [ 0, .68889, 0, 0, 1 ], "88": [ 0, .68889, 0, 0, .72222 ], "89": [ 0, .68889, 0, 0, .72222 ], "90": [ 0, .68889, 0, 0, .66667 ], "107": [ 0, .68889, 0, 0, .55556 ], "160": [ 0, 0, 0, 0, .25 ], "165": [ 0, .675, .025, 0, .75 ], "174": [ .15559, .69224, 0, 0, .94666 ], "240": [ 0, .68889, 0, 0, .55556 ], "295": [ 0, .68889, 0, 0, .54028 ], "710": [ 0, .825, 0, 0, 2.33334 ], "732": [ 0, .9, 0, 0, 2.33334 ], "770": [ 0, .825, 0, 0, 2.33334 ], "771": [ 0, .9, 0, 0, 2.33334 ], "989": [ .08167, .58167, 0, 0, .77778 ], "1008": [ 0, .43056, .04028, 0, .66667 ], "8245": [ 0, .54986, 0, 0, .275 ], "8463": [ 0, .68889, 0, 0, .54028 ], "8487": [ 0, .68889, 0, 0, .72222 ], "8498": [ 0, .68889, 0, 0, .55556 ], "8502": [ 0, .68889, 0, 0, .66667 ], "8503": [ 0, .68889, 0, 0, .44445 ], "8504": [ 0, .68889, 0, 0, .66667 ], "8513": [ 0, .68889, 0, 0, .63889 ], "8592": [ -.03598, .46402, 0, 0, .5 ], "8594": [ -.03598, .46402, 0, 0, .5 ], "8602": [ -.13313, .36687, 0, 0, 1 ], "8603": [ -.13313, .36687, 0, 0, 1 ], "8606": [ .01354, .52239, 0, 0, 1 ], "8608": [ .01354, .52239, 0, 0, 1 ], "8610": [ .01354, .52239, 0, 0, 1.11111 ], "8611": [ .01354, .52239, 0, 0, 1.11111 ], "8619": [ 0, .54986, 0, 0, 1 ], "8620": [ 0, .54986, 0, 0, 1 ], "8621": [ -.13313, .37788, 0, 0, 1.38889 ], "8622": [ -.13313, .36687, 0, 0, 1 ], "8624": [ 0, .69224, 0, 0, .5 ], "8625": [ 0, .69224, 0, 0, .5 ], "8630": [ 0, .43056, 0, 0, 1 ], "8631": [ 0, .43056, 0, 0, 1 ], "8634": [ .08198, .58198, 0, 0, .77778 ], "8635": [ .08198, .58198, 0, 0, .77778 ], "8638": [ .19444, .69224, 0, 0, .41667 ], "8639": [ .19444, .69224, 0, 0, .41667 ], "8642": [ .19444, .69224, 0, 0, .41667 ], "8643": [ .19444, .69224, 0, 0, .41667 ], "8644": [ .1808, .675, 0, 0, 1 ], "8646": [ .1808, .675, 0, 0, 1 ], "8647": [ .1808, .675, 0, 0, 1 ], "8648": [ .19444, .69224, 0, 0, .83334 ], "8649": [ .1808, .675, 0, 0, 1 ], "8650": [ .19444, .69224, 0, 0, .83334 ], "8651": [ .01354, .52239, 0, 0, 1 ], "8652": [ .01354, .52239, 0, 0, 1 ], "8653": [ -.13313, .36687, 0, 0, 1 ], "8654": [ -.13313, .36687, 0, 0, 1 ], "8655": [ -.13313, .36687, 0, 0, 1 ], "8666": [ .13667, .63667, 0, 0, 1 ], "8667": [ .13667, .63667, 0, 0, 1 ], "8669": [ -.13313, .37788, 0, 0, 1 ], "8672": [ -.064, .437, 0, 0, 1.334 ], "8674": [ -.064, .437, 0, 0, 1.334 ], "8705": [ 0, .825, 0, 0, .5 ], "8708": [ 0, .68889, 0, 0, .55556 ], "8709": [ .08167, .58167, 0, 0, .77778 ], "8717": [ 0, .43056, 0, 0, .42917 ], "8722": [ -.03598, .46402, 0, 0, .5 ], "8724": [ .08198, .69224, 0, 0, .77778 ], "8726": [ .08167, .58167, 0, 0, .77778 ], "8733": [ 0, .69224, 0, 0, .77778 ], "8736": [ 0, .69224, 0, 0, .72222 ], "8737": [ 0, .69224, 0, 0, .72222 ], "8738": [ .03517, .52239, 0, 0, .72222 ], "8739": [ .08167, .58167, 0, 0, .22222 ], "8740": [ .25142, .74111, 0, 0, .27778 ], "8741": [ .08167, .58167, 0, 0, .38889 ], "8742": [ .25142, .74111, 0, 0, .5 ], "8756": [ 0, .69224, 0, 0, .66667 ], "8757": [ 0, .69224, 0, 0, .66667 ], "8764": [ -.13313, .36687, 0, 0, .77778 ], "8765": [ -.13313, .37788, 0, 0, .77778 ], "8769": [ -.13313, .36687, 0, 0, .77778 ], "8770": [ -.03625, .46375, 0, 0, .77778 ], "8774": [ .30274, .79383, 0, 0, .77778 ], "8776": [ -.01688, .48312, 0, 0, .77778 ], "8778": [ .08167, .58167, 0, 0, .77778 ], "8782": [ .06062, .54986, 0, 0, .77778 ], "8783": [ .06062, .54986, 0, 0, .77778 ], "8785": [ .08198, .58198, 0, 0, .77778 ], "8786": [ .08198, .58198, 0, 0, .77778 ], "8787": [ .08198, .58198, 0, 0, .77778 ], "8790": [ 0, .69224, 0, 0, .77778 ], "8791": [ .22958, .72958, 0, 0, .77778 ], "8796": [ .08198, .91667, 0, 0, .77778 ], "8806": [ .25583, .75583, 0, 0, .77778 ], "8807": [ .25583, .75583, 0, 0, .77778 ], "8808": [ .25142, .75726, 0, 0, .77778 ], "8809": [ .25142, .75726, 0, 0, .77778 ], "8812": [ .25583, .75583, 0, 0, .5 ], "8814": [ .20576, .70576, 0, 0, .77778 ], "8815": [ .20576, .70576, 0, 0, .77778 ], "8816": [ .30274, .79383, 0, 0, .77778 ], "8817": [ .30274, .79383, 0, 0, .77778 ], "8818": [ .22958, .72958, 0, 0, .77778 ], "8819": [ .22958, .72958, 0, 0, .77778 ], "8822": [ .1808, .675, 0, 0, .77778 ], "8823": [ .1808, .675, 0, 0, .77778 ], "8828": [ .13667, .63667, 0, 0, .77778 ], "8829": [ .13667, .63667, 0, 0, .77778 ], "8830": [ .22958, .72958, 0, 0, .77778 ], "8831": [ .22958, .72958, 0, 0, .77778 ], "8832": [ .20576, .70576, 0, 0, .77778 ], "8833": [ .20576, .70576, 0, 0, .77778 ], "8840": [ .30274, .79383, 0, 0, .77778 ], "8841": [ .30274, .79383, 0, 0, .77778 ], "8842": [ .13597, .63597, 0, 0, .77778 ], "8843": [ .13597, .63597, 0, 0, .77778 ], "8847": [ .03517, .54986, 0, 0, .77778 ], "8848": [ .03517, .54986, 0, 0, .77778 ], "8858": [ .08198, .58198, 0, 0, .77778 ], "8859": [ .08198, .58198, 0, 0, .77778 ], "8861": [ .08198, .58198, 0, 0, .77778 ], "8862": [ 0, .675, 0, 0, .77778 ], "8863": [ 0, .675, 0, 0, .77778 ], "8864": [ 0, .675, 0, 0, .77778 ], "8865": [ 0, .675, 0, 0, .77778 ], "8872": [ 0, .69224, 0, 0, .61111 ], "8873": [ 0, .69224, 0, 0, .72222 ], "8874": [ 0, .69224, 0, 0, .88889 ], "8876": [ 0, .68889, 0, 0, .61111 ], "8877": [ 0, .68889, 0, 0, .61111 ], "8878": [ 0, .68889, 0, 0, .72222 ], "8879": [ 0, .68889, 0, 0, .72222 ], "8882": [ .03517, .54986, 0, 0, .77778 ], "8883": [ .03517, .54986, 0, 0, .77778 ], "8884": [ .13667, .63667, 0, 0, .77778 ], "8885": [ .13667, .63667, 0, 0, .77778 ], "8888": [ 0, .54986, 0, 0, 1.11111 ], "8890": [ .19444, .43056, 0, 0, .55556 ], "8891": [ .19444, .69224, 0, 0, .61111 ], "8892": [ .19444, .69224, 0, 0, .61111 ], "8901": [ 0, .54986, 0, 0, .27778 ], "8903": [ .08167, .58167, 0, 0, .77778 ], "8905": [ .08167, .58167, 0, 0, .77778 ], "8906": [ .08167, .58167, 0, 0, .77778 ], "8907": [ 0, .69224, 0, 0, .77778 ], "8908": [ 0, .69224, 0, 0, .77778 ], "8909": [ -.03598, .46402, 0, 0, .77778 ], "8910": [ 0, .54986, 0, 0, .76042 ], "8911": [ 0, .54986, 0, 0, .76042 ], "8912": [ .03517, .54986, 0, 0, .77778 ], "8913": [ .03517, .54986, 0, 0, .77778 ], "8914": [ 0, .54986, 0, 0, .66667 ], "8915": [ 0, .54986, 0, 0, .66667 ], "8916": [ 0, .69224, 0, 0, .66667 ], "8918": [ .0391, .5391, 0, 0, .77778 ], "8919": [ .0391, .5391, 0, 0, .77778 ], "8920": [ .03517, .54986, 0, 0, 1.33334 ], "8921": [ .03517, .54986, 0, 0, 1.33334 ], "8922": [ .38569, .88569, 0, 0, .77778 ], "8923": [ .38569, .88569, 0, 0, .77778 ], "8926": [ .13667, .63667, 0, 0, .77778 ], "8927": [ .13667, .63667, 0, 0, .77778 ], "8928": [ .30274, .79383, 0, 0, .77778 ], "8929": [ .30274, .79383, 0, 0, .77778 ], "8934": [ .23222, .74111, 0, 0, .77778 ], "8935": [ .23222, .74111, 0, 0, .77778 ], "8936": [ .23222, .74111, 0, 0, .77778 ], "8937": [ .23222, .74111, 0, 0, .77778 ], "8938": [ .20576, .70576, 0, 0, .77778 ], "8939": [ .20576, .70576, 0, 0, .77778 ], "8940": [ .30274, .79383, 0, 0, .77778 ], "8941": [ .30274, .79383, 0, 0, .77778 ], "8994": [ .19444, .69224, 0, 0, .77778 ], "8995": [ .19444, .69224, 0, 0, .77778 ], "9416": [ .15559, .69224, 0, 0, .90222 ], "9484": [ 0, .69224, 0, 0, .5 ], "9488": [ 0, .69224, 0, 0, .5 ], "9492": [ 0, .37788, 0, 0, .5 ], "9496": [ 0, .37788, 0, 0, .5 ], "9585": [ .19444, .68889, 0, 0, .88889 ], "9586": [ .19444, .74111, 0, 0, .88889 ], "9632": [ 0, .675, 0, 0, .77778 ], "9633": [ 0, .675, 0, 0, .77778 ], "9650": [ 0, .54986, 0, 0, .72222 ], "9651": [ 0, .54986, 0, 0, .72222 ], "9654": [ .03517, .54986, 0, 0, .77778 ], "9660": [ 0, .54986, 0, 0, .72222 ], "9661": [ 0, .54986, 0, 0, .72222 ], "9664": [ .03517, .54986, 0, 0, .77778 ], "9674": [ .11111, .69224, 0, 0, .66667 ], "9733": [ .19444, .69224, 0, 0, .94445 ], "10003": [ 0, .69224, 0, 0, .83334 ], "10016": [ 0, .69224, 0, 0, .83334 ], "10731": [ .11111, .69224, 0, 0, .66667 ], "10846": [ .19444, .75583, 0, 0, .61111 ], "10877": [ .13667, .63667, 0, 0, .77778 ], "10878": [ .13667, .63667, 0, 0, .77778 ], "10885": [ .25583, .75583, 0, 0, .77778 ], "10886": [ .25583, .75583, 0, 0, .77778 ], "10887": [ .13597, .63597, 0, 0, .77778 ], "10888": [ .13597, .63597, 0, 0, .77778 ], "10889": [ .26167, .75726, 0, 0, .77778 ], "10890": [ .26167, .75726, 0, 0, .77778 ], "10891": [ .48256, .98256, 0, 0, .77778 ], "10892": [ .48256, .98256, 0, 0, .77778 ], "10901": [ .13667, .63667, 0, 0, .77778 ], "10902": [ .13667, .63667, 0, 0, .77778 ], "10933": [ .25142, .75726, 0, 0, .77778 ], "10934": [ .25142, .75726, 0, 0, .77778 ], "10935": [ .26167, .75726, 0, 0, .77778 ], "10936": [ .26167, .75726, 0, 0, .77778 ], "10937": [ .26167, .75726, 0, 0, .77778 ], "10938": [ .26167, .75726, 0, 0, .77778 ], "10949": [ .25583, .75583, 0, 0, .77778 ], "10950": [ .25583, .75583, 0, 0, .77778 ], "10955": [ .28481, .79383, 0, 0, .77778 ], "10956": [ .28481, .79383, 0, 0, .77778 ], "57350": [ .08167, .58167, 0, 0, .22222 ], "57351": [ .08167, .58167, 0, 0, .38889 ], "57352": [ .08167, .58167, 0, 0, .77778 ], "57353": [ 0, .43056, .04028, 0, .66667 ], "57356": [ .25142, .75726, 0, 0, .77778 ], "57357": [ .25142, .75726, 0, 0, .77778 ], "57358": [ .41951, .91951, 0, 0, .77778 ], "57359": [ .30274, .79383, 0, 0, .77778 ], "57360": [ .30274, .79383, 0, 0, .77778 ], "57361": [ .41951, .91951, 0, 0, .77778 ], "57366": [ .25142, .75726, 0, 0, .77778 ], "57367": [ .25142, .75726, 0, 0, .77778 ], "57368": [ .25142, .75726, 0, 0, .77778 ], "57369": [ .25142, .75726, 0, 0, .77778 ], "57370": [ .13597, .63597, 0, 0, .77778 ], "57371": [ .13597, .63597, 0, 0, .77778 ] }, "Caligraphic-Regular": { "32": [ 0, 0, 0, 0, .25 ], "65": [ 0, .68333, 0, .19445, .79847 ], "66": [ 0, .68333, .03041, .13889, .65681 ], "67": [ 0, .68333, .05834, .13889, .52653 ], "68": [ 0, .68333, .02778, .08334, .77139 ], "69": [ 0, .68333, .08944, .11111, .52778 ], "70": [ 0, .68333, .09931, .11111, .71875 ], "71": [ .09722, .68333, .0593, .11111, .59487 ], "72": [ 0, .68333, .00965, .11111, .84452 ], "73": [ 0, .68333, .07382, 0, .54452 ], "74": [ .09722, .68333, .18472, .16667, .67778 ], "75": [ 0, .68333, .01445, .05556, .76195 ], "76": [ 0, .68333, 0, .13889, .68972 ], "77": [ 0, .68333, 0, .13889, 1.2009 ], "78": [ 0, .68333, .14736, .08334, .82049 ], "79": [ 0, .68333, .02778, .11111, .79611 ], "80": [ 0, .68333, .08222, .08334, .69556 ], "81": [ .09722, .68333, 0, .11111, .81667 ], "82": [ 0, .68333, 0, .08334, .8475 ], "83": [ 0, .68333, .075, .13889, .60556 ], "84": [ 0, .68333, .25417, 0, .54464 ], "85": [ 0, .68333, .09931, .08334, .62583 ], "86": [ 0, .68333, .08222, 0, .61278 ], "87": [ 0, .68333, .08222, .08334, .98778 ], "88": [ 0, .68333, .14643, .13889, .7133 ], "89": [ .09722, .68333, .08222, .08334, .66834 ], "90": [ 0, .68333, .07944, .13889, .72473 ], "160": [ 0, 0, 0, 0, .25 ] }, "Fraktur-Regular": { "32": [ 0, 0, 0, 0, .25 ], "33": [ 0, .69141, 0, 0, .29574 ], "34": [ 0, .69141, 0, 0, .21471 ], "38": [ 0, .69141, 0, 0, .73786 ], "39": [ 0, .69141, 0, 0, .21201 ], "40": [ .24982, .74947, 0, 0, .38865 ], "41": [ .24982, .74947, 0, 0, .38865 ], "42": [ 0, .62119, 0, 0, .27764 ], "43": [ .08319, .58283, 0, 0, .75623 ], "44": [ 0, .10803, 0, 0, .27764 ], "45": [ .08319, .58283, 0, 0, .75623 ], "46": [ 0, .10803, 0, 0, .27764 ], "47": [ .24982, .74947, 0, 0, .50181 ], "48": [ 0, .47534, 0, 0, .50181 ], "49": [ 0, .47534, 0, 0, .50181 ], "50": [ 0, .47534, 0, 0, .50181 ], "51": [ .18906, .47534, 0, 0, .50181 ], "52": [ .18906, .47534, 0, 0, .50181 ], "53": [ .18906, .47534, 0, 0, .50181 ], "54": [ 0, .69141, 0, 0, .50181 ], "55": [ .18906, .47534, 0, 0, .50181 ], "56": [ 0, .69141, 0, 0, .50181 ], "57": [ .18906, .47534, 0, 0, .50181 ], "58": [ 0, .47534, 0, 0, .21606 ], "59": [ .12604, .47534, 0, 0, .21606 ], "61": [ -.13099, .36866, 0, 0, .75623 ], "63": [ 0, .69141, 0, 0, .36245 ], "65": [ 0, .69141, 0, 0, .7176 ], "66": [ 0, .69141, 0, 0, .88397 ], "67": [ 0, .69141, 0, 0, .61254 ], "68": [ 0, .69141, 0, 0, .83158 ], "69": [ 0, .69141, 0, 0, .66278 ], "70": [ .12604, .69141, 0, 0, .61119 ], "71": [ 0, .69141, 0, 0, .78539 ], "72": [ .06302, .69141, 0, 0, .7203 ], "73": [ 0, .69141, 0, 0, .55448 ], "74": [ .12604, .69141, 0, 0, .55231 ], "75": [ 0, .69141, 0, 0, .66845 ], "76": [ 0, .69141, 0, 0, .66602 ], "77": [ 0, .69141, 0, 0, 1.04953 ], "78": [ 0, .69141, 0, 0, .83212 ], "79": [ 0, .69141, 0, 0, .82699 ], "80": [ .18906, .69141, 0, 0, .82753 ], "81": [ .03781, .69141, 0, 0, .82699 ], "82": [ 0, .69141, 0, 0, .82807 ], "83": [ 0, .69141, 0, 0, .82861 ], "84": [ 0, .69141, 0, 0, .66899 ], "85": [ 0, .69141, 0, 0, .64576 ], "86": [ 0, .69141, 0, 0, .83131 ], "87": [ 0, .69141, 0, 0, 1.04602 ], "88": [ 0, .69141, 0, 0, .71922 ], "89": [ .18906, .69141, 0, 0, .83293 ], "90": [ .12604, .69141, 0, 0, .60201 ], "91": [ .24982, .74947, 0, 0, .27764 ], "93": [ .24982, .74947, 0, 0, .27764 ], "94": [ 0, .69141, 0, 0, .49965 ], "97": [ 0, .47534, 0, 0, .50046 ], "98": [ 0, .69141, 0, 0, .51315 ], "99": [ 0, .47534, 0, 0, .38946 ], "100": [ 0, .62119, 0, 0, .49857 ], "101": [ 0, .47534, 0, 0, .40053 ], "102": [ .18906, .69141, 0, 0, .32626 ], "103": [ .18906, .47534, 0, 0, .5037 ], "104": [ .18906, .69141, 0, 0, .52126 ], "105": [ 0, .69141, 0, 0, .27899 ], "106": [ 0, .69141, 0, 0, .28088 ], "107": [ 0, .69141, 0, 0, .38946 ], "108": [ 0, .69141, 0, 0, .27953 ], "109": [ 0, .47534, 0, 0, .76676 ], "110": [ 0, .47534, 0, 0, .52666 ], "111": [ 0, .47534, 0, 0, .48885 ], "112": [ .18906, .52396, 0, 0, .50046 ], "113": [ .18906, .47534, 0, 0, .48912 ], "114": [ 0, .47534, 0, 0, .38919 ], "115": [ 0, .47534, 0, 0, .44266 ], "116": [ 0, .62119, 0, 0, .33301 ], "117": [ 0, .47534, 0, 0, .5172 ], "118": [ 0, .52396, 0, 0, .5118 ], "119": [ 0, .52396, 0, 0, .77351 ], "120": [ .18906, .47534, 0, 0, .38865 ], "121": [ .18906, .47534, 0, 0, .49884 ], "122": [ .18906, .47534, 0, 0, .39054 ], "160": [ 0, 0, 0, 0, .25 ], "8216": [ 0, .69141, 0, 0, .21471 ], "8217": [ 0, .69141, 0, 0, .21471 ], "58112": [ 0, .62119, 0, 0, .49749 ], "58113": [ 0, .62119, 0, 0, .4983 ], "58114": [ .18906, .69141, 0, 0, .33328 ], "58115": [ .18906, .69141, 0, 0, .32923 ], "58116": [ .18906, .47534, 0, 0, .50343 ], "58117": [ 0, .69141, 0, 0, .33301 ], "58118": [ 0, .62119, 0, 0, .33409 ], "58119": [ 0, .47534, 0, 0, .50073 ] }, "Main-Bold": { "32": [ 0, 0, 0, 0, .25 ], "33": [ 0, .69444, 0, 0, .35 ], "34": [ 0, .69444, 0, 0, .60278 ], "35": [ .19444, .69444, 0, 0, .95833 ], "36": [ .05556, .75, 0, 0, .575 ], "37": [ .05556, .75, 0, 0, .95833 ], "38": [ 0, .69444, 0, 0, .89444 ], "39": [ 0, .69444, 0, 0, .31944 ], "40": [ .25, .75, 0, 0, .44722 ], "41": [ .25, .75, 0, 0, .44722 ], "42": [ 0, .75, 0, 0, .575 ], "43": [ .13333, .63333, 0, 0, .89444 ], "44": [ .19444, .15556, 0, 0, .31944 ], "45": [ 0, .44444, 0, 0, .38333 ], "46": [ 0, .15556, 0, 0, .31944 ], "47": [ .25, .75, 0, 0, .575 ], "48": [ 0, .64444, 0, 0, .575 ], "49": [ 0, .64444, 0, 0, .575 ], "50": [ 0, .64444, 0, 0, .575 ], "51": [ 0, .64444, 0, 0, .575 ], "52": [ 0, .64444, 0, 0, .575 ], "53": [ 0, .64444, 0, 0, .575 ], "54": [ 0, .64444, 0, 0, .575 ], "55": [ 0, .64444, 0, 0, .575 ], "56": [ 0, .64444, 0, 0, .575 ], "57": [ 0, .64444, 0, 0, .575 ], "58": [ 0, .44444, 0, 0, .31944 ], "59": [ .19444, .44444, 0, 0, .31944 ], "60": [ .08556, .58556, 0, 0, .89444 ], "61": [ -.10889, .39111, 0, 0, .89444 ], "62": [ .08556, .58556, 0, 0, .89444 ], "63": [ 0, .69444, 0, 0, .54305 ], "64": [ 0, .69444, 0, 0, .89444 ], "65": [ 0, .68611, 0, 0, .86944 ], "66": [ 0, .68611, 0, 0, .81805 ], "67": [ 0, .68611, 0, 0, .83055 ], "68": [ 0, .68611, 0, 0, .88194 ], "69": [ 0, .68611, 0, 0, .75555 ], "70": [ 0, .68611, 0, 0, .72361 ], "71": [ 0, .68611, 0, 0, .90416 ], "72": [ 0, .68611, 0, 0, .9 ], "73": [ 0, .68611, 0, 0, .43611 ], "74": [ 0, .68611, 0, 0, .59444 ], "75": [ 0, .68611, 0, 0, .90138 ], "76": [ 0, .68611, 0, 0, .69166 ], "77": [ 0, .68611, 0, 0, 1.09166 ], "78": [ 0, .68611, 0, 0, .9 ], "79": [ 0, .68611, 0, 0, .86388 ], "80": [ 0, .68611, 0, 0, .78611 ], "81": [ .19444, .68611, 0, 0, .86388 ], "82": [ 0, .68611, 0, 0, .8625 ], "83": [ 0, .68611, 0, 0, .63889 ], "84": [ 0, .68611, 0, 0, .8 ], "85": [ 0, .68611, 0, 0, .88472 ], "86": [ 0, .68611, .01597, 0, .86944 ], "87": [ 0, .68611, .01597, 0, 1.18888 ], "88": [ 0, .68611, 0, 0, .86944 ], "89": [ 0, .68611, .02875, 0, .86944 ], "90": [ 0, .68611, 0, 0, .70277 ], "91": [ .25, .75, 0, 0, .31944 ], "92": [ .25, .75, 0, 0, .575 ], "93": [ .25, .75, 0, 0, .31944 ], "94": [ 0, .69444, 0, 0, .575 ], "95": [ .31, .13444, .03194, 0, .575 ], "97": [ 0, .44444, 0, 0, .55902 ], "98": [ 0, .69444, 0, 0, .63889 ], "99": [ 0, .44444, 0, 0, .51111 ], "100": [ 0, .69444, 0, 0, .63889 ], "101": [ 0, .44444, 0, 0, .52708 ], "102": [ 0, .69444, .10903, 0, .35139 ], "103": [ .19444, .44444, .01597, 0, .575 ], "104": [ 0, .69444, 0, 0, .63889 ], "105": [ 0, .69444, 0, 0, .31944 ], "106": [ .19444, .69444, 0, 0, .35139 ], "107": [ 0, .69444, 0, 0, .60694 ], "108": [ 0, .69444, 0, 0, .31944 ], "109": [ 0, .44444, 0, 0, .95833 ], "110": [ 0, .44444, 0, 0, .63889 ], "111": [ 0, .44444, 0, 0, .575 ], "112": [ .19444, .44444, 0, 0, .63889 ], "113": [ .19444, .44444, 0, 0, .60694 ], "114": [ 0, .44444, 0, 0, .47361 ], "115": [ 0, .44444, 0, 0, .45361 ], "116": [ 0, .63492, 0, 0, .44722 ], "117": [ 0, .44444, 0, 0, .63889 ], "118": [ 0, .44444, .01597, 0, .60694 ], "119": [ 0, .44444, .01597, 0, .83055 ], "120": [ 0, .44444, 0, 0, .60694 ], "121": [ .19444, .44444, .01597, 0, .60694 ], "122": [ 0, .44444, 0, 0, .51111 ], "123": [ .25, .75, 0, 0, .575 ], "124": [ .25, .75, 0, 0, .31944 ], "125": [ .25, .75, 0, 0, .575 ], "126": [ .35, .34444, 0, 0, .575 ], "160": [ 0, 0, 0, 0, .25 ], "163": [ 0, .69444, 0, 0, .86853 ], "168": [ 0, .69444, 0, 0, .575 ], "172": [ 0, .44444, 0, 0, .76666 ], "176": [ 0, .69444, 0, 0, .86944 ], "177": [ .13333, .63333, 0, 0, .89444 ], "184": [ .17014, 0, 0, 0, .51111 ], "198": [ 0, .68611, 0, 0, 1.04166 ], "215": [ .13333, .63333, 0, 0, .89444 ], "216": [ .04861, .73472, 0, 0, .89444 ], "223": [ 0, .69444, 0, 0, .59722 ], "230": [ 0, .44444, 0, 0, .83055 ], "247": [ .13333, .63333, 0, 0, .89444 ], "248": [ .09722, .54167, 0, 0, .575 ], "305": [ 0, .44444, 0, 0, .31944 ], "338": [ 0, .68611, 0, 0, 1.16944 ], "339": [ 0, .44444, 0, 0, .89444 ], "567": [ .19444, .44444, 0, 0, .35139 ], "710": [ 0, .69444, 0, 0, .575 ], "711": [ 0, .63194, 0, 0, .575 ], "713": [ 0, .59611, 0, 0, .575 ], "714": [ 0, .69444, 0, 0, .575 ], "715": [ 0, .69444, 0, 0, .575 ], "728": [ 0, .69444, 0, 0, .575 ], "729": [ 0, .69444, 0, 0, .31944 ], "730": [ 0, .69444, 0, 0, .86944 ], "732": [ 0, .69444, 0, 0, .575 ], "733": [ 0, .69444, 0, 0, .575 ], "915": [ 0, .68611, 0, 0, .69166 ], "916": [ 0, .68611, 0, 0, .95833 ], "920": [ 0, .68611, 0, 0, .89444 ], "923": [ 0, .68611, 0, 0, .80555 ], "926": [ 0, .68611, 0, 0, .76666 ], "928": [ 0, .68611, 0, 0, .9 ], "931": [ 0, .68611, 0, 0, .83055 ], "933": [ 0, .68611, 0, 0, .89444 ], "934": [ 0, .68611, 0, 0, .83055 ], "936": [ 0, .68611, 0, 0, .89444 ], "937": [ 0, .68611, 0, 0, .83055 ], "8211": [ 0, .44444, .03194, 0, .575 ], "8212": [ 0, .44444, .03194, 0, 1.14999 ], "8216": [ 0, .69444, 0, 0, .31944 ], "8217": [ 0, .69444, 0, 0, .31944 ], "8220": [ 0, .69444, 0, 0, .60278 ], "8221": [ 0, .69444, 0, 0, .60278 ], "8224": [ .19444, .69444, 0, 0, .51111 ], "8225": [ .19444, .69444, 0, 0, .51111 ], "8242": [ 0, .55556, 0, 0, .34444 ], "8407": [ 0, .72444, .15486, 0, .575 ], "8463": [ 0, .69444, 0, 0, .66759 ], "8465": [ 0, .69444, 0, 0, .83055 ], "8467": [ 0, .69444, 0, 0, .47361 ], "8472": [ .19444, .44444, 0, 0, .74027 ], "8476": [ 0, .69444, 0, 0, .83055 ], "8501": [ 0, .69444, 0, 0, .70277 ], "8592": [ -.10889, .39111, 0, 0, 1.14999 ], "8593": [ .19444, .69444, 0, 0, .575 ], "8594": [ -.10889, .39111, 0, 0, 1.14999 ], "8595": [ .19444, .69444, 0, 0, .575 ], "8596": [ -.10889, .39111, 0, 0, 1.14999 ], "8597": [ .25, .75, 0, 0, .575 ], "8598": [ .19444, .69444, 0, 0, 1.14999 ], "8599": [ .19444, .69444, 0, 0, 1.14999 ], "8600": [ .19444, .69444, 0, 0, 1.14999 ], "8601": [ .19444, .69444, 0, 0, 1.14999 ], "8636": [ -.10889, .39111, 0, 0, 1.14999 ], "8637": [ -.10889, .39111, 0, 0, 1.14999 ], "8640": [ -.10889, .39111, 0, 0, 1.14999 ], "8641": [ -.10889, .39111, 0, 0, 1.14999 ], "8656": [ -.10889, .39111, 0, 0, 1.14999 ], "8657": [ .19444, .69444, 0, 0, .70277 ], "8658": [ -.10889, .39111, 0, 0, 1.14999 ], "8659": [ .19444, .69444, 0, 0, .70277 ], "8660": [ -.10889, .39111, 0, 0, 1.14999 ], "8661": [ .25, .75, 0, 0, .70277 ], "8704": [ 0, .69444, 0, 0, .63889 ], "8706": [ 0, .69444, .06389, 0, .62847 ], "8707": [ 0, .69444, 0, 0, .63889 ], "8709": [ .05556, .75, 0, 0, .575 ], "8711": [ 0, .68611, 0, 0, .95833 ], "8712": [ .08556, .58556, 0, 0, .76666 ], "8715": [ .08556, .58556, 0, 0, .76666 ], "8722": [ .13333, .63333, 0, 0, .89444 ], "8723": [ .13333, .63333, 0, 0, .89444 ], "8725": [ .25, .75, 0, 0, .575 ], "8726": [ .25, .75, 0, 0, .575 ], "8727": [ -.02778, .47222, 0, 0, .575 ], "8728": [ -.02639, .47361, 0, 0, .575 ], "8729": [ -.02639, .47361, 0, 0, .575 ], "8730": [ .18, .82, 0, 0, .95833 ], "8733": [ 0, .44444, 0, 0, .89444 ], "8734": [ 0, .44444, 0, 0, 1.14999 ], "8736": [ 0, .69224, 0, 0, .72222 ], "8739": [ .25, .75, 0, 0, .31944 ], "8741": [ .25, .75, 0, 0, .575 ], "8743": [ 0, .55556, 0, 0, .76666 ], "8744": [ 0, .55556, 0, 0, .76666 ], "8745": [ 0, .55556, 0, 0, .76666 ], "8746": [ 0, .55556, 0, 0, .76666 ], "8747": [ .19444, .69444, .12778, 0, .56875 ], "8764": [ -.10889, .39111, 0, 0, .89444 ], "8768": [ .19444, .69444, 0, 0, .31944 ], "8771": [ .00222, .50222, 0, 0, .89444 ], "8773": [ .027, .638, 0, 0, .894 ], "8776": [ .02444, .52444, 0, 0, .89444 ], "8781": [ .00222, .50222, 0, 0, .89444 ], "8801": [ .00222, .50222, 0, 0, .89444 ], "8804": [ .19667, .69667, 0, 0, .89444 ], "8805": [ .19667, .69667, 0, 0, .89444 ], "8810": [ .08556, .58556, 0, 0, 1.14999 ], "8811": [ .08556, .58556, 0, 0, 1.14999 ], "8826": [ .08556, .58556, 0, 0, .89444 ], "8827": [ .08556, .58556, 0, 0, .89444 ], "8834": [ .08556, .58556, 0, 0, .89444 ], "8835": [ .08556, .58556, 0, 0, .89444 ], "8838": [ .19667, .69667, 0, 0, .89444 ], "8839": [ .19667, .69667, 0, 0, .89444 ], "8846": [ 0, .55556, 0, 0, .76666 ], "8849": [ .19667, .69667, 0, 0, .89444 ], "8850": [ .19667, .69667, 0, 0, .89444 ], "8851": [ 0, .55556, 0, 0, .76666 ], "8852": [ 0, .55556, 0, 0, .76666 ], "8853": [ .13333, .63333, 0, 0, .89444 ], "8854": [ .13333, .63333, 0, 0, .89444 ], "8855": [ .13333, .63333, 0, 0, .89444 ], "8856": [ .13333, .63333, 0, 0, .89444 ], "8857": [ .13333, .63333, 0, 0, .89444 ], "8866": [ 0, .69444, 0, 0, .70277 ], "8867": [ 0, .69444, 0, 0, .70277 ], "8868": [ 0, .69444, 0, 0, .89444 ], "8869": [ 0, .69444, 0, 0, .89444 ], "8900": [ -.02639, .47361, 0, 0, .575 ], "8901": [ -.02639, .47361, 0, 0, .31944 ], "8902": [ -.02778, .47222, 0, 0, .575 ], "8968": [ .25, .75, 0, 0, .51111 ], "8969": [ .25, .75, 0, 0, .51111 ], "8970": [ .25, .75, 0, 0, .51111 ], "8971": [ .25, .75, 0, 0, .51111 ], "8994": [ -.13889, .36111, 0, 0, 1.14999 ], "8995": [ -.13889, .36111, 0, 0, 1.14999 ], "9651": [ .19444, .69444, 0, 0, 1.02222 ], "9657": [ -.02778, .47222, 0, 0, .575 ], "9661": [ .19444, .69444, 0, 0, 1.02222 ], "9667": [ -.02778, .47222, 0, 0, .575 ], "9711": [ .19444, .69444, 0, 0, 1.14999 ], "9824": [ .12963, .69444, 0, 0, .89444 ], "9825": [ .12963, .69444, 0, 0, .89444 ], "9826": [ .12963, .69444, 0, 0, .89444 ], "9827": [ .12963, .69444, 0, 0, .89444 ], "9837": [ 0, .75, 0, 0, .44722 ], "9838": [ .19444, .69444, 0, 0, .44722 ], "9839": [ .19444, .69444, 0, 0, .44722 ], "10216": [ .25, .75, 0, 0, .44722 ], "10217": [ .25, .75, 0, 0, .44722 ], "10815": [ 0, .68611, 0, 0, .9 ], "10927": [ .19667, .69667, 0, 0, .89444 ], "10928": [ .19667, .69667, 0, 0, .89444 ], "57376": [ .19444, .69444, 0, 0, 0 ] }, "Main-BoldItalic": { "32": [ 0, 0, 0, 0, .25 ], "33": [ 0, .69444, .11417, 0, .38611 ], "34": [ 0, .69444, .07939, 0, .62055 ], "35": [ .19444, .69444, .06833, 0, .94444 ], "37": [ .05556, .75, .12861, 0, .94444 ], "38": [ 0, .69444, .08528, 0, .88555 ], "39": [ 0, .69444, .12945, 0, .35555 ], "40": [ .25, .75, .15806, 0, .47333 ], "41": [ .25, .75, .03306, 0, .47333 ], "42": [ 0, .75, .14333, 0, .59111 ], "43": [ .10333, .60333, .03306, 0, .88555 ], "44": [ .19444, .14722, 0, 0, .35555 ], "45": [ 0, .44444, .02611, 0, .41444 ], "46": [ 0, .14722, 0, 0, .35555 ], "47": [ .25, .75, .15806, 0, .59111 ], "48": [ 0, .64444, .13167, 0, .59111 ], "49": [ 0, .64444, .13167, 0, .59111 ], "50": [ 0, .64444, .13167, 0, .59111 ], "51": [ 0, .64444, .13167, 0, .59111 ], "52": [ .19444, .64444, .13167, 0, .59111 ], "53": [ 0, .64444, .13167, 0, .59111 ], "54": [ 0, .64444, .13167, 0, .59111 ], "55": [ .19444, .64444, .13167, 0, .59111 ], "56": [ 0, .64444, .13167, 0, .59111 ], "57": [ 0, .64444, .13167, 0, .59111 ], "58": [ 0, .44444, .06695, 0, .35555 ], "59": [ .19444, .44444, .06695, 0, .35555 ], "61": [ -.10889, .39111, .06833, 0, .88555 ], "63": [ 0, .69444, .11472, 0, .59111 ], "64": [ 0, .69444, .09208, 0, .88555 ], "65": [ 0, .68611, 0, 0, .86555 ], "66": [ 0, .68611, .0992, 0, .81666 ], "67": [ 0, .68611, .14208, 0, .82666 ], "68": [ 0, .68611, .09062, 0, .87555 ], "69": [ 0, .68611, .11431, 0, .75666 ], "70": [ 0, .68611, .12903, 0, .72722 ], "71": [ 0, .68611, .07347, 0, .89527 ], "72": [ 0, .68611, .17208, 0, .8961 ], "73": [ 0, .68611, .15681, 0, .47166 ], "74": [ 0, .68611, .145, 0, .61055 ], "75": [ 0, .68611, .14208, 0, .89499 ], "76": [ 0, .68611, 0, 0, .69777 ], "77": [ 0, .68611, .17208, 0, 1.07277 ], "78": [ 0, .68611, .17208, 0, .8961 ], "79": [ 0, .68611, .09062, 0, .85499 ], "80": [ 0, .68611, .0992, 0, .78721 ], "81": [ .19444, .68611, .09062, 0, .85499 ], "82": [ 0, .68611, .02559, 0, .85944 ], "83": [ 0, .68611, .11264, 0, .64999 ], "84": [ 0, .68611, .12903, 0, .7961 ], "85": [ 0, .68611, .17208, 0, .88083 ], "86": [ 0, .68611, .18625, 0, .86555 ], "87": [ 0, .68611, .18625, 0, 1.15999 ], "88": [ 0, .68611, .15681, 0, .86555 ], "89": [ 0, .68611, .19803, 0, .86555 ], "90": [ 0, .68611, .14208, 0, .70888 ], "91": [ .25, .75, .1875, 0, .35611 ], "93": [ .25, .75, .09972, 0, .35611 ], "94": [ 0, .69444, .06709, 0, .59111 ], "95": [ .31, .13444, .09811, 0, .59111 ], "97": [ 0, .44444, .09426, 0, .59111 ], "98": [ 0, .69444, .07861, 0, .53222 ], "99": [ 0, .44444, .05222, 0, .53222 ], "100": [ 0, .69444, .10861, 0, .59111 ], "101": [ 0, .44444, .085, 0, .53222 ], "102": [ .19444, .69444, .21778, 0, .4 ], "103": [ .19444, .44444, .105, 0, .53222 ], "104": [ 0, .69444, .09426, 0, .59111 ], "105": [ 0, .69326, .11387, 0, .35555 ], "106": [ .19444, .69326, .1672, 0, .35555 ], "107": [ 0, .69444, .11111, 0, .53222 ], "108": [ 0, .69444, .10861, 0, .29666 ], "109": [ 0, .44444, .09426, 0, .94444 ], "110": [ 0, .44444, .09426, 0, .64999 ], "111": [ 0, .44444, .07861, 0, .59111 ], "112": [ .19444, .44444, .07861, 0, .59111 ], "113": [ .19444, .44444, .105, 0, .53222 ], "114": [ 0, .44444, .11111, 0, .50167 ], "115": [ 0, .44444, .08167, 0, .48694 ], "116": [ 0, .63492, .09639, 0, .385 ], "117": [ 0, .44444, .09426, 0, .62055 ], "118": [ 0, .44444, .11111, 0, .53222 ], "119": [ 0, .44444, .11111, 0, .76777 ], "120": [ 0, .44444, .12583, 0, .56055 ], "121": [ .19444, .44444, .105, 0, .56166 ], "122": [ 0, .44444, .13889, 0, .49055 ], "126": [ .35, .34444, .11472, 0, .59111 ], "160": [ 0, 0, 0, 0, .25 ], "168": [ 0, .69444, .11473, 0, .59111 ], "176": [ 0, .69444, 0, 0, .94888 ], "184": [ .17014, 0, 0, 0, .53222 ], "198": [ 0, .68611, .11431, 0, 1.02277 ], "216": [ .04861, .73472, .09062, 0, .88555 ], "223": [ .19444, .69444, .09736, 0, .665 ], "230": [ 0, .44444, .085, 0, .82666 ], "248": [ .09722, .54167, .09458, 0, .59111 ], "305": [ 0, .44444, .09426, 0, .35555 ], "338": [ 0, .68611, .11431, 0, 1.14054 ], "339": [ 0, .44444, .085, 0, .82666 ], "567": [ .19444, .44444, .04611, 0, .385 ], "710": [ 0, .69444, .06709, 0, .59111 ], "711": [ 0, .63194, .08271, 0, .59111 ], "713": [ 0, .59444, .10444, 0, .59111 ], "714": [ 0, .69444, .08528, 0, .59111 ], "715": [ 0, .69444, 0, 0, .59111 ], "728": [ 0, .69444, .10333, 0, .59111 ], "729": [ 0, .69444, .12945, 0, .35555 ], "730": [ 0, .69444, 0, 0, .94888 ], "732": [ 0, .69444, .11472, 0, .59111 ], "733": [ 0, .69444, .11472, 0, .59111 ], "915": [ 0, .68611, .12903, 0, .69777 ], "916": [ 0, .68611, 0, 0, .94444 ], "920": [ 0, .68611, .09062, 0, .88555 ], "923": [ 0, .68611, 0, 0, .80666 ], "926": [ 0, .68611, .15092, 0, .76777 ], "928": [ 0, .68611, .17208, 0, .8961 ], "931": [ 0, .68611, .11431, 0, .82666 ], "933": [ 0, .68611, .10778, 0, .88555 ], "934": [ 0, .68611, .05632, 0, .82666 ], "936": [ 0, .68611, .10778, 0, .88555 ], "937": [ 0, .68611, .0992, 0, .82666 ], "8211": [ 0, .44444, .09811, 0, .59111 ], "8212": [ 0, .44444, .09811, 0, 1.18221 ], "8216": [ 0, .69444, .12945, 0, .35555 ], "8217": [ 0, .69444, .12945, 0, .35555 ], "8220": [ 0, .69444, .16772, 0, .62055 ], "8221": [ 0, .69444, .07939, 0, .62055 ] }, "Main-Italic": { "32": [ 0, 0, 0, 0, .25 ], "33": [ 0, .69444, .12417, 0, .30667 ], "34": [ 0, .69444, .06961, 0, .51444 ], "35": [ .19444, .69444, .06616, 0, .81777 ], "37": [ .05556, .75, .13639, 0, .81777 ], "38": [ 0, .69444, .09694, 0, .76666 ], "39": [ 0, .69444, .12417, 0, .30667 ], "40": [ .25, .75, .16194, 0, .40889 ], "41": [ .25, .75, .03694, 0, .40889 ], "42": [ 0, .75, .14917, 0, .51111 ], "43": [ .05667, .56167, .03694, 0, .76666 ], "44": [ .19444, .10556, 0, 0, .30667 ], "45": [ 0, .43056, .02826, 0, .35778 ], "46": [ 0, .10556, 0, 0, .30667 ], "47": [ .25, .75, .16194, 0, .51111 ], "48": [ 0, .64444, .13556, 0, .51111 ], "49": [ 0, .64444, .13556, 0, .51111 ], "50": [ 0, .64444, .13556, 0, .51111 ], "51": [ 0, .64444, .13556, 0, .51111 ], "52": [ .19444, .64444, .13556, 0, .51111 ], "53": [ 0, .64444, .13556, 0, .51111 ], "54": [ 0, .64444, .13556, 0, .51111 ], "55": [ .19444, .64444, .13556, 0, .51111 ], "56": [ 0, .64444, .13556, 0, .51111 ], "57": [ 0, .64444, .13556, 0, .51111 ], "58": [ 0, .43056, .0582, 0, .30667 ], "59": [ .19444, .43056, .0582, 0, .30667 ], "61": [ -.13313, .36687, .06616, 0, .76666 ], "63": [ 0, .69444, .1225, 0, .51111 ], "64": [ 0, .69444, .09597, 0, .76666 ], "65": [ 0, .68333, 0, 0, .74333 ], "66": [ 0, .68333, .10257, 0, .70389 ], "67": [ 0, .68333, .14528, 0, .71555 ], "68": [ 0, .68333, .09403, 0, .755 ], "69": [ 0, .68333, .12028, 0, .67833 ], "70": [ 0, .68333, .13305, 0, .65277 ], "71": [ 0, .68333, .08722, 0, .77361 ], "72": [ 0, .68333, .16389, 0, .74333 ], "73": [ 0, .68333, .15806, 0, .38555 ], "74": [ 0, .68333, .14028, 0, .525 ], "75": [ 0, .68333, .14528, 0, .76888 ], "76": [ 0, .68333, 0, 0, .62722 ], "77": [ 0, .68333, .16389, 0, .89666 ], "78": [ 0, .68333, .16389, 0, .74333 ], "79": [ 0, .68333, .09403, 0, .76666 ], "80": [ 0, .68333, .10257, 0, .67833 ], "81": [ .19444, .68333, .09403, 0, .76666 ], "82": [ 0, .68333, .03868, 0, .72944 ], "83": [ 0, .68333, .11972, 0, .56222 ], "84": [ 0, .68333, .13305, 0, .71555 ], "85": [ 0, .68333, .16389, 0, .74333 ], "86": [ 0, .68333, .18361, 0, .74333 ], "87": [ 0, .68333, .18361, 0, .99888 ], "88": [ 0, .68333, .15806, 0, .74333 ], "89": [ 0, .68333, .19383, 0, .74333 ], "90": [ 0, .68333, .14528, 0, .61333 ], "91": [ .25, .75, .1875, 0, .30667 ], "93": [ .25, .75, .10528, 0, .30667 ], "94": [ 0, .69444, .06646, 0, .51111 ], "95": [ .31, .12056, .09208, 0, .51111 ], "97": [ 0, .43056, .07671, 0, .51111 ], "98": [ 0, .69444, .06312, 0, .46 ], "99": [ 0, .43056, .05653, 0, .46 ], "100": [ 0, .69444, .10333, 0, .51111 ], "101": [ 0, .43056, .07514, 0, .46 ], "102": [ .19444, .69444, .21194, 0, .30667 ], "103": [ .19444, .43056, .08847, 0, .46 ], "104": [ 0, .69444, .07671, 0, .51111 ], "105": [ 0, .65536, .1019, 0, .30667 ], "106": [ .19444, .65536, .14467, 0, .30667 ], "107": [ 0, .69444, .10764, 0, .46 ], "108": [ 0, .69444, .10333, 0, .25555 ], "109": [ 0, .43056, .07671, 0, .81777 ], "110": [ 0, .43056, .07671, 0, .56222 ], "111": [ 0, .43056, .06312, 0, .51111 ], "112": [ .19444, .43056, .06312, 0, .51111 ], "113": [ .19444, .43056, .08847, 0, .46 ], "114": [ 0, .43056, .10764, 0, .42166 ], "115": [ 0, .43056, .08208, 0, .40889 ], "116": [ 0, .61508, .09486, 0, .33222 ], "117": [ 0, .43056, .07671, 0, .53666 ], "118": [ 0, .43056, .10764, 0, .46 ], "119": [ 0, .43056, .10764, 0, .66444 ], "120": [ 0, .43056, .12042, 0, .46389 ], "121": [ .19444, .43056, .08847, 0, .48555 ], "122": [ 0, .43056, .12292, 0, .40889 ], "126": [ .35, .31786, .11585, 0, .51111 ], "160": [ 0, 0, 0, 0, .25 ], "168": [ 0, .66786, .10474, 0, .51111 ], "176": [ 0, .69444, 0, 0, .83129 ], "184": [ .17014, 0, 0, 0, .46 ], "198": [ 0, .68333, .12028, 0, .88277 ], "216": [ .04861, .73194, .09403, 0, .76666 ], "223": [ .19444, .69444, .10514, 0, .53666 ], "230": [ 0, .43056, .07514, 0, .71555 ], "248": [ .09722, .52778, .09194, 0, .51111 ], "338": [ 0, .68333, .12028, 0, .98499 ], "339": [ 0, .43056, .07514, 0, .71555 ], "710": [ 0, .69444, .06646, 0, .51111 ], "711": [ 0, .62847, .08295, 0, .51111 ], "713": [ 0, .56167, .10333, 0, .51111 ], "714": [ 0, .69444, .09694, 0, .51111 ], "715": [ 0, .69444, 0, 0, .51111 ], "728": [ 0, .69444, .10806, 0, .51111 ], "729": [ 0, .66786, .11752, 0, .30667 ], "730": [ 0, .69444, 0, 0, .83129 ], "732": [ 0, .66786, .11585, 0, .51111 ], "733": [ 0, .69444, .1225, 0, .51111 ], "915": [ 0, .68333, .13305, 0, .62722 ], "916": [ 0, .68333, 0, 0, .81777 ], "920": [ 0, .68333, .09403, 0, .76666 ], "923": [ 0, .68333, 0, 0, .69222 ], "926": [ 0, .68333, .15294, 0, .66444 ], "928": [ 0, .68333, .16389, 0, .74333 ], "931": [ 0, .68333, .12028, 0, .71555 ], "933": [ 0, .68333, .11111, 0, .76666 ], "934": [ 0, .68333, .05986, 0, .71555 ], "936": [ 0, .68333, .11111, 0, .76666 ], "937": [ 0, .68333, .10257, 0, .71555 ], "8211": [ 0, .43056, .09208, 0, .51111 ], "8212": [ 0, .43056, .09208, 0, 1.02222 ], "8216": [ 0, .69444, .12417, 0, .30667 ], "8217": [ 0, .69444, .12417, 0, .30667 ], "8220": [ 0, .69444, .1685, 0, .51444 ], "8221": [ 0, .69444, .06961, 0, .51444 ], "8463": [ 0, .68889, 0, 0, .54028 ] }, "Main-Regular": { "32": [ 0, 0, 0, 0, .25 ], "33": [ 0, .69444, 0, 0, .27778 ], "34": [ 0, .69444, 0, 0, .5 ], "35": [ .19444, .69444, 0, 0, .83334 ], "36": [ .05556, .75, 0, 0, .5 ], "37": [ .05556, .75, 0, 0, .83334 ], "38": [ 0, .69444, 0, 0, .77778 ], "39": [ 0, .69444, 0, 0, .27778 ], "40": [ .25, .75, 0, 0, .38889 ], "41": [ .25, .75, 0, 0, .38889 ], "42": [ 0, .75, 0, 0, .5 ], "43": [ .08333, .58333, 0, 0, .77778 ], "44": [ .19444, .10556, 0, 0, .27778 ], "45": [ 0, .43056, 0, 0, .33333 ], "46": [ 0, .10556, 0, 0, .27778 ], "47": [ .25, .75, 0, 0, .5 ], "48": [ 0, .64444, 0, 0, .5 ], "49": [ 0, .64444, 0, 0, .5 ], "50": [ 0, .64444, 0, 0, .5 ], "51": [ 0, .64444, 0, 0, .5 ], "52": [ 0, .64444, 0, 0, .5 ], "53": [ 0, .64444, 0, 0, .5 ], "54": [ 0, .64444, 0, 0, .5 ], "55": [ 0, .64444, 0, 0, .5 ], "56": [ 0, .64444, 0, 0, .5 ], "57": [ 0, .64444, 0, 0, .5 ], "58": [ 0, .43056, 0, 0, .27778 ], "59": [ .19444, .43056, 0, 0, .27778 ], "60": [ .0391, .5391, 0, 0, .77778 ], "61": [ -.13313, .36687, 0, 0, .77778 ], "62": [ .0391, .5391, 0, 0, .77778 ], "63": [ 0, .69444, 0, 0, .47222 ], "64": [ 0, .69444, 0, 0, .77778 ], "65": [ 0, .68333, 0, 0, .75 ], "66": [ 0, .68333, 0, 0, .70834 ], "67": [ 0, .68333, 0, 0, .72222 ], "68": [ 0, .68333, 0, 0, .76389 ], "69": [ 0, .68333, 0, 0, .68056 ], "70": [ 0, .68333, 0, 0, .65278 ], "71": [ 0, .68333, 0, 0, .78472 ], "72": [ 0, .68333, 0, 0, .75 ], "73": [ 0, .68333, 0, 0, .36111 ], "74": [ 0, .68333, 0, 0, .51389 ], "75": [ 0, .68333, 0, 0, .77778 ], "76": [ 0, .68333, 0, 0, .625 ], "77": [ 0, .68333, 0, 0, .91667 ], "78": [ 0, .68333, 0, 0, .75 ], "79": [ 0, .68333, 0, 0, .77778 ], "80": [ 0, .68333, 0, 0, .68056 ], "81": [ .19444, .68333, 0, 0, .77778 ], "82": [ 0, .68333, 0, 0, .73611 ], "83": [ 0, .68333, 0, 0, .55556 ], "84": [ 0, .68333, 0, 0, .72222 ], "85": [ 0, .68333, 0, 0, .75 ], "86": [ 0, .68333, .01389, 0, .75 ], "87": [ 0, .68333, .01389, 0, 1.02778 ], "88": [ 0, .68333, 0, 0, .75 ], "89": [ 0, .68333, .025, 0, .75 ], "90": [ 0, .68333, 0, 0, .61111 ], "91": [ .25, .75, 0, 0, .27778 ], "92": [ .25, .75, 0, 0, .5 ], "93": [ .25, .75, 0, 0, .27778 ], "94": [ 0, .69444, 0, 0, .5 ], "95": [ .31, .12056, .02778, 0, .5 ], "97": [ 0, .43056, 0, 0, .5 ], "98": [ 0, .69444, 0, 0, .55556 ], "99": [ 0, .43056, 0, 0, .44445 ], "100": [ 0, .69444, 0, 0, .55556 ], "101": [ 0, .43056, 0, 0, .44445 ], "102": [ 0, .69444, .07778, 0, .30556 ], "103": [ .19444, .43056, .01389, 0, .5 ], "104": [ 0, .69444, 0, 0, .55556 ], "105": [ 0, .66786, 0, 0, .27778 ], "106": [ .19444, .66786, 0, 0, .30556 ], "107": [ 0, .69444, 0, 0, .52778 ], "108": [ 0, .69444, 0, 0, .27778 ], "109": [ 0, .43056, 0, 0, .83334 ], "110": [ 0, .43056, 0, 0, .55556 ], "111": [ 0, .43056, 0, 0, .5 ], "112": [ .19444, .43056, 0, 0, .55556 ], "113": [ .19444, .43056, 0, 0, .52778 ], "114": [ 0, .43056, 0, 0, .39167 ], "115": [ 0, .43056, 0, 0, .39445 ], "116": [ 0, .61508, 0, 0, .38889 ], "117": [ 0, .43056, 0, 0, .55556 ], "118": [ 0, .43056, .01389, 0, .52778 ], "119": [ 0, .43056, .01389, 0, .72222 ], "120": [ 0, .43056, 0, 0, .52778 ], "121": [ .19444, .43056, .01389, 0, .52778 ], "122": [ 0, .43056, 0, 0, .44445 ], "123": [ .25, .75, 0, 0, .5 ], "124": [ .25, .75, 0, 0, .27778 ], "125": [ .25, .75, 0, 0, .5 ], "126": [ .35, .31786, 0, 0, .5 ], "160": [ 0, 0, 0, 0, .25 ], "163": [ 0, .69444, 0, 0, .76909 ], "167": [ .19444, .69444, 0, 0, .44445 ], "168": [ 0, .66786, 0, 0, .5 ], "172": [ 0, .43056, 0, 0, .66667 ], "176": [ 0, .69444, 0, 0, .75 ], "177": [ .08333, .58333, 0, 0, .77778 ], "182": [ .19444, .69444, 0, 0, .61111 ], "184": [ .17014, 0, 0, 0, .44445 ], "198": [ 0, .68333, 0, 0, .90278 ], "215": [ .08333, .58333, 0, 0, .77778 ], "216": [ .04861, .73194, 0, 0, .77778 ], "223": [ 0, .69444, 0, 0, .5 ], "230": [ 0, .43056, 0, 0, .72222 ], "247": [ .08333, .58333, 0, 0, .77778 ], "248": [ .09722, .52778, 0, 0, .5 ], "305": [ 0, .43056, 0, 0, .27778 ], "338": [ 0, .68333, 0, 0, 1.01389 ], "339": [ 0, .43056, 0, 0, .77778 ], "567": [ .19444, .43056, 0, 0, .30556 ], "710": [ 0, .69444, 0, 0, .5 ], "711": [ 0, .62847, 0, 0, .5 ], "713": [ 0, .56778, 0, 0, .5 ], "714": [ 0, .69444, 0, 0, .5 ], "715": [ 0, .69444, 0, 0, .5 ], "728": [ 0, .69444, 0, 0, .5 ], "729": [ 0, .66786, 0, 0, .27778 ], "730": [ 0, .69444, 0, 0, .75 ], "732": [ 0, .66786, 0, 0, .5 ], "733": [ 0, .69444, 0, 0, .5 ], "915": [ 0, .68333, 0, 0, .625 ], "916": [ 0, .68333, 0, 0, .83334 ], "920": [ 0, .68333, 0, 0, .77778 ], "923": [ 0, .68333, 0, 0, .69445 ], "926": [ 0, .68333, 0, 0, .66667 ], "928": [ 0, .68333, 0, 0, .75 ], "931": [ 0, .68333, 0, 0, .72222 ], "933": [ 0, .68333, 0, 0, .77778 ], "934": [ 0, .68333, 0, 0, .72222 ], "936": [ 0, .68333, 0, 0, .77778 ], "937": [ 0, .68333, 0, 0, .72222 ], "8211": [ 0, .43056, .02778, 0, .5 ], "8212": [ 0, .43056, .02778, 0, 1 ], "8216": [ 0, .69444, 0, 0, .27778 ], "8217": [ 0, .69444, 0, 0, .27778 ], "8220": [ 0, .69444, 0, 0, .5 ], "8221": [ 0, .69444, 0, 0, .5 ], "8224": [ .19444, .69444, 0, 0, .44445 ], "8225": [ .19444, .69444, 0, 0, .44445 ], "8230": [ 0, .123, 0, 0, 1.172 ], "8242": [ 0, .55556, 0, 0, .275 ], "8407": [ 0, .71444, .15382, 0, .5 ], "8463": [ 0, .68889, 0, 0, .54028 ], "8465": [ 0, .69444, 0, 0, .72222 ], "8467": [ 0, .69444, 0, .11111, .41667 ], "8472": [ .19444, .43056, 0, .11111, .63646 ], "8476": [ 0, .69444, 0, 0, .72222 ], "8501": [ 0, .69444, 0, 0, .61111 ], "8592": [ -.13313, .36687, 0, 0, 1 ], "8593": [ .19444, .69444, 0, 0, .5 ], "8594": [ -.13313, .36687, 0, 0, 1 ], "8595": [ .19444, .69444, 0, 0, .5 ], "8596": [ -.13313, .36687, 0, 0, 1 ], "8597": [ .25, .75, 0, 0, .5 ], "8598": [ .19444, .69444, 0, 0, 1 ], "8599": [ .19444, .69444, 0, 0, 1 ], "8600": [ .19444, .69444, 0, 0, 1 ], "8601": [ .19444, .69444, 0, 0, 1 ], "8614": [ .011, .511, 0, 0, 1 ], "8617": [ .011, .511, 0, 0, 1.126 ], "8618": [ .011, .511, 0, 0, 1.126 ], "8636": [ -.13313, .36687, 0, 0, 1 ], "8637": [ -.13313, .36687, 0, 0, 1 ], "8640": [ -.13313, .36687, 0, 0, 1 ], "8641": [ -.13313, .36687, 0, 0, 1 ], "8652": [ .011, .671, 0, 0, 1 ], "8656": [ -.13313, .36687, 0, 0, 1 ], "8657": [ .19444, .69444, 0, 0, .61111 ], "8658": [ -.13313, .36687, 0, 0, 1 ], "8659": [ .19444, .69444, 0, 0, .61111 ], "8660": [ -.13313, .36687, 0, 0, 1 ], "8661": [ .25, .75, 0, 0, .61111 ], "8704": [ 0, .69444, 0, 0, .55556 ], "8706": [ 0, .69444, .05556, .08334, .5309 ], "8707": [ 0, .69444, 0, 0, .55556 ], "8709": [ .05556, .75, 0, 0, .5 ], "8711": [ 0, .68333, 0, 0, .83334 ], "8712": [ .0391, .5391, 0, 0, .66667 ], "8715": [ .0391, .5391, 0, 0, .66667 ], "8722": [ .08333, .58333, 0, 0, .77778 ], "8723": [ .08333, .58333, 0, 0, .77778 ], "8725": [ .25, .75, 0, 0, .5 ], "8726": [ .25, .75, 0, 0, .5 ], "8727": [ -.03472, .46528, 0, 0, .5 ], "8728": [ -.05555, .44445, 0, 0, .5 ], "8729": [ -.05555, .44445, 0, 0, .5 ], "8730": [ .2, .8, 0, 0, .83334 ], "8733": [ 0, .43056, 0, 0, .77778 ], "8734": [ 0, .43056, 0, 0, 1 ], "8736": [ 0, .69224, 0, 0, .72222 ], "8739": [ .25, .75, 0, 0, .27778 ], "8741": [ .25, .75, 0, 0, .5 ], "8743": [ 0, .55556, 0, 0, .66667 ], "8744": [ 0, .55556, 0, 0, .66667 ], "8745": [ 0, .55556, 0, 0, .66667 ], "8746": [ 0, .55556, 0, 0, .66667 ], "8747": [ .19444, .69444, .11111, 0, .41667 ], "8764": [ -.13313, .36687, 0, 0, .77778 ], "8768": [ .19444, .69444, 0, 0, .27778 ], "8771": [ -.03625, .46375, 0, 0, .77778 ], "8773": [ -.022, .589, 0, 0, .778 ], "8776": [ -.01688, .48312, 0, 0, .77778 ], "8781": [ -.03625, .46375, 0, 0, .77778 ], "8784": [ -.133, .673, 0, 0, .778 ], "8801": [ -.03625, .46375, 0, 0, .77778 ], "8804": [ .13597, .63597, 0, 0, .77778 ], "8805": [ .13597, .63597, 0, 0, .77778 ], "8810": [ .0391, .5391, 0, 0, 1 ], "8811": [ .0391, .5391, 0, 0, 1 ], "8826": [ .0391, .5391, 0, 0, .77778 ], "8827": [ .0391, .5391, 0, 0, .77778 ], "8834": [ .0391, .5391, 0, 0, .77778 ], "8835": [ .0391, .5391, 0, 0, .77778 ], "8838": [ .13597, .63597, 0, 0, .77778 ], "8839": [ .13597, .63597, 0, 0, .77778 ], "8846": [ 0, .55556, 0, 0, .66667 ], "8849": [ .13597, .63597, 0, 0, .77778 ], "8850": [ .13597, .63597, 0, 0, .77778 ], "8851": [ 0, .55556, 0, 0, .66667 ], "8852": [ 0, .55556, 0, 0, .66667 ], "8853": [ .08333, .58333, 0, 0, .77778 ], "8854": [ .08333, .58333, 0, 0, .77778 ], "8855": [ .08333, .58333, 0, 0, .77778 ], "8856": [ .08333, .58333, 0, 0, .77778 ], "8857": [ .08333, .58333, 0, 0, .77778 ], "8866": [ 0, .69444, 0, 0, .61111 ], "8867": [ 0, .69444, 0, 0, .61111 ], "8868": [ 0, .69444, 0, 0, .77778 ], "8869": [ 0, .69444, 0, 0, .77778 ], "8872": [ .249, .75, 0, 0, .867 ], "8900": [ -.05555, .44445, 0, 0, .5 ], "8901": [ -.05555, .44445, 0, 0, .27778 ], "8902": [ -.03472, .46528, 0, 0, .5 ], "8904": [ .005, .505, 0, 0, .9 ], "8942": [ .03, .903, 0, 0, .278 ], "8943": [ -.19, .313, 0, 0, 1.172 ], "8945": [ -.1, .823, 0, 0, 1.282 ], "8968": [ .25, .75, 0, 0, .44445 ], "8969": [ .25, .75, 0, 0, .44445 ], "8970": [ .25, .75, 0, 0, .44445 ], "8971": [ .25, .75, 0, 0, .44445 ], "8994": [ -.14236, .35764, 0, 0, 1 ], "8995": [ -.14236, .35764, 0, 0, 1 ], "9136": [ .244, .744, 0, 0, .412 ], "9137": [ .244, .745, 0, 0, .412 ], "9651": [ .19444, .69444, 0, 0, .88889 ], "9657": [ -.03472, .46528, 0, 0, .5 ], "9661": [ .19444, .69444, 0, 0, .88889 ], "9667": [ -.03472, .46528, 0, 0, .5 ], "9711": [ .19444, .69444, 0, 0, 1 ], "9824": [ .12963, .69444, 0, 0, .77778 ], "9825": [ .12963, .69444, 0, 0, .77778 ], "9826": [ .12963, .69444, 0, 0, .77778 ], "9827": [ .12963, .69444, 0, 0, .77778 ], "9837": [ 0, .75, 0, 0, .38889 ], "9838": [ .19444, .69444, 0, 0, .38889 ], "9839": [ .19444, .69444, 0, 0, .38889 ], "10216": [ .25, .75, 0, 0, .38889 ], "10217": [ .25, .75, 0, 0, .38889 ], "10222": [ .244, .744, 0, 0, .412 ], "10223": [ .244, .745, 0, 0, .412 ], "10229": [ .011, .511, 0, 0, 1.609 ], "10230": [ .011, .511, 0, 0, 1.638 ], "10231": [ .011, .511, 0, 0, 1.859 ], "10232": [ .024, .525, 0, 0, 1.609 ], "10233": [ .024, .525, 0, 0, 1.638 ], "10234": [ .024, .525, 0, 0, 1.858 ], "10236": [ .011, .511, 0, 0, 1.638 ], "10815": [ 0, .68333, 0, 0, .75 ], "10927": [ .13597, .63597, 0, 0, .77778 ], "10928": [ .13597, .63597, 0, 0, .77778 ], "57376": [ .19444, .69444, 0, 0, 0 ] }, "Math-BoldItalic": { "32": [ 0, 0, 0, 0, .25 ], "48": [ 0, .44444, 0, 0, .575 ], "49": [ 0, .44444, 0, 0, .575 ], "50": [ 0, .44444, 0, 0, .575 ], "51": [ .19444, .44444, 0, 0, .575 ], "52": [ .19444, .44444, 0, 0, .575 ], "53": [ .19444, .44444, 0, 0, .575 ], "54": [ 0, .64444, 0, 0, .575 ], "55": [ .19444, .44444, 0, 0, .575 ], "56": [ 0, .64444, 0, 0, .575 ], "57": [ .19444, .44444, 0, 0, .575 ], "65": [ 0, .68611, 0, 0, .86944 ], "66": [ 0, .68611, .04835, 0, .8664 ], "67": [ 0, .68611, .06979, 0, .81694 ], "68": [ 0, .68611, .03194, 0, .93812 ], "69": [ 0, .68611, .05451, 0, .81007 ], "70": [ 0, .68611, .15972, 0, .68889 ], "71": [ 0, .68611, 0, 0, .88673 ], "72": [ 0, .68611, .08229, 0, .98229 ], "73": [ 0, .68611, .07778, 0, .51111 ], "74": [ 0, .68611, .10069, 0, .63125 ], "75": [ 0, .68611, .06979, 0, .97118 ], "76": [ 0, .68611, 0, 0, .75555 ], "77": [ 0, .68611, .11424, 0, 1.14201 ], "78": [ 0, .68611, .11424, 0, .95034 ], "79": [ 0, .68611, .03194, 0, .83666 ], "80": [ 0, .68611, .15972, 0, .72309 ], "81": [ .19444, .68611, 0, 0, .86861 ], "82": [ 0, .68611, .00421, 0, .87235 ], "83": [ 0, .68611, .05382, 0, .69271 ], "84": [ 0, .68611, .15972, 0, .63663 ], "85": [ 0, .68611, .11424, 0, .80027 ], "86": [ 0, .68611, .25555, 0, .67778 ], "87": [ 0, .68611, .15972, 0, 1.09305 ], "88": [ 0, .68611, .07778, 0, .94722 ], "89": [ 0, .68611, .25555, 0, .67458 ], "90": [ 0, .68611, .06979, 0, .77257 ], "97": [ 0, .44444, 0, 0, .63287 ], "98": [ 0, .69444, 0, 0, .52083 ], "99": [ 0, .44444, 0, 0, .51342 ], "100": [ 0, .69444, 0, 0, .60972 ], "101": [ 0, .44444, 0, 0, .55361 ], "102": [ .19444, .69444, .11042, 0, .56806 ], "103": [ .19444, .44444, .03704, 0, .5449 ], "104": [ 0, .69444, 0, 0, .66759 ], "105": [ 0, .69326, 0, 0, .4048 ], "106": [ .19444, .69326, .0622, 0, .47083 ], "107": [ 0, .69444, .01852, 0, .6037 ], "108": [ 0, .69444, .0088, 0, .34815 ], "109": [ 0, .44444, 0, 0, 1.0324 ], "110": [ 0, .44444, 0, 0, .71296 ], "111": [ 0, .44444, 0, 0, .58472 ], "112": [ .19444, .44444, 0, 0, .60092 ], "113": [ .19444, .44444, .03704, 0, .54213 ], "114": [ 0, .44444, .03194, 0, .5287 ], "115": [ 0, .44444, 0, 0, .53125 ], "116": [ 0, .63492, 0, 0, .41528 ], "117": [ 0, .44444, 0, 0, .68102 ], "118": [ 0, .44444, .03704, 0, .56666 ], "119": [ 0, .44444, .02778, 0, .83148 ], "120": [ 0, .44444, 0, 0, .65903 ], "121": [ .19444, .44444, .03704, 0, .59028 ], "122": [ 0, .44444, .04213, 0, .55509 ], "160": [ 0, 0, 0, 0, .25 ], "915": [ 0, .68611, .15972, 0, .65694 ], "916": [ 0, .68611, 0, 0, .95833 ], "920": [ 0, .68611, .03194, 0, .86722 ], "923": [ 0, .68611, 0, 0, .80555 ], "926": [ 0, .68611, .07458, 0, .84125 ], "928": [ 0, .68611, .08229, 0, .98229 ], "931": [ 0, .68611, .05451, 0, .88507 ], "933": [ 0, .68611, .15972, 0, .67083 ], "934": [ 0, .68611, 0, 0, .76666 ], "936": [ 0, .68611, .11653, 0, .71402 ], "937": [ 0, .68611, .04835, 0, .8789 ], "945": [ 0, .44444, 0, 0, .76064 ], "946": [ .19444, .69444, .03403, 0, .65972 ], "947": [ .19444, .44444, .06389, 0, .59003 ], "948": [ 0, .69444, .03819, 0, .52222 ], "949": [ 0, .44444, 0, 0, .52882 ], "950": [ .19444, .69444, .06215, 0, .50833 ], "951": [ .19444, .44444, .03704, 0, .6 ], "952": [ 0, .69444, .03194, 0, .5618 ], "953": [ 0, .44444, 0, 0, .41204 ], "954": [ 0, .44444, 0, 0, .66759 ], "955": [ 0, .69444, 0, 0, .67083 ], "956": [ .19444, .44444, 0, 0, .70787 ], "957": [ 0, .44444, .06898, 0, .57685 ], "958": [ .19444, .69444, .03021, 0, .50833 ], "959": [ 0, .44444, 0, 0, .58472 ], "960": [ 0, .44444, .03704, 0, .68241 ], "961": [ .19444, .44444, 0, 0, .6118 ], "962": [ .09722, .44444, .07917, 0, .42361 ], "963": [ 0, .44444, .03704, 0, .68588 ], "964": [ 0, .44444, .13472, 0, .52083 ], "965": [ 0, .44444, .03704, 0, .63055 ], "966": [ .19444, .44444, 0, 0, .74722 ], "967": [ .19444, .44444, 0, 0, .71805 ], "968": [ .19444, .69444, .03704, 0, .75833 ], "969": [ 0, .44444, .03704, 0, .71782 ], "977": [ 0, .69444, 0, 0, .69155 ], "981": [ .19444, .69444, 0, 0, .7125 ], "982": [ 0, .44444, .03194, 0, .975 ], "1009": [ .19444, .44444, 0, 0, .6118 ], "1013": [ 0, .44444, 0, 0, .48333 ], "57649": [ 0, .44444, 0, 0, .39352 ], "57911": [ .19444, .44444, 0, 0, .43889 ] }, "Math-Italic": { "32": [ 0, 0, 0, 0, .25 ], "48": [ 0, .43056, 0, 0, .5 ], "49": [ 0, .43056, 0, 0, .5 ], "50": [ 0, .43056, 0, 0, .5 ], "51": [ .19444, .43056, 0, 0, .5 ], "52": [ .19444, .43056, 0, 0, .5 ], "53": [ .19444, .43056, 0, 0, .5 ], "54": [ 0, .64444, 0, 0, .5 ], "55": [ .19444, .43056, 0, 0, .5 ], "56": [ 0, .64444, 0, 0, .5 ], "57": [ .19444, .43056, 0, 0, .5 ], "65": [ 0, .68333, 0, .13889, .75 ], "66": [ 0, .68333, .05017, .08334, .75851 ], "67": [ 0, .68333, .07153, .08334, .71472 ], "68": [ 0, .68333, .02778, .05556, .82792 ], "69": [ 0, .68333, .05764, .08334, .7382 ], "70": [ 0, .68333, .13889, .08334, .64306 ], "71": [ 0, .68333, 0, .08334, .78625 ], "72": [ 0, .68333, .08125, .05556, .83125 ], "73": [ 0, .68333, .07847, .11111, .43958 ], "74": [ 0, .68333, .09618, .16667, .55451 ], "75": [ 0, .68333, .07153, .05556, .84931 ], "76": [ 0, .68333, 0, .02778, .68056 ], "77": [ 0, .68333, .10903, .08334, .97014 ], "78": [ 0, .68333, .10903, .08334, .80347 ], "79": [ 0, .68333, .02778, .08334, .76278 ], "80": [ 0, .68333, .13889, .08334, .64201 ], "81": [ .19444, .68333, 0, .08334, .79056 ], "82": [ 0, .68333, .00773, .08334, .75929 ], "83": [ 0, .68333, .05764, .08334, .6132 ], "84": [ 0, .68333, .13889, .08334, .58438 ], "85": [ 0, .68333, .10903, .02778, .68278 ], "86": [ 0, .68333, .22222, 0, .58333 ], "87": [ 0, .68333, .13889, 0, .94445 ], "88": [ 0, .68333, .07847, .08334, .82847 ], "89": [ 0, .68333, .22222, 0, .58056 ], "90": [ 0, .68333, .07153, .08334, .68264 ], "97": [ 0, .43056, 0, 0, .52859 ], "98": [ 0, .69444, 0, 0, .42917 ], "99": [ 0, .43056, 0, .05556, .43276 ], "100": [ 0, .69444, 0, .16667, .52049 ], "101": [ 0, .43056, 0, .05556, .46563 ], "102": [ .19444, .69444, .10764, .16667, .48959 ], "103": [ .19444, .43056, .03588, .02778, .47697 ], "104": [ 0, .69444, 0, 0, .57616 ], "105": [ 0, .65952, 0, 0, .34451 ], "106": [ .19444, .65952, .05724, 0, .41181 ], "107": [ 0, .69444, .03148, 0, .5206 ], "108": [ 0, .69444, .01968, .08334, .29838 ], "109": [ 0, .43056, 0, 0, .87801 ], "110": [ 0, .43056, 0, 0, .60023 ], "111": [ 0, .43056, 0, .05556, .48472 ], "112": [ .19444, .43056, 0, .08334, .50313 ], "113": [ .19444, .43056, .03588, .08334, .44641 ], "114": [ 0, .43056, .02778, .05556, .45116 ], "115": [ 0, .43056, 0, .05556, .46875 ], "116": [ 0, .61508, 0, .08334, .36111 ], "117": [ 0, .43056, 0, .02778, .57246 ], "118": [ 0, .43056, .03588, .02778, .48472 ], "119": [ 0, .43056, .02691, .08334, .71592 ], "120": [ 0, .43056, 0, .02778, .57153 ], "121": [ .19444, .43056, .03588, .05556, .49028 ], "122": [ 0, .43056, .04398, .05556, .46505 ], "160": [ 0, 0, 0, 0, .25 ], "915": [ 0, .68333, .13889, .08334, .61528 ], "916": [ 0, .68333, 0, .16667, .83334 ], "920": [ 0, .68333, .02778, .08334, .76278 ], "923": [ 0, .68333, 0, .16667, .69445 ], "926": [ 0, .68333, .07569, .08334, .74236 ], "928": [ 0, .68333, .08125, .05556, .83125 ], "931": [ 0, .68333, .05764, .08334, .77986 ], "933": [ 0, .68333, .13889, .05556, .58333 ], "934": [ 0, .68333, 0, .08334, .66667 ], "936": [ 0, .68333, .11, .05556, .61222 ], "937": [ 0, .68333, .05017, .08334, .7724 ], "945": [ 0, .43056, .0037, .02778, .6397 ], "946": [ .19444, .69444, .05278, .08334, .56563 ], "947": [ .19444, .43056, .05556, 0, .51773 ], "948": [ 0, .69444, .03785, .05556, .44444 ], "949": [ 0, .43056, 0, .08334, .46632 ], "950": [ .19444, .69444, .07378, .08334, .4375 ], "951": [ .19444, .43056, .03588, .05556, .49653 ], "952": [ 0, .69444, .02778, .08334, .46944 ], "953": [ 0, .43056, 0, .05556, .35394 ], "954": [ 0, .43056, 0, 0, .57616 ], "955": [ 0, .69444, 0, 0, .58334 ], "956": [ .19444, .43056, 0, .02778, .60255 ], "957": [ 0, .43056, .06366, .02778, .49398 ], "958": [ .19444, .69444, .04601, .11111, .4375 ], "959": [ 0, .43056, 0, .05556, .48472 ], "960": [ 0, .43056, .03588, 0, .57003 ], "961": [ .19444, .43056, 0, .08334, .51702 ], "962": [ .09722, .43056, .07986, .08334, .36285 ], "963": [ 0, .43056, .03588, 0, .57141 ], "964": [ 0, .43056, .1132, .02778, .43715 ], "965": [ 0, .43056, .03588, .02778, .54028 ], "966": [ .19444, .43056, 0, .08334, .65417 ], "967": [ .19444, .43056, 0, .05556, .62569 ], "968": [ .19444, .69444, .03588, .11111, .65139 ], "969": [ 0, .43056, .03588, 0, .62245 ], "977": [ 0, .69444, 0, .08334, .59144 ], "981": [ .19444, .69444, 0, .08334, .59583 ], "982": [ 0, .43056, .02778, 0, .82813 ], "1009": [ .19444, .43056, 0, .08334, .51702 ], "1013": [ 0, .43056, 0, .05556, .4059 ], "57649": [ 0, .43056, 0, .02778, .32246 ], "57911": [ .19444, .43056, 0, .08334, .38403 ] }, "SansSerif-Bold": { "32": [ 0, 0, 0, 0, .25 ], "33": [ 0, .69444, 0, 0, .36667 ], "34": [ 0, .69444, 0, 0, .55834 ], "35": [ .19444, .69444, 0, 0, .91667 ], "36": [ .05556, .75, 0, 0, .55 ], "37": [ .05556, .75, 0, 0, 1.02912 ], "38": [ 0, .69444, 0, 0, .83056 ], "39": [ 0, .69444, 0, 0, .30556 ], "40": [ .25, .75, 0, 0, .42778 ], "41": [ .25, .75, 0, 0, .42778 ], "42": [ 0, .75, 0, 0, .55 ], "43": [ .11667, .61667, 0, 0, .85556 ], "44": [ .10556, .13056, 0, 0, .30556 ], "45": [ 0, .45833, 0, 0, .36667 ], "46": [ 0, .13056, 0, 0, .30556 ], "47": [ .25, .75, 0, 0, .55 ], "48": [ 0, .69444, 0, 0, .55 ], "49": [ 0, .69444, 0, 0, .55 ], "50": [ 0, .69444, 0, 0, .55 ], "51": [ 0, .69444, 0, 0, .55 ], "52": [ 0, .69444, 0, 0, .55 ], "53": [ 0, .69444, 0, 0, .55 ], "54": [ 0, .69444, 0, 0, .55 ], "55": [ 0, .69444, 0, 0, .55 ], "56": [ 0, .69444, 0, 0, .55 ], "57": [ 0, .69444, 0, 0, .55 ], "58": [ 0, .45833, 0, 0, .30556 ], "59": [ .10556, .45833, 0, 0, .30556 ], "61": [ -.09375, .40625, 0, 0, .85556 ], "63": [ 0, .69444, 0, 0, .51945 ], "64": [ 0, .69444, 0, 0, .73334 ], "65": [ 0, .69444, 0, 0, .73334 ], "66": [ 0, .69444, 0, 0, .73334 ], "67": [ 0, .69444, 0, 0, .70278 ], "68": [ 0, .69444, 0, 0, .79445 ], "69": [ 0, .69444, 0, 0, .64167 ], "70": [ 0, .69444, 0, 0, .61111 ], "71": [ 0, .69444, 0, 0, .73334 ], "72": [ 0, .69444, 0, 0, .79445 ], "73": [ 0, .69444, 0, 0, .33056 ], "74": [ 0, .69444, 0, 0, .51945 ], "75": [ 0, .69444, 0, 0, .76389 ], "76": [ 0, .69444, 0, 0, .58056 ], "77": [ 0, .69444, 0, 0, .97778 ], "78": [ 0, .69444, 0, 0, .79445 ], "79": [ 0, .69444, 0, 0, .79445 ], "80": [ 0, .69444, 0, 0, .70278 ], "81": [ .10556, .69444, 0, 0, .79445 ], "82": [ 0, .69444, 0, 0, .70278 ], "83": [ 0, .69444, 0, 0, .61111 ], "84": [ 0, .69444, 0, 0, .73334 ], "85": [ 0, .69444, 0, 0, .76389 ], "86": [ 0, .69444, .01528, 0, .73334 ], "87": [ 0, .69444, .01528, 0, 1.03889 ], "88": [ 0, .69444, 0, 0, .73334 ], "89": [ 0, .69444, .0275, 0, .73334 ], "90": [ 0, .69444, 0, 0, .67223 ], "91": [ .25, .75, 0, 0, .34306 ], "93": [ .25, .75, 0, 0, .34306 ], "94": [ 0, .69444, 0, 0, .55 ], "95": [ .35, .10833, .03056, 0, .55 ], "97": [ 0, .45833, 0, 0, .525 ], "98": [ 0, .69444, 0, 0, .56111 ], "99": [ 0, .45833, 0, 0, .48889 ], "100": [ 0, .69444, 0, 0, .56111 ], "101": [ 0, .45833, 0, 0, .51111 ], "102": [ 0, .69444, .07639, 0, .33611 ], "103": [ .19444, .45833, .01528, 0, .55 ], "104": [ 0, .69444, 0, 0, .56111 ], "105": [ 0, .69444, 0, 0, .25556 ], "106": [ .19444, .69444, 0, 0, .28611 ], "107": [ 0, .69444, 0, 0, .53056 ], "108": [ 0, .69444, 0, 0, .25556 ], "109": [ 0, .45833, 0, 0, .86667 ], "110": [ 0, .45833, 0, 0, .56111 ], "111": [ 0, .45833, 0, 0, .55 ], "112": [ .19444, .45833, 0, 0, .56111 ], "113": [ .19444, .45833, 0, 0, .56111 ], "114": [ 0, .45833, .01528, 0, .37222 ], "115": [ 0, .45833, 0, 0, .42167 ], "116": [ 0, .58929, 0, 0, .40417 ], "117": [ 0, .45833, 0, 0, .56111 ], "118": [ 0, .45833, .01528, 0, .5 ], "119": [ 0, .45833, .01528, 0, .74445 ], "120": [ 0, .45833, 0, 0, .5 ], "121": [ .19444, .45833, .01528, 0, .5 ], "122": [ 0, .45833, 0, 0, .47639 ], "126": [ .35, .34444, 0, 0, .55 ], "160": [ 0, 0, 0, 0, .25 ], "168": [ 0, .69444, 0, 0, .55 ], "176": [ 0, .69444, 0, 0, .73334 ], "180": [ 0, .69444, 0, 0, .55 ], "184": [ .17014, 0, 0, 0, .48889 ], "305": [ 0, .45833, 0, 0, .25556 ], "567": [ .19444, .45833, 0, 0, .28611 ], "710": [ 0, .69444, 0, 0, .55 ], "711": [ 0, .63542, 0, 0, .55 ], "713": [ 0, .63778, 0, 0, .55 ], "728": [ 0, .69444, 0, 0, .55 ], "729": [ 0, .69444, 0, 0, .30556 ], "730": [ 0, .69444, 0, 0, .73334 ], "732": [ 0, .69444, 0, 0, .55 ], "733": [ 0, .69444, 0, 0, .55 ], "915": [ 0, .69444, 0, 0, .58056 ], "916": [ 0, .69444, 0, 0, .91667 ], "920": [ 0, .69444, 0, 0, .85556 ], "923": [ 0, .69444, 0, 0, .67223 ], "926": [ 0, .69444, 0, 0, .73334 ], "928": [ 0, .69444, 0, 0, .79445 ], "931": [ 0, .69444, 0, 0, .79445 ], "933": [ 0, .69444, 0, 0, .85556 ], "934": [ 0, .69444, 0, 0, .79445 ], "936": [ 0, .69444, 0, 0, .85556 ], "937": [ 0, .69444, 0, 0, .79445 ], "8211": [ 0, .45833, .03056, 0, .55 ], "8212": [ 0, .45833, .03056, 0, 1.10001 ], "8216": [ 0, .69444, 0, 0, .30556 ], "8217": [ 0, .69444, 0, 0, .30556 ], "8220": [ 0, .69444, 0, 0, .55834 ], "8221": [ 0, .69444, 0, 0, .55834 ] }, "SansSerif-Italic": { "32": [ 0, 0, 0, 0, .25 ], "33": [ 0, .69444, .05733, 0, .31945 ], "34": [ 0, .69444, .00316, 0, .5 ], "35": [ .19444, .69444, .05087, 0, .83334 ], "36": [ .05556, .75, .11156, 0, .5 ], "37": [ .05556, .75, .03126, 0, .83334 ], "38": [ 0, .69444, .03058, 0, .75834 ], "39": [ 0, .69444, .07816, 0, .27778 ], "40": [ .25, .75, .13164, 0, .38889 ], "41": [ .25, .75, .02536, 0, .38889 ], "42": [ 0, .75, .11775, 0, .5 ], "43": [ .08333, .58333, .02536, 0, .77778 ], "44": [ .125, .08333, 0, 0, .27778 ], "45": [ 0, .44444, .01946, 0, .33333 ], "46": [ 0, .08333, 0, 0, .27778 ], "47": [ .25, .75, .13164, 0, .5 ], "48": [ 0, .65556, .11156, 0, .5 ], "49": [ 0, .65556, .11156, 0, .5 ], "50": [ 0, .65556, .11156, 0, .5 ], "51": [ 0, .65556, .11156, 0, .5 ], "52": [ 0, .65556, .11156, 0, .5 ], "53": [ 0, .65556, .11156, 0, .5 ], "54": [ 0, .65556, .11156, 0, .5 ], "55": [ 0, .65556, .11156, 0, .5 ], "56": [ 0, .65556, .11156, 0, .5 ], "57": [ 0, .65556, .11156, 0, .5 ], "58": [ 0, .44444, .02502, 0, .27778 ], "59": [ .125, .44444, .02502, 0, .27778 ], "61": [ -.13, .37, .05087, 0, .77778 ], "63": [ 0, .69444, .11809, 0, .47222 ], "64": [ 0, .69444, .07555, 0, .66667 ], "65": [ 0, .69444, 0, 0, .66667 ], "66": [ 0, .69444, .08293, 0, .66667 ], "67": [ 0, .69444, .11983, 0, .63889 ], "68": [ 0, .69444, .07555, 0, .72223 ], "69": [ 0, .69444, .11983, 0, .59722 ], "70": [ 0, .69444, .13372, 0, .56945 ], "71": [ 0, .69444, .11983, 0, .66667 ], "72": [ 0, .69444, .08094, 0, .70834 ], "73": [ 0, .69444, .13372, 0, .27778 ], "74": [ 0, .69444, .08094, 0, .47222 ], "75": [ 0, .69444, .11983, 0, .69445 ], "76": [ 0, .69444, 0, 0, .54167 ], "77": [ 0, .69444, .08094, 0, .875 ], "78": [ 0, .69444, .08094, 0, .70834 ], "79": [ 0, .69444, .07555, 0, .73611 ], "80": [ 0, .69444, .08293, 0, .63889 ], "81": [ .125, .69444, .07555, 0, .73611 ], "82": [ 0, .69444, .08293, 0, .64584 ], "83": [ 0, .69444, .09205, 0, .55556 ], "84": [ 0, .69444, .13372, 0, .68056 ], "85": [ 0, .69444, .08094, 0, .6875 ], "86": [ 0, .69444, .1615, 0, .66667 ], "87": [ 0, .69444, .1615, 0, .94445 ], "88": [ 0, .69444, .13372, 0, .66667 ], "89": [ 0, .69444, .17261, 0, .66667 ], "90": [ 0, .69444, .11983, 0, .61111 ], "91": [ .25, .75, .15942, 0, .28889 ], "93": [ .25, .75, .08719, 0, .28889 ], "94": [ 0, .69444, .0799, 0, .5 ], "95": [ .35, .09444, .08616, 0, .5 ], "97": [ 0, .44444, .00981, 0, .48056 ], "98": [ 0, .69444, .03057, 0, .51667 ], "99": [ 0, .44444, .08336, 0, .44445 ], "100": [ 0, .69444, .09483, 0, .51667 ], "101": [ 0, .44444, .06778, 0, .44445 ], "102": [ 0, .69444, .21705, 0, .30556 ], "103": [ .19444, .44444, .10836, 0, .5 ], "104": [ 0, .69444, .01778, 0, .51667 ], "105": [ 0, .67937, .09718, 0, .23889 ], "106": [ .19444, .67937, .09162, 0, .26667 ], "107": [ 0, .69444, .08336, 0, .48889 ], "108": [ 0, .69444, .09483, 0, .23889 ], "109": [ 0, .44444, .01778, 0, .79445 ], "110": [ 0, .44444, .01778, 0, .51667 ], "111": [ 0, .44444, .06613, 0, .5 ], "112": [ .19444, .44444, .0389, 0, .51667 ], "113": [ .19444, .44444, .04169, 0, .51667 ], "114": [ 0, .44444, .10836, 0, .34167 ], "115": [ 0, .44444, .0778, 0, .38333 ], "116": [ 0, .57143, .07225, 0, .36111 ], "117": [ 0, .44444, .04169, 0, .51667 ], "118": [ 0, .44444, .10836, 0, .46111 ], "119": [ 0, .44444, .10836, 0, .68334 ], "120": [ 0, .44444, .09169, 0, .46111 ], "121": [ .19444, .44444, .10836, 0, .46111 ], "122": [ 0, .44444, .08752, 0, .43472 ], "126": [ .35, .32659, .08826, 0, .5 ], "160": [ 0, 0, 0, 0, .25 ], "168": [ 0, .67937, .06385, 0, .5 ], "176": [ 0, .69444, 0, 0, .73752 ], "184": [ .17014, 0, 0, 0, .44445 ], "305": [ 0, .44444, .04169, 0, .23889 ], "567": [ .19444, .44444, .04169, 0, .26667 ], "710": [ 0, .69444, .0799, 0, .5 ], "711": [ 0, .63194, .08432, 0, .5 ], "713": [ 0, .60889, .08776, 0, .5 ], "714": [ 0, .69444, .09205, 0, .5 ], "715": [ 0, .69444, 0, 0, .5 ], "728": [ 0, .69444, .09483, 0, .5 ], "729": [ 0, .67937, .07774, 0, .27778 ], "730": [ 0, .69444, 0, 0, .73752 ], "732": [ 0, .67659, .08826, 0, .5 ], "733": [ 0, .69444, .09205, 0, .5 ], "915": [ 0, .69444, .13372, 0, .54167 ], "916": [ 0, .69444, 0, 0, .83334 ], "920": [ 0, .69444, .07555, 0, .77778 ], "923": [ 0, .69444, 0, 0, .61111 ], "926": [ 0, .69444, .12816, 0, .66667 ], "928": [ 0, .69444, .08094, 0, .70834 ], "931": [ 0, .69444, .11983, 0, .72222 ], "933": [ 0, .69444, .09031, 0, .77778 ], "934": [ 0, .69444, .04603, 0, .72222 ], "936": [ 0, .69444, .09031, 0, .77778 ], "937": [ 0, .69444, .08293, 0, .72222 ], "8211": [ 0, .44444, .08616, 0, .5 ], "8212": [ 0, .44444, .08616, 0, 1 ], "8216": [ 0, .69444, .07816, 0, .27778 ], "8217": [ 0, .69444, .07816, 0, .27778 ], "8220": [ 0, .69444, .14205, 0, .5 ], "8221": [ 0, .69444, .00316, 0, .5 ] }, "SansSerif-Regular": { "32": [ 0, 0, 0, 0, .25 ], "33": [ 0, .69444, 0, 0, .31945 ], "34": [ 0, .69444, 0, 0, .5 ], "35": [ .19444, .69444, 0, 0, .83334 ], "36": [ .05556, .75, 0, 0, .5 ], "37": [ .05556, .75, 0, 0, .83334 ], "38": [ 0, .69444, 0, 0, .75834 ], "39": [ 0, .69444, 0, 0, .27778 ], "40": [ .25, .75, 0, 0, .38889 ], "41": [ .25, .75, 0, 0, .38889 ], "42": [ 0, .75, 0, 0, .5 ], "43": [ .08333, .58333, 0, 0, .77778 ], "44": [ .125, .08333, 0, 0, .27778 ], "45": [ 0, .44444, 0, 0, .33333 ], "46": [ 0, .08333, 0, 0, .27778 ], "47": [ .25, .75, 0, 0, .5 ], "48": [ 0, .65556, 0, 0, .5 ], "49": [ 0, .65556, 0, 0, .5 ], "50": [ 0, .65556, 0, 0, .5 ], "51": [ 0, .65556, 0, 0, .5 ], "52": [ 0, .65556, 0, 0, .5 ], "53": [ 0, .65556, 0, 0, .5 ], "54": [ 0, .65556, 0, 0, .5 ], "55": [ 0, .65556, 0, 0, .5 ], "56": [ 0, .65556, 0, 0, .5 ], "57": [ 0, .65556, 0, 0, .5 ], "58": [ 0, .44444, 0, 0, .27778 ], "59": [ .125, .44444, 0, 0, .27778 ], "61": [ -.13, .37, 0, 0, .77778 ], "63": [ 0, .69444, 0, 0, .47222 ], "64": [ 0, .69444, 0, 0, .66667 ], "65": [ 0, .69444, 0, 0, .66667 ], "66": [ 0, .69444, 0, 0, .66667 ], "67": [ 0, .69444, 0, 0, .63889 ], "68": [ 0, .69444, 0, 0, .72223 ], "69": [ 0, .69444, 0, 0, .59722 ], "70": [ 0, .69444, 0, 0, .56945 ], "71": [ 0, .69444, 0, 0, .66667 ], "72": [ 0, .69444, 0, 0, .70834 ], "73": [ 0, .69444, 0, 0, .27778 ], "74": [ 0, .69444, 0, 0, .47222 ], "75": [ 0, .69444, 0, 0, .69445 ], "76": [ 0, .69444, 0, 0, .54167 ], "77": [ 0, .69444, 0, 0, .875 ], "78": [ 0, .69444, 0, 0, .70834 ], "79": [ 0, .69444, 0, 0, .73611 ], "80": [ 0, .69444, 0, 0, .63889 ], "81": [ .125, .69444, 0, 0, .73611 ], "82": [ 0, .69444, 0, 0, .64584 ], "83": [ 0, .69444, 0, 0, .55556 ], "84": [ 0, .69444, 0, 0, .68056 ], "85": [ 0, .69444, 0, 0, .6875 ], "86": [ 0, .69444, .01389, 0, .66667 ], "87": [ 0, .69444, .01389, 0, .94445 ], "88": [ 0, .69444, 0, 0, .66667 ], "89": [ 0, .69444, .025, 0, .66667 ], "90": [ 0, .69444, 0, 0, .61111 ], "91": [ .25, .75, 0, 0, .28889 ], "93": [ .25, .75, 0, 0, .28889 ], "94": [ 0, .69444, 0, 0, .5 ], "95": [ .35, .09444, .02778, 0, .5 ], "97": [ 0, .44444, 0, 0, .48056 ], "98": [ 0, .69444, 0, 0, .51667 ], "99": [ 0, .44444, 0, 0, .44445 ], "100": [ 0, .69444, 0, 0, .51667 ], "101": [ 0, .44444, 0, 0, .44445 ], "102": [ 0, .69444, .06944, 0, .30556 ], "103": [ .19444, .44444, .01389, 0, .5 ], "104": [ 0, .69444, 0, 0, .51667 ], "105": [ 0, .67937, 0, 0, .23889 ], "106": [ .19444, .67937, 0, 0, .26667 ], "107": [ 0, .69444, 0, 0, .48889 ], "108": [ 0, .69444, 0, 0, .23889 ], "109": [ 0, .44444, 0, 0, .79445 ], "110": [ 0, .44444, 0, 0, .51667 ], "111": [ 0, .44444, 0, 0, .5 ], "112": [ .19444, .44444, 0, 0, .51667 ], "113": [ .19444, .44444, 0, 0, .51667 ], "114": [ 0, .44444, .01389, 0, .34167 ], "115": [ 0, .44444, 0, 0, .38333 ], "116": [ 0, .57143, 0, 0, .36111 ], "117": [ 0, .44444, 0, 0, .51667 ], "118": [ 0, .44444, .01389, 0, .46111 ], "119": [ 0, .44444, .01389, 0, .68334 ], "120": [ 0, .44444, 0, 0, .46111 ], "121": [ .19444, .44444, .01389, 0, .46111 ], "122": [ 0, .44444, 0, 0, .43472 ], "126": [ .35, .32659, 0, 0, .5 ], "160": [ 0, 0, 0, 0, .25 ], "168": [ 0, .67937, 0, 0, .5 ], "176": [ 0, .69444, 0, 0, .66667 ], "184": [ .17014, 0, 0, 0, .44445 ], "305": [ 0, .44444, 0, 0, .23889 ], "567": [ .19444, .44444, 0, 0, .26667 ], "710": [ 0, .69444, 0, 0, .5 ], "711": [ 0, .63194, 0, 0, .5 ], "713": [ 0, .60889, 0, 0, .5 ], "714": [ 0, .69444, 0, 0, .5 ], "715": [ 0, .69444, 0, 0, .5 ], "728": [ 0, .69444, 0, 0, .5 ], "729": [ 0, .67937, 0, 0, .27778 ], "730": [ 0, .69444, 0, 0, .66667 ], "732": [ 0, .67659, 0, 0, .5 ], "733": [ 0, .69444, 0, 0, .5 ], "915": [ 0, .69444, 0, 0, .54167 ], "916": [ 0, .69444, 0, 0, .83334 ], "920": [ 0, .69444, 0, 0, .77778 ], "923": [ 0, .69444, 0, 0, .61111 ], "926": [ 0, .69444, 0, 0, .66667 ], "928": [ 0, .69444, 0, 0, .70834 ], "931": [ 0, .69444, 0, 0, .72222 ], "933": [ 0, .69444, 0, 0, .77778 ], "934": [ 0, .69444, 0, 0, .72222 ], "936": [ 0, .69444, 0, 0, .77778 ], "937": [ 0, .69444, 0, 0, .72222 ], "8211": [ 0, .44444, .02778, 0, .5 ], "8212": [ 0, .44444, .02778, 0, 1 ], "8216": [ 0, .69444, 0, 0, .27778 ], "8217": [ 0, .69444, 0, 0, .27778 ], "8220": [ 0, .69444, 0, 0, .5 ], "8221": [ 0, .69444, 0, 0, .5 ] }, "Script-Regular": { "32": [ 0, 0, 0, 0, .25 ], "65": [ 0, .7, .22925, 0, .80253 ], "66": [ 0, .7, .04087, 0, .90757 ], "67": [ 0, .7, .1689, 0, .66619 ], "68": [ 0, .7, .09371, 0, .77443 ], "69": [ 0, .7, .18583, 0, .56162 ], "70": [ 0, .7, .13634, 0, .89544 ], "71": [ 0, .7, .17322, 0, .60961 ], "72": [ 0, .7, .29694, 0, .96919 ], "73": [ 0, .7, .19189, 0, .80907 ], "74": [ .27778, .7, .19189, 0, 1.05159 ], "75": [ 0, .7, .31259, 0, .91364 ], "76": [ 0, .7, .19189, 0, .87373 ], "77": [ 0, .7, .15981, 0, 1.08031 ], "78": [ 0, .7, .3525, 0, .9015 ], "79": [ 0, .7, .08078, 0, .73787 ], "80": [ 0, .7, .08078, 0, 1.01262 ], "81": [ 0, .7, .03305, 0, .88282 ], "82": [ 0, .7, .06259, 0, .85 ], "83": [ 0, .7, .19189, 0, .86767 ], "84": [ 0, .7, .29087, 0, .74697 ], "85": [ 0, .7, .25815, 0, .79996 ], "86": [ 0, .7, .27523, 0, .62204 ], "87": [ 0, .7, .27523, 0, .80532 ], "88": [ 0, .7, .26006, 0, .94445 ], "89": [ 0, .7, .2939, 0, .70961 ], "90": [ 0, .7, .24037, 0, .8212 ], "160": [ 0, 0, 0, 0, .25 ] }, "Size1-Regular": { "32": [ 0, 0, 0, 0, .25 ], "40": [ .35001, .85, 0, 0, .45834 ], "41": [ .35001, .85, 0, 0, .45834 ], "47": [ .35001, .85, 0, 0, .57778 ], "91": [ .35001, .85, 0, 0, .41667 ], "92": [ .35001, .85, 0, 0, .57778 ], "93": [ .35001, .85, 0, 0, .41667 ], "123": [ .35001, .85, 0, 0, .58334 ], "125": [ .35001, .85, 0, 0, .58334 ], "160": [ 0, 0, 0, 0, .25 ], "710": [ 0, .72222, 0, 0, .55556 ], "732": [ 0, .72222, 0, 0, .55556 ], "770": [ 0, .72222, 0, 0, .55556 ], "771": [ 0, .72222, 0, 0, .55556 ], "8214": [ -99e-5, .601, 0, 0, .77778 ], "8593": [ 1e-5, .6, 0, 0, .66667 ], "8595": [ 1e-5, .6, 0, 0, .66667 ], "8657": [ 1e-5, .6, 0, 0, .77778 ], "8659": [ 1e-5, .6, 0, 0, .77778 ], "8719": [ .25001, .75, 0, 0, .94445 ], "8720": [ .25001, .75, 0, 0, .94445 ], "8721": [ .25001, .75, 0, 0, 1.05556 ], "8730": [ .35001, .85, 0, 0, 1 ], "8739": [ -.00599, .606, 0, 0, .33333 ], "8741": [ -.00599, .606, 0, 0, .55556 ], "8747": [ .30612, .805, .19445, 0, .47222 ], "8748": [ .306, .805, .19445, 0, .47222 ], "8749": [ .306, .805, .19445, 0, .47222 ], "8750": [ .30612, .805, .19445, 0, .47222 ], "8896": [ .25001, .75, 0, 0, .83334 ], "8897": [ .25001, .75, 0, 0, .83334 ], "8898": [ .25001, .75, 0, 0, .83334 ], "8899": [ .25001, .75, 0, 0, .83334 ], "8968": [ .35001, .85, 0, 0, .47222 ], "8969": [ .35001, .85, 0, 0, .47222 ], "8970": [ .35001, .85, 0, 0, .47222 ], "8971": [ .35001, .85, 0, 0, .47222 ], "9168": [ -99e-5, .601, 0, 0, .66667 ], "10216": [ .35001, .85, 0, 0, .47222 ], "10217": [ .35001, .85, 0, 0, .47222 ], "10752": [ .25001, .75, 0, 0, 1.11111 ], "10753": [ .25001, .75, 0, 0, 1.11111 ], "10754": [ .25001, .75, 0, 0, 1.11111 ], "10756": [ .25001, .75, 0, 0, .83334 ], "10758": [ .25001, .75, 0, 0, .83334 ] }, "Size2-Regular": { "32": [ 0, 0, 0, 0, .25 ], "40": [ .65002, 1.15, 0, 0, .59722 ], "41": [ .65002, 1.15, 0, 0, .59722 ], "47": [ .65002, 1.15, 0, 0, .81111 ], "91": [ .65002, 1.15, 0, 0, .47222 ], "92": [ .65002, 1.15, 0, 0, .81111 ], "93": [ .65002, 1.15, 0, 0, .47222 ], "123": [ .65002, 1.15, 0, 0, .66667 ], "125": [ .65002, 1.15, 0, 0, .66667 ], "160": [ 0, 0, 0, 0, .25 ], "710": [ 0, .75, 0, 0, 1 ], "732": [ 0, .75, 0, 0, 1 ], "770": [ 0, .75, 0, 0, 1 ], "771": [ 0, .75, 0, 0, 1 ], "8719": [ .55001, 1.05, 0, 0, 1.27778 ], "8720": [ .55001, 1.05, 0, 0, 1.27778 ], "8721": [ .55001, 1.05, 0, 0, 1.44445 ], "8730": [ .65002, 1.15, 0, 0, 1 ], "8747": [ .86225, 1.36, .44445, 0, .55556 ], "8748": [ .862, 1.36, .44445, 0, .55556 ], "8749": [ .862, 1.36, .44445, 0, .55556 ], "8750": [ .86225, 1.36, .44445, 0, .55556 ], "8896": [ .55001, 1.05, 0, 0, 1.11111 ], "8897": [ .55001, 1.05, 0, 0, 1.11111 ], "8898": [ .55001, 1.05, 0, 0, 1.11111 ], "8899": [ .55001, 1.05, 0, 0, 1.11111 ], "8968": [ .65002, 1.15, 0, 0, .52778 ], "8969": [ .65002, 1.15, 0, 0, .52778 ], "8970": [ .65002, 1.15, 0, 0, .52778 ], "8971": [ .65002, 1.15, 0, 0, .52778 ], "10216": [ .65002, 1.15, 0, 0, .61111 ], "10217": [ .65002, 1.15, 0, 0, .61111 ], "10752": [ .55001, 1.05, 0, 0, 1.51112 ], "10753": [ .55001, 1.05, 0, 0, 1.51112 ], "10754": [ .55001, 1.05, 0, 0, 1.51112 ], "10756": [ .55001, 1.05, 0, 0, 1.11111 ], "10758": [ .55001, 1.05, 0, 0, 1.11111 ] }, "Size3-Regular": { "32": [ 0, 0, 0, 0, .25 ], "40": [ .95003, 1.45, 0, 0, .73611 ], "41": [ .95003, 1.45, 0, 0, .73611 ], "47": [ .95003, 1.45, 0, 0, 1.04445 ], "91": [ .95003, 1.45, 0, 0, .52778 ], "92": [ .95003, 1.45, 0, 0, 1.04445 ], "93": [ .95003, 1.45, 0, 0, .52778 ], "123": [ .95003, 1.45, 0, 0, .75 ], "125": [ .95003, 1.45, 0, 0, .75 ], "160": [ 0, 0, 0, 0, .25 ], "710": [ 0, .75, 0, 0, 1.44445 ], "732": [ 0, .75, 0, 0, 1.44445 ], "770": [ 0, .75, 0, 0, 1.44445 ], "771": [ 0, .75, 0, 0, 1.44445 ], "8730": [ .95003, 1.45, 0, 0, 1 ], "8968": [ .95003, 1.45, 0, 0, .58334 ], "8969": [ .95003, 1.45, 0, 0, .58334 ], "8970": [ .95003, 1.45, 0, 0, .58334 ], "8971": [ .95003, 1.45, 0, 0, .58334 ], "10216": [ .95003, 1.45, 0, 0, .75 ], "10217": [ .95003, 1.45, 0, 0, .75 ] }, "Size4-Regular": { "32": [ 0, 0, 0, 0, .25 ], "40": [ 1.25003, 1.75, 0, 0, .79167 ], "41": [ 1.25003, 1.75, 0, 0, .79167 ], "47": [ 1.25003, 1.75, 0, 0, 1.27778 ], "91": [ 1.25003, 1.75, 0, 0, .58334 ], "92": [ 1.25003, 1.75, 0, 0, 1.27778 ], "93": [ 1.25003, 1.75, 0, 0, .58334 ], "123": [ 1.25003, 1.75, 0, 0, .80556 ], "125": [ 1.25003, 1.75, 0, 0, .80556 ], "160": [ 0, 0, 0, 0, .25 ], "710": [ 0, .825, 0, 0, 1.8889 ], "732": [ 0, .825, 0, 0, 1.8889 ], "770": [ 0, .825, 0, 0, 1.8889 ], "771": [ 0, .825, 0, 0, 1.8889 ], "8730": [ 1.25003, 1.75, 0, 0, 1 ], "8968": [ 1.25003, 1.75, 0, 0, .63889 ], "8969": [ 1.25003, 1.75, 0, 0, .63889 ], "8970": [ 1.25003, 1.75, 0, 0, .63889 ], "8971": [ 1.25003, 1.75, 0, 0, .63889 ], "9115": [ .64502, 1.155, 0, 0, .875 ], "9116": [ 1e-5, .6, 0, 0, .875 ], "9117": [ .64502, 1.155, 0, 0, .875 ], "9118": [ .64502, 1.155, 0, 0, .875 ], "9119": [ 1e-5, .6, 0, 0, .875 ], "9120": [ .64502, 1.155, 0, 0, .875 ], "9121": [ .64502, 1.155, 0, 0, .66667 ], "9122": [ -99e-5, .601, 0, 0, .66667 ], "9123": [ .64502, 1.155, 0, 0, .66667 ], "9124": [ .64502, 1.155, 0, 0, .66667 ], "9125": [ -99e-5, .601, 0, 0, .66667 ], "9126": [ .64502, 1.155, 0, 0, .66667 ], "9127": [ 1e-5, .9, 0, 0, .88889 ], "9128": [ .65002, 1.15, 0, 0, .88889 ], "9129": [ .90001, 0, 0, 0, .88889 ], "9130": [ 0, .3, 0, 0, .88889 ], "9131": [ 1e-5, .9, 0, 0, .88889 ], "9132": [ .65002, 1.15, 0, 0, .88889 ], "9133": [ .90001, 0, 0, 0, .88889 ], "9143": [ .88502, .915, 0, 0, 1.05556 ], "10216": [ 1.25003, 1.75, 0, 0, .80556 ], "10217": [ 1.25003, 1.75, 0, 0, .80556 ], "57344": [ -.00499, .605, 0, 0, 1.05556 ], "57345": [ -.00499, .605, 0, 0, 1.05556 ], "57680": [ 0, .12, 0, 0, .45 ], "57681": [ 0, .12, 0, 0, .45 ], "57682": [ 0, .12, 0, 0, .45 ], "57683": [ 0, .12, 0, 0, .45 ] }, "Typewriter-Regular": { "32": [ 0, 0, 0, 0, .525 ], "33": [ 0, .61111, 0, 0, .525 ], "34": [ 0, .61111, 0, 0, .525 ], "35": [ 0, .61111, 0, 0, .525 ], "36": [ .08333, .69444, 0, 0, .525 ], "37": [ .08333, .69444, 0, 0, .525 ], "38": [ 0, .61111, 0, 0, .525 ], "39": [ 0, .61111, 0, 0, .525 ], "40": [ .08333, .69444, 0, 0, .525 ], "41": [ .08333, .69444, 0, 0, .525 ], "42": [ 0, .52083, 0, 0, .525 ], "43": [ -.08056, .53055, 0, 0, .525 ], "44": [ .13889, .125, 0, 0, .525 ], "45": [ -.08056, .53055, 0, 0, .525 ], "46": [ 0, .125, 0, 0, .525 ], "47": [ .08333, .69444, 0, 0, .525 ], "48": [ 0, .61111, 0, 0, .525 ], "49": [ 0, .61111, 0, 0, .525 ], "50": [ 0, .61111, 0, 0, .525 ], "51": [ 0, .61111, 0, 0, .525 ], "52": [ 0, .61111, 0, 0, .525 ], "53": [ 0, .61111, 0, 0, .525 ], "54": [ 0, .61111, 0, 0, .525 ], "55": [ 0, .61111, 0, 0, .525 ], "56": [ 0, .61111, 0, 0, .525 ], "57": [ 0, .61111, 0, 0, .525 ], "58": [ 0, .43056, 0, 0, .525 ], "59": [ .13889, .43056, 0, 0, .525 ], "60": [ -.05556, .55556, 0, 0, .525 ], "61": [ -.19549, .41562, 0, 0, .525 ], "62": [ -.05556, .55556, 0, 0, .525 ], "63": [ 0, .61111, 0, 0, .525 ], "64": [ 0, .61111, 0, 0, .525 ], "65": [ 0, .61111, 0, 0, .525 ], "66": [ 0, .61111, 0, 0, .525 ], "67": [ 0, .61111, 0, 0, .525 ], "68": [ 0, .61111, 0, 0, .525 ], "69": [ 0, .61111, 0, 0, .525 ], "70": [ 0, .61111, 0, 0, .525 ], "71": [ 0, .61111, 0, 0, .525 ], "72": [ 0, .61111, 0, 0, .525 ], "73": [ 0, .61111, 0, 0, .525 ], "74": [ 0, .61111, 0, 0, .525 ], "75": [ 0, .61111, 0, 0, .525 ], "76": [ 0, .61111, 0, 0, .525 ], "77": [ 0, .61111, 0, 0, .525 ], "78": [ 0, .61111, 0, 0, .525 ], "79": [ 0, .61111, 0, 0, .525 ], "80": [ 0, .61111, 0, 0, .525 ], "81": [ .13889, .61111, 0, 0, .525 ], "82": [ 0, .61111, 0, 0, .525 ], "83": [ 0, .61111, 0, 0, .525 ], "84": [ 0, .61111, 0, 0, .525 ], "85": [ 0, .61111, 0, 0, .525 ], "86": [ 0, .61111, 0, 0, .525 ], "87": [ 0, .61111, 0, 0, .525 ], "88": [ 0, .61111, 0, 0, .525 ], "89": [ 0, .61111, 0, 0, .525 ], "90": [ 0, .61111, 0, 0, .525 ], "91": [ .08333, .69444, 0, 0, .525 ], "92": [ .08333, .69444, 0, 0, .525 ], "93": [ .08333, .69444, 0, 0, .525 ], "94": [ 0, .61111, 0, 0, .525 ], "95": [ .09514, 0, 0, 0, .525 ], "96": [ 0, .61111, 0, 0, .525 ], "97": [ 0, .43056, 0, 0, .525 ], "98": [ 0, .61111, 0, 0, .525 ], "99": [ 0, .43056, 0, 0, .525 ], "100": [ 0, .61111, 0, 0, .525 ], "101": [ 0, .43056, 0, 0, .525 ], "102": [ 0, .61111, 0, 0, .525 ], "103": [ .22222, .43056, 0, 0, .525 ], "104": [ 0, .61111, 0, 0, .525 ], "105": [ 0, .61111, 0, 0, .525 ], "106": [ .22222, .61111, 0, 0, .525 ], "107": [ 0, .61111, 0, 0, .525 ], "108": [ 0, .61111, 0, 0, .525 ], "109": [ 0, .43056, 0, 0, .525 ], "110": [ 0, .43056, 0, 0, .525 ], "111": [ 0, .43056, 0, 0, .525 ], "112": [ .22222, .43056, 0, 0, .525 ], "113": [ .22222, .43056, 0, 0, .525 ], "114": [ 0, .43056, 0, 0, .525 ], "115": [ 0, .43056, 0, 0, .525 ], "116": [ 0, .55358, 0, 0, .525 ], "117": [ 0, .43056, 0, 0, .525 ], "118": [ 0, .43056, 0, 0, .525 ], "119": [ 0, .43056, 0, 0, .525 ], "120": [ 0, .43056, 0, 0, .525 ], "121": [ .22222, .43056, 0, 0, .525 ], "122": [ 0, .43056, 0, 0, .525 ], "123": [ .08333, .69444, 0, 0, .525 ], "124": [ .08333, .69444, 0, 0, .525 ], "125": [ .08333, .69444, 0, 0, .525 ], "126": [ 0, .61111, 0, 0, .525 ], "127": [ 0, .61111, 0, 0, .525 ], "160": [ 0, 0, 0, 0, .525 ], "176": [ 0, .61111, 0, 0, .525 ], "184": [ .19445, 0, 0, 0, .525 ], "305": [ 0, .43056, 0, 0, .525 ], "567": [ .22222, .43056, 0, 0, .525 ], "711": [ 0, .56597, 0, 0, .525 ], "713": [ 0, .56555, 0, 0, .525 ], "714": [ 0, .61111, 0, 0, .525 ], "715": [ 0, .61111, 0, 0, .525 ], "728": [ 0, .61111, 0, 0, .525 ], "730": [ 0, .61111, 0, 0, .525 ], "770": [ 0, .61111, 0, 0, .525 ], "771": [ 0, .61111, 0, 0, .525 ], "776": [ 0, .61111, 0, 0, .525 ], "915": [ 0, .61111, 0, 0, .525 ], "916": [ 0, .61111, 0, 0, .525 ], "920": [ 0, .61111, 0, 0, .525 ], "923": [ 0, .61111, 0, 0, .525 ], "926": [ 0, .61111, 0, 0, .525 ], "928": [ 0, .61111, 0, 0, .525 ], "931": [ 0, .61111, 0, 0, .525 ], "933": [ 0, .61111, 0, 0, .525 ], "934": [ 0, .61111, 0, 0, .525 ], "936": [ 0, .61111, 0, 0, .525 ], "937": [ 0, .61111, 0, 0, .525 ], "8216": [ 0, .61111, 0, 0, .525 ], "8217": [ 0, .61111, 0, 0, .525 ], "8242": [ 0, .61111, 0, 0, .525 ], "9251": [ .11111, .21944, 0, 0, .525 ] } }; /** * This file contains metrics regarding fonts and individual symbols. The sigma * and xi variables, as well as the metricMap map contain data extracted from * TeX, TeX font metrics, and the TTF files. These data are then exposed via the * `metrics` variable and the getCharacterMetrics function. */ var sigmasAndXis = { slant: [ .25, .25, .25 ], space: [ 0, 0, 0 ], stretch: [ 0, 0, 0 ], shrink: [ 0, 0, 0 ], xHeight: [ .431, .431, .431 ], quad: [ 1, 1.171, 1.472 ], extraSpace: [ 0, 0, 0 ], num1: [ .677, .732, .925 ], num2: [ .394, .384, .387 ], num3: [ .444, .471, .504 ], denom1: [ .686, .752, 1.025 ], denom2: [ .345, .344, .532 ], sup1: [ .413, .503, .504 ], sup2: [ .363, .431, .404 ], sup3: [ .289, .286, .294 ], sub1: [ .15, .143, .2 ], sub2: [ .247, .286, .4 ], supDrop: [ .386, .353, .494 ], subDrop: [ .05, .071, .1 ], delim1: [ 2.39, 1.7, 1.98 ], delim2: [ 1.01, 1.157, 1.42 ], axisHeight: [ .25, .25, .25 ], defaultRuleThickness: [ .04, .049, .049 ], bigOpSpacing1: [ .111, .111, .111 ], bigOpSpacing2: [ .166, .166, .166 ], bigOpSpacing3: [ .2, .2, .2 ], bigOpSpacing4: [ .6, .611, .611 ], bigOpSpacing5: [ .1, .143, .143 ], sqrtRuleThickness: [ .04, .04, .04 ], ptPerEm: [ 10, 10, 10 ], doubleRuleSep: [ .2, .2, .2 ], arrayRuleWidth: [ .04, .04, .04 ], fboxsep: [ .3, .3, .3 ], fboxrule: [ .04, .04, .04 ] }; var extraCharacterMap = { "Å": "A", "Ð": "D", "Þ": "o", "å": "a", "ð": "d", "þ": "o", "А": "A", "Б": "B", "В": "B", "Г": "F", "Д": "A", "Е": "E", "Ж": "K", "З": "3", "И": "N", "Й": "N", "К": "K", "Л": "N", "М": "M", "Н": "H", "О": "O", "П": "N", "Р": "P", "С": "C", "Т": "T", "У": "y", "Ф": "O", "Х": "X", "Ц": "U", "Ч": "h", "Ш": "W", "Щ": "W", "Ъ": "B", "Ы": "X", "Ь": "B", "Э": "3", "Ю": "X", "Я": "R", "а": "a", "б": "b", "в": "a", "г": "r", "д": "y", "е": "e", "ж": "m", "з": "e", "и": "n", "й": "n", "к": "n", "л": "n", "м": "m", "н": "n", "о": "o", "п": "n", "р": "p", "с": "c", "т": "o", "у": "y", "ф": "b", "х": "x", "ц": "n", "ч": "n", "ш": "w", "щ": "w", "ъ": "a", "ы": "m", "ь": "a", "э": "e", "ю": "m", "я": "r" }; /** * This function adds new font metrics to default metricMap * It can also override existing metrics */ function setFontMetrics(fontName, metrics) { fontMetricsData[fontName] = metrics; } /** * This function is a convenience function for looking up information in the * metricMap table. It takes a character as a string, and a font. * * Note: the `width` property may be undefined if fontMetricsData.js wasn't * built using `Make extended_metrics`. */ function getCharacterMetrics(character, font, mode) { if (!fontMetricsData[font]) throw new Error("Font metrics not found for font: " + font + "."); var ch = character.charCodeAt(0); var metrics = fontMetricsData[font][ch]; if (!metrics && character[0] in extraCharacterMap) { ch = extraCharacterMap[character[0]].charCodeAt(0); metrics = fontMetricsData[font][ch]; } if (!metrics && mode === "text") { if (supportedCodepoint(ch)) metrics = fontMetricsData[font][77]; } if (metrics) return { depth: metrics[0], height: metrics[1], italic: metrics[2], skew: metrics[3], width: metrics[4] }; } var fontMetricsBySizeIndex = {}; /** * Get the font metrics for a given size. */ function getGlobalMetrics(size) { var sizeIndex; if (size >= 5) sizeIndex = 0; else if (size >= 3) sizeIndex = 1; else sizeIndex = 2; if (!fontMetricsBySizeIndex[sizeIndex]) { var metrics = fontMetricsBySizeIndex[sizeIndex] = { cssEmPerMu: sigmasAndXis.quad[sizeIndex] / 18 }; for (var key of Object.keys(sigmasAndXis)) metrics[key] = sigmasAndXis[key][sizeIndex]; } return fontMetricsBySizeIndex[sizeIndex]; } /** * This file holds a list of all no-argument functions and single-character * symbols (like 'a' or ';'). * * For each of the symbols, there are three properties they can have: * - font (required): the font to be used for this symbol. Either "main" (the normal font), or "ams" (the ams fonts). * - group (required): the ParseNode group type the symbol should have (i.e. "textord", "mathord", etc). See https://github.com/KaTeX/KaTeX/wiki/Examining-TeX#group-types * - replace: the character that this symbol or function should be * replaced with (i.e. "\phi" has a replace value of "\u03d5", the phi * character in the main font). * * The outermost map in the table indicates what mode the symbols should be * accepted in (e.g. "math" or "text"). */ var symbols = { "math": {}, "text": {} }; /** `acceptUnicodeChar = true` is only applicable if `replace` is set. */ function defineSymbol(mode, font, group, replace, name, acceptUnicodeChar) { symbols[mode][name] = { font, group, replace }; if (acceptUnicodeChar && replace) symbols[mode][replace] = symbols[mode][name]; } var math = "math"; var text$2 = "text"; var main = "main"; var ams = "ams"; var accent = "accent-token"; var bin = "bin"; var close = "close"; var inner = "inner"; var mathord = "mathord"; var op = "op-token"; var open = "open"; var punct = "punct"; var rel = "rel"; var spacing = "spacing"; var textord = "textord"; defineSymbol(math, main, rel, "≡", "\\equiv", true); defineSymbol(math, main, rel, "≺", "\\prec", true); defineSymbol(math, main, rel, "≻", "\\succ", true); defineSymbol(math, main, rel, "∼", "\\sim", true); defineSymbol(math, main, rel, "⊥", "\\perp"); defineSymbol(math, main, rel, "⪯", "\\preceq", true); defineSymbol(math, main, rel, "⪰", "\\succeq", true); defineSymbol(math, main, rel, "≃", "\\simeq", true); defineSymbol(math, main, rel, "∣", "\\mid", true); defineSymbol(math, main, rel, "≪", "\\ll", true); defineSymbol(math, main, rel, "≫", "\\gg", true); defineSymbol(math, main, rel, "≍", "\\asymp", true); defineSymbol(math, main, rel, "∥", "\\parallel"); defineSymbol(math, main, rel, "⋈", "\\bowtie", true); defineSymbol(math, main, rel, "⌣", "\\smile", true); defineSymbol(math, main, rel, "⊑", "\\sqsubseteq", true); defineSymbol(math, main, rel, "⊒", "\\sqsupseteq", true); defineSymbol(math, main, rel, "≐", "\\doteq", true); defineSymbol(math, main, rel, "⌢", "\\frown", true); defineSymbol(math, main, rel, "∋", "\\ni", true); defineSymbol(math, main, rel, "∝", "\\propto", true); defineSymbol(math, main, rel, "⊢", "\\vdash", true); defineSymbol(math, main, rel, "⊣", "\\dashv", true); defineSymbol(math, main, rel, "∋", "\\owns"); defineSymbol(math, main, punct, ".", "\\ldotp"); defineSymbol(math, main, punct, "⋅", "\\cdotp"); defineSymbol(math, main, punct, "⋅", "·"); defineSymbol(text$2, main, textord, "⋅", "·"); defineSymbol(math, main, textord, "#", "\\#"); defineSymbol(text$2, main, textord, "#", "\\#"); defineSymbol(math, main, textord, "&", "\\&"); defineSymbol(text$2, main, textord, "&", "\\&"); defineSymbol(math, main, textord, "ℵ", "\\aleph", true); defineSymbol(math, main, textord, "∀", "\\forall", true); defineSymbol(math, main, textord, "ℏ", "\\hbar", true); defineSymbol(math, main, textord, "∃", "\\exists", true); defineSymbol(math, main, textord, "∇", "\\nabla", true); defineSymbol(math, main, textord, "♭", "\\flat", true); defineSymbol(math, main, textord, "ℓ", "\\ell", true); defineSymbol(math, main, textord, "♮", "\\natural", true); defineSymbol(math, main, textord, "♣", "\\clubsuit", true); defineSymbol(math, main, textord, "℘", "\\wp", true); defineSymbol(math, main, textord, "♯", "\\sharp", true); defineSymbol(math, main, textord, "♢", "\\diamondsuit", true); defineSymbol(math, main, textord, "ℜ", "\\Re", true); defineSymbol(math, main, textord, "♡", "\\heartsuit", true); defineSymbol(math, main, textord, "ℑ", "\\Im", true); defineSymbol(math, main, textord, "♠", "\\spadesuit", true); defineSymbol(math, main, textord, "§", "\\S", true); defineSymbol(text$2, main, textord, "§", "\\S"); defineSymbol(math, main, textord, "¶", "\\P", true); defineSymbol(text$2, main, textord, "¶", "\\P"); defineSymbol(math, main, textord, "†", "\\dag"); defineSymbol(text$2, main, textord, "†", "\\dag"); defineSymbol(text$2, main, textord, "†", "\\textdagger"); defineSymbol(math, main, textord, "‡", "\\ddag"); defineSymbol(text$2, main, textord, "‡", "\\ddag"); defineSymbol(text$2, main, textord, "‡", "\\textdaggerdbl"); defineSymbol(math, main, close, "⎱", "\\rmoustache", true); defineSymbol(math, main, open, "⎰", "\\lmoustache", true); defineSymbol(math, main, close, "⟯", "\\rgroup", true); defineSymbol(math, main, open, "⟮", "\\lgroup", true); defineSymbol(math, main, bin, "∓", "\\mp", true); defineSymbol(math, main, bin, "⊖", "\\ominus", true); defineSymbol(math, main, bin, "⊎", "\\uplus", true); defineSymbol(math, main, bin, "⊓", "\\sqcap", true); defineSymbol(math, main, bin, "∗", "\\ast"); defineSymbol(math, main, bin, "⊔", "\\sqcup", true); defineSymbol(math, main, bin, "◯", "\\bigcirc", true); defineSymbol(math, main, bin, "∙", "\\bullet", true); defineSymbol(math, main, bin, "‡", "\\ddagger"); defineSymbol(math, main, bin, "≀", "\\wr", true); defineSymbol(math, main, bin, "⨿", "\\amalg"); defineSymbol(math, main, bin, "&", "\\And"); defineSymbol(math, main, rel, "⟵", "\\longleftarrow", true); defineSymbol(math, main, rel, "⇐", "\\Leftarrow", true); defineSymbol(math, main, rel, "⟸", "\\Longleftarrow", true); defineSymbol(math, main, rel, "⟶", "\\longrightarrow", true); defineSymbol(math, main, rel, "⇒", "\\Rightarrow", true); defineSymbol(math, main, rel, "⟹", "\\Longrightarrow", true); defineSymbol(math, main, rel, "↔", "\\leftrightarrow", true); defineSymbol(math, main, rel, "⟷", "\\longleftrightarrow", true); defineSymbol(math, main, rel, "⇔", "\\Leftrightarrow", true); defineSymbol(math, main, rel, "⟺", "\\Longleftrightarrow", true); defineSymbol(math, main, rel, "↦", "\\mapsto", true); defineSymbol(math, main, rel, "⟼", "\\longmapsto", true); defineSymbol(math, main, rel, "↗", "\\nearrow", true); defineSymbol(math, main, rel, "↩", "\\hookleftarrow", true); defineSymbol(math, main, rel, "↪", "\\hookrightarrow", true); defineSymbol(math, main, rel, "↘", "\\searrow", true); defineSymbol(math, main, rel, "↼", "\\leftharpoonup", true); defineSymbol(math, main, rel, "⇀", "\\rightharpoonup", true); defineSymbol(math, main, rel, "↙", "\\swarrow", true); defineSymbol(math, main, rel, "↽", "\\leftharpoondown", true); defineSymbol(math, main, rel, "⇁", "\\rightharpoondown", true); defineSymbol(math, main, rel, "↖", "\\nwarrow", true); defineSymbol(math, main, rel, "⇌", "\\rightleftharpoons", true); defineSymbol(math, ams, rel, "≮", "\\nless", true); defineSymbol(math, ams, rel, "", "\\@nleqslant"); defineSymbol(math, ams, rel, "", "\\@nleqq"); defineSymbol(math, ams, rel, "⪇", "\\lneq", true); defineSymbol(math, ams, rel, "≨", "\\lneqq", true); defineSymbol(math, ams, rel, "", "\\@lvertneqq"); defineSymbol(math, ams, rel, "⋦", "\\lnsim", true); defineSymbol(math, ams, rel, "⪉", "\\lnapprox", true); defineSymbol(math, ams, rel, "⊀", "\\nprec", true); defineSymbol(math, ams, rel, "⋠", "\\npreceq", true); defineSymbol(math, ams, rel, "⋨", "\\precnsim", true); defineSymbol(math, ams, rel, "⪹", "\\precnapprox", true); defineSymbol(math, ams, rel, "≁", "\\nsim", true); defineSymbol(math, ams, rel, "", "\\@nshortmid"); defineSymbol(math, ams, rel, "∤", "\\nmid", true); defineSymbol(math, ams, rel, "⊬", "\\nvdash", true); defineSymbol(math, ams, rel, "⊭", "\\nvDash", true); defineSymbol(math, ams, rel, "⋪", "\\ntriangleleft"); defineSymbol(math, ams, rel, "⋬", "\\ntrianglelefteq", true); defineSymbol(math, ams, rel, "⊊", "\\subsetneq", true); defineSymbol(math, ams, rel, "", "\\@varsubsetneq"); defineSymbol(math, ams, rel, "⫋", "\\subsetneqq", true); defineSymbol(math, ams, rel, "", "\\@varsubsetneqq"); defineSymbol(math, ams, rel, "≯", "\\ngtr", true); defineSymbol(math, ams, rel, "", "\\@ngeqslant"); defineSymbol(math, ams, rel, "", "\\@ngeqq"); defineSymbol(math, ams, rel, "⪈", "\\gneq", true); defineSymbol(math, ams, rel, "≩", "\\gneqq", true); defineSymbol(math, ams, rel, "", "\\@gvertneqq"); defineSymbol(math, ams, rel, "⋧", "\\gnsim", true); defineSymbol(math, ams, rel, "⪊", "\\gnapprox", true); defineSymbol(math, ams, rel, "⊁", "\\nsucc", true); defineSymbol(math, ams, rel, "⋡", "\\nsucceq", true); defineSymbol(math, ams, rel, "⋩", "\\succnsim", true); defineSymbol(math, ams, rel, "⪺", "\\succnapprox", true); defineSymbol(math, ams, rel, "≆", "\\ncong", true); defineSymbol(math, ams, rel, "", "\\@nshortparallel"); defineSymbol(math, ams, rel, "∦", "\\nparallel", true); defineSymbol(math, ams, rel, "⊯", "\\nVDash", true); defineSymbol(math, ams, rel, "⋫", "\\ntriangleright"); defineSymbol(math, ams, rel, "⋭", "\\ntrianglerighteq", true); defineSymbol(math, ams, rel, "", "\\@nsupseteqq"); defineSymbol(math, ams, rel, "⊋", "\\supsetneq", true); defineSymbol(math, ams, rel, "", "\\@varsupsetneq"); defineSymbol(math, ams, rel, "⫌", "\\supsetneqq", true); defineSymbol(math, ams, rel, "", "\\@varsupsetneqq"); defineSymbol(math, ams, rel, "⊮", "\\nVdash", true); defineSymbol(math, ams, rel, "⪵", "\\precneqq", true); defineSymbol(math, ams, rel, "⪶", "\\succneqq", true); defineSymbol(math, ams, rel, "", "\\@nsubseteqq"); defineSymbol(math, ams, bin, "⊴", "\\unlhd"); defineSymbol(math, ams, bin, "⊵", "\\unrhd"); defineSymbol(math, ams, rel, "↚", "\\nleftarrow", true); defineSymbol(math, ams, rel, "↛", "\\nrightarrow", true); defineSymbol(math, ams, rel, "⇍", "\\nLeftarrow", true); defineSymbol(math, ams, rel, "⇏", "\\nRightarrow", true); defineSymbol(math, ams, rel, "↮", "\\nleftrightarrow", true); defineSymbol(math, ams, rel, "⇎", "\\nLeftrightarrow", true); defineSymbol(math, ams, rel, "△", "\\vartriangle"); defineSymbol(math, ams, textord, "ℏ", "\\hslash"); defineSymbol(math, ams, textord, "▽", "\\triangledown"); defineSymbol(math, ams, textord, "◊", "\\lozenge"); defineSymbol(math, ams, textord, "Ⓢ", "\\circledS"); defineSymbol(math, ams, textord, "®", "\\circledR"); defineSymbol(text$2, ams, textord, "®", "\\circledR"); defineSymbol(math, ams, textord, "∡", "\\measuredangle", true); defineSymbol(math, ams, textord, "∄", "\\nexists"); defineSymbol(math, ams, textord, "℧", "\\mho"); defineSymbol(math, ams, textord, "Ⅎ", "\\Finv", true); defineSymbol(math, ams, textord, "⅁", "\\Game", true); defineSymbol(math, ams, textord, "‵", "\\backprime"); defineSymbol(math, ams, textord, "▲", "\\blacktriangle"); defineSymbol(math, ams, textord, "▼", "\\blacktriangledown"); defineSymbol(math, ams, textord, "■", "\\blacksquare"); defineSymbol(math, ams, textord, "⧫", "\\blacklozenge"); defineSymbol(math, ams, textord, "★", "\\bigstar"); defineSymbol(math, ams, textord, "∢", "\\sphericalangle", true); defineSymbol(math, ams, textord, "∁", "\\complement", true); defineSymbol(math, ams, textord, "ð", "\\eth", true); defineSymbol(text$2, main, textord, "ð", "ð"); defineSymbol(math, ams, textord, "╱", "\\diagup"); defineSymbol(math, ams, textord, "╲", "\\diagdown"); defineSymbol(math, ams, textord, "□", "\\square"); defineSymbol(math, ams, textord, "□", "\\Box"); defineSymbol(math, ams, textord, "◊", "\\Diamond"); defineSymbol(math, ams, textord, "¥", "\\yen", true); defineSymbol(text$2, ams, textord, "¥", "\\yen", true); defineSymbol(math, ams, textord, "✓", "\\checkmark", true); defineSymbol(text$2, ams, textord, "✓", "\\checkmark"); defineSymbol(math, ams, textord, "ℶ", "\\beth", true); defineSymbol(math, ams, textord, "ℸ", "\\daleth", true); defineSymbol(math, ams, textord, "ℷ", "\\gimel", true); defineSymbol(math, ams, textord, "ϝ", "\\digamma", true); defineSymbol(math, ams, textord, "ϰ", "\\varkappa"); defineSymbol(math, ams, open, "┌", "\\@ulcorner", true); defineSymbol(math, ams, close, "┐", "\\@urcorner", true); defineSymbol(math, ams, open, "└", "\\@llcorner", true); defineSymbol(math, ams, close, "┘", "\\@lrcorner", true); defineSymbol(math, ams, rel, "≦", "\\leqq", true); defineSymbol(math, ams, rel, "⩽", "\\leqslant", true); defineSymbol(math, ams, rel, "⪕", "\\eqslantless", true); defineSymbol(math, ams, rel, "≲", "\\lesssim", true); defineSymbol(math, ams, rel, "⪅", "\\lessapprox", true); defineSymbol(math, ams, rel, "≊", "\\approxeq", true); defineSymbol(math, ams, bin, "⋖", "\\lessdot"); defineSymbol(math, ams, rel, "⋘", "\\lll", true); defineSymbol(math, ams, rel, "≶", "\\lessgtr", true); defineSymbol(math, ams, rel, "⋚", "\\lesseqgtr", true); defineSymbol(math, ams, rel, "⪋", "\\lesseqqgtr", true); defineSymbol(math, ams, rel, "≑", "\\doteqdot"); defineSymbol(math, ams, rel, "≓", "\\risingdotseq", true); defineSymbol(math, ams, rel, "≒", "\\fallingdotseq", true); defineSymbol(math, ams, rel, "∽", "\\backsim", true); defineSymbol(math, ams, rel, "⋍", "\\backsimeq", true); defineSymbol(math, ams, rel, "⫅", "\\subseteqq", true); defineSymbol(math, ams, rel, "⋐", "\\Subset", true); defineSymbol(math, ams, rel, "⊏", "\\sqsubset", true); defineSymbol(math, ams, rel, "≼", "\\preccurlyeq", true); defineSymbol(math, ams, rel, "⋞", "\\curlyeqprec", true); defineSymbol(math, ams, rel, "≾", "\\precsim", true); defineSymbol(math, ams, rel, "⪷", "\\precapprox", true); defineSymbol(math, ams, rel, "⊲", "\\vartriangleleft"); defineSymbol(math, ams, rel, "⊴", "\\trianglelefteq"); defineSymbol(math, ams, rel, "⊨", "\\vDash", true); defineSymbol(math, ams, rel, "⊪", "\\Vvdash", true); defineSymbol(math, ams, rel, "⌣", "\\smallsmile"); defineSymbol(math, ams, rel, "⌢", "\\smallfrown"); defineSymbol(math, ams, rel, "≏", "\\bumpeq", true); defineSymbol(math, ams, rel, "≎", "\\Bumpeq", true); defineSymbol(math, ams, rel, "≧", "\\geqq", true); defineSymbol(math, ams, rel, "⩾", "\\geqslant", true); defineSymbol(math, ams, rel, "⪖", "\\eqslantgtr", true); defineSymbol(math, ams, rel, "≳", "\\gtrsim", true); defineSymbol(math, ams, rel, "⪆", "\\gtrapprox", true); defineSymbol(math, ams, bin, "⋗", "\\gtrdot"); defineSymbol(math, ams, rel, "⋙", "\\ggg", true); defineSymbol(math, ams, rel, "≷", "\\gtrless", true); defineSymbol(math, ams, rel, "⋛", "\\gtreqless", true); defineSymbol(math, ams, rel, "⪌", "\\gtreqqless", true); defineSymbol(math, ams, rel, "≖", "\\eqcirc", true); defineSymbol(math, ams, rel, "≗", "\\circeq", true); defineSymbol(math, ams, rel, "≜", "\\triangleq", true); defineSymbol(math, ams, rel, "∼", "\\thicksim"); defineSymbol(math, ams, rel, "≈", "\\thickapprox"); defineSymbol(math, ams, rel, "⫆", "\\supseteqq", true); defineSymbol(math, ams, rel, "⋑", "\\Supset", true); defineSymbol(math, ams, rel, "⊐", "\\sqsupset", true); defineSymbol(math, ams, rel, "≽", "\\succcurlyeq", true); defineSymbol(math, ams, rel, "⋟", "\\curlyeqsucc", true); defineSymbol(math, ams, rel, "≿", "\\succsim", true); defineSymbol(math, ams, rel, "⪸", "\\succapprox", true); defineSymbol(math, ams, rel, "⊳", "\\vartriangleright"); defineSymbol(math, ams, rel, "⊵", "\\trianglerighteq"); defineSymbol(math, ams, rel, "⊩", "\\Vdash", true); defineSymbol(math, ams, rel, "∣", "\\shortmid"); defineSymbol(math, ams, rel, "∥", "\\shortparallel"); defineSymbol(math, ams, rel, "≬", "\\between", true); defineSymbol(math, ams, rel, "⋔", "\\pitchfork", true); defineSymbol(math, ams, rel, "∝", "\\varpropto"); defineSymbol(math, ams, rel, "◀", "\\blacktriangleleft"); defineSymbol(math, ams, rel, "∴", "\\therefore", true); defineSymbol(math, ams, rel, "∍", "\\backepsilon"); defineSymbol(math, ams, rel, "▶", "\\blacktriangleright"); defineSymbol(math, ams, rel, "∵", "\\because", true); defineSymbol(math, ams, rel, "⋘", "\\llless"); defineSymbol(math, ams, rel, "⋙", "\\gggtr"); defineSymbol(math, ams, bin, "⊲", "\\lhd"); defineSymbol(math, ams, bin, "⊳", "\\rhd"); defineSymbol(math, ams, rel, "≂", "\\eqsim", true); defineSymbol(math, main, rel, "⋈", "\\Join"); defineSymbol(math, ams, rel, "≑", "\\Doteq", true); defineSymbol(math, ams, bin, "∔", "\\dotplus", true); defineSymbol(math, ams, bin, "∖", "\\smallsetminus"); defineSymbol(math, ams, bin, "⋒", "\\Cap", true); defineSymbol(math, ams, bin, "⋓", "\\Cup", true); defineSymbol(math, ams, bin, "⩞", "\\doublebarwedge", true); defineSymbol(math, ams, bin, "⊟", "\\boxminus", true); defineSymbol(math, ams, bin, "⊞", "\\boxplus", true); defineSymbol(math, ams, bin, "⋇", "\\divideontimes", true); defineSymbol(math, ams, bin, "⋉", "\\ltimes", true); defineSymbol(math, ams, bin, "⋊", "\\rtimes", true); defineSymbol(math, ams, bin, "⋋", "\\leftthreetimes", true); defineSymbol(math, ams, bin, "⋌", "\\rightthreetimes", true); defineSymbol(math, ams, bin, "⋏", "\\curlywedge", true); defineSymbol(math, ams, bin, "⋎", "\\curlyvee", true); defineSymbol(math, ams, bin, "⊝", "\\circleddash", true); defineSymbol(math, ams, bin, "⊛", "\\circledast", true); defineSymbol(math, ams, bin, "⋅", "\\centerdot"); defineSymbol(math, ams, bin, "⊺", "\\intercal", true); defineSymbol(math, ams, bin, "⋒", "\\doublecap"); defineSymbol(math, ams, bin, "⋓", "\\doublecup"); defineSymbol(math, ams, bin, "⊠", "\\boxtimes", true); defineSymbol(math, ams, rel, "⇢", "\\dashrightarrow", true); defineSymbol(math, ams, rel, "⇠", "\\dashleftarrow", true); defineSymbol(math, ams, rel, "⇇", "\\leftleftarrows", true); defineSymbol(math, ams, rel, "⇆", "\\leftrightarrows", true); defineSymbol(math, ams, rel, "⇚", "\\Lleftarrow", true); defineSymbol(math, ams, rel, "↞", "\\twoheadleftarrow", true); defineSymbol(math, ams, rel, "↢", "\\leftarrowtail", true); defineSymbol(math, ams, rel, "↫", "\\looparrowleft", true); defineSymbol(math, ams, rel, "⇋", "\\leftrightharpoons", true); defineSymbol(math, ams, rel, "↶", "\\curvearrowleft", true); defineSymbol(math, ams, rel, "↺", "\\circlearrowleft", true); defineSymbol(math, ams, rel, "↰", "\\Lsh", true); defineSymbol(math, ams, rel, "⇈", "\\upuparrows", true); defineSymbol(math, ams, rel, "↿", "\\upharpoonleft", true); defineSymbol(math, ams, rel, "⇃", "\\downharpoonleft", true); defineSymbol(math, main, rel, "⊶", "\\origof", true); defineSymbol(math, main, rel, "⊷", "\\imageof", true); defineSymbol(math, ams, rel, "⊸", "\\multimap", true); defineSymbol(math, ams, rel, "↭", "\\leftrightsquigarrow", true); defineSymbol(math, ams, rel, "⇉", "\\rightrightarrows", true); defineSymbol(math, ams, rel, "⇄", "\\rightleftarrows", true); defineSymbol(math, ams, rel, "↠", "\\twoheadrightarrow", true); defineSymbol(math, ams, rel, "↣", "\\rightarrowtail", true); defineSymbol(math, ams, rel, "↬", "\\looparrowright", true); defineSymbol(math, ams, rel, "↷", "\\curvearrowright", true); defineSymbol(math, ams, rel, "↻", "\\circlearrowright", true); defineSymbol(math, ams, rel, "↱", "\\Rsh", true); defineSymbol(math, ams, rel, "⇊", "\\downdownarrows", true); defineSymbol(math, ams, rel, "↾", "\\upharpoonright", true); defineSymbol(math, ams, rel, "⇂", "\\downharpoonright", true); defineSymbol(math, ams, rel, "⇝", "\\rightsquigarrow", true); defineSymbol(math, ams, rel, "⇝", "\\leadsto"); defineSymbol(math, ams, rel, "⇛", "\\Rrightarrow", true); defineSymbol(math, ams, rel, "↾", "\\restriction"); defineSymbol(math, main, textord, "‘", "`"); defineSymbol(math, main, textord, "$", "\\$"); defineSymbol(text$2, main, textord, "$", "\\$"); defineSymbol(text$2, main, textord, "$", "\\textdollar"); defineSymbol(math, main, textord, "%", "\\%"); defineSymbol(text$2, main, textord, "%", "\\%"); defineSymbol(math, main, textord, "_", "\\_"); defineSymbol(text$2, main, textord, "_", "\\_"); defineSymbol(text$2, main, textord, "_", "\\textunderscore"); defineSymbol(math, main, textord, "∠", "\\angle", true); defineSymbol(math, main, textord, "∞", "\\infty", true); defineSymbol(math, main, textord, "′", "\\prime"); defineSymbol(math, main, textord, "△", "\\triangle"); defineSymbol(math, main, textord, "Γ", "\\Gamma", true); defineSymbol(math, main, textord, "Δ", "\\Delta", true); defineSymbol(math, main, textord, "Θ", "\\Theta", true); defineSymbol(math, main, textord, "Λ", "\\Lambda", true); defineSymbol(math, main, textord, "Ξ", "\\Xi", true); defineSymbol(math, main, textord, "Π", "\\Pi", true); defineSymbol(math, main, textord, "Σ", "\\Sigma", true); defineSymbol(math, main, textord, "Υ", "\\Upsilon", true); defineSymbol(math, main, textord, "Φ", "\\Phi", true); defineSymbol(math, main, textord, "Ψ", "\\Psi", true); defineSymbol(math, main, textord, "Ω", "\\Omega", true); defineSymbol(math, main, textord, "A", "Α"); defineSymbol(math, main, textord, "B", "Β"); defineSymbol(math, main, textord, "E", "Ε"); defineSymbol(math, main, textord, "Z", "Ζ"); defineSymbol(math, main, textord, "H", "Η"); defineSymbol(math, main, textord, "I", "Ι"); defineSymbol(math, main, textord, "K", "Κ"); defineSymbol(math, main, textord, "M", "Μ"); defineSymbol(math, main, textord, "N", "Ν"); defineSymbol(math, main, textord, "O", "Ο"); defineSymbol(math, main, textord, "P", "Ρ"); defineSymbol(math, main, textord, "T", "Τ"); defineSymbol(math, main, textord, "X", "Χ"); defineSymbol(math, main, textord, "¬", "\\neg", true); defineSymbol(math, main, textord, "¬", "\\lnot"); defineSymbol(math, main, textord, "⊤", "\\top"); defineSymbol(math, main, textord, "⊥", "\\bot"); defineSymbol(math, main, textord, "∅", "\\emptyset"); defineSymbol(math, ams, textord, "∅", "\\varnothing"); defineSymbol(math, main, mathord, "α", "\\alpha", true); defineSymbol(math, main, mathord, "β", "\\beta", true); defineSymbol(math, main, mathord, "γ", "\\gamma", true); defineSymbol(math, main, mathord, "δ", "\\delta", true); defineSymbol(math, main, mathord, "ϵ", "\\epsilon", true); defineSymbol(math, main, mathord, "ζ", "\\zeta", true); defineSymbol(math, main, mathord, "η", "\\eta", true); defineSymbol(math, main, mathord, "θ", "\\theta", true); defineSymbol(math, main, mathord, "ι", "\\iota", true); defineSymbol(math, main, mathord, "κ", "\\kappa", true); defineSymbol(math, main, mathord, "λ", "\\lambda", true); defineSymbol(math, main, mathord, "μ", "\\mu", true); defineSymbol(math, main, mathord, "ν", "\\nu", true); defineSymbol(math, main, mathord, "ξ", "\\xi", true); defineSymbol(math, main, mathord, "ο", "\\omicron", true); defineSymbol(math, main, mathord, "π", "\\pi", true); defineSymbol(math, main, mathord, "ρ", "\\rho", true); defineSymbol(math, main, mathord, "σ", "\\sigma", true); defineSymbol(math, main, mathord, "τ", "\\tau", true); defineSymbol(math, main, mathord, "υ", "\\upsilon", true); defineSymbol(math, main, mathord, "ϕ", "\\phi", true); defineSymbol(math, main, mathord, "χ", "\\chi", true); defineSymbol(math, main, mathord, "ψ", "\\psi", true); defineSymbol(math, main, mathord, "ω", "\\omega", true); defineSymbol(math, main, mathord, "ε", "\\varepsilon", true); defineSymbol(math, main, mathord, "ϑ", "\\vartheta", true); defineSymbol(math, main, mathord, "ϖ", "\\varpi", true); defineSymbol(math, main, mathord, "ϱ", "\\varrho", true); defineSymbol(math, main, mathord, "ς", "\\varsigma", true); defineSymbol(math, main, mathord, "φ", "\\varphi", true); defineSymbol(math, main, bin, "∗", "*", true); defineSymbol(math, main, bin, "+", "+"); defineSymbol(math, main, bin, "−", "-", true); defineSymbol(math, main, bin, "⋅", "\\cdot", true); defineSymbol(math, main, bin, "∘", "\\circ", true); defineSymbol(math, main, bin, "÷", "\\div", true); defineSymbol(math, main, bin, "±", "\\pm", true); defineSymbol(math, main, bin, "×", "\\times", true); defineSymbol(math, main, bin, "∩", "\\cap", true); defineSymbol(math, main, bin, "∪", "\\cup", true); defineSymbol(math, main, bin, "∖", "\\setminus", true); defineSymbol(math, main, bin, "∧", "\\land"); defineSymbol(math, main, bin, "∨", "\\lor"); defineSymbol(math, main, bin, "∧", "\\wedge", true); defineSymbol(math, main, bin, "∨", "\\vee", true); defineSymbol(math, main, textord, "√", "\\surd"); defineSymbol(math, main, open, "⟨", "\\langle", true); defineSymbol(math, main, open, "∣", "\\lvert"); defineSymbol(math, main, open, "∥", "\\lVert"); defineSymbol(math, main, close, "?", "?"); defineSymbol(math, main, close, "!", "!"); defineSymbol(math, main, close, "⟩", "\\rangle", true); defineSymbol(math, main, close, "∣", "\\rvert"); defineSymbol(math, main, close, "∥", "\\rVert"); defineSymbol(math, main, rel, "=", "="); defineSymbol(math, main, rel, ":", ":"); defineSymbol(math, main, rel, "≈", "\\approx", true); defineSymbol(math, main, rel, "≅", "\\cong", true); defineSymbol(math, main, rel, "≥", "\\ge"); defineSymbol(math, main, rel, "≥", "\\geq", true); defineSymbol(math, main, rel, "←", "\\gets"); defineSymbol(math, main, rel, ">", "\\gt", true); defineSymbol(math, main, rel, "∈", "\\in", true); defineSymbol(math, main, rel, "", "\\@not"); defineSymbol(math, main, rel, "⊂", "\\subset", true); defineSymbol(math, main, rel, "⊃", "\\supset", true); defineSymbol(math, main, rel, "⊆", "\\subseteq", true); defineSymbol(math, main, rel, "⊇", "\\supseteq", true); defineSymbol(math, ams, rel, "⊈", "\\nsubseteq", true); defineSymbol(math, ams, rel, "⊉", "\\nsupseteq", true); defineSymbol(math, main, rel, "⊨", "\\models"); defineSymbol(math, main, rel, "←", "\\leftarrow", true); defineSymbol(math, main, rel, "≤", "\\le"); defineSymbol(math, main, rel, "≤", "\\leq", true); defineSymbol(math, main, rel, "<", "\\lt", true); defineSymbol(math, main, rel, "→", "\\rightarrow", true); defineSymbol(math, main, rel, "→", "\\to"); defineSymbol(math, ams, rel, "≱", "\\ngeq", true); defineSymbol(math, ams, rel, "≰", "\\nleq", true); defineSymbol(math, main, spacing, "\xA0", "\\ "); defineSymbol(math, main, spacing, "\xA0", "\\space"); defineSymbol(math, main, spacing, "\xA0", "\\nobreakspace"); defineSymbol(text$2, main, spacing, "\xA0", "\\ "); defineSymbol(text$2, main, spacing, "\xA0", " "); defineSymbol(text$2, main, spacing, "\xA0", "\\space"); defineSymbol(text$2, main, spacing, "\xA0", "\\nobreakspace"); defineSymbol(math, main, spacing, "", "\\nobreak"); defineSymbol(math, main, spacing, "", "\\allowbreak"); defineSymbol(math, main, punct, ",", ","); defineSymbol(math, main, punct, ";", ";"); defineSymbol(math, ams, bin, "⊼", "\\barwedge", true); defineSymbol(math, ams, bin, "⊻", "\\veebar", true); defineSymbol(math, main, bin, "⊙", "\\odot", true); defineSymbol(math, main, bin, "⊕", "\\oplus", true); defineSymbol(math, main, bin, "⊗", "\\otimes", true); defineSymbol(math, main, textord, "∂", "\\partial", true); defineSymbol(math, main, bin, "⊘", "\\oslash", true); defineSymbol(math, ams, bin, "⊚", "\\circledcirc", true); defineSymbol(math, ams, bin, "⊡", "\\boxdot", true); defineSymbol(math, main, bin, "△", "\\bigtriangleup"); defineSymbol(math, main, bin, "▽", "\\bigtriangledown"); defineSymbol(math, main, bin, "†", "\\dagger"); defineSymbol(math, main, bin, "⋄", "\\diamond"); defineSymbol(math, main, bin, "⋆", "\\star"); defineSymbol(math, main, bin, "◃", "\\triangleleft"); defineSymbol(math, main, bin, "▹", "\\triangleright"); defineSymbol(math, main, open, "{", "\\{"); defineSymbol(text$2, main, textord, "{", "\\{"); defineSymbol(text$2, main, textord, "{", "\\textbraceleft"); defineSymbol(math, main, close, "}", "\\}"); defineSymbol(text$2, main, textord, "}", "\\}"); defineSymbol(text$2, main, textord, "}", "\\textbraceright"); defineSymbol(math, main, open, "{", "\\lbrace"); defineSymbol(math, main, close, "}", "\\rbrace"); defineSymbol(math, main, open, "[", "\\lbrack", true); defineSymbol(text$2, main, textord, "[", "\\lbrack", true); defineSymbol(math, main, close, "]", "\\rbrack", true); defineSymbol(text$2, main, textord, "]", "\\rbrack", true); defineSymbol(math, main, open, "(", "\\lparen", true); defineSymbol(math, main, close, ")", "\\rparen", true); defineSymbol(text$2, main, textord, "<", "\\textless", true); defineSymbol(text$2, main, textord, ">", "\\textgreater", true); defineSymbol(math, main, open, "⌊", "\\lfloor", true); defineSymbol(math, main, close, "⌋", "\\rfloor", true); defineSymbol(math, main, open, "⌈", "\\lceil", true); defineSymbol(math, main, close, "⌉", "\\rceil", true); defineSymbol(math, main, textord, "\\", "\\backslash"); defineSymbol(math, main, textord, "∣", "|"); defineSymbol(math, main, textord, "∣", "\\vert"); defineSymbol(text$2, main, textord, "|", "\\textbar", true); defineSymbol(math, main, textord, "∥", "\\|"); defineSymbol(math, main, textord, "∥", "\\Vert"); defineSymbol(text$2, main, textord, "∥", "\\textbardbl"); defineSymbol(text$2, main, textord, "~", "\\textasciitilde"); defineSymbol(text$2, main, textord, "\\", "\\textbackslash"); defineSymbol(text$2, main, textord, "^", "\\textasciicircum"); defineSymbol(math, main, rel, "↑", "\\uparrow", true); defineSymbol(math, main, rel, "⇑", "\\Uparrow", true); defineSymbol(math, main, rel, "↓", "\\downarrow", true); defineSymbol(math, main, rel, "⇓", "\\Downarrow", true); defineSymbol(math, main, rel, "↕", "\\updownarrow", true); defineSymbol(math, main, rel, "⇕", "\\Updownarrow", true); defineSymbol(math, main, op, "∐", "\\coprod"); defineSymbol(math, main, op, "⋁", "\\bigvee"); defineSymbol(math, main, op, "⋀", "\\bigwedge"); defineSymbol(math, main, op, "⨄", "\\biguplus"); defineSymbol(math, main, op, "⋂", "\\bigcap"); defineSymbol(math, main, op, "⋃", "\\bigcup"); defineSymbol(math, main, op, "∫", "\\int"); defineSymbol(math, main, op, "∫", "\\intop"); defineSymbol(math, main, op, "∬", "\\iint"); defineSymbol(math, main, op, "∭", "\\iiint"); defineSymbol(math, main, op, "∏", "\\prod"); defineSymbol(math, main, op, "∑", "\\sum"); defineSymbol(math, main, op, "⨂", "\\bigotimes"); defineSymbol(math, main, op, "⨁", "\\bigoplus"); defineSymbol(math, main, op, "⨀", "\\bigodot"); defineSymbol(math, main, op, "∮", "\\oint"); defineSymbol(math, main, op, "∯", "\\oiint"); defineSymbol(math, main, op, "∰", "\\oiiint"); defineSymbol(math, main, op, "⨆", "\\bigsqcup"); defineSymbol(math, main, op, "∫", "\\smallint"); defineSymbol(text$2, main, inner, "…", "\\textellipsis"); defineSymbol(math, main, inner, "…", "\\mathellipsis"); defineSymbol(text$2, main, inner, "…", "\\ldots", true); defineSymbol(math, main, inner, "…", "\\ldots", true); defineSymbol(math, main, inner, "⋯", "\\@cdots", true); defineSymbol(math, main, inner, "⋱", "\\ddots", true); defineSymbol(math, main, textord, "⋮", "\\varvdots"); defineSymbol(text$2, main, textord, "⋮", "\\varvdots"); defineSymbol(math, main, accent, "ˊ", "\\acute"); defineSymbol(math, main, accent, "ˋ", "\\grave"); defineSymbol(math, main, accent, "¨", "\\ddot"); defineSymbol(math, main, accent, "~", "\\tilde"); defineSymbol(math, main, accent, "ˉ", "\\bar"); defineSymbol(math, main, accent, "˘", "\\breve"); defineSymbol(math, main, accent, "ˇ", "\\check"); defineSymbol(math, main, accent, "^", "\\hat"); defineSymbol(math, main, accent, "⃗", "\\vec"); defineSymbol(math, main, accent, "˙", "\\dot"); defineSymbol(math, main, accent, "˚", "\\mathring"); defineSymbol(math, main, mathord, "", "\\@imath"); defineSymbol(math, main, mathord, "", "\\@jmath"); defineSymbol(math, main, textord, "ı", "ı"); defineSymbol(math, main, textord, "ȷ", "ȷ"); defineSymbol(text$2, main, textord, "ı", "\\i", true); defineSymbol(text$2, main, textord, "ȷ", "\\j", true); defineSymbol(text$2, main, textord, "ß", "\\ss", true); defineSymbol(text$2, main, textord, "æ", "\\ae", true); defineSymbol(text$2, main, textord, "œ", "\\oe", true); defineSymbol(text$2, main, textord, "ø", "\\o", true); defineSymbol(text$2, main, textord, "Æ", "\\AE", true); defineSymbol(text$2, main, textord, "Œ", "\\OE", true); defineSymbol(text$2, main, textord, "Ø", "\\O", true); defineSymbol(text$2, main, accent, "ˊ", "\\'"); defineSymbol(text$2, main, accent, "ˋ", "\\`"); defineSymbol(text$2, main, accent, "ˆ", "\\^"); defineSymbol(text$2, main, accent, "˜", "\\~"); defineSymbol(text$2, main, accent, "ˉ", "\\="); defineSymbol(text$2, main, accent, "˘", "\\u"); defineSymbol(text$2, main, accent, "˙", "\\."); defineSymbol(text$2, main, accent, "¸", "\\c"); defineSymbol(text$2, main, accent, "˚", "\\r"); defineSymbol(text$2, main, accent, "ˇ", "\\v"); defineSymbol(text$2, main, accent, "¨", "\\\""); defineSymbol(text$2, main, accent, "˝", "\\H"); defineSymbol(text$2, main, accent, "◯", "\\textcircled"); var ligatures = { "--": true, "---": true, "``": true, "''": true }; defineSymbol(text$2, main, textord, "–", "--", true); defineSymbol(text$2, main, textord, "–", "\\textendash"); defineSymbol(text$2, main, textord, "—", "---", true); defineSymbol(text$2, main, textord, "—", "\\textemdash"); defineSymbol(text$2, main, textord, "‘", "`", true); defineSymbol(text$2, main, textord, "‘", "\\textquoteleft"); defineSymbol(text$2, main, textord, "’", "'", true); defineSymbol(text$2, main, textord, "’", "\\textquoteright"); defineSymbol(text$2, main, textord, "“", "``", true); defineSymbol(text$2, main, textord, "“", "\\textquotedblleft"); defineSymbol(text$2, main, textord, "”", "''", true); defineSymbol(text$2, main, textord, "”", "\\textquotedblright"); defineSymbol(math, main, textord, "°", "\\degree", true); defineSymbol(text$2, main, textord, "°", "\\degree"); defineSymbol(text$2, main, textord, "°", "\\textdegree", true); defineSymbol(math, main, textord, "£", "\\pounds"); defineSymbol(math, main, textord, "£", "\\mathsterling", true); defineSymbol(text$2, main, textord, "£", "\\pounds"); defineSymbol(text$2, main, textord, "£", "\\textsterling", true); defineSymbol(math, ams, textord, "✠", "\\maltese"); defineSymbol(text$2, ams, textord, "✠", "\\maltese"); var mathTextSymbols = "0123456789/@.\""; for (var i = 0; i < mathTextSymbols.length; i++) { var ch = mathTextSymbols.charAt(i); defineSymbol(math, main, textord, ch, ch); } var textSymbols = "0123456789!@*()-=+\";:?/.,"; for (var _i = 0; _i < textSymbols.length; _i++) { var _ch = textSymbols.charAt(_i); defineSymbol(text$2, main, textord, _ch, _ch); } var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (var _i2 = 0; _i2 < letters.length; _i2++) { var _ch2 = letters.charAt(_i2); defineSymbol(math, main, mathord, _ch2, _ch2); defineSymbol(text$2, main, textord, _ch2, _ch2); } defineSymbol(math, ams, textord, "C", "ℂ"); defineSymbol(text$2, ams, textord, "C", "ℂ"); defineSymbol(math, ams, textord, "H", "ℍ"); defineSymbol(text$2, ams, textord, "H", "ℍ"); defineSymbol(math, ams, textord, "N", "ℕ"); defineSymbol(text$2, ams, textord, "N", "ℕ"); defineSymbol(math, ams, textord, "P", "ℙ"); defineSymbol(text$2, ams, textord, "P", "ℙ"); defineSymbol(math, ams, textord, "Q", "ℚ"); defineSymbol(text$2, ams, textord, "Q", "ℚ"); defineSymbol(math, ams, textord, "R", "ℝ"); defineSymbol(text$2, ams, textord, "R", "ℝ"); defineSymbol(math, ams, textord, "Z", "ℤ"); defineSymbol(text$2, ams, textord, "Z", "ℤ"); defineSymbol(math, main, mathord, "h", "ℎ"); defineSymbol(text$2, main, mathord, "h", "ℎ"); var wideChar; for (var _i3 = 0; _i3 < letters.length; _i3++) { var _ch3 = letters.charAt(_i3); wideChar = String.fromCharCode(55349, 56320 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); wideChar = String.fromCharCode(55349, 56372 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); wideChar = String.fromCharCode(55349, 56424 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); wideChar = String.fromCharCode(55349, 56580 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); wideChar = String.fromCharCode(55349, 56684 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); wideChar = String.fromCharCode(55349, 56736 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); wideChar = String.fromCharCode(55349, 56788 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); wideChar = String.fromCharCode(55349, 56840 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); wideChar = String.fromCharCode(55349, 56944 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); if (_i3 < 26) { wideChar = String.fromCharCode(55349, 56632 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); wideChar = String.fromCharCode(55349, 56476 + _i3); defineSymbol(math, main, mathord, _ch3, wideChar); defineSymbol(text$2, main, textord, _ch3, wideChar); } } wideChar = String.fromCharCode(55349, 56668); defineSymbol(math, main, mathord, "k", wideChar); defineSymbol(text$2, main, textord, "k", wideChar); for (var _i4 = 0; _i4 < 10; _i4++) { var _ch4 = _i4.toString(); wideChar = String.fromCharCode(55349, 57294 + _i4); defineSymbol(math, main, mathord, _ch4, wideChar); defineSymbol(text$2, main, textord, _ch4, wideChar); wideChar = String.fromCharCode(55349, 57314 + _i4); defineSymbol(math, main, mathord, _ch4, wideChar); defineSymbol(text$2, main, textord, _ch4, wideChar); wideChar = String.fromCharCode(55349, 57324 + _i4); defineSymbol(math, main, mathord, _ch4, wideChar); defineSymbol(text$2, main, textord, _ch4, wideChar); wideChar = String.fromCharCode(55349, 57334 + _i4); defineSymbol(math, main, mathord, _ch4, wideChar); defineSymbol(text$2, main, textord, _ch4, wideChar); } var extraLatin = "ÐÞþ"; for (var _i5 = 0; _i5 < extraLatin.length; _i5++) { var _ch5 = extraLatin.charAt(_i5); defineSymbol(math, main, mathord, _ch5, _ch5); defineSymbol(text$2, main, textord, _ch5, _ch5); } /** * This file provides support for Unicode range U+1D400 to U+1D7FF, * Mathematical Alphanumeric Symbols. * * Function wideCharacterFont takes a wide character as input and returns * the font information necessary to render it properly. */ var boldUpright = { mathClass: "mathbf", textClass: "textbf", font: "Main-Bold" }; var italic = { mathClass: "mathnormal", textClass: "textit", font: "Math-Italic" }; var boldItalic = { mathClass: "boldsymbol", textClass: "boldsymbol", font: "Main-BoldItalic" }; var script = { mathClass: "mathscr", textClass: "textscr", font: "Script-Regular" }; var noFont = { mathClass: "", textClass: "", font: "" }; var fraktur = { mathClass: "mathfrak", textClass: "textfrak", font: "Fraktur-Regular" }; var doubleStruck = { mathClass: "mathbb", textClass: "textbb", font: "AMS-Regular" }; var boldFraktur = { mathClass: "mathboldfrak", textClass: "textboldfrak", font: "Fraktur-Regular" }; var sansSerif = { mathClass: "mathsf", textClass: "textsf", font: "SansSerif-Regular" }; var boldSansSerif = { mathClass: "mathboldsf", textClass: "textboldsf", font: "SansSerif-Bold" }; var italicSansSerif = { mathClass: "mathitsf", textClass: "textitsf", font: "SansSerif-Italic" }; var monospace = { mathClass: "mathtt", textClass: "texttt", font: "Typewriter-Regular" }; /** * Data below is from https://www.unicode.org/charts/PDF/U1D400.pdf * That document sorts characters into groups by font type, say bold or italic. * * In the arrays below, each object consists of three properties: * * The CSS class of that group when in math mode. * * The CSS class of that group when in text mode. * * The font name, so that KaTeX can get font metrics. */ var wideLatinLetterData = [ boldUpright, boldUpright, italic, italic, boldItalic, boldItalic, script, noFont, noFont, noFont, fraktur, fraktur, doubleStruck, doubleStruck, boldFraktur, boldFraktur, sansSerif, sansSerif, boldSansSerif, boldSansSerif, italicSansSerif, italicSansSerif, noFont, noFont, monospace, monospace ]; var wideNumeralData = [ boldUpright, noFont, sansSerif, boldSansSerif, monospace ]; var wideCharacterFont = (wideChar) => { var H = wideChar.charCodeAt(0); var L = wideChar.charCodeAt(1); var codePoint = (H - 55296) * 1024 + (L - 56320) + 65536; if (119808 <= codePoint && codePoint < 120484) return wideLatinLetterData[Math.floor((codePoint - 119808) / 26)]; else if (120782 <= codePoint && codePoint <= 120831) return wideNumeralData[Math.floor((codePoint - 120782) / 10)]; else if (codePoint === 120485 || codePoint === 120486) return wideLatinLetterData[0]; else if (120486 < codePoint && codePoint < 120782) return noFont; else throw new ParseError("Unsupported character: " + wideChar); }; function handleStrict(params) { var strict = params.strict, errorCode = params.errorCode, errorMsg = params.errorMsg, token = params.token, report = params.report; var behavior = strict; if (typeof strict === "function") { if (report) behavior = strict(errorCode, errorMsg, token); else try { behavior = strict(errorCode, errorMsg, token); } catch (error) { behavior = "error"; } } switch (behavior) { case true: case "error": if (report) throw new ParseError("LaTeX-incompatible input and strict mode is set to 'error': " + (errorMsg + " [" + errorCode + "]"), token); else return true; case false: case "ignore": if (!report) return false; break; default: typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to 'warn': " + (errorMsg + " [" + errorCode + "]")); if (!report) return false; } } /** * This module contains general functions that can be used for building * different kinds of domTree nodes in a consistent manner. */ /** * Looks up the given symbol in fontMetrics, after applying any symbol * replacements defined in symbol.js */ var lookupSymbol = function lookupSymbol(value, fontName, mode) { if (symbols[mode][value]) { var replacement = symbols[mode][value].replace; if (replacement) value = replacement; } return { value, metrics: getCharacterMetrics(value, fontName, mode) }; }; /** * Makes a symbolNode after translation via the list of symbols in symbols.js. * Correctly pulls out metrics for the character, and optionally takes a list of * classes to be attached to the node. * * TODO: make argument order closer to makeSpan * TODO: add a separate argument for math class (e.g. `mop`, `mbin`), which * should if present come first in `classes`. */ var makeSymbol = function makeSymbol(value, fontName, mode, options, classes) { var lookup = lookupSymbol(value, fontName, mode); var metrics = lookup.metrics; value = lookup.value; var symbolNode; if (metrics) { var italic = metrics.italic; if (mode === "text" || options && options.font === "mathit") italic = 0; symbolNode = new SymbolNode(value, metrics.height, metrics.depth, italic, metrics.skew, metrics.width, classes); } else { handleStrict({ strict: options.strict, errorCode: "symbolNotInFont", errorMsg: "No character metrics for '" + value + "' in style '" + fontName + "' and mode '" + mode + "'", report: true }); symbolNode = new SymbolNode(value, 0, 0, 0, 0, 0, classes); } symbolNode.maxFontSize = options.sizeMultiplier; if (options.style.isTight()) symbolNode.classes.push("mtight"); var color = options.getColor(); if (color) symbolNode.style.color = color; return symbolNode; }; /** * Makes a symbol in Main-Regular or AMS-Regular. * Used for rel, bin, open, close, inner, and punct. */ var mathsym = function mathsym(value, mode, options, classes) { if (classes === void 0) classes = []; if (options.font === "boldsymbol" && lookupSymbol(value, "Main-Bold", mode).metrics) return makeSymbol(value, "Main-Bold", mode, options, classes.concat(["mathbf"])); else if (value === "\\" || symbols[mode][value].font === "main") return makeSymbol(value, "Main-Regular", mode, options, classes); else return makeSymbol(value, "AMS-Regular", mode, options, classes.concat(["amsrm"])); }; /** * Determines which of the two font names (Main-Bold and Math-BoldItalic) and * corresponding style tags (mathbf or boldsymbol) to use for font "boldsymbol", * depending on the symbol. Use this function instead of fontMap for font * "boldsymbol". */ var boldSymbol = function boldSymbol(value, mode, type) { if (type !== "textord" && lookupSymbol(value, "Math-BoldItalic", mode).metrics) return { fontName: "Math-BoldItalic", fontClass: "boldsymbol" }; else return { fontName: "Main-Bold", fontClass: "mathbf" }; }; /** * Makes either a mathord or textord in the correct font and color. */ var makeOrd = function makeOrd(group, options) { var type = group.type === "mathord" ? "mathord" : "textord"; var mode = group.mode; var text = group.text; var classes = ["mord"]; var font = options.font, fontFamily = options.fontFamily, fontWeight = options.fontWeight, fontShape = options.fontShape; var useFont = mode === "math" || mode === "text" && !!font; var fontOrFamily = useFont ? font : fontFamily; var wideFontName = ""; var wideFontClass = ""; if (text.charCodeAt(0) === 55349) { var wideCharData = wideCharacterFont(text); wideFontName = wideCharData.font; wideFontClass = wideCharData[mode + "Class"]; } if (wideFontName) return makeSymbol(text, wideFontName, mode, options, classes.concat(wideFontClass)); else if (fontOrFamily) { var fontName; var fontClasses; if (fontOrFamily === "boldsymbol") { var fontData = boldSymbol(text, mode, type); fontName = fontData.fontName; fontClasses = [fontData.fontClass]; } else if (useFont) { fontName = fontMap[font].fontName; fontClasses = [font]; } else { fontName = retrieveTextFontName(fontFamily, fontWeight, fontShape); fontClasses = [ fontFamily, fontWeight, fontShape ]; } if (lookupSymbol(text, fontName, mode).metrics) return makeSymbol(text, fontName, mode, options, classes.concat(fontClasses)); else if (Object.prototype.hasOwnProperty.call(ligatures, text) && fontName.slice(0, 10) === "Typewriter") { var parts = []; for (var i = 0; i < text.length; i++) parts.push(makeSymbol(text[i], fontName, mode, options, classes.concat(fontClasses))); return makeFragment(parts); } } if (type === "mathord") return makeSymbol(text, "Math-Italic", mode, options, classes.concat(["mathnormal"])); else if (type === "textord") { var _font = symbols[mode][text] && symbols[mode][text].font; if (_font === "ams") return makeSymbol(text, retrieveTextFontName("amsrm", fontWeight, fontShape), mode, options, classes.concat("amsrm", fontWeight, fontShape)); else if (_font === "main" || !_font) return makeSymbol(text, retrieveTextFontName("textrm", fontWeight, fontShape), mode, options, classes.concat(fontWeight, fontShape)); else { var _fontName3 = retrieveTextFontName(_font, fontWeight, fontShape); return makeSymbol(text, _fontName3, mode, options, classes.concat(_fontName3, fontWeight, fontShape)); } } else throw new Error("unexpected type: " + type + " in makeOrd"); }; /** * Returns true if subsequent symbolNodes have the same classes, skew, maxFont, * and styles. For mathnormal text, the left node must also have zero italic * correction so we don't lose spacing between combined glyphs. */ var canCombine = (prev, next) => { if (createClass(prev.classes) !== createClass(next.classes) || prev.skew !== next.skew || prev.maxFontSize !== next.maxFontSize || prev.italic !== 0 && prev.hasClass("mathnormal")) return false; if (prev.classes.length === 1) { var cls = prev.classes[0]; if (cls === "mbin" || cls === "mord") return false; } for (var key of Object.keys(prev.style)) if (prev.style[key] !== next.style[key]) return false; for (var _key of Object.keys(next.style)) if (prev.style[_key] !== next.style[_key]) return false; return true; }; /** * Combine consecutive domTree.symbolNodes into a single symbolNode. * Note: this function mutates the argument. */ var tryCombineChars = (chars) => { for (var i = 0; i < chars.length - 1; i++) { var prev = chars[i]; var next = chars[i + 1]; if (prev instanceof SymbolNode && next instanceof SymbolNode && canCombine(prev, next)) { prev.text += next.text; prev.height = Math.max(prev.height, next.height); prev.depth = Math.max(prev.depth, next.depth); prev.italic = next.italic; chars.splice(i + 1, 1); i--; } } return chars; }; /** * Calculate the height, depth, and maxFontSize of an element based on its * children. */ var sizeElementFromChildren = function sizeElementFromChildren(elem) { var height = 0; var depth = 0; var maxFontSize = 0; for (var i = 0; i < elem.children.length; i++) { var child = elem.children[i]; if (child.height > height) height = child.height; if (child.depth > depth) depth = child.depth; if (child.maxFontSize > maxFontSize) maxFontSize = child.maxFontSize; } elem.height = height; elem.depth = depth; elem.maxFontSize = maxFontSize; }; /** * Makes a span with the given list of classes, list of children, and options. * * TODO(#953): Ensure that `options` is always provided (currently some call * sites don't pass it) and make the type below mandatory. * TODO: add a separate argument for math class (e.g. `mop`, `mbin`), which * should if present come first in `classes`. */ var makeSpan = function makeSpan(classes, children, options, style) { var span = new Span(classes, children, options, style); sizeElementFromChildren(span); return span; }; var makeSvgSpan = (classes, children, options, style) => new Span(classes, children, options, style); var makeLineSpan = function makeLineSpan(className, options, thickness) { var line = makeSpan([className], [], options); line.height = Math.max(thickness || options.fontMetrics().defaultRuleThickness, options.minRuleThickness); line.style.borderBottomWidth = makeEm(line.height); line.maxFontSize = 1; return line; }; /** * Makes an anchor with the given href, list of classes, list of children, * and options. */ var makeAnchor = function makeAnchor(href, classes, children, options) { var anchor = new Anchor(href, classes, children, options); sizeElementFromChildren(anchor); return anchor; }; /** * Makes a document fragment with the given list of children. */ var makeFragment = function makeFragment(children) { var fragment = new DocumentFragment(children); sizeElementFromChildren(fragment); return fragment; }; /** * Wraps group in a span if it's a document fragment, allowing to apply classes * and styles */ var wrapFragment = function wrapFragment(group, options) { if (group instanceof DocumentFragment) return makeSpan([], [group], options); return group; }; var getVListChildrenAndDepth = function getVListChildrenAndDepth(params) { if (params.positionType === "individualShift") { var oldChildren = params.children; var children = [oldChildren[0]]; var _depth = -oldChildren[0].shift - oldChildren[0].elem.depth; var currPos = _depth; for (var i = 1; i < oldChildren.length; i++) { var diff = -oldChildren[i].shift - currPos - oldChildren[i].elem.depth; var size = diff - (oldChildren[i - 1].elem.height + oldChildren[i - 1].elem.depth); currPos = currPos + diff; children.push({ type: "kern", size }); children.push(oldChildren[i]); } return { children, depth: _depth }; } var depth; if (params.positionType === "top") { var bottom = params.positionData; for (var _i = 0; _i < params.children.length; _i++) { var child = params.children[_i]; bottom -= child.type === "kern" ? child.size : child.elem.height + child.elem.depth; } depth = bottom; } else if (params.positionType === "bottom") depth = -params.positionData; else { var firstChild = params.children[0]; if (firstChild.type !== "elem") throw new Error("First child must have type \"elem\"."); if (params.positionType === "shift") depth = -firstChild.elem.depth - params.positionData; else if (params.positionType === "firstBaseline") depth = -firstChild.elem.depth; else throw new Error("Invalid positionType " + params.positionType + "."); } return { children: params.children, depth }; }; /** * Makes a vertical list by stacking elements and kerns on top of each other. * Allows for many different ways of specifying the positioning method. * * See VListParam documentation above. */ var makeVList = function makeVList(params, options) { var _getVListChildrenAndD = getVListChildrenAndDepth(params), children = _getVListChildrenAndD.children, depth = _getVListChildrenAndD.depth; var pstrutSize = 0; for (var i = 0; i < children.length; i++) { var child = children[i]; if (child.type === "elem") { var elem = child.elem; pstrutSize = Math.max(pstrutSize, elem.maxFontSize, elem.height); } } pstrutSize += 2; var pstrut = makeSpan(["pstrut"], []); pstrut.style.height = makeEm(pstrutSize); var realChildren = []; var minPos = depth; var maxPos = depth; var currPos = depth; for (var _i2 = 0; _i2 < children.length; _i2++) { var _child = children[_i2]; if (_child.type === "kern") currPos += _child.size; else { var _elem = _child.elem; var classes = _child.wrapperClasses || []; var style = _child.wrapperStyle || {}; var childWrap = makeSpan(classes, [pstrut, _elem], void 0, style); childWrap.style.top = makeEm(-pstrutSize - currPos - _elem.depth); if (_child.marginLeft) childWrap.style.marginLeft = _child.marginLeft; if (_child.marginRight) childWrap.style.marginRight = _child.marginRight; realChildren.push(childWrap); currPos += _elem.height + _elem.depth; } minPos = Math.min(minPos, currPos); maxPos = Math.max(maxPos, currPos); } var vlist = makeSpan(["vlist"], realChildren); vlist.style.height = makeEm(maxPos); var rows; if (minPos < 0) { var depthStrut = makeSpan(["vlist"], [makeSpan([], [])]); depthStrut.style.height = makeEm(-minPos); rows = [makeSpan(["vlist-r"], [vlist, makeSpan(["vlist-s"], [new SymbolNode("​")])]), makeSpan(["vlist-r"], [depthStrut])]; } else rows = [makeSpan(["vlist-r"], [vlist])]; var vtable = makeSpan(["vlist-t"], rows); if (rows.length === 2) vtable.classes.push("vlist-t2"); vtable.height = maxPos; vtable.depth = -minPos; return vtable; }; var makeGlue = (measurement, options) => { var rule = makeSpan(["mspace"], [], options); var size = calculateSize(measurement, options); rule.style.marginRight = makeEm(size); return rule; }; var retrieveTextFontName = (fontFamily, fontWeight, fontShape) => { var baseFontName; var fontStylesName; switch (fontFamily) { case "amsrm": baseFontName = "AMS"; break; case "textrm": baseFontName = "Main"; break; case "textsf": baseFontName = "SansSerif"; break; case "texttt": baseFontName = "Typewriter"; break; default: baseFontName = fontFamily; } if (fontWeight === "textbf" && fontShape === "textit") fontStylesName = "BoldItalic"; else if (fontWeight === "textbf") fontStylesName = "Bold"; else if (fontShape === "textit") fontStylesName = "Italic"; else fontStylesName = "Regular"; return baseFontName + "-" + fontStylesName; }; /** * Maps TeX font commands to objects containing: * - variant: string used for "mathvariant" attribute in buildMathML.js * - fontName: the "style" parameter to fontMetrics.getCharacterMetrics */ var fontMap = { "mathbf": { variant: "bold", fontName: "Main-Bold" }, "mathrm": { variant: "normal", fontName: "Main-Regular" }, "textit": { variant: "italic", fontName: "Main-Italic" }, "mathit": { variant: "italic", fontName: "Main-Italic" }, "mathnormal": { variant: "italic", fontName: "Math-Italic" }, "mathsfit": { variant: "sans-serif-italic", fontName: "SansSerif-Italic" }, "mathbb": { variant: "double-struck", fontName: "AMS-Regular" }, "mathcal": { variant: "script", fontName: "Caligraphic-Regular" }, "mathfrak": { variant: "fraktur", fontName: "Fraktur-Regular" }, "mathscr": { variant: "script", fontName: "Script-Regular" }, "mathsf": { variant: "sans-serif", fontName: "SansSerif-Regular" }, "mathtt": { variant: "monospace", fontName: "Typewriter-Regular" } }; var svgData = { vec: [ "vec", .471, .714 ], oiintSize1: [ "oiintSize1", .957, .499 ], oiintSize2: [ "oiintSize2", 1.472, .659 ], oiiintSize1: [ "oiiintSize1", 1.304, .499 ], oiiintSize2: [ "oiiintSize2", 1.98, .659 ] }; var staticSvg = function staticSvg(value, options) { var _svgData$value = svgData[value], pathName = _svgData$value[0], width = _svgData$value[1], height = _svgData$value[2]; var span = makeSvgSpan(["katex-overlay"], [new SvgNode([new PathNode(pathName)], { "width": makeEm(width), "height": makeEm(height), "style": "width:" + makeEm(width), "viewBox": "0 0 " + 1e3 * width + " " + 1e3 * height, "preserveAspectRatio": "xMinYMin" })], options); span.height = height; span.style.height = makeEm(height); span.style.width = makeEm(width); return span; }; /** * Describes spaces between different classes of atoms. */ var thinspace = { number: 3, unit: "mu" }; var mediumspace = { number: 4, unit: "mu" }; var thickspace = { number: 5, unit: "mu" }; var spacings = { mord: { mop: thinspace, mbin: mediumspace, mrel: thickspace, minner: thinspace }, mop: { mord: thinspace, mop: thinspace, mrel: thickspace, minner: thinspace }, mbin: { mord: mediumspace, mop: mediumspace, mopen: mediumspace, minner: mediumspace }, mrel: { mord: thickspace, mop: thickspace, mopen: thickspace, minner: thickspace }, mopen: {}, mclose: { mop: thinspace, mbin: mediumspace, mrel: thickspace, minner: thinspace }, mpunct: { mord: thinspace, mop: thinspace, mrel: thickspace, mopen: thinspace, mclose: thinspace, mpunct: thinspace, minner: thinspace }, minner: { mord: thinspace, mop: thinspace, mbin: mediumspace, mrel: thickspace, mopen: thinspace, mpunct: thinspace, minner: thinspace } }; var tightSpacings = { mord: { mop: thinspace }, mop: { mord: thinspace, mop: thinspace }, mbin: {}, mrel: {}, mopen: {}, mclose: { mop: thinspace }, mpunct: {}, minner: { mop: thinspace } }; /** * All registered functions. * `functions.js` just exports this same dictionary again and makes it public. * `Parser.js` requires this dictionary. */ var _functions = {}; /** * All HTML builders. Should be only used in the `define*` and the `build*ML` * functions. * * Builders for different node types are stored side by side, but * `HtmlBuilder<T>` is contravariant in `T`, so there is no single type * argument that makes storing/retrieving them typecheck. `any` is used * as an existential-quantifier escape hatch. */ var _htmlGroupBuilders = {}; /** * All MathML builders. Should be only used in the `define*` and the `build*ML` * functions. See `_htmlGroupBuilders` above for the rationale behind `any`. */ var _mathmlGroupBuilders = {}; function defineFunction(data) { var type = data.type, names = data.names, htmlBuilder = data.htmlBuilder, mathmlBuilder = data.mathmlBuilder; for (var i = 0; i < names.length; ++i) _functions[names[i]] = data; if (type) { if (htmlBuilder) _htmlGroupBuilders[type] = htmlBuilder; if (mathmlBuilder) _mathmlGroupBuilders[type] = mathmlBuilder; } } /** * Use this to register only the HTML and MathML builders for a function (e.g. * if the function's ParseNode is generated in Parser.js rather than via a * stand-alone handler provided to `defineFunction`). */ function defineFunctionBuilders(_ref) { var type = _ref.type, htmlBuilder = _ref.htmlBuilder, mathmlBuilder = _ref.mathmlBuilder; if (htmlBuilder) _htmlGroupBuilders[type] = htmlBuilder; if (mathmlBuilder) _mathmlGroupBuilders[type] = mathmlBuilder; } var normalizeArgument = function normalizeArgument(arg) { return arg.type === "ordgroup" && arg.body.length === 1 ? arg.body[0] : arg; }; var ordargument = function ordargument(arg) { return arg.type === "ordgroup" ? arg.body : [arg]; }; /** * This file does the main work of building a domTree structure from a parse * tree. The entry point is the `buildHTML` function, which takes a parse tree. * Then, the buildExpression, buildGroup, and various groupBuilders functions * are called, to produce a final HTML tree. */ var binLeftCanceller = /* @__PURE__ */ new Set([ "leftmost", "mbin", "mopen", "mrel", "mop", "mpunct" ]); var binRightCanceller = /* @__PURE__ */ new Set([ "rightmost", "mrel", "mclose", "mpunct" ]); var styleMap$1 = { "display": Style$1.DISPLAY, "text": Style$1.TEXT, "script": Style$1.SCRIPT, "scriptscript": Style$1.SCRIPTSCRIPT }; var DomEnum = { mord: "mord", mop: "mop", mbin: "mbin", mrel: "mrel", mopen: "mopen", mclose: "mclose", mpunct: "mpunct", minner: "minner" }; /** * Take a list of nodes, build them in order, and return a list of the built * nodes. documentFragments are flattened into their contents, so the * returned list contains no fragments. `isRealGroup` is true if `expression` * is a real group (no atoms will be added on either side), as opposed to * a partial group (e.g. one created by \color). `surrounding` is an array * consisting type of nodes that will be added to the left and right. */ var buildExpression$1 = function buildExpression(expression, options, isRealGroup, surrounding) { if (surrounding === void 0) surrounding = [null, null]; var groups = []; for (var i = 0; i < expression.length; i++) { var output = buildGroup$1(expression[i], options); if (output instanceof DocumentFragment) { var children = output.children; groups.push(...children); } else groups.push(output); } tryCombineChars(groups); if (!isRealGroup) return groups; var glueOptions = options; if (expression.length === 1) { var node = expression[0]; if (node.type === "sizing") glueOptions = options.havingSize(node.size); else if (node.type === "styling") glueOptions = options.havingStyle(styleMap$1[node.style]); } var dummyPrev = makeSpan([surrounding[0] || "leftmost"], [], options); var dummyNext = makeSpan([surrounding[1] || "rightmost"], [], options); var isRoot = isRealGroup === "root"; _traverseNonSpaceNodes(groups, (node, prev) => { var prevType = prev.classes[0]; var type = node.classes[0]; if (prevType === "mbin" && binRightCanceller.has(type)) prev.classes[0] = "mord"; else if (type === "mbin" && binLeftCanceller.has(prevType)) node.classes[0] = "mord"; }, { node: dummyPrev }, dummyNext, isRoot); _traverseNonSpaceNodes(groups, (node, prev) => { var _tightSpacings$prevTy, _spacings$prevType; var prevType = getTypeOfDomTree(prev); var type = getTypeOfDomTree(node); var space = prevType && type ? node.hasClass("mtight") ? (_tightSpacings$prevTy = tightSpacings[prevType]) == null ? void 0 : _tightSpacings$prevTy[type] : (_spacings$prevType = spacings[prevType]) == null ? void 0 : _spacings$prevType[type] : null; if (space) return makeGlue(space, glueOptions); }, { node: dummyPrev }, dummyNext, isRoot); return groups; }; var _traverseNonSpaceNodes = function traverseNonSpaceNodes(nodes, callback, prev, next, isRoot) { if (next) nodes.push(next); var i = 0; for (; i < nodes.length; i++) { var node = nodes[i]; var partialGroup = checkPartialGroup(node); if (partialGroup) { _traverseNonSpaceNodes(partialGroup.children, callback, prev, null, isRoot); continue; } var nonspace = !node.hasClass("mspace"); if (nonspace) { var result = callback(node, prev.node); if (result) { if (prev.insertAfter) prev.insertAfter(result); else { nodes.unshift(result); i++; } } } if (nonspace) prev.node = node; else if (isRoot && node.hasClass("katex-newline")) prev.node = makeSpan(["leftmost"]); prev.insertAfter = ((index) => (n) => { nodes.splice(index + 1, 0, n); i++; })(i); } if (next) nodes.pop(); }; var checkPartialGroup = function checkPartialGroup(node) { if (node instanceof DocumentFragment || node instanceof Anchor || node instanceof Span && node.hasClass("enclosing")) return node; return null; }; var _getOutermostNode = function getOutermostNode(node, side) { var partialGroup = checkPartialGroup(node); if (partialGroup) { var children = partialGroup.children; if (children.length) { if (side === "right") return _getOutermostNode(children[children.length - 1], "right"); else if (side === "left") return _getOutermostNode(children[0], "left"); } } return node; }; var getTypeOfDomTree = function getTypeOfDomTree(node, side) { if (!node) return null; if (side) node = _getOutermostNode(node, side); return DomEnum[node.classes[0]] || null; }; var makeNullDelimiter = function makeNullDelimiter(options, classes) { var moreClasses = ["nulldelimiter"].concat(options.baseSizingClasses()); return makeSpan(classes.concat(moreClasses)); }; /** * buildGroup is the function that takes a group and calls the correct groupType * function for it. It also handles the interaction of size and style changes * between parents and children. */ var buildGroup$1 = function buildGroup(group, options, baseOptions) { if (!group) return makeSpan(); if (_htmlGroupBuilders[group.type]) { var groupNode = _htmlGroupBuilders[group.type](group, options); if (baseOptions && options.size !== baseOptions.size) { groupNode = makeSpan(options.sizingClasses(baseOptions), [groupNode], options); var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier; groupNode.height *= multiplier; groupNode.depth *= multiplier; } return groupNode; } else throw new ParseError("Got group of unknown type: '" + group.type + "'"); }; /** * Combine an array of HTML DOM nodes (e.g., the output of `buildExpression`) * into an unbreakable HTML node of class .katex-base, with proper struts to * guarantee correct vertical extent. `buildHTML` calls this repeatedly to * make up the entire expression as a sequence of unbreakable units. */ function buildHTMLUnbreakable(children, options) { var body = makeSpan(["katex-base"], children, options); var strut = makeSpan(["katex-strut"]); strut.style.height = makeEm(body.height + body.depth); if (body.depth) strut.style.verticalAlign = makeEm(-body.depth); body.children.unshift(strut); return body; } /** * Take an entire parse tree, and build it into an appropriate set of HTML * nodes. */ function buildHTML(tree, options) { var tag = null; if (tree.length === 1 && tree[0].type === "tag") { tag = tree[0].tag; tree = tree[0].body; } var expression = buildExpression$1(tree, options, "root"); var eqnNum; if (expression.length === 2 && expression[1].hasClass("katex-tag")) eqnNum = expression.pop(); var children = []; var parts = []; for (var i = 0; i < expression.length; i++) { parts.push(expression[i]); if (expression[i].hasClass("mbin") || expression[i].hasClass("mrel") || expression[i].hasClass("allowbreak")) { var nobreak = false; while (i < expression.length - 1 && expression[i + 1].hasClass("mspace") && !expression[i + 1].hasClass("katex-newline")) { i++; parts.push(expression[i]); if (expression[i].hasClass("nobreak")) nobreak = true; } if (!nobreak) { children.push(buildHTMLUnbreakable(parts, options)); parts = []; } } else if (expression[i].hasClass("katex-newline")) { parts.pop(); if (parts.length > 0) { children.push(buildHTMLUnbreakable(parts, options)); parts = []; } children.push(expression[i]); } } if (parts.length > 0) children.push(buildHTMLUnbreakable(parts, options)); var tagChild; if (tag) { tagChild = buildHTMLUnbreakable(buildExpression$1(tag, options, true), options); tagChild.classes = ["katex-tag"]; children.push(tagChild); } else if (eqnNum) children.push(eqnNum); var htmlNode = makeSpan(["katex-html"], children); htmlNode.setAttribute("aria-hidden", "true"); if (tagChild) { var strut = tagChild.children[0]; strut.style.height = makeEm(htmlNode.height + htmlNode.depth); if (htmlNode.depth) strut.style.verticalAlign = makeEm(-htmlNode.depth); } return htmlNode; } /** * These objects store data about MathML nodes. This is the MathML equivalent * of the types in domTree.js. Since MathML handles its own rendering, and * since we're mainly using MathML to improve accessibility, we don't manage * any of the styling state that the plain DOM nodes do. * * The `toNode` and `toMarkup` functions work similarly to how they do in * domTree.js, creating namespaced DOM nodes and HTML text markup respectively. */ function newDocumentFragment(children) { return new DocumentFragment(children); } /** * This node represents a general purpose MathML node of any type. The * constructor requires the type of node to create (for example, `"mo"` or * `"mspace"`, corresponding to `<mo>` and `<mspace>` tags). */ var MathNode = class { constructor(type, children, classes) { this.type = void 0; this.attributes = void 0; this.children = void 0; this.classes = void 0; this.type = type; this.attributes = {}; this.children = children || []; this.classes = classes || []; } /** * Sets an attribute on a MathML node. MathML depends on attributes to convey a * semantic content, so this is used heavily. */ setAttribute(name, value) { this.attributes[name] = value; } /** * Gets an attribute on a MathML node. */ getAttribute(name) { return this.attributes[name]; } /** * Converts the math node into a MathML-namespaced DOM element. */ toNode() { var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", this.type); for (var _ref2 of Object.entries(this.attributes)) { var attr = _ref2[0]; var value = _ref2[1]; node.setAttribute(attr, value); } if (this.classes.length > 0) node.className = createClass(this.classes); for (var i = 0; i < this.children.length; i++) if (this.children[i] instanceof TextNode && this.children[i + 1] instanceof TextNode) { var text = this.children[i].toText() + this.children[++i].toText(); while (this.children[i + 1] instanceof TextNode) text += this.children[++i].toText(); node.appendChild(new TextNode(text).toNode()); } else node.appendChild(this.children[i].toNode()); return node; } /** * Converts the math node into an HTML markup string. */ toMarkup() { var markup = "<" + this.type; for (var _ref4 of Object.entries(this.attributes)) { var attr = _ref4[0]; var value = _ref4[1]; markup += " " + attr + "=\""; markup += escape(value); markup += "\""; } if (this.classes.length > 0) markup += " class =\"" + escape(createClass(this.classes)) + "\""; markup += ">"; for (var i = 0; i < this.children.length; i++) markup += this.children[i].toMarkup(); markup += "</" + this.type + ">"; return markup; } /** * Converts the math node into a string, similar to innerText, but escaped. */ toText() { return this.children.map((child) => child.toText()).join(""); } }; /** * This node represents a piece of text. */ var TextNode = class { constructor(text) { this.text = void 0; this.text = text; } /** * Converts the text node into a DOM text node. */ toNode() { return document.createTextNode(this.text); } /** * Converts the text node into escaped HTML markup * (representing the text itself). */ toMarkup() { return escape(this.toText()); } /** * Converts the text node into a string * (representing the text itself). */ toText() { return this.text; } }; /** * This node represents a space, but may render as <mspace.../> or as text, * depending on the width. */ var SpaceNode = class { /** * Create a Space node with width given in CSS ems. */ constructor(width) { this.width = void 0; this.character = void 0; this.width = width; if (width >= .05555 && width <= .05556) this.character = " "; else if (width >= .1666 && width <= .1667) this.character = " "; else if (width >= .2222 && width <= .2223) this.character = " "; else if (width >= .2777 && width <= .2778) this.character = "  "; else if (width >= -.05556 && width <= -.05555) this.character = " ⁣"; else if (width >= -.1667 && width <= -.1666) this.character = " ⁣"; else if (width >= -.2223 && width <= -.2222) this.character = " ⁣"; else if (width >= -.2778 && width <= -.2777) this.character = " ⁣"; else this.character = null; } /** * Converts the math node into a MathML-namespaced DOM element. */ toNode() { if (this.character) return document.createTextNode(this.character); else { var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", "mspace"); node.setAttribute("width", makeEm(this.width)); return node; } } /** * Converts the math node into an HTML markup string. */ toMarkup() { if (this.character) return "<mtext>" + this.character + "</mtext>"; else return "<mspace width=\"" + makeEm(this.width) + "\"/>"; } /** * Converts the math node into a string, similar to innerText. */ toText() { if (this.character) return this.character; else return " "; } }; /** * This file converts a parse tree into a corresponding MathML tree. The main * entry point is the `buildMathML` function, which takes a parse tree from the * parser. */ var noVariantSymbols = /* @__PURE__ */ new Set(["\\imath", "\\jmath"]); var rowLikeTypes = /* @__PURE__ */ new Set(["mrow", "mtable"]); /** * Takes a symbol and converts it into a MathML text node after performing * optional replacement from symbols.js. */ var makeText = function makeText(text, mode, options) { var _options$fontFamily, _options$font; if (symbols[mode][text] && symbols[mode][text].replace && text.charCodeAt(0) !== 55349 && !(Object.prototype.hasOwnProperty.call(ligatures, text) && ((options == null || (_options$fontFamily = options.fontFamily) == null ? void 0 : _options$fontFamily.slice(4, 6)) === "tt" || (options == null || (_options$font = options.font) == null ? void 0 : _options$font.slice(4, 6)) === "tt"))) text = symbols[mode][text].replace; return new TextNode(text); }; /** * Wrap the given array of nodes in an <mrow> node if needed, i.e., * unless the array has length 1. Always returns a single node. */ var makeRow = function makeRow(body) { if (body.length === 1) return body[0]; else return new MathNode("mrow", body); }; var mathFontVariants = { mathit: "italic", boldsymbol: (group) => group.type === "textord" ? "bold" : "bold-italic", mathbf: "bold", mathbb: "double-struck", mathsfit: "sans-serif-italic", mathfrak: "fraktur", mathscr: "script", mathcal: "script", mathsf: "sans-serif", mathtt: "monospace" }; /** * Returns the math variant as a string or null if none is required. */ var getVariant = (group, options) => { if (group.mode === "text") { if (options.fontFamily === "texttt") return "monospace"; else if (options.fontFamily === "textsf") { if (options.fontShape === "textit" && options.fontWeight === "textbf") return "sans-serif-bold-italic"; else if (options.fontShape === "textit") return "sans-serif-italic"; else if (options.fontWeight === "textbf") return "bold-sans-serif"; else return "sans-serif"; } else if (options.fontShape === "textit" && options.fontWeight === "textbf") return "bold-italic"; else if (options.fontShape === "textit") return "italic"; else if (options.fontWeight === "textbf") return "bold"; } var font = options.font; if (!font || font === "mathnormal") return null; var mode = group.mode; var mathVariant = mathFontVariants[font]; if (mathVariant) return typeof mathVariant === "function" ? mathVariant(group) : mathVariant; var text = group.text; if (noVariantSymbols.has(text)) return null; if (symbols[mode][text]) { var replacement = symbols[mode][text].replace; if (replacement) text = replacement; } var fontName = fontMap[font].fontName; if (getCharacterMetrics(text, fontName, mode)) return fontMap[font].variant; return null; }; /** * Check for <mi>.</mi> which is how a dot renders in MathML, * or <mo separator="true" lspace="0em" rspace="0em">,</mo> * which is how a braced comma {,} renders in MathML */ function isNumberPunctuation(group) { if (!group) return false; if (group.type === "mi" && group.children.length === 1) { var child = group.children[0]; return child instanceof TextNode && child.text === "."; } else if (group.type === "mo" && group.children.length === 1 && group.getAttribute("separator") === "true" && group.getAttribute("lspace") === "0em" && group.getAttribute("rspace") === "0em") { var _child = group.children[0]; return _child instanceof TextNode && _child.text === ","; } else return false; } /** * Takes a list of nodes, builds them, and returns a list of the generated * MathML nodes. Also combine consecutive <mtext> outputs into a single * <mtext> tag. */ var buildExpression = function buildExpression(expression, options, isOrdgroup) { if (expression.length === 1) { var group = buildGroup(expression[0], options); if (isOrdgroup && group instanceof MathNode && group.type === "mo") { group.setAttribute("lspace", "0em"); group.setAttribute("rspace", "0em"); } return [group]; } var groups = []; var lastGroup; for (var i = 0; i < expression.length; i++) { var _group = buildGroup(expression[i], options); if (_group instanceof MathNode && lastGroup instanceof MathNode) { if (_group.type === "mtext" && lastGroup.type === "mtext" && _group.getAttribute("mathvariant") === lastGroup.getAttribute("mathvariant")) { lastGroup.children.push(..._group.children); continue; } else if (_group.type === "mn" && lastGroup.type === "mn") { lastGroup.children.push(..._group.children); continue; } else if (isNumberPunctuation(_group) && lastGroup.type === "mn") { lastGroup.children.push(..._group.children); continue; } else if (_group.type === "mn" && isNumberPunctuation(lastGroup)) { _group.children = [...lastGroup.children, ..._group.children]; groups.pop(); } else if ((_group.type === "msup" || _group.type === "msub") && _group.children.length >= 1 && (lastGroup.type === "mn" || isNumberPunctuation(lastGroup))) { var base = _group.children[0]; if (base instanceof MathNode && base.type === "mn") { base.children = [...lastGroup.children, ...base.children]; groups.pop(); } } else if (lastGroup.type === "mi" && lastGroup.children.length === 1) { var lastChild = lastGroup.children[0]; if (lastChild instanceof TextNode && lastChild.text === "̸" && (_group.type === "mo" || _group.type === "mi" || _group.type === "mn")) { var child = _group.children[0]; if (child instanceof TextNode && child.text.length > 0) { child.text = child.text.slice(0, 1) + "̸" + child.text.slice(1); groups.pop(); } } } } groups.push(_group); lastGroup = _group; } return groups; }; /** * Equivalent to buildExpression, but wraps the elements in an <mrow> * if there's more than one. Returns a single node instead of an array. */ var buildExpressionRow = function buildExpressionRow(expression, options, isOrdgroup) { return makeRow(buildExpression(expression, options, isOrdgroup)); }; /** * Takes a group from the parser and calls the appropriate groupBuilders function * on it to produce a MathML node. */ var buildGroup = function buildGroup(group, options) { if (!group) return new MathNode("mrow"); if (_mathmlGroupBuilders[group.type]) return _mathmlGroupBuilders[group.type](group, options); else throw new ParseError("Got group of unknown type: '" + group.type + "'"); }; /** * Takes a full parse tree and settings and builds a MathML representation of * it. In particular, we put the elements from building the parse tree into a * <semantics> tag so we can also include that TeX source as an annotation. * * Note that we actually return a domTree element with a `<math>` inside it so * we can do appropriate styling. */ function buildMathML(tree, texExpression, options, isDisplayMode, forMathmlOnly) { var expression = buildExpression(tree, options); var wrapper; if (expression.length === 1 && expression[0] instanceof MathNode && rowLikeTypes.has(expression[0].type)) wrapper = expression[0]; else wrapper = new MathNode("mrow", expression); var annotation = new MathNode("annotation", [new TextNode(texExpression)]); annotation.setAttribute("encoding", "application/x-tex"); var math = new MathNode("math", [new MathNode("semantics", [wrapper, annotation])]); math.setAttribute("xmlns", "http://www.w3.org/1998/Math/MathML"); if (isDisplayMode) math.setAttribute("display", "block"); return makeSpan([forMathmlOnly ? "katex" : "katex-mathml"], [math]); } /** * This file contains information about the options that the Parser carries * around with it while parsing. Data is held in an `Options` object, and when * recursing, a new `Options` object can be created with the `.with*` and * `.reset` functions. */ var sizeStyleMap = [ [ 1, 1, 1 ], [ 2, 1, 1 ], [ 3, 1, 1 ], [ 4, 2, 1 ], [ 5, 2, 1 ], [ 6, 3, 1 ], [ 7, 4, 2 ], [ 8, 6, 3 ], [ 9, 7, 6 ], [ 10, 8, 7 ], [ 11, 10, 9 ] ]; var sizeMultipliers = [ .5, .6, .7, .8, .9, 1, 1.2, 1.44, 1.728, 2.074, 2.488 ]; var sizeAtStyle = function sizeAtStyle(size, style) { return style.size < 2 ? size : sizeStyleMap[size - 1][style.size - 1]; }; /** * This is the main options class. It contains the current style, size, color, * and font. * * Options objects should not be modified. To create a new Options with * different properties, call a `.having*` method. */ var Options = class Options { constructor(data) { this.style = void 0; this.color = void 0; this.size = void 0; this.textSize = void 0; this.phantom = void 0; this.font = void 0; this.fontFamily = void 0; this.fontWeight = void 0; this.fontShape = void 0; this.sizeMultiplier = void 0; this.maxSize = void 0; this.minRuleThickness = void 0; this._fontMetrics = void 0; this.strict = void 0; this.style = data.style; this.color = data.color; this.size = data.size || Options.BASESIZE; this.textSize = data.textSize || this.size; this.phantom = !!data.phantom; this.font = data.font || ""; this.fontFamily = data.fontFamily || ""; this.fontWeight = data.fontWeight || ""; this.fontShape = data.fontShape || ""; this.sizeMultiplier = sizeMultipliers[this.size - 1]; this.maxSize = data.maxSize; this.minRuleThickness = data.minRuleThickness; this.strict = data.strict; this._fontMetrics = void 0; } /** * Returns a new options object with the same properties as "this". Properties * from "extension" will be copied to the new options object. */ extend(extension) { var data = { style: this.style, size: this.size, textSize: this.textSize, color: this.color, phantom: this.phantom, font: this.font, fontFamily: this.fontFamily, fontWeight: this.fontWeight, fontShape: this.fontShape, maxSize: this.maxSize, minRuleThickness: this.minRuleThickness, strict: this.strict }; Object.assign(data, extension); return new Options(data); } /** * Return an options object with the given style. If `this.style === style`, * returns `this`. */ havingStyle(style) { if (this.style === style) return this; else return this.extend({ style, size: sizeAtStyle(this.textSize, style) }); } /** * Return an options object with a cramped version of the current style. If * the current style is cramped, returns `this`. */ havingCrampedStyle() { return this.havingStyle(this.style.cramp()); } /** * Return an options object with the given size and in at least `\textstyle`. * Returns `this` if appropriate. */ havingSize(size) { if (this.size === size && this.textSize === size) return this; else return this.extend({ style: this.style.text(), size, textSize: size, sizeMultiplier: sizeMultipliers[size - 1] }); } /** * Like `this.havingSize(BASESIZE).havingStyle(style)`. If `style` is omitted, * changes to at least `\textstyle`. */ havingBaseStyle(style) { style = style || this.style.text(); var wantSize = sizeAtStyle(Options.BASESIZE, style); if (this.size === wantSize && this.textSize === Options.BASESIZE && this.style === style) return this; else return this.extend({ style, size: wantSize }); } /** * Remove the effect of sizing changes such as \Huge. * Keep the effect of the current style, such as \scriptstyle. */ havingBaseSizing() { var size; switch (this.style.id) { case 4: case 5: size = 3; break; case 6: case 7: size = 1; break; default: size = 6; } return this.extend({ style: this.style.text(), size }); } /** * Create a new options object with the given color. */ withColor(color) { return this.extend({ color }); } /** * Create a new options object with "phantom" set to true. */ withPhantom() { return this.extend({ phantom: true }); } /** * Creates a new options object with the given math font or old text font. * @type {[type]} */ withFont(font) { return this.extend({ font }); } /** * Create a new options objects with the given fontFamily. */ withTextFontFamily(fontFamily) { return this.extend({ fontFamily, font: "" }); } /** * Creates a new options object with the given font weight */ withTextFontWeight(fontWeight) { return this.extend({ fontWeight, font: "" }); } /** * Creates a new options object with the given font weight */ withTextFontShape(fontShape) { return this.extend({ fontShape, font: "" }); } /** * Return the CSS sizing classes required to switch from enclosing options * `oldOptions` to `this`. Returns an array of classes. */ sizingClasses(oldOptions) { if (oldOptions.size !== this.size) return [ "katex-sizing", "reset-size" + oldOptions.size, "size" + this.size ]; else return []; } /** * Return the CSS sizing classes required to switch to the base size. Like * `this.havingSize(BASESIZE).sizingClasses(this)`. */ baseSizingClasses() { if (this.size !== Options.BASESIZE) return [ "katex-sizing", "reset-size" + this.size, "size" + Options.BASESIZE ]; else return []; } /** * Return the font metrics for this size. */ fontMetrics() { if (!this._fontMetrics) this._fontMetrics = getGlobalMetrics(this.size); return this._fontMetrics; } /** * Gets the CSS color of the current options object */ getColor() { if (this.phantom) return "transparent"; else return this.color; } }; /** * The base size index. */ Options.BASESIZE = 6; var optionsFromSettings = (settings) => new Options({ style: settings.displayMode ? Style$1.DISPLAY : Style$1.TEXT, maxSize: settings.maxSize, minRuleThickness: settings.minRuleThickness, strict: settings.strict }); var displayWrap = function displayWrap(node, settings) { if (settings.displayMode) { var classes = ["katex-display"]; if (settings.leqno) classes.push("leqno"); if (settings.fleqn) classes.push("fleqn"); node = makeSpan(classes, [node]); } return node; }; var buildTree = function buildTree(tree, expression, settings) { var options = optionsFromSettings(settings); var katexNode; if (settings.output === "mathml") return buildMathML(tree, expression, options, settings.displayMode, true); else if (settings.output === "html") katexNode = makeSpan(["katex"], [buildHTML(tree, options)]); else katexNode = makeSpan(["katex"], [buildMathML(tree, expression, options, settings.displayMode, false), buildHTML(tree, options)]); return displayWrap(katexNode, settings); }; var buildHTMLTree = function buildHTMLTree(tree, settings) { return displayWrap(makeSpan(["katex"], [buildHTML(tree, optionsFromSettings(settings))]), settings); }; /** * This file provides support to buildMathML.js and buildHTML.js * for stretchy wide elements rendered from SVG files * and other CSS trickery. */ var stretchyCodePoint = { widehat: "^", widecheck: "ˇ", widetilde: "~", utilde: "~", overleftarrow: "←", underleftarrow: "←", xleftarrow: "←", overrightarrow: "→", underrightarrow: "→", xrightarrow: "→", underbrace: "⏟", overbrace: "⏞", underbracket: "⎵", overbracket: "⎴", overgroup: "⏠", undergroup: "⏡", overleftrightarrow: "↔", underleftrightarrow: "↔", xleftrightarrow: "↔", Overrightarrow: "⇒", xRightarrow: "⇒", overleftharpoon: "↼", xleftharpoonup: "↼", overrightharpoon: "⇀", xrightharpoonup: "⇀", xLeftarrow: "⇐", xLeftrightarrow: "⇔", xhookleftarrow: "↩", xhookrightarrow: "↪", xmapsto: "↦", xrightharpoondown: "⇁", xleftharpoondown: "↽", xrightleftharpoons: "⇌", xleftrightharpoons: "⇋", xtwoheadleftarrow: "↞", xtwoheadrightarrow: "↠", xlongequal: "=", xtofrom: "⇄", xrightleftarrows: "⇄", xrightequilibrium: "⇌", xleftequilibrium: "⇋", "\\cdrightarrow": "→", "\\cdleftarrow": "←", "\\cdlongequal": "=" }; var stretchyMathML = function stretchyMathML(label) { var node = new MathNode("mo", [new TextNode(stretchyCodePoint[label.replace(/^\\/, "")])]); node.setAttribute("stretchy", "true"); return node; }; var katexImagesData = { overrightarrow: [ ["rightarrow"], .888, 522, "xMaxYMin" ], overleftarrow: [ ["leftarrow"], .888, 522, "xMinYMin" ], underrightarrow: [ ["rightarrow"], .888, 522, "xMaxYMin" ], underleftarrow: [ ["leftarrow"], .888, 522, "xMinYMin" ], xrightarrow: [ ["rightarrow"], 1.469, 522, "xMaxYMin" ], "\\cdrightarrow": [ ["rightarrow"], 3, 522, "xMaxYMin" ], xleftarrow: [ ["leftarrow"], 1.469, 522, "xMinYMin" ], "\\cdleftarrow": [ ["leftarrow"], 3, 522, "xMinYMin" ], Overrightarrow: [ ["doublerightarrow"], .888, 560, "xMaxYMin" ], xRightarrow: [ ["doublerightarrow"], 1.526, 560, "xMaxYMin" ], xLeftarrow: [ ["doubleleftarrow"], 1.526, 560, "xMinYMin" ], overleftharpoon: [ ["leftharpoon"], .888, 522, "xMinYMin" ], xleftharpoonup: [ ["leftharpoon"], .888, 522, "xMinYMin" ], xleftharpoondown: [ ["leftharpoondown"], .888, 522, "xMinYMin" ], overrightharpoon: [ ["rightharpoon"], .888, 522, "xMaxYMin" ], xrightharpoonup: [ ["rightharpoon"], .888, 522, "xMaxYMin" ], xrightharpoondown: [ ["rightharpoondown"], .888, 522, "xMaxYMin" ], xlongequal: [ ["longequal"], .888, 334, "xMinYMin" ], "\\cdlongequal": [ ["longequal"], 3, 334, "xMinYMin" ], xtwoheadleftarrow: [ ["twoheadleftarrow"], .888, 334, "xMinYMin" ], xtwoheadrightarrow: [ ["twoheadrightarrow"], .888, 334, "xMaxYMin" ], overleftrightarrow: [ ["leftarrow", "rightarrow"], .888, 522 ], overbrace: [ [ "leftbrace", "midbrace", "rightbrace" ], 1.6, 548 ], underbrace: [ [ "leftbraceunder", "midbraceunder", "rightbraceunder" ], 1.6, 548 ], underleftrightarrow: [ ["leftarrow", "rightarrow"], .888, 522 ], xleftrightarrow: [ ["leftarrow", "rightarrow"], 1.75, 522 ], xLeftrightarrow: [ ["doubleleftarrow", "doublerightarrow"], 1.75, 560 ], xrightleftharpoons: [ ["leftharpoondownplus", "rightharpoonplus"], 1.75, 716 ], xleftrightharpoons: [ ["leftharpoonplus", "rightharpoondownplus"], 1.75, 716 ], xhookleftarrow: [ ["leftarrow", "righthook"], 1.08, 522 ], xhookrightarrow: [ ["lefthook", "rightarrow"], 1.08, 522 ], overlinesegment: [ ["leftlinesegment", "rightlinesegment"], .888, 522 ], underlinesegment: [ ["leftlinesegment", "rightlinesegment"], .888, 522 ], overbracket: [ ["leftbracketover", "rightbracketover"], 1.6, 440 ], underbracket: [ ["leftbracketunder", "rightbracketunder"], 1.6, 410 ], overgroup: [ ["leftgroup", "rightgroup"], .888, 342 ], undergroup: [ ["leftgroupunder", "rightgroupunder"], .888, 342 ], xmapsto: [ ["leftmapsto", "rightarrow"], 1.5, 522 ], xtofrom: [ ["leftToFrom", "rightToFrom"], 1.75, 528 ], xrightleftarrows: [ ["baraboveleftarrow", "rightarrowabovebar"], 1.75, 901 ], xrightequilibrium: [ ["baraboveshortleftharpoon", "rightharpoonaboveshortbar"], 1.75, 716 ], xleftequilibrium: [ ["shortbaraboveleftharpoon", "shortrightharpoonabovebar"], 1.75, 716 ] }; var wideAccentLabels = /* @__PURE__ */ new Set([ "widehat", "widecheck", "widetilde", "utilde" ]); var stretchySvg = function stretchySvg(group, options) { function buildSvgSpan_() { var viewBoxWidth = 4e5; var label = group.label.slice(1); if (wideAccentLabels.has(label) && "base" in group) { var numChars = group.base.type === "ordgroup" ? group.base.body.length : 1; var viewBoxHeight; var pathName; var _height; if (numChars > 5) { if (label === "widehat" || label === "widecheck") { viewBoxHeight = 420; viewBoxWidth = 2364; _height = .42; pathName = label + "4"; } else { viewBoxHeight = 312; viewBoxWidth = 2340; _height = .34; pathName = "tilde4"; } } else { var imgIndex = [ 1, 1, 2, 2, 3, 3 ][numChars]; if (label === "widehat" || label === "widecheck") { viewBoxWidth = [ 0, 1062, 2364, 2364, 2364 ][imgIndex]; viewBoxHeight = [ 0, 239, 300, 360, 420 ][imgIndex]; _height = [ 0, .24, .3, .3, .36, .42 ][imgIndex]; pathName = label + imgIndex; } else { viewBoxWidth = [ 0, 600, 1033, 2339, 2340 ][imgIndex]; viewBoxHeight = [ 0, 260, 286, 306, 312 ][imgIndex]; _height = [ 0, .26, .286, .3, .306, .34 ][imgIndex]; pathName = "tilde" + imgIndex; } } return { span: makeSvgSpan([], [new SvgNode([new PathNode(pathName)], { "width": "100%", "height": makeEm(_height), "viewBox": "0 0 " + viewBoxWidth + " " + viewBoxHeight, "preserveAspectRatio": "none" })], options), minWidth: 0, height: _height }; } else { var spans = []; var data = katexImagesData[label]; if (!data) throw new Error("No SVG data for \"" + label + "\"."); var paths = data[0], _minWidth = data[1], _viewBoxHeight = data[2]; var _height2 = _viewBoxHeight / 1e3; var numSvgChildren = paths.length; var widthClasses; var aligns; if (numSvgChildren === 1) { if (data.length !== 4) throw new Error("Expected 4-tuple for single-path SVG data \"" + label + "\"."); widthClasses = ["hide-tail"]; aligns = [data[3]]; } else if (numSvgChildren === 2) { widthClasses = ["halfarrow-left", "halfarrow-right"]; aligns = ["xMinYMin", "xMaxYMin"]; } else if (numSvgChildren === 3) { widthClasses = [ "brace-left", "brace-center", "brace-right" ]; aligns = [ "xMinYMin", "xMidYMin", "xMaxYMin" ]; } else throw new Error("Correct katexImagesData or update code here to support\n " + numSvgChildren + " children."); for (var i = 0; i < numSvgChildren; i++) { var _svgNode = new SvgNode([new PathNode(paths[i])], { "width": "400em", "height": makeEm(_height2), "viewBox": "0 0 " + viewBoxWidth + " " + _viewBoxHeight, "preserveAspectRatio": aligns[i] + " slice" }); var _span = makeSvgSpan([widthClasses[i]], [_svgNode], options); if (numSvgChildren === 1) return { span: _span, minWidth: _minWidth, height: _height2 }; else { _span.style.height = makeEm(_height2); spans.push(_span); } } return { span: makeSpan(["katex-stretchy"], spans, options), minWidth: _minWidth, height: _height2 }; } } var _buildSvgSpan_ = buildSvgSpan_(), span = _buildSvgSpan_.span, minWidth = _buildSvgSpan_.minWidth, height = _buildSvgSpan_.height; span.height = height; span.style.height = makeEm(height); if (minWidth > 0) span.style.minWidth = makeEm(minWidth); return span; }; var stretchyEnclose = function stretchyEnclose(inner, label, topPad, bottomPad, options) { var img; var totalHeight = inner.height + inner.depth + topPad + bottomPad; if (/fbox|color|angl/.test(label)) { img = makeSpan(["katex-stretchy", label], [], options); if (label === "fbox") { var color = options.color && options.getColor(); if (color) img.style.borderColor = color; } } else { var lines = []; if (/^[bx]cancel$/.test(label)) lines.push(new LineNode({ "x1": "0", "y1": "0", "x2": "100%", "y2": "100%", "stroke-width": "0.046em" })); if (/^x?cancel$/.test(label)) lines.push(new LineNode({ "x1": "0", "y1": "100%", "x2": "100%", "y2": "0", "stroke-width": "0.046em" })); img = makeSvgSpan([], [new SvgNode(lines, { "width": "100%", "height": makeEm(totalHeight) })], options); } img.height = totalHeight; img.style.height = makeEm(totalHeight); return img; }; /** * Small module for atom-group constants and type guard. Kept separate from * `symbols.ts` so that consumers (notably `contrib/render-a11y-string`) can * pull in `isAtom` without dragging in the ~870-line symbol tables. */ var atomList = [ "bin", "close", "inner", "open", "punct", "rel" ]; var nonAtomList = [ "accent-token", "mathord", "op-token", "spacing", "textord" ]; var Atoms = new Set(atomList); var NonAtoms = new Set(nonAtomList); function isAtom(value) { return Atoms.has(value); } /** * Asserts that the node is of the given type and returns it with stricter * typing. Throws if the node's type does not match. */ function assertNodeType(node, type) { if (!node || node.type !== type) throw new Error("Expected node of type " + type + ", but got " + (node ? "node of type " + node.type : String(node))); return node; } /** * Returns the node more strictly typed iff it is of the given type. Otherwise, * returns null. */ function assertSymbolNodeType(node) { var typedNode = checkSymbolNodeType(node); if (!typedNode) throw new Error("Expected node of symbol group type, but got " + (node ? "node of type " + node.type : String(node))); return typedNode; } /** * Returns the node more strictly typed if it is of the given type. Otherwise, * returns null. */ function checkSymbolNodeType(node) { if (node.type === "atom" || NonAtoms.has(node.type)) return node; return null; } /** * Returns the string spelled out by a group of plain characters, throwing the * given ParseError if the group holds anything else. With allowSpaces, a * literal space counts as a character; `~` and `\ ` do not. */ function assertCharacterGroup(group, errorMessage, allowSpaces) { var text = ""; for (var node of group.body) if (node.type === "textord") text += node.text; else if (allowSpaces && node.type === "spacing" && node.text === " ") text += " "; else throw new ParseError(errorMessage, group); return text; } var getBaseSymbol = (group) => { if (group instanceof SymbolNode) return group; if (hasHtmlDomChildren(group) && group.children.length === 1) return getBaseSymbol(group.children[0]); }; var htmlBuilder$a = (grp, options) => { var base; var group; var supSubGroup; if (grp && grp.type === "supsub") { group = assertNodeType(grp.base, "accent"); base = group.base; grp.base = base; supSubGroup = assertSpan(buildGroup$1(grp, options)); grp.base = group; } else { group = assertNodeType(grp, "accent"); base = group.base; } var body = buildGroup$1(base, options.havingCrampedStyle()); var mustShift = group.isShifty && isCharacterBox(base); var skew = 0; if (mustShift) { var _getBaseSymbol$skew, _getBaseSymbol; skew = (_getBaseSymbol$skew = (_getBaseSymbol = getBaseSymbol(body)) == null ? void 0 : _getBaseSymbol.skew) != null ? _getBaseSymbol$skew : 0; } var accentBelow = group.label === "\\c"; var clearance = accentBelow ? body.height + body.depth : Math.min(body.height, options.fontMetrics().xHeight); var accentBody; if (!group.isStretchy) { var accent; var width; if (group.label === "\\vec") { accent = staticSvg("vec", options); width = svgData.vec[1]; } else { accent = makeOrd({ type: "textord", mode: group.mode, text: group.label }, options); accent = assertSymbolDomNode(accent); accent.italic = 0; width = accent.width; if (accentBelow) clearance += accent.depth; } accentBody = makeSpan(["accent-body"], [accent]); var accentFull = group.label === "\\textcircled"; if (accentFull) { accentBody.classes.push("accent-full"); clearance = body.height; } var left = skew; if (!accentFull) left -= width / 2; accentBody.style.left = makeEm(left); if (group.label === "\\textcircled") accentBody.style.top = ".2em"; accentBody = makeVList({ positionType: "firstBaseline", children: [ { type: "elem", elem: body }, { type: "kern", size: -clearance }, { type: "elem", elem: accentBody } ] }); } else { accentBody = stretchySvg(group, options); accentBody = makeVList({ positionType: "firstBaseline", children: [{ type: "elem", elem: body }, { type: "elem", elem: accentBody, wrapperClasses: ["svg-align"], wrapperStyle: skew > 0 ? { width: "calc(100% - " + makeEm(2 * skew) + ")", marginLeft: makeEm(2 * skew) } : void 0 }] }); } var accentWrap = makeSpan(["mord", "katex-accent"], [accentBody], options); if (supSubGroup) { supSubGroup.children[0] = accentWrap; supSubGroup.height = Math.max(accentWrap.height, supSubGroup.height); supSubGroup.classes[0] = "mord"; return supSubGroup; } else return accentWrap; }; var mathmlBuilder$9 = (group, options) => { var accentNode = group.isStretchy ? stretchyMathML(group.label) : new MathNode("mo", [makeText(group.label, group.mode)]); var node = new MathNode("mover", [buildGroup(group.base, options), accentNode]); node.setAttribute("accent", "true"); return node; }; var NON_STRETCHY_ACCENT_REGEX = new RegExp([ "\\acute", "\\grave", "\\ddot", "\\tilde", "\\bar", "\\breve", "\\check", "\\hat", "\\vec", "\\dot", "\\mathring" ].map((accent) => "\\" + accent).join("|")); defineFunction({ type: "accent", names: [ "\\acute", "\\grave", "\\ddot", "\\tilde", "\\bar", "\\breve", "\\check", "\\hat", "\\vec", "\\dot", "\\mathring", "\\widecheck", "\\widehat", "\\widetilde", "\\overrightarrow", "\\overleftarrow", "\\Overrightarrow", "\\overleftrightarrow", "\\overgroup", "\\overlinesegment", "\\overleftharpoon", "\\overrightharpoon" ], numArgs: 1, handler: (context, args) => { var base = normalizeArgument(args[0]); var isStretchy = !NON_STRETCHY_ACCENT_REGEX.test(context.funcName); var isShifty = !isStretchy || context.funcName === "\\widehat" || context.funcName === "\\widetilde" || context.funcName === "\\widecheck"; return { type: "accent", mode: context.parser.mode, label: context.funcName, isStretchy, isShifty, base }; }, htmlBuilder: htmlBuilder$a, mathmlBuilder: mathmlBuilder$9 }); defineFunction({ type: "accent", names: [ "\\'", "\\`", "\\^", "\\~", "\\=", "\\u", "\\.", "\\\"", "\\c", "\\r", "\\H", "\\v", "\\textcircled" ], numArgs: 1, allowedInText: true, allowedInMath: true, argTypes: ["primitive"], handler: (context, args) => { var base = args[0]; var mode = context.parser.mode; if (mode === "math") { handleStrict({ strict: context.parser.settings.strict, errorCode: "mathVsTextAccents", errorMsg: "LaTeX's accent " + context.funcName + " works only in text mode", report: true }); mode = "text"; } return { type: "accent", mode, label: context.funcName, isStretchy: false, isShifty: true, base }; } }); defineFunction({ type: "accentUnder", names: [ "\\underleftarrow", "\\underrightarrow", "\\underleftrightarrow", "\\undergroup", "\\underlinesegment", "\\utilde" ], numArgs: 1, handler: (_ref, args) => { var parser = _ref.parser, funcName = _ref.funcName; var base = args[0]; return { type: "accentUnder", mode: parser.mode, label: funcName, base }; }, htmlBuilder: (group, options) => { var innerGroup = buildGroup$1(group.base, options); var accentBody = stretchySvg(group, options); var kern = group.label === "\\utilde" ? .12 : 0; return makeSpan(["mord", "accentunder"], [makeVList({ positionType: "top", positionData: innerGroup.height, children: [ { type: "elem", elem: accentBody, wrapperClasses: ["svg-align"] }, { type: "kern", size: kern }, { type: "elem", elem: innerGroup } ] })], options); }, mathmlBuilder: (group, options) => { var accentNode = stretchyMathML(group.label); var node = new MathNode("munder", [buildGroup(group.base, options), accentNode]); node.setAttribute("accentunder", "true"); return node; } }); var paddedNode = (group) => { var node = new MathNode("mpadded", group ? [group] : []); node.setAttribute("width", "+0.6em"); node.setAttribute("lspace", "0.3em"); return node; }; defineFunction({ type: "xArrow", names: [ "\\xleftarrow", "\\xrightarrow", "\\xLeftarrow", "\\xRightarrow", "\\xleftrightarrow", "\\xLeftrightarrow", "\\xhookleftarrow", "\\xhookrightarrow", "\\xmapsto", "\\xrightharpoondown", "\\xrightharpoonup", "\\xleftharpoondown", "\\xleftharpoonup", "\\xrightleftharpoons", "\\xleftrightharpoons", "\\xlongequal", "\\xtwoheadrightarrow", "\\xtwoheadleftarrow", "\\xtofrom", "\\xrightleftarrows", "\\xrightequilibrium", "\\xleftequilibrium", "\\\\cdrightarrow", "\\\\cdleftarrow", "\\\\cdlongequal" ], numArgs: 1, numOptionalArgs: 1, handler(_ref, args, optArgs) { var parser = _ref.parser, funcName = _ref.funcName; return { type: "xArrow", mode: parser.mode, label: funcName, body: args[0], below: optArgs[0] }; }, htmlBuilder(group, options) { var style = options.style; var newOptions = options.havingStyle(style.sup()); var upperGroup = wrapFragment(buildGroup$1(group.body, newOptions, options), options); var arrowPrefix = group.label.slice(0, 2) === "\\x" ? "x" : "cd"; upperGroup.classes.push(arrowPrefix + "-arrow-pad"); var lowerGroup; if (group.below) { newOptions = options.havingStyle(style.sub()); lowerGroup = wrapFragment(buildGroup$1(group.below, newOptions, options), options); lowerGroup.classes.push(arrowPrefix + "-arrow-pad"); } var arrowBody = stretchySvg(group, options); var arrowShift = -options.fontMetrics().axisHeight + .5 * arrowBody.height; var upperShift = -options.fontMetrics().axisHeight - .5 * arrowBody.height - .111; if (upperGroup.depth > .25 || group.label === "\\xleftequilibrium") upperShift -= upperGroup.depth; var vlist; if (lowerGroup) { var lowerShift = -options.fontMetrics().axisHeight + lowerGroup.height + .5 * arrowBody.height + .111; vlist = makeVList({ positionType: "individualShift", children: [ { type: "elem", elem: upperGroup, shift: upperShift }, { type: "elem", elem: arrowBody, shift: arrowShift, wrapperClasses: ["svg-align"] }, { type: "elem", elem: lowerGroup, shift: lowerShift } ] }); } else vlist = makeVList({ positionType: "individualShift", children: [{ type: "elem", elem: upperGroup, shift: upperShift }, { type: "elem", elem: arrowBody, shift: arrowShift, wrapperClasses: ["svg-align"] }] }); return makeSpan(["mrel", "x-arrow"], [vlist], options); }, mathmlBuilder(group, options) { var arrowNode = stretchyMathML(group.label); arrowNode.setAttribute("minsize", group.label.charAt(0) === "x" ? "1.75em" : "3.0em"); var node; if (group.body) { var upperNode = paddedNode(buildGroup(group.body, options)); if (group.below) node = new MathNode("munderover", [ arrowNode, paddedNode(buildGroup(group.below, options)), upperNode ]); else node = new MathNode("mover", [arrowNode, upperNode]); } else if (group.below) node = new MathNode("munder", [arrowNode, paddedNode(buildGroup(group.below, options))]); else { node = paddedNode(); node = new MathNode("mover", [arrowNode, node]); } return node; } }); function htmlBuilder$9(group, options) { var elements = buildExpression$1(group.body, options, true); return makeSpan([group.mclass], elements, options); } function mathmlBuilder$8(group, options) { var node; var inner = buildExpression(group.body, options); if (group.mclass === "minner") node = new MathNode("mpadded", inner); else if (group.mclass === "mord") { if (group.isCharacterBox) { node = inner[0]; node.type = "mi"; } else node = new MathNode("mi", inner); } else { if (group.isCharacterBox) { node = inner[0]; node.type = "mo"; } else node = new MathNode("mo", inner); if (group.mclass === "mbin") { node.attributes.lspace = "0.22em"; node.attributes.rspace = "0.22em"; } else if (group.mclass === "mpunct") { node.attributes.lspace = "0em"; node.attributes.rspace = "0.17em"; } else if (group.mclass === "mopen" || group.mclass === "mclose") { node.attributes.lspace = "0em"; node.attributes.rspace = "0em"; } } return node; } defineFunction({ type: "mclass", names: [ "\\mathord", "\\mathbin", "\\mathrel", "\\mathopen", "\\mathclose", "\\mathpunct", "\\mathinner" ], numArgs: 1, primitive: true, handler(_ref, args) { var parser = _ref.parser, funcName = _ref.funcName; var body = args[0]; return { type: "mclass", mode: parser.mode, mclass: "m" + funcName.slice(5), body: ordargument(body), isCharacterBox: isCharacterBox(body) }; }, htmlBuilder: htmlBuilder$9, mathmlBuilder: mathmlBuilder$8 }); var binrelClass = (arg) => { var atom = arg.type === "ordgroup" && arg.body.length ? arg.body[0] : arg; if (atom.type === "atom" && (atom.family === "bin" || atom.family === "rel")) return "m" + atom.family; else return "mord"; }; defineFunction({ type: "mclass", names: ["\\@binrel"], numArgs: 2, handler(_ref2, args) { return { type: "mclass", mode: _ref2.parser.mode, mclass: binrelClass(args[0]), body: ordargument(args[1]), isCharacterBox: isCharacterBox(args[1]) }; } }); defineFunction({ type: "mclass", names: [ "\\stackrel", "\\overset", "\\underset" ], numArgs: 2, handler(_ref3, args) { var parser = _ref3.parser, funcName = _ref3.funcName; var baseArg = args[1]; var shiftedArg = args[0]; var mclass; if (funcName !== "\\stackrel") mclass = binrelClass(baseArg); else mclass = "mrel"; var baseOp = { type: "op", mode: baseArg.mode, limits: true, alwaysHandleSupSub: true, parentIsSupSub: false, symbol: false, suppressBaseShift: funcName !== "\\stackrel", body: ordargument(baseArg) }; var supsub = funcName === "\\underset" ? { type: "supsub", mode: shiftedArg.mode, base: baseOp, sub: shiftedArg } : { type: "supsub", mode: shiftedArg.mode, base: baseOp, sup: shiftedArg }; return { type: "mclass", mode: parser.mode, mclass, body: [supsub], isCharacterBox: isCharacterBox(supsub) }; } }); defineFunction({ type: "pmb", names: ["\\pmb"], numArgs: 1, allowedInText: true, handler(_ref, args) { return { type: "pmb", mode: _ref.parser.mode, mclass: binrelClass(args[0]), body: ordargument(args[0]) }; }, htmlBuilder(group, options) { var elements = buildExpression$1(group.body, options, true); var node = makeSpan([group.mclass], elements, options); node.style.textShadow = "0.02em 0.01em 0.04px"; return node; }, mathmlBuilder(group, style) { var node = new MathNode("mstyle", buildExpression(group.body, style)); node.setAttribute("style", "text-shadow: 0.02em 0.01em 0.04px"); return node; } }); var cdArrowFunctionName = { ">": "\\\\cdrightarrow", "<": "\\\\cdleftarrow", "=": "\\\\cdlongequal", "A": "\\uparrow", "V": "\\downarrow", "|": "\\Vert", ".": "no arrow" }; var newCell = () => { return { type: "styling", body: [], mode: "math", style: "display", resetFont: true }; }; var isStartOfArrow = (node) => { return node.type === "textord" && node.text === "@"; }; var isLabelEnd = (node, endChar) => { return (node.type === "mathord" || node.type === "atom") && node.text === endChar; }; function cdArrow(arrowChar, labels, parser) { var funcName = cdArrowFunctionName[arrowChar]; switch (funcName) { case "\\\\cdrightarrow": case "\\\\cdleftarrow": return parser.callFunction(funcName, [labels[0]], [labels[1]]); case "\\uparrow": case "\\downarrow": var leftLabel = parser.callFunction("\\\\cdleft", [labels[0]], []); var bareArrow = { type: "atom", text: funcName, mode: "math", family: "rel" }; var arrowGroup = { type: "ordgroup", mode: "math", body: [ leftLabel, parser.callFunction("\\Big", [bareArrow], []), parser.callFunction("\\\\cdright", [labels[1]], []) ] }; return parser.callFunction("\\\\cdparent", [arrowGroup], []); case "\\\\cdlongequal": return parser.callFunction("\\\\cdlongequal", [], []); case "\\Vert": return parser.callFunction("\\Big", [{ type: "textord", text: "\\Vert", mode: "math" }], []); default: return { type: "textord", text: " ", mode: "math" }; } } function parseCD(parser) { var parsedRows = []; parser.gullet.beginGroup(); parser.gullet.macros.set("\\cr", "\\\\\\relax"); parser.gullet.beginGroup(); while (true) { parsedRows.push(parser.parseExpression(false, "\\\\")); parser.gullet.endGroup(); parser.gullet.beginGroup(); var next = parser.fetch().text; if (next === "&" || next === "\\\\") parser.consume(); else if (next === "\\end") { if (parsedRows[parsedRows.length - 1].length === 0) parsedRows.pop(); break; } else throw new ParseError("Expected \\\\ or \\cr or \\end", parser.nextToken); } var row = []; var body = [row]; for (var i = 0; i < parsedRows.length; i++) { var rowNodes = parsedRows[i]; var cell = newCell(); for (var j = 0; j < rowNodes.length; j++) if (!isStartOfArrow(rowNodes[j])) cell.body.push(rowNodes[j]); else { row.push(cell); j += 1; var arrowChar = assertSymbolNodeType(rowNodes[j]).text; var labels = new Array(2); labels[0] = { type: "ordgroup", mode: "math", body: [] }; labels[1] = { type: "ordgroup", mode: "math", body: [] }; if ("=|.".includes(arrowChar)); else if ("<>AV".includes(arrowChar)) for (var labelNum = 0; labelNum < 2; labelNum++) { var inLabel = true; for (var k = j + 1; k < rowNodes.length; k++) { if (isLabelEnd(rowNodes[k], arrowChar)) { inLabel = false; j = k; break; } if (isStartOfArrow(rowNodes[k])) throw new ParseError("Missing a " + arrowChar + " character to complete a CD arrow.", rowNodes[k]); labels[labelNum].body.push(rowNodes[k]); } if (inLabel) throw new ParseError("Missing a " + arrowChar + " character to complete a CD arrow.", rowNodes[j]); } else throw new ParseError("Expected one of \"<>AV=|.\" after @", rowNodes[j]); var wrappedArrow = { type: "styling", body: [cdArrow(arrowChar, labels, parser)], mode: "math", style: "display", resetFont: true }; row.push(wrappedArrow); cell = newCell(); } if (i % 2 === 0) row.push(cell); else row.shift(); row = []; body.push(row); } parser.gullet.endGroup(); parser.gullet.endGroup(); return { type: "array", mode: "math", body, arraystretch: 1, addJot: true, rowGaps: [null], cols: new Array(body[0].length).fill({ type: "align", align: "c", pregap: .25, postgap: .25 }), colSeparationType: "CD", hLinesBeforeRow: new Array(body.length + 1).fill([]) }; } defineFunction({ type: "cdlabel", names: ["\\\\cdleft", "\\\\cdright"], numArgs: 1, handler(_ref, args) { var parser = _ref.parser, funcName = _ref.funcName; return { type: "cdlabel", mode: parser.mode, side: funcName.slice(4), label: args[0] }; }, htmlBuilder(group, options) { var newOptions = options.havingStyle(options.style.sup()); var label = wrapFragment(buildGroup$1(group.label, newOptions, options), options); label.classes.push("cd-label-" + group.side); label.style.bottom = makeEm(.8 - label.depth); label.height = 0; label.depth = 0; return label; }, mathmlBuilder(group, options) { var label = new MathNode("mrow", [buildGroup(group.label, options)]); label = new MathNode("mpadded", [label]); label.setAttribute("width", "0"); if (group.side === "left") label.setAttribute("lspace", "-1width"); label.setAttribute("voffset", "0.7em"); label = new MathNode("mstyle", [label]); label.setAttribute("displaystyle", "false"); label.setAttribute("scriptlevel", "1"); return label; } }); defineFunction({ type: "cdlabelparent", names: ["\\\\cdparent"], numArgs: 1, handler(_ref2, args) { return { type: "cdlabelparent", mode: _ref2.parser.mode, fragment: args[0] }; }, htmlBuilder(group, options) { var parent = wrapFragment(buildGroup$1(group.fragment, options), options); parent.classes.push("cd-vert-arrow"); return parent; }, mathmlBuilder(group, options) { return new MathNode("mrow", [buildGroup(group.fragment, options)]); } }); defineFunction({ type: "textord", names: ["\\@char"], numArgs: 1, allowedInText: true, handler(_ref, args) { var parser = _ref.parser; var number = assertCharacterGroup(assertNodeType(args[0], "ordgroup"), "\\@char has non-numeric argument"); var code = parseInt(number); var text; if (isNaN(code)) throw new ParseError("\\@char has non-numeric argument " + number); else if (code < 0 || code > 1114111) throw new ParseError("\\@char with invalid code point " + number); else if (code <= 65535) text = String.fromCharCode(code); else { code -= 65536; text = String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320); } return { type: "textord", mode: parser.mode, text }; } }); var htmlBuilder$8 = (group, options) => { return makeFragment(buildExpression$1(group.body, options.withColor(group.color), false)); }; var mathmlBuilder$7 = (group, options) => { var node = new MathNode("mstyle", buildExpression(group.body, options.withColor(group.color))); node.setAttribute("mathcolor", group.color); return node; }; defineFunction({ type: "color", names: ["\\textcolor"], numArgs: 2, allowedInText: true, argTypes: ["color", "original"], handler(_ref, args) { var parser = _ref.parser; var color = assertNodeType(args[0], "color-token").color; var body = args[1]; return { type: "color", mode: parser.mode, color, body: ordargument(body) }; }, htmlBuilder: htmlBuilder$8, mathmlBuilder: mathmlBuilder$7 }); defineFunction({ type: "color", names: ["\\color"], numArgs: 1, allowedInText: true, argTypes: ["color"], handler(_ref2, args) { var parser = _ref2.parser, breakOnTokenText = _ref2.breakOnTokenText; var color = assertNodeType(args[0], "color-token").color; parser.gullet.macros.set("\\current@color", color); var body = parser.parseExpression(true, breakOnTokenText); return { type: "color", mode: parser.mode, color, body }; } }); defineFunction({ type: "cr", names: ["\\\\"], numArgs: 0, numOptionalArgs: 0, allowedInText: true, handler(_ref) { var parser = _ref.parser; var size = parser.gullet.future().text === "[" ? parser.parseSizeGroup(true) : null; var newLine = !parser.settings.displayMode || !handleStrict({ strict: parser.settings.strict, errorCode: "newLineInDisplayMode", errorMsg: "In LaTeX, \\\\ or \\newline does nothing in display mode", report: false }); return { type: "cr", mode: parser.mode, newLine, size: size && assertNodeType(size, "size").value }; }, htmlBuilder(group, options) { var span = makeSpan(["mspace"], [], options); if (group.newLine) { span.classes.push("katex-newline"); if (group.size) span.style.marginTop = makeEm(calculateSize(group.size, options)); } return span; }, mathmlBuilder(group, options) { var node = new MathNode("mspace"); if (group.newLine) { node.setAttribute("linebreak", "newline"); if (group.size) node.setAttribute("height", makeEm(calculateSize(group.size, options))); } return node; } }); var globalMap = { "\\global": "\\global", "\\long": "\\\\globallong", "\\\\globallong": "\\\\globallong", "\\def": "\\gdef", "\\gdef": "\\gdef", "\\edef": "\\xdef", "\\xdef": "\\xdef", "\\let": "\\\\globallet", "\\futurelet": "\\\\globalfuture" }; var checkControlSequence = (tok) => { var name = tok.text; if (/^(?:[\\{}$&#^_]|EOF)$/.test(name)) throw new ParseError("Expected a control sequence", tok); return name; }; var getRHS = (parser) => { var tok = parser.gullet.popToken(); if (tok.text === "=") { tok = parser.gullet.popToken(); if (tok.text === " ") tok = parser.gullet.popToken(); } return tok; }; var letCommand = (parser, name, tok, global) => { var macro = parser.gullet.macros.get(tok.text); if (macro == null) { tok.noexpand = true; macro = { tokens: [tok], numArgs: 0, unexpandable: !parser.gullet.isExpandable(tok.text) }; } parser.gullet.macros.set(name, macro, global); }; defineFunction({ type: "internal", names: [ "\\global", "\\long", "\\\\globallong" ], numArgs: 0, allowedInText: true, handler(_ref) { var parser = _ref.parser, funcName = _ref.funcName; parser.consumeSpaces(); var token = parser.fetch(); if (globalMap[token.text]) { if (funcName === "\\global" || funcName === "\\\\globallong") token.text = globalMap[token.text]; return assertNodeType(parser.parseFunction(), "internal"); } throw new ParseError("Invalid token after macro prefix", token); } }); defineFunction({ type: "internal", names: [ "\\def", "\\gdef", "\\edef", "\\xdef" ], numArgs: 0, allowedInText: true, primitive: true, handler(_ref2) { var parser = _ref2.parser, funcName = _ref2.funcName; var tok = parser.gullet.popToken(); var name = tok.text; if (/^(?:[\\{}$&#^_]|EOF)$/.test(name)) throw new ParseError("Expected a control sequence", tok); var numArgs = 0; var insert; var delimiters = [[]]; while (parser.gullet.future().text !== "{") { tok = parser.gullet.popToken(); if (tok.text === "#") { if (parser.gullet.future().text === "{") { insert = parser.gullet.future(); delimiters[numArgs].push("{"); break; } tok = parser.gullet.popToken(); if (!/^[1-9]$/.test(tok.text)) throw new ParseError("Invalid argument number \"" + tok.text + "\""); if (parseInt(tok.text) !== numArgs + 1) throw new ParseError("Argument number \"" + tok.text + "\" out of order"); numArgs++; delimiters.push([]); } else if (tok.text === "EOF") throw new ParseError("Expected a macro definition"); else delimiters[numArgs].push(tok.text); } var tokens = parser.gullet.consumeArg().tokens; if (insert) tokens.unshift(insert); if (funcName === "\\edef" || funcName === "\\xdef") { tokens = parser.gullet.expandTokens(tokens); tokens.reverse(); } parser.gullet.macros.set(name, { tokens, numArgs, delimiters }, funcName === globalMap[funcName]); return { type: "internal", mode: parser.mode }; } }); defineFunction({ type: "internal", names: ["\\let", "\\\\globallet"], numArgs: 0, allowedInText: true, primitive: true, handler(_ref3) { var parser = _ref3.parser, funcName = _ref3.funcName; var name = checkControlSequence(parser.gullet.popToken()); parser.gullet.consumeSpaces(); letCommand(parser, name, getRHS(parser), funcName === "\\\\globallet"); return { type: "internal", mode: parser.mode }; } }); defineFunction({ type: "internal", names: ["\\futurelet", "\\\\globalfuture"], numArgs: 0, allowedInText: true, primitive: true, handler(_ref4) { var parser = _ref4.parser, funcName = _ref4.funcName; var name = checkControlSequence(parser.gullet.popToken()); var middle = parser.gullet.popToken(); var tok = parser.gullet.popToken(); letCommand(parser, name, tok, funcName === "\\\\globalfuture"); parser.gullet.pushToken(tok); parser.gullet.pushToken(middle); return { type: "internal", mode: parser.mode }; } }); /** * This file deals with creating delimiters of various sizes. The TeXbook * discusses these routines on page 441-442, in the "Another subroutine sets box * x to a specified variable delimiter" paragraph. * * There are three main routines here. `makeSmallDelim` makes a delimiter in the * normal font, but in either text, script, or scriptscript style. * `makeLargeDelim` makes a delimiter in textstyle, but in one of the Size1, * Size2, Size3, or Size4 fonts. `makeStackedDelim` makes a delimiter out of * smaller pieces that are stacked on top of one another. * * The functions take a parameter `center`, which determines if the delimiter * should be centered around the axis. * * Then, there are three exposed functions. `sizedDelim` makes a delimiter in * one of the given sizes. This is used for things like `\bigl`. * `customSizedDelim` makes a delimiter with a given total height+depth. It is * called in places like `\sqrt`. `leftRightDelim` makes an appropriate * delimiter which surrounds an expression of a given height an depth. It is * used in `\left` and `\right`. */ /** * Get the metrics for a given symbol and font, after transformation (i.e. * after following replacement from symbols.js) */ var getMetrics = function getMetrics(symbol, font, mode) { var metrics = getCharacterMetrics(symbols.math[symbol] && symbols.math[symbol].replace || symbol, font, mode); if (!metrics) throw new Error("Unsupported symbol " + symbol + " and font size " + font + "."); return metrics; }; /** * Puts a delimiter span in a given style, and adds appropriate height, depth, * and maxFontSizes. */ var styleWrap = function styleWrap(delim, toStyle, options, classes) { var newOptions = options.havingBaseStyle(toStyle); var span = makeSpan(classes.concat(newOptions.sizingClasses(options)), [delim], options); var delimSizeMultiplier = newOptions.sizeMultiplier / options.sizeMultiplier; span.height *= delimSizeMultiplier; span.depth *= delimSizeMultiplier; span.maxFontSize = newOptions.sizeMultiplier; return span; }; var centerSpan = function centerSpan(span, options, style) { var newOptions = options.havingBaseStyle(style); var shift = (1 - options.sizeMultiplier / newOptions.sizeMultiplier) * options.fontMetrics().axisHeight; span.classes.push("delimcenter"); span.style.top = makeEm(shift); span.height -= shift; span.depth += shift; }; /** * Makes a small delimiter. This is a delimiter that comes in the Main-Regular * font, but is restyled to either be in textstyle, scriptstyle, or * scriptscriptstyle. */ var makeSmallDelim = function makeSmallDelim(delim, style, center, options, mode, classes) { var span = styleWrap(makeSymbol(delim, "Main-Regular", mode, options), style, options, classes); if (center) centerSpan(span, options, style); return span; }; /** * Builds a symbol in the given font size (note size is an integer) */ var mathrmSize = function mathrmSize(value, size, mode, options) { return makeSymbol(value, "Size" + size + "-Regular", mode, options); }; /** * Makes a large delimiter. This is a delimiter that comes in the Size1, Size2, * Size3, or Size4 fonts. It is always rendered in textstyle. */ var makeLargeDelim = function makeLargeDelim(delim, size, center, options, mode, classes) { var inner = mathrmSize(delim, size, mode, options); var span = styleWrap(makeSpan(["delimsizing", "size" + size], [inner], options), Style$1.TEXT, options, classes); if (center) centerSpan(span, options, Style$1.TEXT); return span; }; /** * Make a span from a font glyph with the given offset and in the given font. * This is used in makeStackedDelim to make the stacking pieces for the delimiter. */ var makeGlyphSpan = function makeGlyphSpan(symbol, font, mode, options) { var sizeClass; if (font === "Size1-Regular") sizeClass = "delim-size1"; else sizeClass = "delim-size4"; return { type: "elem", elem: makeSpan(["delimsizinginner", sizeClass], [makeSpan([], [makeSymbol(symbol, font, mode, options)])]) }; }; var makeInner = function makeInner(ch, height, options) { var width = fontMetricsData["Size4-Regular"][ch.charCodeAt(0)] ? fontMetricsData["Size4-Regular"][ch.charCodeAt(0)][4] : fontMetricsData["Size1-Regular"][ch.charCodeAt(0)][4]; var span = makeSvgSpan([], [new SvgNode([new PathNode("inner", innerPath(ch, Math.round(1e3 * height)))], { "width": makeEm(width), "height": makeEm(height), "style": "width:" + makeEm(width), "viewBox": "0 0 " + 1e3 * width + " " + Math.round(1e3 * height), "preserveAspectRatio": "xMinYMin" })], options); span.height = height; span.style.height = makeEm(height); span.style.width = makeEm(width); return { type: "elem", elem: span }; }; var lapInEms = .008; var lap = { type: "kern", size: -1 * lapInEms }; var verts = /* @__PURE__ */ new Set([ "|", "\\lvert", "\\rvert", "\\vert" ]); var doubleVerts = /* @__PURE__ */ new Set([ "\\|", "\\lVert", "\\rVert", "\\Vert" ]); /** * Make a stacked delimiter out of a given delimiter, with the total height at * least `heightTotal`. This routine is mentioned on page 442 of the TeXbook. */ var makeStackedDelim = function makeStackedDelim(delim, heightTotal, center, options, mode, classes) { var top; var middle; var repeat; var bottom; var svgLabel = ""; var viewBoxWidth = 0; top = repeat = bottom = delim; middle = null; var font = "Size1-Regular"; if (delim === "\\uparrow") repeat = bottom = "⏐"; else if (delim === "\\Uparrow") repeat = bottom = "‖"; else if (delim === "\\downarrow") top = repeat = "⏐"; else if (delim === "\\Downarrow") top = repeat = "‖"; else if (delim === "\\updownarrow") { top = "\\uparrow"; repeat = "⏐"; bottom = "\\downarrow"; } else if (delim === "\\Updownarrow") { top = "\\Uparrow"; repeat = "‖"; bottom = "\\Downarrow"; } else if (verts.has(delim)) { repeat = "∣"; svgLabel = "vert"; viewBoxWidth = 333; } else if (doubleVerts.has(delim)) { repeat = "∥"; svgLabel = "doublevert"; viewBoxWidth = 556; } else if (delim === "[" || delim === "\\lbrack") { top = "⎡"; repeat = "⎢"; bottom = "⎣"; font = "Size4-Regular"; svgLabel = "lbrack"; viewBoxWidth = 667; } else if (delim === "]" || delim === "\\rbrack") { top = "⎤"; repeat = "⎥"; bottom = "⎦"; font = "Size4-Regular"; svgLabel = "rbrack"; viewBoxWidth = 667; } else if (delim === "\\lfloor" || delim === "⌊") { repeat = top = "⎢"; bottom = "⎣"; font = "Size4-Regular"; svgLabel = "lfloor"; viewBoxWidth = 667; } else if (delim === "\\lceil" || delim === "⌈") { top = "⎡"; repeat = bottom = "⎢"; font = "Size4-Regular"; svgLabel = "lceil"; viewBoxWidth = 667; } else if (delim === "\\rfloor" || delim === "⌋") { repeat = top = "⎥"; bottom = "⎦"; font = "Size4-Regular"; svgLabel = "rfloor"; viewBoxWidth = 667; } else if (delim === "\\rceil" || delim === "⌉") { top = "⎤"; repeat = bottom = "⎥"; font = "Size4-Regular"; svgLabel = "rceil"; viewBoxWidth = 667; } else if (delim === "(" || delim === "\\lparen") { top = "⎛"; repeat = "⎜"; bottom = "⎝"; font = "Size4-Regular"; svgLabel = "lparen"; viewBoxWidth = 875; } else if (delim === ")" || delim === "\\rparen") { top = "⎞"; repeat = "⎟"; bottom = "⎠"; font = "Size4-Regular"; svgLabel = "rparen"; viewBoxWidth = 875; } else if (delim === "\\{" || delim === "\\lbrace") { top = "⎧"; middle = "⎨"; bottom = "⎩"; repeat = "⎪"; font = "Size4-Regular"; } else if (delim === "\\}" || delim === "\\rbrace") { top = "⎫"; middle = "⎬"; bottom = "⎭"; repeat = "⎪"; font = "Size4-Regular"; } else if (delim === "\\lgroup" || delim === "⟮") { top = "⎧"; bottom = "⎩"; repeat = "⎪"; font = "Size4-Regular"; } else if (delim === "\\rgroup" || delim === "⟯") { top = "⎫"; bottom = "⎭"; repeat = "⎪"; font = "Size4-Regular"; } else if (delim === "\\lmoustache" || delim === "⎰") { top = "⎧"; bottom = "⎭"; repeat = "⎪"; font = "Size4-Regular"; } else if (delim === "\\rmoustache" || delim === "⎱") { top = "⎫"; bottom = "⎩"; repeat = "⎪"; font = "Size4-Regular"; } var topMetrics = getMetrics(top, font, mode); var topHeightTotal = topMetrics.height + topMetrics.depth; var repeatMetrics = getMetrics(repeat, font, mode); var repeatHeightTotal = repeatMetrics.height + repeatMetrics.depth; var bottomMetrics = getMetrics(bottom, font, mode); var bottomHeightTotal = bottomMetrics.height + bottomMetrics.depth; var middleHeightTotal = 0; var middleFactor = 1; if (middle !== null) { var middleMetrics = getMetrics(middle, font, mode); middleHeightTotal = middleMetrics.height + middleMetrics.depth; middleFactor = 2; } var minHeight = topHeightTotal + bottomHeightTotal + middleHeightTotal; var realHeightTotal = minHeight + Math.max(0, Math.ceil((heightTotal - minHeight) / (middleFactor * repeatHeightTotal))) * middleFactor * repeatHeightTotal; var axisHeight = options.fontMetrics().axisHeight; if (center) axisHeight *= options.sizeMultiplier; var depth = realHeightTotal / 2 - axisHeight; var stack = []; if (svgLabel.length > 0) { var midHeight = realHeightTotal - topHeightTotal - bottomHeightTotal; var viewBoxHeight = Math.round(realHeightTotal * 1e3); var pathStr = tallDelim(svgLabel, Math.round(midHeight * 1e3)); var path = new PathNode(svgLabel, pathStr); var width = makeEm(viewBoxWidth / 1e3); var height = makeEm(viewBoxHeight / 1e3); var wrapper = makeSvgSpan([], [new SvgNode([path], { "width": width, "height": height, "viewBox": "0 0 " + viewBoxWidth + " " + viewBoxHeight })], options); wrapper.height = viewBoxHeight / 1e3; wrapper.style.width = width; wrapper.style.height = height; stack.push({ type: "elem", elem: wrapper }); } else { stack.push(makeGlyphSpan(bottom, font, mode, options)); stack.push(lap); if (middle === null) { var innerHeight = realHeightTotal - topHeightTotal - bottomHeightTotal + 2 * lapInEms; stack.push(makeInner(repeat, innerHeight, options)); } else { var _innerHeight = (realHeightTotal - topHeightTotal - bottomHeightTotal - middleHeightTotal) / 2 + 2 * lapInEms; stack.push(makeInner(repeat, _innerHeight, options)); stack.push(lap); stack.push(makeGlyphSpan(middle, font, mode, options)); stack.push(lap); stack.push(makeInner(repeat, _innerHeight, options)); } stack.push(lap); stack.push(makeGlyphSpan(top, font, mode, options)); } var newOptions = options.havingBaseStyle(Style$1.TEXT); return styleWrap(makeSpan(["delimsizing", "mult"], [makeVList({ positionType: "bottom", positionData: depth, children: stack })], newOptions), Style$1.TEXT, options, classes); }; var vbPad = 80; var emPad = .08; var sqrtSvg = function sqrtSvg(sqrtName, height, viewBoxHeight, extraVinculum, options) { return makeSvgSpan(["hide-tail"], [new SvgNode([new PathNode(sqrtName, sqrtPath(sqrtName, extraVinculum, viewBoxHeight))], { "width": "400em", "height": makeEm(height), "viewBox": "0 0 400000 " + viewBoxHeight, "preserveAspectRatio": "xMinYMin slice" })], options); }; /** * Make a sqrt image of the given height, */ var makeSqrtImage = function makeSqrtImage(height, options) { var newOptions = options.havingBaseSizing(); var delim = traverseSequence("\\surd", height * newOptions.sizeMultiplier, stackLargeDelimiterSequence, newOptions); var sizeMultiplier = newOptions.sizeMultiplier; var extraVinculum = Math.max(0, options.minRuleThickness - options.fontMetrics().sqrtRuleThickness); var span; var spanHeight; var texHeight; var viewBoxHeight; var advanceWidth; if (delim.type === "small") { viewBoxHeight = 1e3 + 1e3 * extraVinculum + vbPad; if (height < 1) sizeMultiplier = 1; else if (height < 1.4) sizeMultiplier = .7; spanHeight = (1 + extraVinculum + emPad) / sizeMultiplier; texHeight = (1 + extraVinculum) / sizeMultiplier; span = sqrtSvg("sqrtMain", spanHeight, viewBoxHeight, extraVinculum, options); span.style.minWidth = "0.853em"; advanceWidth = .833 / sizeMultiplier; } else if (delim.type === "large") { viewBoxHeight = (1e3 + vbPad) * sizeToMaxHeight[delim.size]; texHeight = (sizeToMaxHeight[delim.size] + extraVinculum) / sizeMultiplier; spanHeight = (sizeToMaxHeight[delim.size] + extraVinculum + emPad) / sizeMultiplier; span = sqrtSvg("sqrtSize" + delim.size, spanHeight, viewBoxHeight, extraVinculum, options); span.style.minWidth = "1.02em"; advanceWidth = 1 / sizeMultiplier; } else { spanHeight = height + extraVinculum + emPad; texHeight = height + extraVinculum; viewBoxHeight = Math.floor(1e3 * height + extraVinculum) + vbPad; span = sqrtSvg("sqrtTall", spanHeight, viewBoxHeight, extraVinculum, options); span.style.minWidth = "0.742em"; advanceWidth = 1.056; } span.height = texHeight; span.style.height = makeEm(spanHeight); return { span, advanceWidth, ruleWidth: (options.fontMetrics().sqrtRuleThickness + extraVinculum) * sizeMultiplier }; }; var stackLargeDelimiters = /* @__PURE__ */ new Set([ "(", "\\lparen", ")", "\\rparen", "[", "\\lbrack", "]", "\\rbrack", "\\{", "\\lbrace", "\\}", "\\rbrace", "\\lfloor", "\\rfloor", "⌊", "⌋", "\\lceil", "\\rceil", "⌈", "⌉", "\\surd" ]); var stackAlwaysDelimiters = /* @__PURE__ */ new Set([ "\\uparrow", "\\downarrow", "\\updownarrow", "\\Uparrow", "\\Downarrow", "\\Updownarrow", "|", "\\|", "\\vert", "\\Vert", "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\lgroup", "\\rgroup", "⟮", "⟯", "\\lmoustache", "\\rmoustache", "⎰", "⎱" ]); var stackNeverDelimiters = /* @__PURE__ */ new Set([ "<", ">", "\\langle", "\\rangle", "/", "\\backslash", "\\lt", "\\gt" ]); var sizeToMaxHeight = [ 0, 1.2, 1.8, 2.4, 3 ]; /** * Used to create a delimiter of a specific size, where `size` is 1, 2, 3, or 4. */ var makeSizedDelim = function makeSizedDelim(delim, size, options, mode, classes) { if (delim === "<" || delim === "\\lt" || delim === "⟨") delim = "\\langle"; else if (delim === ">" || delim === "\\gt" || delim === "⟩") delim = "\\rangle"; if (stackLargeDelimiters.has(delim) || stackNeverDelimiters.has(delim)) return makeLargeDelim(delim, size, false, options, mode, classes); else if (stackAlwaysDelimiters.has(delim)) return makeStackedDelim(delim, sizeToMaxHeight[size], false, options, mode, classes); else throw new ParseError("Illegal delimiter: '" + delim + "'"); }; var stackNeverDelimiterSequence = [ { type: "small", style: Style$1.SCRIPTSCRIPT }, { type: "small", style: Style$1.SCRIPT }, { type: "small", style: Style$1.TEXT }, { type: "large", size: 1 }, { type: "large", size: 2 }, { type: "large", size: 3 }, { type: "large", size: 4 } ]; var stackAlwaysDelimiterSequence = [ { type: "small", style: Style$1.SCRIPTSCRIPT }, { type: "small", style: Style$1.SCRIPT }, { type: "small", style: Style$1.TEXT }, { type: "stack" } ]; var stackLargeDelimiterSequence = [ { type: "small", style: Style$1.SCRIPTSCRIPT }, { type: "small", style: Style$1.SCRIPT }, { type: "small", style: Style$1.TEXT }, { type: "large", size: 1 }, { type: "large", size: 2 }, { type: "large", size: 3 }, { type: "large", size: 4 }, { type: "stack" } ]; /** * Get the font used in a delimiter based on what kind of delimiter it is. * TODO(#963) Use more specific font family return type once that is introduced. */ var delimTypeToFont = function delimTypeToFont(type) { if (type.type === "small") return "Main-Regular"; else if (type.type === "large") return "Size" + type.size + "-Regular"; else if (type.type === "stack") return "Size4-Regular"; else { var delimKind = type.type; throw new Error("Add support for delim type '" + delimKind + "' here."); } }; /** * Traverse a sequence of types of delimiters to decide what kind of delimiter * should be used to create a delimiter of the given height+depth. */ var traverseSequence = function traverseSequence(delim, height, sequence, options) { for (var i = Math.min(2, 3 - options.style.size); i < sequence.length; i++) { var delimType = sequence[i]; if (delimType.type === "stack") break; var metrics = getMetrics(delim, delimTypeToFont(delimType), "math"); var heightDepth = metrics.height + metrics.depth; if (delimType.type === "small") { var newOptions = options.havingBaseStyle(delimType.style); heightDepth *= newOptions.sizeMultiplier; } if (heightDepth > height) return delimType; } return sequence[sequence.length - 1]; }; /** * Make a delimiter of a given height+depth, with optional centering. Here, we * traverse the sequences, and create a delimiter that the sequence tells us to. */ var makeCustomSizedDelim = function makeCustomSizedDelim(delim, height, center, options, mode, classes) { if (delim === "<" || delim === "\\lt" || delim === "⟨") delim = "\\langle"; else if (delim === ">" || delim === "\\gt" || delim === "⟩") delim = "\\rangle"; var sequence; if (stackNeverDelimiters.has(delim)) sequence = stackNeverDelimiterSequence; else if (stackLargeDelimiters.has(delim)) sequence = stackLargeDelimiterSequence; else sequence = stackAlwaysDelimiterSequence; var delimType = traverseSequence(delim, height, sequence, options); if (delimType.type === "small") return makeSmallDelim(delim, delimType.style, center, options, mode, classes); else if (delimType.type === "large") return makeLargeDelim(delim, delimType.size, center, options, mode, classes); else return makeStackedDelim(delim, height, center, options, mode, classes); }; /** * Make a delimiter for use with `\left` and `\right`, given a height and depth * of an expression that the delimiters surround. */ var makeLeftRightDelim = function makeLeftRightDelim(delim, height, depth, options, mode, classes) { var axisHeight = options.fontMetrics().axisHeight * options.sizeMultiplier; var delimiterFactor = 901; var delimiterExtend = 5 / options.fontMetrics().ptPerEm; var maxDistFromAxis = Math.max(height - axisHeight, depth + axisHeight); return makeCustomSizedDelim(delim, Math.max(maxDistFromAxis / 500 * delimiterFactor, 2 * maxDistFromAxis - delimiterExtend), true, options, mode, classes); }; var delimiterSizes = { "\\bigl": { mclass: "mopen", size: 1 }, "\\Bigl": { mclass: "mopen", size: 2 }, "\\biggl": { mclass: "mopen", size: 3 }, "\\Biggl": { mclass: "mopen", size: 4 }, "\\bigr": { mclass: "mclose", size: 1 }, "\\Bigr": { mclass: "mclose", size: 2 }, "\\biggr": { mclass: "mclose", size: 3 }, "\\Biggr": { mclass: "mclose", size: 4 }, "\\bigm": { mclass: "mrel", size: 1 }, "\\Bigm": { mclass: "mrel", size: 2 }, "\\biggm": { mclass: "mrel", size: 3 }, "\\Biggm": { mclass: "mrel", size: 4 }, "\\big": { mclass: "mord", size: 1 }, "\\Big": { mclass: "mord", size: 2 }, "\\bigg": { mclass: "mord", size: 3 }, "\\Bigg": { mclass: "mord", size: 4 } }; var delimiters = /* @__PURE__ */ new Set([ "(", "\\lparen", ")", "\\rparen", "[", "\\lbrack", "]", "\\rbrack", "\\{", "\\lbrace", "\\}", "\\rbrace", "\\lfloor", "\\rfloor", "⌊", "⌋", "\\lceil", "\\rceil", "⌈", "⌉", "<", ">", "\\langle", "⟨", "\\rangle", "⟩", "\\lt", "\\gt", "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\lgroup", "\\rgroup", "⟮", "⟯", "\\lmoustache", "\\rmoustache", "⎰", "⎱", "/", "\\backslash", "|", "\\vert", "\\|", "\\Vert", "\\uparrow", "\\Uparrow", "\\downarrow", "\\Downarrow", "\\updownarrow", "\\Updownarrow", "." ]); function isMiddleDelimNode(node) { return "isMiddle" in node; } function checkDelimiter(delim, context) { var symDelim = checkSymbolNodeType(delim); if (symDelim && delimiters.has(symDelim.text)) return symDelim; else if (symDelim) throw new ParseError("Invalid delimiter '" + symDelim.text + "' after '" + context.funcName + "'", delim); else throw new ParseError("Invalid delimiter type '" + delim.type + "'", delim); } defineFunction({ type: "delimsizing", names: [ "\\bigl", "\\Bigl", "\\biggl", "\\Biggl", "\\bigr", "\\Bigr", "\\biggr", "\\Biggr", "\\bigm", "\\Bigm", "\\biggm", "\\Biggm", "\\big", "\\Big", "\\bigg", "\\Bigg" ], numArgs: 1, argTypes: ["primitive"], handler: (context, args) => { var delim = checkDelimiter(normalizeArgument(args[0]), context); return { type: "delimsizing", mode: context.parser.mode, size: delimiterSizes[context.funcName].size, mclass: delimiterSizes[context.funcName].mclass, delim: delim.text }; }, htmlBuilder: (group, options) => { if (group.delim === ".") return makeSpan([group.mclass]); return makeSizedDelim(group.delim, group.size, options, group.mode, [group.mclass]); }, mathmlBuilder: (group) => { var children = []; if (group.delim !== ".") children.push(makeText(group.delim, group.mode)); var node = new MathNode("mo", children); if (group.mclass === "mopen" || group.mclass === "mclose") node.setAttribute("fence", "true"); else node.setAttribute("fence", "false"); node.setAttribute("stretchy", "true"); var size = makeEm(sizeToMaxHeight[group.size]); node.setAttribute("minsize", size); node.setAttribute("maxsize", size); return node; } }); function assertParsed(group) { if (!group.body) throw new Error("Bug: The leftright ParseNode wasn't fully parsed."); } defineFunction({ type: "leftright-right", names: ["\\right"], numArgs: 1, primitive: true, handler: (context, args) => { var color = context.parser.gullet.macros.get("\\current@color"); if (color && typeof color !== "string") throw new ParseError("\\current@color set to non-string in \\right"); return { type: "leftright-right", mode: context.parser.mode, delim: checkDelimiter(args[0], context).text, color }; } }); defineFunction({ type: "leftright", names: ["\\left"], numArgs: 1, primitive: true, handler: (context, args) => { var delim = checkDelimiter(args[0], context); var parser = context.parser; ++parser.leftrightDepth; var body = parser.parseExpression(false); --parser.leftrightDepth; parser.expect("\\right", false); var right = assertNodeType(parser.parseFunction(), "leftright-right"); return { type: "leftright", mode: parser.mode, body, left: delim.text, right: right.delim, rightColor: right.color }; }, htmlBuilder: (group, options) => { assertParsed(group); var inner = buildExpression$1(group.body, options, true, ["mopen", "mclose"]); var innerHeight = 0; var innerDepth = 0; var hadMiddle = false; for (var i = 0; i < inner.length; i++) { var node = inner[i]; if (isMiddleDelimNode(node)) hadMiddle = true; else { innerHeight = Math.max(inner[i].height, innerHeight); innerDepth = Math.max(inner[i].depth, innerDepth); } } innerHeight *= options.sizeMultiplier; innerDepth *= options.sizeMultiplier; var leftDelim; if (group.left === ".") leftDelim = makeNullDelimiter(options, ["mopen"]); else leftDelim = makeLeftRightDelim(group.left, innerHeight, innerDepth, options, group.mode, ["mopen"]); inner.unshift(leftDelim); if (hadMiddle) for (var _i = 1; _i < inner.length; _i++) { var middleDelim = inner[_i]; if (isMiddleDelimNode(middleDelim)) { var isMiddle = middleDelim.isMiddle; inner[_i] = makeLeftRightDelim(isMiddle.delim, innerHeight, innerDepth, isMiddle.options, group.mode, []); } } var rightDelim; if (group.right === ".") rightDelim = makeNullDelimiter(options, ["mclose"]); else { var colorOptions = group.rightColor ? options.withColor(group.rightColor) : options; rightDelim = makeLeftRightDelim(group.right, innerHeight, innerDepth, colorOptions, group.mode, ["mclose"]); } inner.push(rightDelim); return makeSpan(["minner"], inner, options); }, mathmlBuilder: (group, options) => { assertParsed(group); var inner = buildExpression(group.body, options); if (group.left !== ".") { var leftNode = new MathNode("mo", [makeText(group.left, group.mode)]); leftNode.setAttribute("fence", "true"); inner.unshift(leftNode); } if (group.right !== ".") { var rightNode = new MathNode("mo", [makeText(group.right, group.mode)]); rightNode.setAttribute("fence", "true"); if (group.rightColor) rightNode.setAttribute("mathcolor", group.rightColor); inner.push(rightNode); } return makeRow(inner); } }); defineFunction({ type: "middle", names: ["\\middle"], numArgs: 1, primitive: true, handler: (context, args) => { var delim = checkDelimiter(args[0], context); if (!context.parser.leftrightDepth) throw new ParseError("\\middle without preceding \\left", delim); return { type: "middle", mode: context.parser.mode, delim: delim.text }; }, htmlBuilder: (group, options) => { var middleDelim; if (group.delim === ".") middleDelim = makeNullDelimiter(options, []); else { middleDelim = makeSizedDelim(group.delim, 1, options, group.mode, []); middleDelim.isMiddle = { delim: group.delim, options }; } return middleDelim; }, mathmlBuilder: (group, options) => { var middleNode = new MathNode("mo", [group.delim === "\\vert" || group.delim === "|" ? makeText("|", "text") : makeText(group.delim, group.mode)]); middleNode.setAttribute("fence", "true"); middleNode.setAttribute("lspace", "0.05em"); middleNode.setAttribute("rspace", "0.05em"); return middleNode; } }); var htmlBuilder$7 = (group, options) => { var inner = wrapFragment(buildGroup$1(group.body, options), options); var label = group.label.slice(1); var scale = options.sizeMultiplier; var img; var imgShift; var isSingleChar = isCharacterBox(group.body); if (label === "sout") { img = makeSpan(["katex-stretchy", "katex-sout"]); img.height = options.fontMetrics().defaultRuleThickness / scale; imgShift = -.5 * options.fontMetrics().xHeight; } else if (label === "phase") { var lineWeight = calculateSize({ number: .6, unit: "pt" }, options); var clearance = calculateSize({ number: .35, unit: "ex" }, options); var newOptions = options.havingBaseSizing(); scale = scale / newOptions.sizeMultiplier; var angleHeight = inner.height + inner.depth + lineWeight + clearance; inner.style.paddingLeft = makeEm(angleHeight / 2 + lineWeight); var viewBoxHeight = Math.floor(1e3 * angleHeight * scale); img = makeSvgSpan(["hide-tail"], [new SvgNode([new PathNode("phase", phasePath(viewBoxHeight))], { "width": "400em", "height": makeEm(viewBoxHeight / 1e3), "viewBox": "0 0 400000 " + viewBoxHeight, "preserveAspectRatio": "xMinYMin slice" })], options); img.style.height = makeEm(angleHeight); imgShift = inner.depth + lineWeight + clearance; } else { if (/cancel/.test(label)) { if (!isSingleChar) inner.classes.push("cancel-pad"); } else if (label === "angl") inner.classes.push("anglpad"); else inner.classes.push("boxpad"); var topPad; var bottomPad; var ruleThickness = 0; if (/box/.test(label)) { ruleThickness = Math.max(options.fontMetrics().fboxrule, options.minRuleThickness); topPad = options.fontMetrics().fboxsep + (label === "colorbox" ? 0 : ruleThickness); bottomPad = topPad; } else if (label === "angl") { ruleThickness = Math.max(options.fontMetrics().defaultRuleThickness, options.minRuleThickness); topPad = 4 * ruleThickness; bottomPad = Math.max(0, .25 - inner.depth); } else { topPad = isSingleChar ? .2 : 0; bottomPad = topPad; } img = stretchyEnclose(inner, label, topPad, bottomPad, options); if (/fbox|boxed|fcolorbox/.test(label)) { img.style.borderStyle = "solid"; img.style.borderWidth = makeEm(ruleThickness); } else if (label === "angl" && ruleThickness !== .049) { img.style.borderTopWidth = makeEm(ruleThickness); img.style.borderRightWidth = makeEm(ruleThickness); } imgShift = inner.depth + bottomPad; if (group.backgroundColor) { img.style.backgroundColor = group.backgroundColor; if (group.borderColor) img.style.borderColor = group.borderColor; } } var vlist; if (group.backgroundColor) vlist = makeVList({ positionType: "individualShift", children: [{ type: "elem", elem: img, shift: imgShift }, { type: "elem", elem: inner, shift: 0 }] }); else { var classes = /cancel|phase/.test(label) ? ["svg-align"] : []; vlist = makeVList({ positionType: "individualShift", children: [{ type: "elem", elem: inner, shift: 0 }, { type: "elem", elem: img, shift: imgShift, wrapperClasses: classes }] }); } if (/cancel/.test(label)) { vlist.height = inner.height; vlist.depth = inner.depth; } if (/cancel/.test(label) && !isSingleChar) return makeSpan(["mord", "cancel-lap"], [vlist], options); else return makeSpan(["mord"], [vlist], options); }; var mathmlBuilder$6 = (group, options) => { var fboxsep; var node = new MathNode(group.label.includes("colorbox") ? "mpadded" : "menclose", [buildGroup(group.body, options)]); switch (group.label) { case "\\cancel": node.setAttribute("notation", "updiagonalstrike"); break; case "\\bcancel": node.setAttribute("notation", "downdiagonalstrike"); break; case "\\phase": node.setAttribute("notation", "phasorangle"); break; case "\\sout": node.setAttribute("notation", "horizontalstrike"); break; case "\\fbox": node.setAttribute("notation", "box"); break; case "\\angl": node.setAttribute("notation", "actuarial"); break; case "\\fcolorbox": case "\\colorbox": fboxsep = options.fontMetrics().fboxsep * options.fontMetrics().ptPerEm; node.setAttribute("width", "+" + 2 * fboxsep + "pt"); node.setAttribute("height", "+" + 2 * fboxsep + "pt"); node.setAttribute("lspace", fboxsep + "pt"); node.setAttribute("voffset", fboxsep + "pt"); if (group.label === "\\fcolorbox") { var thk = Math.max(options.fontMetrics().fboxrule, options.minRuleThickness); node.setAttribute("style", "border: " + makeEm(thk) + " solid " + group.borderColor); } break; case "\\xcancel": node.setAttribute("notation", "updiagonalstrike downdiagonalstrike"); } if (group.backgroundColor) node.setAttribute("mathbackground", group.backgroundColor); return node; }; defineFunction({ type: "enclose", names: ["\\colorbox"], numArgs: 2, allowedInText: true, argTypes: ["color", "hbox"], handler(_ref, args, optArgs) { var parser = _ref.parser, funcName = _ref.funcName; var color = assertNodeType(args[0], "color-token").color; var body = args[1]; return { type: "enclose", mode: parser.mode, label: funcName, backgroundColor: color, body }; }, htmlBuilder: htmlBuilder$7, mathmlBuilder: mathmlBuilder$6 }); defineFunction({ type: "enclose", names: ["\\fcolorbox"], numArgs: 3, allowedInText: true, argTypes: [ "color", "color", "hbox" ], handler(_ref2, args, optArgs) { var parser = _ref2.parser, funcName = _ref2.funcName; var borderColor = assertNodeType(args[0], "color-token").color; var backgroundColor = assertNodeType(args[1], "color-token").color; var body = args[2]; return { type: "enclose", mode: parser.mode, label: funcName, backgroundColor, borderColor, body }; } }); defineFunction({ type: "enclose", names: ["\\fbox"], numArgs: 1, argTypes: ["hbox"], allowedInText: true, handler(_ref3, args) { return { type: "enclose", mode: _ref3.parser.mode, label: "\\fbox", body: args[0] }; } }); defineFunction({ type: "enclose", names: [ "\\cancel", "\\bcancel", "\\xcancel", "\\phase" ], numArgs: 1, handler(_ref4, args) { var parser = _ref4.parser, funcName = _ref4.funcName; var body = args[0]; return { type: "enclose", mode: parser.mode, label: funcName, body }; } }); defineFunction({ type: "enclose", names: ["\\sout"], numArgs: 1, allowedInText: true, handler(_ref5, args) { var parser = _ref5.parser, funcName = _ref5.funcName; if (parser.mode === "math") handleStrict({ strict: parser.settings.strict, errorCode: "mathVsSout", errorMsg: "LaTeX's \\sout works only in text mode", report: true }); var body = args[0]; return { type: "enclose", mode: parser.mode, label: funcName, body }; } }); defineFunction({ type: "enclose", names: ["\\angl"], numArgs: 1, argTypes: ["hbox"], allowedInText: false, handler(_ref6, args) { return { type: "enclose", mode: _ref6.parser.mode, label: "\\angl", body: args[0] }; } }); /** * All registered environments. * `environments.js` exports this same dictionary again and makes it public. * `Parser.js` requires this dictionary via `environments.js`. */ var _environments = {}; function defineEnvironment(_ref) { var type = _ref.type, names = _ref.names, props = _ref.props, handler = _ref.handler, htmlBuilder = _ref.htmlBuilder, mathmlBuilder = _ref.mathmlBuilder; var data = { type, numArgs: props.numArgs || 0, allowedInText: false, numOptionalArgs: 0, handler }; for (var i = 0; i < names.length; ++i) _environments[names[i]] = data; if (htmlBuilder) _htmlGroupBuilders[type] = htmlBuilder; if (mathmlBuilder) _mathmlGroupBuilders[type] = mathmlBuilder; } /** * All registered global/built-in macros. * `macros.js` exports this same dictionary again and makes it public. * `Parser.js` requires this dictionary via `macros.js`. */ var _macros = {}; function defineMacro(name, body) { _macros[name] = body; } /** * Lexing or parsing positional information for error reporting. * This object is immutable. */ var SourceLocation = class SourceLocation { constructor(lexer, start, end) { this.lexer = void 0; this.start = void 0; this.end = void 0; this.lexer = lexer; this.start = start; this.end = end; } /** * Merges two `SourceLocation`s from location providers, given they are * provided in order of appearance. * - Returns the first one's location if only the first is provided. * - Returns a merged range of the first and the last if both are provided * and their lexers match. * - Otherwise, returns null. */ static range(first, second) { if (!second) return first && first.loc; else if (!first || !first.loc || !second.loc || first.loc.lexer !== second.loc.lexer) return null; else return new SourceLocation(first.loc.lexer, first.loc.start, second.loc.end); } }; /** * The resulting token returned from `lex`. * * It consists of the token text plus some position information. * The position information is essentially a range in an input string, * but instead of referencing the bare input string, we refer to the lexer. * That way it is possible to attach extra metadata to the input string, * like for example a file name or similar. * * The position information is optional, so it is OK to construct synthetic * tokens if appropriate. Not providing available position information may * lead to degraded error reporting, though. */ var Token = class Token { constructor(text, loc) { this.text = void 0; this.loc = void 0; this.noexpand = void 0; this.treatAsRelax = void 0; this.text = text; this.loc = loc; } /** * Given a pair of tokens (this and endToken), compute a `Token` encompassing * the whole input range enclosed by these two. */ range(endToken, text) { return new Token(text, SourceLocation.range(this, endToken)); } }; function getHLines(parser) { var hlineInfo = []; parser.consumeSpaces(); var nxt = parser.fetch().text; if (nxt === "\\relax") { parser.consume(); parser.consumeSpaces(); nxt = parser.fetch().text; } while (nxt === "\\hline" || nxt === "\\hdashline") { parser.consume(); hlineInfo.push(nxt === "\\hdashline"); parser.consumeSpaces(); nxt = parser.fetch().text; } return hlineInfo; } var validateAmsEnvironmentContext = (context) => { if (!context.parser.settings.displayMode) throw new ParseError("{" + context.envName + "} can be used only in display mode."); }; var gatherEnvironments = /* @__PURE__ */ new Set(["gather", "gather*"]); function getAutoTag(name) { if (!name.includes("ed")) return !name.includes("*"); } /** * Parse the body of the environment, with rows delimited by \\ and * columns delimited by &, and create a nested list in row-major order * with one group per cell. If given an optional argument style * ("text", "display", etc.), then each cell is cast into that style. */ function parseArray(parser, _ref, style) { var hskipBeforeAndAfter = _ref.hskipBeforeAndAfter, addJot = _ref.addJot, cols = _ref.cols, arraystretch = _ref.arraystretch, colSeparationType = _ref.colSeparationType, autoTag = _ref.autoTag, singleRow = _ref.singleRow, emptySingleRow = _ref.emptySingleRow, maxNumCols = _ref.maxNumCols, leqno = _ref.leqno; parser.gullet.beginGroup(); if (!singleRow) parser.gullet.macros.set("\\cr", "\\\\\\relax"); if (!arraystretch) { var stretch = parser.gullet.expandMacroAsText("\\arraystretch"); if (stretch == null) arraystretch = 1; else { arraystretch = parseFloat(stretch); if (!arraystretch || arraystretch < 0) throw new ParseError("Invalid \\arraystretch: " + stretch); } } parser.gullet.beginGroup(); var row = []; var body = [row]; var rowGaps = []; var hLinesBeforeRow = []; var tags = autoTag != null ? [] : void 0; function beginRow() { if (autoTag) parser.gullet.macros.set("\\@eqnsw", "1", true); } function endRow() { if (tags) { if (parser.gullet.macros.get("\\df@tag")) { tags.push(parser.subparse([new Token("\\df@tag")])); parser.gullet.macros.set("\\df@tag", void 0, true); } else tags.push(Boolean(autoTag) && parser.gullet.macros.get("\\@eqnsw") === "1"); } } beginRow(); hLinesBeforeRow.push(getHLines(parser)); while (true) { var cellBody = parser.parseExpression(false, singleRow ? "\\end" : "\\\\"); parser.gullet.endGroup(); parser.gullet.beginGroup(); var cell = { type: "ordgroup", mode: parser.mode, body: cellBody }; if (style) cell = { type: "styling", mode: parser.mode, style, resetFont: true, body: [cell] }; row.push(cell); var next = parser.fetch().text; if (next === "&") { if (maxNumCols && row.length === maxNumCols) { if (singleRow || colSeparationType) throw new ParseError("Too many tab characters: &", parser.nextToken); else handleStrict({ strict: parser.settings.strict, errorCode: "textEnv", errorMsg: "Too few columns specified in the {array} column argument.", report: true }); } parser.consume(); } else if (next === "\\end") { endRow(); if (row.length === 1 && cell.type === "styling" && cell.body.length === 1 && cell.body[0].type === "ordgroup" && cell.body[0].body.length === 0 && (body.length > 1 || !emptySingleRow) && !Array.isArray(tags == null ? void 0 : tags[tags.length - 1]) && !(autoTag && (tags == null ? void 0 : tags[tags.length - 1]) === true)) body.pop(); if (hLinesBeforeRow.length < body.length + 1) hLinesBeforeRow.push([]); break; } else if (next === "\\\\") { parser.consume(); var size = void 0; if (parser.gullet.future().text !== " ") size = parser.parseSizeGroup(true); rowGaps.push(size ? size.value : null); endRow(); hLinesBeforeRow.push(getHLines(parser)); row = []; body.push(row); beginRow(); } else throw new ParseError("Expected & or \\\\ or \\cr or \\end", parser.nextToken); } parser.gullet.endGroup(); parser.gullet.endGroup(); return { type: "array", mode: parser.mode, addJot, arraystretch, body, cols, rowGaps, hskipBeforeAndAfter, hLinesBeforeRow, colSeparationType, tags, leqno }; } function dCellStyle(envName) { if (envName.slice(0, 1) === "d") return "display"; else return "text"; } var htmlBuilder$6 = function htmlBuilder(group, options) { var r; var c; var nr = group.body.length; var hLinesBeforeRow = group.hLinesBeforeRow; var nc = 0; var body = new Array(nr); var hlines = []; var ruleThickness = Math.max(options.fontMetrics().arrayRuleWidth, options.minRuleThickness); var pt = 1 / options.fontMetrics().ptPerEm; var arraycolsep = 5 * pt; if (group.colSeparationType && group.colSeparationType === "small") arraycolsep = .2778 * (options.havingStyle(Style$1.SCRIPT).sizeMultiplier / options.sizeMultiplier); var baselineskip = group.colSeparationType === "CD" ? calculateSize({ number: 3, unit: "ex" }, options) : 12 * pt; var jot = 3 * pt; var arrayskip = group.arraystretch * baselineskip; var arstrutHeight = .7 * arrayskip; var arstrutDepth = .3 * arrayskip; var totalHeight = 0; function setHLinePos(hlinesInGap) { for (var i = 0; i < hlinesInGap.length; ++i) { if (i > 0) totalHeight += .25; hlines.push({ pos: totalHeight, isDashed: hlinesInGap[i] }); } } setHLinePos(hLinesBeforeRow[0]); for (r = 0; r < group.body.length; ++r) { var inrow = group.body[r]; var height = arstrutHeight; var depth = arstrutDepth; if (nc < inrow.length) nc = inrow.length; var outrow = { cells: new Array(inrow.length), height: 0, depth: 0, pos: 0 }; for (c = 0; c < inrow.length; ++c) { var elt = buildGroup$1(inrow[c], options); if (depth < elt.depth) depth = elt.depth; if (height < elt.height) height = elt.height; outrow.cells[c] = elt; } var rowGap = group.rowGaps[r]; var gap = 0; if (rowGap) { gap = calculateSize(rowGap, options); if (gap > 0) { gap += arstrutDepth; if (depth < gap) depth = gap; gap = 0; } } if (group.addJot && r < group.body.length - 1) depth += jot; outrow.height = height; outrow.depth = depth; totalHeight += height; outrow.pos = totalHeight; totalHeight += depth + gap; body[r] = outrow; setHLinePos(hLinesBeforeRow[r + 1]); } var offset = totalHeight / 2 + options.fontMetrics().axisHeight; var colDescriptions = group.cols || []; var cols = []; var colSep; var colDescrNum; var tagSpans = []; if (group.tags && group.tags.some((tag) => tag)) for (r = 0; r < nr; ++r) { var rw = body[r]; var shift = rw.pos - offset; var tag = group.tags[r]; var tagSpan = void 0; if (tag === true) tagSpan = makeSpan(["eqn-num"], [], options); else if (tag === false) tagSpan = makeSpan([], [], options); else tagSpan = makeSpan([], buildExpression$1(tag, options, true), options); tagSpan.depth = rw.depth; tagSpan.height = rw.height; tagSpans.push({ type: "elem", elem: tagSpan, shift }); } for (c = 0, colDescrNum = 0; c < nc || colDescrNum < colDescriptions.length; ++c, ++colDescrNum) { var _colDescr3; var colDescr = colDescriptions[colDescrNum]; var firstSeparator = true; while (((_colDescr = colDescr) == null ? void 0 : _colDescr.type) === "separator") { var _colDescr; if (!firstSeparator) { colSep = makeSpan(["arraycolsep"], []); colSep.style.width = makeEm(options.fontMetrics().doubleRuleSep); cols.push(colSep); } if (colDescr.separator === "|" || colDescr.separator === ":") { var lineType = colDescr.separator === "|" ? "solid" : "dashed"; var separator = makeSpan(["vertical-separator"], [], options); separator.style.height = makeEm(totalHeight); separator.style.borderRightWidth = makeEm(ruleThickness); separator.style.borderRightStyle = lineType; separator.style.margin = "0 " + makeEm(-ruleThickness / 2); var _shift = totalHeight - offset; if (_shift) separator.style.verticalAlign = makeEm(-_shift); cols.push(separator); } else throw new ParseError("Invalid separator type: " + colDescr.separator); colDescrNum++; colDescr = colDescriptions[colDescrNum]; firstSeparator = false; } if (c >= nc) continue; var sepwidth = void 0; if (c > 0 || group.hskipBeforeAndAfter) { var _colDescr$pregap, _colDescr2; sepwidth = (_colDescr$pregap = (_colDescr2 = colDescr) == null ? void 0 : _colDescr2.pregap) != null ? _colDescr$pregap : arraycolsep; if (sepwidth !== 0) { colSep = makeSpan(["arraycolsep"], []); colSep.style.width = makeEm(sepwidth); cols.push(colSep); } } var colElems = []; for (r = 0; r < nr; ++r) { var row = body[r]; var elem = row.cells[c]; if (!elem) continue; var _shift2 = row.pos - offset; elem.depth = row.depth; elem.height = row.height; colElems.push({ type: "elem", elem, shift: _shift2 }); } var colVList = makeVList({ positionType: "individualShift", children: colElems }); var colSpan = makeSpan(["col-align-" + (((_colDescr3 = colDescr) == null ? void 0 : _colDescr3.align) || "c")], [colVList]); cols.push(colSpan); if (c < nc - 1 || group.hskipBeforeAndAfter) { var _colDescr$postgap, _colDescr4; sepwidth = (_colDescr$postgap = (_colDescr4 = colDescr) == null ? void 0 : _colDescr4.postgap) != null ? _colDescr$postgap : arraycolsep; if (sepwidth !== 0) { colSep = makeSpan(["arraycolsep"], []); colSep.style.width = makeEm(sepwidth); cols.push(colSep); } } } var tableBody = makeSpan(["mtable"], cols); if (hlines.length > 0) { var line = makeLineSpan("katex-hline", options, ruleThickness); var dashes = makeLineSpan("katex-hdashline", options, ruleThickness); var vListElems = [{ type: "elem", elem: tableBody, shift: 0 }]; while (hlines.length > 0) { var hline = hlines.pop(); var lineShift = hline.pos - offset; if (hline.isDashed) vListElems.push({ type: "elem", elem: dashes, shift: lineShift }); else vListElems.push({ type: "elem", elem: line, shift: lineShift }); } tableBody = makeVList({ positionType: "individualShift", children: vListElems }); } if (tagSpans.length === 0) return makeSpan(["mord"], [tableBody], options); else { var tagCol = makeSpan(["katex-tag"], [makeVList({ positionType: "individualShift", children: tagSpans })], options); return makeFragment([tableBody, tagCol]); } }; var alignMap = { c: "center ", l: "left ", r: "right " }; var mathmlBuilder$5 = function mathmlBuilder(group, options) { var tbl = []; var glue = new MathNode("mtd", [], ["mtr-glue"]); var tag = new MathNode("mtd", [], ["mml-eqn-num"]); for (var i = 0; i < group.body.length; i++) { var rw = group.body[i]; var row = []; for (var j = 0; j < rw.length; j++) row.push(new MathNode("mtd", [buildGroup(rw[j], options)])); if (group.tags && group.tags[i]) { row.unshift(glue); row.push(glue); if (group.leqno) row.unshift(tag); else row.push(tag); } tbl.push(new MathNode("mtr", row)); } var table = new MathNode("mtable", tbl); var gap = group.arraystretch === .5 ? .1 : .16 + group.arraystretch - 1 + (group.addJot ? .09 : 0); table.setAttribute("rowspacing", makeEm(gap)); var menclose = ""; var align = ""; if (group.cols && group.cols.length > 0) { var cols = group.cols; var columnLines = ""; var prevTypeWasAlign = false; var iStart = 0; var iEnd = cols.length; if (cols[0].type === "separator") { menclose += "top "; iStart = 1; } if (cols[cols.length - 1].type === "separator") { menclose += "bottom "; iEnd -= 1; } for (var _i = iStart; _i < iEnd; _i++) { var col = cols[_i]; if (col.type === "align") { align += alignMap[col.align]; if (prevTypeWasAlign) columnLines += "none "; prevTypeWasAlign = true; } else if (col.type === "separator") { if (prevTypeWasAlign) { columnLines += col.separator === "|" ? "solid " : "dashed "; prevTypeWasAlign = false; } } } table.setAttribute("columnalign", align.trim()); if (/[sd]/.test(columnLines)) table.setAttribute("columnlines", columnLines.trim()); } if (group.colSeparationType === "align") { var _cols = group.cols || []; var spacing = ""; for (var _i2 = 1; _i2 < _cols.length; _i2++) spacing += _i2 % 2 ? "0em " : "1em "; table.setAttribute("columnspacing", spacing.trim()); } else if (group.colSeparationType === "alignat" || group.colSeparationType === "gather") table.setAttribute("columnspacing", "0em"); else if (group.colSeparationType === "small") table.setAttribute("columnspacing", "0.2778em"); else if (group.colSeparationType === "CD") table.setAttribute("columnspacing", "0.5em"); else table.setAttribute("columnspacing", "1em"); var rowLines = ""; var hlines = group.hLinesBeforeRow; menclose += hlines[0].length > 0 ? "left " : ""; menclose += hlines[hlines.length - 1].length > 0 ? "right " : ""; for (var _i3 = 1; _i3 < hlines.length - 1; _i3++) rowLines += hlines[_i3].length === 0 ? "none " : hlines[_i3][0] ? "dashed " : "solid "; if (/[sd]/.test(rowLines)) table.setAttribute("rowlines", rowLines.trim()); if (menclose !== "") { table = new MathNode("menclose", [table]); table.setAttribute("notation", menclose.trim()); } if (group.arraystretch && group.arraystretch < 1) { table = new MathNode("mstyle", [table]); table.setAttribute("scriptlevel", "1"); } return table; }; var alignedHandler = function alignedHandler(context, args) { if (!context.envName.includes("ed")) validateAmsEnvironmentContext(context); var cols = []; var isSplit = context.envName === "split"; var res = parseArray(context.parser, { cols, addJot: true, autoTag: isSplit ? void 0 : getAutoTag(context.envName), emptySingleRow: true, colSeparationType: context.envName.includes("at") ? "alignat" : "align", maxNumCols: isSplit ? 2 : void 0, leqno: context.parser.settings.leqno }, "display"); var numMaths = 0; var numCols = 0; var emptyGroup = { type: "ordgroup", mode: context.mode, body: [] }; if (args[0] && args[0].type === "ordgroup") { var message = "Number of columns should be a positive integer"; var numColumns = assertCharacterGroup(args[0], message); if (!/^[0-9]+$/.test(numColumns) || Number(numColumns) < 1) throw new ParseError(message, args[0]); numMaths = Number(numColumns); numCols = numMaths * 2; } var isAligned = !numCols; res.body.forEach(function(row) { for (var i = 1; i < row.length; i += 2) assertNodeType(assertNodeType(row[i], "styling").body[0], "ordgroup").body.unshift(emptyGroup); if (!isAligned) { var curMaths = row.length / 2; if (numMaths < curMaths) throw new ParseError("Too many math in a row: " + ("expected " + numMaths + ", but got " + curMaths), row[0]); } else if (numCols < row.length) numCols = row.length; }); for (var i = 0; i < numCols; ++i) { var align = "r"; var pregap = 0; if (i % 2 === 1) align = "l"; else if (i > 0 && isAligned) pregap = 1; cols[i] = { type: "align", align, pregap, postgap: 0 }; } res.colSeparationType = isAligned ? "align" : "alignat"; return res; }; defineEnvironment({ type: "array", names: ["array", "darray"], props: { numArgs: 1 }, handler(context, args) { var cols = (checkSymbolNodeType(args[0]) ? [args[0]] : assertNodeType(args[0], "ordgroup").body).map(function(nde) { var ca = assertSymbolNodeType(nde).text; if ("lcr".includes(ca)) return { type: "align", align: ca }; else if (ca === "|") return { type: "separator", separator: "|" }; else if (ca === ":") return { type: "separator", separator: ":" }; throw new ParseError("Unknown column alignment: " + ca, nde); }); var res = { cols, hskipBeforeAndAfter: true, maxNumCols: cols.length }; return parseArray(context.parser, res, dCellStyle(context.envName)); }, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineEnvironment({ type: "array", names: [ "matrix", "pmatrix", "bmatrix", "Bmatrix", "vmatrix", "Vmatrix", "matrix*", "pmatrix*", "bmatrix*", "Bmatrix*", "vmatrix*", "Vmatrix*" ], props: { numArgs: 0 }, handler(context) { var delimiters = { "matrix": null, "pmatrix": ["(", ")"], "bmatrix": ["[", "]"], "Bmatrix": ["\\{", "\\}"], "vmatrix": ["|", "|"], "Vmatrix": ["\\Vert", "\\Vert"] }[context.envName.replace("*", "")]; var colAlign = "c"; var payload = { hskipBeforeAndAfter: false, cols: [{ type: "align", align: colAlign }] }; if (context.envName.charAt(context.envName.length - 1) === "*") { var parser = context.parser; parser.consumeSpaces(); if (parser.fetch().text === "[") { parser.consume(); parser.consumeSpaces(); colAlign = parser.fetch().text; if (!"lcr".includes(colAlign)) throw new ParseError("Expected l or c or r", parser.nextToken); parser.consume(); parser.consumeSpaces(); parser.expect("]"); parser.consume(); payload.cols = [{ type: "align", align: colAlign }]; } } var res = parseArray(context.parser, payload, dCellStyle(context.envName)); var numCols = Math.max(0, ...res.body.map((row) => row.length)); res.cols = new Array(numCols).fill({ type: "align", align: colAlign }); return delimiters ? { type: "leftright", mode: context.mode, body: [res], left: delimiters[0], right: delimiters[1], rightColor: void 0 } : res; }, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineEnvironment({ type: "array", names: ["smallmatrix"], props: { numArgs: 0 }, handler(context) { var res = parseArray(context.parser, { arraystretch: .5 }, "script"); res.colSeparationType = "small"; return res; }, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineEnvironment({ type: "array", names: ["subarray"], props: { numArgs: 1 }, handler(context, args) { var cols = (checkSymbolNodeType(args[0]) ? [args[0]] : assertNodeType(args[0], "ordgroup").body).map(function(nde) { var ca = assertSymbolNodeType(nde).text; if ("lc".includes(ca)) return { type: "align", align: ca }; throw new ParseError("Unknown column alignment: " + ca, nde); }); if (cols.length > 1) throw new ParseError("{subarray} can contain only one column"); var payload = { cols, hskipBeforeAndAfter: false, arraystretch: .5 }; var res = parseArray(context.parser, payload, "script"); if (res.body.length > 0 && res.body[0].length > 1) throw new ParseError("{subarray} can contain only one column"); return res; }, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineEnvironment({ type: "array", names: [ "cases", "dcases", "rcases", "drcases" ], props: { numArgs: 0 }, handler(context) { var res = parseArray(context.parser, { arraystretch: 1.2, cols: [{ type: "align", align: "l", pregap: 0, postgap: 1 }, { type: "align", align: "l", pregap: 0, postgap: 0 }] }, dCellStyle(context.envName)); return { type: "leftright", mode: context.mode, body: [res], left: context.envName.includes("r") ? "." : "\\{", right: context.envName.includes("r") ? "\\}" : ".", rightColor: void 0 }; }, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineEnvironment({ type: "array", names: [ "align", "align*", "aligned", "split" ], props: { numArgs: 0 }, handler: alignedHandler, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineEnvironment({ type: "array", names: [ "gathered", "gather", "gather*" ], props: { numArgs: 0 }, handler(context) { if (gatherEnvironments.has(context.envName)) validateAmsEnvironmentContext(context); var res = { cols: [{ type: "align", align: "c" }], addJot: true, colSeparationType: "gather", autoTag: getAutoTag(context.envName), emptySingleRow: true, leqno: context.parser.settings.leqno }; return parseArray(context.parser, res, "display"); }, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineEnvironment({ type: "array", names: [ "alignat", "alignat*", "alignedat" ], props: { numArgs: 1 }, handler: alignedHandler, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineEnvironment({ type: "array", names: ["equation", "equation*"], props: { numArgs: 0 }, handler(context) { validateAmsEnvironmentContext(context); var res = { autoTag: getAutoTag(context.envName), emptySingleRow: true, singleRow: true, maxNumCols: 1, leqno: context.parser.settings.leqno }; return parseArray(context.parser, res, "display"); }, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineEnvironment({ type: "array", names: ["CD"], props: { numArgs: 0 }, handler(context) { validateAmsEnvironmentContext(context); return parseCD(context.parser); }, htmlBuilder: htmlBuilder$6, mathmlBuilder: mathmlBuilder$5 }); defineMacro("\\nonumber", "\\gdef\\@eqnsw{0}"); defineMacro("\\notag", "\\nonumber"); defineFunction({ type: "text", names: ["\\hline", "\\hdashline"], numArgs: 0, allowedInText: true, allowedInMath: true, handler(context, args) { throw new ParseError(context.funcName + " valid only within array environment"); } }); var environments = _environments; defineFunction({ type: "environment", names: ["\\begin", "\\end"], numArgs: 1, argTypes: ["text"], handler(_ref, args) { var parser = _ref.parser, funcName = _ref.funcName; var nameGroup = args[0]; if (nameGroup.type !== "ordgroup") throw new ParseError("Invalid environment name", nameGroup); var envName = assertCharacterGroup(nameGroup, "Environment name should contain only text characters and spaces", true); if (funcName === "\\begin") { if (!Object.prototype.hasOwnProperty.call(environments, envName)) throw new ParseError("No such environment: " + envName, nameGroup); var env = environments[envName]; var _parser$parseArgument = parser.parseArguments("\\begin{" + envName + "}", env), _args = _parser$parseArgument.args, optArgs = _parser$parseArgument.optArgs; var context = { mode: parser.mode, envName, parser }; var result = env.handler(context, _args, optArgs); parser.expect("\\end", false); var endNameToken = parser.nextToken; var end = assertNodeType(parser.parseFunction(), "environment"); if (end.name !== envName) throw new ParseError("Mismatch: \\begin{" + envName + "} matched by \\end{" + end.name + "}", endNameToken); return result; } return { type: "environment", mode: parser.mode, name: envName, nameGroup }; } }); var htmlBuilder$5 = (group, options) => { var font = group.font; var newOptions = options.withFont(font); return buildGroup$1(group.body, newOptions); }; var mathmlBuilder$4 = (group, options) => { var font = group.font; var newOptions = options.withFont(font); return buildGroup(group.body, newOptions); }; var fontAliases = { "\\Bbb": "\\mathbb", "\\bold": "\\mathbf", "\\frak": "\\mathfrak" }; defineFunction({ type: "font", names: [ "\\mathrm", "\\mathit", "\\mathbf", "\\mathnormal", "\\mathsfit", "\\mathbb", "\\mathcal", "\\mathfrak", "\\mathscr", "\\mathsf", "\\mathtt", "\\Bbb", "\\bold", "\\frak" ], numArgs: 1, allowedInArgument: true, handler: (_ref, args) => { var parser = _ref.parser, funcName = _ref.funcName; var body = normalizeArgument(args[0]); var func = funcName in fontAliases ? fontAliases[funcName] : funcName; return { type: "font", mode: parser.mode, font: func.slice(1), body }; }, htmlBuilder: htmlBuilder$5, mathmlBuilder: mathmlBuilder$4 }); defineFunction({ type: "mclass", names: ["\\boldsymbol", "\\bm"], numArgs: 1, handler: (_ref2, args) => { var parser = _ref2.parser; var body = args[0]; return { type: "mclass", mode: parser.mode, mclass: binrelClass(body), body: [{ type: "font", mode: parser.mode, font: "boldsymbol", body }], isCharacterBox: isCharacterBox(body) }; } }); defineFunction({ type: "font", names: [ "\\rm", "\\sf", "\\tt", "\\bf", "\\it", "\\cal" ], numArgs: 0, allowedInText: true, handler: (_ref3, args) => { var parser = _ref3.parser, funcName = _ref3.funcName, breakOnTokenText = _ref3.breakOnTokenText; var mode = parser.mode; var body = parser.parseExpression(true, breakOnTokenText); return { type: "font", mode, font: "math" + funcName.slice(1), body: { type: "ordgroup", mode: parser.mode, body } }; } }); var htmlBuilder$4 = (group, options) => { var style = options.style; var nstyle = style.fracNum(); var dstyle = style.fracDen(); var newOptions = options.havingStyle(nstyle); var numerm = buildGroup$1(group.numer, newOptions, options); if (group.continued) { var hStrut = 8.5 / options.fontMetrics().ptPerEm; var dStrut = 3.5 / options.fontMetrics().ptPerEm; numerm.height = numerm.height < hStrut ? hStrut : numerm.height; numerm.depth = numerm.depth < dStrut ? dStrut : numerm.depth; } newOptions = options.havingStyle(dstyle); var denomm = buildGroup$1(group.denom, newOptions, options); var rule; var ruleWidth; var ruleSpacing; if (group.hasBarLine) { if (group.barSize) { ruleWidth = calculateSize(group.barSize, options); rule = makeLineSpan("frac-line", options, ruleWidth); } else rule = makeLineSpan("frac-line", options); ruleWidth = rule.height; ruleSpacing = rule.height; } else { rule = null; ruleWidth = 0; ruleSpacing = options.fontMetrics().defaultRuleThickness; } var numShift; var clearance; var denomShift; if (style.size === Style$1.DISPLAY.size) { numShift = options.fontMetrics().num1; if (ruleWidth > 0) clearance = 3 * ruleSpacing; else clearance = 7 * ruleSpacing; denomShift = options.fontMetrics().denom1; } else { if (ruleWidth > 0) { numShift = options.fontMetrics().num2; clearance = ruleSpacing; } else { numShift = options.fontMetrics().num3; clearance = 3 * ruleSpacing; } denomShift = options.fontMetrics().denom2; } var frac; if (!rule) { var candidateClearance = numShift - numerm.depth - (denomm.height - denomShift); if (candidateClearance < clearance) { numShift += .5 * (clearance - candidateClearance); denomShift += .5 * (clearance - candidateClearance); } frac = makeVList({ positionType: "individualShift", children: [{ type: "elem", elem: denomm, shift: denomShift }, { type: "elem", elem: numerm, shift: -numShift }] }); } else { var axisHeight = options.fontMetrics().axisHeight; if (numShift - numerm.depth - (axisHeight + .5 * ruleWidth) < clearance) numShift += clearance - (numShift - numerm.depth - (axisHeight + .5 * ruleWidth)); if (axisHeight - .5 * ruleWidth - (denomm.height - denomShift) < clearance) denomShift += clearance - (axisHeight - .5 * ruleWidth - (denomm.height - denomShift)); var midShift = -(axisHeight - .5 * ruleWidth); frac = makeVList({ positionType: "individualShift", children: [ { type: "elem", elem: denomm, shift: denomShift }, { type: "elem", elem: rule, shift: midShift }, { type: "elem", elem: numerm, shift: -numShift } ] }); } newOptions = options.havingStyle(style); frac.height *= newOptions.sizeMultiplier / options.sizeMultiplier; frac.depth *= newOptions.sizeMultiplier / options.sizeMultiplier; var delimSize; if (style.size === Style$1.DISPLAY.size) delimSize = options.fontMetrics().delim1; else if (style.size === Style$1.SCRIPTSCRIPT.size) delimSize = options.havingStyle(Style$1.SCRIPT).fontMetrics().delim2; else delimSize = options.fontMetrics().delim2; var leftDelim; var rightDelim; if (group.leftDelim == null) leftDelim = makeNullDelimiter(options, ["mopen"]); else leftDelim = makeCustomSizedDelim(group.leftDelim, delimSize, true, options.havingStyle(style), group.mode, ["mopen"]); if (group.continued) rightDelim = makeSpan([]); else if (group.rightDelim == null) rightDelim = makeNullDelimiter(options, ["mclose"]); else rightDelim = makeCustomSizedDelim(group.rightDelim, delimSize, true, options.havingStyle(style), group.mode, ["mclose"]); return makeSpan(["mord"].concat(newOptions.sizingClasses(options)), [ leftDelim, makeSpan(["mfrac"], [frac]), rightDelim ], options); }; var mathmlBuilder$3 = (group, options) => { var node = new MathNode("mfrac", [buildGroup(group.numer, options), buildGroup(group.denom, options)]); if (!group.hasBarLine) node.setAttribute("linethickness", "0px"); else if (group.barSize) { var ruleWidth = calculateSize(group.barSize, options); node.setAttribute("linethickness", makeEm(ruleWidth)); } if (group.leftDelim != null || group.rightDelim != null) { var withDelims = []; if (group.leftDelim != null) { var leftOp = new MathNode("mo", [new TextNode(group.leftDelim.replace("\\", ""))]); leftOp.setAttribute("fence", "true"); withDelims.push(leftOp); } withDelims.push(node); if (group.rightDelim != null) { var rightOp = new MathNode("mo", [new TextNode(group.rightDelim.replace("\\", ""))]); rightOp.setAttribute("fence", "true"); withDelims.push(rightOp); } return makeRow(withDelims); } return node; }; var wrapWithStyle = (frac, style) => { if (!style) return frac; return { type: "styling", mode: frac.mode, style, body: [frac] }; }; defineFunction({ type: "genfrac", names: [ "\\cfrac", "\\dfrac", "\\frac", "\\tfrac", "\\dbinom", "\\binom", "\\tbinom", "\\\\atopfrac", "\\\\bracefrac", "\\\\brackfrac" ], numArgs: 2, allowedInArgument: true, handler: (_ref, args) => { var parser = _ref.parser, funcName = _ref.funcName; var numer = args[0]; var denom = args[1]; var hasBarLine; var leftDelim = null; var rightDelim = null; switch (funcName) { case "\\cfrac": case "\\dfrac": case "\\frac": case "\\tfrac": hasBarLine = true; break; case "\\\\atopfrac": hasBarLine = false; break; case "\\dbinom": case "\\binom": case "\\tbinom": hasBarLine = false; leftDelim = "("; rightDelim = ")"; break; case "\\\\bracefrac": hasBarLine = false; leftDelim = "\\{"; rightDelim = "\\}"; break; case "\\\\brackfrac": hasBarLine = false; leftDelim = "["; rightDelim = "]"; break; default: throw new Error("Unrecognized genfrac command"); } var continued = funcName === "\\cfrac"; var style = null; if (continued || funcName.startsWith("\\d")) style = "display"; else if (funcName.startsWith("\\t")) style = "text"; return wrapWithStyle({ type: "genfrac", mode: parser.mode, numer, denom, continued, hasBarLine, leftDelim, rightDelim, barSize: null }, style); }, htmlBuilder: htmlBuilder$4, mathmlBuilder: mathmlBuilder$3 }); defineFunction({ type: "infix", names: [ "\\over", "\\choose", "\\atop", "\\brace", "\\brack" ], numArgs: 0, infix: true, handler(_ref2) { var parser = _ref2.parser, funcName = _ref2.funcName, token = _ref2.token; var replaceWith; switch (funcName) { case "\\over": replaceWith = "\\frac"; break; case "\\choose": replaceWith = "\\binom"; break; case "\\atop": replaceWith = "\\\\atopfrac"; break; case "\\brace": replaceWith = "\\\\bracefrac"; break; case "\\brack": replaceWith = "\\\\brackfrac"; break; default: throw new Error("Unrecognized infix genfrac command"); } return { type: "infix", mode: parser.mode, replaceWith, token }; } }); var stylArray = [ "display", "text", "script", "scriptscript" ]; var delimFromValue = function delimFromValue(delimString) { var delim = null; if (delimString.length > 0) { delim = delimString; delim = delim === "." ? null : delim; } return delim; }; defineFunction({ type: "genfrac", names: ["\\genfrac"], numArgs: 6, allowedInArgument: true, argTypes: [ "math", "math", "size", "text", "math", "math" ], handler(_ref3, args) { var parser = _ref3.parser; var numer = args[4]; var denom = args[5]; var leftNode = normalizeArgument(args[0]); var leftDelim = leftNode.type === "atom" && leftNode.family === "open" ? delimFromValue(leftNode.text) : null; var rightNode = normalizeArgument(args[1]); var rightDelim = rightNode.type === "atom" && rightNode.family === "close" ? delimFromValue(rightNode.text) : null; var barNode = assertNodeType(args[2], "size"); var hasBarLine; var barSize = null; if (barNode.isBlank) hasBarLine = true; else { barSize = barNode.value; hasBarLine = barSize.number > 0; } var size = null; var styl = args[3]; if (styl.type === "ordgroup") { if (styl.body.length > 0) { var textOrd = assertNodeType(styl.body[0], "textord"); size = stylArray[Number(textOrd.text)]; } } else { styl = assertNodeType(styl, "textord"); size = stylArray[Number(styl.text)]; } return wrapWithStyle({ type: "genfrac", mode: parser.mode, numer, denom, continued: false, hasBarLine, barSize, leftDelim, rightDelim }, size); } }); defineFunction({ type: "infix", names: ["\\above"], numArgs: 1, argTypes: ["size"], infix: true, handler(_ref4, args) { var parser = _ref4.parser; _ref4.funcName; var token = _ref4.token; return { type: "infix", mode: parser.mode, replaceWith: "\\\\abovefrac", size: assertNodeType(args[0], "size").value, token }; } }); defineFunction({ type: "genfrac", names: ["\\\\abovefrac"], numArgs: 3, argTypes: [ "math", "size", "math" ], handler: (_ref5, args) => { var parser = _ref5.parser; _ref5.funcName; var numer = args[0]; var barSize = assertNodeType(args[1], "infix").size; if (!barSize) throw new Error("\\\\abovefrac expected size, but got " + String(barSize)); var denom = args[2]; var hasBarLine = barSize.number > 0; return { type: "genfrac", mode: parser.mode, numer, denom, continued: false, hasBarLine, barSize, leftDelim: null, rightDelim: null }; } }); var htmlBuilder$3 = (grp, options) => { var style = options.style; var supSubGroup; var group; if (grp.type === "supsub") { supSubGroup = grp.sup ? buildGroup$1(grp.sup, options.havingStyle(style.sup()), options) : buildGroup$1(grp.sub, options.havingStyle(style.sub()), options); group = assertNodeType(grp.base, "horizBrace"); } else group = assertNodeType(grp, "horizBrace"); var body = buildGroup$1(group.base, options.havingBaseStyle(Style$1.DISPLAY)); var braceBody = stretchySvg(group, options); var vlist; if (group.isOver) vlist = makeVList({ positionType: "firstBaseline", children: [ { type: "elem", elem: body }, { type: "kern", size: .1 }, { type: "elem", elem: braceBody, wrapperClasses: ["svg-align"] } ] }); else vlist = makeVList({ positionType: "bottom", positionData: body.depth + .1 + braceBody.height, children: [ { type: "elem", elem: braceBody, wrapperClasses: ["svg-align"] }, { type: "kern", size: .1 }, { type: "elem", elem: body } ] }); if (supSubGroup) { var vSpan = makeSpan(["minner", group.isOver ? "mover" : "munder"], [vlist], options); if (group.isOver) vlist = makeVList({ positionType: "firstBaseline", children: [ { type: "elem", elem: vSpan }, { type: "kern", size: .2 }, { type: "elem", elem: supSubGroup } ] }); else vlist = makeVList({ positionType: "bottom", positionData: vSpan.depth + .2 + supSubGroup.height + supSubGroup.depth, children: [ { type: "elem", elem: supSubGroup }, { type: "kern", size: .2 }, { type: "elem", elem: vSpan } ] }); } return makeSpan(["minner", group.isOver ? "mover" : "munder"], [vlist], options); }; var mathmlBuilder$2 = (group, options) => { var accentNode = stretchyMathML(group.label); return new MathNode(group.isOver ? "mover" : "munder", [buildGroup(group.base, options), accentNode]); }; defineFunction({ type: "horizBrace", names: [ "\\overbrace", "\\underbrace", "\\overbracket", "\\underbracket" ], numArgs: 1, handler(_ref, args) { var parser = _ref.parser, funcName = _ref.funcName; return { type: "horizBrace", mode: parser.mode, label: funcName, isOver: funcName.includes("\\over"), base: args[0] }; }, htmlBuilder: htmlBuilder$3, mathmlBuilder: mathmlBuilder$2 }); defineFunction({ type: "href", names: ["\\href"], numArgs: 2, argTypes: ["url", "original"], allowedInText: true, handler: (_ref, args) => { var parser = _ref.parser; var body = args[1]; var href = assertNodeType(args[0], "url").url; if (!parser.settings.isTrusted({ command: "\\href", url: href })) return parser.formatUnsupportedCmd("\\href"); return { type: "href", mode: parser.mode, href, body: ordargument(body) }; }, htmlBuilder: (group, options) => { var elements = buildExpression$1(group.body, options, false); return makeAnchor(group.href, [], elements, options); }, mathmlBuilder: (group, options) => { var math = buildExpressionRow(group.body, options); if (!(math instanceof MathNode)) math = new MathNode("mrow", [math]); math.setAttribute("href", group.href); return math; } }); defineFunction({ type: "href", names: ["\\url"], numArgs: 1, argTypes: ["url"], allowedInText: true, handler: (_ref2, args) => { var parser = _ref2.parser; var href = assertNodeType(args[0], "url").url; if (!parser.settings.isTrusted({ command: "\\url", url: href })) return parser.formatUnsupportedCmd("\\url"); var chars = []; for (var i = 0; i < href.length; i++) { var c = href[i]; if (c === "~") c = "\\textasciitilde"; chars.push({ type: "textord", mode: "text", text: c }); } var body = { type: "text", mode: parser.mode, font: "\\texttt", body: chars }; return { type: "href", mode: parser.mode, href, body: ordargument(body) }; } }); defineFunction({ type: "hbox", names: ["\\hbox"], numArgs: 1, argTypes: ["text"], allowedInText: true, primitive: true, handler(_ref, args) { return { type: "hbox", mode: _ref.parser.mode, body: ordargument(args[0]) }; }, htmlBuilder(group, options) { return makeFragment(buildExpression$1(group.body, options.withFont(""), false)); }, mathmlBuilder(group, options) { return new MathNode("mrow", buildExpression(group.body, options.withFont(""))); } }); defineFunction({ type: "html", names: [ "\\htmlClass", "\\htmlId", "\\htmlStyle", "\\htmlData" ], numArgs: 2, argTypes: ["raw", "original"], allowedInText: true, handler: (_ref, args) => { var parser = _ref.parser, funcName = _ref.funcName; _ref.token; var value = assertNodeType(args[0], "raw").string; var body = args[1]; if (parser.settings.strict) handleStrict({ strict: parser.settings.strict, errorCode: "htmlExtension", errorMsg: "HTML extension is disabled on strict mode", report: true }); var trustContext; var attributes = {}; switch (funcName) { case "\\htmlClass": attributes.class = value; trustContext = { command: "\\htmlClass", class: value }; break; case "\\htmlId": attributes.id = value; trustContext = { command: "\\htmlId", id: value }; break; case "\\htmlStyle": attributes.style = value; trustContext = { command: "\\htmlStyle", style: value }; break; case "\\htmlData": var ESCAPED_COMMA = "{,}"; var data = []; var current = ""; for (var i = 0; i < value.length; i++) if (value.startsWith(ESCAPED_COMMA, i)) { current += ","; i += ESCAPED_COMMA.length - 1; } else if (value[i] === ",") { data.push(current); current = ""; } else current += value[i]; data.push(current); for (var _i = 0; _i < data.length; _i++) { var item = data[_i]; var firstEquals = item.indexOf("="); if (firstEquals < 0) throw new ParseError("\\htmlData key/value '" + item + "' missing equals sign"); var key = item.slice(0, firstEquals); var _value = item.slice(firstEquals + 1); attributes["data-" + key.trim()] = _value; } trustContext = { command: "\\htmlData", attributes }; break; default: throw new Error("Unrecognized html command"); } if (!parser.settings.isTrusted(trustContext)) return parser.formatUnsupportedCmd(funcName); return { type: "html", mode: parser.mode, attributes, body: ordargument(body) }; }, htmlBuilder: (group, options) => { var elements = buildExpression$1(group.body, options, false); var classes = ["enclosing"]; if (group.attributes.class) classes.push(...group.attributes.class.trim().split(/\s+/)); var span = makeSpan(classes, elements, options); for (var _ref3 of Object.entries(group.attributes)) { var attr = _ref3[0]; var value = _ref3[1]; if (attr !== "class") span.setAttribute(attr, value); } return span; }, mathmlBuilder: (group, options) => { return buildExpressionRow(group.body, options); } }); defineFunction({ type: "htmlmathml", names: ["\\html@mathml"], numArgs: 2, allowedInArgument: true, allowedInText: true, handler: (_ref, args) => { return { type: "htmlmathml", mode: _ref.parser.mode, html: ordargument(args[0]), mathml: ordargument(args[1]) }; }, htmlBuilder: (group, options) => { return makeFragment(buildExpression$1(group.html, options, false)); }, mathmlBuilder: (group, options) => { return buildExpressionRow(group.mathml, options); } }); var sizeData = function sizeData(str) { if (/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(str)) return { number: +str, unit: "bp" }; else { var match = /([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(str); if (!match) throw new ParseError("Invalid size: '" + str + "' in \\includegraphics"); var data = { number: +(match[1] + match[2]), unit: match[3] }; if (!validUnit(data)) throw new ParseError("Invalid unit: '" + data.unit + "' in \\includegraphics."); return data; } }; defineFunction({ type: "includegraphics", names: ["\\includegraphics"], numArgs: 1, numOptionalArgs: 1, argTypes: ["raw", "url"], allowedInText: false, handler: (_ref, args, optArgs) => { var parser = _ref.parser; var width = { number: 0, unit: "em" }; var height = { number: .9, unit: "em" }; var totalheight = { number: 0, unit: "em" }; var alt = ""; if (optArgs[0]) { var attributes = assertNodeType(optArgs[0], "raw").string.split(","); for (var i = 0; i < attributes.length; i++) { var keyVal = attributes[i].split("="); if (keyVal.length === 2) { var str = keyVal[1].trim(); switch (keyVal[0].trim()) { case "alt": alt = str; break; case "width": width = sizeData(str); break; case "height": height = sizeData(str); break; case "totalheight": totalheight = sizeData(str); break; default: throw new ParseError("Invalid key: '" + keyVal[0] + "' in \\includegraphics."); } } } } var src = assertNodeType(args[0], "url").url; if (alt === "") { alt = src; alt = alt.replace(/^.*[\\/]/, ""); alt = alt.substring(0, alt.lastIndexOf(".")); } if (!parser.settings.isTrusted({ command: "\\includegraphics", url: src })) return parser.formatUnsupportedCmd("\\includegraphics"); return { type: "includegraphics", mode: parser.mode, alt, width, height, totalheight, src }; }, htmlBuilder: (group, options) => { var height = calculateSize(group.height, options); var depth = 0; if (group.totalheight.number > 0) depth = calculateSize(group.totalheight, options) - height; var width = 0; if (group.width.number > 0) width = calculateSize(group.width, options); var style = { height: makeEm(height + depth) }; if (width > 0) style.width = makeEm(width); if (depth > 0) style.verticalAlign = makeEm(-depth); var node = new Img(group.src, group.alt, style); node.height = height; node.depth = depth; return node; }, mathmlBuilder: (group, options) => { var node = new MathNode("mglyph", []); node.setAttribute("alt", group.alt); var height = calculateSize(group.height, options); var depth = 0; if (group.totalheight.number > 0) { depth = calculateSize(group.totalheight, options) - height; node.setAttribute("valign", makeEm(-depth)); } node.setAttribute("height", makeEm(height + depth)); if (group.width.number > 0) { var width = calculateSize(group.width, options); node.setAttribute("width", makeEm(width)); } node.setAttribute("src", group.src); return node; } }); defineFunction({ type: "kern", names: [ "\\kern", "\\mkern", "\\hskip", "\\mskip" ], numArgs: 1, argTypes: ["size"], primitive: true, allowedInText: true, handler(_ref, args) { var parser = _ref.parser, funcName = _ref.funcName; var size = assertNodeType(args[0], "size"); if (parser.settings.strict) { var mathFunction = funcName[1] === "m"; var muUnit = size.value.unit === "mu"; if (mathFunction) { if (!muUnit) handleStrict({ strict: parser.settings.strict, errorCode: "mathVsTextUnits", errorMsg: "LaTeX's " + funcName + " supports only mu units, " + ("not " + size.value.unit + " units"), report: true }); if (parser.mode !== "math") handleStrict({ strict: parser.settings.strict, errorCode: "mathVsTextUnits", errorMsg: "LaTeX's " + funcName + " works only in math mode", report: true }); } else if (muUnit) handleStrict({ strict: parser.settings.strict, errorCode: "mathVsTextUnits", errorMsg: "LaTeX's " + funcName + " doesn't support mu units", report: true }); } return { type: "kern", mode: parser.mode, dimension: size.value }; }, htmlBuilder(group, options) { return makeGlue(group.dimension, options); }, mathmlBuilder(group, options) { return new SpaceNode(calculateSize(group.dimension, options)); } }); defineFunction({ type: "lap", names: [ "\\mathllap", "\\mathrlap", "\\mathclap" ], numArgs: 1, allowedInText: true, handler: (_ref, args) => { var parser = _ref.parser, funcName = _ref.funcName; var body = args[0]; return { type: "lap", mode: parser.mode, alignment: funcName.slice(5), body }; }, htmlBuilder: (group, options) => { var inner; if (group.alignment === "clap") { inner = makeSpan([], [buildGroup$1(group.body, options)]); inner = makeSpan(["katex-inner"], [inner], options); } else inner = makeSpan(["katex-inner"], [buildGroup$1(group.body, options)]); var fix = makeSpan(["katex-fix"], []); var node = makeSpan([group.alignment], [inner, fix], options); var strut = makeSpan(["katex-strut"]); strut.style.height = makeEm(node.height + node.depth); if (node.depth) strut.style.verticalAlign = makeEm(-node.depth); node.children.unshift(strut); node = makeSpan(["katex-thinbox"], [node], options); return makeSpan(["mord", "katex-vbox"], [node], options); }, mathmlBuilder: (group, options) => { var node = new MathNode("mpadded", [buildGroup(group.body, options)]); if (group.alignment !== "rlap") { var offset = group.alignment === "llap" ? "-1" : "-0.5"; node.setAttribute("lspace", offset + "width"); } node.setAttribute("width", "0px"); return node; } }); defineFunction({ type: "styling", names: ["\\(", "$"], numArgs: 0, allowedInText: true, allowedInMath: false, handler(_ref, args) { var funcName = _ref.funcName, parser = _ref.parser; var outerMode = parser.mode; parser.switchMode("math"); var close = funcName === "\\(" ? "\\)" : "$"; var body = parser.parseExpression(false, close); parser.expect(close); parser.switchMode(outerMode); return { type: "styling", mode: parser.mode, style: "text", resetFont: true, body }; } }); defineFunction({ type: "text", names: ["\\)", "\\]"], numArgs: 0, allowedInText: true, allowedInMath: false, handler(context, args) { throw new ParseError("Mismatched " + context.funcName); } }); var chooseMathStyle = (group, options) => { switch (options.style.size) { case Style$1.DISPLAY.size: return group.display; case Style$1.TEXT.size: return group.text; case Style$1.SCRIPT.size: return group.script; case Style$1.SCRIPTSCRIPT.size: return group.scriptscript; default: return group.text; } }; defineFunction({ type: "mathchoice", names: ["\\mathchoice"], numArgs: 4, primitive: true, handler: (_ref, args) => { return { type: "mathchoice", mode: _ref.parser.mode, display: ordargument(args[0]), text: ordargument(args[1]), script: ordargument(args[2]), scriptscript: ordargument(args[3]) }; }, htmlBuilder: (group, options) => { return makeFragment(buildExpression$1(chooseMathStyle(group, options), options, false)); }, mathmlBuilder: (group, options) => { return buildExpressionRow(chooseMathStyle(group, options), options); } }); var assembleSupSub = (base, supGroup, subGroup, options, style, slant, baseShift) => { base = makeSpan([], [base]); var subIsSingleCharacter = subGroup && isCharacterBox(subGroup); var sub; var sup; if (supGroup) { var elem = buildGroup$1(supGroup, options.havingStyle(style.sup()), options); sup = { elem, kern: Math.max(options.fontMetrics().bigOpSpacing1, options.fontMetrics().bigOpSpacing3 - elem.depth) }; } if (subGroup) { var _elem = buildGroup$1(subGroup, options.havingStyle(style.sub()), options); sub = { elem: _elem, kern: Math.max(options.fontMetrics().bigOpSpacing2, options.fontMetrics().bigOpSpacing4 - _elem.height) }; } var finalGroup; if (sup && sub) finalGroup = makeVList({ positionType: "bottom", positionData: options.fontMetrics().bigOpSpacing5 + sub.elem.height + sub.elem.depth + sub.kern + base.depth + baseShift, children: [ { type: "kern", size: options.fontMetrics().bigOpSpacing5 }, { type: "elem", elem: sub.elem, marginLeft: makeEm(-slant) }, { type: "kern", size: sub.kern }, { type: "elem", elem: base }, { type: "kern", size: sup.kern }, { type: "elem", elem: sup.elem, marginLeft: makeEm(slant) }, { type: "kern", size: options.fontMetrics().bigOpSpacing5 } ] }); else if (sub) finalGroup = makeVList({ positionType: "top", positionData: base.height - baseShift, children: [ { type: "kern", size: options.fontMetrics().bigOpSpacing5 }, { type: "elem", elem: sub.elem, marginLeft: makeEm(-slant) }, { type: "kern", size: sub.kern }, { type: "elem", elem: base } ] }); else if (sup) finalGroup = makeVList({ positionType: "bottom", positionData: base.depth + baseShift, children: [ { type: "elem", elem: base }, { type: "kern", size: sup.kern }, { type: "elem", elem: sup.elem, marginLeft: makeEm(slant) }, { type: "kern", size: options.fontMetrics().bigOpSpacing5 } ] }); else return base; var parts = [finalGroup]; if (sub && slant !== 0 && !subIsSingleCharacter) { var spacer = makeSpan(["mspace"], [], options); spacer.style.marginRight = makeEm(slant); parts.unshift(spacer); } return makeSpan(["mop", "op-limits"], parts, options); }; var noSuccessor = /* @__PURE__ */ new Set(["\\smallint"]); var htmlBuilder$2 = (grp, options) => { var supGroup; var subGroup; var hasLimits = false; var group; if (grp.type === "supsub") { supGroup = grp.sup; subGroup = grp.sub; group = assertNodeType(grp.base, "op"); hasLimits = true; } else group = assertNodeType(grp, "op"); var style = options.style; var large = false; if (style.size === Style$1.DISPLAY.size && group.symbol && !noSuccessor.has(group.name)) large = true; var base; var symbolItalic; if (group.symbol) { var fontName = large ? "Size2-Regular" : "Size1-Regular"; var stash = ""; if (group.name === "\\oiint" || group.name === "\\oiiint") { stash = group.name.slice(1); group.name = stash === "oiint" ? "\\iint" : "\\iiint"; } base = makeSymbol(group.name, fontName, "math", options, [ "mop", "op-symbol", large ? "large-op" : "small-op" ]); symbolItalic = base.italic; if (stash.length > 0) { var oval = staticSvg(stash + "Size" + (large ? "2" : "1"), options); base = makeVList({ positionType: "individualShift", children: [{ type: "elem", elem: base, shift: 0 }, { type: "elem", elem: oval, shift: large ? .08 : 0 }] }); group.name = "\\" + stash; base.classes.unshift("mop"); base.italic = symbolItalic; } } else if (group.body) { var inner = buildExpression$1(group.body, options, true); if (inner.length === 1 && inner[0] instanceof SymbolNode) { base = inner[0]; base.classes[0] = "mop"; } else base = makeSpan(["mop"], inner, options); } else { var output = []; for (var i = 1; i < group.name.length; i++) output.push(mathsym(group.name[i], group.mode, options)); base = makeSpan(["mop"], output, options); } var baseShift = 0; var slant = 0; if ((base instanceof SymbolNode || group.name === "\\oiint" || group.name === "\\oiiint") && !group.suppressBaseShift) { var _base$italic; baseShift = (base.height - base.depth) / 2 - options.fontMetrics().axisHeight; slant = (_base$italic = base.italic) != null ? _base$italic : 0; } if (hasLimits) return assembleSupSub(base, supGroup, subGroup, options, style, slant, baseShift); else { if (baseShift) { base.style.position = "relative"; base.style.top = makeEm(baseShift); } return base; } }; var mathmlBuilder$1 = (group, options) => { var node; if (group.symbol) { node = new MathNode("mo", [makeText(group.name, group.mode)]); if (noSuccessor.has(group.name)) node.setAttribute("largeop", "false"); } else if (group.body) node = new MathNode("mo", buildExpression(group.body, options)); else { node = new MathNode("mi", [new TextNode(group.name.slice(1))]); var operator = new MathNode("mo", [makeText("⁡", "text")]); if (group.parentIsSupSub) node = new MathNode("mrow", [node, operator]); else node = newDocumentFragment([node, operator]); } return node; }; var singleCharBigOps = { "∏": "\\prod", "∐": "\\coprod", "∑": "\\sum", "⋀": "\\bigwedge", "⋁": "\\bigvee", "⋂": "\\bigcap", "⋃": "\\bigcup", "⨀": "\\bigodot", "⨁": "\\bigoplus", "⨂": "\\bigotimes", "⨄": "\\biguplus", "⨆": "\\bigsqcup" }; defineFunction({ type: "op", names: [ "\\coprod", "\\bigvee", "\\bigwedge", "\\biguplus", "\\bigcap", "\\bigcup", "\\intop", "\\prod", "\\sum", "\\bigotimes", "\\bigoplus", "\\bigodot", "\\bigsqcup", "\\smallint", "∏", "∐", "∑", "⋀", "⋁", "⋂", "⋃", "⨀", "⨁", "⨂", "⨄", "⨆" ], numArgs: 0, handler: (_ref, args) => { var parser = _ref.parser; var fName = _ref.funcName; if (fName.length === 1) fName = singleCharBigOps[fName]; return { type: "op", mode: parser.mode, limits: true, parentIsSupSub: false, symbol: true, name: fName }; }, htmlBuilder: htmlBuilder$2, mathmlBuilder: mathmlBuilder$1 }); defineFunction({ type: "op", names: ["\\mathop"], numArgs: 1, primitive: true, handler: (_ref2, args) => { var parser = _ref2.parser; var body = args[0]; return { type: "op", mode: parser.mode, limits: false, parentIsSupSub: false, symbol: false, body: ordargument(body) }; } }); var singleCharIntegrals = { "∫": "\\int", "∬": "\\iint", "∭": "\\iiint", "∮": "\\oint", "∯": "\\oiint", "∰": "\\oiiint" }; defineFunction({ type: "op", names: [ "\\arcsin", "\\arccos", "\\arctan", "\\arctg", "\\arcctg", "\\arg", "\\ch", "\\cos", "\\cosec", "\\cosh", "\\cot", "\\cotg", "\\coth", "\\csc", "\\ctg", "\\cth", "\\deg", "\\dim", "\\exp", "\\hom", "\\ker", "\\lg", "\\ln", "\\log", "\\sec", "\\sin", "\\sinh", "\\sh", "\\tan", "\\tanh", "\\tg", "\\th" ], numArgs: 0, handler(_ref3) { var parser = _ref3.parser, funcName = _ref3.funcName; return { type: "op", mode: parser.mode, limits: false, parentIsSupSub: false, symbol: false, name: funcName }; } }); defineFunction({ type: "op", names: [ "\\det", "\\gcd", "\\inf", "\\lim", "\\max", "\\min", "\\Pr", "\\sup" ], numArgs: 0, handler(_ref4) { var parser = _ref4.parser, funcName = _ref4.funcName; return { type: "op", mode: parser.mode, limits: true, parentIsSupSub: false, symbol: false, name: funcName }; } }); defineFunction({ type: "op", names: [ "\\int", "\\iint", "\\iiint", "\\oint", "\\oiint", "\\oiiint", "∫", "∬", "∭", "∮", "∯", "∰" ], numArgs: 0, allowedInArgument: true, handler(_ref5) { var parser = _ref5.parser; var fName = _ref5.funcName; if (fName.length === 1) fName = singleCharIntegrals[fName]; return { type: "op", mode: parser.mode, limits: false, parentIsSupSub: false, symbol: true, name: fName }; } }); var htmlBuilder$1 = (grp, options) => { var supGroup; var subGroup; var hasLimits = false; var group; if (grp.type === "supsub") { supGroup = grp.sup; subGroup = grp.sub; group = assertNodeType(grp.base, "operatorname"); hasLimits = true; } else group = assertNodeType(grp, "operatorname"); var base; if (group.body.length > 0) { var expression = buildExpression$1(group.body.map((child) => { var childText = "text" in child ? child.text : void 0; if (typeof childText === "string") return { type: "textord", mode: child.mode, text: childText }; else return child; }), options.withFont("mathrm"), true); for (var i = 0; i < expression.length; i++) { var child = expression[i]; if (child instanceof SymbolNode) child.text = child.text.replace(/\u2212/, "-").replace(/\u2217/, "*"); } base = makeSpan(["mop"], expression, options); } else base = makeSpan(["mop"], [], options); if (hasLimits) return assembleSupSub(base, supGroup, subGroup, options, options.style, 0, 0); else return base; }; var mathmlBuilder = (group, options) => { var expression = buildExpression(group.body, options.withFont("mathrm")); var isAllString = true; for (var i = 0; i < expression.length; i++) { var node = expression[i]; if (node instanceof SpaceNode); else if (node instanceof MathNode) switch (node.type) { case "mi": case "mn": case "mspace": case "mtext": break; case "mo": var child = node.children[0]; if (node.children.length === 1 && child instanceof TextNode) child.text = child.text.replace(/\u2212/, "-").replace(/\u2217/, "*"); else isAllString = false; break; default: isAllString = false; } else isAllString = false; } if (isAllString) expression = [new TextNode(expression.map((node) => node.toText()).join(""))]; var identifier = new MathNode("mi", expression); identifier.setAttribute("mathvariant", "normal"); var operator = new MathNode("mo", [makeText("⁡", "text")]); if (group.parentIsSupSub) return new MathNode("mrow", [identifier, operator]); else return newDocumentFragment([identifier, operator]); }; defineFunction({ type: "operatorname", names: ["\\operatorname@", "\\operatornamewithlimits"], numArgs: 1, handler: (_ref, args) => { var parser = _ref.parser, funcName = _ref.funcName; var body = args[0]; return { type: "operatorname", mode: parser.mode, body: ordargument(body), alwaysHandleSupSub: funcName === "\\operatornamewithlimits", limits: false, parentIsSupSub: false }; }, htmlBuilder: htmlBuilder$1, mathmlBuilder }); defineMacro("\\operatorname", "\\@ifstar\\operatornamewithlimits\\operatorname@"); defineFunctionBuilders({ type: "ordgroup", htmlBuilder(group, options) { if (group.semisimple) return makeFragment(buildExpression$1(group.body, options, false)); return makeSpan(["mord"], buildExpression$1(group.body, options, true), options); }, mathmlBuilder(group, options) { return buildExpressionRow(group.body, options, true); } }); defineFunction({ type: "overline", names: ["\\overline"], numArgs: 1, handler(_ref, args) { var parser = _ref.parser; var body = args[0]; return { type: "overline", mode: parser.mode, body }; }, htmlBuilder(group, options) { var innerGroup = buildGroup$1(group.body, options.havingCrampedStyle()); var line = makeLineSpan("overline-line", options); var defaultRuleThickness = options.fontMetrics().defaultRuleThickness; return makeSpan(["mord", "katex-overline"], [makeVList({ positionType: "firstBaseline", children: [ { type: "elem", elem: innerGroup }, { type: "kern", size: 3 * defaultRuleThickness }, { type: "elem", elem: line }, { type: "kern", size: defaultRuleThickness } ] })], options); }, mathmlBuilder(group, options) { var operator = new MathNode("mo", [new TextNode("‾")]); operator.setAttribute("stretchy", "true"); var node = new MathNode("mover", [buildGroup(group.body, options), operator]); node.setAttribute("accent", "true"); return node; } }); defineFunction({ type: "phantom", names: ["\\phantom"], numArgs: 1, allowedInText: true, handler: (_ref, args) => { var parser = _ref.parser; var body = args[0]; return { type: "phantom", mode: parser.mode, body: ordargument(body) }; }, htmlBuilder: (group, options) => { return makeFragment(buildExpression$1(group.body, options.withPhantom(), false)); }, mathmlBuilder: (group, options) => { return new MathNode("mphantom", buildExpression(group.body, options)); } }); defineMacro("\\hphantom", "\\smash{\\phantom{#1}}"); defineFunction({ type: "vphantom", names: ["\\vphantom"], numArgs: 1, allowedInText: true, handler: (_ref2, args) => { var parser = _ref2.parser; var body = args[0]; return { type: "vphantom", mode: parser.mode, body }; }, htmlBuilder: (group, options) => { return makeSpan(["mord", "rlap"], [makeSpan(["katex-inner"], [buildGroup$1(group.body, options.withPhantom())]), makeSpan(["katex-fix"], [])], options); }, mathmlBuilder: (group, options) => { var node = new MathNode("mpadded", [new MathNode("mphantom", buildExpression(ordargument(group.body), options))]); node.setAttribute("width", "0px"); return node; } }); defineFunction({ type: "raisebox", names: ["\\raisebox"], numArgs: 2, argTypes: ["size", "hbox"], allowedInText: true, handler(_ref, args) { var parser = _ref.parser; var amount = assertNodeType(args[0], "size").value; var body = args[1]; return { type: "raisebox", mode: parser.mode, dy: amount, body }; }, htmlBuilder(group, options) { var body = buildGroup$1(group.body, options); return makeVList({ positionType: "shift", positionData: -calculateSize(group.dy, options), children: [{ type: "elem", elem: body }] }); }, mathmlBuilder(group, options) { var node = new MathNode("mpadded", [buildGroup(group.body, options)]); var dy = group.dy.number + group.dy.unit; node.setAttribute("voffset", dy); return node; } }); var handler = (_ref, args) => { return { type: "reflectbox", mode: _ref.parser.mode, body: args[0] }; }; defineFunction({ type: "reflectbox", names: ["\\reflectbox"], numArgs: 1, argTypes: ["hbox"], allowedInText: true, handler, htmlBuilder(group, options) { return makeSpan(["mord", "reflectbox"], [buildGroup$1(group.body, options)], options); }, mathmlBuilder(group, options) { return buildGroup(group.body, options); } }); defineFunction({ type: "reflectbox", names: ["\\mathreflectbox"], numArgs: 1, argTypes: ["math"], handler }); defineFunction({ type: "internal", names: ["\\relax"], numArgs: 0, allowedInText: true, allowedInArgument: true, handler(_ref) { return { type: "internal", mode: _ref.parser.mode }; } }); defineFunction({ type: "rule", names: ["\\rule"], numArgs: 2, numOptionalArgs: 1, allowedInText: true, allowedInMath: true, argTypes: [ "size", "size", "size" ], handler(_ref, args, optArgs) { var parser = _ref.parser; var shift = optArgs[0]; var width = assertNodeType(args[0], "size"); var height = assertNodeType(args[1], "size"); return { type: "rule", mode: parser.mode, shift: shift && assertNodeType(shift, "size").value, width: width.value, height: height.value }; }, htmlBuilder(group, options) { var rule = makeSpan(["mord", "katex-rule"], [], options); var width = calculateSize(group.width, options); var height = calculateSize(group.height, options); var shift = group.shift ? calculateSize(group.shift, options) : 0; rule.style.borderRightWidth = makeEm(width); rule.style.borderTopWidth = makeEm(height); rule.style.bottom = makeEm(shift); rule.width = width; rule.height = height + shift; rule.depth = -shift; rule.maxFontSize = height * 1.125 * options.sizeMultiplier; return rule; }, mathmlBuilder(group, options) { var width = calculateSize(group.width, options); var height = calculateSize(group.height, options); var shift = group.shift ? calculateSize(group.shift, options) : 0; var color = options.color && options.getColor() || "black"; var rule = new MathNode("mspace"); rule.setAttribute("mathbackground", color); rule.setAttribute("width", makeEm(width)); rule.setAttribute("height", makeEm(height)); var wrapper = new MathNode("mpadded", [rule]); if (shift >= 0) wrapper.setAttribute("height", makeEm(shift)); else { wrapper.setAttribute("height", makeEm(shift)); wrapper.setAttribute("depth", makeEm(-shift)); } wrapper.setAttribute("voffset", makeEm(shift)); return wrapper; } }); function sizingGroup(value, options, baseOptions) { var inner = buildExpression$1(value, options, false); var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier; for (var i = 0; i < inner.length; i++) { var pos = inner[i].classes.indexOf("katex-sizing"); if (pos < 0) Array.prototype.push.apply(inner[i].classes, options.sizingClasses(baseOptions)); else if (inner[i].classes[pos + 1] === "reset-size" + options.size) inner[i].classes[pos + 1] = "reset-size" + baseOptions.size; inner[i].height *= multiplier; inner[i].depth *= multiplier; } return makeFragment(inner); } var sizeFuncs = [ "\\tiny", "\\sixptsize", "\\scriptsize", "\\footnotesize", "\\small", "\\normalsize", "\\large", "\\Large", "\\LARGE", "\\huge", "\\Huge" ]; var htmlBuilder = (group, options) => { var newOptions = options.havingSize(group.size); return sizingGroup(group.body, newOptions, options); }; defineFunction({ type: "sizing", names: sizeFuncs, numArgs: 0, allowedInText: true, handler: (_ref, args) => { var breakOnTokenText = _ref.breakOnTokenText, funcName = _ref.funcName, parser = _ref.parser; var body = parser.parseExpression(false, breakOnTokenText); return { type: "sizing", mode: parser.mode, size: sizeFuncs.indexOf(funcName) + 1, body }; }, htmlBuilder, mathmlBuilder: (group, options) => { var newOptions = options.havingSize(group.size); var node = new MathNode("mstyle", buildExpression(group.body, newOptions)); node.setAttribute("mathsize", makeEm(newOptions.sizeMultiplier)); return node; } }); defineFunction({ type: "smash", names: ["\\smash"], numArgs: 1, numOptionalArgs: 1, allowedInText: true, handler: (_ref, args, optArgs) => { var parser = _ref.parser; var smashHeight = false; var smashDepth = false; var tbArg = optArgs[0] && assertNodeType(optArgs[0], "ordgroup"); if (tbArg) { var letter; for (var i = 0; i < tbArg.body.length; ++i) { var node = tbArg.body[i]; letter = assertSymbolNodeType(node).text; if (letter === "t") smashHeight = true; else if (letter === "b") smashDepth = true; else { smashHeight = false; smashDepth = false; break; } } } else { smashHeight = true; smashDepth = true; } var body = args[0]; return { type: "smash", mode: parser.mode, body, smashHeight, smashDepth }; }, htmlBuilder: (group, options) => { var node = makeSpan([], [buildGroup$1(group.body, options)]); if (!group.smashHeight && !group.smashDepth) return node; if (group.smashHeight) node.height = 0; if (group.smashDepth) node.depth = 0; if (group.smashHeight && group.smashDepth) return makeSpan(["mord", "katex-smash"], [node], options); if (node.children) for (var i = 0; i < node.children.length; i++) { if (group.smashHeight) node.children[i].height = 0; if (group.smashDepth) node.children[i].depth = 0; } return makeSpan(["mord"], [makeVList({ positionType: "firstBaseline", children: [{ type: "elem", elem: node }] })], options); }, mathmlBuilder: (group, options) => { var node = new MathNode("mpadded", [buildGroup(group.body, options)]); if (group.smashHeight) node.setAttribute("height", "0px"); if (group.smashDepth) node.setAttribute("depth", "0px"); return node; } }); defineFunction({ type: "sqrt", names: ["\\sqrt"], numArgs: 1, numOptionalArgs: 1, handler(_ref, args, optArgs) { var parser = _ref.parser; var index = optArgs[0]; var body = args[0]; return { type: "sqrt", mode: parser.mode, body, index }; }, htmlBuilder(group, options) { var inner = buildGroup$1(group.body, options.havingCrampedStyle()); if (inner.height === 0) inner.height = options.fontMetrics().xHeight; inner = wrapFragment(inner, options); var theta = options.fontMetrics().defaultRuleThickness; var phi = theta; if (options.style.id < Style$1.TEXT.id) phi = options.fontMetrics().xHeight; var lineClearance = theta + phi / 4; var _makeSqrtImage = makeSqrtImage(inner.height + inner.depth + lineClearance + theta, options), img = _makeSqrtImage.span, ruleWidth = _makeSqrtImage.ruleWidth, advanceWidth = _makeSqrtImage.advanceWidth; var delimDepth = img.height - ruleWidth; if (delimDepth > inner.height + inner.depth + lineClearance) lineClearance = (lineClearance + delimDepth - inner.height - inner.depth) / 2; var imgShift = img.height - inner.height - lineClearance - ruleWidth; inner.style.paddingLeft = makeEm(advanceWidth); var body = makeVList({ positionType: "firstBaseline", children: [ { type: "elem", elem: inner, wrapperClasses: ["svg-align"] }, { type: "kern", size: -(inner.height + imgShift) }, { type: "elem", elem: img }, { type: "kern", size: ruleWidth } ] }); if (!group.index) return makeSpan(["mord", "sqrt"], [body], options); else { var newOptions = options.havingStyle(Style$1.SCRIPTSCRIPT); var rootm = buildGroup$1(group.index, newOptions, options); return makeSpan(["mord", "sqrt"], [makeSpan(["katex-root"], [makeVList({ positionType: "shift", positionData: -(.6 * (body.height - body.depth)), children: [{ type: "elem", elem: rootm }] })]), body], options); } }, mathmlBuilder(group, options) { var body = group.body, index = group.index; return index ? new MathNode("mroot", [buildGroup(body, options), buildGroup(index, options)]) : new MathNode("msqrt", [buildGroup(body, options)]); } }); var styleMap = { "display": Style$1.DISPLAY, "text": Style$1.TEXT, "script": Style$1.SCRIPT, "scriptscript": Style$1.SCRIPTSCRIPT }; function isStyleStr(s) { return s in styleMap; } defineFunction({ type: "styling", names: [ "\\displaystyle", "\\textstyle", "\\scriptstyle", "\\scriptscriptstyle" ], numArgs: 0, allowedInText: true, primitive: true, handler(_ref, args) { var breakOnTokenText = _ref.breakOnTokenText, funcName = _ref.funcName, parser = _ref.parser; var body = parser.parseExpression(true, breakOnTokenText); var style = funcName.slice(1, funcName.length - 5); if (!isStyleStr(style)) throw new Error("Unknown style: " + style); return { type: "styling", mode: parser.mode, style, body }; }, htmlBuilder(group, options) { var newStyle = styleMap[group.style]; var newOptions = options.havingStyle(newStyle); if (group.resetFont) newOptions = newOptions.withFont(""); return sizingGroup(group.body, newOptions, options); }, mathmlBuilder(group, options) { var newStyle = styleMap[group.style]; var newOptions = options.havingStyle(newStyle); if (group.resetFont) newOptions = newOptions.withFont(""); var node = new MathNode("mstyle", buildExpression(group.body, newOptions)); var attr = { "display": ["0", "true"], "text": ["0", "false"], "script": ["1", "false"], "scriptscript": ["2", "false"] }[group.style]; node.setAttribute("scriptlevel", attr[0]); node.setAttribute("displaystyle", attr[1]); return node; } }); /** * Sometimes, groups perform special rules when they have superscripts or * subscripts attached to them. This function lets the `supsub` group know that * Sometimes, groups perform special rules when they have superscripts or * its inner element should handle the superscripts and subscripts instead of * handling them itself. */ var htmlBuilderDelegate = function htmlBuilderDelegate(group, options) { var base = group.base; if (!base) return null; else if (base.type === "op") return base.limits && (options.style.size === Style$1.DISPLAY.size || base.alwaysHandleSupSub) ? htmlBuilder$2 : null; else if (base.type === "operatorname") return base.alwaysHandleSupSub && (options.style.size === Style$1.DISPLAY.size || base.limits) ? htmlBuilder$1 : null; else if (base.type === "accent") return isCharacterBox(base.base) ? htmlBuilder$a : null; else if (base.type === "horizBrace") return !group.sub === base.isOver ? htmlBuilder$3 : null; else return null; }; defineFunctionBuilders({ type: "supsub", htmlBuilder(group, options) { var builderDelegate = htmlBuilderDelegate(group, options); if (builderDelegate) return builderDelegate(group, options); var valueBase = group.base, valueSup = group.sup, valueSub = group.sub; var base = buildGroup$1(valueBase, options); var supm; var subm; var metrics = options.fontMetrics(); var supShift = 0; var subShift = 0; var isCharBox = valueBase && isCharacterBox(valueBase); if (valueSup) { var newOptions = options.havingStyle(options.style.sup()); supm = buildGroup$1(valueSup, newOptions, options); if (!isCharBox) supShift = base.height - newOptions.fontMetrics().supDrop * newOptions.sizeMultiplier / options.sizeMultiplier; } if (valueSub) { var _newOptions = options.havingStyle(options.style.sub()); subm = buildGroup$1(valueSub, _newOptions, options); if (!isCharBox) subShift = base.depth + _newOptions.fontMetrics().subDrop * _newOptions.sizeMultiplier / options.sizeMultiplier; } var minSupShift; if (options.style === Style$1.DISPLAY) minSupShift = metrics.sup1; else if (options.style.cramped) minSupShift = metrics.sup3; else minSupShift = metrics.sup2; var multiplier = options.sizeMultiplier; var marginRight = makeEm(.5 / metrics.ptPerEm / multiplier); var marginLeft = null; if (subm) { var isOiint = group.base && group.base.type === "op" && group.base.name && (group.base.name === "\\oiint" || group.base.name === "\\oiiint"); if (base instanceof SymbolNode || isOiint) { var _base$italic; marginLeft = makeEm(-((_base$italic = base.italic) != null ? _base$italic : 0)); } } var supsub; if (supm && subm) { supShift = Math.max(supShift, minSupShift, supm.depth + .25 * metrics.xHeight); subShift = Math.max(subShift, metrics.sub2); var maxWidth = 4 * metrics.defaultRuleThickness; if (supShift - supm.depth - (subm.height - subShift) < maxWidth) { subShift = maxWidth - (supShift - supm.depth) + subm.height; var psi = .8 * metrics.xHeight - (supShift - supm.depth); if (psi > 0) { supShift += psi; subShift -= psi; } } supsub = makeVList({ positionType: "individualShift", children: [{ type: "elem", elem: subm, shift: subShift, marginRight, marginLeft }, { type: "elem", elem: supm, shift: -supShift, marginRight }] }); } else if (subm) { subShift = Math.max(subShift, metrics.sub1, subm.height - .8 * metrics.xHeight); supsub = makeVList({ positionType: "shift", positionData: subShift, children: [{ type: "elem", elem: subm, marginLeft, marginRight }] }); } else if (supm) { supShift = Math.max(supShift, minSupShift, supm.depth + .25 * metrics.xHeight); supsub = makeVList({ positionType: "shift", positionData: -supShift, children: [{ type: "elem", elem: supm, marginRight }] }); } else throw new Error("supsub must have either sup or sub."); return makeSpan([getTypeOfDomTree(base, "right") || "mord"], [base, makeSpan(["msupsub"], [supsub])], options); }, mathmlBuilder(group, options) { var isBrace = false; var isOver; var isSup; if (group.base && group.base.type === "horizBrace") { isSup = !!group.sup; if (isSup === group.base.isOver) { isBrace = true; isOver = group.base.isOver; } } if (group.base && (group.base.type === "op" || group.base.type === "operatorname")) group.base.parentIsSupSub = true; var children = [buildGroup(group.base, options)]; if (group.sub) children.push(buildGroup(group.sub, options)); if (group.sup) children.push(buildGroup(group.sup, options)); var nodeType; if (isBrace) nodeType = isOver ? "mover" : "munder"; else if (!group.sub) { var base = group.base; if (base && base.type === "op" && base.limits && (options.style === Style$1.DISPLAY || base.alwaysHandleSupSub)) nodeType = "mover"; else if (base && base.type === "operatorname" && base.alwaysHandleSupSub && (base.limits || options.style === Style$1.DISPLAY)) nodeType = "mover"; else nodeType = "msup"; } else if (!group.sup) { var _base = group.base; if (_base && _base.type === "op" && _base.limits && (options.style === Style$1.DISPLAY || _base.alwaysHandleSupSub)) nodeType = "munder"; else if (_base && _base.type === "operatorname" && _base.alwaysHandleSupSub && (_base.limits || options.style === Style$1.DISPLAY)) nodeType = "munder"; else nodeType = "msub"; } else { var _base2 = group.base; if (_base2 && _base2.type === "op" && _base2.limits && options.style === Style$1.DISPLAY) nodeType = "munderover"; else if (_base2 && _base2.type === "operatorname" && _base2.alwaysHandleSupSub && (options.style === Style$1.DISPLAY || _base2.limits)) nodeType = "munderover"; else nodeType = "msubsup"; } return new MathNode(nodeType, children); } }); defineFunctionBuilders({ type: "atom", htmlBuilder(group, options) { return mathsym(group.text, group.mode, options, ["m" + group.family]); }, mathmlBuilder(group, options) { var node = new MathNode("mo", [makeText(group.text, group.mode)]); if (group.family === "bin") { var variant = getVariant(group, options); if (variant === "bold-italic") node.setAttribute("mathvariant", variant); } else if (group.family === "punct") node.setAttribute("separator", "true"); else if (group.family === "open" || group.family === "close") node.setAttribute("stretchy", "false"); return node; } }); var defaultVariant = { "mi": "italic", "mn": "normal", "mtext": "normal" }; defineFunctionBuilders({ type: "mathord", htmlBuilder(group, options) { return makeOrd(group, options); }, mathmlBuilder(group, options) { var node = new MathNode("mi", [makeText(group.text, group.mode, options)]); var variant = getVariant(group, options) || "italic"; if (variant !== defaultVariant[node.type]) node.setAttribute("mathvariant", variant); return node; } }); defineFunctionBuilders({ type: "textord", htmlBuilder(group, options) { return makeOrd(group, options); }, mathmlBuilder(group, options) { var text = makeText(group.text, group.mode, options); var variant = getVariant(group, options) || "normal"; var node; if (group.mode === "text") node = new MathNode("mtext", [text]); else if (/[0-9]/.test(group.text)) node = new MathNode("mn", [text]); else if (group.text === "\\prime") node = new MathNode("mo", [text]); else node = new MathNode("mi", [text]); if (variant !== defaultVariant[node.type]) node.setAttribute("mathvariant", variant); return node; } }); var cssSpace = /* @__PURE__ */ new Map([["\\nobreak", "nobreak"], ["\\allowbreak", "allowbreak"]]); var regularSpace = /* @__PURE__ */ new Map([ [" ", {}], ["\\ ", {}], ["~", { className: "nobreak" }], ["\\space", {}], ["\\nobreakspace", { className: "nobreak" }] ]); defineFunctionBuilders({ type: "spacing", htmlBuilder(group, options) { var regularSpaceItem = regularSpace.get(group.text); var cssSpaceClass = cssSpace.get(group.text); if (regularSpaceItem) { var className = regularSpaceItem.className || ""; if (group.mode === "text") { var ord = makeOrd(group, options); ord.classes.push(className); return ord; } else return makeSpan(["mspace", className], [mathsym(group.text, group.mode, options)], options); } else if (cssSpaceClass) return makeSpan(["mspace", cssSpaceClass], [], options); else throw new ParseError("Unknown type of space \"" + group.text + "\""); }, mathmlBuilder(group, options) { var node; if (regularSpace.has(group.text)) node = new MathNode("mtext", [new TextNode("\xA0")]); else if (cssSpace.has(group.text)) return new MathNode("mspace"); else throw new ParseError("Unknown type of space \"" + group.text + "\""); return node; } }); var pad = () => { var padNode = new MathNode("mtd", []); padNode.setAttribute("width", "50%"); return padNode; }; defineFunctionBuilders({ type: "tag", mathmlBuilder(group, options) { var table = new MathNode("mtable", [new MathNode("mtr", [ pad(), new MathNode("mtd", [buildExpressionRow(group.body, options)]), pad(), new MathNode("mtd", [buildExpressionRow(group.tag, options)]) ])]); table.setAttribute("width", "100%"); return table; } }); var textFontFamilies = { "\\text": void 0, "\\textrm": "textrm", "\\textsf": "textsf", "\\texttt": "texttt", "\\textnormal": "textrm" }; var textFontWeights = { "\\textbf": "textbf", "\\textmd": "textmd" }; var textFontShapes = { "\\textit": "textit", "\\textup": "textup" }; var optionsWithFont = (group, options) => { var font = group.font; if (!font) return options; else if (textFontFamilies[font]) return options.withTextFontFamily(textFontFamilies[font]); else if (textFontWeights[font]) return options.withTextFontWeight(textFontWeights[font]); else if (font === "\\emph") return options.fontShape === "textit" ? options.withTextFontShape("textup") : options.withTextFontShape("textit"); return options.withTextFontShape(textFontShapes[font]); }; defineFunction({ type: "text", names: [ "\\text", "\\textrm", "\\textsf", "\\texttt", "\\textnormal", "\\textbf", "\\textmd", "\\textit", "\\textup", "\\emph" ], numArgs: 1, argTypes: ["text"], allowedInArgument: true, allowedInText: true, handler(_ref, args) { var parser = _ref.parser, funcName = _ref.funcName; var body = args[0]; return { type: "text", mode: parser.mode, body: ordargument(body), font: funcName }; }, htmlBuilder(group, options) { var newOptions = optionsWithFont(group, options); return makeSpan(["mord", "text"], buildExpression$1(group.body, newOptions, true), newOptions); }, mathmlBuilder(group, options) { var newOptions = optionsWithFont(group, options); return buildExpressionRow(group.body, newOptions); } }); defineFunction({ type: "underline", names: ["\\underline"], numArgs: 1, allowedInText: true, handler(_ref, args) { return { type: "underline", mode: _ref.parser.mode, body: args[0] }; }, htmlBuilder(group, options) { var innerGroup = buildGroup$1(group.body, options); var line = makeLineSpan("underline-line", options); var defaultRuleThickness = options.fontMetrics().defaultRuleThickness; return makeSpan(["mord", "katex-underline"], [makeVList({ positionType: "top", positionData: innerGroup.height, children: [ { type: "kern", size: defaultRuleThickness }, { type: "elem", elem: line }, { type: "kern", size: 3 * defaultRuleThickness }, { type: "elem", elem: innerGroup } ] })], options); }, mathmlBuilder(group, options) { var operator = new MathNode("mo", [new TextNode("‾")]); operator.setAttribute("stretchy", "true"); var node = new MathNode("munder", [buildGroup(group.body, options), operator]); node.setAttribute("accentunder", "true"); return node; } }); defineFunction({ type: "vcenter", names: ["\\vcenter"], numArgs: 1, argTypes: ["original"], allowedInText: false, handler(_ref, args) { return { type: "vcenter", mode: _ref.parser.mode, body: args[0] }; }, htmlBuilder(group, options) { var body = buildGroup$1(group.body, options); var axisHeight = options.fontMetrics().axisHeight; return makeVList({ positionType: "shift", positionData: .5 * (body.height - axisHeight - (body.depth + axisHeight)), children: [{ type: "elem", elem: body }] }); }, mathmlBuilder(group, options) { return new MathNode("mrow", [new MathNode("mpadded", [buildGroup(group.body, options)], ["vcenter"])]); } }); defineFunction({ type: "verb", names: ["\\verb"], numArgs: 0, allowedInText: true, handler(context, args, optArgs) { throw new ParseError("\\verb ended by end of line instead of matching delimiter"); }, htmlBuilder(group, options) { var text = makeVerb(group); var body = []; var newOptions = options.havingStyle(options.style.text()); for (var i = 0; i < text.length; i++) { var c = text[i]; if (c === "~") c = "\\textasciitilde"; body.push(makeSymbol(c, "Typewriter-Regular", group.mode, newOptions, ["mord", "texttt"])); } return makeSpan(["mord", "text"].concat(newOptions.sizingClasses(options)), tryCombineChars(body), newOptions); }, mathmlBuilder(group, options) { var node = new MathNode("mtext", [new TextNode(makeVerb(group))]); node.setAttribute("mathvariant", "monospace"); return node; } }); /** * Converts verb group into body string. * * \verb* replaces each space with an open box \u2423 * \verb replaces each space with a no-break space \xA0 */ var makeVerb = (group) => group.body.replace(/ /g, group.star ? "␣" : "\xA0"); /** Include this to ensure that all functions are defined. */ var functions = _functions; /** * The Lexer class handles tokenizing the input in various ways. Since our * parser expects us to be able to backtrack, the lexer allows lexing from any * given starting point. * * Its main exposed function is the `lex` function, which takes a position to * lex from and a type of token to lex. It defers to the appropriate `_innerLex` * function. * * The various `_innerLex` functions perform the actual lexing of different * kinds. */ var spaceRegexString = "[ \r\n ]"; var controlWordRegexString = "\\\\[a-zA-Z@]+"; var controlSymbolRegexString = "\\\\[^\ud800-\udfff]"; var controlWordWhitespaceRegexString = "(" + controlWordRegexString + ")" + spaceRegexString + "*"; var controlSpaceRegexString = "\\\\(\n|[ \r ]+\n?)[ \r ]*"; var combiningDiacriticalMarkString = "[̀-ͯ]"; var combiningDiacriticalMarksEndRegex = new RegExp(combiningDiacriticalMarkString + "+$"); var tokenRegexString = "(" + spaceRegexString + "+)|" + (controlSpaceRegexString + "|") + "([!-\\[\\]-‧‪-퟿豈-￿]" + (combiningDiacriticalMarkString + "*") + "|[\ud800-\udbff][\udc00-\udfff]" + (combiningDiacriticalMarkString + "*") + "|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5" + ("|" + controlWordWhitespaceRegexString) + ("|" + controlSymbolRegexString + ")"); /** Main Lexer class */ var Lexer = class { constructor(input, settings) { this.input = void 0; this.settings = void 0; this.tokenRegex = void 0; this.catcodes = void 0; this.input = input; this.settings = settings; this.tokenRegex = new RegExp(tokenRegexString, "g"); this.catcodes = { "%": 14, "~": 13 }; } setCatcode(char, code) { this.catcodes[char] = code; } /** * This function lexes a single token. */ lex() { var input = this.input; var pos = this.tokenRegex.lastIndex; if (pos === input.length) return new Token("EOF", new SourceLocation(this, pos, pos)); var match = this.tokenRegex.exec(input); if (match === null || match.index !== pos) throw new ParseError("Unexpected character: '" + input[pos] + "'", new Token(input[pos], new SourceLocation(this, pos, pos + 1))); var text = match[6] || match[3] || (match[2] ? "\\ " : " "); if (this.catcodes[text] === 14) { var nlIndex = input.indexOf("\n", this.tokenRegex.lastIndex); if (nlIndex === -1) { this.tokenRegex.lastIndex = input.length; handleStrict({ strict: this.settings.strict, errorCode: "commentAtEnd", errorMsg: "% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)", report: true }); } else this.tokenRegex.lastIndex = nlIndex + 1; return this.lex(); } return new Token(text, new SourceLocation(this, pos, this.tokenRegex.lastIndex)); } }; /** * A `Namespace` refers to a space of nameable things like macros or lengths, * which can be `set` either globally or local to a nested group, using an * undo stack similar to how TeX implements this functionality. * Performance-wise, `get` and local `set` take constant time, while global * `set` takes time proportional to the depth of group nesting. */ var Namespace = class { /** * Both arguments are optional. The first argument is an object of * built-in mappings which never change. The second argument is an object * of initial (global-level) mappings, which will constantly change * according to any global/top-level `set`s done. */ constructor(builtins, globalMacros) { if (builtins === void 0) builtins = {}; if (globalMacros === void 0) globalMacros = {}; this.current = void 0; this.builtins = void 0; this.undefStack = void 0; this.current = globalMacros; this.builtins = builtins; this.undefStack = []; } /** * Start a new nested group, affecting future local `set`s. */ beginGroup() { this.undefStack.push({}); } /** * End current nested group, restoring values before the group began. */ endGroup() { if (this.undefStack.length === 0) throw new ParseError("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug"); var undefs = this.undefStack.pop(); for (var key of Object.keys(undefs)) if (undefs[key] === void 0) delete this.current[key]; else this.current[key] = undefs[key]; } /** * Ends all currently nested groups (if any), restoring values before the * groups began. Useful in case of an error in the middle of parsing. */ endGroups() { while (this.undefStack.length > 0) this.endGroup(); } /** * Detect whether `name` has a definition. Equivalent to * `get(name) != null`. */ has(name) { return Object.prototype.hasOwnProperty.call(this.current, name) || Object.prototype.hasOwnProperty.call(this.builtins, name); } /** * Get the current value of a name, or `undefined` if there is no value. * * Note: Do not use `if (namespace.get(...))` to detect whether a macro * is defined, as the definition may be the empty string which evaluates * to `false` in JavaScript. Use `if (namespace.get(...) != null)` or * `if (namespace.has(...))`. */ get(name) { if (Object.prototype.hasOwnProperty.call(this.current, name)) return this.current[name]; else if (Object.prototype.hasOwnProperty.call(this.builtins, name)) return this.builtins[name]; else return; } /** * Set the current value of a name, and optionally set it globally too. * Local set() sets the current value and (when appropriate) adds an undo * operation to the undo stack. Global set() may change the undo * operation at every level, so takes time linear in their number. * A value of undefined means to delete existing definitions. */ set(name, value, global) { if (global === void 0) global = false; if (global) { for (var i = 0; i < this.undefStack.length; i++) delete this.undefStack[i][name]; if (this.undefStack.length > 0) this.undefStack[this.undefStack.length - 1][name] = value; } else { var top = this.undefStack[this.undefStack.length - 1]; if (top && !Object.prototype.hasOwnProperty.call(top, name)) top[name] = Object.prototype.hasOwnProperty.call(this.current, name) ? this.current[name] : void 0; } if (value == null) delete this.current[name]; else this.current[name] = value; } }; /** * Predefined macros for KaTeX. * This can be used to define some commands in terms of others. */ var macros = _macros; defineMacro("\\noexpand", function(context) { var t = context.popToken(); if (context.isExpandable(t.text)) { t.noexpand = true; t.treatAsRelax = true; } return { tokens: [t], numArgs: 0 }; }); defineMacro("\\expandafter", function(context) { var t = context.popToken(); context.expandOnce(true); return { tokens: [t], numArgs: 0 }; }); defineMacro("\\@firstoftwo", function(context) { return { tokens: context.consumeArgs(2)[0], numArgs: 0 }; }); defineMacro("\\@secondoftwo", function(context) { return { tokens: context.consumeArgs(2)[1], numArgs: 0 }; }); defineMacro("\\@ifnextchar", function(context) { var args = context.consumeArgs(3); context.consumeSpaces(); var nextToken = context.future(); if (args[0].length === 1 && args[0][0].text === nextToken.text) return { tokens: args[1], numArgs: 0 }; else return { tokens: args[2], numArgs: 0 }; }); defineMacro("\\@ifstar", "\\@ifnextchar *{\\@firstoftwo{#1}}"); defineMacro("\\TextOrMath", function(context) { var args = context.consumeArgs(2); if (context.mode === "text") return { tokens: args[0], numArgs: 0 }; else return { tokens: args[1], numArgs: 0 }; }); var digitToNumber = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "a": 10, "A": 10, "b": 11, "B": 11, "c": 12, "C": 12, "d": 13, "D": 13, "e": 14, "E": 14, "f": 15, "F": 15 }; defineMacro("\\char", function(context) { var token = context.popToken(); var base; var number = 0; if (token.text === "'") { base = 8; token = context.popToken(); } else if (token.text === "\"") { base = 16; token = context.popToken(); } else if (token.text === "`") { token = context.popToken(); if (token.text[0] === "\\") number = token.text.charCodeAt(1); else if (token.text === "EOF") throw new ParseError("\\char` missing argument"); else number = token.text.charCodeAt(0); } else base = 10; if (base) { number = digitToNumber[token.text]; if (number == null || number >= base) throw new ParseError("Invalid base-" + base + " digit " + token.text); var digit; while ((digit = digitToNumber[context.future().text]) != null && digit < base) { number *= base; number += digit; context.popToken(); } } return "\\@char{" + number + "}"; }); var newcommand = (context, existsOK, nonexistsOK, skipIfExists) => { var arg = context.consumeArg().tokens; if (arg.length !== 1) throw new ParseError("\\newcommand's first argument must be a macro name"); var name = arg[0].text; var exists = context.isDefined(name); if (exists && !existsOK) throw new ParseError("\\newcommand{" + name + "} attempting to redefine " + (name + "; use \\renewcommand")); if (!exists && !nonexistsOK) throw new ParseError("\\renewcommand{" + name + "} when command " + name + " does not yet exist; use \\newcommand"); var numArgs = 0; arg = context.consumeArg().tokens; if (arg.length === 1 && arg[0].text === "[") { var argText = ""; var token = context.expandNextToken(); while (token.text !== "]" && token.text !== "EOF") { argText += token.text; token = context.expandNextToken(); } if (!argText.match(/^\s*[0-9]+\s*$/)) throw new ParseError("Invalid number of arguments: " + argText); numArgs = parseInt(argText); arg = context.consumeArg().tokens; } if (!(exists && skipIfExists)) context.macros.set(name, { tokens: arg, numArgs }); return ""; }; defineMacro("\\newcommand", (context) => newcommand(context, false, true, false)); defineMacro("\\renewcommand", (context) => newcommand(context, true, false, false)); defineMacro("\\providecommand", (context) => newcommand(context, true, true, true)); defineMacro("\\message", (context) => { var arg = context.consumeArgs(1)[0]; console.log(arg.reverse().map((token) => token.text).join("")); return ""; }); defineMacro("\\errmessage", (context) => { var arg = context.consumeArgs(1)[0]; console.error(arg.reverse().map((token) => token.text).join("")); return ""; }); defineMacro("\\show", (context) => { var tok = context.popToken(); var name = tok.text; console.log(tok, context.macros.get(name), functions[name], symbols.math[name], symbols.text[name]); return ""; }); defineMacro("\\bgroup", "{"); defineMacro("\\egroup", "}"); defineMacro("~", "\\nobreakspace"); defineMacro("\\lq", "`"); defineMacro("\\rq", "'"); defineMacro("\\aa", "\\r a"); defineMacro("\\AA", "\\r A"); defineMacro("\\textcopyright", "\\html@mathml{\\textcircled{c}}{\\char`©}"); defineMacro("\\copyright", "\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}"); defineMacro("\\textregistered", "\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"); defineMacro("ℬ", "\\mathscr{B}"); defineMacro("ℰ", "\\mathscr{E}"); defineMacro("ℱ", "\\mathscr{F}"); defineMacro("ℋ", "\\mathscr{H}"); defineMacro("ℐ", "\\mathscr{I}"); defineMacro("ℒ", "\\mathscr{L}"); defineMacro("ℳ", "\\mathscr{M}"); defineMacro("ℛ", "\\mathscr{R}"); defineMacro("ℭ", "\\mathfrak{C}"); defineMacro("ℌ", "\\mathfrak{H}"); defineMacro("ℨ", "\\mathfrak{Z}"); defineMacro("\\Bbbk", "\\Bbb{k}"); defineMacro("\\llap", "\\mathllap{\\textrm{#1}}"); defineMacro("\\rlap", "\\mathrlap{\\textrm{#1}}"); defineMacro("\\clap", "\\mathclap{\\textrm{#1}}"); defineMacro("\\mathstrut", "\\vphantom{(}"); defineMacro("\\underbar", "\\underline{\\text{#1}}"); defineMacro("\\not", "\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char\"338}"); defineMacro("\\neq", "\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`≠}}"); defineMacro("\\ne", "\\neq"); defineMacro("≠", "\\neq"); defineMacro("\\notin", "\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`∉}}"); defineMacro("∉", "\\notin"); defineMacro("≘", "\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`≘}}"); defineMacro("≙", "\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`≘}}"); defineMacro("≚", "\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`≚}}"); defineMacro("≛", "\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`≛}}"); defineMacro("≝", "\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`≝}}"); defineMacro("≞", "\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`≞}}"); defineMacro("≟", "\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`≟}}"); defineMacro("⟂", "\\perp"); defineMacro("‼", "\\mathclose{!\\mkern-0.8mu!}"); defineMacro("∌", "\\notni"); defineMacro("⌜", "\\ulcorner"); defineMacro("⌝", "\\urcorner"); defineMacro("⌞", "\\llcorner"); defineMacro("⌟", "\\lrcorner"); defineMacro("©", "\\copyright"); defineMacro("®", "\\textregistered"); defineMacro("\\ulcorner", "\\html@mathml{\\@ulcorner}{\\mathop{\\char\"231c}}"); defineMacro("\\urcorner", "\\html@mathml{\\@urcorner}{\\mathop{\\char\"231d}}"); defineMacro("\\llcorner", "\\html@mathml{\\@llcorner}{\\mathop{\\char\"231e}}"); defineMacro("\\lrcorner", "\\html@mathml{\\@lrcorner}{\\mathop{\\char\"231f}}"); defineMacro("\\vdots", "{\\varvdots\\rule{0pt}{15pt}}"); defineMacro("⋮", "\\vdots"); defineMacro("\\varGamma", "\\mathit{\\Gamma}"); defineMacro("\\varDelta", "\\mathit{\\Delta}"); defineMacro("\\varTheta", "\\mathit{\\Theta}"); defineMacro("\\varLambda", "\\mathit{\\Lambda}"); defineMacro("\\varXi", "\\mathit{\\Xi}"); defineMacro("\\varPi", "\\mathit{\\Pi}"); defineMacro("\\varSigma", "\\mathit{\\Sigma}"); defineMacro("\\varUpsilon", "\\mathit{\\Upsilon}"); defineMacro("\\varPhi", "\\mathit{\\Phi}"); defineMacro("\\varPsi", "\\mathit{\\Psi}"); defineMacro("\\varOmega", "\\mathit{\\Omega}"); defineMacro("\\substack", "\\begin{subarray}{c}#1\\end{subarray}"); defineMacro("\\colon", "\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax"); defineMacro("\\boxed", "\\fbox{$\\displaystyle{#1}$}"); defineMacro("\\iff", "\\DOTSB\\;\\Longleftrightarrow\\;"); defineMacro("\\implies", "\\DOTSB\\;\\Longrightarrow\\;"); defineMacro("\\impliedby", "\\DOTSB\\;\\Longleftarrow\\;"); defineMacro("\\dddot", "{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}"); defineMacro("\\ddddot", "{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}"); var dotsByToken = { ",": "\\dotsc", "\\not": "\\dotsb", "+": "\\dotsb", "=": "\\dotsb", "<": "\\dotsb", ">": "\\dotsb", "-": "\\dotsb", "*": "\\dotsb", ":": "\\dotsb", "\\DOTSB": "\\dotsb", "\\coprod": "\\dotsb", "\\bigvee": "\\dotsb", "\\bigwedge": "\\dotsb", "\\biguplus": "\\dotsb", "\\bigcap": "\\dotsb", "\\bigcup": "\\dotsb", "\\prod": "\\dotsb", "\\sum": "\\dotsb", "\\bigotimes": "\\dotsb", "\\bigoplus": "\\dotsb", "\\bigodot": "\\dotsb", "\\bigsqcup": "\\dotsb", "\\And": "\\dotsb", "\\longrightarrow": "\\dotsb", "\\Longrightarrow": "\\dotsb", "\\longleftarrow": "\\dotsb", "\\Longleftarrow": "\\dotsb", "\\longleftrightarrow": "\\dotsb", "\\Longleftrightarrow": "\\dotsb", "\\mapsto": "\\dotsb", "\\longmapsto": "\\dotsb", "\\hookrightarrow": "\\dotsb", "\\doteq": "\\dotsb", "\\mathbin": "\\dotsb", "\\mathrel": "\\dotsb", "\\relbar": "\\dotsb", "\\Relbar": "\\dotsb", "\\xrightarrow": "\\dotsb", "\\xleftarrow": "\\dotsb", "\\DOTSI": "\\dotsi", "\\int": "\\dotsi", "\\oint": "\\dotsi", "\\iint": "\\dotsi", "\\iiint": "\\dotsi", "\\iiiint": "\\dotsi", "\\idotsint": "\\dotsi", "\\DOTSX": "\\dotsx" }; var dotsbGroups = /* @__PURE__ */ new Set(["bin", "rel"]); defineMacro("\\dots", function(context) { var thedots = "\\dotso"; var next = context.expandAfterFuture().text; if (next in dotsByToken) thedots = dotsByToken[next]; else if (next.slice(0, 4) === "\\not") thedots = "\\dotsb"; else if (next in symbols.math) { if (dotsbGroups.has(symbols.math[next].group)) thedots = "\\dotsb"; } return thedots; }); var spaceAfterDots = { ")": true, "]": true, "\\rbrack": true, "\\}": true, "\\rbrace": true, "\\rangle": true, "\\rceil": true, "\\rfloor": true, "\\rgroup": true, "\\rmoustache": true, "\\right": true, "\\bigr": true, "\\biggr": true, "\\Bigr": true, "\\Biggr": true, "$": true, ";": true, ".": true, ",": true }; defineMacro("\\dotso", function(context) { if (context.future().text in spaceAfterDots) return "\\ldots\\,"; else return "\\ldots"; }); defineMacro("\\dotsc", function(context) { var next = context.future().text; if (next in spaceAfterDots && next !== ",") return "\\ldots\\,"; else return "\\ldots"; }); defineMacro("\\cdots", function(context) { if (context.future().text in spaceAfterDots) return "\\@cdots\\,"; else return "\\@cdots"; }); defineMacro("\\dotsb", "\\cdots"); defineMacro("\\dotsm", "\\cdots"); defineMacro("\\dotsi", "\\!\\cdots"); defineMacro("\\dotsx", "\\ldots\\,"); defineMacro("\\DOTSI", "\\relax"); defineMacro("\\DOTSB", "\\relax"); defineMacro("\\DOTSX", "\\relax"); defineMacro("\\tmspace", "\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax"); defineMacro("\\,", "\\tmspace+{3mu}{.1667em}"); defineMacro("\\thinspace", "\\,"); defineMacro("\\>", "\\mskip{4mu}"); defineMacro("\\:", "\\tmspace+{4mu}{.2222em}"); defineMacro("\\medspace", "\\:"); defineMacro("\\;", "\\tmspace+{5mu}{.2777em}"); defineMacro("\\thickspace", "\\;"); defineMacro("\\!", "\\tmspace-{3mu}{.1667em}"); defineMacro("\\negthinspace", "\\!"); defineMacro("\\negmedspace", "\\tmspace-{4mu}{.2222em}"); defineMacro("\\negthickspace", "\\tmspace-{5mu}{.277em}"); defineMacro("\\enspace", "\\kern.5em "); defineMacro("\\enskip", "\\hskip.5em\\relax"); defineMacro("\\quad", "\\hskip1em\\relax"); defineMacro("\\qquad", "\\hskip2em\\relax"); defineMacro("\\tag", "\\@ifstar\\tag@literal\\tag@paren"); defineMacro("\\tag@paren", "\\tag@literal{({#1})}"); defineMacro("\\tag@literal", (context) => { if (context.macros.get("\\df@tag")) throw new ParseError("Multiple \\tag"); return "\\gdef\\df@tag{\\text{#1}}"; }); defineMacro("\\bmod", "\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}"); defineMacro("\\pod", "\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)"); defineMacro("\\pmod", "\\pod{{\\rm mod}\\mkern6mu#1}"); defineMacro("\\mod", "\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1"); defineMacro("\\newline", "\\\\\\relax"); defineMacro("\\TeX", "\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}"); var latexRaiseA = makeEm(fontMetricsData["Main-Regular"]["T".charCodeAt(0)][1] - .7 * fontMetricsData["Main-Regular"]["A".charCodeAt(0)][1]); defineMacro("\\LaTeX", "\\textrm{\\html@mathml{" + ("L\\kern-.36em\\raisebox{" + latexRaiseA + "}{\\scriptstyle A}") + "\\kern-.15em\\TeX}{LaTeX}}"); defineMacro("\\KaTeX", "\\textrm{\\html@mathml{" + ("K\\kern-.17em\\raisebox{" + latexRaiseA + "}{\\scriptstyle A}") + "\\kern-.15em\\TeX}{KaTeX}}"); defineMacro("\\hspace", "\\@ifstar\\@hspacer\\@hspace"); defineMacro("\\@hspace", "\\hskip #1\\relax"); defineMacro("\\@hspacer", "\\rule{0pt}{0pt}\\hskip #1\\relax"); defineMacro("\\ordinarycolon", ":"); defineMacro("\\vcentcolon", "\\mathrel{\\mathop\\ordinarycolon}"); defineMacro("\\dblcolon", "\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char\"2237}}"); defineMacro("\\coloneqq", "\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char\"2254}}"); defineMacro("\\Coloneqq", "\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char\"2237\\char\"3d}}"); defineMacro("\\coloneq", "\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char\"3a\\char\"2212}}"); defineMacro("\\Coloneq", "\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char\"2237\\char\"2212}}"); defineMacro("\\eqqcolon", "\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char\"2255}}"); defineMacro("\\Eqqcolon", "\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char\"3d\\char\"2237}}"); defineMacro("\\eqcolon", "\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char\"2239}}"); defineMacro("\\Eqcolon", "\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char\"2212\\char\"2237}}"); defineMacro("\\colonapprox", "\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char\"3a\\char\"2248}}"); defineMacro("\\Colonapprox", "\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char\"2237\\char\"2248}}"); defineMacro("\\colonsim", "\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char\"3a\\char\"223c}}"); defineMacro("\\Colonsim", "\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char\"2237\\char\"223c}}"); defineMacro("∷", "\\dblcolon"); defineMacro("∹", "\\eqcolon"); defineMacro("≔", "\\coloneqq"); defineMacro("≕", "\\eqqcolon"); defineMacro("⩴", "\\Coloneqq"); defineMacro("\\ratio", "\\vcentcolon"); defineMacro("\\coloncolon", "\\dblcolon"); defineMacro("\\colonequals", "\\coloneqq"); defineMacro("\\coloncolonequals", "\\Coloneqq"); defineMacro("\\equalscolon", "\\eqqcolon"); defineMacro("\\equalscoloncolon", "\\Eqqcolon"); defineMacro("\\colonminus", "\\coloneq"); defineMacro("\\coloncolonminus", "\\Coloneq"); defineMacro("\\minuscolon", "\\eqcolon"); defineMacro("\\minuscoloncolon", "\\Eqcolon"); defineMacro("\\coloncolonapprox", "\\Colonapprox"); defineMacro("\\coloncolonsim", "\\Colonsim"); defineMacro("\\simcolon", "\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}"); defineMacro("\\simcoloncolon", "\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}"); defineMacro("\\approxcolon", "\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}"); defineMacro("\\approxcoloncolon", "\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}"); defineMacro("\\notni", "\\html@mathml{\\not\\ni}{\\mathrel{\\char`∌}}"); defineMacro("\\limsup", "\\DOTSB\\operatorname*{lim\\,sup}"); defineMacro("\\liminf", "\\DOTSB\\operatorname*{lim\\,inf}"); defineMacro("\\injlim", "\\DOTSB\\operatorname*{inj\\,lim}"); defineMacro("\\projlim", "\\DOTSB\\operatorname*{proj\\,lim}"); defineMacro("\\varlimsup", "\\DOTSB\\operatorname*{\\overline{lim}}"); defineMacro("\\varliminf", "\\DOTSB\\operatorname*{\\underline{lim}}"); defineMacro("\\varinjlim", "\\DOTSB\\operatorname*{\\underrightarrow{lim}}"); defineMacro("\\varprojlim", "\\DOTSB\\operatorname*{\\underleftarrow{lim}}"); defineMacro("\\gvertneqq", "\\html@mathml{\\@gvertneqq}{≩}"); defineMacro("\\lvertneqq", "\\html@mathml{\\@lvertneqq}{≨}"); defineMacro("\\ngeqq", "\\html@mathml{\\@ngeqq}{≱}"); defineMacro("\\ngeqslant", "\\html@mathml{\\@ngeqslant}{≱}"); defineMacro("\\nleqq", "\\html@mathml{\\@nleqq}{≰}"); defineMacro("\\nleqslant", "\\html@mathml{\\@nleqslant}{≰}"); defineMacro("\\nshortmid", "\\html@mathml{\\@nshortmid}{∤}"); defineMacro("\\nshortparallel", "\\html@mathml{\\@nshortparallel}{∦}"); defineMacro("\\nsubseteqq", "\\html@mathml{\\@nsubseteqq}{⊈}"); defineMacro("\\nsupseteqq", "\\html@mathml{\\@nsupseteqq}{⊉}"); defineMacro("\\varsubsetneq", "\\html@mathml{\\@varsubsetneq}{⊊}"); defineMacro("\\varsubsetneqq", "\\html@mathml{\\@varsubsetneqq}{⫋}"); defineMacro("\\varsupsetneq", "\\html@mathml{\\@varsupsetneq}{⊋}"); defineMacro("\\varsupsetneqq", "\\html@mathml{\\@varsupsetneqq}{⫌}"); defineMacro("\\imath", "\\html@mathml{\\@imath}{ı}"); defineMacro("\\jmath", "\\html@mathml{\\@jmath}{ȷ}"); defineMacro("\\llbracket", "\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`⟦}}"); defineMacro("\\rrbracket", "\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`⟧}}"); defineMacro("⟦", "\\llbracket"); defineMacro("⟧", "\\rrbracket"); defineMacro("\\lBrace", "\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`⦃}}"); defineMacro("\\rBrace", "\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`⦄}}"); defineMacro("↤", "\\mapsfrom"); defineMacro("\\mapsfrom", "\\html@mathml{\\mathrel{\\mathreflectbox{\\mapsto}}}{\\mathrel{\\char`↤}}"); defineMacro("⦃", "\\lBrace"); defineMacro("⦄", "\\rBrace"); defineMacro("\\minuso", "\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`⦵}}"); defineMacro("⦵", "\\minuso"); defineMacro("\\darr", "\\downarrow"); defineMacro("\\dArr", "\\Downarrow"); defineMacro("\\Darr", "\\Downarrow"); defineMacro("\\lang", "\\langle"); defineMacro("\\rang", "\\rangle"); defineMacro("\\uarr", "\\uparrow"); defineMacro("\\uArr", "\\Uparrow"); defineMacro("\\Uarr", "\\Uparrow"); defineMacro("\\N", "\\mathbb{N}"); defineMacro("\\R", "\\mathbb{R}"); defineMacro("\\Z", "\\mathbb{Z}"); defineMacro("\\alef", "\\aleph"); defineMacro("\\alefsym", "\\aleph"); defineMacro("\\Alpha", "\\mathrm{A}"); defineMacro("\\Beta", "\\mathrm{B}"); defineMacro("\\bull", "\\bullet"); defineMacro("\\Chi", "\\mathrm{X}"); defineMacro("\\clubs", "\\clubsuit"); defineMacro("\\cnums", "\\mathbb{C}"); defineMacro("\\Complex", "\\mathbb{C}"); defineMacro("\\Dagger", "\\ddagger"); defineMacro("\\diamonds", "\\diamondsuit"); defineMacro("\\empty", "\\emptyset"); defineMacro("\\Epsilon", "\\mathrm{E}"); defineMacro("\\Eta", "\\mathrm{H}"); defineMacro("\\exist", "\\exists"); defineMacro("\\harr", "\\leftrightarrow"); defineMacro("\\hArr", "\\Leftrightarrow"); defineMacro("\\Harr", "\\Leftrightarrow"); defineMacro("\\hearts", "\\heartsuit"); defineMacro("\\image", "\\Im"); defineMacro("\\infin", "\\infty"); defineMacro("\\Iota", "\\mathrm{I}"); defineMacro("\\isin", "\\in"); defineMacro("\\Kappa", "\\mathrm{K}"); defineMacro("\\larr", "\\leftarrow"); defineMacro("\\lArr", "\\Leftarrow"); defineMacro("\\Larr", "\\Leftarrow"); defineMacro("\\lrarr", "\\leftrightarrow"); defineMacro("\\lrArr", "\\Leftrightarrow"); defineMacro("\\Lrarr", "\\Leftrightarrow"); defineMacro("\\Mu", "\\mathrm{M}"); defineMacro("\\natnums", "\\mathbb{N}"); defineMacro("\\Nu", "\\mathrm{N}"); defineMacro("\\Omicron", "\\mathrm{O}"); defineMacro("\\plusmn", "\\pm"); defineMacro("\\rarr", "\\rightarrow"); defineMacro("\\rArr", "\\Rightarrow"); defineMacro("\\Rarr", "\\Rightarrow"); defineMacro("\\real", "\\Re"); defineMacro("\\reals", "\\mathbb{R}"); defineMacro("\\Reals", "\\mathbb{R}"); defineMacro("\\Rho", "\\mathrm{P}"); defineMacro("\\sdot", "\\cdot"); defineMacro("\\sect", "\\S"); defineMacro("\\spades", "\\spadesuit"); defineMacro("\\sub", "\\subset"); defineMacro("\\sube", "\\subseteq"); defineMacro("\\supe", "\\supseteq"); defineMacro("\\Tau", "\\mathrm{T}"); defineMacro("\\thetasym", "\\vartheta"); defineMacro("\\weierp", "\\wp"); defineMacro("\\Zeta", "\\mathrm{Z}"); defineMacro("\\argmin", "\\DOTSB\\operatorname*{arg\\,min}"); defineMacro("\\argmax", "\\DOTSB\\operatorname*{arg\\,max}"); defineMacro("\\plim", "\\DOTSB\\mathop{\\operatorname{plim}}\\limits"); defineMacro("\\bra", "\\mathinner{\\langle{#1}|}"); defineMacro("\\ket", "\\mathinner{|{#1}\\rangle}"); defineMacro("\\braket", "\\mathinner{\\langle{#1}\\rangle}"); defineMacro("\\Bra", "\\left\\langle#1\\right|"); defineMacro("\\Ket", "\\left|#1\\right\\rangle"); var braketHelper = (one) => (context) => { var left = context.consumeArg().tokens; var middle = context.consumeArg().tokens; var middleDouble = context.consumeArg().tokens; var right = context.consumeArg().tokens; var oldMiddle = context.macros.get("|"); var oldMiddleDouble = context.macros.get("\\|"); context.macros.beginGroup(); var midMacro = (double) => (context) => { if (one) { context.macros.set("|", oldMiddle); if (middleDouble.length) context.macros.set("\\|", oldMiddleDouble); } var doubled = double; if (!double && middleDouble.length) { if (context.future().text === "|") { context.popToken(); doubled = true; } } return { tokens: doubled ? middleDouble : middle, numArgs: 0 }; }; context.macros.set("|", midMacro(false)); if (middleDouble.length) context.macros.set("\\|", midMacro(true)); var arg = context.consumeArg().tokens; var expanded = context.expandTokens([ ...right, ...arg, ...left ]); context.macros.endGroup(); return { tokens: expanded.reverse(), numArgs: 0 }; }; defineMacro("\\bra@ket", braketHelper(false)); defineMacro("\\bra@set", braketHelper(true)); defineMacro("\\Braket", "\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}"); defineMacro("\\Set", "\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}"); defineMacro("\\set", "\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}"); defineMacro("\\angln", "{\\angl n}"); defineMacro("\\blue", "\\textcolor{##6495ed}{#1}"); defineMacro("\\orange", "\\textcolor{##ffa500}{#1}"); defineMacro("\\pink", "\\textcolor{##ff00af}{#1}"); defineMacro("\\red", "\\textcolor{##df0030}{#1}"); defineMacro("\\green", "\\textcolor{##28ae7b}{#1}"); defineMacro("\\gray", "\\textcolor{gray}{#1}"); defineMacro("\\purple", "\\textcolor{##9d38bd}{#1}"); defineMacro("\\blueA", "\\textcolor{##ccfaff}{#1}"); defineMacro("\\blueB", "\\textcolor{##80f6ff}{#1}"); defineMacro("\\blueC", "\\textcolor{##63d9ea}{#1}"); defineMacro("\\blueD", "\\textcolor{##11accd}{#1}"); defineMacro("\\blueE", "\\textcolor{##0c7f99}{#1}"); defineMacro("\\tealA", "\\textcolor{##94fff5}{#1}"); defineMacro("\\tealB", "\\textcolor{##26edd5}{#1}"); defineMacro("\\tealC", "\\textcolor{##01d1c1}{#1}"); defineMacro("\\tealD", "\\textcolor{##01a995}{#1}"); defineMacro("\\tealE", "\\textcolor{##208170}{#1}"); defineMacro("\\greenA", "\\textcolor{##b6ffb0}{#1}"); defineMacro("\\greenB", "\\textcolor{##8af281}{#1}"); defineMacro("\\greenC", "\\textcolor{##74cf70}{#1}"); defineMacro("\\greenD", "\\textcolor{##1fab54}{#1}"); defineMacro("\\greenE", "\\textcolor{##0d923f}{#1}"); defineMacro("\\goldA", "\\textcolor{##ffd0a9}{#1}"); defineMacro("\\goldB", "\\textcolor{##ffbb71}{#1}"); defineMacro("\\goldC", "\\textcolor{##ff9c39}{#1}"); defineMacro("\\goldD", "\\textcolor{##e07d10}{#1}"); defineMacro("\\goldE", "\\textcolor{##a75a05}{#1}"); defineMacro("\\redA", "\\textcolor{##fca9a9}{#1}"); defineMacro("\\redB", "\\textcolor{##ff8482}{#1}"); defineMacro("\\redC", "\\textcolor{##f9685d}{#1}"); defineMacro("\\redD", "\\textcolor{##e84d39}{#1}"); defineMacro("\\redE", "\\textcolor{##bc2612}{#1}"); defineMacro("\\maroonA", "\\textcolor{##ffbde0}{#1}"); defineMacro("\\maroonB", "\\textcolor{##ff92c6}{#1}"); defineMacro("\\maroonC", "\\textcolor{##ed5fa6}{#1}"); defineMacro("\\maroonD", "\\textcolor{##ca337c}{#1}"); defineMacro("\\maroonE", "\\textcolor{##9e034e}{#1}"); defineMacro("\\purpleA", "\\textcolor{##ddd7ff}{#1}"); defineMacro("\\purpleB", "\\textcolor{##c6b9fc}{#1}"); defineMacro("\\purpleC", "\\textcolor{##aa87ff}{#1}"); defineMacro("\\purpleD", "\\textcolor{##7854ab}{#1}"); defineMacro("\\purpleE", "\\textcolor{##543b78}{#1}"); defineMacro("\\mintA", "\\textcolor{##f5f9e8}{#1}"); defineMacro("\\mintB", "\\textcolor{##edf2df}{#1}"); defineMacro("\\mintC", "\\textcolor{##e0e5cc}{#1}"); defineMacro("\\grayA", "\\textcolor{##f6f7f7}{#1}"); defineMacro("\\grayB", "\\textcolor{##f0f1f2}{#1}"); defineMacro("\\grayC", "\\textcolor{##e3e5e6}{#1}"); defineMacro("\\grayD", "\\textcolor{##d6d8da}{#1}"); defineMacro("\\grayE", "\\textcolor{##babec2}{#1}"); defineMacro("\\grayF", "\\textcolor{##888d93}{#1}"); defineMacro("\\grayG", "\\textcolor{##626569}{#1}"); defineMacro("\\grayH", "\\textcolor{##3b3e40}{#1}"); defineMacro("\\grayI", "\\textcolor{##21242c}{#1}"); defineMacro("\\kaBlue", "\\textcolor{##314453}{#1}"); defineMacro("\\kaGreen", "\\textcolor{##71B307}{#1}"); /** * This file contains the “gullet” where macros are expanded * until only non-macro tokens remain. */ var implicitCommands = { "^": true, "_": true, "\\limits": true, "\\nolimits": true }; var MacroExpander = class { constructor(input, settings, mode) { this.settings = void 0; this.expansionCount = void 0; this.lexer = void 0; this.macros = void 0; this.stack = void 0; this.mode = void 0; this.settings = settings; this.expansionCount = 0; this.feed(input); this.macros = new Namespace(macros, settings.macros); this.mode = mode; this.stack = []; } /** * Feed a new input string to the same MacroExpander * (with existing macros etc.). */ feed(input) { this.lexer = new Lexer(input, this.settings); } /** * Switches between "text" and "math" modes. */ switchMode(newMode) { this.mode = newMode; } /** * Start a new group nesting within all namespaces. */ beginGroup() { this.macros.beginGroup(); } /** * End current group nesting within all namespaces. */ endGroup() { this.macros.endGroup(); } /** * Ends all currently nested groups (if any), restoring values before the * groups began. Useful in case of an error in the middle of parsing. */ endGroups() { this.macros.endGroups(); } /** * Returns the topmost token on the stack, without expanding it. * Similar in behavior to TeX's `\futurelet`. */ future() { if (this.stack.length === 0) this.pushToken(this.lexer.lex()); return this.stack[this.stack.length - 1]; } /** * Remove and return the next unexpanded token. */ popToken() { this.future(); return this.stack.pop(); } /** * Add a given token to the token stack. In particular, this get be used * to put back a token returned from one of the other methods. */ pushToken(token) { this.stack.push(token); } /** * Append an array of tokens to the token stack. */ pushTokens(tokens) { this.stack.push(...tokens); } /** * Find an macro argument without expanding tokens and append the array of * tokens to the token stack. Uses Token as a container for the result. */ scanArgument(isOptional) { var start; var end; var tokens; if (isOptional) { this.consumeSpaces(); if (this.future().text !== "[") return null; start = this.popToken(); var _this$consumeArg = this.consumeArg(["]"]); tokens = _this$consumeArg.tokens; end = _this$consumeArg.end; } else { var _this$consumeArg2 = this.consumeArg(); tokens = _this$consumeArg2.tokens; start = _this$consumeArg2.start; end = _this$consumeArg2.end; } this.pushToken(new Token("EOF", end.loc)); this.pushTokens(tokens); return new Token("", SourceLocation.range(start, end)); } /** * Consume all following space tokens, without expansion. */ consumeSpaces() { for (;;) if (this.future().text === " ") this.stack.pop(); else break; } /** * Consume an argument from the token stream, and return the resulting array * of tokens and start/end token. */ consumeArg(delims) { var tokens = []; var isDelimited = delims && delims.length > 0; if (!isDelimited) this.consumeSpaces(); var start = this.future(); var tok; var depth = 0; var match = 0; do { tok = this.popToken(); tokens.push(tok); if (tok.text === "{") ++depth; else if (tok.text === "}") { --depth; if (depth === -1) throw new ParseError("Extra }", tok); } else if (tok.text === "EOF") throw new ParseError("Unexpected end of input in a macro argument, expected '" + (delims && isDelimited ? delims[match] : "}") + "'", tok); if (delims && isDelimited) { if ((depth === 0 || depth === 1 && delims[match] === "{") && tok.text === delims[match]) { ++match; if (match === delims.length) { tokens.splice(-match, match); break; } } else match = 0; } } while (depth !== 0 || isDelimited); if (start.text === "{" && tokens[tokens.length - 1].text === "}") { tokens.pop(); tokens.shift(); } tokens.reverse(); return { tokens, start, end: tok }; } /** * Consume the specified number of (delimited) arguments from the token * stream and return the resulting array of arguments. */ consumeArgs(numArgs, delimiters) { if (delimiters) { if (delimiters.length !== numArgs + 1) throw new ParseError("The length of delimiters doesn't match the number of args!"); var delims = delimiters[0]; for (var i = 0; i < delims.length; i++) { var tok = this.popToken(); if (delims[i] !== tok.text) throw new ParseError("Use of the macro doesn't match its definition", tok); } } var args = []; for (var _i = 0; _i < numArgs; _i++) args.push(this.consumeArg(delimiters && delimiters[_i + 1]).tokens); return args; } /** * Increment `expansionCount` by the specified amount. * Throw an error if it exceeds `maxExpand`. */ countExpansion(amount) { this.expansionCount += amount; if (this.expansionCount > this.settings.maxExpand) throw new ParseError("Too many expansions: infinite loop or need to increase maxExpand setting"); } /** * Expand the next token only once if possible. * * If the token is expanded, the resulting tokens will be pushed onto * the stack in reverse order, and the number of such tokens will be * returned. This number might be zero or positive. * * If not, the return value is `false`, and the next token remains at the * top of the stack. * * In either case, the next token will be on the top of the stack, * or the stack will be empty (in case of empty expansion * and no other tokens). * * Used to implement `expandAfterFuture` and `expandNextToken`. * * If expandableOnly, only expandable tokens are expanded and * an undefined control sequence results in an error. */ expandOnce(expandableOnly) { var topToken = this.popToken(); var name = topToken.text; var expansion = !topToken.noexpand ? this._getExpansion(name) : null; if (expansion == null || expandableOnly && expansion.unexpandable) { if (expandableOnly && expansion == null && name[0] === "\\" && !this.isDefined(name)) throw new ParseError("Undefined control sequence: " + name); this.pushToken(topToken); return false; } this.countExpansion(1); var tokens = expansion.tokens; var args = this.consumeArgs(expansion.numArgs, expansion.delimiters); if (expansion.numArgs) { tokens = tokens.slice(); for (var i = tokens.length - 1; i >= 0; --i) { var tok = tokens[i]; if (tok.text === "#") { if (i === 0) throw new ParseError("Incomplete placeholder at end of macro body", tok); tok = tokens[--i]; if (tok.text === "#") tokens.splice(i + 1, 1); else if (/^[1-9]$/.test(tok.text)) tokens.splice(i, 2, ...args[+tok.text - 1]); else throw new ParseError("Not a valid argument number", tok); } } } this.pushTokens(tokens); return tokens.length; } /** * Expand the next token only once (if possible), and return the resulting * top token on the stack (without removing anything from the stack). * Similar in behavior to TeX's `\expandafter\futurelet`. * Equivalent to expandOnce() followed by future(). */ expandAfterFuture() { this.expandOnce(); return this.future(); } /** * Recursively expand first token, then return first non-expandable token. */ expandNextToken() { for (;;) if (this.expandOnce() === false) { var token = this.stack.pop(); if (token.treatAsRelax) token.text = "\\relax"; return token; } } /** * Fully expand the given macro name and return the resulting list of * tokens, or return `undefined` if no such macro is defined. */ expandMacro(name) { return this.macros.has(name) ? this.expandTokens([new Token(name)]) : void 0; } /** * Fully expand the given token stream and return the resulting list of * tokens. Note that the input tokens are in reverse order, but the * output tokens are in forward order. */ expandTokens(tokens) { var output = []; var oldStackLength = this.stack.length; this.pushTokens(tokens); while (this.stack.length > oldStackLength) if (this.expandOnce(true) === false) { var token = this.stack.pop(); if (token.treatAsRelax) { token.noexpand = false; token.treatAsRelax = false; } output.push(token); } this.countExpansion(output.length); return output; } /** * Fully expand the given macro name and return the result as a string, * or return `undefined` if no such macro is defined. */ expandMacroAsText(name) { var tokens = this.expandMacro(name); if (tokens) return tokens.map((token) => token.text).join(""); else return tokens; } /** * Returns the expanded macro as a reversed array of tokens and a macro * argument count. Or returns `null` if no such macro. */ _getExpansion(name) { var definition = this.macros.get(name); if (definition == null) return definition; if (name.length === 1) { var catcode = this.lexer.catcodes[name]; if (catcode != null && catcode !== 13) return; } var expansion = typeof definition === "function" ? definition(this) : definition; if (typeof expansion === "string") { var numArgs = 0; if (expansion.includes("#")) { var stripped = expansion.replace(/##/g, ""); while (stripped.includes("#" + (numArgs + 1))) ++numArgs; } var bodyLexer = new Lexer(expansion, this.settings); var tokens = []; var tok = bodyLexer.lex(); while (tok.text !== "EOF") { tokens.push(tok); tok = bodyLexer.lex(); } tokens.reverse(); return { tokens, numArgs }; } return expansion; } /** * Determine whether a command is currently "defined" (has some * functionality), meaning that it's a macro (in the current group), * a function, a symbol, or one of the special commands listed in * `implicitCommands`. */ isDefined(name) { return this.macros.has(name) || Object.prototype.hasOwnProperty.call(functions, name) || Object.prototype.hasOwnProperty.call(symbols.math, name) || Object.prototype.hasOwnProperty.call(symbols.text, name) || Object.prototype.hasOwnProperty.call(implicitCommands, name); } /** * Determine whether a command is expandable. */ isExpandable(name) { var macro = this.macros.get(name); if (macro != null) return typeof macro === "string" || typeof macro === "function" || !macro.unexpandable; return Object.prototype.hasOwnProperty.call(functions, name) && !functions[name].primitive; } }; var unicodeSubRegEx = /^[₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ]/; var uSubsAndSups = Object.freeze({ "₊": "+", "₋": "-", "₌": "=", "₍": "(", "₎": ")", "₀": "0", "₁": "1", "₂": "2", "₃": "3", "₄": "4", "₅": "5", "₆": "6", "₇": "7", "₈": "8", "₉": "9", "ₐ": "a", "ₑ": "e", "ₕ": "h", "ᵢ": "i", "ⱼ": "j", "ₖ": "k", "ₗ": "l", "ₘ": "m", "ₙ": "n", "ₒ": "o", "ₚ": "p", "ᵣ": "r", "ₛ": "s", "ₜ": "t", "ᵤ": "u", "ᵥ": "v", "ₓ": "x", "ᵦ": "β", "ᵧ": "γ", "ᵨ": "ρ", "ᵩ": "ϕ", "ᵪ": "χ", "⁺": "+", "⁻": "-", "⁼": "=", "⁽": "(", "⁾": ")", "⁰": "0", "¹": "1", "²": "2", "³": "3", "⁴": "4", "⁵": "5", "⁶": "6", "⁷": "7", "⁸": "8", "⁹": "9", "ᴬ": "A", "ᴮ": "B", "ᴰ": "D", "ᴱ": "E", "ᴳ": "G", "ᴴ": "H", "ᴵ": "I", "ᴶ": "J", "ᴷ": "K", "ᴸ": "L", "ᴹ": "M", "ᴺ": "N", "ᴼ": "O", "ᴾ": "P", "ᴿ": "R", "ᵀ": "T", "ᵁ": "U", "ⱽ": "V", "ᵂ": "W", "ᵃ": "a", "ᵇ": "b", "ᶜ": "c", "ᵈ": "d", "ᵉ": "e", "ᶠ": "f", "ᵍ": "g", "ʰ": "h", "ⁱ": "i", "ʲ": "j", "ᵏ": "k", "ˡ": "l", "ᵐ": "m", "ⁿ": "n", "ᵒ": "o", "ᵖ": "p", "ʳ": "r", "ˢ": "s", "ᵗ": "t", "ᵘ": "u", "ᵛ": "v", "ʷ": "w", "ˣ": "x", "ʸ": "y", "ᶻ": "z", "ᵝ": "β", "ᵞ": "γ", "ᵟ": "δ", "ᵠ": "ϕ", "ᵡ": "χ", "ᶿ": "θ" }); var unicodeAccents = { "́": { "text": "\\'", "math": "\\acute" }, "̀": { "text": "\\`", "math": "\\grave" }, "̈": { "text": "\\\"", "math": "\\ddot" }, "̃": { "text": "\\~", "math": "\\tilde" }, "̄": { "text": "\\=", "math": "\\bar" }, "̆": { "text": "\\u", "math": "\\breve" }, "̌": { "text": "\\v", "math": "\\check" }, "̂": { "text": "\\^", "math": "\\hat" }, "̇": { "text": "\\.", "math": "\\dot" }, "̊": { "text": "\\r", "math": "\\mathring" }, "̋": { "text": "\\H" }, "̧": { "text": "\\c" } }; var unicodeSymbols = { "á": "á", "à": "à", "ä": "ä", "ǟ": "ǟ", "ã": "ã", "ā": "ā", "ă": "ă", "ắ": "ắ", "ằ": "ằ", "ẵ": "ẵ", "ǎ": "ǎ", "â": "â", "ấ": "ấ", "ầ": "ầ", "ẫ": "ẫ", "ȧ": "ȧ", "ǡ": "ǡ", "å": "å", "ǻ": "ǻ", "ḃ": "ḃ", "ć": "ć", "ḉ": "ḉ", "č": "č", "ĉ": "ĉ", "ċ": "ċ", "ç": "ç", "ď": "ď", "ḋ": "ḋ", "ḑ": "ḑ", "é": "é", "è": "è", "ë": "ë", "ẽ": "ẽ", "ē": "ē", "ḗ": "ḗ", "ḕ": "ḕ", "ĕ": "ĕ", "ḝ": "ḝ", "ě": "ě", "ê": "ê", "ế": "ế", "ề": "ề", "ễ": "ễ", "ė": "ė", "ȩ": "ȩ", "ḟ": "ḟ", "ǵ": "ǵ", "ḡ": "ḡ", "ğ": "ğ", "ǧ": "ǧ", "ĝ": "ĝ", "ġ": "ġ", "ģ": "ģ", "ḧ": "ḧ", "ȟ": "ȟ", "ĥ": "ĥ", "ḣ": "ḣ", "ḩ": "ḩ", "í": "í", "ì": "ì", "ï": "ï", "ḯ": "ḯ", "ĩ": "ĩ", "ī": "ī", "ĭ": "ĭ", "ǐ": "ǐ", "î": "î", "ǰ": "ǰ", "ĵ": "ĵ", "ḱ": "ḱ", "ǩ": "ǩ", "ķ": "ķ", "ĺ": "ĺ", "ľ": "ľ", "ļ": "ļ", "ḿ": "ḿ", "ṁ": "ṁ", "ń": "ń", "ǹ": "ǹ", "ñ": "ñ", "ň": "ň", "ṅ": "ṅ", "ņ": "ņ", "ó": "ó", "ò": "ò", "ö": "ö", "ȫ": "ȫ", "õ": "õ", "ṍ": "ṍ", "ṏ": "ṏ", "ȭ": "ȭ", "ō": "ō", "ṓ": "ṓ", "ṑ": "ṑ", "ŏ": "ŏ", "ǒ": "ǒ", "ô": "ô", "ố": "ố", "ồ": "ồ", "ỗ": "ỗ", "ȯ": "ȯ", "ȱ": "ȱ", "ő": "ő", "ṕ": "ṕ", "ṗ": "ṗ", "ŕ": "ŕ", "ř": "ř", "ṙ": "ṙ", "ŗ": "ŗ", "ś": "ś", "ṥ": "ṥ", "š": "š", "ṧ": "ṧ", "ŝ": "ŝ", "ṡ": "ṡ", "ş": "ş", "ẗ": "ẗ", "ť": "ť", "ṫ": "ṫ", "ţ": "ţ", "ú": "ú", "ù": "ù", "ü": "ü", "ǘ": "ǘ", "ǜ": "ǜ", "ǖ": "ǖ", "ǚ": "ǚ", "ũ": "ũ", "ṹ": "ṹ", "ū": "ū", "ṻ": "ṻ", "ŭ": "ŭ", "ǔ": "ǔ", "û": "û", "ů": "ů", "ű": "ű", "ṽ": "ṽ", "ẃ": "ẃ", "ẁ": "ẁ", "ẅ": "ẅ", "ŵ": "ŵ", "ẇ": "ẇ", "ẘ": "ẘ", "ẍ": "ẍ", "ẋ": "ẋ", "ý": "ý", "ỳ": "ỳ", "ÿ": "ÿ", "ỹ": "ỹ", "ȳ": "ȳ", "ŷ": "ŷ", "ẏ": "ẏ", "ẙ": "ẙ", "ź": "ź", "ž": "ž", "ẑ": "ẑ", "ż": "ż", "Á": "Á", "À": "À", "Ä": "Ä", "Ǟ": "Ǟ", "Ã": "Ã", "Ā": "Ā", "Ă": "Ă", "Ắ": "Ắ", "Ằ": "Ằ", "Ẵ": "Ẵ", "Ǎ": "Ǎ", "Â": "Â", "Ấ": "Ấ", "Ầ": "Ầ", "Ẫ": "Ẫ", "Ȧ": "Ȧ", "Ǡ": "Ǡ", "Å": "Å", "Ǻ": "Ǻ", "Ḃ": "Ḃ", "Ć": "Ć", "Ḉ": "Ḉ", "Č": "Č", "Ĉ": "Ĉ", "Ċ": "Ċ", "Ç": "Ç", "Ď": "Ď", "Ḋ": "Ḋ", "Ḑ": "Ḑ", "É": "É", "È": "È", "Ë": "Ë", "Ẽ": "Ẽ", "Ē": "Ē", "Ḗ": "Ḗ", "Ḕ": "Ḕ", "Ĕ": "Ĕ", "Ḝ": "Ḝ", "Ě": "Ě", "Ê": "Ê", "Ế": "Ế", "Ề": "Ề", "Ễ": "Ễ", "Ė": "Ė", "Ȩ": "Ȩ", "Ḟ": "Ḟ", "Ǵ": "Ǵ", "Ḡ": "Ḡ", "Ğ": "Ğ", "Ǧ": "Ǧ", "Ĝ": "Ĝ", "Ġ": "Ġ", "Ģ": "Ģ", "Ḧ": "Ḧ", "Ȟ": "Ȟ", "Ĥ": "Ĥ", "Ḣ": "Ḣ", "Ḩ": "Ḩ", "Í": "Í", "Ì": "Ì", "Ï": "Ï", "Ḯ": "Ḯ", "Ĩ": "Ĩ", "Ī": "Ī", "Ĭ": "Ĭ", "Ǐ": "Ǐ", "Î": "Î", "İ": "İ", "Ĵ": "Ĵ", "Ḱ": "Ḱ", "Ǩ": "Ǩ", "Ķ": "Ķ", "Ĺ": "Ĺ", "Ľ": "Ľ", "Ļ": "Ļ", "Ḿ": "Ḿ", "Ṁ": "Ṁ", "Ń": "Ń", "Ǹ": "Ǹ", "Ñ": "Ñ", "Ň": "Ň", "Ṅ": "Ṅ", "Ņ": "Ņ", "Ó": "Ó", "Ò": "Ò", "Ö": "Ö", "Ȫ": "Ȫ", "Õ": "Õ", "Ṍ": "Ṍ", "Ṏ": "Ṏ", "Ȭ": "Ȭ", "Ō": "Ō", "Ṓ": "Ṓ", "Ṑ": "Ṑ", "Ŏ": "Ŏ", "Ǒ": "Ǒ", "Ô": "Ô", "Ố": "Ố", "Ồ": "Ồ", "Ỗ": "Ỗ", "Ȯ": "Ȯ", "Ȱ": "Ȱ", "Ő": "Ő", "Ṕ": "Ṕ", "Ṗ": "Ṗ", "Ŕ": "Ŕ", "Ř": "Ř", "Ṙ": "Ṙ", "Ŗ": "Ŗ", "Ś": "Ś", "Ṥ": "Ṥ", "Š": "Š", "Ṧ": "Ṧ", "Ŝ": "Ŝ", "Ṡ": "Ṡ", "Ş": "Ş", "Ť": "Ť", "Ṫ": "Ṫ", "Ţ": "Ţ", "Ú": "Ú", "Ù": "Ù", "Ü": "Ü", "Ǘ": "Ǘ", "Ǜ": "Ǜ", "Ǖ": "Ǖ", "Ǚ": "Ǚ", "Ũ": "Ũ", "Ṹ": "Ṹ", "Ū": "Ū", "Ṻ": "Ṻ", "Ŭ": "Ŭ", "Ǔ": "Ǔ", "Û": "Û", "Ů": "Ů", "Ű": "Ű", "Ṽ": "Ṽ", "Ẃ": "Ẃ", "Ẁ": "Ẁ", "Ẅ": "Ẅ", "Ŵ": "Ŵ", "Ẇ": "Ẇ", "Ẍ": "Ẍ", "Ẋ": "Ẋ", "Ý": "Ý", "Ỳ": "Ỳ", "Ÿ": "Ÿ", "Ỹ": "Ỹ", "Ȳ": "Ȳ", "Ŷ": "Ŷ", "Ẏ": "Ẏ", "Ź": "Ź", "Ž": "Ž", "Ẑ": "Ẑ", "Ż": "Ż", "ά": "ά", "ὰ": "ὰ", "ᾱ": "ᾱ", "ᾰ": "ᾰ", "έ": "έ", "ὲ": "ὲ", "ή": "ή", "ὴ": "ὴ", "ί": "ί", "ὶ": "ὶ", "ϊ": "ϊ", "ΐ": "ΐ", "ῒ": "ῒ", "ῑ": "ῑ", "ῐ": "ῐ", "ό": "ό", "ὸ": "ὸ", "ύ": "ύ", "ὺ": "ὺ", "ϋ": "ϋ", "ΰ": "ΰ", "ῢ": "ῢ", "ῡ": "ῡ", "ῠ": "ῠ", "ώ": "ώ", "ὼ": "ὼ", "Ύ": "Ύ", "Ὺ": "Ὺ", "Ϋ": "Ϋ", "Ῡ": "Ῡ", "Ῠ": "Ῠ", "Ώ": "Ώ", "Ὼ": "Ὼ" }; /** * This file contains the parser used to parse out a TeX expression from the * input. Since TeX isn't context-free, standard parsers don't work particularly * well. * * The strategy of this parser is as such: * * The main functions (the `.parse...` ones) take a position in the current * parse string to parse tokens from. The lexer (found in Lexer.js, stored at * this.gullet.lexer) also supports pulling out tokens at arbitrary places. When * individual tokens are needed at a position, the lexer is called to pull out a * token, which is then used. * * The parser has a property called "mode" indicating the mode that * the parser is currently in. Currently it has to be one of "math" or * "text", which denotes whether the current environment is a math-y * one or a text-y one (e.g. inside \text). Currently, this serves to * limit the functions which can be used in text mode. * * The main functions then return an object which contains the useful data that * was parsed at its given point, and a new position at the end of the parsed * data. The main functions can call each other and continue the parsing by * using the returned position as a new starting point. * * There are also extra `.handle...` functions, which pull out some reused * functionality into self-contained functions. * * The functions return ParseNodes. */ var Parser = class Parser { constructor(input, settings) { this.mode = void 0; this.gullet = void 0; this.settings = void 0; this.leftrightDepth = void 0; this.nextToken = void 0; this.mode = "math"; this.gullet = new MacroExpander(input, settings, this.mode); this.settings = settings; this.leftrightDepth = 0; this.nextToken = null; } /** * Checks a result to make sure it has the right type, and throws an * appropriate error otherwise. */ expect(text, consume) { if (consume === void 0) consume = true; if (this.fetch().text !== text) throw new ParseError("Expected '" + text + "', got '" + this.fetch().text + "'", this.fetch()); if (consume) this.consume(); } /** * Discards the current lookahead token, considering it consumed. */ consume() { this.nextToken = null; } /** * Return the current lookahead token, or if there isn't one (at the * beginning, or if the previous lookahead token was consume()d), * fetch the next token as the new lookahead token and return it. */ fetch() { if (this.nextToken == null) this.nextToken = this.gullet.expandNextToken(); return this.nextToken; } /** * Switches between "text" and "math" modes. */ switchMode(newMode) { this.mode = newMode; this.gullet.switchMode(newMode); } /** * Main parsing function, which parses an entire input. */ parse() { if (!this.settings.globalGroup) this.gullet.beginGroup(); if (this.settings.colorIsTextColor) this.gullet.macros.set("\\color", "\\textcolor"); try { var parse = this.parseExpression(false); this.expect("EOF"); if (!this.settings.globalGroup) this.gullet.endGroup(); return parse; } finally { this.gullet.endGroups(); } } /** * Fully parse a separate sequence of tokens as a separate job. * Tokens should be specified in reverse order, as in a MacroDefinition. */ subparse(tokens) { var oldToken = this.nextToken; this.consume(); this.gullet.pushToken(new Token("}")); this.gullet.pushTokens(tokens); var parse = this.parseExpression(false); this.expect("}"); this.nextToken = oldToken; return parse; } /** * Parses an "expression", which is a list of atoms. * * `breakOnInfix`: Should the parsing stop when we hit infix nodes? This * happens when functions have higher precedence than infix * nodes in implicit parses. * * `breakOnTokenText`: The text of the token that the expression should end * with, or `null` if something else should end the * expression. */ parseExpression(breakOnInfix, breakOnTokenText) { var body = []; while (true) { if (this.mode === "math") this.consumeSpaces(); var lex = this.fetch(); if (Parser.endOfExpression.has(lex.text)) break; if (breakOnTokenText && lex.text === breakOnTokenText) break; if (breakOnInfix && functions[lex.text] && functions[lex.text].infix) break; var atom = this.parseAtom(breakOnTokenText); if (!atom) break; else if (atom.type === "internal") continue; body.push(atom); } if (this.mode === "text") this.formLigatures(body); return this.handleInfixNodes(body); } /** * Rewrites infix operators such as \over with corresponding commands such * as \frac. * * There can only be one infix operator per group. If there's more than one * then the expression is ambiguous. This can be resolved by adding {}. */ handleInfixNodes(body) { var overIndex = -1; var funcName; for (var i = 0; i < body.length; i++) { var node = body[i]; if (node.type === "infix") { if (overIndex !== -1) throw new ParseError("only one infix operator per group", node.token); overIndex = i; funcName = node.replaceWith; } } if (overIndex !== -1 && funcName) { var numerNode; var denomNode; var numerBody = body.slice(0, overIndex); var denomBody = body.slice(overIndex + 1); if (numerBody.length === 1 && numerBody[0].type === "ordgroup") numerNode = numerBody[0]; else numerNode = { type: "ordgroup", mode: this.mode, body: numerBody }; if (denomBody.length === 1 && denomBody[0].type === "ordgroup") denomNode = denomBody[0]; else denomNode = { type: "ordgroup", mode: this.mode, body: denomBody }; var _node; if (funcName === "\\\\abovefrac") _node = this.callFunction(funcName, [ numerNode, body[overIndex], denomNode ], []); else _node = this.callFunction(funcName, [numerNode, denomNode], []); return [_node]; } else return body; } /** * Handle a subscript or superscript with nice errors. */ handleSupSubscript(name) { var symbolToken = this.fetch(); var symbol = symbolToken.text; this.consume(); this.consumeSpaces(); var group; do { var _group; group = this.parseGroup(name); } while (((_group = group) == null ? void 0 : _group.type) === "internal"); if (!group) throw new ParseError("Expected group after '" + symbol + "'", symbolToken); return group; } /** * Converts the textual input of an unsupported command into a text node * contained within a color node whose color is determined by errorColor */ formatUnsupportedCmd(text) { var textordArray = []; for (var i = 0; i < text.length; i++) textordArray.push({ type: "textord", mode: "text", text: text[i] }); var textNode = { type: "text", mode: this.mode, body: textordArray }; return { type: "color", mode: this.mode, color: this.settings.errorColor, body: [textNode] }; } /** * Parses a group with optional super/subscripts. */ parseAtom(breakOnTokenText) { var base = this.parseGroup("atom", breakOnTokenText); if ((base == null ? void 0 : base.type) === "internal") return base; if (this.mode === "text") return base; var superscript; var subscript; while (true) { this.consumeSpaces(); var lex = this.fetch(); if (lex.text === "\\limits" || lex.text === "\\nolimits") { if (base && base.type === "op") { base.limits = lex.text === "\\limits"; base.alwaysHandleSupSub = true; } else if (base && base.type === "operatorname") { if (base.alwaysHandleSupSub) base.limits = lex.text === "\\limits"; } else throw new ParseError("Limit controls must follow a math operator", lex); this.consume(); } else if (lex.text === "^") { if (superscript) throw new ParseError("Double superscript", lex); superscript = this.handleSupSubscript("superscript"); } else if (lex.text === "_") { if (subscript) throw new ParseError("Double subscript", lex); subscript = this.handleSupSubscript("subscript"); } else if (lex.text === "'") { if (superscript) throw new ParseError("Double superscript", lex); var prime = { type: "textord", mode: this.mode, text: "\\prime" }; var primes = [prime]; this.consume(); while (this.fetch().text === "'") { primes.push(prime); this.consume(); } if (this.fetch().text === "^") primes.push(this.handleSupSubscript("superscript")); superscript = { type: "ordgroup", mode: this.mode, body: primes }; } else if (uSubsAndSups[lex.text]) { var isSub = unicodeSubRegEx.test(lex.text); var subsupTokens = []; subsupTokens.push(new Token(uSubsAndSups[lex.text])); this.consume(); while (true) { var token = this.fetch().text; if (!uSubsAndSups[token]) break; if (unicodeSubRegEx.test(token) !== isSub) break; subsupTokens.unshift(new Token(uSubsAndSups[token])); this.consume(); } var body = this.subparse(subsupTokens); if (isSub) subscript = { type: "ordgroup", mode: "math", body }; else superscript = { type: "ordgroup", mode: "math", body }; } else break; } if (superscript && subscript) return { type: "supsub", mode: this.mode, base, sup: superscript, sub: subscript }; else if (superscript) return { type: "supsub", mode: this.mode, base, sup: superscript }; else if (subscript) return { type: "supsub", mode: this.mode, base, sub: subscript }; else return base; } /** * Parses an entire function, including its base and all of its arguments. */ parseFunction(breakOnTokenText, name) { var token = this.fetch(); var func = token.text; var funcData = functions[func]; if (!funcData) return null; this.consume(); if (name && name !== "atom" && !funcData.allowedInArgument) throw new ParseError("Got function '" + func + "' with no arguments" + (name ? " as " + name : ""), token); else if (this.mode === "text" && !funcData.allowedInText) throw new ParseError("Can't use function '" + func + "' in text mode", token); else if (this.mode === "math" && funcData.allowedInMath === false) throw new ParseError("Can't use function '" + func + "' in math mode", token); var _this$parseArguments = this.parseArguments(func, funcData), args = _this$parseArguments.args, optArgs = _this$parseArguments.optArgs; return this.callFunction(func, args, optArgs, token, breakOnTokenText); } /** * Call a function handler with a suitable context and arguments. */ callFunction(name, args, optArgs, token, breakOnTokenText) { var context = { funcName: name, parser: this, token, breakOnTokenText }; var func = functions[name]; if (func && func.handler) return func.handler(context, args, optArgs); else throw new ParseError("No function handler for " + name); } /** * Parses the arguments of a function or environment */ parseArguments(func, funcData) { var _funcData$numOptional; var numOptionalArgs = (_funcData$numOptional = funcData.numOptionalArgs) != null ? _funcData$numOptional : 0; var totalArgs = funcData.numArgs + numOptionalArgs; if (totalArgs === 0) return { args: [], optArgs: [] }; var args = []; var optArgs = []; for (var i = 0; i < totalArgs; i++) { var _funcData$argTypes; var argType = (_funcData$argTypes = funcData.argTypes) == null ? void 0 : _funcData$argTypes[i]; var isOptional = i < numOptionalArgs; if ("primitive" in funcData && funcData.primitive && argType == null || funcData.type === "sqrt" && i === 1 && optArgs[0] == null) argType = "primitive"; var arg = this.parseGroupOfType("argument to '" + func + "'", argType, isOptional); if (isOptional) optArgs.push(arg); else if (arg != null) args.push(arg); else throw new ParseError("Null argument, please report this as a bug"); } return { args, optArgs }; } /** * Parses a group when the mode is changing. */ parseGroupOfType(name, type, optional) { switch (type) { case "color": return this.parseColorGroup(optional); case "size": return this.parseSizeGroup(optional); case "url": return this.parseUrlGroup(optional); case "math": case "text": return this.parseArgumentGroup(optional, type); case "hbox": var group = this.parseArgumentGroup(optional, "text"); return group != null ? { type: "styling", mode: group.mode, body: [group], style: "text", resetFont: true } : null; case "raw": this.gullet.consumeSpaces(); var percentCatcode = this.gullet.lexer.catcodes["%"]; this.gullet.lexer.setCatcode("%", 12); var token = this.parseStringGroup(optional); this.gullet.lexer.setCatcode("%", percentCatcode); return token != null ? { type: "raw", mode: "text", string: token.text } : null; case "primitive": if (optional) throw new ParseError("A primitive argument cannot be optional"); var _group2 = this.parseGroup(name); if (_group2 == null) throw new ParseError("Expected group as " + name, this.fetch()); return _group2; case "original": case void 0: return this.parseArgumentGroup(optional); default: throw new ParseError("Unknown group type as " + name, this.fetch()); } } /** * Discard any space tokens, fetching the next non-space token. */ consumeSpaces() { while (this.fetch().text === " ") this.consume(); } /** * Parses a group, essentially returning the string formed by the * brace-enclosed tokens plus some position information. */ parseStringGroup(optional) { var argToken = this.gullet.scanArgument(optional); if (argToken == null) return null; var str = ""; var nextToken; while ((nextToken = this.fetch()).text !== "EOF") { str += nextToken.text; this.consume(); } this.consume(); argToken.text = str; return argToken; } /** * Parses a regex-delimited group: the largest sequence of tokens * whose concatenated strings match `regex`. Returns the string * formed by the tokens plus some position information. */ parseRegexGroup(regex, modeName) { var firstToken = this.fetch(); var lastToken = firstToken; var str = ""; var nextToken; while ((nextToken = this.fetch()).text !== "EOF" && regex.test(str + nextToken.text)) { lastToken = nextToken; str += lastToken.text; this.consume(); } if (str === "") throw new ParseError("Invalid " + modeName + ": '" + firstToken.text + "'", firstToken); return firstToken.range(lastToken, str); } /** * Parses a color description. */ parseColorGroup(optional) { var res = this.parseStringGroup(optional); if (res == null) return null; var match = /^(#[a-f0-9]{3,4}|#[a-f0-9]{6}|#[a-f0-9]{8}|[a-f0-9]{6}|[a-z]+)$/i.exec(res.text); if (!match) throw new ParseError("Invalid color: '" + res.text + "'", res); var color = match[0]; if (/^[0-9a-f]{6}$/i.test(color)) color = "#" + color; return { type: "color-token", mode: this.mode, color }; } /** * Parses a size specification, consisting of magnitude and unit. */ parseSizeGroup(optional) { var res; var isBlank = false; this.gullet.consumeSpaces(); if (!optional && this.gullet.future().text !== "{") res = this.parseRegexGroup(/^[-+]? *(?:$|\d+|\d+\.\d*|\.\d*) *[a-z]{0,2} *$/, "size"); else res = this.parseStringGroup(optional); if (!res) return null; if (!optional && res.text.length === 0) { res.text = "0pt"; isBlank = true; } var match = /([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(res.text); if (!match) throw new ParseError("Invalid size: '" + res.text + "'", res); var data = { number: +(match[1] + match[2]), unit: match[3] }; if (!validUnit(data)) throw new ParseError("Invalid unit: '" + data.unit + "'", res); return { type: "size", mode: this.mode, value: data, isBlank }; } /** * Parses an URL, checking escaped letters and allowed protocols, * and setting the catcode of % as an active character (as in \hyperref). */ parseUrlGroup(optional) { var percentCatcode = this.gullet.lexer.catcodes["%"]; var tildeCatcode = this.gullet.lexer.catcodes["~"]; this.gullet.lexer.setCatcode("%", 13); this.gullet.lexer.setCatcode("~", 12); var res = this.parseStringGroup(optional); this.gullet.lexer.setCatcode("%", percentCatcode); this.gullet.lexer.setCatcode("~", tildeCatcode); if (res == null) return null; var url = res.text.replace(/\\([#$%&~_^{}])/g, "$1"); return { type: "url", mode: this.mode, url }; } /** * Parses an argument with the mode specified. */ parseArgumentGroup(optional, mode) { var argToken = this.gullet.scanArgument(optional); if (argToken == null) return null; var outerMode = this.mode; if (mode) this.switchMode(mode); this.gullet.beginGroup(); var expression = this.parseExpression(false, "EOF"); this.expect("EOF"); this.gullet.endGroup(); var result = { type: "ordgroup", mode: this.mode, loc: argToken.loc, body: expression }; if (mode) this.switchMode(outerMode); return result; } /** * Parses an ordinary group, which is either a single nucleus (like "x") * or an expression in braces (like "{x+y}") or an implicit group, a group * that starts at the current position, and ends right before a higher explicit * group ends, or at EOF. */ parseGroup(name, breakOnTokenText) { var firstToken = this.fetch(); var text = firstToken.text; var result; if (text === "{" || text === "\\begingroup") { this.consume(); var groupEnd = text === "{" ? "}" : "\\endgroup"; this.gullet.beginGroup(); var expression = this.parseExpression(false, groupEnd); var lastToken = this.fetch(); this.expect(groupEnd); this.gullet.endGroup(); result = { type: "ordgroup", mode: this.mode, loc: SourceLocation.range(firstToken, lastToken), body: expression, semisimple: text === "\\begingroup" || void 0 }; } else { result = this.parseFunction(breakOnTokenText, name) || this.parseSymbol(); if (result == null && text[0] === "\\" && !Object.prototype.hasOwnProperty.call(implicitCommands, text)) { if (this.settings.throwOnError) throw new ParseError("Undefined control sequence: " + text, firstToken); result = this.formatUnsupportedCmd(text); this.consume(); } } return result; } /** * Form ligature-like combinations of characters for text mode. * This includes inputs like "--", "---", "``" and "''". * The result will simply replace multiple textord nodes with a single * character in each value by a single textord node having multiple * characters in its value. The representation is still ASCII source. * The group will be modified in place. */ formLigatures(group) { var n = group.length - 1; for (var i = 0; i < n; ++i) { var a = group[i]; if (a.type !== "textord") continue; var v = a.text; var next = group[i + 1]; if (!next || next.type !== "textord") continue; if (v === "-" && next.text === "-") { var afterNext = group[i + 2]; if (i + 1 < n && afterNext && afterNext.type === "textord" && afterNext.text === "-") { group.splice(i, 3, { type: "textord", mode: "text", loc: SourceLocation.range(a, afterNext), text: "---" }); n -= 2; } else { group.splice(i, 2, { type: "textord", mode: "text", loc: SourceLocation.range(a, next), text: "--" }); n -= 1; } } if ((v === "'" || v === "`") && next.text === v) { group.splice(i, 2, { type: "textord", mode: "text", loc: SourceLocation.range(a, next), text: v + v }); n -= 1; } } } /** * Parse a single symbol out of the string. Here, we handle single character * symbols and special functions like \verb. */ parseSymbol() { var nucleus = this.fetch(); var text = nucleus.text; if (/^\\verb[^a-zA-Z]/.test(text)) { this.consume(); var arg = text.slice(5); var star = arg.charAt(0) === "*"; if (star) arg = arg.slice(1); if (arg.length < 2 || arg.charAt(0) !== arg.slice(-1)) throw new ParseError("\\verb assertion failed --\n please report what input caused this bug"); arg = arg.slice(1, -1); return { type: "verb", mode: "text", body: arg, star }; } if (Object.prototype.hasOwnProperty.call(unicodeSymbols, text[0]) && !symbols[this.mode][text[0]]) { if (this.settings.strict && this.mode === "math") handleStrict({ strict: this.settings.strict, errorCode: "unicodeTextInMathMode", errorMsg: "Accented Unicode text character \"" + text[0] + "\" used in math mode", report: true, token: nucleus }); text = unicodeSymbols[text[0]] + text.slice(1); } var match = combiningDiacriticalMarksEndRegex.exec(text); if (match) { text = text.substring(0, match.index); if (text === "i") text = "ı"; else if (text === "j") text = "ȷ"; } var symbol; if (symbols[this.mode][text]) { if (this.settings.strict && this.mode === "math" && extraLatin.includes(text)) handleStrict({ strict: this.settings.strict, errorCode: "unicodeTextInMathMode", errorMsg: "Latin-1/Unicode text character \"" + text[0] + "\" used in math mode", report: true, token: nucleus }); var group = symbols[this.mode][text].group; var loc = SourceLocation.range(nucleus); var s; if (isAtom(group)) s = { type: "atom", mode: this.mode, family: group, loc, text }; else s = { type: group, mode: this.mode, loc, text }; symbol = s; } else if (text.charCodeAt(0) >= 128) { if (this.settings.strict) { if (!supportedCodepoint(text.charCodeAt(0))) handleStrict({ strict: this.settings.strict, errorCode: "unknownSymbol", errorMsg: "Unrecognized Unicode character \"" + text[0] + "\"" + (" (" + text.charCodeAt(0) + ")"), report: true, token: nucleus }); else if (this.mode === "math") handleStrict({ strict: this.settings.strict, errorCode: "unicodeTextInMathMode", errorMsg: "Unicode text character \"" + text[0] + "\" used in math mode", report: true, token: nucleus }); } symbol = { type: "textord", mode: "text", loc: SourceLocation.range(nucleus), text }; } else return null; this.consume(); if (match) for (var i = 0; i < match[0].length; i++) { var accent = match[0][i]; if (!unicodeAccents[accent]) throw new ParseError("Unknown accent ' " + accent + "'", nucleus); var command = unicodeAccents[accent][this.mode] || unicodeAccents[accent].text; if (!command) throw new ParseError("Accent " + accent + " unsupported in " + this.mode + " mode", nucleus); symbol = { type: "accent", mode: this.mode, loc: SourceLocation.range(nucleus), label: command, isStretchy: false, isShifty: true, base: symbol }; } return symbol; } }; Parser.endOfExpression = /* @__PURE__ */ new Set([ "}", "\\endgroup", "\\end", "\\right", "&" ]); /** * Parses an expression using a Parser, then returns the parsed result. */ var parseTree = function parseTree(toParse, settings) { if (!(typeof toParse === "string" || toParse instanceof String)) throw new TypeError("KaTeX can only parse string typed expression"); var parser = new Parser(toParse, settings); delete parser.gullet.macros.current["\\df@tag"]; var tree = parser.parse(); delete parser.gullet.macros.current["\\current@color"]; delete parser.gullet.macros.current["\\color"]; if (parser.gullet.macros.get("\\df@tag")) { if (!settings.displayMode) throw new ParseError("\\tag works only in display equations"); tree = [{ type: "tag", mode: "text", body: tree, tag: parser.subparse([new Token("\\df@tag")]) }]; } return tree; }; /** * Parse and build an expression, and place that expression in the DOM node * given. */ var render = function render(expression, baseNode, options) { baseNode.textContent = ""; var node = renderToDomTree(expression, options).toNode(); baseNode.appendChild(node); }; if (typeof document !== "undefined") { if (document.compatMode !== "CSS1Compat") { typeof console !== "undefined" && console.warn("Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype."); render = function render() { throw new ParseError("KaTeX doesn't work in quirks mode."); }; } } /** * Parse and build an expression, and return the markup for that. */ var renderToString = function renderToString(expression, options) { return renderToDomTree(expression, options).toMarkup(); }; /** * Parse an expression and return the parse tree. */ var generateParseTree = function generateParseTree(expression, options) { return parseTree(expression, new Settings(options)); }; /** * If the given error is a KaTeX ParseError and options.throwOnError is false, * renders the invalid LaTeX as a span with hover title giving the KaTeX * error message. Otherwise, simply throws the error. */ var renderError = function renderError(error, expression, options) { if (options.throwOnError || !(error instanceof ParseError)) throw error; var node = makeSpan(["katex-error"], [new SymbolNode(expression)]); node.setAttribute("title", error.toString()); node.setAttribute("style", "color:" + options.errorColor); return node; }; /** * Generates and returns the katex build tree. This is used for advanced * use cases (like rendering to custom output). */ var renderToDomTree = function renderToDomTree(expression, options) { var settings = new Settings(options); try { return buildTree(parseTree(expression, settings), expression, settings); } catch (error) { return renderError(error, expression, settings); } }; var katex = { /** * Current KaTeX version */ version: "0.19.1", /** * Renders the given LaTeX into an HTML+MathML combination, and adds * it as a child to the specified DOM node. */ render, /** * Renders the given LaTeX into an HTML+MathML combination string, * for sending to the client. */ renderToString, /** * KaTeX error, usually during parsing. */ ParseError, /** * The schema of Settings */ SETTINGS_SCHEMA, /** * Parses the given LaTeX into KaTeX's internal parse tree structure, * without rendering to HTML or MathML. * * NOTE: This method is not currently recommended for public use. * The internal tree representation is unstable and is very likely * to change. Use at your own risk. */ __parse: generateParseTree, /** * Renders the given LaTeX into an HTML+MathML internal DOM tree * representation, without flattening that representation to a string. * * NOTE: This method is not currently recommended for public use. * The internal tree representation is unstable and is very likely * to change. Use at your own risk. */ __renderToDomTree: renderToDomTree, /** * Renders the given LaTeX into an HTML internal DOM tree representation, * without MathML and without flattening that representation to a string. * * NOTE: This method is not currently recommended for public use. * The internal tree representation is unstable and is very likely * to change. Use at your own risk. */ __renderToHTMLTree: function renderToHTMLTree(expression, options) { var settings = new Settings(options); try { return buildHTMLTree(parseTree(expression, settings), settings); } catch (error) { return renderError(error, expression, settings); } }, /** * extends internal font metrics object with a new object * each key in the new object represents a font name */ __setFontMetrics: setFontMetrics, /** * adds a new symbol to builtin symbols table */ __defineSymbol: defineSymbol, /** * adds a new function to builtin function list, * which directly produce parse tree elements * and have their own html/mathml builders */ __defineFunction: defineFunction, /** * adds a new macro to builtin macro list */ __defineMacro: defineMacro, /** * Expose the dom tree node types, which can be useful for type checking nodes. * * NOTE: These methods are not currently recommended for public use. * The internal tree representation is unstable and is very likely * to change. Use at your own risk. */ __domTree: { Span, Anchor, SymbolNode, SvgNode, PathNode, LineNode } }; // src/client/markdown/katex.tsx /** * TeX-to-React via KaTeX, replicating the rehype-katex pipeline this renderer * replaced: the same three-arm error chain (strict render, `strict: 'ignore'` * retry, error span) and a DOM-identical element tree, so settled math keeps * its exact markup. KaTeX emits an HTML string; the browser's own HTML parser * (`DOMParser`, applying the spec's SVG/MathML foreign-content attribute * adjustments KaTeX output relies on) turns it into a tree this module maps * onto React elements — KaTeX output is a static span/MathML/SVG vocabulary * with no raw user HTML, the same trust shiki's tree gets in CodeBlock. * * React 18 has no MathML support, so the `.katex-mathml` subtree's elements * land in the HTML namespace — exactly as they did under the replaced * hast-util-to-jsx-runtime pipeline. The visual arm is the `.katex-html` * span tree; the MathML arm serves assistive technology, which reads it by * tag name regardless of namespace. */ /** * Convert one inline `style` attribute string into React's style object. * KaTeX emits only plain kebab-case declarations (no custom properties and no * nameless declarations), so camel-casing the property is the whole mapping. */ function styleObject(css) { const style = {}; for (const declaration of css.split(";")) { const colon = declaration.indexOf(":"); if (colon === -1) continue; const key = declaration.slice(0, colon).trim().replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()); style[key] = declaration.slice(colon + 1).trim(); } return style; } /** Map one parsed DOM node onto a React element (text nodes pass through). */ function domToReact(node, key) { if (node.nodeType === Node.TEXT_NODE) return node.textContent; /* v8 ignore next 2 -- KaTeX output holds only elements and text; other node kinds cannot appear in its serialized vocabulary. */ if (node.nodeType !== Node.ELEMENT_NODE) return null; const element = node; const props = { key }; for (const attribute of element.attributes) if (attribute.name === "class") props["className"] = attribute.value; else if (attribute.name === "style") props["style"] = styleObject(attribute.value); else props[attribute.name] = attribute.value; const children = [...element.childNodes].map(domToReact); return children.length === 0 ? (0, react.createElement)(element.localName, props) : (0, react.createElement)(element.localName, props, ...children); } /** * Render TeX source to React elements through KaTeX. * @param value - The TeX source (math node value; fenced `math` blocks append * their trailing newline to match the replaced pipeline's text extraction). * @param displayMode - Display (block) versus inline rendering. * @returns KaTeX's element tree, or the error span when the source does not * parse (colored with KaTeX's stock `errorColor`, matching rehype-katex). */ function renderTexToReact(value, displayMode) { let html; try { html = katex.renderToString(value, { displayMode, throwOnError: true }); } catch (error) { try { html = katex.renderToString(value, { displayMode, strict: "ignore", throwOnError: false }); } catch { /* v8 ignore next 8 */ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "katex-error", style: { color: "#cc0000" }, title: String(error), children: value }); } } return [...new DOMParser().parseFromString(html, "text/html").body.childNodes].map(domToReact); } // \0dshx-css-module:src/client/markdown/MarkdownText.module.css.mjs const css$6 = ".mFG9SG_markdown{overflow-wrap:anywhere;min-width:0;font:var(--dsw-font-markdown-base);color:var(--dsw-alias-label-primary)}.mFG9SG_markdown strong{font-weight:600}.mFG9SG_markdown h1{font:var(--dsw-font-markdown-h1);margin:32px 0 16px}.mFG9SG_markdown h2{font:var(--dsw-font-markdown-h2);margin:32px 0 16px}.mFG9SG_markdown h3{font:var(--dsw-font-markdown-h3);margin:32px 0 16px}.mFG9SG_markdown h4{font:var(--dsw-font-markdown-h4);margin:16px 0}.mFG9SG_markdown :where(h5,h6){font:var(--dsw-font-markdown-base-strong);margin:16px 0}.mFG9SG_markdown :where(h1,h2,h3,h4,h5,h6) strong{font-weight:inherit}.mFG9SG_markdown p{margin:16px 0}.mFG9SG_markdown :where(h4,h5,h6)+:where(ul,ol){margin-top:8px}.mFG9SG_markdown :where(h4,h5,h6):has(+:where(ul,ol)){margin-bottom:8px}.mFG9SG_markdown a{color:var(--dsw-alias-state-business-primary);transition:box-shadow var(--ds-transition-duration) var(--ds-ease-in-out);border:2px solid #fff0;border-width:2px 3px;margin-left:-3px;margin-right:-3px;text-decoration:none;position:relative}.mFG9SG_markdown a:hover,.mFG9SG_markdown a:focus{-webkit-text-decoration:underline var(--dsw-alias-state-business-primary);text-decoration:underline var(--dsw-alias-state-business-primary);outline:none}.mFG9SG_markdown a:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-state-business-primary)}.mFG9SG_markdown :where(ul,ol){margin:16px 0;padding-left:18px}.mFG9SG_markdown li:not(:first-child){margin-top:6px}.mFG9SG_markdown li>:where(ul,ol){margin-top:4px}.mFG9SG_markdown li::marker{color:var(--dsw-alias-label-secondary);line-height:28px}.mFG9SG_markdown :where(ul,ol) ol{padding-left:0;list-style-position:inside}.mFG9SG_markdown :where(ul,ol) ol li p{display:inline}.mFG9SG_markdown li>p{margin:8px 0}.mFG9SG_markdown li>:first-child{margin-top:0}.mFG9SG_markdown li>:last-child:not(.md-code-block){margin-bottom:0}.mFG9SG_markdown hr{background:var(--dsw-alias-border-l2);border:none;height:1px;margin:32px 0;display:block}.mFG9SG_markdown blockquote{border-left:2px solid var(--dsw-alias-label-caption);margin:16px 0 0;padding-left:14px}.mFG9SG_markdown pre{font-family:var(--ds-font-family-code);margin:16px 0;overflow:auto}.mFG9SG_markdown :not(pre)>code{box-sizing:border-box;font:var(--dsw-font-markdown-code);font-family:var(--ds-font-family-code);background-color:var(--dsw-alias-markdown-inline-code);border-radius:6px;align-items:center;padding:0 5px;display:inline-flex;font-size:.875em!important}.mFG9SG_markdown :where(h1,h2,h3,h4,h5,h6) code{font:inherit;font-family:var(--ds-font-family-code)}.mFG9SG_markdown .katex-display{max-width:100%;overflow:auto hidden}.mFG9SG_markdown input[type=checkbox]{accent-color:var(--dsw-alias-label-secondary);margin:0 8px 0 0}.mFG9SG_tableScroll{overscroll-behavior-x:contain;max-width:100%;overflow-x:auto}.mFG9SG_tableScroll.md-table-wide{padding-bottom:var(--dsh-scrollbar-width,8px);overflow-x:hidden}:is(.mFG9SG_tableScroll.md-table-wide:hover,.mFG9SG_tableScroll.md-table-wide:focus-visible){padding-bottom:0;overflow-x:auto}.mFG9SG_tableScroll:focus-visible{box-shadow:0 0 0 2px var(--dsw-alias-state-business-primary);outline:none}.mFG9SG_tableScroll table{border-collapse:collapse;width:max-content;max-width:max-content}.mFG9SG_tableFill table{width:100%;max-width:none}.mFG9SG_tableScroll th{text-align:start;border-bottom:1px solid var(--dsw-alias-border-l3);font:var(--dsw-font-markdown-table-head);border-top:none;min-width:100px;max-width:min(30vw,320px);padding:10px 16px}.mFG9SG_tableScroll td{border-bottom:1px solid var(--dsw-alias-border-l2);font:var(--dsw-font-markdown-table);min-width:100px;max-width:min(30vw,320px);padding:10px 16px}.mFG9SG_tableScroll th:first-child,.mFG9SG_tableScroll td:first-child{padding-left:0}.mFG9SG_tableScroll td:last-child{padding-right:0}.mFG9SG_tableScroll table code{font-size:13px}.mFG9SG_markdown>:first-child,.mFG9SG_markdown p:first-child{margin-top:0!important}.mFG9SG_markdown>:last-child,.mFG9SG_markdown p:last-child{margin-bottom:0!important}.mFG9SG_imageAlt{color:var(--dsw-alias-label-tertiary);font-style:italic}.mFG9SG_image{background:var(--dsw-alias-bg-base);object-fit:contain;border-radius:8px;width:auto;max-width:100%;height:auto;margin:0;display:block}.mFG9SG_fileMention{font:inherit;color:var(--dsw-alias-state-business-primary);cursor:pointer;background:0 0;border:none;margin:0;padding:0;text-decoration:none}.mFG9SG_fileMention:hover,.mFG9SG_fileMention:focus{-webkit-text-decoration:underline var(--dsw-alias-state-business-primary);text-decoration:underline var(--dsw-alias-state-business-primary);text-underline-offset:3px;outline:none}"; const tagId$6 = "dsh-better-chat/MarkdownText.module.css"; if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$6) + "]") === null) { const tag = document.createElement("style"); tag.dataset.plugin = "dsh-better-chat"; tag.dataset.pluginCss = tagId$6; tag.textContent = css$6; document.head.appendChild(tag); } var MarkdownText_module_css_default = { "fileMention": "mFG9SG_fileMention", "image": "mFG9SG_image", "imageAlt": "mFG9SG_imageAlt", "markdown": "mFG9SG_markdown", "tableFill": "mFG9SG_tableFill", "tableScroll": "mFG9SG_tableScroll" }; // src/client/markdown/render.tsx /** * Direct mdast→React markdown renderer. Replaces the react-markdown / * remark-rehype pipeline with one switch over parsed nodes so streaming can * cache frozen blocks as React elements; the rendered DOM is pinned * byte-for-byte by `tests/fixtures/markdown-dom` and must not drift. * * Untrusted-output policy (unchanged from the replaced pipeline): link and * image destinations pass a protocol allowlist, images additionally require * absolute HTTP(S), raw HTML renders as literal text (no HTML enters the * DOM), and KaTeX runs without trusted commands. Fragment-anchor URLs fail * the allowlist, so footnote references and back-references render as plain * text rather than in-page links. * * Merge-extensible node unions fall through the documented default (render * nothing) rather than ending in assertNever: grammars registered elsewhere * may add node types this renderer has no mapping for. */ function sanitizeUrl(url) { try { switch (new URL(url).protocol) { case "http:": case "https:": case "mailto:": return url; default: return ""; } } catch { return ""; } } function remoteImageUrl(url) { try { const protocol = new URL(url).protocol; return protocol === "http:" || protocol === "https:" ? url : void 0; } catch { return; } } /** * Create an empty {@link ReferenceTargets}. * @returns Fresh empty maps. */ function createReferenceTargets() { return { definitions: /* @__PURE__ */ new Map(), footnotes: /* @__PURE__ */ new Map() }; } /** * Record every definition and footnote definition under `nodes` into * `targets`, depth-first, keeping the first definition per identifier. * @param nodes - Subtrees to walk (top-level blocks or any nested children). * @param targets - Accumulator, typically shared across incremental segments. */ function collectReferenceTargets(nodes, targets) { for (const node of nodes) { if (node.type === "definition") { const id = node.identifier.toUpperCase(); if (!targets.definitions.has(id)) targets.definitions.set(id, node); } else if (node.type === "footnoteDefinition") { const id = node.identifier.toUpperCase(); if (!targets.footnotes.has(id)) targets.footnotes.set(id, node); } if ("children" in node) collectReferenceTargets(node.children, targets); } } /** * Render top-level blocks. Nodes that render nothing (definitions, unmapped * types) are dropped rather than kept as null placeholders, matching the * replaced pipeline's child lists so separator newlines land identically. * @param blocks - Blocks with their stream-stable render keys. * @param context - The pass state; footnote numbering mutates in document order. * @returns One React node per rendered block. */ function renderBlocks(blocks, context) { return blocks.map((block) => renderNode(block.node, block.key, { ...context, sourceOffset: block.key - (block.node.position?.start.offset ?? block.key) })).filter((element) => element !== null); } /** * Interleave the newline text nodes the replaced pipeline emitted between * block-level children. They are invisible between elements but coalesce * into adjacent literal raw-HTML text, where the DOM parity fixtures pin * them. * @param elements - Rendered block children with empty renders already dropped. * @param edges - Also emit the leading and trailing newline (hast's loose wrap). * @returns The interleaved children. */ function wrapBlockChildren(elements, edges) { const wrapped = []; for (const element of elements) { if (edges || wrapped.length > 0) wrapped.push("\n"); wrapped.push(element); } if (edges && elements.length > 0) wrapped.push("\n"); return wrapped; } /** Render container children into {@link BlockEntry} values, dropping empty renders. */ function renderBlockEntries(blocks, context) { const entries = []; for (const [index, block] of blocks.entries()) if (block.type === "paragraph") entries.push({ paragraph: renderChildren(block.children, context) }); else { const element = renderNode(block, index, context); if (element !== null) entries.push({ element }); } return entries; } function renderChildren(nodes, context) { return nodes.map((node, index) => renderNode(node, index, context)); } function renderNode(node, key, context) { switch (node.type) { case "text": return context.renderText ? context.renderText(node.value, (context.sourceOffset ?? 0) + (node.position?.start.offset ?? 0)) : node.value; case "paragraph": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: renderChildren(node.children, context) }, key); case "heading": return (0, react.createElement)(`h${node.depth}`, { key }, ...renderChildren(node.children, context)); case "blockquote": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("blockquote", { children: wrapBlockChildren(renderChildren(node.children, { ...context, inBlockquote: true }).filter((child) => child !== null), true) }, key); case "thematicBreak": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("hr", {}, key); case "break": return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("br", {}), "\n"] }, key); case "strong": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: renderChildren(node.children, context) }, key); case "emphasis": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("em", { children: renderChildren(node.children, context) }, key); case "delete": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("del", { children: renderChildren(node.children, context) }, key); case "inlineCode": { const value = node.value.replace(/\r?\n|\r/g, " "); const content = context.renderText ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: context.renderText(value, (context.sourceOffset ?? 0) + (node.position?.start.offset ?? 0), true) }) : value; const href = inlineCodeHttpUrl(value); if (href !== void 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { children: renderSafeLink(href, [content], "link") }, key); const mention = context.inLink === true ? void 0 : context.fileMentions?.resolve(value); if (mention !== void 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: MarkdownText_module_css_default.fileMention, title: mention.title, "aria-label": mention.label, onClick: mention.open, children: content }) }, key); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { children: content }, key); } case "html": return context.renderText ? context.renderText(node.value, (context.sourceOffset ?? 0) + (node.position?.start.offset ?? 0)) : node.value; case "code": { const code = renderCode(node, key, context); return context.renderAtom ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: context.renderAtom(code, (context.sourceOffset ?? 0) + (node.position?.start.offset ?? 0)) }, key) : code; } case "math": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: renderTexToReact(node.value, true) }, key); case "inlineMath": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: renderTexToReact(node.value, false) }, key); case "list": return renderList(node, key, context); case "listItem": return renderListItem(node, listItemLoose(node), key, context); case "table": return renderTable(node, key, context); case "link": return renderAnchor(node.url, renderChildren(node.children, { ...context, inLink: true }), key); case "linkReference": return renderLinkReference(node, key, context); case "image": return renderImage(node.url, node.alt ?? "", key, context); case "imageReference": return renderImageReference(node, key, context); case "footnoteReference": return renderFootnoteReference(node, key, context); case "definition": case "footnoteDefinition": return null; default: return null; } } function renderCode(node, key, context) { const language = node.lang ?? void 0; if (node.value === "") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { className: language === void 0 ? void 0 : `language-${language}` }) }, key); const lang = language === void 0 ? void 0 : /^[\w-]+/.exec(language)?.[0]; if (isMcpAppCodeBlock(node.lang, node.meta, node.value)) { const title = extractMcpAppTitle(node.meta, node.value); const initialHeight = extractMcpAppHeight(node.meta); if (context.streaming) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StreamingMcpAppPlaceholder, { title }, key); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(McpAppCodeBlock, { html: node.value, title, initialHeight }, key); } if (!context.streaming && lang === "math") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: renderTexToReact(`${node.value}\n`, true) }, key); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.CodeBlock, { code: `${node.value}\n`, lang: context.streaming ? void 0 : lang, copyLabel: context.codeLabels?.copyLabel ?? "复制代码", copiedLabel: context.codeLabels?.copiedLabel ?? "已复制" }, key); } /** A list is loose when it or any of its items is spread; every item then keeps its paragraphs. */ function listLoose(list) { return (list.spread ?? false) || list.children.some(listItemLoose); } function listItemLoose(item) { return item.spread ?? item.children.length > 1; } function renderList(node, key, context) { const loose = listLoose(node); const properties = {}; if (typeof node.start === "number" && node.start !== 1) properties.start = node.start; if (node.children.some((item) => typeof item.checked === "boolean")) properties.className = "contains-task-list"; return (0, react.createElement)(node.ordered === true ? "ol" : "ul", { key, ...properties }, ...node.children.map((item, index) => renderListItem(item, loose, index, context))); } function renderListItem(item, loose, key, context) { const entries = renderBlockEntries(item.children, context); const task = typeof item.checked === "boolean"; if (task) { const checkbox = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", { type: "checkbox", checked: item.checked === true, disabled: true }, "task-checkbox"); const head = entries[0]; if (head !== void 0 && "paragraph" in head) head.paragraph = head.paragraph.length > 0 ? [ checkbox, " ", ...head.paragraph ] : [checkbox]; else entries.unshift({ paragraph: [checkbox] }); } const parts = []; for (const [index, entry] of entries.entries()) { const isParagraph = "paragraph" in entry; if (loose || index !== 0 || !isParagraph) parts.push("\n"); if (!isParagraph) parts.push(entry.element); else if (loose) parts.push(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: entry.paragraph }, `p-${index}`)); else parts.push(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: entry.paragraph }, `p-${index}`)); } const tail = entries[entries.length - 1]; if (tail !== void 0 && (loose || !("paragraph" in tail))) parts.push("\n"); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("li", { className: task ? "task-list-item" : void 0, children: parts }, key); } function renderTable(node, key, context) { const align = node.align ?? null; const [headRow, ...bodyRows] = node.children; const wide = (align === null ? headRow?.children.length ?? 0 : align.length) >= 4 && context.inBlockquote !== true; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: clsx(MarkdownText_module_css_default.tableScroll, wide ? "md-table-wide" : MarkdownText_module_css_default.tableFill), tabIndex: wide ? 0 : void 0, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", { children: [headRow !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", { children: renderTableRow(headRow, "th", align, 0, context) }), bodyRows.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: bodyRows.map((row, index) => renderTableRow(row, "td", align, index + 1, context)) })] }) }, key); } function renderTableRow(row, cellTag, align, key, context) { const length = align === null ? row.children.length : align.length; const cells = []; for (let index = 0; index < length; index++) { const cell = row.children[index]; const alignValue = align?.[index]; cells.push((0, react.createElement)(cellTag, { key: index, style: alignValue == null ? void 0 : { textAlign: alignValue } }, ...cell === void 0 ? [] : renderChildren(cell.children, context))); } return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tr", { children: cells }, key); } /** Anchor over an already-authored href: allowlisted or unwrapped, external links get the safe attributes. */ function renderSafeLink(href, children, key) { const safeHref = sanitizeUrl(href); if (safeHref === "") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children }, key); const external = ["http:", "https:"].includes(new URL(safeHref).protocol); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", { href: safeHref, ...external ? { target: "_blank", rel: "noopener noreferrer" } : {}, children }, key); } /** Anchor over a parsed markdown destination, which hast normalized before the allowlist saw it. */ function renderAnchor(url, children, key) { return renderSafeLink(normalizeUri(url), children, key); } /** * The complete inline-code value when it is exactly an absolute HTTP(S) URL * (no surrounding whitespace); anything else stays inert code. */ function inlineCodeHttpUrl(value) { if (value.trim() !== value) return void 0; try { const protocol = new URL(value).protocol; return protocol === "http:" || protocol === "https:" ? value : void 0; } catch { return; } } function renderImage(url, alt, key, context) { const remote = remoteImageUrl(sanitizeUrl(normalizeUri(url))); const rewritten = remote === void 0 ? context.pathImages?.resolve(url) : void 0; let imageSrc = remote; if (rewritten !== void 0) try { const parsed = new URL(rewritten); if ([ "http:", "https:", "blob:", "data:" ].includes(parsed.protocol) || rewritten.startsWith("dsh-app://app/api/file?")) imageSrc = rewritten; } catch {} if (imageSrc === void 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: MarkdownText_module_css_default.imageAlt, children: alt }, key); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MarkdownImage, { src: imageSrc, alt, destination: url }, `${key}:${imageSrc}`); } function MarkdownImage({ src, alt, destination }) { const [failed, setFailed] = (0, react.useState)(false); if (failed) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: MarkdownText_module_css_default.imageAlt, children: alt || destination }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", { className: MarkdownText_module_css_default.image, src, alt, onError: () => { setFailed(true); }, loading: "lazy", decoding: "async", referrerPolicy: "no-referrer" }); } /** The bracketed source text a reference reverts to when its definition is missing. */ function referenceSuffix(node) { if (node.referenceType === "collapsed") return "][]"; if (node.referenceType === "full") return `][${node.label ?? node.identifier}]`; return "]"; } function renderLinkReference(node, key, context) { const definition = context.targets.definitions.get(node.identifier.toUpperCase()); if (definition === void 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react.Fragment, { children: [ "[", renderChildren(node.children, context), referenceSuffix(node) ] }, key); return renderAnchor(definition.url, renderChildren(node.children, { ...context, inLink: true }), key); } function renderImageReference(node, key, context) { const definition = context.targets.definitions.get(node.identifier.toUpperCase()); if (definition === void 0) return `![${node.alt ?? ""}${referenceSuffix(node)}`; return renderImage(definition.url, node.alt ?? "", key, context); } function renderFootnoteReference(node, key, context) { const id = node.identifier.toUpperCase(); const seen = context.footnoteCounts.get(id); if (seen === void 0) context.footnoteOrder.push(id); context.footnoteCounts.set(id, (seen ?? 0) + 1); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("sup", { children: String(context.footnoteOrder.indexOf(id) + 1) }, key); } /** * Render the trailing footnote section for every footnote referenced during * the pass, in first-reference order, with one plain-text back-reference * marker per rendered reference. * @param context - The pass state after all blocks rendered. * @returns The section, or null when no referenced footnote has a definition. */ function renderFootnoteSection(context) { const items = []; for (const id of context.footnoteOrder) { const definition = context.targets.footnotes.get(id); if (definition === void 0) continue; const count = context.footnoteCounts.get(id) ?? 0; const backrefs = []; for (let reference = 1; reference <= count; reference++) { if (backrefs.length > 0) backrefs.push(" "); backrefs.push("↩"); if (reference > 1) backrefs.push(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("sup", { children: String(reference) }, `re-${reference}`)); } const entries = renderBlockEntries(definition.children, context); const tail = entries[entries.length - 1]; const body = entries.map((entry, index) => "paragraph" in entry ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", { children: [entry.paragraph, entry === tail && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [" ", backrefs] })] }, `p-${index}`) : entry.element); if (tail === void 0 || !("paragraph" in tail)) body.push(...backrefs); items.push(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("li", { id: `user-content-fn-${normalizeUri(id.toLowerCase())}`, children: wrapBlockChildren(body, true) }, id)); } if (items.length === 0) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", { "data-footnotes": true, className: "footnotes", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", { id: "footnote-label", className: "sr-only", children: "Footnotes" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ol", { children: items })] }, "footnotes"); } // src/client/markdown/MarkdownText.tsx /** * Untrusted assistant-Markdown renderer over the direct mdast pipeline: * `parse.ts` grammars, the incremental streaming parser, and `render.tsx`. * While a message streams, all but the trailing two blocks freeze as cached * React elements and only the source tail behind them re-parses per chunk, * so per-chunk work tracks the tail size instead of the whole reply. Frozen * blocks keep their source-offset keys when they cross the freeze boundary, * so React reconciles instead of remounting. Known deviation while * streaming: a reference-style link or footnote whose definition sits on the * other side of the freeze boundary renders literally until the settled * full parse self-heals it. */ /** One settled full render: parse with math, resolve references, append the footnote section. */ function renderSettled(text, codeLabels, fileMentions, pathImages, renderText, renderAtom) { const root = parseGfmWithMath(text); const targets = createReferenceTargets(); collectReferenceTargets(root.children, targets); const context = { renderText, renderAtom, streaming: false, codeLabels, fileMentions, pathImages, targets, footnoteOrder: [], footnoteCounts: /* @__PURE__ */ new Map() }; const blocks = wrapBlockChildren(renderBlocks(root.children.map((node, index) => ({ node, key: node.position?.start.offset ?? -(index + 1) })), context), false); const section = renderFootnoteSection(context); return section === null ? blocks : [ ...blocks, "\n", section ]; } /** * Streaming render state for one growing message: the incremental parser, * the frozen blocks' cached elements, and the reference/footnote state their * rendering consumed (footnote numbering assigned to frozen references is * final, so the tail continues from a copy of it each frame). */ var StreamingRenderer = class { codeLabels; renderText; renderAtom; pathImages; parser = new IncrementalMarkdownParser(parseGfm); generation = -1; frozenCount = 0; frozenElements = []; frozenTargets = createReferenceTargets(); frozenFootnoteOrder = []; frozenFootnoteCounts = /* @__PURE__ */ new Map(); lastText = null; lastRendered = []; /** @param codeLabels - Fence copy labels baked into cached elements; the owner replaces the renderer when they change. */ constructor(codeLabels, renderText, renderAtom, pathImages) { this.codeLabels = codeLabels; this.renderText = renderText; this.renderAtom = renderAtom; this.pathImages = pathImages; } /** * Render the current accumulated text. Idempotent per text value, so React * may re-execute the calling render freely. * @param text - The full accumulated markdown source. * @returns Frozen elements, re-rendered tail, and the footnote section. */ render(text) { if (text === this.lastText) return this.lastRendered; const { frozen, tail, generation } = this.parser.update(text); if (generation !== this.generation) { this.generation = generation; this.frozenCount = 0; this.frozenElements = []; this.frozenTargets = createReferenceTargets(); this.frozenFootnoteOrder = []; this.frozenFootnoteCounts = /* @__PURE__ */ new Map(); } const newlyFrozen = frozen.slice(this.frozenCount); collectReferenceTargets(newlyFrozen.map((block) => block.node), this.frozenTargets); const frameTargets = { definitions: new Map(this.frozenTargets.definitions), footnotes: new Map(this.frozenTargets.footnotes) }; collectReferenceTargets(tail.map((block) => block.node), frameTargets); if (newlyFrozen.length > 0) { const frozenContext = { renderText: this.renderText, renderAtom: this.renderAtom, streaming: true, codeLabels: this.codeLabels, fileMentions: void 0, pathImages: this.pathImages, targets: frameTargets, footnoteOrder: this.frozenFootnoteOrder, footnoteCounts: this.frozenFootnoteCounts }; const batch = [...this.frozenElements]; for (const element of renderBlocks(newlyFrozen, frozenContext)) { if (batch.length > 0) batch.push("\n"); batch.push(element); } this.frozenElements = batch; this.frozenCount = frozen.length; } const tailContext = { renderText: this.renderText, renderAtom: this.renderAtom, streaming: true, codeLabels: this.codeLabels, fileMentions: void 0, pathImages: this.pathImages, targets: frameTargets, footnoteOrder: [...this.frozenFootnoteOrder], footnoteCounts: new Map(this.frozenFootnoteCounts) }; const children = [...this.frozenElements]; for (const element of renderBlocks(tail, tailContext)) { if (children.length > 0) children.push("\n"); children.push(element); } const section = renderFootnoteSection(tailContext); if (section !== null) children.push("\n", section); this.lastText = text; this.lastRendered = children; return this.lastRendered; } }; /** * Render untrusted assistant-authored Markdown as semantic React elements. * @param props - Markdown source text preserved by the session projection; * `streaming` renders fences and TeX plain (highlighting and KaTeX land on * the finalize swap) and parses incrementally across chunks; `codeLabels` * forwards localized copy-button labels to fence CodeBlocks — pass a * reference-stable object (memoized per locale revision), because a new * identity discards the streaming render cache mid-message. `fileMentions` * links inline-code tokens its resolver recognizes as real files; this is * the single streaming gate — it applies to settled renders only, because a * streaming message's vocabulary is not final and frozen cached elements * must not bake in handlers that could go stale. * @returns A GFM document with TeX math rendered through KaTeX; raw HTML, * relative links, and unsafe protocols are disabled, while absolute HTTP(S) * images render directly. */ const MarkdownText$2 = (0, react.memo)(function MarkdownText({ text, streaming = false, codeLabels, fileMentions, pathImages, renderText, renderAtom }) { const streamRef = (0, react.useRef)(null); const streamImagesRef = (0, react.useRef)(pathImages); const streamLabelsRef = (0, react.useRef)(codeLabels); const children = (0, react.useMemo)(() => { if (!streaming) { streamRef.current = null; return renderSettled(text, codeLabels, fileMentions, pathImages, renderText, renderAtom); } if (streamRef.current === null || streamLabelsRef.current !== codeLabels || streamImagesRef.current !== pathImages) { streamRef.current = new StreamingRenderer(codeLabels, renderText, renderAtom, pathImages); streamLabelsRef.current = codeLabels; streamImagesRef.current = pathImages; } return streamRef.current.render(text); }, [ text, streaming, codeLabels, fileMentions, pathImages, renderText, renderAtom ]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: MarkdownText_module_css_default.markdown, children }); }); // src/client/platform-media.ts /** Web or Desktop file route. Authorization stays Host-side. */ function localPathMediaUrl(protocol, origin, value) { if (!value.startsWith("/") || value.startsWith("//")) return void 0; if (protocol === "http:" || protocol === "https:") return `${origin}/api/file?path=${encodeURIComponent(value)}`; if (protocol === "dsh-app:" && origin === "dsh-app://app") return `dsh-app://app/api/file?path=${encodeURIComponent(value)}`; } const readerPathImages = { resolve: (value) => typeof window === "undefined" ? void 0 : localPathMediaUrl(window.location.protocol, window.location.origin, value) }; // \0dshx-css-module:src/client/Reader.module.css.mjs const css$5 = ".Nr89iW_root{color:var(--dsw-alias-label-primary);padding:16px calc(var(--dsh-composer-side-clearance,16px) + 16px) 24px;overflow-anchor:auto;--reader-lane-block:max(40px, calc(40px + var(--dsh-content-font-delta,0px)));--reader-lane-plate:linear-gradient(var(--dsw-alias-bg-base), var(--dsw-alias-bg-base)), linear-gradient(var(--dsw-alias-bg-layer-1,transparent), var(--dsw-alias-bg-layer-1,transparent));flex:none;min-width:0;font-family:inherit;font-size:16px;line-height:28px;container-type:inline-size}.Nr89iW_column{max-width:var(--dsh-chat-content-width,748px);flex-direction:column;gap:22px;width:100%;min-width:0;margin:0 auto;display:flex}.Nr89iW_column:focus,.Nr89iW_column:focus-visible{outline:none}.Nr89iW_toolbar{min-height:32px;color:var(--dsw-alias-label-tertiary);background:var(--dsw-alias-bg-base);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);justify-content:flex-end;align-items:center;gap:6px;padding:0;font-size:12px;display:flex;position:sticky;top:0}.Nr89iW_turnProcessSticky{background:var(--dsw-alias-bg-base);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);align-items:center;min-height:32px;display:flex;position:sticky}.Nr89iW_turnProcessSticky .Nr89iW_disclosureButton{min-height:32px}.Nr89iW_textButton,.Nr89iW_historyButton,.Nr89iW_iconButton,.Nr89iW_jump,.Nr89iW_disclosureButton,.Nr89iW_imageOpen,.Nr89iW_dialogClose{font:inherit;cursor:pointer}.Nr89iW_textButton{color:var(--dsw-alias-label-secondary);white-space:nowrap;background:0 0;border:0;border-radius:6px;padding:2px 6px}.Nr89iW_textButton:hover,.Nr89iW_iconButton:hover,.Nr89iW_disclosureButton:hover{background:var(--dsw-alias-interactive-bg-hover)}.Nr89iW_root button:focus-visible,.Nr89iW_root summary:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:3px}.Nr89iW_turn,.Nr89iW_turnStickyRegion{flex-direction:column;gap:14px;min-width:0;display:flex}.Nr89iW_turnStickyLanes{top:var(--reader-toolbar-height,var(--reader-lane-block,40px));z-index:6;flex-direction:column;min-width:0;display:flex;position:sticky}.Nr89iW_turn+.Nr89iW_turn,.Nr89iW_retiringContent+.Nr89iW_retiringContent>.Nr89iW_turn{margin-top:12px}.Nr89iW_userCluster{flex-direction:column;align-self:stretch;align-items:flex-end;gap:8px;width:100%;min-width:0;max-width:100%;margin-bottom:4px;display:flex}.Nr89iW_userCluster>[data-slot]>*{box-sizing:border-box;align-self:stretch;width:100%;min-width:0;max-width:100%}.Nr89iW_userImages{flex-direction:column;align-self:flex-end;align-items:flex-end;width:fit-content;min-width:0;max-width:100%;display:flex}.Nr89iW_userImages .Nr89iW_imageFigure{align-self:flex-end}.Nr89iW_user{width:fit-content;max-width:min(calc(var(--dsh-chat-content-width,748px) * .702), 82%);border-radius:var(--dsw-radius-xl,22px);background:var(--dsw-specific-bubble);color:var(--dsw-alias-label-primary);font-size:var(--dsh-content-font-size,14px);line-height:calc(22px + var(--dsh-content-font-delta,0px));white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;box-sizing:border-box;align-self:flex-end;margin-left:auto;padding:10px 16px;font-weight:400}.Nr89iW_user .Nr89iW_blocks{gap:10px}.Nr89iW_answer{overflow-wrap:anywhere;flex-direction:column;min-width:0;display:flex}.Nr89iW_readingText{min-width:0}.Nr89iW_reasonPlain{white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;color:inherit}.Nr89iW_readingText button{min-width:24px;min-height:24px}.Nr89iW_streamWord{display:inline-block}.Nr89iW_streamInlineWord{display:inline}.Nr89iW_streamWord,.Nr89iW_streamInlineWord,.Nr89iW_streamAtom{opacity:1;filter:none}.Nr89iW_streamAtom{min-width:0}@media (prefers-reduced-motion:reduce){.Nr89iW_streamWord,.Nr89iW_streamInlineWord,.Nr89iW_streamAtom{opacity:1!important;filter:none!important}}.Nr89iW_retiringContent{min-width:0}.Nr89iW_retiringContent[data-reader-retiring=retiring]{overflow:hidden}.Nr89iW_mainFlow,.Nr89iW_blocks{flex-direction:column;gap:16px;min-width:0;display:flex}.Nr89iW_mainFlow:empty,.Nr89iW_blocks:empty{display:none}.Nr89iW_blocks>:first-child{margin-top:0}.Nr89iW_blocks>:last-child{margin-bottom:0}.Nr89iW_blocks .md-table-wide{max-width:100%}.Nr89iW_disclosure{min-width:0}.Nr89iW_disclosureButton{max-width:100%;min-height:32px;color:var(--dsw-alias-label-tertiary);font-size:calc(14px + var(--dsh-content-font-delta,0px));line-height:calc(24px + var(--dsh-content-font-delta,0px));text-align:left;background:0 0;border:0;border-radius:7px;align-items:center;gap:6px;margin-left:-6px;padding:4px 6px;font-weight:400;display:inline-flex}.Nr89iW_disclosure[data-reader-status-only]{align-items:center;min-height:32px;display:flex}.Nr89iW_statusText{min-width:0;max-width:100%;font-size:calc(14px + var(--dsh-content-font-delta,0px));line-height:calc(24px + var(--dsh-content-font-delta,0px));color:var(--dsw-alias-label-secondary);font-weight:400;display:inline-flex}.Nr89iW_srOnly{clip-path:inset(50%);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.Nr89iW_think{--think-swap:.15s;--think-gap:50ms;--think-distance:8px;--think-blur:2px;--think-shimmer:2s;--think-base:var(--dsw-alias-label-secondary);--think-highlight:var(--dsw-alias-label-primary);--think-ease:ease-in-out;text-align:left;max-width:100%;display:inline-block;position:relative}.Nr89iW_thinkSizer{visibility:hidden;white-space:nowrap;display:block}.Nr89iW_thinkText{color:var(--think-base);white-space:nowrap;text-overflow:ellipsis;filter:blur();opacity:1;transition:transform var(--think-swap) var(--think-ease), filter var(--think-swap) var(--think-ease), opacity var(--think-swap) var(--think-ease);display:block;position:absolute;top:0;left:0;right:0;overflow:hidden;transform:translateY(0)}.Nr89iW_think[data-reader-status-phase=running] .Nr89iW_thinkText[data-reader-status-copy=current]{transition-delay:var(--think-gap)}.Nr89iW_think:not([data-reader-status-phase=idle]) .Nr89iW_thinkText{will-change:transform, filter, opacity}@supports (background-clip:text){.Nr89iW_think[data-active=true] .Nr89iW_thinkText:before{content:attr(data-text);pointer-events:none;background-image:linear-gradient(90deg, transparent 0%, transparent 40%, var(--think-highlight) 50%, transparent 60%, transparent 100%);color:#0000;-webkit-text-fill-color:transparent;animation:Nr89iW_thinkShimmer var(--think-shimmer) linear infinite;background-repeat:no-repeat;background-size:400% 100%;background-clip:text;position:absolute;inset:0}}@keyframes Nr89iW_thinkShimmer{0%{background-position:100% 0}to{background-position:0 0}}.Nr89iW_thinkText.Nr89iW_isExit{transform:translateY(calc(var(--think-distance) * -1));filter:blur(var(--think-blur));opacity:0}.Nr89iW_thinkText.Nr89iW_isEnterStart{transform:translateY(var(--think-distance));filter:blur(var(--think-blur));opacity:0;transition:none}[data-motion=off] .Nr89iW_thinkText{filter:none!important;opacity:1!important;transition:none!important;transform:none!important}[data-motion=off] .Nr89iW_thinkText[data-reader-status-copy=outgoing],[data-motion=off] .Nr89iW_thinkText:before{display:none!important}@media (prefers-reduced-motion:reduce),(forced-colors:active){.Nr89iW_thinkText{filter:none!important;opacity:1!important;transition:none!important;transform:none!important}.Nr89iW_thinkText[data-reader-status-copy=outgoing],.Nr89iW_thinkText:before{display:none!important}}.Nr89iW_processMeta{opacity:0;grid-template-rows:0fr;transition:grid-template-rows .26s cubic-bezier(.22,1,.36,1),opacity .16s ease-out;display:grid}.Nr89iW_processMeta[data-open=true]{opacity:1;grid-template-rows:1fr}.Nr89iW_processMetaInner{min-height:0;overflow:hidden}.Nr89iW_processMetaLine{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;flex-wrap:wrap;align-items:baseline;gap:8px;padding:8px 0 0 16px;font-size:12px;line-height:20px;display:flex}.Nr89iW_processMetaLine .Nr89iW_meta{color:inherit}.Nr89iW_chevron{stroke:currentColor;fill:none;stroke-width:1.4px;stroke-linecap:round;stroke-linejoin:round;flex:none;transition:transform .26s cubic-bezier(.22,1,.36,1)}.Nr89iW_chevron[data-open=true]{transform:rotate(90deg)}.Nr89iW_disclosureBody{transform-origin:top;will-change:height, opacity, transform;height:0;overflow:hidden}.Nr89iW_processContents{border-left:1px solid var(--dsw-alias-border-l2);padding:3px 0 2px var(--reader-gutter,16px);margin:0 0 0 var(--reader-rail,6px);color:var(--dsw-alias-label-secondary);font-size:14px;line-height:24px;display:flow-root}.Nr89iW_processContents>:last-child{margin-bottom:0}.Nr89iW_processSeamRow{min-height:40px;margin-left:var(--reader-rail,6px);padding-left:var(--reader-gutter,16px);border-left:1px solid var(--dsw-alias-border-l2);box-sizing:border-box;align-items:center;display:flex}.Nr89iW_processSeamRow>.Nr89iW_disclosure{align-items:center;min-height:24px;display:flex}.Nr89iW_processSeamRow .Nr89iW_disclosureButton{min-height:24px;color:var(--dsw-alias-label-tertiary);padding-block:2px;font-size:12px;line-height:20px}.Nr89iW_flowCell:has(>.Nr89iW_flowCellInner>[data-reader-seam-after])>.Nr89iW_flowCellInner{padding-bottom:0}.Nr89iW_processFrame{min-width:0}.Nr89iW_toolActivity{min-width:0;color:var(--dsw-alias-label-secondary)}.Nr89iW_nativeToolRow{min-width:0}.Nr89iW_rowSeparator{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.Nr89iW_nativeToolSummary{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-tertiary);flex:1;font-size:14px;line-height:24px;overflow:hidden}.Nr89iW_nativeToolRow:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:3px;border-radius:4px}.Nr89iW_toolHeading{width:100%;color:inherit;font:inherit;text-align:left;cursor:pointer;background:0 0;border:0;border-radius:11px;grid-template-columns:20px minmax(0,1fr) auto;align-items:start;gap:10px;padding:10px 14px 4px;display:grid}.Nr89iW_toolHeading:hover{background:var(--dsw-alias-interactive-bg-hover)}.Nr89iW_toolHeading:focus-visible{outline-offset:-3px!important}.Nr89iW_toolGlyph{height:22px;color:var(--dsw-alias-label-secondary);justify-content:center;align-items:center;display:flex}.Nr89iW_toolHeadingCopy{flex-direction:column;gap:3px;min-width:0;display:flex}.Nr89iW_toolTitle{overflow-wrap:anywhere;font-size:13px;font-weight:500;line-height:22px}.Nr89iW_toolTarget{-webkit-line-clamp:2;overflow-wrap:anywhere;color:var(--dsw-alias-label-secondary);-webkit-box-orient:vertical;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;line-height:19px;display:-webkit-box;overflow:hidden}.Nr89iW_toolHeadingState{min-height:22px;color:var(--dsw-alias-label-secondary);align-items:center;gap:7px;display:flex}.Nr89iW_diffStat{font-variant-numeric:tabular-nums;font-feature-settings:\"tnum\";white-space:nowrap;flex:none;gap:6px;margin-left:8px;font-size:11px;line-height:18px;display:inline-flex}.Nr89iW_diffAdded{color:var(--dsw-alias-state-success-primary,#2f9e63)}.Nr89iW_diffRemoved{color:var(--dsw-alias-state-error-primary,#d1483c)}.Nr89iW_summaryRow{flex-wrap:wrap;align-items:center;gap:8px;min-width:0;max-width:100%;display:flex}.Nr89iW_summaryRow>.Nr89iW_diffStatRoot{flex:none;margin-left:auto}.Nr89iW_summaryRow>:first-child{min-width:0}.Nr89iW_diffStatRoot{flex:none;position:relative}.Nr89iW_diffStatButton{cursor:pointer;font:inherit;font-variant-numeric:tabular-nums;font-feature-settings:\"tnum\";color:var(--dsw-alias-label-secondary);background:0 0;border:1px solid #0000;border-radius:6px;align-items:center;gap:6px;padding:2px 8px;font-size:11px;line-height:16px;transition:background .12s,border-color .12s;display:inline-flex}.Nr89iW_diffStatButton:hover,.Nr89iW_diffStatButton:focus-visible,.Nr89iW_diffStatButton[aria-expanded=true]{background:var(--dsw-alias-bg-module-platform,#7f7f7f1a);border-color:var(--dsw-alias-border-l2,#7f7f7f47)}.Nr89iW_diffStatButton:focus-visible{outline:none}.Nr89iW_diffStatButton[aria-expanded=true] .Nr89iW_diffCaret{opacity:1}.Nr89iW_diffOverlayRow{box-sizing:border-box;flex:100%;width:100%;min-width:0;max-width:100%;margin-top:6px}.Nr89iW_diffOverlay{box-sizing:border-box;background:var(--dsw-alias-bg-module-platform,#7f7f7f14);border:1px solid var(--dsw-alias-border-l2,#80808038);border-radius:10px;flex-direction:column;width:100%;min-width:0;max-width:100%;padding:8px;display:flex;overflow:hidden}.Nr89iW_diffTabs{scrollbar-width:thin;flex-wrap:nowrap;gap:6px;max-width:100%;margin-bottom:4px;padding-bottom:6px;display:flex;overflow-x:auto}.Nr89iW_diffTab{text-overflow:ellipsis;white-space:nowrap;cursor:pointer;max-width:220px;font:inherit;color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-bg-base,#fffc);border:1px solid var(--dsw-alias-border-l2,#80808033);border-radius:6px;flex:none;padding:3px 10px;font-size:11px;line-height:16px;transition:all .12s;overflow:hidden}.Nr89iW_diffTab:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.Nr89iW_diffTab[data-active]{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-state-business-primary,#1e90ff);background:var(--dsw-alias-bg-base);font-weight:500}.Nr89iW_diffScrollArea{overscroll-behavior:contain;-webkit-overflow-scrolling:touch;border:1px solid var(--dsw-alias-border-l2,#80808026);background:var(--dsw-alias-markdown-code-block,#0000000a);border-radius:8px;max-height:420px;overflow:auto}.Nr89iW_diffScrollArea [data-diff]{background:0 0!important;border-radius:0!important;margin:0!important}.Nr89iW_diffCaret{opacity:.6;flex:none;width:10px;font-size:10px}.Nr89iW_diffPath{text-overflow:ellipsis;white-space:nowrap;text-align:left;direction:rtl;flex:auto;min-width:0;overflow:hidden}.Nr89iW_diffStat{font-variant-numeric:tabular-nums;flex:none;gap:6px;font-size:11px;display:inline-flex}.Nr89iW_diffHunkBody{flex-direction:column;gap:4px;padding:2px 7px 7px 25px;display:flex}.Nr89iW_diffLines{font-size:11px;line-height:1.55;font-family:var(--dsw-font-mono,ui-monospace, SFMono-Regular, Menlo, monospace);white-space:pre;border-radius:6px;margin:0;padding:6px 8px;overflow-x:auto}.Nr89iW_diffLines[data-side=removed]{background:#d1483c1f}.Nr89iW_diffLines[data-side=added]{background:#2f9e631f}.Nr89iW_diffLineRemoved,.Nr89iW_diffLineAdded{display:block}.Nr89iW_diffLineRemoved{color:var(--dsw-alias-state-error-primary,#d1483c)}.Nr89iW_diffLineAdded{color:var(--dsw-alias-state-success-primary,#2f9e63)}.Nr89iW_diffEmpty{color:var(--dsw-alias-label-secondary);margin:0;padding:2px 0;font-size:11px}.Nr89iW_nativeToolSummary[data-running]{background-image:linear-gradient(90deg, currentColor 0%, currentColor 35%, color-mix(in srgb, currentColor 35%, transparent) 50%, currentColor 65%, currentColor 100%);-webkit-text-fill-color:transparent;background-position:100% 0;background-repeat:no-repeat;background-size:300% 100%;background-clip:text;animation:1.6s linear infinite Nr89iW_readerStepShimmer}@keyframes Nr89iW_readerStepShimmer{to{background-position:0 0}}.Nr89iW_toolElapsed[data-slow]{opacity:1;color:var(--dsw-alias-state-warning-primary,#d8862c);font-weight:500}.Nr89iW_toolElapsed{opacity:.72;font-variant-numeric:tabular-nums;font-feature-settings:\"tnum\";white-space:nowrap;flex:none;margin-left:8px;font-size:11px;line-height:18px}[data-motion=off] .Nr89iW_nativeToolSummary[data-running]{-webkit-text-fill-color:currentColor;background-image:none;animation:none!important}@media (prefers-reduced-motion:reduce){.Nr89iW_nativeToolSummary[data-running]{-webkit-text-fill-color:currentColor;background-image:none;animation:none!important}}.Nr89iW_toolState{white-space:nowrap;flex:none;margin-left:8px;font-size:11px;line-height:18px}.Nr89iW_toolState[data-phase=preparing],.Nr89iW_toolState[data-phase=running]{color:var(--dsw-alias-state-business-primary)}.Nr89iW_toolState[data-phase=preparing]:before,.Nr89iW_toolState[data-phase=running]:before{content:\"\";vertical-align:middle;background:currentColor;border-radius:50%;width:6px;height:6px;margin-right:6px;animation:1.4s ease-in-out infinite Nr89iW_readerRunningGlow;display:inline-block}@keyframes Nr89iW_readerRunningGlow{0%{box-shadow:0 0 0 0 color-mix(in srgb, currentColor 60%, transparent);opacity:1}70%{opacity:.7;box-shadow:0 0 0 7px #0000}to{opacity:1;box-shadow:0 0 #0000}}[data-motion=off] .Nr89iW_toolState[data-phase=preparing]:before,[data-motion=off] .Nr89iW_toolState[data-phase=running]:before{animation:none!important}@media (prefers-reduced-motion:reduce){.Nr89iW_toolState[data-phase=preparing]:before,.Nr89iW_toolState[data-phase=running]:before{animation:none!important}}.Nr89iW_toolState[data-phase=failed]{color:var(--dsw-alias-state-error-primary)}.Nr89iW_toolState[data-phase=interrupted]{color:inherit;opacity:.7}.Nr89iW_toolLedger{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;flex-wrap:wrap;align-items:baseline;gap:4px 12px;padding:10px 14px 0;font-size:11px;line-height:18px;display:flex}.Nr89iW_toolEngine{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.Nr89iW_toolDetails{border:1px solid var(--dsw-alias-border-l2);border-radius:8px;min-width:0;margin:6px 0 0 22px;overflow:hidden}.Nr89iW_toolTabs{align-items:center;gap:15px;padding:0 14px;display:flex}.Nr89iW_toolTabs>button{font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:0;border-bottom:2px solid #0000;padding:10px 1px 8px;font-size:12px;line-height:20px}.Nr89iW_toolTabs>button[aria-selected=true]{color:var(--dsw-alias-label-primary);border-bottom-color:var(--dsw-alias-state-business-primary)}.Nr89iW_toolPanel{flex-direction:column;gap:12px;min-width:0;padding:12px 14px 14px;font-size:13px;line-height:22px;display:flex}.Nr89iW_toolPanel:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:-3px}.Nr89iW_toolDetailNote{color:var(--dsw-alias-label-secondary);margin:0 0 9px;font-size:12px;line-height:20px}.Nr89iW_toolRawLabel{color:var(--dsw-alias-label-secondary);margin:0;font-size:12px;font-weight:500}.Nr89iW_toolRaw{background:var(--dsw-alias-bg-module-platform);max-height:400px;color:var(--dsw-alias-label-primary);white-space:pre-wrap;overflow-wrap:anywhere;border-radius:8px;margin:0;padding:12px;font:12px/20px ui-monospace,SFMono-Regular,Menlo,monospace;overflow:auto}.Nr89iW_systemPrompt{background:var(--dsw-alias-bg-module-platform);max-height:320px;color:var(--dsw-alias-label-primary);white-space:pre-wrap;overflow-wrap:anywhere;border-radius:8px;margin:0;padding:12px;font:12px/20px ui-monospace,SFMono-Regular,Menlo,monospace;overflow:auto}.Nr89iW_commandInput{white-space:pre-wrap;overflow-wrap:anywhere;margin:0}.Nr89iW_toolReceipt .Nr89iW_blocks,.Nr89iW_toolDocument .Nr89iW_blocks{font-size:13px;line-height:22px}.Nr89iW_toolChildren{margin:0 14px 12px var(--reader-rail,6px);padding-left:var(--reader-gutter,16px);border-left:1px solid var(--dsw-alias-border-l2);flex-direction:column;gap:9px;display:flex}@container (width<=420px){.Nr89iW_toolHeading{grid-template-columns:16px minmax(0,1fr) auto;gap:7px;padding:11px 10px 6px}.Nr89iW_toolHeadingState{gap:4px}.Nr89iW_toolLedger{padding-left:33px;padding-right:10px}.Nr89iW_toolPanel{padding:10px}}@media (pointer:coarse){.Nr89iW_toolTabs>button{min-height:44px}}.Nr89iW_reasonCard{--reason-preview-height:224px;--reason-hold:.84s;--reason-step:.5s;--reason-lines:2;--reason-fade:28px;--reason-ease:cubic-bezier(.22, 1, .36, 1);border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-module-platform);min-width:0;scroll-margin-block:16px calc(var(--dsh-composer-height,152px) + 16px);border-radius:12px;position:relative;overflow:hidden}.Nr89iW_reasonHeading{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;justify-content:space-between;align-items:baseline;gap:12px;padding:10px 16px 0;font-size:12px;line-height:20px;display:flex}.Nr89iW_reasonCard[data-overflow=false][data-expanded=false]{background:0 0;border-color:#0000;border-radius:0}.Nr89iW_reasonCard[data-overflow=false][data-expanded=false] .Nr89iW_reasonHeading{padding:0}.Nr89iW_reasonCard[data-overflow=false][data-expanded=false] .Nr89iW_reasonText{padding:4px 0 0 22px}.Nr89iW_reasonLabel{font-weight:500}.Nr89iW_reasonViewport{max-height:var(--reason-preview-height);scroll-behavior:auto;overflow-anchor:none;overscroll-behavior-y:contain;scrollbar-width:thin;scrollbar-color:var(--dsw-alias-border-l1) transparent;position:relative;overflow:auto}.Nr89iW_reasonCard[data-expanded=true] .Nr89iW_reasonViewport{max-height:min(60vh, 560px, var(--reason-reading-height,560px))}.Nr89iW_reasonViewport[data-edges=both],.Nr89iW_reasonCard[data-following=true][data-overflow=true] .Nr89iW_reasonViewport{-webkit-mask-image:linear-gradient(transparent 0, black var(--reason-fade), black calc(100% - var(--reason-fade)), transparent 100%);mask-image:linear-gradient(transparent 0, black var(--reason-fade), black calc(100% - var(--reason-fade)), transparent 100%)}.Nr89iW_reasonViewport[data-edges=top]{-webkit-mask-image:linear-gradient(transparent 0, black var(--reason-fade), black 100%);mask-image:linear-gradient(transparent 0, black var(--reason-fade), black 100%)}.Nr89iW_reasonViewport[data-edges=bottom]{-webkit-mask-image:linear-gradient(black 0, black calc(100% - var(--reason-fade)), transparent 100%);mask-image:linear-gradient(black 0, black calc(100% - var(--reason-fade)), transparent 100%)}.Nr89iW_reasonCard[data-expanded=true] .Nr89iW_reasonViewport{mask-image:none}.Nr89iW_reasonViewport:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:-3px}.Nr89iW_reasonTrack{position:relative;transform:translateY(0)}.Nr89iW_reasonCard[data-following=true] .Nr89iW_reasonTrack{will-change:transform}.Nr89iW_reasonText{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;padding:8px 16px 16px;font-size:14px;line-height:24px}.Nr89iW_reasonText .Nr89iW_readingText>div{font-size:inherit;line-height:inherit;color:inherit}.Nr89iW_reasonFooter{color:var(--dsw-alias-label-secondary);justify-content:space-between;align-items:center;gap:8px;padding:2px 10px 8px;font-size:12px;line-height:20px;display:flex}.Nr89iW_reasonAction{min-height:28px;color:inherit;font:inherit;cursor:pointer;white-space:nowrap;background:0 0;border:0;border-radius:6px;justify-content:center;align-items:center;gap:5px;padding:4px 6px;display:inline-flex}.Nr89iW_reasonAction:hover{background:var(--dsw-alias-interactive-bg-hover)}.Nr89iW_reasonAction:disabled{cursor:default;opacity:.65}.Nr89iW_reasonAction svg{fill:none;stroke:currentColor;stroke-width:1.3px;stroke-linecap:round;stroke-linejoin:round;flex:none}.Nr89iW_reasonCaption{padding-left:6px}@container (width<=480px){.Nr89iW_reasonCard{--reason-preview-height:192px}}@media (pointer:coarse){.Nr89iW_reasonAction{min-height:44px}}@media (prefers-reduced-motion:reduce){.Nr89iW_reasonTrack{will-change:auto!important;transition:none!important;transform:none!important}}@media (forced-colors:active){.Nr89iW_reasonViewport{mask-image:none!important}}.Nr89iW_processItem,.Nr89iW_tool{min-width:0;margin:0 0 18px}.Nr89iW_processLabel{color:var(--dsw-alias-label-tertiary);align-items:baseline;gap:12px;margin:0 0 6px;font-size:12px;line-height:20px;display:flex}.Nr89iW_processFootnote{color:var(--dsw-alias-label-tertiary);margin:14px 0 0;font-size:12px;line-height:20px}.Nr89iW_detail{color:var(--dsw-alias-label-secondary);font-size:13px;line-height:22px}.Nr89iW_detail>summary{cursor:pointer;padding:3px 0}.Nr89iW_detail[open]>summary{margin-bottom:8px}.Nr89iW_tool>.Nr89iW_tool{margin:10px 0 0 12px}.Nr89iW_meta{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:20px}.Nr89iW_stopped{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-tertiary);border-radius:6px;align-self:flex-start;margin-top:12px;padding:0 6px;font-size:11px;line-height:18px}.Nr89iW_compactionRow{box-sizing:border-box;flex-direction:column;align-items:center;width:100%;margin:16px 0;display:flex}.Nr89iW_compactionLine{width:100%;color:var(--dsw-alias-label-tertiary);-webkit-user-select:none;user-select:none;justify-content:center;align-items:center;gap:12px;font-size:11px;line-height:18px;display:flex}.Nr89iW_compactionLine:before,.Nr89iW_compactionLine:after{content:\"\";background:var(--dsw-alias-border-l1);opacity:.7;flex:1;height:1px}.Nr89iW_compactionRow>.Nr89iW_compactionLine{animation:.52s cubic-bezier(.4,0,.2,1) both Nr89iW_compactionLineIn}.Nr89iW_compactionRow>.Nr89iW_compactionLine>.Nr89iW_compactionPill{animation:.42s cubic-bezier(.34,1.4,.64,1) .12s both Nr89iW_compactionPillIn}.Nr89iW_compactionRow>.Nr89iW_compactionLine .Nr89iW_compactionIcon{animation:.9s cubic-bezier(.4,0,.2,1) .2s both Nr89iW_compactionDial}@keyframes Nr89iW_compactionLineIn{0%{opacity:0;transform:scaleX(.6)}to{opacity:1;transform:scaleX(1)}}@keyframes Nr89iW_compactionPillIn{0%{opacity:0;transform:translateY(-6px)scale(.94)}to{opacity:1;transform:translateY(0)scale(1)}}@keyframes Nr89iW_compactionDial{0%{opacity:0;transform:rotate(-140deg)}to{opacity:.7;transform:rotate(0)}}[data-motion=off] .Nr89iW_compactionRow>.Nr89iW_compactionLine,[data-motion=off] .Nr89iW_compactionRow>.Nr89iW_compactionLine>.Nr89iW_compactionPill,[data-motion=off] .Nr89iW_compactionRow>.Nr89iW_compactionLine .Nr89iW_compactionIcon{animation:none!important}@media (prefers-reduced-motion:reduce){.Nr89iW_compactionRow>.Nr89iW_compactionLine,.Nr89iW_compactionRow>.Nr89iW_compactionLine>.Nr89iW_compactionPill,.Nr89iW_compactionRow>.Nr89iW_compactionLine .Nr89iW_compactionIcon{animation:none!important}}.Nr89iW_compactionPill{background:var(--dsw-alias-bg-module-platform);border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-tertiary);border-radius:12px;align-items:center;gap:6px;padding:2px 10px;font-family:inherit;font-size:11px;line-height:18px;display:inline-flex}.Nr89iW_compactionButton{cursor:pointer;transition:color .14s,border-color .14s,background-color .14s}.Nr89iW_compactionButton:hover{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-border-l2);background:var(--dsw-alias-interactive-bg-hover)}.Nr89iW_compactionIcon{opacity:.7;flex:none;width:12px;height:12px}.Nr89iW_compactionToggle{opacity:.8;margin-left:2px;font-size:10px}.Nr89iW_compactionSummaryBox{background:var(--dsw-alias-bg-module-platform);border:1px solid var(--dsw-alias-border-l2);width:100%;max-width:680px;color:var(--dsw-alias-label-secondary);box-sizing:border-box;border-radius:8px;margin-top:10px;padding:12px 16px;font-size:12px;line-height:20px}.Nr89iW_compactionSummaryHeader{color:var(--dsw-alias-label-tertiary);border-bottom:1px dashed var(--dsw-alias-border-l1);margin-bottom:8px;padding-bottom:4px;font-size:11px;font-weight:500}.Nr89iW_notice,.Nr89iW_error,.Nr89iW_attention{overflow-wrap:anywhere;border-radius:10px;padding:12px 14px;font-size:13px;line-height:20px}.Nr89iW_notice{background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary);border:1px solid var(--dsw-alias-border-l2)}.Nr89iW_error{color:var(--dsw-alias-label-primary);background:#ef44440f;border:1px solid #ef444438;align-items:flex-start;gap:10px;display:flex}.Nr89iW_errorIcon{color:#ef4444;flex:none;width:16px;height:16px;margin-top:2px}.Nr89iW_errorCopy{flex:1;min-width:0}.Nr89iW_errorTitle{color:#dc2626;align-items:center;gap:8px;margin-bottom:2px;font-weight:500;display:flex}.Nr89iW_errorMessage{color:var(--dsw-alias-label-secondary);word-break:break-word;margin:0;font-size:12px;line-height:18px}.Nr89iW_errorCode{color:#dc2626;background:#ef44441f;border-radius:4px;padding:1px 5px;font-family:inherit;font-size:11px}.Nr89iW_attention{border:1px solid var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);flex-direction:column;gap:3px;display:flex}.Nr89iW_attention span{color:var(--dsw-alias-label-secondary)}.Nr89iW_unknown{background:var(--dsw-alias-bg-module-platform);border:1px solid var(--dsw-alias-border-l2);border-radius:10px;padding:12px 14px;font-size:13px;line-height:22px}.Nr89iW_unknown p{margin:0 0 6px}.Nr89iW_historyButton{border:1px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary);background:0 0;border-radius:8px;align-self:center;padding:4px 12px;font-size:12px}.Nr89iW_historyButton:disabled{opacity:.55;cursor:default}.Nr89iW_empty{color:var(--dsw-alias-label-tertiary);text-align:center;padding:40px 0}.Nr89iW_answerActions{align-items:center;gap:8px;min-height:28px;margin:13px 0 0 -6px;display:flex}.Nr89iW_userActions{align-items:center;gap:8px;min-height:28px;display:flex}.Nr89iW_messageClock{color:var(--dsw-alias-label-tertiary);white-space:nowrap;font-variant-numeric:tabular-nums;font-size:13px;line-height:24px}.Nr89iW_iconButton{color:var(--dsw-alias-label-tertiary);background:0 0;border:0;border-radius:6px;justify-content:center;align-items:center;padding:6px;display:inline-flex}.Nr89iW_iconButton svg{fill:none;stroke:currentColor;stroke-width:1.2px;stroke-linecap:round;stroke-linejoin:round}.Nr89iW_imageFigure{box-sizing:border-box;align-self:flex-start;width:min(100%,360px);max-width:100%;margin:0}.Nr89iW_imageFrame{background:var(--dsw-alias-bg-module-platform);border:1px solid var(--dsw-alias-border-l2);box-sizing:border-box;border-radius:12px;max-width:100%;min-height:96px;max-height:440px;position:relative;overflow:hidden}.Nr89iW_imageOpen{background:0 0;border:0;width:100%;height:100%;padding:0;display:flex;position:absolute;inset:0}.Nr89iW_imageOpen img{object-fit:contain;opacity:0;width:100%;height:100%;transition:opacity .2s cubic-bezier(.4,0,.2,1);display:block}.Nr89iW_imageOpen img[data-ready=true]{opacity:1}.Nr89iW_pendingImage{object-fit:contain;width:100%;max-width:100%;height:100%;display:block}.Nr89iW_imagePlaceholder{color:var(--dsw-alias-label-tertiary);pointer-events:none;flex-direction:column;justify-content:center;align-items:center;gap:8px;font-size:13px;display:flex;position:absolute;inset:0}.Nr89iW_imagePlaceholder button{pointer-events:auto}.Nr89iW_imageFigure figcaption{color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere;margin-top:6px;font-size:12px;line-height:20px}.Nr89iW_imageDialog{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);border-radius:16px;max-width:90vw;max-height:90vh;padding:38px 20px 20px}.Nr89iW_imageDialog::backdrop{background:var(--dsw-alias-bg-mask-photo)}.Nr89iW_imageDialog img{object-fit:contain;max-width:82vw;max-height:75vh;display:block}.Nr89iW_dialogClose{color:inherit;background:0 0;border:0;border-radius:8px;width:32px;height:32px;font-size:24px;position:absolute;top:4px;right:8px}.Nr89iW_jumpDock{bottom:calc(var(--dsh-composer-height,152px) + 16px);z-index:8;pointer-events:none;justify-content:flex-end;height:0;display:flex;position:sticky}.Nr89iW_deliverablesRoot{grid-template-columns:max-content minmax(0,1fr);align-items:start;column-gap:10px;margin-top:14px;font-size:13px;line-height:22px;display:grid}.Nr89iW_deliverablesLabel{color:var(--dsw-alias-label-tertiary);grid-area:1/1;padding-top:2px;font-size:12px;font-weight:500}.Nr89iW_deliverablesLane{grid-area:1/2;min-width:0}.Nr89iW_deliverablesRow{flex-wrap:wrap;align-items:center;gap:8px;min-width:0;display:flex}.Nr89iW_deliverableChip{box-sizing:border-box;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary);border-radius:6px;align-items:center;font-size:12px;line-height:20px;transition:border-color .16s,background-color .16s,color .16s;display:inline-flex;overflow:hidden}.Nr89iW_deliverableChip:hover{border-color:var(--dsw-alias-border-l3);background:var(--dsw-alias-bg-module-platform);box-shadow:0 1px 4px var(--dsw-alias-border-l1)}.Nr89iW_deliverableChip[data-status=opened]{color:#059669;background:#10b9811f;border-color:#10b981}.Nr89iW_chipMain{max-width:220px;color:inherit;font:inherit;cursor:pointer;text-align:left;background:0 0;border:none;align-items:center;gap:5px;padding:3px 6px 3px 8px;display:inline-flex}.Nr89iW_chipMain:hover{color:var(--dsw-alias-label-primary)}.Nr89iW_deliverableIcon,.Nr89iW_statusIcon{opacity:.8;flex:none;width:13px;height:13px}.Nr89iW_statusIcon{color:#10b981}.Nr89iW_deliverableName{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.Nr89iW_chipActions{opacity:.65;border-left:1px solid #0000;align-items:center;gap:2px;padding-right:4px;transition:opacity .15s,border-left-color .15s;display:inline-flex}.Nr89iW_deliverableChip:hover .Nr89iW_chipActions{opacity:1;border-left-color:var(--dsw-alias-border-l2)}.Nr89iW_chipActionBtn{width:20px;height:20px;color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:none;border-radius:4px;justify-content:center;align-items:center;padding:0;transition:color .12s,background-color .12s;display:inline-flex}.Nr89iW_chipActionBtn:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}.Nr89iW_actionIcon{width:12px;height:12px}.Nr89iW_deliverablesMore{color:var(--dsw-alias-label-tertiary);white-space:nowrap;font-size:12px}.Nr89iW_deliverablesShowFolder{color:var(--dsw-alias-label-tertiary);font:inherit;cursor:pointer;background:0 0;border:1px solid #0000;border-radius:5px;align-items:center;gap:4px;padding:2px 7px;font-size:12px;transition:all .15s;display:inline-flex}.Nr89iW_deliverablesShowFolder:hover{color:var(--dsw-alias-state-business-primary);background:var(--dsw-alias-interactive-bg-hover);border-color:var(--dsw-alias-border-l2)}.Nr89iW_deliverablesShowFolder[data-status=opened]{color:#10b981;background:#10b98114;border-color:#10b9814d}.Nr89iW_morphCluster{flex-direction:column;width:100%;min-width:0;display:flex}.Nr89iW_morphDrawer{transform-origin:top;will-change:height, opacity, transform;height:0;overflow:hidden}.Nr89iW_liveFoldImpact{animation:.18s cubic-bezier(.2,0,0,1) both Nr89iW_liveFoldElastic}@keyframes Nr89iW_liveFoldElastic{0%{transform:scale(1)}50%{transform:scale(1.015)}to{transform:scale(1)}}.Nr89iW_liveFoldContainer{top:calc(var(--reader-toolbar-height,var(--reader-lane-block,40px)) + var(--reader-status-height,var(--reader-lane-block,40px)) + var(--reader-summary-height,var(--reader-lane-block,40px)));z-index:4;background:var(--dsw-alias-bg-base);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);transform-origin:0;will-change:transform, opacity;margin-bottom:6px;padding:4px 0;animation:.32s cubic-bezier(.16,1,.3,1) both Nr89iW_liveFoldPulse;position:sticky}@keyframes Nr89iW_liveFoldPulse{0%{opacity:.8;transform:translateY(-4px)scale(.98)}50%{opacity:1;transform:translateY(0)scale(1.02)}to{opacity:1;transform:translateY(0)scale(1)}}[data-motion=off] .Nr89iW_liveFoldContainer{animation:none!important}@media (prefers-reduced-motion:reduce){.Nr89iW_liveFoldContainer{animation:none!important}}.Nr89iW_priorFoldDrawer{flex-direction:column;gap:14px;width:100%;min-width:0;display:flex}.Nr89iW_jump{width:34px;height:34px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-button-floating-fill,var(--dsw-alias-bg-base));box-shadow:var(--dsw-elevation-panel,0 2px 8px var(--dsw-alias-border-l1));pointer-events:auto;border:0;border-radius:100px;flex:none;justify-content:center;align-items:center;margin-top:-34px;padding:0;display:flex}.Nr89iW_jump:hover{background:var(--dsw-alias-button-floating-hover,var(--dsw-alias-interactive-bg-hover))}.Nr89iW_foldSummary{text-overflow:ellipsis;align-items:baseline;max-width:100%;display:inline-flex;overflow:hidden;white-space:nowrap!important}.Nr89iW_foldSummaryPart{flex:none;align-items:baseline;display:inline-flex;white-space:nowrap!important}.Nr89iW_numberRollRoot{vertical-align:baseline;line-height:inherit;font-variant-numeric:tabular-nums;font-feature-settings:\"tnum\";text-align:center;flex-shrink:0;justify-content:center;min-width:1.45em;display:inline-flex;position:relative;overflow:hidden;white-space:nowrap!important}.Nr89iW_numberRollSizer{visibility:hidden;-webkit-user-select:none;user-select:none;pointer-events:none;line-height:inherit;white-space:nowrap}.Nr89iW_numberRollDigit{line-height:inherit;white-space:nowrap;justify-content:center;align-items:center;display:flex;position:absolute;inset:0}.Nr89iW_numberRollExit{animation:.24s cubic-bezier(.16,1,.3,1) forwards Nr89iW_numberRollOut}.Nr89iW_numberRollEnter{animation:.24s cubic-bezier(.16,1,.3,1) forwards Nr89iW_numberRollIn}@keyframes Nr89iW_numberRollOut{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-100%)}}@keyframes Nr89iW_numberRollIn{0%{opacity:0;transform:translateY(100%)}to{opacity:1;transform:translateY(0)}}[data-motion=off] .Nr89iW_chevron,[data-motion=off] .Nr89iW_imageOpen img,[data-motion=off] .Nr89iW_processMeta,[data-motion=off] .Nr89iW_numberRollDigit{transition:none!important;animation:none!important}@media (prefers-reduced-motion:reduce){.Nr89iW_chevron,.Nr89iW_imageOpen img,.Nr89iW_processMeta,.Nr89iW_numberRollDigit{transition:none!important;animation:none!important}}.Nr89iW_turnStatus{white-space:nowrap;flex:none;align-self:flex-start;align-items:center;height:26px;margin:4px 0 12px;padding:0 4px;font-size:14px;line-height:22px;display:inline-flex}.Nr89iW_turnStatusLabel{background:linear-gradient(90deg, var(--dsw-static-deepseek-500,#4d6bfe) 0%, var(--dsw-static-deepseek-500,#4d6bfe) 40%, var(--dsw-static-deepseek-200,#a8c7fa) 50%, var(--dsw-static-deepseek-500,#4d6bfe) 60%, var(--dsw-static-deepseek-500,#4d6bfe) 100%);color:#0000;-webkit-text-fill-color:transparent;background-position:100% 0;background-size:250% 100%;background-clip:text;font-weight:500;animation:1.8s linear infinite Nr89iW_dsh-turn-status-shimmer}.Nr89iW_waitClock{flex:none;align-items:center;margin-left:8px;display:inline-flex}.Nr89iW_waitSeconds{font-variant-numeric:tabular-nums;font-feature-settings:\"tnum\";color:var(--dsw-alias-label-caption,#86909c);font-size:13px;font-weight:400}.Nr89iW_waitOvertime{color:var(--dsw-alias-state-warning-primary,#d8862c);background:color-mix(in srgb, var(--dsw-alias-state-warning-primary,#d8862c) 16%, transparent);border-radius:5px;margin-left:8px;padding:0 6px;font-size:11px;line-height:16px}.Nr89iW_turnStatusClock{font-variant-numeric:tabular-nums;font-feature-settings:\"tnum\";color:var(--dsw-alias-label-caption,#86868b);-webkit-text-fill-color:var(--dsw-alias-label-caption,#86868b);margin-left:8px;font-size:13px;font-weight:400}@keyframes Nr89iW_dsh-turn-status-shimmer{to{background-position:0 0}}[data-motion=off] .Nr89iW_turnStatusLabel{color:var(--dsw-static-deepseek-500,#4d6bfe)!important;-webkit-text-fill-color:var(--dsw-static-deepseek-500,#4d6bfe)!important;animation:none!important}@media (prefers-reduced-motion:reduce){.Nr89iW_turnStatusLabel{color:var(--dsw-static-deepseek-500,#4d6bfe)!important;-webkit-text-fill-color:var(--dsw-static-deepseek-500,#4d6bfe)!important;animation:none!important}}@media (pointer:coarse){.Nr89iW_disclosureButton{min-height:44px}}@media (max-width:600px){.Nr89iW_root{padding-inline:20px}.Nr89iW_column{gap:18px}.Nr89iW_toolbar{font-size:11px}}.Nr89iW_choreographedFlow{overflow-anchor:none;flex-direction:column;min-width:0;display:flex}.Nr89iW_flowCell{min-width:0;display:flow-root;overflow:clip}.Nr89iW_flowCell[hidden]{display:none}.Nr89iW_flowCellInner{flex-direction:column;min-width:0;padding-bottom:16px;display:flex}.Nr89iW_flowCellInner:empty{padding-bottom:0}.Nr89iW_choreographedFlow[data-reader-transition=collapse] .Nr89iW_flowCell *{animation-play-state:paused!important}.Nr89iW_numberRollExit,.Nr89iW_numberRollEnter{animation-duration:.16s}.Nr89iW_foldSummary{align-items:baseline;display:inline-flex;white-space:nowrap!important;flex-wrap:nowrap!important}.Nr89iW_toolbar{box-sizing:border-box;width:100%;max-width:100%;min-height:var(--reader-lane-block,40px);z-index:7;-webkit-backdrop-filter:none;backdrop-filter:none;border-bottom:0;align-self:stretch}.Nr89iW_turnProcessSticky{box-sizing:border-box;width:calc(100% - var(--reader-control-width,148px));top:var(--reader-toolbar-height,var(--reader-lane-block,40px));min-height:var(--reader-lane-block,40px);z-index:6;-webkit-backdrop-filter:none;backdrop-filter:none;box-shadow:0 -14px 0 var(--dsw-alias-bg-base), var(--reader-control-width,148px) 0 0 var(--dsw-alias-bg-base), 0 -14px 0 var(--dsw-alias-bg-layer-1,transparent), var(--reader-control-width,148px) 0 0 var(--dsw-alias-bg-layer-1,transparent), 0 -14px 0 Canvas, var(--reader-control-width,148px) 0 0 Canvas;background-clip:padding-box;border-bottom:1px solid #0000;padding-right:0}.Nr89iW_turnStickyLanes .Nr89iW_turnProcessSticky,.Nr89iW_turnStickyLanes .Nr89iW_closedProcessSummary{z-index:auto;position:static;top:auto}.Nr89iW_flowCell[data-flow-summary],.Nr89iW_closedProcessSummary{top:calc(var(--reader-toolbar-height,var(--reader-lane-block,40px)) + var(--reader-status-height,var(--reader-lane-block,40px)));z-index:5;box-sizing:border-box;min-height:var(--reader-lane-block,40px);background:var(--dsw-alias-bg-base);border-bottom:0;padding-block:4px;position:sticky;overflow:visible}.Nr89iW_root .md-code-block{z-index:0}.Nr89iW_turnStickyRegion:has(>.Nr89iW_turnStickyLanes>.Nr89iW_closedProcessSummary),.Nr89iW_turnStickyRegion:has(.Nr89iW_flowCell[data-flow-summary]){--reader-code-summary-height:var(--reader-summary-height,var(--reader-lane-block,40px))}.Nr89iW_root .md-code-block>:has(+[data-code-block-content]){top:calc(max(var(--reader-toolbar-height,40px), var(--reader-status-height,0px)) + var(--reader-status-height,0px) + var(--reader-code-summary-height,0px))}.Nr89iW_flowCell[data-flow-summary]{box-shadow:0 -16px 0 var(--dsw-alias-bg-base), 0 -16px 0 var(--dsw-alias-bg-layer-1,transparent), 0 -16px 0 Canvas}.Nr89iW_closedProcessSummary{box-shadow:0 -14px 0 var(--dsw-alias-bg-base), 0 -14px 0 var(--dsw-alias-bg-layer-1,transparent), 0 -14px 0 Canvas}.Nr89iW_foldControl{background:var(--dsw-alias-bg-module-platform);border-radius:8px;align-items:center;gap:0;padding:2px;display:inline-flex}.Nr89iW_foldStop{color:var(--dsw-alias-label-secondary);white-space:nowrap;font:inherit;cursor:pointer;background:0 0;border:0;border-radius:6px;padding:2px 8px;font-size:12px;line-height:18px}.Nr89iW_foldStop[data-on]{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary)}.Nr89iW_flowCell[data-flow-summary]>.Nr89iW_flowCellInner{padding-bottom:0}.Nr89iW_flowCell[data-flow-summary] .Nr89iW_disclosureButton,.Nr89iW_closedProcessSummary .Nr89iW_disclosureButton{width:auto;max-width:100%}.Nr89iW_flowCell[data-flow-summary] .Nr89iW_foldSummary,.Nr89iW_closedProcessSummary .Nr89iW_foldSummary{min-width:0}.Nr89iW_turnProcessSticky>.Nr89iW_disclosure{flex:auto;min-width:0}.Nr89iW_disclosureButton{width:max-content;max-width:calc(100% + 6px)}.Nr89iW_statusText{flex:0 auto}.Nr89iW_think{width:max-content;min-width:0}.Nr89iW_thinkSizer{white-space:normal;overflow-wrap:anywhere}.Nr89iW_thinkText{white-space:normal;overflow-wrap:anywhere;text-overflow:clip;overflow:visible}.Nr89iW_toolbar,.Nr89iW_turnStickyLanes,.Nr89iW_turnProcessSticky,.Nr89iW_liveFoldContainer,.Nr89iW_flowCell[data-flow-summary],.Nr89iW_closedProcessSummary{background-color:canvas;background-image:var(--reader-lane-plate);background-repeat:no-repeat}.Nr89iW_root[data-reader-glass] .Nr89iW_toolbar,.Nr89iW_root[data-reader-glass] .Nr89iW_turnProcessSticky,.Nr89iW_root[data-reader-glass] .Nr89iW_liveFoldContainer{-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px);box-shadow:none;background:0 0;border:0;border-radius:0}.Nr89iW_root[data-reader-glass] .Nr89iW_toolbar,.Nr89iW_root[data-reader-glass] .Nr89iW_turnProcessSticky{-webkit-backdrop-filter:none;backdrop-filter:none}.Nr89iW_root[data-reader-glass] .Nr89iW_toolbar{pointer-events:none}.Nr89iW_root[data-reader-glass] .Nr89iW_toolbar>.Nr89iW_textButton,.Nr89iW_root[data-reader-glass] .Nr89iW_turnProcessSticky .Nr89iW_disclosureButton{pointer-events:auto;background:color-mix(in srgb, var(--dsw-alias-bg-layer-1,#ffffffb3) 80%, transparent);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);border-radius:999px;padding:2px 10px}.Nr89iW_root[data-reader-glass] .Nr89iW_turnProcessSticky .Nr89iW_disclosureButton{max-width:100%;margin-left:0}.Nr89iW_root[data-reader-glass] .Nr89iW_toolbar>.Nr89iW_textButton:hover,.Nr89iW_root[data-reader-glass] .Nr89iW_turnProcessSticky .Nr89iW_disclosureButton:hover{background:var(--dsw-alias-interactive-bg-hover)}.Nr89iW_root[data-reader-glass] .Nr89iW_flowCell[data-flow-summary],.Nr89iW_root[data-reader-glass] .Nr89iW_closedProcessSummary{box-shadow:none;z-index:auto;border-left:2px solid color-mix(in srgb, var(--dsw-alias-border-l2,#80808059) 80%, transparent);padding-block:2px;background:0 0;border-radius:0;min-height:32px;padding-left:10px;position:static}.Nr89iW_root[data-reader-glass] .Nr89iW_turnStickyLanes{z-index:auto;display:contents;position:static;top:auto}.Nr89iW_root[data-reader-glass] .Nr89iW_turnStickyRegion{--reader-code-summary-height:0px}.Nr89iW_root[data-reader-glass] .Nr89iW_turnStickyLanes .Nr89iW_turnProcessSticky{top:var(--reader-toolbar-height,var(--reader-lane-block,40px));z-index:6;position:sticky}.Nr89iW_root[data-reader-glass] .Nr89iW_user{background:color-mix(in srgb, var(--dsw-specific-bubble,#00000014) 25%, transparent);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);border:1px solid color-mix(in srgb, var(--dsw-alias-border-l1,#8080804d) 30%, transparent)}.Nr89iW_root[data-reader-glass] .Nr89iW_reasonCard{border-color:color-mix(in srgb, var(--dsw-alias-border-l1,#80808059) 65%, transparent);background:0 0}.Nr89iW_root[data-reader-glass] .Nr89iW_toolDetails,.Nr89iW_root[data-reader-glass] .Nr89iW_notice,.Nr89iW_root[data-reader-glass] .Nr89iW_unknown,.Nr89iW_root[data-reader-glass] .Nr89iW_toolRaw,.Nr89iW_root[data-reader-glass] .Nr89iW_systemPrompt,.Nr89iW_root[data-reader-glass] .Nr89iW_compactionSummaryBox,.Nr89iW_root[data-reader-glass] .Nr89iW_attention,.Nr89iW_root[data-reader-glass] .Nr89iW_imageFrame,.Nr89iW_root[data-reader-glass] .Nr89iW_imageDialog{background:0 0}.Nr89iW_root[data-reader-glass] .Nr89iW_diffOverlay{background:color-mix(in srgb, var(--dsw-alias-bg-module-platform,#7f7f7f1a) 20%, transparent);-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px)}.Nr89iW_root[data-reader-glass] .Nr89iW_diffScrollArea{background:0 0}.Nr89iW_root[data-reader-glass] .Nr89iW_diffTab{background:color-mix(in srgb, var(--dsw-alias-bg-base,#fffc) 25%, transparent)}.Nr89iW_root[data-reader-glass] .Nr89iW_diffTab[data-active]{background:color-mix(in srgb, var(--dsw-alias-bg-base,#fff) 45%, transparent)}:is(.Nr89iW_root[data-reader-glass] .md-code-block,.Nr89iW_root[data-reader-glass] [data-diff]){border:1px solid color-mix(in srgb, var(--dsw-alias-border-l1,#80808033) 30%, transparent);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);background:color-mix(in srgb, var(--dsw-alias-markdown-code-block,#0000000f) 25%, transparent)!important}.Nr89iW_root[data-reader-glass] .Nr89iW_foldControl{background:color-mix(in srgb, var(--dsw-alias-bg-module-platform,#7f7f7f1a) 25%, transparent);border:1px solid color-mix(in srgb, var(--dsw-alias-border-l2,#80808033) 30%, transparent)}.Nr89iW_root[data-reader-glass] .Nr89iW_foldStop[data-on]{background:color-mix(in srgb, var(--dsw-alias-bg-base,#fff) 35%, transparent)}.Nr89iW_root[data-reader-glass] .Nr89iW_compactionPill,.Nr89iW_root[data-reader-glass] .Nr89iW_deliverableChip,.Nr89iW_root[data-reader-glass] .Nr89iW_toolState,.Nr89iW_root[data-reader-glass] .Nr89iW_diffStatButton{background:0 0;border-color:#0000}.Nr89iW_root[data-reader-glass] .Nr89iW_compactionPill:hover,.Nr89iW_root[data-reader-glass] .Nr89iW_compactionPill:focus-visible,.Nr89iW_root[data-reader-glass] .Nr89iW_deliverableChip:hover,.Nr89iW_root[data-reader-glass] .Nr89iW_deliverableChip:focus-within,.Nr89iW_root[data-reader-glass] .Nr89iW_toolState:hover,.Nr89iW_root[data-reader-glass] .Nr89iW_diffStatButton:hover,.Nr89iW_root[data-reader-glass] .Nr89iW_diffStatButton:focus-visible,.Nr89iW_root[data-reader-glass] .Nr89iW_diffStatButton[aria-expanded=true]{background:var(--dsw-alias-bg-module-platform,#7f7f7f1a);border-color:var(--dsw-alias-border-l2,#7f7f7f47)}html body[data-dsh-claude-style][data-dsh-claude-composer-active] [data-dsh-claude-composer-hidden]:has([data-dsh-better-display]) [data-composer-seat]{display:flex!important}"; const tagId$5 = "dsh-better-chat/Reader.module.css"; if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$5) + "]") === null) { const tag = document.createElement("style"); tag.dataset.plugin = "dsh-better-chat"; tag.dataset.pluginCss = tagId$5; tag.textContent = css$5; document.head.appendChild(tag); } var Reader_module_css_default = { "actionIcon": "Nr89iW_actionIcon", "answer": "Nr89iW_answer", "answerActions": "Nr89iW_answerActions", "attention": "Nr89iW_attention", "blocks": "Nr89iW_blocks", "chevron": "Nr89iW_chevron", "chipActionBtn": "Nr89iW_chipActionBtn", "chipActions": "Nr89iW_chipActions", "chipMain": "Nr89iW_chipMain", "choreographedFlow": "Nr89iW_choreographedFlow", "closedProcessSummary": "Nr89iW_closedProcessSummary", "column": "Nr89iW_column", "commandInput": "Nr89iW_commandInput", "compactionButton": "Nr89iW_compactionButton", "compactionDial": "Nr89iW_compactionDial", "compactionIcon": "Nr89iW_compactionIcon", "compactionLine": "Nr89iW_compactionLine", "compactionLineIn": "Nr89iW_compactionLineIn", "compactionPill": "Nr89iW_compactionPill", "compactionPillIn": "Nr89iW_compactionPillIn", "compactionRow": "Nr89iW_compactionRow", "compactionSummaryBox": "Nr89iW_compactionSummaryBox", "compactionSummaryHeader": "Nr89iW_compactionSummaryHeader", "compactionToggle": "Nr89iW_compactionToggle", "deliverableChip": "Nr89iW_deliverableChip", "deliverableIcon": "Nr89iW_deliverableIcon", "deliverableName": "Nr89iW_deliverableName", "deliverablesLabel": "Nr89iW_deliverablesLabel", "deliverablesLane": "Nr89iW_deliverablesLane", "deliverablesMore": "Nr89iW_deliverablesMore", "deliverablesRoot": "Nr89iW_deliverablesRoot", "deliverablesRow": "Nr89iW_deliverablesRow", "deliverablesShowFolder": "Nr89iW_deliverablesShowFolder", "detail": "Nr89iW_detail", "dialogClose": "Nr89iW_dialogClose", "diffAdded": "Nr89iW_diffAdded", "diffCaret": "Nr89iW_diffCaret", "diffEmpty": "Nr89iW_diffEmpty", "diffHunkBody": "Nr89iW_diffHunkBody", "diffLineAdded": "Nr89iW_diffLineAdded", "diffLineRemoved": "Nr89iW_diffLineRemoved", "diffLines": "Nr89iW_diffLines", "diffOverlay": "Nr89iW_diffOverlay", "diffOverlayRow": "Nr89iW_diffOverlayRow", "diffPath": "Nr89iW_diffPath", "diffRemoved": "Nr89iW_diffRemoved", "diffScrollArea": "Nr89iW_diffScrollArea", "diffStat": "Nr89iW_diffStat", "diffStatButton": "Nr89iW_diffStatButton", "diffStatRoot": "Nr89iW_diffStatRoot", "diffTab": "Nr89iW_diffTab", "diffTabs": "Nr89iW_diffTabs", "disclosure": "Nr89iW_disclosure", "disclosureBody": "Nr89iW_disclosureBody", "disclosureButton": "Nr89iW_disclosureButton", "dsh-turn-status-shimmer": "Nr89iW_dsh-turn-status-shimmer", "empty": "Nr89iW_empty", "error": "Nr89iW_error", "errorCode": "Nr89iW_errorCode", "errorCopy": "Nr89iW_errorCopy", "errorIcon": "Nr89iW_errorIcon", "errorMessage": "Nr89iW_errorMessage", "errorTitle": "Nr89iW_errorTitle", "flowCell": "Nr89iW_flowCell", "flowCellInner": "Nr89iW_flowCellInner", "foldControl": "Nr89iW_foldControl", "foldStop": "Nr89iW_foldStop", "foldSummary": "Nr89iW_foldSummary", "foldSummaryPart": "Nr89iW_foldSummaryPart", "historyButton": "Nr89iW_historyButton", "iconButton": "Nr89iW_iconButton", "imageDialog": "Nr89iW_imageDialog", "imageFigure": "Nr89iW_imageFigure", "imageFrame": "Nr89iW_imageFrame", "imageOpen": "Nr89iW_imageOpen", "imagePlaceholder": "Nr89iW_imagePlaceholder", "isEnterStart": "Nr89iW_isEnterStart", "isExit": "Nr89iW_isExit", "jump": "Nr89iW_jump", "jumpDock": "Nr89iW_jumpDock", "liveFoldContainer": "Nr89iW_liveFoldContainer", "liveFoldElastic": "Nr89iW_liveFoldElastic", "liveFoldImpact": "Nr89iW_liveFoldImpact", "liveFoldPulse": "Nr89iW_liveFoldPulse", "mainFlow": "Nr89iW_mainFlow", "messageClock": "Nr89iW_messageClock", "meta": "Nr89iW_meta", "morphCluster": "Nr89iW_morphCluster", "morphDrawer": "Nr89iW_morphDrawer", "nativeToolRow": "Nr89iW_nativeToolRow", "nativeToolSummary": "Nr89iW_nativeToolSummary", "notice": "Nr89iW_notice", "numberRollDigit": "Nr89iW_numberRollDigit", "numberRollEnter": "Nr89iW_numberRollEnter", "numberRollExit": "Nr89iW_numberRollExit", "numberRollIn": "Nr89iW_numberRollIn", "numberRollOut": "Nr89iW_numberRollOut", "numberRollRoot": "Nr89iW_numberRollRoot", "numberRollSizer": "Nr89iW_numberRollSizer", "pendingImage": "Nr89iW_pendingImage", "priorFoldDrawer": "Nr89iW_priorFoldDrawer", "processContents": "Nr89iW_processContents", "processFootnote": "Nr89iW_processFootnote", "processFrame": "Nr89iW_processFrame", "processItem": "Nr89iW_processItem", "processLabel": "Nr89iW_processLabel", "processMeta": "Nr89iW_processMeta", "processMetaInner": "Nr89iW_processMetaInner", "processMetaLine": "Nr89iW_processMetaLine", "processSeamRow": "Nr89iW_processSeamRow", "readerRunningGlow": "Nr89iW_readerRunningGlow", "readerStepShimmer": "Nr89iW_readerStepShimmer", "readingText": "Nr89iW_readingText", "reasonAction": "Nr89iW_reasonAction", "reasonCaption": "Nr89iW_reasonCaption", "reasonCard": "Nr89iW_reasonCard", "reasonFooter": "Nr89iW_reasonFooter", "reasonHeading": "Nr89iW_reasonHeading", "reasonLabel": "Nr89iW_reasonLabel", "reasonPlain": "Nr89iW_reasonPlain", "reasonText": "Nr89iW_reasonText", "reasonTrack": "Nr89iW_reasonTrack", "reasonViewport": "Nr89iW_reasonViewport", "retiringContent": "Nr89iW_retiringContent", "root": "Nr89iW_root", "rowSeparator": "Nr89iW_rowSeparator", "srOnly": "Nr89iW_srOnly", "statusIcon": "Nr89iW_statusIcon", "statusText": "Nr89iW_statusText", "stopped": "Nr89iW_stopped", "streamAtom": "Nr89iW_streamAtom", "streamInlineWord": "Nr89iW_streamInlineWord", "streamWord": "Nr89iW_streamWord", "summaryRow": "Nr89iW_summaryRow", "systemPrompt": "Nr89iW_systemPrompt", "textButton": "Nr89iW_textButton", "think": "Nr89iW_think", "thinkShimmer": "Nr89iW_thinkShimmer", "thinkSizer": "Nr89iW_thinkSizer", "thinkText": "Nr89iW_thinkText", "tool": "Nr89iW_tool", "toolActivity": "Nr89iW_toolActivity", "toolbar": "Nr89iW_toolbar", "toolChildren": "Nr89iW_toolChildren", "toolDetailNote": "Nr89iW_toolDetailNote", "toolDetails": "Nr89iW_toolDetails", "toolDocument": "Nr89iW_toolDocument", "toolElapsed": "Nr89iW_toolElapsed", "toolEngine": "Nr89iW_toolEngine", "toolGlyph": "Nr89iW_toolGlyph", "toolHeading": "Nr89iW_toolHeading", "toolHeadingCopy": "Nr89iW_toolHeadingCopy", "toolHeadingState": "Nr89iW_toolHeadingState", "toolLedger": "Nr89iW_toolLedger", "toolPanel": "Nr89iW_toolPanel", "toolRaw": "Nr89iW_toolRaw", "toolRawLabel": "Nr89iW_toolRawLabel", "toolReceipt": "Nr89iW_toolReceipt", "toolState": "Nr89iW_toolState", "toolTabs": "Nr89iW_toolTabs", "toolTarget": "Nr89iW_toolTarget", "toolTitle": "Nr89iW_toolTitle", "turn": "Nr89iW_turn", "turnProcessSticky": "Nr89iW_turnProcessSticky", "turnStatus": "Nr89iW_turnStatus", "turnStatusClock": "Nr89iW_turnStatusClock", "turnStatusLabel": "Nr89iW_turnStatusLabel", "turnStickyLanes": "Nr89iW_turnStickyLanes", "turnStickyRegion": "Nr89iW_turnStickyRegion", "unknown": "Nr89iW_unknown", "user": "Nr89iW_user", "userActions": "Nr89iW_userActions", "userCluster": "Nr89iW_userCluster", "userImages": "Nr89iW_userImages", "waitClock": "Nr89iW_waitClock", "waitOvertime": "Nr89iW_waitOvertime", "waitSeconds": "Nr89iW_waitSeconds" }; // src/client/word-motion.tsx const WordScope = (0, react.createContext)({ enabled: false, generation: 0 }); const CODE_LABELS = { copyLabel: "复制代码", copiedLabel: "已复制" }; function useSourceReveal(element, born, generation) { const scope = (0, react.useContext)(WordScope); const cancelled = (0, react.useRef)(false); (0, react.useLayoutEffect)(() => { const target = element.current; if (!target) return; target.dataset.wordState = "settled"; if (!scope.enabled || scope.generation !== generation) { cancelled.current = true; return; } if (cancelled.current || born === null || document.hidden) return; if (Number(document.timeline.currentTime ?? performance.now()) - born >= WORD_MOTION.duration || typeof target.animate !== "function") return; const animation = target.animate([{ opacity: 0, filter: `blur(${WORD_MOTION.blur}px)` }, { opacity: 1, filter: "blur(0px)" }], { duration: WORD_MOTION.duration, easing: WORD_MOTION.easing, fill: "backwards" }); animation.startTime = born; target.dataset.wordState = "resolving"; const finish = () => { animation.cancel(); target.dataset.wordState = "settled"; document.removeEventListener("visibilitychange", hidden); }; animation.onfinish = finish; const hidden = () => { if (document.hidden) { cancelled.current = true; finish(); } }; document.addEventListener("visibilitychange", hidden); return () => { animation.cancel(); document.removeEventListener("visibilitychange", hidden); target.dataset.wordState = "settled"; }; }, [ element, born, generation, scope.enabled, scope.generation ]); } function Word({ children, born, generation, offset, inline }) { const element = (0, react.useRef)(null); useSourceReveal(element, born, generation); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { ref: element, className: inline ? Reader_module_css_default.streamInlineWord : Reader_module_css_default.streamWord, "data-reader-word": true, "data-source-start": offset, "data-source-birth": born ?? void 0, children }); } /** A native code block enters on the same clock, without rebuilding its text. */ function MotionAtom({ children, born, generation, offset }) { const element = (0, react.useRef)(null); useSourceReveal(element, born, generation); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref: element, className: Reader_module_css_default.streamAtom, "data-reader-atom": true, "data-source-start": offset, "data-source-birth": born ?? void 0, children }); } /** Native Think is literal text, not Markdown. Spans never alter its bytes. */ function MotionPlainText({ text, enabled, revision }) { const timeline = (0, react.useRef)(); timeline.current ??= new WordTimeline(); timeline.current.begin(text, enabled, revision, Number(document.timeline.currentTime ?? performance.now())); const current = timeline.current; const generation = current.generation; const scope = (0, react.useMemo)(() => ({ enabled, generation }), [enabled, generation]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WordScope.Provider, { value: scope, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.reasonPlain, children: current.hasLiveText ? current.words(text, 0).map((word) => word.text.trim() ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Word, { born: word.born, generation, offset: word.key, inline: true, children: word.text }, word.key) : word.text) : text }) }); } /** Native DSH Markdown semantics with a stable text-leaf animation hook. */ function MotionMarkdown({ text, streaming, enabled, revision, fileMentions }) { const timeline = (0, react.useRef)(); timeline.current ??= new WordTimeline(); timeline.current.begin(text, enabled, revision, Number(document.timeline.currentTime ?? performance.now())); const generation = timeline.current.generation; const scope = (0, react.useMemo)(() => ({ enabled, generation }), [enabled, generation]); const renderText = (0, react.useMemo)(() => (value, offset, inline = false) => { const current = timeline.current; if (!current.hasLiveText) return value; return current.words(value, offset).map((word) => word.text.trim() ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Word, { born: word.born, generation: current.generation, offset: word.key, inline: inline || /^\p{P}+$/u.test(word.text), children: word.text }, word.key) : word.text); }, []); const renderAtom = (0, react.useMemo)(() => (children, offset) => { const current = timeline.current; return current.hasLiveText ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MotionAtom, { born: current.bornAt(offset), generation: current.generation, offset, children }) : children; }, []); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WordScope.Provider, { value: scope, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MarkdownText$2, { text, streaming, codeLabels: CODE_LABELS, fileMentions, pathImages: readerPathImages, renderText, renderAtom }) }); } // src/client/text-transform.ts /** * Cordis service name. Another client plugin lists this in `inject` and * registers a transformer. The reading view paints the result. The session * block, transcript, and fold inputs stay on the original text. */ const TEXT_TRANSFORM_SERVICE = "dsh-better-display.text-transform"; const KINDS = /* @__PURE__ */ new Set(["reasoning", "body"]); function isKind(value) { return KINDS.has(value); } function reportTransformError(error) { console.warn("[dsh-better-display] text transform failed; showing original text", error); } function passthrough(request) { return { text: request.text, final: !request.streaming, transformRevision: 0, motionRevision: 0 }; } function normalize(value, request) { if (typeof value === "string") return { text: value, final: !request.streaming }; if (!value || typeof value.text !== "string") return { text: request.text, final: !request.streaming }; return { text: value.text, final: typeof value.final === "boolean" ? value.final : !request.streaming }; } /** * Appends keep the motion revision. A replacement gets a new one so the * timeline treats the swapped string as already settled. */ function nextDisplayCursor(previous, display) { if (!previous) return { ...display, transformRevision: 0, motionRevision: 0 }; if (previous.text === display.text && previous.final === display.final) return previous; const appended = display.text.startsWith(previous.text); return { text: display.text, final: display.final, transformRevision: previous.transformRevision + 1, motionRevision: appended ? previous.motionRevision : previous.motionRevision + 1 }; } /** * Streaming flag fed to the reveal. With no transformer this is the model's * flag. A transformer that reports `final: !streaming` produces the same flag. */ function displayStreaming(sourceStreaming, shown, active) { return active ? !shown.final : sourceStreaming; } var TextTransformRegistryImpl = class { stacks = /* @__PURE__ */ new Map(); listeners = /* @__PURE__ */ new Map(); cursors = /* @__PURE__ */ new Map(); register(kind, transformer) { const requested = [...new Set(Array.isArray(kind) ? kind : [kind])]; for (const item of requested) if (!isKind(item)) throw new Error(`Unknown display text kind: ${String(item)}`); const bound = []; for (const item of requested) { const entry = { transformer }; try { entry.unsubscribe = transformer.subscribe?.(() => { this.emit(item); }); } catch (error) { reportTransformError(error); } const stack = this.stacks.get(item) ?? []; stack.push(entry); this.stacks.set(item, stack); bound.push({ kind: item, entry }); this.emit(item); } return () => { for (const { kind: item, entry } of bound) { try { entry.unsubscribe?.(); } catch (error) { reportTransformError(error); } const stack = this.stacks.get(item); if (!stack) continue; const next = stack.filter((candidate) => candidate !== entry); if (next.length > 0) this.stacks.set(item, next); else this.stacks.delete(item); this.emit(item); } }; } has(kind) { return (this.stacks.get(kind)?.length ?? 0) > 0; } read(request) { const transformer = this.stacks.get(request.kind)?.at(-1)?.transformer; if (!transformer) return passthrough(request); let display; try { display = normalize(transformer.read(request), request); } catch (error) { reportTransformError(error); display = { text: request.text, final: !request.streaming }; } const key = `${request.kind}\u0000${request.blockKey}`; const next = nextDisplayCursor(this.cursors.get(key), display); this.cursors.set(key, next); return next; } subscribe(kind, listener) { const set = this.listeners.get(kind) ?? /* @__PURE__ */ new Set(); set.add(listener); this.listeners.set(kind, set); return () => { set.delete(listener); }; } release(kind, blockKey) { this.cursors.delete(`${kind}\u0000${blockKey}`); } emit(kind) { const set = this.listeners.get(kind); if (!set) return; for (const listener of [...set]) listener(); } }; function createTextTransformRegistry() { return new TextTransformRegistryImpl(); } let active; /** Points the reading view at the registry this client plugin provides. */ function installTextTransformRegistry(registry) { const previous = active; active = registry; return () => { active = previous; }; } function activeTextTransform() { return active; } /** * Subscribe while mounted. The reveal components call this only after * `has(kind)`, so an empty registry adds no hook and no listener. */ function useDisplayText(registry, request) { const [epoch, setEpoch] = (0, react.useState)(0); const { text, streaming, blockKey, kind, source } = request; (0, react.useEffect)(() => registry.subscribe(kind, () => { setEpoch((value) => value + 1); }), [registry, kind]); (0, react.useEffect)(() => () => { registry.release(kind, blockKey); }, [ registry, kind, blockKey ]); return (0, react.useMemo)(() => registry.read({ text, streaming, blockKey, kind, source }), [ registry, text, streaming, blockKey, kind, source, epoch ]); } /** Chain-slot owner. Extra fields are optional so older callers still type-check. */ function readerBlockOwner(block, streaming, source, presentation, holdFormatting) { return { block, streaming, source, presentation: { startedAt: presentation.startedAt, interrupted: presentation.interrupted, liveText: presentation.liveText }, holdFormatting, liveText: presentation.liveText }; } /** Copy actions read this. Display text never replaces it. */ function originalAnswerText(blocks) { return blocks.flatMap((block) => block.kind === "text" && typeof block.text === "string" ? [block.text] : []).join("\n\n"); } // \0dshx-css-module:src/client/TurnMetrics.module.css.mjs const css$4 = ".Dds6gq_container{color:var(--dsw-alias-label-tertiary);align-items:center;gap:2px;font-size:13px;line-height:24px;display:inline-flex;position:relative}.Dds6gq_pillButton{border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-tertiary);cursor:pointer;border-radius:12px;outline:none;align-items:center;gap:5px;padding:2px 8px;font-family:inherit;font-size:11px;transition:all .14s;display:inline-flex}.Dds6gq_pillButton:hover,.Dds6gq_pillButton[data-active=true]{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-border-l2);background:var(--dsw-alias-interactive-bg-hover)}.Dds6gq_timeButton{height:28px;color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;white-space:nowrap;cursor:pointer;background:0 0;border:none;border-radius:28px;align-items:center;gap:4px;padding:6px 8px;font-family:inherit;font-size:13px;line-height:24px;display:inline-flex}.Dds6gq_timeButton:hover,.Dds6gq_timeButton[data-active=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}.Dds6gq_pillIcon{opacity:.8;flex:none;width:12px;height:12px}.Dds6gq_metricsPop{background:var(--dsw-alias-bg-base);border:1px solid var(--dsw-alias-border-l2);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);z-index:50;text-align:left;border-radius:10px;flex-direction:column;gap:8px;width:260px;padding:12px 14px;animation:.14s ease-out Dds6gq_popIn;display:flex;position:absolute;bottom:calc(100% + 8px);left:0;box-shadow:0 6px 20px #00000024}@keyframes Dds6gq_popIn{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.Dds6gq_popHeader{color:var(--dsw-alias-label-primary);border-bottom:1px solid var(--dsw-alias-border-l1);justify-content:space-between;align-items:center;padding-bottom:6px;font-size:12px;font-weight:600;display:flex}.Dds6gq_popSection{flex-direction:column;gap:4px;display:flex}.Dds6gq_popSectionTitle{text-transform:uppercase;letter-spacing:.5px;color:var(--dsw-alias-label-tertiary);margin-top:2px;font-size:10px;font-weight:600}.Dds6gq_popGrid{grid-template-columns:1fr auto;gap:3px 12px;font-size:11px;line-height:18px;display:grid}.Dds6gq_popLabel{color:var(--dsw-alias-label-secondary)}.Dds6gq_popValue{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;text-align:right;font-weight:500}.Dds6gq_popBadge{background:var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);border-radius:3px;margin-left:4px;padding:0 4px;font-size:10px}"; const tagId$4 = "dsh-better-chat/TurnMetrics.module.css"; if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$4) + "]") === null) { const tag = document.createElement("style"); tag.dataset.plugin = "dsh-better-chat"; tag.dataset.pluginCss = tagId$4; tag.textContent = css$4; document.head.appendChild(tag); } var TurnMetrics_module_css_default = { "container": "Dds6gq_container", "metricsPop": "Dds6gq_metricsPop", "pillButton": "Dds6gq_pillButton", "pillIcon": "Dds6gq_pillIcon", "popBadge": "Dds6gq_popBadge", "popGrid": "Dds6gq_popGrid", "popHeader": "Dds6gq_popHeader", "popIn": "Dds6gq_popIn", "popLabel": "Dds6gq_popLabel", "popSection": "Dds6gq_popSection", "popSectionTitle": "Dds6gq_popSectionTitle", "popValue": "Dds6gq_popValue", "timeButton": "Dds6gq_timeButton" }; // src/client/TurnMetrics.tsx function formatTokens(count) { if (count >= 1e6) return `${(count / 1e6).toFixed(2)}M tok`; if (count >= 1e3) return `${(count / 1e3).toFixed(1)}k tok`; return `${count} tok`; } const TurnMetrics = (0, react.memo)(function TurnMetrics({ usage, runMs, tokensPerSecond, ttftMs }) { const [open, setOpen] = (0, react.useState)(false); const containerRef = (0, react.useRef)(null); (0, react.useEffect)(() => { if (!open) return; const onClickOutside = (e) => { if (containerRef.current && !containerRef.current.contains(e.target)) setOpen(false); }; const onKeyDown = (e) => { if (e.key === "Escape") setOpen(false); }; document.addEventListener("pointerdown", onClickOutside); document.addEventListener("keydown", onKeyDown); return () => { document.removeEventListener("pointerdown", onClickOutside); document.removeEventListener("keydown", onKeyDown); }; }, [open]); const totalTokens = usage?.totalTokens; const hasTiming = typeof runMs === "number" && runMs > 0; const hasTokens = typeof totalTokens === "number" && totalTokens > 0; if (!hasTiming && !hasTokens) return null; const cacheHitPercent = usage && usage.cacheReadTokens && usage.totalTokens > usage.outputTokens ? Math.round(usage.cacheReadTokens / (usage.totalTokens - usage.outputTokens) * 100) : null; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { ref: containerRef, className: TurnMetrics_module_css_default.container, children: [ hasTokens && typeof totalTokens === "number" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { type: "button", className: TurnMetrics_module_css_default.pillButton, "data-active": open, onClick: () => setOpen((v) => !v), "aria-expanded": open, title: "查看本轮 Token 消耗", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { className: TurnMetrics_module_css_default.pillIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ellipse", { cx: "8", cy: "4.2", rx: "5", ry: "2.2", strokeWidth: "1.2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 4.2v7.6c0 1.2 2.2 2.2 5 2.2s5-1 5-2.2V4.2", strokeWidth: "1.2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 8c0 1.2 2.2 2.2 5 2.2s5-1 5-2.2", strokeWidth: "1.2" }) ] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: ["用量 ", formatTokens(totalTokens)] })] }), hasTiming && typeof runMs === "number" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { type: "button", className: TurnMetrics_module_css_default.timeButton, "data-active": open, onClick: () => setOpen((v) => !v), "aria-expanded": open, "aria-label": formatRanFor(runMs), title: "查看本轮用时和速度", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { className: TurnMetrics_module_css_default.pillIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", { cx: "8", cy: "8", r: "6.5", strokeWidth: "1.2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 4.5v3.8l2.5 1.5", strokeWidth: "1.2", strokeLinecap: "round", strokeLinejoin: "round" })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: formatRanFor(runMs) })] }), open && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: TurnMetrics_module_css_default.metricsPop, role: "dialog", "aria-label": "本轮概况", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: TurnMetrics_module_css_default.popHeader, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "本轮性能与用量概况" }) }), hasTiming && typeof runMs === "number" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: TurnMetrics_module_css_default.popSection, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: TurnMetrics_module_css_default.popSectionTitle, children: "耗时与生成速度" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: TurnMetrics_module_css_default.popGrid, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: TurnMetrics_module_css_default.popLabel, children: "总用时" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: TurnMetrics_module_css_default.popValue, children: formatRunDuration(runMs) }), typeof tokensPerSecond === "number" && tokensPerSecond > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: TurnMetrics_module_css_default.popLabel, children: "生成吞吐 (TPS)" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popValue, children: [tokensPerSecond.toFixed(1), " tok/s"] })] }), typeof ttftMs === "number" && ttftMs > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: TurnMetrics_module_css_default.popLabel, children: "首字延迟 (TTFT)" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popValue, children: [(ttftMs / 1e3).toFixed(2), "s"] })] }) ] })] }), hasTokens && usage && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: TurnMetrics_module_css_default.popSection, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: TurnMetrics_module_css_default.popSectionTitle, children: "Token 消耗分解" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: TurnMetrics_module_css_default.popGrid, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: TurnMetrics_module_css_default.popLabel, children: "总消耗" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popValue, children: [usage.totalTokens.toLocaleString(), " tok"] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popLabel, children: ["输入", cacheHitPercent !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popBadge, children: [ "命中 ", cacheHitPercent, "%" ] })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popValue, children: [(usage.totalTokens - usage.outputTokens).toLocaleString(), " tok"] }), typeof usage.cacheReadTokens === "number" && usage.cacheReadTokens > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: TurnMetrics_module_css_default.popLabel, children: "缓存读取" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popValue, children: [usage.cacheReadTokens.toLocaleString(), " tok"] })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popLabel, children: ["输出", typeof usage.reasoningTokens === "number" && usage.reasoningTokens > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popBadge, children: ["思考 ", usage.reasoningTokens.toLocaleString()] })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: TurnMetrics_module_css_default.popValue, children: [usage.outputTokens?.toLocaleString() ?? 0, " tok"] }) ] })] }) ] }) ] }); }); // src/client/Blocks.tsx const IMAGE_TYPES = /* @__PURE__ */ new Set([ "image/png", "image/jpeg", "image/webp", "image/gif" ]); var BlockBoundary = class extends react.Component { state = { failed: false, detail: "" }; static getDerivedStateFromError(error) { return { failed: true, detail: String(error?.message ?? error).slice(0, 160) }; } render() { return this.state.failed ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.notice, children: ["此内容暂时无法在阅读页显示;原对话中的记录未受影响。", /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { "data-reader-block-error": true, style: { opacity: .65 }, children: [ "(", this.state.detail, ")" ] })] }) : this.props.children; } }; const ImageBlock = (0, react.memo)(function ImageBlock({ attachment, loadImage }) { const [attempt, setAttempt] = (0, react.useState)(0); const [url, setUrl] = (0, react.useState)(null); const [error, setError] = (0, react.useState)(false); const [decoded, setDecoded] = (0, react.useState)(false); const dialog = (0, react.useRef)(null); const opener = (0, react.useRef)(null); (0, react.useEffect)(() => { let active = true; let owned = null; const timeout = setTimeout(() => { if (active) { setError(true); active = false; } }, 2e4); setError(false); setDecoded(false); setUrl(null); loadImage(attachment).then((result) => { if (!active) return; clearTimeout(timeout); if (!IMAGE_TYPES.has(result.mediaType)) throw new Error("Unsupported image media type"); const bytes = Uint8Array.from(result.data); owned = URL.createObjectURL(new Blob([bytes.buffer], { type: result.mediaType })); setUrl(owned); }).catch(() => { clearTimeout(timeout); if (active) setError(true); }); return () => { active = false; clearTimeout(timeout); if (owned) URL.revokeObjectURL(owned); }; }, [ attachment.attachmentId, attempt, loadImage ]); const width = Number.isFinite(attachment.width) && attachment.width > 0 ? attachment.width : 4; const height = Number.isFinite(attachment.height) && attachment.height > 0 ? attachment.height : 3; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("figure", { className: Reader_module_css_default.imageFigure, "data-reader-image": true, "data-image-state": error ? "error" : decoded ? "ready" : "loading", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.imageFrame, style: { aspectRatio: `${width} / ${height}` }, children: [!error && url && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { ref: opener, type: "button", className: Reader_module_css_default.imageOpen, "aria-label": `放大图片${attachment.name ? `:${attachment.name}` : ""}`, onClick: () => dialog.current?.showModal(), children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", { src: url, alt: attachment.name ?? "会话图片", width, height, onLoad: () => setDecoded(true), onError: () => setError(true), "data-ready": decoded }) }), (!decoded || error) && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.imagePlaceholder, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: error ? "图片未能加载" : "正在加载图片" }), error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.textButton, onClick: () => setAttempt((value) => value + 1), children: "重试" })] })] }), attachment.name && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("figcaption", { children: attachment.name }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("dialog", { ref: dialog, className: Reader_module_css_default.imageDialog, "aria-label": "图片预览", onClose: () => opener.current?.focus(), onClick: (event) => { if (event.target === dialog.current) dialog.current?.close(); }, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", autoFocus: true, className: Reader_module_css_default.dialogClose, "aria-label": "关闭图片预览", onClick: () => dialog.current?.close(), children: "×" }), url && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", { src: url, alt: attachment.name ?? "会话图片" })] }) ] }); }); function contentBlocks(content) { return content.map((block) => { if (block.type === "text") return { kind: "text", text: block.text }; if (block.type === "image") return { kind: "image", attachment: block.attachment }; return { kind: "other", block }; }); } function MarkdownStream({ text, streaming, holdFormatting, startedAt, interrupted = false, liveText = false, kind = "body", fileMentions, transformed = false }) { const root = (0, react.useRef)(null); const presentation = useStreamingText(text, streaming, { startedAt, interrupted: interrupted || !liveText, selected: holdFormatting }); const committedMode = (0, react.useRef)(streaming); const effectiveMode = holdFormatting ? committedMode.current : presentation.formatStreaming; (0, react.useLayoutEffect)(() => { committedMode.current = effectiveMode; }, [effectiveMode]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref: root, className: Reader_module_css_default.readingText, "data-reader-text": true, "data-reader-text-kind": kind, "data-received-length": text.length, "data-shown-length": presentation.text.length, "data-presentation-pending": presentation.pending || void 0, "data-motion-style": "opacity-blur", "data-ud-motion": "reader-text-arrival", "data-ud-motion-type": "reveal", "data-ud-motion-no-flash": "true", "data-text-transform": transformed ? streaming ? "live" : "final" : void 0, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MotionMarkdown, { text: presentation.text, streaming: effectiveMode, enabled: liveText && presentation.reveal && effectiveMode, revision: presentation.revision, fileMentions }) }); } function TransformedMarkdown({ registry, blockKey, source, text, streaming, ...props }) { const shown = useDisplayText(registry, { text, streaming, blockKey, kind: "body", source }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MarkdownStream, { ...props, text: shown.text, streaming: displayStreaming(streaming, shown, true), transformed: true }); } function ReadingMarkdown({ blockKey, source, ...props }) { const registry = activeTextTransform(); if (registry?.has("body")) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TransformedMarkdown, { registry, blockKey, source, ...props }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MarkdownStream, { ...props }); } function ReasoningStream({ blockKey, text, streaming, holdFormatting, startedAt, interrupted = false, liveText = false, transformed = false }) { const presentation = useStreamingText(text, streaming, { startedAt, interrupted: interrupted || !liveText, selected: holdFormatting }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.readingText, "data-reader-text": true, "data-reader-text-kind": "reasoning", "data-reader-reasoning-block-key": blockKey, "data-received-length": text.length, "data-shown-length": presentation.text.length, "data-presentation-pending": presentation.pending || void 0, "data-motion-style": "opacity-blur", "data-ud-motion": "reader-text-arrival", "data-ud-motion-type": "reveal", "data-ud-motion-no-flash": "true", "data-text-transform": transformed ? streaming ? "live" : "final" : void 0, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MotionPlainText, { text: presentation.text, enabled: liveText && presentation.reveal, revision: presentation.revision }) }); } function TransformedReasoning({ registry, blockKey, source, text, streaming, ...props }) { const shown = useDisplayText(registry, { text, streaming, blockKey, kind: "reasoning", source }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ReasoningStream, { ...props, blockKey, text: shown.text, streaming: displayStreaming(streaming, shown, true), transformed: true }); } function ReadingReasoning({ blockKey, source, ...props }) { const registry = activeTextTransform(); if (registry?.has("reasoning")) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TransformedReasoning, { registry, blockKey, source, ...props }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ReasoningStream, { ...props, blockKey }); } function fallback(block, streaming, source, loadImage, fillComposer, holdFormatting, presentation, blockKey, fileMentions) { switch (block.kind) { case "text": return source === "user" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.MarkdownText, { text: block.text, labels: markdownLabels }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ReadingMarkdown, { text: block.text, streaming, holdFormatting, ...presentation, fileMentions, blockKey, source }); case "image": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ImageBlock, { attachment: block.attachment, loadImage }); case "reasoning": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ReadingReasoning, { text: block.text, streaming, holdFormatting, ...presentation, blockKey, source }); case "tool-call": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonBlock, { label: `工具参数 · ${block.name}`, payload: block.argsRaw, truncatedLabel: truncatedJsonLabel }); case "other": { const raw = block.block; if (raw && typeof raw === "object") { const item = raw; if ((item.type === "mcp-app" || item.type === "mcpapp" || item.type === "ui") && typeof item.html === "string") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(McpAppFrame, { html: item.html, title: typeof item.title === "string" ? item.title : void 0, fillComposer }); } return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.unknown, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "此内容类型尚未接入阅读页,原始内容已保留。" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonBlock, { label: "查看原始内容", payload: block.block, truncatedLabel: truncatedJsonLabel })] }); } } } const Blocks = (0, react.memo)(function Blocks({ blocks, streaming = false, source = "assistant", holdFormatting = false, startedAt, interrupted, liveText, renderSlotChain, loadImage, fillComposer, fileMentions }) { const reactId = (0, react.useId)(); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ComposerFillContext.Provider, { value: fillComposer, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.blocks, "data-streaming": streaming || void 0, children: blocks.map((block, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BlockBoundary, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: renderSlotChain("dsh-better-display.block", readerBlockOwner(block, streaming, source, { startedAt, interrupted, liveText }, holdFormatting), { fallback: fallback(block, streaming, source, loadImage, fillComposer, holdFormatting, { startedAt, interrupted, liveText }, `${reactId}:${index}:${block.kind}`, fileMentions) }) }) }, block.kind === "image" ? `image:${block.attachment.attachmentId}:${index}` : `${index}:${block.kind}`)) }) }); }); function CopyGlyph() { return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { viewBox: "0 0 16 16", width: "16", height: "16", "aria-hidden": "true", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", { x: "5", y: "5", width: "8", height: "8", rx: "1.5" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 10H2.8A.8.8 0 0 1 2 9.2V2.8a.8.8 0 0 1 .8-.8h6.4a.8.8 0 0 1 .8.8V3" })] }); } function useCopyReceipt() { const [receipt, setReceipt] = (0, react.useState)(""); const timer = (0, react.useRef)(null); (0, react.useEffect)(() => () => { if (timer.current) clearTimeout(timer.current); }, []); const copy = async (text) => { const accepted = await (0, _deepseek_ai_dsh_client_ui_primitives.writeClipboard)(text); setReceipt(accepted ? "已复制" : "未能复制,请手动选择文字"); if (timer.current) clearTimeout(timer.current); timer.current = setTimeout(() => setReceipt(""), 2e3); }; return { receipt, copy }; } function MessageClock({ time }) { return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("time", { className: Reader_module_css_default.messageClock, dateTime: new Date(time).toISOString(), children: formatMessageClock(time) }); } function CopyAnswer({ blocks, onFork, metrics, extraActions }) { const { receipt, copy } = useCopyReceipt(); const text = originalAnswerText(blocks); const endedAt = metrics?.endedAt; const hasMetrics = metrics !== void 0 && (metrics.usage !== void 0 || metrics.runMs !== void 0 || endedAt !== void 0); if (!text.trim() && !onFork && !hasMetrics) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.answerActions, children: [ text.trim() !== "" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.iconButton, "aria-label": "复制回答", title: "复制回答", onClick: () => { copy(text); }, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopyGlyph, {}) }), extraActions, onFork && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.iconButton, "aria-label": "以此处为基础创建分叉会话", title: "以此处为基础创建分叉会话 (Fork)", onClick: onFork, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { viewBox: "0 0 16 16", width: "14", height: "14", fill: "none", stroke: "currentColor", strokeWidth: "1.2", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", { cx: "4.5", cy: "3.5", r: "1.8" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", { cx: "4.5", cy: "12.5", r: "1.8" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", { cx: "11.5", cy: "5.5", r: "1.8" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4.5 5.5v5M4.5 8c2.5 0 4.5-1 7-2.5", strokeLinecap: "round" }) ] }) }), metrics && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TurnMetrics, { usage: metrics.usage, runMs: metrics.runMs, tokensPerSecond: metrics.tokensPerSecond, ttftMs: metrics.ttftMs }), endedAt !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessageClock, { time: endedAt }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { role: "status", className: Reader_module_css_default.meta, children: receipt }) ] }); } function UserMessageActions({ text, time }) { const { receipt, copy } = useCopyReceipt(); const hasText = text.trim() !== ""; if (!hasText && time === void 0) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.userActions, children: [ time !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessageClock, { time }), hasText && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.iconButton, "aria-label": "复制消息", title: "复制消息", onClick: () => { copy(text); }, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopyGlyph, {}) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { role: "status", className: Reader_module_css_default.meta, children: receipt }) ] }); } function reasoningTarget(top, contentHeight, viewportHeight, lineHeight, backlogLines = 0) { const end = Math.max(0, contentHeight - viewportHeight); return Math.min(end, Math.min(end, Math.max(0, top)) + Math.max(1, lineHeight) * Math.max(2, Math.min(40, Math.ceil(backlogLines)))); } // src/client/ReasoningCard.tsx const EASING$1 = "cubic-bezier(.22,1,.36,1)"; /** One real transcript: reference transform while following, native scroll while reading. */ function ReasoningCard({ children, step, active, motion, selected, onRead }) { const viewport = (0, react.useRef)(null); const track = (0, react.useRef)(null); const content = (0, react.useRef)(null); const controls = (0, react.useId)(); const [expanded, setExpanded] = (0, react.useState)(false); const [following, setFollowing] = (0, react.useState)(true); const [overflow, setOverflow] = (0, react.useState)(false); const [edges, setEdges] = (0, react.useState)("none"); const lastHeight = (0, react.useRef)(0); const resize = (0, react.useRef)(null); const previousExpanded = (0, react.useRef)(expanded); const stopFollow = (0, react.useRef)(() => {}); const { paused = false } = (0, react.useContext)(StreamMotionContext); const allowed = following && active && motion && !selected && !paused; const pause = (0, react.useCallback)(() => { stopFollow.current(); setFollowing(false); onRead(); }, [onRead]); (0, react.useLayoutEffect)(() => { if (!selected) return; stopFollow.current(); setFollowing(false); }, [selected]); (0, react.useLayoutEffect)(() => { if (!expanded) return; const port = viewport.current; const host = port?.closest("[data-conversation-scroll]"); if (!port || !host) return; const fit = () => { const composer = parseFloat(getComputedStyle(host).getPropertyValue("--dsh-composer-height")) || 152; const heading = port.parentElement?.querySelector("[data-reader-reasoning-heading]")?.offsetHeight || 30; const footer = port.parentElement?.querySelector("[data-ud-check=reasoning-controls]")?.offsetHeight || 38; const available = Math.max(120, host.clientHeight - composer - heading - footer - 32); port.style.setProperty("--reason-reading-height", `${available}px`); }; fit(); const observer = new ResizeObserver(fit); observer.observe(host); return () => { observer.disconnect(); }; }, [expanded]); (0, react.useLayoutEffect)(() => { const port = viewport.current; const text = content.current; const scrollTrack = track.current; if (!port || !text || !scrollTrack) return; let frame = 0; let timer; let nextAt = performance.now() + 840; let alive = true; let automatic = false; let lastPainted = port.scrollTop; let targetOffset = lastPainted; const tail = () => Math.max(0, text.offsetHeight - port.clientHeight); const clamp = (value) => Math.max(0, Math.min(tail(), value)); const paintedOffset = () => { if (!automatic) return port.scrollTop; const transform = getComputedStyle(scrollTrack).transform; return clamp(transform === "none" ? lastPainted : port.scrollTop - new DOMMatrixReadOnly(transform).m42); }; const hasSelection = () => { const selection = document.getSelection(); return !!selection && !selection.isCollapsed && !!selection.anchorNode && text.contains(selection.anchorNode); }; const cancel = () => { cancelAnimationFrame(frame); frame = 0; clearTimeout(timer); timer = void 0; delete port.dataset.reasoningMoving; }; const manual = () => { if (!automatic) return; const top = paintedOffset(); automatic = false; scrollTrack.style.transition = "none"; scrollTrack.style.transform = "none"; port.style.overflow = "auto"; port.scrollTop = top; lastPainted = port.scrollTop; port.dataset.reasoningMode = "manual"; }; const follow = () => { if (automatic) return; targetOffset = lastPainted = clamp(port.scrollTop); scrollTrack.style.transition = "none"; scrollTrack.style.transform = `translateY(-${lastPainted}px)`; port.scrollTop = 0; port.style.overflow = "hidden"; automatic = true; port.dataset.reasoningMode = "transform"; }; const measure = (recordHeight = true) => { const previewHeight = parseFloat(getComputedStyle(port).getPropertyValue("--reason-preview-height")); setOverflow(text.offsetHeight > previewHeight + 1); lastPainted = paintedOffset(); const top = lastPainted > 1; const bottom = tail() - lastPainted > 1; const next = top ? bottom ? "both" : "top" : bottom ? "bottom" : "none"; setEdges((value) => value === next ? value : next); if (recordHeight && !resize.current) lastHeight.current = port.clientHeight; }; stopFollow.current = () => { cancel(); manual(); measure(false); }; const canFollow = () => allowed && alive && !document.hidden && !hasSelection(); const schedule = () => { if (!canFollow() || frame || timer !== void 0) return; follow(); if (tail() - paintedOffset() < 1) return; timer = setTimeout(start, Math.max(0, nextAt - performance.now())); }; const start = () => { timer = void 0; if (!canFollow()) return; const from = paintedOffset(); const lineHeight = parseFloat(getComputedStyle(text).lineHeight) || 24; const backlogLines = Math.max(0, (tail() - from) / lineHeight); const target = reasoningTarget(from, text.offsetHeight, port.clientHeight, lineHeight, backlogLines); if (target - from < 1) return; const began = performance.now(); nextAt = began + (backlogLines > 2 ? 40 : 840); targetOffset = target; scrollTrack.style.transition = "none"; scrollTrack.style.transform = `translateY(-${from}px)`; scrollTrack.offsetHeight; scrollTrack.style.transition = "transform var(--reason-step) var(--reason-ease)"; scrollTrack.style.transform = `translateY(-${target}px)`; port.dataset.reasoningMoving = "true"; port.dataset.reasoningFrom = String(from); port.dataset.reasoningTarget = String(target); port.dataset.reasoningBegan = String(began); const tick = (now) => { frame = 0; if (!canFollow()) { cancel(); manual(); return; } measure(); if (now - began < 500 || Math.abs(lastPainted - target) > .05) frame = requestAnimationFrame(tick); else { delete port.dataset.reasoningMoving; schedule(); } }; frame = requestAnimationFrame(tick); }; const onScroll = () => { measure(); if (automatic && port.scrollTop > 1) pause(); }; const onWheel = (event) => { if (!event.deltaY) return; const handoff = automatic && event.cancelable; if (handoff) event.preventDefault(); const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? parseFloat(getComputedStyle(text).lineHeight) || 24 : event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? port.clientHeight : 1; pause(); if (handoff) { port.scrollTop = clamp(port.scrollTop + event.deltaY * unit); measure(); } }; const onSelection = () => { if (hasSelection()) pause(); }; const onVisibility = () => { cancel(); manual(); nextAt = performance.now() + 840; if (!document.hidden) schedule(); }; const observer = new ResizeObserver(() => { if (automatic && targetOffset > tail() + 1) { cancel(); manual(); nextAt = performance.now() + 840; } measure(); schedule(); }); observer.observe(text); observer.observe(port); port.addEventListener("scroll", onScroll, { passive: true }); port.addEventListener("wheel", onWheel, { passive: false }); document.addEventListener("selectionchange", onSelection); document.addEventListener("visibilitychange", onVisibility); measure(false); schedule(); return () => { alive = false; cancel(); manual(); observer.disconnect(); port.removeEventListener("scroll", onScroll); port.removeEventListener("wheel", onWheel); document.removeEventListener("selectionchange", onSelection); document.removeEventListener("visibilitychange", onVisibility); stopFollow.current = () => {}; }; }, [allowed, pause]); (0, react.useLayoutEffect)(() => { const port = viewport.current; if (!port) return; const changed = expanded !== previousExpanded.current; previousExpanded.current = expanded; const from = resize.current ? port.clientHeight : lastHeight.current; resize.current?.cancel(); resize.current = null; port.style.maxHeight = ""; port.style.height = ""; const target = port.clientHeight; if (changed && !selected) { const card = port.parentElement; const host = port.closest("[data-conversation-scroll]"); if (card && host) { const composer = parseFloat(getComputedStyle(host).getPropertyValue("--dsh-composer-height")) || 152; const region = host.getBoundingClientRect(); const box = card.getBoundingClientRect(); const top = region.top + 16; const bottom = region.bottom - composer - 16; const delta = box.top < top ? box.top - top : box.bottom > bottom ? Math.min(box.bottom - bottom, box.top - top) : 0; if (Math.abs(delta) > 1) host.scrollTo({ top: Math.max(0, host.scrollTop + delta), behavior: motion ? "smooth" : "instant" }); } } if (!changed || !motion || from < 1 || Math.abs(target - from) < 1) { lastHeight.current = target; return; } port.style.maxHeight = "none"; const animation = port.animate([{ height: `${from}px` }, { height: `${target}px` }], { duration: 300, easing: EASING$1, fill: "both" }); resize.current = animation; const restore = () => { port.style.maxHeight = ""; port.style.height = ""; lastHeight.current = port.clientHeight; }; let settled = false; const settle = () => { if (settled) return; settled = true; if (resize.current === animation) resize.current = null; animation.cancel(); restore(); }; animation.onfinish = settle; const deadline = window.setTimeout(settle, 540); return () => { window.clearTimeout(deadline); }; }, [ expanded, motion, selected ]); (0, react.useEffect)(() => () => resize.current?.cancel(), []); const toggleReading = () => { onRead(); setExpanded((value) => !value); }; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.reasonCard, "data-reader-reasoning-card": true, "data-reader-anchor": true, "data-expanded": expanded, "data-following": allowed, "data-overflow": overflow, "data-ud-motion": "reader-reasoning-size", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.reasonHeading, "data-reader-reasoning-heading": true, "data-ud-check": "reasoning-identity", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.reasonLabel, "data-reader-reasoning-label": true, children: "思考" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: ["步骤 ", step] })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref: viewport, id: controls, className: Reader_module_css_default.reasonViewport, "data-reader-reasoning-scroll": true, "data-edges": edges, "data-ud-motion": "reader-reasoning-scroll", role: "region", "aria-label": `步骤 ${step} 的思考${overflow ? ",可滚动阅读" : ""}`, tabIndex: overflow ? 0 : void 0, onPointerDown: pause, onFocus: pause, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref: track, className: Reader_module_css_default.reasonTrack, "data-reader-reasoning-track": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref: content, className: Reader_module_css_default.reasonText, "data-reader-reasoning-text": true, children }) }) }), (overflow || expanded) && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.reasonFooter, "data-ud-check": "reasoning-controls", children: [active && motion ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { type: "button", className: Reader_module_css_default.reasonAction, disabled: selected, "aria-controls": controls, "aria-label": following ? "暂停自动跟随思考" : "继续跟随最新思考", title: selected ? "取消文字选择后可继续跟随" : void 0, onClick: () => { if (following) pause(); else { onRead(); setFollowing(true); } }, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { width: "12", height: "12", viewBox: "0 0 16 16", "aria-hidden": "true", children: following ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M5.5 4v8m5-8v8" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 3v10m-4-4 4 4 4-4" }) }), following ? "暂停跟随" : "跟随最新"] }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.reasonCaption, children: expanded ? "手动阅读" : "可滚动阅读" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { type: "button", className: Reader_module_css_default.reasonAction, "aria-expanded": expanded, "aria-controls": controls, "aria-label": expanded ? "收起完整思考" : "展开阅读完整思考", onClick: toggleReading, children: [expanded ? "收起" : "展开阅读", /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { width: "12", height: "12", viewBox: "0 0 16 16", "aria-hidden": "true", children: expanded ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m4 10 4-4 4 4" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m4 6 4 4 4-4" }) })] })] }) ] }); } // src/client/official-slots.tsx /** * RC2 composition adapter. Only public registry operations are used. We lend * registrations a Reader-owned seat, not a second implementation of their UI. * The platform still binds injection, hooks, locale, stores and boundaries. * Original entries, declarations and components are never changed. * * Child seats have unique names because RC2 declarations have one owner. The * sole component wrapper translates those names before delegating to the * framework-provided renderSlot. It does not implement a slot renderer. */ const OFFICIAL_SLOTS = { actions: "conversation.chat.assistant-actions", tools: "tool.call.toolview", tail: "conversation.chat.turnTail", nodes: "conversation.chat.node", messageImages: "conversation.chat.message.images", userImages: "conversation.chat.user.images" }; const OFFICIAL_SEATS = { actions: "dsh-better-display.official.actions/conversation.chat.assistant-actions", tools: "dsh-better-display.official.tools/tool.call.toolview", tail: "dsh-better-display.official.tail/conversation.chat.turnTail", nodes: "dsh-better-display.official.nodes/conversation.chat.node", messageImages: "dsh-better-display.official.messageImages/conversation.chat.message.images", userImages: "dsh-better-display.official.userImages/conversation.chat.user.images" }; const officialSeat = (family, source = OFFICIAL_SLOTS[family]) => `dsh-better-display.official.${family}/${source}`; /** * Searchable hide for official nodes drawn outside the Chat flow viewport. * The flow's own `useGroupAction` is not in scope here; this keeps the same * `hidden="until-found"` contract so browser find can still reveal the row. */ function useReaderGroupAction(hidden, reveal) { const ref = (0, react.useRef)(null); (0, react.useLayoutEffect)(() => { const element = ref.current; if (element === null) return; if (hidden && element.contains(element.ownerDocument.activeElement)) { reveal(); return; } if (hidden) element.setAttribute("hidden", "until-found"); else element.removeAttribute("hidden"); }, [hidden, reveal]); (0, react.useEffect)(() => { const element = ref.current; if (element === null) return; element.addEventListener("beforematch", reveal); return () => { element.removeEventListener("beforematch", reveal); }; }, [reveal]); return ref; } const readerGroupAction = useReaderGroupAction; const READER_OWNED_NODES = /* @__PURE__ */ new Set([ "tool-call", "turn-tail", "turn-process" ]); /** * Mirror a chat-node registration into the Reader seat. * Assistant replacements are the entries that would actually replace the * official renderer on the host. The official priority itself stays out, so * Reader keeps its own answer markdown until a plugin opts in. */ function acceptMirroredChatNode(entry) { const key = entry.options.key ?? ""; if (key === "assistant-step") return (entry.options.priority ?? 0) < 0; return !READER_OWNED_NODES.has(key); } const EXPECTED = { actions: { kind: "list", scope: "session" }, tools: { kind: "keyed", scope: "session" }, tail: { kind: "list", scope: "session" }, nodes: { kind: "keyed", scope: "session" }, messageImages: { kind: "single", scope: "session" }, userImages: { kind: "single", scope: "session" } }; /** * Reader already presents produced paths with its copy/reveal actions. RC2's * official tail additionally owns explicit `present` artifacts. Leave those * cards, actions and state intact, and omit only the duplicate produced chips. * This changes a presentation prop, never the source match or session data. * Unrecognized shapes pass through intact for safe forward degradation. */ function readerTailMatch(value, displayedPaths) { if (!value || typeof value !== "object") return value; const match = value; const displayed = new Set(displayedPaths ?? []); return displayed.size > 0 && Array.isArray(match.produced) && Array.isArray(match.presented) ? { ...match, produced: match.produced.filter((path) => !displayed.has(path)) } : value; } function tailPresentation(component) { const Original = component; return (0, react.memo)(function ReaderTailPresentation(props) { const matched = (0, react.useMemo)(() => readerTailMatch(props.matched, props.readerProducedPaths), [props.matched, props.readerProducedPaths]); return (0, react.createElement)(Original, { ...props, matched }); }); } function officialChildren(slots) { return Object.fromEntries(Object.entries(OFFICIAL_SLOTS).map(([name, source]) => { const family = name; const spec = slots.spec(source); if (spec && (spec.kind !== EXPECTED[family].kind || spec.scope !== EXPECTED[family].scope)) throw new Error(`Official slot contract changed: ${source} (${spec.kind}/${spec.scope})`); return [officialSeat(family), spec ?? EXPECTED[family]]; })); } function translatedComponent(entry, names) { if (names.size === 0) return entry.component; const Original = entry.component; return (0, react.memo)(function OfficialSlotChildren(props) { const renders = (0, react.useMemo)(() => { const translate = (render) => (key, owner, options) => { const seat = names.get(key); if (!seat || !render) throw new Error(`Undeclared official child slot: ${key}`); return render(seat, owner, options); }; return { renderSlot: translate(props.renderSlot), ...props.renderSlotChain ? { renderSlotChain: translate(props.renderSlotChain) } : {} }; }, [props.renderSlot, props.renderSlotChain]); return (0, react.createElement)(Original, { ...props, ...renders }); }); } /** * Mirror one elected contribution set incrementally. Unrelated additions do not * remount existing cards or recreate their subscriptions. A source unload/HMR * disposes the corresponding subtree and closures before its replacement. */ function mirrorOfficialSlot(slots, source, target, namespace, accept = () => true) { const mounted = /* @__PURE__ */ new Map(); let stopped = false; const reconcile = () => { if (stopped) return; const entries = slots.entriesOfSlot(source).filter(accept); const wanted = new Set(entries); for (const [entry, dispose] of mounted) { if (wanted.has(entry)) continue; dispose(); mounted.delete(entry); } for (const entry of entries) { if (mounted.has(entry)) continue; const names = new Map(Object.keys(entry.children ?? {}).map((key) => [key, `${namespace}/${key}`])); const children = Object.fromEntries([...names].map(([key, seat]) => [seat, entry.children[key]])); const disposers = []; const dispose = () => { for (const stop of disposers.splice(0).reverse()) stop(); }; try { const { component: _component, options, children: _children, ...metadata } = entry; const presentation = source === OFFICIAL_SLOTS.tail && entry.locale === "deliverables" ? { ...entry, component: tailPresentation(entry.component) } : entry; disposers.push(slots.register({ ...options, ...metadata, name: target, ...names.size ? { children } : {}, registrant: `dsh-better-display → ${entry.registrant ?? source}` }, translatedComponent(presentation, names))); for (const [key, seat] of names) disposers.push(mirrorOfficialSlot(slots, key, seat, namespace)); mounted.set(entry, dispose); } catch (error) { dispose(); throw error; } } }; const unsubscribe = slots.subscribe(source, reconcile); const dispose = () => { stopped = true; unsubscribe(); for (const stop of [...mounted.values()].reverse()) stop(); mounted.clear(); }; try { reconcile(); } catch (error) { dispose(); throw error; } return dispose; } function installOfficialSlots(ctx) { const slots = ctx.slots; const disposers = []; try { for (const [name, source] of Object.entries(OFFICIAL_SLOTS)) { const family = name; disposers.push(slots.inject(source, () => { const spec = slots.spec(source); const target = officialSeat(family); const declared = slots.spec(target); if (spec.kind !== declared?.kind || spec.scope !== declared.scope) throw new Error(`Official slot contract changed: ${source}`); return mirrorOfficialSlot(slots, source, target, `dsh-better-display.official.${family}`, family === "nodes" ? acceptMirroredChatNode : void 0); })); } } catch (error) { for (const stop of disposers.reverse()) stop(); throw error; } return () => { for (const stop of disposers.splice(0).reverse()) stop(); }; } // src/client/chat-seat.ts function chatSeatProps(kind, key) { return { "data-chat-anchor-key": key, "data-chat-flow-key": key, "data-chat-node-key": key, "data-chat-flow-kind": kind }; } // src/client/OfficialContent.tsx function OfficialActions({ official, messageId }) { if (!official || !messageId) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { "data-reader-official-actions": true, style: { display: "contents" }, children: official.renderSlot(OFFICIAL_SEATS.actions, { messageId }) }); } /** Each atomic Tool view owns its disclosure state through this stable Hook prop. */ const useToolDisclosure = () => { const [expanded, setExpanded] = (0, react.useState)(false); return { expanded, setExpanded, toggle: (0, react.useCallback)(() => setExpanded((previous) => !previous), []) }; }; function OfficialTool({ official, block, toolName, cwd, openFile, fallback }) { const home = (0, react.useSyncExternalStore)(official.officialHost.subscribe, official.officialHost.getSnapshot).home; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-tool-official": true, children: official.renderSlot(OFFICIAL_SEATS.tools, { callId: block.callId, toolName, phase: "kind" in block ? "result" : block.phase, block, cwd, home, openFile: openFile ?? (() => {}), loadImage: official.officialImageLoader, useDisclosure: useToolDisclosure, inspect: () => official.openView("trajectory", block.callId) }, { entryKey: toolName, hookContext: { callId: block.callId, assistant: void 0 }, fallback }) }); } function chatNodeOwner(render, official) { return { cwd: render.cwd, openFile: render.openFile ?? (() => {}), forkAt: render.forkAt ?? (() => {}), inspectCall: (callId) => official.openView("trajectory", callId), loadImage: official.officialImageLoader, fileMentions: official.officialFileMentions }; } function nodeHookContext(turnData, disclosureReset) { return { turnData, disclosureReset, useGroupAction: readerGroupAction }; } function OfficialNode({ node, fallback, ...render }) { const official = render.official; const [disclosureReset] = (0, react.useState)(() => (0, _deepseek_ai_dsh_client_store.createSnapshotStore)(0)); if (!official) return fallback; const turn = node.location.kind === "turn" || node.location.kind === "step" ? node.location.turn : void 0; const renderNode = official.renderSlot; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-official-node": node.kind, ...node.kind === "user" || node.kind === "steering" ? chatSeatProps(node.kind, node.key) : {}, children: renderNode(OFFICIAL_SEATS.nodes, { ...chatNodeOwner(render, official), node }, { entryKey: node.kind, hookContext: nodeHookContext(turn?.data, disclosureReset), fallback }) }); } /** * Body of one assistant segment. A mirrored assistant-step replacement draws * it; Reader markdown is the fallback when no replacement is registered. * The caller keeps reasoning blocks on the reading card. */ function OfficialAssistantBody({ node, blocks, streaming = false, holdFormatting = false, startedAt, interrupted = false, liveText = false, ...render }) { const official = render.official; const [disclosureReset] = (0, react.useState)(() => (0, _deepseek_ai_dsh_client_store.createSnapshotStore)(0)); const fallback = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Blocks, { ...render, blocks, streaming, holdFormatting, startedAt, interrupted, liveText }); if (!official) return fallback; const turn = node.location.kind === "turn" || node.location.kind === "step" ? node.location.turn : void 0; const view = blocks.length === node.data.blocks.length && blocks.every((block, index) => block === node.data.blocks[index]) ? node : { ...node, data: { ...node.data, blocks } }; const renderNode = official.renderSlot; return renderNode(OFFICIAL_SEATS.nodes, { ...chatNodeOwner(render, official), node: view, groupPart: "response" }, { entryKey: "assistant-step", hookContext: nodeHookContext(turn?.data, disclosureReset), fallback }); } function OfficialTail({ official, owner, produced }) { const tailOwner = owner && official ? { ...owner, openFile: official.officialPreviewFile, readerProducedPaths: produced } : void 0; return official && tailOwner ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-official-tail": true, style: { display: "contents" }, children: official.renderSlot(OFFICIAL_SEATS.tail, tailOwner) }) : null; } // src/client/turn-slots.ts /** * Keep live turns in the incoming `groups` order, and keep a departing turn * next to the live neighbour that preceded it. * * A rewind removes turn keys from the visible order. Unmounting them in that * same commit snaps the transcript, so the lane retains the last group object * until the collapse finishes. A re-render, a stream tick, or a reconnect that * still contains the same keys only replaces the group object and leaves * `live` true — those updates must not start a collapse. A key that returns * is live again where `groups` places it. Loading older history therefore * stays in transcript order instead of appending the older turns after the * ones already on screen. A departing slot is inserted immediately after the * nearest preceding slot that is still live, or at the front when it had none, * so several departing neighbours keep their relative order. * * Returns `current` itself when nothing changed, so a React state update can * bail out on `Object.is`. */ function reconcileTurnSlots(current, groups) { const incoming = new Map(groups.map((group) => [group.key, group])); const next = groups.map((group) => ({ group, live: true })); for (const slot of current) { if (incoming.has(slot.group.key)) continue; insertDeparting(next, { group: slot.group, live: false }, precedingLiveKey(current, incoming, slot.group.key)); } return next.length === current.length && next.every((slot, index) => slot.live === current[index].live && slot.group === current[index].group) ? current : next; } /** Nearest preceding slot that is still in the incoming order, if any. */ function precedingLiveKey(current, incoming, key) { const index = current.findIndex((slot) => slot.group.key === key); for (let cursor = index - 1; cursor >= 0; cursor--) { const candidate = current[cursor].group.key; if (incoming.has(candidate)) return candidate; } } /** * Place a departing slot after `anchorKey`, or at the front when the slot had * no preceding live neighbour. Slots that share an anchor keep `current` order * because each one is inserted at the end of the departing run after that anchor. */ function insertDeparting(next, slot, anchorKey) { if (anchorKey === void 0) { const firstLive = next.findIndex((item) => item.live); next.splice(firstLive < 0 ? next.length : firstLive, 0, slot); return; } const anchorIndex = next.findIndex((item) => item.group.key === anchorKey); if (anchorIndex < 0) { next.unshift(slot); return; } let insertAt = anchorIndex + 1; while (insertAt < next.length && next[insertAt]?.live === false) insertAt++; next.splice(insertAt, 0, slot); } // src/client/motion.tsx const EASING = "cubic-bezier(.22,1,.36,1)"; function useMotionAllowed(enabled) { const [reduced, setReduced] = (0, react.useState)(() => window.matchMedia("(prefers-reduced-motion: reduce)").matches); (0, react.useEffect)(() => { const query = window.matchMedia("(prefers-reduced-motion: reduce)"); const change = () => setReduced(query.matches); query.addEventListener("change", change); return () => query.removeEventListener("change", change); }, []); return enabled && !reduced; } function usePinnedSelection(root, selector = "[data-reader-answer], [data-reader-body], [data-reader-process]") { const [keys, setKeys] = (0, react.useState)([]); (0, react.useEffect)(() => { const update = () => { const selection = document.getSelection(); const range = selection && !selection.isCollapsed && selection.rangeCount ? selection.getRangeAt(0) : null; const next = range && root.current ? [...new Set(Array.from(root.current.querySelectorAll(selector)).filter((element) => range.intersectsNode(element)).map((element) => element.dataset.readerKey ?? element.dataset.readerProcessKey).filter(Boolean))] : []; setKeys((previous) => previous.length === next.length && previous.every((key, index) => key === next[index]) ? previous : next); }; document.addEventListener("selectionchange", update); return () => document.removeEventListener("selectionchange", update); }, [root, selector]); return keys; } function StatusText({ text, motion, shimmer = false }) { const ref = (0, react.useRef)(null); const [visible, setVisible] = (0, react.useState)(() => !document.hidden); const [forcedColors, setForcedColors] = (0, react.useState)(() => window.matchMedia("(forced-colors: active)").matches); const allowed = motion && visible && !forcedColors; const [frame, setFrame] = (0, react.useState)({ text, id: 0, phase: "idle", outgoing: null }); if (frame.text !== text) setFrame({ text, id: frame.id + 1, phase: allowed ? "start" : "idle", outgoing: allowed ? { text: frame.text, id: frame.id } : null }); (0, react.useEffect)(() => { const update = () => setVisible(!document.hidden); const query = window.matchMedia("(forced-colors: active)"); const colors = () => setForcedColors(query.matches); document.addEventListener("visibilitychange", update); query.addEventListener("change", colors); return () => { document.removeEventListener("visibilitychange", update); query.removeEventListener("change", colors); }; }, []); (0, react.useLayoutEffect)(() => { const id = frame.id; const settle = () => setFrame((current) => current.id === id && current.outgoing ? { ...current, phase: "idle", outgoing: null } : current); if (!allowed) { settle(); return; } if (!frame.outgoing || !ref.current) return; ref.current.getBoundingClientRect(); let timer = 0; const tick = requestAnimationFrame(() => { setFrame((current) => current.id === id ? { ...current, phase: "running" } : current); timer = window.setTimeout(settle, 200); }); return () => { cancelAnimationFrame(tick); window.clearTimeout(timer); }; }, [frame.id, allowed]); const active = shimmer && allowed; const swapping = allowed && frame.outgoing !== null; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.statusText, "data-reader-status": true, "data-reader-busy": shimmer, "data-ud-check": "reader-status", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.think, "aria-hidden": "true", "data-active": active, "data-reader-status-phase": swapping ? frame.phase : "idle", "data-ud-motion": "reader-thinking-state", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.thinkSizer, children: text }), swapping && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: `${Reader_module_css_default.thinkText} ${frame.phase === "running" ? Reader_module_css_default.isExit : ""}`, "data-reader-status-copy": "outgoing", "data-text": frame.outgoing.text, children: frame.outgoing.text }, frame.outgoing.id), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { ref, className: `${Reader_module_css_default.thinkText} ${swapping && frame.phase === "start" ? Reader_module_css_default.isEnterStart : ""}`, "data-reader-status-copy": "current", "data-reader-shimmer": active || void 0, "data-text": text, children: text }, frame.id) ] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.srOnly, role: "status", "aria-live": "polite", "aria-atomic": "true", children: text })] }); } function Disclosure({ open, onChange, label, controls, buttonRef, ariaLabel }) { const name = ariaLabel ?? "思考与过程"; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.disclosure, "data-reader-disclosure": true, "data-expanded": open, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { ref: buttonRef, type: "button", className: Reader_module_css_default.disclosureButton, "aria-label": `${open ? "收起" : "展开"}${name}`, "aria-expanded": open, ...controls ? { "aria-controls": controls } : {}, onClick: () => onChange(!open), children: [label, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { className: Reader_module_css_default.chevron, "data-open": open, viewBox: "0 0 16 16", width: "12", height: "12", "aria-hidden": "true", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "m6 4 4 4-4 4" }) })] }) }); } /** Supplemental details stay in source order beside their own narration. */ function ProcessFragment({ open, motion, onRead, returnFocusTo, nodeKey, children, framed = false }) { const body = (0, react.useRef)(null); const running = (0, react.useRef)(null); const previous = (0, react.useRef)(open); const [present, setPresent] = (0, react.useState)(open); (0, react.useLayoutEffect)(() => { const element = body.current; if (!element) return; const from = running.current ? element.getBoundingClientRect().height : previous.current ? element.scrollHeight : 0; running.current?.cancel(); running.current = null; const changed = previous.current !== open; previous.current = open; if (open) setPresent(true); if (!open && element.contains(document.activeElement)) returnFocusTo.current?.focus(); element.style.height = open ? "auto" : "0px"; const target = open ? element.scrollHeight : 0; if (!motion || !changed || Math.abs(from - target) < 1) { setPresent(open); return; } const animation = element.animate(from > target ? [ { offset: 0, height: `${from}px`, opacity: 1, transform: "scaleY(1) translateY(0)" }, { offset: .32, height: `${Math.round(from * .92)}px`, opacity: .35, transform: "scaleY(0.96) translateY(-2px)" }, { offset: 1, height: `${target}px`, opacity: 0, transform: "scaleY(0.68) translateY(-8px)" } ] : [ { offset: 0, height: `${from}px`, opacity: 0, transform: "scaleY(0.8) translateY(6px)" }, { offset: .3, height: `${Math.round(target * .4)}px`, opacity: .4, transform: "scaleY(0.92) translateY(3px)" }, { offset: 1, height: `${target}px`, opacity: 1, transform: "scaleY(1) translateY(0)" } ], { duration: 380, easing: "cubic-bezier(0.16, 1, 0.3, 1)", fill: "both" }); running.current = animation; let settled = false; const settle = () => { if (settled) return; settled = true; if (running.current === animation) running.current = null; animation.cancel(); setPresent(open); }; animation.onfinish = settle; const deadline = window.setTimeout(settle, 620); return () => { window.clearTimeout(deadline); running.current?.cancel(); }; }, [ open, motion, returnFocusTo ]); if (!open && !present) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref: body, className: Reader_module_css_default.disclosureBody, "data-reader-process": true, "data-reader-process-key": nodeKey, "data-ud-motion": "reader-process-size", "aria-hidden": !open, onPointerDown: () => { if (open) onRead(); }, onFocusCapture: () => { if (open) onRead(); }, ...!open ? { inert: "" } : {}, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: framed ? Reader_module_css_default.processFrame : Reader_module_css_default.processContents, children }) }); } /** Retire only narration that was actually visible; historical rows stay folded. */ function RetiringContent({ visible, children, onRetired }) { const { enabled } = (0, react.useContext)(StreamMotionContext); const root = (0, react.useRef)(null); const animation = (0, react.useRef)(null); const [present, setPresent] = (0, react.useState)(visible); const [focusHeld, setFocusHeld] = (0, react.useState)(false); const retired = (0, react.useRef)(onRetired); retired.current = onRetired; (0, react.useLayoutEffect)(() => { const element = root.current; if (visible) { animation.current?.cancel(); animation.current = null; setPresent(true); return; } if (!element) return; let retiredNow = false; const retireNow = () => { if (retiredNow) return; retiredNow = true; animation.current?.cancel(); animation.current = null; focusSurvivesRetire(element); setPresent(false); retired.current?.(); }; if (!enabled || document.hidden) { retireNow(); return; } const canListen = typeof document.addEventListener === "function"; const holdsFocus = element.contains(document.activeElement); if (holdsFocus || focusHeld) { if (holdsFocus) setFocusHeld(true); const onHiddenWhileHeld = () => { if (document.hidden) retireNow(); }; if (canListen) document.addEventListener("visibilitychange", onHiddenWhileHeld); return () => { if (canListen) document.removeEventListener("visibilitychange", onHiddenWhileHeld); }; } const from = element.getBoundingClientRect().height; animation.current?.cancel(); animation.current = null; if (from < 1) { setPresent(false); retired.current?.(); return; } const next = element.animate([{ height: `${from}px`, opacity: 1 }, { height: "0px", opacity: 0 }], { duration: 220, easing: EASING, fill: "both" }); animation.current = next; let settled = false; const settle = () => { if (settled || animation.current !== next) return; settled = true; animation.current = null; next.cancel(); setPresent(false); retired.current?.(); }; next.onfinish = settle; const deadline = window.setTimeout(settle, 460); const onHide = () => { if (document.hidden) settle(); }; if (canListen) document.addEventListener("visibilitychange", onHide); return () => { window.clearTimeout(deadline); if (canListen) document.removeEventListener("visibilitychange", onHide); if (animation.current === next) animation.current = null; next.cancel(); }; }, [ visible, enabled, focusHeld ]); (0, react.useEffect)(() => () => animation.current?.cancel(), []); if (!visible && !present) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref: root, className: Reader_module_css_default.retiringContent, "data-reader-retiring": visible ? "visible" : "retiring", "data-ud-motion": "reader-progress-retire", onBlur: (event) => { if (!event.currentTarget.contains(event.relatedTarget)) setFocusHeld(false); }, children }); } /** * Keeps a departing turn mounted for the length of its own collapse. * * A rewind removes turns from the visible order, and unmounting them outright * snapped the transcript: every withdrawn row disappeared in one frame with * nothing to scroll. Instead each departing turn is retained, rendered with * `visible={false}` so it animates to zero height, and released only once the * collapse has settled — so the reader watches the rows fold away and the rows * below glide up into their place. * * Live slots follow the incoming group order, so older history stays above the * tail. A collapsing turn stays next to the live neighbour that preceded it; * appending it would jump it to the bottom for the length of the animation. * Retention is bounded by the animation itself: `onRetired` * drops the slot, so a departing turn lives for one collapse and no longer — * and a key that comes back later is re-added as a live slot. */ function RetiringTurns({ groups, render }) { const [slots, setSlots] = (0, react.useState)(() => groups.map((group) => ({ group, live: true }))); (0, react.useLayoutEffect)(() => { setSlots((current) => reconcileTurnSlots(current, groups)); }, [groups]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: slots.map((slot) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RetiringContent, { visible: slot.live, onRetired: () => setSlots((current) => current.filter((candidate) => candidate.live || candidate.group.key !== slot.group.key)), children: render(slot.group) }, slot.group.key)) }); } /** A turn that is still on screen, not one this commit is about to unmount. */ function survivingTurn(node) { if (!(node instanceof HTMLElement) || node.dataset.readerRetiring === "retiring") return null; const turn = node.hasAttribute("data-reader-turn") ? node : node.querySelector("[data-reader-turn]"); if (turn === null) return null; const retiring = turn.closest("[data-reader-retiring]"); if (retiring instanceof HTMLElement && retiring.dataset.readerRetiring === "retiring") return null; return turn; } /** * Where focus goes when cut content is removed without an animation. * Prefer the nearest turn that is still live. Otherwise the reading column * (or the host scrollport) so focus does not fall through to the document. */ function retireFocusTarget(element) { const parent = element.parentElement; if (parent) { const siblings = [...parent.children]; const index = siblings.indexOf(element); for (let cursor = index - 1; cursor >= 0; cursor--) { const turn = survivingTurn(siblings[cursor]); if (turn) return turn; } for (let cursor = index + 1; cursor < siblings.length; cursor++) { const turn = survivingTurn(siblings[cursor]); if (turn) return turn; } } const column = element.closest("[data-chat-flow]"); if (column && !element.contains(column)) return column; const scroll = element.closest("[data-conversation-scroll]"); if (scroll && !element.contains(scroll)) return scroll; return null; } /** Move focus out of `element` before it unmounts. A no-op when focus is elsewhere. */ function focusSurvivesRetire(element) { const active = document.activeElement; if (active === null || !element.contains(active)) return; const target = retireFocusTarget(element); if (target === null || element.contains(target)) return; if (target.tabIndex < 0) target.tabIndex = -1; target.focus({ preventScroll: true }); } function useReadingScroll(root, motion) { const port = (0, react.useRef)(null); const following = (0, react.useRef)(true); const pinned = (0, react.useRef)(true); const anchor = (0, react.useRef)(null); const cancelFollow = (0, react.useRef)(() => {}); const [detached, setDetached] = (0, react.useState)(false); (0, react.useLayoutEffect)(() => { const content = root.current; if (!content) return; const scroll = content.closest("[data-conversation-scroll]") ?? content; port.current = scroll; const previousOverflowAnchor = scroll.style.overflowAnchor; scroll.style.overflowAnchor = "none"; let followFrame = 0; let lastFrameAt = 0; let layoutDepth = 0; let lastWrittenTop = null; const layoutStart = () => { layoutDepth++; cancelAnimationFrame(followFrame); followFrame = 0; capture(); }; const layoutEnd = () => { layoutDepth = Math.max(0, layoutDepth - 1); if (!layoutDepth && following.current && !followFrame) { lastFrameAt = performance.now(); followFrame = requestAnimationFrame(follow); } }; cancelFollow.current = () => { cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null; }; const selected = () => { const selection = document.getSelection(); return selection && !selection.isCollapsed && selection.anchorNode && content.contains(selection.anchorNode); }; const editingText = () => { const active = document.activeElement; if (!(active instanceof HTMLElement)) return false; if (!content.contains(active)) return false; return active.isContentEditable || active.tagName === "TEXTAREA" || active.tagName === "INPUT"; }; const capture = () => { const top = scroll.getBoundingClientRect().top; const candidates = content.querySelectorAll("[data-reader-anchor]"); let candidate = null; for (let index = 0; index < candidates.length; index++) { const element = candidates[index]; if (element.getBoundingClientRect().bottom > top + 8) { candidate = element; break; } } anchor.current = candidate ? { element: candidate, docTop: candidate.getBoundingClientRect().top + scroll.scrollTop } : null; }; let captureFrame = 0; const scheduleCapture = () => { if (captureFrame) return; captureFrame = requestAnimationFrame(() => { captureFrame = 0; capture(); }); }; const atBottom = () => scroll.scrollHeight - scroll.scrollTop - scroll.clientHeight < 25; pinned.current = true; const onScroll = () => { if (followFrame !== 0 || layoutDepth > 0) return; if (lastWrittenTop !== null && Math.abs(scroll.scrollTop - lastWrittenTop) < 1) return; const bottom = atBottom(); pinned.current = bottom; if (!bottom) { cancelAnimationFrame(followFrame); followFrame = 0; scheduleCapture(); } if (!following.current) { if (bottom) { following.current = true; setDetached(false); } return; } if (!bottom) { following.current = false; setDetached(true); } }; const onWheel = (event) => { cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null; if (event.deltaY < 0) { following.current = false; setDetached(true); pinned.current = false; scheduleCapture(); } }; const onTouch = () => { cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null; }; const onKey = (event) => { if (event.target instanceof HTMLElement && event.target.closest("textarea,input,[contenteditable=true]")) return; if ([ "PageUp", "Home", "ArrowUp" ].includes(event.key)) { cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null; following.current = false; setDetached(true); pinned.current = false; scheduleCapture(); } }; const writeTop = (top) => { scroll.scrollTop = top; lastWrittenTop = scroll.scrollTop; }; const follow = (now) => { followFrame = 0; if (!following.current || selected() || editingText()) return; if (layoutDepth > 0) return; const gap = scroll.scrollHeight - scroll.clientHeight - scroll.scrollTop; const delta = Math.min(48, Math.max(1, now - lastFrameAt)); lastFrameAt = now; if (!motion || Math.abs(gap) < 1.5) { writeTop(scroll.scrollHeight); capture(); return; } writeTop(scroll.scrollTop + gap * (1 - Math.exp(-delta / 52))); followFrame = requestAnimationFrame(follow); }; const firstFrame = requestAnimationFrame(() => { if (following.current && !selected()) writeTop(scroll.scrollHeight); capture(); }); let lastHeight = content.scrollHeight; const observer = new ResizeObserver(() => { if (selected()) return; const height = scroll.scrollHeight; const grew = height > lastHeight + 1; lastHeight = height; if (grew && pinned.current && !editingText()) { following.current = true; setDetached(false); } if (following.current && !editingText()) { if (!motion || layoutDepth > 0) writeTop(scroll.scrollHeight); else if (!followFrame) { lastFrameAt = performance.now(); followFrame = requestAnimationFrame(follow); } } else if (!following.current && anchor.current?.element.isConnected) { const delta = anchor.current.element.getBoundingClientRect().top + scroll.scrollTop - anchor.current.docTop; if (Math.abs(delta) > .5) writeTop(scroll.scrollTop + delta); } capture(); }); observer.observe(content); if (scroll !== content) observer.observe(scroll); content.addEventListener("reader-layout-start", layoutStart); content.addEventListener("reader-layout-end", layoutEnd); scroll.addEventListener("scroll", onScroll, { passive: true }); scroll.addEventListener("wheel", onWheel, { passive: true }); scroll.addEventListener("touchstart", onTouch, { passive: true }); scroll.addEventListener("touchmove", onTouch, { passive: true }); scroll.addEventListener("keydown", onKey); return () => { cancelAnimationFrame(firstFrame); cancelAnimationFrame(followFrame); cancelAnimationFrame(captureFrame); observer.disconnect(); content.removeEventListener("reader-layout-start", layoutStart); content.removeEventListener("reader-layout-end", layoutEnd); scroll.style.overflowAnchor = previousOverflowAnchor; scroll.removeEventListener("scroll", onScroll); scroll.removeEventListener("wheel", onWheel); scroll.removeEventListener("touchstart", onTouch); scroll.removeEventListener("touchmove", onTouch); scroll.removeEventListener("keydown", onKey); }; }, [root, motion]); return { detached, jump: (0, react.useCallback)(() => { cancelFollow.current(); anchor.current = null; following.current = true; pinned.current = true; setDetached(false); if (port.current) port.current.scrollTop = port.current.scrollHeight; }, []), release: (0, react.useCallback)(() => { cancelFollow.current(); following.current = false; pinned.current = false; anchor.current = null; setDetached(true); }, []) }; } // src/client/fold-choreography.ts /** Presentation clock, not model/network time. */ const FOLD_TIMING = { collapse: 320, count: 160, settle: 80, reveal: 180, /** * Slack added to every phase deadline before the watchdog forces the next phase. * * The choreography advances on animation promises and rendered frames. Both are * best-effort: a cancelled animation *rejects* and a compositor that never * finishes one leaves its promise pending, while a backgrounded tab stops * delivering frames. Without a deadline the machine would sit in a non-idle * phase forever, and a non-idle phase freezes both the frame source and the text * reveal, so the turn would look stuck until a remount. This is the liveness * guarantee that does not depend on any of them. */ watchdogSlack: 240 }; /** A step always has the same parent and React key, even when its membership changes. */ function flowRows(items) { return items.flatMap((item) => item.kind === "fold" ? [{ kind: "summary", key: item.key, item }, ...item.steps.map((step) => ({ kind: "step", key: step.key, step, foldKey: item.key }))] : [{ kind: "step", key: item.key, step: item.step }]); } function retiringKeys(before, after, open) { const folded = new Set(flowRows(after).filter((row) => row.kind === "step" && row.foldKey && !open[row.foldKey]).map((row) => row.key)); return flowRows(before).filter((row) => row.kind === "step" && !row.foldKey && folded.has(row.key)).map((row) => row.key); } /** Insert only new summary slots. Never admit incoming content during shrink. */ function collapseRows(before, target) { const rows = flowRows(before); const headers = new Set(rows.filter((row) => row.kind === "summary").map((row) => row.key)); for (const item of target) { if (item.kind !== "fold" || headers.has(item.key)) continue; const members = new Set(item.steps.map((step) => step.key)); const at = rows.findIndex((row) => members.has(row.key)); if (at >= 0) rows.splice(at, 0, { kind: "summary", key: item.key, item: { ...item, summary: item.summary.replace(/\d+/g, "0") } }); } return rows; } function containsNewUser(before, after) { const users = new Set(before.filter((item) => item.kind === "user").map((item) => item.key)); return after.some((item) => item.kind === "user" && !users.has(item.key)); } // src/client/LiveFold.tsx /** Values are presentation commits, never live network counters. */ function SubtleNumberRoll({ value, motion }) { const [outgoing, setOutgoing] = (0, react.useState)(null); const previous = (0, react.useRef)(value); (0, react.useLayoutEffect)(() => { if (value === previous.current) return; const old = previous.current; previous.current = value; if (!motion) { setOutgoing(null); return; } setOutgoing(old); const timer = window.setTimeout(() => setOutgoing(null), FOLD_TIMING.count); return () => window.clearTimeout(timer); }, [value, motion]); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.numberRollRoot, "aria-hidden": "true", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.numberRollSizer, children: value }), outgoing !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: `${Reader_module_css_default.numberRollDigit} ${Reader_module_css_default.numberRollExit}`, children: outgoing }, `out-${outgoing}`), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: `${Reader_module_css_default.numberRollDigit} ${outgoing !== null ? Reader_module_css_default.numberRollEnter : ""}`, children: value }, `cur-${value}`) ] }); } function FoldSummaryText({ summary, motion }) { const parts = (0, react.useMemo)(() => { const regex = /([^\d]+)(\d+)/g; const result = []; let end = 0; for (const match of summary.matchAll(regex)) { result.push({ text: match[1], number: Number(match[2]) }); end = match.index + match[0].length; } if (end < summary.length) result.push({ text: summary.slice(end) }); return result; }, [summary]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.foldSummary, "data-reader-fold-summary": summary, "aria-label": summary, children: parts.map((part) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.foldSummaryPart, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: part.text }), part.number !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SubtleNumberRoll, { value: part.number, motion })] }, part.text)) }); } // src/client/projection.ts function groupNodes(order, get) { const groups = []; const seenTurns = /* @__PURE__ */ new Set(); for (const key of order) { const node = get(key); if (!node || node.visibility === "hidden") continue; const turn = node.location.kind === "step" || node.location.kind === "turn" ? node.location.turn.turn : null; const previous = groups.at(-1); if (turn !== null && previous?.turn === turn) previous.keys.push(key); else { groups.push({ key: turn === null ? `node:${key}` : seenTurns.has(turn) ? `turn:${turn}:${key}` : `turn:${turn}`, turn, keys: [key] }); if (turn !== null) seenTurns.add(turn); } } return groups; } function boundaryOf(turn) { return { status: turn?.status ?? "unknown", reason: turn?.end?.data.reason.kind ?? null, latestStep: turn?.steps.at(-1)?.step ?? -1, closingStep: turn?.data.get("turn-tail")?.closing?.step ?? null }; } /** * A settled body step before the closing step of a successful turn. * * This is presentation classification only. Narration is never process content * and never folds. The flag only marks body text that is no longer the turn's * final answer, so copy and fork stay on that final answer. */ function isEarlierNarration(data, boundary) { if (data.status !== "settled" || boundary.status !== "closed" || boundary.reason !== "completed") return false; if (data.blocks.some((block) => block.kind === "image" || block.kind === "other")) return false; return boundary.closingStep !== null && data.step < boundary.closingStep; } function processExpanded(choice, boundary) { return choice ?? !(boundary.status === "closed" && boundary.reason === "completed"); } /** Reading while running must not pin the process open after completion. */ function processChoiceKey(groupKey, boundary) { return `${groupKey}:${boundary.status}:${boundary.reason ?? "pending"}`; } /** * A body-only assistant step is not a thinking/process disclosure. * * Narration (text/image/other blocks) is always visible, so it never counts as * foldable process content; only literal reasoning does. Tool calls arrive as * their own flow entries and are checked separately by the reader. */ function hasProcessContent(node, _boundary) { if (!node || node.visibility === "hidden") return false; if (node.kind === "assistant-step") return node.data.blocks.some((block) => block.kind === "reasoning" && block.text.trim() !== ""); return node.kind === "context" || node.kind === "model-retry" || node.kind === "system-prompt" || node.kind === "turn-process" || node.kind === "command" || node.kind === "manual-compaction" || node.kind === "compaction"; } function hasVisibleBody(blocks) { return blocks.some((block) => block.kind === "image" || block.kind === "other" || block.kind === "text" && block.text.trim() !== ""); } /** Keep native block order. In particular, never lift a later Think above text. */ function assistantSegments(blocks) { const segments = []; let previous; blocks.forEach((block, index) => { if (block.kind === "tool-call") { previous = void 0; return; } const kind = block.kind === "reasoning" ? "reasoning" : "body"; if (previous?.kind === kind) previous.blocks.push(block); else { previous = { kind, start: index, blocks: [block] }; segments.push(previous); } }); return segments; } function terminalLabel(reason) { switch (reason) { case "completed": return null; case "aborted": case "interrupted": return "本轮已停止,已生成的内容仍保留。"; case "blocked": return "本轮需要处理阻塞事项;请查看原对话与下方操作区。"; case "max-tokens": return "输出达到本轮长度限制,内容可能尚未完整。"; case "error": return "本轮未完成;错误信息保留在下方。"; case null: return null; default: return `本轮结束状态:${reason}。请在原对话中核对完整记录。`; } } /** * Extract the first usable fork anchor seq from candidate message nodes. * Only the durable closing message seq cuts the intended turn prefix: an * absent anchor must surface as undefined (never as 0 or NaN), because the * host treats a missing atSeq as a whole-session fork. */ function forkAnchorSeq(candidates) { for (const candidate of candidates) { const seq = candidate?.seq; if (typeof seq === "number" && Number.isFinite(seq)) return seq; } } // src/client/AssistantNode.tsx function isNode$1(node, kind) { return node.kind === kind; } const AssistantNode = (0, react.memo)(function AssistantNode({ useChat, nodeKey, boundary, processOpen = false, pinned = false, folded = false, partStart, seamSummary, seamAfter = false, motion, onRead, returnFocusTo, ...render }) { const node = useChat((snapshot) => snapshot.nodes.get(nodeKey)); if (!node || node.visibility === "hidden" || !isNode$1(node, "assistant-step")) return null; const data = node.data; const parts = assistantSegments(data.blocks); const earlier = isEarlierNarration(data, boundary); const hasToolCalls = data.blocks.some((block) => block.kind === "tool-call"); const isProcessStep = earlier || folded || hasToolCalls || boundary.latestStep > 0 && data.step < boundary.latestStep; const body = data.blocks.filter((block) => block.kind !== "reasoning" && block.kind !== "tool-call"); const visible = partStart === void 0 ? parts : parts.filter((part) => part.start === partStart); const bodyProps = { streaming: data.status === "running", holdFormatting: pinned, startedAt: data.time, interrupted: data.status === "interrupted", liveText: true }; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: visible.map((part) => { const last = parts.findIndex((item) => item.start === part.start) === parts.length - 1; if (part.kind === "reasoning") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProcessFragment, { open: processOpen, motion, onRead, returnFocusTo, nodeKey, framed: true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ReasoningCard, { step: data.step, active: processOpen && boundary.status === "open" && data.step === boundary.latestStep, motion, selected: pinned, onRead, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Blocks, { ...render, blocks: part.blocks, streaming: data.status === "running" && last && data.blocks.at(-1)?.kind === "reasoning", holdFormatting: pinned, startedAt: data.time, interrupted: data.status === "interrupted", liveText: true }) }) }, part.start); if (!hasVisibleBody(part.blocks)) return null; const isFinalAnswer = !isProcessStep; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react.Fragment, { children: [seamSummary && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.processSeamRow, "data-reader-process-seam": true, "data-reader-process-seam-summary": seamSummary, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Disclosure, { open: false, onChange: () => onRead(), ariaLabel: "被折叠的过程", label: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FoldSummaryText, { summary: seamSummary, motion: false }) }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("article", { className: Reader_module_css_default.answer, "data-reader-body": true, "data-reader-anchor": true, "data-reader-key": nodeKey, "data-reader-source-start": part.start, "data-reader-seam-after": seamAfter || void 0, "data-answer-status": data.status, "data-answer-phase": isFinalAnswer ? "body" : "process", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OfficialAssistantBody, { ...render, node, blocks: part.blocks, ...bodyProps }), isFinalAnswer && last && data.status === "interrupted" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.stopped, children: "已停止" }), isFinalAnswer && last && data.status !== "running" && boundary.status === "closed" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopyAnswer, { blocks: body, onFork: (() => { const anchor = forkAnchorSeq([data.finalNode, { seq: render.forkSeq }]); return render.forkAt && anchor !== void 0 ? () => render.forkAt(anchor) : void 0; })(), metrics: render.metrics, extraActions: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OfficialActions, { official: render.official, messageId: data.finalNode?.messageId }) }) ] })] }, part.start); }) }); }); // src/client/native/tool-call-model.ts /** * Pure row-model derivation for tool summary rows: variant classification, * one-line summary, expanded-body text, and flattened result output from the * frozen call slice. Input material comes from the call ARGUMENTS; output and * error material from the settled result node. A call whose render intent is * a terminal card gets its expanded body from the views instead, through * `terminalCardModel` in terminal-card-model.ts. */ /** Figma row titles per variant (design literals, not translatable copy). */ const VARIANT_TITLES = { search: "Search", read: "Read", bash: "Bash", write: "Write", edit: "Edit", code: "Code", others: "Tool call" }; /** * Known tool name -> variant. * * `cordis_define` is deliberately absent: ui-cordis registers a keyed * `tool.call.toolview` entry for it, and a keyed hit REPLACES the generic row * (this table is only reached through GenericToolCard, the dispatch fallback in * ToolCallTree). An entry here would be unreachable, and a second title for the * same call would be a second answer to a question the card already owns. */ const TOOL_VARIANTS = { bash: "bash", pwsh: "bash", read: "read", web_fetch: "read", web_search: "search", grep: "search", glob: "search", write: "write", edit: "edit", run_code: "code", cordis_package_inspect: "read", cordis_runtime_inspect: "read", cordis_run: "others", cordis_stop: "others", cordis_undefine: "others" }; /** Tool-owned titles that refine a generic row variant without replacing it. */ const TOOL_TITLES = { cordis_package_inspect: "Inspect", cordis_runtime_inspect: "Inspect", cordis_run: "Run Cordis Plugin", cordis_stop: "Stop Cordis Plugin", cordis_undefine: "Remove Cordis Plugin", pwsh: "Pwsh" }; /** * Classify a tool name into its row variant. * @param toolName - wire tool name. * @returns matching variant, others when unknown. */ function classifyTool(toolName) { return TOOL_VARIANTS[toolName] ?? "others"; } /** * Flatten a settled result's content blocks to display text: text blocks * verbatim, other block shapes as pretty JSON. Empty content on a failed call * falls back to the structured error's `name: code` line. * @param node - the settled result node. * @returns the flattened result text (may be empty). */ function resultText(node) { const parts = []; for (const block of node.content) if (block.type === "text") parts.push(block.text); else parts.push(JSON.stringify(block, null, 2)); if (parts.length === 0 && node.error !== void 0) parts.push(`${node.error.name}: ${node.error.code}`); return parts.join("\n"); } function parseArgs(argsRaw) { try { return JSON.parse(argsRaw); } catch { return; } } function firstLine(text) { const nl = text.indexOf("\n"); return nl === -1 ? text : text.slice(0, nl); } function pickString(args, keys) { for (const key of keys) { const v = args[key]; if (typeof v === "string" && v !== "") return v; } } /** Summary key preference per variant (args-derived; result-derived summaries are a ledger item). */ const SUMMARY_KEYS = { bash: ["description", "command"], read: [ "path", "file_path", "url" ], search: [ "query", "pattern", "url" ], write: ["path", "file_path"], edit: ["path", "file_path"], code: ["description"], others: [] }; /** * Strip the workspace root from a workspace-rooted absolute path (display only). * @param text - the path to shorten. * @param cwd - session workspace root; absent or empty leaves the path unchanged. * @returns the path relative to the workspace root, or unchanged when it is not rooted there. */ function relativizeToCwd(text, cwd) { if (cwd === void 0 || cwd === "") return text; const root = cwd.replace(/[/\\]+$/, ""); if (text.startsWith(`${root}/`) || text.startsWith(`${root}\\`)) return text.slice(root.length + 1); return text; } function deriveSummary(variant, argsRaw) { const parsed = parseArgs(argsRaw); if (typeof parsed !== "object" || parsed === null) return firstLine(argsRaw); const args = parsed; if (variant === "search" && Array.isArray(args.queries)) { const queries = args.queries.filter((query) => typeof query === "string" && query !== ""); if (queries.length > 0) return queries.map(firstLine).join(", "); } const picked = pickString(args, SUMMARY_KEYS[variant]); if (picked !== void 0) return firstLine(picked); for (const v of Object.values(args)) if (typeof v === "string" && v !== "") return firstLine(v); return firstLine(argsRaw); } /** Path keys only — never `url` (web_fetch lands on the read variant). */ const FILE_PATH_KEYS = ["path", "file_path"]; /** File-tool variants whose summary may be an openable workspace path. */ const FILE_PATH_VARIANTS = /* @__PURE__ */ new Set([ "read", "write", "edit" ]); function deriveFilePath(variant, argsRaw) { if (!FILE_PATH_VARIANTS.has(variant)) return void 0; const parsed = parseArgs(argsRaw); if (typeof parsed !== "object" || parsed === null) return void 0; const picked = pickString(parsed, FILE_PATH_KEYS); return picked === void 0 ? void 0 : firstLine(picked); } function deriveBody(variant, argsRaw) { if (argsRaw === "") return null; const parsed = parseArgs(argsRaw); if (parsed === void 0) return argsRaw; if (variant === "code" && typeof parsed === "object" && parsed !== null) { const code = parsed.code; if (typeof code === "string" && code !== "") return code; } return JSON.stringify(parsed, null, 2); } /** * Derive the full row model from a frozen call slice. * @param toolName - wire tool name (dispatch-supplied; survives windowless results). * @param block - RunningToolCall or ToolResultNode off the snapshot caches. * @param cwd - session workspace root; workspace-rooted path summaries display relative to it. * @param home - host account home; a leftover POSIX home path displays as `~`. * @returns the row model. */ function toolRowModel(toolName, block, cwd, home) { const variant = classifyTool(toolName); const done = "kind" in block; const argsRaw = (done ? block.call?.argsRaw : "argsRaw" in block ? block.argsRaw : "") ?? ""; const state = !done ? "running" : block.error?.code === "interrupted" ? "stopped" : block.isError ? "error" : "ok"; const base = argsRaw === "" ? block.callId : abbreviateHomePath(relativizeToCwd(deriveSummary(variant, argsRaw), cwd), home); const toolTitle = TOOL_TITLES[toolName]; const summary = variant === "others" && toolName !== "" && toolTitle === void 0 ? `${toolName} · ${base}` : base; const output = done ? resultText(block) || null : null; const errorSummary = state === "error" && output !== null ? firstLine(output) : null; return { variant, title: toolTitle ?? VARIANT_TITLES[variant], summary, filePath: deriveFilePath(variant, argsRaw), body: deriveBody(variant, argsRaw), output, errorSummary, state }; } // src/client/ToolActivity.tsx const LABEL = { preparing: "输入生成中", running: "执行中", returned: "已返回", succeeded: "已完成", failed: "失败", interrupted: "已中断" }; const ICONS = { write: _deepseek_ai_dsh_client_ui_primitives.IconEditOutlineRegular, read: _deepseek_ai_dsh_client_ui_primitives.IconBrowseOutlineRegular, terminal: _deepseek_ai_dsh_client_ui_primitives.IconApiOutlineRegular, search: _deepseek_ai_dsh_client_ui_primitives.IconSearchOutlineRegular, web: _deepseek_ai_dsh_client_ui_primitives.IconSearchOutlineRegular, code: _deepseek_ai_dsh_client_ui_primitives.IconApiOutlineRegular, other: _deepseek_ai_dsh_client_ui_primitives.IconSparkleRegular }; const number = new Intl.NumberFormat("zh-CN"); const preparingTerminalLabels = { ...terminalBlockLabels, running: "正在生成命令" }; const language = (path) => path?.split(".").at(-1); const duration = (ms) => ms < 1e3 ? `${Math.round(ms)} 毫秒` : `${(ms / 1e3).toFixed(ms < 1e4 ? 1 : 0)} 秒`; function generatedInput(content, target, preparing) { const lines = content.split("\n").map((text, index) => ({ number: index + 1, text })); const visible = preparing ? lines.slice(-12) : lines.slice(0, 1600); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { "data-reader-tool-file": true, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", { className: Reader_module_css_default.toolDetailNote, children: [preparing ? "正在生成的输入 · 尚未执行 · 末尾 12 行" : "工具输入中的文件内容", !preparing && lines.length > visible.length ? " · 预览前 1,600 行,完整内容在原始数据中" : ""] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.ReadBlock, { label: target ?? "文件内容", lang: language(target), lines: visible, totalLines: lines.length, maxLines: 16, labels: readBlockLabels })] }); } function InputView({ model, phase, fillComposer }) { const preparing = phase === "preparing"; const inProgress = preparing || phase === "running"; if ((model.name === "render_ui" || model.name === "show_widget") && typeof model.args?.html === "string") return preparing ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StreamingMcpAppPlaceholder, { title: typeof model.args.title === "string" ? model.args.title : void 0 }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(McpAppFrame, { html: model.args.html, title: typeof model.args.title === "string" ? model.args.title : void 0, fillComposer }); if (model.content) return generatedInput(model.content, model.target, preparing); if (model.command) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { "data-reader-tool-terminal": true, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, children: preparing ? "正在生成命令 · 尚未执行" : "提交的命令" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.TerminalBlock, { command: model.command, cwd: model.cwd, running: inProgress, labels: preparing ? preparingTerminalLabels : terminalBlockLabels })] }); if (model.category === "terminal" && preparing && model.argsState === "partial") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, "data-reader-tool-command-pending": true, children: "命令仍在生成,收到可识别的命令文本后会显示预览。" }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonTree, { data: model.args, label: preparing ? "已收到的输入字段" : "工具输入", labels: jsonTreeLabels }); } function readLines(value) { if (!Array.isArray(value)) return null; const lines = []; for (const item of value) { const row = objectValue(item); if (typeof row?.number !== "number" || !Number.isInteger(row.number) || typeof row.text !== "string") return null; lines.push({ number: row.number, text: row.text }); } return lines; } /** A step past this reads as slow rather than merely in progress. */ const SLOW_TOOL_MS = 1e4; function diffHunks(value) { if (!Array.isArray(value) || value.length === 0) return null; const diffs = []; for (const item of value) { const row = objectValue(item); if (typeof row?.path !== "string" || row.oldText !== null && typeof row.oldText !== "string" || typeof row.newText !== "string") return null; diffs.push({ path: row.path, oldText: row.oldText, newText: row.newText }); } return diffs; } function searchFiles(value) { if (!Array.isArray(value)) return null; const files = []; for (const item of value) { const row = objectValue(item); if (typeof row?.path !== "string" || !Array.isArray(row.matches)) return null; const matches = []; for (const itemMatch of row.matches) { const match = objectValue(itemMatch); if (typeof match?.lineNumber !== "number" || !Number.isInteger(match.lineNumber) || typeof match.line !== "string") return null; matches.push({ lineNumber: match.lineNumber, line: match.line }); } files.push({ path: row.path, matches }); } return files; } function ResultView(props) { const { official, entry, model } = props; const fallback = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ResultFallback, { ...props }); if (!official || !entry.block || model.name === "render_ui" || model.name === "show_widget") return fallback; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OfficialTool, { ...props, official, block: entry.block, toolName: model.name, cwd: props.cwd ?? model.cwd, fallback }); } function ResultFallback({ entry, model, phase, ...render }) { if ((model.name === "render_ui" || model.name === "show_widget") && typeof model.args?.html === "string") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(McpAppFrame, { html: model.args.html, title: typeof model.args.title === "string" ? model.args.title : void 0, fillComposer: render.fillComposer }); const block = entry.block; if (!block || !("kind" in block)) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, children: phase === "interrupted" ? "已中断,没有工具结果。已生成的输入仍可查看。" : phase === "preparing" ? "模型正在生成工具输入,工具还未开始执行。" : "工具已开始执行,正在等待结果。" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(InputView, { model, phase, fillComposer: render.fillComposer })] }); const meta = objectValue(block.meta); const text = block.content.filter((item) => item.type === "text").map((item) => item.text).join("\n"); if (phase === "interrupted") return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, children: "工具已取消,未正常完成。输入和原始返回记录仍可查看。" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(InputView, { model, phase, fillComposer: render.fillComposer }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { className: Reader_module_css_default.toolRaw, children: text }) ] }); if (model.category === "terminal") { const facts = executionFacts(block); const output = text.replace(/\n\[(?:exit code: \d+|killed by signal: [^\]\n]+)\]$/, ""); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-tool-terminal": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.TerminalBlock, { command: model.command ?? model.name, cwd: model.cwd, output, exitCode: facts.exitCode, signal: facts.signal, maxLines: 18, labels: terminalBlockLabels }) }); } const lines = readLines(meta?.lines); if (model.category === "read" && typeof meta?.path === "string" && typeof meta.totalLines === "number" && lines) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-tool-file": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.ReadBlock, { label: meta.path, lang: typeof meta.lang === "string" ? meta.lang : void 0, lines, totalLines: meta.totalLines, maxLines: 18, labels: readBlockLabels }) }); const diffs = diffHunks(meta?.diffs) ?? callDiffHunks(block, model.args, model.name); if (diffs.length) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-tool-diff": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.DiffBlock, { diffs, maxLines: 18, labels: diffBlockLabels }) }); if (model.category === "search" && typeof meta?.total === "number" && typeof meta.truncated === "boolean") { if (meta.shape === "paths" && Array.isArray(meta.paths) && meta.paths.every((path) => typeof path === "string")) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-tool-search": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SearchBlock, { kind: "paths", paths: meta.paths, total: meta.total, truncated: meta.truncated, maxLines: 18, labels: searchBlockLabels }) }); const files = searchFiles(meta.files); if (meta.shape === "matches" && files) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-tool-search": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.SearchBlock, { kind: "matches", files, total: meta.total, truncated: meta.truncated, maxLines: 18, labels: searchBlockLabels }) }); } if (model.category === "web" && typeof meta?.truncated === "boolean") { if (model.name === "web_fetch" && typeof meta.url === "string" && typeof meta.statusCode === "number") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-tool-web": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.WebBlock, { kind: "fetch", url: meta.url, statusCode: meta.statusCode, truncated: meta.truncated, labels: webBlockLabels }) }); if (model.name === "web_search" && Array.isArray(meta.sources)) { const sources = meta.sources.flatMap((source) => { const item = objectValue(source); return typeof item?.url === "string" ? [{ url: item.url, ...typeof item.title === "string" ? { title: item.title } : {}, ...typeof item.snippet === "string" ? { snippet: item.snippet } : {}, ...typeof item.publishedAt === "string" ? { publishedAt: item.publishedAt } : {} }] : []; }); if (sources.length === meta.sources.length) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-tool-web": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.WebBlock, { kind: "search", sources, answer: typeof meta.answer === "string" ? meta.answer : void 0, truncated: meta.truncated, labels: webBlockLabels }) }); } } if (model.category === "write" && model.content && !block.isError) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, children: "文件工具已返回。以下为提交的内容;完整返回记录可在「原始数据」查看。" }), generatedInput(model.content, model.target, false)] }); const content = block.content; if (model.category === "code") { const output = content.filter((item) => item.type === "text").map((item) => item.text).join("\n"); const facts = executionFacts(block); if (output.trim()) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-tool-code": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.TerminalBlock, { command: model.command ?? model.name, cwd: model.cwd, output, exitCode: facts.exitCode, signal: facts.signal, maxLines: 18, labels: terminalBlockLabels }) }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, children: "代码已执行,没有可展示的输出。" }); } if (content.some((item) => item.type === "text")) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.toolDocument, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Blocks, { ...render, blocks: contentBlocks(content).filter((item) => item.kind === "text"), source: "tool" }) }); if (content.length) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, children: "图片或扩展内容已在对话中单独展示。" }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, children: "工具没有返回可展示的内容。" }); } /** One occurrence, keyed by call id all the way from generation to result. */ const ToolActivity = (0, react.memo)(function ToolActivityView({ entry, motion, turnClosed, onRead, depth = 0, ...render }) { const [open, setOpen] = (0, react.useState)(false); const [tab, setTab] = (0, react.useState)("result"); const control = (0, react.useRef)(null); const panel = (0, react.useRef)(null); const [selected, setSelected] = (0, react.useState)(false); const detailId = (0, react.useId)(); const tabRefs = (0, react.useRef)([]); const model = (0, react.useMemo)(() => activitySummary(entry), [entry.block, entry.draft]); const phase = activityPhase(entry, turnClosed); const heldPreview = (0, react.useRef)({ entry, model, phase }); if (!selected) heldPreview.current = { entry, model, phase }; const preview = heldPreview.current; (0, react.useEffect)(() => { const track = () => { const selection = document.getSelection(); setSelected(!!selection && !selection.isCollapsed && !!selection.anchorNode && !!panel.current?.contains(selection.anchorNode)); }; document.addEventListener("selectionchange", track); return () => document.removeEventListener("selectionchange", track); }, []); const facts = executionFacts(entry.block); const Icon = model.name === "skill" ? _deepseek_ai_dsh_client_ui_primitives.IconSkillOutlineRegular : ICONS[model.category]; const block = entry.block; const native = block ? toolRowModel(model.name, block) : null; const skillName = typeof model.args?.name === "string" ? model.args.name.split("\n")[0] : model.raw.split("\n")[0]; const rowTitle = model.name === "skill" ? "Skill" : native?.title ?? VARIANT_TITLES[classifyTool(model.name)]; const rowSummary = phase === "interrupted" ? "已停止 · 调用记录保留" : model.name === "skill" ? skillName : native?.errorSummary ?? native?.summary ?? (classifyTool(model.name) === "others" ? `${model.name} · ${model.target ?? model.title}` : model.target ?? model.title); const diff = (0, react.useMemo)(() => diffTotals$1(block, model.args, model.name), [ block, model.args, model.name ]); const showState = phase === "preparing" || phase === "running" || phase === "failed" || phase === "interrupted"; const running = phase === "preparing" || phase === "running"; const [liveMs, setLiveMs] = (0, react.useState)(null); (0, react.useEffect)(() => { if (!running) { forgetCallClock(entry.callId); setLiveMs(null); return; } const base = runningClockBase(entry.callId, block); const tick = () => setLiveMs(Math.max(0, Date.now() - base)); tick(); const timer = setInterval(tick, 200); return () => clearInterval(timer); }, [ running, block, entry.callId ]); const elapsed = block && "kind" in block && block.callTime != null ? Math.max(0, block.time - block.callTime) : null; const shownMs = liveMs ?? (elapsed !== null && elapsed >= SLOW_TOOL_MS ? elapsed : null); const rawResult = (0, react.useMemo)(() => { const value = preview.entry.block; return value && "kind" in value ? JSON.stringify({ content: value.content, isError: value.isError, meta: value.meta }, null, 2) : ""; }, [preview.entry.block]); const tabs = [ ["result", phase === "preparing" ? "生成预览" : "结果"], ["input", "输入"], ["raw", "原始数据"] ]; const activate = (index) => { const item = tabs[(index + tabs.length) % tabs.length]; setTab(item[0]); tabRefs.current[(index + tabs.length) % tabs.length]?.focus(); }; if (depth > 6) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.meta, children: "更深的嵌套调用可在原对话查看。" }); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { ref: (element) => { control.current = element?.querySelector("[data-disclosure-row]") ?? null; }, className: Reader_module_css_default.toolActivity, "data-reader-tool-call": entry.callId, "data-tool-phase": phase, "data-tool-args-length": model.raw.length, "data-tool-category": model.category, "data-expanded": open, "data-ud-check": "reader-tool-activity", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.DisclosureRow, { icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, { size: 14 }), title: rowTitle, open, expandable: true, expandOnRowClick: true, keepContentWhenOpen: true, onToggle: () => { onRead(); setOpen((value) => !value); }, rowClassName: Reader_module_css_default.nativeToolRow, collapsedContent: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.rowSeparator, "aria-hidden": true }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.nativeToolSummary, title: rowSummary, "data-reader-tool-summary": true, ...running ? { "data-running": "" } : {}, children: rowSummary }), shownMs !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.toolElapsed, "data-reader-tool-elapsed": true, ...shownMs >= SLOW_TOOL_MS ? { "data-slow": "" } : {}, children: [(shownMs / 1e3).toFixed(shownMs < 1e4 ? 1 : 0), "s"] }), diff && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.diffStat, "data-reader-diff-stat": true, children: [diff.added > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.diffAdded, children: ["+", number.format(diff.added)] }), diff.removed > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.diffRemoved, children: ["-", number.format(diff.removed)] })] }), showState && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.toolState, "data-phase": phase, children: LABEL[phase] }) ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProcessFragment, { open, motion, onRead, returnFocusTo: control, nodeKey: `${entry.key}:detail`, framed: true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { id: detailId, className: Reader_module_css_default.toolDetails, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.toolLedger, "aria-live": "off", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: ["工具 · ", /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.toolEngine, children: model.name })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { "data-reader-tool-progress": true, children: phase === "preparing" ? `已接收 ${number.format(model.raw.length)} 字符输入` : phase === "running" ? "已提交 · 等待工具返回" : phase === "interrupted" ? "已停止 · 输入记录保留" : elapsed !== null ? `执行 ${duration(elapsed)}` : "结果已记录" }), facts.exitCode !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: ["退出码 ", facts.exitCode] }), facts.signal && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: ["信号 ", facts.signal] }) ] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.toolTabs, role: "tablist", "aria-label": `${model.title}的执行数据`, onKeyDown: (event) => { const index = tabs.findIndex((item) => item[0] === tab); if (event.key === "ArrowRight" || event.key === "ArrowLeft") { event.preventDefault(); activate(index + (event.key === "ArrowRight" ? 1 : -1)); } else if (event.key === "Home" || event.key === "End") { event.preventDefault(); activate(event.key === "Home" ? 0 : tabs.length - 1); } }, children: tabs.map(([id, title], index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { ref: (element) => { tabRefs.current[index] = element; }, type: "button", role: "tab", id: `${detailId}-${id}`, "aria-selected": tab === id, "aria-controls": `${detailId}-panel`, tabIndex: tab === id ? 0 : -1, onClick: () => setTab(id), children: title }, id)) }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { ref: panel, id: `${detailId}-panel`, className: Reader_module_css_default.toolPanel, role: "tabpanel", "aria-labelledby": `${detailId}-${tab}`, tabIndex: 0, children: [ selected && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, children: "为保留选区,预览暂停更新;当前状态见卡片标题。" }), tab === "result" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ResultView, { ...render, ...preview }), tab === "input" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(InputView, { model: preview.model, phase: preview.phase, fillComposer: render.fillComposer }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", { className: Reader_module_css_default.detail, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", { children: "全部输入字段" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonTree, { data: preview.model.args, label: "输入字段", labels: jsonTreeLabels })] })] }), tab === "raw" && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.toolDetailNote, children: "完整记录 · 只读 · 不执行其中的代码" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", { className: Reader_module_css_default.toolRawLabel, children: "工具输入" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { className: Reader_module_css_default.toolRaw, children: preview.model.raw || "输入尚未到达" }), rawResult && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", { className: Reader_module_css_default.toolRawLabel, children: "工具结果" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { className: Reader_module_css_default.toolRaw, children: rawResult })] }) ] }) ] }) ] }) }), !!block?.subCalls.length && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.toolChildren, "aria-label": "子调用", children: block.subCalls.map((child, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolActivity, { ...render, entry: { kind: "tool", key: `reader-tool:${child.callId}`, callId: child.callId, step: entry.step, order: index, block: child }, motion, turnClosed, onRead, depth: depth + 1 }, child.callId)) }) ] }); }, (previous, next) => previous.entry.callId === next.entry.callId && previous.entry.block === next.entry.block && previous.entry.draft === next.entry.draft && previous.entry.step === next.entry.step && previous.motion === next.motion && previous.turnClosed === next.turnClosed && previous.depth === next.depth && previous.onRead === next.onRead && previous.renderSlotChain === next.renderSlotChain && previous.loadImage === next.loadImage && previous.fillComposer === next.fillComposer && previous.official === next.official && previous.cwd === next.cwd && previous.openFile === next.openFile); /** Rich media (images, MCP widgets) rendered outside the folded tool ledger. */ function ToolMedia({ block, depth = 0, ...render }) { if (depth > 6) return null; const visible = "kind" in block ? contentBlocks(block.content).filter((item) => item.kind === "image" || item.kind === "other") : []; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [visible.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Blocks, { ...render, blocks: visible, source: "tool" }), block.subCalls.map((child) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolMedia, { ...render, block: child, depth: depth + 1 }, child.callId))] }); } // src/client/open-file.ts function deliverableOpenModeOf(value) { return value === "sidebar" ? "sidebar" : "external"; } function modeFromSnapshot(store) { try { return deliverableOpenModeOf(store?.getSnapshot()?.deliverableOpenMode); } catch { return "external"; } } /** Workspace-folder affordances stay on the OS opener, not the Sidebar switch. */ function isFolderOpenPath(path) { return path === "." || path === ""; } function encodeSegment(segment) { return encodeURIComponent(segment).replace(/%3A/gi, ":"); } function encodePath(path) { return path.split("/").map(encodeSegment).join("/"); } /** * Session-scoped `dsh-resource://file/session/<id>/…` address. * Matches official `fileAddressFor` / `sessionFileAddress` (0.1.5). */ function fileAddressFor(sessionId, cwd, path) { const normalized = path.replace(/\\/g, "/"); const address = (relative) => { const cleaned = relative.replace(/\\/g, "/").replace(/^(?:\.\/)+/, ""); return `dsh-resource://file/session/${encodeSegment(sessionId)}/${encodePath(cleaned)}`; }; if (!isAbsoluteWorkspacePath(normalized)) return address(normalized); const root = cwd === void 0 ? "" : cwd.replace(/\\/g, "/").replace(/\/+$/, ""); if (root !== "" && normalized === root) return address(""); if (root !== "" && normalized.startsWith(`${root}/`)) return address(normalized.slice(root.length + 1)); return address(normalized); } function resolveOpenWorkspacePath(cwd, path, resolveWorkspacePath) { return isFolderOpenPath(path) ? cwd ?? "." : resolveWorkspacePath(cwd, path); } async function openDeliverableFile(args) { const targetPath = resolveOpenWorkspacePath(args.cwd, args.path, args.resolveWorkspacePath); if (args.mode === "sidebar" && !isFolderOpenPath(args.path)) { if (typeof args.openSidebar !== "function") args.warn?.("[dsh-better-display] sidebarRight.openResource is not available; falling back to system app"); else try { const address = (args.fileAddressFor ?? fileAddressFor)(args.sessionId, args.cwd, args.path); args.openSidebar(address); return "sidebar"; } catch (error) { args.warn?.("[dsh-better-display] sidebar open failed; falling back to system app", error); } } await args.openExternal(targetPath); return "external"; } // src/client/pending-submission.ts function asReadonlyArray(value) { return Array.isArray(value) ? value : []; } function isImage(value) { return value !== null && typeof value === "object" && typeof value.previewUrl === "string"; } /** * Safe image list for conversation.view pending echoes. * Official 0.1.5 uses `images`; older hosts used `attachments`. * Either field may be missing — never read `.length` on undefined. */ function pendingSubmissionImages(submission) { if (submission == null) return []; if (Array.isArray(submission.images)) return submission.images.filter(isImage); if (Array.isArray(submission.attachments)) { const images = []; for (const item of submission.attachments) if (item?.type === "image" && isImage(item.value)) images.push(item.value); return images; } return []; } // src/client/WaitClock.tsx /** Past this, a wait stops being a pause and reads as the model not answering. */ const WAIT_OVERTIME_MS = 1e4; /** * How long the model has been given the turn, counted in plain seconds. * * Just the number and, past ten seconds, a「暂未响应」badge — no bar, because the * question the reader has is「how long has this been hanging」, not「how far * along」: there is no known total to be a fraction of. * * The clock restarts whenever the anchor changes, so each wait is timed from the * event that started it rather than from the beginning of the turn. */ function WaitClock({ startTime }) { const [mountedAt] = (0, react.useState)(() => Date.now()); const [now, setNow] = (0, react.useState)(() => Date.now()); const anchor = startTime ?? mountedAt; (0, react.useEffect)(() => { const id = setInterval(() => setNow(Date.now()), 250); return () => clearInterval(id); }, []); const waited = Math.max(0, now - anchor); const overtime = waited >= WAIT_OVERTIME_MS; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.waitClock, "data-reader-wait-clock": true, ...overtime ? { "data-overtime": "" } : {}, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.waitSeconds, children: formatRunDuration(waited) }), overtime && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.waitOvertime, "data-reader-wait-badge": true, children: "暂未响应" })] }); } // src/client/WaitingStatus.tsx function WaitingStatus({ anchor, label }) { return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.turnStatus, role: "status", "aria-live": "polite", "data-reader-turn-status": true, "data-reader-wait-start": anchor.time ?? "", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.turnStatusLabel, children: label }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WaitClock, { startTime: anchor.time }, anchor.key)] }); } // src/client/waiting-clock.ts const timestamp = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; /** * Chat-layer kinds that hand the turn back to the model unconditionally. * * These are `ChatNodeDataMap` keys, NOT conversation-layer `ConversationNode` kinds. * The two layers name the same idea differently: a returned tool is `tool-result` * in the conversation contract, but the row the reader sees is the `tool-call` node. * A name copied from the wrong layer silently disables the branch it guards, so * the `satisfies` below makes the compiler reject any name that is not a real kind. */ const WAIT_AFTER = /* @__PURE__ */ new Set(["context", "model-retry"]); /** * Mirrors the host's `isSettledTool`: a running call has no `kind`, a settled one * carries `kind: 'tool-result'`. Kept local so this module stays dependency-free, * and pinned by a test against the host's own helper contract. */ function toolSettled(data) { const root = data?.root; return typeof root === "object" && root !== null && root.kind === "tool-result"; } /** A command that is still executing has no outcome yet; only a settled one hands over. */ function commandSettled(data) { return data?.outcome != null; } /** * Does this node leave the model on the hook for the next move? * * A tool or command that is *still running* is not a wait — the tool is the one * working. Only its returned form hands control back, which is exactly the moment * the model can stall. */ function handsBackToModel(node) { if (node.kind === "user" || node.kind === "steering") return true; if (node.kind === "tool-call") return toolSettled(node.data); if (node.kind === "command") return commandSettled(node.data); return WAIT_AFTER.has(node.kind); } /** * The moment the current wait began. * * This is the time of the **last** node that handed control to the model — a * returned tool, an injected context, or the user's own message. Anchoring on the * user's message alone made the readout count the entire turn, so a wait that had * only just begun showed the minutes the tools had already spent. */ function waitingAnchor(order, get, pending = []) { let anchor = { key: "unresolved", time: null }; for (let i = order.length - 1; i >= 0; i--) { const node = get(order[i]); if (!node) continue; if (!handsBackToModel(node)) continue; const time = node.data && typeof node.data === "object" && "time" in node.data && typeof node.data.time === "number" ? node.data.time : void 0; anchor = { key: order[i], time: timestamp(time) }; break; } for (let i = pending.length - 1; i >= 0; i--) { const input = pending[i]; if (input.placement === "queued") continue; const time = timestamp(input.time); if (time === null || anchor.time === null || time >= anchor.time) return { key: `pending:${input.requestId}`, time }; break; } return anchor; } // src/client/native/ReferenceIcon.tsx /** * Render the icon that identifies one inline reference domain. * @param props - Reference kind, optional size, and optional CSS class. * @returns The corresponding current-color SVG glyph. */ function ReferenceIcon({ kind, size = 16, className }) { switch (kind) { case "session": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { width: size, height: size, className, viewBox: "0 0 16 16", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 0.597656C3.91296 0.597656 0.599716 3.91103 0.599609 7.99805C0.599609 9.13171 0.854567 10.2079 1.31152 11.1699L1.59277 11.7607L2.77441 11.1992L2.49414 10.6084L2.36035 10.3076C2.06865 9.59612 1.90723 8.81645 1.90723 7.99805C1.90733 4.63362 4.63554 1.90625 8 1.90625C11.3644 1.90635 14.0917 4.63368 14.0918 7.99805C14.0918 11.3625 11.3644 14.0907 8 14.0908C7.311 14.0908 6.80642 14.0414 6.35938 13.918C5.919 13.7963 5.50105 13.5929 5.00098 13.2441C4.26805 12.7329 3.21756 12.5526 2.35156 13.0996L2.33789 13.1084L2.32422 13.1182L1.74805 13.5234L2.18164 14.8184L3.05957 14.2002C3.37505 14.0068 3.84248 14.0319 4.25195 14.3174C4.84447 14.7307 5.39718 15.009 6.01172 15.1787C6.61963 15.3465 7.25579 15.3984 8 15.3984C12.087 15.3983 15.4004 12.0851 15.4004 7.99805C15.4003 3.9111 12.087 0.59776 8 0.597656ZM4.56836 8.50977V9.80371H8.12402V8.50977H4.56836ZM4.56836 7.30078H11.4619V6.00684H4.56836V7.30078Z", fill: "currentColor" }) }); case "file": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconBrowseOutlineRegular, { size, className }); case "folder": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderCloseRegular, { size, className }); } } // \0dshx-css-module:src/client/native/ContextBody.module.css.mjs const css$3 = "._1q5eoq_text{color:var(--dsw-alias-label-secondary);font:inherit;white-space:pre-wrap;overflow-wrap:anywhere;margin:0}._1q5eoq_fields{border-top:1px solid var(--dsw-alias-line-secondary);flex-direction:column;gap:2px;margin:8px 0 0;padding-top:8px;display:flex}._1q5eoq_field{gap:8px;min-width:0;display:flex}._1q5eoq_fieldKey{min-width:96px;color:var(--dsw-alias-label-caption);flex:none}._1q5eoq_fieldValue{min-width:0;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere;flex:auto;margin:0}._1q5eoq_files{flex-wrap:wrap;gap:4px 12px;margin:0 0 8px;padding:0;list-style:none;display:flex}._1q5eoq_file{align-items:baseline;gap:6px;min-width:0;display:flex}._1q5eoq_filePath{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}._1q5eoq_fileAction{color:var(--dsw-alias-label-caption)}._1q5eoq_catalogNotice{color:var(--dsw-alias-label-caption);margin:0 0 6px}._1q5eoq_entries{flex-direction:column;gap:4px;margin:0;padding:0;list-style:none;display:flex}._1q5eoq_entry{gap:8px;min-width:0;display:flex}._1q5eoq_entryName{color:var(--dsw-alias-label-secondary);flex:none}._1q5eoq_entryDescription{min-width:0;color:var(--dsw-alias-label-tertiary);text-overflow:ellipsis;white-space:nowrap;flex:auto;overflow:hidden}._1q5eoq_sections{flex-direction:column;gap:8px;margin:0;display:flex}._1q5eoq_section{flex-direction:column;gap:2px;min-width:0;display:flex}._1q5eoq_sectionName{color:var(--dsw-alias-label-caption)}._1q5eoq_sectionText{color:var(--dsw-alias-label-secondary);white-space:pre-wrap;overflow-wrap:anywhere;margin:0}._1q5eoq_relaySender{color:var(--dsw-alias-label-caption);overflow-wrap:anywhere;margin:0 0 6px}._1q5eoq_recalls{flex-direction:column;gap:2px;margin:0 0 8px;padding:0;list-style:none;display:flex}._1q5eoq_recall{gap:8px;min-width:0;display:flex}._1q5eoq_recallLabel{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}._1q5eoq_recallCounts{color:var(--dsw-alias-label-caption);flex:none}"; const tagId$3 = "dsh-better-chat/ContextBody.module.css"; if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$3) + "]") === null) { const tag = document.createElement("style"); tag.dataset.plugin = "dsh-better-chat"; tag.dataset.pluginCss = tagId$3; tag.textContent = css$3; document.head.appendChild(tag); } var ContextBody_module_css_default = { "catalogNotice": "_1q5eoq_catalogNotice", "entries": "_1q5eoq_entries", "entry": "_1q5eoq_entry", "entryDescription": "_1q5eoq_entryDescription", "entryName": "_1q5eoq_entryName", "field": "_1q5eoq_field", "fieldKey": "_1q5eoq_fieldKey", "fields": "_1q5eoq_fields", "fieldValue": "_1q5eoq_fieldValue", "file": "_1q5eoq_file", "fileAction": "_1q5eoq_fileAction", "filePath": "_1q5eoq_filePath", "files": "_1q5eoq_files", "recall": "_1q5eoq_recall", "recallCounts": "_1q5eoq_recallCounts", "recallLabel": "_1q5eoq_recallLabel", "recalls": "_1q5eoq_recalls", "relaySender": "_1q5eoq_relaySender", "section": "_1q5eoq_section", "sectionName": "_1q5eoq_sectionName", "sections": "_1q5eoq_sections", "sectionText": "_1q5eoq_sectionText", "text": "_1q5eoq_text" }; // src/client/native/ContextBody.tsx /** Model-facing text stays bounded at the disclosure, not at the producer. */ const MAX_CHARS = 2e4; /** Rows a list body materializes before summarizing the remainder. */ const MAX_ENTRIES = 200; /** One durable source narrowed to the readable-record shape; null for anything else. */ function asRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null; } /** * The content blocks as runs, IN THE ORDER the model received them. * * Adjacent text blocks join with no separator, matching how provider adapters * flatten them — inserting a line break would show the reader a line the model * never saw. An unknown block breaks the run and keeps its own fallback rather * than being hoisted past the text around it or vanishing; the block union is * merge-extensible, so a foreign log may interleave shapes this build does not * know. */ function contentRuns(content) { const runs = []; for (const block of content) { if (block.type !== "text") { runs.push({ block }); continue; } const last = runs[runs.length - 1]; if (last !== void 0 && "text" in last) last.text += block.text; else runs.push({ text: block.text }); } return runs; } /** Only the blocks this UI version does not know, for bodies that replace the text. */ function unknownBlocks(content) { return contentRuns(content).flatMap((run) => "block" in run ? [run.block] : []); } /** The model-facing text, truncated to the display bound. */ function boundedText(text, t) { return text.length > MAX_CHARS ? `${text.slice(0, MAX_CHARS)}\n${t("json.truncated", { total: text.length })}` : text; } /** * One source field rendered as a value row; nested shapes stay compact JSON. * Bounded on its own, because source fields are as unbounded as the text: an unknown * producer may record an arbitrarily large string or array. */ function fieldValue(value, t) { return boundedText(typeof value === "string" ? value : typeof value === "number" || typeof value === "boolean" ? String(value) : JSON.stringify(value), t); } /** * Source fields as a key/value list. `kind` is always omitted because the * row header already names the producer. `form` is omitted only when a * dedicated body rendered for it — then the presentation the reader is looking * at IS that value. On the opaque fallback the declaration is kept, because * that is the one place a form this version cannot present would otherwise * disappear from the UI entirely. */ function SourceFields({ source, formRendered, t }) { const record = asRecord(source); if (record === null) return null; const hidden = formRendered ? ["kind", "form"] : ["kind"]; const rows = Object.entries(record).filter(([key]) => !hidden.includes(key)); if (rows.length === 0) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("dl", { className: ContextBody_module_css_default.fields, "data-context-fields": true, children: rows.map(([key, value]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: ContextBody_module_css_default.field, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("dt", { className: ContextBody_module_css_default.fieldKey, children: key }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("dd", { className: ContextBody_module_css_default.fieldValue, children: fieldValue(value, t) })] }, key)) }); } /** * Content blocks this UI version does not know, kept visible rather than * dropped: the block union is merge-extensible, so a newer or foreign log may * carry a shape this build has no presentation for. * @param props - The unrecognized blocks and the locale seat. * @returns One generic JSON block per unknown entry. */ function UnknownBlocks({ blocks, t }) { return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: blocks.map((block, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonBlock, { label: t("message.unknownBlock"), payload: block, truncatedLabel: (total) => t("json.truncated", { total }) }, index)) }); } /** * The model-facing content of one context, shared by every form that shows it: * the text with its real line breaks, then any block this UI version does not * know, which keeps its own fallback rather than vanishing. * @param props - Durable content and the locale seat. * @returns The content blocks as the model received them. */ function ModelFacingContent({ content, t }) { return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: contentRuns(content).map((run, index) => "text" in run ? run.text !== "" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { className: ContextBody_module_css_default.text, "data-context-text": true, children: boundedText(run.text, t) }, index) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonBlock, { label: t("message.unknownBlock"), payload: run.block, truncatedLabel: (total) => t("json.truncated", { total }) }, index)) }); } /** * Default presentation: the model-facing text as text, with its real line * breaks, and the remaining source fields beneath it. This is what every form * this UI version does not recognize renders as. * @param props - Durable content, its source, and the locale seat. * @returns The opaque context body. */ function OpaqueBody({ content, source, t }) { return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ModelFacingContent, { content, t }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SourceFields, { source, formRendered: false, t })] }); } /** * Instruction changes read off the source, or null when the record is not a * usable instruction list. * * The read is all-or-nothing: silently dropping one unreadable entry would show * a confident, incomplete file list for a log this version cannot fully read. * Paths are deduplicated in first-seen order, matching how the header label is * derived from the same array. */ function instructionChanges(source) { const record = asRecord(source); const list = record === null ? void 0 : record["changes"]; if (!Array.isArray(list)) return null; const changes = []; const seen = /* @__PURE__ */ new Set(); for (const entry of list) { const change = asRecord(entry); if (change === null) return null; const path = change["path"]; if (typeof path !== "string" || path === "") return null; const action = change["action"]; if (action !== "set" && action !== "replace" && action !== "remove") return null; const digest = change["digest"]; if (seen.has(path)) continue; seen.add(path); changes.push({ action, path, ...typeof digest === "string" ? { digest } : {} }); } return changes.length === 0 ? null : changes; } /** * Locale key for one reconciled file. The baseline loads a file; a later delta * distinguishes a newly reconciled path from a rewritten one, which `set` and * `replace` already separate at the producer. * @param action - the durable change action. * @param baseline - whether this context is the startup/resume baseline. * @returns the key naming what happened to that file. */ function instructionAction(action, baseline) { if (action === "remove") return "message.context.instructions.removed"; if (baseline) return "message.context.instructions.loaded"; return action === "set" ? "message.context.instructions.added" : "message.context.instructions.updated"; } /** * `instructions` form: the files this context reconciled, then their text. * * The text keeps its `<system-reminder>` framing verbatim — the framing is part * of what the model read, so hiding it would misreport the request. * @param props - Durable content, its source, and the locale seat. * @returns The instructions context body, or the opaque body when the change * list is unreadable. */ function InstructionsBody({ content, source, t }) { const changes = instructionChanges(source); if (changes === null) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OpaqueBody, { content, source, t }); const baseline = asRecord(source)?.["baseline"] === true; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", { className: ContextBody_module_css_default.files, "data-context-files": true, children: changes.map((change) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", { className: ContextBody_module_css_default.file, title: change.digest, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextBody_module_css_default.filePath, children: change.path }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextBody_module_css_default.fileAction, children: t(instructionAction(change.action, baseline)) })] }, change.path)) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ModelFacingContent, { content, t })] }); } /** * Catalog entries read off the source, or null when the record is not a usable * catalog. All-or-nothing for the same reason as the instruction list: this body * replaces the model-facing text, so a partial list would hide the only complete * account of what the model read. */ function catalogEntries(source) { const record = asRecord(source); const list = record === null ? void 0 : record["entries"]; if (!Array.isArray(list)) return null; const entries = []; for (const item of list) { const entry = asRecord(item); if (entry === null) return null; const name = entry["name"]; const description = entry["description"]; if (typeof name !== "string" || name === "" || typeof description !== "string") return null; entries.push({ name, description }); } return entries; } /** * `catalog` form: the published entries as a list, read from the source rather * than re-parsed out of the model-facing prose. * * A catalog whose source carries no usable entries falls through to the opaque * body, so an older or hand-edited log still shows its text. * @param props - Durable content, its source, and the locale seat. * @returns The catalog context body, or the opaque body when the entry list is * unreadable. */ function CatalogBody({ content, source, t }) { const entries = catalogEntries(source); if (entries === null) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OpaqueBody, { content, source, t }); const update = asRecord(source)?.["update"] === true; const shown = entries.slice(0, MAX_ENTRIES); const rest = unknownBlocks(content); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ update && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: ContextBody_module_css_default.catalogNotice, "data-context-catalog-update": true, children: t("message.context.catalog.replaced") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", { className: ContextBody_module_css_default.entries, "data-context-entries": true, children: shown.map((entry, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", { className: ContextBody_module_css_default.entry, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { className: ContextBody_module_css_default.entryName, children: entry.name }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextBody_module_css_default.entryDescription, children: entry.description })] }, index)) }), shown.length < entries.length && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: ContextBody_module_css_default.catalogNotice, "data-context-entries-truncated": true, children: t("message.context.catalog.more", { count: entries.length - shown.length }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UnknownBlocks, { blocks: rest, t }) ] }); } /** Snapshot sections read off the source, or null when the record is unusable. */ function snapshotSections(source) { const record = asRecord(source); const list = record === null ? void 0 : record["sections"]; if (!Array.isArray(list)) return null; const sections = []; for (const item of list) { const section = asRecord(item); if (section === null) return null; const name = section["name"]; const text = section["text"]; if (typeof name !== "string" || name === "" || typeof text !== "string") return null; sections.push({ name, text }); } return sections.length === 0 ? null : sections; } /** * `snapshot` form: the named contributions this snapshot assembled, in order. * * The sections are the same bytes the model read, split at the boundaries the * producer assembled them on, so a reader sees which subsystem contributed * which state instead of one undifferentiated wall. * * One sentence of the model-facing text is NOT in any section: the producer's * framing line declaring that this snapshot supersedes earlier ones. Unlike the * `<system-reminder>` wrapper an instruction context carries — which wraps * content and cannot be separated from it — that line states the form's own * semantics, so the body states them as a caption instead of reprinting the * joined prose beside the sections it was split from. * @param props - Durable content, its source, and the locale seat. * @returns The snapshot context body, or the opaque body when unreadable. */ function SnapshotBody({ content, source, t }) { const sections = snapshotSections(source); /* v8 ignore next -- contextBody reads the sections before choosing this body. */ if (sections === null) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OpaqueBody, { content, source, t }); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: ContextBody_module_css_default.catalogNotice, "data-context-snapshot-supersedes": true, children: t("message.context.snapshot.supersedes") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("dl", { className: ContextBody_module_css_default.sections, "data-context-sections": true, children: sections.map((section, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: ContextBody_module_css_default.section, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("dt", { className: ContextBody_module_css_default.sectionName, children: section.name }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("dd", { className: ContextBody_module_css_default.sectionText, children: boundedText(section.text, t) })] }, index)) })] }); } /** * `notice` form: what just happened, with the model-facing text beneath it. * * The one-line account also rides the collapsed row ({@link contextBody}), so a * notice is usually readable without expanding at all. * @param props - Durable content, its source, and the locale seat. * @returns The notice context body. */ function NoticeBody({ content, t }) { return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ModelFacingContent, { content, t }); } /** * `relay` form: which agent sent this, then what it said. * * The sender is an opaque session id; it is shown as a field rather than a * label, because this client cannot resolve it to a title. * @param props - Durable content, its source, and the locale seat. * @returns The relay context body. */ function RelayBody({ content, source, t }) { const sender = relaySender(source); /* v8 ignore next -- contextBody resolves the sender before choosing this body. */ if (sender === null) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OpaqueBody, { content, source, t }); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: ContextBody_module_css_default.relaySender, "data-context-relay-sender": true, children: t("message.context.relay.from", { session: sender }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ModelFacingContent, { content, t })] }); } /** The sending agent's session id, or null when the record does not name one. */ function relaySender(source) { const sender = asRecord(source)?.["senderSessionId"]; return typeof sender === "string" && sender !== "" ? sender : null; } /** Recalled sessions read off the source, or null when the record is unusable. */ function recalledSessions(source) { const record = asRecord(source); const list = record === null ? void 0 : record["references"]; if (!Array.isArray(list)) return null; const sessions = []; for (const item of list) { const reference = asRecord(item); if (reference === null) return null; const label = reference["label"]; const retained = reference["retainedMessages"]; const omitted = reference["omittedMessages"]; const truncated = reference["truncated"]; if (typeof label !== "string" || label === "" || typeof retained !== "number" || typeof omitted !== "number" || typeof truncated !== "boolean") return null; sessions.push({ label, retained, omitted, truncated }); } return sessions.length === 0 ? null : sessions; } /** * `recall` form: which sessions this material came from and how much of each * survived the read, then the material itself. * * Completeness is the fact a reader needs first: recalled context is bounded on * the way in, so a card that hid the omitted count would overstate what the * model received. * @param props - Durable content, its source, and the locale seat. * @returns The recall context body, or the opaque body when unreadable. */ function RecallBody({ content, source, t }) { const sessions = recalledSessions(source); if (sessions === null) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OpaqueBody, { content, source, t }); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", { className: ContextBody_module_css_default.recalls, "data-context-recalls": true, children: sessions.map((session, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", { className: ContextBody_module_css_default.recall, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextBody_module_css_default.recallLabel, children: session.label }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextBody_module_css_default.recallCounts, children: t("message.context.recall.counts", { retained: session.retained, omitted: session.omitted }) }), session.truncated && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextBody_module_css_default.recallCounts, children: t("message.context.recall.truncated") }) ] }, index)) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ModelFacingContent, { content, t })] }); } /** The one-line account a `notice` puts on its collapsed row, when it records one. */ function noticeSummary(source) { const summary = asRecord(source)?.["summary"]; return typeof summary === "string" && summary !== "" ? summary : null; } /** * Choose the body for one context node. * * Returns the form the body actually rendered as, which is not always the * declared one: a declared form whose fields are unreadable falls back to * opaque, and the caller labels the row with what it really shows. * `summary` is the collapsed row's one-line account, which only a `notice` * records: its whole point is being readable without expanding. * @param form - the producer-declared form projected onto the node. * @param props - durable content, its source, and the locale seat. * @returns the rendered form (null for opaque), its collapsed summary, and its body. */ function contextBody(form, props) { const opaque = { rendered: null, summary: null, body: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OpaqueBody, { ...props }) }; switch (form) { case "instructions": return instructionChanges(props.source) === null ? opaque : { rendered: "instructions", summary: null, body: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(InstructionsBody, { ...props }) }; case "catalog": return catalogEntries(props.source) === null ? opaque : { rendered: "catalog", summary: null, body: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CatalogBody, { ...props }) }; case "snapshot": return snapshotSections(props.source) === null ? opaque : { rendered: "snapshot", summary: null, body: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SnapshotBody, { ...props }) }; case "notice": { const summary = noticeSummary(props.source); return summary === null ? opaque : { rendered: "notice", summary, body: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NoticeBody, { ...props }) }; } case "relay": return relaySender(props.source) === null ? opaque : { rendered: "relay", summary: null, body: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RelayBody, { ...props }) }; case "recall": return recalledSessions(props.source) === null ? opaque : { rendered: "recall", summary: null, body: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RecallBody, { ...props }) }; case null: return opaque; /* v8 ignore next 4 -- closed-union backstop; the compiler rejects a new KnownContextForm here rather than letting it degrade to opaque silently. */ default: throw new Error(`unreachable context form: ${String(form)}`); } } // src/client/native/tool-update.ts /** * Classify a context as the rc.2 tool-update row. * Mixed or empty content stays on the generic injection presentation. * @param content - durable context blocks. * @returns collected names, or null when any block is not a tool change. */ function toolUpdateRows(content) { if (content.length === 0) return null; const rows = []; for (const block of content) { if (block.type !== "tool-addition" && block.type !== "tool-removal") return null; if (typeof block.toolName !== "string") return null; rows.push({ type: block.type, toolName: block.toolName }); } return { added: rows.flatMap((row) => row.type === "tool-addition" ? [row.toolName] : []), removed: rows.flatMap((row) => row.type === "tool-removal" ? [row.toolName] : []), single: rows.length === 1 ? rows[0] : null }; } // \0dshx-css-module:src/client/native/ContextInjectionRow.module.css.mjs const css$2 = ".Zj4cZW_root{min-width:0}.Zj4cZW_root[data-open]{padding-bottom:4px}.Zj4cZW_chevron{color:var(--dsw-alias-label-secondary)}.Zj4cZW_sep{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.Zj4cZW_source{min-width:0;color:var(--dsw-alias-label-tertiary);text-overflow:ellipsis;white-space:nowrap;flex:none;font-size:14px;line-height:24px;overflow:hidden}.Zj4cZW_summary{min-width:0;color:var(--dsw-alias-label-tertiary);text-overflow:ellipsis;white-space:nowrap;flex:auto;font-size:14px;line-height:24px;overflow:hidden}.Zj4cZW_body{box-sizing:border-box;background:var(--dsw-alias-markdown-code-block);width:calc(100% - 22px);max-height:141px;color:var(--dsw-alias-label-tertiary);font:400 11px/16px var(--ds-font-family-code);border:none;border-radius:8px;margin:4px 0 0 22px;padding:10px 16px 12px 12px;overflow:auto}.Zj4cZW_toolChanges{white-space:nowrap}"; const tagId$2 = "dsh-better-chat/ContextInjectionRow.module.css"; if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$2) + "]") === null) { const tag = document.createElement("style"); tag.dataset.plugin = "dsh-better-chat"; tag.dataset.pluginCss = tagId$2; tag.textContent = css$2; document.head.appendChild(tag); } var ContextInjectionRow_module_css_default = { "body": "Zj4cZW_body", "chevron": "Zj4cZW_chevron", "root": "Zj4cZW_root", "sep": "Zj4cZW_sep", "source": "Zj4cZW_source", "summary": "Zj4cZW_summary", "toolChanges": "Zj4cZW_toolChanges" }; // src/client/native/ContextInjectionRow.tsx /** * Render logged context with the Tool calls disclosure chrome from Figma. * * The header names the role the context plays and, beside it, the producer the * durable source identifies, so a reader can tell an injected skill catalog * from a workspace instruction file or a recalled session without expanding. * The expanded body follows the producer-declared form; an absent or unknown * form renders the opaque body. * @param props - Durable content, its projected producer role/name and form, and the locale seat. * @returns A collapsed context row with a bounded, form-specific body. */ function ContextInjectionRow({ content, source, provenance, producer, form, t }) { const [open, setOpen] = (0, react.useState)(false); const view = provenance ?? producer ?? { role: "inject", label: null }; const { rendered, summary, body } = contextBody(form, { content, source, t }); const tools = toolUpdateRows(content); const toolSummary = tools === null || tools.single !== null ? null : tools.added.length > 0 && tools.removed.length > 0 ? t("message.toolsChanged", { added: tools.added.length, removed: tools.removed.length }) : tools.added.length > 0 ? t("message.toolsAddedCount", { count: tools.added.length }) : t("message.toolsRemovedCount", { count: tools.removed.length }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.DisclosureRow, { className: ContextInjectionRow_module_css_default.root, icon: view.role === "recall" && tools === null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { "data-context-recall-icon": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ReferenceIcon, { kind: "session" }) }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconBrowseOutlineRegular, { size: 14 }), chevronClassName: ContextInjectionRow_module_css_default.chevron, title: tools?.single !== void 0 && tools.single !== null ? t(tools.single.type === "tool-addition" ? "message.toolAdded" : "message.toolRemoved", { name: tools.single.toolName }) : tools !== null ? t("message.toolsUpdated") : t(view.role === "recall" ? "message.contextRecall" : "message.contextInjection"), collapsedContent: toolSummary !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextInjectionRow_module_css_default.sep, "aria-hidden": true }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextInjectionRow_module_css_default.summary, children: toolSummary })] }) : tools !== null || view.label === null ? void 0 : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextInjectionRow_module_css_default.sep, "aria-hidden": true }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextInjectionRow_module_css_default.source, "data-context-source": true, children: view.label }), summary !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextInjectionRow_module_css_default.sep, "aria-hidden": true }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: ContextInjectionRow_module_css_default.summary, "data-context-summary": true, children: summary })] }) ] }), keepContentWhenOpen: true, open: open && tools?.single == null, expandable: tools?.single == null, expandOnRowClick: true, onToggle: () => { setOpen((value) => !value); }, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: ContextInjectionRow_module_css_default.body, "data-context-injection-body": true, "data-context-form": rendered ?? void 0, children: tools === null ? body : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: ContextInjectionRow_module_css_default.toolChanges, children: [tools.added.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { children: t("message.toolsAdded", { names: tools.added.join(", ") }) }), tools.removed.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { children: t("message.toolsRemoved", { names: tools.removed.join(", ") }) })] }) }) }); } // \0dshx-css-module:src/client/TimelineRail.module.css.mjs const css$1 = ".yMsdPa_slot{z-index:10;pointer-events:none;height:0;position:sticky;top:0}.yMsdPa_frame{--turn-rail-band:calc(var(--dsh-conversation-viewport-height,100dvh) - var(--dsh-composer-height,152px));--turn-preview-height:100px;top:calc(var(--turn-rail-band) / 2);width:26px;height:min(var(--turn-natural-height), max(0px, calc(var(--turn-rail-band) - 64px)), 420px);cursor:pointer;pointer-events:auto;transition:height .22s cubic-bezier(.2,.8,.2,1);position:absolute;right:6px;transform:translateY(-50%)}.yMsdPa_scroller{overscroll-behavior:contain;scrollbar-width:none;position:absolute;inset:0;overflow-y:auto}.yMsdPa_scroller::-webkit-scrollbar{display:none}.yMsdPa_fadeTop{mask-image:linear-gradient(#0000 0,#000 24px 100%)}.yMsdPa_fadeBottom{mask-image:linear-gradient(#000 0 calc(100% - 24px),#0000 100%)}.yMsdPa_fadeTop.yMsdPa_fadeBottom{mask-image:linear-gradient(#0000 0,#000 24px calc(100% - 24px),#0000 100%)}.yMsdPa_marks{height:var(--turn-natural-height);position:relative}.yMsdPa_markPosition{top:calc(var(--turn-natural-position) + var(--turn-rail-inset));height:12px;transition:top .22s cubic-bezier(.2,.8,.2,1);position:absolute;left:0;right:0;transform:translateY(-50%)}.yMsdPa_mark{cursor:pointer;pointer-events:none;background:0 0;border:0;justify-content:flex-end;align-items:center;width:24px;padding:0;display:flex;position:absolute;inset:0 0 0 auto}.yMsdPa_tick{border-radius:2px;flex:none;transition:width .1s cubic-bezier(.16,1,.3,1),height .1s cubic-bezier(.16,1,.3,1),opacity .1s,background-color .14s}.yMsdPa_markBusy .yMsdPa_tick{animation:1s ease-in-out infinite alternate yMsdPa_markBusyPulse}@keyframes yMsdPa_markBusyPulse{0%{opacity:.4;width:8px}to{opacity:1;width:18px}}.yMsdPa_preview{top:clamp(0px, calc(var(--turn-natural-position) + var(--turn-rail-inset) - var(--turn-scroll-top,0px) - var(--turn-preview-height) / 2), calc(100% - var(--turn-preview-height)));box-sizing:border-box;width:min(280px,100cqw - 120px);max-height:var(--turn-preview-height);border:1px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);pointer-events:none;z-index:40;border-radius:10px;padding:10px 12px;transition:top .14s cubic-bezier(.2,.8,.2,1);animation:.12s ease-out yMsdPa_previewFadeIn;position:absolute;right:calc(100% + 10px);overflow:hidden;box-shadow:0 4px 18px #0000001f}@keyframes yMsdPa_previewFadeIn{0%{opacity:0;transform:translate(4px)}to{opacity:1;transform:translate(0)}}.yMsdPa_previewPrompt{-webkit-line-clamp:2;text-overflow:ellipsis;word-break:break-word;-webkit-box-orient:vertical;font-size:12px;font-weight:500;line-height:18px;display:-webkit-box;overflow:hidden}.yMsdPa_previewResponse{color:var(--dsw-alias-label-tertiary);-webkit-line-clamp:2;text-overflow:ellipsis;word-break:break-word;-webkit-box-orient:vertical;margin-top:4px;font-size:11px;line-height:16px;display:-webkit-box;overflow:hidden}@media (max-width:960px){.yMsdPa_slot{display:none!important}}"; const tagId$1 = "dsh-better-chat/TimelineRail.module.css"; if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$1) + "]") === null) { const tag = document.createElement("style"); tag.dataset.plugin = "dsh-better-chat"; tag.dataset.pluginCss = tagId$1; tag.textContent = css$1; document.head.appendChild(tag); } var TimelineRail_module_css_default = { "fadeBottom": "yMsdPa_fadeBottom", "fadeTop": "yMsdPa_fadeTop", "frame": "yMsdPa_frame", "mark": "yMsdPa_mark", "markBusy": "yMsdPa_markBusy", "markBusyPulse": "yMsdPa_markBusyPulse", "markPosition": "yMsdPa_markPosition", "marks": "yMsdPa_marks", "preview": "yMsdPa_preview", "previewFadeIn": "yMsdPa_previewFadeIn", "previewPrompt": "yMsdPa_previewPrompt", "previewResponse": "yMsdPa_previewResponse", "scroller": "yMsdPa_scroller", "slot": "yMsdPa_slot", "tick": "yMsdPa_tick" }; // src/client/TimelineRail.tsx const TURN_SPACING_PX = 12; const RAIL_INSET_PX = 6; const FADE_PX = 24; function itemPosition(index) { return { "--turn-natural-position": `${index * TURN_SPACING_PX}px` }; } function frameStyle(count, scrollTop) { return { "--turn-natural-height": `${(count - 1) * TURN_SPACING_PX + 12}px`, "--turn-rail-inset": `${RAIL_INSET_PX}px`, "--turn-scroll-top": `${scrollTop}px` }; } function itemIndexAtPointer(items, frame, scrollTop, clientY) { const offset = clientY - frame.getBoundingClientRect().top + scrollTop - RAIL_INSET_PX; return Math.max(0, Math.min(items.length - 1, Math.round(offset / TURN_SPACING_PX))); } const RAIL_AT_REST = { top: 0, canScrollUp: false, canScrollDown: false }; function railScrollState(scroller) { const top = scroller.scrollTop; return { top, canScrollUp: top > 1, canScrollDown: top < scroller.scrollHeight - scroller.clientHeight - 1 }; } const TimelineRail = (0, react.memo)(function TimelineRail({ items, activeTurn, busyTurn, onNavigate }) { const [hoveredIndex, setHoveredIndex] = (0, react.useState)(null); const [scrollState, setScrollState] = (0, react.useState)(RAIL_AT_REST); const scrollerRef = (0, react.useRef)(null); const pointerInsideRef = (0, react.useRef)(false); const previewId = (0, react.useId)(); const syncScrollState = () => { const scroller = scrollerRef.current; if (!scroller) return; const next = railScrollState(scroller); setScrollState((cur) => cur.top === next.top && cur.canScrollUp === next.canScrollUp && cur.canScrollDown === next.canScrollDown ? cur : next); }; (0, react.useEffect)(() => { const scroller = scrollerRef.current; if (!scroller || typeof ResizeObserver === "undefined") return; const observer = new ResizeObserver(syncScrollState); observer.observe(scroller); return () => observer.disconnect(); }, []); (0, react.useEffect)(syncScrollState, [items.length]); (0, react.useEffect)(() => { const scroller = scrollerRef.current; const index = items.findIndex((item) => item.turn === activeTurn); if (!scroller || index < 0 || pointerInsideRef.current) return; const markTop = index * TURN_SPACING_PX + RAIL_INSET_PX; const viewTop = scroller.scrollTop; const viewHeight = scroller.clientHeight; if (viewHeight <= 0 || markTop >= viewTop + FADE_PX && markTop <= viewTop + viewHeight - FADE_PX) return; const target = Math.max(0, markTop - viewHeight / 2); if (typeof scroller.scrollTo === "function") scroller.scrollTo({ top: target, behavior: "smooth" }); else scroller.scrollTop = target; syncScrollState(); }, [activeTurn, items]); if (items.length < 2) return null; const preview = hoveredIndex !== null && hoveredIndex >= 0 ? items[hoveredIndex] : void 0; const previewPosition = hoveredIndex !== null && hoveredIndex >= 0 ? itemPosition(hoveredIndex) : void 0; const onPointerMove = (event) => { const scrollTop = scrollerRef.current?.scrollTop ?? 0; const idx = itemIndexAtPointer(items, event.currentTarget, scrollTop, event.clientY); setHoveredIndex(idx); }; const onPointerLeave = () => { pointerInsideRef.current = false; setHoveredIndex(null); }; const navigateAtPointer = (event) => { const scrollTop = scrollerRef.current?.scrollTop ?? 0; const item = items[itemIndexAtPointer(items, event.currentTarget, scrollTop, event.clientY)]; if (item !== void 0) onNavigate(item); }; const fadeClasses = [TimelineRail_module_css_default.scroller]; if (scrollState.canScrollUp) fadeClasses.push(TimelineRail_module_css_default.fadeTop); if (scrollState.canScrollDown) fadeClasses.push(TimelineRail_module_css_default.fadeBottom); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: TimelineRail_module_css_default.slot, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("nav", { className: TimelineRail_module_css_default.frame, style: frameStyle(items.length, scrollState.top), "aria-label": "轮次导航时间轴", onClick: navigateAtPointer, onPointerMove, onPointerEnter: () => { pointerInsideRef.current = true; }, onPointerLeave, onMouseDown: (event) => { event.preventDefault(); }, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref: scrollerRef, className: fadeClasses.join(" "), onScroll: syncScrollState, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: TimelineRail_module_css_default.marks, children: items.map((item, index) => { const isBusy = busyTurn === item.turn; const isActive = activeTurn === item.turn; const isUnloaded = item.anchor.kind === "unloaded"; let width = isUnloaded ? 6 : 8; let height = 2; let opacity = isUnloaded ? .3 : .45; let background = "var(--dsw-alias-label-tertiary)"; if (hoveredIndex !== null) { const diff = Math.abs(index - hoveredIndex); if (diff === 0) { width = 26; height = 2.8; opacity = 1; background = "var(--dsw-alias-label-primary)"; } else if (diff === 1) { width = 18; height = 2.2; opacity = .8; background = "var(--dsw-alias-label-primary)"; } else if (diff === 2) { width = 13; height = 1.8; opacity = .6; background = "var(--dsw-alias-label-secondary)"; } else if (diff === 3) { width = 9; height = 1.6; opacity = .45; background = "var(--dsw-alias-label-tertiary)"; } else { width = 8; height = 2; opacity = .35; background = "var(--dsw-alias-label-tertiary)"; } } else if (isActive) { width = 20; height = 2.4; opacity = .95; background = "var(--dsw-alias-label-primary)"; } const tickStyle = { width: `${width}px`, height: `${height}px`, opacity, backgroundColor: background }; const markClasses = [TimelineRail_module_css_default.mark]; if (isBusy) markClasses.push(TimelineRail_module_css_default.markBusy); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: TimelineRail_module_css_default.markPosition, style: itemPosition(index), children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: markClasses.join(" "), "aria-label": `第 ${item.turn + 1} 轮`, "aria-current": isActive ? "true" : void 0, "aria-busy": isBusy ? "true" : void 0, "aria-describedby": hoveredIndex === index ? previewId : void 0, onMouseDown: (event) => { event.preventDefault(); }, onClick: (e) => { e.stopPropagation(); onNavigate(item); }, onFocus: () => setHoveredIndex(index), onBlur: () => setHoveredIndex(null), children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: TimelineRail_module_css_default.tick, style: tickStyle }) }) }, item.turn); }) }) }), preview !== void 0 && previewPosition !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { id: previewId, role: "tooltip", className: TimelineRail_module_css_default.preview, style: previewPosition, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: TimelineRail_module_css_default.previewPrompt, children: preview.prompt || `第 ${preview.turn + 1} 轮` }), preview.response !== "" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: TimelineRail_module_css_default.previewResponse, children: preview.response })] })] }) }); }); /** Active column host when present; otherwise the view-local scroller. */ function scrollerOf(from) { return from.closest("[data-conversation-scroll]") ?? from; } /** Row position in scrollport coordinates (viewport-independent). */ function flowTop(row, scrollport) { return row.getBoundingClientRect().top - scrollport.getBoundingClientRect().top; } /** * Place `row` on the conversation scroller only. Never calls scrollIntoView. * @param row - a rendered `[data-reader-turn]` row. * @param scrollport - `scrollerOf` of the reader root. */ function landTurn(row, scrollport, offsetPx = 24) { scrollport.scrollTop += flowTop(row, scrollport) - offsetPx; } // src/client/timeline.ts /** * Merge host turn outline with loaded navigation items and turn deliverables. * Guarantees strictly ascending turn order and dedupes entries. */ function mergeTimelineItems(loaded, outline, turnsWithDeliverables) { const byTurn = /* @__PURE__ */ new Map(); if (Array.isArray(outline)) for (const raw of outline) { if (typeof raw !== "object" || raw === null) continue; const entry = raw; if (typeof entry.turn !== "number" || !Number.isSafeInteger(entry.turn) || entry.turn < 0) continue; if (typeof entry.seq !== "number" || !Number.isSafeInteger(entry.seq) || entry.seq < 0) continue; byTurn.set(entry.turn, { turn: entry.turn, prompt: typeof entry.prompt === "string" ? entry.prompt.trim() : "", response: typeof entry.response === "string" ? entry.response.trim() : "", hasDeliverables: turnsWithDeliverables?.has(entry.turn) ?? false, anchor: { kind: "unloaded", seq: entry.seq } }); } if (Array.isArray(loaded)) for (const item of loaded) { if (typeof item.turn !== "number") continue; const preview = byTurn.get(item.turn); const prompt = item.prompt?.trim() || preview?.prompt || ""; const response = item.response?.trim() || preview?.response || ""; const hasDeliverables = turnsWithDeliverables?.has(item.turn) ?? preview?.hasDeliverables ?? false; byTurn.set(item.turn, { turn: item.turn, prompt, response, hasDeliverables, anchor: { kind: "loaded", key: item.anchorKey } }); } if (byTurn.size === 0) return []; return [...byTurn.values()].sort((a, b) => a.turn - b.turn); } // src/client/live-turn.ts function liveFoldEnabled(boundary) { return boundary.status === "open"; } function foldSummary(steps) { let reasoning = 0; let body = 0; let tool = 0; let extra = 0; for (const step of steps) if (step.kind === "reasoning") reasoning += 1; else if (step.kind === "body") body += 1; else if (step.kind === "tool") tool += 1; else if (step.kind !== "user") extra += 1; const parts = []; if (reasoning) parts.push(`思考×${reasoning}`); if (body) parts.push(`输出×${body}`); if (tool) parts.push(`工具×${tool}`); if (extra) parts.push(`记录×${extra}`); return parts.join(" · ") || "此前步骤"; } function skipReasoning(part) { return part.kind === "reasoning" && !part.blocks.some((block) => block.kind === "reasoning" && block.text.trim() !== ""); } function skipBody(part) { return part.kind === "body" && !hasVisibleBody(part.blocks); } function stepsFromAssistant(nodeKey, data, toolsByCallId, consumed) { const marks = []; for (const part of assistantSegments(data.blocks)) { if (skipReasoning(part) || skipBody(part)) continue; marks.push({ at: part.start, step: { kind: part.kind, key: `${nodeKey}:${part.kind}:${part.start}`, nodeKey, start: part.start, blocks: part.blocks, step: data.step } }); } data.blocks.forEach((block, index) => { if (block.kind !== "tool-call" || !block.callId) return; const tool = toolsByCallId.get(block.callId); if (!tool || consumed.has(tool.callId)) return; consumed.add(tool.callId); marks.push({ at: index, step: { kind: "tool", key: tool.key, entry: tool } }); }); marks.sort((left, right) => left.at - right.at || left.step.key.localeCompare(right.step.key)); return marks.map((mark) => mark.step); } /** Expand readerFlow into source-ordered live steps using existing block boundaries. */ function segmentLiveTurn(flow, get) { const steps = []; const consumed = /* @__PURE__ */ new Set(); const toolsByCallId = /* @__PURE__ */ new Map(); for (const entry of flow) if (entry.kind === "tool") toolsByCallId.set(entry.callId, entry); for (const entry of flow) { if (entry.kind === "tool") { if (!consumed.has(entry.callId)) { steps.push({ kind: "tool", key: entry.key, entry }); consumed.add(entry.callId); } continue; } const node = get(entry.nodeKey); if (!node || node.visibility === "hidden" || node.kind === "turn-tail") continue; if (node.kind === "user" || node.kind === "steering") { steps.push({ kind: "user", key: entry.key, nodeKey: entry.nodeKey }); continue; } if (node.kind === "assistant-step") { steps.push(...stepsFromAssistant(entry.nodeKey, node.data, toolsByCallId, consumed)); continue; } steps.push({ kind: "other", key: entry.key, nodeKey: entry.nodeKey }); } return steps; } /** Only a run that contains real thinking/tool work is worth folding. */ function foldableRun(run) { return run.some((step) => step.kind === "reasoning" || step.kind === "tool"); } /** * One live chain: narration stays visible, while every earlier reasoning/tool * run collapses into its own box at its original position. */ function presentLiveTurn(steps, boundary, autoFold = true) { const live = autoFold && liveFoldEnabled(boundary); const items = []; const open = (step) => items.push({ kind: "open", key: step.key, step }); const fold = (run) => { if (!run.length) return; if (live && foldableRun(run)) items.push({ kind: "fold", key: `live-fold:${run[0].key}`, steps: run, summary: foldSummary(run) }); else for (const step of run) open(step); }; let run = []; const flush = () => { fold(run); run = []; }; const segments = []; let segment = []; for (const step of steps) if (step.kind === "user") { segments.push(segment); segments.push([step]); segment = []; } else segment.push(step); segments.push(segment); for (const part of segments) { if (!part.length) continue; const first = part[0]; if (part.length === 1 && first.kind === "user") { items.push({ kind: "user", key: first.key, step: first }); continue; } if (!live) { for (const step of part) open(step); continue; } const lastReasoning = part.findLastIndex((step) => step.kind === "reasoning"); if (lastReasoning <= 0) { for (const step of part) open(step); continue; } for (let index = 0; index < part.length; index++) { const step = part[index]; if (index < lastReasoning) { if (step.kind === "body") { flush(); open(step); } else run.push(step); } else { if (index === lastReasoning) flush(); open(step); } } flush(); } return items; } /** * Summaries for collapsed process that sits between two narration blocks. * * A live-fold cell already shows that summary while the turn is open. Drawing * the seam as well repeats the same counts, so a run whose every step is * already inside a fold cell contributes neither a seam nor `after`. `after` * is what marks the previous body with `data-reader-seam-after` and drops its * bottom padding; skipping the seam must leave that spacing alone. */ function planProcessSeams(steps, liveItems, expanded) { const before = /* @__PURE__ */ new Map(); const after = /* @__PURE__ */ new Set(); if (expanded) return { before, after }; const liveFolded = new Set(liveItems.flatMap((item) => item.kind === "fold" ? item.steps.map((step) => step.key) : [])); let previousBody; let process = []; for (const step of steps) if (step.kind === "body") { const folded = process.filter((item) => item.kind !== "user"); if (!(folded.length > 0 && folded.every((item) => liveFolded.has(item.key))) && previousBody && folded.some((item) => item.kind === "reasoning" || item.kind === "tool" || item.kind === "other")) { before.set(step.key, foldSummary(folded)); after.add(previousBody.key); } previousBody = step; process = []; } else if (step.kind === "user") { previousBody = void 0; process = []; } else process.push(step); return { before, after }; } // src/client/fold-intensity.ts function frostedGlassOf(state) { if (state && typeof state === "object" && "frostedGlass" in state) return state.frostedGlass === true; return state === true; } function autoFoldFromIntensity(intensity) { return intensity !== 0; } function processOnlyFromIntensity(intensity) { return intensity === 2; } // src/client/DiffPanel.tsx /** * Reveals and withdraws its child by animating real height, in the plugin's own * motion language. Height is the animated property rather than transform because * the panel pushes the transcript down and the reading scroll measures that * growth; the curve and duration are the fold choreography's, so this reads as * the same gesture as opening a digest. * * Closing animates too: the child stays mounted until the shrink finishes, which * is why the owner keeps it alive on an `open` flag instead of unmounting it. */ function MorphPanel({ open, children, onSettled, onClosed }) { const ref = (0, react.useRef)(null); (0, react.useLayoutEffect)(() => { const element = ref.current; if (!element) return; element.dispatchEvent(new CustomEvent("reader-layout-start", { bubbles: true })); let released = false; const release = () => { if (!released) { released = true; element.dispatchEvent(new CustomEvent("reader-layout-end", { bubbles: true })); } }; if (typeof element.animate !== "function") { release(); if (!open) onClosed(); return; } const height = element.scrollHeight; const frames = open ? [{ height: "0px", opacity: 0, transform: "translateY(-6px)" }, { height: `${height}px`, opacity: 1, transform: "translateY(0)" }] : [{ height: `${height}px`, opacity: 1 }, { height: "0px", opacity: 0 }]; const animation = element.animate(frames, { duration: FOLD_TIMING.reveal + FOLD_TIMING.settle, easing: "cubic-bezier(.4,0,.2,1)" }); let settled = false; const settle = () => { if (settled) return; settled = true; release(); if (open) { element.style.height = "auto"; element.style.overflow = "visible"; onSettled?.(element); } else onClosed(); }; animation.onfinish = settle; const deadline = window.setTimeout(settle, FOLD_TIMING.reveal + FOLD_TIMING.settle + 240); return () => { window.clearTimeout(deadline); animation.cancel(); release(); }; }, [open]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref, className: Reader_module_css_default.diffOverlay, children }); } /** * Keeps a newly opened panel on screen. * * Opening grows the row downward, so a badge near the fold reveals its card below * the viewport and the reader has to chase it. The scroll container is not known * here, so the nearest scrollable ancestor is found and the card's head is brought * to the top of it — the same thing a jump-to-anchor does. */ function revealPanel(element) { let port = element.parentElement; while (port && port.scrollHeight <= port.clientHeight + 1) port = port.parentElement; if (!port) { element.scrollIntoView({ block: "nearest" }); return; } const gap = element.getBoundingClientRect().top - port.getBoundingClientRect().top; if (gap >= 0 && element.getBoundingClientRect().bottom <= port.getBoundingClientRect().bottom) return; port.scrollTop += gap - 8; } /** * Line counts for everything a folded run of steps changed. * * A run that touched no files renders nothing, so an ordinary process digest is * unchanged. Clicking the counts opens the same diff surface the official tool * row uses — one file at a time, red removed / green added, expandable. */ function DiffStat({ steps, label }) { const hunks = (0, react.useMemo)(() => foldDiffHunks(steps), [steps]); const [open, setOpen] = (0, react.useState)(false); const [visible, setVisible] = (0, react.useState)(false); const totals = (0, react.useMemo)(() => (0, _deepseek_ai_dsh_client_ui_primitives.diffTotals)(hunks), [hunks]); const [active, setActive] = (0, react.useState)(0); if (!hunks.length) return null; const current = hunks[Math.min(active, hunks.length - 1)]; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.diffStatRoot, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { type: "button", className: Reader_module_css_default.diffStatButton, "aria-expanded": open, "aria-label": `${label} · 改动 ${totals.added} 行,删除 ${totals.removed} 行`, onClick: (event) => { event.stopPropagation(); if (open) { setOpen(false); return; } setVisible(true); setOpen(true); }, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.diffCaret, "aria-hidden": true, children: open ? "▾" : "▸" }), totals.added > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.diffAdded, children: ["+", totals.added] }), totals.removed > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.diffRemoved, children: ["-", totals.removed] }) ] }) }), visible && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.diffOverlayRow, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(MorphPanel, { open, onSettled: revealPanel, onClosed: () => setVisible(false), children: [hunks.length > 1 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.diffTabs, children: hunks.map((hunk, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.diffTab, "data-active": index === active || void 0, onClick: () => setActive(index), title: hunk.path, children: hunk.path.split(/[/\\]+/).filter(Boolean).slice(-1)[0] ?? hunk.path }, `${hunk.path}:${index}`)) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.diffScrollArea, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.DiffBlock, { diffs: [current], maxLines: 36, labels: diffBlockLabels }) })] }) })] }); } // src/client/StickyLane.tsx const MIN_LANE_PX = 40; const LaneOwnerContext = (0, react.createContext)(null); const ownersByRoot = /* @__PURE__ */ new WeakMap(); /** One map per Reader, so two roots that both contain turn 1 do not share a writer. */ function ReaderLaneScope({ children }) { const owners = (0, react.useRef)(/* @__PURE__ */ new Map()); (0, react.useLayoutEffect)(() => { const map = owners.current; return () => { map.clear(); }; }, []); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LaneOwnerContext.Provider, { value: owners.current, children }); } function laneScope(el) { return el.closest("[data-reader-turn]") ?? el.closest("[data-dsh-better-display]"); } function ownersFor(el, scoped) { if (scoped) return scoped; const root = el.closest("[data-dsh-better-display]") ?? el; let owners = ownersByRoot.get(root); if (!owners) { owners = /* @__PURE__ */ new Map(); ownersByRoot.set(root, owners); } return owners; } function publishedLanePx(el) { return Math.max(MIN_LANE_PX, Math.ceil(el.getBoundingClientRect().height)); } /** One writer per turn inside a single Reader. A retiring summary cannot clear the lane that replaced it. */ function publishLaneHeight(el, property, scoped = null) { const scope = laneScope(el); if (!scope) return () => {}; const owners = ownersFor(el, scoped); const root = el.closest("[data-dsh-better-display]"); const key = `${property}\0${scope.getAttribute("data-reader-turn") ?? "root"}`; const update = () => { if (owners.get(key) !== el) return; scope.style.setProperty(property, `${publishedLanePx(el)}px`); }; owners.set(key, el); update(); const observer = new ResizeObserver(update); observer.observe(el); return () => { observer.disconnect(); if (owners.get(key) !== el) return; owners.delete(key); scope.style.removeProperty(property); if (!scoped && root && owners.size === 0) ownersByRoot.delete(root); }; } function usePublishedHeight(property) { const owners = (0, react.useContext)(LaneOwnerContext); const ref = (0, react.useRef)(null); (0, react.useLayoutEffect)(() => { const el = ref.current; if (!el) return; return publishLaneHeight(el, property, owners); }, [owners, property]); return ref; } function useSummaryLane(ref, active) { const owners = (0, react.useContext)(LaneOwnerContext); (0, react.useLayoutEffect)(() => { const el = ref.current; if (!active || !el) return; return publishLaneHeight(el, "--reader-summary-height", owners); }, [ active, owners, ref ]); } /** Publish real lane geometry; wrapped labels must not collide with statistics. */ function StickyLane({ kind, className, children }) { const ref = (0, react.useRef)(null); (0, react.useLayoutEffect)(() => { const el = ref.current; const scope = el?.closest(kind === "toolbar" ? "[data-dsh-better-display]" : "[data-reader-turn]"); if (!el || !scope) return; const property = kind === "toolbar" ? "--reader-toolbar-height" : "--reader-status-height"; const update = () => { scope.style.setProperty(property, `${Math.max(MIN_LANE_PX, el.getBoundingClientRect().height)}px`); if (kind !== "toolbar") return; const controls = el.querySelectorAll("button"); let width = 80; if (controls.length > 0) { const first = controls[0].getBoundingClientRect(); width = controls[controls.length - 1].getBoundingClientRect().right - first.left; } scope.style.setProperty("--reader-control-width", `${width + 28}px`); }; update(); const observer = new ResizeObserver(update); observer.observe(el); if (kind === "toolbar") for (const control of el.querySelectorAll("button")) observer.observe(control); return () => { observer.disconnect(); scope.style.removeProperty(property); if (kind === "toolbar") scope.style.removeProperty("--reader-control-width"); }; }, [kind]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref, className, "data-reader-lane": kind, "data-ud-check": kind === "toolbar" ? "reader-toolbar" : void 0, children }); } // src/client/ChoreographedFlow.tsx const FlowSnapshot = (0, react.createContext)(null); /** Public projection only. Descendants cannot leak live data through a frozen frame. */ const useFlowChat = (selector) => { const snapshot = (0, react.useContext)(FlowSnapshot); if (!snapshot) throw new Error("Flow snapshot provider missing"); return selector(snapshot); }; const idle = (frame) => ({ phase: "idle", shown: frame, target: frame, retiring: [], beforeKeys: /* @__PURE__ */ new Set() }); function Summary({ item, open, onChange, motion }) { const button = (0, react.useRef)(null); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { "data-reader-live-fold": true, "data-expanded": open, "data-reader-live-fold-summary": item.summary, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.summaryRow, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Disclosure, { open, onChange, buttonRef: button, ariaLabel: "此前步骤", label: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FoldSummaryText, { summary: item.summary, motion }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DiffStat, { steps: item.steps, label: item.summary })] }) }); } /** Manual disclosure shares the measured-size path; children survive until finish. */ function FlowCell({ hidden, instant, motion, rowKey, children, summary = false }) { const ref = (0, react.useRef)(null); useSummaryLane(ref, summary); const [present, setPresent] = (0, react.useState)(!hidden); const previous = (0, react.useRef)(hidden); if (!hidden && !present) setPresent(true); (0, react.useLayoutEffect)(() => { const el = ref.current; const changed = previous.current !== hidden; previous.current = hidden; if (!el) return; if (!changed || instant || !motion) { setPresent(!hidden); return; } const height = el.scrollHeight; const animation = el.animate([{ height: `${hidden ? height : 0}px`, opacity: hidden ? 1 : 0 }, { height: `${hidden ? 0 : height}px`, opacity: hidden ? 0 : 1 }], { duration: 220, easing: "cubic-bezier(.4,0,.2,1)", fill: "both" }); el.dispatchEvent(new CustomEvent("reader-layout-start", { bubbles: true })); let released = false; const release = () => { if (!released) { released = true; el.dispatchEvent(new CustomEvent("reader-layout-end", { bubbles: true })); } }; let settled = false; const settle = () => { if (settled) return; settled = true; if (!hidden) animation.cancel(); setPresent(!hidden); release(); }; animation.onfinish = settle; const deadline = window.setTimeout(settle, 460); return () => { window.clearTimeout(deadline); animation.cancel(); release(); }; }, [ hidden, instant, motion, present ]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref, className: Reader_module_css_default.flowCell, "data-flow-key": rowKey, "data-flow-summary": summary || void 0, hidden: hidden && !present, "aria-hidden": hidden || void 0, ...hidden ? { inert: "" } : {}, children: present && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.flowCellInner, children }) }); } function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpenChange, processOpen, renderStep, id }) { const root = (0, react.useRef)(null); const stream = (0, react.useContext)(StreamMotionContext); const latest = (0, react.useRef)(frame); latest.current = frame; const [visible, setVisible] = (0, react.useState)(() => !document.hidden); const [state, setState] = (0, react.useState)(() => idle(frame)); if ((!motion || !enabled || urgent || !visible || !processOpen || state.phase !== "idle" && Object.values(open).some(Boolean) || containsNewUser(state.shown.items, frame.items)) && (state.phase !== "idle" || state.shown !== frame)) setState(idle(frame)); else if (state.phase === "idle" && state.shown !== frame) { const retiring = retiringKeys(state.shown.items, frame.items, open); setState(retiring.length ? { ...state, phase: "collapse", target: frame, retiring, beforeKeys: new Set(flowRows(state.shown.items).map((row) => row.key)) } : idle(frame)); } (0, react.useEffect)(() => { const update = () => setVisible(!document.hidden); document.addEventListener("visibilitychange", update); return () => document.removeEventListener("visibilitychange", update); }, []); (0, react.useLayoutEffect)(() => { if (state.phase !== "collapse") return; const el = root.current; if (!el) return; const retiring = new Set(state.retiring); const animations = []; el.dispatchEvent(new CustomEvent("reader-layout-start", { bubbles: true })); for (const cell of el.querySelectorAll(":scope > [data-flow-key]")) { const key = cell.dataset.flowKey; const isHeader = cell.dataset.flowSummary && !state.beforeKeys.has(key); if (!retiring.has(key) && !isHeader) continue; const height = cell.getBoundingClientRect().height; animations.push(cell.animate(isHeader ? [{ height: "0px", opacity: 0 }, { height: `${height}px`, opacity: 1 }] : [ { height: `${height}px`, opacity: 1 }, { height: `${height * .5}px`, opacity: .85, offset: .5 }, { height: "0px", opacity: 0 } ], { duration: FOLD_TIMING.collapse, easing: "cubic-bezier(.4,0,.2,1)", fill: "both" })); } let cancelled = false; let advanced = false; const advance = () => { if (cancelled || advanced) return; advanced = true; setState((current) => current.phase === "collapse" ? { ...current, phase: "count", target: latest.current } : current); }; const deadline = window.setTimeout(advance, FOLD_TIMING.collapse + FOLD_TIMING.watchdogSlack); Promise.all(animations.map((animation) => animation.finished)).then(advance, advance); return () => { cancelled = true; window.clearTimeout(deadline); animations.forEach((animation) => animation.cancel()); el.dispatchEvent(new CustomEvent("reader-layout-end", { bubbles: true })); }; }, [state.phase]); (0, react.useEffect)(() => { if (state.phase !== "count" && state.phase !== "settle" && state.phase !== "reveal") return; const phase = state.phase; let done = false; const finish = () => { if (done) return; done = true; setState((current) => { if (current.phase !== phase) return current; if (phase === "count") return { ...current, phase: "settle" }; if (phase === "settle") return { ...current, phase: "reveal" }; return idle(current.target); }); }; let elapsed = 0; let previous; let raf = 0; const tick = (now) => { if (previous !== void 0) elapsed += Math.min(40, now - previous); previous = now; if (elapsed < FOLD_TIMING[phase]) { raf = requestAnimationFrame(tick); return; } finish(); }; raf = requestAnimationFrame(tick); const deadline = window.setTimeout(finish, FOLD_TIMING[phase] + FOLD_TIMING.watchdogSlack); return () => { window.clearTimeout(deadline); cancelAnimationFrame(raf); }; }, [state.phase]); (0, react.useLayoutEffect)(() => { if (state.phase !== "reveal" || !root.current) return; const el = root.current; el.dispatchEvent(new CustomEvent("reader-layout-start", { bubbles: true })); const animations = Array.from(el.children).filter((child) => !child.hidden && !state.beforeKeys.has(child.dataset.flowKey)).map((child) => child.animate([{ height: "0px", opacity: 0 }, { height: `${child.getBoundingClientRect().height}px`, opacity: 1 }], { duration: FOLD_TIMING.reveal, easing: "cubic-bezier(.4,0,.2,1)", fill: "both" })); return () => { animations.forEach((animation) => animation.cancel()); el.dispatchEvent(new CustomEvent("reader-layout-end", { bubbles: true })); }; }, [state.phase]); const blocked = state.phase === "collapse" || state.phase === "count" || state.phase === "settle"; const source = state.phase === "idle" || state.phase === "collapse" ? state.shown : state.target; const rows = state.phase === "collapse" ? collapseRows(state.shown.items, state.target.items) : flowRows(source.items); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FlowSnapshot.Provider, { value: source.snapshot, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StreamMotionContext.Provider, { value: { ...stream, paused: state.phase !== "idle", resumed: state.phase === "reveal" }, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { id, ref: root, className: Reader_module_css_default.choreographedFlow, "data-reader-flow": true, "data-reader-transition": state.phase, "data-ud-motion": "fold-choreography", children: rows.map((row) => { if (row.kind === "summary") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FlowCell, { rowKey: row.key, hidden: false, instant: true, motion, summary: true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Summary, { item: row.item, open: processOpen && !!open[row.key], onChange: (value) => onOpenChange(row.key, value), motion: motion && state.phase !== "collapse" }) }, row.key); const hidden = !!row.foldKey && (!processOpen || !open[row.foldKey]) || blocked && state.phase !== "collapse" && !state.beforeKeys.has(row.key); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FlowCell, { rowKey: row.key, hidden, instant: state.phase !== "idle", motion, children: renderStep(row.step, !!row.foldKey) }, row.key); }) }) }) }); } // src/client/ClosedProcessSummary.tsx /** Keep process counts discoverable after the live-fold presentation retires. */ function ClosedProcessSummary({ steps, open, onChange, controls }) { const button = (0, react.useRef)(null); const lane = usePublishedHeight("--reader-summary-height"); if (!steps.length) return null; const summary = foldSummary(steps); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { ref: lane, className: Reader_module_css_default.closedProcessSummary, "data-reader-closed-summary": summary, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.summaryRow, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Disclosure, { open, onChange, controls, buttonRef: button, ariaLabel: "本轮过程详情", label: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FoldSummaryText, { summary, motion: false }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DiffStat, { steps, label: summary })] }) }); } // src/client/Reader.tsx function isNode(node, kind) { return node.kind === kind; } function observedInputIds(order, getNode) { const ids = /* @__PURE__ */ new Set(); for (const key of order) { const node = getNode(key); if (!node || node.kind !== "user" && node.kind !== "steering" && node.kind !== "turn-trigger") continue; const source = node.data.source; if (source?.kind === "user" && typeof source.rpcId === "string") ids.add(source.rpcId); } return ids; } function inboxText(item) { return (item.content ?? []).filter((block) => { return typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string"; }).map((block) => block.text).join(""); } function inboxAttachmentCount(item) { return (item.content ?? []).filter((block) => typeof block === "object" && block !== null && block.type !== "text").length; } function cleanErrorMessage(raw) { if (!raw) return "模型服务暂时无响应或连接中断,请稍后重试。"; let str = raw.trim(); if (str.includes("\"error\"") || str.startsWith("{")) try { const idx = str.indexOf("{"); const parsed = JSON.parse(str.slice(idx)); const msg = parsed?.error?.message || parsed?.message || parsed?.error; if (typeof msg === "string") str = msg; } catch {} return str; } const CompactionDivider = (0, react.memo)(function CompactionDivider({ data }) { const [open, setOpen] = (0, react.useState)(false); if (!data) return null; const hasSummary = typeof data.summary === "string" && data.summary.trim().length > 0; const items = data.shadowedItemCount; const tokens = data.shadowedTokenCount; let label = "已压缩历史上下文"; if (items && tokens) label = `已压缩 ${items} 条上下文 · 释放约 ${tokens >= 1e3 ? `${(tokens / 1e3).toFixed(1)}k` : String(tokens)} tokens`; else if (items) label = `已压缩 ${items} 条上下文`; else if (tokens) label = `已压缩上下文 · 释放约 ${tokens >= 1e3 ? `${(tokens / 1e3).toFixed(1)}k` : String(tokens)} tokens`; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.compactionRow, "data-reader-compaction": true, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.compactionLine, children: hasSummary ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { type: "button", className: `${Reader_module_css_default.compactionPill} ${Reader_module_css_default.compactionButton}`, onClick: () => setOpen((v) => !v), "aria-expanded": open, title: open ? "收起历史记忆摘要" : "展开查看此节点提炼的记忆摘要", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { className: Reader_module_css_default.compactionIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2z", strokeWidth: "1.2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 5v3.2l2 1.8", strokeWidth: "1.2", strokeLinecap: "round", strokeLinejoin: "round" })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: label }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.compactionToggle, children: open ? "收起备忘" : "查看备忘" }) ] }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.compactionPill, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { className: Reader_module_css_default.compactionIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2z", strokeWidth: "1.2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 5v3.2l2 1.8", strokeWidth: "1.2", strokeLinecap: "round", strokeLinejoin: "round" })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: label })] }) }), open && hasSummary && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.compactionSummaryBox, "data-reader-anchor": true, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.compactionSummaryHeader, children: "前期对话要点备忘" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.MarkdownText, { text: data.summary, labels: markdownLabels })] })] }); }); const ProcessNode = (0, react.memo)(function ProcessNode({ useChat, t, nodeKey, open, motion, onRead, returnFocusTo }) { const node = useChat((snapshot) => snapshot.nodes.get(nodeKey)); if (!node || node.visibility === "hidden") return null; let content = null; if (isNode(node, "context")) content = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ContextInjectionRow, { ...node.data, t }); else if (isNode(node, "system-prompt")) content = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", { className: Reader_module_css_default.detail, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", { children: "系统提示词" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { className: Reader_module_css_default.systemPrompt, children: node.data.text })] }); else if (isNode(node, "model-retry")) content = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonBlock, { label: "模型重试记录", payload: node.data.attempts, truncatedLabel: truncatedJsonLabel }); else if (isNode(node, "manual-compaction")) { if (node.data.command.outcome?.kind === "error") content = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.error, role: "alert", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { className: Reader_module_css_default.errorIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", { cx: "8", cy: "8", r: "6.5", strokeWidth: "1.2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 5v3.5M8 11.2h.01", strokeWidth: "1.5", strokeLinecap: "round" })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.errorCopy, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.errorTitle, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "上下文压缩未成功" }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.errorMessage, children: node.data.command.outcome.text })] })] }); else content = node.data.compaction ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CompactionDivider, { data: node.data.compaction }) : null; } else if (isNode(node, "compaction")) content = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CompactionDivider, { data: node.data }); else if (isNode(node, "command")) content = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonBlock, { label: "命令记录", payload: node.data, truncatedLabel: truncatedJsonLabel }); return content && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProcessFragment, { open, motion, onRead, returnFocusTo, nodeKey, framed: true, children: content }); }); const MainNode = (0, react.memo)(function MainNode({ useChat, nodeKey, boundary, pinned, processOpen: _processOpen = false, ...render }) { const node = useChat((snapshot) => snapshot.nodes.get(nodeKey)); const [disclosureReset] = (0, react.useState)(() => (0, _deepseek_ai_dsh_client_store.createSnapshotStore)(0)); if (!node || node.visibility === "hidden") return null; if (isNode(node, "user") || isNode(node, "steering")) { const blocks = contentBlocks(node.data.content); const imageBlocks = blocks.filter((b) => b.kind === "image"); const otherBlocks = blocks.filter((b) => b.kind !== "image"); const text = otherBlocks.filter((block) => block.kind === "text").map((block) => block.text).join("\n\n"); const time = node.data.time; const fallback = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ node.kind === "steering" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.meta, children: "补充消息" }), imageBlocks.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.userImages, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Blocks, { ...render, blocks: imageBlocks, source: "user" }) }), otherBlocks.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.user, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Blocks, { ...render, blocks: otherBlocks, source: "user" }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UserMessageActions, { text, time }) ] }); const official = render.official; let rendered = fallback; if (official) { const turn = node.location.kind === "turn" || node.location.kind === "step" ? node.location.turn : void 0; const owner = { cwd: render.cwd, openFile: render.openFile ?? (() => {}), forkAt: render.forkAt ?? (() => {}), inspectCall: (callId) => official.openView("trajectory", callId), loadImage: official.officialImageLoader, fileMentions: official.officialFileMentions, sessionId: render.sessionId }; const options = { hookContext: { turnData: turn?.data, disclosureReset, useGroupAction: readerGroupAction }, fallback }; rendered = node.kind === "user" ? official.renderSlot(OFFICIAL_SEATS.nodes, { ...owner, node }, { ...options, entryKey: "user" }) : official.renderSlot(OFFICIAL_SEATS.nodes, { ...owner, node }, { ...options, entryKey: "steering" }); } return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.userCluster, "data-reader-anchor": true, "data-reader-key": nodeKey, ...chatSeatProps(node.kind, nodeKey), children: rendered }); } if (isNode(node, "assistant-step")) return null; if (isNode(node, "tool-call")) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolMedia, { ...render, block: node.data.root }); if (isNode(node, "turn-error")) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.error, role: "alert", "data-reader-anchor": true, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { className: Reader_module_css_default.errorIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", { cx: "8", cy: "8", r: "6.5", strokeWidth: "1.2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 5v3.5M8 11.2h.01", strokeWidth: "1.5", strokeLinecap: "round" })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.errorCopy, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.errorTitle, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "本轮运行失败" }), node.data.code && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { className: Reader_module_css_default.errorCode, children: node.data.code })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.errorMessage, children: cleanErrorMessage(node.data.message) })] })] }); if (isNode(node, "turn-max-tokens")) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.notice, children: "已到达输出长度限制,回答尚未完整。" }); if (isNode(node, "model-retry")) return node.data.current.retryState === "scheduled" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.notice, role: "status", children: "模型请求未成功,正在等待重试。详情保留在执行过程中。" }) : null; if (isNode(node, "command") && render.official) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OfficialNode, { ...render, node, fallback: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonBlock, { label: "命令记录", payload: node.data, truncatedLabel: truncatedJsonLabel }) }); if (isNode(node, "command")) { if (node.data.outcome?.kind === "error") return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.error, role: "alert", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { className: Reader_module_css_default.errorIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", { cx: "8", cy: "8", r: "6.5", strokeWidth: "1.2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M8 5v3.5M8 11.2h.01", strokeWidth: "1.5", strokeLinecap: "round" })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.errorCopy, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.errorTitle, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "命令执行未成功" }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.errorMessage, children: node.data.outcome.text ?? node.data.name ?? "查看原对话中的命令记录" })] })] }); return node.data.outcome?.text ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.MarkdownText, { text: node.data.outcome.text, labels: markdownLabels }) : null; } if (isNode(node, "manual-compaction") || isNode(node, "compaction")) return null; if (node.kind === "context" || node.kind === "turn-tail" || node.kind === "system-prompt" || node.kind === "turn-process") return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OfficialNode, { ...render, node, fallback: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.unknown, "data-reader-anchor": true, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", { children: ["此记录类型暂未接入阅读页:", node.kind] }), render.official && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.textButton, onClick: () => render.official.openView("chat", node.key), children: "在对话中查看" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.JsonBlock, { label: "查看原始记录", payload: node.data, truncatedLabel: truncatedJsonLabel }) ] }) }); }); /** * Sub-agents this turn dispatched, read from the host's own Turn-process row. * * The host already derives this from the dispatch tree (`subagentCount` on * `TurnProcessChatData`), so counting calls here would only risk disagreeing with * it. The row is otherwise hidden by the reader, which is why this is the one place * its counters are read. */ function subagentCount(snapshot, keys) { for (const key of keys) { const node = snapshot.nodes.get(key); if (!node || node.kind !== "turn-process") continue; const value = node.data.subagentCount; if (typeof value === "number" && Number.isFinite(value) && value > 0) return value; } return 0; } function GroupStatus({ group, useChat, pending, motion }) { const text = useChat((snapshot) => { const turn = group.turn === null ? void 0 : snapshot.timeline.turns.get(group.turn); if (turn?.status === "closed") { if (turn.end?.data.reason.kind !== "completed") return "执行过程"; const elapsed = turn.start && turn.end ? Math.max(0, Math.round((turn.end.time - turn.start.time) / 1e3)) : null; return elapsed === null ? "执行过程" : elapsed < 60 ? `用时 ${elapsed} 秒` : `用时 ${Math.floor(elapsed / 60)} 分 ${elapsed % 60} 秒`; } if (turn?.status !== "open") return "执行过程"; if (pending !== void 0) return "等待你的操作"; const current = turn.steps.at(-1)?.data.get("assistant-step"); const last = current?.blocks.at(-1); if (current?.status === "running" && last?.kind === "tool-call") { const spawned = subagentCount(snapshot, group.keys); return spawned ? `${preparingLabel(last.name)}·${spawned} 个子代理` : preparingLabel(last.name); } for (let index = group.keys.length - 1; index >= 0; index--) { const node = snapshot.nodes.get(group.keys[index]); if (!node) continue; if (isNode(node, "tool-call") && !("kind" in node.data.root)) return "正在使用工具"; if (isNode(node, "assistant-step") && node.data.status === "running") { const last = node.data.blocks.at(-1); return last?.kind === "reasoning" ? "正在思考" : last?.kind === "text" ? "正在输出" : "正在准备回复"; } } return "正在处理"; }); const busy = useChat((snapshot) => group.turn !== null && snapshot.timeline.turns.get(group.turn)?.status === "open" && pending === void 0); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatusText, { text, motion, shimmer: busy }); } const DeliverableChip = (0, react.memo)(function DeliverableChip({ path, openFile, revealFile, openMode }) { const [status, setStatus] = (0, react.useState)("idle"); const timer = (0, react.useRef)(); const flash = (next) => { setStatus(next); clearTimeout(timer.current); timer.current = setTimeout(() => setStatus("idle"), 1600); }; const onOpen = (event) => { event.stopPropagation(); try { openFile?.(path); flash("opened"); } catch {} }; const onReveal = (event) => { event.stopPropagation(); try { if (revealFile) revealFile(path); else openFile?.(dirname(path)); flash("revealed"); } catch {} }; const onCopy = (event) => { event.stopPropagation(); try { navigator.clipboard?.writeText(path); flash("copied"); } catch {} }; const name = basename(path); const folder = dirname(path); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.deliverableChip, "data-status": status, title: path, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { type: "button", className: Reader_module_css_default.chipMain, onClick: onOpen, onDoubleClick: onOpen, "aria-label": openMode === "sidebar" ? `在内置面板中打开 ${path}` : `用系统应用打开 ${path}`, children: [status === "opened" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { className: Reader_module_css_default.statusIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3.5 8.5l3 3 6-7", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round" }) }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { className: Reader_module_css_default.deliverableIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 2.5h5l3 3V13.5H4V2.5z", strokeWidth: "1.2", strokeLinejoin: "round" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M9 2.5v3h3", strokeWidth: "1.2", strokeLinejoin: "round" })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.deliverableName, children: status === "opened" ? openMode === "sidebar" ? "已在面板打开" : "已在外部打开" : name })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.chipActions, "aria-label": "文件操作", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.chipActionBtn, title: `在访达中定位所在目录 (${folder})`, "aria-label": "在访达中显示所在目录", onClick: onReveal, children: status === "revealed" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { className: Reader_module_css_default.actionIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3.5 8.5l3 3 6-7", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round" }) }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { className: Reader_module_css_default.actionIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M2 4.5h4l1.5 2H14v6.5H2V4.5z", strokeWidth: "1.2", strokeLinejoin: "round" }) }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.chipActionBtn, title: "复制相对路径", "aria-label": "复制相对路径", onClick: onCopy, children: status === "copied" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { className: Reader_module_css_default.actionIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3.5 8.5l3 3 6-7", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round" }) }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", { className: Reader_module_css_default.actionIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", { x: "5.5", y: "5.5", width: "8", height: "8", rx: "1.5", strokeWidth: "1.2" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M4 10.5H3a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v1", strokeWidth: "1.2", strokeLinecap: "round" })] }) })] })] }); }); function DeliverablesRow({ deliverables, openFile, revealFile, openMode }) { const [folderStatus, setFolderStatus] = (0, react.useState)("idle"); const onOpenWorkspace = () => { try { openFile?.("."); setFolderStatus("opened"); setTimeout(() => setFolderStatus("idle"), 1600); } catch {} }; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.deliverablesRoot, "data-reader-deliverables": true, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: Reader_module_css_default.deliverablesLabel, children: "产物" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.deliverablesLane, children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.deliverablesRow, children: [ deliverables.slice(0, 8).map((path) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DeliverableChip, { path, openFile, revealFile, openMode }, path)), deliverables.length > 8 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { className: Reader_module_css_default.deliverablesMore, children: [ "+ ", deliverables.length - 8, " 个文件" ] }), deliverables.length > 1 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", { type: "button", className: Reader_module_css_default.deliverablesShowFolder, "data-status": folderStatus, onClick: onOpenWorkspace, title: "在访达中打开整个工作区目录", children: [folderStatus === "opened" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { className: Reader_module_css_default.statusIcon, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3.5 8.5l3 3 6-7", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round" }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: folderStatus === "opened" ? "已打开访达" : "在文件夹中显示" })] }) ] }) })] }); } const TurnGroup = (0, react.memo)(function TurnGroup({ group, motion, autoFold, pinnedKeys, selectedProcessKeys, isAwaitingModel = false, ...props }) { const snapshot = props.useChat((snapshot) => snapshot); const nodes = snapshot.nodes; const turn = group.turn === null ? void 0 : snapshot.timeline.turns.get(group.turn); const interaction = props.useSessionStatus((snapshot) => snapshot.get(props.sessionId)?.pendingInteraction); const sessionRunning = props.useSession((snapshot) => snapshot.running); const boundary = (0, react.useMemo)(() => boundaryOf(turn), [turn]); const choiceKey = processChoiceKey(group.key, boundary); const expansionChoice = props.useStore((state) => state.expanded[choiceKey]); const flowId = (0, react.useId)(); const processButton = (0, react.useRef)(null); const setExpanded = (0, react.useCallback)((value) => props.actions.setExpanded(choiceKey, value), [props.actions, choiceKey]); const pinProcess = (0, react.useCallback)(() => setExpanded(true), [setExpanded]); const startsWithUser = props.useChat((snapshot) => snapshot.nodes.get(group.keys[0])?.kind) === "user"; const mainKeys = startsWithUser ? group.keys.slice(1) : group.keys; const flow = (0, react.useMemo)(() => readerFlow({ ...group, keys: mainKeys }, turn, (key) => nodes.get(key), snapshot.order), [ nodes, group, mainKeys, turn, snapshot.order ]); const steps = (0, react.useMemo)(() => segmentLiveTurn(flow, (key) => nodes.get(key)), [flow, nodes]); const liveItems = (0, react.useMemo)(() => presentLiveTurn(steps, boundary, autoFold), [ steps, boundary, autoFold ]); const openMode = deliverableOpenModeOf((0, react.useSyncExternalStore)(props.openPrefs?.subscribe ?? ((fn) => { return () => {}; }), () => props.openPrefs?.getSnapshot()?.deliverableOpenMode, () => "external")); const hasProcess = flow.some((item) => item.kind === "tool" || hasProcessContent(nodes.get(item.nodeKey), boundary)); const showStatusLane = hasProcess && !isAwaitingModel; const showClosedSummary = boundary.status === "closed" && hasProcess && autoFold; const holdingSelection = selectedProcessKeys.some((key) => flow.some((item) => item.key === key) || liveItems.some((item) => item.kind === "fold" ? item.key === key || item.steps.some((step) => step.key === key || "nodeKey" in step && step.nodeKey === key) : item.key === key || "nodeKey" in item.step && item.step.nodeKey === key)); const expanded = !autoFold || holdingSelection || processExpanded(expansionChoice, boundary); const seamPlan = (0, react.useMemo)(() => planProcessSeams(steps, liveItems, expanded), [ steps, liveItems, expanded ]); const [foldOpenByKey, setFoldOpenByKey] = (0, react.useState)({}); (0, react.useLayoutEffect)(() => { if (autoFold) setFoldOpenByKey((current) => Object.keys(current).length ? {} : current); }, [autoFold]); const deliverables = (0, react.useMemo)(() => getTurnDeliverables(turn, flow), [turn, flow]); const tailData = (0, react.useMemo)(() => { for (const key of group.keys) { const n = nodes.get(key); if (n && isNode(n, "turn-tail")) return n.data; } }, [group.keys, nodes]); const tailOwner = (0, react.useMemo)(() => turn && tailData ? { turn, seq: tailData.closing?.finalNode.seq ?? tailData.seq, openFile: props.openFile } : void 0, [ turn, tailData, props.openFile ]); const fileMentions = (0, react.useMemo)(() => { const official = tailOwner ? props.officialFileMentions(tailOwner) : void 0; const reader = deliverables.length > 0 ? createProducedFileMentions(deliverables, props.openFile) : void 0; return official || reader ? { resolve: (value) => official?.resolve(value) ?? reader?.resolve(value) } : void 0; }, [ tailOwner, props.officialFileMentions, deliverables, props.openFile ]); const official = (0, react.useMemo)(() => ({ renderSlot: props.renderSlot, renderSlotChain: props.renderSlotChain, officialImageLoader: props.officialImageLoader, officialFileMentions: props.officialFileMentions, officialPreviewFile: props.officialPreviewFile, officialHost: props.officialHost, openView: props.openView }), [ props.renderSlot, props.renderSlotChain, props.officialImageLoader, props.officialFileMentions, props.officialPreviewFile, props.officialHost, props.openView ]); const cwd = props.useSessions((state) => state.byId[props.sessionId]?.cwd); const runMs = turn?.start && turn?.end ? Math.max(0, turn.end.time - turn.start.time) : void 0; const metrics = (0, react.useMemo)(() => ({ usage: tailData?.tokenUsage, runMs, tokensPerSecond: tailData?.tokensPerSecond, ttftMs: tailData?.ttftMs, endedAt: tailData?.closing?.time ?? turn?.end?.time }), [ tailData, runMs, turn?.end?.time ]); const forkSeq = forkAnchorSeq([tailData?.closing?.finalNode]); const presentation = (0, react.useMemo)(() => { const captured = new Map(group.keys.flatMap((key) => { const node = nodes.get(key); return node ? [[key, node]] : []; })); return { items: holdingSelection ? presentLiveTurn(steps, boundary, false) : liveItems, snapshot: { ...snapshot, nodes: { ...nodes, get: (key) => captured.get(key), values: () => [...captured.values()] } } }; }, [ snapshot, nodes, group, steps, boundary, liveItems, holdingSelection ]); const shared = { useChat: useFlowChat, renderSlotChain: props.renderSlotChain, loadImage: props.loadImage, fillComposer: props.fillComposer, openFile: props.openFile, revealFile: props.revealFile, forkAt: props.forkAt, forkSeq, fileMentions, metrics, official, sessionId: props.sessionId, cwd }; const terminal = terminalLabel(boundary.reason); const hasTurnError = flow.some((item) => item.kind === "node" && nodes.get(item.nodeKey)?.kind === "turn-error"); const hasAnswerProse = steps.some((step) => step.kind === "body" && step.blocks.some((block) => block.kind === "text" && block.text.trim() !== "")); const stoppedWithoutAnswer = (boundary.reason === "interrupted" || boundary.reason === "aborted") && !hasAnswerProse; const showTerminalNotice = terminal && !hasTurnError && (stoppedWithoutAnswer || boundary.reason !== "interrupted" && boundary.reason !== "aborted"); const renderStep = (step, folded) => { const processOpen = folded || expanded; if (step.kind === "reasoning" || step.kind === "body") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BlockBoundary, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(AssistantNode, { ...shared, boundary, nodeKey: step.nodeKey, partStart: step.start, pinned: pinnedKeys.includes(step.nodeKey), processOpen, folded, motion, onRead: pinProcess, returnFocusTo: processButton, seamSummary: step.kind === "body" ? seamPlan.before.get(step.key) : void 0, seamAfter: step.kind === "body" && seamPlan.after.has(step.key) }) }); if (step.kind === "tool") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BlockBoundary, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(ProcessFragment, { open: processOpen, motion, onRead: pinProcess, returnFocusTo: processButton, nodeKey: step.key, framed: true, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolActivity, { ...shared, entry: step.entry, motion, turnClosed: boundary.status === "closed", onRead: pinProcess }), step.entry.block && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolMedia, { ...shared, block: step.entry.block })] }) }); if (step.kind === "user") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BlockBoundary, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MainNode, { ...shared, boundary, nodeKey: step.nodeKey }) }); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(BlockBoundary, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProcessNode, { useChat: useFlowChat, t: props.t, nodeKey: step.nodeKey, open: processOpen, motion, onRead: pinProcess, returnFocusTo: processButton }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BlockBoundary, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MainNode, { ...shared, boundary, nodeKey: step.nodeKey, pinned: pinnedKeys.includes(step.nodeKey), processOpen }) })] }); }; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", { className: Reader_module_css_default.turn, "data-reader-turn": group.turn ?? "unresolved", "data-reader-turn-state": boundary.status, "data-reader-turn-result": boundary.reason ?? void 0, children: [ startsWithUser && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BlockBoundary, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MainNode, { ...shared, useChat: props.useChat, boundary, nodeKey: group.keys[0] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.turnStickyRegion, "data-reader-sticky-region": true, children: [(showStatusLane || showClosedSummary) && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.turnStickyLanes, children: [showStatusLane && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StickyLane, { kind: "status", className: Reader_module_css_default.turnProcessSticky, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Disclosure, { open: expanded, onChange: setExpanded, controls: flowId, buttonRef: processButton, label: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GroupStatus, { group, useChat: props.useChat, pending: interaction, motion }) }) }), showClosedSummary && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ClosedProcessSummary, { open: expanded, onChange: setExpanded, controls: flowId, steps: steps.filter((step) => step.kind !== "user" && step.kind !== "body") })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChoreographedFlow, { id: flowId, frame: presentation, motion, enabled: autoFold && boundary.status === "open" && !holdingSelection, urgent: hasTurnError || interaction !== void 0 || !sessionRunning, open: foldOpenByKey, processOpen: expanded, onOpenChange: (key, value) => { pinProcess(); setFoldOpenByKey((current) => ({ ...current, [key]: value })); }, renderStep })] }), !hasProcess && boundary.status === "open" && !isAwaitingModel && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.disclosure, "data-reader-status-only": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GroupStatus, { group, useChat: props.useChat, pending: interaction, motion }) }), showDeliverablesRow(boundary.status, deliverables) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DeliverablesRow, { deliverables, openFile: props.openFile, revealFile: props.revealFile, openMode }), boundary.status === "closed" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BlockBoundary, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OfficialTail, { official, owner: tailOwner, produced: deliverables }) }), showTerminalNotice && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.notice, "data-reader-terminal": true, children: terminal }) ] }); }); function Reader(props) { (0, react.useInsertionEffect)(() => { ensureStyles(); }, []); const root = (0, react.useRef)(null); const activatedAt = (0, react.useRef)(Date.now()); const order = props.useChat((snapshot) => snapshot.order); const nodes = props.useChat((snapshot) => snapshot.nodes); const rewindSignature = props.useChat((snapshot) => visibleChatSignature(snapshot)); const renderKeys = (0, react.useMemo)(() => visibleChatKeys({ order, nodes }), [ order, nodes, rewindSignature ]); const timeline = props.useChat((snapshot) => snapshot.timeline); const running = props.useSession((snapshot) => snapshot.running); const pending = props.useSessionStatus((snapshot) => snapshot.get(props.sessionId)?.pendingInteraction); const openError = props.useSession((snapshot) => snapshot.openError); const loading = props.useSession((snapshot) => snapshot.openState === "loading"); const hasMore = props.useSession((snapshot) => snapshot.hasMore); const loadingOlder = props.useSession((snapshot) => snapshot.loadingOlder); const pendingList = asReadonlyArray(props.useSession((snapshot) => snapshot.pendingSubmissions)); const inbox = props.useProjection?.("inbox"); const inboxSteering = asReadonlyArray(inbox?.["next-step"]).filter((item) => item.source?.kind === "user"); const observed = (0, react.useMemo)(() => observedInputIds(order, (key) => nodes.get(key)), [order, nodes]); const visibleSubmissions = (0, react.useMemo)(() => pendingList.filter((sub) => sub.placement !== "queued" && !observed.has(sub.requestId)), [pendingList, observed]); const pendingInputs = (0, react.useMemo)(() => { const local = new Map(visibleSubmissions.map((sub) => [sub.requestId, sub])); const localIds = new Set(pendingList.filter((sub) => sub.placement !== "queued").map((sub) => sub.requestId)); const rows = []; for (const item of inboxSteering) { const rpcId = typeof item.source?.rpcId === "string" ? item.source.rpcId : void 0; if (!rpcId) { rows.push(item); continue; } const submission = local.get(rpcId); if (submission) { local.delete(rpcId); rows.push(submission); } else if (!localIds.has(rpcId)) rows.push(item); } rows.push(...local.values()); return rows; }, [ inboxSteering, pendingList, visibleSubmissions ]); const waitAnchor = waitingAnchor(renderKeys, (key) => nodes.get(key), pendingList); const motion = useMotionAllowed(props.useStore((state) => state.motion)); const prefsSnap = (0, react.useSyncExternalStore)(props.openPrefs?.subscribe ?? ((fn) => { return () => {}; }), () => props.openPrefs?.getSnapshot?.(), () => void 0); const storeAutoFold = props.useStore((state) => state.autoFold); const autoFold = prefsSnap?.autoFold ?? (prefsSnap?.foldIntensity !== void 0 ? prefsSnap.foldIntensity !== 0 : void 0) ?? storeAutoFold ?? true; const previousAutoFold = (0, react.useRef)(autoFold); (0, react.useLayoutEffect)(() => { const restored = autoFold && !previousAutoFold.current; previousAutoFold.current = autoFold; if (restored) props.actions.resetExpanded(); }, [autoFold, props.actions]); const frostedGlass = frostedGlassOf(prefsSnap); const streamMotion = (0, react.useMemo)(() => ({ enabled: motion, activatedAt: activatedAt.current }), [motion]); const groups = (0, react.useMemo)(() => groupNodes(renderKeys, (key) => nodes.get(key)), [ renderKeys, nodes, timeline ]); const isAwaitingModel = (0, react.useMemo)(() => { if (!running && pendingList.length > 0) return true; const lastKey = renderKeys.at(-1); const lastNode = lastKey ? nodes.get(lastKey) : void 0; if (!lastKey || !lastNode) return false; if (lastNode.kind === "assistant-step") { const data = lastNode.data; return (data.blocks ?? []).length === 0 && data.status === "running"; } if (!handsBackToModel(lastNode)) return false; const lastGroup = groups.at(-1); return (lastGroup?.turn === null || lastGroup?.turn === void 0 ? void 0 : timeline.turns.get(lastGroup.turn))?.status !== "closed"; }, [ running, pendingList, renderKeys, nodes, groups, timeline ]); const scroll = useReadingScroll(root, motion); const pinnedKeys = usePinnedSelection(root); const selectedProcessKeys = usePinnedSelection(root, "[data-reader-process]"); const [historyError, setHistoryError] = (0, react.useState)(false); const turnNavigationItems = props.useChat((snapshot) => snapshot.navigation?.items ? snapshot.navigation.items() : void 0); const turnOutline = props.useProjection?.("turnOutline"); const turnsWithDeliverables = (0, react.useMemo)(() => { const set = /* @__PURE__ */ new Set(); for (const [turnNum, loc] of timeline.turns) { const deliv = loc.data?.get("deliverables"); if (Array.isArray(deliv?.produced) && deliv.produced.length > 0) set.add(turnNum); } return set; }, [timeline]); const timelineItems = (0, react.useMemo)(() => mergeTimelineItems(turnNavigationItems, turnOutline, turnsWithDeliverables), [ turnNavigationItems, turnOutline, turnsWithDeliverables ]); const [activeTurn, setActiveTurn] = (0, react.useState)(null); const [busyTurn, setBusyTurn] = (0, react.useState)(null); (0, react.useEffect)(() => { const el = root.current; if (!el) return; const scroller = el.closest("[data-conversation-scroll]") ?? el; let ticking = false; const updateActive = () => { if (ticking) return; ticking = true; requestAnimationFrame(() => { ticking = false; const line = (scroller instanceof HTMLElement ? scroller.clientHeight : window.innerHeight) * .35; const turnRows = el.querySelectorAll("[data-reader-turn]:not([data-reader-turn=\"unresolved\"])"); let current = null; for (const row of turnRows) if (row.getBoundingClientRect().top <= line) { const num = Number(row.dataset.readerTurn); if (Number.isSafeInteger(num)) current = num; } else break; if (current !== null) setActiveTurn(current); else if (turnRows.length > 0) { const first = Number(turnRows[0].dataset.readerTurn); if (Number.isSafeInteger(first)) setActiveTurn(first); } }); }; scroller.addEventListener("scroll", updateActive, { passive: true }); updateActive(); return () => scroller.removeEventListener("scroll", updateActive); }, [groups]); const onNavigateTurn = (0, react.useCallback)(async (item) => { const el = root.current; if (!el) return; const port = scrollerOf(el); const reveal = (turn) => { const targetRow = el.querySelector(`[data-reader-turn="${turn}"]`); if (!targetRow) return; const last = timelineItems.at(-1); if (last !== void 0 && last.turn === turn) scroll.jump(); else { scroll.release(); landTurn(targetRow, port); } setActiveTurn(turn); }; if (item.anchor.kind === "loaded") { reveal(item.turn); return; } setBusyTurn(item.turn); try { if (props.loadThrough) await props.loadThrough(item.anchor.seq); else await props.loadOlder(); setTimeout(() => { reveal(item.turn); }, 50); } finally { setBusyTurn(null); } }, [ props.loadThrough, props.loadOlder, scroll.jump, scroll.release, timelineItems ]); const lastKey = renderKeys.at(-1); const lastNode = lastKey ? nodes.get(lastKey) : void 0; const lastSubmissionId = pendingList.length ? pendingList[pendingList.length - 1].requestId : null; const lastOrderKeyRef = (0, react.useRef)(lastKey); const lastSubmissionRef = (0, react.useRef)(lastSubmissionId); (0, react.useLayoutEffect)(() => { const appendedUser = lastKey !== lastOrderKeyRef.current && (lastNode?.kind === "user" || lastNode?.kind === "steering"); const appendedSubmission = lastSubmissionId !== null && lastSubmissionId !== lastSubmissionRef.current; lastOrderKeyRef.current = lastKey; lastSubmissionRef.current = lastSubmissionId; if (appendedUser || appendedSubmission) scroll.jump(); }, [ lastKey, lastNode?.kind, lastSubmissionId, scroll ]); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StreamMotionContext.Provider, { value: streamMotion, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ReaderLaneScope, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { ref: root, className: Reader_module_css_default.root, "data-reader-build": "0.3.4", "data-dsh-better-display": "0.3.4", "data-reader-wait-clock-version": "input-v1", "data-reader-wait-start": waitAnchor.time ?? void 0, "data-motion": motion ? "on" : "off", "data-reader-glass": frostedGlass || void 0, "data-reader-auto-fold": autoFold ? "on" : "off", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(TimelineRail, { items: timelineItems, activeTurn, busyTurn, onNavigate: onNavigateTurn }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.column, "data-chat-flow": "", tabIndex: -1, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StickyLane, { kind: "toolbar", className: Reader_module_css_default.toolbar, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.textButton, "aria-pressed": autoFold, onClick: () => { props.actions.setAutoFold(!autoFold); props.openPrefs?.actions?.setAutoFold?.(!autoFold); }, title: "新思考产生时,是否自动将此前步骤收拢为一行汇总。关闭后完整保留原始过程与流式输出。", children: `自动折叠${autoFold ? "开" : "关"}` }) }), hasMore && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.historyButton, disabled: loadingOlder, onClick: async () => { setHistoryError(false); try { await props.loadOlder(); } catch { setHistoryError(true); } }, children: loadingOlder ? "正在加载更早记录" : "加载更早记录" }), historyError && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.notice, children: "历史记录加载失败,可再次尝试;现有内容未改变。" }), openError && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.error, role: "alert", children: ["会话暂时无法读取:", openError.message] }), loading && groups.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: Reader_module_css_default.empty, role: "status", children: "正在读取会话…" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RetiringTurns, { groups, render: (group) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TurnGroup, { ...props, group, motion, autoFold, pinnedKeys, selectedProcessKeys, isAwaitingModel: isAwaitingModel && group.key === groups.at(-1)?.key }) }), pendingInputs.map((item, index) => { const submission = "requestId" in item ? item : void 0; const text = submission?.text ?? inboxText(item); const images = submission ? pendingSubmissionImages(submission) : []; const attachmentCount = submission ? images.length : inboxAttachmentCount(item); const requestId = submission?.requestId ?? `inbox-${index}`; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.userCluster, "data-reader-pending-submission": true, "data-pending-steering": submission ? void 0 : "", "data-pending-attachment-count": attachmentCount, children: [ images.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.userImages, children: images.map((item, idx) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("figure", { className: Reader_module_css_default.imageFigure, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.imageFrame, style: { aspectRatio: `${item.width || 4} / ${item.height || 3}` }, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", { src: item.previewUrl, alt: item.name ?? "发送的图片", className: Reader_module_css_default.pendingImage }) }) }, idx)) }), text ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.user, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.blocks, children: text }) }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UserMessageActions, { text, time: submission?.time }) ] }, requestId); }), isAwaitingModel && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WaitingStatus, { anchor: waitAnchor, label: props.t ? props.t("chat.deepDiving") : "深度求索中..." }), pending !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: Reader_module_css_default.attention, role: "alert", "data-reader-attention": true, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: pending.kind === "question" ? "需要你回答一个问题" : "需要你的确认" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "请在下方原生操作区处理。此提示不会收进执行过程。" })] }), scroll.detached && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: Reader_module_css_default.jumpDock, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: Reader_module_css_default.jump, "aria-label": "回到底部", title: "回到底部", onClick: scroll.jump, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", { viewBox: "0 0 14 14", width: "14", height: "14", "aria-hidden": "true", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", { d: "M3 5.5 7 9.5 11 5.5", fill: "none", stroke: "currentColor", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round" }) }) }) }) ] })] }) }) }); } // src/client/store.ts function applyFoldIntensity(draft, value) { draft.foldIntensity = value; draft.autoFold = autoFoldFromIntensity(value); draft.processOnly = processOnlyFromIntensity(value); } function createReaderStore() { return (0, _deepseek_ai_dsh_client_store.defineStore)({ init: () => ({ expanded: {}, motion: true, autoFold: true, deliverableOpenMode: "external", foldIntensity: 1, frostedGlass: false, processOnly: false }), persist: "dsh.reader.v1", actions: { setExpanded: (draft, key, value) => { draft.expanded[key] = value; }, resetExpanded: (draft) => { draft.expanded = {}; }, setMotion: (draft, value) => { draft.motion = value; }, setAutoFold: (draft, value) => { applyFoldIntensity(draft, value ? draft.foldIntensity === 2 ? 2 : 1 : 0); }, setDeliverableOpenMode: (draft, value) => { draft.deliverableOpenMode = value; }, setFoldIntensity: (draft, value) => { applyFoldIntensity(draft, value); }, setFrostedGlass: (draft, value) => { draft.frostedGlass = value; } } }); } // src/client/entry-policy.ts /** Select the reading view on entry, without fighting a later explicit tab choice. */ var ReaderEntryPolicy = class { requested; consumeRequest; entered = false; constructor(requested, consumeRequest = () => {}) { this.requested = requested; this.consumeRequest = consumeRequest; } select(view) { const requested = !this.entered && this.requested; if (!this.entered) { this.entered = true; if (this.requested) this.consumeRequest(); } return (requested || view == null) && view !== "reader" ? "reader" : null; } }; function readerEntryRequested(search) { const value = new URLSearchParams(search).get("reader"); return value === "1" || /^0\.1\.0-trial\.\d+$/.test(value ?? ""); } // src/client/entry.tsx function isConversationStore(store) { return typeof store === "object" && store !== null && store.spec.persist === "dsh.conversation" && typeof store.spec.actions.setView === "function"; } function ReaderEntry({ useStore, actions, policy }) { const view = useStore((state) => state.view); (0, react.useLayoutEffect)(() => { const next = policy.select(view); if (next) actions.setView(next); }, [ view, actions, policy ]); return null; } /** Reuse the native store handle; its framework-owned instance preserves drafts. */ function installReaderEntry(ctx) { const native = ctx.slots.entriesOfSlot("conversation.session")[0]?.store; if (!isConversationStore(native)) throw new Error("DSH Reader cannot bind the native conversation view store."); const policy = new ReaderEntryPolicy(readerEntryRequested(location.search), () => { const url = new URL(location.href); url.searchParams.delete("reader"); history.replaceState(history.state, "", `${url.pathname}${url.search}${url.hash}`); }); return ctx.slots.register({ name: "conversation.input.dock", id: "dsh-better-display-entry", store: native, inject: () => ({ policy }) }, ReaderEntry); } // src/client/settings-copy.ts const en = { nav: "Better Chat", openTitle: "Open deliverables in built-in panel", openDescription: "Off by default: chips and inline file mentions open in the system app. Turn this on to preview them in the right Sidebar, matching official chat. Reveal and folder actions still use the system file manager.", glassTitle: "Translucent frosted glass", glassDescription: "Off by default: reading chrome stays opaque, matching the current Host look. Turn this on to let wallpaper and skins show through the panel; path and count chips stay clear until hover or focus.", foldTitle: "Auto-fold process", foldDescription: "Default on: collapses earlier steps when new thoughts appear. Turn off to keep all thinking and tools expanded in full.", foldNone: "Off", foldStandard: "On", foldSummary: "Summary", shortcutTitle: "Approval card shortcuts", shortcutDescription: "Click a keycap and press the new combination. Allow-type actions use Enter, reject uses Esc; modifiers are free. Esc alone cancels while recording. Stored in the plugin config.", shortcutAllow: "Allow once", shortcutAlways: "Always allow", shortcutReject: "Reject", shortcutRecording: "Press keys…", shortcutDisabled: "Not set", shortcutDisable: "Clear", shortcutReset: "Restore defaults", shortcutErrorKey: "Allow actions must use Enter; reject must use Esc.", shortcutErrorModifier: "Always allow needs at least one modifier key.", shortcutErrorConflict: "That combination is already used by another action.", skillTitle: "generative-mcpapps skill", skillInstalled: "Installed", skillMissing: "Not detected", skillPurpose: "This install is for model auto-selection of MCP Apps. Reader already renders mcp-app fences when the model emits them.", skillPluginNote: "Shipping the pack inside this plugin repository does not install it into the harness skill catalog.", skillInstall: "Copy the whole generative-mcpapps folder (including references and examples) into .dsh/skills or .agents/skills — in your home or the project, you choose — then Re-check. There is no one-click install that works on every host.", skillRecheck: "Re-check", skillChecking: "Checking…", skillUnavailable: "Could not query the host skill catalog. Copy into .dsh/skills or .agents/skills (home or project), then Re-check." }; const zh = { nav: "Better Chat", openTitle: "在内置面板中打开产物", openDescription: "默认关闭:产物芯片和正文中的文件提及会用系统应用打开。打开后与官方对话一致,在右侧栏预览。访达 / 资源管理器中的显示与打开所在文件夹不受此开关控制。", glassTitle: "半透明毛玻璃", glassDescription: "默认关闭:阅读栏保持不透明,和现在的 Host 观感一致。打开后透出宿主壁纸与皮肤;路径、行数等标签静止时透明,悬停或聚焦才显出轮廓。", foldTitle: "自动折叠过程", foldDescription: "默认开启:新思考产生时自动折叠此前步骤。关闭后全程展开,完整保留原始思考与工具流。", foldNone: "关闭", foldStandard: "开启", foldSummary: "摘要", shortcutTitle: "审批卡快捷键", shortcutDescription: "点键帽后按下新的组合键。允许类只能用 Enter,拒绝只能用 Esc,修饰键随意;录制时单独按 Esc 取消。保存在插件配置里,重启后仍在。", shortcutAllow: "允许(单次)", shortcutAlways: "始终允许", shortcutReject: "拒绝", shortcutRecording: "按下组合键…", shortcutDisabled: "未设置", shortcutDisable: "清除", shortcutReset: "恢复默认", shortcutErrorKey: "允许类动作只能用 Enter,拒绝只能用 Esc。", shortcutErrorModifier: "「始终允许」至少需要一个修饰键(Ctrl/Shift/Alt)。", shortcutErrorConflict: "这个组合键已经被另一个动作占用。", skillTitle: "generative-mcpapps 技能", skillInstalled: "已安装", skillMissing: "未检测到", skillPurpose: "这项安装是为了让模型自动选用 MCP Apps。阅读页在模型写出 mcp-app 代码块时已经会渲染,不依赖该技能是否装进宿主。", skillPluginNote: "技能包只出现在本插件仓库里,并不等于当前 Agent 已经加载它。", skillInstall: "把完整的 generative-mcpapps 文件夹(含 references 与 examples)复制到 .dsh/skills 或 .agents/skills(家目录或项目目录,由你选),然后重新检测。没有在所有宿主上都可用的一键安装。", skillRecheck: "重新检测", skillChecking: "正在检测…", skillUnavailable: "无法查询宿主技能目录。请复制到 .dsh/skills 或 .agents/skills(家目录或项目),再重新检测。" }; function settingsLanguage(tag) { return (tag ?? "").toLowerCase().startsWith("zh") ? "zh" : "en"; } function settingsCopyFor(tag) { return settingsLanguage(tag) === "zh" ? zh : en; } // src/skill-status.ts /** Shared generative-mcpapps identity. Plugin-tree presence is not installation. */ const GENERATIVE_MCPAPPS_SKILL = "generative-mcpapps"; /** Conventional relative roots only. Never expand $HOME or dump host `root.path`. */ const CONVENTIONAL_SKILL_ROOTS = [".dsh/skills", ".agents/skills"]; /** Copy source relative to the plugin / checkout, not an absolute pack path. */ const SKILL_PACK_RELATIVE = `skills/${GENERATIVE_MCPAPPS_SKILL}`; function skillNameMatches(name) { return typeof name === "string" && name === "generative-mcpapps"; } function skillListIncludes(entries) { return Array.isArray(entries) && entries.some((entry) => skillNameMatches(entry?.name)); } function skillsFromListResult(result) { if (Array.isArray(result)) return result; if (result === null || typeof result !== "object") return []; const record = result; if (record.ok === false) return []; if (Array.isArray(record.skills)) return record.skills; if (record.value && typeof record.value === "object") { const value = record.value; if (Array.isArray(value.skills)) return value.skills; if (Array.isArray(record.value)) return record.value; } return []; } function publicSkillRoots() { return CONVENTIONAL_SKILL_ROOTS.map((path) => ({ source: "conventional", path })); } /** * Strip host home / pack absolutes before anything user-facing (HTTP or Settings). * Detection still uses the raw scan; this is the public face. */ function toPublicSkillStatus(status) { return { name: status.name, installed: status.installed, via: status.via, roots: publicSkillRoots() }; } // src/client/skill-status.ts async function detectGenerativeMcpappsSkill(probe) { let host; if (probe.fetchHostStatus) try { host = await probe.fetchHostStatus(); } catch { host = void 0; } let remoteHit = false; if (probe.listRemoteSkills) try { remoteHit = skillListIncludes(await probe.listRemoteSkills()); } catch { remoteHit = false; } const installed = Boolean(host?.installed || remoteHit); const via = remoteHit ? "skills.list" : host?.via ?? null; const publicHost = host === void 0 ? void 0 : toPublicSkillStatus(host); return { name: GENERATIVE_MCPAPPS_SKILL, installed, via, roots: publicHost?.roots ?? publicSkillRoots(), hostReached: host !== void 0 }; } /** mkdir/cp using conventional relative roots only. Host paths are ignored. */ function shortestInstallCommand(_status) { const dest = CONVENTIONAL_SKILL_ROOTS[0]; return `mkdir -p ${dest} && cp -R ${SKILL_PACK_RELATIVE} ${dest}/`; } function firstSessionId(list) { if (list?.ids && list.ids.length > 0) return list.ids[0]; return (list?.byId ? Object.keys(list.byId) : [])[0]; } // \0dshx-css-module:src/client/SettingsSection.module.css.mjs const css = ".TSdzRq_section{flex-direction:column;gap:28px;width:100%;max-width:720px;display:flex}.TSdzRq_row{border-bottom:.5px solid var(--dsw-alias-border-l2);align-items:center;gap:8px;padding:16px 0;display:flex}.TSdzRq_rowText{flex-direction:column;flex:1;gap:4px;min-width:0;padding-right:24px;display:flex}.TSdzRq_title{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:400;line-height:22px}.TSdzRq_desc{color:var(--dsw-alias-label-tertiary);font-size:12px;font-weight:400;line-height:18px}.TSdzRq_switch{background:var(--dsw-alias-bg-module-platform);cursor:pointer;border:none;border-radius:12px;flex:none;width:40px;height:24px;padding:0;position:relative}.TSdzRq_switch:after{content:\"\";background:var(--dsw-alias-label-primary);border-radius:50%;width:18px;height:18px;transition:transform .16s;position:absolute;top:3px;left:3px}.TSdzRq_switch[data-on]:after{transform:translate(16px)}.TSdzRq_switch[data-on]{background:var(--dsw-alias-state-business-primary)}.TSdzRq_block{flex-direction:column;gap:10px;display:flex}.TSdzRq_status{color:var(--dsw-alias-label-secondary);align-items:center;gap:8px;font-size:13px;line-height:20px;display:inline-flex}.TSdzRq_badge{background:var(--dsw-alias-bg-module-platform);height:22px;color:var(--dsw-alias-label-secondary);border-radius:11px;align-items:center;padding:0 8px;font-size:12px;display:inline-flex}.TSdzRq_badge[data-ok]{color:#059669;background:#10b98124}.TSdzRq_pre{background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;white-space:pre-wrap;border-radius:8px;margin:0;padding:10px 12px;font-size:12px;line-height:18px}.TSdzRq_roots{color:var(--dsw-alias-label-tertiary);margin:0;padding-left:18px;font-size:12px;line-height:18px}.TSdzRq_actions{gap:8px;display:flex}.TSdzRq_button{border:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-module-platform);height:32px;color:var(--dsw-alias-label-primary);font:inherit;cursor:pointer;border-radius:8px;padding:0 12px;font-size:13px}.TSdzRq_button:hover{background:var(--dsw-alias-interactive-bg-hover)}.TSdzRq_button:disabled{opacity:.6;cursor:default}.TSdzRq_segment{background:var(--dsw-alias-bg-module-platform);border-radius:10px;gap:2px;width:100%;margin-top:8px;padding:2px;display:flex}.TSdzRq_segmentStop{min-width:0;height:32px;color:var(--dsw-alias-label-secondary);font:inherit;cursor:pointer;background:0 0;border:0;border-radius:8px;flex:1 1 0;padding:0 8px;font-size:12px;line-height:18px}.TSdzRq_segmentStop[data-on]{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);box-shadow:0 0 0 .5px var(--dsw-alias-border-l2)}.TSdzRq_slider{width:100%;accent-color:var(--dsw-alias-state-business-primary);margin:10px 0 0}.TSdzRq_keyActions{flex:none;align-items:center;gap:8px;display:flex}.TSdzRq_keyButton{border:.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);min-width:96px;height:32px;color:var(--dsw-alias-label-primary);font-family:var(--ds-font-family-code,ui-monospace, SFMono-Regular, Consolas, monospace);cursor:pointer;border-radius:8px;padding:0 12px;font-size:12px;line-height:20px}.TSdzRq_keyButton:hover{border-color:var(--dsw-alias-border-l3)}.TSdzRq_keyButton[data-recording]{border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary);background:var(--dsw-alias-bg-module-platform)}.TSdzRq_error{color:var(--dsw-alias-state-error-primary,#d1483c);margin:0;font-size:12px;line-height:18px}"; const tagId = "dsh-better-chat/SettingsSection.module.css"; if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) { const tag = document.createElement("style"); tag.dataset.plugin = "dsh-better-chat"; tag.dataset.pluginCss = tagId; tag.textContent = css; document.head.appendChild(tag); } var SettingsSection_module_css_default = { "actions": "TSdzRq_actions", "badge": "TSdzRq_badge", "block": "TSdzRq_block", "button": "TSdzRq_button", "desc": "TSdzRq_desc", "error": "TSdzRq_error", "keyActions": "TSdzRq_keyActions", "keyButton": "TSdzRq_keyButton", "pre": "TSdzRq_pre", "roots": "TSdzRq_roots", "row": "TSdzRq_row", "rowText": "TSdzRq_rowText", "section": "TSdzRq_section", "segment": "TSdzRq_segment", "segmentStop": "TSdzRq_segmentStop", "slider": "TSdzRq_slider", "status": "TSdzRq_status", "switch": "TSdzRq_switch", "title": "TSdzRq_title" }; // src/client/SettingsSection.tsx function text(props, copy, key) { if (typeof props.t === "function") try { const value = props.t(key); if (typeof value === "string" && value.length > 0 && value !== key) return value; } catch {} return copy[key]; } function SettingsSection(props) { const copy = props.copy ?? settingsCopyFor(props.languageTag); const snap = (0, react.useSyncExternalStore)(props.prefs.subscribe, () => props.prefs.getSnapshot() ?? {}, () => ({})); const mode = deliverableOpenModeOf(snap.deliverableOpenMode); const glass = frostedGlassOf(snap); const autoFold = snap.autoFold !== false && snap.foldIntensity !== 0; const setMode = (value) => { props.prefs.actions.setDeliverableOpenMode(value); }; const on = mode === "sidebar"; const [skill, setSkill] = (0, react.useState)(); const [checking, setChecking] = (0, react.useState)(false); const recheck = (0, react.useCallback)(async () => { setChecking(true); try { setSkill(await detectGenerativeMcpappsSkill(props.checkSkill)); } catch { setSkill({ name: "generative-mcpapps", installed: false, via: null, roots: [], hostReached: false }); } finally { setChecking(false); } }, [props.checkSkill]); (0, react.useEffect)(() => { recheck(); }, [recheck]); const chat = props.chat; const chatSnap = (0, react.useSyncExternalStore)(chat?.subscribe ?? (() => () => {}), () => chat?.getSnapshot() ?? { bindings: void 0 }, () => ({ bindings: void 0 })); const bindings = normalizeBindings(chatSnap); const mac = typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/.test(navigator.platform); const [recording, setRecording] = (0, react.useState)(null); const [keyError, setKeyError] = (0, react.useState)(); const announceBindings = (0, react.useCallback)(() => { if (typeof window === "undefined") return; window.dispatchEvent(new CustomEvent(BINDINGS_CHANGED_EVENT)); }, []); (0, react.useEffect)(() => { if (!recording || !chat) return; const onKey = (event) => { event.preventDefault(); event.stopPropagation(); if (event.key === "Escape" && recording !== "reject" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) { setRecording(null); setKeyError(void 0); return; } const key = event.key === "Enter" ? "Enter" : event.key === "Escape" ? "Escape" : void 0; if (!key) { setKeyError(copy.shortcutErrorKey); return; } const binding = { key, primary: event.ctrlKey || event.metaKey, shift: event.shiftKey, alt: event.altKey }; const verdict = validateBinding(recording, binding, bindings); if (verdict === "key") { setKeyError(copy.shortcutErrorKey); return; } if (verdict === "modifier") { setKeyError(copy.shortcutErrorModifier); return; } if (verdict === "conflict") { setKeyError(copy.shortcutErrorConflict); return; } chat.actions.setApprovalBinding(recording, binding); announceBindings(); setRecording(null); setKeyError(void 0); }; window.addEventListener("keydown", onKey, true); return () => window.removeEventListener("keydown", onKey, true); }, [ recording, chat, chatSnap, copy, bindings, announceBindings ]); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: SettingsSection_module_css_default.section, "data-better-display-settings": true, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: SettingsSection_module_css_default.row, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: SettingsSection_module_css_default.rowText, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.title, children: text(props, copy, "openTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.desc, children: text(props, copy, "openDescription") })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", role: "switch", "aria-checked": on, className: SettingsSection_module_css_default.switch, "data-on": on || void 0, "data-better-display-open-mode": mode, onClick: () => { setMode(on ? "external" : "sidebar"); } })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: SettingsSection_module_css_default.row, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: SettingsSection_module_css_default.rowText, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.title, children: text(props, copy, "glassTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.desc, children: text(props, copy, "glassDescription") })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", role: "switch", "aria-checked": glass, className: SettingsSection_module_css_default.switch, "data-on": glass || void 0, "data-better-display-glass": glass ? "on" : "off", onClick: () => { props.prefs.actions.setFrostedGlass(!glass); } })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: SettingsSection_module_css_default.row, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: SettingsSection_module_css_default.rowText, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.title, children: text(props, copy, "foldTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.desc, children: text(props, copy, "foldDescription") })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", role: "switch", "aria-checked": autoFold, className: SettingsSection_module_css_default.switch, "data-on": autoFold || void 0, "data-better-display-auto-fold": autoFold ? "on" : "off", onClick: () => { props.prefs.actions.setAutoFold?.(!autoFold); props.prefs.actions.setFoldIntensity?.(!autoFold ? 1 : 0); } })] }), chat ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", { className: SettingsSection_module_css_default.block, "data-better-chat-shortcuts": true, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.title, children: text(props, copy, "shortcutTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: SettingsSection_module_css_default.desc, children: text(props, copy, "shortcutDescription") }), [ [ "allow", "shortcutAllow", bindings.allow ], [ "always", "shortcutAlways", bindings.always ], [ "reject", "shortcutReject", bindings.reject ] ].map(([action, title, binding]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: SettingsSection_module_css_default.row, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.rowText, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.title, children: text(props, copy, title) }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: SettingsSection_module_css_default.keyActions, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: SettingsSection_module_css_default.keyButton, "data-recording": recording === action || void 0, onClick: () => { setKeyError(void 0); setRecording(action); }, children: recording === action ? text(props, copy, "shortcutRecording") : binding ? bindingKeycap(binding, mac) : text(props, copy, "shortcutDisabled") }), action === "always" && binding ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: SettingsSection_module_css_default.button, onClick: () => { chat.actions.setApprovalBinding("always", null); announceBindings(); setKeyError(void 0); }, children: text(props, copy, "shortcutDisable") }) : null] })] }, action)), keyError ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: SettingsSection_module_css_default.error, "data-better-chat-key-error": true, children: keyError }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.actions, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: SettingsSection_module_css_default.button, onClick: () => { chat.actions.resetApprovalBindings(); announceBindings(); setRecording(null); setKeyError(void 0); }, children: text(props, copy, "shortcutReset") }) }) ] }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", { className: SettingsSection_module_css_default.block, "data-better-display-skill": skill?.installed ? "installed" : "missing", children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.title, children: text(props, copy, "skillTitle") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.status, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: SettingsSection_module_css_default.badge, "data-ok": skill?.installed || void 0, children: skill?.installed ? text(props, copy, "skillInstalled") : text(props, copy, "skillMissing") }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: SettingsSection_module_css_default.desc, children: text(props, copy, "skillPurpose") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: SettingsSection_module_css_default.desc, children: text(props, copy, "skillPluginNote") }), skill && !skill.installed ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: SettingsSection_module_css_default.desc, children: skill.hostReached ? text(props, copy, "skillInstall") : text(props, copy, "skillUnavailable") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { className: SettingsSection_module_css_default.pre, children: shortestInstallCommand() }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", { className: SettingsSection_module_css_default.roots, "data-better-display-skill-roots": true, children: CONVENTIONAL_SKILL_ROOTS.map((root) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("li", { children: root }, root)) }) ] }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: SettingsSection_module_css_default.actions, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: SettingsSection_module_css_default.button, disabled: checking, onClick: () => { recheck(); }, children: checking ? text(props, copy, "skillChecking") : text(props, copy, "skillRecheck") }) }) ] }) ] }); } // src/client/settings.tsx function languageTag(ctx) { const snap = (ctx.get?.("locale") ?? ctx.locale)?.getSnapshot?.(); return snap?.locale ?? snap?.language ?? (typeof document !== "undefined" ? document.documentElement.lang : void 0) ?? (typeof navigator !== "undefined" ? navigator.language : void 0); } function createSkillProbe(ctx) { return { fetchHostStatus: async () => { const snap = ctx.sessions?.list?.getSnapshot?.(); const id = firstSessionId(snap); const cwd = id && snap?.byId ? snap.byId[id]?.cwd : void 0; const url = cwd ? `/better-display/skill-status?cwd=${encodeURIComponent(cwd)}` : "/better-display/skill-status"; const res = await fetch(url); if (!res.ok) return void 0; return await res.json(); }, listRemoteSkills: async () => { const skills = ctx.remote?.skills ?? ctx.get?.("remote.skills") ?? (ctx.get?.("remote"))?.skills; const sessions = ctx.sessions; const sessionId = firstSessionId(sessions?.list?.getSnapshot?.()); if (!skills?.list || !sessionId) return void 0; return skillsFromListResult(await skills.list({ sessionId })); } }; } function installBetterDisplaySettings(ctx, prefs, chat) { const locale = ctx.get?.("locale") ?? ctx.locale; if (locale?.register) ctx.effect(() => locale.register("better-display", { zh, en }), "dsh-better-display: settings copy"); const checkSkill = createSkillProbe(ctx); const injected = () => ({ prefs, chat, copy: settingsCopyFor(languageTag(ctx)), languageTag: languageTag(ctx), checkSkill }); ctx.slots.inject("settings.section", () => ctx.slots.register({ name: "settings.section", id: "better-display", order: 40, label: () => locale?.bind?.("better-display")?.("nav") || settingsCopyFor(languageTag(ctx)).nav, locale: locale?.bind ? "better-display" : void 0, inject: injected }, SettingsSection)); } // src/client/reader-plugin.tsx const officialFileAddressFor = fileAddressFor$1; async function openWorkspacePath(ctx, path) { const remoteSession = ctx.remote?.session ?? ctx.get?.("remote.session") ?? (ctx.get?.("remote"))?.session; if (remoteSession?.openWorkspacePath) { const result = await remoteSession.openWorkspacePath({ path }); if (!result?.ok) console.warn("[dsh-better-display] openWorkspacePath failed:", result?.error?.message); } else console.warn("[dsh-better-display] remote.session is not available"); } ensureStyles(); function apply$1(ctx, options = {}) { const textTransform = createTextTransformRegistry(); const restoreTextTransform = installTextTransformRegistry(textTransform); ctx.provide(TEXT_TRANSFORM_SERVICE, textTransform); ctx.effect(() => restoreTextTransform); const store = createReaderStore(); const prefs = store.create(); installBetterDisplaySettings(ctx, prefs, options.chatPrefs); ctx.slots.inject("conversation.chat.node", function* () { yield ctx.slots.register({ name: "conversation.view", id: "reader", order: -5, label: () => "阅读", locale: "chat", children: { "dsh-better-display.block": { kind: "chain", scope: "session" }, ...officialChildren(ctx.slots) }, store, inject: (sessionId) => { const session = () => { const current = ctx.sessions.binding(sessionId)?.session; if (!current) throw new Error("阅读页对应的会话已关闭。"); return current; }; return { openPrefs: prefs, officialImageLoader: Object.assign((attachment) => ctx.uiConversation.imageUrl(sessionId, attachment), { peek: (attachment) => ctx.uiConversation.peekImageUrl(sessionId, attachment) }), officialFileMentions: (owner) => ctx.get("chatFileMentions")?.forClosing(owner, sessionId), officialPreviewFile: (path) => { const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd; const sidebar = ctx.get("sidebarRight"); if (!sidebar?.openResource) throw new Error("文件预览面板不可用。"); sidebar.openResource((officialFileAddressFor ?? fileAddressFor)(sessionId, cwd, path)); }, officialHost: { getSnapshot: () => ctx.remote.$host, subscribe: (listener) => ctx.on("connection/reset", listener) }, loadOlder: async () => { await session().loadOlder(); }, loadImage: async (attachment) => { const receipt = await session().readAttachment(attachment.attachmentId); if (!receipt.ok) throw new Error(receipt.error.message); return { data: Uint8Array.from(receipt.value.data), mediaType: receipt.value.attachment.mediaType }; }, openFile: async (path, options) => { try { const cwd = ctx.sessions?.list?.getSnapshot?.()?.byId[sessionId]?.cwd; const sidebar = ctx.get?.("sidebarRight") ?? ctx.sidebarRight; await openDeliverableFile({ path, mode: modeFromSnapshot(prefs), sessionId, cwd, resolveWorkspacePath, openExternal: async (absolutePath) => { await openWorkspacePath(ctx, absolutePath); }, openSidebar: typeof sidebar?.openResource === "function" ? (address) => { sidebar.openResource(address, options?.line === void 0 ? void 0 : { params: { line: options.line } }); } : void 0, fileAddressFor: officialFileAddressFor ?? fileAddressFor, warn: (message, extra) => { console.warn(message, extra); } }); } catch (error) { console.warn("[dsh-better-display] openFile error:", error); } }, revealFile: async (path) => { try { const cwd = ctx.sessions?.list?.getSnapshot?.()?.byId[sessionId]?.cwd; const targetPath = resolveWorkspacePath(cwd, path); try { const res = await fetch("/better-display/reveal", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path: targetPath, sessionId }) }); if (res.ok) { if ((await res.json()).ok) return; } } catch {} const parentDir = dirname(targetPath); if (!isAbsoluteWorkspacePath(parentDir)) { console.warn("[dsh-better-display] reveal failed; refusing to open a relative parent:", targetPath); return; } const remoteSession = ctx.remote?.session ?? ctx.get?.("remote.session"); if (remoteSession?.openWorkspacePath) await remoteSession.openWorkspacePath({ path: parentDir }); } catch (error) { console.warn("[dsh-better-display] revealFile error:", error); } }, forkAt: (seq) => { if (typeof seq !== "number" || !Number.isFinite(seq)) { console.warn("[dsh-better-display] fork refused: missing anchor seq"); return; } try { const sessionsApi = ctx.sessions; if (sessionsApi?.fork) sessionsApi.fork({ sessionId, atSeq: seq, increaseTitle: true }).then((childId) => { sessionsApi.open?.(childId); }).catch((err) => { console.warn("[dsh-better-display] fork failed:", err); }); } catch (error) { console.warn("[dsh-better-display] forkAt error:", error); } }, loadThrough: async (seq) => { try { const current = session(); if (typeof current?.loadThrough === "function") await current.loadThrough(seq); else await session().loadOlder(); } catch (error) { console.warn("[dsh-better-display] loadThrough error:", error); } }, fillComposer: (text) => { try { const shell = ctx.conversation?.input?.shell?.(sessionId); if (shell && typeof shell.setDraft === "function") { shell.setDraft(text); return true; } } catch {} try { return fillComposerDom(text); } catch { return false; } } }; } }, Reader); yield installOfficialSlots(ctx); yield installReaderEntry(ctx); }); } // src/client/index.tsx const name = "dsh-better-chat"; /** 阅读视图所需的宿主客户端服务;聊天增强不额外依赖服务。 */ const inject = [ "slots", "sessions", "conversation", "uiConversation", "remote", "remote.session" ]; function apply(ctx) { const chatPrefs = createChatStore().create(); const getBindings = () => currentBindings(chatPrefs); ctx.effect(() => install(document, getBindings), "dsh-better-chat: approval key routing"); ctx.effect(() => installKeyHints(document, { getBindings }), "dsh-better-chat: approval key hints"); ctx.effect(() => installPermissionPolicy(document), "dsh-better-chat: permission policy (no full access)"); try { ctx.plugin(storeUpdatePlugin); } catch {} apply$1(ctx, { chatPrefs }); } exports.apply = apply; exports.inject = inject; exports.name = name; return module.exports; } }); //# sourceMappingURL=client.js.map