@crawlith/core 0.1.0 → 0.1.2

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 (238) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +70 -0
  3. package/dist/analysis/analysis_list.html +35 -0
  4. package/dist/analysis/analysis_page.html +123 -0
  5. package/dist/analysis/analyze.d.ts +40 -5
  6. package/dist/analysis/analyze.js +395 -347
  7. package/dist/analysis/clustering.d.ts +23 -0
  8. package/dist/analysis/clustering.js +206 -0
  9. package/dist/analysis/content.d.ts +1 -1
  10. package/dist/analysis/content.js +11 -5
  11. package/dist/analysis/duplicate.d.ts +34 -0
  12. package/dist/analysis/duplicate.js +305 -0
  13. package/dist/analysis/heading.d.ts +116 -0
  14. package/dist/analysis/heading.js +356 -0
  15. package/dist/analysis/images.d.ts +1 -1
  16. package/dist/analysis/images.js +6 -5
  17. package/dist/analysis/links.d.ts +1 -1
  18. package/dist/analysis/links.js +8 -8
  19. package/dist/{scoring/orphanSeverity.d.ts → analysis/orphan.d.ts} +12 -23
  20. package/dist/{scoring/orphanSeverity.js → analysis/orphan.js} +9 -3
  21. package/dist/analysis/scoring.js +11 -2
  22. package/dist/analysis/seo.d.ts +8 -4
  23. package/dist/analysis/seo.js +41 -30
  24. package/dist/analysis/soft404.d.ts +17 -0
  25. package/dist/analysis/soft404.js +62 -0
  26. package/dist/analysis/structuredData.d.ts +1 -1
  27. package/dist/analysis/structuredData.js +5 -4
  28. package/dist/analysis/templates.d.ts +2 -0
  29. package/dist/analysis/templates.js +7 -0
  30. package/dist/application/index.d.ts +2 -0
  31. package/dist/application/index.js +2 -0
  32. package/dist/application/usecase.d.ts +3 -0
  33. package/dist/application/usecase.js +1 -0
  34. package/dist/application/usecases.d.ts +114 -0
  35. package/dist/application/usecases.js +201 -0
  36. package/dist/audit/index.js +1 -1
  37. package/dist/audit/transport.d.ts +1 -1
  38. package/dist/audit/transport.js +5 -4
  39. package/dist/audit/types.d.ts +1 -0
  40. package/dist/constants.d.ts +17 -0
  41. package/dist/constants.js +23 -0
  42. package/dist/core/scope/scopeManager.js +3 -0
  43. package/dist/core/security/ipGuard.d.ts +11 -0
  44. package/dist/core/security/ipGuard.js +71 -3
  45. package/dist/crawler/crawl.d.ts +4 -22
  46. package/dist/crawler/crawl.js +4 -335
  47. package/dist/crawler/crawler.d.ts +87 -0
  48. package/dist/crawler/crawler.js +683 -0
  49. package/dist/crawler/extract.d.ts +4 -1
  50. package/dist/crawler/extract.js +7 -2
  51. package/dist/crawler/fetcher.d.ts +2 -1
  52. package/dist/crawler/fetcher.js +26 -11
  53. package/dist/crawler/metricsRunner.d.ts +23 -1
  54. package/dist/crawler/metricsRunner.js +202 -72
  55. package/dist/crawler/normalize.d.ts +41 -0
  56. package/dist/crawler/normalize.js +119 -3
  57. package/dist/crawler/parser.d.ts +1 -3
  58. package/dist/crawler/parser.js +2 -49
  59. package/dist/crawler/resolver.d.ts +11 -0
  60. package/dist/crawler/resolver.js +67 -0
  61. package/dist/crawler/sitemap.d.ts +6 -0
  62. package/dist/crawler/sitemap.js +27 -17
  63. package/dist/crawler/trap.d.ts +5 -1
  64. package/dist/crawler/trap.js +23 -2
  65. package/dist/db/CrawlithDB.d.ts +110 -0
  66. package/dist/db/CrawlithDB.js +500 -0
  67. package/dist/db/graphLoader.js +42 -30
  68. package/dist/db/index.d.ts +11 -0
  69. package/dist/db/index.js +41 -29
  70. package/dist/db/migrations.d.ts +2 -0
  71. package/dist/db/{schema.js → migrations.js} +90 -43
  72. package/dist/db/pluginRegistry.d.ts +9 -0
  73. package/dist/db/pluginRegistry.js +19 -0
  74. package/dist/db/repositories/EdgeRepository.d.ts +13 -0
  75. package/dist/db/repositories/EdgeRepository.js +20 -0
  76. package/dist/db/repositories/MetricsRepository.d.ts +16 -8
  77. package/dist/db/repositories/MetricsRepository.js +28 -7
  78. package/dist/db/repositories/PageRepository.d.ts +15 -2
  79. package/dist/db/repositories/PageRepository.js +169 -25
  80. package/dist/db/repositories/SiteRepository.d.ts +9 -0
  81. package/dist/db/repositories/SiteRepository.js +13 -0
  82. package/dist/db/repositories/SnapshotRepository.d.ts +14 -5
  83. package/dist/db/repositories/SnapshotRepository.js +64 -5
  84. package/dist/db/reset.d.ts +9 -0
  85. package/dist/db/reset.js +32 -0
  86. package/dist/db/statements.d.ts +12 -0
  87. package/dist/db/statements.js +40 -0
  88. package/dist/diff/compare.d.ts +0 -5
  89. package/dist/diff/compare.js +0 -12
  90. package/dist/diff/service.d.ts +16 -0
  91. package/dist/diff/service.js +41 -0
  92. package/dist/domain/index.d.ts +4 -0
  93. package/dist/domain/index.js +4 -0
  94. package/dist/events.d.ts +56 -0
  95. package/dist/events.js +1 -0
  96. package/dist/graph/graph.d.ts +36 -42
  97. package/dist/graph/graph.js +26 -17
  98. package/dist/graph/hits.d.ts +23 -0
  99. package/dist/graph/hits.js +111 -0
  100. package/dist/graph/metrics.d.ts +0 -4
  101. package/dist/graph/metrics.js +25 -9
  102. package/dist/graph/pagerank.d.ts +17 -4
  103. package/dist/graph/pagerank.js +126 -91
  104. package/dist/graph/simhash.d.ts +6 -0
  105. package/dist/graph/simhash.js +14 -0
  106. package/dist/index.d.ts +29 -8
  107. package/dist/index.js +29 -8
  108. package/dist/lock/hashKey.js +1 -1
  109. package/dist/lock/lockManager.d.ts +5 -1
  110. package/dist/lock/lockManager.js +38 -13
  111. package/dist/plugin-system/plugin-cli.d.ts +10 -0
  112. package/dist/plugin-system/plugin-cli.js +31 -0
  113. package/dist/plugin-system/plugin-config.d.ts +16 -0
  114. package/dist/plugin-system/plugin-config.js +36 -0
  115. package/dist/plugin-system/plugin-loader.d.ts +17 -0
  116. package/dist/plugin-system/plugin-loader.js +122 -0
  117. package/dist/plugin-system/plugin-registry.d.ts +25 -0
  118. package/dist/plugin-system/plugin-registry.js +167 -0
  119. package/dist/plugin-system/plugin-types.d.ts +205 -0
  120. package/dist/plugin-system/plugin-types.js +1 -0
  121. package/dist/ports/index.d.ts +9 -0
  122. package/dist/ports/index.js +1 -0
  123. package/{src/report/sitegraph_template.ts → dist/report/crawl.html} +330 -81
  124. package/dist/report/crawlExport.d.ts +3 -0
  125. package/dist/report/{sitegraphExport.js → crawlExport.js} +3 -3
  126. package/dist/report/crawl_template.d.ts +1 -0
  127. package/dist/report/crawl_template.js +7 -0
  128. package/dist/report/export.d.ts +3 -0
  129. package/dist/report/export.js +81 -0
  130. package/dist/report/html.js +15 -216
  131. package/dist/report/insight.d.ts +27 -0
  132. package/dist/report/insight.js +103 -0
  133. package/dist/scoring/health.d.ts +56 -0
  134. package/dist/scoring/health.js +213 -0
  135. package/dist/utils/chalk.d.ts +6 -0
  136. package/dist/utils/chalk.js +41 -0
  137. package/dist/utils/secureConfig.d.ts +23 -0
  138. package/dist/utils/secureConfig.js +128 -0
  139. package/package.json +12 -6
  140. package/CHANGELOG.md +0 -7
  141. package/dist/db/schema.d.ts +0 -2
  142. package/dist/graph/cluster.d.ts +0 -6
  143. package/dist/graph/cluster.js +0 -173
  144. package/dist/graph/duplicate.d.ts +0 -10
  145. package/dist/graph/duplicate.js +0 -251
  146. package/dist/report/sitegraphExport.d.ts +0 -3
  147. package/dist/report/sitegraph_template.d.ts +0 -1
  148. package/dist/report/sitegraph_template.js +0 -630
  149. package/dist/scoring/hits.d.ts +0 -9
  150. package/dist/scoring/hits.js +0 -111
  151. package/src/analysis/analyze.ts +0 -548
  152. package/src/analysis/content.ts +0 -62
  153. package/src/analysis/images.ts +0 -28
  154. package/src/analysis/links.ts +0 -41
  155. package/src/analysis/scoring.ts +0 -59
  156. package/src/analysis/seo.ts +0 -82
  157. package/src/analysis/structuredData.ts +0 -62
  158. package/src/audit/dns.ts +0 -49
  159. package/src/audit/headers.ts +0 -98
  160. package/src/audit/index.ts +0 -66
  161. package/src/audit/scoring.ts +0 -232
  162. package/src/audit/transport.ts +0 -258
  163. package/src/audit/types.ts +0 -102
  164. package/src/core/network/proxyAdapter.ts +0 -21
  165. package/src/core/network/rateLimiter.ts +0 -39
  166. package/src/core/network/redirectController.ts +0 -47
  167. package/src/core/network/responseLimiter.ts +0 -34
  168. package/src/core/network/retryPolicy.ts +0 -57
  169. package/src/core/scope/domainFilter.ts +0 -45
  170. package/src/core/scope/scopeManager.ts +0 -52
  171. package/src/core/scope/subdomainPolicy.ts +0 -39
  172. package/src/core/security/ipGuard.ts +0 -92
  173. package/src/crawler/crawl.ts +0 -382
  174. package/src/crawler/extract.ts +0 -34
  175. package/src/crawler/fetcher.ts +0 -233
  176. package/src/crawler/metricsRunner.ts +0 -124
  177. package/src/crawler/normalize.ts +0 -108
  178. package/src/crawler/parser.ts +0 -190
  179. package/src/crawler/sitemap.ts +0 -73
  180. package/src/crawler/trap.ts +0 -96
  181. package/src/db/graphLoader.ts +0 -105
  182. package/src/db/index.ts +0 -70
  183. package/src/db/repositories/EdgeRepository.ts +0 -29
  184. package/src/db/repositories/MetricsRepository.ts +0 -49
  185. package/src/db/repositories/PageRepository.ts +0 -128
  186. package/src/db/repositories/SiteRepository.ts +0 -32
  187. package/src/db/repositories/SnapshotRepository.ts +0 -74
  188. package/src/db/schema.ts +0 -177
  189. package/src/diff/compare.ts +0 -84
  190. package/src/graph/cluster.ts +0 -192
  191. package/src/graph/duplicate.ts +0 -286
  192. package/src/graph/graph.ts +0 -172
  193. package/src/graph/metrics.ts +0 -110
  194. package/src/graph/pagerank.ts +0 -125
  195. package/src/graph/simhash.ts +0 -61
  196. package/src/index.ts +0 -30
  197. package/src/lock/hashKey.ts +0 -51
  198. package/src/lock/lockManager.ts +0 -124
  199. package/src/lock/pidCheck.ts +0 -13
  200. package/src/report/html.ts +0 -227
  201. package/src/report/sitegraphExport.ts +0 -58
  202. package/src/scoring/hits.ts +0 -131
  203. package/src/scoring/orphanSeverity.ts +0 -176
  204. package/src/utils/version.ts +0 -18
  205. package/tests/__snapshots__/orphanSeverity.test.ts.snap +0 -49
  206. package/tests/analysis.unit.test.ts +0 -98
  207. package/tests/analyze.integration.test.ts +0 -98
  208. package/tests/audit/dns.test.ts +0 -31
  209. package/tests/audit/headers.test.ts +0 -45
  210. package/tests/audit/scoring.test.ts +0 -133
  211. package/tests/audit/security.test.ts +0 -12
  212. package/tests/audit/transport.test.ts +0 -112
  213. package/tests/clustering.test.ts +0 -118
  214. package/tests/crawler.test.ts +0 -358
  215. package/tests/db.test.ts +0 -159
  216. package/tests/diff.test.ts +0 -67
  217. package/tests/duplicate.test.ts +0 -110
  218. package/tests/fetcher.test.ts +0 -106
  219. package/tests/fetcher_safety.test.ts +0 -85
  220. package/tests/fixtures/analyze-crawl.json +0 -26
  221. package/tests/hits.test.ts +0 -134
  222. package/tests/html_report.test.ts +0 -58
  223. package/tests/lock/lockManager.test.ts +0 -138
  224. package/tests/metrics.test.ts +0 -196
  225. package/tests/normalize.test.ts +0 -101
  226. package/tests/orphanSeverity.test.ts +0 -160
  227. package/tests/pagerank.test.ts +0 -98
  228. package/tests/parser.test.ts +0 -117
  229. package/tests/proxy_safety.test.ts +0 -57
  230. package/tests/redirect_safety.test.ts +0 -73
  231. package/tests/safety.test.ts +0 -114
  232. package/tests/scope.test.ts +0 -66
  233. package/tests/scoring.test.ts +0 -59
  234. package/tests/sitemap.test.ts +0 -88
  235. package/tests/soft404.test.ts +0 -41
  236. package/tests/trap.test.ts +0 -39
  237. package/tests/visualization_data.test.ts +0 -46
  238. package/tsconfig.json +0 -11
package/src/db/index.ts DELETED
@@ -1,70 +0,0 @@
1
- import Database from 'better-sqlite3';
2
- import path from 'node:path';
3
- import fs from 'node:fs';
4
- import os from 'node:os';
5
- import { initSchema } from './schema.js';
6
-
7
- let dbInstance: Database.Database | null = null;
8
-
9
- export function getDbPath(): string {
10
- if (process.env.NODE_ENV === 'test') {
11
- return ':memory:';
12
- }
13
- if (process.env.CRAWLITH_DB_PATH) {
14
- return process.env.CRAWLITH_DB_PATH;
15
- }
16
- const homeDir = os.homedir();
17
- const crawlithDir = path.join(homeDir, '.crawlith');
18
- if (!fs.existsSync(crawlithDir)) {
19
- fs.mkdirSync(crawlithDir, { recursive: true });
20
- // Set permissions to 700 (user only)
21
- fs.chmodSync(crawlithDir, 0o700);
22
- }
23
- return path.join(crawlithDir, 'crawlith.db');
24
- }
25
-
26
- export function getDb(): Database.Database {
27
- if (dbInstance) {
28
- return dbInstance;
29
- }
30
-
31
- const dbPath = getDbPath();
32
- const db = new Database(dbPath);
33
-
34
- // Hardening & Performance Configuration
35
- db.pragma('journal_mode = WAL');
36
- db.pragma('synchronous = NORMAL');
37
- db.pragma('foreign_keys = ON');
38
- db.pragma('temp_store = MEMORY');
39
- db.pragma('mmap_size = 30000000000');
40
- db.pragma('cache_size = -20000');
41
- db.pragma('busy_timeout = 5000');
42
-
43
- // Security controls
44
- // Ensure file permissions are 600 (user read/write only)
45
- try {
46
- fs.chmodSync(dbPath, 0o600);
47
- } catch (_e) {
48
- // might fail on first creation if file doesn't exist yet, but better-sqlite3 creates it
49
- // so we can try again or ignore if it's new
50
- }
51
-
52
- // Integrity check on startup
53
- const integrity = db.pragma('integrity_check', { simple: true });
54
- if (integrity !== 'ok') {
55
- console.warn('Database integrity check failed:', integrity);
56
- }
57
-
58
- // Initialize schema
59
- initSchema(db);
60
-
61
- dbInstance = db;
62
- return db;
63
- }
64
-
65
- export function closeDb() {
66
- if (dbInstance) {
67
- dbInstance.close();
68
- dbInstance = null;
69
- }
70
- }
@@ -1,29 +0,0 @@
1
- import { Database } from 'better-sqlite3';
2
-
3
- export interface Edge {
4
- id: number;
5
- snapshot_id: number;
6
- source_page_id: number;
7
- target_page_id: number;
8
- weight: number;
9
- rel: 'nofollow' | 'sponsored' | 'ugc' | 'internal' | 'external' | 'unknown';
10
- }
11
-
12
- export class EdgeRepository {
13
- private insertStmt;
14
-
15
- constructor(private db: Database) {
16
- this.insertStmt = this.db.prepare(`
17
- INSERT INTO edges (snapshot_id, source_page_id, target_page_id, weight, rel)
18
- VALUES (?, ?, ?, ?, ?)
19
- `);
20
- }
21
-
22
- insertEdge(snapshotId: number, sourcePageId: number, targetPageId: number, weight: number = 1.0, rel: string = 'internal') {
23
- this.insertStmt.run(snapshotId, sourcePageId, targetPageId, weight, rel);
24
- }
25
-
26
- getEdgesBySnapshot(snapshotId: number): Edge[] {
27
- return this.db.prepare('SELECT * FROM edges WHERE snapshot_id = ?').all(snapshotId) as Edge[];
28
- }
29
- }
@@ -1,49 +0,0 @@
1
- import { Database } from 'better-sqlite3';
2
-
3
- export interface DbMetrics {
4
- snapshot_id: number;
5
- page_id: number;
6
- authority_score: number | null;
7
- hub_score: number | null;
8
- pagerank: number | null;
9
- pagerank_score: number | null;
10
- link_role: 'hub' | 'authority' | 'power' | 'balanced' | 'peripheral' | null;
11
- crawl_status: string | null;
12
- word_count: number | null;
13
- thin_content_score: number | null;
14
- external_link_ratio: number | null;
15
- orphan_score: number | null;
16
- duplicate_cluster_id: string | null;
17
- duplicate_type: 'exact' | 'near' | 'template_heavy' | 'none' | null;
18
- is_cluster_primary: number;
19
- }
20
-
21
- export class MetricsRepository {
22
- private insertStmt;
23
-
24
- constructor(private db: Database) {
25
- this.insertStmt = this.db.prepare(`
26
- INSERT OR REPLACE INTO metrics (
27
- snapshot_id, page_id, authority_score, hub_score, pagerank, pagerank_score,
28
- link_role, crawl_status, word_count, thin_content_score, external_link_ratio,
29
- orphan_score, duplicate_cluster_id, duplicate_type, is_cluster_primary
30
- ) VALUES (
31
- @snapshot_id, @page_id, @authority_score, @hub_score, @pagerank, @pagerank_score,
32
- @link_role, @crawl_status, @word_count, @thin_content_score, @external_link_ratio,
33
- @orphan_score, @duplicate_cluster_id, @duplicate_type, @is_cluster_primary
34
- )
35
- `);
36
- }
37
-
38
- insertMetrics(metrics: DbMetrics) {
39
- this.insertStmt.run(metrics);
40
- }
41
-
42
- getMetrics(snapshotId: number): DbMetrics[] {
43
- return this.db.prepare('SELECT * FROM metrics WHERE snapshot_id = ?').all(snapshotId) as DbMetrics[];
44
- }
45
-
46
- getMetricsForPage(snapshotId: number, pageId: number): DbMetrics | undefined {
47
- return this.db.prepare('SELECT * FROM metrics WHERE snapshot_id = ? AND page_id = ?').get(snapshotId, pageId) as DbMetrics | undefined;
48
- }
49
- }
@@ -1,128 +0,0 @@
1
- import { Database } from 'better-sqlite3';
2
-
3
- export interface Page {
4
- id: number;
5
- site_id: number;
6
- normalized_url: string;
7
- first_seen_snapshot_id: number | null;
8
- last_seen_snapshot_id: number | null;
9
- http_status: number | null;
10
- canonical_url: string | null;
11
- content_hash: string | null;
12
- simhash: string | null;
13
- etag: string | null;
14
- last_modified: string | null;
15
- html: string | null;
16
- soft404_score: number | null;
17
- noindex: number;
18
- nofollow: number;
19
- security_error: string | null;
20
- retries: number;
21
- depth: number;
22
- redirect_chain: string | null;
23
- bytes_received: number | null;
24
- crawl_trap_flag: number;
25
- crawl_trap_risk: number | null;
26
- trap_type: string | null;
27
- created_at: string;
28
- updated_at: string;
29
- }
30
-
31
- export class PageRepository {
32
- private upsertStmt;
33
- private getIdStmt;
34
-
35
- constructor(private db: Database) {
36
- this.upsertStmt = this.db.prepare(`
37
- INSERT INTO pages (
38
- site_id, normalized_url, first_seen_snapshot_id, last_seen_snapshot_id,
39
- http_status, canonical_url, content_hash, simhash, etag, last_modified, html,
40
- soft404_score, noindex, nofollow, security_error, retries, depth,
41
- redirect_chain, bytes_received, crawl_trap_flag, crawl_trap_risk, trap_type,
42
- updated_at
43
- ) VALUES (
44
- @site_id, @normalized_url, @first_seen_snapshot_id, @last_seen_snapshot_id,
45
- @http_status, @canonical_url, @content_hash, @simhash, @etag, @last_modified, @html,
46
- @soft404_score, @noindex, @nofollow, @security_error, @retries, @depth,
47
- @redirect_chain, @bytes_received, @crawl_trap_flag, @crawl_trap_risk, @trap_type,
48
- datetime('now')
49
- )
50
- ON CONFLICT(site_id, normalized_url) DO UPDATE SET
51
- last_seen_snapshot_id = excluded.last_seen_snapshot_id,
52
- http_status = excluded.http_status,
53
- canonical_url = excluded.canonical_url,
54
- content_hash = excluded.content_hash,
55
- simhash = excluded.simhash,
56
- etag = excluded.etag,
57
- last_modified = excluded.last_modified,
58
- html = excluded.html,
59
- soft404_score = excluded.soft404_score,
60
- noindex = excluded.noindex,
61
- nofollow = excluded.nofollow,
62
- security_error = excluded.security_error,
63
- retries = excluded.retries,
64
- depth = excluded.depth,
65
- redirect_chain = excluded.redirect_chain,
66
- bytes_received = excluded.bytes_received,
67
- crawl_trap_flag = excluded.crawl_trap_flag,
68
- crawl_trap_risk = excluded.crawl_trap_risk,
69
- trap_type = excluded.trap_type,
70
- updated_at = datetime('now')
71
- `);
72
-
73
- this.getIdStmt = this.db.prepare('SELECT id FROM pages WHERE site_id = ? AND normalized_url = ?');
74
- }
75
-
76
- upsertPage(page: Partial<Page> & { site_id: number; normalized_url: string; last_seen_snapshot_id: number }) {
77
- const params = {
78
- site_id: page.site_id,
79
- normalized_url: page.normalized_url,
80
- first_seen_snapshot_id: page.first_seen_snapshot_id ?? page.last_seen_snapshot_id,
81
- last_seen_snapshot_id: page.last_seen_snapshot_id,
82
- http_status: page.http_status ?? null,
83
- canonical_url: page.canonical_url ?? null,
84
- content_hash: page.content_hash ?? null,
85
- simhash: page.simhash ?? null,
86
- etag: page.etag ?? null,
87
- last_modified: page.last_modified ?? null,
88
- html: page.html ?? null,
89
- soft404_score: page.soft404_score ?? null,
90
- noindex: page.noindex ?? 0,
91
- nofollow: page.nofollow ?? 0,
92
- security_error: page.security_error ?? null,
93
- retries: page.retries ?? 0,
94
- depth: page.depth ?? 0,
95
- redirect_chain: page.redirect_chain ?? null,
96
- bytes_received: page.bytes_received ?? null,
97
- crawl_trap_flag: page.crawl_trap_flag ?? 0,
98
- crawl_trap_risk: page.crawl_trap_risk ?? null,
99
- trap_type: page.trap_type ?? null,
100
- };
101
-
102
- const info = this.upsertStmt.run(params);
103
- return info;
104
- }
105
-
106
- upsertAndGetId(page: Partial<Page> & { site_id: number; normalized_url: string; last_seen_snapshot_id: number }): number {
107
- const tx = this.db.transaction(() => {
108
- this.upsertPage(page);
109
- const row = this.getIdStmt.get(page.site_id, page.normalized_url) as { id: number } | undefined;
110
- if (!row) throw new Error(`Failed to retrieve ID for upserted page: ${page.normalized_url}`);
111
- return row.id;
112
- });
113
- return tx();
114
- }
115
-
116
- getPage(siteId: number, url: string): Page | undefined {
117
- return this.db.prepare('SELECT * FROM pages WHERE site_id = ? AND normalized_url = ?').get(siteId, url) as Page | undefined;
118
- }
119
-
120
- getPagesBySnapshot(snapshotId: number): Page[] {
121
- return this.db.prepare('SELECT * FROM pages WHERE last_seen_snapshot_id = ?').all(snapshotId) as Page[];
122
- }
123
-
124
- getIdByUrl(siteId: number, url: string): number | undefined {
125
- const row = this.getIdStmt.get(siteId, url) as { id: number } | undefined;
126
- return row?.id;
127
- }
128
- }
@@ -1,32 +0,0 @@
1
- import { Database } from 'better-sqlite3';
2
-
3
- export interface Site {
4
- id: number;
5
- domain: string;
6
- created_at: string;
7
- settings_json: string | null;
8
- is_active: number;
9
- }
10
-
11
- export class SiteRepository {
12
- constructor(private db: Database) { }
13
-
14
- getSite(domain: string): Site | undefined {
15
- return this.db.prepare('SELECT * FROM sites WHERE domain = ?').get(domain) as Site | undefined;
16
- }
17
-
18
- createSite(domain: string): number {
19
- const stmt = this.db.prepare('INSERT INTO sites (domain) VALUES (?)');
20
- const info = stmt.run(domain);
21
- return info.lastInsertRowid as number;
22
- }
23
-
24
- firstOrCreateSite(domain: string): Site {
25
- let site = this.getSite(domain);
26
- if (!site) {
27
- this.createSite(domain);
28
- site = this.getSite(domain);
29
- }
30
- return site!;
31
- }
32
- }
@@ -1,74 +0,0 @@
1
- import { Database } from 'better-sqlite3';
2
-
3
- export interface Snapshot {
4
- id: number;
5
- site_id: number;
6
- type: 'full' | 'partial' | 'incremental';
7
- created_at: string;
8
- node_count: number;
9
- edge_count: number;
10
- status: 'running' | 'completed' | 'failed';
11
- limit_reached: number;
12
- health_score: number | null;
13
- orphan_count: number | null;
14
- thin_content_count: number | null;
15
- }
16
-
17
- export class SnapshotRepository {
18
- constructor(private db: Database) {}
19
-
20
- createSnapshot(siteId: number, type: 'full' | 'partial' | 'incremental', status: 'running' | 'completed' | 'failed' = 'running'): number {
21
- const stmt = this.db.prepare('INSERT INTO snapshots (site_id, type, status) VALUES (?, ?, ?)');
22
- const info = stmt.run(siteId, type, status);
23
- return info.lastInsertRowid as number;
24
- }
25
-
26
- getLatestSnapshot(siteId: number, status?: 'completed' | 'running' | 'failed'): Snapshot | undefined {
27
- let sql = 'SELECT * FROM snapshots WHERE site_id = ?';
28
- const params: any[] = [siteId];
29
- if (status) {
30
- sql += ' AND status = ?';
31
- params.push(status);
32
- }
33
- sql += ' ORDER BY created_at DESC LIMIT 1';
34
- return this.db.prepare(sql).get(...params) as Snapshot | undefined;
35
- }
36
-
37
- updateSnapshotStatus(id: number, status: 'completed' | 'failed', stats: Partial<Snapshot> = {}) {
38
- const sets: string[] = ['status = ?'];
39
- const params: any[] = [status];
40
-
41
- if (stats.node_count !== undefined) {
42
- sets.push('node_count = ?');
43
- params.push(stats.node_count);
44
- }
45
- if (stats.edge_count !== undefined) {
46
- sets.push('edge_count = ?');
47
- params.push(stats.edge_count);
48
- }
49
- if (stats.limit_reached !== undefined) {
50
- sets.push('limit_reached = ?');
51
- params.push(stats.limit_reached);
52
- }
53
- if (stats.health_score !== undefined) {
54
- sets.push('health_score = ?');
55
- params.push(stats.health_score);
56
- }
57
- if (stats.orphan_count !== undefined) {
58
- sets.push('orphan_count = ?');
59
- params.push(stats.orphan_count);
60
- }
61
- if (stats.thin_content_count !== undefined) {
62
- sets.push('thin_content_count = ?');
63
- params.push(stats.thin_content_count);
64
- }
65
-
66
- params.push(id);
67
- const sql = `UPDATE snapshots SET ${sets.join(', ')} WHERE id = ?`;
68
- this.db.prepare(sql).run(...params);
69
- }
70
-
71
- getSnapshot(id: number): Snapshot | undefined {
72
- return this.db.prepare('SELECT * FROM snapshots WHERE id = ?').get(id) as Snapshot | undefined;
73
- }
74
- }
package/src/db/schema.ts DELETED
@@ -1,177 +0,0 @@
1
- import { Database } from 'better-sqlite3';
2
-
3
- export function initSchema(db: Database) {
4
- // Sites Table
5
- db.exec(`
6
- CREATE TABLE IF NOT EXISTS sites (
7
- id INTEGER PRIMARY KEY AUTOINCREMENT,
8
- domain TEXT UNIQUE NOT NULL,
9
- created_at TEXT DEFAULT (datetime('now')),
10
- settings_json TEXT,
11
- is_active INTEGER DEFAULT 1
12
- );
13
- `);
14
-
15
- // Snapshots Table
16
- db.exec(`
17
- CREATE TABLE IF NOT EXISTS snapshots (
18
- id INTEGER PRIMARY KEY AUTOINCREMENT,
19
- site_id INTEGER NOT NULL,
20
- type TEXT CHECK(type IN ('full', 'partial', 'incremental')) NOT NULL,
21
- created_at TEXT DEFAULT (datetime('now')),
22
- node_count INTEGER DEFAULT 0,
23
- edge_count INTEGER DEFAULT 0,
24
- status TEXT CHECK(status IN ('running', 'completed', 'failed')) DEFAULT 'running',
25
- limit_reached INTEGER DEFAULT 0,
26
- health_score REAL,
27
- orphan_count INTEGER,
28
- thin_content_count INTEGER,
29
- FOREIGN KEY(site_id) REFERENCES sites(id) ON DELETE CASCADE
30
- );
31
- `);
32
-
33
- // Pages Table
34
- db.exec(`
35
- CREATE TABLE IF NOT EXISTS pages (
36
- id INTEGER PRIMARY KEY AUTOINCREMENT,
37
- site_id INTEGER NOT NULL,
38
- normalized_url TEXT NOT NULL,
39
- first_seen_snapshot_id INTEGER,
40
- last_seen_snapshot_id INTEGER,
41
- http_status INTEGER,
42
- canonical_url TEXT,
43
- content_hash TEXT,
44
- simhash TEXT,
45
- etag TEXT,
46
- last_modified TEXT,
47
- html TEXT,
48
- soft404_score REAL,
49
- noindex INTEGER DEFAULT 0,
50
- nofollow INTEGER DEFAULT 0,
51
- security_error TEXT,
52
- retries INTEGER DEFAULT 0,
53
- depth INTEGER DEFAULT 0,
54
- redirect_chain TEXT,
55
- bytes_received INTEGER,
56
- crawl_trap_flag INTEGER DEFAULT 0,
57
- crawl_trap_risk REAL,
58
- trap_type TEXT,
59
- created_at TEXT DEFAULT (datetime('now')),
60
- updated_at TEXT DEFAULT (datetime('now')),
61
- FOREIGN KEY(site_id) REFERENCES sites(id) ON DELETE CASCADE,
62
- FOREIGN KEY(first_seen_snapshot_id) REFERENCES snapshots(id),
63
- FOREIGN KEY(last_seen_snapshot_id) REFERENCES snapshots(id),
64
- UNIQUE(site_id, normalized_url)
65
- );
66
- `);
67
-
68
- // Index for Pages
69
- db.exec(`CREATE INDEX IF NOT EXISTS idx_pages_site_last_seen ON pages(site_id, last_seen_snapshot_id);`);
70
-
71
- // Edges Table
72
- db.exec(`
73
- CREATE TABLE IF NOT EXISTS edges (
74
- id INTEGER PRIMARY KEY AUTOINCREMENT,
75
- snapshot_id INTEGER NOT NULL,
76
- source_page_id INTEGER NOT NULL,
77
- target_page_id INTEGER NOT NULL,
78
- weight REAL DEFAULT 1.0,
79
- rel TEXT CHECK(rel IN ('nofollow', 'sponsored', 'ugc', 'internal', 'external', 'unknown')) DEFAULT 'internal',
80
- FOREIGN KEY(snapshot_id) REFERENCES snapshots(id) ON DELETE CASCADE,
81
- FOREIGN KEY(source_page_id) REFERENCES pages(id) ON DELETE CASCADE,
82
- FOREIGN KEY(target_page_id) REFERENCES pages(id) ON DELETE CASCADE
83
- );
84
- `);
85
-
86
- // Index for Edges
87
- db.exec(`CREATE INDEX IF NOT EXISTS idx_edges_snapshot_source ON edges(snapshot_id, source_page_id);`);
88
- db.exec(`CREATE INDEX IF NOT EXISTS idx_edges_snapshot ON edges(snapshot_id);`);
89
-
90
- // Metrics Table
91
- db.exec(`
92
- CREATE TABLE IF NOT EXISTS metrics (
93
- snapshot_id INTEGER NOT NULL,
94
- page_id INTEGER NOT NULL,
95
- authority_score REAL,
96
- hub_score REAL,
97
- pagerank REAL,
98
- pagerank_score REAL,
99
- link_role TEXT CHECK(link_role IN ('hub', 'authority', 'power', 'balanced', 'peripheral')),
100
- crawl_status TEXT,
101
- word_count INTEGER,
102
- thin_content_score REAL,
103
- external_link_ratio REAL,
104
- orphan_score INTEGER,
105
- duplicate_cluster_id TEXT,
106
- duplicate_type TEXT CHECK(duplicate_type IN ('exact', 'near', 'template_heavy', 'none')),
107
- is_cluster_primary INTEGER DEFAULT 0,
108
- PRIMARY KEY(snapshot_id, page_id),
109
- FOREIGN KEY(snapshot_id) REFERENCES snapshots(id) ON DELETE CASCADE,
110
- FOREIGN KEY(page_id) REFERENCES pages(id) ON DELETE CASCADE
111
- );
112
- `);
113
-
114
- db.exec(`CREATE INDEX IF NOT EXISTS idx_metrics_snapshot ON metrics(snapshot_id);`);
115
-
116
- // Duplicate Clusters Table
117
- db.exec(`
118
- CREATE TABLE IF NOT EXISTS duplicate_clusters (
119
- id TEXT NOT NULL,
120
- snapshot_id INTEGER NOT NULL,
121
- type TEXT CHECK(type IN ('exact', 'near', 'template_heavy')) NOT NULL,
122
- size INTEGER NOT NULL,
123
- representative TEXT NOT NULL,
124
- severity TEXT CHECK(severity IN ('low', 'medium', 'high')) NOT NULL,
125
- PRIMARY KEY(snapshot_id, id),
126
- FOREIGN KEY(snapshot_id) REFERENCES snapshots(id) ON DELETE CASCADE
127
- );
128
- `);
129
-
130
- // Content Clusters Table
131
- db.exec(`
132
- CREATE TABLE IF NOT EXISTS content_clusters (
133
- id INTEGER NOT NULL,
134
- snapshot_id INTEGER NOT NULL,
135
- count INTEGER NOT NULL,
136
- primary_url TEXT NOT NULL,
137
- risk TEXT CHECK(risk IN ('low', 'medium', 'high')) NOT NULL,
138
- shared_path_prefix TEXT,
139
- PRIMARY KEY(snapshot_id, id),
140
- FOREIGN KEY(snapshot_id) REFERENCES snapshots(id) ON DELETE CASCADE
141
- );
142
- `);
143
-
144
- // Migration: add columns to existing DBs that were created before this update
145
- migrateSchema(db);
146
- }
147
-
148
- function migrateSchema(db: Database) {
149
- // Add missing columns to pages (safe: ALTER TABLE ADD COLUMN is idempotent-safe with try/catch)
150
- const pageColumns = [
151
- ['redirect_chain', 'TEXT'],
152
- ['bytes_received', 'INTEGER'],
153
- ['crawl_trap_flag', 'INTEGER DEFAULT 0'],
154
- ['crawl_trap_risk', 'REAL'],
155
- ['trap_type', 'TEXT'],
156
- ];
157
-
158
- for (const [col, type] of pageColumns) {
159
- try { db.exec(`ALTER TABLE pages ADD COLUMN ${col} ${type}`); } catch { /* already exists */ }
160
- }
161
-
162
- // Add missing columns to edges
163
- try { db.exec('ALTER TABLE edges ADD COLUMN weight REAL DEFAULT 1.0'); } catch { /* already exists */ }
164
-
165
- // Add missing columns to metrics
166
- const metricsColumns = [
167
- ['pagerank_score', 'REAL'],
168
- ['link_role', 'TEXT'],
169
- ['duplicate_cluster_id', 'TEXT'],
170
- ['duplicate_type', 'TEXT'],
171
- ['is_cluster_primary', 'INTEGER DEFAULT 0'],
172
- ];
173
-
174
- for (const [col, type] of metricsColumns) {
175
- try { db.exec(`ALTER TABLE metrics ADD COLUMN ${col} ${type}`); } catch { /* already exists */ }
176
- }
177
- }
@@ -1,84 +0,0 @@
1
- import { Graph } from '../graph/graph.js';
2
- import { calculateMetrics } from '../graph/metrics.js';
3
-
4
- export interface DiffResult {
5
- addedUrls: string[];
6
- removedUrls: string[];
7
- changedStatus: { url: string; oldStatus: number; newStatus: number }[];
8
- changedCanonical: { url: string; oldCanonical: string | null; newCanonical: string | null }[];
9
- changedDuplicateGroup: { url: string; oldGroup: string | null; newGroup: string | null }[];
10
- metricDeltas: {
11
- structuralEntropy: number;
12
- orphanCount: number;
13
- crawlEfficiency: number;
14
- };
15
- }
16
-
17
- export function compareGraphs(oldGraph: Graph, newGraph: Graph): DiffResult {
18
- const oldNodes = new Map(oldGraph.getNodes().map(n => [n.url, n]));
19
- const newNodes = new Map(newGraph.getNodes().map(n => [n.url, n]));
20
-
21
- const addedUrls: string[] = [];
22
- const removedUrls: string[] = [];
23
- const changedStatus: { url: string; oldStatus: number; newStatus: number }[] = [];
24
- const changedCanonical: { url: string; oldCanonical: string | null; newCanonical: string | null }[] = [];
25
- const changedDuplicateGroup: { url: string; oldGroup: string | null; newGroup: string | null }[] = [];
26
-
27
- // Added & Changed
28
- for (const [url, newNode] of newNodes) {
29
- const oldNode = oldNodes.get(url);
30
- if (!oldNode) {
31
- addedUrls.push(url);
32
- } else {
33
- // Changed Status
34
- if (oldNode.status !== newNode.status) {
35
- changedStatus.push({ url, oldStatus: oldNode.status, newStatus: newNode.status });
36
- }
37
- // Changed Canonical
38
- if (oldNode.canonical !== newNode.canonical) {
39
- changedCanonical.push({
40
- url,
41
- oldCanonical: oldNode.canonical || null,
42
- newCanonical: newNode.canonical || null
43
- });
44
- }
45
- // Changed Duplicate Group
46
- const oldGroup = oldNode.duplicateClusterId || null;
47
- const newGroup = newNode.duplicateClusterId || null;
48
- if (oldGroup !== newGroup) {
49
- changedDuplicateGroup.push({
50
- url,
51
- oldGroup,
52
- newGroup
53
- });
54
- }
55
- }
56
- }
57
-
58
- // Removed
59
- for (const url of oldNodes.keys()) {
60
- if (!newNodes.has(url)) {
61
- removedUrls.push(url);
62
- }
63
- }
64
-
65
- // Metrics
66
- // maxDepth is ignored by current calculateMetrics implementation but required by signature
67
- const oldMetrics = calculateMetrics(oldGraph, 10);
68
- const newMetrics = calculateMetrics(newGraph, 10);
69
-
70
- const metricDeltas = {
71
- structuralEntropy: newMetrics.structuralEntropy - oldMetrics.structuralEntropy,
72
- orphanCount: newMetrics.orphanPages.length - oldMetrics.orphanPages.length,
73
- crawlEfficiency: newMetrics.crawlEfficiencyScore - oldMetrics.crawlEfficiencyScore
74
- };
75
-
76
- return {
77
- addedUrls,
78
- removedUrls,
79
- changedStatus,
80
- changedCanonical,
81
- changedDuplicateGroup,
82
- metricDeltas
83
- };
84
- }