context-mode 2.0.0-next.15 → 2.0.0-next.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,6 +33,7 @@ function REPLACE_HANDLE_LINE(intent, handle, bytes4, prefix = "", asked = "") {
33
33
  var HANDLE_PROMPT_WORDS = 3;
34
34
  var MAX_CHUNK_BYTES = 4096;
35
35
  var SEARCH_PAGE_SIZE = 20;
36
+ var SEARCH_REPLY_HITS = 5;
36
37
  var SNIPPET_MAX_BYTES = 800;
37
38
  var SNIPPET_CODE_MAX_BYTES = 2048;
38
39
  var MAX_CANDIDATES = 85;
@@ -358,7 +359,7 @@ var DECISION_OPTION_KEY = "option";
358
359
  var DECISION_LABEL_JOIN = " | ";
359
360
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
360
361
  var RELEASE_BRANCH = "release";
361
- var BUNDLE_SHA = true ? "5ef1f1894d68b94c068a7c7afe5c1203fcb78624" : void 0;
362
+ var BUNDLE_SHA = true ? "d526f1e54835a809b09257c9587a22172141d4c3" : void 0;
362
363
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
363
364
  var DOCTOR_LABEL = Object.freeze({
364
365
  D1: "version",
@@ -2313,8 +2314,8 @@ function jqPath(s) {
2313
2314
  }
2314
2315
  return true;
2315
2316
  }
2316
- function jqWhitelisted(filter) {
2317
- const s = filter.trim();
2317
+ function jqWhitelisted(filter2) {
2318
+ const s = filter2.trim();
2318
2319
  if (s === JQ_WHITELIST.identity || s === JQ_WHITELIST.length) return true;
2319
2320
  const bar = s.indexOf(JQ_WHITELIST.pipeLength.charAt(0));
2320
2321
  if (bar < 0) return jqPath(s);
@@ -3171,15 +3172,15 @@ function matchesAnyDenyPattern(text, patterns, subject = BASH_SUBJECT) {
3171
3172
  // src/prompt/_generated.ts
3172
3173
  var INSTRUCTIONS = "context-mode keeps large output out of the conversation.\n\nWhen a step counts, sums, filters or finds something in over about 20 lines of data (logs, test or build output, big JSON or CSV, long files, web pages), use ctx_execute and print only the answer, not a raw Bash or Read result.\n\nA large tool result is indexed and cut to its best-matching parts; ctx_search finds the rest. A large file's Read is denied: use offset and limit, or ctx_execute with file set. Use normal tools for small output and edits.\n";
3173
3174
  var TOOL_DESCRIPTIONS = Object.freeze({
3174
- ctx_execute: "Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.\n",
3175
- ctx_batch: "Runs several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.",
3176
- ctx_index: "Stores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.",
3177
- ctx_search: "Searches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.",
3178
- ctx_resume: "Returns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",
3179
- ctx_stats: "Reports how many bytes context-mode kept out of the conversation in this session and in this project, per agent, as a Markdown table. Show the table to the user as it is. Use it when the user asks what context-mode saved.",
3180
- ctx_doctor: "Checks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause and the fix in one line. It changes nothing. Use it when the user asks whether context-mode works, or after a context-mode error.",
3181
- ctx_upgrade: "Updates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",
3182
- ctx_purge: "Deletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data."
3175
+ ctx_execute: 'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nRuns code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',
3176
+ ctx_batch: 'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',
3177
+ ctx_index: 'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',
3178
+ ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',
3179
+ ctx_resume: "Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",
3180
+ ctx_stats: "Example: `ctx_stats({})`. Required: none.\nReports how many bytes context-mode kept out of the conversation in this session and in this project, per agent, as a Markdown table. Show the table to the user as it is. Use it when the user asks what context-mode saved.",
3181
+ ctx_doctor: "Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause and the fix in one line. It changes nothing. Use it when the user asks whether context-mode works, or after a context-mode error.",
3182
+ ctx_upgrade: "Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",
3183
+ ctx_purge: 'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'
3183
3184
  });
3184
3185
  var READ_DENY_TEMPLATE = 'context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';
3185
3186
 
@@ -3211,7 +3212,7 @@ var ALLOW = Object.freeze({ kind: "allow" });
3211
3212
  var deny = (reason) => ({ kind: "deny", reason });
3212
3213
  var str = (v) => typeof v === "string" ? v : void 0;
3213
3214
  var present = (v) => v !== void 0 && v !== null;
3214
- var has = (list3, v) => list3.includes(v);
3215
+ var has = (list4, v) => list4.includes(v);
3215
3216
  function decide(ev, row5, userDeny) {
3216
3217
  const tool = ev.tool;
3217
3218
  if (tool === void 0) return ALLOW;
@@ -4228,7 +4229,7 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
4228
4229
  if (blocks.length === 0) return clipLine(row5, 0, row5.length, -1, maxBytes);
4229
4230
  const lower = row5.toLowerCase();
4230
4231
  const hay = lower.length === row5.length ? lower : row5;
4231
- const find = (t) => {
4232
+ const find2 = (t) => {
4232
4233
  const out = [];
4233
4234
  if (t.text === "") return out;
4234
4235
  for (let p = hay.indexOf(t.text); p >= 0 && out.length < MAX_POSITIONS; p = hay.indexOf(t.text, p + 1)) {
@@ -4238,10 +4239,10 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
4238
4239
  return out;
4239
4240
  };
4240
4241
  let terms = given;
4241
- let pos = terms.map(find);
4242
+ let pos = terms.map(find2);
4242
4243
  if (pos.every((p) => p.length === 0)) {
4243
4244
  terms = given.filter((t) => t.text.length >= 5).map((t) => ({ ...t, text: t.text.slice(0, Math.max(4, t.text.length - 2)) }));
4244
- pos = terms.map(find);
4245
+ pos = terms.map(find2);
4245
4246
  }
4246
4247
  const count = (ti, a, b) => {
4247
4248
  const ps = pos[ti];
@@ -6025,6 +6026,8 @@ RETURNING id`;
6025
6026
  var INSERT_CHUNK = `
6026
6027
  INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`;
6027
6028
  var TITLE_WEIGHT = 1;
6029
+ var RAW_LABEL_SUFFIX = " (raw)";
6030
+ var NOT_RAW = `AND (:source IS NOT NULL OR substr(s.label, -${RAW_LABEL_SUFFIX.length}) <> '${RAW_LABEL_SUFFIX}')`;
6028
6031
  var PORTER_MATCH = `
6029
6032
  SELECT chunks.rowid AS rid, chunks.source_id AS source_id, chunks.session_id AS session_id,
6030
6033
  chunks.worktree AS worktree, chunks.ord AS ord, s.created_ts AS created_ts,
@@ -6034,7 +6037,8 @@ var PORTER_MATCH = `
6034
6037
  WHERE chunks MATCH :match
6035
6038
  AND (:scope <> 'session' OR chunks.session_id = :session_id)
6036
6039
  AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
6037
- AND (:source IS NULL OR s.label = :source)`;
6040
+ AND (:source IS NULL OR s.label = :source)
6041
+ ${NOT_RAW}`;
6038
6042
  var PORTER_ORDER = `
6039
6043
  ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`;
6040
6044
  var PORTER_RANK_PROJECT = `
@@ -6062,6 +6066,7 @@ WHERE chunks_tri MATCH :match
6062
6066
  AND (:scope <> 'session' OR c.session_id = :session_id)
6063
6067
  AND (:scope <> 'worktree' OR c.worktree = :worktree)
6064
6068
  AND (:source IS NULL OR s.label = :source)
6069
+ ${NOT_RAW}
6065
6070
  ORDER BY bm25(chunks_tri, 1.0, ${TITLE_WEIGHT}) ASC, c.source_id DESC, c.ord ASC`;
6066
6071
  var PAGE_ROWS = `
6067
6072
  SELECT c.rowid AS rid, c.source_id AS source_id, c.ord AS ord, c.body AS body, s.label AS label
@@ -6336,16 +6341,16 @@ function typoTerms(db, words) {
6336
6341
  function ftsQuery(db, q, scope, ctx, sessionId, limit, offset, source) {
6337
6342
  const terms = searchTerms(q);
6338
6343
  if (terms.length === 0) return [];
6339
- const filter = { scope, session_id: sessionId, worktree: ctx.worktree, source: source ?? null };
6344
+ const filter2 = { scope, session_id: sessionId, worktree: ctx.worktree, source: source ?? null };
6340
6345
  const rrf = scope === "project" ? { k: RRF_K } : {};
6341
- const porter = (t) => stmt(db.raw, porterRankSql(scope)).all({ ...filter, match: t.join(" OR "), all: t.join(" "), ...rrf });
6346
+ const porter = (t) => stmt(db.raw, porterRankSql(scope)).all({ ...filter2, match: t.join(" OR "), all: t.join(" "), ...rrf });
6342
6347
  let pList = porter(terms);
6343
6348
  if (pList.length === 0) {
6344
6349
  const fixed = typoTerms(db, terms.map((t) => t.slice(1, -2).replaceAll('""', '"')));
6345
6350
  if (fixed !== null) pList = porter(fixed);
6346
6351
  }
6347
6352
  const tm = trigramMatch(q);
6348
- const tList = tm === "" ? [] : stmt(db.raw, TRI_RANK).all({ ...filter, match: tm });
6353
+ const tList = tm === "" ? [] : stmt(db.raw, TRI_RANK).all({ ...filter2, match: tm });
6349
6354
  const fused = /* @__PURE__ */ new Map();
6350
6355
  pList.forEach((r, i) => fused.set(Number(r.rid), { r, s: 1 / (RRF_K + i + 1), full: Number(r.full ?? 0), p: i }));
6351
6356
  tList.forEach((r, i) => {
@@ -6443,7 +6448,7 @@ function timelineOrder(a, b) {
6443
6448
  return pa < pb ? -1 : pa > pb ? 1 : 0;
6444
6449
  }
6445
6450
  function ftsQueryTimeline(db, scope, ctx, sessionId, limit, after, source, memory) {
6446
- const filter = {
6451
+ const filter2 = {
6447
6452
  scope,
6448
6453
  session_id: sessionId,
6449
6454
  worktree: ctx.worktree,
@@ -6453,7 +6458,7 @@ function ftsQueryTimeline(db, scope, ctx, sessionId, limit, after, source, memor
6453
6458
  const reserved = DECISION_SOURCE;
6454
6459
  const off = limit - 1;
6455
6460
  const merged = [];
6456
- for (const e of db.raw.prepare(TL_EVENTS).all({ ...filter, after: from, off })) {
6461
+ for (const e of db.raw.prepare(TL_EVENTS).all({ ...filter2, after: from, off })) {
6457
6462
  merged.push({
6458
6463
  origin: "session",
6459
6464
  ts: Number(e.created_at),
@@ -6464,7 +6469,7 @@ function ftsQueryTimeline(db, scope, ctx, sessionId, limit, after, source, memor
6464
6469
  text: e.body ?? e.key ?? e.path ?? ""
6465
6470
  });
6466
6471
  }
6467
- const srcRows = db.raw.prepare(TL_SOURCES).all({ ...filter, after: from, off, reserved });
6472
+ const srcRows = db.raw.prepare(TL_SOURCES).all({ ...filter2, after: from, off, reserved });
6468
6473
  if (srcRows.length > 0) {
6469
6474
  const bodies = /* @__PURE__ */ new Map();
6470
6475
  const ids = JSON.stringify(srcRows.map((r) => Number(r.id)));
@@ -6488,7 +6493,7 @@ function ftsQueryTimeline(db, scope, ctx, sessionId, limit, after, source, memor
6488
6493
  const rows = merged.slice(0, end);
6489
6494
  if (rows.length === 0) return { rows, more: false };
6490
6495
  if (merged.length > end) return { rows, more: true };
6491
- const res = db.raw.prepare(TL_MORE).get({ ...filter, after: rows[rows.length - 1].ts, reserved });
6496
+ const res = db.raw.prepare(TL_MORE).get({ ...filter2, after: rows[rows.length - 1].ts, reserved });
6492
6497
  return { rows, more: Number(res.more) === 1 };
6493
6498
  }
6494
6499
  var RANK_DDL = `CREATE VIRTUAL TABLE r USING fts5(body, ${FTS_TOKENIZE}, content='')`;
@@ -6612,8 +6617,8 @@ function make(section, row5, text, repeatCount, query) {
6612
6617
  if (bytes4 < 1) throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");
6613
6618
  return { section, seq: row5.seq, turn: row5.turn, text, bytes: bytes4, repeatCount, pinned: section === "last_request", query };
6614
6619
  }
6615
- function capSection(list3) {
6616
- return list3.length > MAX_CANDIDATES ? list3.slice(list3.length - MAX_CANDIDATES) : list3;
6620
+ function capSection(list4) {
6621
+ return list4.length > MAX_CANDIDATES ? list4.slice(list4.length - MAX_CANDIDATES) : list4;
6617
6622
  }
6618
6623
  function emptySet() {
6619
6624
  return { lastRequest: null, openErrors: [], changedFiles: [], decisions: [], earlierRequests: [], indexedSources: [] };
@@ -6962,10 +6967,10 @@ function lineBlocks(src, md) {
6962
6967
  heading = void 0;
6963
6968
  fenceInfo = void 0;
6964
6969
  };
6965
- const add = (from, to, table) => {
6970
+ const add = (from, to, table2) => {
6966
6971
  if (start < 0) start = from;
6967
6972
  end = to;
6968
- inTable = table;
6973
+ inTable = table2;
6969
6974
  };
6970
6975
  let pos = 0;
6971
6976
  while (pos <= src.length) {
@@ -6986,9 +6991,9 @@ function lineBlocks(src, md) {
6986
6991
  } else {
6987
6992
  const opener = md ? fenceOf(line) : "";
6988
6993
  const head = md && opener === "" ? headingOf(line) : void 0;
6989
- const table = md && opener === "" && head === void 0 && line.includes("|");
6990
- if (md && start >= 0 && (table !== inTable || opener !== "" || head !== void 0)) close();
6991
- add(pos, eol, table);
6994
+ const table2 = md && opener === "" && head === void 0 && line.includes("|");
6995
+ if (md && start >= 0 && (table2 !== inTable || opener !== "" || head !== void 0)) close();
6996
+ add(pos, eol, table2);
6992
6997
  fence = opener;
6993
6998
  if (opener !== "") fenceInfo = { fence: opener, openEnd: eol, closeStart: -1 };
6994
6999
  if (head !== void 0) {
@@ -7695,8 +7700,8 @@ function nodeTooOld(version2) {
7695
7700
  }
7696
7701
  return false;
7697
7702
  }
7698
- function has2(list3, name) {
7699
- return list3 !== void 0 && list3.some((n) => n.toLowerCase() === name);
7703
+ function has2(list4, name) {
7704
+ return list4 !== void 0 && list4.some((n) => n.toLowerCase() === name);
7700
7705
  }
7701
7706
  function kindOf(row5, name) {
7702
7707
  const n = name.toLowerCase();
@@ -19606,15 +19611,19 @@ function callText(queries, scope, source, cursor) {
19606
19611
  function decisionQueries(input) {
19607
19612
  return input.source === DECISION_SOURCE && input.queries.length === 0 ? [""] : input.queries;
19608
19613
  }
19614
+ function pageSize(input) {
19615
+ return input.source === DECISION_SOURCE ? SEARCH_PAGE_SIZE : SEARCH_REPLY_HITS;
19616
+ }
19609
19617
  function page(db, q, input, scope, ctx, offset) {
19618
+ const size = pageSize(input);
19610
19619
  if (input.source === DECISION_SOURCE && q.trim() === "") {
19611
- return ftsListSource(db, DECISION_SOURCE, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, offset);
19620
+ return ftsListSource(db, DECISION_SOURCE, scope, ctx.project, ctx.sessionId, size, offset);
19612
19621
  }
19613
- const hits = ftsQuery(db, q, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, offset, input.source);
19622
+ const hits = ftsQuery(db, q, scope, ctx.project, ctx.sessionId, size, offset, input.source);
19614
19623
  if (hits.length > 0 || input.source === void 0) return hits;
19615
19624
  const any2 = offset === 0 ? hits : ftsQuery(db, q, scope, ctx.project, ctx.sessionId, 1, 0, input.source);
19616
19625
  if (any2.length > 0) return hits;
19617
- return ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, offset);
19626
+ return ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, size, offset);
19618
19627
  }
19619
19628
  var JSON_ROWS_PAGE = 5;
19620
19629
  var JSON_SOURCE_MAX_BYTES = 8 * 1024 * 1024;
@@ -19658,12 +19667,13 @@ function jsonRowsReply(db, input, scope, ctx) {
19658
19667
  function relevance(db, given, scope, ctx) {
19659
19668
  const input = { ...given, queries: decisionQueries(given) };
19660
19669
  const offset = input.offset ?? 0;
19670
+ const size = pageSize(input);
19661
19671
  const seen = /* @__PURE__ */ new Set();
19662
19672
  const entries = [];
19663
19673
  const full = /* @__PURE__ */ new Set();
19664
19674
  input.queries.forEach((q, qi) => {
19665
19675
  const hits = page(db, q, input, scope, ctx, offset);
19666
- if (hits.length === SEARCH_PAGE_SIZE) full.add(qi);
19676
+ if (hits.length === size) full.add(qi);
19667
19677
  hits.forEach((hit, i) => {
19668
19678
  const key = hit.sourceId + ":" + hit.ord;
19669
19679
  if (seen.has(key)) return;
@@ -19674,7 +19684,7 @@ function relevance(db, given, scope, ctx) {
19674
19684
  if (entries.length === 0) return zeroHits(db, scope, ctx, input.source);
19675
19685
  const moreLine3 = (q, pos) => "More: " + callText([q], scope, input.source, "offset:" + pos);
19676
19686
  let reserve = 0;
19677
- for (const q of input.queries) reserve += bytes2(moreLine3(q, offset + SEARCH_PAGE_SIZE)) + 1;
19687
+ for (const q of input.queries) reserve += bytes2(moreLine3(q, offset + size)) + 1;
19678
19688
  const lines = [];
19679
19689
  const more = [];
19680
19690
  let used = 0;
@@ -19698,7 +19708,7 @@ function relevance(db, given, scope, ctx) {
19698
19708
  lines.push(line);
19699
19709
  used += bytes2(line) + 1;
19700
19710
  }
19701
- if (!stopped && full.has(qi)) more.push(moreLine3(q, offset + SEARCH_PAGE_SIZE));
19711
+ if (!stopped && full.has(qi)) more.push(moreLine3(q, offset + size));
19702
19712
  });
19703
19713
  return reply(lines.concat(more).join("\n"), false);
19704
19714
  }
@@ -21918,17 +21928,17 @@ function generateConvertTOMLValue(convertValue) {
21918
21928
  return baseTable;
21919
21929
  },
21920
21930
  TOMLTable(node, baseTable = {}) {
21921
- const table = getTable(baseTable, resolveValue(node.key), node.kind === "array");
21922
- for (const body of node.body) resolveValue(body, table);
21931
+ const table2 = getTable(baseTable, resolveValue(node.key), node.kind === "array");
21932
+ for (const body of node.body) resolveValue(body, table2);
21923
21933
  return baseTable;
21924
21934
  },
21925
21935
  TOMLArray(node) {
21926
21936
  return node.elements.map((e) => resolveValue(e));
21927
21937
  },
21928
21938
  TOMLInlineTable(node) {
21929
- const table = {};
21930
- for (const body of node.body) resolveValue(body, table);
21931
- return table;
21939
+ const table2 = {};
21940
+ for (const body of node.body) resolveValue(body, table2);
21941
+ return table2;
21932
21942
  },
21933
21943
  TOMLKey(node) {
21934
21944
  return node.keys.map((key) => resolveValue(key));
@@ -22471,8 +22481,8 @@ function listTarget(key, own2, v1, alt = []) {
22471
22481
  return {
22472
22482
  key: [key],
22473
22483
  next(current) {
22474
- const list3 = Array.isArray(current) ? current.filter((x) => x !== v1) : [];
22475
- return list3.includes(own2) || alt.some((a) => list3.includes(a)) ? list3 : [...list3, own2];
22484
+ const list4 = Array.isArray(current) ? current.filter((x) => x !== v1) : [];
22485
+ return list4.includes(own2) || alt.some((a) => list4.includes(a)) ? list4 : [...list4, own2];
22476
22486
  }
22477
22487
  };
22478
22488
  }
@@ -24100,216 +24110,4041 @@ async function safeFetch(url2, signal) {
24100
24110
  }
24101
24111
  }
24102
24112
 
24103
- // src/core/tools/index.ts
24104
- var ctxIndexSchema = external_exports.object({
24105
- path: external_exports.string().optional(),
24106
- content: external_exports.string().optional(),
24107
- url: external_exports.string().optional(),
24108
- source: external_exports.string().optional()
24109
- }, { error: unknownField }).strict();
24110
- var INPUT_FIELDS = ["path", "content", "url"];
24111
- var EXT_KIND = Object.freeze({ ".md": "md", ".html": "html", ".htm": "html" });
24112
- var TYPE_KIND = Object.freeze({ "text/html": "html", "text/markdown": "md" });
24113
- var DEFAULT_CONTENT_LABEL = "content";
24114
- var utf8 = new TextDecoder("utf-8", { fatal: true });
24115
- function userLabel(label) {
24116
- return label === DECISION_SOURCE ? DECISION_USER_LABEL : label;
24117
- }
24118
- function kindOfPath(p) {
24119
- return EXT_KIND[extname(p).toLowerCase()] ?? "text";
24120
- }
24121
- function kindOfType(contentType) {
24122
- const semi = contentType.indexOf(";");
24123
- const media = (semi < 0 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
24124
- return TYPE_KIND[media] ?? "text";
24113
+ // node_modules/entities/dist/decode-codepoint.js
24114
+ var c1 = [
24115
+ 8364,
24116
+ 0,
24117
+ 8218,
24118
+ 402,
24119
+ 8222,
24120
+ 8230,
24121
+ 8224,
24122
+ 8225,
24123
+ 710,
24124
+ 8240,
24125
+ 352,
24126
+ 8249,
24127
+ 338,
24128
+ 0,
24129
+ 381,
24130
+ 0,
24131
+ 0,
24132
+ 8216,
24133
+ 8217,
24134
+ 8220,
24135
+ 8221,
24136
+ 8226,
24137
+ 8211,
24138
+ 8212,
24139
+ 732,
24140
+ 8482,
24141
+ 353,
24142
+ 8250,
24143
+ 339,
24144
+ 0,
24145
+ 382,
24146
+ 376
24147
+ ];
24148
+ function isInvalidCodePoint(codePoint) {
24149
+ return codePoint === 0 || codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111;
24125
24150
  }
24126
- function readUtf8(absPath) {
24127
- try {
24128
- return utf8.decode(readFileSync13(absPath));
24129
- } catch {
24130
- return void 0;
24151
+ function replaceCodePoint(codePoint) {
24152
+ if (isInvalidCodePoint(codePoint)) {
24153
+ return 65533;
24131
24154
  }
24155
+ if (codePoint >= 128 && codePoint <= 159) {
24156
+ return c1[codePoint - 128] || codePoint;
24157
+ }
24158
+ return codePoint;
24132
24159
  }
24133
- function missingOrOutside(given, abs, root) {
24134
- let dir = abs;
24135
- while (!existsSync12(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
24136
- if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
24137
- return new CtxError("OUTSIDE_ROOT", { p: given, root });
24160
+ function replaceCodePointXML(codePoint) {
24161
+ return isInvalidCodePoint(codePoint) ? 65533 : codePoint;
24138
24162
  }
24139
- function pathItems(input, project) {
24140
- const abs = resolve5(project.worktree, input.path);
24141
- if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
24142
- const base = relative3(project.worktree, abs);
24143
- if (statSync6(abs).isDirectory()) {
24144
- return walkDir(abs, project.containmentRoot).map((f) => ({
24145
- sourceKind: "path",
24146
- label: join16(base, f.relPath),
24147
- kind: kindOfPath(f.relPath),
24148
- read: () => readUtf8(f.absPath)
24149
- }));
24163
+
24164
+ // node_modules/entities/dist/internal/decode-shared.js
24165
+ var BASE91_INVERSE = /* @__PURE__ */ (() => {
24166
+ const table2 = new Uint8Array(127);
24167
+ let code = 0;
24168
+ for (let char = 33; char <= 126; char++) {
24169
+ if (char !== 34 && char !== 36 && char !== 92) {
24170
+ table2[char] = code++;
24171
+ }
24172
+ }
24173
+ return table2;
24174
+ })();
24175
+ function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCount, dictSize) {
24176
+ const base = 91;
24177
+ const inputLength = input.length;
24178
+ const twoCharBias = dictSize * (base - 1);
24179
+ let pos = 0;
24180
+ const readSlotCode = () => {
24181
+ const c12 = BASE91_INVERSE[input.charCodeAt(pos++)];
24182
+ return c12 < dictSize ? c12 : c12 * base - twoCharBias + BASE91_INVERSE[input.charCodeAt(pos++)];
24183
+ };
24184
+ const dict2AtomCount = atomCount - dict1AtomCount;
24185
+ const slotCount = atomCount + ngramCount;
24186
+ const single = new Int32Array(slotCount);
24187
+ single.fill(-1, dict1AtomCount, dictSize);
24188
+ single.fill(-1, dictSize + dict2AtomCount, slotCount);
24189
+ const start = new Int32Array(slotCount);
24190
+ const length = new Int32Array(slotCount);
24191
+ function decodeDelta(count, off) {
24192
+ let previous = 0;
24193
+ let slot = off;
24194
+ const end = off + count;
24195
+ while (slot < end) {
24196
+ const code = BASE91_INVERSE[input.charCodeAt(pos++)];
24197
+ if (code < 89) {
24198
+ previous += code;
24199
+ single[slot++] = previous;
24200
+ } else if (code === 89) {
24201
+ let runLength = BASE91_INVERSE[input.charCodeAt(pos++)] + 2;
24202
+ while (runLength--)
24203
+ single[slot++] = ++previous;
24204
+ } else {
24205
+ const next = BASE91_INVERSE[input.charCodeAt(pos++)];
24206
+ previous += 89 + // eslint-disable-next-line unicorn/prefer-minimal-ternary -- branches read a different number of side-effecting input bytes
24207
+ (next < 90 ? next * base + BASE91_INVERSE[input.charCodeAt(pos++)] : BASE91_INVERSE[input.charCodeAt(pos++)] * 8281 + BASE91_INVERSE[input.charCodeAt(pos++)] * base + BASE91_INVERSE[input.charCodeAt(pos++)]);
24208
+ single[slot++] = previous;
24209
+ }
24210
+ }
24211
+ }
24212
+ decodeDelta(dict1AtomCount, 0);
24213
+ decodeDelta(dict2AtomCount, dictSize);
24214
+ const references = new Int32Array(ngramCount * 2);
24215
+ let poolSize = 0;
24216
+ let ngramIndex = 0;
24217
+ function readNgramReferences(count, startSlot) {
24218
+ for (let index = 0; index < count; index++) {
24219
+ const slot = startSlot + index;
24220
+ const a = readSlotCode();
24221
+ const b = readSlotCode();
24222
+ references[ngramIndex * 2] = a;
24223
+ references[ngramIndex * 2 + 1] = b;
24224
+ ngramIndex += 1;
24225
+ start[slot] = poolSize;
24226
+ const entryLength = (single[a] < 0 ? length[a] : 1) + (single[b] < 0 ? length[b] : 1);
24227
+ length[slot] = entryLength;
24228
+ poolSize += entryLength;
24229
+ }
24230
+ }
24231
+ readNgramReferences(ngramCount - dictSize + dict1AtomCount, dictSize + dict2AtomCount);
24232
+ readNgramReferences(dictSize - dict1AtomCount, dict1AtomCount);
24233
+ const pool = new Uint16Array(poolSize);
24234
+ let write2 = 0;
24235
+ for (let index = 0; index < ngramIndex; index++) {
24236
+ for (let half = 0; half < 2; half++) {
24237
+ const source = references[index * 2 + half];
24238
+ const value = single[source];
24239
+ if (value < 0) {
24240
+ let read3 = start[source];
24241
+ const readEnd = read3 + length[source];
24242
+ while (read3 < readEnd)
24243
+ pool[write2++] = pool[read3++];
24244
+ } else {
24245
+ pool[write2++] = value;
24246
+ }
24247
+ }
24150
24248
  }
24151
- return [{ sourceKind: "path", label: base === "" ? input.path : base, kind: kindOfPath(abs), read: () => readUtf8(abs) }];
24249
+ const out = new Uint16Array(resultLength);
24250
+ let outIndex = 0;
24251
+ while (pos < inputLength) {
24252
+ let slot = BASE91_INVERSE[input.charCodeAt(pos++)];
24253
+ if (slot >= dictSize) {
24254
+ slot = slot * base - twoCharBias + BASE91_INVERSE[input.charCodeAt(pos++)];
24255
+ }
24256
+ const value = single[slot];
24257
+ if (value < 0) {
24258
+ let read3 = start[slot];
24259
+ const readEnd = read3 + length[slot];
24260
+ while (read3 < readEnd)
24261
+ out[outIndex++] = pool[read3++];
24262
+ } else {
24263
+ out[outIndex++] = value;
24264
+ }
24265
+ }
24266
+ return out;
24152
24267
  }
24153
- async function itemsOf(input, ctx) {
24154
- if (input.content !== void 0) {
24155
- const text2 = input.content;
24156
- const label2 = input.source ?? DEFAULT_CONTENT_LABEL;
24157
- const kind = hasMdStructure(text2) ? "md" : "text";
24158
- return { items: [{ sourceKind: "content", label: label2, kind, read: () => text2 }], from: label2 };
24268
+
24269
+ // node_modules/entities/dist/generated/decode-data-html.js
24270
+ var htmlDecodeTree = /* @__PURE__ */ decodeTrieDict("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}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js
24273
+ var xmlDecodeTree = /* @__PURE__ */ new Uint16Array([
24274
+ 512,
24275
+ 26465,
24276
+ 29036,
24277
+ 7,
24278
+ 0,
24279
+ 2,
24280
+ 4,
24281
+ 116,
24282
+ 24638,
24283
+ 116,
24284
+ 24636,
24285
+ 8693,
24286
+ 29807,
24287
+ 24610,
24288
+ 621,
24289
+ 1,
24290
+ 0,
24291
+ 0,
24292
+ 3,
24293
+ 112,
24294
+ 24614,
24295
+ 111,
24296
+ 115,
24297
+ 24615
24298
+ ]);
24299
+
24300
+ // node_modules/entities/dist/internal/bin-trie-flags.js
24301
+ var BinTrieFlags;
24302
+ (function(BinTrieFlags2) {
24303
+ BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
24304
+ BinTrieFlags2[BinTrieFlags2["FLAG13"] = 8192] = "FLAG13";
24305
+ BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 8064] = "BRANCH_LENGTH";
24306
+ BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
24307
+ BinTrieFlags2[BinTrieFlags2["VALUE_MASK"] = 8191] = "VALUE_MASK";
24308
+ })(BinTrieFlags || (BinTrieFlags = {}));
24309
+
24310
+ // node_modules/entities/dist/decode.js
24311
+ var CharCodes;
24312
+ (function(CharCodes3) {
24313
+ CharCodes3[CharCodes3["AMP"] = 38] = "AMP";
24314
+ CharCodes3[CharCodes3["NUM"] = 35] = "NUM";
24315
+ CharCodes3[CharCodes3["SEMI"] = 59] = "SEMI";
24316
+ CharCodes3[CharCodes3["EQUALS"] = 61] = "EQUALS";
24317
+ CharCodes3[CharCodes3["ZERO"] = 48] = "ZERO";
24318
+ CharCodes3[CharCodes3["NINE"] = 57] = "NINE";
24319
+ CharCodes3[CharCodes3["LOWER_A"] = 97] = "LOWER_A";
24320
+ CharCodes3[CharCodes3["LOWER_X"] = 120] = "LOWER_X";
24321
+ })(CharCodes || (CharCodes = {}));
24322
+ var TO_LOWER_BIT = 32;
24323
+ function isNumber2(code) {
24324
+ return code - CharCodes.ZERO >>> 0 <= 9;
24325
+ }
24326
+ function isHexadecimalCharacter(code) {
24327
+ return (code | TO_LOWER_BIT) - CharCodes.LOWER_A >>> 0 <= 5;
24328
+ }
24329
+ function isAlpha2(code) {
24330
+ return (code | TO_LOWER_BIT) - CharCodes.LOWER_A >>> 0 <= 25;
24331
+ }
24332
+ function isEntityInAttributeInvalidEnd(code) {
24333
+ return code === CharCodes.EQUALS || isAlpha2(code) || isNumber2(code);
24334
+ }
24335
+ var EntityDecoderState;
24336
+ (function(EntityDecoderState2) {
24337
+ EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
24338
+ EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
24339
+ EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
24340
+ EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
24341
+ EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
24342
+ })(EntityDecoderState || (EntityDecoderState = {}));
24343
+ var DecodingMode;
24344
+ (function(DecodingMode2) {
24345
+ DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
24346
+ DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
24347
+ DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
24348
+ })(DecodingMode || (DecodingMode = {}));
24349
+ var EntityDecoder = class {
24350
+ decodeTree;
24351
+ emitCodePoint;
24352
+ errors;
24353
+ /** The current state of the decoder. */
24354
+ state = EntityDecoderState.EntityStart;
24355
+ /** Characters that were consumed while parsing an entity. */
24356
+ consumed = 1;
24357
+ /**
24358
+ * The result of the entity.
24359
+ *
24360
+ * For named entities: the trie index of the best legacy match so far
24361
+ * (0 = none). For numeric entities: the accumulated code point.
24362
+ */
24363
+ result = 0;
24364
+ /** The current index in the decode tree. */
24365
+ treeIndex = 0;
24366
+ /**
24367
+ * Characters consumed since the last recorded legacy match, plus one.
24368
+ * Invariant at the top of the `stateNamedEntity` loop: `excess` equals
24369
+ * the number of unrecorded consumed characters + 1.
24370
+ */
24371
+ // biome-ignore lint/correctness/noUnusedPrivateClassMembers: False positive (read via destructuring)
24372
+ excess = 1;
24373
+ /** The mode in which the decoder is operating. */
24374
+ decodeMode = DecodingMode.Strict;
24375
+ /** The number of characters that have been consumed in the current run. */
24376
+ // biome-ignore lint/correctness/noUnusedPrivateClassMembers: False positive
24377
+ runConsumed = 0;
24378
+ constructor(decodeTree, emitCodePoint, errors) {
24379
+ this.decodeTree = decodeTree;
24380
+ this.emitCodePoint = emitCodePoint;
24381
+ this.errors = errors;
24159
24382
  }
24160
- if (input.path !== void 0) {
24161
- const items = pathItems({ ...input, path: input.path }, ctx.project);
24162
- return { items, from: items.length === 1 ? items[0].label : input.path };
24383
+ /**
24384
+ * Resets the instance to make it reusable.
24385
+ * @param decodeMode Entity decoding mode to use.
24386
+ */
24387
+ startEntity(decodeMode) {
24388
+ this.decodeMode = decodeMode;
24389
+ this.state = EntityDecoderState.EntityStart;
24390
+ this.result = 0;
24391
+ this.treeIndex = 0;
24392
+ this.excess = 1;
24393
+ this.consumed = 1;
24394
+ this.runConsumed = 0;
24163
24395
  }
24164
- const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
24165
- const text = res.body.toString("utf8");
24166
- const label = res.finalUrl;
24167
- return { items: [{ sourceKind: "url", label, kind: kindOfType(res.contentType), read: () => text }], from: label };
24168
- }
24169
- async function handler4(input, ctx) {
24170
- const given = INPUT_FIELDS.filter((f) => input[f] !== void 0);
24171
- if (given.length !== 1) return { text: new CtxError("ONE_OF_INPUT", { names: INPUT_FIELDS.join(", ") }).toLine(), isError: true, sandboxBytes: 0 };
24172
- try {
24173
- const got = await itemsOf(input, ctx);
24174
- const items = got.items.map((it) => ({ ...it, label: userLabel(it.label) }));
24175
- const from = userLabel(got.from);
24176
- const db = await openDb(ctx.project);
24177
- let sources = 0;
24178
- let chunks = 0;
24179
- let bytes4 = 0;
24180
- let lastId = 0;
24181
- try {
24182
- for (const it of items) {
24183
- const text = it.read();
24184
- if (text === void 0) continue;
24185
- const stored = storeText(db, ctx.project, ctx.sessionId, it.sourceKind, it.label, text, it.kind);
24186
- chunks += stored.chunks;
24187
- lastId = stored.sourceId;
24188
- bytes4 += Buffer.byteLength(text, "utf8");
24189
- sources += 1;
24396
+ /**
24397
+ * Write an entity to the decoder. This can be called multiple times with partial entities.
24398
+ * If the entity is incomplete, the decoder will return -1.
24399
+ *
24400
+ * Mirrors the non-streaming `decodeWithTrie`, but with the ability to stop decoding if the
24401
+ * entity is incomplete, and resume when the next string is written.
24402
+ * @param input The string containing the entity (or a continuation of the entity).
24403
+ * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
24404
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
24405
+ */
24406
+ write(input, offset) {
24407
+ switch (this.state) {
24408
+ case EntityDecoderState.EntityStart: {
24409
+ if (input.charCodeAt(offset) === CharCodes.NUM) {
24410
+ this.state = EntityDecoderState.NumericStart;
24411
+ this.consumed += 1;
24412
+ return this.stateNumericStart(input, offset + 1);
24413
+ }
24414
+ this.state = EntityDecoderState.NamedEntity;
24415
+ return this.stateNamedEntity(input, offset);
24416
+ }
24417
+ case EntityDecoderState.NumericStart: {
24418
+ return this.stateNumericStart(input, offset);
24419
+ }
24420
+ case EntityDecoderState.NumericDecimal: {
24421
+ return this.stateNumericDecimal(input, offset);
24422
+ }
24423
+ case EntityDecoderState.NumericHex: {
24424
+ return this.stateNumericHex(input, offset);
24425
+ }
24426
+ default: {
24427
+ return this.stateNamedEntity(input, offset);
24190
24428
  }
24191
- } finally {
24192
- closeDb(db);
24193
24429
  }
24194
- const shown2 = Buffer.byteLength(from, "utf8") > ECHO_MAX_BYTES ? sourceHandle(lastId) : from;
24195
- const line = "Indexed " + sources + " source(s), " + chunks + " chunk(s) from " + shown2 + ".";
24196
- return {
24197
- text: capBytes(line, OUTPUT_CAP).text,
24198
- isError: false,
24199
- sandboxBytes: bytes4,
24200
- journal: { kind: "index", key: from, path: from, exit_code: null }
24201
- };
24202
- } catch (err) {
24203
- if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0 };
24204
- throw err;
24205
24430
  }
24206
- }
24207
- var ctxIndex = {
24208
- name: "ctx_index",
24209
- schema: ctxIndexSchema,
24210
- readOnly: false,
24211
- alwaysLoad: false,
24212
- handler: handler4
24213
- };
24214
-
24215
- // src/core/tools/purge.ts
24216
- var ctxPurgeSchema = external_exports.object({
24217
- session: external_exports.string().optional(),
24218
- source: external_exports.string().optional(),
24219
- project: external_exports.boolean().optional()
24220
- }, { error: unknownField }).strict();
24221
- function reply2(text, isError) {
24222
- return { text, isError, sandboxBytes: 0 };
24223
- }
24224
- function scopesOf(input) {
24225
- const set3 = {
24226
- session: input.session !== void 0,
24227
- source: input.source !== void 0,
24228
- project: input.project === true
24229
- };
24230
- return PURGE_SCOPES.filter((s) => set3[s]);
24231
- }
24232
- function changes(raw, sql, ...args) {
24233
- return Number(raw.prepare(sql).run(...args).changes);
24234
- }
24235
- function purgeScope(raw, scope, input) {
24236
- if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
24237
- if (scope === "source") {
24238
- const label = input.source;
24239
- return deleteChunkRows(raw, { label }) + changes(raw, "DELETE FROM sources WHERE label = ?", label);
24431
+ /**
24432
+ * Switches between the numeric decimal and hexadecimal states.
24433
+ *
24434
+ * Equivalent to the `Numeric character reference state` in the HTML spec.
24435
+ * @param input The string containing the entity (or a continuation of the entity).
24436
+ * @param offset The current offset.
24437
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
24438
+ */
24439
+ // eslint-disable-next-line unicorn/consistent-class-member-order
24440
+ stateNumericStart(input, offset) {
24441
+ if (offset >= input.length) {
24442
+ return -1;
24443
+ }
24444
+ if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
24445
+ this.state = EntityDecoderState.NumericHex;
24446
+ this.consumed += 1;
24447
+ return this.stateNumericHex(input, offset + 1);
24448
+ }
24449
+ this.state = EntityDecoderState.NumericDecimal;
24450
+ return this.stateNumericDecimal(input, offset);
24240
24451
  }
24241
- const chunks = deleteChunkRows(raw, "all");
24242
- return changes(raw, "DELETE FROM events") + chunks + changes(raw, "DELETE FROM sources");
24243
- }
24244
- function isBusy(err) {
24245
- const code = err?.errcode;
24246
- return typeof code === "number" && (code & SQLITE_PRIMARY_CODE_MASK) === SQLITE_BUSY_CODE;
24247
- }
24248
- async function handler5(input, ctx) {
24249
- const scopes = scopesOf(input);
24250
- if (scopes.length === 0) return reply2(PURGE_NO_SCOPE_LINE, true);
24251
- if (scopes.length > 1) return reply2(PURGE_MANY_SCOPES_LINE, true);
24252
- const scope = scopes[0];
24253
- try {
24254
- const db = await openDb(ctx.project);
24255
- try {
24256
- const rows = withWrite(db, (h) => purgeScope(h.raw, scope, input));
24257
- return reply2(PURGE_SUMMARY(rows, scope), false);
24258
- } finally {
24259
- closeDb(db);
24452
+ /**
24453
+ * Parses a hexadecimal numeric entity.
24454
+ *
24455
+ * Equivalent to the `Hexademical character reference state` in the HTML
24456
+ * spec. Digit parsing matches the hex loop in `parseNumericEntity`.
24457
+ * The accumulated value is preserved for numeric validation callbacks.
24458
+ * @param input The string containing the entity (or a continuation of the entity).
24459
+ * @param offset The current offset.
24460
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
24461
+ */
24462
+ stateNumericHex(input, offset) {
24463
+ const inputLength = input.length;
24464
+ let { result } = this;
24465
+ let { consumed } = this;
24466
+ while (offset < inputLength) {
24467
+ const char = input.charCodeAt(offset);
24468
+ if (isNumber2(char) || isHexadecimalCharacter(char)) {
24469
+ const digit = char <= CharCodes.NINE ? char - CharCodes.ZERO : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10;
24470
+ result = result * 16 + digit;
24471
+ consumed += 1;
24472
+ offset += 1;
24473
+ } else {
24474
+ this.result = result;
24475
+ this.consumed = consumed;
24476
+ return this.emitNumericEntity(char, 3);
24477
+ }
24260
24478
  }
24261
- } catch (err) {
24262
- if (isBusy(err)) return reply2(PURGE_BUSY_LINE, true);
24263
- throw err;
24479
+ this.result = result;
24480
+ this.consumed = consumed;
24481
+ return -1;
24264
24482
  }
24265
- }
24266
- var ctxPurge = Object.freeze({
24267
- name: "ctx_purge",
24268
- description: "",
24269
- schema: ctxPurgeSchema,
24270
- readOnly: false,
24271
- alwaysLoad: false,
24272
- handler: handler5
24273
- });
24274
-
24275
- // src/core/tools/resume.ts
24276
- var ctxResumeSchema = external_exports.object({
24277
- session: external_exports.string().optional(),
24278
- seq: external_exports.number().int().positive().optional()
24279
- }, {
24280
- error: (issue2) => issue2.code === "unrecognized_keys" ? RESUME_UNKNOWN_FIELD_LINE : void 0
24281
- }).strict();
24282
- function reply3(text, isError) {
24283
- return { text, isError, sandboxBytes: 0 };
24284
- }
24285
- async function handler6(input, ctx) {
24286
- const sessionId = input.session ?? ctx.sessionId;
24287
- if (sessionId === "") return reply3(RESUME_NO_SESSION_LINE, true);
24288
- const db = await openDb(ctx.project, { readOnly: true });
24289
- try {
24290
- if (input.seq !== void 0) {
24291
- const row5 = readEventBySeq(db, input.seq);
24292
- if (row5 === null || row5.session_id !== sessionId) return reply3(RESUME_NO_ROW_LINE(input.seq), true);
24293
- return reply3(row5.body, false);
24483
+ /**
24484
+ * Parses a decimal numeric entity.
24485
+ *
24486
+ * Equivalent to the `Decimal character reference state` in the HTML
24487
+ * spec. Digit parsing matches the decimal loop in `parseNumericEntity`.
24488
+ * The accumulated value is preserved for numeric validation callbacks.
24489
+ * @param input The string containing the entity (or a continuation of the entity).
24490
+ * @param offset The current offset.
24491
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
24492
+ */
24493
+ stateNumericDecimal(input, offset) {
24494
+ const inputLength = input.length;
24495
+ let { result } = this;
24496
+ let { consumed } = this;
24497
+ while (offset < inputLength) {
24498
+ const digit = input.charCodeAt(offset) - CharCodes.ZERO;
24499
+ if (digit >>> 0 > 9) {
24500
+ this.result = result;
24501
+ this.consumed = consumed;
24502
+ return this.emitNumericEntity(digit + CharCodes.ZERO, 2);
24503
+ }
24504
+ result = result * 10 + digit;
24505
+ consumed += 1;
24506
+ offset += 1;
24507
+ }
24508
+ this.result = result;
24509
+ this.consumed = consumed;
24510
+ return -1;
24511
+ }
24512
+ /**
24513
+ * Validate and emit a numeric entity.
24514
+ *
24515
+ * Implements the logic from the `Hexademical character reference start
24516
+ * state` and `Numeric character reference end state` in the HTML spec.
24517
+ * @param lastCp The last code point of the entity. Used to see if the
24518
+ * entity was terminated with a semicolon.
24519
+ * @param expectedLength The minimum number of characters that should be
24520
+ * consumed. Used to validate that at least one digit
24521
+ * was consumed.
24522
+ * @returns The number of characters that were consumed.
24523
+ */
24524
+ emitNumericEntity(lastCp, expectedLength) {
24525
+ if (this.consumed <= expectedLength) {
24526
+ this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed);
24527
+ return 0;
24528
+ }
24529
+ if (lastCp === CharCodes.SEMI) {
24530
+ this.consumed += 1;
24531
+ } else if (this.decodeMode === DecodingMode.Strict) {
24532
+ return 0;
24533
+ }
24534
+ this.emitCodePoint((this.decodeTree === xmlDecodeTree ? replaceCodePointXML : replaceCodePoint)(this.result), this.consumed);
24535
+ if (this.errors) {
24536
+ if (lastCp !== CharCodes.SEMI) {
24537
+ this.errors.missingSemicolonAfterCharacterReference();
24538
+ }
24539
+ this.errors.validateNumericCharacterReference(this.result);
24540
+ }
24541
+ return this.consumed;
24542
+ }
24543
+ /**
24544
+ * Flush locally-tracked walk state back to the fields, then emit the
24545
+ * recorded legacy match or reject (cold path — at most once per
24546
+ * entity). Called after failed navigation (leaf node, branch miss, or
24547
+ * compact-run mismatch). In attribute mode, reject if no legacy was
24548
+ * recorded at the current node, if we descended past it, or if the
24549
+ * pending input character is an invalid attribute terminator.
24550
+ * @param consumed Locally-tracked consumed count.
24551
+ * @param excess Locally-tracked excess count.
24552
+ * @param char Pending input character (may be the mismatching char).
24553
+ * @param valueLength Value length at the current trie node.
24554
+ */
24555
+ flushAndEmitLegacyOrReject(consumed, excess, char, valueLength) {
24556
+ this.consumed = consumed;
24557
+ this.excess = excess;
24558
+ return this.result === 0 || this.decodeMode === DecodingMode.Attribute && (valueLength === 0 || excess > 1 || isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
24559
+ }
24560
+ /**
24561
+ * Parses a named entity.
24562
+ *
24563
+ * Equivalent to the `Named character reference state` in the HTML spec.
24564
+ * @param input The string containing the entity (or a continuation of the entity).
24565
+ * @param offset The current offset.
24566
+ * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
24567
+ */
24568
+ stateNamedEntity(input, offset) {
24569
+ const { decodeTree } = this;
24570
+ const inputLength = input.length;
24571
+ const isStrict = this.decodeMode === DecodingMode.Strict;
24572
+ let { treeIndex } = this;
24573
+ let { excess } = this;
24574
+ let { consumed } = this;
24575
+ let current = decodeTree[treeIndex];
24576
+ while (offset < inputLength) {
24577
+ while ((current & (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) === 0 && (current & BinTrieFlags.JUMP_TABLE) !== 0) {
24578
+ const char2 = input.charCodeAt(offset);
24579
+ const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
24580
+ const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
24581
+ if (branchCount === 0) {
24582
+ if (char2 !== jumpOffset) {
24583
+ return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
24584
+ }
24585
+ treeIndex += 1;
24586
+ } else {
24587
+ const slot = char2 - jumpOffset;
24588
+ if (slot >>> 0 >= branchCount) {
24589
+ return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
24590
+ }
24591
+ const stored = decodeTree[treeIndex + 1 + slot];
24592
+ if (stored === 0) {
24593
+ return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
24594
+ }
24595
+ treeIndex = treeIndex + branchCount + stored & 65535;
24596
+ }
24597
+ current = decodeTree[treeIndex];
24598
+ offset += 1;
24599
+ excess += 1;
24600
+ if (offset >= inputLength)
24601
+ break;
24602
+ }
24603
+ if (offset >= inputLength)
24604
+ break;
24605
+ if ((current & (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) === BinTrieFlags.FLAG13) {
24606
+ const runLength = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
24607
+ let { runConsumed } = this;
24608
+ if (runConsumed === 0) {
24609
+ const char2 = input.charCodeAt(offset);
24610
+ if (char2 !== (current & BinTrieFlags.JUMP_TABLE)) {
24611
+ return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
24612
+ }
24613
+ offset += 1;
24614
+ excess += 1;
24615
+ runConsumed = 1;
24616
+ }
24617
+ while (runConsumed < runLength) {
24618
+ if (offset >= inputLength) {
24619
+ this.treeIndex = treeIndex;
24620
+ this.excess = excess;
24621
+ this.consumed = consumed;
24622
+ this.runConsumed = runConsumed;
24623
+ return -1;
24624
+ }
24625
+ const charIndexInPacked = runConsumed - 1;
24626
+ const packedWord = decodeTree[treeIndex + 1 + (charIndexInPacked >> 1)];
24627
+ const expectedChar = packedWord >> ((charIndexInPacked & 1) << 3) & 255;
24628
+ const char2 = input.charCodeAt(offset);
24629
+ if (char2 !== expectedChar) {
24630
+ this.runConsumed = 0;
24631
+ return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
24632
+ }
24633
+ offset += 1;
24634
+ excess += 1;
24635
+ runConsumed += 1;
24636
+ }
24637
+ this.runConsumed = 0;
24638
+ treeIndex += 1 + (runLength >> 1);
24639
+ current = decodeTree[treeIndex];
24640
+ continue;
24641
+ }
24642
+ const valueLength = current >>> 14;
24643
+ const char = input.charCodeAt(offset);
24644
+ if (valueLength !== 0) {
24645
+ if (!isStrict && (current & BinTrieFlags.FLAG13) === 0) {
24646
+ this.result = treeIndex;
24647
+ consumed += excess - 1;
24648
+ excess = 1;
24649
+ }
24650
+ if (char === CharCodes.SEMI) {
24651
+ return this.emitNamedEntityData(treeIndex, valueLength, consumed + excess);
24652
+ }
24653
+ if (valueLength === 1) {
24654
+ return this.flushAndEmitLegacyOrReject(consumed, excess, char, valueLength);
24655
+ }
24656
+ }
24657
+ const next = determineBranch(decodeTree, current, treeIndex + (valueLength || 1), char);
24658
+ if (next < 0) {
24659
+ return this.flushAndEmitLegacyOrReject(consumed, excess, char, valueLength);
24660
+ }
24661
+ treeIndex = next;
24662
+ current = decodeTree[treeIndex];
24663
+ offset += 1;
24664
+ excess += 1;
24294
24665
  }
24295
- const rows = readSessionEvents(db, sessionId);
24296
- const newest = rows.at(-1);
24297
- if (newest === void 0) return reply3(RESUME_EMPTY_LINE, false);
24298
- const sources = listSessionSources(db, sessionId, MAX_CANDIDATES).map((r) => "source " + sourceHandle(r.id) + ": " + r.label + " (" + r.bytes + " B)");
24299
- const goal = readFirstPrompt(db, sessionId);
24300
- const last2 = readLastPrompt(db, sessionId);
24301
- const units = queryUnits(db, sessionId, recallQueryText(last2, goal), RECALL_UNIT_CANDIDATES).map((u) => ({ ...u, label: sourceHandle(u.sourceId) }));
24302
- const block = renderState(rows, newest.turn, { sources, units });
24303
- if (Buffer.byteLength(block, "utf8") > RESUME_CAP) throw new Error("ctx_resume: state block over RESUME_CAP (render bug).");
24304
- return reply3(block, false);
24305
- } finally {
24306
- closeDb(db);
24666
+ if (!isStrict && current >>> 14 !== 0 && (current & BinTrieFlags.FLAG13) === 0) {
24667
+ this.result = treeIndex;
24668
+ consumed += excess - 1;
24669
+ excess = 1;
24670
+ }
24671
+ this.treeIndex = treeIndex;
24672
+ this.excess = excess;
24673
+ this.consumed = consumed;
24674
+ return -1;
24307
24675
  }
24308
- }
24309
- var ctxResume = Object.freeze({
24310
- name: "ctx_resume",
24311
- schema: ctxResumeSchema,
24312
- readOnly: true,
24676
+ /**
24677
+ * Emit a named entity that was not terminated with a semicolon.
24678
+ * @returns The number of characters consumed.
24679
+ */
24680
+ emitNotTerminatedNamedEntity() {
24681
+ const { result, decodeTree } = this;
24682
+ const valueLength = decodeTree[result] >>> 14;
24683
+ this.emitNamedEntityData(result, valueLength, this.consumed);
24684
+ this.errors?.missingSemicolonAfterCharacterReference();
24685
+ return this.consumed;
24686
+ }
24687
+ /**
24688
+ * Emit a named entity.
24689
+ * @param result The index of the entity in the decode tree.
24690
+ * @param valueLength Encoded value length (header plus any value words).
24691
+ * @param consumed The number of characters consumed.
24692
+ * @returns The number of characters consumed.
24693
+ */
24694
+ emitNamedEntityData(result, valueLength, consumed) {
24695
+ const { decodeTree } = this;
24696
+ this.emitCodePoint(valueLength === 1 ? decodeTree[result] & BinTrieFlags.VALUE_MASK : decodeTree[result + 1], consumed);
24697
+ if (valueLength === 3) {
24698
+ this.emitCodePoint(decodeTree[result + 2], consumed);
24699
+ }
24700
+ return consumed;
24701
+ }
24702
+ /**
24703
+ * Signal to the parser that the end of the input was reached.
24704
+ *
24705
+ * Remaining data will be emitted and relevant errors will be produced.
24706
+ * @returns The number of characters consumed.
24707
+ */
24708
+ end() {
24709
+ switch (this.state) {
24710
+ case EntityDecoderState.NamedEntity: {
24711
+ return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
24712
+ }
24713
+ // Otherwise, emit a numeric entity if we have one.
24714
+ case EntityDecoderState.NumericDecimal: {
24715
+ return this.emitNumericEntity(0, 2);
24716
+ }
24717
+ case EntityDecoderState.NumericHex: {
24718
+ return this.emitNumericEntity(0, 3);
24719
+ }
24720
+ case EntityDecoderState.NumericStart: {
24721
+ this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed);
24722
+ return 0;
24723
+ }
24724
+ default: {
24725
+ return 0;
24726
+ }
24727
+ }
24728
+ }
24729
+ };
24730
+ function determineBranch(decodeTree, current, nodeIndex, char) {
24731
+ const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
24732
+ const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
24733
+ if (jumpOffset) {
24734
+ if (branchCount === 0) {
24735
+ return char === jumpOffset ? nodeIndex : -1;
24736
+ }
24737
+ const slot = char - jumpOffset;
24738
+ if (slot >>> 0 >= branchCount)
24739
+ return -1;
24740
+ const stored = decodeTree[nodeIndex + slot];
24741
+ return stored === 0 ? -1 : nodeIndex + branchCount + stored - 1 & 65535;
24742
+ }
24743
+ if (branchCount === 0)
24744
+ return -1;
24745
+ const packedKeySlots = branchCount + 1 >> 1;
24746
+ const branchEnd = nodeIndex + packedKeySlots + branchCount;
24747
+ for (let index = 0; index < branchCount; index++) {
24748
+ const packed = decodeTree[nodeIndex + (index >> 1)];
24749
+ const key = packed >> ((index & 1) << 3) & 255;
24750
+ if (key === char) {
24751
+ const pointerIndex = nodeIndex + packedKeySlots + index;
24752
+ return branchEnd + decodeTree[pointerIndex] & 65535;
24753
+ }
24754
+ if (key > char)
24755
+ return -1;
24756
+ }
24757
+ return -1;
24758
+ }
24759
+
24760
+ // node_modules/htmlparser2/dist/Tokenizer.js
24761
+ var CharCodes2;
24762
+ (function(CharCodes3) {
24763
+ CharCodes3[CharCodes3["Tab"] = 9] = "Tab";
24764
+ CharCodes3[CharCodes3["NewLine"] = 10] = "NewLine";
24765
+ CharCodes3[CharCodes3["FormFeed"] = 12] = "FormFeed";
24766
+ CharCodes3[CharCodes3["CarriageReturn"] = 13] = "CarriageReturn";
24767
+ CharCodes3[CharCodes3["Space"] = 32] = "Space";
24768
+ CharCodes3[CharCodes3["ExclamationMark"] = 33] = "ExclamationMark";
24769
+ CharCodes3[CharCodes3["Number"] = 35] = "Number";
24770
+ CharCodes3[CharCodes3["Amp"] = 38] = "Amp";
24771
+ CharCodes3[CharCodes3["SingleQuote"] = 39] = "SingleQuote";
24772
+ CharCodes3[CharCodes3["DoubleQuote"] = 34] = "DoubleQuote";
24773
+ CharCodes3[CharCodes3["Dash"] = 45] = "Dash";
24774
+ CharCodes3[CharCodes3["Slash"] = 47] = "Slash";
24775
+ CharCodes3[CharCodes3["Zero"] = 48] = "Zero";
24776
+ CharCodes3[CharCodes3["Nine"] = 57] = "Nine";
24777
+ CharCodes3[CharCodes3["Semi"] = 59] = "Semi";
24778
+ CharCodes3[CharCodes3["Lt"] = 60] = "Lt";
24779
+ CharCodes3[CharCodes3["Eq"] = 61] = "Eq";
24780
+ CharCodes3[CharCodes3["Gt"] = 62] = "Gt";
24781
+ CharCodes3[CharCodes3["Questionmark"] = 63] = "Questionmark";
24782
+ CharCodes3[CharCodes3["UpperA"] = 65] = "UpperA";
24783
+ CharCodes3[CharCodes3["LowerA"] = 97] = "LowerA";
24784
+ CharCodes3[CharCodes3["UpperF"] = 70] = "UpperF";
24785
+ CharCodes3[CharCodes3["LowerF"] = 102] = "LowerF";
24786
+ CharCodes3[CharCodes3["UpperZ"] = 90] = "UpperZ";
24787
+ CharCodes3[CharCodes3["LowerZ"] = 122] = "LowerZ";
24788
+ CharCodes3[CharCodes3["LowerX"] = 120] = "LowerX";
24789
+ CharCodes3[CharCodes3["OpeningSquareBracket"] = 91] = "OpeningSquareBracket";
24790
+ })(CharCodes2 || (CharCodes2 = {}));
24791
+ var State;
24792
+ (function(State2) {
24793
+ State2[State2["Text"] = 1] = "Text";
24794
+ State2[State2["BeforeTagName"] = 2] = "BeforeTagName";
24795
+ State2[State2["InTagName"] = 3] = "InTagName";
24796
+ State2[State2["InSelfClosingTag"] = 4] = "InSelfClosingTag";
24797
+ State2[State2["BeforeClosingTagName"] = 5] = "BeforeClosingTagName";
24798
+ State2[State2["InClosingTagName"] = 6] = "InClosingTagName";
24799
+ State2[State2["AfterClosingTagName"] = 7] = "AfterClosingTagName";
24800
+ State2[State2["BeforeAttributeName"] = 8] = "BeforeAttributeName";
24801
+ State2[State2["InAttributeName"] = 9] = "InAttributeName";
24802
+ State2[State2["AfterAttributeName"] = 10] = "AfterAttributeName";
24803
+ State2[State2["BeforeAttributeValue"] = 11] = "BeforeAttributeValue";
24804
+ State2[State2["InAttributeValueDq"] = 12] = "InAttributeValueDq";
24805
+ State2[State2["InAttributeValueSq"] = 13] = "InAttributeValueSq";
24806
+ State2[State2["InAttributeValueNq"] = 14] = "InAttributeValueNq";
24807
+ State2[State2["BeforeDeclaration"] = 15] = "BeforeDeclaration";
24808
+ State2[State2["InDeclaration"] = 16] = "InDeclaration";
24809
+ State2[State2["InProcessingInstruction"] = 17] = "InProcessingInstruction";
24810
+ State2[State2["BeforeComment"] = 18] = "BeforeComment";
24811
+ State2[State2["CDATASequence"] = 19] = "CDATASequence";
24812
+ State2[State2["DeclarationSequence"] = 20] = "DeclarationSequence";
24813
+ State2[State2["InSpecialComment"] = 21] = "InSpecialComment";
24814
+ State2[State2["InCommentLike"] = 22] = "InCommentLike";
24815
+ State2[State2["SpecialStartSequence"] = 23] = "SpecialStartSequence";
24816
+ State2[State2["InSpecialTag"] = 24] = "InSpecialTag";
24817
+ State2[State2["InPlainText"] = 25] = "InPlainText";
24818
+ State2[State2["InEntity"] = 26] = "InEntity";
24819
+ })(State || (State = {}));
24820
+ function isWhitespace2(c) {
24821
+ return c === CharCodes2.Space || c === CharCodes2.NewLine || c === CharCodes2.Tab || c === CharCodes2.FormFeed || c === CharCodes2.CarriageReturn;
24822
+ }
24823
+ function isEndOfTagSection(c) {
24824
+ return c === CharCodes2.Slash || c === CharCodes2.Gt || isWhitespace2(c);
24825
+ }
24826
+ function isASCIIAlpha(c) {
24827
+ return c >= CharCodes2.LowerA && c <= CharCodes2.LowerZ || c >= CharCodes2.UpperA && c <= CharCodes2.UpperZ;
24828
+ }
24829
+ var QuoteType;
24830
+ (function(QuoteType2) {
24831
+ QuoteType2[QuoteType2["NoValue"] = 0] = "NoValue";
24832
+ QuoteType2[QuoteType2["Unquoted"] = 1] = "Unquoted";
24833
+ QuoteType2[QuoteType2["Single"] = 2] = "Single";
24834
+ QuoteType2[QuoteType2["Double"] = 3] = "Double";
24835
+ })(QuoteType || (QuoteType = {}));
24836
+ var Sequences = {
24837
+ Empty: new Uint8Array(0),
24838
+ Cdata: new Uint8Array([67, 68, 65, 84, 65, 91]),
24839
+ // CDATA[
24840
+ CdataEnd: new Uint8Array([93, 93, 62]),
24841
+ // ]]>
24842
+ CommentEnd: new Uint8Array([45, 45, 33, 62]),
24843
+ // `--!>`
24844
+ Doctype: new Uint8Array([100, 111, 99, 116, 121, 112, 101]),
24845
+ // `doctype`
24846
+ IframeEnd: new Uint8Array([60, 47, 105, 102, 114, 97, 109, 101]),
24847
+ // `</iframe`
24848
+ NoembedEnd: new Uint8Array([
24849
+ 60,
24850
+ 47,
24851
+ 110,
24852
+ 111,
24853
+ 101,
24854
+ 109,
24855
+ 98,
24856
+ 101,
24857
+ 100
24858
+ ]),
24859
+ // `</noembed`
24860
+ NoframesEnd: new Uint8Array([
24861
+ 60,
24862
+ 47,
24863
+ 110,
24864
+ 111,
24865
+ 102,
24866
+ 114,
24867
+ 97,
24868
+ 109,
24869
+ 101,
24870
+ 115
24871
+ ]),
24872
+ // `</noframes`
24873
+ Plaintext: new Uint8Array([
24874
+ 60,
24875
+ 47,
24876
+ 112,
24877
+ 108,
24878
+ 97,
24879
+ 105,
24880
+ 110,
24881
+ 116,
24882
+ 101,
24883
+ 120,
24884
+ 116
24885
+ ]),
24886
+ // `</plaintext`
24887
+ ScriptEnd: new Uint8Array([60, 47, 115, 99, 114, 105, 112, 116]),
24888
+ // `</script`
24889
+ StyleEnd: new Uint8Array([60, 47, 115, 116, 121, 108, 101]),
24890
+ // `</style`
24891
+ TitleEnd: new Uint8Array([60, 47, 116, 105, 116, 108, 101]),
24892
+ // `</title`
24893
+ TextareaEnd: new Uint8Array([
24894
+ 60,
24895
+ 47,
24896
+ 116,
24897
+ 101,
24898
+ 120,
24899
+ 116,
24900
+ 97,
24901
+ 114,
24902
+ 101,
24903
+ 97
24904
+ ]),
24905
+ // `</textarea`
24906
+ XmpEnd: new Uint8Array([60, 47, 120, 109, 112])
24907
+ // `</xmp`
24908
+ };
24909
+ var specialStartSequences = /* @__PURE__ */ new Map([
24910
+ [Sequences.IframeEnd[2], Sequences.IframeEnd],
24911
+ [Sequences.NoembedEnd[2], Sequences.NoembedEnd],
24912
+ [Sequences.Plaintext[2], Sequences.Plaintext],
24913
+ [Sequences.ScriptEnd[2], Sequences.ScriptEnd],
24914
+ [Sequences.TitleEnd[2], Sequences.TitleEnd],
24915
+ [Sequences.XmpEnd[2], Sequences.XmpEnd]
24916
+ ]);
24917
+ var Tokenizer2 = class {
24918
+ cbs;
24919
+ /** The current state the tokenizer is in. */
24920
+ state = State.Text;
24921
+ /** The read buffer. */
24922
+ buffer = "";
24923
+ /** The beginning of the section that is currently being read. */
24924
+ sectionStart = 0;
24925
+ /** The index within the buffer that we are currently looking at. */
24926
+ index = 0;
24927
+ /** The start of the last entity. */
24928
+ entityStart = 0;
24929
+ /** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */
24930
+ baseState = State.Text;
24931
+ /** For special parsing behavior inside of script and style tags. */
24932
+ isSpecial = false;
24933
+ /** Indicates whether the tokenizer has been paused. */
24934
+ running = true;
24935
+ /** The offset of the current buffer. */
24936
+ offset = 0;
24937
+ xmlMode;
24938
+ decodeEntities;
24939
+ recognizeSelfClosing;
24940
+ entityDecoder;
24941
+ constructor({ xmlMode = false, decodeEntities = true, recognizeSelfClosing = xmlMode }, cbs) {
24942
+ this.cbs = cbs;
24943
+ this.xmlMode = xmlMode;
24944
+ this.decodeEntities = decodeEntities;
24945
+ this.recognizeSelfClosing = recognizeSelfClosing;
24946
+ this.entityDecoder = new EntityDecoder(xmlMode ? xmlDecodeTree : htmlDecodeTree, (cp, consumed) => this.emitCodePoint(cp, consumed));
24947
+ }
24948
+ reset() {
24949
+ this.state = State.Text;
24950
+ this.buffer = "";
24951
+ this.sectionStart = 0;
24952
+ this.index = 0;
24953
+ this.baseState = State.Text;
24954
+ this.isSpecial = false;
24955
+ this.currentSequence = Sequences.Empty;
24956
+ this.sequenceIndex = 0;
24957
+ this.running = true;
24958
+ this.offset = 0;
24959
+ }
24960
+ write(chunk) {
24961
+ this.offset += this.buffer.length;
24962
+ this.buffer = chunk;
24963
+ this.parse();
24964
+ }
24965
+ end() {
24966
+ if (this.running)
24967
+ this.finish();
24968
+ }
24969
+ pause() {
24970
+ this.running = false;
24971
+ }
24972
+ resume() {
24973
+ this.running = true;
24974
+ if (this.index < this.buffer.length + this.offset) {
24975
+ this.parse();
24976
+ }
24977
+ }
24978
+ stateText(c) {
24979
+ if (c === CharCodes2.Lt || !this.decodeEntities && this.fastForwardTo(CharCodes2.Lt)) {
24980
+ if (this.index > this.sectionStart) {
24981
+ this.cbs.ontext(this.sectionStart, this.index);
24982
+ }
24983
+ this.state = State.BeforeTagName;
24984
+ this.sectionStart = this.index;
24985
+ } else if (this.decodeEntities && c === CharCodes2.Amp) {
24986
+ this.startEntity();
24987
+ }
24988
+ }
24989
+ currentSequence = Sequences.Empty;
24990
+ sequenceIndex = 0;
24991
+ enterTagBody() {
24992
+ if (this.currentSequence === Sequences.Plaintext) {
24993
+ this.currentSequence = Sequences.Empty;
24994
+ this.state = State.InPlainText;
24995
+ } else if (this.isSpecial) {
24996
+ this.state = State.InSpecialTag;
24997
+ this.sequenceIndex = 0;
24998
+ } else {
24999
+ this.state = State.Text;
25000
+ }
25001
+ }
25002
+ /**
25003
+ * Match the opening tag name against an HTML text-only tag sequence.
25004
+ *
25005
+ * Some tags share an initial prefix (`script`/`style`, `title`/`textarea`,
25006
+ * `noembed`/`noframes`), so we may switch to an alternate sequence at the
25007
+ * first distinguishing byte. On a successful full match we fall back to
25008
+ * the normal tag-name state; a later `>` will enter raw-text, RCDATA, or
25009
+ * plaintext mode based on `currentSequence` / `isSpecial`.
25010
+ * @param c Current character code point.
25011
+ */
25012
+ stateSpecialStartSequence(c) {
25013
+ const lower = c | 32;
25014
+ if (this.sequenceIndex < this.currentSequence.length) {
25015
+ if (lower === this.currentSequence[this.sequenceIndex]) {
25016
+ this.sequenceIndex++;
25017
+ return;
25018
+ }
25019
+ if (this.sequenceIndex === 3) {
25020
+ if (this.currentSequence === Sequences.ScriptEnd && lower === Sequences.StyleEnd[3]) {
25021
+ this.currentSequence = Sequences.StyleEnd;
25022
+ this.sequenceIndex = 4;
25023
+ return;
25024
+ }
25025
+ if (this.currentSequence === Sequences.TitleEnd && lower === Sequences.TextareaEnd[3]) {
25026
+ this.currentSequence = Sequences.TextareaEnd;
25027
+ this.sequenceIndex = 4;
25028
+ return;
25029
+ }
25030
+ } else if (this.sequenceIndex === 4 && this.currentSequence === Sequences.NoembedEnd && lower === Sequences.NoframesEnd[4]) {
25031
+ this.currentSequence = Sequences.NoframesEnd;
25032
+ this.sequenceIndex = 5;
25033
+ return;
25034
+ }
25035
+ } else if (isEndOfTagSection(c)) {
25036
+ this.sequenceIndex = 0;
25037
+ this.state = State.InTagName;
25038
+ this.stateInTagName(c);
25039
+ return;
25040
+ }
25041
+ this.isSpecial = false;
25042
+ this.currentSequence = Sequences.Empty;
25043
+ this.sequenceIndex = 0;
25044
+ this.state = State.InTagName;
25045
+ this.stateInTagName(c);
25046
+ }
25047
+ stateCDATASequence(c) {
25048
+ if (c === Sequences.Cdata[this.sequenceIndex]) {
25049
+ if (++this.sequenceIndex === Sequences.Cdata.length) {
25050
+ this.state = State.InCommentLike;
25051
+ this.currentSequence = Sequences.CdataEnd;
25052
+ this.sequenceIndex = 0;
25053
+ this.sectionStart = this.index + 1;
25054
+ }
25055
+ } else {
25056
+ this.sequenceIndex = 0;
25057
+ if (this.xmlMode) {
25058
+ this.state = State.InDeclaration;
25059
+ this.stateInDeclaration(c);
25060
+ } else {
25061
+ this.state = State.InSpecialComment;
25062
+ this.stateInSpecialComment(c);
25063
+ }
25064
+ }
25065
+ }
25066
+ /**
25067
+ * When we wait for one specific character, we can speed things up
25068
+ * by skipping through the buffer until we find it.
25069
+ * @param c Current character code point.
25070
+ * @returns Whether the character was found.
25071
+ */
25072
+ fastForwardTo(c) {
25073
+ while (++this.index < this.buffer.length + this.offset) {
25074
+ if (this.buffer.charCodeAt(this.index - this.offset) === c) {
25075
+ return true;
25076
+ }
25077
+ }
25078
+ this.index = this.buffer.length + this.offset - 1;
25079
+ return false;
25080
+ }
25081
+ /**
25082
+ * Emit a comment token and return to the text state.
25083
+ * @param offset Number of characters in the end sequence that have already been matched.
25084
+ */
25085
+ emitComment(offset) {
25086
+ this.cbs.oncomment(this.sectionStart, this.index, offset);
25087
+ this.sequenceIndex = 0;
25088
+ this.sectionStart = this.index + 1;
25089
+ this.state = State.Text;
25090
+ }
25091
+ /**
25092
+ * Comments and CDATA end with `-->` and `]]>`.
25093
+ *
25094
+ * Their common qualities are:
25095
+ * - Their end sequences have a distinct character they start with.
25096
+ * - That character is then repeated, so we have to check multiple repeats.
25097
+ * - All characters but the start character of the sequence can be skipped.
25098
+ * @param c Current character code point.
25099
+ */
25100
+ stateInCommentLike(c) {
25101
+ if (!this.xmlMode && this.currentSequence === Sequences.CommentEnd && this.sequenceIndex <= 1 && /*
25102
+ * We're still at the very start of the comment: the only
25103
+ * characters consumed since `<!--` are the dashes that
25104
+ * advanced sequenceIndex (0 for `<!-->`, 1 for `<!--->`).
25105
+ */
25106
+ this.index === this.sectionStart + this.sequenceIndex && c === CharCodes2.Gt) {
25107
+ this.emitComment(this.sequenceIndex);
25108
+ } else if (this.currentSequence === Sequences.CommentEnd && this.sequenceIndex === 2 && c === CharCodes2.Gt) {
25109
+ this.emitComment(2);
25110
+ } else if (this.currentSequence === Sequences.CommentEnd && this.sequenceIndex === this.currentSequence.length - 1 && c !== CharCodes2.Gt) {
25111
+ this.sequenceIndex = Number(c === CharCodes2.Dash);
25112
+ } else if (c === this.currentSequence[this.sequenceIndex]) {
25113
+ if (++this.sequenceIndex === this.currentSequence.length) {
25114
+ if (this.currentSequence === Sequences.CdataEnd) {
25115
+ this.cbs.oncdata(this.sectionStart, this.index, 2);
25116
+ } else {
25117
+ this.cbs.oncomment(this.sectionStart, this.index, 3);
25118
+ }
25119
+ this.sequenceIndex = 0;
25120
+ this.sectionStart = this.index + 1;
25121
+ this.state = State.Text;
25122
+ }
25123
+ } else if (this.sequenceIndex === 0) {
25124
+ if (this.fastForwardTo(this.currentSequence[0])) {
25125
+ this.sequenceIndex = 1;
25126
+ }
25127
+ } else if (c !== this.currentSequence[this.sequenceIndex - 1]) {
25128
+ this.sequenceIndex = 0;
25129
+ }
25130
+ }
25131
+ /**
25132
+ * HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a tag name.
25133
+ *
25134
+ * XML allows a lot more characters here (@see https://www.w3.org/TR/REC-xml/#NT-NameStartChar).
25135
+ * We allow anything that wouldn't end the tag.
25136
+ * @param c Current character code point.
25137
+ */
25138
+ isTagStartChar(c) {
25139
+ return this.xmlMode ? !isEndOfTagSection(c) : isASCIIAlpha(c);
25140
+ }
25141
+ /**
25142
+ * Scan raw-text / RCDATA content for the matching end tag.
25143
+ *
25144
+ * For RCDATA tags (`<title>`, `<textarea>`) entities are decoded inline.
25145
+ * For raw-text tags (`<script>`, `<style>`, etc.) we fast-forward to `<`.
25146
+ * @param c Current character code point.
25147
+ */
25148
+ stateInSpecialTag(c) {
25149
+ if (this.sequenceIndex === this.currentSequence.length) {
25150
+ if (isEndOfTagSection(c)) {
25151
+ const endOfText = this.index - this.currentSequence.length;
25152
+ if (this.sectionStart < endOfText) {
25153
+ const actualIndex = this.index;
25154
+ this.index = endOfText;
25155
+ this.cbs.ontext(this.sectionStart, endOfText);
25156
+ this.index = actualIndex;
25157
+ }
25158
+ this.isSpecial = false;
25159
+ this.sectionStart = endOfText + 2;
25160
+ this.stateInClosingTagName(c);
25161
+ return;
25162
+ }
25163
+ this.sequenceIndex = 0;
25164
+ }
25165
+ if ((c | 32) === this.currentSequence[this.sequenceIndex]) {
25166
+ this.sequenceIndex += 1;
25167
+ } else if (this.sequenceIndex === 0) {
25168
+ if (this.currentSequence === Sequences.TitleEnd || this.currentSequence === Sequences.TextareaEnd) {
25169
+ if (this.decodeEntities && c === CharCodes2.Amp) {
25170
+ this.startEntity();
25171
+ }
25172
+ } else if (this.fastForwardTo(CharCodes2.Lt)) {
25173
+ this.sequenceIndex = 1;
25174
+ }
25175
+ } else {
25176
+ this.sequenceIndex = Number(c === CharCodes2.Lt);
25177
+ }
25178
+ }
25179
+ stateBeforeTagName(c) {
25180
+ if (c === CharCodes2.ExclamationMark) {
25181
+ this.state = State.BeforeDeclaration;
25182
+ this.sectionStart = this.index + 1;
25183
+ } else if (c === CharCodes2.Questionmark) {
25184
+ if (this.xmlMode) {
25185
+ this.state = State.InProcessingInstruction;
25186
+ this.sequenceIndex = 0;
25187
+ this.sectionStart = this.index + 1;
25188
+ } else {
25189
+ this.state = State.InSpecialComment;
25190
+ this.sectionStart = this.index;
25191
+ }
25192
+ } else if (this.isTagStartChar(c)) {
25193
+ this.sectionStart = this.index;
25194
+ const special = this.xmlMode || this.cbs.isInForeignContext?.() ? void 0 : specialStartSequences.get(c | 32);
25195
+ if (special === void 0) {
25196
+ this.state = State.InTagName;
25197
+ } else {
25198
+ this.isSpecial = true;
25199
+ this.currentSequence = special;
25200
+ this.sequenceIndex = 3;
25201
+ this.state = State.SpecialStartSequence;
25202
+ }
25203
+ } else if (c === CharCodes2.Slash) {
25204
+ this.state = State.BeforeClosingTagName;
25205
+ } else {
25206
+ this.state = State.Text;
25207
+ this.stateText(c);
25208
+ }
25209
+ }
25210
+ stateInTagName(c) {
25211
+ if (isEndOfTagSection(c)) {
25212
+ this.cbs.onopentagname(this.sectionStart, this.index);
25213
+ this.sectionStart = -1;
25214
+ this.state = State.BeforeAttributeName;
25215
+ this.stateBeforeAttributeName(c);
25216
+ }
25217
+ }
25218
+ stateBeforeClosingTagName(c) {
25219
+ if (isWhitespace2(c)) {
25220
+ if (this.xmlMode) {
25221
+ } else {
25222
+ this.state = State.InSpecialComment;
25223
+ this.sectionStart = this.index;
25224
+ }
25225
+ } else if (c === CharCodes2.Gt) {
25226
+ this.state = State.Text;
25227
+ if (!this.xmlMode) {
25228
+ this.sectionStart = this.index + 1;
25229
+ }
25230
+ } else {
25231
+ this.state = this.isTagStartChar(c) ? State.InClosingTagName : State.InSpecialComment;
25232
+ this.sectionStart = this.index;
25233
+ }
25234
+ }
25235
+ stateInClosingTagName(c) {
25236
+ if (isEndOfTagSection(c)) {
25237
+ this.cbs.onclosetag(this.sectionStart, this.index);
25238
+ this.sectionStart = -1;
25239
+ this.state = State.AfterClosingTagName;
25240
+ this.stateAfterClosingTagName(c);
25241
+ }
25242
+ }
25243
+ stateAfterClosingTagName(c) {
25244
+ if (c === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
25245
+ this.state = State.Text;
25246
+ this.sectionStart = this.index + 1;
25247
+ }
25248
+ }
25249
+ stateBeforeAttributeName(c) {
25250
+ if (c === CharCodes2.Gt) {
25251
+ this.cbs.onopentagend(this.index);
25252
+ this.enterTagBody();
25253
+ this.sectionStart = this.index + 1;
25254
+ } else if (c === CharCodes2.Slash) {
25255
+ this.state = State.InSelfClosingTag;
25256
+ } else if (!isWhitespace2(c)) {
25257
+ this.state = State.InAttributeName;
25258
+ this.sectionStart = this.index;
25259
+ }
25260
+ }
25261
+ /**
25262
+ * Handle `/` before `>` in an opening tag.
25263
+ *
25264
+ * In HTML mode, text-only tags ignore the self-closing flag and still enter
25265
+ * their raw-text/RCDATA/plaintext state unless self-closing tags are being
25266
+ * recognized. In XML mode, or for ordinary tags, the tokenizer returns to
25267
+ * regular text parsing after emitting the self-closing callback.
25268
+ * @param c Current character code point.
25269
+ */
25270
+ stateInSelfClosingTag(c) {
25271
+ if (c === CharCodes2.Gt) {
25272
+ this.cbs.onselfclosingtag(this.index);
25273
+ this.sectionStart = this.index + 1;
25274
+ if (!this.recognizeSelfClosing) {
25275
+ this.enterTagBody();
25276
+ return;
25277
+ }
25278
+ this.state = State.Text;
25279
+ this.isSpecial = false;
25280
+ this.currentSequence = Sequences.Empty;
25281
+ } else if (!isWhitespace2(c)) {
25282
+ this.state = State.BeforeAttributeName;
25283
+ this.stateBeforeAttributeName(c);
25284
+ }
25285
+ }
25286
+ stateInAttributeName(c) {
25287
+ if (c === CharCodes2.Eq || isEndOfTagSection(c)) {
25288
+ this.cbs.onattribname(this.sectionStart, this.index);
25289
+ this.sectionStart = this.index;
25290
+ this.state = State.AfterAttributeName;
25291
+ this.stateAfterAttributeName(c);
25292
+ }
25293
+ }
25294
+ stateAfterAttributeName(c) {
25295
+ if (c === CharCodes2.Eq) {
25296
+ this.state = State.BeforeAttributeValue;
25297
+ } else if (c === CharCodes2.Slash || c === CharCodes2.Gt) {
25298
+ this.cbs.onattribend(QuoteType.NoValue, this.sectionStart);
25299
+ this.sectionStart = -1;
25300
+ this.state = State.BeforeAttributeName;
25301
+ this.stateBeforeAttributeName(c);
25302
+ } else if (!isWhitespace2(c)) {
25303
+ this.cbs.onattribend(QuoteType.NoValue, this.sectionStart);
25304
+ this.state = State.InAttributeName;
25305
+ this.sectionStart = this.index;
25306
+ }
25307
+ }
25308
+ stateBeforeAttributeValue(c) {
25309
+ if (c === CharCodes2.DoubleQuote) {
25310
+ this.state = State.InAttributeValueDq;
25311
+ this.sectionStart = this.index + 1;
25312
+ } else if (c === CharCodes2.SingleQuote) {
25313
+ this.state = State.InAttributeValueSq;
25314
+ this.sectionStart = this.index + 1;
25315
+ } else if (!isWhitespace2(c)) {
25316
+ this.sectionStart = this.index;
25317
+ this.state = State.InAttributeValueNq;
25318
+ this.stateInAttributeValueNoQuotes(c);
25319
+ }
25320
+ }
25321
+ handleInAttributeValue(c, quote) {
25322
+ if (c === quote || !this.decodeEntities && this.fastForwardTo(quote)) {
25323
+ this.cbs.onattribdata(this.sectionStart, this.index);
25324
+ this.sectionStart = -1;
25325
+ this.cbs.onattribend(quote === CharCodes2.DoubleQuote ? QuoteType.Double : QuoteType.Single, this.index + 1);
25326
+ this.state = State.BeforeAttributeName;
25327
+ } else if (this.decodeEntities && c === CharCodes2.Amp) {
25328
+ this.startEntity();
25329
+ }
25330
+ }
25331
+ stateInAttributeValueDoubleQuotes(c) {
25332
+ this.handleInAttributeValue(c, CharCodes2.DoubleQuote);
25333
+ }
25334
+ stateInAttributeValueSingleQuotes(c) {
25335
+ this.handleInAttributeValue(c, CharCodes2.SingleQuote);
25336
+ }
25337
+ stateInAttributeValueNoQuotes(c) {
25338
+ if (isWhitespace2(c) || c === CharCodes2.Gt) {
25339
+ this.cbs.onattribdata(this.sectionStart, this.index);
25340
+ this.sectionStart = -1;
25341
+ this.cbs.onattribend(QuoteType.Unquoted, this.index);
25342
+ this.state = State.BeforeAttributeName;
25343
+ this.stateBeforeAttributeName(c);
25344
+ } else if (this.decodeEntities && c === CharCodes2.Amp) {
25345
+ this.startEntity();
25346
+ }
25347
+ }
25348
+ /**
25349
+ * Distinguish between CDATA, declarations, HTML comments, and HTML bogus
25350
+ * comments after `<!`.
25351
+ *
25352
+ * In HTML mode, only real comments and doctypes stay on declaration paths;
25353
+ * everything else becomes a bogus comment terminated by the next `>`.
25354
+ * @param c Current character code point.
25355
+ */
25356
+ stateBeforeDeclaration(c) {
25357
+ if (c === CharCodes2.OpeningSquareBracket) {
25358
+ this.state = State.CDATASequence;
25359
+ this.sequenceIndex = 0;
25360
+ } else if (this.xmlMode) {
25361
+ this.state = c === CharCodes2.Dash ? State.BeforeComment : State.InDeclaration;
25362
+ } else if ((c | 32) === Sequences.Doctype[0]) {
25363
+ this.state = State.DeclarationSequence;
25364
+ this.currentSequence = Sequences.Doctype;
25365
+ this.sequenceIndex = 1;
25366
+ } else if (c === CharCodes2.Gt) {
25367
+ this.cbs.oncomment(this.sectionStart, this.index, 0);
25368
+ this.state = State.Text;
25369
+ this.sectionStart = this.index + 1;
25370
+ } else if (c === CharCodes2.Dash) {
25371
+ this.state = State.BeforeComment;
25372
+ } else {
25373
+ this.state = State.InSpecialComment;
25374
+ }
25375
+ }
25376
+ /**
25377
+ * Continue matching `doctype` after `<!d`.
25378
+ *
25379
+ * A full `doctype` match stays on the declaration path; any other name falls
25380
+ * back to an HTML bogus comment, which matches browser behavior for
25381
+ * non-doctype `<!...>` constructs.
25382
+ * @param c Current character code point.
25383
+ */
25384
+ stateDeclarationSequence(c) {
25385
+ if (this.sequenceIndex === this.currentSequence.length) {
25386
+ this.state = State.InDeclaration;
25387
+ this.stateInDeclaration(c);
25388
+ } else if ((c | 32) === this.currentSequence[this.sequenceIndex]) {
25389
+ this.sequenceIndex += 1;
25390
+ } else if (c === CharCodes2.Gt) {
25391
+ this.cbs.oncomment(this.sectionStart, this.index, 0);
25392
+ this.state = State.Text;
25393
+ this.sectionStart = this.index + 1;
25394
+ } else {
25395
+ this.state = State.InSpecialComment;
25396
+ }
25397
+ }
25398
+ stateInDeclaration(c) {
25399
+ if (c === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
25400
+ this.cbs.ondeclaration(this.sectionStart, this.index);
25401
+ this.state = State.Text;
25402
+ this.sectionStart = this.index + 1;
25403
+ }
25404
+ }
25405
+ /**
25406
+ * XML processing instructions (`<?...?>`).
25407
+ *
25408
+ * In HTML mode `<?` is routed to `InSpecialComment` instead, so this
25409
+ * state is only reachable in XML mode.
25410
+ * @param c Current character code point.
25411
+ */
25412
+ stateInProcessingInstruction(c) {
25413
+ if (c === CharCodes2.Questionmark) {
25414
+ this.sequenceIndex = 1;
25415
+ } else if (c === CharCodes2.Gt && this.sequenceIndex === 1) {
25416
+ this.cbs.onprocessinginstruction(this.sectionStart, this.index - 1);
25417
+ this.sequenceIndex = 0;
25418
+ this.state = State.Text;
25419
+ this.sectionStart = this.index + 1;
25420
+ } else {
25421
+ this.sequenceIndex = Number(this.fastForwardTo(CharCodes2.Questionmark));
25422
+ }
25423
+ }
25424
+ stateBeforeComment(c) {
25425
+ if (c === CharCodes2.Dash) {
25426
+ this.state = State.InCommentLike;
25427
+ this.currentSequence = Sequences.CommentEnd;
25428
+ this.sequenceIndex = 0;
25429
+ this.sectionStart = this.index + 1;
25430
+ } else if (this.xmlMode) {
25431
+ this.state = State.InDeclaration;
25432
+ } else if (c === CharCodes2.Gt) {
25433
+ this.cbs.oncomment(this.sectionStart, this.index, 0);
25434
+ this.state = State.Text;
25435
+ this.sectionStart = this.index + 1;
25436
+ } else {
25437
+ this.state = State.InSpecialComment;
25438
+ }
25439
+ }
25440
+ stateInSpecialComment(c) {
25441
+ if (c === CharCodes2.Gt || this.fastForwardTo(CharCodes2.Gt)) {
25442
+ this.cbs.oncomment(this.sectionStart, this.index, 0);
25443
+ this.state = State.Text;
25444
+ this.sectionStart = this.index + 1;
25445
+ }
25446
+ }
25447
+ startEntity() {
25448
+ this.baseState = this.state;
25449
+ this.state = State.InEntity;
25450
+ this.entityStart = this.index;
25451
+ this.entityDecoder.startEntity(this.xmlMode ? DecodingMode.Strict : this.baseState === State.Text || this.baseState === State.InSpecialTag ? DecodingMode.Legacy : DecodingMode.Attribute);
25452
+ }
25453
+ stateInEntity() {
25454
+ const indexInBuffer = this.index - this.offset;
25455
+ const length = this.entityDecoder.write(this.buffer, indexInBuffer);
25456
+ if (length >= 0) {
25457
+ this.state = this.baseState;
25458
+ if (length === 0) {
25459
+ this.index -= 1;
25460
+ }
25461
+ } else {
25462
+ if (indexInBuffer < this.buffer.length && this.buffer.charCodeAt(indexInBuffer) === CharCodes2.Amp) {
25463
+ this.state = this.baseState;
25464
+ this.index -= 1;
25465
+ return;
25466
+ }
25467
+ this.index = this.offset + this.buffer.length - 1;
25468
+ }
25469
+ }
25470
+ /**
25471
+ * Remove data that has already been consumed from the buffer.
25472
+ */
25473
+ cleanup() {
25474
+ if (this.running && this.sectionStart !== this.index) {
25475
+ if (this.state === State.Text || this.state === State.InPlainText || this.state === State.InSpecialTag && this.sequenceIndex === 0) {
25476
+ this.cbs.ontext(this.sectionStart, this.index);
25477
+ this.sectionStart = this.index;
25478
+ } else if (this.state === State.InAttributeValueDq || this.state === State.InAttributeValueSq || this.state === State.InAttributeValueNq) {
25479
+ this.cbs.onattribdata(this.sectionStart, this.index);
25480
+ this.sectionStart = this.index;
25481
+ }
25482
+ }
25483
+ }
25484
+ shouldContinue() {
25485
+ return this.index < this.buffer.length + this.offset && this.running;
25486
+ }
25487
+ /**
25488
+ * Iterates through the buffer, calling the function corresponding to the current state.
25489
+ *
25490
+ * States that are more likely to be hit are higher up, as a performance improvement.
25491
+ */
25492
+ parse() {
25493
+ while (this.shouldContinue()) {
25494
+ const c = this.buffer.charCodeAt(this.index - this.offset);
25495
+ switch (this.state) {
25496
+ case State.Text: {
25497
+ this.stateText(c);
25498
+ break;
25499
+ }
25500
+ case State.InPlainText: {
25501
+ this.index = this.buffer.length + this.offset - 1;
25502
+ break;
25503
+ }
25504
+ case State.SpecialStartSequence: {
25505
+ this.stateSpecialStartSequence(c);
25506
+ break;
25507
+ }
25508
+ case State.InSpecialTag: {
25509
+ this.stateInSpecialTag(c);
25510
+ break;
25511
+ }
25512
+ case State.CDATASequence: {
25513
+ this.stateCDATASequence(c);
25514
+ break;
25515
+ }
25516
+ case State.DeclarationSequence: {
25517
+ this.stateDeclarationSequence(c);
25518
+ break;
25519
+ }
25520
+ case State.InAttributeValueDq: {
25521
+ this.stateInAttributeValueDoubleQuotes(c);
25522
+ break;
25523
+ }
25524
+ case State.InAttributeName: {
25525
+ this.stateInAttributeName(c);
25526
+ break;
25527
+ }
25528
+ case State.InCommentLike: {
25529
+ this.stateInCommentLike(c);
25530
+ break;
25531
+ }
25532
+ case State.InSpecialComment: {
25533
+ this.stateInSpecialComment(c);
25534
+ break;
25535
+ }
25536
+ case State.BeforeAttributeName: {
25537
+ this.stateBeforeAttributeName(c);
25538
+ break;
25539
+ }
25540
+ case State.InTagName: {
25541
+ this.stateInTagName(c);
25542
+ break;
25543
+ }
25544
+ case State.InClosingTagName: {
25545
+ this.stateInClosingTagName(c);
25546
+ break;
25547
+ }
25548
+ case State.BeforeTagName: {
25549
+ this.stateBeforeTagName(c);
25550
+ break;
25551
+ }
25552
+ case State.AfterAttributeName: {
25553
+ this.stateAfterAttributeName(c);
25554
+ break;
25555
+ }
25556
+ case State.InAttributeValueSq: {
25557
+ this.stateInAttributeValueSingleQuotes(c);
25558
+ break;
25559
+ }
25560
+ case State.BeforeAttributeValue: {
25561
+ this.stateBeforeAttributeValue(c);
25562
+ break;
25563
+ }
25564
+ case State.BeforeClosingTagName: {
25565
+ this.stateBeforeClosingTagName(c);
25566
+ break;
25567
+ }
25568
+ case State.AfterClosingTagName: {
25569
+ this.stateAfterClosingTagName(c);
25570
+ break;
25571
+ }
25572
+ case State.InAttributeValueNq: {
25573
+ this.stateInAttributeValueNoQuotes(c);
25574
+ break;
25575
+ }
25576
+ case State.InSelfClosingTag: {
25577
+ this.stateInSelfClosingTag(c);
25578
+ break;
25579
+ }
25580
+ case State.InDeclaration: {
25581
+ this.stateInDeclaration(c);
25582
+ break;
25583
+ }
25584
+ case State.BeforeDeclaration: {
25585
+ this.stateBeforeDeclaration(c);
25586
+ break;
25587
+ }
25588
+ case State.BeforeComment: {
25589
+ this.stateBeforeComment(c);
25590
+ break;
25591
+ }
25592
+ case State.InProcessingInstruction: {
25593
+ this.stateInProcessingInstruction(c);
25594
+ break;
25595
+ }
25596
+ case State.InEntity: {
25597
+ this.stateInEntity();
25598
+ break;
25599
+ }
25600
+ }
25601
+ this.index++;
25602
+ }
25603
+ this.cleanup();
25604
+ }
25605
+ finish() {
25606
+ if (this.state === State.InEntity) {
25607
+ this.entityDecoder.end();
25608
+ this.state = this.baseState;
25609
+ }
25610
+ this.handleTrailingData();
25611
+ this.cbs.onend();
25612
+ }
25613
+ handleTrailingCommentLikeData(endIndex) {
25614
+ if (this.state !== State.InCommentLike) {
25615
+ return false;
25616
+ }
25617
+ if (this.currentSequence === Sequences.CdataEnd) {
25618
+ if (this.xmlMode) {
25619
+ if (this.sectionStart < endIndex) {
25620
+ this.cbs.oncdata(this.sectionStart, endIndex, 0);
25621
+ }
25622
+ } else {
25623
+ const cdataStart = this.sectionStart - Sequences.Cdata.length - 1;
25624
+ this.cbs.oncomment(cdataStart, endIndex, 0);
25625
+ }
25626
+ } else {
25627
+ const offset = this.xmlMode ? 0 : Math.min(this.sequenceIndex, Sequences.CommentEnd.length - 1);
25628
+ this.cbs.oncomment(this.sectionStart, endIndex, offset);
25629
+ }
25630
+ return true;
25631
+ }
25632
+ handleTrailingMarkupDeclaration(endIndex) {
25633
+ if (this.xmlMode) {
25634
+ switch (this.state) {
25635
+ case State.InSpecialComment:
25636
+ case State.BeforeComment:
25637
+ case State.CDATASequence:
25638
+ case State.DeclarationSequence:
25639
+ case State.InDeclaration: {
25640
+ this.cbs.ontext(this.sectionStart, endIndex);
25641
+ return true;
25642
+ }
25643
+ default: {
25644
+ return false;
25645
+ }
25646
+ }
25647
+ }
25648
+ switch (this.state) {
25649
+ case State.BeforeDeclaration:
25650
+ case State.InSpecialComment:
25651
+ case State.BeforeComment:
25652
+ case State.CDATASequence: {
25653
+ this.cbs.oncomment(this.sectionStart, endIndex, 0);
25654
+ return true;
25655
+ }
25656
+ case State.DeclarationSequence: {
25657
+ if (this.sequenceIndex !== Sequences.Doctype.length) {
25658
+ this.cbs.oncomment(this.sectionStart, endIndex, 0);
25659
+ }
25660
+ return true;
25661
+ }
25662
+ case State.InDeclaration: {
25663
+ return true;
25664
+ }
25665
+ default: {
25666
+ return false;
25667
+ }
25668
+ }
25669
+ }
25670
+ /** Handle any trailing data. */
25671
+ handleTrailingData() {
25672
+ const endIndex = this.buffer.length + this.offset;
25673
+ if (this.handleTrailingCommentLikeData(endIndex) || this.handleTrailingMarkupDeclaration(endIndex)) {
25674
+ return;
25675
+ }
25676
+ if (this.sectionStart >= endIndex) {
25677
+ return;
25678
+ }
25679
+ switch (this.state) {
25680
+ case State.InTagName:
25681
+ case State.BeforeAttributeName:
25682
+ case State.BeforeAttributeValue:
25683
+ case State.AfterAttributeName:
25684
+ case State.InAttributeName:
25685
+ case State.InAttributeValueSq:
25686
+ case State.InAttributeValueDq:
25687
+ case State.InAttributeValueNq:
25688
+ case State.InClosingTagName: {
25689
+ break;
25690
+ }
25691
+ default: {
25692
+ this.cbs.ontext(this.sectionStart, endIndex);
25693
+ }
25694
+ }
25695
+ }
25696
+ emitCodePoint(cp, consumed) {
25697
+ if (this.baseState !== State.Text && this.baseState !== State.InSpecialTag) {
25698
+ if (this.sectionStart < this.entityStart) {
25699
+ this.cbs.onattribdata(this.sectionStart, this.entityStart);
25700
+ }
25701
+ this.sectionStart = this.entityStart + consumed;
25702
+ this.index = this.sectionStart - 1;
25703
+ this.cbs.onattribentity(cp);
25704
+ } else {
25705
+ if (this.sectionStart < this.entityStart) {
25706
+ this.cbs.ontext(this.sectionStart, this.entityStart);
25707
+ }
25708
+ this.sectionStart = this.entityStart + consumed;
25709
+ this.index = this.sectionStart - 1;
25710
+ this.cbs.ontextentity(cp, this.sectionStart);
25711
+ }
25712
+ }
25713
+ };
25714
+
25715
+ // node_modules/htmlparser2/dist/Parser.js
25716
+ var { fromCodePoint } = String;
25717
+ var formTags = /* @__PURE__ */ new Set([
25718
+ "input",
25719
+ "option",
25720
+ "optgroup",
25721
+ "select",
25722
+ "button",
25723
+ "datalist",
25724
+ "textarea"
25725
+ ]);
25726
+ var pTag = /* @__PURE__ */ new Set(["p"]);
25727
+ var headingTags = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6", "p"]);
25728
+ var tableSectionTags = /* @__PURE__ */ new Set(["thead", "tbody"]);
25729
+ var ddtTags = /* @__PURE__ */ new Set(["dd", "dt"]);
25730
+ var rtpTags = /* @__PURE__ */ new Set(["rt", "rp"]);
25731
+ var openImpliesClose = /* @__PURE__ */ new Map([
25732
+ ["tr", /* @__PURE__ */ new Set(["tr", "th", "td"])],
25733
+ ["th", /* @__PURE__ */ new Set(["th"])],
25734
+ ["td", /* @__PURE__ */ new Set(["thead", "th", "td"])],
25735
+ ["body", /* @__PURE__ */ new Set(["head", "link", "script"])],
25736
+ ["a", /* @__PURE__ */ new Set(["a"])],
25737
+ ["li", /* @__PURE__ */ new Set(["li"])],
25738
+ ["p", pTag],
25739
+ ["h1", headingTags],
25740
+ ["h2", headingTags],
25741
+ ["h3", headingTags],
25742
+ ["h4", headingTags],
25743
+ ["h5", headingTags],
25744
+ ["h6", headingTags],
25745
+ ["select", formTags],
25746
+ ["input", formTags],
25747
+ ["output", formTags],
25748
+ ["button", formTags],
25749
+ ["datalist", formTags],
25750
+ ["textarea", formTags],
25751
+ ["option", /* @__PURE__ */ new Set(["option"])],
25752
+ ["optgroup", /* @__PURE__ */ new Set(["optgroup", "option"])],
25753
+ ["dd", ddtTags],
25754
+ ["dt", ddtTags],
25755
+ ["address", pTag],
25756
+ ["article", pTag],
25757
+ ["aside", pTag],
25758
+ ["blockquote", pTag],
25759
+ ["details", pTag],
25760
+ ["div", pTag],
25761
+ ["dl", pTag],
25762
+ ["fieldset", pTag],
25763
+ ["figcaption", pTag],
25764
+ ["figure", pTag],
25765
+ ["footer", pTag],
25766
+ ["form", pTag],
25767
+ ["header", pTag],
25768
+ ["hr", pTag],
25769
+ ["main", pTag],
25770
+ ["nav", pTag],
25771
+ ["ol", pTag],
25772
+ ["pre", pTag],
25773
+ ["section", pTag],
25774
+ ["table", pTag],
25775
+ ["ul", pTag],
25776
+ ["rt", rtpTags],
25777
+ ["rp", rtpTags],
25778
+ ["tbody", tableSectionTags],
25779
+ ["tfoot", tableSectionTags]
25780
+ ]);
25781
+ var DOCUMENT_TYPE = "doctype";
25782
+ var voidElements = /* @__PURE__ */ new Set([
25783
+ "area",
25784
+ "base",
25785
+ "basefont",
25786
+ "br",
25787
+ "col",
25788
+ "command",
25789
+ "embed",
25790
+ "frame",
25791
+ "hr",
25792
+ "img",
25793
+ "input",
25794
+ "isindex",
25795
+ "keygen",
25796
+ "link",
25797
+ "meta",
25798
+ "param",
25799
+ "source",
25800
+ "track",
25801
+ "wbr"
25802
+ ]);
25803
+ var foreignContextElements = /* @__PURE__ */ new Set(["math", "svg"]);
25804
+ var htmlIntegrationElements = /* @__PURE__ */ new Set([
25805
+ "mi",
25806
+ "mo",
25807
+ "mn",
25808
+ "ms",
25809
+ "mtext",
25810
+ "annotation-xml",
25811
+ "foreignObject",
25812
+ "desc",
25813
+ "title"
25814
+ ]);
25815
+ var svgTagNameAdjustments = /* @__PURE__ */ new Map([
25816
+ ["altglyph", "altGlyph"],
25817
+ ["altglyphdef", "altGlyphDef"],
25818
+ ["altglyphitem", "altGlyphItem"],
25819
+ ["animatecolor", "animateColor"],
25820
+ ["animatemotion", "animateMotion"],
25821
+ ["animatetransform", "animateTransform"],
25822
+ ["clippath", "clipPath"],
25823
+ ["feblend", "feBlend"],
25824
+ ["fecolormatrix", "feColorMatrix"],
25825
+ ["fecomponenttransfer", "feComponentTransfer"],
25826
+ ["fecomposite", "feComposite"],
25827
+ ["feconvolvematrix", "feConvolveMatrix"],
25828
+ ["fediffuselighting", "feDiffuseLighting"],
25829
+ ["fedisplacementmap", "feDisplacementMap"],
25830
+ ["fedistantlight", "feDistantLight"],
25831
+ ["fedropshadow", "feDropShadow"],
25832
+ ["feflood", "feFlood"],
25833
+ ["fefunca", "feFuncA"],
25834
+ ["fefuncb", "feFuncB"],
25835
+ ["fefuncg", "feFuncG"],
25836
+ ["fefuncr", "feFuncR"],
25837
+ ["fegaussianblur", "feGaussianBlur"],
25838
+ ["feimage", "feImage"],
25839
+ ["femerge", "feMerge"],
25840
+ ["femergenode", "feMergeNode"],
25841
+ ["femorphology", "feMorphology"],
25842
+ ["feoffset", "feOffset"],
25843
+ ["fepointlight", "fePointLight"],
25844
+ ["fespecularlighting", "feSpecularLighting"],
25845
+ ["fespotlight", "feSpotLight"],
25846
+ ["fetile", "feTile"],
25847
+ ["feturbulence", "feTurbulence"],
25848
+ ["foreignobject", "foreignObject"],
25849
+ ["glyphref", "glyphRef"],
25850
+ ["lineargradient", "linearGradient"],
25851
+ ["radialgradient", "radialGradient"],
25852
+ ["textpath", "textPath"]
25853
+ ]);
25854
+ var ForeignContext;
25855
+ (function(ForeignContext2) {
25856
+ ForeignContext2[ForeignContext2["None"] = 0] = "None";
25857
+ ForeignContext2[ForeignContext2["Svg"] = 1] = "Svg";
25858
+ ForeignContext2[ForeignContext2["MathML"] = 2] = "MathML";
25859
+ })(ForeignContext || (ForeignContext = {}));
25860
+ var reNameEnd = /\s|\//;
25861
+ var Parser = class {
25862
+ options;
25863
+ /** The start index of the last event. */
25864
+ startIndex = 0;
25865
+ /** The end index of the last event. */
25866
+ endIndex = 0;
25867
+ /**
25868
+ * Store the start index of the current open tag,
25869
+ * so we can update the start index for attributes.
25870
+ */
25871
+ openTagStart = 0;
25872
+ tagname = "";
25873
+ attribname = "";
25874
+ attribvalue = "";
25875
+ attribs = null;
25876
+ stack = [];
25877
+ foreignContext;
25878
+ cbs;
25879
+ lowerCaseTagNames;
25880
+ lowerCaseAttributeNames;
25881
+ recognizeSelfClosing;
25882
+ /** We are parsing HTML. Inverse of the `xmlMode` option. */
25883
+ htmlMode;
25884
+ tokenizer;
25885
+ buffers = [];
25886
+ bufferOffset = 0;
25887
+ /** The index of the last written buffer. Used when resuming after a `pause()`. */
25888
+ writeIndex = 0;
25889
+ /** Indicates whether the parser has finished running / `.end` has been called. */
25890
+ ended = false;
25891
+ constructor(cbs, options = {}) {
25892
+ this.options = options;
25893
+ this.cbs = cbs ?? {};
25894
+ this.htmlMode = !this.options.xmlMode;
25895
+ this.lowerCaseTagNames = options.lowerCaseTags ?? this.htmlMode;
25896
+ this.lowerCaseAttributeNames = options.lowerCaseAttributeNames ?? this.htmlMode;
25897
+ this.recognizeSelfClosing = options.recognizeSelfClosing ?? !this.htmlMode;
25898
+ this.tokenizer = new (options.Tokenizer ?? Tokenizer2)(this.options, this);
25899
+ this.foreignContext = [ForeignContext.None];
25900
+ this.cbs.onparserinit?.(this);
25901
+ }
25902
+ // Tokenizer event handlers
25903
+ /**
25904
+ * @param start Start index for the current parser event.
25905
+ * @param endIndex End index for the current parser event.
25906
+ * @internal
25907
+ */
25908
+ ontext(start, endIndex) {
25909
+ const data = this.getSlice(start, endIndex);
25910
+ this.endIndex = endIndex - 1;
25911
+ this.cbs.ontext?.(data);
25912
+ this.startIndex = endIndex;
25913
+ }
25914
+ /**
25915
+ * @param cp Current Unicode code point.
25916
+ * @param endIndex End index for the current parser event.
25917
+ * @internal
25918
+ */
25919
+ ontextentity(cp, endIndex) {
25920
+ this.endIndex = endIndex - 1;
25921
+ this.cbs.ontext?.(fromCodePoint(cp));
25922
+ this.startIndex = endIndex;
25923
+ }
25924
+ /** @internal */
25925
+ isInForeignContext() {
25926
+ return this.foreignContext[0] !== ForeignContext.None;
25927
+ }
25928
+ /**
25929
+ * Checks if the current tag is a void element. Override this if you want
25930
+ * to specify your own additional void elements.
25931
+ * @param name Name of the pseudo selector.
25932
+ */
25933
+ isVoidElement(name) {
25934
+ return this.htmlMode && voidElements.has(name);
25935
+ }
25936
+ /**
25937
+ * Read a tag name from the buffer.
25938
+ *
25939
+ * When `lowerCaseTagNames` is enabled (the default in HTML mode), the name
25940
+ * is lowercased and may be adjusted for SVG casing or the `image` → `img`
25941
+ * alias.
25942
+ * @param start Start index of the tag name in the buffer.
25943
+ * @param endIndex End index of the tag name in the buffer.
25944
+ */
25945
+ readTagName(start, endIndex) {
25946
+ const name = this.lowerCaseTagNames ? this.getSlice(start, endIndex).toLowerCase() : this.getSlice(start, endIndex);
25947
+ if (!(this.lowerCaseTagNames && this.htmlMode)) {
25948
+ return name;
25949
+ }
25950
+ if (this.foreignContext[0] === ForeignContext.Svg) {
25951
+ return svgTagNameAdjustments.get(name) ?? name;
25952
+ }
25953
+ if (this.foreignContext.length > 1) {
25954
+ const adjusted = svgTagNameAdjustments.get(name);
25955
+ if (adjusted !== void 0 && this.stack.includes(adjusted)) {
25956
+ return adjusted;
25957
+ }
25958
+ }
25959
+ if (!this.isInForeignContext()) {
25960
+ return name === "image" ? "img" : name;
25961
+ }
25962
+ return name;
25963
+ }
25964
+ /**
25965
+ * @param start Start index for the current parser event.
25966
+ * @param endIndex End index for the current parser event.
25967
+ * @internal
25968
+ */
25969
+ onopentagname(start, endIndex) {
25970
+ this.endIndex = endIndex;
25971
+ this.emitOpenTag(this.readTagName(start, endIndex));
25972
+ }
25973
+ emitOpenTag(name) {
25974
+ this.openTagStart = this.startIndex;
25975
+ this.tagname = name;
25976
+ if (this.htmlMode && name === "form" && this.stack.includes("form")) {
25977
+ this.tagname = "";
25978
+ return;
25979
+ }
25980
+ const impliesClose = this.htmlMode && openImpliesClose.get(name);
25981
+ if (impliesClose) {
25982
+ while (this.stack.length > 0 && impliesClose.has(this.stack[0])) {
25983
+ this.popElement(true);
25984
+ }
25985
+ }
25986
+ if (!this.isVoidElement(name)) {
25987
+ this.stack.unshift(name);
25988
+ if (this.htmlMode) {
25989
+ if (name === "svg") {
25990
+ this.foreignContext.unshift(ForeignContext.Svg);
25991
+ } else if (name === "math") {
25992
+ this.foreignContext.unshift(ForeignContext.MathML);
25993
+ } else if (htmlIntegrationElements.has(name)) {
25994
+ this.foreignContext.unshift(ForeignContext.None);
25995
+ }
25996
+ }
25997
+ }
25998
+ this.cbs.onopentagname?.(name);
25999
+ if (this.cbs.onopentag)
26000
+ this.attribs = {};
26001
+ }
26002
+ endOpenTag(isImplied) {
26003
+ this.startIndex = this.openTagStart;
26004
+ if (this.attribs) {
26005
+ this.cbs.onopentag?.(this.tagname, this.attribs, isImplied);
26006
+ this.attribs = null;
26007
+ }
26008
+ if (this.cbs.onclosetag && this.isVoidElement(this.tagname)) {
26009
+ this.cbs.onclosetag(this.tagname, true);
26010
+ }
26011
+ this.tagname = "";
26012
+ }
26013
+ /**
26014
+ * @param endIndex End index for the current parser event.
26015
+ * @internal
26016
+ */
26017
+ onopentagend(endIndex) {
26018
+ this.endIndex = endIndex;
26019
+ this.endOpenTag(false);
26020
+ this.startIndex = endIndex + 1;
26021
+ }
26022
+ /**
26023
+ * @param start Start index for the current parser event.
26024
+ * @param endIndex End index for the current parser event.
26025
+ * @internal
26026
+ */
26027
+ onclosetag(start, endIndex) {
26028
+ this.endIndex = endIndex;
26029
+ const name = this.readTagName(start, endIndex);
26030
+ if (!this.isVoidElement(name)) {
26031
+ const pos = this.stack.indexOf(name);
26032
+ if (pos !== -1) {
26033
+ for (let index = 0; index < pos; index++) {
26034
+ this.popElement(true);
26035
+ }
26036
+ this.popElement(false);
26037
+ } else if (this.htmlMode && name === "p") {
26038
+ this.emitOpenTag("p");
26039
+ this.closeCurrentTag(true);
26040
+ }
26041
+ } else if (this.htmlMode && name === "br") {
26042
+ this.cbs.onopentagname?.("br");
26043
+ this.cbs.onopentag?.("br", {}, true);
26044
+ this.cbs.onclosetag?.("br", false);
26045
+ }
26046
+ this.startIndex = endIndex + 1;
26047
+ }
26048
+ /**
26049
+ * @param endIndex End index for the current parser event.
26050
+ * @internal
26051
+ */
26052
+ onselfclosingtag(endIndex) {
26053
+ this.endIndex = endIndex;
26054
+ if (this.recognizeSelfClosing || this.isInForeignContext()) {
26055
+ this.closeCurrentTag(false);
26056
+ this.startIndex = endIndex + 1;
26057
+ } else {
26058
+ this.onopentagend(endIndex);
26059
+ }
26060
+ }
26061
+ /**
26062
+ * Pop the top element off the stack, emit a close event, and maintain
26063
+ * the foreign context stack.
26064
+ * @param implied Whether this close is implied (not from an explicit end tag).
26065
+ */
26066
+ popElement(implied) {
26067
+ const element2 = this.stack.shift();
26068
+ if (this.htmlMode && (foreignContextElements.has(element2) || htmlIntegrationElements.has(element2))) {
26069
+ this.foreignContext.shift();
26070
+ }
26071
+ this.cbs.onclosetag?.(element2, implied);
26072
+ }
26073
+ closeCurrentTag(isOpenImplied) {
26074
+ const name = this.tagname;
26075
+ this.endOpenTag(isOpenImplied);
26076
+ if (this.stack[0] === name) {
26077
+ this.popElement(!isOpenImplied);
26078
+ }
26079
+ }
26080
+ /**
26081
+ * @param start Start index for the current parser event.
26082
+ * @param endIndex End index for the current parser event.
26083
+ * @internal
26084
+ */
26085
+ onattribname(start, endIndex) {
26086
+ this.startIndex = start;
26087
+ const name = this.getSlice(start, endIndex);
26088
+ this.attribname = this.lowerCaseAttributeNames ? name.toLowerCase() : name;
26089
+ }
26090
+ /**
26091
+ * @param start Start index for the current parser event.
26092
+ * @param endIndex End index for the current parser event.
26093
+ * @internal
26094
+ */
26095
+ onattribdata(start, endIndex) {
26096
+ this.attribvalue += this.getSlice(start, endIndex);
26097
+ }
26098
+ /**
26099
+ * @param cp Current Unicode code point.
26100
+ * @internal
26101
+ */
26102
+ onattribentity(cp) {
26103
+ this.attribvalue += fromCodePoint(cp);
26104
+ }
26105
+ /**
26106
+ * @param quote Quote type used for the current attribute.
26107
+ * @param endIndex End index for the current parser event.
26108
+ * @internal
26109
+ */
26110
+ onattribend(quote, endIndex) {
26111
+ this.endIndex = endIndex;
26112
+ this.cbs.onattribute?.(this.attribname, this.attribvalue, quote === QuoteType.Double ? '"' : quote === QuoteType.Single ? "'" : quote === QuoteType.NoValue ? void 0 : null);
26113
+ if (this.attribs && !Object.hasOwn(this.attribs, this.attribname)) {
26114
+ this.attribs[this.attribname] = this.attribvalue;
26115
+ }
26116
+ this.attribvalue = "";
26117
+ }
26118
+ getInstructionName(value) {
26119
+ const index = value.search(reNameEnd);
26120
+ let name = index < 0 ? value : value.substr(0, index);
26121
+ if (this.lowerCaseTagNames) {
26122
+ name = name.toLowerCase();
26123
+ }
26124
+ return name;
26125
+ }
26126
+ /**
26127
+ * @param start Start index for the current parser event.
26128
+ * @param endIndex End index for the current parser event.
26129
+ * @internal
26130
+ */
26131
+ ondeclaration(start, endIndex) {
26132
+ this.endIndex = endIndex;
26133
+ const value = this.getSlice(start, endIndex);
26134
+ if (this.cbs.onprocessinginstruction) {
26135
+ const name = this.htmlMode ? this.lowerCaseTagNames ? DOCUMENT_TYPE : value.slice(0, DOCUMENT_TYPE.length) : this.getInstructionName(value);
26136
+ this.cbs.onprocessinginstruction(`!${name}`, `!${value}`);
26137
+ }
26138
+ this.startIndex = endIndex + 1;
26139
+ }
26140
+ /**
26141
+ * @param start Start index for the current parser event.
26142
+ * @param endIndex End index for the current parser event.
26143
+ * @internal
26144
+ */
26145
+ onprocessinginstruction(start, endIndex) {
26146
+ this.endIndex = endIndex;
26147
+ const value = this.getSlice(start, endIndex);
26148
+ if (this.cbs.onprocessinginstruction) {
26149
+ const name = this.getInstructionName(value);
26150
+ this.cbs.onprocessinginstruction(`?${name}`, `?${value}`);
26151
+ }
26152
+ this.startIndex = endIndex + 1;
26153
+ }
26154
+ /**
26155
+ * @param start Start index for the current parser event.
26156
+ * @param endIndex End index for the current parser event.
26157
+ * @param offset Offset applied when computing parser indices.
26158
+ * @internal
26159
+ */
26160
+ oncomment(start, endIndex, offset) {
26161
+ this.endIndex = endIndex;
26162
+ this.cbs.oncomment?.(this.getSlice(start, endIndex - offset));
26163
+ this.cbs.oncommentend?.();
26164
+ this.startIndex = endIndex + 1;
26165
+ }
26166
+ /**
26167
+ * @param start Start index for the current parser event.
26168
+ * @param endIndex End index for the current parser event.
26169
+ * @param offset Offset applied when computing parser indices.
26170
+ * @internal
26171
+ */
26172
+ oncdata(start, endIndex, offset) {
26173
+ this.endIndex = endIndex;
26174
+ const value = this.getSlice(start, endIndex - offset);
26175
+ if (!this.htmlMode || this.options.recognizeCDATA) {
26176
+ this.cbs.oncdatastart?.();
26177
+ this.cbs.ontext?.(value);
26178
+ this.cbs.oncdataend?.();
26179
+ } else if (this.isInForeignContext()) {
26180
+ this.cbs.ontext?.(value);
26181
+ } else {
26182
+ this.cbs.oncomment?.(`[CDATA[${value}]]`);
26183
+ this.cbs.oncommentend?.();
26184
+ }
26185
+ this.startIndex = endIndex + 1;
26186
+ }
26187
+ /** @internal */
26188
+ onend() {
26189
+ if (this.cbs.onclosetag) {
26190
+ this.endIndex = this.startIndex;
26191
+ for (let index = 0; index < this.stack.length; index++) {
26192
+ this.cbs.onclosetag(this.stack[index], true);
26193
+ }
26194
+ }
26195
+ this.cbs.onend?.();
26196
+ }
26197
+ /**
26198
+ * Resets the parser to a blank state, ready to parse a new HTML document
26199
+ */
26200
+ reset() {
26201
+ this.cbs.onreset?.();
26202
+ this.tokenizer.reset();
26203
+ this.tagname = "";
26204
+ this.attribname = "";
26205
+ this.attribvalue = "";
26206
+ this.attribs = null;
26207
+ this.stack.length = 0;
26208
+ this.startIndex = 0;
26209
+ this.endIndex = 0;
26210
+ this.cbs.onparserinit?.(this);
26211
+ this.buffers.length = 0;
26212
+ this.foreignContext.length = 0;
26213
+ this.foreignContext.unshift(ForeignContext.None);
26214
+ this.bufferOffset = 0;
26215
+ this.writeIndex = 0;
26216
+ this.ended = false;
26217
+ }
26218
+ /**
26219
+ * Resets the parser, then parses a complete document and
26220
+ * pushes it to the handler.
26221
+ * @param data Document to parse.
26222
+ */
26223
+ parseComplete(data) {
26224
+ this.reset();
26225
+ this.end(data);
26226
+ }
26227
+ getSlice(start, end) {
26228
+ if (start === end) {
26229
+ return "";
26230
+ }
26231
+ while (start - this.bufferOffset >= this.buffers[0].length) {
26232
+ this.shiftBuffer();
26233
+ }
26234
+ let slice = this.buffers[0].slice(start - this.bufferOffset, end - this.bufferOffset);
26235
+ while (end - this.bufferOffset > this.buffers[0].length) {
26236
+ this.shiftBuffer();
26237
+ slice += this.buffers[0].slice(0, end - this.bufferOffset);
26238
+ }
26239
+ return slice;
26240
+ }
26241
+ shiftBuffer() {
26242
+ this.bufferOffset += this.buffers[0].length;
26243
+ this.writeIndex--;
26244
+ this.buffers.shift();
26245
+ }
26246
+ /**
26247
+ * Parses a chunk of data and calls the corresponding callbacks.
26248
+ * @param chunk Chunk to parse.
26249
+ */
26250
+ write(chunk) {
26251
+ if (this.ended) {
26252
+ this.cbs.onerror?.(new Error(".write() after done!"));
26253
+ return;
26254
+ }
26255
+ this.buffers.push(chunk);
26256
+ if (this.tokenizer.running) {
26257
+ this.tokenizer.write(chunk);
26258
+ this.writeIndex++;
26259
+ }
26260
+ }
26261
+ /**
26262
+ * Parses the end of the buffer and clears the stack, calls onend.
26263
+ * @param chunk Optional final chunk to parse.
26264
+ */
26265
+ end(chunk) {
26266
+ if (this.ended) {
26267
+ this.cbs.onerror?.(new Error(".end() after done!"));
26268
+ return;
26269
+ }
26270
+ if (chunk)
26271
+ this.write(chunk);
26272
+ this.ended = true;
26273
+ this.tokenizer.end();
26274
+ }
26275
+ /**
26276
+ * Pauses parsing. The parser won't emit events until `resume` is called.
26277
+ */
26278
+ pause() {
26279
+ this.tokenizer.pause();
26280
+ }
26281
+ /**
26282
+ * Resumes parsing after `pause` was called.
26283
+ */
26284
+ resume() {
26285
+ this.tokenizer.resume();
26286
+ while (this.tokenizer.running && this.writeIndex < this.buffers.length) {
26287
+ this.tokenizer.write(this.buffers[this.writeIndex++]);
26288
+ }
26289
+ if (this.ended)
26290
+ this.tokenizer.end();
26291
+ }
26292
+ };
26293
+
26294
+ // node_modules/domelementtype/dist/index.js
26295
+ var ElementType;
26296
+ (function(ElementType2) {
26297
+ ElementType2["Root"] = "root";
26298
+ ElementType2["Text"] = "text";
26299
+ ElementType2["Directive"] = "directive";
26300
+ ElementType2["Comment"] = "comment";
26301
+ ElementType2["Script"] = "script";
26302
+ ElementType2["Style"] = "style";
26303
+ ElementType2["Tag"] = "tag";
26304
+ ElementType2["CDATA"] = "cdata";
26305
+ ElementType2["Doctype"] = "doctype";
26306
+ })(ElementType || (ElementType = {}));
26307
+ function isTag(element2) {
26308
+ return element2.type === ElementType.Tag || element2.type === ElementType.Script || element2.type === ElementType.Style;
26309
+ }
26310
+ var Root = ElementType.Root;
26311
+ var Text = ElementType.Text;
26312
+ var Directive = ElementType.Directive;
26313
+ var Comment = ElementType.Comment;
26314
+ var Script = ElementType.Script;
26315
+ var Style = ElementType.Style;
26316
+ var Tag = ElementType.Tag;
26317
+ var CDATA = ElementType.CDATA;
26318
+ var Doctype = ElementType.Doctype;
26319
+
26320
+ // node_modules/domhandler/dist/node.js
26321
+ var Node = class {
26322
+ /** Parent of the node */
26323
+ parent = null;
26324
+ /** Previous sibling */
26325
+ prev = null;
26326
+ /** Next sibling */
26327
+ next = null;
26328
+ /** The start index of the node. Requires `withStartIndices` on the handler to be `true. */
26329
+ startIndex = null;
26330
+ /** The end index of the node. Requires `withEndIndices` on the handler to be `true. */
26331
+ endIndex = null;
26332
+ // Read-write aliases for properties
26333
+ /**
26334
+ * Same as {@link parent}.
26335
+ * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
26336
+ */
26337
+ get parentNode() {
26338
+ return this.parent;
26339
+ }
26340
+ set parentNode(parent) {
26341
+ this.parent = parent;
26342
+ }
26343
+ /**
26344
+ * Same as {@link prev}.
26345
+ * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
26346
+ */
26347
+ get previousSibling() {
26348
+ return this.prev;
26349
+ }
26350
+ set previousSibling(previous) {
26351
+ this.prev = previous;
26352
+ }
26353
+ /**
26354
+ * Same as {@link next}.
26355
+ * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
26356
+ */
26357
+ get nextSibling() {
26358
+ return this.next;
26359
+ }
26360
+ set nextSibling(next) {
26361
+ this.next = next;
26362
+ }
26363
+ /**
26364
+ * Clone this node, and optionally its children.
26365
+ * @param recursive Clone child nodes as well.
26366
+ * @returns A clone of the node.
26367
+ */
26368
+ cloneNode(recursive = false) {
26369
+ return cloneNode(this, recursive);
26370
+ }
26371
+ };
26372
+ var DataNode = class extends Node {
26373
+ data;
26374
+ /**
26375
+ * @param data The content of the data node
26376
+ */
26377
+ constructor(data) {
26378
+ super();
26379
+ this.data = data;
26380
+ }
26381
+ /**
26382
+ * Same as {@link data}.
26383
+ * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
26384
+ */
26385
+ get nodeValue() {
26386
+ return this.data;
26387
+ }
26388
+ set nodeValue(data) {
26389
+ this.data = data;
26390
+ }
26391
+ };
26392
+ var Text2 = class extends DataNode {
26393
+ type = ElementType.Text;
26394
+ get nodeType() {
26395
+ return 3;
26396
+ }
26397
+ };
26398
+ var Comment2 = class extends DataNode {
26399
+ type = ElementType.Comment;
26400
+ get nodeType() {
26401
+ return 8;
26402
+ }
26403
+ };
26404
+ var ProcessingInstruction = class extends DataNode {
26405
+ type = ElementType.Directive;
26406
+ name;
26407
+ constructor(name, data) {
26408
+ super(data);
26409
+ this.name = name;
26410
+ }
26411
+ get nodeType() {
26412
+ return 1;
26413
+ }
26414
+ /** If this is a doctype, the document type name (parse5 only). */
26415
+ "x-name";
26416
+ /** If this is a doctype, the document type public identifier (parse5 only). */
26417
+ "x-publicId";
26418
+ /** If this is a doctype, the document type system identifier (parse5 only). */
26419
+ "x-systemId";
26420
+ };
26421
+ var NodeWithChildren = class extends Node {
26422
+ children;
26423
+ /**
26424
+ * @param children Children of the node. Only certain node types can have children.
26425
+ */
26426
+ constructor(children) {
26427
+ super();
26428
+ this.children = children;
26429
+ }
26430
+ // Aliases
26431
+ /** First child of the node. */
26432
+ get firstChild() {
26433
+ return this.children[0] ?? null;
26434
+ }
26435
+ /** Last child of the node. */
26436
+ get lastChild() {
26437
+ return this.children.length > 0 ? this.children[this.children.length - 1] : null;
26438
+ }
26439
+ /**
26440
+ * Same as {@link children}.
26441
+ * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
26442
+ */
26443
+ get childNodes() {
26444
+ return this.children;
26445
+ }
26446
+ set childNodes(children) {
26447
+ this.children = children;
26448
+ }
26449
+ };
26450
+ var CDATA2 = class extends NodeWithChildren {
26451
+ type = ElementType.CDATA;
26452
+ get nodeType() {
26453
+ return 4;
26454
+ }
26455
+ };
26456
+ var Document = class extends NodeWithChildren {
26457
+ type = ElementType.Root;
26458
+ get nodeType() {
26459
+ return 9;
26460
+ }
26461
+ };
26462
+ var Element = class extends NodeWithChildren {
26463
+ name;
26464
+ attribs;
26465
+ type;
26466
+ /**
26467
+ * @param name Name of the tag, eg. `div`, `span`.
26468
+ * @param attribs Object mapping attribute names to attribute values.
26469
+ * @param children Children of the node.
26470
+ * @param type Node type used for the new node instance.
26471
+ */
26472
+ constructor(name, attribs, children = [], type = name === "script" ? ElementType.Script : name === "style" ? ElementType.Style : ElementType.Tag) {
26473
+ super(children);
26474
+ this.name = name;
26475
+ this.attribs = attribs;
26476
+ this.type = type;
26477
+ }
26478
+ get nodeType() {
26479
+ return 1;
26480
+ }
26481
+ // DOM Level 1 aliases
26482
+ /**
26483
+ * Same as {@link name}.
26484
+ * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
26485
+ */
26486
+ get tagName() {
26487
+ return this.name;
26488
+ }
26489
+ set tagName(name) {
26490
+ this.name = name;
26491
+ }
26492
+ get attributes() {
26493
+ return Object.keys(this.attribs).map((name) => ({
26494
+ name,
26495
+ value: this.attribs[name],
26496
+ namespace: this["x-attribsNamespace"]?.[name],
26497
+ prefix: this["x-attribsPrefix"]?.[name]
26498
+ }));
26499
+ }
26500
+ /** Element namespace (parse5 only). */
26501
+ namespace;
26502
+ /** Element attribute namespaces (parse5 only). */
26503
+ "x-attribsNamespace";
26504
+ /** Element attribute namespace-related prefixes (parse5 only). */
26505
+ "x-attribsPrefix";
26506
+ };
26507
+ function isTag2(node) {
26508
+ return isTag(node);
26509
+ }
26510
+ function isCDATA(node) {
26511
+ return node.type === ElementType.CDATA;
26512
+ }
26513
+ function isText(node) {
26514
+ return node.type === ElementType.Text;
26515
+ }
26516
+ function isComment(node) {
26517
+ return node.type === ElementType.Comment;
26518
+ }
26519
+ function isDirective(node) {
26520
+ return node.type === ElementType.Directive;
26521
+ }
26522
+ function isDocument(node) {
26523
+ return node.type === ElementType.Root;
26524
+ }
26525
+ function hasChildren(node) {
26526
+ return Object.hasOwn(node, "children");
26527
+ }
26528
+ function cloneNode(node, recursive = false) {
26529
+ let result;
26530
+ if (isText(node)) {
26531
+ result = new Text2(node.data);
26532
+ } else if (isComment(node)) {
26533
+ result = new Comment2(node.data);
26534
+ } else if (isTag2(node)) {
26535
+ const children = recursive ? cloneChildren(node.children) : [];
26536
+ const clone2 = new Element(node.name, { ...node.attribs }, children);
26537
+ for (const child of children) {
26538
+ child.parent = clone2;
26539
+ }
26540
+ if (node.namespace != null) {
26541
+ clone2.namespace = node.namespace;
26542
+ }
26543
+ if (node["x-attribsNamespace"]) {
26544
+ clone2["x-attribsNamespace"] = { ...node["x-attribsNamespace"] };
26545
+ }
26546
+ if (node["x-attribsPrefix"]) {
26547
+ clone2["x-attribsPrefix"] = { ...node["x-attribsPrefix"] };
26548
+ }
26549
+ result = clone2;
26550
+ } else if (isCDATA(node)) {
26551
+ const children = recursive ? cloneChildren(node.children) : [];
26552
+ const clone2 = new CDATA2(children);
26553
+ for (const child of children) {
26554
+ child.parent = clone2;
26555
+ }
26556
+ result = clone2;
26557
+ } else if (isDocument(node)) {
26558
+ const children = recursive ? cloneChildren(node.children) : [];
26559
+ const clone2 = new Document(children);
26560
+ for (const child of children) {
26561
+ child.parent = clone2;
26562
+ }
26563
+ if (node["x-mode"]) {
26564
+ clone2["x-mode"] = node["x-mode"];
26565
+ }
26566
+ result = clone2;
26567
+ } else if (isDirective(node)) {
26568
+ const instruction = new ProcessingInstruction(node.name, node.data);
26569
+ if (node["x-name"] != null) {
26570
+ instruction["x-name"] = node["x-name"];
26571
+ instruction["x-publicId"] = node["x-publicId"];
26572
+ instruction["x-systemId"] = node["x-systemId"];
26573
+ }
26574
+ result = instruction;
26575
+ } else {
26576
+ throw new Error(`Not implemented yet: ${node.type}`);
26577
+ }
26578
+ result.startIndex = node.startIndex;
26579
+ result.endIndex = node.endIndex;
26580
+ if (node.sourceCodeLocation != null) {
26581
+ result.sourceCodeLocation = node.sourceCodeLocation;
26582
+ }
26583
+ return result;
26584
+ }
26585
+ function cloneChildren(childs) {
26586
+ const children = childs.map((child) => cloneNode(child, true));
26587
+ for (let index = 1; index < children.length; index++) {
26588
+ children[index].prev = children[index - 1];
26589
+ children[index - 1].next = children[index];
26590
+ }
26591
+ return children;
26592
+ }
26593
+
26594
+ // node_modules/domhandler/dist/index.js
26595
+ var defaultOptions = {
26596
+ withStartIndices: false,
26597
+ withEndIndices: false,
26598
+ xmlMode: false
26599
+ };
26600
+ var DomHandler = class {
26601
+ /** The elements of the DOM */
26602
+ dom = [];
26603
+ /** The root element for the DOM */
26604
+ root = new Document(this.dom);
26605
+ /** Called once parsing has completed. */
26606
+ callback;
26607
+ /** Settings for the handler. */
26608
+ options;
26609
+ /** Callback whenever a tag is closed. */
26610
+ elementCB;
26611
+ /** Indicated whether parsing has been completed. */
26612
+ done = false;
26613
+ /** Stack of open tags. */
26614
+ tagStack = [this.root];
26615
+ /** A data node that is still being written to. */
26616
+ lastNode = null;
26617
+ /** Reference to the parser instance. Used for location information. */
26618
+ parser = null;
26619
+ /**
26620
+ * @param callback Called once parsing has completed.
26621
+ * @param options Settings for the handler.
26622
+ * @param elementCB Callback whenever a tag is closed.
26623
+ */
26624
+ constructor(callback, options, elementCB) {
26625
+ if (typeof options === "function") {
26626
+ elementCB = options;
26627
+ options = defaultOptions;
26628
+ }
26629
+ if (typeof callback === "object") {
26630
+ options = callback;
26631
+ callback = void 0;
26632
+ }
26633
+ this.callback = callback ?? null;
26634
+ this.options = options ?? defaultOptions;
26635
+ this.elementCB = elementCB ?? null;
26636
+ }
26637
+ onparserinit(parser) {
26638
+ this.parser = parser;
26639
+ }
26640
+ // Resets the handler back to starting state
26641
+ onreset() {
26642
+ this.dom = [];
26643
+ this.root = new Document(this.dom);
26644
+ this.done = false;
26645
+ this.tagStack = [this.root];
26646
+ this.lastNode = null;
26647
+ this.parser = null;
26648
+ }
26649
+ // Signals the handler that parsing is done
26650
+ onend() {
26651
+ if (this.done)
26652
+ return;
26653
+ this.done = true;
26654
+ this.parser = null;
26655
+ this.handleCallback(null);
26656
+ }
26657
+ onerror(error40) {
26658
+ this.handleCallback(error40);
26659
+ }
26660
+ onclosetag() {
26661
+ this.lastNode = null;
26662
+ const element2 = this.tagStack.pop();
26663
+ if (this.options.withEndIndices && this.parser) {
26664
+ element2.endIndex = this.parser.endIndex;
26665
+ }
26666
+ if (this.elementCB)
26667
+ this.elementCB(element2);
26668
+ }
26669
+ onopentag(name, attribs) {
26670
+ const type = this.options.xmlMode ? ElementType.Tag : void 0;
26671
+ const element2 = new Element(name, attribs, void 0, type);
26672
+ this.addNode(element2);
26673
+ this.tagStack.push(element2);
26674
+ }
26675
+ ontext(data) {
26676
+ const { lastNode } = this;
26677
+ if (lastNode && lastNode.type === ElementType.Text) {
26678
+ lastNode.data += data;
26679
+ if (this.options.withEndIndices && this.parser) {
26680
+ lastNode.endIndex = this.parser.endIndex;
26681
+ }
26682
+ } else {
26683
+ const node = new Text2(data);
26684
+ this.addNode(node);
26685
+ this.lastNode = node;
26686
+ }
26687
+ }
26688
+ oncomment(data) {
26689
+ if (this.lastNode && this.lastNode.type === ElementType.Comment) {
26690
+ this.lastNode.data += data;
26691
+ return;
26692
+ }
26693
+ const node = new Comment2(data);
26694
+ this.addNode(node);
26695
+ this.lastNode = node;
26696
+ }
26697
+ oncommentend() {
26698
+ this.lastNode = null;
26699
+ }
26700
+ oncdatastart() {
26701
+ const text = new Text2("");
26702
+ const node = new CDATA2([text]);
26703
+ this.addNode(node);
26704
+ text.parent = node;
26705
+ this.lastNode = text;
26706
+ }
26707
+ oncdataend() {
26708
+ this.lastNode = null;
26709
+ }
26710
+ onprocessinginstruction(name, data) {
26711
+ const node = new ProcessingInstruction(name, data);
26712
+ this.addNode(node);
26713
+ }
26714
+ handleCallback(error40) {
26715
+ if (typeof this.callback === "function") {
26716
+ this.callback(error40, this.dom);
26717
+ } else if (error40) {
26718
+ throw error40;
26719
+ }
26720
+ }
26721
+ addNode(node) {
26722
+ const parent = this.tagStack[this.tagStack.length - 1];
26723
+ const previousSibling = parent.children[parent.children.length - 1];
26724
+ if (this.options.withStartIndices && this.parser) {
26725
+ node.startIndex = this.parser.startIndex;
26726
+ }
26727
+ if (this.options.withEndIndices && this.parser) {
26728
+ node.endIndex = this.parser.endIndex;
26729
+ }
26730
+ parent.children.push(node);
26731
+ if (previousSibling) {
26732
+ node.prev = previousSibling;
26733
+ previousSibling.next = node;
26734
+ }
26735
+ node.parent = parent;
26736
+ this.lastNode = null;
26737
+ }
26738
+ };
26739
+
26740
+ // node_modules/domutils/dist/index.js
26741
+ var dist_exports2 = {};
26742
+ __export(dist_exports2, {
26743
+ DocumentPosition: () => DocumentPosition,
26744
+ append: () => append,
26745
+ appendChild: () => appendChild,
26746
+ compareDocumentPosition: () => compareDocumentPosition,
26747
+ existsOne: () => existsOne,
26748
+ filter: () => filter,
26749
+ find: () => find,
26750
+ findAll: () => findAll,
26751
+ findOne: () => findOne,
26752
+ getAttributeValue: () => getAttributeValue,
26753
+ getChildren: () => getChildren,
26754
+ getElementById: () => getElementById,
26755
+ getElements: () => getElements,
26756
+ getElementsByClassName: () => getElementsByClassName,
26757
+ getElementsByTagName: () => getElementsByTagName,
26758
+ getElementsByTagType: () => getElementsByTagType,
26759
+ getFeed: () => getFeed,
26760
+ getInnerHTML: () => getInnerHTML,
26761
+ getName: () => getName,
26762
+ getOuterHTML: () => getOuterHTML,
26763
+ getParent: () => getParent,
26764
+ getSiblings: () => getSiblings,
26765
+ getText: () => getText,
26766
+ hasAttrib: () => hasAttrib,
26767
+ innerText: () => innerText,
26768
+ nextElementSibling: () => nextElementSibling,
26769
+ prepend: () => prepend,
26770
+ prependChild: () => prependChild,
26771
+ prevElementSibling: () => prevElementSibling,
26772
+ removeElement: () => removeElement,
26773
+ removeSubsets: () => removeSubsets,
26774
+ replaceElement: () => replaceElement,
26775
+ testElement: () => testElement,
26776
+ textContent: () => textContent,
26777
+ uniqueSort: () => uniqueSort
26778
+ });
26779
+
26780
+ // node_modules/domutils/dist/querying.js
26781
+ function filter(test, node, recurse = true, limit = Number.POSITIVE_INFINITY) {
26782
+ return find(test, Array.isArray(node) ? node : [node], recurse, limit);
26783
+ }
26784
+ function find(test, nodes, recurse, limit) {
26785
+ const result = [];
26786
+ const nodeStack = [Array.isArray(nodes) ? nodes : [nodes]];
26787
+ const indexStack = [0];
26788
+ for (; ; ) {
26789
+ if (indexStack[0] >= nodeStack[0].length) {
26790
+ if (indexStack.length === 1) {
26791
+ return result;
26792
+ }
26793
+ nodeStack.shift();
26794
+ indexStack.shift();
26795
+ continue;
26796
+ }
26797
+ const element2 = nodeStack[0][indexStack[0]++];
26798
+ if (test(element2)) {
26799
+ result.push(element2);
26800
+ if (--limit <= 0)
26801
+ return result;
26802
+ }
26803
+ if (recurse && hasChildren(element2) && element2.children.length > 0) {
26804
+ indexStack.unshift(0);
26805
+ nodeStack.unshift(element2.children);
26806
+ }
26807
+ }
26808
+ }
26809
+ function findOne(test, nodes, recurse = true) {
26810
+ const searchedNodes = Array.isArray(nodes) ? nodes : [nodes];
26811
+ for (const node of searchedNodes) {
26812
+ if (isTag2(node) && test(node)) {
26813
+ return node;
26814
+ }
26815
+ if (recurse && hasChildren(node) && node.children.length > 0) {
26816
+ const found = findOne(test, node.children, true);
26817
+ if (found)
26818
+ return found;
26819
+ }
26820
+ }
26821
+ return null;
26822
+ }
26823
+ function existsOne(test, nodes) {
26824
+ return (Array.isArray(nodes) ? nodes : [nodes]).some((node) => isTag2(node) && test(node) || hasChildren(node) && existsOne(test, node.children));
26825
+ }
26826
+ function findAll(test, nodes) {
26827
+ const result = [];
26828
+ const nodeStack = [Array.isArray(nodes) ? nodes : [nodes]];
26829
+ const indexStack = [0];
26830
+ for (; ; ) {
26831
+ if (indexStack[0] >= nodeStack[0].length) {
26832
+ if (nodeStack.length === 1) {
26833
+ return result;
26834
+ }
26835
+ nodeStack.shift();
26836
+ indexStack.shift();
26837
+ continue;
26838
+ }
26839
+ const element2 = nodeStack[0][indexStack[0]++];
26840
+ if (isTag2(element2) && test(element2))
26841
+ result.push(element2);
26842
+ if (hasChildren(element2) && element2.children.length > 0) {
26843
+ indexStack.unshift(0);
26844
+ nodeStack.unshift(element2.children);
26845
+ }
26846
+ }
26847
+ }
26848
+
26849
+ // node_modules/domutils/dist/legacy.js
26850
+ var Checks = {
26851
+ tag_name(name) {
26852
+ if (typeof name === "function") {
26853
+ return (element2) => isTag2(element2) && name(element2.name);
26854
+ }
26855
+ if (name === "*") {
26856
+ return isTag2;
26857
+ }
26858
+ return (element2) => isTag2(element2) && element2.name === name;
26859
+ },
26860
+ tag_type(type) {
26861
+ if (typeof type === "function") {
26862
+ return (element2) => type(element2.type);
26863
+ }
26864
+ return (element2) => element2.type === type;
26865
+ },
26866
+ tag_contains(data) {
26867
+ if (typeof data === "function") {
26868
+ return (element2) => isText(element2) && data(element2.data);
26869
+ }
26870
+ return (element2) => isText(element2) && element2.data === data;
26871
+ }
26872
+ };
26873
+ function getAttribCheck(attrib, value) {
26874
+ if (typeof value === "function") {
26875
+ return (element2) => isTag2(element2) && value(element2.attribs[attrib]);
26876
+ }
26877
+ return (element2) => isTag2(element2) && element2.attribs[attrib] === value;
26878
+ }
26879
+ function combineFuncs(a, b) {
26880
+ return (element2) => a(element2) || b(element2);
26881
+ }
26882
+ function compileTest(options) {
26883
+ const funcs = Object.keys(options).map((key) => {
26884
+ const value = options[key];
26885
+ return Object.hasOwn(Checks, key) ? Checks[key](value) : getAttribCheck(key, value);
26886
+ });
26887
+ return funcs.length === 0 ? null : funcs.reduce(combineFuncs);
26888
+ }
26889
+ function testElement(options, node) {
26890
+ const test = compileTest(options);
26891
+ return test ? test(node) : true;
26892
+ }
26893
+ function getElements(options, nodes, recurse, limit = Number.POSITIVE_INFINITY) {
26894
+ const test = compileTest(options);
26895
+ return test ? filter(test, nodes, recurse, limit) : [];
26896
+ }
26897
+ function getElementById(id2, nodes, recurse = true) {
26898
+ if (!Array.isArray(nodes))
26899
+ nodes = [nodes];
26900
+ return findOne(getAttribCheck("id", id2), nodes, recurse);
26901
+ }
26902
+ function getElementsByTagName(tagName, nodes, recurse = true, limit = Number.POSITIVE_INFINITY) {
26903
+ return filter(Checks["tag_name"](tagName), nodes, recurse, limit);
26904
+ }
26905
+ function getElementsByClassName(className, nodes, recurse = true, limit = Number.POSITIVE_INFINITY) {
26906
+ return filter(getAttribCheck("class", className), nodes, recurse, limit);
26907
+ }
26908
+ function getElementsByTagType(type, nodes, recurse = true, limit = Number.POSITIVE_INFINITY) {
26909
+ return filter(Checks["tag_type"](type), nodes, recurse, limit);
26910
+ }
26911
+
26912
+ // node_modules/entities/dist/escape.js
26913
+ function getEscape(char) {
26914
+ return char === 34 ? "&quot;" : char === 38 ? "&amp;" : char === 39 ? "&apos;" : char === 60 ? "&lt;" : char === 62 ? "&gt;" : "&nbsp;";
26915
+ }
26916
+ var XML_BITSET_VALUE = 1342177476;
26917
+ var xmlEncodeRegex = /["&'<>\u0080-\uFFFF]/g;
26918
+ function isXmlEscapable(code) {
26919
+ return code >= 128 || code >= 32 && code < 64 && (XML_BITSET_VALUE >>> code & 1) === 1;
26920
+ }
26921
+ function encodeXML(input) {
26922
+ const { length } = input;
26923
+ let out;
26924
+ let last2 = 0;
26925
+ let index = 0;
26926
+ while (index < length) {
26927
+ const char = input.charCodeAt(index);
26928
+ if (!isXmlEscapable(char)) {
26929
+ const bound = Math.min(index + 32, length);
26930
+ let next = index + 1;
26931
+ while (next < bound && !isXmlEscapable(input.charCodeAt(next))) {
26932
+ next++;
26933
+ }
26934
+ if (next < bound) {
26935
+ index = next;
26936
+ continue;
26937
+ }
26938
+ if (next >= length)
26939
+ break;
26940
+ xmlEncodeRegex.lastIndex = next;
26941
+ if (!xmlEncodeRegex.test(input))
26942
+ break;
26943
+ index = xmlEncodeRegex.lastIndex - 1;
26944
+ continue;
26945
+ }
26946
+ if (out === void 0)
26947
+ out = input.substring(0, index);
26948
+ else if (last2 !== index)
26949
+ out += input.substring(last2, index);
26950
+ if (char < 64) {
26951
+ out += getEscape(char);
26952
+ last2 = index += 1;
26953
+ continue;
26954
+ }
26955
+ const cp = input.codePointAt(index);
26956
+ out += `&#x${cp.toString(16)};`;
26957
+ if (cp !== char)
26958
+ index++;
26959
+ last2 = index += 1;
26960
+ }
26961
+ if (out === void 0)
26962
+ return input;
26963
+ if (last2 < length)
26964
+ out += input.substr(last2);
26965
+ return out;
26966
+ }
26967
+ function escapeWithRegex(re, data) {
26968
+ re.lastIndex = 0;
26969
+ if (!re.test(data))
26970
+ return data;
26971
+ let out = "";
26972
+ let last2 = 0;
26973
+ do {
26974
+ const index = re.lastIndex - 1;
26975
+ if (last2 !== index)
26976
+ out += data.substring(last2, index);
26977
+ const char = data.charCodeAt(index);
26978
+ out += getEscape(char);
26979
+ last2 = index + 1;
26980
+ } while (re.test(data));
26981
+ return out + data.substring(last2);
26982
+ }
26983
+ var attributeEscapeRegex = /["&\u{A0}]/gu;
26984
+ function escapeAttribute(data) {
26985
+ return escapeWithRegex(attributeEscapeRegex, data);
26986
+ }
26987
+ var textEscapeRegex = /[&<>\u{A0}]/gu;
26988
+ function escapeText(data) {
26989
+ return escapeWithRegex(textEscapeRegex, data);
26990
+ }
26991
+
26992
+ // node_modules/entities/dist/index.js
26993
+ var EntityLevel;
26994
+ (function(EntityLevel2) {
26995
+ EntityLevel2[EntityLevel2["XML"] = 0] = "XML";
26996
+ EntityLevel2[EntityLevel2["HTML"] = 1] = "HTML";
26997
+ })(EntityLevel || (EntityLevel = {}));
26998
+ var EncodingMode;
26999
+ (function(EncodingMode2) {
27000
+ EncodingMode2[EncodingMode2["UTF8"] = 0] = "UTF8";
27001
+ EncodingMode2[EncodingMode2["ASCII"] = 1] = "ASCII";
27002
+ EncodingMode2[EncodingMode2["Extensive"] = 2] = "Extensive";
27003
+ EncodingMode2[EncodingMode2["Attribute"] = 3] = "Attribute";
27004
+ EncodingMode2[EncodingMode2["Text"] = 4] = "Text";
27005
+ })(EncodingMode || (EncodingMode = {}));
27006
+
27007
+ // node_modules/dom-serializer/dist/foreign-names.js
27008
+ var elementNames = new Map("altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject glyphRef linearGradient radialGradient textPath".split(" ").map((name) => [name.toLowerCase(), name]));
27009
+ var attributeNames = new Map("definitionURL attributeName attributeType baseFrequency baseProfile calcMode clipPathUnits diffuseConstant edgeMode filterUnits glyphRef gradientTransform gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth maskContentUnits maskUnits numOctaves pathLength patternContentUnits patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur requiredExtensions requiredFeatures specularConstant specularExponent spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage tableValues targetX targetY textLength viewBox viewTarget xChannelSelector yChannelSelector zoomAndPan".split(" ").map((name) => [name.toLowerCase(), name]));
27010
+
27011
+ // node_modules/dom-serializer/dist/index.js
27012
+ var unencodedElements = new Set("style script xmp iframe noembed noframes plaintext noscript".split(" "));
27013
+ var voidElements2 = new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" "));
27014
+ var foreignElements = /* @__PURE__ */ new Set(["svg", "math"]);
27015
+ var foreignModeIntegrationPoints = new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));
27016
+ function render2(node, options = {}) {
27017
+ const nodes = "length" in node ? node : [node];
27018
+ const xmlMode = options.xmlMode ?? false;
27019
+ let output = "";
27020
+ for (let index = 0; index < nodes.length; index++) {
27021
+ output += renderNode(nodes[index], options, xmlMode);
27022
+ }
27023
+ return output;
27024
+ }
27025
+ var dist_default = render2;
27026
+ function renderChildren(children, options, xmlMode) {
27027
+ let output = "";
27028
+ for (let index = 0; index < children.length; index++) {
27029
+ output += renderNode(children[index], options, xmlMode);
27030
+ }
27031
+ return output;
27032
+ }
27033
+ function renderNode(node, options, xmlMode) {
27034
+ switch (node.type) {
27035
+ case Root: {
27036
+ return renderChildren(node.children, options, xmlMode);
27037
+ }
27038
+ case Directive: {
27039
+ return `<${node.data}>`;
27040
+ }
27041
+ case Comment: {
27042
+ return `<!--${node.data}-->`;
27043
+ }
27044
+ case CDATA: {
27045
+ return `<![CDATA[${node.children[0].data}]]>`;
27046
+ }
27047
+ case Script:
27048
+ case Style:
27049
+ case Tag: {
27050
+ return renderTag(node, options, xmlMode);
27051
+ }
27052
+ case Text: {
27053
+ const element2 = node;
27054
+ const data = element2.data || "";
27055
+ if ((options.encodeEntities ?? options.decodeEntities) !== false && !(!xmlMode && element2.parent && unencodedElements.has(element2.parent.name))) {
27056
+ return xmlMode || options.encodeEntities !== "utf8" ? encodeXML(data) : escapeText(data);
27057
+ }
27058
+ return data;
27059
+ }
27060
+ }
27061
+ }
27062
+ function renderTag(element2, options, xmlMode) {
27063
+ if (xmlMode === "foreign") {
27064
+ element2.name = elementNames.get(element2.name) ?? element2.name;
27065
+ if (element2.parent && foreignModeIntegrationPoints.has(element2.parent.name)) {
27066
+ xmlMode = false;
27067
+ }
27068
+ }
27069
+ if (!xmlMode && foreignElements.has(element2.name)) {
27070
+ xmlMode = "foreign";
27071
+ }
27072
+ const { name, children } = element2;
27073
+ const isVoid = !xmlMode && voidElements2.has(name);
27074
+ let tag2 = `<${name}${formatAttributes(element2.attribs, options, xmlMode)}`;
27075
+ if (children.length === 0 && (xmlMode ? options.selfClosingTags !== false : options.selfClosingTags && isVoid)) {
27076
+ tag2 += xmlMode ? "/>" : " />";
27077
+ } else {
27078
+ tag2 += ">";
27079
+ if (children.length > 0) {
27080
+ tag2 += renderChildren(children, options, xmlMode);
27081
+ }
27082
+ if (!isVoid) {
27083
+ tag2 += `</${name}>`;
27084
+ }
27085
+ }
27086
+ return tag2;
27087
+ }
27088
+ function replaceQuotes(value) {
27089
+ return value.replaceAll('"', "&quot;");
27090
+ }
27091
+ function formatAttributes(attributes, options, xmlMode) {
27092
+ if (!attributes)
27093
+ return "";
27094
+ const encode11 = (options.encodeEntities ?? options.decodeEntities) === false ? replaceQuotes : xmlMode || options.encodeEntities !== "utf8" ? encodeXML : escapeAttribute;
27095
+ const isForeign = xmlMode === "foreign";
27096
+ const showEmpty = !!(options.emptyAttrs ?? xmlMode);
27097
+ let result = "";
27098
+ for (const key in attributes) {
27099
+ if (!Object.hasOwn(attributes, key))
27100
+ continue;
27101
+ const value = attributes[key];
27102
+ const k = isForeign ? attributeNames.get(key) ?? key : key;
27103
+ result += !showEmpty && (value == null || value === "") ? ` ${k}` : ` ${k}="${encode11(value == null ? "" : String(value))}"`;
27104
+ }
27105
+ return result;
27106
+ }
27107
+
27108
+ // node_modules/domutils/dist/stringify.js
27109
+ function getOuterHTML(node, options) {
27110
+ return dist_default(node, options);
27111
+ }
27112
+ function getInnerHTML(node, options) {
27113
+ return hasChildren(node) ? node.children.map((node2) => getOuterHTML(node2, options)).join("") : "";
27114
+ }
27115
+ function getText(node) {
27116
+ if (Array.isArray(node))
27117
+ return node.map(getText).join("");
27118
+ if (isTag2(node))
27119
+ return node.name === "br" ? "\n" : getText(node.children);
27120
+ if (isCDATA(node))
27121
+ return getText(node.children);
27122
+ if (isText(node))
27123
+ return node.data;
27124
+ return "";
27125
+ }
27126
+ function textContent(node) {
27127
+ if (Array.isArray(node))
27128
+ return node.map(textContent).join("");
27129
+ if (hasChildren(node) && !isComment(node)) {
27130
+ return textContent(node.children);
27131
+ }
27132
+ if (isText(node))
27133
+ return node.data;
27134
+ return "";
27135
+ }
27136
+ function innerText(node) {
27137
+ if (Array.isArray(node))
27138
+ return node.map(innerText).join("");
27139
+ if (hasChildren(node) && (node.type === ElementType.Tag || isCDATA(node))) {
27140
+ return innerText(node.children);
27141
+ }
27142
+ if (isText(node))
27143
+ return node.data;
27144
+ return "";
27145
+ }
27146
+
27147
+ // node_modules/domutils/dist/feeds.js
27148
+ function getFeed(document) {
27149
+ const feedRoot = getOneElement(isValidFeed, document);
27150
+ return feedRoot ? feedRoot.name === "feed" ? getAtomFeed(feedRoot) : getRssFeed(feedRoot) : null;
27151
+ }
27152
+ function getAtomFeed(feedRoot) {
27153
+ const childs = feedRoot.children;
27154
+ const feed = {
27155
+ type: "atom",
27156
+ items: getElementsByTagName("entry", childs).map((item) => {
27157
+ const { children } = item;
27158
+ const entry = { media: getMediaElements(children) };
27159
+ addConditionally(entry, "id", "id", children);
27160
+ addConditionally(entry, "title", "title", children);
27161
+ const href2 = getOneElement("link", children)?.attribs["href"];
27162
+ if (href2) {
27163
+ entry.link = href2;
27164
+ }
27165
+ const description = fetch("summary", children) || fetch("content", children);
27166
+ if (description) {
27167
+ entry.description = description;
27168
+ }
27169
+ const pubDate = fetch("updated", children);
27170
+ if (pubDate) {
27171
+ entry.pubDate = new Date(pubDate);
27172
+ }
27173
+ return entry;
27174
+ })
27175
+ };
27176
+ addConditionally(feed, "id", "id", childs);
27177
+ addConditionally(feed, "title", "title", childs);
27178
+ const href = getOneElement("link", childs)?.attribs["href"];
27179
+ if (href) {
27180
+ feed.link = href;
27181
+ }
27182
+ addConditionally(feed, "description", "subtitle", childs);
27183
+ const updated = fetch("updated", childs);
27184
+ if (updated) {
27185
+ feed.updated = new Date(updated);
27186
+ }
27187
+ addConditionally(feed, "author", "email", childs, true);
27188
+ return feed;
27189
+ }
27190
+ function getRssFeed(feedRoot) {
27191
+ const childs = getOneElement("channel", feedRoot.children)?.children ?? [];
27192
+ const feed = {
27193
+ type: feedRoot.name.substr(0, 3),
27194
+ id: "",
27195
+ items: getElementsByTagName("item", feedRoot.children).map((item) => {
27196
+ const { children } = item;
27197
+ const entry = { media: getMediaElements(children) };
27198
+ addConditionally(entry, "id", "guid", children);
27199
+ addConditionally(entry, "title", "title", children);
27200
+ addConditionally(entry, "link", "link", children);
27201
+ addConditionally(entry, "description", "description", children);
27202
+ const pubDate = fetch("pubDate", children) || fetch("dc:date", children);
27203
+ if (pubDate)
27204
+ entry.pubDate = new Date(pubDate);
27205
+ return entry;
27206
+ })
27207
+ };
27208
+ addConditionally(feed, "title", "title", childs);
27209
+ addConditionally(feed, "link", "link", childs);
27210
+ addConditionally(feed, "description", "description", childs);
27211
+ const updated = fetch("lastBuildDate", childs);
27212
+ if (updated) {
27213
+ feed.updated = new Date(updated);
27214
+ }
27215
+ addConditionally(feed, "author", "managingEditor", childs, true);
27216
+ return feed;
27217
+ }
27218
+ var MEDIA_KEYS_STRING = ["url", "type", "lang"];
27219
+ var MEDIA_KEYS_INT = [
27220
+ "fileSize",
27221
+ "bitrate",
27222
+ "framerate",
27223
+ "samplingrate",
27224
+ "channels",
27225
+ "duration",
27226
+ "height",
27227
+ "width"
27228
+ ];
27229
+ function getMediaElements(where) {
27230
+ return getElementsByTagName("media:content", where).map((element2) => {
27231
+ const { attribs } = element2;
27232
+ const media = {
27233
+ medium: attribs["medium"],
27234
+ isDefault: !!attribs["isDefault"]
27235
+ };
27236
+ for (const attrib of MEDIA_KEYS_STRING) {
27237
+ if (attribs[attrib]) {
27238
+ media[attrib] = attribs[attrib];
27239
+ }
27240
+ }
27241
+ for (const attrib of MEDIA_KEYS_INT) {
27242
+ if (attribs[attrib]) {
27243
+ media[attrib] = Number.parseInt(attribs[attrib], 10);
27244
+ }
27245
+ }
27246
+ if (attribs["expression"]) {
27247
+ media.expression = attribs["expression"];
27248
+ }
27249
+ return media;
27250
+ });
27251
+ }
27252
+ function getOneElement(tagName, node) {
27253
+ return getElementsByTagName(tagName, node, true, 1)[0];
27254
+ }
27255
+ function fetch(tagName, where, recurse = false) {
27256
+ return textContent(getElementsByTagName(tagName, where, recurse, 1)).trim();
27257
+ }
27258
+ function addConditionally(object2, property, tagName, where, recurse = false) {
27259
+ const value = fetch(tagName, where, recurse);
27260
+ if (value)
27261
+ object2[property] = value;
27262
+ }
27263
+ function isValidFeed(value) {
27264
+ return value === "rss" || value === "feed" || value === "rdf:RDF";
27265
+ }
27266
+
27267
+ // node_modules/domutils/dist/helpers.js
27268
+ function removeSubsets(nodes) {
27269
+ let index = nodes.length;
27270
+ while (--index >= 0) {
27271
+ const node = nodes[index];
27272
+ if (index > 0 && nodes.lastIndexOf(node, index - 1) >= 0) {
27273
+ nodes.splice(index, 1);
27274
+ continue;
27275
+ }
27276
+ for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
27277
+ if (nodes.includes(ancestor)) {
27278
+ nodes.splice(index, 1);
27279
+ break;
27280
+ }
27281
+ }
27282
+ }
27283
+ return nodes;
27284
+ }
27285
+ var DocumentPosition;
27286
+ (function(DocumentPosition2) {
27287
+ DocumentPosition2[DocumentPosition2["DISCONNECTED"] = 1] = "DISCONNECTED";
27288
+ DocumentPosition2[DocumentPosition2["PRECEDING"] = 2] = "PRECEDING";
27289
+ DocumentPosition2[DocumentPosition2["FOLLOWING"] = 4] = "FOLLOWING";
27290
+ DocumentPosition2[DocumentPosition2["CONTAINS"] = 8] = "CONTAINS";
27291
+ DocumentPosition2[DocumentPosition2["CONTAINED_BY"] = 16] = "CONTAINED_BY";
27292
+ })(DocumentPosition || (DocumentPosition = {}));
27293
+ function compareDocumentPosition(nodeA, nodeB) {
27294
+ const aParents = [];
27295
+ const bParents = [];
27296
+ if (nodeA === nodeB) {
27297
+ return 0;
27298
+ }
27299
+ let current = hasChildren(nodeA) ? nodeA : nodeA.parent;
27300
+ while (current) {
27301
+ aParents.unshift(current);
27302
+ current = current.parent;
27303
+ }
27304
+ current = hasChildren(nodeB) ? nodeB : nodeB.parent;
27305
+ while (current) {
27306
+ bParents.unshift(current);
27307
+ current = current.parent;
27308
+ }
27309
+ const maxIndex = Math.min(aParents.length, bParents.length);
27310
+ let index = 0;
27311
+ while (index < maxIndex && aParents[index] === bParents[index]) {
27312
+ index++;
27313
+ }
27314
+ if (index === 0) {
27315
+ return DocumentPosition.DISCONNECTED;
27316
+ }
27317
+ const sharedParent = aParents[index - 1];
27318
+ const siblings = sharedParent.children;
27319
+ const aSibling = aParents[index];
27320
+ const bSibling = bParents[index];
27321
+ if (siblings.indexOf(aSibling) > siblings.indexOf(bSibling)) {
27322
+ if (sharedParent === nodeB) {
27323
+ return DocumentPosition.FOLLOWING | DocumentPosition.CONTAINED_BY;
27324
+ }
27325
+ return DocumentPosition.FOLLOWING;
27326
+ }
27327
+ if (sharedParent === nodeA) {
27328
+ return DocumentPosition.PRECEDING | DocumentPosition.CONTAINS;
27329
+ }
27330
+ return DocumentPosition.PRECEDING;
27331
+ }
27332
+ function uniqueSort(nodes) {
27333
+ nodes = nodes.filter((node, index, array2) => !array2.includes(node, index + 1));
27334
+ nodes.sort((a, b) => {
27335
+ const relative4 = compareDocumentPosition(a, b);
27336
+ if (relative4 & DocumentPosition.PRECEDING) {
27337
+ return -1;
27338
+ }
27339
+ if (relative4 & DocumentPosition.FOLLOWING) {
27340
+ return 1;
27341
+ }
27342
+ return 0;
27343
+ });
27344
+ return nodes;
27345
+ }
27346
+
27347
+ // node_modules/domutils/dist/manipulation.js
27348
+ function removeElement(element2) {
27349
+ if (element2.prev)
27350
+ element2.prev.next = element2.next;
27351
+ if (element2.next)
27352
+ element2.next.prev = element2.prev;
27353
+ if (element2.parent) {
27354
+ const childs = element2.parent.children;
27355
+ const childsIndex = childs.lastIndexOf(element2);
27356
+ if (childsIndex !== -1) {
27357
+ childs.splice(childsIndex, 1);
27358
+ }
27359
+ }
27360
+ element2.next = null;
27361
+ element2.prev = null;
27362
+ element2.parent = null;
27363
+ }
27364
+ function replaceElement(element2, replacement) {
27365
+ replacement.prev = element2.prev;
27366
+ if (replacement.prev) {
27367
+ replacement.prev.next = replacement;
27368
+ }
27369
+ replacement.next = element2.next;
27370
+ if (replacement.next) {
27371
+ replacement.next.prev = replacement;
27372
+ }
27373
+ replacement.parent = element2.parent;
27374
+ if (replacement.parent) {
27375
+ const { children } = replacement.parent;
27376
+ const elementIndex = children.lastIndexOf(element2);
27377
+ if (elementIndex === -1) {
27378
+ return;
27379
+ }
27380
+ children[elementIndex] = replacement;
27381
+ element2.parent = null;
27382
+ }
27383
+ }
27384
+ function appendChild(parent, child) {
27385
+ removeElement(child);
27386
+ child.next = null;
27387
+ child.parent = parent;
27388
+ if (parent.children.push(child) > 1) {
27389
+ const sibling = parent.children[parent.children.length - 2];
27390
+ sibling.next = child;
27391
+ child.prev = sibling;
27392
+ } else {
27393
+ child.prev = null;
27394
+ }
27395
+ }
27396
+ function append(element2, next) {
27397
+ removeElement(next);
27398
+ const { parent } = element2;
27399
+ const currentNext = element2.next;
27400
+ next.next = currentNext;
27401
+ next.prev = element2;
27402
+ element2.next = next;
27403
+ next.parent = parent;
27404
+ if (currentNext) {
27405
+ currentNext.prev = next;
27406
+ if (parent) {
27407
+ const childs = parent.children;
27408
+ childs.splice(childs.lastIndexOf(currentNext), 0, next);
27409
+ }
27410
+ } else if (parent) {
27411
+ parent.children.push(next);
27412
+ }
27413
+ }
27414
+ function prependChild(parent, child) {
27415
+ removeElement(child);
27416
+ child.parent = parent;
27417
+ child.prev = null;
27418
+ if (parent.children.unshift(child) === 1) {
27419
+ child.next = null;
27420
+ } else {
27421
+ const sibling = parent.children[1];
27422
+ sibling.prev = child;
27423
+ child.next = sibling;
27424
+ }
27425
+ }
27426
+ function prepend(element2, previous) {
27427
+ removeElement(previous);
27428
+ const { parent } = element2;
27429
+ if (parent) {
27430
+ const childs = parent.children;
27431
+ childs.splice(childs.indexOf(element2), 0, previous);
27432
+ }
27433
+ if (element2.prev) {
27434
+ element2.prev.next = previous;
27435
+ }
27436
+ previous.parent = parent;
27437
+ previous.prev = element2.prev;
27438
+ previous.next = element2;
27439
+ element2.prev = previous;
27440
+ }
27441
+
27442
+ // node_modules/domutils/dist/traversal.js
27443
+ function getChildren(element2) {
27444
+ return hasChildren(element2) ? element2.children : [];
27445
+ }
27446
+ function getParent(element2) {
27447
+ return element2.parent || null;
27448
+ }
27449
+ function getSiblings(element2) {
27450
+ const parent = getParent(element2);
27451
+ if (parent != null)
27452
+ return getChildren(parent);
27453
+ const siblings = [element2];
27454
+ let { prev, next } = element2;
27455
+ while (prev != null) {
27456
+ siblings.unshift(prev);
27457
+ ({ prev } = prev);
27458
+ }
27459
+ while (next != null) {
27460
+ siblings.push(next);
27461
+ ({ next } = next);
27462
+ }
27463
+ return siblings;
27464
+ }
27465
+ function getAttributeValue(element2, name) {
27466
+ const { attribs } = element2;
27467
+ return attribs?.[name];
27468
+ }
27469
+ function hasAttrib(element2, name) {
27470
+ const { attribs } = element2;
27471
+ return attribs != null && Object.hasOwn(attribs, name) && attribs[name] != null;
27472
+ }
27473
+ function getName(element2) {
27474
+ return element2.name;
27475
+ }
27476
+ function nextElementSibling(element2) {
27477
+ let { next } = element2;
27478
+ while (next !== null && !isTag2(next))
27479
+ ({ next } = next);
27480
+ return next;
27481
+ }
27482
+ function prevElementSibling(element2) {
27483
+ let { prev } = element2;
27484
+ while (prev !== null && !isTag2(prev))
27485
+ ({ prev } = prev);
27486
+ return prev;
27487
+ }
27488
+
27489
+ // node_modules/htmlparser2/dist/index.js
27490
+ function parseDocument(data, options) {
27491
+ const handler9 = new DomHandler(void 0, options);
27492
+ new Parser(handler9, options).end(data);
27493
+ return handler9.root;
27494
+ }
27495
+
27496
+ // src/core/index/html-text.ts
27497
+ function isText2(n) {
27498
+ return n.type === "text";
27499
+ }
27500
+ function isTag3(n) {
27501
+ return n.type === "tag" || n.type === "script" || n.type === "style";
27502
+ }
27503
+ var DROP = /* @__PURE__ */ new Set([
27504
+ "script",
27505
+ "style",
27506
+ "noscript",
27507
+ "template",
27508
+ "svg",
27509
+ "math",
27510
+ "iframe",
27511
+ "canvas",
27512
+ "object",
27513
+ "embed",
27514
+ "head",
27515
+ "title",
27516
+ "nav",
27517
+ "footer",
27518
+ "button",
27519
+ "select",
27520
+ "option",
27521
+ "textarea",
27522
+ "input",
27523
+ "dialog",
27524
+ "audio",
27525
+ "video",
27526
+ "picture",
27527
+ "img"
27528
+ ]);
27529
+ var DROP_ROLES = /* @__PURE__ */ new Set(["navigation", "banner", "contentinfo", "search", "dialog", "tooltip"]);
27530
+ var LINE = /* @__PURE__ */ new Set(["div", "section", "article", "main", "header", "aside", "figure", "figcaption", "details", "summary", "address", "dl", "dt", "dd", "fieldset", "form", "center", "li", "tr", "body", "html", "caption"]);
27531
+ var PARA = /* @__PURE__ */ new Set(["p", "blockquote", "hr", "table", "ul", "ol", "pre", "h1", "h2", "h3", "h4", "h5", "h6"]);
27532
+ var PRE_LINE = /* @__PURE__ */ new Set(["div", "p", "li", "tr"]);
27533
+ var LANG_PREFIXES = ["language-", "lang-", "highlight-source-", "highlight-text-"];
27534
+ var BLOCK_INSIDE_LINK = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6", "p", "div", "pre", "ul", "ol", "table", "blockquote", "section", "article"]);
27535
+ function isSpace2(c) {
27536
+ return c === " " || c === " " || c === "\n" || c === "\r" || c === "\f" || c === "\xA0";
27537
+ }
27538
+ function isInvisible(c) {
27539
+ return c === "\u200B" || c === "\uFEFF" || c === "\xAD";
27540
+ }
27541
+ function collapse(s) {
27542
+ let out = "";
27543
+ let gap = false;
27544
+ for (const c of s) {
27545
+ if (isInvisible(c)) continue;
27546
+ if (isSpace2(c)) {
27547
+ gap = true;
27548
+ continue;
27549
+ }
27550
+ if (gap) {
27551
+ out += " ";
27552
+ gap = false;
27553
+ }
27554
+ out += c;
27555
+ }
27556
+ return gap ? out + " " : out;
27557
+ }
27558
+ function hidden(el) {
27559
+ const a = el.attribs;
27560
+ if (a.hidden !== void 0 || a["aria-hidden"] === "true") return true;
27561
+ if (a.role !== void 0 && DROP_ROLES.has(a.role.toLowerCase())) return true;
27562
+ if (a.style !== void 0) {
27563
+ let s = "";
27564
+ for (const c of a.style.toLowerCase()) if (!isSpace2(c)) s += c;
27565
+ if (s.includes("display:none")) return true;
27566
+ }
27567
+ return false;
27568
+ }
27569
+ function dropped(el) {
27570
+ return DROP.has(el.name) || hidden(el);
27571
+ }
27572
+ function plainText(node) {
27573
+ let out = "";
27574
+ const visit2 = (n) => {
27575
+ if (isText2(n)) {
27576
+ out += n.data;
27577
+ return;
27578
+ }
27579
+ if (!isTag3(n) || dropped(n)) return;
27580
+ if (n.name === "br") {
27581
+ out += " ";
27582
+ return;
27583
+ }
27584
+ const block = LINE.has(n.name) || PARA.has(n.name);
27585
+ if (block) out += " ";
27586
+ for (const c of n.children) visit2(c);
27587
+ if (block) out += " ";
27588
+ };
27589
+ visit2(node);
27590
+ return collapse(out).trim();
27591
+ }
27592
+ function preText(node) {
27593
+ const buf = [];
27594
+ let last2 = "\n";
27595
+ const put = (s) => {
27596
+ if (s === "") return;
27597
+ buf.push(s);
27598
+ last2 = s[s.length - 1];
27599
+ };
27600
+ const visit2 = (n) => {
27601
+ if (isText2(n)) {
27602
+ let s = "";
27603
+ for (const c of n.data) {
27604
+ if (isInvisible(c)) continue;
27605
+ s += c === "\xA0" ? " " : c;
27606
+ }
27607
+ put(s);
27608
+ return;
27609
+ }
27610
+ if (!isTag3(n) || dropped(n)) return;
27611
+ if (n.name === "br") {
27612
+ put("\n");
27613
+ return;
27614
+ }
27615
+ for (const c of n.children) visit2(c);
27616
+ if (PRE_LINE.has(n.name) && last2 !== "\n") put("\n");
27617
+ };
27618
+ for (const c of node.children) visit2(c);
27619
+ let code = "";
27620
+ for (const s of buf) code += s;
27621
+ const lines = code.split("\r\n").join("\n").split("\n");
27622
+ while (lines.length > 0 && lines[0].trim() === "") lines.shift();
27623
+ while (lines.length > 0 && lines[lines.length - 1].trim() === "") lines.pop();
27624
+ return lines.join("\n");
27625
+ }
27626
+ function langFrom(classes) {
27627
+ if (classes === void 0) return "";
27628
+ for (const token of classes.split(" ")) {
27629
+ for (const p of LANG_PREFIXES) {
27630
+ if (token.startsWith(p) && token.length > p.length) return token.slice(p.length);
27631
+ }
27632
+ }
27633
+ return "";
27634
+ }
27635
+ function langOf(pre) {
27636
+ const code = dist_exports2.findOne((e) => e.name === "code", pre.children, true);
27637
+ const chain = [pre];
27638
+ if (code !== null) chain.push(code);
27639
+ let up = pre.parent;
27640
+ for (let i = 0; i < 2 && up !== null && isTag3(up); i += 1) {
27641
+ chain.push(up);
27642
+ up = up.parent;
27643
+ }
27644
+ for (const el of chain) {
27645
+ const l = langFrom(el.attribs.class) || el.attribs["data-language"] || el.attribs["data-lang"] || "";
27646
+ if (l !== "") return safeLang(l);
27647
+ }
27648
+ return "";
27649
+ }
27650
+ function safeLang(l) {
27651
+ let out = "";
27652
+ for (const c of l.toLowerCase()) {
27653
+ const ok = c >= "a" && c <= "z" || c >= "0" && c <= "9" || c === "+" || c === "-" || c === "#" || c === "_" || c === ".";
27654
+ if (!ok) return out;
27655
+ out += c;
27656
+ }
27657
+ return out;
27658
+ }
27659
+ var Writer = class {
27660
+ parts = [];
27661
+ pending = 0;
27662
+ fresh = true;
27663
+ endsSpace = false;
27664
+ stack = [];
27665
+ depth() {
27666
+ return this.stack.length;
27667
+ }
27668
+ push(first, rest) {
27669
+ this.stack.push({ first, rest, used: false });
27670
+ }
27671
+ pop() {
27672
+ this.stack.pop();
27673
+ }
27674
+ line() {
27675
+ if (this.pending < 1) this.pending = 1;
27676
+ }
27677
+ block() {
27678
+ this.pending = 2;
27679
+ }
27680
+ prefix() {
27681
+ let p = "";
27682
+ for (const l of this.stack) {
27683
+ p += l.used ? l.rest : l.first;
27684
+ l.used = true;
27685
+ }
27686
+ return p;
27687
+ }
27688
+ flush() {
27689
+ if (this.parts.length > 0 && this.pending > 0) {
27690
+ const i = this.parts.length - 1;
27691
+ let end = this.parts[i].length;
27692
+ while (end > 0 && this.parts[i][end - 1] === " ") end -= 1;
27693
+ this.parts[i] = this.parts[i].slice(0, end);
27694
+ this.parts.push("\n".repeat(this.pending));
27695
+ this.fresh = true;
27696
+ this.endsSpace = false;
27697
+ }
27698
+ this.pending = 0;
27699
+ if (this.fresh) {
27700
+ this.parts.push(this.prefix());
27701
+ this.fresh = false;
27702
+ }
27703
+ }
27704
+ text(raw) {
27705
+ let s = raw;
27706
+ if ((this.fresh || this.pending > 0 || this.endsSpace) && s.startsWith(" ")) s = s.slice(1);
27707
+ if (s === "") return;
27708
+ this.flush();
27709
+ this.parts.push(s);
27710
+ this.endsSpace = s.endsWith(" ");
27711
+ }
27712
+ /** One whole line, white space kept (a code line, a table row). */
27713
+ emitLine(s) {
27714
+ this.line();
27715
+ this.flush();
27716
+ this.parts.push(s);
27717
+ this.endsSpace = false;
27718
+ this.line();
27719
+ }
27720
+ code(lang, code) {
27721
+ let run = 0;
27722
+ let most = 0;
27723
+ for (const c of code) {
27724
+ run = c === "`" ? run + 1 : 0;
27725
+ if (run > most) most = run;
27726
+ }
27727
+ const fence = "`".repeat(Math.max(3, most + 1));
27728
+ this.block();
27729
+ this.emitLine(fence + lang);
27730
+ for (const l of code.split("\n")) this.emitLine(l);
27731
+ this.emitLine(fence);
27732
+ this.block();
27733
+ }
27734
+ result() {
27735
+ let s = "";
27736
+ for (const p of this.parts) s += p;
27737
+ return s.trimEnd();
27738
+ }
27739
+ };
27740
+ function resolveHref(href, base) {
27741
+ if (href === void 0) return void 0;
27742
+ const h = href.trim();
27743
+ if (h === "" || h.startsWith("#")) return void 0;
27744
+ try {
27745
+ const u = base !== void 0 ? new URL(h, base) : new URL(h);
27746
+ return u.protocol === "http:" || u.protocol === "https:" ? u.href : void 0;
27747
+ } catch {
27748
+ return base === void 0 && !h.includes(":") ? h : void 0;
27749
+ }
27750
+ }
27751
+ function hasBlock(el) {
27752
+ return dist_exports2.findOne((e) => BLOCK_INSIDE_LINK.has(e.name), el.children, true) !== null;
27753
+ }
27754
+ function inlineCode(text) {
27755
+ let run = 0;
27756
+ let most = 0;
27757
+ for (const c of text) {
27758
+ run = c === "`" ? run + 1 : 0;
27759
+ if (run > most) most = run;
27760
+ }
27761
+ const tick = "`".repeat(most === 0 ? 1 : most + 1);
27762
+ const pad = text.startsWith("`") || text.endsWith("`") ? " " : "";
27763
+ return tick + pad + text + pad + tick;
27764
+ }
27765
+ function cell2(el) {
27766
+ const t = plainText(el);
27767
+ let out = "";
27768
+ for (const c of t) out += c === "|" ? "\\|" : c;
27769
+ return out;
27770
+ }
27771
+ function table(st, el) {
27772
+ const rows = dist_exports2.findAll((e) => e.name === "tr", el.children).map((tr) => tr.children.filter((c) => isTag3(c) && (c.name === "td" || c.name === "th")).map(cell2));
27773
+ const cols = rows.reduce((m, r) => Math.max(m, r.length), 0);
27774
+ if (cols === 0) return;
27775
+ st.w.block();
27776
+ rows.forEach((r, i) => {
27777
+ const padded = r.concat(Array.from({ length: cols - r.length }, () => ""));
27778
+ st.w.emitLine("| " + padded.join(" | ") + " |");
27779
+ if (i === 0) st.w.emitLine("|" + " --- |".repeat(cols));
27780
+ });
27781
+ st.w.block();
27782
+ }
27783
+ function list3(st, el) {
27784
+ const ordered = el.name === "ol";
27785
+ const start = Number.parseInt(el.attribs.start ?? "1", 10);
27786
+ let n = Number.isFinite(start) ? start : 1;
27787
+ if (st.w.depth() === 0) st.w.block();
27788
+ else st.w.line();
27789
+ for (const c of el.children) {
27790
+ if (isTag3(c) && c.name === "li" && !dropped(c)) {
27791
+ const marker = ordered ? String(n) + ". " : "- ";
27792
+ n += 1;
27793
+ st.w.line();
27794
+ st.w.push(marker, " ".repeat(marker.length));
27795
+ for (const k of c.children) walk(st, k);
27796
+ st.w.pop();
27797
+ st.w.line();
27798
+ } else {
27799
+ walk(st, c);
27800
+ }
27801
+ }
27802
+ if (st.w.depth() === 0) st.w.block();
27803
+ else st.w.line();
27804
+ }
27805
+ function walk(st, node) {
27806
+ if (isText2(node)) {
27807
+ st.w.text(collapse(node.data));
27808
+ return;
27809
+ }
27810
+ if (!isTag3(node) || dropped(node)) return;
27811
+ const name = node.name;
27812
+ if (name.length === 2 && name[0] === "h" && name[1] >= "1" && name[1] <= "6") {
27813
+ const t = plainText(node);
27814
+ if (t === "") return;
27815
+ if (name === "h1") st.sawH1 = true;
27816
+ st.w.block();
27817
+ st.w.text("#".repeat(Number(name[1])) + " " + t);
27818
+ st.w.block();
27819
+ return;
27820
+ }
27821
+ switch (name) {
27822
+ case "pre": {
27823
+ const code = preText(node);
27824
+ if (code !== "") st.w.code(langOf(node), code);
27825
+ return;
27826
+ }
27827
+ case "ul":
27828
+ case "ol":
27829
+ list3(st, node);
27830
+ return;
27831
+ case "table":
27832
+ table(st, node);
27833
+ return;
27834
+ case "br":
27835
+ st.w.line();
27836
+ return;
27837
+ case "hr":
27838
+ st.w.block();
27839
+ st.w.text("---");
27840
+ st.w.block();
27841
+ return;
27842
+ case "blockquote":
27843
+ st.w.block();
27844
+ st.w.push("> ", "> ");
27845
+ for (const c of node.children) walk(st, c);
27846
+ st.w.pop();
27847
+ st.w.block();
27848
+ return;
27849
+ case "code": {
27850
+ const t = plainText(node);
27851
+ if (t !== "") st.w.text(inlineCode(t));
27852
+ return;
27853
+ }
27854
+ case "a": {
27855
+ if (hasBlock(node)) break;
27856
+ const t = plainText(node);
27857
+ if (t === "") return;
27858
+ const href = resolveHref(node.attribs.href, st.base);
27859
+ st.w.text(href === void 0 ? t : "[" + t + "](" + href + ")");
27860
+ return;
27861
+ }
27862
+ default:
27863
+ }
27864
+ const para = PARA.has(name);
27865
+ const line = LINE.has(name);
27866
+ if (para) st.w.block();
27867
+ else if (line) st.w.line();
27868
+ for (const c of node.children) walk(st, c);
27869
+ if (para) st.w.block();
27870
+ else if (line) st.w.line();
27871
+ }
27872
+ function isWordChar3(c) {
27873
+ return c.toLowerCase() !== c.toUpperCase() || c >= "0" && c <= "9";
27874
+ }
27875
+ function wordCount(text) {
27876
+ let n = 0;
27877
+ for (const w of text.split(" ").join("\n").split("\n")) {
27878
+ for (const c of w) if (isWordChar3(c)) {
27879
+ n += 1;
27880
+ break;
27881
+ }
27882
+ }
27883
+ return n;
27884
+ }
27885
+ var SPARSE_MAX_WORDS = 20;
27886
+ var SPARSE_RATIO = 20;
27887
+ function contentRoot(children) {
27888
+ const main = dist_exports2.findOne((e) => e.name === "main", children, true);
27889
+ if (main !== null) return [main];
27890
+ const articles = dist_exports2.findAll((e) => e.name === "article", children);
27891
+ if (articles.length === 1) return articles;
27892
+ const body = dist_exports2.findOne((e) => e.name === "body", children, true);
27893
+ return body !== null ? [body] : children;
27894
+ }
27895
+ function htmlToReadable(html, baseUrl) {
27896
+ const doc = parseDocument(html);
27897
+ const titleEl = dist_exports2.findOne((e) => e.name === "title", doc.children, true);
27898
+ const title = titleEl === null ? "" : collapse(titleEl.children.map((c) => isText2(c) ? c.data : "").join("")).trim();
27899
+ let base;
27900
+ try {
27901
+ base = baseUrl === void 0 ? void 0 : new URL(baseUrl);
27902
+ } catch {
27903
+ base = void 0;
27904
+ }
27905
+ const st = { w: new Writer(), base, sawH1: false };
27906
+ for (const n of contentRoot(doc.children)) walk(st, n);
27907
+ const body = st.w.result();
27908
+ const words = wordCount(body);
27909
+ const text = !st.sawH1 && title !== "" && words > 0 ? "# " + title + "\n\n" + body : body;
27910
+ const sparse = words < SPARSE_MAX_WORDS && html.length > SPARSE_RATIO * Math.max(text.length, 1);
27911
+ return { text: text === "" ? "" : text + "\n", title, words, sparse };
27912
+ }
27913
+
27914
+ // src/core/tools/index.ts
27915
+ var ctxIndexSchema = external_exports.object({
27916
+ path: external_exports.string().optional(),
27917
+ content: external_exports.string().optional(),
27918
+ url: external_exports.string().optional(),
27919
+ source: external_exports.string().optional()
27920
+ }, { error: unknownField }).strict();
27921
+ var INPUT_FIELDS = ["path", "content", "url"];
27922
+ var EXT_KIND = Object.freeze({ ".md": "md", ".html": "html", ".htm": "html" });
27923
+ var TYPE_KIND = Object.freeze({ "text/html": "html", "text/markdown": "md" });
27924
+ var DEFAULT_CONTENT_LABEL = "content";
27925
+ var utf8 = new TextDecoder("utf-8", { fatal: true });
27926
+ function userLabel(label) {
27927
+ return label === DECISION_SOURCE ? DECISION_USER_LABEL : label;
27928
+ }
27929
+ function kindOfPath(p) {
27930
+ return EXT_KIND[extname(p).toLowerCase()] ?? "text";
27931
+ }
27932
+ function kindOfType(contentType) {
27933
+ const semi = contentType.indexOf(";");
27934
+ const media = (semi < 0 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
27935
+ return TYPE_KIND[media] ?? "text";
27936
+ }
27937
+ function readUtf8(absPath) {
27938
+ try {
27939
+ return utf8.decode(readFileSync13(absPath));
27940
+ } catch {
27941
+ return void 0;
27942
+ }
27943
+ }
27944
+ function missingOrOutside(given, abs, root) {
27945
+ let dir = abs;
27946
+ while (!existsSync12(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
27947
+ if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
27948
+ return new CtxError("OUTSIDE_ROOT", { p: given, root });
27949
+ }
27950
+ function pathItems(input, project) {
27951
+ const abs = resolve5(project.worktree, input.path);
27952
+ if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
27953
+ const base = relative3(project.worktree, abs);
27954
+ if (statSync6(abs).isDirectory()) {
27955
+ return walkDir(abs, project.containmentRoot).map((f) => ({
27956
+ sourceKind: "path",
27957
+ label: join16(base, f.relPath),
27958
+ kind: kindOfPath(f.relPath),
27959
+ read: () => readUtf8(f.absPath)
27960
+ }));
27961
+ }
27962
+ return [{ sourceKind: "path", label: base === "" ? input.path : base, kind: kindOfPath(abs), read: () => readUtf8(abs) }];
27963
+ }
27964
+ async function itemsOf(input, ctx) {
27965
+ if (input.content !== void 0) {
27966
+ const text2 = input.content;
27967
+ const label2 = input.source ?? DEFAULT_CONTENT_LABEL;
27968
+ const kind = hasMdStructure(text2) ? "md" : "text";
27969
+ return { items: [{ sourceKind: "content", label: label2, kind, read: () => text2 }], from: label2 };
27970
+ }
27971
+ if (input.path !== void 0) {
27972
+ const items = pathItems({ ...input, path: input.path }, ctx.project);
27973
+ return { items, from: items.length === 1 ? items[0].label : input.path };
27974
+ }
27975
+ const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
27976
+ const text = res.body.toString("utf8");
27977
+ const label = res.finalUrl;
27978
+ return { items: [{ sourceKind: "url", label, kind: kindOfType(res.contentType), read: () => text, base: label }], from: label };
27979
+ }
27980
+ async function handler4(input, ctx) {
27981
+ const given = INPUT_FIELDS.filter((f) => input[f] !== void 0);
27982
+ if (given.length !== 1) return { text: new CtxError("ONE_OF_INPUT", { names: INPUT_FIELDS.join(", ") }).toLine(), isError: true, sandboxBytes: 0 };
27983
+ try {
27984
+ const got = await itemsOf(input, ctx);
27985
+ const items = got.items.map((it) => ({ ...it, label: userLabel(it.label) }));
27986
+ const from = userLabel(got.from);
27987
+ const db = await openDb(ctx.project);
27988
+ let sources = 0;
27989
+ let chunks = 0;
27990
+ let bytes4 = 0;
27991
+ let lastId = 0;
27992
+ const notes = [];
27993
+ try {
27994
+ for (const it of items) {
27995
+ const text = it.read();
27996
+ if (text === void 0) continue;
27997
+ bytes4 += Buffer.byteLength(text, "utf8");
27998
+ if (it.kind === "html") {
27999
+ let readable;
28000
+ try {
28001
+ readable = htmlToReadable(text, it.base);
28002
+ } catch {
28003
+ readable = void 0;
28004
+ }
28005
+ if (readable !== void 0) {
28006
+ const rawLabel = it.label + RAW_LABEL_SUFFIX;
28007
+ const raw = storeText(db, ctx.project, ctx.sessionId, it.sourceKind, rawLabel, text, "text");
28008
+ notes.push('Raw HTML kept as "' + rawLabel + '" (' + raw.chunks + " chunk(s)); pass it as `source` to search the markup.");
28009
+ lastId = raw.sourceId;
28010
+ if (readable.words === 0 || readable.sparse) {
28011
+ notes.unshift("No readable text found in " + it.label + " (the page is client-rendered or empty); nothing was added to default search.");
28012
+ continue;
28013
+ }
28014
+ const stored2 = storeText(db, ctx.project, ctx.sessionId, it.sourceKind, it.label, readable.text, "md");
28015
+ chunks += stored2.chunks;
28016
+ lastId = stored2.sourceId;
28017
+ sources += 1;
28018
+ continue;
28019
+ }
28020
+ }
28021
+ const stored = storeText(db, ctx.project, ctx.sessionId, it.sourceKind, it.label, text, it.kind);
28022
+ chunks += stored.chunks;
28023
+ lastId = stored.sourceId;
28024
+ sources += 1;
28025
+ }
28026
+ } finally {
28027
+ closeDb(db);
28028
+ }
28029
+ const shown2 = Buffer.byteLength(from, "utf8") > ECHO_MAX_BYTES ? sourceHandle(lastId) : from;
28030
+ const line = ["Indexed " + sources + " source(s), " + chunks + " chunk(s) from " + shown2 + ".", ...notes].join("\n");
28031
+ return {
28032
+ text: capBytes(line, OUTPUT_CAP).text,
28033
+ isError: false,
28034
+ sandboxBytes: bytes4,
28035
+ journal: { kind: "index", key: from, path: from, exit_code: null }
28036
+ };
28037
+ } catch (err) {
28038
+ if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0 };
28039
+ throw err;
28040
+ }
28041
+ }
28042
+ var ctxIndex = {
28043
+ name: "ctx_index",
28044
+ schema: ctxIndexSchema,
28045
+ readOnly: false,
28046
+ alwaysLoad: false,
28047
+ handler: handler4
28048
+ };
28049
+
28050
+ // src/core/tools/purge.ts
28051
+ var ctxPurgeSchema = external_exports.object({
28052
+ session: external_exports.string().optional(),
28053
+ source: external_exports.string().optional(),
28054
+ project: external_exports.boolean().optional()
28055
+ }, { error: unknownField }).strict();
28056
+ function reply2(text, isError) {
28057
+ return { text, isError, sandboxBytes: 0 };
28058
+ }
28059
+ function scopesOf(input) {
28060
+ const set3 = {
28061
+ session: input.session !== void 0,
28062
+ source: input.source !== void 0,
28063
+ project: input.project === true
28064
+ };
28065
+ return PURGE_SCOPES.filter((s) => set3[s]);
28066
+ }
28067
+ function changes(raw, sql, ...args) {
28068
+ return Number(raw.prepare(sql).run(...args).changes);
28069
+ }
28070
+ function purgeScope(raw, scope, input) {
28071
+ if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
28072
+ if (scope === "source") {
28073
+ const label = input.source;
28074
+ return deleteChunkRows(raw, { label }) + changes(raw, "DELETE FROM sources WHERE label = ?", label);
28075
+ }
28076
+ const chunks = deleteChunkRows(raw, "all");
28077
+ return changes(raw, "DELETE FROM events") + chunks + changes(raw, "DELETE FROM sources");
28078
+ }
28079
+ function isBusy(err) {
28080
+ const code = err?.errcode;
28081
+ return typeof code === "number" && (code & SQLITE_PRIMARY_CODE_MASK) === SQLITE_BUSY_CODE;
28082
+ }
28083
+ async function handler5(input, ctx) {
28084
+ const scopes = scopesOf(input);
28085
+ if (scopes.length === 0) return reply2(PURGE_NO_SCOPE_LINE, true);
28086
+ if (scopes.length > 1) return reply2(PURGE_MANY_SCOPES_LINE, true);
28087
+ const scope = scopes[0];
28088
+ try {
28089
+ const db = await openDb(ctx.project);
28090
+ try {
28091
+ const rows = withWrite(db, (h) => purgeScope(h.raw, scope, input));
28092
+ return reply2(PURGE_SUMMARY(rows, scope), false);
28093
+ } finally {
28094
+ closeDb(db);
28095
+ }
28096
+ } catch (err) {
28097
+ if (isBusy(err)) return reply2(PURGE_BUSY_LINE, true);
28098
+ throw err;
28099
+ }
28100
+ }
28101
+ var ctxPurge = Object.freeze({
28102
+ name: "ctx_purge",
28103
+ description: "",
28104
+ schema: ctxPurgeSchema,
28105
+ readOnly: false,
28106
+ alwaysLoad: false,
28107
+ handler: handler5
28108
+ });
28109
+
28110
+ // src/core/tools/resume.ts
28111
+ var ctxResumeSchema = external_exports.object({
28112
+ session: external_exports.string().optional(),
28113
+ seq: external_exports.number().int().positive().optional()
28114
+ }, {
28115
+ error: (issue2) => issue2.code === "unrecognized_keys" ? RESUME_UNKNOWN_FIELD_LINE : void 0
28116
+ }).strict();
28117
+ function reply3(text, isError) {
28118
+ return { text, isError, sandboxBytes: 0 };
28119
+ }
28120
+ async function handler6(input, ctx) {
28121
+ const sessionId = input.session ?? ctx.sessionId;
28122
+ if (sessionId === "") return reply3(RESUME_NO_SESSION_LINE, true);
28123
+ const db = await openDb(ctx.project, { readOnly: true });
28124
+ try {
28125
+ if (input.seq !== void 0) {
28126
+ const row5 = readEventBySeq(db, input.seq);
28127
+ if (row5 === null || row5.session_id !== sessionId) return reply3(RESUME_NO_ROW_LINE(input.seq), true);
28128
+ return reply3(row5.body, false);
28129
+ }
28130
+ const rows = readSessionEvents(db, sessionId);
28131
+ const newest = rows.at(-1);
28132
+ if (newest === void 0) return reply3(RESUME_EMPTY_LINE, false);
28133
+ const sources = listSessionSources(db, sessionId, MAX_CANDIDATES).map((r) => "source " + sourceHandle(r.id) + ": " + r.label + " (" + r.bytes + " B)");
28134
+ const goal = readFirstPrompt(db, sessionId);
28135
+ const last2 = readLastPrompt(db, sessionId);
28136
+ const units = queryUnits(db, sessionId, recallQueryText(last2, goal), RECALL_UNIT_CANDIDATES).map((u) => ({ ...u, label: sourceHandle(u.sourceId) }));
28137
+ const block = renderState(rows, newest.turn, { sources, units });
28138
+ if (Buffer.byteLength(block, "utf8") > RESUME_CAP) throw new Error("ctx_resume: state block over RESUME_CAP (render bug).");
28139
+ return reply3(block, false);
28140
+ } finally {
28141
+ closeDb(db);
28142
+ }
28143
+ }
28144
+ var ctxResume = Object.freeze({
28145
+ name: "ctx_resume",
28146
+ schema: ctxResumeSchema,
28147
+ readOnly: true,
24313
28148
  alwaysLoad: false,
24314
28149
  handler: handler6
24315
28150
  });
@@ -24355,7 +28190,7 @@ async function handler7(_input, ctx) {
24355
28190
  const project = sum(groups);
24356
28191
  const allTime = project;
24357
28192
  const agentIds = [.../* @__PURE__ */ new Set([...groups.map((g) => g.agent), ctx.project.agent])].sort();
24358
- const table = [
28193
+ const table2 = [
24359
28194
  "| " + STATS_COLUMNS.join(" | ") + " |",
24360
28195
  "|" + STATS_COLUMNS.map(() => "---").join("|") + "|",
24361
28196
  tableRow("session", session),
@@ -24364,7 +28199,7 @@ async function handler7(_input, ctx) {
24364
28199
  ...agentIds.map((a) => tableRow("agent " + a, sum(groups.filter((g) => g.agent === a))))
24365
28200
  ].join("\n");
24366
28201
  const summary = STATS_SUMMARY(reductionPct(allTime), reductionPct(session));
24367
- return { text: capBytes(summary + "\n\n" + table, OUTPUT_CAP).text, isError: false, sandboxBytes: 0 };
28202
+ return { text: capBytes(summary + "\n\n" + table2, OUTPUT_CAP).text, isError: false, sandboxBytes: 0 };
24368
28203
  }
24369
28204
  var ctxStats = Object.freeze({
24370
28205
  name: "ctx_stats",
@@ -24399,11 +28234,11 @@ function hostConfigPath(agent, home, env) {
24399
28234
  return join17(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
24400
28235
  }
24401
28236
  }
24402
- function cell2(value) {
28237
+ function cell3(value) {
24403
28238
  return value === void 0 ? "" : JSON.stringify(value);
24404
28239
  }
24405
28240
  function toRow(file2, edit) {
24406
- return { area: file2 + UPGRADE_AREA_KEY_SEP + edit.path, before: cell2(edit.before), after: cell2(edit.after) };
28241
+ return { area: file2 + UPGRADE_AREA_KEY_SEP + edit.path, before: cell3(edit.before), after: cell3(edit.after) };
24407
28242
  }
24408
28243
  function writeWithRollback(file2, text, write2, atomic) {
24409
28244
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
@@ -24739,16 +28574,16 @@ function removeV1(agent, findings) {
24739
28574
  } else done.set(f, UPGRADE_NOT_FOUND);
24740
28575
  } else entries.set(f.file, [...entries.get(f.file) ?? [], f]);
24741
28576
  }
24742
- for (const [file2, list3] of entries) {
28577
+ for (const [file2, list4] of entries) {
24743
28578
  if (!existsSync17(file2)) {
24744
- for (const f of list3) done.set(f, UPGRADE_NOT_FOUND);
28579
+ for (const f of list4) done.set(f, UPGRADE_NOT_FOUND);
24745
28580
  continue;
24746
28581
  }
24747
28582
  if (file2.endsWith(TOML_EXT)) {
24748
28583
  const rawToml = readFileSync14(file2, "utf8");
24749
28584
  const tomlLayout = hostLayout(rawToml);
24750
28585
  let text = hostText(rawToml);
24751
- for (const f of list3) {
28586
+ for (const f of list4) {
24752
28587
  const next = cutTomlTable(text, f.path);
24753
28588
  if (next === null) {
24754
28589
  done.set(f, UPGRADE_NOT_FOUND);
@@ -24757,14 +28592,14 @@ function removeV1(agent, findings) {
24757
28592
  text = next;
24758
28593
  done.set(f, UPGRADE_REMOVED);
24759
28594
  }
24760
- if (list3.some((f) => done.get(f) === UPGRADE_REMOVED)) {
28595
+ if (list4.some((f) => done.get(f) === UPGRADE_REMOVED)) {
24761
28596
  keepOriginal(file2, kept, undo);
24762
28597
  writeAtomic(file2, withLayout(text, tomlLayout));
24763
28598
  }
24764
28599
  continue;
24765
28600
  }
24766
- const hit = stripJsonEntries(agent, file2, list3, kept, undo);
24767
- for (const f of list3) done.set(f, hit.has(f) ? UPGRADE_REMOVED : UPGRADE_NOT_FOUND);
28601
+ const hit = stripJsonEntries(agent, file2, list4, kept, undo);
28602
+ for (const f of list4) done.set(f, hit.has(f) ? UPGRADE_REMOVED : UPGRADE_NOT_FOUND);
24768
28603
  }
24769
28604
  return {
24770
28605
  rows: findings.map((f) => row3(f, done.get(f) ?? UPGRADE_NOT_FOUND)),
@@ -24801,12 +28636,12 @@ function parseSums(text) {
24801
28636
  }
24802
28637
  return sums;
24803
28638
  }
24804
- function walk(dir, prefix, out) {
28639
+ function walk2(dir, prefix, out) {
24805
28640
  for (const entry of readdirSync8(dir, { withFileTypes: true })) {
24806
28641
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
24807
28642
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
24808
28643
  const abs = join21(dir, entry.name);
24809
- if (entry.isDirectory()) walk(abs, rel, out);
28644
+ if (entry.isDirectory()) walk2(abs, rel, out);
24810
28645
  else if (entry.isFile()) out.set(rel, abs);
24811
28646
  else throw mismatch();
24812
28647
  }
@@ -24817,7 +28652,7 @@ function verifySums(dir) {
24817
28652
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
24818
28653
  const sums = parseSums(readFileSync15(sumsPath, "utf8"));
24819
28654
  const files = /* @__PURE__ */ new Map();
24820
- walk(dir, "", files);
28655
+ walk2(dir, "", files);
24821
28656
  if (files.size !== sums.size) throw mismatch();
24822
28657
  for (const [rel, abs] of files) {
24823
28658
  const want = sums.get(rel);
@@ -24887,12 +28722,12 @@ async function upgrade(adapter, deps, home) {
24887
28722
  throw err;
24888
28723
  }
24889
28724
  }
24890
- function cell3(text) {
28725
+ function cell4(text) {
24891
28726
  return text.split(TABLE_PIPE).join(TABLE_PIPE_ESCAPED);
24892
28727
  }
24893
28728
  function renderTable(rows) {
24894
28729
  const lines = [UPGRADE_TABLE_HEADER, UPGRADE_TABLE_RULE];
24895
- for (const r of rows) lines.push(TABLE_ROW_START + [r.area, r.before, r.after].map(cell3).join(TABLE_CELL_SEP) + TABLE_ROW_END);
28730
+ for (const r of rows) lines.push(TABLE_ROW_START + [r.area, r.before, r.after].map(cell4).join(TABLE_CELL_SEP) + TABLE_ROW_END);
24896
28731
  return lines.join("\n");
24897
28732
  }
24898
28733
  async function runUpgrade(input, deps) {
@@ -24948,6 +28783,26 @@ function define(name) {
24948
28783
  };
24949
28784
  }
24950
28785
  var TOOLS = Object.freeze(TOOL_ORDER.map(define));
28786
+ function callExample(tool) {
28787
+ const a = tool.description.indexOf("`");
28788
+ const b = tool.description.indexOf("`", a + 1);
28789
+ return a < 0 || b < 0 ? tool.name + "({})" : tool.description.slice(a + 1, b);
28790
+ }
28791
+ function invalidCallLine(tool, issues) {
28792
+ const parts = [];
28793
+ for (const issue2 of issues.slice(0, 3)) {
28794
+ const where = issue2.path.length === 0 ? "" : issue2.path.map(String).join(".") + ": ";
28795
+ let one = (where + issue2.message).split("\n").join(" ").trim();
28796
+ while (one.endsWith(".")) one = one.slice(0, -1);
28797
+ parts.push(one);
28798
+ }
28799
+ const detail = parts.length === 0 ? "Invalid arguments" : parts.join("; ");
28800
+ return tool.name + ": " + detail + ". Correct call: " + callExample(tool);
28801
+ }
28802
+ function checkCall(tool, input) {
28803
+ const parsed = tool.schema.safeParse(input);
28804
+ return parsed.success ? { ok: true, data: parsed.data } : { ok: false, line: invalidCallLine(tool, parsed.error.issues) };
28805
+ }
24951
28806
 
24952
28807
  // src/entries/opencode.ts
24953
28808
  var AGENT = "opencode";
@@ -24976,8 +28831,8 @@ async function setup(app) {
24976
28831
  description: tool.description,
24977
28832
  args: tool.schema,
24978
28833
  async execute(args, toolCtx) {
24979
- const parsed = tool.schema.safeParse(args);
24980
- if (!parsed.success) return parsed.error.message;
28834
+ const checked = checkCall(tool, args);
28835
+ if (!checked.ok) return checked.line;
24981
28836
  const sessionId = toolCtx.sessionID ?? "";
24982
28837
  let resolved;
24983
28838
  const ctx = {
@@ -24992,7 +28847,7 @@ async function setup(app) {
24992
28847
  };
24993
28848
  let reply4;
24994
28849
  try {
24995
- reply4 = await tool.handler(parsed.data, ctx);
28850
+ reply4 = await tool.handler(checked.data, ctx);
24996
28851
  } catch (err) {
24997
28852
  return err instanceof CtxError ? err.toLine() : INTERNAL_ERROR_LINE;
24998
28853
  }