openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2,728 lines • 97.7 kB
JavaScript
import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { a as tableExists, o as tableHasColumn } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs";
import { a as runSqliteImmediateTransactionSync } from "./sqlite-transaction-BHHu6P5-.mjs";
import "./sqlite-worker-runtime-CKocuU_N.mjs";
import { closeSync, constants, lstatSync, openSync, realpathSync, statSync } from "node:fs";
import path from "node:path";
import { syncDirectorySync } from "@openclaw/fs-safe/durability";
import { Check } from "typebox/value";
import { Type } from "typebox";
//#region extensions/knowledge/src/model.ts
const text = (e = 200) => Type.String({ maxLength: e });
const name = Type.String({ pattern: "^[a-z][a-z0-9_-]{0,63}$" });
const id = Type.String({ pattern: "^[a-zA-Z0-9][a-zA-Z0-9_-]{7,95}$" });
const timestamp = Type.String({ pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$" });
const strings = Type.Array(text(), { maxItems: 100 });
const Recall = Type.Object({
summary: Type.String({
minLength: 1,
maxLength: 500,
pattern: "^(?=.*\\S)[\\s\\S]+$"
}),
triggers: Type.Optional(Type.Array(Type.String({
minLength: 1,
maxLength: 100,
pattern: "^(?=.*\\S)[^\\r\\n;|]+$"
}), { maxItems: 20 })),
importance: Type.Optional(Type.Integer({
minimum: 1,
maximum: 10
})),
projects: Type.Optional(Type.Array(Type.String({
minLength: 1,
maxLength: 500,
pattern: "^(?=.*\\S)[^\\r\\n<>]+$"
}), { maxItems: 20 })),
approved_by: Type.Literal("owner-private"),
approved_at: timestamp
}, { additionalProperties: false });
/** Returns only complete service-issued recall approvals. Invalid authored blocks fail closed. */
function approvedRecall(e) {
if (!Check(Recall, e)) return;
const t = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/.exec(e.approved_at);
const n = new Date(e.approved_at);
if (!t || !Number.isFinite(n.getTime())) return;
return [
n.getUTCFullYear(),
n.getUTCMonth() + 1,
n.getUTCDate(),
n.getUTCHours(),
n.getUTCMinutes(),
n.getUTCSeconds()
].every((e, n) => e === Number(t[n + 1])) ? e : void 0;
}
const Evidence = Type.Object({
source: Type.Optional(Type.String({ pattern: "^[a-f0-9]{64}$" })),
path: text(500),
sha256: Type.String({ pattern: "^[a-f0-9]{64}$" }),
start_line: Type.Optional(Type.Integer({ minimum: 1 })),
end_line: Type.Optional(Type.Integer({ minimum: 1 })),
filename: Type.Optional(text(200)),
mediaType: Type.Optional(text(200)),
size: Type.Optional(Type.Integer({ minimum: 0 })),
attribution: Type.Optional(text(1e3)),
quote: Type.Optional(text(4e3))
}, { additionalProperties: false });
const supportedBasis = {
basis: Type.String({
minLength: 1,
maxLength: 1e3
}),
evidence: Type.Array(Evidence, {
minItems: 1,
maxItems: 20
})
};
const RecordAnnotations = Type.Object({
record_class: Type.Optional(Type.Union([Type.Literal("production"), Type.Literal("fixture")])),
source_page: Type.Optional(id),
source_event: Type.Optional(Type.Boolean()),
identity: Type.Optional(Type.Object({
status: Type.Union([Type.Literal("partial"), Type.Literal("resolved")]),
context: text(1e3),
candidates: Type.Optional(Type.Array(Type.Object({
id,
...supportedBasis
}, { additionalProperties: false }), { maxItems: 10 }))
}, { additionalProperties: false })),
attribution_confidence: Type.Optional(Type.Object({
level: Type.Union([
Type.Literal("high"),
Type.Literal("medium"),
Type.Literal("low")
]),
...supportedBasis
}, { additionalProperties: false })),
continuity: Type.Optional(Type.Array(Type.Object({
id,
relation: Type.Union([
Type.Literal("reaffirms"),
Type.Literal("updates"),
Type.Literal("contradicts")
]),
...supportedBasis
}, { additionalProperties: false }), { maxItems: 50 }))
}, { additionalProperties: false });
const Scope = Type.Union([
Type.Object({ visibility: Type.Literal("sample") }, { additionalProperties: false }),
Type.Object({ visibility: Type.Literal("private") }, { additionalProperties: false }),
Type.Object({
visibility: Type.Literal("conversation"),
sessionId: Type.String({ pattern: "^[a-f0-9-]{36}$" })
}, { additionalProperties: false })
]);
/** What one identity merge added to its surviving page, so an unmerge can remove exactly that. */
const MergedFrom = Type.Object({
id,
request_id: Type.String({ pattern: "^[a-f0-9-]{36}$" }),
at: timestamp,
added: Type.Object({
aliases: strings,
tags: strings,
fields: strings,
evidence: Type.Array(Type.Object({
path: text(500),
sha256: Type.String({ pattern: "^[a-f0-9]{64}$" }),
start_line: Type.Optional(Type.Integer({ minimum: 1 })),
end_line: Type.Optional(Type.Integer({ minimum: 1 }))
}, { additionalProperties: false }), { maxItems: 1e3 })
}, { additionalProperties: false })
}, { additionalProperties: false });
const Envelope = Type.Object({
...RecordAnnotations.properties,
format: Type.Literal("knowledge-record-v1"),
id,
revision: Type.Integer({ minimum: 1 }),
kind: Type.Union([
Type.Literal("page"),
Type.Literal("claim"),
Type.Literal("relationship")
]),
title: Type.String({
minLength: 1,
maxLength: 200
}),
scope: Scope,
recorded_at: timestamp,
updated_at: timestamp,
lifecycle: Type.Union([
Type.Literal("active"),
Type.Literal("superseded"),
Type.Literal("withdrawn"),
Type.Literal("merged")
]),
supersedes: Type.Optional(id),
superseded_by: Type.Optional(id),
merged_into: Type.Optional(id),
merged_from: Type.Optional(Type.Array(MergedFrom, { maxItems: 100 })),
lifecycle_change: Type.Optional(Type.Object({
reason: Type.String({
minLength: 1,
maxLength: 2e3
}),
at: timestamp,
actor: text(100),
request_id: Type.String({ pattern: "^[a-f0-9-]{36}$" })
}, { additionalProperties: false })),
aliases: Type.Optional(strings),
tags: Type.Optional(strings),
type: Type.Optional(name),
fields: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
claim_kind: Type.Optional(Type.Union([
Type.Literal("fact"),
Type.Literal("preference"),
Type.Literal("decision"),
Type.Literal("commitment"),
Type.Literal("event"),
Type.Literal("belief")
])),
assertion_origin: Type.Optional(Type.Union([
Type.Literal("source"),
Type.Literal("user_belief"),
Type.Literal("agent_inference")
])),
occurred_at: Type.Optional(Type.String({ pattern: "^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?(?:Z|[+-]\\d{2}:\\d{2}))?$" })),
valid_from: Type.Optional(timestamp),
valid_until: Type.Optional(timestamp),
expires_at: Type.Optional(timestamp),
owner: Type.Optional(id),
due_at: Type.Optional(Type.String({ maxLength: 40 })),
attribution: Type.Optional(text(1e3)),
entities: Type.Optional(Type.Array(id, { maxItems: 100 })),
/** Saver's free-text description of a claim's subject; maintenance uses it to link the claim. */
subject_hint: Type.Optional(text(200)),
recall: Type.Optional(Type.Unknown()),
from: Type.Optional(id),
to: Type.Optional(id),
label: Type.Optional(name),
evidence: Type.Optional(Type.Array(Evidence)),
dependencies: Type.Optional(Type.Array(id, { maxItems: 100 }))
}, { additionalProperties: true });
const Field = Type.Object({
name,
label: text(),
type: Type.Union([
Type.Literal("string"),
Type.Literal("number"),
Type.Literal("boolean"),
Type.Literal("string[]")
]),
required: Type.Optional(Type.Boolean()),
values: Type.Optional(strings)
}, { additionalProperties: false });
const Definition = Type.Object({
name,
label: text(),
description: text(2e3),
kind: Type.Union([Type.Literal("page"), Type.Literal("relationship")]),
directory: Type.String({
maxLength: 100,
pattern: "^(?:[a-z][a-z0-9_-]*/)+$"
}),
fields: Type.Array(Field, { maxItems: 50 }),
primitive: Type.Optional(Type.Union([
Type.Literal("entity"),
Type.Literal("media"),
Type.Literal("temporal"),
Type.Literal("annotation"),
Type.Literal("concept")
])),
aliases: Type.Optional(Type.Array(Type.String({
minLength: 1,
maxLength: 64
}), { maxItems: 100 })),
path_prefixes: Type.Optional(Type.Array(Type.String({
maxLength: 100,
pattern: "^(?:[a-z][a-z0-9_-]*/)+$"
}), { maxItems: 100 })),
behaviors: Type.Optional(Type.Object({
extractable: Type.Boolean(),
expert_routing: Type.Boolean()
}, { additionalProperties: false })),
from_types: Type.Optional(strings),
to_types: Type.Optional(strings)
}, { additionalProperties: false });
//#endregion
//#region extensions/knowledge/src/limits.ts
/** Durable UTF-8 record bytes, including frontmatter; not a transport allowance. */
const RECORD_MAX_BYTES = 5e6;
/** Ontology, manifests and inline source files keep their independent bound. */
const AUXILIARY_MAX_BYTES = 65536;
/** A single authored body/replacement is bounded; edits can grow larger records. */
const BODY_INPUT_MAX_CHARS = 48e3;
/** Maximum requested text window; complete JSON budgets may reduce it further. */
const TEXT_PAGE_MAX_CHARS = 65536;
const TEXT_PAGE_DEFAULT_CHARS = 12e3;
/** Whole record-inspection response budget, including metadata and navigation. */
const RECORD_RESPONSE_MAX_BYTES = 24576;
/** Bound SQLite full-document highlight work independently of matching/ranking. */
const SEARCH_HIGHLIGHT_MAX_BYTES = 65536;
//#endregion
//#region node_modules/.pnpm/marked@18.1.1/node_modules/marked/lib/marked.esm.js
/**
* marked v18.1.1 - a markdown parser
* Copyright (c) 2018-2026, MarkedJS. (MIT License)
* Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License)
* https://github.com/markedjs/marked
*/
/**
* DO NOT EDIT THIS FILE
* The code in this file is generated from files in ./src/
*/
function B() {
return {
async: !1,
breaks: !1,
extensions: null,
gfm: !0,
hooks: null,
pedantic: !1,
renderer: null,
silent: !1,
tokenizer: null,
walkTokens: null
};
}
var y = B();
function V(e) {
y = e;
}
var M = { exec: () => null };
function D(e) {
let t = [];
return (n) => {
let r = Math.max(0, Math.min(3, n - 1)), o = t[r];
return o || (o = e(r), t[r] = o), o;
};
}
function h(e, t = "") {
let n = typeof e == "string" ? e : e.source, r = {
replace: (e, t) => {
let o = typeof t == "string" ? t : t.source;
return o = o.replace(x.caret, "$1"), n = n.replace(e, o), r;
},
getRegex: () => new RegExp(n, t)
};
return r;
}
var ze = ((e = "") => {
try {
return !!new RegExp("(?<=1)(?<!1)" + e);
} catch {
return !1;
}
})();
var x = {
codeRemoveIndent: /^(?: {0,3}\t| {1,4})/gm,
outputLinkReplace: /\\([\[\]])/g,
indentCodeCompensation: /^(\s+)(?:```)/,
beginningSpace: /^\s+/,
endingHash: /#$/,
startingSpaceChar: /^ /,
endingSpaceChar: / $/,
endingSpaceTabChar: /[ \t]$/,
nonSpaceChar: /[^ ]/,
newLineCharGlobal: /\n/g,
tabCharGlobal: /\t/g,
leadingSpaceTab: /^[ \t]+/,
multipleSpaceGlobal: /\s+/g,
blankLine: /^[ \t]*$/,
doubleBlankLine: /\n[ \t]*\n[ \t]*$/,
blockquoteStart: /^ {0,3}>/,
blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g,
blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm,
listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,
listIsTask: /^\[[ xX]\] +\S/,
listReplaceTask: /^\[[ xX]\] +/,
listTaskCheckbox: /\[[ xX]\]/,
anyLine: /\n.*\n/,
hrefBrackets: /^<(.*)>$/,
tableDelimiter: /[:|]/,
tableAlignChars: /^\||\| *$/g,
tableRowBlankLine: /\n[ \t]*$/,
tableAlignRight: /^ *-+: *$/,
tableAlignCenter: /^ *:-+: *$/,
tableAlignLeft: /^ *:-+ *$/,
startATag: /^<a /i,
endATag: /^<\/a>/i,
startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i,
endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i,
startAngleBracket: /^</,
endAngleBracket: />$/,
pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/,
unicodeAlphaNumeric: /[\p{L}\p{N}]/u,
numericCharacterReference: /&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,
numericCharacterReferenceOrAmpersand: /&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
escapeTest: /[&<>"']/,
escapeReplace: /[&<>"']/g,
escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,
escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
caret: /(^|[^\[])\^/g,
percentDecode: /%25/g,
findPipe: /\|/g,
splitPipe: / \|/,
slashPipe: /\\\|/g,
carriageReturn: /\r\n|\r/g,
spaceLine: /^ +$/gm,
notSpaceStart: /^\S*/,
endingNewline: /\n$/,
listItemRegex: (e) => new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),
nextBulletRegex: D((e) => new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),
hrRegex: D((e) => new RegExp(`^ {0,${e}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),
fencesBeginRegex: D((e) => new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),
headingBeginRegex: D((e) => new RegExp(`^ {0,${e}}#`)),
htmlBeginRegex: D((e) => new RegExp(`^ {0,${e}}(?:</?(?:${Q})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`, "i")),
blockquoteBeginRegex: D((e) => new RegExp(`^ {0,${e}}>`))
};
var Ee = /^(?:[ \t]*(?:\n|$))+/;
var Me = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
var Ce = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
var N = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
var Ie = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
var Y = / {0,3}(?:[*+-]|\d{1,9}[.)])/;
var fe = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;
var me = h(fe).replace(/bull/g, Y).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}(?:\s|$)/).replace(/hr/g, / {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex();
var Be = h(fe).replace(/bull/g, Y).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}(?:\s|$)/).replace(/hr/g, / {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex();
var ee = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/;
var De = /^[^\n]+/;
var te = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/;
var qe = h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", te).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
var Ze = h(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g, Y).getRegex();
var Q = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
var ne = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
var ve = h("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))", "i").replace("comment", ne).replace("tag", Q).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
var xe = (e) => h(ee).replace("hr", N).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list", e).replace("html", " {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag", Q).getRegex();
var He = xe(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/);
var Ge = xe(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/);
var re = {
blockquote: h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", Ge).getRegex(),
code: Me,
def: qe,
fences: Ce,
heading: Ie,
hr: N,
html: ve,
lheading: me,
list: Ze,
newline: Ee,
paragraph: He,
table: M,
text: De
};
var de = h("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", N).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3} )[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", " {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag", Q).getRegex();
var Qe = {
...re,
lheading: Be,
table: de,
paragraph: h(ee).replace("hr", N).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", de).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html", " {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag", Q).getRegex()
};
var je = {
...re,
html: h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", ne).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
heading: /^(#{1,6})(.*)(?:\n+|$)/,
fences: M,
lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
paragraph: h(ee).replace("hr", N).replace("heading", ` *#{1,6} *[^
]`).replace("lheading", me).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
};
var Fe = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
var Ue = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
var be = /^( {2,}|\\)\n(?!\s*$)[ \t]*/;
var Ke = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
var S = /[\p{P}\p{S}]/u;
var q = /[\s\p{P}\p{S}]/u;
var j = /[^\s\p{P}\p{S}]/u;
var Xe = h(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, q).getRegex();
var We = /[\p{Pi}\p{Ps}"']/u;
var Re = /(?!~)[\p{P}\p{S}]/u;
var Ve = /(?!~)[\s\p{P}\p{S}]/u;
var Je = /(?:[^\s\p{P}\p{S}]|~)/u;
var Ye = h(/link|precode-code|html/, "g").replace("link", /\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-", ze ? "(?<!`)()" : "(^^|[^`])").replace("code", /(?<b>`+)[^`]+\k<b>(?!`)/).replace("html", /<(?! )[^<>]*?>/).getRegex();
var Te = /^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/;
var et = h(Te, "u").replace(/punct/g, S).getRegex();
var tt = h(Te, "u").replace(/punct/g, Re).getRegex();
var rt = h(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/, "u").replace(/openQuote/g, We).replace(/punct/g, S).getRegex();
var Oe = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)";
var st = h(Oe, "gu").replace(/notPunctSpace/g, j).replace(/punctSpace/g, q).replace(/punct/g, S).getRegex();
var it = h(Oe, "gu").replace(/notPunctSpace/g, Je).replace(/punctSpace/g, Ve).replace(/punct/g, Re).getRegex();
var at = h("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)", "gu").replace(/notPunctSpace/g, j).replace(/punctSpace/g, q).replace(/punct/g, S).getRegex();
var lt = h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, j).replace(/punctSpace/g, q).replace(/punct/g, S).getRegex();
var pt = h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)", "gu").replace(/notPunctSpace/g, j).replace(/punctSpace/g, q).replace(/punct/g, S).getRegex();
var ct = h(/^~~?(?:((?!~)punct)|[^\s~])/, "u").replace(/punct/g, S).getRegex();
var dt = h("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)", "gu").replace(/notPunctSpace/g, j).replace(/punctSpace/g, q).replace(/punct/g, S).getRegex();
var kt = h(/\\(punct)/, "gu").replace(/punct/g, S).getRegex();
var gt = h(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/, "gu").replace(/punct/g, S).getRegex();
var ft = h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
var mt = h(ne).replace("(?:-->|$)", "-->").getRegex();
var xt = h("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", mt).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
var we = /\[(?:\\[\s\S]|[^\[\]\\])*\]/;
var K = h(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets", we).getRegex();
var bt = h(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label", K).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
var Rt = h(/^!?\[(label)\]\[(ref)\]/).replace("label", K).replace("ref", te).getRegex();
var Tt = h(/^!?\[(ref)\](?:\[\])?/).replace("ref", te).getRegex();
var ke = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/;
var Ot = h(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets", we).getRegex();
var wt = h("reflink|nolink(?!\\()", "g").replace("reflink", h(/^!?\[(label)\]\[(ref)\]/).replace("label", Ot).replace("ref", ke).getRegex()).replace("nolink", h(/^!?\[(ref)\](?:\[\])?/).replace("ref", ke).getRegex()).getRegex();
var ge = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;
var yt = h(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g, /[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex();
var se = {
_backpedal: M,
anyPunctuation: kt,
anyPunctuationOutsideCode: gt,
autolink: ft,
blockSkip: Ye,
br: be,
code: Ue,
del: M,
delLDelim: M,
delRDelim: M,
emStrongLDelim: et,
emStrongRDelimAst: st,
emStrongRDelimUnd: lt,
escape: Fe,
link: bt,
nolink: Tt,
punctuation: Xe,
reflink: Rt,
reflinkSearch: wt,
tag: xt,
text: Ke,
url: M
};
var St = {
...se,
emStrongLDelim: rt,
emStrongRDelimAst: at,
emStrongRDelimUnd: pt,
link: h(/^!?\[(label)\]\((.*?)\)/).replace("label", K).getRegex(),
reflink: h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", K).getRegex()
};
var J = {
...se,
emStrongRDelimAst: it,
emStrongLDelim: tt,
delLDelim: ct,
delRDelim: dt,
url: h(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol", yt).replace("protocol", ge).replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),
_backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,
text: h(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace("protocol", ge).replace(/emailProtocol/g, /(?:mailto|xmpp):/).getRegex()
};
var _t = {
...J,
br: h(be).replace("{2,}", "*").getRegex(),
text: h(J.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
};
var F = {
normal: re,
gfm: Qe,
pedantic: je
};
var Z = {
normal: se,
gfm: J,
breaks: _t,
pedantic: St
};
var $t = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
};
var Pe = (e) => $t[e];
function w(e, t) {
if (t) {
if (x.escapeTest.test(e)) return e.replace(x.escapeReplace, Pe);
} else if (x.escapeTestNoEncode.test(e)) return e.replace(x.escapeReplaceNoEncode, Pe);
return e;
}
function ye(e) {
return x.numericCharacterReference.test(e) ? e.replace(x.numericCharacterReferenceOrAmpersand, (e, t, n) => {
if (t === void 0 && n === void 0) return "&";
let r = t === void 0 ? Number.parseInt(n, 16) : Number.parseInt(t, 10);
return r === 0 || r > 1114111 || r >= 55296 && r <= 57343 ? "�" : r === 38 ? "&" : String.fromCodePoint(r);
}) : e;
}
function ie(e) {
try {
e = encodeURI(e).replace(x.percentDecode, "%");
} catch {
return null;
}
return e;
}
function oe(e, t) {
let n = e.replace(x.findPipe, (e, t, n) => {
let r = !1, o = t;
for (; --o >= 0 && n[o] === "\\";) r = !r;
return r ? "|" : " |";
}).split(x.splitPipe), r = 0;
if (n[0].trim() || n.shift(), n.length > 0 && !n.at(-1)?.trim() && n.pop(), t) if (n.length > t) n.splice(t);
else for (; n.length < t;) n.push("");
for (; r < n.length; r++) n[r] = n[r].trim().replace(x.slashPipe, "|");
return n;
}
function A(e, t, n) {
let r = e.length;
if (r === 0) return "";
let o = 0;
for (; o < r;) {
let s = e.charAt(r - o - 1);
if (s === t && !n) o++;
else if (s !== t && n) o++;
else break;
}
return e.slice(0, r - o);
}
function ae(e) {
let t = e.split(`
`), n = t.length - 1;
for (; n >= 0 && x.blankLine.test(t[n]);) n--;
return t.length - n <= 2 ? e : t.slice(0, n + 1).join(`
`);
}
function v(e) {
return e.trim().toLowerCase().toUpperCase().toLowerCase();
}
function le(e, t) {
if (e.indexOf(t[0]) === -1 && e.indexOf(t[1]) === -1) return -1;
let n = 0;
for (let r = 0; r < e.length; r++) if (e[r] === "\\") r++;
else if (e[r] === t[0]) n++;
else if (e[r] === t[1] && (n--, n < 0)) return r;
return n > 0 ? -2 : -1;
}
function X(e, t = 0) {
let n = t, r = "";
for (let t of e) if (t === " ") {
let e = 4 - n % 4;
r += " ".repeat(e), n += e;
} else r += t, n++;
return r;
}
function Se(e, t, n, r, o) {
let s = t.href, c = t.title || null, u = e[1].replace(o.other.outputLinkReplace, "$1"), d = e[0].charAt(0) === "!", p = r.state.inLink, m = r.state.linkEmitted, g = r.state.inRawBlock;
r.state.inLink = !0, r.state.linkEmitted = !1;
let b = r.inlineTokens(u), E = r.state.linkEmitted;
if (r.state.linkEmitted = m, r.state.inLink = p, !d) {
if (E) {
r.state.inRawBlock = g;
return;
}
r.state.linkEmitted = !0;
}
return {
type: d ? "image" : "link",
raw: n,
href: s,
title: c,
text: u,
tokens: b
};
}
function Lt(e, t, n) {
let r = e.match(n.other.indentCodeCompensation);
if (r === null) return t;
let o = r[1];
return t.split(`
`).map((e) => {
let t = e.match(n.other.beginningSpace);
if (t === null) return e;
let [r] = t;
return e.slice(Math.min(r.length, o.length));
}).join(`
`);
}
function _e(e, t, n, r) {
if (!t.includes("<")) return !1;
for (let o = 0; o < t.length; o++) {
if (t[o] === "\\") {
o++;
continue;
}
if (t[o] === "`") {
let e = r.inline.code.exec(t.slice(o));
if (e) {
o += e[0].length - 1;
continue;
}
}
if (t[o] !== "<") continue;
let s = e.slice(n + o), c = r.inline.tag.exec(s) || r.inline.autolink.exec(s);
if (c) {
if (c[0].length > t.length - o) return !0;
o += c[0].length - 1;
}
}
return !1;
}
var _ = class {
options;
rules;
lexer;
constructor(e) {
this.options = e || y;
}
space(e) {
let t = this.rules.block.newline.exec(e);
if (t && t[0].length > 0) return {
type: "space",
raw: t[0]
};
}
code(e) {
let t = this.rules.block.code.exec(e);
if (t) {
let e = this.options.pedantic ? t[0] : ae(t[0]);
return {
type: "code",
raw: e,
codeBlockStyle: "indented",
text: e.replace(this.rules.other.codeRemoveIndent, "")
};
}
}
fences(e) {
let t = this.rules.block.fences.exec(e);
if (t) {
let e = t[0], n = Lt(e, t[3] || "", this.rules);
return {
type: "code",
raw: e,
lang: t[2] ? t[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t[2],
text: n
};
}
}
heading(e) {
let t = this.rules.block.heading.exec(e);
if (t) {
let e = t[2].trim();
if (this.rules.other.endingHash.test(e)) {
let t = A(e, "#");
(this.options.pedantic || !t || this.rules.other.endingSpaceTabChar.test(t)) && (e = t.trim());
}
return {
type: "heading",
raw: A(t[0], `
`),
depth: t[1].length,
text: e,
tokens: this.lexer.inline(e)
};
}
}
hr(e) {
let t = this.rules.block.hr.exec(e);
if (t) return {
type: "hr",
raw: A(t[0], `
`)
};
}
blockquote(e) {
let t = this.rules.block.blockquote.exec(e);
if (t) {
let e = A(t[0], `
`).split(`
`), n = "", r = "", o = [];
for (; e.length > 0;) {
let t = !1, s = [], c = 0;
for (; c < e.length; c++) if (this.rules.other.blockquoteStart.test(e[c])) s.push(e[c]), t = !0;
else if (!t) s.push(e[c]);
else break;
e = e.slice(c);
let u = s.join(`
`), d = u.replace(this.rules.other.blockquoteSetextReplace, `
$1`).replace(this.rules.other.blockquoteSetextReplace2, "");
n = n ? `${n}
${u}` : u, r = r ? `${r}
${d}` : d;
let p = this.lexer.state.top;
if (this.lexer.state.top = !0, this.lexer.blockTokens(d, o, !0), this.lexer.state.top = p, e.length === 0) break;
let m = o.at(-1);
if (m?.type === "code" || m?.type === "heading" || m?.type === "hr" || m?.type === "html") break;
if (m?.type === "blockquote") {
let t = m, s = e.join(`
`), c = t.raw + `
` + s.replace(this.rules.other.blockquoteSetextReplace2, ""), u = this.blockquote(c);
o[o.length - 1] = u;
let d = c.substring(u.raw.length).replace(/^\n/, ""), p = d ? d.split(`
`).length : 0, g = p ? e.slice(0, -p) : e;
g.length > 0 && (n = `${n}
${g.join(`
`)}`), r = r.substring(0, r.length - t.text.length) + u.text;
break;
} else if (m?.type === "list") {
let t = m, s = t.raw + `
` + e.join(`
`), c = this.list(s);
o[o.length - 1] = c, n = n.substring(0, n.length - m.raw.length) + c.raw, r = r.substring(0, r.length - t.raw.length) + c.raw, e = s.substring(o.at(-1).raw.length).split(`
`);
continue;
}
}
return {
type: "blockquote",
raw: n,
tokens: o,
text: r
};
}
}
list(e) {
let t = this.rules.block.list.exec(e);
if (t) {
let n = e, i = () => n.length - e.length, r = t[1].trim(), o = r.length > 1, s = {
type: "list",
raw: "",
ordered: o,
start: o ? +r.slice(0, -1) : "",
loose: !1,
items: []
};
r = o ? `\\d{1,9}\\${r.slice(-1)}` : `\\${r}`, this.options.pedantic && (r = o ? r : "[*+-]");
let c = this.rules.other.listItemRegex(r), u = !1;
for (; e;) {
let r = !1, o = "";
if (!(t = c.exec(e)) || this.rules.block.hr.test(e)) break;
let d = i();
e = e.substring(t[0].length);
let p = t[2].split(`
`, 1)[0], m = t[1].length, g = this.options.pedantic ? X(p, m) : p.replace(this.rules.other.leadingSpaceTab, (e) => X(e, m)), b = e.split(`
`, 1)[0], E = !g.trim(), k = 0;
if (this.options.pedantic ? (k = 2, o = g.trimStart()) : E ? k = m + 1 : (k = g.search(this.rules.other.nonSpaceChar), k = k > 4 ? 1 : k, o = g.slice(k), k += m), E && this.rules.other.blankLine.test(b) && (e = e.substring(b.length + 1), r = !0), !r) {
let t = this.rules.other.nextBulletRegex(k), n = this.rules.other.hrRegex(k), r = this.rules.other.fencesBeginRegex(k), s = this.rules.other.headingBeginRegex(k), c = this.rules.other.htmlBeginRegex(k), u = this.rules.other.blockquoteBeginRegex(k);
for (; e;) {
let d = e.split(`
`, 1)[0], p;
if (b = d, this.options.pedantic ? (b = b.replace(this.rules.other.listReplaceNesting, " "), p = b) : p = b.replace(this.rules.other.leadingSpaceTab, (e) => X(e)), r.test(b) || s.test(b) || c.test(b) || u.test(b) || t.test(b) || n.test(b)) break;
if (p.search(this.rules.other.nonSpaceChar) >= k || !b.trim()) o += `
` + p.slice(k);
else {
if (E || g.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4 || r.test(g) || s.test(g) || n.test(g)) break;
o += `
` + b;
}
E = !b.trim(), e = e.substring(d.length + 1), g = p.slice(k);
}
}
let P = n.slice(d, i());
s.loose || (u ? s.loose = !0 : this.rules.other.doubleBlankLine.test(P) && (u = !0)), s.items.push({
type: "list_item",
raw: P,
task: !!this.options.gfm && this.rules.other.listIsTask.test(o),
loose: !1,
text: o,
tokens: []
});
}
let d = s.items.at(-1);
if (d) d.raw = d.raw.trimEnd(), d.text = d.text.trimEnd();
else return;
s.raw = n.slice(0, i()).trimEnd();
for (let e of s.items) if (this.lexer.state.top = !1, e.tokens = this.lexer.blockTokens(e.text, []), !s.loose) {
let t = e.tokens.filter((e) => e.type === "space");
s.loose = t.length > 0 && t.some((e) => this.rules.other.anyLine.test(e.raw));
}
for (let e of s.items) {
let t = e.tokens[0];
if (e.task && (t?.type === "text" || t?.type === "paragraph")) {
e.text = e.text.replace(this.rules.other.listReplaceTask, ""), t.raw = t.raw.replace(this.rules.other.listReplaceTask, ""), t.text = t.text.replace(this.rules.other.listReplaceTask, "");
for (let e = this.lexer.inlineQueue.length - 1; e >= 0; e--) if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)) {
this.lexer.inlineQueue[e].src = this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask, "");
break;
}
let n = this.rules.other.listTaskCheckbox.exec(e.raw);
if (n) {
let t = {
type: "checkbox",
raw: n[0] + " ",
checked: n[0] !== "[ ]"
};
e.checked = t.checked, s.loose ? e.tokens[0] && ["paragraph", "text"].includes(e.tokens[0].type) && "tokens" in e.tokens[0] && e.tokens[0].tokens ? (e.tokens[0].raw = t.raw + e.tokens[0].raw, e.tokens[0].text = t.raw + e.tokens[0].text, e.tokens[0].tokens.unshift(t)) : e.tokens.unshift({
type: "paragraph",
raw: t.raw,
text: t.raw,
tokens: [t]
}) : e.tokens.unshift(t);
}
} else e.task && (e.task = !1);
}
if (s.loose) for (let e of s.items) {
e.loose = !0;
for (let t of e.tokens) t.type === "text" && (t.type = "paragraph");
}
return s;
}
}
html(e) {
let t = this.rules.block.html.exec(e);
if (t) {
let e = ae(t[0]);
return {
type: "html",
block: !0,
raw: e,
pre: t[1] === "pre" || t[1] === "script" || t[1] === "style",
text: e
};
}
}
def(e) {
let t = this.rules.block.def.exec(e);
if (t) {
if (!this.rules.other.startAngleBracket.test(t[2]) && le(t[2], "()") !== -1) return;
let e = v(t[1]).replace(this.rules.other.multipleSpaceGlobal, " "), n = t[2] ? t[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", r = t[3] ? t[3].substring(1, t[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t[3];
return {
type: "def",
tag: e,
raw: A(t[0], `
`),
href: n,
title: r
};
}
}
table(e) {
let t = this.rules.block.table.exec(e);
if (!t || !this.rules.other.tableDelimiter.test(t[2])) return;
let n = oe(t[1]), r = t[2].replace(this.rules.other.tableAlignChars, "").split("|"), o = t[3]?.trim() ? t[3].replace(this.rules.other.tableRowBlankLine, "").split(`
`) : [], s = {
type: "table",
raw: A(t[0], `
`),
header: [],
align: [],
rows: []
};
if (n.length === r.length) {
for (let e of r) this.rules.other.tableAlignRight.test(e) ? s.align.push("right") : this.rules.other.tableAlignCenter.test(e) ? s.align.push("center") : this.rules.other.tableAlignLeft.test(e) ? s.align.push("left") : s.align.push(null);
for (let e = 0; e < n.length; e++) s.header.push({
text: n[e],
tokens: this.lexer.inline(n[e]),
header: !0,
align: s.align[e]
});
for (let e of o) s.rows.push(oe(e, s.header.length).map((e, t) => ({
text: e,
tokens: this.lexer.inline(e),
header: !1,
align: s.align[t]
})));
return s;
}
}
lheading(e) {
let t = this.rules.block.lheading.exec(e);
if (t) {
let e = t[1].trim();
return {
type: "heading",
raw: A(t[0], `
`),
depth: t[2].charAt(0) === "=" ? 1 : 2,
text: e,
tokens: this.lexer.inline(e)
};
}
}
paragraph(e) {
let t = this.rules.block.paragraph.exec(e);
if (t) {
let e = t[1].charAt(t[1].length - 1) === `
` ? t[1].slice(0, -1) : t[1];
return {
type: "paragraph",
raw: t[0],
text: e,
tokens: this.lexer.inline(e)
};
}
}
text(e) {
let t = this.rules.block.text.exec(e);
if (t) return {
type: "text",
raw: t[0],
text: t[0],
tokens: this.lexer.inline(t[0])
};
}
escape(e) {
let t = this.rules.inline.escape.exec(e);
if (t) return {
type: "escape",
raw: t[0],
text: t[1]
};
}
tag(e) {
let t = this.rules.inline.tag.exec(e);
if (t) return !this.lexer.state.inLink && this.rules.other.startATag.test(t[0]) ? this.lexer.state.inLink = !0 : this.lexer.state.inLink && this.rules.other.endATag.test(t[0]) && (this.lexer.state.inLink = !1), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t[0]) ? this.lexer.state.inRawBlock = !0 : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t[0]) && (this.lexer.state.inRawBlock = !1), {
type: "html",
raw: t[0],
inLink: this.lexer.state.inLink,
inRawBlock: this.lexer.state.inRawBlock,
block: !1,
text: t[0]
};
}
link(e) {
if (this.lexer.state.linkParenPossible === !1) return;
let t = this.rules.inline.link.exec(e);
if (t) {
let n = t[0].charAt(0) === "!" ? 2 : 1;
if (!this.options.pedantic && _e(e, t[1], n, this.rules)) return;
let r = t[2].trim();
if (!this.options.pedantic && this.rules.other.startAngleBracket.test(r)) {
if (!this.rules.other.endAngleBracket.test(r)) return;
let e = A(r.slice(0, -1), "\\");
if ((r.length - e.length) % 2 === 0) return;
} else {
let e = le(t[2], "()");
if (e === -2) return;
if (e > -1) {
let n = (t[0].indexOf("!") === 0 ? 5 : 4) + t[1].length + e;
t[2] = t[2].substring(0, e), t[0] = t[0].substring(0, n).trim(), t[3] = "";
}
}
let o = t[2], s = "";
if (this.options.pedantic) {
let e = this.rules.other.pedanticHrefTitle.exec(o);
e && (o = e[1], s = e[3]);
} else s = t[3] ? t[3].slice(1, -1) : "";
return o = o.trim(), this.rules.other.startAngleBracket.test(o) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(r) ? o = o.slice(1) : o = o.slice(1, -1)), Se(t, {
href: o && o.replace(this.rules.inline.anyPunctuation, "$1"),
title: s && s.replace(this.rules.inline.anyPunctuation, "$1")
}, t[0], this.lexer, this.rules);
}
}
reflink(e, t) {
let n;
if ((n = this.rules.inline.reflink.exec(e)) || (n = this.rules.inline.nolink.exec(e))) {
let r = n[0].charAt(0) === "!" ? 2 : 1;
if (!this.options.pedantic && _e(e, n[1], r, this.rules)) return;
let o = t[v((n[2] || n[1]).replace(this.rules.other.multipleSpaceGlobal, " "))];
if (!o) {
let e = n[0].charAt(0);
return {
type: "text",
raw: e,
text: e
};
}
return Se(n, o, n[0], this.lexer, this.rules);
}
}
emStrong(e, t, n = "") {
let r = this.rules.inline.emStrongLDelim.exec(e);
if (!r || !r[1] && !r[2] && !r[3] && !r[4] || r[4] && n.match(this.rules.other.unicodeAlphaNumeric)) return;
if (!(r[1] || r[3] || "") || !n || this.rules.inline.punctuation.exec(n)) {
let o = [...r[0]].length - 1, s, c, u = o, d = 0, p = r[0][0], m = n === p, g = p === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
for (g.lastIndex = 0, t = t.slice(-1 * e.length + o); (r = g.exec(t)) !== null;) {
if (s = r[1] || r[2] || r[3] || r[4] || r[5] || r[6], !s) continue;
if (c = [...s].length, r[3] || r[4]) {
u += c;
continue;
} else if (r[5] || r[6]) {
if (o % 3 && !((o + c) % 3)) {
d += c;
continue;
}
if (m) break;
}
if (u -= c, u > 0) continue;
c = Math.min(c, c + u + d);
let t = [...r[0]][0].length, n = e.slice(0, o + r.index + t + c);
if (Math.min(o, c) % 2) {
let e = n.slice(1, -1);
return {
type: "em",
raw: n,
text: e,
tokens: this.lexer.inlineTokens(e)
};
}
let p = n.slice(2, -2);
return {
type: "strong",
raw: n,
text: p,
tokens: this.lexer.inlineTokens(p)
};
}
}
}
codespan(e) {
let t = this.rules.inline.code.exec(e);
if (t) {
let e = t[2].replace(this.rules.other.newLineCharGlobal, " "), n = this.rules.other.nonSpaceChar.test(e), r = this.rules.other.startingSpaceChar.test(e) && this.rules.other.endingSpaceChar.test(e);
return n && r && (e = e.substring(1, e.length - 1)), {
type: "codespan",
raw: t[0],
text: e
};
}
}
br(e) {
let t = this.rules.inline.br.exec(e);
if (t) return {
type: "br",
raw: t[0]
};
}
del(e, t, n = "") {
let r = this.rules.inline.delLDelim.exec(e);
if (!r) return;
if (!(r[1] || "") || !n || this.rules.inline.punctuation.exec(n)) {
let n = [...r[0]].length - 1, o, s, c = n, u = this.rules.inline.delRDelim;
for (u.lastIndex = 0, t = t.slice(-1 * e.length + n); (r = u.exec(t)) !== null;) {
if (o = r[1] || r[2] || r[3] || r[4] || r[5] || r[6], !o || (s = [...o].length, s !== n)) continue;
if (r[3] || r[4]) {
c += s;
continue;
}
if (c -= s, c > 0) continue;
s = Math.min(s, s + c);
let t = [...r[0]][0].length, u = e.slice(0, n + r.index + t + s), d = u.slice(n, -n);
return {
type: "del",
raw: u,
text: d,
tokens: this.lexer.inlineTokens(d)
};
}
}
}
autolink(e) {
let t = this.rules.inline.autolink.exec(e);
if (t) {
let e, n;
return t[2] === "@" ? (e = t[1], n = "mailto:" + e) : (e = t[1], n = e), {
type: "link",
raw: t[0],
text: e,
href: n,
autolink: !0,
tokens: [{
type: "text",
raw: e,
text: e
}]
};
}
}
url(e) {
let t;
if (t = this.rules.inline.url.exec(e)) {
let e, n;
if (t[2] === "@") e = t[0], n = "mailto:" + e;
else {
let r;
do
r = t[0], t[0] = this.rules.inline._backpedal.exec(t[0])?.[0] ?? "";
while (r !== t[0]);
e = t[0], t[1] === "www." ? n = "http://" + t[0] : n = t[0];
}
return {
type: "link",
raw: t[0],
text: e,
href: n,
autolink: !0,
tokens: [{
type: "text",
raw: e,
text: e
}]
};
}
}
inlineText(e) {
let t = this.rules.inline.text.exec(e);
if (t) {
let e = this.lexer.state.inRawBlock;
return {
type: "text",
raw: t[0],
text: e ? t[0] : ye(t[0]),
escaped: e
};
}
}
};
var T = class a {
tokens;
options;
state;
inlineQueue;
tokenizer;
constructor(e) {
this.tokens = [], this.tokens.links = Object.create(null), this.options = e || y, this.options.tokenizer = this.options.tokenizer || new _(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = {
inLink: !1,
inRawBlock: !1,
linkEmitted: !1,
linkParenPossible: !0,
top: !0
};
let t = {
other: x,
block: F.normal,
inline: Z.normal
};
this.options.pedantic ? (t.block = F.pedantic, t.inline = Z.pedantic) : this.options.gfm && (t.block = F.gfm, this.options.breaks ? t.inline = Z.breaks : t.inline = Z.gfm), this.tokenizer.rules = t;
}
static get rules() {
return {
block: F,
inline: Z
};
}
static lex(e, t) {
return new a(t).lex(e);
}
static lexInline(e, t) {
return new a(t).inlineTokens(e);
}
lex(e) {
e = e.replace(x.carriageReturn, `
`), this.blockTokens(e, this.tokens);
for (let e = 0; e < this.inlineQueue.length; e++) {
let t = this.inlineQueue[e];
this.inlineTokens(t.src, t.tokens);
}
return this.inlineQueue = [], this.tokens;
}
blockTokens(e, t = [], n = !1) {
this.tokenizer.lexer = this, this.options.pedantic && (e = e.replace(x.tabCharGlobal, " ").replace(x.spaceLine, ""));
let r = 1 / 0;
for (; e;) {
if (e.length < r) r = e.length;
else {
this.infiniteLoopError(e.charCodeAt(0));
break;
}
let o;
if (this.options.extensions?.block?.some((n) => (o = n.call({ lexer: this }, e, t)) ? (e = e.substring(o.raw.length), t.push(o), !0) : !1)) continue;
if (o = this.tokenizer.space(e)) {
e = e.substring(o.raw.length);
let n = t.at(-1);
o.raw.length === 1 && n !== void 0 ? n.raw += `
` : t.push(o);
continue;
}
if (o = this.tokenizer.code(e)) {
e = e.substring(o.raw.length);
let n = t.at(-1);
n?.type === "paragraph" || n?.type === "text" ? (n.raw += (n.raw.endsWith(`
`) ? "" : `
`) + o.raw, n.text += `
` + o.text, this.inlineQueue.at(-1).src = n.text) : t.push(o);
continue;
}
if (o = this.tokenizer.fences(e)) {
e = e.substring(o.raw.length), t.push(o);
continue;
}
if (o = this.tokenizer.heading(e)) {
e = e.substring(o.raw.length), t.push(o);
continue;
}
if (o = this.tokenizer.hr(e)) {
e = e.substring(o.raw.length), t.push(o);
continue;
}
if (o = this.tokenizer.blockquote(e)) {
e = e.substring(o.raw.length), t.push(o);
continue;
}
if (o = this.tokenizer.list(e)) {
e = e.substring(o.raw.length), t.push(o);
continue;
}
if (o = this.tokenizer.html(e)) {
e = e.substring(o.raw.length), t.push(o);
continue;
}
if (o = this.tokenizer.def(e)) {
e = e.substring(o.raw.length);
let n = t.at(-1);
n?.type === "paragraph" || n?.type === "text" ? (n.raw += (n.raw.endsWith(`
`) ? "" : `
`) + o.raw, n.text += `
` + o.raw, this.inlineQueue.at(-1).src = n.text) : this.tokens.links[o.tag] || (this.tokens.links[o.tag] = {
href: o.href,
title: o.title
}, t.push(o));
continue;
}
if (o = this.tokenizer.table(e)) {
e = e.substring(o.raw.length), t.push(o);
continue;
}
if (o = this.tokenizer.lheading(e)) {
e = e.substring(o.raw.length), t.push(o);
continue;
}
let s = e;
if (this.options.extensions?.startBlock) {
let t = 1 / 0, n = e.slice(1), r;
this.options.extensions.startBlock.forEach((e) => {
r = e.call({ lexer: this }, n), typeof r == "number" && r >= 0 && (t = Math.min(t, r));
}), t < 1 / 0 && t >= 0 && (s = e.substring(0, t + 1));
}
if (this.state.top && (o = this.tokenizer.paragraph(s))) {
let r = t.at(-1);
n && r?.type === "paragraph" ? (r.raw += (r.raw.endsWith(`
`) ? "" : `
`) + o.raw, r.text += `
` + o.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = r.text) : t.push(o), n = s.length !== e.length, e = e.substring(o.raw.length);
continue;
}
if (o = this.tokenizer.text(e)) {
e = e.substring(o.raw.length);
let n = t.at(-1);
n?.type === "text" ? (n.raw += (n.raw.endsWith(`
`) ? "" : `
`) + o.raw, n.text += `
` + o.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = n.text) : t.push(o);
continue;
}
if (e) {
this.infiniteLoopError(e.charCodeAt(0));
break;
}
}
return this.state.top = !0, t;
}
inline(e, t = []) {
return this.inlineQueue.push({
src: e,
tokens: t
}), t;
}
linkInText(e) {
if (!e.includes("[")) return !1;
let t = this.tokenizer.rules.inline.link;
for (let n of e.matchAll(this.tokenizer.rules.inline.blockSkip)) if (t.test(n[0]) && e.charAt(n.index - 1) !== "!") return !0;
for (let t of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)) {
let e = t[0], n = e.lastIndexOf("[");
if (!(e.charAt(0) === "!" || !Object.hasOwn(this.tokens.links, v(e.slice(n + 1, -1)))) && !(n > 1 && this.linkInText(e.slice(1, n - 1)))) return !0;
}
return !1;
}
inlineTokens(e, t = []) {
this.tokenizer.lexer = this;
let n = this.state.linkParenPossible;
this.state.linkParenPossible = n && e.includes(")");
try {
return this.#e(e, t);
} finally {
this.state.linkParenPossible = n;
}
}
#e(e, t) {
let n = e;
if (this.tokens.links && e.includes("[")) {
let e = this.tokenizer.rules.inline.reflinkSearch, l = (t) => {
let n = t.lastIndexOf("[");
if (!Object.hasOwn(this.tokens.links, v(t.slice(n + 1, -1)))) return t;
if (n > 1 && t.charAt(0) !== "!") {
let r = t.slice(1, n - 1);
if (this.linkInText(r)) return "[" + r.replace(e, l) + "][" + "a".repeat(t.length - n - 2) + "]";
}
return "[" + "a".repeat(t.length - 2) + "]";
};
n = n.replace(e, l);
}
n = n.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode, (e, t, n) => n ? "+".repeat(e.length) : t ? t + e.slice(t.length, -t.length).replace(/`/g, "+") + t : e), n = n.replace(this.tokenizer.rules.inline.blockSkip, (e, t, n) => {
let r = n ? n.length : 0;
return e.slice(0, r) + "[" + "a".repeat(e.length - r - 2) + "]";
}), n = this.options.hooks?.emStrongMask?.call({ lexer: this }, n) ?? n;
let r = !1, o = "", s = 1 / 0;
for (; e;) {
if (e.length < s) s = e.length;
else {
this.infiniteLoopError(e.charCodeAt(0));
break;
}
r || (o = ""), r = !1;
let c;
if (this.options.extensions?.inline?.some((n) => (c = n.call({ lexer: this }, e, t)) ? (e = e.substring(c.raw.length), t.push(c), !0) : !1)) continue;
if (c = this.tokenizer.escape(e)) {
e = e.substring(c.raw.length), t.push(c);
continue;
}
if (c = this.tokenizer.tag(e)) {
e = e.substring(c.raw.length), t.push(c);
continue;
}
if (c = this.tokenizer.link(e)) {
e = e.substring(c.raw.length), t.push(c);
continue;
}
if (c = this.tokenizer.reflink(e, this.tokens.links)) {
e = e.substring(c.raw.length);
let n = t.at(-1);
c.type === "text" && n?.type === "text" ? (n.raw += c.raw, n.text += c.text) : t.push(c);
continue;
}
if (c = this.tokenizer.emStrong(e, n, o)) {
e = e.substring(c.raw.length), t.push(c);
continue;
}
if (c = this.tokenizer.codespan(e)) {
e = e.substring(c.raw.length), t.push(c);
continue;
}
if (c = this.tokenizer.br(e)) {
e = e.substring(c.raw.length), t.push(c);
continue;
}
if (c = this.tokenizer.del(e, n, o)) {
e = e.substring(c.raw.length), t.push(c);
continue;
}
if (c = this.tokenizer.autolink(e)) {
e = e.substring(c.raw.length), t.push(c);
continue;
}
if (!this.state.inLink && (c = this.tokenizer.url(e))) {
e = e.substring(c.raw.length), t.push(c);
continue;
}
let u = e;
if (this.options.extensions?.startInline) {
let t = 1 / 0, n = e.slice(1), r;
this.options.extensions.startInline.forEach((e) => {
r = e.call({ lexer: this }, n), typeof r == "number" && r >= 0 && (t = Math.min(t, r));
}), t < 1 / 0 && t >= 0 && (u = e.substring(0, t + 1));
}
if (c = this.tokenizer.inlineText(u)) {
e = e.substring(c.raw.length), c.raw.slice(-1) !== "_" && (o = c.raw.slice(-1)), r = !0;
let n = t.at(-1);
n?.type === "text" ? (n.raw += c.raw, n.text += c.text) : t.push(c);
continue;
}
if (e) {
this.infiniteLoopError(e.charCodeAt(0));
break;
}
}
return t;
}
infiniteLoopError(e) {
let t = "Infinite loop on byte: " + e;
if (this.options.silent) console.error(t);
else throw new Error(t);
}
};
var $ = class {
options;
parser;
constructor(e) {
this.options = e || y;
}
space(e) {
return "";
}
code({ text: e, lang: t, escaped: n }) {
let r = (t || "").match(x.notSpaceStart)?.[0], o = e ? e.replace(x.endingNewline, "") + `
` : "";
return r ? "<pre><code class=\"language-" + w(r) + "\">" + (n ? o : w(o, !0)) + `</code></pre>
` : "<pre><code>" + (n ? o : w(o, !0)) + `</code></pre>
`;
}
blockquote({ tokens: e }) {
return `<blockquote>
${this.parser.parse(e)}</blockquote>
`;
}
html({ text: e }) {
return e;
}
def(e) {
return "";
}
heading({ tokens: e, depth: t }) {
return `<h${t}>${this.parser.parseInline(e)}</h${t}>
`;
}
hr(e) {
return `<hr>
`;
}
list(e) {
let t = e.ordered, n = e.start, r = "";
for (let t = 0; t < e.items.length; t++) {
let n = e.items[t];
r += this.listitem(n);
}
let o = t ? "ol" : "ul", s = t && n !== 1 ? " start=\"" + n + "\"" : "";
return "<" + o + s + `>
` + r + "</" + o + `>
`;
}
listitem(e) {
return `<li>${this.parser.parse(e.tokens)}</li>
`;
}
checkbox({ checked: e }) {
return "<input " + (e ? "checked=\"\" " : "") + "disabled=\"\" type=\"checkbox\"> ";
}
paragraph({ tokens: e }) {
return `<p>${this.parser.parseInline(e)}</p>
`;
}
table(e) {
let t = "", n = "";
for (let t = 0; t < e.header.length; t++) n += this.tablecell(e.header[t]);
t += this.tablerow({ text: n });
let r = "";
for (let t = 0; t < e.rows.length; t++) {
let o = e.rows[t];
n = "";
for (let e = 0; e < o.length; e++) n += this.tablecell(o[e]);
r += this.tablerow({ text: n });
}
return r && (r = `<tbody>${r}</tbody>`), `<table>
<thead>
` + t + `</thead>
` + r + `</table>
`;
}
tablerow({ text: e }) {
return `<tr>
${e}</tr>
`;
}
tablecell(e) {
let t = this.parser.parseInline(e.tokens), n = e.header ? "th" : "td";
return (e.align ? `<${n} align="${e.align}">` : `<${n}>`) + t + `</${n}>
`;
}
strong({ tokens: e }) {
return `<strong>${this.parser.parseInline(e)}</strong>`;
}
em({ tokens: e }) {
return `<em>${this.parser.parseInline(e)}</em>`;
}
codespan({ text: e }) {
return `<code>${w(e, !0)}</code>`;
}
br(e) {
return "<br>";
}
del({ tokens: e }) {
return `<del>${this.parser.parseInline(e)}</del>`;
}
link({ href: e, title: t, text: n, tokens: r, autolink: o }) {
let s = o ? w(n, !0) : this.parser.parseInline(r), c = ie(e);
if (c === null) return s;
e = w(c, o);
let u = "<a href=\"" + e + "\"";
return t && (u += " title=\"" + w(t) + "\""), u += ">" + s + "</a>", u;
}
image({ href: e, title: t, text: n, tokens: r }) {
r && (n = this.parser.parseInline(r, this.parser.textRenderer));
let o = ie(e);
if (o === null) return w(n);
e = o;
let s = `<img src="${w(e)}" alt="${w(n)}"`;
return t && (s += ` title="${w(t)}"`), s += ">", s;
}
text(e) {
return "tokens" in e && e.tokens ? this.parser.parseInline(e.tokens) : "escaped" in e && e.escaped ? e.text : w(e.text);
}
};
var z = class {
strong({ text: e }) {
return e;
}
em({ text: e }) {
return e;
}
codespan({ text: e }) {
return e;
}
del({ text: e }) {
return e;
}
html({ text: e }) {
return e;
}
text({ text: e }) {
return e;
}
link({ text: e }) {
return "" + e;
}
image({ text: e }) {
return "" + e;
}
br() {
return "";
}
checkbox({ raw: e }) {
return e;
}
};
var O = class a {
options;
renderer;
textRenderer;
constructor(e) {
this.options = e || y, this.options.renderer = this.options.renderer || new $(), this.renderer = this.options.renderer, this.renderer.options = this.options, this.renderer.parser = this, this.textRenderer = new z();
}
static parse(e, t) {
return new a(t).parse(e);
}
static parseInline(e, t) {
return new a(t).parseInline(e);
}
parse(e) {
this.renderer.parser = this;
let t = "";
for (let n = 0; n < e.length; n++) {
let r = e[n];
if (this.options.extensions?.renderers?.[r.type]) {
let e = r, n = this.options.extensions.renderers[e.type].call({ parser: this }, e);
if (n !== !1 || ![
"space",
"hr",
"heading",
"code",
"table",
"blockquote",
"list",
"checkbox",
"html",
"def",
"paragraph",
"text"
].includes(e.type)) {
t += n || "";
continue;
}
}
let o = r;
switch (o.type) {
case "space":
t += this.renderer.space(o);
break;
case "hr":
t += this.renderer.hr(o);
break;
case "heading":
t += this.renderer.heading(o);
break;
case "code":
t += this.renderer.code(o);
break;
case "table":
t += this.renderer.table(o);
break;
case "blockquote":
t += this.renderer.blockquote(o);
break;
case "list":
t += this.renderer.list(o);
break;
case "checkbox":
t += this.renderer.checkbox(o);
break;
case "html":
t += this.renderer.html(o);
break;
case "def":
t += this.renderer.def(o);
break;
case "paragraph":
t += this.renderer.paragraph(o);
break;
case "text":
t += this.renderer.text(o);
break;
default: {
let e = "Token with \"" + o.type + "\" type was not found.";
if (this.options.silent) return console.error(e), "";
throw new Error(e);
}
}
}
return t;
}
parseInline(e, t = this.renderer) {
this.renderer.parser = this;
let n = "";
for (let r = 0; r < e.length; r++) {
let o = e[r];
if (this.options.extensions?.renderers?.[o.type]) {
let e = this.options.extensions.renderers[o.type].call({ parser: this }, o);
if (e !== !1 || ![
"escape",
"html",
"link",
"image",
"checkbox",
"strong",
"em",
"codespan",
"br",
"del",
"text"
].includes(o.type)) {
n += e || "";
continue;
}
}
let s = o;
switch (s.type) {
case "escape":
n += t.text(s);
break;
case "html":
n += t.html(s);
break;
case "link":
n += t.link(s);
break;
case "image":
n += t.image(s);
break;
case "checkbox":
n += t.checkbox(s);
break;
case "strong":
n += t.strong(s);
break;
case "em":
n += t.em(s);
break;
case "codespan":
n += t.codespan(s);
break;
case "br":
n += t.br(s);
break;
case "del":
n += t.del(s);
break;
case "text":
n += t.text(s);
break;
default: {
let e = "Token with \"" + s.type + "\" type was not found.";
if (this.options.silent) return console.error(e), "";
throw new Error(e);
}
}
}
return n;
}
};
var L = class {
options;
block;
constructor(e) {
this.options = e || y;
}
static passThroughHooks = /* @__PURE__ */ new Set([
"preprocess",
"postprocess",
"processAllTokens",
"emStrongMask"
]);
static passThroughHooksRespectAsync = /* @__PURE__ */ new Set([
"preprocess",
"postprocess",
"processAllTokens"
]);
preprocess(e) {
return e;
}
postprocess(e) {
return e;
}
processAllTokens(e) {
return e;
}
emStrongMask(e) {
return e;
}
provideLexer(e = this.block) {
return e ? T.lex : T.lexInline;
}
provideParser(e = this.block) {
return e ? O.parse : O.parseInline;
}
};
function C(e, t) {
if (Array.isArray(t)) for (let n = 0; n < t.length; n++) e.push(t[n]);
else e.push(t);
}
var U = class {
defaults = B();
options = this.setOptions;
parse = this.parseMarkdown(!0);
parseInline = this.parseMarkdown(!1);
Parser = O;
Renderer = $;
TextRenderer = z;
Lexer = T;
Tokenizer = _;
Hooks = L;
constructor(...e) {
this.use(...e);
}
walkTokens(e, t) {
let n = [];
for (let r of e) switch (C(n, t.call(this, r)), r.type) {
case "table": {
let e = r;
for (let r of e.header) C(n, this.walkTokens(r.tokens, t));
for (let r of e.rows) for (let e of r) C(n, this.walkTokens(e.tokens, t));
break;
}
case "list": {
let e = r;
C(n, this.walkTokens(e.items, t));
break;
}
default: {
let e = r;
this.defaults.extensions?.childTokens?.[e.type] ? this.defaults.extensions.childTokens[e.type].forEach((r) => {
let o = e[r].flat(1 / 0);
C(n, this.walkTokens(o, t));
}) : e.tokens && C(n, this.walkTokens(e.tokens, t));
}
}
return n;
}
use(...e) {
let t = this.defaults.extensions || {
renderers: {},
childTokens: {}
};
return e.forEach((e) => {
let n = { ...e };
if (n.async = this.defaults.async || n.async || !1, e.extensions && (e.extensions.forEach((e) => {
if (!e.name) throw new Error("extension name required");
if ("renderer" in e) {
let n = t.renderers[e.name];
n ? t.renderers[e.name] = function(...t) {
let r = e.renderer.apply(this, t);
return r === !1 && (r = n.apply(this, t)), r;
} : t.renderers[e.name] = e.renderer;
}
if ("tokenizer" in e) {
if (!e.level || e.level !== "block" && e.level !== "inline") throw new Error("extension level must be 'block' or 'inline'");
let n = t[e.level];
n ? n.unshift(e.tokenizer) : t[e.level] = [e.tokenizer], e.start && (e.level === "block" ? t.startBlock ? t.startBlock.push(e.start) : t.startBlock = [e.start] : e.level === "inline" && (t.startInline ? t.startInline.push(e.start) : t.startInline = [e.start]));
}
"childTokens" in e && e.childTokens && (t.childTokens[e.name] = e.childTokens);
}), n.extensions = t), e.renderer) {
let t = this.defaults.renderer || new $(this.defaults);
for (let n in e.renderer) {
if (!(n in t)) throw new Error(`renderer '${n}' does not exist`);
if (["options", "parser"].includes(n)) continue;
let r = n, o = e.renderer[r], s = t[r];
t[r] = (...e) => {
let n = o.apply(t, e);
return n === !1 && (n = s.apply(t, e)), n || "";
};
}
n.renderer = t;
}
if (e.tokenizer) {
let t = this.defaults.tokenizer || new _(this.defaults);
for (let n in e.tokenizer) {
if (!(n in t)) throw new Error(`tokenizer '${n}' does not exist`);
if ([
"options",
"rules",
"lexer"
].includes(n)) continue;
let r = n, o = e.tokenizer[r], s = t[r];
t[r] = (...e) => {
let n = o.apply(t, e);
return n === !1 && (n = s.apply(t, e)), n;
};
}
n.tokenizer = t;
}
if (e.hooks) {
let t = this.defaults.hooks || new L();
for (let n in e.hooks) {
if (!(n in t)) throw new Error(`hook '${n}' does not exist`);
if (["options", "block"].includes(n)) continue;
let r = n, o = e.hooks[r], s = t[r];
L.passThroughHooks.has(n) ? t[r] = (e) => {
if (this.defaults.async && L.passThroughHooksRespectAsync.has(n)) return (async () => {
let n = await o.call(t, e);
return s.call(t, n);
})();
let r = o.call(t, e);
return s.call(t, r);
} : t[r] = (...e) => {
if (this.defaults.async) return (async () => {
let n = await o.apply(t, e);
return n === !1 && (n = await s.apply(t, e)), n;
})();
let n = o.apply(t, e);
return n === !1 && (n = s.apply(t, e)), n;
};
}
n.hooks = t;
}
if (e.walkTokens) {
let t = this.defaults.walkTokens, r = e.walkTokens;
n.walkTokens = function(e) {
let n = [];
return n.push(r.call(this, e)), t && C(n, t.call(this, e)), n;
};
}
this.defaults = {
...this.defaults,
...n
};
}), this;
}
setOptions(e) {
return this.defaults = {
...this.defaults,
...e
}, this;
}
lexer(e, t) {
return T.lex(e, t ?? this.defaults);
}
parser(e, t) {
return O.parse(e, t ?? this.defaults);
}
parseMarkdown(e) {
return (t, n) => {
let r = { ...n }, o = {
...this.defaults,
...r
}, s = this.onError(!!o.silent, !!o.async);
if (this.defaults.async === !0 && r.async === !1) return s(/* @__PURE__ */ new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
if (typeof t > "u" || t === null) return s(/* @__PURE__ */ new Error("marked(): input parameter is undefined or null"));
if (typeof t != "string") return s(/* @__PURE__ */ new Error("marked(): input parameter is of type " + Object.prototype.toString.call(t) + ", string expected"));
if (o.hooks && (o.hooks.options = o, o.hooks.block = e), o.async) return (async () => {
let n = o.hooks ? await o.hooks.preprocess(t) : t, r = await (o.hooks ? await o.hooks.provideLexer(e) : e ? T.lex : T.lexInline)(n, o), s = o.hooks ? await o.hooks.processAllTokens(r) : r;
o.walkTokens && await Promise.all(this.walkTokens(s, o.walkTokens));
let c = await (o.hooks ? await o.hooks.provideParser(e) : e ? O.parse : O.parseInline)(s, o);
return o.hooks ? await o.hooks.postprocess(c) : c;
})().catch(s);
try {
o.hooks && (t = o.hooks.preprocess(t));
let n = (o.hooks ? o.hooks.provideLexer(e) : e ? T.lex : T.lexInline)(t, o);
o.hooks && (n = o.hooks.processAllTokens(n)), o.walkTokens && this.walkTokens(n, o.walkTokens);
let r = (o.hooks ? o.hooks.provideParser(e) : e ? O.parse : O.parseInline)(n, o);
return o.hooks && (r = o.hooks.postprocess(r)), r;
} catch (e) {
return s(e);
}
};
}
onError(e, t) {
return (n) => {
if (n.message += `
Please report this to https://github.com/markedjs/marked.`, e) {
let e = "<p>An error occurred:</p><pre>" + w(n.message + "", !0) + "</pre>";
return t ? Promise.resolve(e) : e;
}
if (t) return Promise.reject(n);
throw n;
};
}
};
var I = new U();
function f(e, t) {
return I.parse(e, t);
}
f.options = f.setOptions = function(e) {
return I.setOptions(e), f.defaults = I.defaults, V(f.defaults), f;
};
f.getDefaults = B;
f.defaults = y;
function At(...e) {
return I.use(...e), f.defaults = I.defaults, V(f.defaults), f;
}
f.use = At;
f.walkTokens = function(e, t) {
return I.walkTokens(e, t);
};
f.parseInline = I.parseInline;
f.Parser = O;
f.parser = O.parse;
f.Renderer = $;
f.TextRenderer = z;
f.Lexer = T;
f.lexer = T.lex;
f.Tokenizer = _;
f.Hooks = L;
f.parse = f;
var Rn = f.options;
var Tn = f.setOptions;
var On = f.walkTokens;
var wn = f.parseInline;
var yn = O.parse;
var Sn = T.lex;
//#endregion
//#region extensions/knowledge/src/markdown-links.ts
const escapeHtml = (e) => e.replace(/[&<>"']/g, (e) => ({
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
})[e]);
const wikiHref = (e) => `#wiki=${encodeURIComponent(e)}`;
/** One parser for navigation and rendering: code, escapes, HTML and images are not links. */
const markdown = new U({
gfm: true,
async: false,
renderer: {
html: ({ text: e }) => /^\s*<!--/.test(e) ? "" : escapeHtml(e),
image: ({ text: e }) => escapeHtml(e)
},
extensions: [{
name: "wikilink",
level: "inline",
start: (e) => e.indexOf("[["),
tokenizer(e) {
const t = /^\[\[([^\]\n|]+)(?:\|([^\]\n]+))?\]\]/.exec(e);
if (t) return {
type: "wikilink",
raw: t[0],
target: t[1].trim(),
label: (t[2] ?? t[1]).trim()
};
},
renderer: (e) => `<a href="${escapeHtml(wikiHref(e.target))}">${escapeHtml(e.label)}</a>`
}]
});
const extracted = /* @__PURE__ */ new WeakMap();
const extractionOwner = Symbol("knowledge.linkExtractionOwner");
/** Merged-reference projections keep the source document's link parse. */
function carryLinkExtraction(e, t) {
t[extractionOwner] = e[extractionOwner] ?? e.metadata;
}
const LEX_RUN_MAX_LINES = 1e4;
function boundBlockRuns(e) {
const t = [];
let n = 0, r = 0;
for (let o = 0; o < e.length;) {
const s = e.indexOf("\n", o), c = s === -1 ? e.length : s;
if (!e.slice(o, c).trim()) n = 0;
else if (++n > LEX_RUN_MAX_LINES) {
t.push(e.slice(r, o), "\n");
r = o;
n = 1;
}
o = c + 1;
}
return t.length ? t.join("") + e.slice(r) : e;
}
const BACKLINKS_START = /^\s*<!--\s*(?:knowledge:)?backlinks:start\s*-->\s*$/i;
const BACKLINKS_END = /^\s*<!--\s*(?:knowledge:)?backlinks:end\s*-->\s*$/i;
function extractLinks(e) {
const t = markdown.lexer(boundBlockRuns(e)).filter((() => {
let e = false;
return (t) => {
if (t.type === "html" && BACKLINKS_START.test(t.raw)) {
e = true;
return false;
}
if (t.type === "html" && BACKLINKS_END.test(t.raw)) {
e = false;
return false;
}
return !e;
};
})());
const n = /* @__PURE__ */ new Set();
markdown.walkTokens(t, (e) => {
if (e.type === "wikilink") n.add(wikiHref(e.target));
if (e.type === "link") n.add(e.href);
});
return [...n];
}
/**
* The links extractLinks reads, in document order with their offsets, so a caller can edit
* exactly a parsed link and no other bytes. marked tokens carry no positions: each leaf
* token is located after the previous one, so text that only looks like a link (in code,
* after an escape) is passed over rather than matched.
*/
function linkSpans(e) {
const t = [];
let n = 0;
const locate = (t) => {
const r = t.split("\n", 1)[0], o = e.indexOf(r, n), s = o === -1 ? n : o, c = o !== -1 && e.startsWith(t, s);
n = s + (c ? t.length : r.length);
return {
start: s,
verbatim: c
};
};
const visit = (e) => {
for (const n of e) if (n.type === "link") {
const e = n.raw.startsWith(`[${n.text}](`) && n.raw.endsWith(")");
t.push({
href: n.href,
raw: n.raw,
label: n.text,
inline: e,
...locate(n.raw)
});
} else if (n.type === "wikilink") t.push({
href: wikiHref(String(n.target)),
raw: n.raw,
label: String(n.label),
inline: false,
...locate(n.raw)
});
else if (n.type === "list") visit(n.items);
else if (n.type === "table") for (const e of [...n.header, ...n.rows.flat()]) visit(e.tokens);
else if ("tokens" in n && n.tokens && n.type !== "image") visit(n.tokens);
else locate(n.raw);
};
let r = false;
for (const t of markdown.lexer(boundBlockRuns(e))) {
if (t.type === "html" && BACKLINKS_START.test(t.raw)) r = true;
else if (t.type === "html" && BACKLINKS_END.test(t.raw)) {
r = false;
locate(t.raw);
continue;
}
if (r) locate(t.raw);
else visit([t]);
}
return t;
}
const UNSAFE_TARGET_CHARACTER = new RegExp(String.raw`[\\\u0000-\u001f]`);
const normalize$1 = (e) => e.normalize("NFKC").toLowerCase();
function cleanPath(e) {
const t = [];
for (const n of e.split("/")) if (n === "..") {
if (!t.length) return;
t.pop();
} else if (n && n !== ".") t.push(n);
return t.join("/");
}
const indexes = /* @__PURE__ */ new WeakMap();
function linkIndex(e) {
let t = indexes.get(e);
if (t) return t;
t = {
byPath: /* @__PURE__ */ new Map(),
byId: /* @__PURE__ */ new Map(),
byName: /* @__PURE__ */ new Map()
};
const add = (e, t, n) => {
let r = e.get(t);
if (!r) e.set(t, r = /* @__PURE__ */ new Set());
r.add(n);
};
for (const n of e) {
add(t.byPath, normalize$1(n.path.replace(/\.md$/i, "")), n);
add(t.byId, n.id, n);
for (const e of [
n.title,
n.path.split("/").at(-1).replace(/\.md$/i, ""),
...n.metadata.aliases ?? []
]) add(t.byName, normalize$1(e), n);
}
indexes.set(e, t);
return t;
}
/** Where one href leads from a record in directory `parent`; undefined when it is not a record link. */
function resolveHref(e, t, n, r) {
const o = e.startsWith("#wiki=");
if (!o && (/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(e) || !/\.md(?:#.*)?$/i.test(e))) return;
let s;
try {
s = o ? decodeURIComponent(e.slice(6)).split("#")[0] : decodeURIComponent(e.split("#")[0]);
} catch {
s = "";
}
if (!s || UNSAFE_TARGET_CHARACTER.test(s) || /^(?:[a-z][a-z0-9+.-]*:|\/)/i.test(s)) return {
href: e,
status: "missing"
};
const c = s.replace(/\.md$/i, "");
const u = o && !s.startsWith(".") ? [cleanPath(s), cleanPath(`${t}/${s}`)] : [cleanPath(`${t}/${s}`)];
let d = /* @__PURE__ */ new Set();
for (const e of u) if (e) for (const t of n.byPath.get(normalize$1(e.replace(/\.md$/i, ""))) ?? []) d.add(t);
if (!d.size) d = new Set(n.byId.get(c.split("/").at(-1)) ?? []);
if (!d.size && o && !s.includes("/")) d = new Set(n.byName.get(normalize$1(c)) ?? []);
const p = new Set([...d].map((e) => r ? r(e.id) : e.id).filter((e) => !r || n.byId.has(e) && r(e) === e));
const [m] = p;
return {
href: e,
status: p.size === 1 ? "resolved" : p.size ? "ambiguous" : "missing",
...p.size === 1 ? { id: m } : {}
};
}
/** Input records must already be authorized and lifecycle-filtered. Never guess ambiguous names.
* `canonical` maps a merged page among `records` to the page it was merged into; a name matching
* both counts once, and a link whose final page is not among `records` is missing. */
function resolveLinks(e, t, n) {
const r = linkIndex(t), o = e.path.split("/").slice(0, -1).join("/");
const s = e[extractionOwner] ?? e.metadata;
let c = extracted.get(s);
if (!c || c.body !== e.body) {
c = {
body: e.body,
hrefs: extractLinks(e.body)
};
extracted.set(s, c);
}
return c.hrefs.flatMap((e) => resolveHref(e, o, r, n) ?? []);
}
/** Where one href leads from a record at path `from`, under the same rules as resolveLinks. */
const resolveLinkHref = (e, t, n, r) => resolveHref(e, t.split("/").slice(0, -1).join("/"), linkIndex(n), r);
//#endregion
//#region extensions/knowledge/src/merge.ts
/** Longest chain of merged pages followed before a redirect is treated as invalid. */
const MAX_MERGE_HOPS = 8;
/** Namespaced aliases such as `discord:123` or `email:a@b.c` identify one entity across sources. */
const IDENTITY_KEY = /^[a-z][a-z0-9_-]*:\S+$/i;
const normalize = (e) => e.normalize("NFKC").trim().replace(/\s+/gu, " ").toLowerCase();
/** Explain why a page's merge metadata cannot be followed; undefined when it is sound or absent. */
function mergeProblem(e, t) {
const n = e.metadata;
if (n.lifecycle !== "merged") return n.merged_into ? "merged_into is only valid on a merged page." : void 0;
if (e.kind !== "page") return "Only pages can be merged.";
if (!n.merged_into) return "A merged page needs merged_into.";
let r = e;
for (let n = 0; n < MAX_MERGE_HOPS; n++) {
const n = t.get(r.metadata.merged_into);
if (!n || n.length !== 1) return "Merge target is missing or ambiguous: " + r.metadata.merged_into;
const o = n[0];
if (o.id === e.id) return "Merge chain forms a cycle.";
if (o.kind !== "page" || o.type !== e.type) return "Merge target must be a page of the same type: " + o.id;
if (o.metadata.lifecycle !== "merged") return;
r = o;
}
return `Merge chain exceeds ${MAX_MERGE_HOPS} hops.`;
}
const redirectCache = /* @__PURE__ */ new WeakMap();
/** Map each valid merged page ID to the final page its chain ends at. */
function mergeRedirects(e) {
const t = redirectCache.get(e);
if (t) return t;
const n = /* @__PURE__ */ new Map();
for (const t of e) n.set(t.id, n.has(t.id) ? null : t);
const r = /* @__PURE__ */ new Map();
for (const t of e) {
if (!t.valid || t.lifecycle !== "merged" || n.get(t.id) !== t) continue;
let e = n.get(t.metadata.merged_into);
for (let t = 1; e && e.lifecycle === "merged" && t < MAX_MERGE_HOPS; t++) e = n.get(e.metadata.merged_into);
if (e && e.lifecycle !== "merged") r.set(t.id, e.id);
}
redirectCache.set(e, r);
return r;
}
/** Page and dependency references a record makes, as authored. */
function referenceIds(e) {
return [
...e.dependencies ?? [],
...e.entities ?? [],
...[
e.from,
e.to,
e.owner
].filter((e) => Boolean(e))
];
}
/** The current view of a record: references to merged pages resolve to their survivors, and
* `redirected` keeps each old → new mapping. Records without such references are returned as is. */
function effectiveRecord(e, t) {
if (!t.size) return e;
const n = {}, r = { ...e.metadata };
const resolve = (e) => {
const r = t.get(e);
if (r) n[e] = r;
return r ?? e;
};
for (const e of [
"owner",
"from",
"to",
"source_page"
]) if (r[e]) r[e] = resolve(r[e]);
for (const e of ["entities", "dependencies"]) if (r[e]) r[e] = [...new Set(r[e].map(resolve))];
if (!Object.keys(n).length) return e;
const o = {
...e,
metadata: r,
redirected: n
};
carryLinkExtraction(e, o);
return o;
}
/** Link candidates for current records, plus the mapping that sends merged pages to their survivors. */
function linkTargets(e, t) {
const n = mergeRedirects(e);
return {
candidates: [...t, ...e.filter((e) => n.has(e.id))],
canonical: (e) => n.get(e) ?? e
};
}
function occurredDay(e) {
const t = e.metadata.occurred_at ?? e.metadata.fields?.occurred_at;
return typeof t === "string" ? t.slice(0, 10) : "";
}
/** Groups of current pages of one type that share an identity-key alias (strong) or a title (weak). Never merges. */
function mergeCandidates(e, t = 100) {
const n = /* @__PURE__ */ new Map();
const add = (e, t, r, o = "") => {
const s = `${e.type}\0${t}\0${normalize(r)}\0${o}`;
const c = n.get(s) ?? {
type: e.type,
key: r,
strength: t,
pages: []
};
if (!c.pages.some((t) => t.id === e.id)) c.pages.push({
id: e.id,
title: e.title
});
n.set(s, c);
};
for (const t of e) {
if (t.kind !== "page" || t.lifecycle !== "active") continue;
for (const e of t.metadata.aliases ?? []) if (IDENTITY_KEY.test(e.trim())) add(t, "identity-key", e.trim());
add(t, "title", t.title, occurredDay(t));
}
const r = [...n.values()].filter((e) => e.pages.length > 1);
const o = new Set(r.filter((e) => e.strength === "identity-key").map((e) => e.pages.map((e) => e.id).toSorted().join("\0")));
return r.filter((e) => e.strength === "identity-key" || !o.has(e.pages.map((e) => e.id).toSorted().join("\0"))).toSorted((e, t) => (e.strength === t.strength ? 0 : e.strength === "identity-key" ? -1 : 1) || e.key.localeCompare(t.key)).slice(0, t);
}
//#endregion
//#region extensions/knowledge/src/page-budget.ts
/**
* Page bodies are budgeted by read cost. A hub page is read whenever an agent
* works on anything connected to it, so its body must fit one default
* knowledge_record read; other pages get two reads. Claims are never budgeted.
*/
const HUB_PAGE_BUDGET_CHARS = TEXT_PAGE_DEFAULT_CHARS;
const PAGE_BUDGET_CHARS = 2 * TEXT_PAGE_DEFAULT_CHARS;
/** Below this many current pages one page spans several percentile points; no hubs. */
const HUB_MIN_PAGES = 20;
/** A hub links with at least this many distinct pages, whatever its percentile. */
const HUB_MIN_DEGREE = 10;
const SECTIONS_REPORTED = 6;
const CANDIDATES_REPORTED = 3;
const chars = Type.Integer({ minimum: 0 });
const Candidate = Type.Object({
id,
title: text(200),
type: text(64),
linked: Type.Boolean({ description: "The section already links to this page." }),
mentions: Type.Integer({ minimum: 0 }),
headroomChars: Type.Integer({ description: "Its budget minus its current size; negative when already over." })
}, { additionalProperties: false });
const SectionReport = Type.Object({
heading: text(200),
level: Type.Integer({
minimum: 1,
maximum: 6
}),
start: chars,
end: chars,
chars,
subsections: Type.Integer({ minimum: 0 }),
candidates: Type.Array(Candidate, {
maxItems: CANDIDATES_REPORTED,
description: "Existing pages connected to this page that the section links to or names. Empty means extract to a new page."
})
}, { additionalProperties: false });
const PageReport = Type.Object({
id: Type.Union([id, Type.Null()], { description: "Null for a page this request would create." }),
title: text(200),
currentChars: chars,
attemptedChars: chars,
budgetChars: chars,
hub: Type.Object({
hub: Type.Boolean(),
degree: Type.Integer({
minimum: 0,
description: "Distinct current pages linked to or from this page by wikilinks or Markdown links."
}),
percentile: Type.Number({ description: "Share of current pages with a lower degree." }),
hubPercentile: Type.Number(),
pages: Type.Integer({ minimum: 0 }),
minPages: Type.Integer(),
minDegree: Type.Integer()
}, { additionalProperties: false }),
sectionsOf: Type.Union([Type.Literal("current"), Type.Literal("attempted")]),
sections: Type.Array(SectionReport, { maxItems: SECTIONS_REPORTED })
}, { additionalProperties: false });
/** Why a rejected receipt saved nothing: the pages whose bodies would grow past their budget. */
const PageBudget = Type.Object({ pages: Type.Array(PageReport, { maxItems: 25 }) }, { additionalProperties: false });
/** ATX headings outside fenced code; each section runs to the next heading of its level or higher. */
function pageSections(e) {
const t = [];
let n;
for (let r = 0; r < e.length;) {
const o = e.indexOf("\n", r), s = o === -1 ? e.length : o;
const c = e.slice(r, s).replace(/\r$/, "");
const u = /^ {0,3}(`{3,}|~{3,})/.exec(c)?.[1];
if (n) {
if (u && u[0] === n[0] && u.length >= n.length && !c.trim().slice(u.length).trim()) n = void 0;
} else if (u) n = u;
else {
const e = /^ {0,3}(#{1,6})(?=[ \t]|$)[ \t]*(.*?)(?:[ \t]+#+)?[ \t]*$/.exec(c);
if (e) t.push({
heading: e[2],
level: e[1].length,
start: r
});
}
r = s + 1;
}
return t.map((n, r) => ({
heading: n.heading,
level: n.level,
start: n.start,
end: t.slice(r + 1).find((e) => e.level <= n.level)?.start ?? e.length
}));
}
/** Undirected page graph of authored body links; typed relationships and claims do not count. */
function linkGraph(e, t) {
const n = new Map(t.filter((e) => e.kind === "page" && e.lifecycle === "active").map((e) => [e.id, e]));
const r = new Map([...n.keys()].map((e) => [e, /* @__PURE__ */ new Set()]));
const o = linkTargets(e, t);
for (const e of n.values()) for (const t of resolveLinks(e, o.candidates, o.canonical)) if (t.id && t.id !== e.id && n.has(t.id)) {
r.get(e.id).add(t.id);
r.get(t.id).add(e.id);
}
return {
pages: n,
neighbours: r,
targets: o,
relationships: t.filter((e) => e.kind === "relationship")
};
}
/** Percentile rank by degree among current pages, with a vault-size and degree floor. */
function hubStatus(e, t, n) {
const r = e.neighbours.get(t)?.size ?? 0, o = e.pages.size;
let s = 0;
for (const t of e.neighbours.values()) s += t.size < r ? 1 : 0;
const c = o ? 100 * s / o : 0;
return {
hub: o >= HUB_MIN_PAGES && r >= HUB_MIN_DEGREE && c >= n,
degree: r,
percentile: Math.floor(c * 10) / 10,
hubPercentile: n,
pages: o,
minPages: HUB_MIN_PAGES,
minDegree: HUB_MIN_DEGREE
};
}
const pageBudget = (e) => e.hub ? HUB_PAGE_BUDGET_CHARS : PAGE_BUDGET_CHARS;
/** Current pages connected to a page by a body link or a typed relationship. */
function connectedPages(e, t) {
const n = new Set(e.neighbours.get(t));
for (const r of e.relationships) {
if (r.metadata.from === t && r.metadata.to) n.add(r.metadata.to);
if (r.metadata.to === t && r.metadata.from) n.add(r.metadata.from);
}
n.delete(t);
return [...n].flatMap((t) => e.pages.get(t) ?? []);
}
const clip = (e, t) => Array.from(e).slice(0, t).join("");
/** Whole-word, case-insensitive mentions of a page's title or aliases of three characters or more. */
function pageMentions(e, t) {
let n = 0;
const r = [t.title, ...t.metadata.aliases ?? []].map((e) => e.trim());
for (const t of new Set(r.filter((e) => e.length >= 3))) {
const r = t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
n += e.match(new RegExp(`(?<![\\p{L}\\p{N}])${r}(?![\\p{L}\\p{N}])`, "giu"))?.length ?? 0;
}
return n;
}
function sectionReports(e, t, n, r) {
const o = pageSections(t), s = connectedPages(n, e.id);
return o.toSorted((e, t) => t.end - t.start - (e.end - e.start) || e.start - t.start).slice(0, SECTIONS_REPORTED).map((c) => {
const u = t.slice(c.start, c.end);
const d = new Set(resolveLinks({
id: e.id,
title: e.title,
path: e.path,
body: u,
metadata: {}
}, n.targets.candidates, n.targets.canonical).flatMap((e) => e.id ? [e.id] : []));
const p = s.map((e) => ({
candidate: e,
linked: d.has(e.id),
mentions: Math.min(999, pageMentions(u, e))
})).filter((e) => e.linked || e.mentions).toSorted((e, t) => Number(t.linked) - Number(e.linked) || t.mentions - e.mentions || e.candidate.title.localeCompare(t.candidate.title)).slice(0, CANDIDATES_REPORTED).map(({ candidate: e, linked: t, mentions: o }) => ({
id: e.id,
title: clip(e.title, 200),
type: clip(e.type, 64),
linked: t,
mentions: o,
headroomChars: pageBudget(hubStatus(n, e.id, r)) - e.body.length
}));
return {
heading: clip(c.heading, 200),
level: c.level,
start: c.start,
end: c.end,
chars: c.end - c.start,
subsections: o.filter((e) => e.start > c.start && e.end <= c.end && e.level > c.level).length,
candidates: p
};
});
}
/**
* One rule for every page-body write: growth past the page's budget is rejected;
* an edit that keeps the body the same size or smaller always passes, so a page
* already over budget can only shrink (the ratchet). Returns undefined to allow.
*/
function pageBudgetRejection(e) {
const t = e.changes.filter(({ before: e, after: t }) => t.kind === "page" && t.body.length > HUB_PAGE_BUDGET_CHARS && t.body.length > (e?.body.length ?? 0));
if (!t.length) return;
const n = linkGraph(e.records, e.current());
const r = t.flatMap(({ before: t, after: r }) => {
const o = hubStatus(n, r.id, e.hubPercentile), s = pageBudget(o);
if (r.body.length <= s) return [];
return [{
id: t ? t.id : null,
title: clip(r.title, 200),
currentChars: t?.body.length ?? 0,
attemptedChars: r.body.length,
budgetChars: s,
hub: o,
sectionsOf: t ? "current" : "attempted",
sections: sectionReports(r, t?.body ?? r.body, n, e.hubPercentile)
}];
});
if (!r.length) return;
const [o] = r;
return {
message: clip(`Nothing was saved: ${o.title} would grow to ${o.attemptedChars} characters, past its ${o.budgetChars}-character ${o.hub.hub ? "hub " : ""}page budget${r.length > 1 ? ` (and ${r.length - 1} more page${r.length > 2 ? "s" : ""})` : ""}. Edits that keep a body the same size or smaller always succeed. Move a whole section to its own page, new or one of the listed connected candidates, with knowledge_extract_section, then retry. Save discrete facts as claims with knowledge_remember. Do not truncate or drop content to fit.`, 1e3),
budget: { pages: r }
};
}
//#endregion
//#region extensions/knowledge/src/directory-sync.ts
/** Keep SQLite publication fences synchronous. Windows may lack directory
* flushing, but fs-safe still verifies the directory and propagates real I/O errors. */
function syncKnowledgeDirectory(e) {
const t = syncDirectorySync(e, { label: "Knowledge directory" });
if (t.status !== "synced" && process.platform !== "win32") throw new Error(`Knowledge directory synchronization unsupported: ${t.code ?? "unknown"}`);
}
//#endregion
//#region extensions/knowledge/src/storage-schema.ts
/** Thrown when a database is not this schema, or was written by a newer Knowledge. */
var UnrecognizedSchema = class extends Error {};
function stampedVersion(e, t) {
if (!tableExists(e, "knowledge_schema")) return;
return executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("knowledge_schema").select("version").where("store", "=", t))?.version;
}
/** Whether a database already carries this schema's latest stamp. */
function isKnowledgeSchemaCurrent(e, t) {
return stampedVersion(e, t.store) === t.steps.at(-1).version;
}
/** Bring a Knowledge database to the latest schema version and stamp it.
* Stores created before stamping are dated by their tables, so existing
* databases keep working; their native header fields are left untouched. */
function ensureKnowledgeSchema(e, t) {
const n = t.steps.at(-1).version;
const r = stampedVersion(e, t.store);
if (r === n) return;
if (r !== void 0 && r > n) throw new UnrecognizedSchema(`Knowledge ${t.store} database uses a newer schema.`);
runSqliteImmediateTransactionSync(e, () => {
const r = stampedVersion(e, t.store) ?? t.detect(e);
if (r === void 0 || r > n) throw new UnrecognizedSchema(`Not a recognized Knowledge ${t.store} database.`);
for (const n of t.steps) if (n.version > r) n.apply(e);
e.exec("CREATE TABLE IF NOT EXISTS knowledge_schema (store TEXT PRIMARY KEY, version INTEGER NOT NULL) STRICT");
executeSqliteQuerySync(e, getNodeSqliteKysely(e).insertInto("knowledge_schema").values({
store: t.store,
version: n
}).onConflict((e) => e.column("store").doUpdateSet({ version: n })));
});
}
//#endregion
//#region extensions/knowledge/src/store-manifest.ts
const uuid = Type.String({ pattern: "^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$" });
/** Store identity file (`vault.json`). The store, not an agent, owns the vault:
* `vaultId` is the immutable physical identity; generation/publicationId fence
* publication, replacement and restore. */
const Manifest = Type.Object({
format: Type.Literal("knowledge-vault-v2"),
vaultId: uuid,
generation: Type.Integer({ minimum: 0 }),
publicationId: uuid
}, { additionalProperties: false });
/** SQLite checkpoint key for a store's manifest. */
const checkpointKey = (e) => `store:${e}`;
//#endregion
//#region extensions/knowledge/src/identity-store.ts
const BUSY_TIMEOUT_MS = 5e3;
const unavailable = () => /* @__PURE__ */ new Error("Knowledge identity checkpoint unavailable; preserve the database and resolve recovery before reading.");
/** Operational database schema. A store written before version stamping is
* dated by its tables; only a zero-byte file is new. In rollback-journal mode
* a database stays zero bytes until its first commit, and a crash during that
* commit is rolled back before `detect` runs under the write lock, so an
* interrupted initialization resumes while a foreign database is refused. */
const stateSchema = (e) => ({
store: "state",
steps: [
{
version: 1,
apply: (e) => e.exec("CREATE TABLE identities (agent_key TEXT PRIMARY KEY, manifest TEXT NOT NULL) STRICT")
},
{
version: 2,
apply: (e) => e.exec(`CREATE TABLE IF NOT EXISTS mutations (
scope TEXT NOT NULL, request TEXT NOT NULL, intent TEXT NOT NULL,
state TEXT NOT NULL, plan TEXT NOT NULL, receipt TEXT NOT NULL,
PRIMARY KEY(scope, request)
) STRICT;
CREATE TABLE IF NOT EXISTS observations (
scope TEXT NOT NULL, id TEXT NOT NULL, path TEXT NOT NULL, hash TEXT NOT NULL,
revision INTEGER NOT NULL, raw TEXT NOT NULL, PRIMARY KEY(scope,id)
) STRICT;
CREATE TABLE IF NOT EXISTS history (
sequence INTEGER PRIMARY KEY, scope TEXT NOT NULL, id TEXT NOT NULL,
provenance TEXT NOT NULL, at TEXT NOT NULL, path TEXT NOT NULL,
revision INTEGER NOT NULL, hash TEXT NOT NULL, raw TEXT NOT NULL
) STRICT;`)
},
{
version: 3,
apply: (e) => e.exec(`CREATE TABLE git_jobs (
sequence INTEGER PRIMARY KEY, scope TEXT NOT NULL, token TEXT NOT NULL UNIQUE,
batch TEXT NOT NULL, state TEXT NOT NULL, commit_id TEXT, message TEXT NOT NULL
) STRICT;
CREATE TABLE git_files (scope TEXT NOT NULL, path TEXT NOT NULL, hash TEXT NOT NULL, PRIMARY KEY(scope,path)) STRICT;`)
},
{
version: 4,
apply: (e) => e.exec(`CREATE TABLE attachment_uploads (
scope TEXT NOT NULL, request TEXT NOT NULL, metadata TEXT NOT NULL,
received INTEGER NOT NULL, receipt TEXT, PRIMARY KEY(scope,request)
) STRICT;
CREATE TABLE attachment_chunks (
scope TEXT NOT NULL, request TEXT NOT NULL, offset INTEGER NOT NULL,
hash TEXT NOT NULL, size INTEGER NOT NULL, final INTEGER NOT NULL, data BLOB,
PRIMARY KEY(scope,request,offset)
) STRICT;`)
},
{
version: 5,
apply: (e) => e.exec("ALTER TABLE history ADD COLUMN agent_id TEXT")
}
],
detect: (t) => {
if (!tableExists(t, "identities")) return statSync(e).size === 0 ? 0 : void 0;
if (!tableExists(t, "mutations")) return 1;
if (!tableExists(t, "git_jobs")) return 2;
if (!tableExists(t, "attachment_uploads")) return 3;
return tableHasColumn(t, "history", "agent_id") ? 5 : 4;
}
});
function installAdditiveTables(e) {
e.exec(`CREATE INDEX IF NOT EXISTS history_record_snapshot ON history(scope,id,hash,revision,provenance,sequence);
CREATE INDEX IF NOT EXISTS history_scope_sequence ON history(scope,sequence);
CREATE INDEX IF NOT EXISTS history_record_sequence ON history(scope,id,sequence);
CREATE TABLE IF NOT EXISTS lifecycle_guards_v1 (binding TEXT NOT NULL, id TEXT NOT NULL, lifecycle TEXT NOT NULL, metadata TEXT NOT NULL, PRIMARY KEY(binding,id)) STRICT;
CREATE TABLE IF NOT EXISTS keyword_withdrawals_v1 (binding TEXT NOT NULL, id TEXT NOT NULL, PRIMARY KEY(binding,id)) STRICT;
CREATE TABLE IF NOT EXISTS keyword_state_v1 (binding TEXT PRIMARY KEY, snapshot TEXT NOT NULL, indexed_at TEXT NOT NULL) STRICT;
CREATE TABLE IF NOT EXISTS recent_requests_v1 (
scope TEXT NOT NULL, request TEXT NOT NULL, operation TEXT, target_id TEXT, at TEXT, reason TEXT, replacement_id TEXT,
PRIMARY KEY(scope,request)
);
CREATE TABLE IF NOT EXISTS recent_records_v1 (
scope TEXT NOT NULL, request TEXT NOT NULL, ordinal INTEGER NOT NULL, id TEXT, hash TEXT, revision, actor TEXT, kind TEXT, type TEXT, title TEXT,
PRIMARY KEY(scope,request,ordinal)
);
CREATE TABLE IF NOT EXISTS session_activity (
sequence INTEGER PRIMARY KEY, scope TEXT NOT NULL, agent_id TEXT NOT NULL,
session_key TEXT NOT NULL, session_id TEXT NOT NULL, call_id TEXT NOT NULL,
operation TEXT NOT NULL, action TEXT NOT NULL, at TEXT NOT NULL,
record_id TEXT NOT NULL, revision INTEGER NOT NULL,
UNIQUE(scope,agent_id,session_id,call_id,operation,action,record_id,revision)
) STRICT;
CREATE INDEX IF NOT EXISTS session_activity_session ON session_activity(scope,agent_id,session_key,session_id,sequence);`);
}
/** Physical databases (device:inode) this thread has admitted. */
const admitted = /* @__PURE__ */ new Set();
/** Short-lived connections: no native handles survive a query or plugin reload.
* Schema, index and table checks run once per physical database per thread,
* not per connection. */
var SqliteIdentityStore = class {
constructor(e) {
this.filename = e;
}
withDatabase(e) {
let t = false;
try {
if (realpathSync(path.dirname(this.filename)) !== path.dirname(this.filename)) throw unavailable();
const e = openSync(this.filename, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 384);
closeSync(e);
t = true;
} catch (e) {
if (e.code !== "EEXIST") throw unavailable();
}
const n = lstatSync(this.filename);
if (!n.isFile() || n.isSymbolicLink() || n.nlink !== 1) throw unavailable();
const r = openNodeSqliteDatabase(this.filename, { timeout: BUSY_TIMEOUT_MS });
try {
const o = lstatSync(this.filename);
if (n.dev !== o.dev || n.ino !== o.ino || o.nlink !== 1) throw unavailable();
const s = `${o.dev}:${o.ino}`;
if (t || !admitted.has(s) || !isKnowledgeSchemaCurrent(r, stateSchema(this.filename))) {
this.admit(r, t);
admitted.add(s);
}
return e(r);
} finally {
r.close();
}
}
admit(e, t) {
try {
ensureKnowledgeSchema(e, stateSchema(this.filename));
} catch (e) {
throw e instanceof UnrecognizedSchema ? unavailable() : e;
}
if (t) syncKnowledgeDirectory(path.dirname(this.filename));
installAdditiveTables(e);
}
async lookup(e) {
return this.withDatabase((t) => {
const n = t.prepare("SELECT manifest FROM identities WHERE agent_key = ?").get(e);
if (!n) return;
const r = JSON.parse(String(n.manifest));
if (!Check(Manifest, r)) throw unavailable();
return r;
});
}
async registerIfAbsent(e, t) {
if (!Check(Manifest, t)) throw unavailable();
return this.withDatabase((n) => registerIdentity(n, e, JSON.stringify(t)));
}
};
/** Record an identity checkpoint unless one already exists; true when this call wrote it. */
function registerIdentity(e, t, n) {
return executeSqliteQuerySync(e, getNodeSqliteKysely(e).insertInto("identities").values({
agent_key: t,
manifest: n
}).onConflict((e) => e.doNothing())).numAffectedRows === 1n;
}
//#endregion
export { TEXT_PAGE_DEFAULT_CHARS as A, name as B, resolveLinkHref as C, RECORD_MAX_BYTES as D, BODY_INPUT_MAX_CHARS as E, Field as F, text as H, Recall as I, RecordAnnotations as L, Definition as M, Envelope as N, RECORD_RESPONSE_MAX_BYTES as O, Evidence as P, approvedRecall as R, linkSpans as S, AUXILIARY_MAX_BYTES as T, strings as V, mergeCandidates as _, UnrecognizedSchema as a, referenceIds as b, HUB_PAGE_BUDGET_CHARS as c, connectedPages as d, linkGraph as f, linkTargets as g, effectiveRecord as h, checkpointKey as i, TEXT_PAGE_MAX_CHARS as j, SEARCH_HIGHLIGHT_MAX_BYTES as k, PAGE_BUDGET_CHARS as l, pageSections as m, registerIdentity as n, ensureKnowledgeSchema as o, pageBudgetRejection as p, Manifest as r, syncKnowledgeDirectory as s, SqliteIdentityStore as t, PageBudget as u, mergeProblem as v, resolveLinks as w, carryLinkExtraction as x, mergeRedirects as y, id as z };