@nitpicker/crawler 0.22.0 → 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 (136) 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/pages/read/get-crawling-state.d.ts +43 -3
  12. package/lib/archive/db-ops/pages/read/get-crawling-state.js +61 -6
  13. package/lib/archive/db-ops/pages/write/update-page.js +10 -2
  14. package/lib/archive/db-ops/templates/assign-template-labels.d.ts +60 -0
  15. package/lib/archive/db-ops/templates/assign-template-labels.js +187 -0
  16. package/lib/archive/db-ops/{analysis → templates}/replace-page-templates.d.ts +19 -3
  17. package/lib/archive/db-ops/templates/replace-page-templates.js +174 -0
  18. package/lib/archive/db-ops/{analysis → templates}/types.d.ts +38 -0
  19. package/lib/archive/init-schema.d.ts +5 -1
  20. package/lib/archive/init-schema.js +13 -2
  21. package/lib/archive/test-utils/build-full-schema-test-db.d.ts +34 -0
  22. package/lib/archive/test-utils/build-full-schema-test-db.js +74 -0
  23. package/lib/archive/transfer/attach-source-database.d.ts +31 -0
  24. package/lib/archive/transfer/attach-source-database.js +40 -0
  25. package/lib/archive/transfer/build-split-config.d.ts +30 -0
  26. package/lib/archive/transfer/build-split-config.js +42 -0
  27. package/lib/archive/transfer/clear-replaced-page-rows.d.ts +20 -0
  28. package/lib/archive/transfer/clear-replaced-page-rows.js +57 -0
  29. package/lib/archive/transfer/concat-archives.d.ts +55 -0
  30. package/lib/archive/transfer/concat-archives.js +95 -0
  31. package/lib/archive/transfer/content-item-rank-sql.d.ts +21 -0
  32. package/lib/archive/transfer/content-item-rank-sql.js +23 -0
  33. package/lib/archive/transfer/copy-analysis-violations.d.ts +19 -0
  34. package/lib/archive/transfer/copy-analysis-violations.js +43 -0
  35. package/lib/archive/transfer/copy-anchor-edges.d.ts +28 -0
  36. package/lib/archive/transfer/copy-anchor-edges.js +42 -0
  37. package/lib/archive/transfer/copy-dictionaries-for-concat.d.ts +39 -0
  38. package/lib/archive/transfer/copy-dictionaries-for-concat.js +81 -0
  39. package/lib/archive/transfer/copy-dictionaries-for-split.d.ts +29 -0
  40. package/lib/archive/transfer/copy-dictionaries-for-split.js +235 -0
  41. package/lib/archive/transfer/copy-header-set-children.d.ts +27 -0
  42. package/lib/archive/transfer/copy-header-set-children.js +51 -0
  43. package/lib/archive/transfer/copy-image-items.d.ts +21 -0
  44. package/lib/archive/transfer/copy-image-items.js +62 -0
  45. package/lib/archive/transfer/copy-inventory-source-lists.d.ts +30 -0
  46. package/lib/archive/transfer/copy-inventory-source-lists.js +61 -0
  47. package/lib/archive/transfer/copy-journal-tables.d.ts +30 -0
  48. package/lib/archive/transfer/copy-journal-tables.js +56 -0
  49. package/lib/archive/transfer/copy-page-console-logs.d.ts +16 -0
  50. package/lib/archive/transfer/copy-page-console-logs.js +27 -0
  51. package/lib/archive/transfer/copy-page-html-blobs.d.ts +31 -0
  52. package/lib/archive/transfer/copy-page-html-blobs.js +43 -0
  53. package/lib/archive/transfer/copy-page-meta.d.ts +27 -0
  54. package/lib/archive/transfer/copy-page-meta.js +68 -0
  55. package/lib/archive/transfer/copy-page-template-clusters.d.ts +31 -0
  56. package/lib/archive/transfer/copy-page-template-clusters.js +56 -0
  57. package/lib/archive/transfer/copy-page-template-labels.d.ts +34 -0
  58. package/lib/archive/transfer/copy-page-template-labels.js +88 -0
  59. package/lib/archive/transfer/copy-resource-items.d.ts +29 -0
  60. package/lib/archive/transfer/copy-resource-items.js +89 -0
  61. package/lib/archive/transfer/copy-resource-ref-edges.d.ts +20 -0
  62. package/lib/archive/transfer/copy-resource-ref-edges.js +33 -0
  63. package/lib/archive/transfer/copy-simple-page-scoped-tables.d.ts +15 -0
  64. package/lib/archive/transfer/copy-simple-page-scoped-tables.js +34 -0
  65. package/lib/archive/transfer/count-external-pages-in-scope.d.ts +26 -0
  66. package/lib/archive/transfer/count-external-pages-in-scope.js +40 -0
  67. package/lib/archive/transfer/create-transfer-temp-tables.d.ts +30 -0
  68. package/lib/archive/transfer/create-transfer-temp-tables.js +59 -0
  69. package/lib/archive/transfer/dictionary-copy-specs.d.ts +32 -0
  70. package/lib/archive/transfer/dictionary-copy-specs.js +29 -0
  71. package/lib/archive/transfer/drop-transfer-temp-tables.d.ts +9 -0
  72. package/lib/archive/transfer/drop-transfer-temp-tables.js +18 -0
  73. package/lib/archive/transfer/flatten-redirect-chains.d.ts +44 -0
  74. package/lib/archive/transfer/flatten-redirect-chains.js +74 -0
  75. package/lib/archive/transfer/insert-content-items.d.ts +35 -0
  76. package/lib/archive/transfer/insert-content-items.js +116 -0
  77. package/lib/archive/transfer/list-transfer-columns.d.ts +35 -0
  78. package/lib/archive/transfer/list-transfer-columns.js +45 -0
  79. package/lib/archive/transfer/mark-in-scope-content-items.d.ts +31 -0
  80. package/lib/archive/transfer/mark-in-scope-content-items.js +54 -0
  81. package/lib/archive/transfer/merge-archive-configs.d.ts +48 -0
  82. package/lib/archive/transfer/merge-archive-configs.js +78 -0
  83. package/lib/archive/transfer/plan-content-items-for-concat.d.ts +33 -0
  84. package/lib/archive/transfer/plan-content-items-for-concat.js +51 -0
  85. package/lib/archive/transfer/plan-content-items-for-split.d.ts +42 -0
  86. package/lib/archive/transfer/plan-content-items-for-split.js +83 -0
  87. package/lib/archive/transfer/plan-resource-items.d.ts +40 -0
  88. package/lib/archive/transfer/plan-resource-items.js +69 -0
  89. package/lib/archive/transfer/quote-transfer-identifier.d.ts +18 -0
  90. package/lib/archive/transfer/quote-transfer-identifier.js +20 -0
  91. package/lib/archive/transfer/reclassify-resource-externality.d.ts +37 -0
  92. package/lib/archive/transfer/reclassify-resource-externality.js +66 -0
  93. package/lib/archive/transfer/remap-redirect-dest-ids.d.ts +34 -0
  94. package/lib/archive/transfer/remap-redirect-dest-ids.js +51 -0
  95. package/lib/archive/transfer/replace-content-items.d.ts +39 -0
  96. package/lib/archive/transfer/replace-content-items.js +83 -0
  97. package/lib/archive/transfer/simple-page-scoped-tables.d.ts +25 -0
  98. package/lib/archive/transfer/simple-page-scoped-tables.js +38 -0
  99. package/lib/archive/transfer/split-archive.d.ts +55 -0
  100. package/lib/archive/transfer/split-archive.js +98 -0
  101. package/lib/archive/transfer/transfer-action.d.ts +34 -0
  102. package/lib/archive/transfer/transfer-action.js +32 -0
  103. package/lib/archive/transfer/transfer-archive-rows.d.ts +65 -0
  104. package/lib/archive/transfer/transfer-archive-rows.js +158 -0
  105. package/lib/archive/transfer/transfer-dictionary-tables.d.ts +12 -0
  106. package/lib/archive/transfer/transfer-dictionary-tables.js +23 -0
  107. package/lib/archive/transfer/transfer-source-alias.d.ts +9 -0
  108. package/lib/archive/transfer/transfer-source-alias.js +9 -0
  109. package/lib/archive/transfer/types.d.ts +111 -0
  110. package/lib/archive/transfer/types.js +35 -0
  111. package/lib/concat-source-transfer-phases.d.ts +10 -0
  112. package/lib/concat-source-transfer-phases.js +17 -0
  113. package/lib/crawler/build-scope-map.d.ts +21 -0
  114. package/lib/crawler/build-scope-map.js +32 -0
  115. package/lib/crawler-orchestrator.js +10 -16
  116. package/lib/crawler.d.ts +13 -1
  117. package/lib/crawler.js +22 -0
  118. package/lib/split-source-transfer-phases.d.ts +11 -0
  119. package/lib/split-source-transfer-phases.js +18 -0
  120. package/lib/template-classification/classify-archive-page-templates.d.ts +41 -0
  121. package/lib/template-classification/classify-archive-page-templates.js +79 -0
  122. package/lib/template-classification/classify-page-templates.d.ts +37 -0
  123. package/lib/template-classification/classify-page-templates.js +69 -0
  124. package/lib/template-classification/collect-page-stylesheet-urls.d.ts +32 -0
  125. package/lib/template-classification/collect-page-stylesheet-urls.js +130 -0
  126. package/lib/template-classification/create-content-root-hint.d.ts +36 -0
  127. package/lib/template-classification/create-content-root-hint.js +47 -0
  128. package/lib/template-classification/create-page-cluster-factory.d.ts +60 -0
  129. package/lib/template-classification/create-page-cluster-factory.js +98 -0
  130. package/lib/template-classification/types.d.ts +108 -0
  131. package/lib/template-classification/types.js +1 -0
  132. package/lib/transfer-post-phases.d.ts +10 -0
  133. package/lib/transfer-post-phases.js +13 -0
  134. package/package.json +3 -2
  135. package/lib/archive/db-ops/analysis/replace-page-templates.js +0 -84
  136. /package/lib/archive/db-ops/{analysis → templates}/types.js +0 -0
@@ -0,0 +1,37 @@
1
+ import type { ExURL, ParseURLOptions } from '@d-zero/shared/parse-url';
2
+ import type { Knex } from 'knex';
3
+ /**
4
+ * Recomputes `resource_items.is_external` for the WHOLE destination
5
+ * archive against its final (merged or narrowed) scope, once every source
6
+ * has been transferred.
7
+ *
8
+ * Unlike `content_items.is_external` ("was this taken on as a crawl
9
+ * target" — a write-time fact this transfer never re-derives, per
10
+ * ARCHITECTURE.md's invariant), `resource_items.is_external` is a pure
11
+ * scope check computed the same way at crawl time
12
+ * (`crawler.ts`'s `#handleResources`: `findScopeEntry(url, this.#scope)
13
+ * === null`). Concat's merged scope is a union of every source's roots,
14
+ * so a resource one source recorded as external can legitimately become
15
+ * internal-by-scope in the output even though nothing about the resource
16
+ * itself changed — recomputing this is the resource-table equivalent of
17
+ * what `content_items` deliberately does NOT do, and the two must not be
18
+ * "unified" into the same rule.
19
+ *
20
+ * Mirrors `repromoteExternalPages`'s shape (load every resource's URL,
21
+ * classify in JS, write matches back in bound-safe chunks) rather than a
22
+ * single SQL scope join — `resource_items.url_id` is nullable
23
+ * (`url_blob_id` rows have no URL to classify and are left as recorded),
24
+ * so the candidate set is every resource with a non-null `url_id`.
25
+ * @param trx - The destination transaction (no source ATTACHed).
26
+ * @param scope - The output archive's final scope map
27
+ * (`buildScopeMap(mergedOrNarrowedRoots, config)`).
28
+ * @param options - URL parsing options forwarded to {@link findScopeEntry}
29
+ * (the output archive's own `disableQueries`).
30
+ * @returns The number of resources whose `is_external` flipped.
31
+ * @example
32
+ * ```ts
33
+ * const scope = buildScopeMap(config.roots, config);
34
+ * const flipped = await reclassifyResourceExternality(knex, scope, config);
35
+ * ```
36
+ */
37
+ export declare function reclassifyResourceExternality(trx: Knex, scope: ReadonlyMap<string, readonly ExURL[]>, options?: ParseURLOptions): Promise<number>;
@@ -0,0 +1,66 @@
1
+ import { tryParseUrl as parseUrl } from '@d-zero/shared/parse-url';
2
+ import { findScopeEntry } from '../../crawler/find-scope-entry.js';
3
+ /**
4
+ * Recomputes `resource_items.is_external` for the WHOLE destination
5
+ * archive against its final (merged or narrowed) scope, once every source
6
+ * has been transferred.
7
+ *
8
+ * Unlike `content_items.is_external` ("was this taken on as a crawl
9
+ * target" — a write-time fact this transfer never re-derives, per
10
+ * ARCHITECTURE.md's invariant), `resource_items.is_external` is a pure
11
+ * scope check computed the same way at crawl time
12
+ * (`crawler.ts`'s `#handleResources`: `findScopeEntry(url, this.#scope)
13
+ * === null`). Concat's merged scope is a union of every source's roots,
14
+ * so a resource one source recorded as external can legitimately become
15
+ * internal-by-scope in the output even though nothing about the resource
16
+ * itself changed — recomputing this is the resource-table equivalent of
17
+ * what `content_items` deliberately does NOT do, and the two must not be
18
+ * "unified" into the same rule.
19
+ *
20
+ * Mirrors `repromoteExternalPages`'s shape (load every resource's URL,
21
+ * classify in JS, write matches back in bound-safe chunks) rather than a
22
+ * single SQL scope join — `resource_items.url_id` is nullable
23
+ * (`url_blob_id` rows have no URL to classify and are left as recorded),
24
+ * so the candidate set is every resource with a non-null `url_id`.
25
+ * @param trx - The destination transaction (no source ATTACHed).
26
+ * @param scope - The output archive's final scope map
27
+ * (`buildScopeMap(mergedOrNarrowedRoots, config)`).
28
+ * @param options - URL parsing options forwarded to {@link findScopeEntry}
29
+ * (the output archive's own `disableQueries`).
30
+ * @returns The number of resources whose `is_external` flipped.
31
+ * @example
32
+ * ```ts
33
+ * const scope = buildScopeMap(config.roots, config);
34
+ * const flipped = await reclassifyResourceExternality(knex, scope, config);
35
+ * ```
36
+ */
37
+ export async function reclassifyResourceExternality(trx, scope, options) {
38
+ const candidates = await trx
39
+ .select('resource_items.id as id', 'url_refs.url as url', 'resource_items.is_external')
40
+ .from('resource_items')
41
+ .join('url_refs', 'url_refs.id', 'resource_items.url_id');
42
+ const toInternal = [];
43
+ const toExternal = [];
44
+ for (const row of candidates) {
45
+ const parsed = parseUrl(row.url, options);
46
+ const isExternal = parsed ? findScopeEntry(parsed, scope, options) === null : true;
47
+ if (isExternal && row.is_external === 0) {
48
+ toExternal.push(row.id);
49
+ }
50
+ else if (!isExternal && row.is_external === 1) {
51
+ toInternal.push(row.id);
52
+ }
53
+ }
54
+ const chunkSize = 500;
55
+ for (const [ids, value] of [
56
+ [toInternal, 0],
57
+ [toExternal, 1],
58
+ ]) {
59
+ for (let i = 0; i < ids.length; i += chunkSize) {
60
+ await trx('resource_items')
61
+ .whereIn('id', ids.slice(i, i + chunkSize))
62
+ .update({ is_external: value });
63
+ }
64
+ }
65
+ return toInternal.length + toExternal.length;
66
+ }
@@ -0,0 +1,34 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Remaps `redirect_dest_id` for every `full`/`stub`/`replace`-action
4
+ * destination row this source just wrote, from the source's own id space
5
+ * into the destination's, via `temp.xfer_ci_plan` (which by this point
6
+ * maps EVERY source id to a destination id, not just the ones this source
7
+ * inserted — `skip`/`replace` rows already had `dest_id` set at plan
8
+ * time).
9
+ *
10
+ * `skip`-action rows are deliberately excluded from the `SET` target
11
+ * (via the `p.action IN (...)` filter) — a `skip` row's `content_items`
12
+ * row belongs to a PRIOR, better-ranked source, and this (losing) source
13
+ * has no business touching its `redirect_dest_id`.
14
+ *
15
+ * Must run AFTER both
16
+ * {@link import('./insert-content-items.js').insertContentItems} and
17
+ * {@link import('./replace-content-items.js').replaceContentItems} —
18
+ * every plan row needs a resolved `dest_id` (its own AND its redirect
19
+ * target's) before this can run. A source row whose `redirect_dest_id`
20
+ * points outside this source's own plan (should not happen — concat's
21
+ * plan covers every source row, and split's plan closure always pulls a
22
+ * kept row's redirect target in too, see `plan-content-items-for-split.ts`)
23
+ * silently leaves that destination row's `redirect_dest_id` at `NULL`
24
+ * rather than erroring — a dangling-but-absent redirect is a safe
25
+ * degrade, never a wrong one.
26
+ * @param trx - Transaction with the source ATTACHed as
27
+ * {@link TRANSFER_SOURCE_ALIAS}.
28
+ * @example
29
+ * ```ts
30
+ * await insertContentItems(trx, { crawlOrderOffset: 0 });
31
+ * await remapRedirectDestIds(trx);
32
+ * ```
33
+ */
34
+ export declare function remapRedirectDestIds(trx: Knex): Promise<void>;
@@ -0,0 +1,51 @@
1
+ import { TRANSFER_ACTION } from './transfer-action.js';
2
+ import { TRANSFER_SOURCE_ALIAS } from './transfer-source-alias.js';
3
+ /**
4
+ * Remaps `redirect_dest_id` for every `full`/`stub`/`replace`-action
5
+ * destination row this source just wrote, from the source's own id space
6
+ * into the destination's, via `temp.xfer_ci_plan` (which by this point
7
+ * maps EVERY source id to a destination id, not just the ones this source
8
+ * inserted — `skip`/`replace` rows already had `dest_id` set at plan
9
+ * time).
10
+ *
11
+ * `skip`-action rows are deliberately excluded from the `SET` target
12
+ * (via the `p.action IN (...)` filter) — a `skip` row's `content_items`
13
+ * row belongs to a PRIOR, better-ranked source, and this (losing) source
14
+ * has no business touching its `redirect_dest_id`.
15
+ *
16
+ * Must run AFTER both
17
+ * {@link import('./insert-content-items.js').insertContentItems} and
18
+ * {@link import('./replace-content-items.js').replaceContentItems} —
19
+ * every plan row needs a resolved `dest_id` (its own AND its redirect
20
+ * target's) before this can run. A source row whose `redirect_dest_id`
21
+ * points outside this source's own plan (should not happen — concat's
22
+ * plan covers every source row, and split's plan closure always pulls a
23
+ * kept row's redirect target in too, see `plan-content-items-for-split.ts`)
24
+ * silently leaves that destination row's `redirect_dest_id` at `NULL`
25
+ * rather than erroring — a dangling-but-absent redirect is a safe
26
+ * degrade, never a wrong one.
27
+ * @param trx - Transaction with the source ATTACHed as
28
+ * {@link TRANSFER_SOURCE_ALIAS}.
29
+ * @example
30
+ * ```ts
31
+ * await insertContentItems(trx, { crawlOrderOffset: 0 });
32
+ * await remapRedirectDestIds(trx);
33
+ * ```
34
+ */
35
+ export async function remapRedirectDestIds(trx) {
36
+ await trx.raw(`
37
+ UPDATE main.content_items
38
+ SET redirect_dest_id = x.redirect_dest_id
39
+ FROM (
40
+ SELECT p.dest_id AS id, p2.dest_id AS redirect_dest_id
41
+ FROM xfer_ci_plan p
42
+ JOIN ${TRANSFER_SOURCE_ALIAS}.content_items s ON s.id = p.src_id
43
+ JOIN xfer_ci_plan p2 ON p2.src_id = s.redirect_dest_id
44
+ WHERE s.redirect_dest_id IS NOT NULL
45
+ AND p.action IN (${TRANSFER_ACTION.full}, ${TRANSFER_ACTION.stub}, ${TRANSFER_ACTION.replace})
46
+ AND p2.dest_id IS NOT NULL
47
+ ) x
48
+ WHERE main.content_items.id = x.id
49
+ AND x.redirect_dest_id != x.id
50
+ `);
51
+ }
@@ -0,0 +1,39 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Overwrites every `replace`-action destination `content_items` row
4
+ * (concat only — split never assigns `replace`) with this source's
5
+ * column values, using the same per-column remap rules
6
+ * {@link import('./insert-content-items.js').insertContentItems} applies
7
+ * (dictionary FKs through their `temp.xfer_map_*` table, `redirect_dest_id`/
8
+ * `alias_of_id`/`dedupe_cap_event_id` always `NULL`, `crawl_order` offset).
9
+ *
10
+ * `url_id` is deliberately excluded from the UPDATE — a `replace` row was
11
+ * matched by URL string in the first place (`plan-content-items-for-concat.ts`),
12
+ * so the destination's `url_id` already points at the correct `url_refs`
13
+ * row and must not change. `is_external`/`is_target` are never forced
14
+ * here (unlike `insertContentItems`'s `stub` case) — concat has no stub
15
+ * action, so the source's own observed values pass straight through the
16
+ * generic `default` branch.
17
+ *
18
+ * Must run BEFORE {@link import('./insert-content-items.js').insertContentItems}
19
+ * would otherwise be fine in either order relative to it (they touch
20
+ * disjoint plan actions), but MUST run before the page-scoped table
21
+ * copies (`copy-page-meta.ts` et al.) — and after
22
+ * {@link import('./clear-replaced-page-rows.js').clearReplacedPageRows}
23
+ * has deleted the old derived rows for these same destination ids, so the
24
+ * fresh page-scoped copy does not collide with stale data.
25
+ * @param trx - Transaction with the source ATTACHed as
26
+ * {@link TRANSFER_SOURCE_ALIAS}.
27
+ * @param options - Options.
28
+ * @param options.crawlOrderOffset - See `insertContentItems`'s parameter
29
+ * of the same name — the same value passed to that call for this source.
30
+ * @example
31
+ * ```ts
32
+ * await clearReplacedPageRows(trx);
33
+ * await replaceContentItems(trx, { crawlOrderOffset: 0 });
34
+ * await insertContentItems(trx, { crawlOrderOffset: 0 });
35
+ * ```
36
+ */
37
+ export declare function replaceContentItems(trx: Knex, options: {
38
+ crawlOrderOffset: number;
39
+ }): Promise<void>;
@@ -0,0 +1,83 @@
1
+ import { listTransferColumns } from './list-transfer-columns.js';
2
+ import { quoteTransferIdentifier } from './quote-transfer-identifier.js';
3
+ import { TRANSFER_ACTION } from './transfer-action.js';
4
+ import { TRANSFER_SOURCE_ALIAS } from './transfer-source-alias.js';
5
+ const SRC = TRANSFER_SOURCE_ALIAS;
6
+ /**
7
+ * Overwrites every `replace`-action destination `content_items` row
8
+ * (concat only — split never assigns `replace`) with this source's
9
+ * column values, using the same per-column remap rules
10
+ * {@link import('./insert-content-items.js').insertContentItems} applies
11
+ * (dictionary FKs through their `temp.xfer_map_*` table, `redirect_dest_id`/
12
+ * `alias_of_id`/`dedupe_cap_event_id` always `NULL`, `crawl_order` offset).
13
+ *
14
+ * `url_id` is deliberately excluded from the UPDATE — a `replace` row was
15
+ * matched by URL string in the first place (`plan-content-items-for-concat.ts`),
16
+ * so the destination's `url_id` already points at the correct `url_refs`
17
+ * row and must not change. `is_external`/`is_target` are never forced
18
+ * here (unlike `insertContentItems`'s `stub` case) — concat has no stub
19
+ * action, so the source's own observed values pass straight through the
20
+ * generic `default` branch.
21
+ *
22
+ * Must run BEFORE {@link import('./insert-content-items.js').insertContentItems}
23
+ * would otherwise be fine in either order relative to it (they touch
24
+ * disjoint plan actions), but MUST run before the page-scoped table
25
+ * copies (`copy-page-meta.ts` et al.) — and after
26
+ * {@link import('./clear-replaced-page-rows.js').clearReplacedPageRows}
27
+ * has deleted the old derived rows for these same destination ids, so the
28
+ * fresh page-scoped copy does not collide with stale data.
29
+ * @param trx - Transaction with the source ATTACHed as
30
+ * {@link TRANSFER_SOURCE_ALIAS}.
31
+ * @param options - Options.
32
+ * @param options.crawlOrderOffset - See `insertContentItems`'s parameter
33
+ * of the same name — the same value passed to that call for this source.
34
+ * @example
35
+ * ```ts
36
+ * await clearReplacedPageRows(trx);
37
+ * await replaceContentItems(trx, { crawlOrderOffset: 0 });
38
+ * await insertContentItems(trx, { crawlOrderOffset: 0 });
39
+ * ```
40
+ */
41
+ export async function replaceContentItems(trx, options) {
42
+ const columns = await listTransferColumns(trx, SRC, 'content_items', ['id', 'url_id']);
43
+ const setList = columns
44
+ .map((col) => `${quoteTransferIdentifier(col)} = x.${quoteTransferIdentifier(col)}`)
45
+ .join(', ');
46
+ const selectList = columns
47
+ .map((col) => {
48
+ const quotedCol = quoteTransferIdentifier(col);
49
+ switch (col) {
50
+ case 'content_type_id': {
51
+ return `mct.dest_id AS ${quotedCol}`;
52
+ }
53
+ case 'header_set_id': {
54
+ return `mhs.dest_id AS ${quotedCol}`;
55
+ }
56
+ case 'redirect_dest_id':
57
+ case 'alias_of_id':
58
+ case 'dedupe_cap_event_id': {
59
+ return `NULL AS ${quotedCol}`;
60
+ }
61
+ case 'crawl_order': {
62
+ return `s.crawl_order + ${options.crawlOrderOffset} AS ${quotedCol}`;
63
+ }
64
+ default: {
65
+ return `s.${quotedCol} AS ${quotedCol}`;
66
+ }
67
+ }
68
+ })
69
+ .join(', ');
70
+ await trx.raw(`
71
+ UPDATE main.content_items
72
+ SET ${setList}
73
+ FROM (
74
+ SELECT p.dest_id AS dest_id, ${selectList}
75
+ FROM xfer_ci_plan p
76
+ JOIN ${SRC}.content_items s ON s.id = p.src_id
77
+ LEFT JOIN xfer_map_content_type_refs mct ON mct.src_id = s.content_type_id
78
+ LEFT JOIN xfer_map_header_sets mhs ON mhs.src_id = s.header_set_id
79
+ WHERE p.action = ${TRANSFER_ACTION.replace}
80
+ ) x
81
+ WHERE main.content_items.id = x.dest_id
82
+ `);
83
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Every page-scoped table whose only FK column is its own page reference
3
+ * — no dictionary or cross-entity FK columns to remap, so every other
4
+ * column passes through unchanged. Covers the 9
5
+ * beholder-`MainContentsData` sub-entity tables, the technology-detection
6
+ * pair (always updated together, per ARCHITECTURE.md's pairing
7
+ * invariant — copying both in the same call keeps that true here too),
8
+ * `page_jsonld`, `page_errors`, `page_html_ref` (`hash` is the content-
9
+ * addressed identity of a `page_html_blobs` row, identical in every archive,
10
+ * so it passes through once `copy-page-html-blobs.ts` has copied the blob),
11
+ * and `page_templates` (`template_key` is a plain string column, not a
12
+ * dictionary FK — see `copy-page-template-clusters.ts` for its paired
13
+ * cluster-evidence table).
14
+ *
15
+ * Shared between {@link import('./copy-simple-page-scoped-tables.js').copySimplePageScopedTables}
16
+ * (what to copy verbatim) and
17
+ * {@link import('./clear-replaced-page-rows.js').clearReplacedPageRows}
18
+ * (a subset of what to delete for a `replace`d page) — a single list here
19
+ * means a future page-scoped table only needs adding in one place to stay
20
+ * consistent between the two operations.
21
+ */
22
+ export declare const SIMPLE_PAGE_SCOPED_TABLES: readonly {
23
+ table: string;
24
+ pageColumn: string;
25
+ }[];
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Every page-scoped table whose only FK column is its own page reference
3
+ * — no dictionary or cross-entity FK columns to remap, so every other
4
+ * column passes through unchanged. Covers the 9
5
+ * beholder-`MainContentsData` sub-entity tables, the technology-detection
6
+ * pair (always updated together, per ARCHITECTURE.md's pairing
7
+ * invariant — copying both in the same call keeps that true here too),
8
+ * `page_jsonld`, `page_errors`, `page_html_ref` (`hash` is the content-
9
+ * addressed identity of a `page_html_blobs` row, identical in every archive,
10
+ * so it passes through once `copy-page-html-blobs.ts` has copied the blob),
11
+ * and `page_templates` (`template_key` is a plain string column, not a
12
+ * dictionary FK — see `copy-page-template-clusters.ts` for its paired
13
+ * cluster-evidence table).
14
+ *
15
+ * Shared between {@link import('./copy-simple-page-scoped-tables.js').copySimplePageScopedTables}
16
+ * (what to copy verbatim) and
17
+ * {@link import('./clear-replaced-page-rows.js').clearReplacedPageRows}
18
+ * (a subset of what to delete for a `replace`d page) — a single list here
19
+ * means a future page-scoped table only needs adding in one place to stay
20
+ * consistent between the two operations.
21
+ */
22
+ export const SIMPLE_PAGE_SCOPED_TABLES = [
23
+ { table: 'page_main_content_headings', pageColumn: 'pageId' },
24
+ { table: 'page_main_content_images', pageColumn: 'pageId' },
25
+ { table: 'page_main_content_tables', pageColumn: 'pageId' },
26
+ { table: 'page_main_content_buttons', pageColumn: 'pageId' },
27
+ { table: 'page_main_content_iframes', pageColumn: 'pageId' },
28
+ { table: 'page_main_content_videos', pageColumn: 'pageId' },
29
+ { table: 'page_main_content_audios', pageColumn: 'pageId' },
30
+ { table: 'page_main_content_canvases', pageColumn: 'pageId' },
31
+ { table: 'page_main_content_custom_elements', pageColumn: 'pageId' },
32
+ { table: 'technology_signals', pageColumn: 'pageId' },
33
+ { table: 'page_technologies', pageColumn: 'pageId' },
34
+ { table: 'page_jsonld', pageColumn: 'pageId' },
35
+ { table: 'page_errors', pageColumn: 'pageId' },
36
+ { table: 'page_html_ref', pageColumn: 'page_id' },
37
+ { table: 'page_templates', pageColumn: 'page_id' },
38
+ ];
@@ -0,0 +1,55 @@
1
+ import type { ArchiveAccessor } from '../archive-accessor.js';
2
+ import type Archive from '../archive.js';
3
+ import type { SplitArchiveResult, TransferCallbacks } from './types.js';
4
+ /**
5
+ * Extracts the subset of one read-only-opened source archive within the
6
+ * given scope URLs into an already `Archive.create`d, empty destination —
7
+ * the crawler-side half of the `split` CLI command. Does not open/close/
8
+ * write anything itself; see `concat-archives.ts`'s docs for the same
9
+ * lifecycle-ownership split (the CLI's `commands/split.ts` owns open →
10
+ * transfer → rebuild-read-model → write).
11
+ *
12
+ * Rejects a `fromList` source up front — see `build-split-config.ts`'s
13
+ * docs for why "roots = the given scope" has no coherent meaning for an
14
+ * archive whose `roots` is a URL list rather than a scope.
15
+ *
16
+ * `flattenRedirectChains` still runs even though a single, not-yet-merged
17
+ * source is already flat by construction — a cheap no-op, kept for the
18
+ * same reason `reclassifyResourceExternality` is written mode-agnostic
19
+ * rather than split having its own near-duplicate of each.
20
+ * @param options - See individual properties.
21
+ * @param options.source - The source, read-only opened
22
+ * (`Archive.openCached`).
23
+ * @param options.source.path
24
+ * @param options.source.accessor
25
+ * @param options.scopeUrls - The scope URLs the operator gave (raw
26
+ * strings; normalised to `withoutHash` form by
27
+ * {@link import('./build-split-config.js').buildSplitConfig}).
28
+ * @param options.destination - The empty destination, already
29
+ * `Archive.create`d by the caller.
30
+ * @param options.name - The output archive's `name` config field.
31
+ * @param options.callbacks - Progress callbacks; see `types.ts`.
32
+ * @returns The derived config and the transfer outcome.
33
+ * @throws {Error} If the source is a `fromList` archive, or `scopeUrls` is empty.
34
+ * @example
35
+ * ```ts
36
+ * const destination = await Archive.create({ filePath: outputPath, cwd });
37
+ * const accessor = await Archive.openCached(archivePath);
38
+ * const result = await splitArchive({
39
+ * source: { path: archivePath, accessor },
40
+ * scopeUrls: ['https://example.com/blog/'],
41
+ * destination,
42
+ * name: 'blog',
43
+ * });
44
+ * ```
45
+ */
46
+ export declare function splitArchive(options: {
47
+ readonly source: {
48
+ readonly accessor: ArchiveAccessor;
49
+ readonly path: string;
50
+ };
51
+ readonly scopeUrls: readonly string[];
52
+ readonly destination: Archive;
53
+ readonly name: string;
54
+ readonly callbacks?: TransferCallbacks;
55
+ }): Promise<SplitArchiveResult>;
@@ -0,0 +1,98 @@
1
+ import path from 'node:path';
2
+ import { buildScopeMap } from '../../crawler/build-scope-map.js';
3
+ import ArchiveDefault from '../archive.js';
4
+ import { buildSplitConfig } from './build-split-config.js';
5
+ import { copyInventorySourceLists } from './copy-inventory-source-lists.js';
6
+ import { countExternalPagesInScope } from './count-external-pages-in-scope.js';
7
+ import { flattenRedirectChains } from './flatten-redirect-chains.js';
8
+ import { reclassifyResourceExternality } from './reclassify-resource-externality.js';
9
+ import { transferArchiveRows } from './transfer-archive-rows.js';
10
+ /**
11
+ * Extracts the subset of one read-only-opened source archive within the
12
+ * given scope URLs into an already `Archive.create`d, empty destination —
13
+ * the crawler-side half of the `split` CLI command. Does not open/close/
14
+ * write anything itself; see `concat-archives.ts`'s docs for the same
15
+ * lifecycle-ownership split (the CLI's `commands/split.ts` owns open →
16
+ * transfer → rebuild-read-model → write).
17
+ *
18
+ * Rejects a `fromList` source up front — see `build-split-config.ts`'s
19
+ * docs for why "roots = the given scope" has no coherent meaning for an
20
+ * archive whose `roots` is a URL list rather than a scope.
21
+ *
22
+ * `flattenRedirectChains` still runs even though a single, not-yet-merged
23
+ * source is already flat by construction — a cheap no-op, kept for the
24
+ * same reason `reclassifyResourceExternality` is written mode-agnostic
25
+ * rather than split having its own near-duplicate of each.
26
+ * @param options - See individual properties.
27
+ * @param options.source - The source, read-only opened
28
+ * (`Archive.openCached`).
29
+ * @param options.source.path
30
+ * @param options.source.accessor
31
+ * @param options.scopeUrls - The scope URLs the operator gave (raw
32
+ * strings; normalised to `withoutHash` form by
33
+ * {@link import('./build-split-config.js').buildSplitConfig}).
34
+ * @param options.destination - The empty destination, already
35
+ * `Archive.create`d by the caller.
36
+ * @param options.name - The output archive's `name` config field.
37
+ * @param options.callbacks - Progress callbacks; see `types.ts`.
38
+ * @returns The derived config and the transfer outcome.
39
+ * @throws {Error} If the source is a `fromList` archive, or `scopeUrls` is empty.
40
+ * @example
41
+ * ```ts
42
+ * const destination = await Archive.create({ filePath: outputPath, cwd });
43
+ * const accessor = await Archive.openCached(archivePath);
44
+ * const result = await splitArchive({
45
+ * source: { path: archivePath, accessor },
46
+ * scopeUrls: ['https://example.com/blog/'],
47
+ * destination,
48
+ * name: 'blog',
49
+ * });
50
+ * ```
51
+ */
52
+ export async function splitArchive(options) {
53
+ const { source, scopeUrls, destination, name, callbacks } = options;
54
+ const sourceConfig = await source.accessor.getConfig();
55
+ if (sourceConfig.fromList) {
56
+ throw new Error('split: cannot split a --list/--list-file archive — its roots are a URL list, ' +
57
+ 'not a scope, so "roots = the given scope" has no coherent meaning for it.');
58
+ }
59
+ const config = buildSplitConfig(sourceConfig, scopeUrls, name);
60
+ await destination.setConfig(config);
61
+ const knex = destination.getKnex();
62
+ const scope = buildScopeMap(config.roots, config);
63
+ callbacks?.onSourceStart?.(0, source.path);
64
+ const sourceDbPath = path.join(source.accessor.tmpDir, ArchiveDefault.SQLITE_DB_FILE_NAME);
65
+ const result = await transferArchiveRows({
66
+ knex,
67
+ sourceDbPath,
68
+ mode: { kind: 'split', scopeMap: scope, parseOptions: config },
69
+ crawlOrderOffset: 0,
70
+ sourceIndex: 0,
71
+ callbacks,
72
+ });
73
+ if (result.inserted === 0) {
74
+ throw new Error('split: no page inside the given scope was found in the source archive — nothing to extract.');
75
+ }
76
+ callbacks?.onPhase?.(1, 'flatteningRedirects');
77
+ await flattenRedirectChains(knex);
78
+ callbacks?.onPhase?.(1, 'reclassifyingResources');
79
+ await reclassifyResourceExternality(knex, scope, config);
80
+ callbacks?.onPhase?.(1, 'countingExternalInScope');
81
+ // Not always 0: the operator's scope URLs are not required to be a
82
+ // SUBSET of the source's original roots. A split scope broader than (or
83
+ // merely different from) the original roots can bring a page that was
84
+ // only ever recorded as an external link (never crawled under the
85
+ // source's narrower original scope) inside the new scope — the same
86
+ // "still external, never fabricate a scrape" rule concat's own
87
+ // `externalInScopeCount` documents.
88
+ const externalInScopeCount = await countExternalPagesInScope(knex, scope, config);
89
+ const inventoryListsCopied = await copyInventorySourceLists(destination, [
90
+ source.accessor.tmpDir,
91
+ ]);
92
+ return {
93
+ config,
94
+ source: result,
95
+ externalInScopeCount,
96
+ inventoryListsCopied,
97
+ };
98
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The action a `content_items` transfer plan (`temp.xfer_ci_plan`) assigns
3
+ * to each source row, stored as a small integer so the plan table can be
4
+ * queried/joined without a TEXT comparison.
5
+ *
6
+ * - `full` — insert the source row (and its page-scoped data) as a
7
+ * brand-new destination row. Used by both concat (no existing dest row
8
+ * for this URL yet) and split (in-scope, kept in full).
9
+ * - `stub` — insert only the `content_items` row itself, forced to
10
+ * `is_external = 1` / `is_target = 0`; no `page_meta` or any other
11
+ * page-scoped row is copied. Split-only — an out-of-scope page that a
12
+ * kept page still references (an anchor target or a redirect
13
+ * destination).
14
+ * - `replace` — an existing destination row for this URL is overwritten
15
+ * because this source's observation outranks it (see
16
+ * `content-item-rank-sql.ts`). Concat-only.
17
+ * - `skip` — the source row is not copied at all; the destination already
18
+ * holds an equal-or-better observation for this URL. Concat-only.
19
+ *
20
+ * `full` and `stub` are the only actions {@link
21
+ * import('./plan-content-items-for-split.js').planContentItemsForSplit}
22
+ * ever assigns; `full`, `replace`, and `skip` are the only actions {@link
23
+ * import('./plan-content-items-for-concat.js').planContentItemsForConcat}
24
+ * ever assigns — a row not present in the plan at all means "dropped"
25
+ * (split-only: out of scope and unreferenced by anything kept).
26
+ */
27
+ export declare const TRANSFER_ACTION: {
28
+ readonly full: 1;
29
+ readonly stub: 2;
30
+ readonly replace: 3;
31
+ readonly skip: 4;
32
+ };
33
+ /** Union of {@link TRANSFER_ACTION}'s values. */
34
+ export type TransferAction = (typeof TRANSFER_ACTION)[keyof typeof TRANSFER_ACTION];
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The action a `content_items` transfer plan (`temp.xfer_ci_plan`) assigns
3
+ * to each source row, stored as a small integer so the plan table can be
4
+ * queried/joined without a TEXT comparison.
5
+ *
6
+ * - `full` — insert the source row (and its page-scoped data) as a
7
+ * brand-new destination row. Used by both concat (no existing dest row
8
+ * for this URL yet) and split (in-scope, kept in full).
9
+ * - `stub` — insert only the `content_items` row itself, forced to
10
+ * `is_external = 1` / `is_target = 0`; no `page_meta` or any other
11
+ * page-scoped row is copied. Split-only — an out-of-scope page that a
12
+ * kept page still references (an anchor target or a redirect
13
+ * destination).
14
+ * - `replace` — an existing destination row for this URL is overwritten
15
+ * because this source's observation outranks it (see
16
+ * `content-item-rank-sql.ts`). Concat-only.
17
+ * - `skip` — the source row is not copied at all; the destination already
18
+ * holds an equal-or-better observation for this URL. Concat-only.
19
+ *
20
+ * `full` and `stub` are the only actions {@link
21
+ * import('./plan-content-items-for-split.js').planContentItemsForSplit}
22
+ * ever assigns; `full`, `replace`, and `skip` are the only actions {@link
23
+ * import('./plan-content-items-for-concat.js').planContentItemsForConcat}
24
+ * ever assigns — a row not present in the plan at all means "dropped"
25
+ * (split-only: out of scope and unreferenced by anything kept).
26
+ */
27
+ export const TRANSFER_ACTION = {
28
+ full: 1,
29
+ stub: 2,
30
+ replace: 3,
31
+ skip: 4,
32
+ };