@nitpicker/crawler 0.22.2 → 0.23.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 (133) hide show
  1. package/lib/archive/archive.d.ts +13 -5
  2. package/lib/archive/archive.js +13 -5
  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/templates/assign-template-labels.d.ts +60 -0
  12. package/lib/archive/db-ops/templates/assign-template-labels.js +187 -0
  13. package/lib/archive/db-ops/{analysis → templates}/replace-page-templates.d.ts +19 -3
  14. package/lib/archive/db-ops/templates/replace-page-templates.js +174 -0
  15. package/lib/archive/db-ops/{analysis → templates}/types.d.ts +38 -0
  16. package/lib/archive/init-schema.d.ts +5 -1
  17. package/lib/archive/init-schema.js +13 -2
  18. package/lib/archive/test-utils/build-full-schema-test-db.d.ts +34 -0
  19. package/lib/archive/test-utils/build-full-schema-test-db.js +74 -0
  20. package/lib/archive/transfer/attach-source-database.d.ts +31 -0
  21. package/lib/archive/transfer/attach-source-database.js +40 -0
  22. package/lib/archive/transfer/build-split-config.d.ts +30 -0
  23. package/lib/archive/transfer/build-split-config.js +42 -0
  24. package/lib/archive/transfer/clear-replaced-page-rows.d.ts +20 -0
  25. package/lib/archive/transfer/clear-replaced-page-rows.js +57 -0
  26. package/lib/archive/transfer/concat-archives.d.ts +55 -0
  27. package/lib/archive/transfer/concat-archives.js +95 -0
  28. package/lib/archive/transfer/content-item-rank-sql.d.ts +21 -0
  29. package/lib/archive/transfer/content-item-rank-sql.js +23 -0
  30. package/lib/archive/transfer/copy-analysis-violations.d.ts +19 -0
  31. package/lib/archive/transfer/copy-analysis-violations.js +43 -0
  32. package/lib/archive/transfer/copy-anchor-edges.d.ts +28 -0
  33. package/lib/archive/transfer/copy-anchor-edges.js +42 -0
  34. package/lib/archive/transfer/copy-dictionaries-for-concat.d.ts +39 -0
  35. package/lib/archive/transfer/copy-dictionaries-for-concat.js +81 -0
  36. package/lib/archive/transfer/copy-dictionaries-for-split.d.ts +29 -0
  37. package/lib/archive/transfer/copy-dictionaries-for-split.js +235 -0
  38. package/lib/archive/transfer/copy-header-set-children.d.ts +27 -0
  39. package/lib/archive/transfer/copy-header-set-children.js +51 -0
  40. package/lib/archive/transfer/copy-image-items.d.ts +21 -0
  41. package/lib/archive/transfer/copy-image-items.js +62 -0
  42. package/lib/archive/transfer/copy-inventory-source-lists.d.ts +30 -0
  43. package/lib/archive/transfer/copy-inventory-source-lists.js +61 -0
  44. package/lib/archive/transfer/copy-journal-tables.d.ts +30 -0
  45. package/lib/archive/transfer/copy-journal-tables.js +56 -0
  46. package/lib/archive/transfer/copy-page-console-logs.d.ts +16 -0
  47. package/lib/archive/transfer/copy-page-console-logs.js +27 -0
  48. package/lib/archive/transfer/copy-page-html-blobs.d.ts +31 -0
  49. package/lib/archive/transfer/copy-page-html-blobs.js +43 -0
  50. package/lib/archive/transfer/copy-page-meta.d.ts +27 -0
  51. package/lib/archive/transfer/copy-page-meta.js +68 -0
  52. package/lib/archive/transfer/copy-page-template-clusters.d.ts +31 -0
  53. package/lib/archive/transfer/copy-page-template-clusters.js +56 -0
  54. package/lib/archive/transfer/copy-page-template-labels.d.ts +34 -0
  55. package/lib/archive/transfer/copy-page-template-labels.js +88 -0
  56. package/lib/archive/transfer/copy-resource-items.d.ts +29 -0
  57. package/lib/archive/transfer/copy-resource-items.js +89 -0
  58. package/lib/archive/transfer/copy-resource-ref-edges.d.ts +20 -0
  59. package/lib/archive/transfer/copy-resource-ref-edges.js +33 -0
  60. package/lib/archive/transfer/copy-simple-page-scoped-tables.d.ts +15 -0
  61. package/lib/archive/transfer/copy-simple-page-scoped-tables.js +34 -0
  62. package/lib/archive/transfer/count-external-pages-in-scope.d.ts +26 -0
  63. package/lib/archive/transfer/count-external-pages-in-scope.js +40 -0
  64. package/lib/archive/transfer/create-transfer-temp-tables.d.ts +30 -0
  65. package/lib/archive/transfer/create-transfer-temp-tables.js +59 -0
  66. package/lib/archive/transfer/dictionary-copy-specs.d.ts +32 -0
  67. package/lib/archive/transfer/dictionary-copy-specs.js +29 -0
  68. package/lib/archive/transfer/drop-transfer-temp-tables.d.ts +9 -0
  69. package/lib/archive/transfer/drop-transfer-temp-tables.js +18 -0
  70. package/lib/archive/transfer/flatten-redirect-chains.d.ts +44 -0
  71. package/lib/archive/transfer/flatten-redirect-chains.js +74 -0
  72. package/lib/archive/transfer/insert-content-items.d.ts +35 -0
  73. package/lib/archive/transfer/insert-content-items.js +116 -0
  74. package/lib/archive/transfer/list-transfer-columns.d.ts +35 -0
  75. package/lib/archive/transfer/list-transfer-columns.js +45 -0
  76. package/lib/archive/transfer/mark-in-scope-content-items.d.ts +31 -0
  77. package/lib/archive/transfer/mark-in-scope-content-items.js +54 -0
  78. package/lib/archive/transfer/merge-archive-configs.d.ts +48 -0
  79. package/lib/archive/transfer/merge-archive-configs.js +78 -0
  80. package/lib/archive/transfer/plan-content-items-for-concat.d.ts +33 -0
  81. package/lib/archive/transfer/plan-content-items-for-concat.js +51 -0
  82. package/lib/archive/transfer/plan-content-items-for-split.d.ts +42 -0
  83. package/lib/archive/transfer/plan-content-items-for-split.js +83 -0
  84. package/lib/archive/transfer/plan-resource-items.d.ts +40 -0
  85. package/lib/archive/transfer/plan-resource-items.js +69 -0
  86. package/lib/archive/transfer/quote-transfer-identifier.d.ts +18 -0
  87. package/lib/archive/transfer/quote-transfer-identifier.js +20 -0
  88. package/lib/archive/transfer/reclassify-resource-externality.d.ts +37 -0
  89. package/lib/archive/transfer/reclassify-resource-externality.js +66 -0
  90. package/lib/archive/transfer/remap-redirect-dest-ids.d.ts +34 -0
  91. package/lib/archive/transfer/remap-redirect-dest-ids.js +51 -0
  92. package/lib/archive/transfer/replace-content-items.d.ts +39 -0
  93. package/lib/archive/transfer/replace-content-items.js +83 -0
  94. package/lib/archive/transfer/simple-page-scoped-tables.d.ts +25 -0
  95. package/lib/archive/transfer/simple-page-scoped-tables.js +38 -0
  96. package/lib/archive/transfer/split-archive.d.ts +55 -0
  97. package/lib/archive/transfer/split-archive.js +98 -0
  98. package/lib/archive/transfer/transfer-action.d.ts +34 -0
  99. package/lib/archive/transfer/transfer-action.js +32 -0
  100. package/lib/archive/transfer/transfer-archive-rows.d.ts +65 -0
  101. package/lib/archive/transfer/transfer-archive-rows.js +158 -0
  102. package/lib/archive/transfer/transfer-dictionary-tables.d.ts +12 -0
  103. package/lib/archive/transfer/transfer-dictionary-tables.js +23 -0
  104. package/lib/archive/transfer/transfer-source-alias.d.ts +9 -0
  105. package/lib/archive/transfer/transfer-source-alias.js +9 -0
  106. package/lib/archive/transfer/types.d.ts +111 -0
  107. package/lib/archive/transfer/types.js +35 -0
  108. package/lib/concat-source-transfer-phases.d.ts +10 -0
  109. package/lib/concat-source-transfer-phases.js +17 -0
  110. package/lib/crawler/build-scope-map.d.ts +21 -0
  111. package/lib/crawler/build-scope-map.js +32 -0
  112. package/lib/crawler-orchestrator.js +3 -16
  113. package/lib/crawler.d.ts +13 -1
  114. package/lib/crawler.js +22 -0
  115. package/lib/split-source-transfer-phases.d.ts +11 -0
  116. package/lib/split-source-transfer-phases.js +18 -0
  117. package/lib/template-classification/classify-archive-page-templates.d.ts +41 -0
  118. package/lib/template-classification/classify-archive-page-templates.js +79 -0
  119. package/lib/template-classification/classify-page-templates.d.ts +37 -0
  120. package/lib/template-classification/classify-page-templates.js +69 -0
  121. package/lib/template-classification/collect-page-stylesheet-urls.d.ts +32 -0
  122. package/lib/template-classification/collect-page-stylesheet-urls.js +130 -0
  123. package/lib/template-classification/create-content-root-hint.d.ts +36 -0
  124. package/lib/template-classification/create-content-root-hint.js +47 -0
  125. package/lib/template-classification/create-page-cluster-factory.d.ts +60 -0
  126. package/lib/template-classification/create-page-cluster-factory.js +98 -0
  127. package/lib/template-classification/types.d.ts +108 -0
  128. package/lib/template-classification/types.js +1 -0
  129. package/lib/transfer-post-phases.d.ts +10 -0
  130. package/lib/transfer-post-phases.js +13 -0
  131. package/package.json +3 -2
  132. package/lib/archive/db-ops/analysis/replace-page-templates.js +0 -84
  133. /package/lib/archive/db-ops/{analysis → templates}/types.js +0 -0
@@ -0,0 +1,158 @@
1
+ import { attachSourceDatabase } from './attach-source-database.js';
2
+ import { clearReplacedPageRows } from './clear-replaced-page-rows.js';
3
+ import { copyAnalysisViolations } from './copy-analysis-violations.js';
4
+ import { copyAnchorEdges } from './copy-anchor-edges.js';
5
+ import { copyDictionariesForConcat } from './copy-dictionaries-for-concat.js';
6
+ import { copyDictionariesForSplit } from './copy-dictionaries-for-split.js';
7
+ import { copyHeaderSetChildren } from './copy-header-set-children.js';
8
+ import { copyImageItems } from './copy-image-items.js';
9
+ import { copyJournalTables } from './copy-journal-tables.js';
10
+ import { copyPageConsoleLogs } from './copy-page-console-logs.js';
11
+ import { copyPageHtmlBlobs } from './copy-page-html-blobs.js';
12
+ import { copyPageMeta } from './copy-page-meta.js';
13
+ import { copyPageTemplateClusters } from './copy-page-template-clusters.js';
14
+ import { copyPageTemplateLabels } from './copy-page-template-labels.js';
15
+ import { copyResourceItems } from './copy-resource-items.js';
16
+ import { copyResourceRefEdges } from './copy-resource-ref-edges.js';
17
+ import { copySimplePageScopedTables } from './copy-simple-page-scoped-tables.js';
18
+ import { createTransferTempTables } from './create-transfer-temp-tables.js';
19
+ import { dropTransferTempTables } from './drop-transfer-temp-tables.js';
20
+ import { insertContentItems } from './insert-content-items.js';
21
+ import { markInScopeContentItems } from './mark-in-scope-content-items.js';
22
+ import { planContentItemsForConcat } from './plan-content-items-for-concat.js';
23
+ import { planContentItemsForSplit } from './plan-content-items-for-split.js';
24
+ import { planResourceItems } from './plan-resource-items.js';
25
+ import { remapRedirectDestIds } from './remap-redirect-dest-ids.js';
26
+ import { replaceContentItems } from './replace-content-items.js';
27
+ import { TRANSFER_ACTION } from './transfer-action.js';
28
+ import { TRANSFER_SOURCE_ALIAS } from './transfer-source-alias.js';
29
+ /**
30
+ * Computes {@link TransferSourceResult} from the finished plan tables.
31
+ * `dropped` (split only) is `sourceTotal - (inserted + stubbed)` — the
32
+ * plan never lists dropped rows explicitly, so this is a subtraction
33
+ * against the source's own total row count rather than a query for
34
+ * absence.
35
+ * @param trx - The open transaction.
36
+ * @param mode - `'split'` computes `dropped`; `'concat'` always reports `0`.
37
+ */
38
+ async function summarizeTransferResult(trx, mode) {
39
+ const rows = await trx
40
+ .select('action')
41
+ .count({ count: '*' })
42
+ .from('xfer_ci_plan')
43
+ .groupBy('action');
44
+ const byAction = new Map(rows.map((r) => [r.action, Number(r.count)]));
45
+ const inserted = byAction.get(TRANSFER_ACTION.full) ?? 0;
46
+ const replaced = byAction.get(TRANSFER_ACTION.replace) ?? 0;
47
+ const skipped = byAction.get(TRANSFER_ACTION.skip) ?? 0;
48
+ const stubbed = byAction.get(TRANSFER_ACTION.stub) ?? 0;
49
+ let dropped = 0;
50
+ if (mode === 'split') {
51
+ const [totalRow] = await trx
52
+ .count({ total: '*' })
53
+ .from(`${TRANSFER_SOURCE_ALIAS}.content_items`);
54
+ dropped = Number(totalRow?.total ?? 0) - (inserted + stubbed);
55
+ }
56
+ return { inserted, replaced, skipped, stubbed, dropped };
57
+ }
58
+ /**
59
+ * Transfers ONE source archive's rows into the destination — the shared
60
+ * engine {@link import('./concat-archives.js').concatArchives} and
61
+ * {@link import('./split-archive.js').splitArchive} both drive, once per
62
+ * source. Attaches the source, plans, copies every table in dependency
63
+ * order, and detaches — always, even on failure (`finally`).
64
+ *
65
+ * Order within the transaction (see each step's own docs for why this
66
+ * exact order, not a different one):
67
+ * 1. Plan `content_items` (mode-specific) and `resource_items`.
68
+ * 2. Copy every dictionary (mode-specific), then their `header_sets`
69
+ * children and `page_html_blobs` (both depend on the dictionary maps
70
+ * dictionaries step just built).
71
+ * 3. Concat only: clear the old page-scoped rows of every `replace`
72
+ * destination, then overwrite its `content_items` row. Both modes:
73
+ * insert every `full`/`stub` row, backfilling `dest_id`; remap
74
+ * `redirect_dest_id` now that every row has one.
75
+ * 4. Copy every page-scoped table.
76
+ * 5. Copy `resource_items` (and its js-scan cache), then
77
+ * `resource_ref_edges` (needs the resource plan's `dest_id`, just
78
+ * resolved).
79
+ * 6. Copy the append-only journal tables.
80
+ * @param options - See individual properties.
81
+ * @param options.knex - Knex connected to the destination archive DB (the
82
+ * connection ATTACH/temp-tables/transaction all operate against).
83
+ * @param options.sourceDbPath - Absolute path to the source's `db.sqlite`
84
+ * (e.g. `path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME)`).
85
+ * @param options.mode - `{ kind: 'concat' }`, or `{ kind: 'split',
86
+ * scopeMap, parseOptions? }` for the narrower-scope pass.
87
+ * @param options.crawlOrderOffset - Forwarded to
88
+ * `insertContentItems`/`replaceContentItems` — see their docs.
89
+ * @param options.sourceIndex - This source's 0-based position, forwarded
90
+ * verbatim to `callbacks` — purely for display, not used in any query.
91
+ * @param options.callbacks - Progress callbacks; see `types.ts`.
92
+ * @returns Per-action row counts — see {@link TransferSourceResult}.
93
+ * @example
94
+ * ```ts
95
+ * const result = await transferArchiveRows({
96
+ * knex: destination.getKnex(),
97
+ * sourceDbPath: path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME),
98
+ * mode: { kind: 'concat' },
99
+ * crawlOrderOffset: 0,
100
+ * sourceIndex: 0,
101
+ * });
102
+ * ```
103
+ */
104
+ export async function transferArchiveRows(options) {
105
+ const { knex, sourceDbPath, mode, crawlOrderOffset, sourceIndex, callbacks } = options;
106
+ const detach = await attachSourceDatabase(knex, sourceDbPath);
107
+ await createTransferTempTables(knex);
108
+ try {
109
+ return await knex.transaction(async (trx) => {
110
+ callbacks?.onPhase?.(sourceIndex, 'planningContentItems');
111
+ if (mode.kind === 'split') {
112
+ await markInScopeContentItems(trx, mode.scopeMap, mode.parseOptions);
113
+ await planContentItemsForSplit(trx);
114
+ await planResourceItems(trx, 'split');
115
+ }
116
+ else {
117
+ await planContentItemsForConcat(trx);
118
+ await planResourceItems(trx, 'concat');
119
+ }
120
+ callbacks?.onPhase?.(sourceIndex, 'copyingDictionaries');
121
+ if (mode.kind === 'split') {
122
+ await copyDictionariesForSplit(trx);
123
+ }
124
+ else {
125
+ await copyDictionariesForConcat(trx);
126
+ }
127
+ await copyHeaderSetChildren(trx);
128
+ await copyPageHtmlBlobs(trx);
129
+ callbacks?.onPhase?.(sourceIndex, 'copyingContentItems');
130
+ if (mode.kind === 'concat') {
131
+ await clearReplacedPageRows(trx);
132
+ await replaceContentItems(trx, { crawlOrderOffset });
133
+ }
134
+ await insertContentItems(trx, { crawlOrderOffset });
135
+ await remapRedirectDestIds(trx);
136
+ callbacks?.onPhase?.(sourceIndex, 'copyingPageRows');
137
+ await copyPageMeta(trx);
138
+ await copyImageItems(trx);
139
+ await copyAnchorEdges(trx);
140
+ await copySimplePageScopedTables(trx);
141
+ await copyPageTemplateClusters(trx);
142
+ await copyPageTemplateLabels(trx);
143
+ await copyPageConsoleLogs(trx);
144
+ await copyAnalysisViolations(trx);
145
+ callbacks?.onPhase?.(sourceIndex, 'copyingResources');
146
+ await copyResourceItems(trx);
147
+ await copyResourceRefEdges(trx);
148
+ callbacks?.onPhase?.(sourceIndex, 'copyingJournals');
149
+ await copyJournalTables(trx, mode.kind);
150
+ callbacks?.onPhase?.(sourceIndex, 'committing');
151
+ return await summarizeTransferResult(trx, mode.kind);
152
+ });
153
+ }
154
+ finally {
155
+ await dropTransferTempTables(knex);
156
+ await detach();
157
+ }
158
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The fixed set of dictionary tables a transfer's need-based dictionary
3
+ * copy tracks per-id "is this row referenced by anything kept" state for.
4
+ * Drives the loop in {@link import('./create-transfer-temp-tables.js').createTransferTempTables} /
5
+ * {@link import('./drop-transfer-temp-tables.js').dropTransferTempTables}
6
+ * that creates/drops one `(src_id PRIMARY KEY)` need-table and one
7
+ * `(src_id PRIMARY KEY, dest_id)` map-table per dictionary — every
8
+ * dictionary table shares that exact temp-table shape, only the
9
+ * population query differs (see `copy-dictionaries-for-concat.ts` /
10
+ * `copy-dictionaries-for-split.ts`).
11
+ */
12
+ export declare const TRANSFER_DICTIONARY_TABLES: readonly string[];
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The fixed set of dictionary tables a transfer's need-based dictionary
3
+ * copy tracks per-id "is this row referenced by anything kept" state for.
4
+ * Drives the loop in {@link import('./create-transfer-temp-tables.js').createTransferTempTables} /
5
+ * {@link import('./drop-transfer-temp-tables.js').dropTransferTempTables}
6
+ * that creates/drops one `(src_id PRIMARY KEY)` need-table and one
7
+ * `(src_id PRIMARY KEY, dest_id)` map-table per dictionary — every
8
+ * dictionary table shares that exact temp-table shape, only the
9
+ * population query differs (see `copy-dictionaries-for-concat.ts` /
10
+ * `copy-dictionaries-for-split.ts`).
11
+ */
12
+ export const TRANSFER_DICTIONARY_TABLES = [
13
+ 'url_refs',
14
+ 'content_type_refs',
15
+ 'text_refs',
16
+ 'json_refs',
17
+ 'blob_refs',
18
+ 'header_name_refs',
19
+ 'header_value_refs',
20
+ 'header_sets',
21
+ 'console_log_items',
22
+ 'analysis_text_refs',
23
+ ];
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The fixed schema alias a source archive's `db.sqlite` is `ATTACH`ed under
3
+ * during a transfer. A constant (not a per-call parameter) because every
4
+ * transfer SQL statement in `archive/transfer/` hard-codes this name —
5
+ * allowing a caller-supplied alias would mean threading it through every
6
+ * one of those statements for no real benefit (a transfer only ever
7
+ * attaches one source at a time; see `transfer-archive-rows.ts`).
8
+ */
9
+ export declare const TRANSFER_SOURCE_ALIAS = "xfer_src";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The fixed schema alias a source archive's `db.sqlite` is `ATTACH`ed under
3
+ * during a transfer. A constant (not a per-call parameter) because every
4
+ * transfer SQL statement in `archive/transfer/` hard-codes this name —
5
+ * allowing a caller-supplied alias would mean threading it through every
6
+ * one of those statements for no real benefit (a transfer only ever
7
+ * attaches one source at a time; see `transfer-archive-rows.ts`).
8
+ */
9
+ export const TRANSFER_SOURCE_ALIAS = 'xfer_src';
@@ -0,0 +1,111 @@
1
+ import type { Config } from '../types.js';
2
+ /**
3
+ * Ordered phase sequence a single source's transfer announces via
4
+ * `onPhase`, unconditionally and always in this order (mirrors
5
+ * `ViewerReadModelBuildPhase`'s contract — no branch skips a phase, so a
6
+ * caller can pre-build one `TaskList` row per phase and rely on them
7
+ * settling in order).
8
+ */
9
+ export type TransferPhase = 'planningContentItems' | 'copyingDictionaries' | 'copyingContentItems' | 'copyingPageRows' | 'copyingResources' | 'copyingJournals' | 'committing' | 'flatteningRedirects' | 'reclassifyingResources' | 'countingExternalInScope';
10
+ /**
11
+ * Progress callbacks a caller (the CLI's `concat`/`split` commands) passes
12
+ * into {@link import('./concat-archives.js').concatArchives} /
13
+ * {@link import('./split-archive.js').splitArchive} to drive a `TaskList`
14
+ * display. `onPhase` fires once per phase per source (plus once per
15
+ * whole-operation post phase); `onProgress` fires zero or more times while
16
+ * a phase is active, with a phase-specific unit (rows copied, ids
17
+ * classified, …).
18
+ */
19
+ export interface TransferCallbacks {
20
+ /** Called when a new source's extraction begins (0-based index). */
21
+ readonly onSourceStart?: (sourceIndex: number, filePath: string) => void;
22
+ /**
23
+ * Called whenever the active phase changes, for the source at
24
+ * `sourceIndex` (or after every source has finished, for the
25
+ * whole-operation post phases — `flatteningRedirects` /
26
+ * `reclassifyingResources` / `countingExternalInScope` — where
27
+ * `sourceIndex` is `sources.length`).
28
+ */
29
+ readonly onPhase?: (sourceIndex: number, phase: TransferPhase) => void;
30
+ /** Called zero or more times while a phase is active. */
31
+ readonly onProgress?: (processed: number, total: number) => void;
32
+ }
33
+ /** Per-source outcome of {@link import('./transfer-archive-rows.js').transferArchiveRows}. */
34
+ export interface TransferSourceResult {
35
+ /** Number of `content_items` rows copied as brand-new rows (no prior dest row for that URL). */
36
+ readonly inserted: number;
37
+ /**
38
+ * Number of existing dest `content_items` rows overwritten because this
39
+ * source's observation outranked the dest's (concat only; always `0`
40
+ * for split, which never merges into an existing archive).
41
+ */
42
+ readonly replaced: number;
43
+ /** Number of source rows skipped because dest already held an equal-or-better observation (concat only). */
44
+ readonly skipped: number;
45
+ /** Number of source rows kept as an external stub, not a full copy (split only; always `0` for concat). */
46
+ readonly stubbed: number;
47
+ /** Number of source rows dropped entirely — out of scope and unreferenced (split only; always `0` for concat). */
48
+ readonly dropped: number;
49
+ }
50
+ /** Result of {@link import('./concat-archives.js').concatArchives}. */
51
+ export interface ConcatArchivesResult {
52
+ /** The merged config written to the destination's `info` row. */
53
+ readonly config: Config;
54
+ /** Per-source transfer outcome, in argument order. */
55
+ readonly sources: readonly TransferSourceResult[];
56
+ /**
57
+ * Number of URLs that fall inside the merged scope but were never
58
+ * fetched as an internal page by any source (still `is_external = 1`
59
+ * in the output) — the count the CLI surfaces with a
60
+ * `crawl <out> --append <root>` hint, since concat never re-promotes
61
+ * external rows on its own (that would fabricate a `scraped = 1`
62
+ * observation with no body/meta behind it).
63
+ */
64
+ readonly externalInScopeCount: number;
65
+ /** Number of `inventory/<sha256>.txt` source lists copied (deduplicated by filename across sources). */
66
+ readonly inventoryListsCopied: number;
67
+ }
68
+ /** Result of {@link import('./split-archive.js').splitArchive}. */
69
+ export interface SplitArchiveResult {
70
+ /** The derived config (roots = the given scope URLs) written to the destination's `info` row. */
71
+ readonly config: Config;
72
+ /** The single source's transfer outcome. */
73
+ readonly source: TransferSourceResult;
74
+ /**
75
+ * Usually `0`, but not structurally guaranteed to be: the operator's
76
+ * scope URLs are not required to be a subset of the source's original
77
+ * roots, so a scope broader than (or merely different from) the
78
+ * original can bring an external-only (never crawled) page inside the
79
+ * new scope, the same way concat's own external-in-scope count can be
80
+ * non-zero.
81
+ */
82
+ readonly externalInScopeCount: number;
83
+ /** Number of `inventory/<sha256>.txt` source lists copied. */
84
+ readonly inventoryListsCopied: number;
85
+ }
86
+ /**
87
+ * Thrown by {@link import('./merge-archive-configs.js').mergeArchiveConfigs}
88
+ * when two source archives disagree on a config field that concat cannot
89
+ * silently reconcile (`disableQueries`, `fromList`) — see that function's
90
+ * docs for why these two specifically cannot fall back to "first archive
91
+ * wins" like every other scalar field.
92
+ */
93
+ export declare class ArchiveConfigConflictError extends Error {
94
+ readonly field: string;
95
+ readonly values: readonly unknown[];
96
+ /**
97
+ * @param field - The conflicting `Config` field name.
98
+ * @param values - The distinct values seen across sources, in argument order.
99
+ */
100
+ constructor(field: string, values: readonly unknown[]);
101
+ }
102
+ /**
103
+ * Thrown when a dictionary-table copy's post-copy id map does not cover
104
+ * every id it needed to map (a source row referencing a value that failed
105
+ * to insert or resolve) — a defensive integrity check, since a silently
106
+ * incomplete map would surface much later as a confusing "no such row" or
107
+ * a dangling NULL FK deep in an unrelated read path.
108
+ */
109
+ export declare class TransferIntegrityError extends Error {
110
+ constructor(message: string);
111
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Thrown by {@link import('./merge-archive-configs.js').mergeArchiveConfigs}
3
+ * when two source archives disagree on a config field that concat cannot
4
+ * silently reconcile (`disableQueries`, `fromList`) — see that function's
5
+ * docs for why these two specifically cannot fall back to "first archive
6
+ * wins" like every other scalar field.
7
+ */
8
+ export class ArchiveConfigConflictError extends Error {
9
+ field;
10
+ values;
11
+ /**
12
+ * @param field - The conflicting `Config` field name.
13
+ * @param values - The distinct values seen across sources, in argument order.
14
+ */
15
+ constructor(field, values) {
16
+ super(`Cannot merge archives: "${field}" differs across sources (${values.map((v) => JSON.stringify(v)).join(' vs ')}). ` +
17
+ 'Re-crawl the sources with matching settings before concatenating them.');
18
+ this.field = field;
19
+ this.values = values;
20
+ this.name = 'ArchiveConfigConflictError';
21
+ }
22
+ }
23
+ /**
24
+ * Thrown when a dictionary-table copy's post-copy id map does not cover
25
+ * every id it needed to map (a source row referencing a value that failed
26
+ * to insert or resolve) — a defensive integrity check, since a silently
27
+ * incomplete map would surface much later as a confusing "no such row" or
28
+ * a dangling NULL FK deep in an unrelated read path.
29
+ */
30
+ export class TransferIntegrityError extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = 'TransferIntegrityError';
34
+ }
35
+ }
@@ -0,0 +1,10 @@
1
+ import type { TransferPhase } from './archive/transfer/types.js';
2
+ /**
3
+ * Ordered phase sequence {@link import('./archive/transfer/transfer-archive-rows.js').transferArchiveRows}
4
+ * announces via `onPhase`, once per concat source, unconditionally and
5
+ * always in this order (see that function's own source — no branch skips
6
+ * a phase). Single source of truth for the per-source `TaskList` rows a
7
+ * CLI caller pre-builds (mirrors `VIEWER_READ_MODEL_FULL_BUILD_PHASES`'s
8
+ * same role for the read-model build).
9
+ */
10
+ export declare const CONCAT_SOURCE_TRANSFER_PHASES: readonly TransferPhase[];
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Ordered phase sequence {@link import('./archive/transfer/transfer-archive-rows.js').transferArchiveRows}
3
+ * announces via `onPhase`, once per concat source, unconditionally and
4
+ * always in this order (see that function's own source — no branch skips
5
+ * a phase). Single source of truth for the per-source `TaskList` rows a
6
+ * CLI caller pre-builds (mirrors `VIEWER_READ_MODEL_FULL_BUILD_PHASES`'s
7
+ * same role for the read-model build).
8
+ */
9
+ export const CONCAT_SOURCE_TRANSFER_PHASES = [
10
+ 'planningContentItems',
11
+ 'copyingDictionaries',
12
+ 'copyingContentItems',
13
+ 'copyingPageRows',
14
+ 'copyingResources',
15
+ 'copyingJournals',
16
+ 'committing',
17
+ ];
@@ -0,0 +1,21 @@
1
+ import type { ExURL, ParseURLOptions } from '@d-zero/shared/parse-url';
2
+ /**
3
+ * Builds a hostname-indexed scope map from a list of root URL strings, for
4
+ * use with {@link findScopeEntry}.
5
+ *
6
+ * Each root that fails to parse is silently skipped (a malformed root can
7
+ * never match anything anyway) rather than throwing, matching the existing
8
+ * inline construction this replaces (`crawler-orchestrator.ts`'s `append`
9
+ * and inventory-classification call sites, `Crawler`'s own scope build).
10
+ * Roots sharing a hostname are grouped under one array entry so
11
+ * `findScopeEntry` can pick the most specific match among them.
12
+ * @param roots - Root URL strings (e.g. `Config.roots`).
13
+ * @param options - URL parsing options forwarded to {@link parseUrl}.
14
+ * @returns A hostname-indexed map of parsed root URLs.
15
+ * @example
16
+ * ```ts
17
+ * const scope = buildScopeMap(['https://example.com/blog/', 'https://example.com/docs/']);
18
+ * findScopeEntry(url, scope); // deepest matching root, or null if external
19
+ * ```
20
+ */
21
+ export declare function buildScopeMap(roots: readonly string[], options?: ParseURLOptions): Map<string, ExURL[]>;
@@ -0,0 +1,32 @@
1
+ import { tryParseUrl as parseUrl } from '@d-zero/shared/parse-url';
2
+ /**
3
+ * Builds a hostname-indexed scope map from a list of root URL strings, for
4
+ * use with {@link findScopeEntry}.
5
+ *
6
+ * Each root that fails to parse is silently skipped (a malformed root can
7
+ * never match anything anyway) rather than throwing, matching the existing
8
+ * inline construction this replaces (`crawler-orchestrator.ts`'s `append`
9
+ * and inventory-classification call sites, `Crawler`'s own scope build).
10
+ * Roots sharing a hostname are grouped under one array entry so
11
+ * `findScopeEntry` can pick the most specific match among them.
12
+ * @param roots - Root URL strings (e.g. `Config.roots`).
13
+ * @param options - URL parsing options forwarded to {@link parseUrl}.
14
+ * @returns A hostname-indexed map of parsed root URLs.
15
+ * @example
16
+ * ```ts
17
+ * const scope = buildScopeMap(['https://example.com/blog/', 'https://example.com/docs/']);
18
+ * findScopeEntry(url, scope); // deepest matching root, or null if external
19
+ * ```
20
+ */
21
+ export function buildScopeMap(roots, options) {
22
+ const scope = new Map();
23
+ for (const raw of roots) {
24
+ const parsed = parseUrl(raw, options);
25
+ if (!parsed) {
26
+ continue;
27
+ }
28
+ const existing = scope.get(parsed.hostname) ?? [];
29
+ scope.set(parsed.hostname, [...existing, parsed]);
30
+ }
31
+ return scope;
32
+ }
@@ -9,6 +9,7 @@ import Archive from './archive/archive.js';
9
9
  import { copyFileWithProgress } from './archive/filesystem/copy-file-with-progress.js';
10
10
  import { REQUIRED_FORMAT_VERSION } from './archive/meta/assert-compatible-version.js';
11
11
  import { computeAutoRetryBackoffDelayMs } from './compute-auto-retry-backoff-delay.js';
12
+ import { buildScopeMap } from './crawler/build-scope-map.js';
12
13
  import { clearDestinationCache } from './crawler/clear-destination-cache.js';
13
14
  import { clearDnsBurnedHostCache } from './crawler/clear-dns-burned-host-cache.js';
14
15
  import Crawler from './crawler/crawler.js';
@@ -1080,14 +1081,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1080
1081
  await copyFileWithProgress(absFilePath, backupPath, setupProgress?.onCopyProgress);
1081
1082
  try {
1082
1083
  await archive.updateConfig(mergedConfig);
1083
- const scopeMap = new Map();
1084
- for (const raw of mergedRoots) {
1085
- const parsed = parseUrl(raw, archived);
1086
- if (!parsed)
1087
- continue;
1088
- const existing = scopeMap.get(parsed.hostname) ?? [];
1089
- scopeMap.set(parsed.hostname, [...existing, parsed]);
1090
- }
1084
+ const scopeMap = buildScopeMap(mergedRoots, archived);
1091
1085
  setupProgress?.onPhase?.(PHASE_REPROMOTING);
1092
1086
  await archive.repromoteExternalPages(scopeMap, archived, setupProgress?.onChunkProgress);
1093
1087
  // Seed the sticky set from prior sessions' confirmed traps so
@@ -1861,14 +1855,7 @@ export class CrawlerOrchestrator extends EventEmitter {
1861
1855
  */
1862
1856
  static async #classifyInventoryCandidateUrls(rawUrls, archived, archive) {
1863
1857
  const parsedAll = sortUrl(rawUrls, archived);
1864
- const scopeMap = new Map();
1865
- for (const raw of archived.roots) {
1866
- const parsed = parseUrl(raw, archived);
1867
- if (!parsed)
1868
- continue;
1869
- const existing = scopeMap.get(parsed.hostname) ?? [];
1870
- scopeMap.set(parsed.hostname, [...existing, parsed]);
1871
- }
1858
+ const scopeMap = buildScopeMap(archived.roots, archived);
1872
1859
  const inScope = [];
1873
1860
  let outOfScope = 0;
1874
1861
  for (const url of parsedAll) {
package/lib/crawler.d.ts CHANGED
@@ -73,4 +73,16 @@ export { populateBlobRefs } from './archive/populate-ref-tables/populate-blob-re
73
73
  export { populateHeaderTables } from './archive/populate-ref-tables/populate-header-tables.js';
74
74
  export { loadResponseHeadersBySetIds } from './archive/db-ops/_shared/load-response-headers-by-set-ids.js';
75
75
  export { decodeJsonRef } from './archive/db-ops/_shared/decode-json-ref.js';
76
- export type { TemplateClusterBlockingEvidence, TemplateClusterBlockingReason, TemplateClusterLandmarkProfile, TemplateClusterLandmarkType, TemplateClusterReason, } from './archive/db-ops/analysis/types.js';
76
+ export type { AssignTemplateLabelsParams, TemplateClusterBlockingEvidence, TemplateClusterBlockingReason, TemplateClusterLandmarkProfile, TemplateClusterLandmarkType, TemplateClusterReason, TemplateLabel, TemplateLabelClusterInput, } from './archive/db-ops/templates/types.js';
77
+ export { assignTemplateLabels } from './archive/db-ops/templates/assign-template-labels.js';
78
+ export { classifyArchivePageTemplates } from './template-classification/classify-archive-page-templates.js';
79
+ export type { ClassifyArchivePageTemplatesOptions, ClassifyArchivePageTemplatesResult, TemplateClassificationProgress, TemplateClusteringProgress, } from './template-classification/types.js';
80
+ export { resolveOutputPath } from './resolve-output-path.js';
81
+ export { buildScopeMap } from './crawler/build-scope-map.js';
82
+ export type { ConcatArchivesResult, SplitArchiveResult, TransferCallbacks, TransferPhase, TransferSourceResult, } from './archive/transfer/types.js';
83
+ export { ArchiveConfigConflictError, TransferIntegrityError, } from './archive/transfer/types.js';
84
+ export { concatArchives } from './archive/transfer/concat-archives.js';
85
+ export { splitArchive } from './archive/transfer/split-archive.js';
86
+ export { CONCAT_SOURCE_TRANSFER_PHASES } from './concat-source-transfer-phases.js';
87
+ export { SPLIT_SOURCE_TRANSFER_PHASES } from './split-source-transfer-phases.js';
88
+ export { TRANSFER_POST_PHASES } from './transfer-post-phases.js';
package/lib/crawler.js CHANGED
@@ -78,3 +78,25 @@ export { populateHeaderTables } from './archive/populate-ref-tables/populate-hea
78
78
  // no cross-package drift.
79
79
  export { loadResponseHeadersBySetIds } from './archive/db-ops/_shared/load-response-headers-by-set-ids.js';
80
80
  export { decodeJsonRef } from './archive/db-ops/_shared/decode-json-ref.js';
81
+ // The label assigner is exported so `@nitpicker/query` can number clusters
82
+ // provisionally, with the exact same rules, for an archive classified before
83
+ // labels were stored — one implementation, no cross-package drift.
84
+ export { assignTemplateLabels } from './archive/db-ops/templates/assign-template-labels.js';
85
+ // Crawl-end DOM-structure template classification (page_templates /
86
+ // page_template_clusters / page_template_labels). A post-crawl derived-data
87
+ // step like `scanJsResourcesForTechnologySignals`, run by the CLI's crawl
88
+ // post-processing, `viewer-build`, `concat` and `split`.
89
+ export { classifyArchivePageTemplates } from './template-classification/classify-archive-page-templates.js';
90
+ // Output-path resolution and scope-map construction, needed by CLI commands
91
+ // that produce a NEW `.nitpicker` archive from existing ones (`concat` /
92
+ // `split`) rather than crawling — same normalization `crawl --output` and
93
+ // `pipeline` already apply, and the same hostname-indexed scope shape
94
+ // `findScopeEntry` consumes.
95
+ export { resolveOutputPath } from './resolve-output-path.js';
96
+ export { buildScopeMap } from './crawler/build-scope-map.js';
97
+ export { ArchiveConfigConflictError, TransferIntegrityError, } from './archive/transfer/types.js';
98
+ export { concatArchives } from './archive/transfer/concat-archives.js';
99
+ export { splitArchive } from './archive/transfer/split-archive.js';
100
+ export { CONCAT_SOURCE_TRANSFER_PHASES } from './concat-source-transfer-phases.js';
101
+ export { SPLIT_SOURCE_TRANSFER_PHASES } from './split-source-transfer-phases.js';
102
+ export { TRANSFER_POST_PHASES } from './transfer-post-phases.js';
@@ -0,0 +1,11 @@
1
+ import type { TransferPhase } from './archive/transfer/types.js';
2
+ /**
3
+ * Ordered phase sequence {@link import('./archive/transfer/transfer-archive-rows.js').transferArchiveRows}
4
+ * announces via `onPhase` for split's single source — identical to
5
+ * {@link import('./concat-source-transfer-phases.js').CONCAT_SOURCE_TRANSFER_PHASES}
6
+ * (the phase sequence inside `transferArchiveRows` does not branch on
7
+ * mode, only what each phase DOES differs), kept as its own named export
8
+ * so a CLI caller building split's `TaskList` rows never has to reason
9
+ * about why it is importing something named "concat".
10
+ */
11
+ export declare const SPLIT_SOURCE_TRANSFER_PHASES: readonly TransferPhase[];
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Ordered phase sequence {@link import('./archive/transfer/transfer-archive-rows.js').transferArchiveRows}
3
+ * announces via `onPhase` for split's single source — identical to
4
+ * {@link import('./concat-source-transfer-phases.js').CONCAT_SOURCE_TRANSFER_PHASES}
5
+ * (the phase sequence inside `transferArchiveRows` does not branch on
6
+ * mode, only what each phase DOES differs), kept as its own named export
7
+ * so a CLI caller building split's `TaskList` rows never has to reason
8
+ * about why it is importing something named "concat".
9
+ */
10
+ export const SPLIT_SOURCE_TRANSFER_PHASES = [
11
+ 'planningContentItems',
12
+ 'copyingDictionaries',
13
+ 'copyingContentItems',
14
+ 'copyingPageRows',
15
+ 'copyingResources',
16
+ 'copyingJournals',
17
+ 'committing',
18
+ ];
@@ -0,0 +1,41 @@
1
+ import type { ClassifyArchivePageTemplatesOptions, ClassifyArchivePageTemplatesResult } from './types.js';
2
+ import type Archive from '../archive/archive.js';
3
+ /**
4
+ * Classifies every internal HTML page of the archive into a template group
5
+ * by DOM-structure similarity and persists the result to `page_templates`,
6
+ * `page_template_clusters` and `page_template_labels`.
7
+ *
8
+ * This is the crawl-end derived-data step (alongside the JS-resource scan
9
+ * and the viewer read-model build): the crawl command runs it before the
10
+ * archive is written, and `viewer-build` / `concat` / `split` re-run it on
11
+ * their archive. It is deliberately **not** an `AnalyzePlugin` — it is a
12
+ * corpus-wide batch computation (template keys are only comparable within
13
+ * one run), whereas plugins process one page at a time.
14
+ *
15
+ * Every page is loaded before clustering starts and clustered **once**,
16
+ * never per `getPagesWithRefs` batch: per-batch keys would only be
17
+ * comparable within their own batch.
18
+ *
19
+ * A run that classifies no page at all (no internal page has a stored HTML
20
+ * snapshot to cluster) leaves the stored classification untouched instead of
21
+ * replacing it with an empty one: nothing could be re-derived, and erasing a
22
+ * previous classification (e.g. rows `concat` copied from its sources) would
23
+ * lose data for no gain. Whenever at least one page is classified the stored
24
+ * classification is replaced wholesale; labels survive either way —
25
+ * `replacePageTemplates` carries them forward across runs and keeps retired
26
+ * ones.
27
+ * @param archive - A writable archive (crawl-end orchestrator archive, or one
28
+ * opened for `viewer-build` / created by `concat` / `split`).
29
+ * @param options - See {@link ClassifyArchivePageTemplatesOptions}.
30
+ * @returns See {@link ClassifyArchivePageTemplatesResult}.
31
+ * @throws {Error} Whatever page loading, clustering or the write throws — callers
32
+ * that treat classification as best-effort (all CLI paths) catch it.
33
+ * @example
34
+ * ```ts
35
+ * const { classifiedPageCount, templateCount } = await classifyArchivePageTemplates(
36
+ * archive,
37
+ * { onProgress: (event) => console.error(event.phase) },
38
+ * );
39
+ * ```
40
+ */
41
+ export declare function classifyArchivePageTemplates(archive: Archive, options?: ClassifyArchivePageTemplatesOptions): Promise<ClassifyArchivePageTemplatesResult>;