@crawlith/core 0.1.0

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 (201) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/analysis/analyze.d.ts +70 -0
  3. package/dist/analysis/analyze.js +436 -0
  4. package/dist/analysis/content.d.ts +12 -0
  5. package/dist/analysis/content.js +33 -0
  6. package/dist/analysis/images.d.ts +6 -0
  7. package/dist/analysis/images.js +18 -0
  8. package/dist/analysis/links.d.ts +7 -0
  9. package/dist/analysis/links.js +30 -0
  10. package/dist/analysis/scoring.d.ts +9 -0
  11. package/dist/analysis/scoring.js +42 -0
  12. package/dist/analysis/seo.d.ts +15 -0
  13. package/dist/analysis/seo.js +64 -0
  14. package/dist/analysis/structuredData.d.ts +6 -0
  15. package/dist/analysis/structuredData.js +51 -0
  16. package/dist/audit/dns.d.ts +2 -0
  17. package/dist/audit/dns.js +42 -0
  18. package/dist/audit/headers.d.ts +2 -0
  19. package/dist/audit/headers.js +95 -0
  20. package/dist/audit/index.d.ts +2 -0
  21. package/dist/audit/index.js +50 -0
  22. package/dist/audit/scoring.d.ts +14 -0
  23. package/dist/audit/scoring.js +214 -0
  24. package/dist/audit/transport.d.ts +6 -0
  25. package/dist/audit/transport.js +207 -0
  26. package/dist/audit/types.d.ts +88 -0
  27. package/dist/audit/types.js +1 -0
  28. package/dist/core/network/proxyAdapter.d.ts +6 -0
  29. package/dist/core/network/proxyAdapter.js +19 -0
  30. package/dist/core/network/rateLimiter.d.ts +6 -0
  31. package/dist/core/network/rateLimiter.js +31 -0
  32. package/dist/core/network/redirectController.d.ts +13 -0
  33. package/dist/core/network/redirectController.js +41 -0
  34. package/dist/core/network/responseLimiter.d.ts +4 -0
  35. package/dist/core/network/responseLimiter.js +26 -0
  36. package/dist/core/network/retryPolicy.d.ts +10 -0
  37. package/dist/core/network/retryPolicy.js +41 -0
  38. package/dist/core/scope/domainFilter.d.ts +11 -0
  39. package/dist/core/scope/domainFilter.js +40 -0
  40. package/dist/core/scope/scopeManager.d.ts +14 -0
  41. package/dist/core/scope/scopeManager.js +39 -0
  42. package/dist/core/scope/subdomainPolicy.d.ts +6 -0
  43. package/dist/core/scope/subdomainPolicy.js +35 -0
  44. package/dist/core/security/ipGuard.d.ts +11 -0
  45. package/dist/core/security/ipGuard.js +84 -0
  46. package/dist/crawler/crawl.d.ts +22 -0
  47. package/dist/crawler/crawl.js +336 -0
  48. package/dist/crawler/extract.d.ts +5 -0
  49. package/dist/crawler/extract.js +33 -0
  50. package/dist/crawler/fetcher.d.ts +40 -0
  51. package/dist/crawler/fetcher.js +161 -0
  52. package/dist/crawler/metricsRunner.d.ts +1 -0
  53. package/dist/crawler/metricsRunner.js +108 -0
  54. package/dist/crawler/normalize.d.ts +7 -0
  55. package/dist/crawler/normalize.js +88 -0
  56. package/dist/crawler/parser.d.ts +22 -0
  57. package/dist/crawler/parser.js +158 -0
  58. package/dist/crawler/sitemap.d.ts +8 -0
  59. package/dist/crawler/sitemap.js +70 -0
  60. package/dist/crawler/trap.d.ts +24 -0
  61. package/dist/crawler/trap.js +78 -0
  62. package/dist/db/graphLoader.d.ts +2 -0
  63. package/dist/db/graphLoader.js +96 -0
  64. package/dist/db/index.d.ts +4 -0
  65. package/dist/db/index.js +61 -0
  66. package/dist/db/repositories/EdgeRepository.d.ts +16 -0
  67. package/dist/db/repositories/EdgeRepository.js +17 -0
  68. package/dist/db/repositories/MetricsRepository.d.ts +26 -0
  69. package/dist/db/repositories/MetricsRepository.js +27 -0
  70. package/dist/db/repositories/PageRepository.d.ts +47 -0
  71. package/dist/db/repositories/PageRepository.js +93 -0
  72. package/dist/db/repositories/SiteRepository.d.ts +15 -0
  73. package/dist/db/repositories/SiteRepository.js +22 -0
  74. package/dist/db/repositories/SnapshotRepository.d.ts +22 -0
  75. package/dist/db/repositories/SnapshotRepository.js +55 -0
  76. package/dist/db/schema.d.ts +2 -0
  77. package/dist/db/schema.js +169 -0
  78. package/dist/diff/compare.d.ts +26 -0
  79. package/dist/diff/compare.js +64 -0
  80. package/dist/graph/cluster.d.ts +6 -0
  81. package/dist/graph/cluster.js +173 -0
  82. package/dist/graph/duplicate.d.ts +10 -0
  83. package/dist/graph/duplicate.js +251 -0
  84. package/dist/graph/graph.d.ts +103 -0
  85. package/dist/graph/graph.js +106 -0
  86. package/dist/graph/metrics.d.ts +29 -0
  87. package/dist/graph/metrics.js +74 -0
  88. package/dist/graph/pagerank.d.ts +12 -0
  89. package/dist/graph/pagerank.js +102 -0
  90. package/dist/graph/simhash.d.ts +17 -0
  91. package/dist/graph/simhash.js +56 -0
  92. package/dist/index.d.ts +30 -0
  93. package/dist/index.js +30 -0
  94. package/dist/lock/hashKey.d.ts +1 -0
  95. package/dist/lock/hashKey.js +44 -0
  96. package/dist/lock/lockManager.d.ts +7 -0
  97. package/dist/lock/lockManager.js +112 -0
  98. package/dist/lock/pidCheck.d.ts +1 -0
  99. package/dist/lock/pidCheck.js +14 -0
  100. package/dist/report/html.d.ts +2 -0
  101. package/dist/report/html.js +223 -0
  102. package/dist/report/sitegraphExport.d.ts +3 -0
  103. package/dist/report/sitegraphExport.js +52 -0
  104. package/dist/report/sitegraph_template.d.ts +1 -0
  105. package/dist/report/sitegraph_template.js +630 -0
  106. package/dist/scoring/hits.d.ts +9 -0
  107. package/dist/scoring/hits.js +111 -0
  108. package/dist/scoring/orphanSeverity.d.ts +39 -0
  109. package/dist/scoring/orphanSeverity.js +125 -0
  110. package/dist/utils/version.d.ts +2 -0
  111. package/dist/utils/version.js +15 -0
  112. package/package.json +33 -0
  113. package/src/analysis/analyze.ts +548 -0
  114. package/src/analysis/content.ts +62 -0
  115. package/src/analysis/images.ts +28 -0
  116. package/src/analysis/links.ts +41 -0
  117. package/src/analysis/scoring.ts +59 -0
  118. package/src/analysis/seo.ts +82 -0
  119. package/src/analysis/structuredData.ts +62 -0
  120. package/src/audit/dns.ts +49 -0
  121. package/src/audit/headers.ts +98 -0
  122. package/src/audit/index.ts +66 -0
  123. package/src/audit/scoring.ts +232 -0
  124. package/src/audit/transport.ts +258 -0
  125. package/src/audit/types.ts +102 -0
  126. package/src/core/network/proxyAdapter.ts +21 -0
  127. package/src/core/network/rateLimiter.ts +39 -0
  128. package/src/core/network/redirectController.ts +47 -0
  129. package/src/core/network/responseLimiter.ts +34 -0
  130. package/src/core/network/retryPolicy.ts +57 -0
  131. package/src/core/scope/domainFilter.ts +45 -0
  132. package/src/core/scope/scopeManager.ts +52 -0
  133. package/src/core/scope/subdomainPolicy.ts +39 -0
  134. package/src/core/security/ipGuard.ts +92 -0
  135. package/src/crawler/crawl.ts +382 -0
  136. package/src/crawler/extract.ts +34 -0
  137. package/src/crawler/fetcher.ts +233 -0
  138. package/src/crawler/metricsRunner.ts +124 -0
  139. package/src/crawler/normalize.ts +108 -0
  140. package/src/crawler/parser.ts +190 -0
  141. package/src/crawler/sitemap.ts +73 -0
  142. package/src/crawler/trap.ts +96 -0
  143. package/src/db/graphLoader.ts +105 -0
  144. package/src/db/index.ts +70 -0
  145. package/src/db/repositories/EdgeRepository.ts +29 -0
  146. package/src/db/repositories/MetricsRepository.ts +49 -0
  147. package/src/db/repositories/PageRepository.ts +128 -0
  148. package/src/db/repositories/SiteRepository.ts +32 -0
  149. package/src/db/repositories/SnapshotRepository.ts +74 -0
  150. package/src/db/schema.ts +177 -0
  151. package/src/diff/compare.ts +84 -0
  152. package/src/graph/cluster.ts +192 -0
  153. package/src/graph/duplicate.ts +286 -0
  154. package/src/graph/graph.ts +172 -0
  155. package/src/graph/metrics.ts +110 -0
  156. package/src/graph/pagerank.ts +125 -0
  157. package/src/graph/simhash.ts +61 -0
  158. package/src/index.ts +30 -0
  159. package/src/lock/hashKey.ts +51 -0
  160. package/src/lock/lockManager.ts +124 -0
  161. package/src/lock/pidCheck.ts +13 -0
  162. package/src/report/html.ts +227 -0
  163. package/src/report/sitegraphExport.ts +58 -0
  164. package/src/report/sitegraph_template.ts +630 -0
  165. package/src/scoring/hits.ts +131 -0
  166. package/src/scoring/orphanSeverity.ts +176 -0
  167. package/src/utils/version.ts +18 -0
  168. package/tests/__snapshots__/orphanSeverity.test.ts.snap +49 -0
  169. package/tests/analysis.unit.test.ts +98 -0
  170. package/tests/analyze.integration.test.ts +98 -0
  171. package/tests/audit/dns.test.ts +31 -0
  172. package/tests/audit/headers.test.ts +45 -0
  173. package/tests/audit/scoring.test.ts +133 -0
  174. package/tests/audit/security.test.ts +12 -0
  175. package/tests/audit/transport.test.ts +112 -0
  176. package/tests/clustering.test.ts +118 -0
  177. package/tests/crawler.test.ts +358 -0
  178. package/tests/db.test.ts +159 -0
  179. package/tests/diff.test.ts +67 -0
  180. package/tests/duplicate.test.ts +110 -0
  181. package/tests/fetcher.test.ts +106 -0
  182. package/tests/fetcher_safety.test.ts +85 -0
  183. package/tests/fixtures/analyze-crawl.json +26 -0
  184. package/tests/hits.test.ts +134 -0
  185. package/tests/html_report.test.ts +58 -0
  186. package/tests/lock/lockManager.test.ts +138 -0
  187. package/tests/metrics.test.ts +196 -0
  188. package/tests/normalize.test.ts +101 -0
  189. package/tests/orphanSeverity.test.ts +160 -0
  190. package/tests/pagerank.test.ts +98 -0
  191. package/tests/parser.test.ts +117 -0
  192. package/tests/proxy_safety.test.ts +57 -0
  193. package/tests/redirect_safety.test.ts +73 -0
  194. package/tests/safety.test.ts +114 -0
  195. package/tests/scope.test.ts +66 -0
  196. package/tests/scoring.test.ts +59 -0
  197. package/tests/sitemap.test.ts +88 -0
  198. package/tests/soft404.test.ts +41 -0
  199. package/tests/trap.test.ts +39 -0
  200. package/tests/visualization_data.test.ts +46 -0
  201. package/tsconfig.json +11 -0
@@ -0,0 +1,233 @@
1
+ import { request } from 'undici';
2
+ import { IPGuard } from '../core/security/ipGuard.js';
3
+ import { RateLimiter } from '../core/network/rateLimiter.js';
4
+ import { RetryPolicy } from '../core/network/retryPolicy.js';
5
+ import { ResponseLimiter } from '../core/network/responseLimiter.js';
6
+ import { RedirectController } from '../core/network/redirectController.js';
7
+ import { ProxyAdapter } from '../core/network/proxyAdapter.js';
8
+ import { ScopeManager } from '../core/scope/scopeManager.js';
9
+ import { version } from '../utils/version.js';
10
+
11
+ export interface RedirectStep {
12
+ url: string;
13
+ status: number;
14
+ target: string;
15
+ }
16
+
17
+ export interface FetchResult {
18
+ status: number
19
+ | 'blocked_internal_ip'
20
+ | 'blocked_by_domain_filter'
21
+ | 'blocked_subdomain'
22
+ | 'oversized'
23
+ | 'failed_after_retries'
24
+ | 'network_error'
25
+ | 'redirect_limit_exceeded'
26
+ | 'redirect_loop'
27
+ | 'proxy_connection_failed';
28
+ headers: Record<string, string | string[] | undefined>;
29
+ body: string;
30
+ redirectChain: RedirectStep[];
31
+ etag: string | null;
32
+ lastModified: string | null;
33
+ finalUrl: string;
34
+ retries?: number;
35
+ bytesReceived?: number;
36
+ }
37
+
38
+ export interface FetchOptions {
39
+ etag?: string;
40
+ lastModified?: string;
41
+ rate?: number;
42
+ maxBytes?: number;
43
+ crawlDelay?: number;
44
+ }
45
+
46
+ export class Fetcher {
47
+ private userAgent = 'crawlith/1.0';
48
+ private rateLimiter: RateLimiter;
49
+ private proxyAdapter: ProxyAdapter;
50
+ private scopeManager?: ScopeManager;
51
+ private maxRedirects: number;
52
+
53
+ constructor(options: {
54
+ rate?: number;
55
+ proxyUrl?: string;
56
+ scopeManager?: ScopeManager;
57
+ maxRedirects?: number;
58
+ userAgent?: string;
59
+ } = {}) {
60
+ this.rateLimiter = new RateLimiter(options.rate || 2);
61
+ this.proxyAdapter = new ProxyAdapter(options.proxyUrl);
62
+ this.scopeManager = options.scopeManager;
63
+ this.maxRedirects = Math.min(options.maxRedirects ?? 2, 11);
64
+ this.userAgent = options.userAgent || `crawlith/${version}`;
65
+ }
66
+
67
+ async fetch(url: string, options: FetchOptions = {}): Promise<FetchResult> {
68
+ const maxBytes = options.maxBytes || 2000000;
69
+ const redirectChain: RedirectStep[] = [];
70
+ const redirectController = new RedirectController(this.maxRedirects, url);
71
+
72
+ let currentUrl = url;
73
+ let totalRetries = 0;
74
+
75
+ // Use a while(true) and explicit return/continue to handle redirects
76
+ while (true) {
77
+ const urlObj = new URL(currentUrl);
78
+
79
+ // 1. SSRF Guard
80
+ const isSafe = await IPGuard.validateHost(urlObj.hostname);
81
+ if (!isSafe) {
82
+ return this.errorResult('blocked_internal_ip', currentUrl, redirectChain, totalRetries);
83
+ }
84
+
85
+ // 2. Scope Validation (Domain & Subdomain)
86
+ if (this.scopeManager) {
87
+ const eligibility = this.scopeManager.isUrlEligible(currentUrl);
88
+ if (eligibility !== 'allowed') {
89
+ return this.errorResult(eligibility, currentUrl, redirectChain, totalRetries);
90
+ }
91
+ }
92
+
93
+ // 3. Rate Limiting
94
+ await this.rateLimiter.waitForToken(urlObj.hostname, options.crawlDelay);
95
+
96
+ try {
97
+ // 4. Retry Strategy
98
+ const result = await RetryPolicy.execute(
99
+ async (attempt) => {
100
+ if (attempt > 0) totalRetries++;
101
+
102
+ const headers: Record<string, string> = {
103
+ 'User-Agent': this.userAgent
104
+ };
105
+
106
+ // Conditional GET only for the FIRST request in a chain
107
+ if (redirectChain.length === 0) {
108
+ if (options.etag) headers['If-None-Match'] = options.etag;
109
+ if (options.lastModified) headers['If-Modified-Since'] = options.lastModified;
110
+ }
111
+
112
+ const res = await request(currentUrl, {
113
+ method: 'GET',
114
+ headers,
115
+ maxRedirections: 0,
116
+ dispatcher: this.proxyAdapter.dispatcher,
117
+ headersTimeout: 10000,
118
+ bodyTimeout: 10000
119
+ });
120
+
121
+ if (RetryPolicy.isRetryableStatus(res.statusCode)) {
122
+ await res.body.dump();
123
+ throw new Error(`Status ${res.statusCode}`);
124
+ }
125
+
126
+ return res;
127
+ },
128
+ (error) => RetryPolicy.isNetworkError(error) || error.message.startsWith('Status ')
129
+ );
130
+
131
+ const status = result.statusCode;
132
+ const resHeaders = result.headers;
133
+
134
+ const getHeader = (name: string): string | null => {
135
+ const val = resHeaders[name.toLowerCase()];
136
+ if (Array.isArray(val)) return val[0];
137
+ return (val as string) || null;
138
+ };
139
+
140
+ const etag = getHeader('etag');
141
+ const lastModified = getHeader('last-modified');
142
+
143
+ // Handle Redirects
144
+ if (status >= 300 && status < 400 && status !== 304) {
145
+ const location = getHeader('location');
146
+ if (location) {
147
+ let targetUrl: string;
148
+ try {
149
+ targetUrl = new URL(location, currentUrl).toString();
150
+ } catch (_e) {
151
+ // Bad redirect location, treat as final but maybe error?
152
+ const body = await ResponseLimiter.streamToString(result.body, maxBytes);
153
+ return { status, headers: resHeaders, body, redirectChain, etag: null, lastModified: null, finalUrl: currentUrl, retries: totalRetries };
154
+ }
155
+
156
+ const redirectError = redirectController.nextHop(targetUrl);
157
+ if (redirectError) {
158
+ await result.body.dump();
159
+ return this.errorResult(redirectError, currentUrl, redirectChain, totalRetries);
160
+ }
161
+
162
+ redirectChain.push({ url: currentUrl, status, target: targetUrl });
163
+ await result.body.dump();
164
+ currentUrl = targetUrl;
165
+ continue; // Next iteration for redirect target
166
+ }
167
+ }
168
+
169
+ // 5. Max Response Size (Streaming)
170
+ let bytesReceived = 0;
171
+ try {
172
+ const body = status === 304 ? '' : await ResponseLimiter.streamToString(
173
+ result.body,
174
+ maxBytes,
175
+ (bytes) => { bytesReceived = bytes; }
176
+ );
177
+
178
+ return {
179
+ status,
180
+ headers: resHeaders,
181
+ body,
182
+ redirectChain,
183
+ etag,
184
+ lastModified,
185
+ finalUrl: currentUrl,
186
+ retries: totalRetries,
187
+ bytesReceived
188
+ };
189
+ } catch (e: any) {
190
+ if (e.message === 'Oversized response') {
191
+ return {
192
+ status: 'oversized',
193
+ headers: resHeaders,
194
+ body: '',
195
+ redirectChain,
196
+ etag: null,
197
+ lastModified: null,
198
+ finalUrl: currentUrl,
199
+ retries: totalRetries,
200
+ bytesReceived
201
+ };
202
+ }
203
+ throw e;
204
+ }
205
+
206
+ } catch (error: any) {
207
+ // Map common network errors to specific statuses if needed
208
+ const isProxyError = error.message?.toLowerCase().includes('proxy') || error.code === 'ECONNREFUSED';
209
+ const finalStatus = isProxyError ? 'proxy_connection_failed' : 'network_error';
210
+
211
+ return this.errorResult(
212
+ totalRetries >= RetryPolicy.DEFAULT_CONFIG.maxRetries ? 'failed_after_retries' : finalStatus,
213
+ currentUrl,
214
+ redirectChain,
215
+ totalRetries
216
+ );
217
+ }
218
+ }
219
+ }
220
+
221
+ private errorResult(status: any, finalUrl: string, redirectChain: RedirectStep[], retries: number): FetchResult {
222
+ return {
223
+ status,
224
+ headers: {},
225
+ body: '',
226
+ redirectChain,
227
+ etag: null,
228
+ lastModified: null,
229
+ finalUrl,
230
+ retries
231
+ };
232
+ }
233
+ }
@@ -0,0 +1,124 @@
1
+ import { getDb } from '../db/index.js';
2
+ import { loadGraphFromSnapshot } from '../db/graphLoader.js';
3
+ import { MetricsRepository } from '../db/repositories/MetricsRepository.js';
4
+ import { SnapshotRepository } from '../db/repositories/SnapshotRepository.js';
5
+ import { PageRepository } from '../db/repositories/PageRepository.js';
6
+ import { computePageRank } from '../graph/pagerank.js';
7
+ import { calculateMetrics } from '../graph/metrics.js';
8
+ import { computeHITS } from '../scoring/hits.js';
9
+
10
+ export function runPostCrawlMetrics(snapshotId: number, maxDepth: number, limitReached: boolean = false) {
11
+ const db = getDb();
12
+ const metricsRepo = new MetricsRepository(db);
13
+ const snapshotRepo = new SnapshotRepository(db);
14
+ const pageRepo = new PageRepository(db);
15
+
16
+ const snapshot = snapshotRepo.getSnapshot(snapshotId);
17
+ if (!snapshot) {
18
+ console.error(`Snapshot ${snapshotId} not found`);
19
+ return;
20
+ }
21
+
22
+ console.log('Loading graph for metrics calculation...');
23
+ const graph = loadGraphFromSnapshot(snapshotId);
24
+
25
+ console.log('Computing PageRank...');
26
+ computePageRank(graph);
27
+
28
+ console.log('Computing HITS...');
29
+ computeHITS(graph);
30
+
31
+ console.log('Updating metrics in DB...');
32
+ const nodes = graph.getNodes();
33
+
34
+ const tx = db.transaction(() => {
35
+ for (const node of nodes) {
36
+ const pageId = pageRepo.getIdByUrl(snapshot.site_id, node.url);
37
+ if (!pageId) continue;
38
+
39
+ const existing = metricsRepo.getMetricsForPage(snapshotId, pageId);
40
+
41
+ metricsRepo.insertMetrics({
42
+ snapshot_id: snapshotId,
43
+ page_id: pageId,
44
+ authority_score: node.authorityScore ?? null,
45
+ hub_score: node.hubScore ?? null,
46
+ pagerank: node.pageRank ?? null,
47
+ pagerank_score: node.pageRankScore ?? null,
48
+ link_role: node.linkRole ?? null,
49
+ crawl_status: existing?.crawl_status ?? null,
50
+ word_count: existing?.word_count ?? null,
51
+ thin_content_score: existing?.thin_content_score ?? null,
52
+ external_link_ratio: existing?.external_link_ratio ?? null,
53
+ orphan_score: existing?.orphan_score ?? null,
54
+ duplicate_cluster_id: node.duplicateClusterId ?? null,
55
+ duplicate_type: node.duplicateType ?? null,
56
+ is_cluster_primary: node.isClusterPrimary ? 1 : 0
57
+ });
58
+
59
+ // Update page-level crawl trap data
60
+ if (node.crawlTrapFlag || node.redirectChain?.length || node.bytesReceived) {
61
+ pageRepo.upsertPage({
62
+ site_id: snapshot.site_id,
63
+ normalized_url: node.url,
64
+ last_seen_snapshot_id: snapshotId,
65
+ redirect_chain: node.redirectChain ? JSON.stringify(node.redirectChain) : null,
66
+ bytes_received: node.bytesReceived ?? null,
67
+ crawl_trap_flag: node.crawlTrapFlag ? 1 : 0,
68
+ crawl_trap_risk: node.crawlTrapRisk ?? null,
69
+ trap_type: node.trapType ?? null,
70
+ });
71
+ }
72
+ }
73
+
74
+ // Save duplicate clusters
75
+ if (graph.duplicateClusters.length > 0) {
76
+ const clusterStmt = db.prepare(`
77
+ INSERT OR REPLACE INTO duplicate_clusters (id, snapshot_id, type, size, representative, severity)
78
+ VALUES (?, ?, ?, ?, ?, ?)
79
+ `);
80
+ for (const cluster of graph.duplicateClusters) {
81
+ clusterStmt.run(cluster.id, snapshotId, cluster.type, cluster.size, cluster.representative, cluster.severity);
82
+ }
83
+ }
84
+
85
+ // Save content clusters
86
+ if (graph.contentClusters.length > 0) {
87
+ const contentStmt = db.prepare(`
88
+ INSERT OR REPLACE INTO content_clusters (id, snapshot_id, count, primary_url, risk, shared_path_prefix)
89
+ VALUES (?, ?, ?, ?, ?, ?)
90
+ `);
91
+ for (const cluster of graph.contentClusters) {
92
+ contentStmt.run(cluster.id, snapshotId, cluster.count, cluster.primaryUrl, cluster.risk, cluster.sharedPathPrefix ?? null);
93
+ }
94
+ }
95
+ });
96
+ tx();
97
+
98
+ console.log('Computing aggregate stats...');
99
+ const metrics = calculateMetrics(graph, maxDepth);
100
+
101
+ let totalScore = 0;
102
+ let totalWeight = 0;
103
+ for (const node of nodes) {
104
+ const score = node.authorityScore || node.pageRankScore || 0;
105
+ const depth = node.depth;
106
+ const weight = 1 / (depth + 1);
107
+ totalScore += score * weight;
108
+ totalWeight += weight;
109
+ }
110
+ const healthScore = totalWeight > 0 ? (totalScore / totalWeight) * 100 : 0;
111
+
112
+ const thinCountRow = db.prepare('SELECT count(*) as count FROM metrics WHERE snapshot_id = ? AND thin_content_score >= 70').get(snapshotId) as { count: number };
113
+
114
+ snapshotRepo.updateSnapshotStatus(snapshotId, 'completed', {
115
+ node_count: metrics.totalPages,
116
+ edge_count: metrics.totalEdges,
117
+ health_score: healthScore,
118
+ orphan_count: metrics.orphanPages.length,
119
+ thin_content_count: thinCountRow.count,
120
+ limit_reached: limitReached ? 1 : 0
121
+ });
122
+
123
+ console.log('Metrics calculation complete.');
124
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Normalizes a URL string based on specific rules.
3
+ */
4
+ export interface NormalizeOptions {
5
+ stripQuery?: boolean;
6
+ }
7
+
8
+ const TRACKING_PARAMS = new Set([
9
+ 'utm_source',
10
+ 'utm_medium',
11
+ 'utm_campaign',
12
+ 'utm_term',
13
+ 'utm_content',
14
+ 'fbclid',
15
+ 'gclid',
16
+ 'msclkid'
17
+ ]);
18
+
19
+ const SKIP_EXTENSIONS = new Set([
20
+ '.pdf', '.jpg', '.png', '.svg', '.webp', '.gif',
21
+ '.zip', '.xml', '.json', '.mp4'
22
+ ]);
23
+
24
+ export function normalizeUrl(input: string, base: string, options: NormalizeOptions = {}): string | null {
25
+ try {
26
+ // 1. Resolve absolute URL
27
+ let u: URL;
28
+ if (base) {
29
+ u = new URL(input, base);
30
+ } else {
31
+ u = new URL(input);
32
+ }
33
+
34
+ // 2. Allow only http/https
35
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') {
36
+ return null;
37
+ }
38
+
39
+ // 3. Lowercase hostname
40
+ u.hostname = u.hostname.toLowerCase();
41
+
42
+ // 4. Remove default ports
43
+ if ((u.protocol === 'http:' && u.port === '80') || (u.protocol === 'https:' && u.port === '443')) {
44
+ u.port = '';
45
+ }
46
+
47
+ // 5. Remove hash fragments
48
+ u.hash = '';
49
+
50
+ // 6. Query params handling
51
+ const params = new URLSearchParams(u.search);
52
+ const newParams = new URLSearchParams();
53
+
54
+ // Check if we should strip all query params
55
+ if (options.stripQuery) {
56
+ u.search = '';
57
+ } else {
58
+ // Filter tracking params
59
+ let hasParams = false;
60
+ for (const [key, value] of params) {
61
+ // Remove utm_* and other tracking params
62
+ if (key.startsWith('utm_') || TRACKING_PARAMS.has(key)) {
63
+ continue;
64
+ }
65
+ newParams.append(key, value);
66
+ hasParams = true;
67
+ }
68
+
69
+ // Sort for consistency
70
+ newParams.sort();
71
+
72
+ if (hasParams || newParams.toString()) {
73
+ u.search = newParams.toString();
74
+ } else {
75
+ u.search = '';
76
+ }
77
+ }
78
+
79
+ // 7. Normalize trailing slash
80
+ // 8. Collapse duplicate slashes in pathname
81
+ let pathname = u.pathname;
82
+
83
+ // Collapse duplicate slashes
84
+ pathname = pathname.replace(/\/+/g, '/');
85
+
86
+ // Remove trailing slash unless root
87
+ if (pathname.length > 1 && pathname.endsWith('/')) {
88
+ pathname = pathname.slice(0, -1);
89
+ }
90
+
91
+ u.pathname = pathname;
92
+
93
+ // 9. Skip non-HTML assets by extension
94
+ const lastDotIndex = u.pathname.lastIndexOf('.');
95
+ if (lastDotIndex !== -1) {
96
+ const ext = u.pathname.slice(lastDotIndex).toLowerCase();
97
+ if (SKIP_EXTENSIONS.has(ext)) {
98
+ return null;
99
+ }
100
+ }
101
+
102
+ // 10. Return final string
103
+ return u.toString();
104
+
105
+ } catch (_e) {
106
+ return null;
107
+ }
108
+ }
@@ -0,0 +1,190 @@
1
+ import * as cheerio from 'cheerio';
2
+ import crypto from 'node:crypto';
3
+ import { normalizeUrl } from './normalize.js';
4
+ import { SimHash } from '../graph/simhash.js';
5
+
6
+ export interface ParseLink {
7
+ url: string;
8
+ weight: number;
9
+ }
10
+
11
+ export interface ParseResult {
12
+ links: ParseLink[];
13
+ html: string;
14
+ canonical: string | null;
15
+ noindex: boolean;
16
+ nofollow: boolean;
17
+ contentHash: string;
18
+ simhash?: string;
19
+ uniqueTokenRatio?: number;
20
+ soft404Score: number;
21
+ soft404Signals: string[];
22
+ }
23
+
24
+ export class Parser {
25
+ /**
26
+ * Parses HTML content to extract metadata and links.
27
+ */
28
+ parse(html: string, baseUrl: string, status: number): ParseResult {
29
+ const $ = cheerio.load(html);
30
+
31
+ // 1. Robots Meta
32
+ let noindex = false;
33
+ let nofollow = false;
34
+ const robotsMeta = $('meta[name="robots"]').attr('content');
35
+ if (robotsMeta) {
36
+ const directives = robotsMeta.toLowerCase().split(',').map(s => s.trim());
37
+ if (directives.includes('noindex') || directives.includes('none')) noindex = true;
38
+ if (directives.includes('nofollow') || directives.includes('none')) nofollow = true;
39
+ }
40
+
41
+ // 2. Canonical
42
+ let canonical: string | null = null;
43
+ const canonicalLink = $('link[rel="canonical"]').attr('href');
44
+ if (canonicalLink) {
45
+ try {
46
+ // Resolve relative canonicals
47
+ const u = new URL(canonicalLink, baseUrl);
48
+ // Normalize minimally (remove default ports, lowercase host, etc)
49
+ // We don't strip query by default for canonical as it might be relevant
50
+ canonical = normalizeUrl(u.toString(), '', { stripQuery: false });
51
+ } catch (_e) {
52
+ // Invalid canonical URL, ignore
53
+ }
54
+ }
55
+
56
+ // 3. Links
57
+ const links = new Map<string, number>();
58
+ if (!nofollow) { // Don't extract links if nofollow is set
59
+ $('a').each((_, element) => {
60
+ const href = $(element).attr('href');
61
+ const rel = $(element).attr('rel');
62
+ const isNofollow = rel && rel.toLowerCase().includes('nofollow');
63
+
64
+ if (href && !isNofollow) {
65
+ try {
66
+ const absoluteUrl = new URL(href, baseUrl);
67
+ if (absoluteUrl.protocol === 'http:' || absoluteUrl.protocol === 'https:') {
68
+ absoluteUrl.hash = '';
69
+ const urlStr = absoluteUrl.toString();
70
+
71
+ // Calculate Weight
72
+ let weight = 1.0; // Default: Body
73
+
74
+ // Semantic Check
75
+ const $el = $(element);
76
+ if ($el.closest('nav').length > 0 || $el.closest('header').length > 0) {
77
+ weight = 0.7;
78
+ } else if ($el.closest('footer').length > 0) {
79
+ weight = 0.4;
80
+ } else {
81
+ // Secondary check: Common attributes
82
+ const parentText = ($el.parent().attr('class') || '') + ($el.parent().attr('id') || '');
83
+ const grandParentText = ($el.parent().parent().attr('class') || '') + ($el.parent().parent().attr('id') || '');
84
+ const combinedContext = (parentText + grandParentText).toLowerCase();
85
+
86
+ if (combinedContext.includes('nav') || combinedContext.includes('menu')) {
87
+ weight = 0.7;
88
+ } else if (combinedContext.includes('footer')) {
89
+ weight = 0.4;
90
+ }
91
+ }
92
+
93
+ // Store highest weight if multiple links to same URL
94
+ const currentMax = links.get(urlStr) || 0;
95
+ if (weight > currentMax) {
96
+ links.set(urlStr, weight);
97
+ }
98
+ }
99
+ } catch (_e) {
100
+ // Invalid URL
101
+ }
102
+ }
103
+ });
104
+ }
105
+
106
+ // 4. Content Hash (ignoring script/style/comments)
107
+ // Clone body to avoid modifying the loaded doc (though we don't reuse it)
108
+ // Actually cheerio load gives us a fresh instance.
109
+ $('script').remove();
110
+ $('style').remove();
111
+ $('noscript').remove();
112
+ $('iframe').remove();
113
+
114
+ const cleanText = $('body').text().replace(/\s+/g, ' ').trim();
115
+ const contentHash = crypto.createHash('sha256').update(cleanText).digest('hex');
116
+
117
+ // 4b. Simhash & Token calculation (limit to 50k chars for performance)
118
+ const limitedText = cleanText.substring(0, 50000).toLowerCase();
119
+ const tokens = limitedText.split(/\W+/).filter(t => t.length > 0);
120
+ const uniqueTokens = new Set(tokens);
121
+ const uniqueTokenRatio = tokens.length > 0 ? (uniqueTokens.size / tokens.length) : 0;
122
+ const simhash = SimHash.generate(tokens).toString();
123
+
124
+ // 5. Soft 404 Detection
125
+ let soft404Score = 0;
126
+ const soft404Signals: string[] = [];
127
+
128
+ if (status === 200) {
129
+ const title = $('title').text().toLowerCase();
130
+ const h1Text = $('h1').first().text().toLowerCase();
131
+ const bodyText = cleanText.toLowerCase();
132
+
133
+ const errorPatterns = ['404', 'not found', 'error', 'doesn\'t exist', 'unavailable', 'invalid'];
134
+
135
+ // Pattern checks
136
+ for (const pattern of errorPatterns) {
137
+ if (title.includes(pattern)) {
138
+ soft404Score += 0.4;
139
+ soft404Signals.push(`title_pattern_${pattern.replace(/\s+/g, '_')}`);
140
+ break;
141
+ }
142
+ }
143
+
144
+ for (const pattern of errorPatterns) {
145
+ if (h1Text.includes(pattern)) {
146
+ soft404Score += 0.3;
147
+ soft404Signals.push(`h1_pattern_${pattern.replace(/\s+/g, '_')}`);
148
+ break;
149
+ }
150
+ }
151
+
152
+ if (bodyText.includes('page not found') || bodyText.includes('404 error')) {
153
+ soft404Score += 0.2;
154
+ soft404Signals.push('body_error_phrase');
155
+ }
156
+
157
+ // Content length check (Word count approximation)
158
+ const words = cleanText.split(/\s+/).filter(w => w.length > 0);
159
+ if (words.length < 50) {
160
+ soft404Score += 0.3;
161
+ soft404Signals.push('very_low_word_count');
162
+ } else if (words.length < 150) {
163
+ soft404Score += 0.1;
164
+ soft404Signals.push('low_word_count');
165
+ }
166
+
167
+ // Link count check
168
+ if (links.size === 0) {
169
+ soft404Score += 0.2;
170
+ soft404Signals.push('no_outbound_links');
171
+ }
172
+
173
+ // Cap at 1.0
174
+ soft404Score = Math.min(1.0, soft404Score);
175
+ }
176
+
177
+ return {
178
+ links: Array.from(links.entries()).map(([url, weight]) => ({ url, weight })),
179
+ html: html, // pass raw HTML for analysis
180
+ canonical,
181
+ noindex,
182
+ nofollow,
183
+ contentHash,
184
+ simhash,
185
+ uniqueTokenRatio,
186
+ soft404Score,
187
+ soft404Signals
188
+ }
189
+ }
190
+ }