@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.
- package/README.md +59 -2
- package/dist/convert.d.ts +56 -0
- package/dist/convert.js +108 -0
- package/dist/core/blocks.d.ts +50 -0
- package/dist/core/blocks.js +372 -0
- package/dist/core/fidelity.d.ts +34 -0
- package/dist/core/fidelity.js +109 -0
- package/dist/core/inline.d.ts +34 -0
- package/dist/core/inline.js +165 -0
- package/dist/dom.d.ts +24 -0
- package/dist/dom.js +34 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +6 -0
- package/dist/profiles/broadcom-techdocs.d.ts +2 -0
- package/dist/profiles/broadcom-techdocs.js +105 -0
- package/dist/profiles/dita-ot-html5.d.ts +2 -0
- package/dist/profiles/dita-ot-html5.js +168 -0
- package/dist/profiles/generic.d.ts +3 -0
- package/dist/profiles/generic.js +18 -0
- package/dist/profiles/index.d.ts +11 -0
- package/dist/profiles/index.js +12 -0
- package/dist/profiles/types.d.ts +20 -0
- package/dist/profiles/types.js +1 -0
- package/dist/site/book.d.ts +154 -0
- package/dist/site/book.js +646 -0
- package/dist/site/gitbook.d.ts +74 -0
- package/dist/site/gitbook.js +730 -0
- package/dist/site/ibm.d.ts +2 -0
- package/dist/site/ibm.js +168 -0
- package/dist/site/index.d.ts +22 -0
- package/dist/site/index.js +20 -0
- package/dist/site/next-data.d.ts +25 -0
- package/dist/site/next-data.js +136 -0
- package/dist/site/redhat.d.ts +2 -0
- package/dist/site/redhat.js +127 -0
- package/dist/site/sniff.d.ts +38 -0
- package/dist/site/sniff.js +57 -0
- package/dist/site/types.d.ts +126 -0
- package/dist/site/types.js +1 -0
- package/package.json +49 -3
package/dist/site/ibm.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IBM Documentation (www.ibm.com/docs). A topic's address answers a browser with IBM's app (no
|
|
3
|
+
* content in the page: it loads it) and other clients with the topic as DITA-OT HTML. Either
|
|
4
|
+
* way this adapter reads what IBM's app reads, from IBM's API, so the CLI and the extension
|
|
5
|
+
* fetch the same things:
|
|
6
|
+
*
|
|
7
|
+
* - the product's contents, `/docs/api/v1/toc/<product path>?lang=<lang>`: JSON, each entry
|
|
8
|
+
* with its file (`href`) and the name its `?topic=` address uses (`topicId`);
|
|
9
|
+
* - each topic, `/docs/api/v1/content/<file>?parsebody=true&lang=<lang>`: the DITA-OT article.
|
|
10
|
+
*
|
|
11
|
+
* A topic's key is its file path, `<lang>/<product code>[_<version>]/…/<topic>.html`: what links
|
|
12
|
+
* between topics use. Its address, `/docs/<key>`, redirects to the `?topic=<name>` address the
|
|
13
|
+
* page names as canonical; the contents say which file each name is (`aliases`).
|
|
14
|
+
*
|
|
15
|
+
* IBM's content is © IBM, not openly licensed: imports are for the reader's own use.
|
|
16
|
+
*/
|
|
17
|
+
import { load } from "cheerio";
|
|
18
|
+
const ORIGIN = "https://www.ibm.com";
|
|
19
|
+
/**
|
|
20
|
+
* /docs/<lang>/<code>[_<version>]/…/<topic>.htm(l): a topic by its file. The code is IBM's
|
|
21
|
+
* product id in capitals, with the version (`SSEPGG_11.5.0`, Db2) or without (`SSAVQO`,
|
|
22
|
+
* watsonx Orchestrate).
|
|
23
|
+
*/
|
|
24
|
+
const FILE_PATH = /^[A-Z][A-Z0-9]{2,}(?:_[^/]+)?\/.+\.html?$/;
|
|
25
|
+
const FILE = /^\/docs\/([a-z]{2}(?:-[a-z]{2})?)\/([A-Z][A-Z0-9]{2,}(?:_[^/]+)?\/.+\.html?)$/;
|
|
26
|
+
/**
|
|
27
|
+
* /docs/<lang>/<product…>/<version>: a product's root, two or more lower-case segments:
|
|
28
|
+
* `db2/11.5.x`, `watsonx/watson-orchestrate/base`.
|
|
29
|
+
*/
|
|
30
|
+
const PRODUCT = /^\/docs\/([a-z]{2}(?:-[a-z]{2})?)\/((?:[a-z0-9][^/]*\/)+[a-z0-9][^/]*)\/?$/;
|
|
31
|
+
const HOSTS = new Set(["www.ibm.com", "ibm.com"]);
|
|
32
|
+
/** IBM's page data names the topic's file: `contentProducer: 'IBM Documentation 1.0 - SSAVQO/about/doc_landing.html'`. */
|
|
33
|
+
const PRODUCER = /contentProducer\s*:\s*['"][^'"]*? - ([A-Z][A-Z0-9]{2,}(?:_[^/'"]+)?\/[^'"\s]+\.html?)['"]/;
|
|
34
|
+
const LANG = /^[a-z]{2}(?:-[a-z]{2})?$/;
|
|
35
|
+
export const ibm = {
|
|
36
|
+
name: "ibm",
|
|
37
|
+
profile: "dita-ot-html5",
|
|
38
|
+
delayMs: 1500,
|
|
39
|
+
matches: ["https://www.ibm.com/docs/*"],
|
|
40
|
+
licence: {
|
|
41
|
+
name: "© IBM Corporation (not openly licensed)",
|
|
42
|
+
url: "https://www.ibm.com/legal",
|
|
43
|
+
notice: "IBM documentation is © IBM Corporation and is not openly licensed: keep this import for your own use and do not republish it.",
|
|
44
|
+
},
|
|
45
|
+
// A topic: as IBM's app (a browser), or as plain HTML (other clients). Not a product's
|
|
46
|
+
// landing page or search: no topic there.
|
|
47
|
+
detect($, url) {
|
|
48
|
+
const u = pageUrl($, url);
|
|
49
|
+
if (!u || !HOSTS.has(u.hostname) || !u.pathname.startsWith("/docs/"))
|
|
50
|
+
return false;
|
|
51
|
+
// On a copy: readPage prepares the page in place
|
|
52
|
+
return !!ibm.readPage(load($.html()), u.href);
|
|
53
|
+
},
|
|
54
|
+
readPage($, url) {
|
|
55
|
+
const u = pageUrl($, url);
|
|
56
|
+
if (!u)
|
|
57
|
+
return null;
|
|
58
|
+
let key = ibm.keyOf(u);
|
|
59
|
+
if (!key)
|
|
60
|
+
return null;
|
|
61
|
+
// The page's product, version and language: from its canonical ?topic= address
|
|
62
|
+
const canonical = $('link[rel="canonical"]').attr("href");
|
|
63
|
+
const c = canonical ? safeUrl(canonical) : null;
|
|
64
|
+
const pm = (c && PRODUCT.exec(c.pathname)) || PRODUCT.exec(u.pathname);
|
|
65
|
+
const lang = pm?.[1] ?? key.split("/")[0];
|
|
66
|
+
// IBM's app names the topic's file in its page data: the key, when the address only has a name
|
|
67
|
+
const file = $("script").toArray().map((s) => PRODUCER.exec($(s).text())?.[1]).find(Boolean);
|
|
68
|
+
// Only when the page names the topic it is at (the canonical's ?topic= is the address's): an
|
|
69
|
+
// app's page data can be the first page loaded's
|
|
70
|
+
const sameTopic = !c || c.searchParams.get("topic") === u.searchParams.get("topic");
|
|
71
|
+
if (file && sameTopic && key.includes("?topic="))
|
|
72
|
+
key = `${lang}/${file}`;
|
|
73
|
+
const article = $("main article").length ? "main article" : "article";
|
|
74
|
+
// Neither a topic nor IBM's app showing one (a product's landing page, search)
|
|
75
|
+
if (!$(article).length && !file && !key.includes("?topic="))
|
|
76
|
+
return null;
|
|
77
|
+
const product = ($('meta[property="og:title"]').attr("content") ?? "").split(" | ").slice(1).join(" | ").trim();
|
|
78
|
+
const version = pm ? pm[2].split("/").pop() : "";
|
|
79
|
+
const meta = { lang };
|
|
80
|
+
// "Db2 for Linux, UNIX and Windows 11.5.x": the name without the version, which is its own fact
|
|
81
|
+
// The version as IBM writes it in the title ("Base"), not as the address has it ("base")
|
|
82
|
+
const named = !!version && product.toLowerCase().endsWith(` ${version.toLowerCase()}`);
|
|
83
|
+
if (product)
|
|
84
|
+
meta.product = named ? product.slice(0, -version.length - 1) : product;
|
|
85
|
+
if (version)
|
|
86
|
+
meta.version = named ? product.slice(-version.length) : version;
|
|
87
|
+
if (pm)
|
|
88
|
+
meta.productPath = pm[2];
|
|
89
|
+
$(`${article} script, ${article} style`).remove();
|
|
90
|
+
// "Last Updated: 2026-08-14", IBM's line in the article: the page's date, not its content
|
|
91
|
+
const stamp = $(`${article} #lastModifiedDate`);
|
|
92
|
+
const updated = /\d{4}-\d{2}-\d{2}/.exec(stamp.text())?.[0];
|
|
93
|
+
stamp.remove();
|
|
94
|
+
return { key, url: ibm.urlOf(key), root: article, meta, ...(updated ? { updated } : {}) };
|
|
95
|
+
},
|
|
96
|
+
contentsUrl: (page) => page.meta.productPath ? `${ORIGIN}/docs/api/v1/toc/${page.meta.productPath}?lang=${page.meta.lang ?? "en"}` : undefined,
|
|
97
|
+
// The contents API: { toc: { label, href, topicId, topics: [...] } }, the product at the top
|
|
98
|
+
// and its books under it; hrefs relative to /docs/<lang>/. A file listed twice has `?pos=2`.
|
|
99
|
+
readContents(_$, page, source) {
|
|
100
|
+
let toc;
|
|
101
|
+
try {
|
|
102
|
+
toc = source ? JSON.parse(source).toc : undefined;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return [];
|
|
106
|
+
}
|
|
107
|
+
if (!toc)
|
|
108
|
+
return [];
|
|
109
|
+
const lang = page.meta.lang ?? "en";
|
|
110
|
+
const base = `${ORIGIN}/docs/${lang}/`;
|
|
111
|
+
const product = page.meta.productPath;
|
|
112
|
+
const entry = (t) => {
|
|
113
|
+
const u = t.href ? safeUrl(t.href, base) : null;
|
|
114
|
+
const key = u ? ibm.keyOf(u) : null;
|
|
115
|
+
return {
|
|
116
|
+
title: (t.label ?? "").replace(/\s+/g, " ").trim(),
|
|
117
|
+
key,
|
|
118
|
+
...(key && product && t.topicId ? { aliases: [`${lang}/${product}?topic=${t.topicId}`] } : {}),
|
|
119
|
+
children: (t.topics ?? []).map(entry),
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
return (toc.topics ?? []).map(entry);
|
|
123
|
+
},
|
|
124
|
+
keyOf(u) {
|
|
125
|
+
if (!HOSTS.has(u.hostname))
|
|
126
|
+
return null;
|
|
127
|
+
const f = FILE.exec(u.pathname);
|
|
128
|
+
if (f)
|
|
129
|
+
return `${f[1]}/${f[2]}`;
|
|
130
|
+
// /docs/<lang>/<product>/<version>?topic=<file path or name>
|
|
131
|
+
const p = PRODUCT.exec(u.pathname);
|
|
132
|
+
const topic = u.searchParams.get("topic");
|
|
133
|
+
if (!p || !topic)
|
|
134
|
+
return null;
|
|
135
|
+
if (FILE_PATH.test(topic))
|
|
136
|
+
return `${p[1]}/${topic}`;
|
|
137
|
+
return `${p[1]}/${p[2]}?topic=${topic}`;
|
|
138
|
+
},
|
|
139
|
+
// A topic's content, as IBM's app fetches it
|
|
140
|
+
fetchUrlOf(key) {
|
|
141
|
+
const [lang, ...rest] = key.split("/");
|
|
142
|
+
const file = rest.join("/");
|
|
143
|
+
if (!LANG.test(lang) || !FILE_PATH.test(file))
|
|
144
|
+
return ibm.urlOf(key);
|
|
145
|
+
return `${ORIGIN}/docs/api/v1/content/${encodeURIComponent(file)}?parsebody=true&lang=${lang}`;
|
|
146
|
+
},
|
|
147
|
+
urlOf: (key) => `${ORIGIN}/docs/${key}`,
|
|
148
|
+
// The topic's file name (`r0002034.html` → r0002034.md); a slug key gives the slug
|
|
149
|
+
fileOf: (key) => {
|
|
150
|
+
const last = key.includes("?topic=") ? key.split("?topic=")[1] : key.split("/").pop();
|
|
151
|
+
return `${last.replace(/\.html?$/, "").replace(/[^\p{L}\p{N}._-]/gu, "_") || "page"}.md`;
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
/** The page's URL: the one it was fetched from, else its canonical link. */
|
|
155
|
+
function pageUrl($, url) {
|
|
156
|
+
if (url)
|
|
157
|
+
return safeUrl(url);
|
|
158
|
+
const canonical = $('link[rel="canonical"]').attr("href");
|
|
159
|
+
return canonical ? safeUrl(canonical) : null;
|
|
160
|
+
}
|
|
161
|
+
function safeUrl(href, base) {
|
|
162
|
+
try {
|
|
163
|
+
return new URL(href, base);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @dogsbay/format-html/site: whole books from documentation sites, through site
|
|
3
|
+
* adapters. Never fetches; the caller passes its fetch to importBook.
|
|
4
|
+
*/
|
|
5
|
+
import type { CheerioAPI } from "cheerio";
|
|
6
|
+
import { gitbook, gitbookSite, gitbookData, readGitbookText, countGitbook } from "./gitbook.js";
|
|
7
|
+
import { ibm } from "./ibm.js";
|
|
8
|
+
import { redhat } from "./redhat.js";
|
|
9
|
+
import type { SiteAdapter } from "./types.js";
|
|
10
|
+
/** Sites by their own domain first; GitBook (any domain, by its generator tag) last. */
|
|
11
|
+
export declare const SITES: SiteAdapter[];
|
|
12
|
+
export declare function siteByName(name: string): SiteAdapter | undefined;
|
|
13
|
+
/** The adapter for a page: an adapter for any site (GitBook) bound to the page's site, or none when it cannot be. */
|
|
14
|
+
export declare function detectSite($: CheerioAPI, url?: string): SiteAdapter | undefined;
|
|
15
|
+
export { redhat, ibm, gitbook, gitbookSite, gitbookData, readGitbookText, countGitbook };
|
|
16
|
+
/** Every adapter's pages, as extension match patterns. */
|
|
17
|
+
export declare const SITE_MATCHES: string[];
|
|
18
|
+
export { importBook, planBook, planScopes, findBook, navYaml } from "./book.js";
|
|
19
|
+
export type { ImportBookOptions, ImportBookResult, PageReport, BookPlan, ScopePlan, ScopeRung } from "./book.js";
|
|
20
|
+
export type { SiteAdapter, SitePageInfo, ContentsEntry, TextPage } from "./types.js";
|
|
21
|
+
export { identifyTool, pageFacts } from "./sniff.js";
|
|
22
|
+
export type { PageFacts, Tool, ToolId } from "./sniff.js";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { gitbook, gitbookSite, gitbookData, readGitbookText, countGitbook } from "./gitbook.js";
|
|
2
|
+
import { ibm } from "./ibm.js";
|
|
3
|
+
import { redhat } from "./redhat.js";
|
|
4
|
+
/** Sites by their own domain first; GitBook (any domain, by its generator tag) last. */
|
|
5
|
+
export const SITES = [redhat, ibm, gitbook];
|
|
6
|
+
export function siteByName(name) {
|
|
7
|
+
return SITES.find((s) => s.name === name);
|
|
8
|
+
}
|
|
9
|
+
/** The adapter for a page: an adapter for any site (GitBook) bound to the page's site, or none when it cannot be. */
|
|
10
|
+
export function detectSite($, url) {
|
|
11
|
+
const site = SITES.find((s) => s.detect($, url));
|
|
12
|
+
if (!site?.bind)
|
|
13
|
+
return site;
|
|
14
|
+
return site.bind($, url) ?? undefined;
|
|
15
|
+
}
|
|
16
|
+
export { redhat, ibm, gitbook, gitbookSite, gitbookData, readGitbookText, countGitbook };
|
|
17
|
+
/** Every adapter's pages, as extension match patterns. */
|
|
18
|
+
export const SITE_MATCHES = [...new Set(SITES.flatMap((s) => s.matches))];
|
|
19
|
+
export { importBook, planBook, planScopes, findBook, navYaml } from "./book.js";
|
|
20
|
+
export { identifyTool, pageFacts } from "./sniff.js";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Next.js page's streamed data (React Server Components): the `self.__next_f.push([1,"…"])`
|
|
3
|
+
* scripts joined into one stream of rows, `<hex id>:<payload>\n`. A payload is JSON, or a text
|
|
4
|
+
* row `T<hex byte length>,<text>` (long strings: GitHub Files' code), or another kind (`I[…]`,
|
|
5
|
+
* `HL[…]`) not read here. In JSON, a string `"$<id>"` or `"$<id>:a:b"` is a reference to a
|
|
6
|
+
* row (and a path in it), `"$$…"` is a string starting `$`, and the other `$` forms (`$L…`
|
|
7
|
+
* lazy components, `$undefined`, `$@…`) are no data. The page is someone else's: sizes, depth
|
|
8
|
+
* and references are capped, and nothing found is trusted as more than plain values.
|
|
9
|
+
*/
|
|
10
|
+
import type { CheerioAPI } from "cheerio";
|
|
11
|
+
/** The joined stream of the page's data scripts, or "" when it has none (or more than 16 MB). */
|
|
12
|
+
export declare function nextStream($: CheerioAPI): string;
|
|
13
|
+
export type Rows = Map<string, unknown>;
|
|
14
|
+
/** The stream's rows by id: JSON values and text rows (as strings). Text rows are measured in UTF-8 bytes. */
|
|
15
|
+
export declare function nextRows(stream: string): Rows;
|
|
16
|
+
/**
|
|
17
|
+
* A value with its references resolved (rows and paths in them), at most `budget` values
|
|
18
|
+
* visited in all (`budget.left` is shared by a caller resolving several), `MAX_DEPTH` deep. A
|
|
19
|
+
* reference being resolved is not followed again (a cycle gives undefined).
|
|
20
|
+
*/
|
|
21
|
+
export declare function resolveRefs(value: unknown, rows: Rows, budget: {
|
|
22
|
+
left: number;
|
|
23
|
+
}, depth?: number, active?: Set<string>): unknown;
|
|
24
|
+
/** Every object in the rows (not following references), depth first, at most `limit`. */
|
|
25
|
+
export declare function objectsIn(rows: Rows, limit?: number): Generator<Record<string, unknown>>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
const MAX_STREAM = 16 * 1024 * 1024;
|
|
2
|
+
/** The joined stream of the page's data scripts, or "" when it has none (or more than 16 MB). */
|
|
3
|
+
export function nextStream($) {
|
|
4
|
+
let stream = "";
|
|
5
|
+
for (const el of $("script").toArray()) {
|
|
6
|
+
const text = $(el).text();
|
|
7
|
+
const m = /^\s*self\.__next_f\.push\((\[[\s\S]*\])\)\s*;?\s*$/.exec(text);
|
|
8
|
+
if (!m)
|
|
9
|
+
continue;
|
|
10
|
+
try {
|
|
11
|
+
const row = JSON.parse(m[1]);
|
|
12
|
+
if (row[0] === 1 && typeof row[1] === "string")
|
|
13
|
+
stream += row[1];
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
// not a data row
|
|
17
|
+
}
|
|
18
|
+
if (stream.length > MAX_STREAM)
|
|
19
|
+
return "";
|
|
20
|
+
}
|
|
21
|
+
return stream;
|
|
22
|
+
}
|
|
23
|
+
/** The stream's rows by id: JSON values and text rows (as strings). Text rows are measured in UTF-8 bytes. */
|
|
24
|
+
export function nextRows(stream) {
|
|
25
|
+
const bytes = new TextEncoder().encode(stream);
|
|
26
|
+
const decode = new TextDecoder();
|
|
27
|
+
const rows = new Map();
|
|
28
|
+
const HEX = (c) => (c >= 0x30 && c <= 0x39) || (c >= 0x61 && c <= 0x66);
|
|
29
|
+
// Linear: every search moves `p` past what it scanned (a newline searched for from each text
|
|
30
|
+
// row, which ends without one, rescanned the stream: quadratic, review 2026-11-19)
|
|
31
|
+
const skipLine = (from) => {
|
|
32
|
+
const nl = bytes.indexOf(0x0a, from);
|
|
33
|
+
return nl < 0 ? bytes.length : nl + 1;
|
|
34
|
+
};
|
|
35
|
+
let p = 0;
|
|
36
|
+
while (p < bytes.length) {
|
|
37
|
+
let q = p;
|
|
38
|
+
while (q < bytes.length && q - p <= 8 && HEX(bytes[q]))
|
|
39
|
+
q++;
|
|
40
|
+
if (q === p || q - p > 8 || bytes[q] !== 0x3a /* : */) {
|
|
41
|
+
p = skipLine(p);
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const id = decode.decode(bytes.subarray(p, q));
|
|
45
|
+
const colon = q;
|
|
46
|
+
if (bytes[colon + 1] === 0x54 /* T */) {
|
|
47
|
+
let comma = colon + 2;
|
|
48
|
+
while (comma < bytes.length && comma - colon < 12 && HEX(bytes[comma]))
|
|
49
|
+
comma++;
|
|
50
|
+
if (bytes[comma] !== 0x2c /* , */) {
|
|
51
|
+
p = skipLine(colon);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const len = parseInt(decode.decode(bytes.subarray(colon + 2, comma)), 16);
|
|
55
|
+
if (!Number.isFinite(len) || comma + 1 + len > bytes.length)
|
|
56
|
+
break;
|
|
57
|
+
rows.set(id, decode.decode(bytes.subarray(comma + 1, comma + 1 + len)));
|
|
58
|
+
p = comma + 1 + len;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const next = skipLine(colon);
|
|
62
|
+
const raw = decode.decode(bytes.subarray(colon + 1, next > colon + 1 && bytes[next - 1] === 0x0a ? next - 1 : next));
|
|
63
|
+
if (/^[[{"]/.test(raw)) {
|
|
64
|
+
try {
|
|
65
|
+
rows.set(id, JSON.parse(raw));
|
|
66
|
+
}
|
|
67
|
+
catch { /* not JSON: skipped */ }
|
|
68
|
+
}
|
|
69
|
+
p = next;
|
|
70
|
+
}
|
|
71
|
+
return rows;
|
|
72
|
+
}
|
|
73
|
+
const MAX_DEPTH = 64;
|
|
74
|
+
/**
|
|
75
|
+
* A value with its references resolved (rows and paths in them), at most `budget` values
|
|
76
|
+
* visited in all (`budget.left` is shared by a caller resolving several), `MAX_DEPTH` deep. A
|
|
77
|
+
* reference being resolved is not followed again (a cycle gives undefined).
|
|
78
|
+
*/
|
|
79
|
+
export function resolveRefs(value, rows, budget, depth = 0, active = new Set()) {
|
|
80
|
+
if (--budget.left < 0 || depth > MAX_DEPTH)
|
|
81
|
+
return undefined;
|
|
82
|
+
if (typeof value === "string") {
|
|
83
|
+
if (!value.startsWith("$"))
|
|
84
|
+
return value;
|
|
85
|
+
if (value.startsWith("$$"))
|
|
86
|
+
return value.slice(1);
|
|
87
|
+
const m = /^\$([0-9a-f]{1,8})((?::[^:]+)*)$/.exec(value);
|
|
88
|
+
if (!m || active.has(value))
|
|
89
|
+
return undefined;
|
|
90
|
+
let target = rows.get(m[1]);
|
|
91
|
+
for (const seg of m[2] ? m[2].slice(1).split(":") : []) {
|
|
92
|
+
// a path may run through references of its own
|
|
93
|
+
if (typeof target === "string" && target.startsWith("$")) {
|
|
94
|
+
active.add(value);
|
|
95
|
+
target = resolveRefs(target, rows, budget, depth + 1, active);
|
|
96
|
+
active.delete(value);
|
|
97
|
+
}
|
|
98
|
+
target = target !== null && typeof target === "object" && Object.prototype.hasOwnProperty.call(target, seg) ? target[seg] : undefined;
|
|
99
|
+
}
|
|
100
|
+
active.add(value);
|
|
101
|
+
const out = resolveRefs(target, rows, budget, depth + 1, active);
|
|
102
|
+
active.delete(value);
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
if (Array.isArray(value))
|
|
106
|
+
return value.map((v) => resolveRefs(v, rows, budget, depth + 1, active));
|
|
107
|
+
if (value !== null && typeof value === "object") {
|
|
108
|
+
const out = Object.create(null);
|
|
109
|
+
for (const [k, v] of Object.entries(value)) {
|
|
110
|
+
if (k === "__proto__")
|
|
111
|
+
continue;
|
|
112
|
+
out[k] = resolveRefs(v, rows, budget, depth + 1, active);
|
|
113
|
+
}
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
return value;
|
|
117
|
+
}
|
|
118
|
+
/** Every object in the rows (not following references), depth first, at most `limit`. */
|
|
119
|
+
export function* objectsIn(rows, limit = 1_000_000) {
|
|
120
|
+
let left = limit;
|
|
121
|
+
const stack = [...rows.values()].reverse();
|
|
122
|
+
while (stack.length && left-- > 0) {
|
|
123
|
+
const v = stack.pop();
|
|
124
|
+
if (Array.isArray(v)) {
|
|
125
|
+
for (let k = v.length - 1; k >= 0; k--)
|
|
126
|
+
stack.push(v[k]);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (v === null || typeof v !== "object")
|
|
130
|
+
continue;
|
|
131
|
+
yield v;
|
|
132
|
+
const vals = Object.values(v);
|
|
133
|
+
for (let k = vals.length - 1; k >= 0; k--)
|
|
134
|
+
stack.push(vals[k]);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
const ORIGIN = "https://docs.redhat.com";
|
|
2
|
+
const PATH = /^\/(?:([a-z]{2}(?:-[a-z]{2})?)\/)?documentation\/([^/]+)\/([^/]+)\/([^/?#]+)\/?$/;
|
|
3
|
+
const HOSTS = new Set(["docs.redhat.com", "localhost"]);
|
|
4
|
+
/** Red Hat's chrome inside the topic. */
|
|
5
|
+
const CHROME = [
|
|
6
|
+
"rh-tooltip", "rh-button", "rh-icon", ".rhdocs-table-show-more-btn", ".rhdocs-table-expand-btn",
|
|
7
|
+
".copy-link-tooltip", ".content-code-block-container-actions", "rh-alert.banner-wrapper",
|
|
8
|
+
];
|
|
9
|
+
/** The header of an rh-alert names the DITA note type. */
|
|
10
|
+
const ALERT_TYPES = {
|
|
11
|
+
note: "note", tip: "tip", important: "important", warning: "warning", caution: "caution", danger: "danger",
|
|
12
|
+
remember: "note", restriction: "warning", attention: "important", notice: "important",
|
|
13
|
+
};
|
|
14
|
+
const ALERT_STATES = { danger: "danger", warning: "warning", caution: "caution", info: "note", success: "tip", neutral: "note" };
|
|
15
|
+
export const redhat = {
|
|
16
|
+
name: "redhat",
|
|
17
|
+
profile: "dita-ot-html5",
|
|
18
|
+
delayMs: 1500,
|
|
19
|
+
matches: ["https://docs.redhat.com/*"],
|
|
20
|
+
licence: {
|
|
21
|
+
name: "CC BY-SA 4.0",
|
|
22
|
+
url: "https://creativecommons.org/licenses/by-sa/4.0/",
|
|
23
|
+
notice: "Red Hat documentation is licensed CC BY-SA 4.0; keep this attribution and licence with anything made from it.",
|
|
24
|
+
},
|
|
25
|
+
detect($, url) {
|
|
26
|
+
// A Red Hat URL shape alone is not enough (another site may use the same paths):
|
|
27
|
+
// the page was fetched from docs.redhat.com, or it carries Red Hat's components
|
|
28
|
+
const u = pageUrl($, url);
|
|
29
|
+
if (!u || redhat.keyOf(u) === null)
|
|
30
|
+
return false;
|
|
31
|
+
if (url && new URL(url).hostname === "docs.redhat.com")
|
|
32
|
+
return true;
|
|
33
|
+
return $(".topic-toc-list rh-accordion").length > 0 || $("rh-alert, rh-code-block, rh-table, rh-tooltip").length > 0;
|
|
34
|
+
},
|
|
35
|
+
readPage($, url) {
|
|
36
|
+
const u = pageUrl($, url);
|
|
37
|
+
const key = u && redhat.keyOf(u);
|
|
38
|
+
if (!key)
|
|
39
|
+
return null;
|
|
40
|
+
const article = $("article").first();
|
|
41
|
+
if (!article.length)
|
|
42
|
+
return null;
|
|
43
|
+
article.find(CHROME.join(",")).remove();
|
|
44
|
+
article.find("rh-alert").each((_, el) => {
|
|
45
|
+
const e = $(el);
|
|
46
|
+
const header = e.children('[slot="header"]').first();
|
|
47
|
+
const label = header.text().trim();
|
|
48
|
+
const type = ALERT_TYPES[label.toLowerCase()] ?? ALERT_STATES[e.attr("state") ?? ""] ?? "note";
|
|
49
|
+
header.remove();
|
|
50
|
+
const body = e.find(".note__body").first();
|
|
51
|
+
const node = el;
|
|
52
|
+
node.name = "div";
|
|
53
|
+
node.attribs = { "data-callout": type, ...(label && label.toLowerCase() !== type ? { "data-callout-title": label } : {}) };
|
|
54
|
+
if (body.length)
|
|
55
|
+
e.empty().append(body.contents());
|
|
56
|
+
});
|
|
57
|
+
// <h2><a href="#id" class="anchor-heading">Title</a></h2>: the self-link is the title
|
|
58
|
+
article.find("a.anchor-heading").each((_, el) => { $(el).replaceWith($(el).contents()); });
|
|
59
|
+
const m = PATH.exec(u.pathname);
|
|
60
|
+
return {
|
|
61
|
+
key,
|
|
62
|
+
url: redhat.urlOf(key),
|
|
63
|
+
root: "article",
|
|
64
|
+
meta: { lang: m[1] ?? "en", product: m[2], version: m[3], slug: m[4] },
|
|
65
|
+
};
|
|
66
|
+
},
|
|
67
|
+
readContents($, page) {
|
|
68
|
+
const base = new URL(page.url);
|
|
69
|
+
const acc = $(".topic-toc-list rh-accordion").first();
|
|
70
|
+
const items = (ul) => $(ul).children("li").map((_, li) => {
|
|
71
|
+
const a = $(li).children("div").children("a").first();
|
|
72
|
+
const href = a.attr("href") ?? "";
|
|
73
|
+
let key = null;
|
|
74
|
+
let fragment;
|
|
75
|
+
if (href) {
|
|
76
|
+
const u = new URL(href, base);
|
|
77
|
+
key = redhat.keyOf(u);
|
|
78
|
+
fragment = u.hash ? decodeURIComponent(u.hash.slice(1)) : undefined;
|
|
79
|
+
}
|
|
80
|
+
const children = $(li).children("ul").toArray().flatMap((u) => items(u));
|
|
81
|
+
const entry = { title: a.text().replace(/\s+/g, " ").trim(), key, children };
|
|
82
|
+
if (fragment)
|
|
83
|
+
entry.fragment = fragment;
|
|
84
|
+
return entry;
|
|
85
|
+
}).get();
|
|
86
|
+
return acc.children("rh-accordion-header").map((_, h) => ({
|
|
87
|
+
title: $(h).text().replace(/\s+/g, " ").trim(),
|
|
88
|
+
key: null,
|
|
89
|
+
children: $(h).next("rh-accordion-panel").children("ul").toArray().flatMap((u) => items(u)),
|
|
90
|
+
})).get();
|
|
91
|
+
},
|
|
92
|
+
keyOf(u) {
|
|
93
|
+
if (!HOSTS.has(u.hostname))
|
|
94
|
+
return null;
|
|
95
|
+
const m = PATH.exec(u.pathname);
|
|
96
|
+
return m ? `${m[1] ?? "en"}/documentation/${m[2]}/${m[3]}/${m[4]}` : null;
|
|
97
|
+
},
|
|
98
|
+
urlOf: (key) => `${ORIGIN}/${key}`,
|
|
99
|
+
// The slug, decoded, with anything a file name or a Markdown link target cannot carry made "_"
|
|
100
|
+
fileOf: (key) => {
|
|
101
|
+
const slug = key.split("/").pop();
|
|
102
|
+
let name;
|
|
103
|
+
try {
|
|
104
|
+
name = decodeURIComponent(slug);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
name = slug;
|
|
108
|
+
}
|
|
109
|
+
return `${name.replace(/[^\p{L}\p{N}._-]/gu, "_") || "page"}.md`;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
/** The page's URL: the one it was fetched from, else its canonical link's path on docs.redhat.com. */
|
|
113
|
+
function pageUrl($, url) {
|
|
114
|
+
try {
|
|
115
|
+
if (url)
|
|
116
|
+
return new URL(url);
|
|
117
|
+
const canonical = $('link[rel="canonical"]').attr("href");
|
|
118
|
+
if (!canonical)
|
|
119
|
+
return null;
|
|
120
|
+
// Red Hat's canonical links name localhost (2026); another host is another site
|
|
121
|
+
const c = new URL(canonical);
|
|
122
|
+
return HOSTS.has(c.hostname) ? new URL(c.pathname, ORIGIN) : null;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which documentation tool made a page, from what the page says about itself: its
|
|
3
|
+
* `generator` meta tags, a published Markdown version (`<link rel="alternate"
|
|
4
|
+
* type="text/markdown">`) and Sphinx's markers (Sphinx writes no generator tag). Read,
|
|
5
|
+
* never fetched; nothing on the page is changed.
|
|
6
|
+
*
|
|
7
|
+
* Two readers give the same facts: `pageFacts` (cheerio, the CLI and tests) and the
|
|
8
|
+
* extension's own DOM function (apps/import-extension/src/sniff.ts, which Chrome runs in
|
|
9
|
+
* the tab and so cannot import this module). Keep them in step.
|
|
10
|
+
*
|
|
11
|
+
* Checked on the tools' own sites 2026-11-18: GitBook, Docusaurus, VitePress, Starlight
|
|
12
|
+
* (beside an Astro tag), Astro, MkDocs Material, Hugo, Mintlify, Jekyll by its documented
|
|
13
|
+
* tag, Sphinx by its footer and `_static/documentation_options.js`, DITA-OT by its generator tag
|
|
14
|
+
* or its HTML5 classes (the dita-ot-html5 profile's markers).
|
|
15
|
+
*/
|
|
16
|
+
import type { CheerioAPI } from "cheerio";
|
|
17
|
+
/** What a page says about the tool that made it. */
|
|
18
|
+
export interface PageFacts {
|
|
19
|
+
/** Every `<meta name="generator">` content, in order (Starlight writes Astro's and its own). */
|
|
20
|
+
generators: string[];
|
|
21
|
+
/** The page's Markdown version, from `<link rel="alternate" type="text/markdown">`. */
|
|
22
|
+
markdown?: string;
|
|
23
|
+
/** Sphinx's markers: "Created using Sphinx" in the footer, or its `_static/documentation_options.js`. */
|
|
24
|
+
sphinx?: boolean;
|
|
25
|
+
/** DITA-OT's HTML5 markers, for builds without its generator tag: `h1.topictitle1`, a `div.body` of a topic type. */
|
|
26
|
+
dita?: boolean;
|
|
27
|
+
}
|
|
28
|
+
export type ToolId = "gitbook" | "docusaurus" | "vitepress" | "starlight" | "mkdocs" | "hugo" | "mintlify" | "jekyll" | "sphinx" | "astro" | "dita-ot";
|
|
29
|
+
export interface Tool {
|
|
30
|
+
id: ToolId;
|
|
31
|
+
/** The tool's name as people know it ("MkDocs Material"). */
|
|
32
|
+
label: string;
|
|
33
|
+
version?: string;
|
|
34
|
+
}
|
|
35
|
+
/** The tool that made a page, or undefined when it does not say. */
|
|
36
|
+
export declare function identifyTool(facts: PageFacts): Tool | undefined;
|
|
37
|
+
/** The facts, from a page parsed with cheerio. */
|
|
38
|
+
export declare function pageFacts($: CheerioAPI, url?: string): PageFacts;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Generator tags, most specific first: Starlight before the Astro tag it sits beside. */
|
|
2
|
+
const GENERATORS = [
|
|
3
|
+
{ id: "gitbook", label: "GitBook", pattern: /^GitBook\b/i },
|
|
4
|
+
{ id: "docusaurus", label: "Docusaurus", pattern: /^Docusaurus\b/i },
|
|
5
|
+
{ id: "vitepress", label: "VitePress", pattern: /^VitePress\b/i },
|
|
6
|
+
{ id: "starlight", label: "Starlight", pattern: /^Starlight\b/i },
|
|
7
|
+
{ id: "mintlify", label: "Mintlify", pattern: /^Mintlify\b/i },
|
|
8
|
+
{ id: "mkdocs", label: "MkDocs", pattern: /^mkdocs\b/i },
|
|
9
|
+
{ id: "hugo", label: "Hugo", pattern: /^Hugo\b/i },
|
|
10
|
+
{ id: "jekyll", label: "Jekyll", pattern: /^Jekyll\b/i },
|
|
11
|
+
{ id: "astro", label: "Astro", pattern: /^Astro\b/i },
|
|
12
|
+
{ id: "dita-ot", label: "DITA-OT", pattern: /^DITA-OT\b/i },
|
|
13
|
+
];
|
|
14
|
+
/** The tool that made a page, or undefined when it does not say. */
|
|
15
|
+
export function identifyTool(facts) {
|
|
16
|
+
const generators = facts.generators.map((g) => g.trim()).filter(Boolean);
|
|
17
|
+
for (const g of GENERATORS) {
|
|
18
|
+
const tag = generators.find((t) => g.pattern.test(t));
|
|
19
|
+
if (!tag)
|
|
20
|
+
continue;
|
|
21
|
+
// MkDocs writes "mkdocs-1.6.1, mkdocs-material-9.8.1": the theme is what people name
|
|
22
|
+
if (g.id === "mkdocs") {
|
|
23
|
+
const material = /mkdocs-material-([\w.-]+)/i.exec(tag);
|
|
24
|
+
return material ? { id: "mkdocs", label: "MkDocs Material", version: material[1] } : { id: "mkdocs", label: "MkDocs", version: /mkdocs-([\d][\w.-]*)/i.exec(tag)?.[1] };
|
|
25
|
+
}
|
|
26
|
+
return { id: g.id, label: g.label, version: versionIn(tag.replace(g.pattern, "")) };
|
|
27
|
+
}
|
|
28
|
+
if (facts.sphinx)
|
|
29
|
+
return { id: "sphinx", label: "Sphinx" };
|
|
30
|
+
if (facts.dita)
|
|
31
|
+
return { id: "dita-ot", label: "DITA-OT" };
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
/** "v4.0.0", " (7ad3fff)", " 0.170.1" → the version; nothing that is not one. */
|
|
35
|
+
function versionIn(rest) {
|
|
36
|
+
return /^\s*\(?v?([\da-f][\w.-]*)\)?\s*$/i.exec(rest)?.[1];
|
|
37
|
+
}
|
|
38
|
+
/** DITA-OT HTML5's own markers (the dita-ot-html5 profile detects by the same). */
|
|
39
|
+
const DITA_MARKERS = "h1.topictitle1, div.body.conbody, div.body.taskbody, div.body.refbody, div.body.glossbody, div.body.troublebody";
|
|
40
|
+
/** The facts, from a page parsed with cheerio. */
|
|
41
|
+
export function pageFacts($, url) {
|
|
42
|
+
const generators = $('meta[name="generator" i]').map((_, e) => $(e).attr("content") ?? "").get().filter(Boolean);
|
|
43
|
+
const href = $('link[rel~="alternate" i][type="text/markdown" i]').first().attr("href");
|
|
44
|
+
let markdown;
|
|
45
|
+
if (href) {
|
|
46
|
+
try {
|
|
47
|
+
markdown = url ? new URL(href, url).href : href;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
markdown = undefined;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const sphinx = $('script[src*="_static/documentation_options.js"]').length > 0 ||
|
|
54
|
+
$("footer, div.footer").toArray().some((e) => /Created using\s+Sphinx/i.test($(e).text()));
|
|
55
|
+
const dita = $(DITA_MARKERS).length > 0;
|
|
56
|
+
return { generators, ...(markdown ? { markdown } : {}), ...(sphinx ? { sphinx } : {}), ...(dita ? { dita } : {}) };
|
|
57
|
+
}
|