@dogsbay/format-html 0.0.0-stage → 0.2.0-beta.180

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.
@@ -0,0 +1,730 @@
1
+ /**
2
+ * GitBook published sites, on any domain (developer.harness.io, gitbook.com/docs). One book
3
+ * is one GitBook **space** (owner, 2026-11-18): the space the reader is on.
4
+ *
5
+ * Measured 2026-11-18 (plans/import-extension-sniffing.md, docs-dev/format-html.md):
6
+ * - Pages are read from their `.md`, not their HTML: the `.md` is GitBook's document written
7
+ * out again, every tag and word of the Git Sync source (checked against GitbookIO/public-docs),
8
+ * which @dogsbay/format-gitbook translates. The HTML lacks Mermaid source, code languages and
9
+ * the API pages' OpenAPI specs, and streams half its content (Next.js `$RC` moves).
10
+ * - The contents come from the start page's own data: Next.js puts the sidebar's whole tree
11
+ * (`"pages":[…]`: id, title, href, pathnames, groups with `descendants`) in the page's
12
+ * `self.__next_f.push(…)` scripts; the server's HTML draws only part of it. `llms.txt` is flat
13
+ * (one `##` per site section, spaces mixed) and not used.
14
+ * - A space's first page has two pathnames (`""` and its slug): its `.md` is `<space>/<slug>.md`;
15
+ * `<space>.md` is a "Page Not Found" Markdown page with status 200 (a soft 404).
16
+ * - Each `.md` starts with a "For the complete documentation index" banner and ends with an
17
+ * appended `# Agent Instructions` section: both are GitBook's, not the page's.
18
+ * - Card links are `{% content-ref url="/pages/<id>" %}`: the id is in the tree, kept as an alias.
19
+ * - Images are on `<n>-files.gitbook.io`, which answers any origin (`Access-Control-Allow-Origin: *`);
20
+ * GitBook's own `/~gitbook/image` proxy needs a signature we cannot make.
21
+ *
22
+ * Detected by `<meta name="generator" content="GitBook …">`; `bind` makes the adapter of the
23
+ * page's site and space. Reads, never fetches.
24
+ */
25
+ import { load } from "cheerio";
26
+ import { integrationNames, needsPage, parseGitbook } from "@dogsbay/format-gitbook";
27
+ import { nextRows, nextStream, objectsIn, resolveRefs } from "./next-data.js";
28
+ import { htmlToTree } from "../convert.js";
29
+ const MAX_DATA = 16 * 1024 * 1024;
30
+ /**
31
+ * The space's page tree and facts, from the page's Next.js data (`self.__next_f.push([1,"…"])`
32
+ * scripts, each a JSON string; together one stream). Null when the page has none.
33
+ */
34
+ export function gitbookData($) {
35
+ const stream = nextStream($);
36
+ if (!stream)
37
+ return null;
38
+ // The first `"pages":[` that reads as a page tree: a page's own text (an API page showing JSON)
39
+ // can hold the words before the sidebar's data does
40
+ const pages = firstJson(stream, '"pages":[', "[", (v) => Array.isArray(v) && v.length > 0 && v.every(isGbPage));
41
+ if (!pages)
42
+ return null;
43
+ const space = firstJson(stream, '"siteSpace":{', "{", (v) => typeof v?.space === "object");
44
+ const title = typeof space?.space?.title === "string" ? space.space.title : undefined;
45
+ const published = typeof space?.space?.urls?.published === "string" ? space.space.urls.published : undefined;
46
+ return { pages: pages, title, published };
47
+ }
48
+ /** Looks like an entry of GitBook's tree: an id, a title and a type, strings. */
49
+ function isGbPage(v) {
50
+ const p = v;
51
+ return !!p && typeof p === "object" && typeof p.id === "string" && typeof p.title === "string" && typeof p.type === "string";
52
+ }
53
+ /** The first value after `marker` that `ok` accepts (at most 50 tried: each try reads the stream once). */
54
+ function firstJson(text, marker, open, ok) {
55
+ for (let from = 0, tries = 0; tries < 50; tries++) {
56
+ const at = text.indexOf(marker, from);
57
+ if (at < 0)
58
+ return undefined;
59
+ const v = jsonAt(text, at + marker.length - 1, open);
60
+ if (v !== undefined && ok(v))
61
+ return v;
62
+ from = at + marker.length;
63
+ }
64
+ return undefined;
65
+ }
66
+ /** The JSON value that starts at `start` (an `open`): read to its matching close, then parsed. */
67
+ function jsonAt(text, start, open) {
68
+ const close = open === "[" ? "]" : "}";
69
+ let depth = 0;
70
+ let inString = false;
71
+ for (let i = start; i < text.length; i++) {
72
+ const c = text[i];
73
+ if (inString) {
74
+ if (c === "\\")
75
+ i++;
76
+ else if (c === '"')
77
+ inString = false;
78
+ }
79
+ else if (c === '"')
80
+ inString = true;
81
+ else if (c === "[" || c === "{")
82
+ depth++;
83
+ else if (c === "]" || c === "}") {
84
+ depth--;
85
+ if (depth === 0) {
86
+ if (c !== close)
87
+ return undefined;
88
+ try {
89
+ return JSON.parse(text.slice(start, i + 1));
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }
95
+ }
96
+ }
97
+ return undefined;
98
+ }
99
+ const isGitbook = ($) => $('meta[name="generator" i]').toArray().some((e) => /^GitBook\b/i.test($(e).attr("content") ?? ""));
100
+ /** Paths on a GitBook site that are never pages. */
101
+ const NOT_PAGES = /^\/(~gitbook|_next|~|llms(-full)?\.txt|sitemap)/;
102
+ /** A page's key: its path, no trailing slash, no `.md`. */
103
+ function pathKey(pathname) {
104
+ const p = pathname.replace(/\.md$/i, "").replace(/\/+$/, "");
105
+ return p || "/";
106
+ }
107
+ /** The deepest tree read (GitBook's sidebar is a handful of levels): deeper is left out. */
108
+ const MAX_DEPTH = 32;
109
+ /**
110
+ * The key of a tree entry's `href`, or null when it is not a page of this site: a path on the
111
+ * origin, percent-encoded as a link's URL is (so the tree and links name a page alike). An href
112
+ * like `@evil.test/x` or `//evil.test` is no page here.
113
+ */
114
+ function hrefKey(origin, href) {
115
+ if (typeof href !== "string" || !href.startsWith("/") || href.startsWith("//") || href.includes("\\"))
116
+ return null;
117
+ try {
118
+ const u = new URL(href, origin);
119
+ return u.origin === origin && !NOT_PAGES.test(u.pathname) ? pathKey(u.pathname) : null;
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ }
125
+ /** The adapter of one GitBook site and space, from a page of it. */
126
+ export function gitbookSite(origin, data) {
127
+ // The space's address: its first page's (the one with an empty pathname); the published URL
128
+ // can name another host (gitbook.io for a custom domain)
129
+ const isRoot = (p) => Array.isArray(p.pathnames) && p.pathnames.includes("");
130
+ const rootPage = data.pages.find((p) => p.type === "document" && isRoot(p));
131
+ const base = rootPage ? hrefKey(origin, rootPage.href) ?? "" : "";
132
+ // The tree as contents: the space's first page is the book, everything else under it
133
+ const entryOf = (p, depth) => {
134
+ if (!isGbPage(p) || depth > MAX_DEPTH)
135
+ return null;
136
+ const children = (Array.isArray(p.descendants) ? p.descendants : []).map((c) => entryOf(c, depth + 1)).filter((e) => !!e);
137
+ if (p.type === "group")
138
+ return children.length ? { title: p.title, key: null, children } : null;
139
+ if (p.type !== "document")
140
+ return null;
141
+ const key = hrefKey(origin, p.href);
142
+ if (!key)
143
+ return null;
144
+ // The `.md` of a space's first page is named by its slug (`<space>/<slug>.md`; `<space>.md` is a
145
+ // soft 404); any other page's is its address + `.md`
146
+ const slug = isRoot(p) ? p.pathnames.find((n) => typeof n === "string" && /^[^/?#\\]+$/.test(n)) : undefined;
147
+ const md = slug ? `${key === "/" ? "" : key}/${encodeURIComponent(slug)}.md` : `${key}.md`;
148
+ const aliases = [`/pages/${encodeURIComponent(p.id)}`, ...(pathKey(md) !== key ? [pathKey(md)] : [])];
149
+ return { title: p.title, key, aliases, fetchUrl: origin + md, children };
150
+ };
151
+ const top = data.pages.map((p) => entryOf(p, 0)).filter((e) => !!e);
152
+ const first = top.find((e) => e.key) ?? null;
153
+ const contents = first
154
+ ? [{ ...first, title: data.title || first.title, children: [...first.children, ...top.filter((e) => e !== first)] }]
155
+ : [];
156
+ const site = {
157
+ name: "gitbook",
158
+ profile: "generic",
159
+ delayMs: 1500,
160
+ matches: [],
161
+ detect: ($, url) => isGitbook($) && !!url && new URL(url).origin === origin,
162
+ readPage($, url) {
163
+ if (!url)
164
+ return null;
165
+ const key = site.keyOf(new URL(url));
166
+ if (!key)
167
+ return null;
168
+ return { key, url: origin + key, root: "main#gitbook-main-content", meta: data.title ? { space: data.title } : {} };
169
+ },
170
+ readContents: () => contents,
171
+ keyOf(url) {
172
+ if (url.origin !== origin || NOT_PAGES.test(url.pathname))
173
+ return null;
174
+ return pathKey(url.pathname);
175
+ },
176
+ urlOf: (key) => origin + key,
177
+ fileOf(key) {
178
+ // The page's path in the space as one file name, made of letters, digits, `.`, `_`, `-`
179
+ // (as Red Hat's and IBM's): no separator, no `..`, no hidden file, nothing a link decodes
180
+ const rel = base && base !== "/" && key.startsWith(base + "/") ? key.slice(base.length + 1) : key.replace(/^\//, "");
181
+ let decoded = rel;
182
+ try {
183
+ decoded = decodeURIComponent(rel);
184
+ }
185
+ catch { /* as written */ }
186
+ const name = decoded.replace(/\//g, "-").replace(/[^\p{L}\p{N}._-]/gu, "_").replace(/^[.]+/, "").slice(0, 120);
187
+ return `${name || "page"}.md`;
188
+ },
189
+ // A page's integration blocks come from its published page when one has no adapter, or an
190
+ // adapter that reads the page: its HTML is fetched too (plans/gitbook-integrations.md)
191
+ pageFor: (text) => needsPage(integrationNames(text)),
192
+ readText: (text, _page, html) => readGitbookText(text, html === undefined ? undefined : gitbookIntegrations(load(html))),
193
+ imageHost: (url) => url.protocol === "https:" && /(^|[-.])files\.gitbook\.io$/i.test(url.hostname),
194
+ };
195
+ return site;
196
+ }
197
+ /** The adapter every GitBook site gets bound from: detects, then `bind`s to the page's site. */
198
+ export const gitbook = {
199
+ name: "gitbook",
200
+ profile: "generic",
201
+ delayMs: 1500,
202
+ matches: [],
203
+ detect: ($) => isGitbook($),
204
+ bind($, url) {
205
+ if (!url || !isGitbook($))
206
+ return null;
207
+ try {
208
+ const data = gitbookData($);
209
+ return data && data.pages.length ? gitbookSite(new URL(url).origin, data) : null;
210
+ }
211
+ catch {
212
+ // Data that does not read as GitBook's: no adapter, not an error
213
+ return null;
214
+ }
215
+ },
216
+ // Unbound, it knows no site: detectSite gives the bound one
217
+ readPage: () => null,
218
+ keyOf: () => null,
219
+ urlOf: (key) => key,
220
+ fileOf: (key) => `${key.split("/").pop() || "index"}.md`,
221
+ };
222
+ /** GitBook's text around a page in its `.md`. */
223
+ const BANNER = /^> For the complete documentation index[^\n]*\n+/;
224
+ const AGENT = "\n---\n\n# Agent Instructions";
225
+ const MAX_BLOCKS = 500;
226
+ const RESOLVE_BUDGET = 2_000_000;
227
+ /**
228
+ * The integration blocks a published GitBook page's data holds (plans/gitbook-integrations.md):
229
+ * each object with `renderContext.integrationName` and `initialInput`, its input props and its
230
+ * ContentKit element (`initialOutput.element`), references resolved. In the data's order, which
231
+ * is not the page's: format-gitbook matches them by props.
232
+ */
233
+ export function gitbookIntegrations($) {
234
+ try {
235
+ return readIntegrations($);
236
+ }
237
+ catch {
238
+ // Data that does not read: the blocks are converted without the page, not the book failed
239
+ return [];
240
+ }
241
+ }
242
+ function readIntegrations($) {
243
+ const stream = nextStream($);
244
+ if (!stream)
245
+ return [];
246
+ const rows = nextRows(stream);
247
+ const budget = { left: RESOLVE_BUDGET };
248
+ const out = [];
249
+ for (const o of objectsIn(rows)) {
250
+ const ctx = o.renderContext;
251
+ const input = o.initialInput;
252
+ if (!ctx || typeof ctx.integrationName !== "string" || !input || typeof input !== "object")
253
+ continue;
254
+ const inp = resolveRefs(input, rows, budget);
255
+ const output = resolveRefs(o.initialOutput, rows, budget);
256
+ if (budget.left < 0)
257
+ break;
258
+ const props = inp?.props && typeof inp.props === "object" && !Array.isArray(inp.props) ? inp.props : {};
259
+ out.push({
260
+ integration: ctx.integrationName,
261
+ component: typeof inp?.componentId === "string" ? inp.componentId : "",
262
+ props,
263
+ url: typeof inp?.action?.url === "string" ? inp.action.url : undefined,
264
+ element: output?.element,
265
+ });
266
+ if (out.length >= MAX_BLOCKS)
267
+ break;
268
+ }
269
+ return out;
270
+ }
271
+ /**
272
+ * A page's `.md` as a tree, or null when it is GitBook's "Page Not Found". With its published
273
+ * page's integration blocks (`gitbookIntegrations`), its own are filled from them.
274
+ */
275
+ export function readGitbookText(text, pageIntegrations) {
276
+ let body = text.replace(/^/, "").replace(/\r\n?/g, "\n").replace(BANNER, "");
277
+ const agent = body.lastIndexOf(AGENT);
278
+ if (agent >= 0)
279
+ body = body.slice(0, agent).replace(/\s+$/, "\n");
280
+ if (/^#\s+Page Not Found\s*$/m.test(body.split("\n").find((l) => /^#\s/.test(l)) ?? ""))
281
+ return null;
282
+ // The book is a Dogsbay project: a block's records go in its data/, shared by the pages showing them
283
+ const parsed = parseGitbook(body, { pageIntegrations, dataFiles: true });
284
+ const { integrations, bodyLine, dataFiles } = parsed;
285
+ const tree = htmlCells(htmlHints(parsed.tree, 0), 0);
286
+ const h1 = tree.findIndex((n) => n.type === "heading" && n.props?.level === 1);
287
+ const title = h1 >= 0 ? plain(tree[h1]) : undefined;
288
+ // GitBook writes the page's description as the paragraph right after the title
289
+ const next = h1 >= 0 ? tree[h1 + 1] : undefined;
290
+ const description = next?.type === "paragraph" ? plain(next) || undefined : undefined;
291
+ // Counted on the source as realized: an integration block as what was written for it (from
292
+ // an adapter or the published page), which the text alone does not hold
293
+ const data = Object.keys(dataFiles).length ? { ...dataFiles } : undefined;
294
+ return { tree, title, description, type: "topic", source: countGitbook(realize(body, integrations, bodyLine)), ...(data ? { data } : {}) };
295
+ }
296
+ /** GitBook's hint styles as callout types (format-gitbook's `{% hint %}` mapping). */
297
+ const HINT_STYLES = { info: "info", success: "success", warning: "warning", danger: "danger", note: "note", tip: "tip" };
298
+ const HINT_DIV = /^\s*<div\s[^<>]*\bdata-gb-custom-block\b/i;
299
+ const MAX_HINT = 256 * 1024;
300
+ /**
301
+ * GitBook's hints written as HTML: inside a list item its `.md` has no `{% hint %}`, but
302
+ * `<div data-gb-custom-block data-tag="hint" data-style="…">…</div>` on one line (measured
303
+ * 2026-11-19: 1,178 on 634 of Harness's 8,428 pages). Each is a callout, its content read with
304
+ * the HTML core, so its links and images are the page's (settled, saved) and its text Markdown.
305
+ */
306
+ function htmlHints(nodes, depth) {
307
+ return nodes.flatMap((n) => {
308
+ const html = n.html;
309
+ if (n.type === "html" && typeof html === "string" && html.length <= MAX_HINT && HINT_DIV.test(html)) {
310
+ const callouts = hintCallouts(html);
311
+ if (callouts)
312
+ return callouts;
313
+ }
314
+ if (n.type === "html" && typeof html === "string" && html.length <= MAX_HINT && HTML_BLOCK.test(html)) {
315
+ const blocks = htmlBlock(html);
316
+ if (blocks)
317
+ return blocks;
318
+ }
319
+ if (n.children && depth < 64)
320
+ n.children = htmlHints(n.children, depth + 1);
321
+ return [n];
322
+ });
323
+ }
324
+ /**
325
+ * The node's hints as callouts: it holds hint divs and nothing else (two on adjacent lines are one
326
+ * node). Else null, and it stays HTML; so does one the HTML core cannot read (a review nested
327
+ * 5,000 divs in one: the stack ran out and the whole book failed).
328
+ */
329
+ function hintCallouts(html) {
330
+ if (tooDeep(html))
331
+ return null;
332
+ try {
333
+ const $ = load(`<main>${html}</main>`, null, false);
334
+ const main = $("main");
335
+ if (main.contents().toArray().some((c) => c.type === "text" && c.data?.trim()))
336
+ return null;
337
+ const divs = main.children().toArray().map((el) => $(el));
338
+ if (!divs.length || divs.some((d) => !d.is("div") || d.attr("data-tag") !== "hint" || d.attr("data-gb-custom-block") === undefined))
339
+ return null;
340
+ return divs.map((div) => {
341
+ const type = HINT_STYLES[div.attr("data-style") ?? ""] ?? "info";
342
+ const { tree } = htmlToTree(`<html><body><main>${div.html() ?? ""}</main></body></html>`, { profile: "generic", root: "main" });
343
+ return { type: "callout", props: { type }, children: tree, meta: { form: "directive" } };
344
+ });
345
+ }
346
+ catch {
347
+ return null;
348
+ }
349
+ }
350
+ const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
351
+ /**
352
+ * HTML the core is not asked to read: past 5,000 tags or 200 deep (a review's 36,000 nested `<b>`
353
+ * took 3 s per block, and the core's stack runs out at a few thousand). One linear scan.
354
+ */
355
+ function tooDeep(html) {
356
+ let depth = 0, tags = 0;
357
+ for (const m of html.matchAll(/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)[^<>]*?(\/?)>/g)) {
358
+ if (++tags > 5000)
359
+ return true;
360
+ if (m[1])
361
+ depth = Math.max(0, depth - 1);
362
+ else if (!m[3] && !VOID.has(m[2].toLowerCase()) && ++depth > 200)
363
+ return true;
364
+ }
365
+ return false;
366
+ }
367
+ /** Letters and digits: what a conversion must keep (a review's cell closed the table and lost its text). */
368
+ const letters = (t) => t.match(/[\p{L}\p{N}]/gu)?.length ?? 0;
369
+ /** A tree's text: text, code (a code block's `code`, or its `html` when it has none), math. */
370
+ const treeText = (x) => {
371
+ if (Array.isArray(x))
372
+ return x.map(treeText).join(" ");
373
+ if (!x || typeof x !== "object")
374
+ return "";
375
+ const o = x;
376
+ const own = [o.text, o.code, o.latex, o.type === "code" && !o.props?.code ? o.html : undefined].filter((v) => typeof v === "string");
377
+ return [...own, ...Object.entries(o).filter(([k]) => k !== "text" && k !== "html").map(([, v]) => treeText(v))].join(" ");
378
+ };
379
+ const htmlText = (html) => load(`<main>${html}</main>`, null, false)("main").text();
380
+ /** Block elements GitBook writes as HTML that the HTML core reads (hints and card tables have their own). */
381
+ const BLOCK_TAGS = ["table", "p", "div", "ul", "ol", "details", "figure", "blockquote", "h1", "h2", "h3", "h4", "h5", "h6", "pre"];
382
+ const HTML_BLOCK = new RegExp(`^\\s*<(?:${BLOCK_TAGS.join("|")})[\\s>]`, "i");
383
+ /**
384
+ * A block GitBook writes as HTML (a table whose cells hold paragraphs, lists and code; a centred
385
+ * image, `<p align="center"><img></p>`; …), read by the HTML core: its links are settled and images
386
+ * saved; the serializer writes Markdown where it can, else HTML again (measured 2026-11-19: tables
387
+ * on 46 of Harness's pages, centred images on 15). The node must be one such element and nothing
388
+ * else; hints and card tables are not this. Null: it stays as written.
389
+ */
390
+ function htmlBlock(html) {
391
+ if (tooDeep(html))
392
+ return null;
393
+ try {
394
+ const $ = load(`<main>${html}</main>`, null, false);
395
+ const main = $("main");
396
+ if (main.contents().toArray().some((c) => c.type === "text" && c.data?.trim()))
397
+ return null;
398
+ const top = main.children();
399
+ if (top.length !== 1)
400
+ return null;
401
+ const el = top.first();
402
+ const tag = el.prop("tagName")?.toLowerCase() ?? "";
403
+ if (!BLOCK_TAGS.includes(tag) || el.attr("data-view") === "cards" || el.attr("data-gb-custom-block") !== undefined)
404
+ return null;
405
+ const { tree } = htmlToTree(`<html><body><main>${html}</main></body></html>`, { profile: "generic", root: "main" });
406
+ return tree.length && letters(treeText(tree)) >= letters(main.text()) ? tree : null;
407
+ }
408
+ catch {
409
+ return null;
410
+ }
411
+ }
412
+ /**
413
+ * A Markdown table's cell holding HTML (GitBook writes `<p>`, `<br>`, `<a>`, lists and code into
414
+ * cells: measured 2026-11-19, 81 of the 116 Harness pages still losing links): the parser leaves the
415
+ * tags as raw HTML between Markdown text, so links in them were not links. The cell is put back
416
+ * together as HTML and read by the HTML core, as one cell of a table, so it gets the core's shape.
417
+ * A cell with anything that has no HTML form here (an icon, a badge, math) is left as it was.
418
+ */
419
+ function htmlCells(nodes, depth) {
420
+ for (const n of nodes) {
421
+ if ((n.type === "td" || n.type === "th") && n.inline?.some((i) => i.type === "html-inline")) {
422
+ const cell = htmlCell(n.inline, n.type);
423
+ if (cell) {
424
+ n.inline = cell.inline;
425
+ if (cell.children?.length)
426
+ n.children = cell.children;
427
+ }
428
+ }
429
+ if (n.children && depth < 64)
430
+ htmlCells(n.children, depth + 1);
431
+ }
432
+ return nodes;
433
+ }
434
+ const escHtml = (t) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
435
+ /** A node with no HTML form, held aside while its cell is read: `\uE000<n>\uE001` in the HTML. */
436
+ const KEEP = /\uE000(\d+)\uE001/;
437
+ function inlineAsHtml(ns, kept) {
438
+ let out = "";
439
+ for (const n of ns) {
440
+ switch (n.type) {
441
+ case "text": {
442
+ let t = escHtml(n.text);
443
+ if (n.strikethrough)
444
+ t = `<s>${t}</s>`;
445
+ if (n.italic)
446
+ t = `<em>${t}</em>`;
447
+ if (n.bold)
448
+ t = `<strong>${t}</strong>`;
449
+ out += t;
450
+ break;
451
+ }
452
+ case "link": {
453
+ const inner = inlineAsHtml(n.children ?? [], kept);
454
+ if (inner === null)
455
+ return null;
456
+ out += `<a href="${escHtml(n.href)}">${inner}</a>`;
457
+ break;
458
+ }
459
+ case "image":
460
+ out += `<img src="${escHtml(n.src)}" alt="${escHtml(n.alt ?? "")}">`;
461
+ break;
462
+ case "code":
463
+ out += `<code>${escHtml(n.text)}</code>`;
464
+ break;
465
+ case "html-inline":
466
+ out += n.html;
467
+ break;
468
+ case "break":
469
+ out += "<br>";
470
+ break;
471
+ case "highlight":
472
+ // `==x==` read ACROSS the cell's HTML (`<code>==</code>, … <code>==</code>`): in HTML, `==`
473
+ // is text, so it goes back as written (Harness, 2026-11-19: those cells stayed raw HTML).
474
+ // A real highlight (no HTML in it) is held aside and put back, as an icon is (review).
475
+ if ((n.children ?? []).some((c) => c.type === "html-inline")) {
476
+ const inner = inlineAsHtml(n.children ?? [], kept);
477
+ if (inner === null)
478
+ return null;
479
+ out += `==${inner}==`;
480
+ break;
481
+ }
482
+ // falls through
483
+ default:
484
+ // An icon, a badge, math: put back where it was once the cell is read
485
+ if (kept.length >= 1000)
486
+ return null;
487
+ out += `\uE000${kept.push(n) - 1}\uE001`;
488
+ }
489
+ }
490
+ return out;
491
+ }
492
+ /** The held nodes back in place of their markers, in every inline run under `n`. */
493
+ function putBack(n, kept) {
494
+ let ok = true;
495
+ const run = (ns) => ns.flatMap((x) => {
496
+ if (x.type === "link") {
497
+ x.children = run(x.children ?? []);
498
+ return [x];
499
+ }
500
+ if (x.type !== "text" || !x.text.includes("\uE000"))
501
+ return [x];
502
+ const parts = [];
503
+ let rest = x.text;
504
+ for (let m = KEEP.exec(rest); m; m = KEEP.exec(rest)) {
505
+ if (m.index)
506
+ parts.push({ ...x, text: rest.slice(0, m.index) });
507
+ const node = kept[Number(m[1])];
508
+ if (node)
509
+ parts.push(node);
510
+ else
511
+ ok = false;
512
+ rest = rest.slice(m.index + m[0].length);
513
+ }
514
+ if (rest)
515
+ parts.push({ ...x, text: rest });
516
+ return parts;
517
+ });
518
+ const walk = (t) => {
519
+ if (t.inline)
520
+ t.inline = run(t.inline);
521
+ for (const c of t.children ?? [])
522
+ walk(c);
523
+ };
524
+ walk(n);
525
+ return ok && !JSON.stringify(n).includes("\uE000");
526
+ }
527
+ function htmlCell(inline, tag) {
528
+ // Someone else's text holding our marker character, as itself or an entity: not read (it would
529
+ // be taken for a held node)
530
+ if (/\uE000|&#(?:x0*e000|0*57344);/i.test(JSON.stringify(inline)))
531
+ return null;
532
+ const kept = [];
533
+ const html = inlineAsHtml(inline, kept);
534
+ if (html === null || html.length > MAX_HINT || tooDeep(html))
535
+ return null;
536
+ try {
537
+ const { tree } = htmlToTree(`<html><body><main><table><tbody><tr><${tag}>${html}</${tag}></tr></tbody></table></main></body></html>`, { profile: "generic", root: "main" });
538
+ let cell = null;
539
+ const find = (ns) => { for (const x of ns ?? []) {
540
+ if (x.type === tag) {
541
+ cell = x;
542
+ return;
543
+ }
544
+ find(x.children);
545
+ } };
546
+ find(tree);
547
+ // All its text, or it stays as it was (HTML that closes the cell takes what follows out of it)
548
+ const before = letters(htmlText(html.replace(/\uE000\d+\uE001/g, "")));
549
+ if (!cell || letters(treeText(cell).replace(/\uE000\d+\uE001/g, "")) < before)
550
+ return null;
551
+ return putBack(cell, kept) ? cell : null;
552
+ }
553
+ catch {
554
+ return null;
555
+ }
556
+ }
557
+ /** The text with each integration block's lines replaced by what was written for it. */
558
+ function realize(text, blocks, bodyLine) {
559
+ if (!blocks.length)
560
+ return text;
561
+ const lines = text.split("\n");
562
+ for (const b of [...blocks].sort((x, y) => y.line - x.line)) {
563
+ lines.splice(bodyLine - 1 + b.line - 1, b.lines, ...(b.markdown ? ["", ...b.markdown.split("\n"), ""] : []));
564
+ }
565
+ return lines.join("\n");
566
+ }
567
+ function plain(n) {
568
+ const text = (ns) => (ns ?? []).map((x) => {
569
+ const i = x;
570
+ return (i.text ?? "") + text(i.children) + text(i.inline);
571
+ }).join("");
572
+ return text(n.inline).replace(/\s+/g, " ").trim();
573
+ }
574
+ /** Longer lines are counted on their first this many characters (a page's text is untrusted). */
575
+ const MAX_LINE = 20_000;
576
+ /**
577
+ * What a GitBook page's text holds, counted from the text (outside code), for the fidelity
578
+ * report: headings, code blocks, tables, list items, images, callouts (hints), links. Every scan
579
+ * is linear (the text is someone else's: a backtracking pattern over `<a href="x" ` repeated took
580
+ * minutes, review 2026-11-18).
581
+ */
582
+ export function countGitbook(text) {
583
+ const c = { headings: 0, codeBlocks: 0, tables: 0, listItems: 0, images: 0, callouts: 0, links: 0 };
584
+ let fence = null;
585
+ let inTable = false;
586
+ let inPre = false;
587
+ let preLines = 0;
588
+ for (const whole of text.split("\n")) {
589
+ const line = whole.length > MAX_LINE ? whole.slice(0, MAX_LINE) : whole;
590
+ const f = /^[ \t]*(`{3,}|~{3,})/.exec(line);
591
+ if (fence) {
592
+ if (f && f[1][0] === fence[0] && f[1].length >= fence.length && line.trim() === f[1])
593
+ fence = null;
594
+ continue;
595
+ }
596
+ if (f) {
597
+ fence = f[1];
598
+ c.codeBlocks++;
599
+ continue;
600
+ }
601
+ if (/^#{1,6}[ \t]/.test(line))
602
+ c.headings++;
603
+ // A Markdown table row; GitBook's card tables become cards, not tables (their links count below)
604
+ const t = line.trim();
605
+ const row = t.length > 1 && t.startsWith("|") && t.endsWith("|");
606
+ if (row && !inTable)
607
+ c.tables++;
608
+ inTable = row;
609
+ // Inside a `<pre>` of raw HTML (a hint's code over several lines) a `- ` line is code
610
+ if (!inPre && /^[ \t]*(>[ \t]*)*([-*+]|\d{1,9}[.)])[ \t]+\S/.test(line))
611
+ c.listItems++;
612
+ // (opened only on a line of raw HTML, outside code spans; never for more than 500 lines)
613
+ // (`<pre` and nothing longer: `<prettier>` is not one; a `</pre>` closes even between backticks,
614
+ // which are not code in raw HTML; review 2026-11-19)
615
+ const lower = line.toLowerCase();
616
+ const opens = [...line.replace(/`[^`\n]*`/g, "").toLowerCase().matchAll(/<pre[\s>]/g)];
617
+ const lastOpen = opens.length ? opens[opens.length - 1].index : -1;
618
+ const lastClose = lower.lastIndexOf("</pre>");
619
+ if (inPre && (lastClose >= 0 || ++preLines > 500))
620
+ inPre = false;
621
+ else if (!inPre && lastOpen >= 0 && lastOpen > lastClose && /^\s*</.test(line)) {
622
+ inPre = true;
623
+ preLines = 0;
624
+ }
625
+ c.callouts += count(line, "{% hint");
626
+ // A hint written as HTML (in a list item) is a callout, and its lists, code and headings are read
627
+ // (alone on its line, as htmlHints converts it)
628
+ // (its HTML may run on over the next lines: nothing after its last `</div>` on this one)
629
+ const close = line.lastIndexOf("</div>");
630
+ const hint = HINT_DIV.test(line) && line.includes('data-tag="hint"') && (close < 0 || !line.slice(close + 6).trim());
631
+ if (hint)
632
+ c.callouts++;
633
+ // A table written as HTML (not a card table) is read by the HTML core too: its lists, code and headings count
634
+ const htmlTableLine = HTML_BLOCK.test(line) && !line.includes('data-view="cards"');
635
+ // (a Markdown table's row too: its cells' HTML is read by the HTML core, htmlCells)
636
+ const inside = hint || htmlTableLine || row;
637
+ const cards = line.includes('data-view="cards"');
638
+ // In a hint's HTML, Markdown is text (GitBook shows `![x](y)` there as written)
639
+ // (and outside code spans and `{% … %}` tags: an embed's `url="<https://…>"` is counted as the embed)
640
+ const prose = hint ? "" : line.replace(/`[^`]*`/g, "").replace(/\{%[^%]*%\}/g, "");
641
+ // Embeds, files and page refs are written as links
642
+ c.links += count(line, "{% embed") + count(line, "{% file") + count(line, "{% page-ref");
643
+ for (const { tag, end } of tags(line)) {
644
+ const name = /^<([a-z][a-z0-9]*)/i.exec(tag)?.[1].toLowerCase();
645
+ if (name === "img")
646
+ c.images++;
647
+ else if (inside && name === "li")
648
+ c.listItems++;
649
+ else if (inside && name === "pre")
650
+ c.codeBlocks++;
651
+ else if (inside && name && /^h[1-6]$/.test(name))
652
+ c.headings++;
653
+ else if (name === "table" && !tag.includes('data-view="cards"'))
654
+ c.tables++;
655
+ // An <a> with an href and content (not GitBook's empty heading anchors)
656
+ // A card table's cover is an image written as a link to the image file: the card's image
657
+ else if (name === "a" && cards && /\shref="[^"]*\.(?:png|jpe?g|gif|svg|webp|avif)(?:[?#"])/i.test(tag))
658
+ c.images++;
659
+ else if (name === "a" && /\shref="[^"]/.test(tag) && !/\shref="\s*(?:javascript|vbscript|data|broken):/i.test(tag) && !/^\s*<\/a>/i.test(line.slice(end, end + 64)))
660
+ c.links++;
661
+ }
662
+ // An autolink, `<https://…>` (a link the converter keeps; it was not counted, 2026-11-19)
663
+ for (const m of withoutHtmlCode(prose).matchAll(/(?<!\]\()<(?:https?|mailto):[^\s<>]*>/gi))
664
+ if (m[0])
665
+ c.links++;
666
+ // Link syntax inside a code span is text (`curl [http://x](http://x)`); a link whose LABEL is
667
+ // code (``[`x`](y)``) is a link, so only spans holding `](` go
668
+ const md = markdownLinks(hint ? "" : line.replace(/`[^`\n]*`/g, (span) => (span.includes("](") ? "" : span)));
669
+ c.images += md.images;
670
+ c.links += md.links;
671
+ }
672
+ return c;
673
+ }
674
+ /** The line with each `<code>…</code>` left out, in one pass (a regex was quadratic on unclosed tags). */
675
+ function withoutHtmlCode(line) {
676
+ const lower = line.toLowerCase();
677
+ let out = "";
678
+ let at = 0;
679
+ for (;;) {
680
+ const open = lower.indexOf("<code", at);
681
+ if (open < 0)
682
+ break;
683
+ const close = lower.indexOf("</code>", open);
684
+ if (close < 0)
685
+ break;
686
+ out += line.slice(at, open);
687
+ at = close + 7;
688
+ }
689
+ return out + line.slice(at);
690
+ }
691
+ function count(line, word) {
692
+ let n = 0;
693
+ for (let at = line.indexOf(word); at >= 0; at = line.indexOf(word, at + word.length))
694
+ n++;
695
+ return n;
696
+ }
697
+ /** The line's HTML start tags (`<name …>`), each found once: a `<` with no `>` after it ends the scan. */
698
+ function tags(line) {
699
+ const out = [];
700
+ for (let at = line.indexOf("<"); at >= 0;) {
701
+ const end = line.indexOf(">", at);
702
+ if (end < 0)
703
+ break;
704
+ if (/^<[a-z]/i.test(line.slice(at, at + 2)))
705
+ out.push({ tag: line.slice(at, end + 1), end: end + 1 });
706
+ at = line.indexOf("<", end + 1);
707
+ }
708
+ return out;
709
+ }
710
+ /** `[label](dest` and `![alt](src`, counted in one pass. */
711
+ function markdownLinks(line) {
712
+ let links = 0, images = 0;
713
+ let open = -1;
714
+ for (let i = 0; i < line.length; i++) {
715
+ const ch = line[i];
716
+ if (ch === "[")
717
+ open = i;
718
+ else if (ch === "]" && open >= 0) {
719
+ const dest = line[i + 1] === "(" ? line[i + 2] : undefined;
720
+ if (dest && dest !== ")" && !/\s/.test(dest)) {
721
+ if (line[open - 1] === "!")
722
+ images++;
723
+ else if (i > open + 1)
724
+ links++;
725
+ }
726
+ open = -1;
727
+ }
728
+ }
729
+ return { links, images };
730
+ }