@arabold/docs-mcp-server 2.4.2 → 2.4.3

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.
Files changed (34) hide show
  1. package/db/migrations/002-normalize-library-table.sql +5 -0
  2. package/db/migrations/003-normalize-vector-table.sql +5 -0
  3. package/db/migrations/004-complete-normalization.sql +7 -0
  4. package/db/migrations/007-dedupe-unversioned-versions.sql +5 -0
  5. package/db/migrations/009-add-pages-table.sql +10 -0
  6. package/db/migrations/014-rebuild-vector-partition-keys.sql +56 -0
  7. package/dist/HtmlDefuddleMiddleware-Cm0vQDqD.js +148 -0
  8. package/dist/HtmlDefuddleMiddleware-Cm0vQDqD.js.map +1 -0
  9. package/dist/assets/main.css +3 -1
  10. package/dist/assets/main.js +7845 -8777
  11. package/dist/assets/main.js.map +1 -1
  12. package/dist/env-DONvEfR5.js +30 -0
  13. package/dist/env-DONvEfR5.js.map +1 -0
  14. package/dist/index.js +10 -8
  15. package/dist/index.js.map +1 -1
  16. package/dist/logger-BBxstTD7.js +82 -0
  17. package/dist/logger-BBxstTD7.js.map +1 -0
  18. package/dist/main-BktKic6L.js +18646 -0
  19. package/dist/main-BktKic6L.js.map +1 -0
  20. package/dist/utils-B-zX5sgp.js +1113 -0
  21. package/dist/utils-B-zX5sgp.js.map +1 -0
  22. package/dist/utils-LjYa0nIu.js +2 -0
  23. package/package.json +61 -61
  24. package/public/assets/main.css +3 -1
  25. package/public/assets/main.js +7845 -8777
  26. package/public/assets/main.js.map +1 -1
  27. package/dist/HtmlDefuddleMiddleware-DjhdN_D2.js +0 -152
  28. package/dist/HtmlDefuddleMiddleware-DjhdN_D2.js.map +0 -1
  29. package/dist/logger-CLtABTNb.js +0 -99
  30. package/dist/logger-CLtABTNb.js.map +0 -1
  31. package/dist/main-WZKPkgC6.js +0 -20454
  32. package/dist/main-WZKPkgC6.js.map +0 -1
  33. package/dist/utils-CJgh41os.js +0 -1152
  34. package/dist/utils-CJgh41os.js.map +0 -1
@@ -1,5 +1,6 @@
1
1
  -- Migration: Normalize schema by introducing libraries and versions tables
2
2
 
3
+ -- @migration-step create normalized tables
3
4
  -- 1. Create libraries table
4
5
  CREATE TABLE IF NOT EXISTS libraries (
5
6
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -16,10 +17,12 @@ CREATE TABLE IF NOT EXISTS versions (
16
17
  UNIQUE(library_id, name) -- Allows one NULL version per library
17
18
  );
18
19
 
20
+ -- @migration-step add document foreign keys
19
21
  -- 3. Add foreign key columns to documents
20
22
  ALTER TABLE documents ADD COLUMN library_id INTEGER REFERENCES libraries(id);
21
23
  ALTER TABLE documents ADD COLUMN version_id INTEGER REFERENCES versions(id);
22
24
 
25
+ -- @migration-step populate libraries and versions
23
26
  -- 4. Populate libraries table from existing documents
24
27
  INSERT OR IGNORE INTO libraries (name)
25
28
  SELECT DISTINCT library FROM documents;
@@ -32,6 +35,7 @@ SELECT DISTINCT
32
35
  FROM documents d
33
36
  JOIN libraries l ON l.name = d.library;
34
37
 
38
+ -- @migration-step backfill document references
35
39
  -- 6. Update documents with foreign key references
36
40
  UPDATE documents
37
41
  SET library_id = (SELECT id FROM libraries WHERE libraries.name = documents.library),
@@ -42,6 +46,7 @@ SET library_id = (SELECT id FROM libraries WHERE libraries.name = documents.libr
42
46
  AND COALESCE(v.name, '') = COALESCE(documents.version, '')
43
47
  );
44
48
 
49
+ -- @migration-step create normalization indexes
45
50
  -- 7. Add indexes for performance
46
51
  CREATE INDEX IF NOT EXISTS idx_documents_library_id ON documents(library_id);
47
52
  CREATE INDEX IF NOT EXISTS idx_documents_version_id ON documents(version_id);
@@ -1,9 +1,11 @@
1
1
  -- Migration: Normalize documents_vec table to use library_id and version_id
2
2
  -- Optimized for large datasets (1GB+)
3
3
 
4
+ -- @migration-step prepare vector join index
4
5
  -- 1. Ensure optimal indexes for the migration JOIN
5
6
  CREATE INDEX IF NOT EXISTS idx_documents_id_lib_ver ON documents(id, library_id, version_id);
6
7
 
8
+ -- @migration-step preserve vectors with normalized keys
7
9
  -- 2. Create temporary table to store vector data with foreign key IDs
8
10
  CREATE TEMPORARY TABLE temp_vector_migration AS
9
11
  SELECT
@@ -14,6 +16,7 @@ SELECT
14
16
  FROM documents_vec dv
15
17
  JOIN documents d ON dv.rowid = d.id;
16
18
 
19
+ -- @migration-step rebuild vector table
17
20
  -- 3. Drop the old virtual table
18
21
  DROP TABLE documents_vec;
19
22
 
@@ -24,10 +27,12 @@ CREATE VIRTUAL TABLE documents_vec USING vec0(
24
27
  embedding FLOAT[1536]
25
28
  );
26
29
 
30
+ -- @migration-step restore normalized vectors
27
31
  -- 5. Restore vector data using foreign key IDs
28
32
  INSERT INTO documents_vec (rowid, library_id, version_id, embedding)
29
33
  SELECT rowid, library_id, version_id, embedding
30
34
  FROM temp_vector_migration;
31
35
 
36
+ -- @migration-step cleanup vector staging data
32
37
  -- 6. Clean up temporary table
33
38
  DROP TABLE temp_vector_migration;
@@ -2,6 +2,7 @@
2
2
  -- This migration finalizes the schema normalization process
3
3
  -- Note: Must recreate table because obsolete columns are part of UNIQUE constraint
4
4
 
5
+ -- @migration-step create normalized documents table
5
6
  -- 1. Create new documents table with only foreign key references
6
7
  CREATE TABLE documents_new (
7
8
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -15,22 +16,26 @@ CREATE TABLE documents_new (
15
16
  UNIQUE(url, library_id, version_id, sort_order)
16
17
  );
17
18
 
19
+ -- @migration-step copy normalized documents
18
20
  -- 2. Copy data from old table (excluding obsolete library and version columns)
19
21
  INSERT INTO documents_new (id, library_id, version_id, url, content, metadata, sort_order, indexed_at)
20
22
  SELECT id, library_id, version_id, url, content, metadata, sort_order, indexed_at
21
23
  FROM documents;
22
24
 
25
+ -- @migration-step replace documents table
23
26
  -- 3. Drop the old documents table
24
27
  DROP TABLE documents;
25
28
 
26
29
  -- 4. Rename the new table to documents
27
30
  ALTER TABLE documents_new RENAME TO documents;
28
31
 
32
+ -- @migration-step recreate document indexes
29
33
  -- 5. Recreate indexes that were lost when dropping the table
30
34
  CREATE INDEX IF NOT EXISTS idx_documents_library_id ON documents(library_id);
31
35
  CREATE INDEX IF NOT EXISTS idx_documents_version_id ON documents(version_id);
32
36
  CREATE INDEX IF NOT EXISTS idx_documents_lib_ver_id ON documents(library_id, version_id);
33
37
 
38
+ -- @migration-step recreate fts schema
34
39
  -- 6. Recreate FTS5 virtual table (gets dropped when main table is dropped)
35
40
  -- Using external content approach - FTS index is maintained entirely through triggers
36
41
  CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
@@ -41,6 +46,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
41
46
  tokenize='porter unicode61'
42
47
  );
43
48
 
49
+ -- @migration-step recreate fts triggers
44
50
  -- 7. Recreate FTS triggers to maintain the index
45
51
  -- Note: Triggers work directly with documents table, no JOIN needed for FTS content
46
52
  CREATE TRIGGER IF NOT EXISTS documents_fts_after_delete AFTER DELETE ON documents BEGIN
@@ -60,6 +66,7 @@ CREATE TRIGGER IF NOT EXISTS documents_fts_after_insert AFTER INSERT ON document
60
66
  VALUES(new.id, new.content, json_extract(new.metadata, '$.title'), new.url, json_extract(new.metadata, '$.path'));
61
67
  END;
62
68
 
69
+ -- @migration-step rebuild fts index
63
70
  -- 8. Rebuild FTS index from existing documents data
64
71
  -- Manually populate the FTS index since we're using external content approach
65
72
  INSERT INTO documents_fts(rowid, content, title, url, path)
@@ -14,6 +14,7 @@
14
14
  -- across multiple subsequent statements. All TEMP objects are connection-scoped
15
15
  -- and vanish automatically; safe for repeated runs (we DROP IF EXISTS first).
16
16
 
17
+ -- @migration-step collect null-name versions
17
18
  DROP TABLE IF EXISTS temp_null_versions;
18
19
  CREATE TEMP TABLE temp_null_versions AS
19
20
  SELECT v.id, v.library_id,
@@ -21,6 +22,7 @@ SELECT v.id, v.library_id,
21
22
  FROM versions v
22
23
  WHERE v.name IS NULL;
23
24
 
25
+ -- @migration-step choose canonical versions
24
26
  -- Build canonical mapping per library (one row per library_id)
25
27
  DROP TABLE IF EXISTS temp_canonical_versions;
26
28
  CREATE TEMP TABLE temp_canonical_versions AS
@@ -40,6 +42,7 @@ SELECT nv.library_id,
40
42
  FROM temp_null_versions nv
41
43
  GROUP BY nv.library_id;
42
44
 
45
+ -- @migration-step repoint documents to canonical versions
43
46
  -- Repoint documents from non-canonical NULL-name versions
44
47
  UPDATE documents
45
48
  SET version_id = (
@@ -49,12 +52,14 @@ SET version_id = (
49
52
  WHERE version_id IN (SELECT id FROM versions WHERE name IS NULL)
50
53
  AND version_id NOT IN (SELECT keep_id FROM temp_canonical_versions);
51
54
 
55
+ -- @migration-step remove surplus versions
52
56
  -- 3: Delete surplus NULL-name rows now unreferenced
53
57
  DELETE FROM versions
54
58
  WHERE name IS NULL
55
59
  AND id NOT IN (SELECT keep_id FROM temp_canonical_versions)
56
60
  AND (SELECT COUNT(*) FROM documents d WHERE d.version_id = versions.id) = 0;
57
61
 
62
+ -- @migration-step normalize remaining version names
58
63
  -- 4: Normalize remaining NULL names to ''
59
64
  UPDATE versions SET name = '' WHERE name IS NULL;
60
65
 
@@ -2,6 +2,7 @@
2
2
  -- This migration introduces a pages table to store page-level metadata once per URL
3
3
  -- and links document chunks to their parent pages via page_id foreign key
4
4
 
5
+ -- @migration-step create pages table
5
6
  -- 1. Create pages table to store unique page-level metadata
6
7
  CREATE TABLE IF NOT EXISTS pages (
7
8
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -16,11 +17,13 @@ CREATE TABLE IF NOT EXISTS pages (
16
17
  UNIQUE(version_id, url)
17
18
  );
18
19
 
20
+ -- @migration-step create page indexes
19
21
  -- 2. Add indexes for efficient querying
20
22
  CREATE INDEX IF NOT EXISTS idx_pages_version_id ON pages(version_id);
21
23
  CREATE INDEX IF NOT EXISTS idx_pages_url ON pages(url);
22
24
  CREATE INDEX IF NOT EXISTS idx_pages_etag ON pages(etag);
23
25
 
26
+ -- @migration-step create page-based documents table
24
27
  -- 3. Create new documents table with page_id foreign key
25
28
  CREATE TABLE documents_new (
26
29
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -32,10 +35,12 @@ CREATE TABLE documents_new (
32
35
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
33
36
  );
34
37
 
38
+ -- @migration-step create new document indexes
35
39
  -- 4. Create indexes for the new documents table
36
40
  CREATE INDEX IF NOT EXISTS idx_documents_page_id ON documents_new(page_id);
37
41
  CREATE INDEX IF NOT EXISTS idx_documents_sort_order ON documents_new(page_id, sort_order);
38
42
 
43
+ -- @migration-step populate pages
39
44
  -- 5. Migrate data from old documents table to new structure
40
45
  -- First, populate pages table with unique page data from existing documents
41
46
  -- Group by version_id and url to ensure uniqueness, using MAX() to handle any duplicates
@@ -49,6 +54,7 @@ SELECT
49
54
  FROM documents
50
55
  GROUP BY version_id, url;
51
56
 
57
+ -- @migration-step migrate document chunks
52
58
  -- 6. Migrate document chunks to new table structure
53
59
  -- Preserve all existing metadata except page-level fields (url, title, library, version)
54
60
  -- that are now stored in pages and versions tables
@@ -72,12 +78,14 @@ SELECT
72
78
  FROM documents d
73
79
  JOIN pages p ON d.version_id = p.version_id AND d.url = p.url;
74
80
 
81
+ -- @migration-step replace documents table
75
82
  -- 7. Drop the old documents table
76
83
  DROP TABLE documents;
77
84
 
78
85
  -- 8. Rename the new table to documents
79
86
  ALTER TABLE documents_new RENAME TO documents;
80
87
 
88
+ -- @migration-step replace fts schema
81
89
  -- 9. Recreate FTS5 virtual table to work with new structure
82
90
  -- Drop existing FTS table and triggers
83
91
  DROP TRIGGER IF EXISTS documents_fts_after_delete;
@@ -94,6 +102,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
94
102
  tokenize='porter unicode61'
95
103
  );
96
104
 
105
+ -- @migration-step recreate fts and page triggers
97
106
  -- 10. Create new FTS triggers that join with pages table
98
107
  CREATE TRIGGER IF NOT EXISTS documents_fts_after_delete AFTER DELETE ON documents BEGIN
99
108
  DELETE FROM documents_fts WHERE rowid = old.id;
@@ -117,6 +126,7 @@ CREATE TRIGGER IF NOT EXISTS pages_updated_at_trigger AFTER UPDATE ON pages BEGI
117
126
  UPDATE pages SET updated_at = CURRENT_TIMESTAMP WHERE id = new.id;
118
127
  END;
119
128
 
129
+ -- @migration-step rebuild fts index
120
130
  -- 12. Rebuild FTS index from migrated data
121
131
  INSERT INTO documents_fts(rowid, content, title, url, path)
122
132
  SELECT d.id, d.content, p.title, p.url, json_extract(d.metadata, '$.path')
@@ -0,0 +1,56 @@
1
+ -- Migration: rebuild documents_vec with sqlite-vec partition keys
2
+ -- This enables selective KNN queries by library_id and version_id.
3
+
4
+ -- @migration-step preserve existing vectors
5
+ -- Preserve compatible vectors from the existing vec table. The migration
6
+ -- runner replaces __DOCUMENTS_VEC_DIMENSION__ with the current documents_vec
7
+ -- dimension so databases already reconciled to a custom embedding dimension
8
+ -- keep their existing vector size. This uses a disk-backed staging table
9
+ -- because large vector indexes can exceed memory.
10
+ DROP TABLE IF EXISTS _documents_vec_partition_migration;
11
+
12
+ CREATE TABLE _documents_vec_partition_migration AS
13
+ SELECT
14
+ d.id AS rowid,
15
+ v.library_id,
16
+ v.id AS version_id,
17
+ dv.embedding
18
+ FROM documents_vec dv
19
+ JOIN documents d ON dv.rowid = d.id
20
+ JOIN pages p ON d.page_id = p.id
21
+ JOIN versions v ON p.version_id = v.id
22
+ WHERE vec_length(dv.embedding) = __DOCUMENTS_VEC_DIMENSION__;
23
+
24
+ -- @migration-step rebuild vector table
25
+ DROP TABLE documents_vec;
26
+
27
+ CREATE VIRTUAL TABLE documents_vec USING vec0(
28
+ library_id INTEGER partition key,
29
+ version_id INTEGER partition key,
30
+ embedding FLOAT[__DOCUMENTS_VEC_DIMENSION__]
31
+ );
32
+
33
+ -- @migration-step restore existing vectors
34
+ INSERT OR REPLACE INTO documents_vec (rowid, library_id, version_id, embedding)
35
+ SELECT rowid, library_id, version_id, embedding
36
+ FROM _documents_vec_partition_migration;
37
+
38
+ -- @migration-step backfill missing vectors
39
+ -- Backfill any vectors stored on documents but missing from the vec table.
40
+ INSERT OR REPLACE INTO documents_vec (rowid, library_id, version_id, embedding)
41
+ SELECT
42
+ d.id,
43
+ v.library_id,
44
+ v.id AS version_id,
45
+ json_extract(d.embedding, '$') AS embedding
46
+ FROM documents d
47
+ JOIN pages p ON d.page_id = p.id
48
+ JOIN versions v ON p.version_id = v.id
49
+ WHERE d.embedding IS NOT NULL
50
+ AND vec_length(json_extract(d.embedding, '$')) = __DOCUMENTS_VEC_DIMENSION__
51
+ AND NOT EXISTS (
52
+ SELECT 1 FROM documents_vec existing WHERE existing.rowid = d.id
53
+ );
54
+
55
+ -- @migration-step cleanup staging data
56
+ DROP TABLE _documents_vec_partition_migration;
@@ -0,0 +1,148 @@
1
+ import { r as logger } from "./logger-BBxstTD7.js";
2
+ import * as cheerio from "cheerio";
3
+ import { Defuddle } from "defuddle/node";
4
+ import { parseHTML } from "linkedom";
5
+ //#region src/scraper/middleware/HtmlDefuddleMiddleware.ts
6
+ var DEFAULT_MIN_RETENTION = .01;
7
+ /**
8
+ * Middleware that runs Defuddle as a drop-in replacement for
9
+ * {@link HtmlSanitizerMiddleware}. It extracts the main article content,
10
+ * removing navigation, footers, ads, and other boilerplate using Defuddle's
11
+ * heuristics rather than a hand-maintained selector list.
12
+ *
13
+ * Pipeline contract:
14
+ * - Reads HTML from `context.dom` (populated by HtmlCheerioParserMiddleware).
15
+ * - Runs Defuddle via linkedom and replaces `context.dom` with a fresh Cheerio
16
+ * DOM containing only the cleaned content (wrapped in `<html><body>…`).
17
+ * - Honours `context.options.excludeSelectors` by stripping them from the
18
+ * *source* DOM before Defuddle runs. Defuddle's standardise step unwraps
19
+ * class/id hooks, so post-extraction selector matching is unreliable;
20
+ * filtering on the source DOM matches the Cheerio sanitiser's behaviour
21
+ * and the user's mental model.
22
+ * - Updates `context.title` if Defuddle found a non-empty title and the
23
+ * previous extractor left it empty.
24
+ * - Falls back to the original DOM if Defuddle returns empty output or removes
25
+ * substantially all text (see {@link minTextRetentionRatio}).
26
+ */
27
+ var HtmlDefuddleMiddleware = class {
28
+ minTextRetentionRatio;
29
+ constructor(options = {}) {
30
+ this.minTextRetentionRatio = options.minTextRetentionRatio ?? DEFAULT_MIN_RETENTION;
31
+ }
32
+ async process(context, next) {
33
+ const $ = context.dom;
34
+ if (!$) {
35
+ logger.warn(`⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware runs before this.`);
36
+ await next();
37
+ return;
38
+ }
39
+ try {
40
+ const originalHtml = $.html();
41
+ const $bodyClone = cheerio.load(`<body>${$("body").html() ?? ""}</body>`);
42
+ $bodyClone("script, style, noscript, template").remove();
43
+ const textLengthBefore = $bodyClone("body").text().trim().length;
44
+ const { document } = parseHTML(originalHtml);
45
+ this.applyExcludePreDefuddle(document, context);
46
+ this.propagateLanguageHints(document);
47
+ const result = await Defuddle(document, context.source, { markdown: false });
48
+ const cleanedContent = typeof result?.content === "string" ? result.content : "";
49
+ const wrappedHtml = `<!doctype html><html><head><title>${escapeHtml(result.title || context.title || "")}</title></head><body>${cleanedContent}</body></html>`;
50
+ const cleaned$ = cheerio.load(wrappedHtml);
51
+ cleaned$("script, style, noscript, iframe, svg, link, meta").remove();
52
+ const cleanedText = cleaned$("body").text().trim();
53
+ const ratio = textLengthBefore > 0 ? cleanedText.length / textLengthBefore : 0;
54
+ if (!cleanedText || ratio < this.minTextRetentionRatio) {
55
+ logger.warn(`⚠️ Defuddle retained ${cleanedText.length}/${textLengthBefore} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}; falling back to original DOM with minimal sanitisation.`);
56
+ $("script, style, noscript, iframe, svg, link, meta").remove();
57
+ await next();
58
+ return;
59
+ }
60
+ context.dom = cleaned$;
61
+ if (!context.title && result.title) context.title = result.title;
62
+ logger.debug(`Defuddle reduced body text from ${textLengthBefore} to ${cleanedText.length} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}`);
63
+ } catch (error) {
64
+ logger.error(`❌ Defuddle extraction failed for ${context.source}: ${error}`);
65
+ context.errors.push(error instanceof Error ? error : /* @__PURE__ */ new Error(`Defuddle extraction failed: ${String(error)}`));
66
+ }
67
+ await next();
68
+ }
69
+ /**
70
+ * Normalise each `<pre>` so Defuddle preserves its language hint.
71
+ *
72
+ * Defuddle's standardise step strips `class="language-X"` unless `X` is one
73
+ * of its allow-listed canonical language names (so `language-python3`,
74
+ * `language-py`, etc. get dropped). It also unwraps highlighter ancestors
75
+ * like `<div class="highlight-python3">`, losing that context entirely.
76
+ *
77
+ * However, Defuddle preserves `data-language` (and `data-lang`) verbatim and
78
+ * promotes them to `class="language-X"` on the inner `<code>`. So this
79
+ * pre-pass collects the language hint from `<pre>`, `<code>`, or nearby
80
+ * ancestor classes and writes it back as `data-language` on `<pre>`. Our
81
+ * Turndown rule in HtmlToMarkdownMiddleware then reads it off and emits a
82
+ * fenced code block with the correct language.
83
+ */
84
+ propagateLanguageHints(document) {
85
+ const pres = document.querySelectorAll("pre");
86
+ for (const pre of Array.from(pres)) {
87
+ const existingCode = pre.querySelector("code");
88
+ if (pre.getAttribute("data-language")) continue;
89
+ let lang = detectLanguageFromClass(pre.getAttribute("class")) || detectLanguageFromClass(existingCode?.getAttribute("class") ?? null);
90
+ if (!lang) {
91
+ let ancestor = pre.parentElement;
92
+ let depth = 0;
93
+ while (ancestor && depth < 5) {
94
+ const found = detectLanguageFromClass(ancestor.getAttribute("class"));
95
+ if (found) {
96
+ lang = found;
97
+ break;
98
+ }
99
+ ancestor = ancestor.parentElement;
100
+ depth++;
101
+ }
102
+ }
103
+ if (!lang) continue;
104
+ pre.setAttribute("data-language", lang);
105
+ let wrapper = pre.parentElement;
106
+ let depth = 0;
107
+ while (wrapper && depth < 5) {
108
+ const cls = wrapper.getAttribute("class") ?? "";
109
+ if (/(?:^|\s)(?:highlight|highlight-source-[A-Za-z0-9_+-]+|highlight-[A-Za-z0-9_+-]+)(?:\s|$)/.test(cls) && wrapper.children.length === 1 && wrapper.parentElement) {
110
+ wrapper.parentElement.replaceChild(pre, wrapper);
111
+ wrapper = pre.parentElement;
112
+ } else break;
113
+ depth++;
114
+ }
115
+ }
116
+ }
117
+ applyExcludePreDefuddle(document, context) {
118
+ const selectors = context.options.excludeSelectors ?? [];
119
+ if (selectors.length === 0) return;
120
+ for (const selector of selectors) try {
121
+ const matches = document.querySelectorAll(selector);
122
+ for (const node of Array.from(matches)) {
123
+ const tag = node.tagName?.toLowerCase();
124
+ if (tag === "html" || tag === "body") continue;
125
+ node.remove();
126
+ }
127
+ } catch (selectorError) {
128
+ logger.warn(`⚠️ Invalid excludeSelector "${selector}" before Defuddle: ${selectorError}`);
129
+ context.errors.push(/* @__PURE__ */ new Error(`Invalid selector "${selector}": ${selectorError}`));
130
+ }
131
+ }
132
+ };
133
+ var LANGUAGE_CLASS_RE = /(?:^|\s)(?:highlight-source-|highlight-|language-)([A-Za-z0-9_+-]+)/;
134
+ function detectLanguageFromClass(className) {
135
+ if (!className) return "";
136
+ const match = LANGUAGE_CLASS_RE.exec(className);
137
+ if (!match) return "";
138
+ const lang = match[1].toLowerCase();
139
+ if (lang === "text" || lang === "highlighted" || lang === "wrap") return "";
140
+ return lang;
141
+ }
142
+ function escapeHtml(value) {
143
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
144
+ }
145
+ //#endregion
146
+ export { HtmlDefuddleMiddleware };
147
+
148
+ //# sourceMappingURL=HtmlDefuddleMiddleware-Cm0vQDqD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HtmlDefuddleMiddleware-Cm0vQDqD.js","names":[],"sources":["../src/scraper/middleware/HtmlDefuddleMiddleware.ts"],"sourcesContent":["import * as cheerio from \"cheerio\";\nimport { Defuddle } from \"defuddle/node\";\nimport { parseHTML } from \"linkedom\";\nimport { logger } from \"../../utils/logger\";\nimport type { ContentProcessorMiddleware, MiddlewareContext } from \"./types\";\n\n/**\n * Options for HtmlDefuddleMiddleware.\n */\nexport interface HtmlDefuddleOptions {\n /**\n * If Defuddle's extracted content drops below this fraction of the original\n * *visible* text length (script/style/noscript excluded), fall back to the\n * pre-extraction DOM. Set very low by default — Defuddle is intentionally\n * aggressive, and the more useful safety net is the empty-output check\n * below. The ratio is here mainly to catch catastrophic mis-extraction\n * (Defuddle latches onto a tiny element on a content-rich page).\n */\n minTextRetentionRatio?: number;\n}\n\nconst DEFAULT_MIN_RETENTION = 0.01;\n\n/**\n * Middleware that runs Defuddle as a drop-in replacement for\n * {@link HtmlSanitizerMiddleware}. It extracts the main article content,\n * removing navigation, footers, ads, and other boilerplate using Defuddle's\n * heuristics rather than a hand-maintained selector list.\n *\n * Pipeline contract:\n * - Reads HTML from `context.dom` (populated by HtmlCheerioParserMiddleware).\n * - Runs Defuddle via linkedom and replaces `context.dom` with a fresh Cheerio\n * DOM containing only the cleaned content (wrapped in `<html><body>…`).\n * - Honours `context.options.excludeSelectors` by stripping them from the\n * *source* DOM before Defuddle runs. Defuddle's standardise step unwraps\n * class/id hooks, so post-extraction selector matching is unreliable;\n * filtering on the source DOM matches the Cheerio sanitiser's behaviour\n * and the user's mental model.\n * - Updates `context.title` if Defuddle found a non-empty title and the\n * previous extractor left it empty.\n * - Falls back to the original DOM if Defuddle returns empty output or removes\n * substantially all text (see {@link minTextRetentionRatio}).\n */\nexport class HtmlDefuddleMiddleware implements ContentProcessorMiddleware {\n private readonly minTextRetentionRatio: number;\n\n constructor(options: HtmlDefuddleOptions = {}) {\n this.minTextRetentionRatio = options.minTextRetentionRatio ?? DEFAULT_MIN_RETENTION;\n }\n\n async process(context: MiddlewareContext, next: () => Promise<void>): Promise<void> {\n const $ = context.dom;\n if (!$) {\n logger.warn(\n `⏭️ Skipping ${this.constructor.name}: context.dom is missing. Ensure HtmlCheerioParserMiddleware runs before this.`,\n );\n await next();\n return;\n }\n\n try {\n const originalHtml = $.html();\n // Measure *visible* text, excluding script/style content. SPA pages\n // (Next.js, Nuxt, etc.) embed huge hydration payloads inside <script>\n // tags whose textContent inflates the body text length by orders of\n // magnitude, which would otherwise trip the retention-ratio fallback.\n const $bodyClone = cheerio.load(`<body>${$(\"body\").html() ?? \"\"}</body>`);\n $bodyClone(\"script, style, noscript, template\").remove();\n const textLengthBefore = $bodyClone(\"body\").text().trim().length;\n\n const { document } = parseHTML(originalHtml);\n\n // Apply user-supplied excludeSelectors *before* Defuddle. Defuddle\n // standardises markup (e.g. unwrapping divs into <p>), which strips the\n // class/id hooks the user supplied — so post-extraction removal often\n // misses. Filtering on the source DOM matches the user's mental model\n // (same as the Cheerio sanitiser path).\n this.applyExcludePreDefuddle(document, context);\n\n // Defuddle's `standardize` step unwraps the language-bearing ancestor\n // divs that highlighters like Pygments/Sphinx and GitHub use (e.g.\n // `<div class=\"highlight-python3\"><pre>...</pre></div>`). Push the\n // detected language onto the inner `<code>` as `class=\"language-X\"` so\n // Defuddle preserves it and our Turndown rule can recover the fenced\n // code-block language.\n this.propagateLanguageHints(document);\n\n const result = await Defuddle(document, context.source, {\n // We do markdown conversion downstream (HtmlToMarkdownMiddleware), so\n // ask Defuddle for cleaned HTML, not markdown.\n markdown: false,\n });\n\n const cleanedContent = typeof result?.content === \"string\" ? result.content : \"\";\n\n // Build the cleaned Cheerio DOM *first*, then measure retention on the\n // post-sanitisation text. Doing the regex-strip-then-measure dance in\n // the other order let `<script>` *contents* (e.g. Next.js `__next_f`\n // hydration payloads) inflate the \"kept\" character count so the ratio\n // check passed, after which removing the script tags emptied the page.\n //\n // Note on H1 handling: Defuddle's standardize step deliberately drops\n // the first H1/H2 when it matches the extracted title (and converts\n // remaining H1s to H2s). The dropped headline text is preserved on\n // `context.title`, which the indexer attaches to every chunk as\n // metadata — so it's still searchable, just not duplicated inside the\n // chunk body. Defuddle exposes no granular flag to opt out of this\n // single behaviour (only the coarse `standardize: false` which would\n // also disable code-block / footnote standardisation).\n const wrappedHtml = `<!doctype html><html><head><title>${escapeHtml(result.title || context.title || \"\")}</title></head><body>${cleanedContent}</body></html>`;\n const cleaned$ = cheerio.load(wrappedHtml);\n\n // Strip dangerous / non-content tags. Defuddle can leak these (Next.js\n // hydration payloads being the worst offender) and they're never useful\n // in indexed markdown.\n cleaned$(\"script, style, noscript, iframe, svg, link, meta\").remove();\n\n // Measure retention on the post-strip text so the ratio reflects what\n // actually survives into the chunked output.\n const cleanedText = cleaned$(\"body\").text().trim();\n const ratio = textLengthBefore > 0 ? cleanedText.length / textLengthBefore : 0;\n\n if (!cleanedText || ratio < this.minTextRetentionRatio) {\n logger.warn(\n `⚠️ Defuddle retained ${cleanedText.length}/${textLengthBefore} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}; falling back to original DOM with minimal sanitisation.`,\n );\n // Strip script/style/iframe defensively even on fallback — without\n // these the markdown converter renders hydration payloads (e.g.\n // Next.js __next_f) as multi-hundred-KB blobs.\n $(\"script, style, noscript, iframe, svg, link, meta\").remove();\n await next();\n return;\n }\n\n context.dom = cleaned$;\n if (!context.title && result.title) {\n context.title = result.title;\n }\n\n logger.debug(\n `Defuddle reduced body text from ${textLengthBefore} to ${cleanedText.length} chars (${(ratio * 100).toFixed(1)}%) for ${context.source}`,\n );\n } catch (error) {\n logger.error(`❌ Defuddle extraction failed for ${context.source}: ${error}`);\n context.errors.push(\n error instanceof Error\n ? error\n : new Error(`Defuddle extraction failed: ${String(error)}`),\n );\n }\n\n await next();\n }\n\n /**\n * Normalise each `<pre>` so Defuddle preserves its language hint.\n *\n * Defuddle's standardise step strips `class=\"language-X\"` unless `X` is one\n * of its allow-listed canonical language names (so `language-python3`,\n * `language-py`, etc. get dropped). It also unwraps highlighter ancestors\n * like `<div class=\"highlight-python3\">`, losing that context entirely.\n *\n * However, Defuddle preserves `data-language` (and `data-lang`) verbatim and\n * promotes them to `class=\"language-X\"` on the inner `<code>`. So this\n * pre-pass collects the language hint from `<pre>`, `<code>`, or nearby\n * ancestor classes and writes it back as `data-language` on `<pre>`. Our\n * Turndown rule in HtmlToMarkdownMiddleware then reads it off and emits a\n * fenced code block with the correct language.\n */\n private propagateLanguageHints(document: Document): void {\n const pres = document.querySelectorAll(\"pre\");\n for (const pre of Array.from(pres)) {\n const existingCode = pre.querySelector(\"code\");\n\n // Already set explicitly — leave alone.\n if (pre.getAttribute(\"data-language\")) continue;\n\n let lang =\n detectLanguageFromClass(pre.getAttribute(\"class\")) ||\n detectLanguageFromClass(existingCode?.getAttribute(\"class\") ?? null);\n\n if (!lang) {\n let ancestor: Element | null = pre.parentElement;\n let depth = 0;\n while (ancestor && depth < 5) {\n const found = detectLanguageFromClass(ancestor.getAttribute(\"class\"));\n if (found) {\n lang = found;\n break;\n }\n ancestor = ancestor.parentElement;\n depth++;\n }\n }\n\n if (!lang) continue;\n\n pre.setAttribute(\"data-language\", lang);\n\n // Unwrap any highlighter wrapper divs around this <pre>. Defuddle's\n // standardise step rewrites the `<pre>` (stripping its attributes,\n // including our data-language) when it sees this wrapped structure.\n // Replacing the wrapper with the bare <pre> sidesteps that path.\n let wrapper: Element | null = pre.parentElement;\n let depth = 0;\n while (wrapper && depth < 5) {\n const cls = wrapper.getAttribute(\"class\") ?? \"\";\n const isHighlightWrapper =\n /(?:^|\\s)(?:highlight|highlight-source-[A-Za-z0-9_+-]+|highlight-[A-Za-z0-9_+-]+)(?:\\s|$)/.test(\n cls,\n );\n if (\n isHighlightWrapper &&\n wrapper.children.length === 1 &&\n wrapper.parentElement\n ) {\n wrapper.parentElement.replaceChild(pre, wrapper);\n wrapper = pre.parentElement;\n } else {\n break;\n }\n depth++;\n }\n }\n }\n\n private applyExcludePreDefuddle(document: Document, context: MiddlewareContext): void {\n const selectors = context.options.excludeSelectors ?? [];\n if (selectors.length === 0) return;\n\n for (const selector of selectors) {\n try {\n const matches = document.querySelectorAll(selector);\n for (const node of Array.from(matches)) {\n const tag = node.tagName?.toLowerCase();\n if (tag === \"html\" || tag === \"body\") continue;\n node.remove();\n }\n } catch (selectorError) {\n logger.warn(\n `⚠️ Invalid excludeSelector \"${selector}\" before Defuddle: ${selectorError}`,\n );\n context.errors.push(\n new Error(`Invalid selector \"${selector}\": ${selectorError}`),\n );\n }\n }\n }\n}\n\nconst LANGUAGE_CLASS_RE =\n /(?:^|\\s)(?:highlight-source-|highlight-|language-)([A-Za-z0-9_+-]+)/;\n\nfunction detectLanguageFromClass(className: string | null | undefined): string {\n if (!className) return \"\";\n const match = LANGUAGE_CLASS_RE.exec(className);\n if (!match) return \"\";\n const lang = match[1].toLowerCase();\n // Skip generic non-language tokens that show up under `highlight-` prefix.\n if (lang === \"text\" || lang === \"highlighted\" || lang === \"wrap\") return \"\";\n return lang;\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n"],"mappings":";;;;;AAqBA,IAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;AAsB9B,IAAa,yBAAb,MAA0E;CACxE;CAEA,YAAY,UAA+B,CAAC,GAAG;EAC7C,KAAK,wBAAwB,QAAQ,yBAAyB;CAChE;CAEA,MAAM,QAAQ,SAA4B,MAA0C;EAClF,MAAM,IAAI,QAAQ;EAClB,IAAI,CAAC,GAAG;GACN,OAAO,KACL,eAAe,KAAK,YAAY,KAAK,+EACvC;GACA,MAAM,KAAK;GACX;EACF;EAEA,IAAI;GACF,MAAM,eAAe,EAAE,KAAK;GAK5B,MAAM,aAAa,QAAQ,KAAK,SAAS,EAAE,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,QAAQ;GACxE,WAAW,mCAAmC,CAAC,CAAC,OAAO;GACvD,MAAM,mBAAmB,WAAW,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GAE1D,MAAM,EAAE,aAAa,UAAU,YAAY;GAO3C,KAAK,wBAAwB,UAAU,OAAO;GAQ9C,KAAK,uBAAuB,QAAQ;GAEpC,MAAM,SAAS,MAAM,SAAS,UAAU,QAAQ,QAAQ,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