/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/queue/frontier/scoring * * Importance model of the crawl frontier: * * ``` * score = opicCash * + anchorWeight * anchorRelevance * + depthDecay ^ depth * + boost + revisitPriority * - min(familyPenaltyCap, familyPenalty * familyDoneCount) * ``` * * - `opicCash`: On-line Page Importance Computation (Abiteboul, Preda, Cobena, * WWW 2003). Seeds start with cash 1.0; a crawled page splits its cash * equally among its out-links. * - `anchorRelevance`: BM25-style saturated term overlap between the crawl goal * and `anchorText + URL path tokens`, in [0, 1]. * - `depthDecay ^ depth`: link-depth prior (BFS-like bias). * - `boost`: static caller prior (e.g. sitemap priority / lastmod recency). * - `revisitPriority`: expected freshness gain of a revisit (set by the * revisit scheduler when a DONE row is re-queued). * - family penalty: each already-DONE member of the same duplicate family * (query-stripped URL, SimHash bucket, ...) lowers the score. */ /** Components passed to a {@link FrontierScoreFn}. */ export interface FrontierScoreInput { /** Current OPIC cash of the URL. */ opicCash: number; /** Accumulated OPIC history (cash already distributed by this URL). */ opicHistory: number; /** Goal relevance of the anchor text + URL path, in [0, 1]. */ anchorRelevance: number; /** Link depth from the seeds (0 for seeds). */ depth: number; /** Number of DONE requests sharing the same family key. */ familyDoneCount: number; /** Static caller-provided prior. */ boost: number; /** Revisit freshness gain (0 for first visits). */ revisitPriority: number; /** Scheduling host key of the URL. */ hostKey: string; } /** Tunable weights of the default score. */ export interface FrontierScoreParams { /** Multiplier applied to anchor relevance. Default: 1. */ anchorWeight: number; /** Base of the depth decay term (`depthDecay ^ depth`). Default: 0.5. */ depthDecay: number; /** Penalty per DONE family member. Default: 0.25. */ familyPenalty: number; /** Maximum total family penalty. Default: 1. */ familyPenaltyCap: number; } /** Pluggable scoring function. Higher scores are dequeued first. */ export type FrontierScoreFn = ( input: FrontierScoreInput, params: FrontierScoreParams, ) => number; export const DEFAULT_SCORE_PARAMS: Readonly = Object.freeze({ anchorWeight: 1, depthDecay: 0.5, familyPenalty: 0.25, familyPenaltyCap: 1, }); /** Default frontier score (see module documentation). */ export const defaultFrontierScore: FrontierScoreFn = (input, params) => { const penalty = Math.min( params.familyPenaltyCap, params.familyPenalty * input.familyDoneCount, ); return ( input.opicCash + params.anchorWeight * input.anchorRelevance + params.depthDecay ** input.depth + input.boost + input.revisitPriority - penalty ); }; // --------------------------------------------------------------------------- // Host / family keys // --------------------------------------------------------------------------- /** * Lower-case hostname of an absolute URL without allocating a `URL` object. * Returns `""` for strings that are not absolute URLs (they share one bucket). */ export function defaultHostKey(url: string): string { const schemeEnd = url.indexOf("://"); let start: number; if (schemeEnd > 0) start = schemeEnd + 3; else if (url.startsWith("//")) start = 2; else return ""; let end = url.length; for (let i = start; i < url.length; i++) { const c = url.charCodeAt(i); // "/", "?", "#", "\" if (c === 47 || c === 63 || c === 35 || c === 92) { end = i; break; } } let authority = url.slice(start, end); const at = authority.lastIndexOf("@"); if (at !== -1) authority = authority.slice(at + 1); if (authority.startsWith("[")) { const close = authority.indexOf("]"); return (close === -1 ? authority : authority.slice(0, close + 1)).toLowerCase(); } const colon = authority.indexOf(":"); if (colon !== -1) authority = authority.slice(0, colon); authority = authority.toLowerCase(); return authority.endsWith(".") ? authority.slice(0, -1) : authority; } /** Family key helper: the URL with its query string and fragment removed. */ export function stripQueryFamilyKey(url: string): string { let end = url.length; const q = url.indexOf("?"); if (q !== -1) end = q; const h = url.indexOf("#"); if (h !== -1 && h < end) end = h; return url.slice(0, end); } // --------------------------------------------------------------------------- // Anchor relevance // --------------------------------------------------------------------------- const STOPWORDS = new Set([ "a", "an", "and", "are", "as", "at", "be", "by", "de", "des", "du", "en", "et", "for", "from", "in", "is", "it", "la", "le", "les", "of", "on", "or", "the", "this", "to", "un", "une", "with", "www", "http", "https", "html", "htm", "php", "asp", "aspx", "jsp", "index", "amp", ]); /** BM25 term-frequency saturation. */ const BM25_K1 = 1.2; /** BM25 length normalisation strength. */ const BM25_B = 0.25; /** Assumed average document length (anchor + path tokens). */ const AVG_DOC_TERMS = 8; /** Weight of URL path tokens relative to anchor-text tokens. */ const PATH_TERM_WEIGHT = 0.5; /** * Light, language-agnostic suffix stripping applied to goal and document terms. * Mismatches left by this crude stemmer are absorbed by the prefix matching of * {@link anchorRelevance}. */ export function stemTerm(term: string): string { if (term.length <= 4) return term; if (term.endsWith("ies")) return `${term.slice(0, -3)}y`; if (/(?:ss|us|is)$/.test(term)) return term; if (/(?:ches|shes|xes|zes|sses)$/.test(term)) return term.slice(0, -2); if (term.endsWith("ing") && term.length >= 7) return term.slice(0, -3); if (term.endsWith("ed") && term.length >= 6) return term.slice(0, -2); if (term.endsWith("s")) return term.slice(0, -1); return term; } /** Split text into normalised, stemmed terms (camelCase aware, stopwords removed). */ export function tokenizeTerms(text: string): string[] { const out: string[] = []; const spaced = text.replace(/([\p{Ll}\p{N}])(\p{Lu})/gu, "$1 $2").toLowerCase(); for (const raw of spaced.split(/[^\p{L}\p{N}]+/u)) { if (raw.length < 2 || STOPWORDS.has(raw)) continue; out.push(stemTerm(raw)); } return out; } /** Tokens of the path + query of a URL (the host is excluded on purpose). */ export function urlPathTerms(url: string): string[] { const schemeEnd = url.indexOf("://"); const hostStart = schemeEnd === -1 ? 0 : schemeEnd + 3; const pathStart = url.indexOf("/", hostStart); if (pathStart === -1) return []; let path = url.slice(pathStart); try { path = decodeURIComponent(path); } catch {} return tokenizeTerms(path); } /** Minimum term length for prefix (stem-variant) matching. */ const MIN_PREFIX_TERM = 4; /** Maximum length difference between two prefix-matching terms. */ const MAX_PREFIX_GAP = 3; /** `crawl` ~ `crawler`, `page` ~ `pag`: one term prefixes the other closely. */ function termsShareStem(a: string, b: string): boolean { if (b.length < MIN_PREFIX_TERM) return false; if (Math.abs(a.length - b.length) > MAX_PREFIX_GAP) return false; return a.length < b.length ? b.startsWith(a) : a.startsWith(b); } /** Pre-compiled crawl goal. */ export interface CrawlGoal { text: string; terms: ReadonlySet; } /** Compile a free-text goal. Returns `null` when it has no usable term. */ export function compileGoal(text: string | null | undefined): CrawlGoal | null { if (!text) return null; const terms = new Set(tokenizeTerms(text)); return terms.size === 0 ? null : { text, terms }; } /** * BM25-style relevance of `anchorText` + URL path tokens to the goal, in [0, 1]. * * Each goal term contributes `tf·(k1+1) / (tf + k1·norm)` capped at 1, where * `norm = 1 - b + b·len/avgLen`; the sum is divided by the number of goal terms. * Path tokens count half as much as anchor tokens. */ export function anchorRelevance( goal: CrawlGoal | null, anchorText: string | null | undefined, url: string, ): number { if (!goal) return 0; const tf = new Map(); let length = 0; if (anchorText) { for (const term of tokenizeTerms(anchorText)) { tf.set(term, (tf.get(term) ?? 0) + 1); length += 1; } } for (const term of urlPathTerms(url)) { tf.set(term, (tf.get(term) ?? 0) + PATH_TERM_WEIGHT); length += PATH_TERM_WEIGHT; } if (length === 0) return 0; const norm = 1 - BM25_B + BM25_B * (length / AVG_DOC_TERMS); let sum = 0; for (const term of goal.terms) { let f = tf.get(term) ?? 0; if (f === 0 && term.length >= MIN_PREFIX_TERM) { for (const [docTerm, count] of tf) { if (termsShareStem(term, docTerm)) f += count; } } if (f === 0) continue; sum += Math.min(1, (f * (BM25_K1 + 1)) / (f + BM25_K1 * norm)); } const relevance = sum / goal.terms.size; return relevance > 1 ? 1 : relevance < 0 ? 0 : relevance; }