@d-zero/page-cluster 0.3.1 → 0.4.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.
@@ -1,11 +1,11 @@
1
1
  import { assignContainedClusters } from './assign-contained-clusters.js';
2
- import { autoCutThreshold } from './auto-cut-threshold.js';
3
2
  import { collapseAnonymousDivs } from './collapse-anonymous-divs.js';
4
3
  import { completeLinkageDendrogram, labelsAtThreshold, } from './complete-linkage-dendrogram.js';
5
4
  import { computeDocumentFrequency } from './compute-document-frequency.js';
6
5
  import { jaccardSimilarity } from './jaccard-similarity.js';
7
6
  import { reservoirSample } from './reservoir-sample.js';
8
7
  import { shapeToken } from './shape-token.js';
8
+ import { shellQuorum } from './shell-quorum.js';
9
9
  import { splitTokensByFrequency } from './split-tokens-by-frequency.js';
10
10
  /**
11
11
  * Fixed complete-linkage threshold for the cross-block fine stage.
@@ -26,11 +26,10 @@ const CROSS_BLOCK_THRESHOLD = 0.8;
26
26
  * on real crawl data. Full union is shell-dominated: 298 pages collapsed into
27
27
  * 4 clusters — also confirmed. 80% quorum avoids both failure modes.
28
28
  *
29
- * Also reused as the fallback clamp for {@link ./auto-cut-threshold.js |
30
- * autoCutThreshold} when running on the per-landmark-instance frequency
31
- * distribution in {@link ./merge-cross-block-clusters.js | shellQuorum}. The
32
- * clamp only ever *loosens* the cut relative to this floor (never tightens),
33
- * and only fires in the degenerate cases the JSDoc there describes.
29
+ * Not shared with {@link ./shell-quorum.js | shellQuorum}'s own fallback
30
+ * clamp (`SHELL_QUORUM_FALLBACK_FRACTION`) the two happen to be the same
31
+ * value today because both were validated against the same real crawl
32
+ * corpora, but they are independently tunable.
34
33
  */
35
34
  const QUORUM_FRACTION = 0.8;
36
35
  /**
@@ -159,97 +158,6 @@ function l2Contained(xSig, ySig) {
159
158
  }
160
159
  return true;
161
160
  }
162
- /**
163
- * Discovers a unit's shell tokens by auto-cutting the per-*token* page-
164
- * frequency histogram of every landmark instance's tokens. This is the same
165
- * max-gap primitive used for Stage A merge-height cutoffs, applied
166
- * recursively at the landmark-token layer.
167
- *
168
- * ## Why per-token and not per-signature
169
- *
170
- * An earlier iteration ran the histogram at the level of full landmark-
171
- * instance signatures (canonicalized token sets). That failed on a real,
172
- * common pattern: a shared site chrome whose markup carries a per-page
173
- * distinguishing element (a breadcrumb, a page-title element with a page-
174
- * specific class, a "current" state). All pages have most of the same
175
- * tokens, but every page's full signature is distinct because tokens embed
176
- * class names. Per-signature counting saw 5 signatures at freq 0.2 each,
177
- * autoCutThreshold on the flat distribution returned the clamp, and the
178
- * shell collapsed to empty even though every page shared the core header
179
- * skeleton. Per-token counting handles the same case correctly — the shared
180
- * skeleton tokens each hit freq 1.0.
181
- *
182
- * ## The histogram
183
- *
184
- * For every member page, all its landmark instances are tokenized and
185
- * unioned into a single per-page token set (order-agnostic, deduped: a
186
- * token appearing in two of the page's landmarks still counts once for
187
- * that page). The corpus histogram is then "how many pages contain each
188
- * token". Tokens that appear on nearly every page are the unit's chrome;
189
- * tokens that appear on only a handful are page-specific content that
190
- * happens to be tagged as a landmark.
191
- *
192
- * ## Why auto-cut instead of a hard-coded quorum
193
- *
194
- * A fixed 80% quorum (this file's earlier implementation) baked one
195
- * threshold in for every unit. Real corpora don't obey a universal cutoff:
196
- * a section-local landmark token that appears on 60% of a unit's pages is
197
- * the section's chrome under any reasonable reading, but 80% quorum
198
- * discards it. Auto-cut looks at the *shape* of the frequency distribution
199
- * and picks the widest gap between adjacent frequencies — if the
200
- * distribution is `{1.00, 1.00, 0.65, 0.03, 0.02}`, the gap between 0.65
201
- * and 0.03 (0.62) dwarfs everything else and the cut lands mid-gap around
202
- * 0.34, correctly grouping the 0.65 tokens with the site-wide 1.00 ones as
203
- * "chrome for this unit". If instead the distribution is flat, the clamp
204
- * to {@link QUORUM_FRACTION} keeps the threshold from being tighter than
205
- * the fallback default.
206
- *
207
- * ## Fallbacks
208
- *
209
- * A single distinct token (`heights.length < 2`) or a perfectly flat
210
- * distribution (`maxGap === 0`) returns the {@link QUORUM_FRACTION} clamp
211
- * verbatim — exactly the same 80%-quorum behavior as before. So degenerate
212
- * cases degrade to the old contract; only richer distributions get the
213
- * auto-cut benefit.
214
- *
215
- * A page with no landmarks contributes an empty set, deliberately, so the
216
- * shell-corroboration jaccard between two landmark-less pages is 0 rather
217
- * than 1 (which it would be if we handed back a `<body></body>`-derived
218
- * `{body}` fallback set to both sides).
219
- * @param perPageInstances
220
- */
221
- function shellQuorum(perPageInstances) {
222
- const pageCount = perPageInstances.length;
223
- if (pageCount === 0)
224
- return new Set();
225
- // Union all instance token sets per page (dedupe within page: a token
226
- // present on both header and footer of the same page still counts once
227
- // for that page's contribution).
228
- const tokenPageCount = new Map();
229
- for (const instances of perPageInstances) {
230
- const perPageUnion = new Set();
231
- for (const inst of instances) {
232
- for (const token of inst.tokens)
233
- perPageUnion.add(token);
234
- }
235
- for (const token of perPageUnion) {
236
- tokenPageCount.set(token, (tokenPageCount.get(token) ?? 0) + 1);
237
- }
238
- }
239
- if (tokenPageCount.size === 0)
240
- return new Set();
241
- const frequencies = [];
242
- for (const count of tokenPageCount.values()) {
243
- frequencies.push(count / pageCount);
244
- }
245
- const cut = autoCutThreshold(frequencies, QUORUM_FRACTION);
246
- const shell = new Set();
247
- for (const [token, count] of tokenPageCount) {
248
- if (count / pageCount >= cut)
249
- shell.add(token);
250
- }
251
- return shell;
252
- }
253
161
  // ---------------------------------------------------------------------------
254
162
  // Main function
255
163
  // ---------------------------------------------------------------------------
@@ -0,0 +1,38 @@
1
+ /**
2
+ * A 1-based line/column position within an HTML string.
3
+ */
4
+ export type LineColumn = {
5
+ readonly line: number;
6
+ readonly column: number;
7
+ };
8
+ /**
9
+ * Precomputed lookup structure for {@link ./offset-to-line-column.js | offsetToLineColumn}:
10
+ * every newline's string-index offset, ascending.
11
+ */
12
+ export type LineColumnIndex = {
13
+ readonly newlineOffsets: readonly number[];
14
+ };
15
+ /**
16
+ * Scans `html` once and records every `\n` offset, so repeated
17
+ * {@link ./offset-to-line-column.js | offsetToLineColumn} calls against the
18
+ * same HTML string can binary-search instead of re-scanning from the start
19
+ * each time. Built once per page and reused across every landmark instance's
20
+ * start/end offset — a page with dozens of landmark instances would
21
+ * otherwise pay for a fresh O(n) scan per offset instead of one O(n) scan
22
+ * total.
23
+ * @param html
24
+ */
25
+ export declare function buildLineColumnIndex(html: string): LineColumnIndex;
26
+ /**
27
+ * Converts a string-index `offset` (the same unit as `htmlparser2`'s
28
+ * `startIndex`/`endIndex`, i.e. UTF-16 code units) into a 1-based
29
+ * `{line, column}` position, using an index built by
30
+ * {@link ./offset-to-line-column.js | buildLineColumnIndex}.
31
+ *
32
+ * `\r\n` line endings are handled without special-casing: the `\r` is
33
+ * counted as the last column of its own line, matching how most editors
34
+ * report position for CRLF files.
35
+ * @param index
36
+ * @param offset
37
+ */
38
+ export declare function offsetToLineColumn(index: LineColumnIndex, offset: number): LineColumn;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Scans `html` once and records every `\n` offset, so repeated
3
+ * {@link ./offset-to-line-column.js | offsetToLineColumn} calls against the
4
+ * same HTML string can binary-search instead of re-scanning from the start
5
+ * each time. Built once per page and reused across every landmark instance's
6
+ * start/end offset — a page with dozens of landmark instances would
7
+ * otherwise pay for a fresh O(n) scan per offset instead of one O(n) scan
8
+ * total.
9
+ * @param html
10
+ */
11
+ export function buildLineColumnIndex(html) {
12
+ const newlineOffsets = [];
13
+ for (let i = 0; i < html.length; i++) {
14
+ if (html.codePointAt(i) === 10)
15
+ newlineOffsets.push(i);
16
+ }
17
+ return { newlineOffsets };
18
+ }
19
+ /**
20
+ * Converts a string-index `offset` (the same unit as `htmlparser2`'s
21
+ * `startIndex`/`endIndex`, i.e. UTF-16 code units) into a 1-based
22
+ * `{line, column}` position, using an index built by
23
+ * {@link ./offset-to-line-column.js | buildLineColumnIndex}.
24
+ *
25
+ * `\r\n` line endings are handled without special-casing: the `\r` is
26
+ * counted as the last column of its own line, matching how most editors
27
+ * report position for CRLF files.
28
+ * @param index
29
+ * @param offset
30
+ */
31
+ export function offsetToLineColumn(index, offset) {
32
+ const { newlineOffsets } = index;
33
+ let low = 0;
34
+ let high = newlineOffsets.length;
35
+ while (low < high) {
36
+ const mid = (low + high) >>> 1;
37
+ if (newlineOffsets[mid] < offset) {
38
+ low = mid + 1;
39
+ }
40
+ else {
41
+ high = mid;
42
+ }
43
+ }
44
+ // `low` is the count of newlines strictly before `offset`, i.e. the
45
+ // number of completed lines — so `low` newlines completed means we're on
46
+ // line `low + 1`.
47
+ const lineStart = low === 0 ? 0 : newlineOffsets[low - 1] + 1;
48
+ return { line: low + 1, column: offset - lineStart + 1 };
49
+ }
@@ -1,4 +1,4 @@
1
- import type { ExtractLandmarksResult, LandmarkType } from './extract-landmarks.js';
1
+ import type { ExtractLandmarksResult, LandmarkPosition, LandmarkType } from './extract-landmarks.js';
2
2
  import type { TokenizeOptions } from './types.js';
3
3
  /**
4
4
  * Every landmark type extractLandmarks may populate, iterated in a fixed
@@ -13,11 +13,20 @@ export declare const ALL_LANDMARK_TYPES: readonly LandmarkType[];
13
13
  * {@link ./canonicalize-token-set.js | canonicalizeTokenSet}). Signatures
14
14
  * are reused across consumers so two callers see the same "same instance"
15
15
  * verdict without independently re-canonicalizing.
16
+ *
17
+ * `position` is the instance's location in the page it came from, computed
18
+ * once by {@link ./extract-landmarks.js | extractLandmarks} and carried here
19
+ * unchanged — a back-reference for callers (e.g.
20
+ * {@link ./build-page-landmark-report.js | buildPageLandmarkReport}) that
21
+ * need to report where a chrome-classified instance actually sits, not just
22
+ * that it exists. It plays no part in `tokens`/`signature` computation or in
23
+ * the corpus-frequency logic that consumes this type.
16
24
  */
17
25
  export type PerPageLandmarkInstance = {
18
26
  readonly type: LandmarkType;
19
27
  readonly tokens: ReadonlySet<string>;
20
28
  readonly signature: string;
29
+ readonly position: LandmarkPosition;
21
30
  };
22
31
  /**
23
32
  * Tokenizes every landmark instance across every page once, keyed by page
@@ -44,17 +44,29 @@ export function computePerPageLandmarkInstances(landmarks, tokenizeOptions) {
44
44
  const seenSignatures = new Set();
45
45
  const out = [];
46
46
  for (const type of ALL_LANDMARK_TYPES) {
47
- for (const instanceHtml of entry[type]) {
48
- if (!instanceHtml)
47
+ for (const instance of entry[type]) {
48
+ if (!instance.html)
49
49
  continue;
50
- const tokens = new Set(tokenize(`<body>${instanceHtml}</body>`, tokenizeOptions).tokens);
50
+ const tokens = new Set(tokenize(`<body>${instance.html}</body>`, tokenizeOptions).tokens);
51
51
  if (tokens.size === 0)
52
52
  continue;
53
53
  const signature = canonicalizeTokenSet(tokens);
54
54
  if (seenSignatures.has(signature))
55
55
  continue;
56
56
  seenSignatures.add(signature);
57
- out.push({ type, tokens, signature });
57
+ out.push({
58
+ type,
59
+ tokens,
60
+ signature,
61
+ position: {
62
+ startOffset: instance.startOffset,
63
+ endOffset: instance.endOffset,
64
+ startLine: instance.startLine,
65
+ startColumn: instance.startColumn,
66
+ endLine: instance.endLine,
67
+ endColumn: instance.endColumn,
68
+ },
69
+ });
58
70
  }
59
71
  }
60
72
  return out;
@@ -1,7 +1,9 @@
1
1
  import type { ExtractLandmarksResult } from './extract-landmarks.js';
2
+ import type { PerPageLandmarkInstance } from './per-page-landmark-signatures.js';
2
3
  import type { ResolveBlockingGroupKeysOptions } from './resolve-blocking-group-keys.js';
3
4
  import type { ResolveStructuralClusterKeysOptions } from './resolve-structural-cluster-keys.js';
4
5
  import type { TokenizeOptions } from './types.js';
6
+ import { type PageLandmarkReport } from './build-page-landmark-report.js';
5
7
  /**
6
8
  * Reinjects each page's *local* (non-corpus-wide) landmark-instance tokens
7
9
  * into its block token set for Stage A clustering, restoring exactly the
@@ -65,6 +67,7 @@ import type { TokenizeOptions } from './types.js';
65
67
  export declare function computeLocalChromeArtifacts(landmarks: readonly ExtractLandmarksResult[], tokenizeOptions: TokenizeOptions | undefined): {
66
68
  readonly localSignatures: ReadonlySet<string>;
67
69
  readonly localTokensByPage: readonly ReadonlySet<string>[];
70
+ readonly perPageInstances: readonly (readonly PerPageLandmarkInstance[])[];
68
71
  };
69
72
  /**
70
73
  * Reinjects each page's *local* (non-corpus-wide) landmark-instance tokens
@@ -162,9 +165,47 @@ export type ResolvePageClusterKeysOptions = TokenizeOptions & ResolveBlockingGro
162
165
  * sync helper to running a per-block async loop that emits
163
166
  * `pass1-block-complete` and `stage-b-start`. Omitting `onProgress`
164
167
  * keeps the small-corpus branch on the pre-refactor sync path with
165
- * zero yield overhead.
168
+ * zero yield overhead. Ignored when `includeLandmarkPositions` is
169
+ * `true` — that option always routes the small-corpus branch through
170
+ * the sync helper (see `includeLandmarkPositions`'s own JSDoc), so no
171
+ * progress events fire in that combination.
166
172
  */
167
173
  onProgress?: (event: ProgressEvent) => void;
174
+ /**
175
+ * When `true`, every result entry additionally carries a
176
+ * {@link PageLandmarkReport} — each landmark instance's position, plus
177
+ * a chrome/content verdict for the six excisable types (see
178
+ * {@link ./build-page-landmark-report.js | buildPageLandmarkReport}).
179
+ * Changes the return shape from `string[]` to
180
+ * `{@link PageClusterKeyResult}[]` (see the overloads on
181
+ * `resolvePageClusterKeysInMemory`/`resolvePageClusterKeys`/
182
+ * `resolvePageClusterKeysFromArray`). Defaults to `false`, in which
183
+ * case every existing caller's behavior and return type are
184
+ * unchanged.
185
+ *
186
+ * Not supported on the streaming path
187
+ * (`pageCount > {@link CORPUS_INLINE_THRESHOLD}`): reservoir sampling
188
+ * and Jaccard-based non-sample assignment there have no notion of
189
+ * "this page's shell tokens" to classify chrome against, and
190
+ * retrofitting one is out of scope. `resolvePageClusterKeys` throws a
191
+ * `RangeError` up front if both apply to the same call, rather than
192
+ * silently degrading semantics.
193
+ *
194
+ * On the async factory-based `resolvePageClusterKeys`, this option
195
+ * forces the small-corpus branch through the sync
196
+ * `resolvePageClusterKeysInMemory` helper regardless of `onProgress`
197
+ * — see `onProgress`'s own JSDoc.
198
+ */
199
+ includeLandmarkPositions?: boolean;
200
+ };
201
+ /**
202
+ * One page's clustering result when `includeLandmarkPositions` is `true`:
203
+ * the same `clusterKey` every caller already gets, plus that page's
204
+ * {@link PageLandmarkReport}.
205
+ */
206
+ export type PageClusterKeyResult = {
207
+ readonly clusterKey: string;
208
+ readonly landmarks: PageLandmarkReport;
168
209
  };
169
210
  /**
170
211
  * Corpus size at or below which the async factory-based
@@ -188,6 +229,17 @@ export type ResolvePageClusterKeysOptions = TokenizeOptions & ResolveBlockingGro
188
229
  * anything above 20,000 is routed to streaming.
189
230
  */
190
231
  export declare const CORPUS_INLINE_THRESHOLD = 20000;
232
+ /**
233
+ * Throws when `includeLandmarkPositions` is combined with a corpus over
234
+ * `threshold` pages (the streaming path — see `includeLandmarkPositions`'s
235
+ * own JSDoc for why it has no sample-based equivalent there). Split out from
236
+ * its call site so tests can exercise the boundary with a small injected
237
+ * `threshold` instead of constructing a 20,001-page fixture to cross the
238
+ * real {@link CORPUS_INLINE_THRESHOLD}.
239
+ * @param pageCount
240
+ * @param threshold
241
+ */
242
+ export declare function assertLandmarkPositionsSupportedForPageCount(pageCount: number, threshold: number): void;
191
243
  /**
192
244
  * Reservoir-sample size per block on the streaming path. Blocks larger than
193
245
  * this have Stage A run on a random sample of `BLOCK_SAMPLE_SIZE` pages,
@@ -240,6 +292,9 @@ export declare const BLOCK_SAMPLE_SIZE = 100;
240
292
  * @param pages
241
293
  * @param options
242
294
  */
295
+ export declare function resolvePageClusterKeysInMemory(pages: readonly PageClusterSignals[], options: ResolvePageClusterKeysOptions & {
296
+ includeLandmarkPositions: true;
297
+ }): PageClusterKeyResult[];
243
298
  export declare function resolvePageClusterKeysInMemory(pages: readonly PageClusterSignals[], options?: ResolvePageClusterKeysOptions): string[];
244
299
  /**
245
300
  * Factory function returning an iterator over pages. Called once per streaming
@@ -303,6 +358,9 @@ export type PageFactory = () => Iterable<PageClusterSignals> | AsyncIterable<Pag
303
358
  * });
304
359
  * ```
305
360
  */
361
+ export declare function resolvePageClusterKeys(pages: PageFactory, options: ResolvePageClusterKeysOptions & {
362
+ includeLandmarkPositions: true;
363
+ }): Promise<PageClusterKeyResult[]>;
306
364
  export declare function resolvePageClusterKeys(pages: PageFactory, options?: ResolvePageClusterKeysOptions): Promise<string[]>;
307
365
  /**
308
366
  * Convenience wrapper that runs {@link ./resolve-page-cluster-keys.js | resolvePageClusterKeys}
@@ -320,4 +378,7 @@ export declare function resolvePageClusterKeys(pages: PageFactory, options?: Res
320
378
  * ]);
321
379
  * ```
322
380
  */
381
+ export declare function resolvePageClusterKeysFromArray(pages: readonly PageClusterSignals[], options: ResolvePageClusterKeysOptions & {
382
+ includeLandmarkPositions: true;
383
+ }): Promise<PageClusterKeyResult[]>;
323
384
  export declare function resolvePageClusterKeysFromArray(pages: readonly PageClusterSignals[], options?: ResolvePageClusterKeysOptions): Promise<string[]>;
@@ -1,4 +1,5 @@
1
1
  import { autoCutThreshold } from './auto-cut-threshold.js';
2
+ import { buildPageLandmarkReport, } from './build-page-landmark-report.js';
2
3
  import { capContentDepth } from './cap-content-depth.js';
3
4
  import { detectContentDepthCap, validateDetectContentDepthCapOptions, } from './detect-content-depth-cap.js';
4
5
  import { extractLandmarks } from './extract-landmarks.js';
@@ -8,6 +9,7 @@ import { mergeCrossBlockClusters } from './merge-cross-block-clusters.js';
8
9
  import { groupIndicesByBlockKey, resolveBlockKeys } from './pass0-blocking.js';
9
10
  import { computePerPageLandmarkInstances } from './per-page-landmark-signatures.js';
10
11
  import { removeContentBlocks } from './remove-content-blocks.js';
12
+ import { shellQuorum } from './shell-quorum.js';
11
13
  import { stageAPerBlock } from './stage-a-per-block.js';
12
14
  import { tokenize } from './tokenize.js';
13
15
  /**
@@ -162,8 +164,9 @@ function assignPageToNearestCluster(html, assignment, excludeLandmarks, contentB
162
164
  */
163
165
  export function computeLocalChromeArtifacts(landmarks, tokenizeOptions) {
164
166
  const pageCount = landmarks.length;
165
- if (pageCount === 0)
166
- return { localSignatures: new Set(), localTokensByPage: [] };
167
+ if (pageCount === 0) {
168
+ return { localSignatures: new Set(), localTokensByPage: [], perPageInstances: [] };
169
+ }
167
170
  const perPageInstances = computePerPageLandmarkInstances(landmarks, tokenizeOptions);
168
171
  // Corpus-wide histogram: signature → { count, tokens }. tokens is the
169
172
  // token set of any one occurrence of the signature (all occurrences are
@@ -184,6 +187,7 @@ export function computeLocalChromeArtifacts(landmarks, tokenizeOptions) {
184
187
  return {
185
188
  localSignatures: new Set(),
186
189
  localTokensByPage: landmarks.map(() => new Set()),
190
+ perPageInstances,
187
191
  };
188
192
  }
189
193
  const frequencies = [];
@@ -202,6 +206,7 @@ export function computeLocalChromeArtifacts(landmarks, tokenizeOptions) {
202
206
  return {
203
207
  localSignatures: new Set(),
204
208
  localTokensByPage: landmarks.map(() => new Set()),
209
+ perPageInstances,
205
210
  };
206
211
  }
207
212
  const localTokensByPage = perPageInstances.map((instances) => {
@@ -214,7 +219,7 @@ export function computeLocalChromeArtifacts(landmarks, tokenizeOptions) {
214
219
  }
215
220
  return out;
216
221
  });
217
- return { localSignatures, localTokensByPage };
222
+ return { localSignatures, localTokensByPage, perPageInstances };
218
223
  }
219
224
  /**
220
225
  * Reinjects each page's *local* (non-corpus-wide) landmark-instance tokens
@@ -232,6 +237,39 @@ export function computeLocalChromeArtifacts(landmarks, tokenizeOptions) {
232
237
  export function computeLocalLandmarkTokens(landmarks, tokenizeOptions) {
233
238
  return [...computeLocalChromeArtifacts(landmarks, tokenizeOptions).localTokensByPage];
234
239
  }
240
+ /**
241
+ * Builds every page's {@link PageLandmarkReport} for the `includeLandmarkPositions`
242
+ * result path. Groups pages by their *final* cluster key (post–Stage-B), runs
243
+ * {@link ./shell-quorum.js | shellQuorum} once per cluster over the pooled
244
+ * member `PerPageLandmarkInstance`s (the same "shell tokens" concept Stage B
245
+ * itself uses for L2 shell corroboration, just recomputed at the final-
246
+ * cluster granularity rather than the pre-merge unit granularity), then
247
+ * classifies each member page's own landmark instances against that
248
+ * cluster-level shell.
249
+ * @param finalKeys
250
+ * @param landmarks
251
+ * @param perPageInstances
252
+ */
253
+ function buildLandmarkReportsByCluster(finalKeys, landmarks, perPageInstances) {
254
+ const indicesByKey = new Map();
255
+ for (const [i, key] of finalKeys.entries()) {
256
+ const indices = indicesByKey.get(key);
257
+ if (indices) {
258
+ indices.push(i);
259
+ }
260
+ else {
261
+ indicesByKey.set(key, [i]);
262
+ }
263
+ }
264
+ const reports = Array.from({ length: finalKeys.length });
265
+ for (const indices of indicesByKey.values()) {
266
+ const shellTokens = shellQuorum(indices.map((i) => perPageInstances[i]));
267
+ for (const i of indices) {
268
+ reports[i] = buildPageLandmarkReport(landmarks[i], shellTokens);
269
+ }
270
+ }
271
+ return reports;
272
+ }
235
273
  /**
236
274
  * Corpus size at or below which the async factory-based
237
275
  * `resolvePageClusterKeys` reads the entire input into an array and delegates
@@ -254,6 +292,21 @@ export function computeLocalLandmarkTokens(landmarks, tokenizeOptions) {
254
292
  * anything above 20,000 is routed to streaming.
255
293
  */
256
294
  export const CORPUS_INLINE_THRESHOLD = 20_000;
295
+ /**
296
+ * Throws when `includeLandmarkPositions` is combined with a corpus over
297
+ * `threshold` pages (the streaming path — see `includeLandmarkPositions`'s
298
+ * own JSDoc for why it has no sample-based equivalent there). Split out from
299
+ * its call site so tests can exercise the boundary with a small injected
300
+ * `threshold` instead of constructing a 20,001-page fixture to cross the
301
+ * real {@link CORPUS_INLINE_THRESHOLD}.
302
+ * @param pageCount
303
+ * @param threshold
304
+ */
305
+ export function assertLandmarkPositionsSupportedForPageCount(pageCount, threshold) {
306
+ if (pageCount > threshold) {
307
+ throw new RangeError(`resolvePageClusterKeys: includeLandmarkPositions is not supported for corpora larger than ${threshold} pages (the streaming path) — this corpus has ${pageCount}`);
308
+ }
309
+ }
257
310
  /**
258
311
  * Reservoir-sample size per block on the streaming path. Blocks larger than
259
312
  * this have Stage A run on a random sample of `BLOCK_SAMPLE_SIZE` pages,
@@ -289,23 +342,6 @@ export const CORPUS_INLINE_THRESHOLD = 20_000;
289
342
  * {@link CORPUS_INLINE_THRESHOLD} — sampling is streaming-mode only.
290
343
  */
291
344
  export const BLOCK_SAMPLE_SIZE = 100;
292
- /**
293
- * Preserves the previous synchronous, array-in / array-out API of
294
- * `resolvePageClusterKeys` under a new name so the factory-based async
295
- * export can take the primary name while callers that already had a
296
- * materialized page array (spec tests, the in-repo dogfood harness,
297
- * downstream code that hasn't switched to streaming yet) retain the
298
- * exact same behavior.
299
- *
300
- * Semantics: identical to the pre-refactor `resolvePageClusterKeys`.
301
- * Corpus-wide chrome discovery, Stage B across every page, no memory
302
- * bound — meant to be called on inputs already known to fit in memory.
303
- * The async factory-based export delegates here whenever
304
- * `pages.length ≤ CORPUS_INLINE_THRESHOLD`, guaranteeing existing corpora
305
- * hit exactly this code path.
306
- * @param pages
307
- * @param options
308
- */
309
345
  export function resolvePageClusterKeysInMemory(pages, options) {
310
346
  const excludeLandmarks = options?.excludeLandmarks ?? true;
311
347
  const similarityThreshold = options?.similarityThreshold ?? 0.8;
@@ -316,8 +352,11 @@ export function resolvePageClusterKeysInMemory(pages, options) {
316
352
  // corroboration regardless of `excludeLandmarks`, and `remainderHtml` is
317
353
  // needed whenever `excludeLandmarks` is true.
318
354
  const landmarks = pages.map((page) => extractLandmarks(page.html));
319
- // Corpus-level chrome discovery
320
- const localLandmarkTokensByPage = computeLocalLandmarkTokens(landmarks, options);
355
+ // Corpus-level chrome discovery. `perPageInstances` is only consumed
356
+ // below when `includeLandmarkPositions` is set — computed unconditionally
357
+ // anyway since `computeLocalChromeArtifacts` already builds it internally
358
+ // for chrome discovery, so exposing it here costs nothing extra.
359
+ const { localTokensByPage: localLandmarkTokensByPage, perPageInstances } = computeLocalChromeArtifacts(landmarks, options);
321
360
  const contentBlockAttribute = options?.contentBlockAttribute;
322
361
  const preparedHtml = pages.map((page, index) => {
323
362
  const landmarksExcised = excludeLandmarks
@@ -363,7 +402,10 @@ export function resolvePageClusterKeysInMemory(pages, options) {
363
402
  finalKeys[i] = rootKey;
364
403
  }
365
404
  }
366
- return finalKeys;
405
+ if (!options?.includeLandmarkPositions)
406
+ return finalKeys;
407
+ const reports = buildLandmarkReportsByCluster(finalKeys, landmarks, perPageInstances);
408
+ return finalKeys.map((clusterKey, i) => ({ clusterKey, landmarks: reports[i] }));
367
409
  }
368
410
  /**
369
411
  * Async twin of {@link ./resolve-page-cluster-keys.js | resolvePageClusterKeysInMemory}
@@ -453,48 +495,6 @@ async function resolveSmallCorpusWithProgress(pages, onProgress, options) {
453
495
  }
454
496
  return finalKeys;
455
497
  }
456
- /**
457
- * Streaming, memory-bounded version of `resolvePageClusterKeysInMemory`.
458
- *
459
- * ## Behavior gate
460
- *
461
- * - `pageCount ≤ CORPUS_INLINE_THRESHOLD` — reads the whole factory into an
462
- * array, delegates to `resolvePageClusterKeysInMemory`. Same corpus-wide
463
- * chrome discovery, same Stage B across every page. All previously
464
- * validated corpora (302 / 1,416 / 8,936 / 89 pages) hit this path.
465
- * - `pageCount > CORPUS_INLINE_THRESHOLD` — streaming path: reads the
466
- * factory twice (once for blocking signals, once for HTML processing),
467
- * dispatches HTML per block, runs Stage A per block, accumulates
468
- * cross-block units, then runs Stage B across all accumulated units. Peak
469
- * memory ≈ largest single block, not the whole corpus.
470
- *
471
- * ## Semantic differences in streaming mode
472
- *
473
- * - **Chrome discovery is per-block, not corpus-wide.** In the in-memory
474
- * path, {@link ./resolve-page-cluster-keys.js | computeLocalLandmarkTokens}
475
- * runs on all pages at once. In streaming mode the entire corpus cannot
476
- * be held at once, so chrome discovery runs per block. A landmark
477
- * signature that is rare corpus-wide but common within one block will
478
- * be treated as global chrome in streaming mode, whereas the in-memory
479
- * mode would treat it as local. This trade-off is why the threshold
480
- * above is set generously — every real corpus historically validated
481
- * here stays on the in-memory path.
482
- * @param pages
483
- * @param options
484
- * @example
485
- * ```ts
486
- * // JSONL file source — factory can be re-invoked to re-open the file.
487
- * import { createReadStream } from 'node:fs';
488
- * import readline from 'node:readline';
489
- *
490
- * const keys = await resolvePageClusterKeys(() => {
491
- * const lines = readline.createInterface({ input: createReadStream('pages.jsonl') });
492
- * return (async function* () {
493
- * for await (const line of lines) yield JSON.parse(line);
494
- * })();
495
- * });
496
- * ```
497
- */
498
498
  export async function resolvePageClusterKeys(pages, options) {
499
499
  const onProgress = options?.onProgress;
500
500
  // Pass 0: HTML-free — collect blocking signals (paths, stylesheetHrefs,
@@ -530,13 +530,22 @@ export async function resolvePageClusterKeys(pages, options) {
530
530
  // into per-block progress, so delegate to the untouched sync path —
531
531
  // keeping behavior byte-for-byte identical (and yield-overhead-free)
532
532
  // to how library-only consumers experienced this before the CLI
533
- // progress work landed.
534
- if (onProgress === undefined) {
533
+ // progress work landed. `includeLandmarkPositions` always routes here
534
+ // too (see its own JSDoc): `resolveSmallCorpusWithProgress` has no
535
+ // landmark-report support, and duplicating that logic into the
536
+ // progress-emitting path for a reporting feature that has nothing to
537
+ // do with progress observability isn't worth the added surface.
538
+ if (onProgress === undefined || options?.includeLandmarkPositions) {
535
539
  return resolvePageClusterKeysInMemory(fullPages, options);
536
540
  }
537
541
  return resolveSmallCorpusWithProgress(fullPages, onProgress, options);
538
542
  }
539
- // Large corpus: streaming path.
543
+ // Large corpus: streaming path. includeLandmarkPositions has no sample-
544
+ // based equivalent (see its own JSDoc) — fail fast rather than silently
545
+ // ignoring the option or returning a semantically-wrong report.
546
+ if (options?.includeLandmarkPositions) {
547
+ assertLandmarkPositionsSupportedForPageCount(blockingSignals.length, CORPUS_INLINE_THRESHOLD);
548
+ }
540
549
  const excludeLandmarks = options?.excludeLandmarks ?? true;
541
550
  const similarityThreshold = options?.similarityThreshold ?? 0.8;
542
551
  if (!(similarityThreshold >= 0 && similarityThreshold <= 1)) {
@@ -728,22 +737,6 @@ export async function resolvePageClusterKeys(pages, options) {
728
737
  }
729
738
  return finalKeys;
730
739
  }
731
- /**
732
- * Convenience wrapper that runs {@link ./resolve-page-cluster-keys.js | resolvePageClusterKeys}
733
- * on a materialized array. Preserves the pre-refactor sync API for callers
734
- * that already have all pages in memory, while flowing through the same
735
- * async driver so behavior stays consistent across the two entry points.
736
- * @param pages
737
- * @param options
738
- * @example
739
- * ```ts
740
- * const keys = await resolvePageClusterKeysFromArray([
741
- * { paths: ['news', '1'], stylesheetHrefs: [], html: '<body><article>one</article></body>' },
742
- * { paths: ['news', '2'], stylesheetHrefs: [], html: '<body><article>two</article></body>' },
743
- * { paths: ['about'], stylesheetHrefs: [], html: '<body><section>about</section></body>' },
744
- * ]);
745
- * ```
746
- */
747
740
  export function resolvePageClusterKeysFromArray(pages, options) {
748
741
  return resolvePageClusterKeys(() => pages, options);
749
742
  }