@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
@@ -1,11 +1,11 @@
1
1
  import type { ReplacePageTemplatesParams } from './types.js';
2
2
  import type { Knex } from 'knex';
3
3
  /**
4
- * Replaces the stored DOM-structure template classification (`--templates`)
5
- * with a freshly generated set.
4
+ * Replaces the stored DOM-structure template classification with a freshly
5
+ * generated set.
6
6
  *
7
7
  * Every classified page is a full-archive, all-or-nothing recomputation
8
- * (see `@nitpicker/core`'s `classifyPageTemplates`), so this always deletes
8
+ * (see `classifyPageTemplates`), so this always deletes
9
9
  * every existing row before inserting the new set — there is no per-page
10
10
  * incremental update path, matching `replaceAnalysisViolations`'s
11
11
  * whole-table replace shape. Unlike violations, a page whose URL can't be
@@ -23,6 +23,22 @@ import type { Knex } from 'knex';
23
23
  * in `templateKeysByUrl` after URL-resolution skips above — harmless
24
24
  * (nothing joins `page_template_clusters` back to `page_templates` by FK;
25
25
  * see the table's own JSDoc), and simpler than cross-filtering the two maps.
26
+ *
27
+ * `page_template_labels` is the one table that is **not** wholesale
28
+ * replaced: the human-facing label of each new cluster is carried forward
29
+ * from whichever previous cluster it shares most pages with
30
+ * (`assignTemplateLabels`), which is what lets "events template B" keep
31
+ * meaning the same template across re-runs, and the rows of clusters that
32
+ * disappeared are kept as *retired* labels so their letters are never
33
+ * re-issued to a different template on a later run (only the rows for the
34
+ * keys being written, and the old row of a label that moved to a new key,
35
+ * are removed). Readers look labels up by the keys
36
+ * currently in `page_templates`, so retired rows are invisible to them.
37
+ * The previous `page_templates` and `page_template_labels` rows are read
38
+ * inside the same transaction that writes — there is no window in which
39
+ * another writer could change what the labels were derived from. An empty
40
+ * `templateKeysByUrl` therefore clears the classification but leaves every
41
+ * label row in place.
26
42
  * @param knex - Knex query builder connected to the archive DB.
27
43
  * @param params - See {@link ReplacePageTemplatesParams}.
28
44
  */
@@ -0,0 +1,174 @@
1
+ import { eachSplitted } from '../../../utils/array/each-splitted.js';
2
+ import { compressPayload } from '../_shared/compress-payload.js';
3
+ import { assignTemplateLabels } from './assign-template-labels.js';
4
+ /**
5
+ * Replaces the stored DOM-structure template classification with a freshly
6
+ * generated set.
7
+ *
8
+ * Every classified page is a full-archive, all-or-nothing recomputation
9
+ * (see `classifyPageTemplates`), so this always deletes
10
+ * every existing row before inserting the new set — there is no per-page
11
+ * incremental update path, matching `replaceAnalysisViolations`'s
12
+ * whole-table replace shape. Unlike violations, a page whose URL can't be
13
+ * resolved back to a `content_items` row is silently skipped rather than
14
+ * treated as a hard failure: losing one page's template classification
15
+ * (e.g. a URL-normalization mismatch between the in-memory `Page.url.href`
16
+ * and the stored `url_refs.url`) should not discard the rest of a
17
+ * potentially multi-thousand-page classification run.
18
+ *
19
+ * `page_template_clusters` is always cleared alongside `page_templates`
20
+ * regardless of whether `clusterReasonsByTemplateKey` is passed — "no
21
+ * reason" must mean "not captured for this run", never "carry over the
22
+ * previous run's reason". Reason rows are inserted for every key in
23
+ * `clusterReasonsByTemplateKey` even if some have no surviving member page
24
+ * in `templateKeysByUrl` after URL-resolution skips above — harmless
25
+ * (nothing joins `page_template_clusters` back to `page_templates` by FK;
26
+ * see the table's own JSDoc), and simpler than cross-filtering the two maps.
27
+ *
28
+ * `page_template_labels` is the one table that is **not** wholesale
29
+ * replaced: the human-facing label of each new cluster is carried forward
30
+ * from whichever previous cluster it shares most pages with
31
+ * (`assignTemplateLabels`), which is what lets "events template B" keep
32
+ * meaning the same template across re-runs, and the rows of clusters that
33
+ * disappeared are kept as *retired* labels so their letters are never
34
+ * re-issued to a different template on a later run (only the rows for the
35
+ * keys being written, and the old row of a label that moved to a new key,
36
+ * are removed). Readers look labels up by the keys
37
+ * currently in `page_templates`, so retired rows are invisible to them.
38
+ * The previous `page_templates` and `page_template_labels` rows are read
39
+ * inside the same transaction that writes — there is no window in which
40
+ * another writer could change what the labels were derived from. An empty
41
+ * `templateKeysByUrl` therefore clears the classification but leaves every
42
+ * label row in place.
43
+ * @param knex - Knex query builder connected to the archive DB.
44
+ * @param params - See {@link ReplacePageTemplatesParams}.
45
+ */
46
+ export async function replacePageTemplates(knex, params) {
47
+ const { templateKeysByUrl, clusterReasonsByTemplateKey } = params;
48
+ // Compressing every reason is pure CPU work independent of the DB — done
49
+ // before opening the transaction below so it doesn't extend how long the
50
+ // SQLite write-lock is held for.
51
+ const reasonRows = clusterReasonsByTemplateKey && clusterReasonsByTemplateKey.size > 0
52
+ ? [...clusterReasonsByTemplateKey].map(([templateKey, reason]) => {
53
+ const { body, codec, sizeRaw, sizeStored } = compressPayload(Buffer.from(JSON.stringify(reason), 'utf8'));
54
+ return {
55
+ template_key: templateKey,
56
+ member_count: reason.memberCount,
57
+ reason_json: body,
58
+ codec,
59
+ size_raw: sizeRaw,
60
+ size_stored: sizeStored,
61
+ };
62
+ })
63
+ : [];
64
+ await knex.transaction(async (trx) => {
65
+ // Resolve the new membership and read the previous one *before* the
66
+ // deletes below — label inheritance needs both sides.
67
+ const urls = [...templateKeysByUrl.keys()];
68
+ const pageIdByUrl = new Map();
69
+ await eachSplitted(urls, 500, async (chunk) => {
70
+ const pageRows = await trx('content_items')
71
+ .join('url_refs', 'url_refs.id', 'content_items.url_id')
72
+ .select('content_items.id as id', 'url_refs.url as url')
73
+ .whereIn('url_refs.url', chunk);
74
+ for (const row of pageRows) {
75
+ pageIdByUrl.set(row.url, row.id);
76
+ }
77
+ });
78
+ const rows = [];
79
+ const clusters = new Map();
80
+ for (const [url, templateKey] of templateKeysByUrl) {
81
+ const pageId = pageIdByUrl.get(url);
82
+ if (pageId == null) {
83
+ continue;
84
+ }
85
+ rows.push({ page_id: pageId, template_key: templateKey });
86
+ let cluster = clusters.get(templateKey);
87
+ if (!cluster) {
88
+ cluster = { pageIds: [], urls: [] };
89
+ clusters.set(templateKey, cluster);
90
+ }
91
+ cluster.pageIds.push(pageId);
92
+ cluster.urls.push(url);
93
+ }
94
+ const previousLabels = await loadPreviousLabels(trx);
95
+ const labels = assignTemplateLabels({
96
+ clusters,
97
+ previousMembership: await loadPreviousMembership(trx),
98
+ previousLabels,
99
+ });
100
+ // Rows to drop: the keys being (re)written, plus previous keys whose
101
+ // label was inherited by a new key — the label moved, so its old row
102
+ // would otherwise linger as a duplicate of the same name.
103
+ const writtenPairs = new Set([...labels.values()].map(labelPair));
104
+ const staleKeys = [...labels.keys()];
105
+ for (const [previousKey, label] of previousLabels) {
106
+ if (!labels.has(previousKey) && writtenPairs.has(labelPair(label))) {
107
+ staleKeys.push(previousKey);
108
+ }
109
+ }
110
+ await trx('page_templates').delete();
111
+ await trx('page_template_clusters').delete();
112
+ await eachSplitted(staleKeys, 500, async (chunk) => {
113
+ await trx('page_template_labels').whereIn('template_key', chunk).delete();
114
+ });
115
+ if (reasonRows.length > 0) {
116
+ await eachSplitted(reasonRows, 100, async (chunk) => {
117
+ await trx('page_template_clusters').insert(chunk);
118
+ });
119
+ }
120
+ if (rows.length === 0) {
121
+ return;
122
+ }
123
+ await eachSplitted(rows, 500, async (chunk) => {
124
+ await trx('page_templates').insert(chunk);
125
+ });
126
+ const labelRows = [...labels].map(([templateKey, label]) => ({
127
+ template_key: templateKey,
128
+ section: label.section,
129
+ ordinal: label.ordinal,
130
+ }));
131
+ await eachSplitted(labelRows, 500, async (chunk) => {
132
+ await trx('page_template_labels').insert(chunk);
133
+ });
134
+ });
135
+ }
136
+ /**
137
+ * The identity of a label as a name: its `(section, ordinal)` pair.
138
+ * @param label - The label.
139
+ * @returns A string key unique per name.
140
+ */
141
+ function labelPair(label) {
142
+ return `${label.section ?? '\0'}:${label.ordinal}`;
143
+ }
144
+ /**
145
+ * Reads the previous run's `page_templates` rows as template key → page ids.
146
+ * @param trx - The replacing transaction.
147
+ * @returns The previous membership; empty on a first run.
148
+ */
149
+ async function loadPreviousMembership(trx) {
150
+ const previousRows = (await trx('page_templates').select('page_id as pageId', 'template_key as templateKey'));
151
+ const membership = new Map();
152
+ for (const row of previousRows) {
153
+ const pageIds = membership.get(row.templateKey);
154
+ if (pageIds) {
155
+ pageIds.push(row.pageId);
156
+ }
157
+ else {
158
+ membership.set(row.templateKey, [row.pageId]);
159
+ }
160
+ }
161
+ return membership;
162
+ }
163
+ /**
164
+ * Reads the previous run's `page_template_labels` rows.
165
+ * @param trx - The replacing transaction.
166
+ * @returns Template key → label; empty on a first run.
167
+ */
168
+ async function loadPreviousLabels(trx) {
169
+ const labelRows = (await trx('page_template_labels').select('template_key as templateKey', 'section', 'ordinal'));
170
+ return new Map(labelRows.map((row) => [
171
+ row.templateKey,
172
+ { section: row.section, ordinal: row.ordinal },
173
+ ]));
174
+ }
@@ -46,6 +46,44 @@ export interface TemplateClusterReason {
46
46
  readonly landmarks: Partial<Record<TemplateClusterLandmarkType, TemplateClusterLandmarkProfile>>;
47
47
  readonly siblingClusterKeys: readonly string[];
48
48
  }
49
+ /**
50
+ * The human-facing name of one template cluster, as stored in
51
+ * `page_template_labels`: rendered as `<section> template <letter>` (or
52
+ * `template <letter>` when `section` is `null`), where the letter is
53
+ * `ordinal` in A, B, …, Z, AA, AB, … form. Assigned by
54
+ * {@link import('./assign-template-labels.js').assignTemplateLabels}.
55
+ */
56
+ export interface TemplateLabel {
57
+ /**
58
+ * The top-level URL directory every member page sits under (`events` for
59
+ * `/events/...`), or `null` when members span several directories or all
60
+ * sit at the site root — the label is then numbered site-wide.
61
+ */
62
+ readonly section: string | null;
63
+ /** 1-based position within `section`'s label sequence. */
64
+ readonly ordinal: number;
65
+ }
66
+ /** One cluster's membership as {@link import('./assign-template-labels.js').assignTemplateLabels} sees it. */
67
+ export interface TemplateLabelClusterInput {
68
+ /** Resolved `content_items.id` of every member page. */
69
+ readonly pageIds: readonly number[];
70
+ /** URL of every member page, for deriving {@link TemplateLabel.section}. */
71
+ readonly urls: readonly string[];
72
+ }
73
+ /**
74
+ * Params for {@link import('./assign-template-labels.js').assignTemplateLabels}.
75
+ */
76
+ export interface AssignTemplateLabelsParams {
77
+ /** The new classification: template key → members. */
78
+ readonly clusters: ReadonlyMap<string, TemplateLabelClusterInput>;
79
+ /**
80
+ * The previous classification's `page_templates` rows: template key →
81
+ * member page ids. Empty on a first run.
82
+ */
83
+ readonly previousMembership: ReadonlyMap<string, readonly number[]>;
84
+ /** The previous classification's `page_template_labels` rows. Empty on a first run. */
85
+ readonly previousLabels: ReadonlyMap<string, TemplateLabel>;
86
+ }
49
87
  /**
50
88
  * Params for {@link import('./replace-page-templates.js').replacePageTemplates}.
51
89
  */
@@ -13,7 +13,7 @@ export declare function applyConnectionPragmas(instance: Knex): Promise<void>;
13
13
  /**
14
14
  * Initializes the archive database schema if tables do not exist.
15
15
  *
16
- * The schema is composed of four groups, each owned by a dedicated DDL
16
+ * The schema is composed of five groups, each owned by a dedicated DDL
17
17
  * function so the migration script (`scripts/migrate-to-0.13.mjs`) can
18
18
  * provision the exact same shapes on archives it upgrades:
19
19
  *
@@ -34,6 +34,10 @@ export declare function applyConnectionPragmas(instance: Knex): Promise<void>;
34
34
  * `analysis_text_refs` + `analysis_violations`, `page_html_blobs` +
35
35
  * `page_html_ref`. Must run AFTER `createEntityTables` because the
36
36
  * page-scoped tables FK into `content_items(id)`.
37
+ * - **Template classification tables** ({@link createTemplateTables}):
38
+ * `page_templates`, `page_template_clusters`, `page_template_labels` —
39
+ * the crawl-end DOM-structure classification, kept apart from the
40
+ * adjunct/analysis tables because it has its own producer and write path.
37
41
  *
38
42
  * The legacy flat write-model tables (`pages` / `anchors` / `images` /
39
43
  * `resources` / `resources-referrers`) are deliberately NOT created:
@@ -1,6 +1,7 @@
1
1
  import { createAdjunctTables } from './create-adjunct-tables.js';
2
2
  import { createEntityTables } from './create-entity-tables.js';
3
3
  import { createRefTables } from './create-ref-tables.js';
4
+ import { createTemplateTables } from './create-template-tables.js';
4
5
  /**
5
6
  * Applies the connection-level PRAGMAs that govern foreign-key enforcement
6
7
  * and BLOB-read performance. These are **per-connection** settings (libsql
@@ -38,7 +39,7 @@ export async function applyConnectionPragmas(instance) {
38
39
  /**
39
40
  * Initializes the archive database schema if tables do not exist.
40
41
  *
41
- * The schema is composed of four groups, each owned by a dedicated DDL
42
+ * The schema is composed of five groups, each owned by a dedicated DDL
42
43
  * function so the migration script (`scripts/migrate-to-0.13.mjs`) can
43
44
  * provision the exact same shapes on archives it upgrades:
44
45
  *
@@ -59,6 +60,10 @@ export async function applyConnectionPragmas(instance) {
59
60
  * `analysis_text_refs` + `analysis_violations`, `page_html_blobs` +
60
61
  * `page_html_ref`. Must run AFTER `createEntityTables` because the
61
62
  * page-scoped tables FK into `content_items(id)`.
63
+ * - **Template classification tables** ({@link createTemplateTables}):
64
+ * `page_templates`, `page_template_clusters`, `page_template_labels` —
65
+ * the crawl-end DOM-structure classification, kept apart from the
66
+ * adjunct/analysis tables because it has its own producer and write path.
62
67
  *
63
68
  * The legacy flat write-model tables (`pages` / `anchors` / `images` /
64
69
  * `resources` / `resources-referrers`) are deliberately NOT created:
@@ -79,7 +84,7 @@ export async function applyConnectionPragmas(instance) {
79
84
  */
80
85
  export async function initSchema(instance) {
81
86
  // Only the one-shot work (PRAGMAs + `info` creation) is gated on the
82
- // `info` table's existence. The three DDL groups below run on EVERY
87
+ // `info` table's existence. The DDL groups below run on EVERY
83
88
  // call: each is internally idempotent (sentinel / IF NOT EXISTS /
84
89
  // per-table guards), and re-running them self-heals an archive whose
85
90
  // provisioning crashed partway through — `info` created but a later
@@ -143,4 +148,10 @@ export async function initSchema(instance) {
143
148
  // two paths is exactly how migrated archives ended up with stale
144
149
  // `REFERENCES pages(id)` declarations in the pre-0.13 era.
145
150
  await createAdjunctTables(instance);
151
+ // Template classification tables (page_templates / page_template_clusters /
152
+ // page_template_labels). Separate from the adjunct group because the
153
+ // producer is the crawl-end classification step, not the crawl write path
154
+ // or analyze. `page_templates` FKs into `content_items(id)`, so this too
155
+ // MUST run after {@link createEntityTables}.
156
+ await createTemplateTables(instance);
146
157
  }
@@ -0,0 +1,34 @@
1
+ import type { Config } from '../types.js';
2
+ import type { Knex } from 'knex';
3
+ /**
4
+ * Builds a file-backed knex connection against the FULL current archive
5
+ * schema (every ref/entity/adjunct table, including columns only a
6
+ * migration adds to a legacy archive — `alias_of_id`, `dedupe_cap_event_id`,
7
+ * `body_hash`, …) by running the exact same {@link init} boot sequence a
8
+ * real `Archive.create`/`Archive.open` uses. Shared by every
9
+ * `archive/transfer/` spec that needs a realistic source or destination
10
+ * database — hand-rolling `createRefTables`/`createEntityTables`/
11
+ * `createAdjunctTables` directly would produce the schema `initSchema`
12
+ * creates but skip the migrations that add columns for archives created
13
+ * before those features existed (which happen to be a no-op on a fresh
14
+ * DB today, but drift is exactly the risk this helper avoids).
15
+ *
16
+ * A DB file must be used (not `:memory:`) because `ATTACH DATABASE` in
17
+ * the transfer primitives needs a real path — see `attach-source-database.ts`.
18
+ * @param filename - Absolute path to the SQLite file. The caller is
19
+ * responsible for removing it (`afterEach`) — see existing specs for the
20
+ * convention.
21
+ * @param config - Overrides merged over {@link DEFAULT_TEST_CONFIG} and
22
+ * written via `setConfig` once the schema exists. Pass `null` to skip
23
+ * writing an `info` row entirely (some specs seed `content_items`
24
+ * directly and never read `getConfig()`).
25
+ * @returns The connected knex instance, on the current schema, with an
26
+ * `info` row unless `config` is `null`.
27
+ * @example
28
+ * ```ts
29
+ * const db = await buildFullSchemaTestDb(path.resolve(workingDir, 'source.sqlite'), {
30
+ * roots: ['https://a.example.com/'],
31
+ * });
32
+ * ```
33
+ */
34
+ export declare function buildFullSchemaTestDb(filename: string, config?: Partial<Config> | null): Promise<Knex>;
@@ -0,0 +1,74 @@
1
+ import knex from 'knex';
2
+ import { setConfig } from '../db-ops/config/set-config.js';
3
+ import { init } from '../db-ops/lifecycle/init.js';
4
+ import { LibsqlDialect } from '../libsql-dialect.js';
5
+ /**
6
+ * Default {@link Config} fields for {@link buildFullSchemaTestDb} — a
7
+ * single-root, recursive, non-list crawl of `https://example.com/`, no
8
+ * excludes. Overridable per-call for scope/`fromList`/`disableQueries`
9
+ * tests.
10
+ */
11
+ const DEFAULT_TEST_CONFIG = {
12
+ version: '0.13.0',
13
+ name: 'test',
14
+ baseUrl: 'https://example.com/',
15
+ roots: ['https://example.com/'],
16
+ recursive: true,
17
+ interval: 0,
18
+ image: false,
19
+ fetchExternal: false,
20
+ parallels: 1,
21
+ excludes: [],
22
+ excludeKeywords: [],
23
+ excludeUrls: [],
24
+ maxExcludedDepth: 0,
25
+ retry: 3,
26
+ fromList: false,
27
+ disableQueries: false,
28
+ userAgent: 'test',
29
+ ignoreRobots: false,
30
+ mainContentSelector: null,
31
+ };
32
+ /**
33
+ * Builds a file-backed knex connection against the FULL current archive
34
+ * schema (every ref/entity/adjunct table, including columns only a
35
+ * migration adds to a legacy archive — `alias_of_id`, `dedupe_cap_event_id`,
36
+ * `body_hash`, …) by running the exact same {@link init} boot sequence a
37
+ * real `Archive.create`/`Archive.open` uses. Shared by every
38
+ * `archive/transfer/` spec that needs a realistic source or destination
39
+ * database — hand-rolling `createRefTables`/`createEntityTables`/
40
+ * `createAdjunctTables` directly would produce the schema `initSchema`
41
+ * creates but skip the migrations that add columns for archives created
42
+ * before those features existed (which happen to be a no-op on a fresh
43
+ * DB today, but drift is exactly the risk this helper avoids).
44
+ *
45
+ * A DB file must be used (not `:memory:`) because `ATTACH DATABASE` in
46
+ * the transfer primitives needs a real path — see `attach-source-database.ts`.
47
+ * @param filename - Absolute path to the SQLite file. The caller is
48
+ * responsible for removing it (`afterEach`) — see existing specs for the
49
+ * convention.
50
+ * @param config - Overrides merged over {@link DEFAULT_TEST_CONFIG} and
51
+ * written via `setConfig` once the schema exists. Pass `null` to skip
52
+ * writing an `info` row entirely (some specs seed `content_items`
53
+ * directly and never read `getConfig()`).
54
+ * @returns The connected knex instance, on the current schema, with an
55
+ * `info` row unless `config` is `null`.
56
+ * @example
57
+ * ```ts
58
+ * const db = await buildFullSchemaTestDb(path.resolve(workingDir, 'source.sqlite'), {
59
+ * roots: ['https://a.example.com/'],
60
+ * });
61
+ * ```
62
+ */
63
+ export async function buildFullSchemaTestDb(filename, config = {}) {
64
+ const instance = knex({
65
+ client: LibsqlDialect,
66
+ connection: { filename },
67
+ useNullAsDefault: true,
68
+ });
69
+ await init(instance, false);
70
+ if (config !== null) {
71
+ await setConfig(instance, { ...DEFAULT_TEST_CONFIG, ...config });
72
+ }
73
+ return instance;
74
+ }
@@ -0,0 +1,31 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Attaches a source archive's `db.sqlite` file to the destination
4
+ * connection under the {@link TRANSFER_SOURCE_ALIAS} schema alias, so a
5
+ * transfer can read the source and write the destination in the same SQL
6
+ * statement (`INSERT INTO main.content_items SELECT ... FROM xfer_src.content_items`).
7
+ *
8
+ * `ATTACH DATABASE` must run OUTSIDE any transaction — SQLite rejects it
9
+ * with "cannot ATTACH database within transaction" otherwise — so this is
10
+ * always called before `knex.transaction(...)` opens, never inside it. The
11
+ * returned function detaches and must be called after the transaction
12
+ * commits or rolls back, in a `finally`.
13
+ * @param knex - Knex query builder connected to the destination archive DB
14
+ * (the connection whose schema this attaches to — not a transaction).
15
+ * @param sourceDbPath - Absolute path to the source's `db.sqlite` file
16
+ * (typically `path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME)`).
17
+ * @returns An async function that detaches the source. Idempotent-safe to
18
+ * call even if the attach itself failed partway (best-effort).
19
+ * @throws {Error} If `ATTACH DATABASE` fails (e.g. the path does not exist,
20
+ * or a transaction is already open on this connection).
21
+ * @example
22
+ * ```ts
23
+ * const detach = await attachSourceDatabase(knex, sourceDbPath);
24
+ * try {
25
+ * await knex.transaction(async (trx) => { ... trx.raw('SELECT * FROM xfer_src.content_items') ... });
26
+ * } finally {
27
+ * await detach();
28
+ * }
29
+ * ```
30
+ */
31
+ export declare function attachSourceDatabase(knex: Knex, sourceDbPath: string): Promise<() => Promise<void>>;
@@ -0,0 +1,40 @@
1
+ import { TRANSFER_SOURCE_ALIAS } from './transfer-source-alias.js';
2
+ /**
3
+ * Attaches a source archive's `db.sqlite` file to the destination
4
+ * connection under the {@link TRANSFER_SOURCE_ALIAS} schema alias, so a
5
+ * transfer can read the source and write the destination in the same SQL
6
+ * statement (`INSERT INTO main.content_items SELECT ... FROM xfer_src.content_items`).
7
+ *
8
+ * `ATTACH DATABASE` must run OUTSIDE any transaction — SQLite rejects it
9
+ * with "cannot ATTACH database within transaction" otherwise — so this is
10
+ * always called before `knex.transaction(...)` opens, never inside it. The
11
+ * returned function detaches and must be called after the transaction
12
+ * commits or rolls back, in a `finally`.
13
+ * @param knex - Knex query builder connected to the destination archive DB
14
+ * (the connection whose schema this attaches to — not a transaction).
15
+ * @param sourceDbPath - Absolute path to the source's `db.sqlite` file
16
+ * (typically `path.join(accessor.tmpDir, Archive.SQLITE_DB_FILE_NAME)`).
17
+ * @returns An async function that detaches the source. Idempotent-safe to
18
+ * call even if the attach itself failed partway (best-effort).
19
+ * @throws {Error} If `ATTACH DATABASE` fails (e.g. the path does not exist,
20
+ * or a transaction is already open on this connection).
21
+ * @example
22
+ * ```ts
23
+ * const detach = await attachSourceDatabase(knex, sourceDbPath);
24
+ * try {
25
+ * await knex.transaction(async (trx) => { ... trx.raw('SELECT * FROM xfer_src.content_items') ... });
26
+ * } finally {
27
+ * await detach();
28
+ * }
29
+ * ```
30
+ */
31
+ export async function attachSourceDatabase(knex, sourceDbPath) {
32
+ await knex.raw('ATTACH DATABASE ? AS ' + TRANSFER_SOURCE_ALIAS, [sourceDbPath]);
33
+ const attached = await knex.raw('PRAGMA database_list');
34
+ if (!attached.some((row) => row.name === TRANSFER_SOURCE_ALIAS)) {
35
+ throw new Error(`Failed to attach source database at ${sourceDbPath} — PRAGMA database_list does not list "${TRANSFER_SOURCE_ALIAS}" after ATTACH.`);
36
+ }
37
+ return async () => {
38
+ await knex.raw('DETACH DATABASE ' + TRANSFER_SOURCE_ALIAS).catch(() => { });
39
+ };
40
+ }
@@ -0,0 +1,30 @@
1
+ import type { Config } from '../types.js';
2
+ /**
3
+ * Derives the output {@link Config} for a `split`, from the source's own
4
+ * config plus the scope URLs the operator gave on the command line.
5
+ *
6
+ * `roots` becomes exactly the given URLs (their `withoutHash` form,
7
+ * matching how `crawl`'s own roots are recorded); `baseUrl` is the first
8
+ * one. Every other scalar field is carried over verbatim from the
9
+ * source — a split narrows WHICH pages are kept, it does not change HOW
10
+ * they were crawled (`recursive`/`interval`/`userAgent`/etc. all still
11
+ * describe the original session honestly). `excludes`/`excludeKeywords`/
12
+ * `excludeUrls` are likewise carried over unchanged (they described the
13
+ * source's own crawl-time exclusions, still true of the subset that
14
+ * survives). `version` is pinned to {@link REQUIRED_FORMAT_VERSION} and
15
+ * `createdCwd` is always `null`, matching `mergeArchiveConfigs`'s same
16
+ * two fields for the same reasons.
17
+ *
18
+ * Callers must reject a `fromList` source BEFORE calling this — `roots`
19
+ * for such an archive is a URL LIST, not a scope, so "roots = the given
20
+ * scope URLs" has no coherent meaning for it (see `docs/split.md`).
21
+ * @param source - The source archive's `getConfig()` result.
22
+ * @param scopeUrls - The scope URLs the operator gave (`withoutHash` form).
23
+ * @param name - The output archive's `name` (typically its basename).
24
+ * @returns The derived {@link Config} to write via `Archive#setConfig`.
25
+ * @example
26
+ * ```ts
27
+ * const config = buildSplitConfig(await source.getConfig(), ['https://example.com/blog/'], 'blog');
28
+ * ```
29
+ */
30
+ export declare function buildSplitConfig(source: Config, scopeUrls: readonly string[], name: string): Config;
@@ -0,0 +1,42 @@
1
+ import { REQUIRED_FORMAT_VERSION } from '../meta/assert-compatible-version.js';
2
+ /**
3
+ * Derives the output {@link Config} for a `split`, from the source's own
4
+ * config plus the scope URLs the operator gave on the command line.
5
+ *
6
+ * `roots` becomes exactly the given URLs (their `withoutHash` form,
7
+ * matching how `crawl`'s own roots are recorded); `baseUrl` is the first
8
+ * one. Every other scalar field is carried over verbatim from the
9
+ * source — a split narrows WHICH pages are kept, it does not change HOW
10
+ * they were crawled (`recursive`/`interval`/`userAgent`/etc. all still
11
+ * describe the original session honestly). `excludes`/`excludeKeywords`/
12
+ * `excludeUrls` are likewise carried over unchanged (they described the
13
+ * source's own crawl-time exclusions, still true of the subset that
14
+ * survives). `version` is pinned to {@link REQUIRED_FORMAT_VERSION} and
15
+ * `createdCwd` is always `null`, matching `mergeArchiveConfigs`'s same
16
+ * two fields for the same reasons.
17
+ *
18
+ * Callers must reject a `fromList` source BEFORE calling this — `roots`
19
+ * for such an archive is a URL LIST, not a scope, so "roots = the given
20
+ * scope URLs" has no coherent meaning for it (see `docs/split.md`).
21
+ * @param source - The source archive's `getConfig()` result.
22
+ * @param scopeUrls - The scope URLs the operator gave (`withoutHash` form).
23
+ * @param name - The output archive's `name` (typically its basename).
24
+ * @returns The derived {@link Config} to write via `Archive#setConfig`.
25
+ * @example
26
+ * ```ts
27
+ * const config = buildSplitConfig(await source.getConfig(), ['https://example.com/blog/'], 'blog');
28
+ * ```
29
+ */
30
+ export function buildSplitConfig(source, scopeUrls, name) {
31
+ if (scopeUrls.length === 0) {
32
+ throw new Error('buildSplitConfig: at least one scope URL is required');
33
+ }
34
+ return {
35
+ ...source,
36
+ version: REQUIRED_FORMAT_VERSION,
37
+ name,
38
+ roots: [...scopeUrls],
39
+ baseUrl: scopeUrls[0],
40
+ createdCwd: null,
41
+ };
42
+ }
@@ -0,0 +1,20 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Deletes every page-scoped derived row for a concat source's `replace`-
4
+ * action destination ids (`temp.xfer_ci_plan.dest_id`), across all 21
5
+ * tables in {@link REMAPPED_PAGE_ROW_TABLES} + {@link SIMPLE_PAGE_SCOPED_TABLES}
6
+ * combined — set-based (`WHERE ... IN (subquery)`), so there is no
7
+ * `SQLITE_LIMIT_VARIABLE_NUMBER` bind-count concern regardless of how many
8
+ * rows are being replaced.
9
+ *
10
+ * Must run BEFORE the page-scoped table copies
11
+ * (`copy-page-meta.ts` et al.) so their `INSERT`s never collide with
12
+ * stale rows left over from the losing destination row's own prior data.
13
+ * @param trx - Transaction with the source ATTACHed.
14
+ * @example
15
+ * ```ts
16
+ * await clearReplacedPageRows(trx);
17
+ * await replaceContentItems(trx, { crawlOrderOffset: 0 });
18
+ * ```
19
+ */
20
+ export declare function clearReplacedPageRows(trx: Knex): Promise<void>;
@@ -0,0 +1,57 @@
1
+ import { SIMPLE_PAGE_SCOPED_TABLES } from './simple-page-scoped-tables.js';
2
+ import { TRANSFER_ACTION } from './transfer-action.js';
3
+ /**
4
+ * The page-scoped tables NOT covered by {@link SIMPLE_PAGE_SCOPED_TABLES}
5
+ * (which this file also clears — see below) — each of these has its own
6
+ * dedicated FK-remapping copy function (`copy-page-meta.ts`,
7
+ * `copy-anchor-edges.ts`, `copy-image-items.ts`,
8
+ * `copy-resource-ref-edges.ts`, `copy-page-console-logs.ts`,
9
+ * `copy-analysis-violations.ts`), so they are listed explicitly rather
10
+ * than folded into the shared "plain passthrough" table. Together the two
11
+ * lists are a superset of `clearPageDerivedRows`' 17 tables (reused by
12
+ * `resetFailedPages`/`repromoteExternalPages` for the same
13
+ * un-scrape-then-re-insert shape) — this combined 21 additionally covers
14
+ * `page_console_logs`/`page_templates`/`analysis_violations`/`page_errors`,
15
+ * which that shared helper deliberately omits (see its own JSDoc for why:
16
+ * `repromoteExternalPages` never needed them cleared, and folding them in
17
+ * would have silently changed its existing behaviour). Concat's replace
18
+ * path needs all 21 — a `replace` is a full Scoped-Replace of every
19
+ * page-scoped table, not a partial one.
20
+ */
21
+ const REMAPPED_PAGE_ROW_TABLES = [
22
+ { table: 'page_meta', pageColumn: 'page_id' },
23
+ { table: 'anchor_edges', pageColumn: 'page_id' },
24
+ { table: 'image_items', pageColumn: 'page_id' },
25
+ { table: 'resource_ref_edges', pageColumn: 'page_id' },
26
+ { table: 'page_console_logs', pageColumn: 'pageId' },
27
+ { table: 'analysis_violations', pageColumn: 'page_id' },
28
+ ];
29
+ /**
30
+ * Deletes every page-scoped derived row for a concat source's `replace`-
31
+ * action destination ids (`temp.xfer_ci_plan.dest_id`), across all 21
32
+ * tables in {@link REMAPPED_PAGE_ROW_TABLES} + {@link SIMPLE_PAGE_SCOPED_TABLES}
33
+ * combined — set-based (`WHERE ... IN (subquery)`), so there is no
34
+ * `SQLITE_LIMIT_VARIABLE_NUMBER` bind-count concern regardless of how many
35
+ * rows are being replaced.
36
+ *
37
+ * Must run BEFORE the page-scoped table copies
38
+ * (`copy-page-meta.ts` et al.) so their `INSERT`s never collide with
39
+ * stale rows left over from the losing destination row's own prior data.
40
+ * @param trx - Transaction with the source ATTACHed.
41
+ * @example
42
+ * ```ts
43
+ * await clearReplacedPageRows(trx);
44
+ * await replaceContentItems(trx, { crawlOrderOffset: 0 });
45
+ * ```
46
+ */
47
+ export async function clearReplacedPageRows(trx) {
48
+ const tables = [...REMAPPED_PAGE_ROW_TABLES, ...SIMPLE_PAGE_SCOPED_TABLES];
49
+ for (const { table, pageColumn } of tables) {
50
+ await trx.raw(`
51
+ DELETE FROM main.${table}
52
+ WHERE ${pageColumn} IN (
53
+ SELECT dest_id FROM xfer_ci_plan WHERE action = ${TRANSFER_ACTION.replace}
54
+ )
55
+ `);
56
+ }
57
+ }