/** * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ /** * @module bxc/crawler/url-param-learner * * Learns which query parameters do not change a page's content, per host. * * Every fetched page reports `(url, simhash)`. For each parameter present in * the URL, the learner looks at pages of the same host whose URL differs only * by that parameter: identical (near-identical) SimHashes are evidence the * parameter is irrelevant, different ones are evidence it matters. A parameter * becomes strippable after `minSamples` agreeing observations and no * contradiction, and {@link ParamLearner.normalize} then removes it before * URLs are enqueued — so `?sessionid=…`, `?ref=…` or `?sort=default` variants * stop multiplying the frontier. */ export interface ParamLearnerOptions { /** Agreeing observations required before a parameter is stripped. Default: 3. */ minSamples?: number; /** SimHash bit distance still considered "same content". Default: 3. */ maxBits?: number; /** Remembered page signatures per host (LRU). Default: 5000. */ maxPagesPerHost?: number; } interface ParamStats { same: number; different: number; } function hamming(a: string, b: string): number { let x = BigInt(`0x${a}`) ^ BigInt(`0x${b}`); let bits = 0; while (x) { x &= x - 1n; bits++; } return bits; } /** URL without `param`, with remaining parameters sorted (comparison key). */ function keyWithout(url: URL, param: string | null): string { const params = [...url.searchParams.entries()].filter(([name]) => name !== param); params.sort(([a, av], [b, bv]) => (a === b ? av.localeCompare(bv) : a.localeCompare(b))); const query = params.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&"); return `${url.host}${url.pathname}${query ? `?${query}` : ""}`; } export class ParamLearner { readonly #minSamples: number; readonly #maxBits: number; readonly #maxPagesPerHost: number; /** host → (url key → simhash) */ readonly #pages = new Map>(); /** host → param → stats */ readonly #stats = new Map>(); constructor(options: ParamLearnerOptions = {}) { this.#minSamples = options.minSamples ?? 3; this.#maxBits = options.maxBits ?? 3; this.#maxPagesPerHost = options.maxPagesPerHost ?? 5000; } /** Record the content signature of a fetched URL. */ observe(rawUrl: string, simhash: string | null | undefined): void { if (!simhash || !/^[0-9a-f]{16}$/i.test(simhash)) return; let url: URL; try { url = new URL(rawUrl); } catch { return; } const host = url.host.toLowerCase(); let pages = this.#pages.get(host); if (!pages) { pages = new Map(); this.#pages.set(host, pages); } for (const param of new Set(url.searchParams.keys())) { // Compare with the same URL minus this parameter, if it was seen. const sibling = pages.get(keyWithout(url, param)); if (!sibling) continue; const stats = this.#paramStats(host, param); if (hamming(sibling, simhash) <= this.#maxBits) stats.same++; else stats.different++; } // Also compare against already-seen URLs that carry one extra parameter. const selfKey = keyWithout(url, null); for (const [key, other] of pages) { if (!key.startsWith(url.host + url.pathname)) continue; const extra = this.#extraParam(selfKey, key); if (!extra) continue; const stats = this.#paramStats(host, extra); if (hamming(other, simhash) <= this.#maxBits) stats.same++; else stats.different++; } pages.delete(selfKey); pages.set(selfKey, simhash.toLowerCase()); if (pages.size > this.#maxPagesPerHost) { const oldest = pages.keys().next().value; if (oldest !== undefined) pages.delete(oldest); } } #paramStats(host: string, param: string): ParamStats { let byParam = this.#stats.get(host); if (!byParam) { byParam = new Map(); this.#stats.set(host, byParam); } let stats = byParam.get(param); if (!stats) { stats = { same: 0, different: 0 }; byParam.set(param, stats); } return stats; } /** Name of the single parameter `longer` has on top of `shorter`, if any. */ #extraParam(shorter: string, longer: string): string | null { const parse = (key: string) => { const q = key.indexOf("?"); return { base: q < 0 ? key : key.slice(0, q), params: q < 0 ? [] : key.slice(q + 1).split("&") }; }; const a = parse(shorter); const b = parse(longer); if (a.base !== b.base || b.params.length !== a.params.length + 1) return null; const remaining = [...b.params]; for (const param of a.params) { const index = remaining.indexOf(param); if (index < 0) return null; remaining.splice(index, 1); } const extra = remaining[0]; return extra ? decodeURIComponent(extra.split("=")[0] ?? "") : null; } /** Parameters currently considered irrelevant for `host`. */ ignoredParams(host: string): string[] { const byParam = this.#stats.get(host.toLowerCase()); if (!byParam) return []; return [...byParam.entries()] .filter(([, s]) => s.same >= this.#minSamples && s.different === 0) .map(([param]) => param) .sort(); } /** Strip learned irrelevant parameters from `rawUrl`. */ normalize(rawUrl: string): string { let url: URL; try { url = new URL(rawUrl); } catch { return rawUrl; } const ignored = this.ignoredParams(url.host); if (ignored.length === 0) return rawUrl; let changed = false; for (const param of ignored) { if (url.searchParams.has(param)) { url.searchParams.delete(param); changed = true; } } return changed ? url.toString() : rawUrl; } }