feedkeeper 0.42.1 → 0.42.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feedkeeper",
3
- "version": "0.42.1",
3
+ "version": "0.42.3",
4
4
  "description": "A lightweight, self-hosted RSS reader and remote MCP server for your news, blogs, and AI workflows.",
5
5
  "keywords": [
6
6
  "rss",
@@ -15,7 +15,7 @@ export function articleText(html) {
15
15
  fragment.querySelectorAll("p, div, br, li, h1, h2, h3, h4, blockquote").forEach(node => node.append(" "));
16
16
  return (fragment.textContent ?? "").replace(/\s+/g, " ").trim();
17
17
  }
18
- const READER_CACHE_LIMIT = 300;
18
+ const READER_CACHE_LIMIT = 600;
19
19
  const readerCache = new Map();
20
20
  /**
21
21
  * Article HTML as a reader shows it, without breadcrumbs, repeated headline and similar page chrome. Computed when
@@ -0,0 +1,96 @@
1
+ import { count, flat, parseAddress } from "../shared.js";
2
+ const REDDIT_HOST = /(?:^|\.)reddit\.com$/i;
3
+ const REDDIT_USER_PATH = /^\/(?:u|user)\/[^/]+/i;
4
+ const REDDIT_COMMENTS_PATH = /^\/r\/[^/]+\/comments\//i;
5
+ const SUBMITTED_BY = /\bsubmitted\s+by\b/i;
6
+ function isRedditUrl(href, pathPattern) {
7
+ if (!href)
8
+ return false;
9
+ const parsed = parseAddress(href);
10
+ return Boolean(parsed && REDDIT_HOST.test(parsed.hostname) && pathPattern.test(parsed.pathname));
11
+ }
12
+ function isRedditPostTable(table) {
13
+ const rows = [...table.querySelectorAll(":scope > tbody > tr, :scope > tr")];
14
+ if (rows.length !== 1)
15
+ return false;
16
+ const cells = [...rows[0].children].filter(child => child.tagName === "TD");
17
+ if (cells.length === 0 || cells.length > 2)
18
+ return false;
19
+ const bodyCell = cells[cells.length - 1];
20
+ if (!SUBMITTED_BY.test(flat(bodyCell.textContent)))
21
+ return false;
22
+ const links = [...bodyCell.querySelectorAll("a[href]")];
23
+ const hasAuthor = links.some(link => isRedditUrl(link.getAttribute("href"), REDDIT_USER_PATH));
24
+ const hasComments = links.some(link => flat(link.textContent).toLowerCase() === "[comments]" && isRedditUrl(link.getAttribute("href"), REDDIT_COMMENTS_PATH));
25
+ return hasAuthor && hasComments;
26
+ }
27
+ function externalLinkHost(href) {
28
+ const parsed = parseAddress(href);
29
+ if (!parsed || !/^https?:$/.test(parsed.protocol))
30
+ return null;
31
+ if (REDDIT_HOST.test(parsed.hostname) || parsed.hostname === "i.redd.it" || parsed.hostname === "v.redd.it")
32
+ return null;
33
+ return parsed.hostname.replace(/^www\./i, "");
34
+ }
35
+ /**
36
+ * Reddit subreddit Atom feeds wrap every post in a 1-row layout `<table>` with a thumbnail cell and a body cell
37
+ * ending in `submitted by /u/… [link] [comments]`. Unwrap the thumbnail and `.md` body and drop the forum chrome.
38
+ */
39
+ export function cleanRedditPost(root, stats) {
40
+ let changed = false;
41
+ for (const table of [...root.querySelectorAll("table")]) {
42
+ if (!isRedditPostTable(table))
43
+ continue;
44
+ const rows = [...table.querySelectorAll(":scope > tbody > tr, :scope > tr")];
45
+ const cells = [...rows[0].children].filter(child => child.tagName === "TD");
46
+ const doc = table.ownerDocument;
47
+ const replacement = [];
48
+ if (cells.length === 2) {
49
+ const thumbImg = cells[0].querySelector("img[src]");
50
+ const src = (thumbImg?.getAttribute("src") ?? "").trim();
51
+ if (thumbImg && src && !/^data:/i.test(src)) {
52
+ const figure = doc.createElement("p");
53
+ const cleanImg = doc.createElement("img");
54
+ cleanImg.setAttribute("src", src);
55
+ const alt = flat(thumbImg.getAttribute("alt"));
56
+ if (alt)
57
+ cleanImg.setAttribute("alt", alt);
58
+ figure.append(cleanImg);
59
+ replacement.push(figure);
60
+ }
61
+ }
62
+ const bodyCell = cells[cells.length - 1];
63
+ const md = bodyCell.querySelector("div.md");
64
+ if (md) {
65
+ for (const child of [...md.childNodes]) {
66
+ if (child.nodeType === 8)
67
+ continue; // Strip HTML comments (e.g. SC_OFF / SC_ON)
68
+ replacement.push(child);
69
+ }
70
+ }
71
+ // For link posts without body prose, preserve the external target link instead of `[link]`.
72
+ if (!md || flat(md.textContent) === "") {
73
+ const external = [...bodyCell.querySelectorAll("a[href]")].find(link => flat(link.textContent).toLowerCase() === "[link]" && externalLinkHost(link.getAttribute("href") ?? ""));
74
+ const href = external?.getAttribute("href") ?? "";
75
+ const host = external ? externalLinkHost(href) : null;
76
+ if (href && host) {
77
+ const p = doc.createElement("p");
78
+ const a = doc.createElement("a");
79
+ a.setAttribute("href", href);
80
+ a.textContent = host;
81
+ p.append("↗ ", a);
82
+ replacement.push(p);
83
+ }
84
+ }
85
+ if (replacement.length > 0) {
86
+ table.replaceWith(...replacement);
87
+ }
88
+ else {
89
+ table.remove();
90
+ }
91
+ count(stats, "reddit-post");
92
+ changed = true;
93
+ }
94
+ return changed;
95
+ }
96
+ //# sourceMappingURL=redditPosts.js.map
@@ -1,4 +1,5 @@
1
1
  import { cleanVideoPage } from "./content/noise/videoPages.js";
2
+ import { cleanRedditPost } from "./content/noise/redditPosts.js";
2
3
  import { lazyImages } from "./content/noise/lazyImages.js";
3
4
  import { JSDOM } from "jsdom";
4
5
  import { SNIPPET_BYLINES, SNIPPET_IMAGE_CREDIT, SNIPPET_IMAGE_FILENAME, SNIPPET_IMAGE_METADATA, SNIPPET_MARKERS } from "./content/patterns/snippet-metadata/index.js";
@@ -700,6 +701,7 @@ export function cleanReaderHtml(html, title, stats = {}, author, url) {
700
701
  return html;
701
702
  const root = JSDOM.fragment(html);
702
703
  const videoPage = cleanVideoPage(root, url, title, stats);
704
+ const redditPost = cleanRedditPost(root, stats);
703
705
  const lazy = lazyImages.apply(root, stats);
704
706
  const images = resolveCustomImages(root, stats);
705
707
  const duplicates = collapseAdjacentImages(root, stats);
@@ -707,7 +709,7 @@ export function cleanReaderHtml(html, title, stats = {}, author, url) {
707
709
  const embeds = resolveEmbeds(root, stats);
708
710
  const noise = removeReaderNoise(root, title, stats, author);
709
711
  const typography = removeTypography(root, stats);
710
- return videoPage || lazy || images || duplicates || variants || embeds || noise || typography ? serialize(root) : html;
712
+ return videoPage || redditPost || lazy || images || duplicates || variants || embeds || noise || typography ? serialize(root) : html;
711
713
  }
712
714
  /**
713
715
  * Some publishers wrap a picture in their own element and let a script fill the image: `<a-img src="/imgs/…">`
@@ -1,117 +1,14 @@
1
- import { SCRIPT_IMAGE_SOURCE } from "./imageSources.js";
2
- import { Readability } from "@mozilla/readability";
3
- import { JSDOM } from "jsdom";
4
1
  import { fetch as undiciFetch } from "undici";
5
- import { cleanPage } from "./content/index.js";
6
2
  import { createPublicDispatcher, SsrfBlockedError } from "./ssrfGuard.js";
7
3
  import { assertPublicFeedUrl } from "./blockedHosts.js";
8
4
  import { articleWorkPool, ArticleHostBusyError, ArticleAccessDeniedError } from "./articleWorkPool.js";
9
5
  import { parseRetryAfter } from "./fetcher.js";
10
6
  import { sourceHost } from "./requestGate.js";
11
7
  import { APP_VERSION } from "../version.js";
8
+ import { isConsentContent, isCachedConsentSnippet } from "./extractorParser.js";
9
+ import { parseArticleInWorker } from "./extractorPool.js";
10
+ export { isConsentContent, isCachedConsentSnippet };
12
11
  const defaultFetch = undiciFetch;
13
- const CONSENT_SELECTORS = [
14
- "#onetrust-consent-sdk",
15
- "#cmpbox",
16
- "#usercentrics-root",
17
- "[id*='sp_message_container']",
18
- "[class*='cookie-banner']",
19
- "[class*='cookie-consent']",
20
- "[class*='consent-banner']",
21
- "[id*='cookie-notice']",
22
- "[id*='cookie-banner']",
23
- ".qc-cmp2-container",
24
- "#didomi-host",
25
- "dialog[open]",
26
- ".cookie-wall",
27
- ".consent-wall",
28
- "[data-nosnippet]",
29
- ];
30
- function cleanConsentDom(doc) {
31
- for (const sel of CONSENT_SELECTORS) {
32
- try {
33
- doc.querySelectorAll(sel).forEach((el) => el.remove());
34
- }
35
- catch {
36
- // ignore invalid selector in edge environments
37
- }
38
- }
39
- }
40
- function isSafeSource(value) {
41
- if (!value)
42
- return false;
43
- const trimmed = value.trim();
44
- if (trimmed.length === 0 || trimmed.length > 4000 || /^javascript:/i.test(trimmed))
45
- return false;
46
- return /^https?:\/\//i.test(trimmed) || /^data:image\//i.test(trimmed) || trimmed.startsWith("/");
47
- }
48
- function resolveLazyImages(doc) {
49
- const images = doc.querySelectorAll("img");
50
- for (const img of images) {
51
- const lazySrc = img.getAttribute("data-lazy-src") ||
52
- img.getAttribute("data-src") ||
53
- img.getAttribute("data-original") ||
54
- img.getAttribute("data-actualsrc");
55
- const src = img.getAttribute("src");
56
- if (isSafeSource(lazySrc) && (!src || src.startsWith("data:") || src.length < 10 || SCRIPT_IMAGE_SOURCE.test(src))) {
57
- img.setAttribute("src", encodeURI(lazySrc.trim()));
58
- }
59
- const lazySrcset = img.getAttribute("data-lazy-srcset") || img.getAttribute("data-srcset");
60
- const srcset = img.getAttribute("srcset");
61
- if (isSafeSource(lazySrcset) && (!srcset || srcset.startsWith("data:"))) {
62
- img.setAttribute("srcset", encodeURI(lazySrcset.trim()));
63
- }
64
- }
65
- const sources = doc.querySelectorAll("source");
66
- for (const source of sources) {
67
- const lazySrcset = source.getAttribute("data-lazy-srcset") || source.getAttribute("data-srcset");
68
- if (isSafeSource(lazySrcset)) {
69
- source.setAttribute("srcset", encodeURI(lazySrcset.trim()));
70
- }
71
- }
72
- }
73
- /**
74
- * Checks if a given URL or extracted HTML/text is a cookie / consent wall rather than article content.
75
- */
76
- export function isConsentContent(finalUrl, html, title, text) {
77
- if (/\/zustimmung[/?]/i.test(finalUrl) ||
78
- /\/consent[/?]/i.test(finalUrl) ||
79
- /\/cookie-wall/i.test(finalUrl) ||
80
- /\/pur-abo[/?]/i.test(finalUrl) ||
81
- /\/cmp[/?]/i.test(finalUrl) ||
82
- /\/privacy-wall/i.test(finalUrl)) {
83
- return true;
84
- }
85
- const combined = `${title || ""} ${text || ""} ${html}`.toLowerCase();
86
- const strongSignatures = [
87
- "cookies zustimmen",
88
- "nutzung aller cookies",
89
- "tracking zustimmen",
90
- "einwilligung verwalten",
91
- "werbung und tracking, indem sie",
92
- "zustimmen & weiter",
93
- "bevor sie fortfahren",
94
- "accept all cookies",
95
- "cookie-einstellungen",
96
- "alle cookies akzeptieren",
97
- "cookies akzeptieren",
98
- "we value your privacy",
99
- ];
100
- const headText = `${title || ""} ${text || ""}`.toLowerCase().slice(0, 600);
101
- const hits = strongSignatures.filter(sig => combined.includes(sig));
102
- if (hits.length === 0)
103
- return false;
104
- const heading = (title || "").toLowerCase();
105
- if (strongSignatures.some(sig => heading.includes(sig)))
106
- return true;
107
- return (text || "").length < 1200 && hits.length >= 2 && hits.some(sig => headText.includes(sig));
108
- }
109
- /**
110
- * Checks cached HTML to see if it was a saved consent banner instead of real article content.
111
- */
112
- export function isCachedConsentSnippet(html) {
113
- return isConsentContent("", html, "", html.replace(/<[^>]+>/g, " "));
114
- }
115
12
  // Browser-like so article pages render normally, but identifies FeedKeeper honestly.
116
13
  const FETCH_USER_AGENT = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 FeedKeeper/${APP_VERSION}`;
117
14
  const FETCH_TIMEOUT_MS = 12_000;
@@ -128,14 +25,6 @@ class ArticleHttpError extends Error {
128
25
  }
129
26
  }
130
27
  const MAX_HTML_BYTES = 2 * 1024 * 1024;
131
- /** From this many characters of text, a page that calls itself not free still holds the article, and its text is kept. */
132
- const PAYWALL_TEXT_MIN = 2500;
133
- /** The link at the end of an article whose publisher flags it as behind a paywall; clients show it as a card. */
134
- function paywallNotice(pageUrl) {
135
- const address = new URL(pageUrl);
136
- const escape = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
137
- return `<p><a href="${escape(address.href)}" data-media="paywall" data-source="${escape(address.hostname.replace(/^www\./, ""))}">${escape(address.hostname.replace(/^www\./, ""))}</a></p>`;
138
- }
139
28
  async function fetchArticleHtml(rawUrl, signal, dispatcher, fetchImpl, ownerSignal) {
140
29
  let currentUrl = rawUrl;
141
30
  for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
@@ -210,51 +99,18 @@ async function extractArticleContent(rawUrl, fetchImpl, signal) {
210
99
  const controller = new AbortController();
211
100
  const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
212
101
  try {
213
- const fetched = await fetchArticleHtml(rawUrl, AbortSignal.any([signal, controller.signal]), dispatcher, fetchImpl, signal);
102
+ const combinedSignal = AbortSignal.any([signal, controller.signal]);
103
+ const fetched = await fetchArticleHtml(rawUrl, combinedSignal, dispatcher, fetchImpl, signal);
214
104
  if (!fetched)
215
105
  return { status: "failed" };
216
- const dom = new JSDOM(fetched.html, { url: fetched.url });
217
- let parsed;
218
- let paywalled = false;
219
- try {
220
- // The content rules run first: players and consent plugins keep the address of an embed in the very tags removed next.
221
- cleanPage(dom.window.document);
222
- dom.window.document.querySelectorAll("script, style, svg, iframe, noscript").forEach(element => element.remove());
223
- const paywall = /"isAccessibleForFree"\s*:\s*(?:false|"false")/i.test(fetched.html);
224
- cleanConsentDom(dom.window.document);
225
- resolveLazyImages(dom.window.document);
226
- parsed = new Readability(dom.window.document, { charThreshold: 60 }).parse();
227
- paywalled = paywall;
228
- if (isConsentContent(fetched.url, parsed?.content ?? fetched.html, parsed?.title, parsed?.textContent)) {
229
- return { status: "consent_wall" };
230
- }
231
- // Publishers flag a whole article as not free although the page carries its text; enough of it is the article.
232
- if ((paywall && (parsed?.textContent?.length ?? 0) < PAYWALL_TEXT_MIN) || ((parsed?.textContent?.length ?? 0) < PAYWALL_TEXT_MIN && /(?:subscribe to (?:continue|read)|sign in to (?:continue|read)|abonnieren und weiterlesen|nur für abonnenten|jetzt abonnieren.{0,40}weiterlesen)/i.test(parsed?.textContent ?? "")))
233
- return { status: "paywall" };
234
- if (!parsed?.content)
235
- return { status: "failed" };
236
- }
237
- finally {
238
- dom.window.close();
239
- }
240
- return {
241
- status: (parsed.textContent?.trim().length ?? 0) < 200 ? "partial" : "ok",
242
- article: {
243
- title: parsed.title || null,
244
- byline: parsed.byline || null,
245
- contentHtml: paywalled ? `${parsed.content}${paywallNotice(fetched.url)}` : parsed.content,
246
- textContent: parsed.textContent || "",
247
- excerpt: parsed.excerpt || null,
248
- siteName: parsed.siteName || null,
249
- },
250
- };
106
+ return await parseArticleInWorker(fetched.html, fetched.url, combinedSignal);
251
107
  }
252
108
  catch (error) {
253
109
  if (error instanceof ArticleHostBusyError)
254
110
  return { status: "throttled", host: error.host, retryAt: error.retryAt, deferred: true };
255
111
  if (error instanceof SsrfBlockedError)
256
112
  throw error;
257
- if (signal.aborted || controller.signal.aborted)
113
+ if (signal.aborted || controller.signal.aborted || (error instanceof Error && ["TimeoutError", "AbortError"].includes(error.name)))
258
114
  return { status: "timeout" };
259
115
  if (error instanceof ArticleHttpError && [401, 402].includes(error.status))
260
116
  return { status: "paywall" };
@@ -0,0 +1,156 @@
1
+ import { Readability } from "@mozilla/readability";
2
+ import { JSDOM } from "jsdom";
3
+ import { cleanPage } from "./content/index.js";
4
+ import { SCRIPT_IMAGE_SOURCE } from "./imageSources.js";
5
+ const CONSENT_SELECTORS = [
6
+ "#onetrust-consent-sdk",
7
+ "#cmpbox",
8
+ "#usercentrics-root",
9
+ "[id*='sp_message_container']",
10
+ "[class*='cookie-banner']",
11
+ "[class*='cookie-consent']",
12
+ "[class*='consent-banner']",
13
+ "[id*='cookie-notice']",
14
+ "[id*='cookie-banner']",
15
+ ".qc-cmp2-container",
16
+ "#didomi-host",
17
+ "dialog[open]",
18
+ ".cookie-wall",
19
+ ".consent-wall",
20
+ "[data-nosnippet]",
21
+ ];
22
+ /** From this many characters of text, a page that calls itself not free still holds the article, and its text is kept. */
23
+ const PAYWALL_TEXT_MIN = 2500;
24
+ function cleanConsentDom(doc) {
25
+ for (const sel of CONSENT_SELECTORS) {
26
+ try {
27
+ doc.querySelectorAll(sel).forEach((el) => el.remove());
28
+ }
29
+ catch {
30
+ // ignore invalid selector in edge environments
31
+ }
32
+ }
33
+ }
34
+ function isSafeSource(value) {
35
+ if (!value)
36
+ return false;
37
+ const trimmed = value.trim();
38
+ if (trimmed.length === 0 || trimmed.length > 4000 || /^javascript:/i.test(trimmed))
39
+ return false;
40
+ return /^https?:\/\//i.test(trimmed) || /^data:image\//i.test(trimmed) || trimmed.startsWith("/");
41
+ }
42
+ function resolveLazyImages(doc) {
43
+ const images = doc.querySelectorAll("img");
44
+ for (const img of images) {
45
+ const lazySrc = img.getAttribute("data-lazy-src") ||
46
+ img.getAttribute("data-src") ||
47
+ img.getAttribute("data-original") ||
48
+ img.getAttribute("data-actualsrc");
49
+ const src = img.getAttribute("src");
50
+ if (isSafeSource(lazySrc) && (!src || src.startsWith("data:") || src.length < 10 || SCRIPT_IMAGE_SOURCE.test(src))) {
51
+ img.setAttribute("src", encodeURI(lazySrc.trim()));
52
+ }
53
+ const lazySrcset = img.getAttribute("data-lazy-srcset") || img.getAttribute("data-srcset");
54
+ const srcset = img.getAttribute("srcset");
55
+ if (isSafeSource(lazySrcset) && (!srcset || srcset.startsWith("data:"))) {
56
+ img.setAttribute("srcset", encodeURI(lazySrcset.trim()));
57
+ }
58
+ }
59
+ const sources = doc.querySelectorAll("source");
60
+ for (const source of sources) {
61
+ const lazySrcset = source.getAttribute("data-lazy-srcset") || source.getAttribute("data-srcset");
62
+ if (isSafeSource(lazySrcset)) {
63
+ source.setAttribute("srcset", encodeURI(lazySrcset.trim()));
64
+ }
65
+ }
66
+ }
67
+ /**
68
+ * Checks if a given URL or extracted HTML/text is a cookie / consent wall rather than article content.
69
+ */
70
+ export function isConsentContent(finalUrl, html, title, text) {
71
+ if (/\/zustimmung[/?]/i.test(finalUrl) ||
72
+ /\/consent[/?]/i.test(finalUrl) ||
73
+ /\/cookie-wall/i.test(finalUrl) ||
74
+ /\/pur-abo[/?]/i.test(finalUrl) ||
75
+ /\/cmp[/?]/i.test(finalUrl) ||
76
+ /\/privacy-wall/i.test(finalUrl)) {
77
+ return true;
78
+ }
79
+ const combined = `${title || ""} ${text || ""} ${html}`.toLowerCase();
80
+ const strongSignatures = [
81
+ "cookies zustimmen",
82
+ "nutzung aller cookies",
83
+ "tracking zustimmen",
84
+ "einwilligung verwalten",
85
+ "werbung und tracking, indem sie",
86
+ "zustimmen & weiter",
87
+ "bevor sie fortfahren",
88
+ "accept all cookies",
89
+ "cookie-einstellungen",
90
+ "alle cookies akzeptieren",
91
+ "cookies akzeptieren",
92
+ "we value your privacy",
93
+ ];
94
+ const headText = `${title || ""} ${text || ""}`.toLowerCase().slice(0, 600);
95
+ const hits = strongSignatures.filter(sig => combined.includes(sig));
96
+ if (hits.length === 0)
97
+ return false;
98
+ const heading = (title || "").toLowerCase();
99
+ if (strongSignatures.some(sig => heading.includes(sig)))
100
+ return true;
101
+ return (text || "").length < 1200 && hits.length >= 2 && hits.some(sig => headText.includes(sig));
102
+ }
103
+ /**
104
+ * Checks cached HTML to see if it was a saved consent banner instead of real article content.
105
+ */
106
+ export function isCachedConsentSnippet(html) {
107
+ return isConsentContent("", html, "", html.replace(/<[^>]+>/g, " "));
108
+ }
109
+ /** The link at the end of an article whose publisher flags it as behind a paywall; clients show it as a card. */
110
+ function paywallNotice(pageUrl) {
111
+ const address = new URL(pageUrl);
112
+ const escape = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
113
+ return `<p><a href="${escape(address.href)}" data-media="paywall" data-source="${escape(address.hostname.replace(/^www\./, ""))}">${escape(address.hostname.replace(/^www\./, ""))}</a></p>`;
114
+ }
115
+ /** Pure CPU-bound JSDOM + Readability extraction so worker threads can run it off the HTTP event loop. */
116
+ export function parseArticleHtml(html, url) {
117
+ const dom = new JSDOM(html, { url });
118
+ let parsed;
119
+ let paywalled = false;
120
+ try {
121
+ // The content rules run first: players and consent plugins keep the address of an embed in the very tags removed next.
122
+ cleanPage(dom.window.document);
123
+ dom.window.document.querySelectorAll("script, style, svg, iframe, noscript").forEach(element => element.remove());
124
+ const paywall = /"isAccessibleForFree"\s*:\s*(?:false|"false")/i.test(html);
125
+ cleanConsentDom(dom.window.document);
126
+ resolveLazyImages(dom.window.document);
127
+ parsed = new Readability(dom.window.document, { charThreshold: 60 }).parse();
128
+ paywalled = paywall;
129
+ if (isConsentContent(url, parsed?.content ?? html, parsed?.title, parsed?.textContent)) {
130
+ return { status: "consent_wall" };
131
+ }
132
+ // Publishers flag a whole article as not free although the page carries its text; enough of it is the article.
133
+ if ((paywall && (parsed?.textContent?.length ?? 0) < PAYWALL_TEXT_MIN) ||
134
+ ((parsed?.textContent?.length ?? 0) < PAYWALL_TEXT_MIN &&
135
+ /(?:subscribe to (?:continue|read)|sign in to (?:continue|read)|abonnieren und weiterlesen|nur für abonnenten|jetzt abonnieren.{0,40}weiterlesen)/i.test(parsed?.textContent ?? ""))) {
136
+ return { status: "paywall" };
137
+ }
138
+ if (!parsed?.content)
139
+ return { status: "failed" };
140
+ }
141
+ finally {
142
+ dom.window.close();
143
+ }
144
+ return {
145
+ status: (parsed.textContent?.trim().length ?? 0) < 200 ? "partial" : "ok",
146
+ article: {
147
+ title: parsed.title || null,
148
+ byline: parsed.byline || null,
149
+ contentHtml: paywalled ? `${parsed.content}${paywallNotice(url)}` : parsed.content,
150
+ textContent: parsed.textContent || "",
151
+ excerpt: parsed.excerpt || null,
152
+ siteName: parsed.siteName || null,
153
+ },
154
+ };
155
+ }
156
+ //# sourceMappingURL=extractorParser.js.map
@@ -0,0 +1,175 @@
1
+ import { Worker } from "node:worker_threads";
2
+ const PARSE_TIMEOUT_MS = 15_000;
3
+ function readWorkerCount() {
4
+ const raw = process.env.EXTRACTOR_WORKERS;
5
+ if (raw === undefined)
6
+ return 2;
7
+ const parsed = Number(raw);
8
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > 4)
9
+ return 2;
10
+ return parsed;
11
+ }
12
+ function createWorker() {
13
+ const isTs = import.meta.url.endsWith(".ts");
14
+ const url = new URL(isTs ? "./extractorWorker.ts" : "./extractorWorker.js", import.meta.url);
15
+ const worker = isTs ? new Worker(url, { execArgv: ["--import", "tsx"] }) : new Worker(url);
16
+ worker.unref();
17
+ return worker;
18
+ }
19
+ class ExtractorWorkerPool {
20
+ slots = [];
21
+ queue = [];
22
+ nextId = 1;
23
+ stopped = false;
24
+ ensureCapacity() {
25
+ const target = readWorkerCount();
26
+ while (!this.stopped && this.slots.length < target && this.slots.length < this.queue.length + this.activeCount()) {
27
+ this.slots.push(this.spawnSlot());
28
+ }
29
+ }
30
+ activeCount() {
31
+ return this.slots.filter(slot => slot.busy).length;
32
+ }
33
+ spawnSlot() {
34
+ const worker = createWorker();
35
+ const slot = { worker, busy: false, current: null, timer: null };
36
+ worker.on("message", (msg) => {
37
+ const task = slot.current;
38
+ if (!task || task.id !== msg.id)
39
+ return;
40
+ this.finishSlot(slot);
41
+ if (msg.error)
42
+ task.reject(new Error(msg.error));
43
+ else if (msg.result)
44
+ task.resolve(msg.result);
45
+ else
46
+ task.reject(new Error("worker_empty_response"));
47
+ this.pump();
48
+ });
49
+ const handleFailure = (reason) => {
50
+ const task = slot.current;
51
+ this.dropSlot(slot);
52
+ if (task)
53
+ task.reject(reason);
54
+ this.pump();
55
+ };
56
+ worker.on("error", err => handleFailure(err instanceof Error ? err : new Error(String(err))));
57
+ worker.on("exit", code => {
58
+ if (this.slots.includes(slot)) {
59
+ handleFailure(new Error(`extractor_worker_exited_${code}`));
60
+ }
61
+ });
62
+ return slot;
63
+ }
64
+ finishSlot(slot) {
65
+ if (slot.timer) {
66
+ clearTimeout(slot.timer);
67
+ slot.timer = null;
68
+ }
69
+ const task = slot.current;
70
+ if (task?.signal && task.abortListener) {
71
+ task.signal.removeEventListener("abort", task.abortListener);
72
+ }
73
+ slot.current = null;
74
+ slot.busy = false;
75
+ slot.worker.unref();
76
+ }
77
+ dropSlot(slot) {
78
+ if (slot.timer) {
79
+ clearTimeout(slot.timer);
80
+ slot.timer = null;
81
+ }
82
+ const task = slot.current;
83
+ if (task?.signal && task.abortListener) {
84
+ task.signal.removeEventListener("abort", task.abortListener);
85
+ }
86
+ slot.current = null;
87
+ slot.busy = false;
88
+ this.slots = this.slots.filter(entry => entry !== slot);
89
+ void slot.worker.terminate().catch(() => { });
90
+ }
91
+ run(html, url, signal) {
92
+ if (this.stopped)
93
+ return Promise.reject(new DOMException("Extractor pool stopped", "AbortError"));
94
+ if (signal?.aborted)
95
+ return Promise.reject(signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError"));
96
+ return new Promise((resolve, reject) => {
97
+ const task = { id: this.nextId++, html, url, signal, resolve, reject };
98
+ if (signal) {
99
+ task.abortListener = () => {
100
+ const idx = this.queue.indexOf(task);
101
+ if (idx !== -1) {
102
+ this.queue.splice(idx, 1);
103
+ reject(signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError"));
104
+ return;
105
+ }
106
+ const runningSlot = this.slots.find(s => s.current === task);
107
+ if (runningSlot) {
108
+ // Terminate a busy worker on abort/timeout so runaway DOM parsing cannot stall later tasks.
109
+ this.dropSlot(runningSlot);
110
+ reject(signal.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError"));
111
+ this.pump();
112
+ }
113
+ };
114
+ signal.addEventListener("abort", task.abortListener, { once: true });
115
+ }
116
+ this.queue.push(task);
117
+ this.pump();
118
+ });
119
+ }
120
+ pump() {
121
+ if (this.stopped || this.queue.length === 0)
122
+ return;
123
+ this.ensureCapacity();
124
+ for (const slot of this.slots) {
125
+ if (slot.busy)
126
+ continue;
127
+ const task = this.queue.shift();
128
+ if (!task)
129
+ break;
130
+ slot.busy = true;
131
+ slot.current = task;
132
+ slot.worker.ref();
133
+ slot.timer = setTimeout(() => {
134
+ if (slot.current !== task)
135
+ return;
136
+ this.dropSlot(slot);
137
+ task.reject(new DOMException("Worker parse deadline exceeded", "TimeoutError"));
138
+ this.pump();
139
+ }, PARSE_TIMEOUT_MS);
140
+ slot.worker.postMessage({ id: task.id, html: task.html, url: task.url });
141
+ }
142
+ }
143
+ async stop() {
144
+ this.stopped = true;
145
+ for (const task of this.queue.splice(0)) {
146
+ if (task.signal && task.abortListener)
147
+ task.signal.removeEventListener("abort", task.abortListener);
148
+ task.reject(new DOMException("Extractor pool stopped", "AbortError"));
149
+ }
150
+ const closing = this.slots.splice(0);
151
+ await Promise.all(closing.map(async (slot) => {
152
+ if (slot.timer)
153
+ clearTimeout(slot.timer);
154
+ const task = slot.current;
155
+ if (task?.signal && task.abortListener)
156
+ task.signal.removeEventListener("abort", task.abortListener);
157
+ if (task)
158
+ task.reject(new DOMException("Extractor pool stopped", "AbortError"));
159
+ await slot.worker.terminate().catch(() => { });
160
+ }));
161
+ }
162
+ }
163
+ let pool;
164
+ export function parseArticleInWorker(html, url, signal) {
165
+ pool ??= new ExtractorWorkerPool();
166
+ return pool.run(html, url, signal);
167
+ }
168
+ export async function stopExtractorPool() {
169
+ if (!pool)
170
+ return;
171
+ const active = pool;
172
+ pool = undefined;
173
+ await active.stop();
174
+ }
175
+ //# sourceMappingURL=extractorPool.js.map
@@ -0,0 +1,12 @@
1
+ import { parentPort } from "node:worker_threads";
2
+ import { parseArticleHtml } from "./extractorParser.js";
3
+ parentPort?.on("message", (task) => {
4
+ try {
5
+ const result = parseArticleHtml(task.html, task.url);
6
+ parentPort?.postMessage({ id: task.id, result });
7
+ }
8
+ catch (error) {
9
+ parentPort?.postMessage({ id: task.id, error: error instanceof Error ? error.message : "worker_parse_failed" });
10
+ }
11
+ });
12
+ //# sourceMappingURL=extractorWorker.js.map