webcrawl 1.2.4 → 1.2.7

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 (116) hide show
  1. package/dist/cli.js +3 -2
  2. package/dist/core/engine/awswaf.d.ts +37 -0
  3. package/dist/core/engine/awswaf.js +189 -0
  4. package/dist/core/engine/cache.d.ts +70 -0
  5. package/dist/core/engine/cache.js +297 -0
  6. package/dist/core/engine/crawl-policy.d.ts +36 -0
  7. package/dist/core/engine/crawl-policy.js +134 -0
  8. package/dist/core/engine/crawler.d.ts +151 -0
  9. package/dist/core/engine/crawler.js +885 -0
  10. package/dist/core/engine/fetcher.d.ts +66 -0
  11. package/dist/core/engine/fetcher.js +185 -0
  12. package/dist/core/engine/index.d.ts +4 -0
  13. package/dist/core/engine/index.js +4 -0
  14. package/dist/core/engine/markdown.d.ts +33 -0
  15. package/dist/core/engine/markdown.js +334 -0
  16. package/dist/core/engine/path-scope.d.ts +21 -0
  17. package/dist/core/engine/path-scope.js +88 -0
  18. package/dist/core/engine/safe-url.d.ts +23 -0
  19. package/dist/core/engine/safe-url.js +92 -0
  20. package/dist/core/engine/stealth.d.ts +79 -0
  21. package/dist/core/engine/stealth.js +155 -0
  22. package/dist/core/engine.d.ts +1 -0
  23. package/dist/core/engine.js +1 -0
  24. package/dist/core/extract/business.d.ts +28 -0
  25. package/dist/core/extract/business.js +344 -0
  26. package/dist/core/extract/currency.d.ts +15 -0
  27. package/dist/core/extract/currency.js +259 -0
  28. package/dist/core/extract/cve-cache.d.ts +62 -0
  29. package/dist/core/extract/cve-cache.js +277 -0
  30. package/dist/core/extract/cve.d.ts +57 -0
  31. package/dist/core/extract/cve.js +397 -0
  32. package/dist/core/extract/dedupe-key.d.ts +12 -0
  33. package/dist/core/extract/dedupe-key.js +36 -0
  34. package/dist/core/extract/flights.d.ts +37 -0
  35. package/dist/core/extract/flights.js +373 -0
  36. package/dist/core/extract/hotels.d.ts +35 -0
  37. package/dist/core/extract/hotels.js +473 -0
  38. package/dist/core/extract/index.d.ts +8 -0
  39. package/dist/core/extract/index.js +8 -0
  40. package/dist/core/extract/real-estate.d.ts +53 -0
  41. package/dist/core/extract/real-estate.js +835 -0
  42. package/dist/core/extract/scaledown.d.ts +14 -0
  43. package/dist/core/extract/scaledown.js +484 -0
  44. package/dist/core/extract/shopping.d.ts +44 -0
  45. package/dist/core/extract/shopping.js +393 -0
  46. package/dist/core/image-url.d.ts +5 -0
  47. package/dist/core/image-url.js +13 -0
  48. package/dist/core/interact/driver.d.ts +49 -0
  49. package/dist/core/interact/driver.js +264 -0
  50. package/dist/core/interact/remote.d.ts +41 -0
  51. package/dist/core/interact/remote.js +133 -0
  52. package/dist/core/interact/spans.d.ts +46 -0
  53. package/dist/core/interact/spans.js +32 -0
  54. package/dist/core/interact/validate.d.ts +34 -0
  55. package/dist/core/interact/validate.js +135 -0
  56. package/dist/core/interact/vm.d.ts +42 -0
  57. package/dist/core/interact/vm.js +296 -0
  58. package/dist/core/local-engine.d.ts +35 -0
  59. package/dist/core/local-engine.js +367 -0
  60. package/dist/core/parse/detect.d.ts +29 -0
  61. package/dist/core/parse/detect.js +152 -0
  62. package/dist/core/parse/fetch.d.ts +20 -0
  63. package/dist/core/parse/fetch.js +39 -0
  64. package/dist/core/parse/image.d.ts +13 -0
  65. package/dist/core/parse/image.js +100 -0
  66. package/dist/core/parse/index.d.ts +53 -0
  67. package/dist/core/parse/index.js +153 -0
  68. package/dist/core/parse/limits.d.ts +12 -0
  69. package/dist/core/parse/limits.js +29 -0
  70. package/dist/core/parse/media.d.ts +42 -0
  71. package/dist/core/parse/media.js +238 -0
  72. package/dist/core/parse/merge.d.ts +19 -0
  73. package/dist/core/parse/merge.js +48 -0
  74. package/dist/core/parse/ocr.d.ts +25 -0
  75. package/dist/core/parse/ocr.js +121 -0
  76. package/dist/core/parse/office.d.ts +28 -0
  77. package/dist/core/parse/office.js +83 -0
  78. package/dist/core/parse/pdf.d.ts +27 -0
  79. package/dist/core/parse/pdf.js +156 -0
  80. package/dist/core/parse/types.d.ts +38 -0
  81. package/dist/core/parse/types.js +1 -0
  82. package/dist/core/parse/youtube.d.ts +30 -0
  83. package/dist/core/parse/youtube.js +264 -0
  84. package/dist/core/ranker/decision.d.ts +28 -0
  85. package/dist/core/ranker/decision.js +151 -0
  86. package/dist/core/ranker/index.d.ts +5 -0
  87. package/dist/core/ranker/index.js +361 -0
  88. package/dist/core/ranker/lexical.d.ts +82 -0
  89. package/dist/core/ranker/lexical.js +642 -0
  90. package/dist/core/ranker/types.d.ts +90 -0
  91. package/dist/core/ranker/types.js +1 -0
  92. package/dist/core/ranker.d.ts +1 -0
  93. package/dist/core/ranker.js +1 -0
  94. package/dist/core/sandbox.d.ts +29 -0
  95. package/dist/core/sandbox.js +182 -0
  96. package/dist/core/search/catalog.d.ts +174 -0
  97. package/dist/core/search/catalog.js +488 -0
  98. package/dist/core/search/index.d.ts +3 -0
  99. package/dist/core/search/index.js +3 -0
  100. package/dist/core/search/pipeline.d.ts +7 -0
  101. package/dist/core/search/pipeline.js +704 -0
  102. package/dist/core/search/providers.d.ts +62 -0
  103. package/dist/core/search/providers.js +1175 -0
  104. package/dist/core/search.d.ts +1 -0
  105. package/dist/core/search.js +1 -0
  106. package/dist/core/targets/developer.d.ts +44 -0
  107. package/dist/core/targets/developer.js +338 -0
  108. package/dist/core/targets/index.d.ts +3 -0
  109. package/dist/core/targets/index.js +3 -0
  110. package/dist/core/targets/registry.d.ts +32 -0
  111. package/dist/core/targets/registry.js +411 -0
  112. package/dist/core/targets/types.d.ts +72 -0
  113. package/dist/core/targets/types.js +8 -0
  114. package/dist/core/targets.d.ts +1 -0
  115. package/dist/core/targets.js +1 -0
  116. package/package.json +82 -4
package/dist/cli.js CHANGED
@@ -241,8 +241,9 @@ async function resolveBackendClient(cfg, deps) {
241
241
  });
242
242
  }
243
243
  try {
244
- const localEngineSpec = ["..", "..", "..", "src", "local-engine.js"].join("/");
245
- const localMod = (await import(localEngineSpec));
244
+ const packagedSpec = ["./core/local-engine.js"].join("");
245
+ const fallbackSpec = ["..", "..", "..", "src", "local-engine.js"].join("/");
246
+ const localMod = (await import(packagedSpec).catch(() => import(fallbackSpec)));
246
247
  return localMod.createLocalEngineClient();
247
248
  }
248
249
  catch {
@@ -0,0 +1,37 @@
1
+ /** True when an HTML response (with optional status) is an AWS WAF challenge interstitial. */
2
+ export declare function isAwsWafChallenge(html: string, status?: number): boolean;
3
+ /** True when a fetch response is any known bot check (upstream detector + AWS WAF). */
4
+ export declare function isBlockedLike(html: string, status?: number): boolean;
5
+ export interface AwsWafPage {
6
+ url: string;
7
+ title: string;
8
+ markdown: string;
9
+ linksCount: number;
10
+ cached: false;
11
+ cacheLayer: "miss";
12
+ structuredData: null;
13
+ statusCode?: number;
14
+ blocked?: boolean;
15
+ error?: string;
16
+ awsWaf?: boolean;
17
+ stealth?: boolean;
18
+ }
19
+ /**
20
+ * Opens `url` in a real local Chromium, waits out the AWS WAF challenge
21
+ * (the interstitial reloads itself once `AwsWafIntegration.getToken()`
22
+ * resolves), then returns the rendered page as a CrawledPage-shaped result.
23
+ * Never fabricates content: a page still showing the challenge comes back
24
+ * `blocked: true` with an honest error.
25
+ */
26
+ export declare function awsWafStealthFetch(url: string, opts?: {
27
+ timeoutMs?: number;
28
+ }): Promise<AwsWafPage>;
29
+ /**
30
+ * Reads one page: plain TLS-impersonated fetch first; when the site answers
31
+ * with an AWS WAF challenge (which the upstream detector misses), routes
32
+ * through the local stealth browser instead.
33
+ */
34
+ export declare function crawlPageWithAwsWaf(url: string, opts?: {
35
+ bypassCache?: boolean;
36
+ stealthTimeoutMs?: number;
37
+ }): Promise<AwsWafPage>;
@@ -0,0 +1,189 @@
1
+ /**
2
+ * AWS WAF challenge handling (local prototype).
3
+ *
4
+ * `webcrawl`'s bot-check detector (`isAntiBotChallenge`) only matches
5
+ * Cloudflare and Vercel Security Checkpoint signatures. AWS WAF serves
6
+ * its invisible JS challenge as **HTTP 202** with an empty `<title>` and
7
+ * none of those markers, so such pages come back as
8
+ * `Empty page (HTTP 202)` with `blocked: false` and never reach the
9
+ * stealth browser. This module adds the missing detection plus a local
10
+ * stealth-routing path so those pages can be solved and read anyway.
11
+ *
12
+ * Detection markers are layered (no single one is proof):
13
+ * - status 202 (documented Challenge interstitial status)
14
+ * - `awsWafCookieDomainList` / `AwsWafIntegration` (documented JS API)
15
+ * - `aws-waf-token` cookie reference
16
+ * - `<div id="challenge-container">` + `/__challenge_<id>/.../challenge.js`
17
+ */
18
+ import { fetchWithTlsImpersonation, fastHtmlToMarkdown, isAntiBotChallenge } from "../engine.js";
19
+ /** Markers that only appear on an AWS WAF challenge interstitial. */
20
+ const AWS_WAF_MARKERS = [
21
+ "awswafcookiedomainlist",
22
+ "awswafintegration",
23
+ "aws-waf-token",
24
+ "id=\"challenge-container\"",
25
+ "/__challenge_",
26
+ ];
27
+ /** True when an HTML response (with optional status) is an AWS WAF challenge interstitial. */
28
+ export function isAwsWafChallenge(html, status) {
29
+ const lower = String(html ?? "").slice(0, 8000).toLowerCase();
30
+ const hasMarker = AWS_WAF_MARKERS.some((m) => lower.includes(m));
31
+ if (hasMarker)
32
+ return true;
33
+ // 202 alone is the documented Challenge status, but APIs can legitimately
34
+ // return 202 - only treat it as a challenge when the body is empty/challenge-ish.
35
+ if (status === 202) {
36
+ // 202 is the documented Challenge interstitial status. The interstitial's
37
+ // entire payload is <script>/<noscript>, so visible text is empty.
38
+ if (!lower.includes("<html"))
39
+ return false;
40
+ const visibleText = lower
41
+ .slice(0, 8000)
42
+ .replace(/<script[\s\S]*?<\/script>/g, "")
43
+ .replace(/<noscript[\s\S]*?<\/noscript>/g, "")
44
+ .replace(/<style[\s\S]*?<\/style>/g, "")
45
+ .replace(/<[^>]+>/g, " ")
46
+ .trim();
47
+ return visibleText.length === 0;
48
+ }
49
+ return false;
50
+ }
51
+ /** True when a fetch response is any known bot check (upstream detector + AWS WAF). */
52
+ export function isBlockedLike(html, status) {
53
+ return isAntiBotChallenge(html ?? "", status ?? 200) || isAwsWafChallenge(html ?? "", status);
54
+ }
55
+ const MAC_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
56
+ const CHALLENGE_TIMEOUT_MS = 45_000;
57
+ /** Waits for a dynamically-installed playwright-core (avoids a hard dep). */
58
+ async function loadPlaywrightCore() {
59
+ // Non-literal specifier: playwright-core stays a soft, runtime-only dependency
60
+ // so `tsc --noEmit` passes without the package installed.
61
+ const specifier = "playwright-core";
62
+ return (await import(specifier));
63
+ }
64
+ function chromePath() {
65
+ return process.env.INTERACT_CHROME_PATH || MAC_CHROME;
66
+ }
67
+ /**
68
+ * Opens `url` in a real local Chromium, waits out the AWS WAF challenge
69
+ * (the interstitial reloads itself once `AwsWafIntegration.getToken()`
70
+ * resolves), then returns the rendered page as a CrawledPage-shaped result.
71
+ * Never fabricates content: a page still showing the challenge comes back
72
+ * `blocked: true` with an honest error.
73
+ */
74
+ export async function awsWafStealthFetch(url, opts = {}) {
75
+ const fail = (error, blocked = true) => ({
76
+ url,
77
+ title: url,
78
+ markdown: "",
79
+ linksCount: 0,
80
+ cached: false,
81
+ cacheLayer: "miss",
82
+ structuredData: null,
83
+ blocked,
84
+ error,
85
+ awsWaf: true,
86
+ stealth: true,
87
+ });
88
+ const { chromium } = await loadPlaywrightCore();
89
+ const executablePath = chromePath();
90
+ const browser = await chromium.launch({
91
+ executablePath,
92
+ headless: true,
93
+ args: [
94
+ "--no-sandbox",
95
+ "--disable-gpu",
96
+ "--disable-dev-shm-usage",
97
+ "--no-first-run",
98
+ "--no-default-browser-check",
99
+ // Hide navigator.webdriver, which bot checks look for.
100
+ "--disable-blink-features=AutomationControlled",
101
+ `--window-size=1280,800`,
102
+ ],
103
+ });
104
+ try {
105
+ const ctx = await browser.newContext({
106
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
107
+ viewport: { width: 1280, height: 800 },
108
+ locale: "en-US",
109
+ });
110
+ await ctx.addInitScript("Object.defineProperty(Navigator.prototype,'webdriver',{get:()=>false});");
111
+ const page = await ctx.newPage();
112
+ let navStatus = null;
113
+ page.on("response", (r) => {
114
+ try {
115
+ if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
116
+ navStatus = r.status();
117
+ }
118
+ catch { }
119
+ });
120
+ // The interstitial reloads itself after getToken(); domcontentloaded +
121
+ // marker polling survives that reload race.
122
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: Math.min(30_000, opts.timeoutMs ?? 30_000) });
123
+ const deadline = Date.now() + (opts.timeoutMs ?? CHALLENGE_TIMEOUT_MS);
124
+ let html = "";
125
+ for (;;) {
126
+ html = await page.content().catch(() => "");
127
+ if (!isAwsWafChallenge(html) && !isAntiBotChallenge(html, 200))
128
+ break;
129
+ if (Date.now() > deadline)
130
+ break;
131
+ await page.waitForTimeout(700).catch(() => { });
132
+ }
133
+ try {
134
+ await page.waitForLoadState("networkidle", { timeout: 2500 });
135
+ }
136
+ catch { }
137
+ html = await page.content().catch(() => html);
138
+ if (isAwsWafChallenge(html) || isAntiBotChallenge(html, 200)) {
139
+ return { ...fail("Still blocked by the site's AWS WAF challenge in local stealth mode"), statusCode: navStatus ?? undefined };
140
+ }
141
+ const finalUrl = page.url();
142
+ const parsed = fastHtmlToMarkdown(html, finalUrl || url, { retainImages: "all" });
143
+ if (parsed.markdown.length === 0) {
144
+ return {
145
+ ...fail(`Empty page after challenge (HTTP ${navStatus ?? "?"})`, false),
146
+ statusCode: navStatus ?? undefined,
147
+ };
148
+ }
149
+ return {
150
+ url,
151
+ title: parsed.title || finalUrl || url,
152
+ markdown: parsed.markdown,
153
+ linksCount: parsed.links.length,
154
+ cached: false,
155
+ cacheLayer: "miss",
156
+ structuredData: null,
157
+ statusCode: navStatus ?? 200,
158
+ awsWaf: true,
159
+ stealth: true,
160
+ };
161
+ }
162
+ finally {
163
+ await browser.close().catch(() => { });
164
+ }
165
+ }
166
+ /**
167
+ * Reads one page: plain TLS-impersonated fetch first; when the site answers
168
+ * with an AWS WAF challenge (which the upstream detector misses), routes
169
+ * through the local stealth browser instead.
170
+ */
171
+ export async function crawlPageWithAwsWaf(url, opts = {}) {
172
+ const fetched = await fetchWithTlsImpersonation(url, 12_000);
173
+ if (!isAwsWafChallenge(fetched.html, fetched.status)) {
174
+ const parsed = fastHtmlToMarkdown(fetched.html, url, { retainImages: "all" });
175
+ return {
176
+ url,
177
+ title: parsed.title || url,
178
+ markdown: parsed.markdown,
179
+ linksCount: parsed.links.length,
180
+ cached: false,
181
+ cacheLayer: "miss",
182
+ structuredData: null,
183
+ statusCode: fetched.status,
184
+ ...(parsed.markdown.length === 0 ? { error: `Empty page (HTTP ${fetched.status})` } : {}),
185
+ };
186
+ }
187
+ console.info("[awswaf] challenge detected, routing through local stealth browser", { url, status: fetched.status });
188
+ return awsWafStealthFetch(url, { timeoutMs: opts.stealthTimeoutMs });
189
+ }
@@ -0,0 +1,70 @@
1
+ interface ExternalCacheDb {
2
+ getCrawledPage(urlHash: string): Promise<{
3
+ title: string;
4
+ markdown: string;
5
+ links: string[];
6
+ structuredData?: Record<string, unknown> | null;
7
+ statusCode: number;
8
+ contentHash: string;
9
+ etag?: string;
10
+ lastModified?: string;
11
+ crawledAt: string | Date;
12
+ expiresAt: string | Date;
13
+ } | null | undefined>;
14
+ upsertCrawledPage(entry: Record<string, unknown>): Promise<unknown>;
15
+ getCrawledSite(cacheKeyHash: string): Promise<{
16
+ links: string[];
17
+ source: string;
18
+ pagesCrawled: number;
19
+ crawledAt: string | Date;
20
+ expiresAt: string | Date;
21
+ } | null | undefined>;
22
+ upsertCrawledSite(entry: Record<string, unknown>): Promise<unknown>;
23
+ }
24
+ /**
25
+ * Registers an external L3 cache database store (e.g., Supabase Postgres in webcrawl.app cloud)
26
+ * when the engine is consumed as an installed npm package (`webcrawl/engine/cache`).
27
+ */
28
+ export declare function registerExternalCacheDb(db: ExternalCacheDb | null): void;
29
+ export interface CacheEntry {
30
+ title: string;
31
+ markdown: string;
32
+ links: string[];
33
+ structuredData?: Record<string, unknown> | null;
34
+ statusCode: number;
35
+ contentHash: string;
36
+ etag?: string;
37
+ lastModified?: string;
38
+ cacheLayer?: "memory" | "disk" | "postgres";
39
+ cachedAt: number;
40
+ expiresAt: number;
41
+ }
42
+ export interface MapCacheEntry {
43
+ links: string[];
44
+ source: string;
45
+ pagesCrawled: number;
46
+ cacheLayer?: "memory" | "disk" | "postgres";
47
+ cachedAt: number;
48
+ expiresAt: number;
49
+ }
50
+ export declare const CACHE_TTL_MS: number;
51
+ export declare function sha256(content: string): string;
52
+ export declare function normalizeCacheUrl(rawUrl: string): {
53
+ normalizedUrl: string;
54
+ domain: string;
55
+ };
56
+ export declare function clearLocalCacheForTests(): void;
57
+ export declare function getCachedPage(url: string, retainImages: string): CacheEntry | undefined;
58
+ /**
59
+ * 3-tier read-through lookup: L1 Memory -> L2 /tmp Disk -> L3 Postgres `crawled_pages`.
60
+ * Promotes L3 Postgres hits back into L1 and L2 so repeat requests never re-crawl the target website.
61
+ */
62
+ export declare function getCachedPageAsync(url: string, retainImages: string): Promise<CacheEntry | undefined>;
63
+ export declare function setCachedPage(url: string, retainImages: string, entry: Omit<CacheEntry, "expiresAt" | "cachedAt">, ttlMs?: number): void;
64
+ export declare function getCachedMap(cacheKey: string): MapCacheEntry | undefined;
65
+ /**
66
+ * 3-tier read-through lookup for website maps/crawls: L1 Memory -> L2 Disk -> L3 Postgres `crawled_sites`.
67
+ */
68
+ export declare function getCachedMapAsync(cacheKey: string): Promise<MapCacheEntry | undefined>;
69
+ export declare function setCachedMap(cacheKey: string, entry: Omit<MapCacheEntry, "cachedAt" | "expiresAt">, ttlMs?: number, rootUrl?: string): void;
70
+ export {};
@@ -0,0 +1,297 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ let cachedDbPromise = null;
5
+ /**
6
+ * Registers an external L3 cache database store (e.g., Supabase Postgres in webcrawl.app cloud)
7
+ * when the engine is consumed as an installed npm package (`webcrawl/engine/cache`).
8
+ */
9
+ export function registerExternalCacheDb(db) {
10
+ cachedDbPromise = Promise.resolve(db);
11
+ }
12
+ function getOptionalDb() {
13
+ if (!cachedDbPromise) {
14
+ const dbModulePath = "../db/index.js";
15
+ cachedDbPromise = import(/* @vite-ignore */ dbModulePath)
16
+ .then((mod) => mod?.db ?? null)
17
+ .catch(() => null);
18
+ }
19
+ return cachedDbPromise;
20
+ }
21
+ // 24-hour cache (L1 in-memory + L2 /tmp disk + L3 Postgres shared URL/website store)
22
+ export const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
23
+ const MAX_CACHE_ENTRIES = 2500;
24
+ const TMP_CACHE_DIR = "/tmp/webcrawl-cache-v1";
25
+ const pageCache = new Map();
26
+ const mapCache = new Map();
27
+ try {
28
+ fs.mkdirSync(TMP_CACHE_DIR, { recursive: true });
29
+ }
30
+ catch {
31
+ // ignore if read-only filesystem
32
+ }
33
+ export function sha256(content) {
34
+ return crypto.createHash("sha256").update(content).digest("hex");
35
+ }
36
+ export function normalizeCacheUrl(rawUrl) {
37
+ try {
38
+ const u = new URL(rawUrl.trim());
39
+ u.hash = "";
40
+ for (const key of Array.from(u.searchParams.keys())) {
41
+ if (/^(utm_|fbclid|gclid|msclkid|_ga|_gl|ref$)/i.test(key)) {
42
+ u.searchParams.delete(key);
43
+ }
44
+ }
45
+ const normalizedUrl = u.toString().replace(/\/$/, "") || u.origin;
46
+ const domain = u.hostname.toLowerCase().replace(/^www\./, "");
47
+ return { normalizedUrl, domain };
48
+ }
49
+ catch {
50
+ return {
51
+ normalizedUrl: rawUrl.trim(),
52
+ domain: "unknown",
53
+ };
54
+ }
55
+ }
56
+ export function clearLocalCacheForTests() {
57
+ pageCache.clear();
58
+ mapCache.clear();
59
+ try {
60
+ if (fs.existsSync(TMP_CACHE_DIR)) {
61
+ for (const f of fs.readdirSync(TMP_CACHE_DIR)) {
62
+ try {
63
+ fs.unlinkSync(path.join(TMP_CACHE_DIR, f));
64
+ }
65
+ catch {
66
+ // ignore
67
+ }
68
+ }
69
+ }
70
+ }
71
+ catch {
72
+ // ignore
73
+ }
74
+ }
75
+ export function getCachedPage(url, retainImages) {
76
+ const { normalizedUrl } = normalizeCacheUrl(url);
77
+ const key = `${normalizedUrl}::${retainImages}`;
78
+ const entry = pageCache.get(key);
79
+ if (entry) {
80
+ if (Date.now() > entry.expiresAt) {
81
+ pageCache.delete(key);
82
+ }
83
+ else {
84
+ return { ...entry, cacheLayer: "memory" };
85
+ }
86
+ }
87
+ // Check L2 /tmp disk cache for 24-hour persistence across warm/cold workers
88
+ try {
89
+ const diskPath = path.join(TMP_CACHE_DIR, `page_${sha256(key)}.json`);
90
+ if (fs.existsSync(diskPath)) {
91
+ const parsed = JSON.parse(fs.readFileSync(diskPath, "utf8"));
92
+ if (Date.now() <= parsed.expiresAt) {
93
+ pageCache.set(key, parsed);
94
+ return { ...parsed, cacheLayer: "disk" };
95
+ }
96
+ fs.unlinkSync(diskPath);
97
+ }
98
+ }
99
+ catch {
100
+ // ignore disk read errors
101
+ }
102
+ return undefined;
103
+ }
104
+ /**
105
+ * 3-tier read-through lookup: L1 Memory -> L2 /tmp Disk -> L3 Postgres `crawled_pages`.
106
+ * Promotes L3 Postgres hits back into L1 and L2 so repeat requests never re-crawl the target website.
107
+ */
108
+ export async function getCachedPageAsync(url, retainImages) {
109
+ const localHit = getCachedPage(url, retainImages);
110
+ if (localHit) {
111
+ return localHit;
112
+ }
113
+ const { normalizedUrl } = normalizeCacheUrl(url);
114
+ const key = `${normalizedUrl}::${retainImages}`;
115
+ const urlHash = sha256(key);
116
+ try {
117
+ const db = await getOptionalDb();
118
+ const pgHit = await db?.getCrawledPage(urlHash);
119
+ if (pgHit) {
120
+ const cachedAt = new Date(pgHit.crawledAt).getTime();
121
+ const expiresAt = new Date(pgHit.expiresAt).getTime();
122
+ if (expiresAt > Date.now()) {
123
+ const promoted = {
124
+ title: pgHit.title,
125
+ markdown: pgHit.markdown,
126
+ links: pgHit.links,
127
+ structuredData: pgHit.structuredData ?? null,
128
+ statusCode: pgHit.statusCode,
129
+ contentHash: pgHit.contentHash,
130
+ etag: pgHit.etag,
131
+ lastModified: pgHit.lastModified,
132
+ cacheLayer: "postgres",
133
+ cachedAt,
134
+ expiresAt,
135
+ };
136
+ pageCache.set(key, promoted);
137
+ try {
138
+ const diskPath = path.join(TMP_CACHE_DIR, `page_${urlHash}.json`);
139
+ fs.writeFileSync(diskPath, JSON.stringify(promoted));
140
+ }
141
+ catch {
142
+ // ignore
143
+ }
144
+ return promoted;
145
+ }
146
+ }
147
+ }
148
+ catch {
149
+ // ignore DB lookup errors
150
+ }
151
+ return undefined;
152
+ }
153
+ export function setCachedPage(url, retainImages, entry, ttlMs = CACHE_TTL_MS) {
154
+ const { normalizedUrl, domain } = normalizeCacheUrl(url);
155
+ const key = `${normalizedUrl}::${retainImages}`;
156
+ const urlHash = sha256(key);
157
+ if (pageCache.size >= MAX_CACHE_ENTRIES) {
158
+ const oldestKey = pageCache.keys().next().value;
159
+ if (oldestKey) {
160
+ pageCache.delete(oldestKey);
161
+ }
162
+ }
163
+ const now = Date.now();
164
+ const fullEntry = {
165
+ ...entry,
166
+ cacheLayer: "memory",
167
+ cachedAt: now,
168
+ expiresAt: now + ttlMs,
169
+ };
170
+ pageCache.set(key, fullEntry);
171
+ try {
172
+ const diskPath = path.join(TMP_CACHE_DIR, `page_${urlHash}.json`);
173
+ fs.writeFileSync(diskPath, JSON.stringify(fullEntry));
174
+ }
175
+ catch {
176
+ // ignore disk write errors
177
+ }
178
+ // Write-through to L3 Postgres `crawled_pages` store (when available)
179
+ void getOptionalDb()
180
+ .then((db) => db?.upsertCrawledPage({
181
+ urlHash,
182
+ normalizedUrl,
183
+ domain,
184
+ title: entry.title,
185
+ markdown: entry.markdown,
186
+ links: entry.links || [],
187
+ structuredData: entry.structuredData ?? null,
188
+ statusCode: entry.statusCode,
189
+ contentHash: entry.contentHash,
190
+ etag: entry.etag,
191
+ lastModified: entry.lastModified,
192
+ retainImages,
193
+ fetchCount: 1,
194
+ crawledAt: new Date(now).toISOString(),
195
+ expiresAt: new Date(now + ttlMs).toISOString(),
196
+ }))
197
+ .catch(() => { });
198
+ }
199
+ export function getCachedMap(cacheKey) {
200
+ const entry = mapCache.get(cacheKey);
201
+ if (entry) {
202
+ if (Date.now() > entry.expiresAt) {
203
+ mapCache.delete(cacheKey);
204
+ }
205
+ else {
206
+ return { ...entry, cacheLayer: "memory" };
207
+ }
208
+ }
209
+ try {
210
+ const diskPath = path.join(TMP_CACHE_DIR, `map_${sha256(cacheKey)}.json`);
211
+ if (fs.existsSync(diskPath)) {
212
+ const parsed = JSON.parse(fs.readFileSync(diskPath, "utf8"));
213
+ if (Date.now() <= parsed.expiresAt) {
214
+ mapCache.set(cacheKey, parsed);
215
+ return { ...parsed, cacheLayer: "disk" };
216
+ }
217
+ fs.unlinkSync(diskPath);
218
+ }
219
+ }
220
+ catch {
221
+ // ignore
222
+ }
223
+ return undefined;
224
+ }
225
+ /**
226
+ * 3-tier read-through lookup for website maps/crawls: L1 Memory -> L2 Disk -> L3 Postgres `crawled_sites`.
227
+ */
228
+ export async function getCachedMapAsync(cacheKey) {
229
+ const localHit = getCachedMap(cacheKey);
230
+ if (localHit) {
231
+ return localHit;
232
+ }
233
+ const cacheKeyHash = sha256(cacheKey);
234
+ try {
235
+ const db = await getOptionalDb();
236
+ const pgHit = await db?.getCrawledSite(cacheKeyHash);
237
+ if (pgHit) {
238
+ const cachedAt = new Date(pgHit.crawledAt).getTime();
239
+ const expiresAt = new Date(pgHit.expiresAt).getTime();
240
+ if (expiresAt > Date.now()) {
241
+ const promoted = {
242
+ links: pgHit.links,
243
+ source: pgHit.source,
244
+ pagesCrawled: pgHit.pagesCrawled,
245
+ cacheLayer: "postgres",
246
+ cachedAt,
247
+ expiresAt,
248
+ };
249
+ mapCache.set(cacheKey, promoted);
250
+ try {
251
+ const diskPath = path.join(TMP_CACHE_DIR, `map_${cacheKeyHash}.json`);
252
+ fs.writeFileSync(diskPath, JSON.stringify(promoted));
253
+ }
254
+ catch {
255
+ // ignore
256
+ }
257
+ return promoted;
258
+ }
259
+ }
260
+ }
261
+ catch {
262
+ // ignore
263
+ }
264
+ return undefined;
265
+ }
266
+ export function setCachedMap(cacheKey, entry, ttlMs = CACHE_TTL_MS, rootUrl) {
267
+ const now = Date.now();
268
+ const cacheKeyHash = sha256(cacheKey);
269
+ const fullEntry = {
270
+ ...entry,
271
+ cacheLayer: "memory",
272
+ cachedAt: now,
273
+ expiresAt: now + ttlMs,
274
+ };
275
+ mapCache.set(cacheKey, fullEntry);
276
+ try {
277
+ const diskPath = path.join(TMP_CACHE_DIR, `map_${cacheKeyHash}.json`);
278
+ fs.writeFileSync(diskPath, JSON.stringify(fullEntry));
279
+ }
280
+ catch {
281
+ // ignore
282
+ }
283
+ const rawRoot = rootUrl || cacheKey.split("::")[0] || "";
284
+ const { normalizedUrl, domain } = normalizeCacheUrl(rawRoot);
285
+ void getOptionalDb()
286
+ .then((db) => db?.upsertCrawledSite({
287
+ cacheKeyHash,
288
+ rootUrl: normalizedUrl,
289
+ domain,
290
+ links: entry.links || [],
291
+ source: entry.source,
292
+ pagesCrawled: entry.pagesCrawled,
293
+ crawledAt: new Date(now).toISOString(),
294
+ expiresAt: new Date(now + ttlMs).toISOString(),
295
+ }))
296
+ .catch(() => { });
297
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Crawl politeness helpers: robots.txt rules, adaptive concurrency (AIMD) and retries.
3
+ * Pure and dependency-free so they are easy to test.
4
+ */
5
+ export interface RobotsRules {
6
+ allows(url: string): boolean;
7
+ /** Crawl-delay in ms for our agent (or `*`), 0 when unset. */
8
+ crawlDelayMs: number;
9
+ }
10
+ /** Parses robots.txt. Our own group wins over `*`; longest matching rule wins; Allow beats Disallow on ties. */
11
+ export declare function parseRobots(text: string | null | undefined): RobotsRules;
12
+ /** Additive-increase / multiplicative-decrease concurrency controller. */
13
+ export declare class AdaptiveConcurrency {
14
+ private readonly min;
15
+ private readonly max;
16
+ private target;
17
+ constructor(min?: number, max?: number, initial?: number);
18
+ get current(): number;
19
+ /** Feed the outcome of a finished wave. */
20
+ record(outcome: {
21
+ ok: number;
22
+ failed: number;
23
+ throttled: boolean;
24
+ }): number;
25
+ }
26
+ export declare const sleep: (ms: number) => Promise<void>;
27
+ export declare function backoffDelayMs(attempt: number, baseMs?: number, capMs?: number, rand?: () => number): number;
28
+ export declare function isRetryableStatus(status: number): boolean;
29
+ /** Retries transient failures (network errors, 408/425/429/5xx) with jittered exponential backoff. */
30
+ export declare function withRetries<T extends {
31
+ status: number;
32
+ }>(run: () => Promise<T>, opts?: {
33
+ retries?: number;
34
+ baseMs?: number;
35
+ sleepFn?: (ms: number) => Promise<void>;
36
+ }): Promise<T>;