@nitpicker/crawler 0.22.2 → 0.24.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 (158) hide show
  1. package/lib/archive/archive.d.ts +13 -5
  2. package/lib/archive/archive.js +16 -7
  3. package/lib/archive/cache/extract-archive-to-cache.d.ts +6 -1
  4. package/lib/archive/cache/extract-archive-to-cache.js +13 -6
  5. package/lib/archive/create-adjunct-tables.d.ts +0 -7
  6. package/lib/archive/create-adjunct-tables.js +0 -50
  7. package/lib/archive/create-template-tables.d.ts +30 -0
  8. package/lib/archive/create-template-tables.js +95 -0
  9. package/lib/archive/database.d.ts +1 -1
  10. package/lib/archive/database.js +1 -1
  11. package/lib/archive/db-ops/config/get-config.d.ts +1 -1
  12. package/lib/archive/db-ops/config/get-config.js +2 -1
  13. package/lib/archive/db-ops/config/info-column-allowlist.js +1 -0
  14. package/lib/archive/db-ops/config/info-json-columns.js +1 -0
  15. package/lib/archive/db-ops/lifecycle/init.js +2 -0
  16. package/lib/archive/db-ops/templates/assign-template-labels.d.ts +60 -0
  17. package/lib/archive/db-ops/templates/assign-template-labels.js +187 -0
  18. package/lib/archive/db-ops/{analysis → templates}/replace-page-templates.d.ts +19 -3
  19. package/lib/archive/db-ops/templates/replace-page-templates.js +174 -0
  20. package/lib/archive/db-ops/{analysis → templates}/types.d.ts +38 -0
  21. package/lib/archive/init-schema.d.ts +5 -1
  22. package/lib/archive/init-schema.js +14 -2
  23. package/lib/archive/migrate-info-request-header-names.d.ts +16 -0
  24. package/lib/archive/migrate-info-request-header-names.js +35 -0
  25. package/lib/archive/test-utils/build-full-schema-test-db.d.ts +34 -0
  26. package/lib/archive/test-utils/build-full-schema-test-db.js +74 -0
  27. package/lib/archive/transfer/attach-source-database.d.ts +31 -0
  28. package/lib/archive/transfer/attach-source-database.js +40 -0
  29. package/lib/archive/transfer/build-split-config.d.ts +30 -0
  30. package/lib/archive/transfer/build-split-config.js +42 -0
  31. package/lib/archive/transfer/clear-replaced-page-rows.d.ts +20 -0
  32. package/lib/archive/transfer/clear-replaced-page-rows.js +57 -0
  33. package/lib/archive/transfer/concat-archives.d.ts +55 -0
  34. package/lib/archive/transfer/concat-archives.js +95 -0
  35. package/lib/archive/transfer/content-item-rank-sql.d.ts +21 -0
  36. package/lib/archive/transfer/content-item-rank-sql.js +23 -0
  37. package/lib/archive/transfer/copy-analysis-violations.d.ts +19 -0
  38. package/lib/archive/transfer/copy-analysis-violations.js +43 -0
  39. package/lib/archive/transfer/copy-anchor-edges.d.ts +28 -0
  40. package/lib/archive/transfer/copy-anchor-edges.js +42 -0
  41. package/lib/archive/transfer/copy-dictionaries-for-concat.d.ts +39 -0
  42. package/lib/archive/transfer/copy-dictionaries-for-concat.js +81 -0
  43. package/lib/archive/transfer/copy-dictionaries-for-split.d.ts +29 -0
  44. package/lib/archive/transfer/copy-dictionaries-for-split.js +235 -0
  45. package/lib/archive/transfer/copy-header-set-children.d.ts +27 -0
  46. package/lib/archive/transfer/copy-header-set-children.js +51 -0
  47. package/lib/archive/transfer/copy-image-items.d.ts +21 -0
  48. package/lib/archive/transfer/copy-image-items.js +62 -0
  49. package/lib/archive/transfer/copy-inventory-source-lists.d.ts +30 -0
  50. package/lib/archive/transfer/copy-inventory-source-lists.js +61 -0
  51. package/lib/archive/transfer/copy-journal-tables.d.ts +30 -0
  52. package/lib/archive/transfer/copy-journal-tables.js +56 -0
  53. package/lib/archive/transfer/copy-page-console-logs.d.ts +16 -0
  54. package/lib/archive/transfer/copy-page-console-logs.js +27 -0
  55. package/lib/archive/transfer/copy-page-html-blobs.d.ts +31 -0
  56. package/lib/archive/transfer/copy-page-html-blobs.js +43 -0
  57. package/lib/archive/transfer/copy-page-meta.d.ts +27 -0
  58. package/lib/archive/transfer/copy-page-meta.js +68 -0
  59. package/lib/archive/transfer/copy-page-template-clusters.d.ts +31 -0
  60. package/lib/archive/transfer/copy-page-template-clusters.js +56 -0
  61. package/lib/archive/transfer/copy-page-template-labels.d.ts +34 -0
  62. package/lib/archive/transfer/copy-page-template-labels.js +88 -0
  63. package/lib/archive/transfer/copy-resource-items.d.ts +29 -0
  64. package/lib/archive/transfer/copy-resource-items.js +89 -0
  65. package/lib/archive/transfer/copy-resource-ref-edges.d.ts +20 -0
  66. package/lib/archive/transfer/copy-resource-ref-edges.js +33 -0
  67. package/lib/archive/transfer/copy-simple-page-scoped-tables.d.ts +15 -0
  68. package/lib/archive/transfer/copy-simple-page-scoped-tables.js +34 -0
  69. package/lib/archive/transfer/count-external-pages-in-scope.d.ts +26 -0
  70. package/lib/archive/transfer/count-external-pages-in-scope.js +40 -0
  71. package/lib/archive/transfer/create-transfer-temp-tables.d.ts +30 -0
  72. package/lib/archive/transfer/create-transfer-temp-tables.js +59 -0
  73. package/lib/archive/transfer/dictionary-copy-specs.d.ts +32 -0
  74. package/lib/archive/transfer/dictionary-copy-specs.js +29 -0
  75. package/lib/archive/transfer/drop-transfer-temp-tables.d.ts +9 -0
  76. package/lib/archive/transfer/drop-transfer-temp-tables.js +18 -0
  77. package/lib/archive/transfer/flatten-redirect-chains.d.ts +44 -0
  78. package/lib/archive/transfer/flatten-redirect-chains.js +74 -0
  79. package/lib/archive/transfer/insert-content-items.d.ts +35 -0
  80. package/lib/archive/transfer/insert-content-items.js +116 -0
  81. package/lib/archive/transfer/list-transfer-columns.d.ts +35 -0
  82. package/lib/archive/transfer/list-transfer-columns.js +45 -0
  83. package/lib/archive/transfer/mark-in-scope-content-items.d.ts +31 -0
  84. package/lib/archive/transfer/mark-in-scope-content-items.js +54 -0
  85. package/lib/archive/transfer/merge-archive-configs.d.ts +51 -0
  86. package/lib/archive/transfer/merge-archive-configs.js +85 -0
  87. package/lib/archive/transfer/plan-content-items-for-concat.d.ts +33 -0
  88. package/lib/archive/transfer/plan-content-items-for-concat.js +51 -0
  89. package/lib/archive/transfer/plan-content-items-for-split.d.ts +42 -0
  90. package/lib/archive/transfer/plan-content-items-for-split.js +83 -0
  91. package/lib/archive/transfer/plan-resource-items.d.ts +40 -0
  92. package/lib/archive/transfer/plan-resource-items.js +69 -0
  93. package/lib/archive/transfer/quote-transfer-identifier.d.ts +18 -0
  94. package/lib/archive/transfer/quote-transfer-identifier.js +20 -0
  95. package/lib/archive/transfer/reclassify-resource-externality.d.ts +37 -0
  96. package/lib/archive/transfer/reclassify-resource-externality.js +66 -0
  97. package/lib/archive/transfer/remap-redirect-dest-ids.d.ts +34 -0
  98. package/lib/archive/transfer/remap-redirect-dest-ids.js +51 -0
  99. package/lib/archive/transfer/replace-content-items.d.ts +39 -0
  100. package/lib/archive/transfer/replace-content-items.js +83 -0
  101. package/lib/archive/transfer/simple-page-scoped-tables.d.ts +25 -0
  102. package/lib/archive/transfer/simple-page-scoped-tables.js +38 -0
  103. package/lib/archive/transfer/split-archive.d.ts +55 -0
  104. package/lib/archive/transfer/split-archive.js +98 -0
  105. package/lib/archive/transfer/transfer-action.d.ts +34 -0
  106. package/lib/archive/transfer/transfer-action.js +32 -0
  107. package/lib/archive/transfer/transfer-archive-rows.d.ts +65 -0
  108. package/lib/archive/transfer/transfer-archive-rows.js +158 -0
  109. package/lib/archive/transfer/transfer-dictionary-tables.d.ts +12 -0
  110. package/lib/archive/transfer/transfer-dictionary-tables.js +23 -0
  111. package/lib/archive/transfer/transfer-source-alias.d.ts +9 -0
  112. package/lib/archive/transfer/transfer-source-alias.js +9 -0
  113. package/lib/archive/transfer/types.d.ts +111 -0
  114. package/lib/archive/transfer/types.js +35 -0
  115. package/lib/archive/types.d.ts +10 -0
  116. package/lib/concat-source-transfer-phases.d.ts +10 -0
  117. package/lib/concat-source-transfer-phases.js +17 -0
  118. package/lib/crawler/apply-request-header-interception.d.ts +22 -0
  119. package/lib/crawler/apply-request-header-interception.js +28 -0
  120. package/lib/crawler/build-scope-map.d.ts +21 -0
  121. package/lib/crawler/build-scope-map.js +32 -0
  122. package/lib/crawler/crawler.js +34 -0
  123. package/lib/crawler/create-scoped-header-request-handler.d.ts +40 -0
  124. package/lib/crawler/create-scoped-header-request-handler.js +64 -0
  125. package/lib/crawler/create-strip-headers-on-redirect.d.ts +41 -0
  126. package/lib/crawler/create-strip-headers-on-redirect.js +67 -0
  127. package/lib/crawler/fetch-destination.d.ts +14 -0
  128. package/lib/crawler/fetch-destination.js +56 -9
  129. package/lib/crawler/fetch-robots-txt.d.ts +7 -0
  130. package/lib/crawler/fetch-robots-txt.js +7 -0
  131. package/lib/crawler/scan-js-resource-for-license-comment.d.ts +6 -0
  132. package/lib/crawler/scan-js-resource-for-license-comment.js +6 -0
  133. package/lib/crawler/types.d.ts +44 -0
  134. package/lib/crawler-orchestrator.d.ts +6 -0
  135. package/lib/crawler-orchestrator.js +17 -17
  136. package/lib/crawler.d.ts +14 -1
  137. package/lib/crawler.js +23 -0
  138. package/lib/split-source-transfer-phases.d.ts +11 -0
  139. package/lib/split-source-transfer-phases.js +18 -0
  140. package/lib/template-classification/classify-archive-page-templates.d.ts +41 -0
  141. package/lib/template-classification/classify-archive-page-templates.js +79 -0
  142. package/lib/template-classification/classify-page-templates.d.ts +37 -0
  143. package/lib/template-classification/classify-page-templates.js +69 -0
  144. package/lib/template-classification/collect-page-stylesheet-urls.d.ts +32 -0
  145. package/lib/template-classification/collect-page-stylesheet-urls.js +130 -0
  146. package/lib/template-classification/create-content-root-hint.d.ts +36 -0
  147. package/lib/template-classification/create-content-root-hint.js +47 -0
  148. package/lib/template-classification/create-page-cluster-factory.d.ts +60 -0
  149. package/lib/template-classification/create-page-cluster-factory.js +98 -0
  150. package/lib/template-classification/types.d.ts +108 -0
  151. package/lib/template-classification/types.js +1 -0
  152. package/lib/transfer-post-phases.d.ts +10 -0
  153. package/lib/transfer-post-phases.js +13 -0
  154. package/lib/utils/object/redact-request-headers.d.ts +15 -0
  155. package/lib/utils/object/redact-request-headers.js +27 -0
  156. package/package.json +4 -3
  157. package/lib/archive/db-ops/analysis/replace-page-templates.js +0 -84
  158. /package/lib/archive/db-ops/{analysis → templates}/types.js +0 -0
@@ -1,4 +1,4 @@
1
- import type { TemplateClusterReason } from './db-ops/analysis/types.js';
1
+ import type { TemplateClusterReason } from './db-ops/templates/types.js';
2
2
  import type { Config, DedupeCapObservationRow, InsertDedupeCapEventParams, InsertNetworkOutageParams, ListReconcileRunMeta, PageSource } from './types.js';
3
3
  import type { OutageWindow } from '../is-within-outage-window.js';
4
4
  import type { PageData, CrawlerError, Resource } from '../utils/types/types.js';
@@ -310,13 +310,14 @@ export default class Archive extends ArchiveAccessor {
310
310
  }[]): Promise<void>;
311
311
  /**
312
312
  * Replaces the archive's DOM-structure template classification
313
- * (`--templates`) with a fresh SQL-backed set.
313
+ * with a fresh SQL-backed set.
314
314
  *
315
315
  * Thin facade over {@link Database.replacePageTemplates}; kept on
316
- * `Archive` so the analyze pipeline can persist template keys without
316
+ * `Archive` so the crawl-end classification step
317
+ * (`classifyArchivePageTemplates`) can persist template keys without
317
318
  * reaching into the low-level database class directly.
318
319
  * @param templateKeysByUrl - Page URL → template key, as produced by
319
- * `@nitpicker/core`'s `classifyPageTemplates`.
320
+ * `classifyPageTemplates`.
320
321
  * @param clusterReasonsByTemplateKey - Template key → cluster-selection
321
322
  * evidence, if the caller captured it. Omitting this always clears the
322
323
  * previously-stored reasons too — "no reason" means "not captured for
@@ -610,6 +611,13 @@ export default class Archive extends ArchiveAccessor {
610
611
  * @param namespace - Optional namespace forwarded to {@link ArchiveAccessor}.
611
612
  * @param onExtractProgress - Forwarded to {@link extractArchiveToCache} —
612
613
  * see that function's docs for the cache-hit/miss contract.
614
+ * @param onLog - Forwarded to the cache-miss migration pass (issue #294)
615
+ * — a legacy archive's self-healing schema migrations otherwise fall
616
+ * back to a bare `console.error`, which can print mid-redraw of a
617
+ * caller's `Lanes`/`TaskList` display. Omit for that fallback
618
+ * (existing callers — the viewer, MCP, query CLI — do not pass this;
619
+ * only callers driving a `TaskList` row for the extraction, like
620
+ * `concat`/`split`, need to).
613
621
  * @returns A read-only {@link ArchiveAccessor} backed by the cache directory.
614
622
  * @example
615
623
  * ```ts
@@ -618,7 +626,7 @@ export default class Archive extends ArchiveAccessor {
618
626
  * // tears down DB handle on scope exit; cacheDir persists.
619
627
  * ```
620
628
  */
621
- static openCached(filePath: string, namespace?: string | null, onExtractProgress?: (readBytes: number, totalBytes: number) => void): Promise<ArchiveAccessor>;
629
+ static openCached(filePath: string, namespace?: string | null, onExtractProgress?: (readBytes: number, totalBytes: number) => void, onLog?: (message: string) => void): Promise<ArchiveAccessor>;
622
630
  /**
623
631
  * Creates a new archive at the specified file path.
624
632
  * Initializes a temporary working directory and a fresh SQLite database.
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path';
2
+ import { redactRequestHeaders } from '../utils/object/redact-request-headers.js';
2
3
  import { ArchiveAccessor } from './archive-accessor.js';
3
4
  import { acquireArchiveLock } from './archive-lock.js';
4
5
  import { computeArchiveCacheKey } from './cache/compute-archive-cache-key.js';
@@ -417,13 +418,14 @@ export default class Archive extends ArchiveAccessor {
417
418
  }
418
419
  /**
419
420
  * Replaces the archive's DOM-structure template classification
420
- * (`--templates`) with a fresh SQL-backed set.
421
+ * with a fresh SQL-backed set.
421
422
  *
422
423
  * Thin facade over {@link Database.replacePageTemplates}; kept on
423
- * `Archive` so the analyze pipeline can persist template keys without
424
+ * `Archive` so the crawl-end classification step
425
+ * (`classifyArchivePageTemplates`) can persist template keys without
424
426
  * reaching into the low-level database class directly.
425
427
  * @param templateKeysByUrl - Page URL → template key, as produced by
426
- * `@nitpicker/core`'s `classifyPageTemplates`.
428
+ * `classifyPageTemplates`.
427
429
  * @param clusterReasonsByTemplateKey - Template key → cluster-selection
428
430
  * evidence, if the caller captured it. Omitting this always clears the
429
431
  * previously-stored reasons too — "no reason" means "not captured for
@@ -510,7 +512,7 @@ export default class Archive extends ArchiveAccessor {
510
512
  * @param config - The configuration object to store.
511
513
  */
512
514
  async setConfig(config) {
513
- dbLog('Set config: %O', config);
515
+ dbLog('Set config: %O', redactRequestHeaders(config));
514
516
  return this.#db.setConfig(config);
515
517
  }
516
518
  /**
@@ -628,7 +630,7 @@ export default class Archive extends ArchiveAccessor {
628
630
  * @param patch - Partial {@link Config} fields to overwrite. `undefined` values are ignored.
629
631
  */
630
632
  async updateConfig(patch) {
631
- dbLog('Update config: %O', patch);
633
+ dbLog('Update config: %O', redactRequestHeaders(patch));
632
634
  await this.#db.updateConfig(patch);
633
635
  }
634
636
  /**
@@ -825,6 +827,13 @@ export default class Archive extends ArchiveAccessor {
825
827
  * @param namespace - Optional namespace forwarded to {@link ArchiveAccessor}.
826
828
  * @param onExtractProgress - Forwarded to {@link extractArchiveToCache} —
827
829
  * see that function's docs for the cache-hit/miss contract.
830
+ * @param onLog - Forwarded to the cache-miss migration pass (issue #294)
831
+ * — a legacy archive's self-healing schema migrations otherwise fall
832
+ * back to a bare `console.error`, which can print mid-redraw of a
833
+ * caller's `Lanes`/`TaskList` display. Omit for that fallback
834
+ * (existing callers — the viewer, MCP, query CLI — do not pass this;
835
+ * only callers driving a `TaskList` row for the extraction, like
836
+ * `concat`/`split`, need to).
828
837
  * @returns A read-only {@link ArchiveAccessor} backed by the cache directory.
829
838
  * @example
830
839
  * ```ts
@@ -833,12 +842,12 @@ export default class Archive extends ArchiveAccessor {
833
842
  * // tears down DB handle on scope exit; cacheDir persists.
834
843
  * ```
835
844
  */
836
- static async openCached(filePath, namespace = null, onExtractProgress) {
845
+ static async openCached(filePath, namespace = null, onExtractProgress, onLog) {
837
846
  const cacheRoot = getArchiveCacheRoot();
838
847
  const cacheKey = await computeArchiveCacheKey(filePath);
839
848
  const cacheDir = resolveArchiveCacheDir(cacheRoot, cacheKey, filePath);
840
849
  log('Open cached: %s (cacheDir=%s)', filePath, cacheDir);
841
- await extractArchiveToCache(filePath, cacheRoot, cacheDir, cacheKey, onExtractProgress);
850
+ await extractArchiveToCache(filePath, cacheRoot, cacheDir, cacheKey, onExtractProgress, onLog);
842
851
  return await Archive.connect(cacheDir, namespace);
843
852
  }
844
853
  /**
@@ -47,6 +47,11 @@
47
47
  * first call actually arrives. Only the first concurrent caller for a
48
48
  * given `cacheDir` sees callbacks; same-`cacheDir` callers deduped
49
49
  * through {@link inFlightByCacheDir} just await the shared promise.
50
+ * @param onLog - Forwarded to the cache-miss writer connection
51
+ * (`runMigrationsOnCacheDir`'s `Database.connect`) so a legacy archive's
52
+ * self-healing schema migrations do not fall back to a bare
53
+ * `console.error` mid-redraw of a caller's display (issue #294). Omit for
54
+ * that fallback — see `Archive.openCached`'s own `onLog` doc.
50
55
  * @returns Resolves once `cacheDir` is ready to be opened read-only.
51
56
  */
52
- export declare function extractArchiveToCache(archivePath: string, cacheRoot: string, cacheDir: string, cacheKey: string, onExtractProgress?: (readBytes: number, totalBytes: number) => void): Promise<void>;
57
+ export declare function extractArchiveToCache(archivePath: string, cacheRoot: string, cacheDir: string, cacheKey: string, onExtractProgress?: (readBytes: number, totalBytes: number) => void, onLog?: (message: string) => void): Promise<void>;
@@ -95,9 +95,14 @@ const inFlightByCacheDir = new Map();
95
95
  * first call actually arrives. Only the first concurrent caller for a
96
96
  * given `cacheDir` sees callbacks; same-`cacheDir` callers deduped
97
97
  * through {@link inFlightByCacheDir} just await the shared promise.
98
+ * @param onLog - Forwarded to the cache-miss writer connection
99
+ * (`runMigrationsOnCacheDir`'s `Database.connect`) so a legacy archive's
100
+ * self-healing schema migrations do not fall back to a bare
101
+ * `console.error` mid-redraw of a caller's display (issue #294). Omit for
102
+ * that fallback — see `Archive.openCached`'s own `onLog` doc.
98
103
  * @returns Resolves once `cacheDir` is ready to be opened read-only.
99
104
  */
100
- export async function extractArchiveToCache(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress) {
105
+ export async function extractArchiveToCache(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress, onLog) {
101
106
  if (await isCacheDirReady(cacheDir)) {
102
107
  return;
103
108
  }
@@ -105,7 +110,7 @@ export async function extractArchiveToCache(archivePath, cacheRoot, cacheDir, ca
105
110
  if (existing) {
106
111
  return existing;
107
112
  }
108
- const promise = runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress).finally(() => {
113
+ const promise = runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress, onLog).finally(() => {
109
114
  inFlightByCacheDir.delete(cacheDir);
110
115
  });
111
116
  inFlightByCacheDir.set(cacheDir, promise);
@@ -120,8 +125,9 @@ export async function extractArchiveToCache(archivePath, cacheRoot, cacheDir, ca
120
125
  * @param cacheDir - Absolute path the extracted contents should end up at.
121
126
  * @param cacheKey - Pre-extraction cache key, re-verified post-extraction.
122
127
  * @param onExtractProgress - See {@link extractArchiveToCache}.
128
+ * @param onLog - See {@link extractArchiveToCache}.
123
129
  */
124
- async function runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress) {
130
+ async function runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtractProgress, onLog) {
125
131
  await fs.mkdir(cacheRoot, { recursive: true });
126
132
  const releaseLock = await acquireLockWithPeerWait(cacheDir);
127
133
  try {
@@ -167,7 +173,7 @@ async function runExtraction(archivePath, cacheRoot, cacheDir, cacheKey, onExtra
167
173
  // cache entry so the next caller does not get stuck on a
168
174
  // "ready"-marked but broken cache.
169
175
  try {
170
- await runMigrationsOnCacheDir(cacheDir);
176
+ await runMigrationsOnCacheDir(cacheDir, onLog);
171
177
  }
172
178
  catch (error) {
173
179
  await fs.rm(cacheDir, { recursive: true, force: true });
@@ -214,13 +220,14 @@ async function acquireLockWithPeerWait(cacheDir) {
214
220
  * `Archive.connect` read-only open never needs to mutate the cache dir
215
221
  * (and never silently misses a newly-added column).
216
222
  * @param cacheDir - Absolute path to the freshly-extracted cache dir.
223
+ * @param onLog - See {@link extractArchiveToCache}.
217
224
  */
218
- async function runMigrationsOnCacheDir(cacheDir) {
225
+ async function runMigrationsOnCacheDir(cacheDir, onLog) {
219
226
  const dbPath = path.join(cacheDir, 'db.sqlite');
220
227
  if (!(await fileExists(dbPath))) {
221
228
  throw new Error(`Cache directory does not contain db.sqlite: ${cacheDir}`);
222
229
  }
223
- const db = await Database.connect({ filename: dbPath, readOnly: false });
230
+ const db = await Database.connect({ filename: dbPath, readOnly: false, onLog });
224
231
  try {
225
232
  // `Database.connect` ran migrations during init. Closing here
226
233
  // flushes WAL + drops the handle so the read-only re-open in
@@ -32,13 +32,6 @@ import type { Knex } from 'knex';
32
32
  * `crawlEnd`)
33
33
  * - `analysis_text_refs` + `analysis_violations` — analyze-phase findings,
34
34
  * FK → `content_items(id)`
35
- * - `page_templates` — DOM-structure template classification (`--templates`,
36
- * `@nitpicker/core`'s `template-classification/`), one row per classified
37
- * page, FK → `content_items(id)`
38
- * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
39
- * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
40
- * `template_key` is not a `page_templates` FK target, so consistency is
41
- * maintained by replacing both tables together, not by a foreign key)
42
35
  * - `page_html_blobs` + `page_html_ref` — content-addressable HTML
43
36
  * snapshots, FK → `content_items(id)`
44
37
  * - `console_log_items` — content-addressable dictionary of distinct
@@ -31,13 +31,6 @@
31
31
  * `crawlEnd`)
32
32
  * - `analysis_text_refs` + `analysis_violations` — analyze-phase findings,
33
33
  * FK → `content_items(id)`
34
- * - `page_templates` — DOM-structure template classification (`--templates`,
35
- * `@nitpicker/core`'s `template-classification/`), one row per classified
36
- * page, FK → `content_items(id)`
37
- * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
38
- * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
39
- * `template_key` is not a `page_templates` FK target, so consistency is
40
- * maintained by replacing both tables together, not by a foreign key)
41
34
  * - `page_html_blobs` + `page_html_ref` — content-addressable HTML
42
35
  * snapshots, FK → `content_items(id)`
43
36
  * - `console_log_items` — content-addressable dictionary of distinct
@@ -470,49 +463,6 @@ export async function createAdjunctTables(instance) {
470
463
  await instance.raw('CREATE INDEX av_code_order ON analysis_violations(code_sort_key, id)');
471
464
  await instance.raw('CREATE INDEX av_page ON analysis_violations(page_id, id)');
472
465
  }
473
- // DOM-structure template classification (`--templates`). One row per
474
- // internal HTML page that was classified; `page_id` is both the PK and
475
- // the natural key (1:1 with `content_items`), so — unlike
476
- // `analysis_violations`, which is 1:many and needs a surrogate `id` —
477
- // there's nothing to index beyond the PK itself. `WITHOUT ROWID` packs
478
- // rows directly in the PK b-tree, matching `page_html_ref`'s shape
479
- // (small fixed-width row, PK-only lookups).
480
- if (!(await instance.schema.hasTable('page_templates'))) {
481
- await instance.raw(`
482
- CREATE TABLE page_templates (
483
- page_id INTEGER PRIMARY KEY REFERENCES content_items(id),
484
- template_key TEXT NOT NULL
485
- ) WITHOUT ROWID
486
- `);
487
- }
488
- // One row per distinct `template_key` produced by the same `--templates`
489
- // classification run, holding `@d-zero/page-cluster`'s cluster-selection
490
- // evidence (`ClusterReason`, renamed `TemplateClusterReason` on this side)
491
- // as a zstd-compressed JSON blob — same BLOB+codec+size shape as
492
- // `page_html_blobs` below. A column on `page_templates` was rejected: that
493
- // table is one row per *page*, so the same cluster's reason would be
494
- // duplicated across every member page (multi-GB on a large archive with a
495
- // few-hundred-member cluster). A `json_refs` row was also rejected: reason
496
- // payloads differ per cluster (distinct `memberCount`/token sets), so
497
- // content-address dedup would not pay for itself, and `json_refs` is a
498
- // shared dictionary that other tables reference — this table's full
499
- // replace-on-every-run write pattern (see `replacePageTemplates`) would
500
- // otherwise leave orphaned rows behind with no owner able to delete them.
501
- // No FK to `page_templates`: `template_key` is not that table's primary
502
- // key (`page_id` is), so there is nothing to reference — consistency is
503
- // instead maintained by replacing both tables in the same transaction.
504
- if (!(await instance.schema.hasTable('page_template_clusters'))) {
505
- await instance.raw(`
506
- CREATE TABLE page_template_clusters (
507
- template_key TEXT PRIMARY KEY,
508
- member_count INTEGER NOT NULL,
509
- reason_json BLOB NOT NULL,
510
- codec TEXT NOT NULL CHECK(codec IN ('zstd', 'none')),
511
- size_raw INTEGER NOT NULL,
512
- size_stored INTEGER NOT NULL
513
- ) WITHOUT ROWID
514
- `);
515
- }
516
466
  // Content-addressable HTML blob storage. Knex's schema builder doesn't
517
467
  // expose a WITHOUT ROWID toggle, so the BLOB tables are created via raw
518
468
  // SQL. WITHOUT ROWID keeps the rows packed inside the b-tree leaves
@@ -0,0 +1,30 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Creates the DOM-structure template classification tables. Kept apart from
4
+ * `createAdjunctTables` because the classification is a derived,
5
+ * archive-wide computation produced by its own crawl-end step
6
+ * (`classifyArchivePageTemplates`), not an observation the crawler writes per
7
+ * page and not an analyze-plugin output (`analysis_violations`) — the two
8
+ * lifecycles and their write paths (`db-ops/templates/` vs `db-ops/analysis/`)
9
+ * share nothing.
10
+ *
11
+ * - `page_templates` — one row per classified page, FK → `content_items(id)`
12
+ * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
13
+ * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
14
+ * `template_key` is not a `page_templates` FK target, so consistency is
15
+ * maintained by replacing both tables together, not by a foreign key)
16
+ * - `page_template_labels` — one row per template key: the stable
17
+ * human-facing name (`events template A`) carried forward across
18
+ * re-classifications (no FK, same reason)
19
+ *
20
+ * Each table is guarded individually (same convergence rule as
21
+ * `createAdjunctTables`) and `initSchema` runs this on every open, so
22
+ * archives created before these tables existed gain them on their next
23
+ * writer open. MUST run after `createEntityTables` because `page_templates`
24
+ * references `content_items(id)`.
25
+ * @param instance - The Knex query builder instance connected to the database.
26
+ * @example
27
+ * await createEntityTables(db);
28
+ * await createTemplateTables(db);
29
+ */
30
+ export declare function createTemplateTables(instance: Knex): Promise<void>;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Creates the DOM-structure template classification tables. Kept apart from
3
+ * `createAdjunctTables` because the classification is a derived,
4
+ * archive-wide computation produced by its own crawl-end step
5
+ * (`classifyArchivePageTemplates`), not an observation the crawler writes per
6
+ * page and not an analyze-plugin output (`analysis_violations`) — the two
7
+ * lifecycles and their write paths (`db-ops/templates/` vs `db-ops/analysis/`)
8
+ * share nothing.
9
+ *
10
+ * - `page_templates` — one row per classified page, FK → `content_items(id)`
11
+ * - `page_template_clusters` — one row per distinct `page_templates.template_key`,
12
+ * holding `@d-zero/page-cluster`'s cluster-selection evidence (no FK;
13
+ * `template_key` is not a `page_templates` FK target, so consistency is
14
+ * maintained by replacing both tables together, not by a foreign key)
15
+ * - `page_template_labels` — one row per template key: the stable
16
+ * human-facing name (`events template A`) carried forward across
17
+ * re-classifications (no FK, same reason)
18
+ *
19
+ * Each table is guarded individually (same convergence rule as
20
+ * `createAdjunctTables`) and `initSchema` runs this on every open, so
21
+ * archives created before these tables existed gain them on their next
22
+ * writer open. MUST run after `createEntityTables` because `page_templates`
23
+ * references `content_items(id)`.
24
+ * @param instance - The Knex query builder instance connected to the database.
25
+ * @example
26
+ * await createEntityTables(db);
27
+ * await createTemplateTables(db);
28
+ */
29
+ export async function createTemplateTables(instance) {
30
+ // One row per internal HTML page that was classified; `page_id` is both
31
+ // the PK and the natural key (1:1 with `content_items`), so — unlike
32
+ // `analysis_violations`, which is 1:many and needs a surrogate `id` —
33
+ // there's nothing to index beyond the PK itself. `WITHOUT ROWID` packs
34
+ // rows directly in the PK b-tree, matching `page_html_ref`'s shape
35
+ // (small fixed-width row, PK-only lookups).
36
+ if (!(await instance.schema.hasTable('page_templates'))) {
37
+ await instance.raw(`
38
+ CREATE TABLE page_templates (
39
+ page_id INTEGER PRIMARY KEY REFERENCES content_items(id),
40
+ template_key TEXT NOT NULL
41
+ ) WITHOUT ROWID
42
+ `);
43
+ }
44
+ // One row per distinct `template_key` produced by the same classification
45
+ // run, holding `@d-zero/page-cluster`'s cluster-selection evidence
46
+ // (`ClusterReason`, renamed `TemplateClusterReason` on this side) as a
47
+ // zstd-compressed JSON blob — same BLOB+codec+size shape as
48
+ // `page_html_blobs`. A column on `page_templates` was rejected: that
49
+ // table is one row per *page*, so the same cluster's reason would be
50
+ // duplicated across every member page (multi-GB on a large archive with a
51
+ // few-hundred-member cluster). A `json_refs` row was also rejected: reason
52
+ // payloads differ per cluster (distinct `memberCount`/token sets), so
53
+ // content-address dedup would not pay for itself, and `json_refs` is a
54
+ // shared dictionary that other tables reference — this table's full
55
+ // replace-on-every-run write pattern (see `replacePageTemplates`) would
56
+ // otherwise leave orphaned rows behind with no owner able to delete them.
57
+ // No FK to `page_templates`: `template_key` is not that table's primary
58
+ // key (`page_id` is), so there is nothing to reference — consistency is
59
+ // instead maintained by replacing both tables in the same transaction.
60
+ if (!(await instance.schema.hasTable('page_template_clusters'))) {
61
+ await instance.raw(`
62
+ CREATE TABLE page_template_clusters (
63
+ template_key TEXT PRIMARY KEY,
64
+ member_count INTEGER NOT NULL,
65
+ reason_json BLOB NOT NULL,
66
+ codec TEXT NOT NULL CHECK(codec IN ('zstd', 'none')),
67
+ size_raw INTEGER NOT NULL,
68
+ size_stored INTEGER NOT NULL
69
+ ) WITHOUT ROWID
70
+ `);
71
+ }
72
+ // One row per distinct `page_templates.template_key`: the human-facing
73
+ // label (`<section> template <letter>`) assigned to that cluster by
74
+ // `assignTemplateLabels` when `replacePageTemplates` wrote it. Stored
75
+ // rather than derived at read time because a label's whole point is to
76
+ // stay attached to the same template across re-classifications, and
77
+ // nothing derivable from the key alone survives one — `cluster:<n>` is
78
+ // the library's per-run index and `css:<hash>` changes with the
79
+ // stylesheet set. `replacePageTemplates` carries labels forward by member
80
+ // overlap against the previous run's `page_templates` before replacing
81
+ // it. Kept apart from `page_template_clusters` because that table's rows
82
+ // are best-effort (a cluster may have no captured reason) while every
83
+ // cluster gets a label. `section` is NULL for a site-wide label (members
84
+ // span several top-level directories). No FK, same reasoning as
85
+ // `page_template_clusters`.
86
+ if (!(await instance.schema.hasTable('page_template_labels'))) {
87
+ await instance.raw(`
88
+ CREATE TABLE page_template_labels (
89
+ template_key TEXT PRIMARY KEY,
90
+ section TEXT,
91
+ ordinal INTEGER NOT NULL
92
+ ) WITHOUT ROWID
93
+ `);
94
+ }
95
+ }
@@ -1,4 +1,4 @@
1
- import type { TemplateClusterReason } from './db-ops/analysis/types.js';
1
+ import type { TemplateClusterReason } from './db-ops/templates/types.js';
2
2
  import type { JsonLdRow, MainContentAudioRow, MainContentButtonRow, MainContentCanvasRow, MainContentCustomElementRow, MainContentHeadingRow, MainContentIframeRow, MainContentImageRow, MainContentTableRow, MainContentVideoRow, PageTechnologyRow, TechnologySignalRow } from './meta/types.js';
3
3
  import type { Config, DatabaseOption, DB_Redirect, DB_Resource, DatabaseEvent, DedupeCapObservationRow, InsertDedupeCapEventParams, InsertNetworkOutageParams, ListReconcileRunMeta, PageFilter, PageSource, ResetPagesByUrlsResult } from './types.js';
4
4
  import type { OutageWindow } from '../is-within-outage-window.js';
@@ -8,7 +8,6 @@ import { emitError } from '../utils/error/emit-error.js';
8
8
  import { createWriteRefCaches } from './db-ops/_shared/create-write-ref-caches.js';
9
9
  import { retrySetting } from './db-ops/_shared/retry-setting.js';
10
10
  import { replaceAnalysisViolations as replaceAnalysisViolationsOp } from './db-ops/analysis/replace-analysis-violations.js';
11
- import { replacePageTemplates as replacePageTemplatesOp } from './db-ops/analysis/replace-page-templates.js';
12
11
  import { getAnchorsOnPage as getAnchorsOnPageOp } from './db-ops/anchors/get-anchors-on-page.js';
13
12
  import { getBaseUrl as getBaseUrlOp } from './db-ops/config/get-base-url.js';
14
13
  import { getConfig as getConfigOp } from './db-ops/config/get-config.js';
@@ -71,6 +70,7 @@ import { getResources as getResourcesOp } from './db-ops/resources/get-resources
71
70
  import { insertInventoryResources as insertInventoryResourcesOp } from './db-ops/resources/insert-inventory-resources.js';
72
71
  import { insertResourceReferrers as insertResourceReferrersOp } from './db-ops/resources/insert-resource-referrers.js';
73
72
  import { insertResource as insertResourceOp } from './db-ops/resources/insert-resource.js';
73
+ import { replacePageTemplates as replacePageTemplatesOp } from './db-ops/templates/replace-page-templates.js';
74
74
  import { mkdir } from './filesystem/mkdir.js';
75
75
  import { LibsqlDialect } from './libsql-dialect.js';
76
76
  /**
@@ -2,7 +2,7 @@ import type { Config } from '../../types.js';
2
2
  import type { Knex } from 'knex';
3
3
  /**
4
4
  * Retrieves the full crawl configuration from the `info` table.
5
- * Deserializes JSON-encoded fields (`roots`, `excludes`, `excludeKeywords`, `excludeUrls`).
5
+ * Deserializes JSON-encoded fields (`roots`, `excludes`, `excludeKeywords`, `excludeUrls`, `requestHeaderNames`).
6
6
  * @param knex - Knex query builder connected to the archive DB.
7
7
  * @returns The parsed {@link Config} object.
8
8
  * @throws {Error} If no configuration is found in the database.
@@ -2,7 +2,7 @@ import { dbLog } from '../../debug.js';
2
2
  import { getJSON } from '../../get-json.js';
3
3
  /**
4
4
  * Retrieves the full crawl configuration from the `info` table.
5
- * Deserializes JSON-encoded fields (`roots`, `excludes`, `excludeKeywords`, `excludeUrls`).
5
+ * Deserializes JSON-encoded fields (`roots`, `excludes`, `excludeKeywords`, `excludeUrls`, `requestHeaderNames`).
6
6
  * @param knex - Knex query builder connected to the archive DB.
7
7
  * @returns The parsed {@link Config} object.
8
8
  * @throws {Error} If no configuration is found in the database.
@@ -18,6 +18,7 @@ export async function getConfig(knex) {
18
18
  excludeKeywords: getJSON(config.excludeKeywords, []),
19
19
  excludeUrls: getJSON(config.excludeUrls, []),
20
20
  roots: getJSON(config.roots, []),
21
+ requestHeaderNames: getJSON(config.requestHeaderNames, []),
21
22
  retry: config.retry ?? 3,
22
23
  maxExcludedDepth: config.maxExcludedDepth ?? 0,
23
24
  };
@@ -24,5 +24,6 @@ export const INFO_COLUMN_ALLOWLIST = new Set([
24
24
  'userAgent',
25
25
  'ignoreRobots',
26
26
  'mainContentSelector',
27
+ 'requestHeaderNames',
27
28
  'createdCwd',
28
29
  ]);
@@ -7,4 +7,5 @@ export const INFO_JSON_COLUMNS = new Set([
7
7
  'excludes',
8
8
  'excludeKeywords',
9
9
  'excludeUrls',
10
+ 'requestHeaderNames',
10
11
  ]);
@@ -5,6 +5,7 @@ import { migrateContentItemsDedupeCapEventId } from '../../migrate-content-items
5
5
  import { migrateContentItemsIsMetadataOnly } from '../../migrate-content-items-is-metadata-only.js';
6
6
  import { migrateInfoCreatedCwd } from '../../migrate-info-created-cwd.js';
7
7
  import { migrateInfoMainContentSelector } from '../../migrate-info-main-content-selector.js';
8
+ import { migrateInfoRequestHeaderNames } from '../../migrate-info-request-header-names.js';
8
9
  import { migrateInfoRoots } from '../../migrate-info-roots.js';
9
10
  import { migrateInventoryRunsToListReconcileRuns } from '../../migrate-inventory-runs-to-list-reconcile-runs.js';
10
11
  import { migrateListReconcileRunsExcludeSkipped } from '../../migrate-list-reconcile-runs-exclude-skipped.js';
@@ -95,6 +96,7 @@ export async function init(knex, readOnly, onLog) {
95
96
  await initSchema(knex);
96
97
  await migrateInfoRoots(knex, onLog);
97
98
  await migrateInfoMainContentSelector(knex, onLog);
99
+ await migrateInfoRequestHeaderNames(knex, onLog);
98
100
  await migrateInfoCreatedCwd(knex, onLog);
99
101
  await migrateMainContentsColumns(knex, onLog);
100
102
  await migratePageMetaBodyHash(knex, onLog);
@@ -0,0 +1,60 @@
1
+ import type { AssignTemplateLabelsParams, TemplateLabel } from './types.js';
2
+ /**
3
+ * Assigns every cluster of a fresh template classification its
4
+ * {@link TemplateLabel}, carrying labels forward from the previous
5
+ * classification wherever the same template survived the re-run.
6
+ *
7
+ * ## Inheritance
8
+ *
9
+ * A new cluster inherits an old cluster's label when the two share a
10
+ * **mutual majority** of pages: the overlap is more than half of the new
11
+ * cluster *and* more than half of the old one. Mutual majority means at
12
+ * most one new cluster can claim a given old label, and a cluster that
13
+ * merely absorbed a few pages of a much larger old template does not steal
14
+ * its name. A split keeps the old label on the half that holds most of the
15
+ * old pages; the other half is named afresh.
16
+ *
17
+ * The old cluster's size counts only pages that are classified in the new
18
+ * run too. Pages the crawl has since dropped (`--recrawl` turned them into
19
+ * redirects, errors, …) are not evidence that the template changed, so
20
+ * they must not dilute the old half of the majority — otherwise an old
21
+ * 7-page cluster whose 4 missing pages left 3 unchanged ones would fail
22
+ * `3 > 7/2` and be renamed for no reason.
23
+ *
24
+ * Page ids are the identity used for overlap (not URLs) because they are
25
+ * what `page_templates` stores and they survive `--append` / `--recrawl`
26
+ * without renumbering.
27
+ *
28
+ * ## Fresh labels
29
+ *
30
+ * Clusters left without an inherited label are numbered in page-count
31
+ * order (largest first, template key as a tie-break) so a first run reads
32
+ * naturally: `A` is the section's biggest template. Each takes the next
33
+ * ordinal **after every ordinal in `previousLabels` for its section**, so a
34
+ * letter is never re-issued to a different template — which would silently
35
+ * change what "events template B" means between two people's archives.
36
+ * That guarantee is only as good as `previousLabels`: `replacePageTemplates`
37
+ * keeps the rows of clusters that disappeared (retired labels) precisely so
38
+ * they stay in this set across any number of later runs.
39
+ *
40
+ * ## Section
41
+ *
42
+ * A cluster's section is the first path segment every member URL shares
43
+ * (`events` for `/events/...`). Members spread over several segments, or
44
+ * all at the site root, yield `null`: such a cluster is numbered in the
45
+ * site-wide sequence. An inherited label keeps its old section even if the
46
+ * cluster's members have since drifted — stability of the name wins over
47
+ * keeping the section literally accurate.
48
+ * @param params - See {@link AssignTemplateLabelsParams}.
49
+ * @returns Template key → label, one entry per cluster in `params.clusters`.
50
+ * @example
51
+ * ```ts
52
+ * const labels = assignTemplateLabels({
53
+ * clusters: new Map([['["path:events","cluster:0"]', { pageIds: [1, 2], urls: ['https://example.com/events/a', 'https://example.com/events/b'] }]]),
54
+ * previousMembership: new Map(),
55
+ * previousLabels: new Map(),
56
+ * });
57
+ * labels.get('["path:events","cluster:0"]'); // { section: 'events', ordinal: 1 }
58
+ * ```
59
+ */
60
+ export declare function assignTemplateLabels(params: AssignTemplateLabelsParams): Map<string, TemplateLabel>;