From 36ad3054062e44298a5653392f062d648063b82a Mon Sep 17 00:00:00 2001 From: Tyler Hallada Date: Sun, 15 Nov 2026 14:30:50 -0500 Subject: [PATCH] Wikipedia client, sanitiser, routes and mock Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab --- server/wiki.ts | 1037 ++++++++++++++++++++++++++++++++++++++++++ server/wikiHtml.ts | 243 ++++++++++ server/wikiMock.ts | 748 ++++++++++++++++++++++++++++++ server/wikiRoutes.ts | 133 ++++++ 4 files changed, 2161 insertions(+) create mode 100644 server/wiki.ts create mode 100644 server/wikiHtml.ts create mode 100644 server/wikiMock.ts create mode 100644 server/wikiRoutes.ts diff --git a/server/wiki.ts b/server/wiki.ts new file mode 100644 index 0000000..7e84135 --- /dev/null +++ b/server/wiki.ts @@ -0,0 +1,1037 @@ +/** + * A small Wikipedia client, used only by the server. See docs/wikipedia.md for the rules it + * follows and why. + * + * lookup(phrases) batched existence check: canonical title, redirect, disambiguation, + * short description, missing. 50 titles per request (the API's limit). + * senses(title) the articles a disambiguation page lists, with their descriptions. + * suggest(prefix) title autocomplete (REST search/title). + * search(query) full-text search with snippets (REST search/page; CirrusSearch syntax). + * summary(title) extract, description, thumbnail, canonical URL, revision (REST page/summary). + * { cacheOnly: true } answers from the cache alone, never the network. + * article(title) lead plus the section list; section(title, id) one section. The whole page + * is fetched once (action=parse), split at its headings, sanitised (images + * dropped), cached. { sections: true } returns every section's html too. + * + * Every request goes through one serial queue with a minimum spacing, priority for interactive + * calls, Retry-After / 429 / 503 / maxlag handling, and a descriptive User-Agent. Results are + * cached on disk under /wiki-cache/, so scanning the same text twice costs nothing. + * Nothing here throws into a caller: failures come back as { ok: false, reason }. + * + * Only the candidate phrase or the search query itself is ever sent, never surrounding text. + */ +import { createHash } from "node:crypto"; +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { dataDir, writeAtomic as write } from "./util"; +import { snippet, splitArticle } from "./wikiHtml"; + +// ---- results ---- + +/** + * interactive: a person is waiting (an article, a preview, autocomplete). bulk: a background job. + * scan: the link scan that follows an edit, which nobody is waiting on as such: it goes last, so + * opening an article is never stuck behind it, except that one waiting over SCAN_STARVE_MS is let + * ahead of a long bulk job, so scans still finish while a library is being scanned. + */ +export type Priority = "interactive" | "bulk" | "scan"; +const SCAN_STARVE_MS = 30_000; +export interface CallOpts { + /** interactive: a person is waiting (jumps the queue, no maxlag). bulk: background jobs. scan: after an edit (last). */ + priority?: Priority; + /** Abort while queued (e.g. a superseded keystroke): the request is then never sent. */ + signal?: AbortSignal; +} +export type UnavailableReason = "offline" | "rate-limited" | "server" | "bad-response" | "aborted"; +export interface Unavailable { + ok: false; + reason: UnavailableReason; + message: string; + /** Seconds until the client will try the network again, when known. */ + retryAfter?: number; +} +export interface Missing { + ok: false; + reason: "missing"; + message: string; +} +/** A cache-only call found nothing cached. */ +export interface Uncached { + ok: false; + reason: "uncached"; + message: string; +} +export interface Ok { + ok: true; + value: V; + /** Served from the disk cache without a request. */ + cached: boolean; + /** Served from an expired cache entry because the network failed. */ + stale?: boolean; +} +export type Result = Ok | Unavailable | Missing; + +export type LookupItem = + | { + input: string; + status: "found"; + title: string; + pageId: number; + /** The input was a redirect to `title`. */ + redirect: boolean; + /** Section the redirect points at, if any. */ + fragment?: string; + disambiguation: boolean; + description: string | null; + url: string; + cached: boolean; + } + | { input: string; status: "missing"; cached: boolean } + | { input: string; status: "invalid"; reason: string; cached: boolean } + | { input: string; status: "unavailable"; reason: UnavailableReason; cached: false }; + +export interface Sense { + title: string; + description: string | null; + url: string; +} +export interface TitleSuggestion { + title: string; + description: string | null; + thumbnail: string | null; + url: string; +} +export interface SearchHit { + title: string; + pageId: number; + description: string | null; + /** Plain text of the snippet. */ + snippet: string; + /** The snippet with matches in , everything else escaped. */ + snippetHtml: string; + thumbnail: string | null; + url: string; +} +export interface Attribution { + title: string; + url: string; + revisionId: number | null; + revisionUrl: string | null; + historyUrl: string; + license: { name: "CC BY-SA 4.0"; url: string }; + /** One line the UI must show next to the text. */ + text: string; + /** What the app removed, which the licence asks us to indicate. Null if shown unmodified. */ + modified: string | null; +} +export interface Summary { + title: string; + pageId: number | null; + description: string | null; + extract: string; + thumbnail: { url: string; width: number; height: number } | null; + url: string; + revisionId: number | null; + disambiguation: boolean; + attribution: Attribution; +} +export interface SectionInfo { + /** 1-based, in page order; equals the API's section index for sections written on the page. */ + id: number; + level: number; + heading: string; + anchor: string; + /** "2.1" style number from the table of contents, when available. */ + number: string | null; + /** id of the enclosing section, 0 for top level. */ + parent: number; +} +export interface Article { + title: string; + pageId: number; + revisionId: number; + url: string; + /** A disambiguation page: a list of other articles rather than an article. */ + disambiguation: boolean; + /** Sanitised HTML of the lead (section 0). */ + lead: string; + sections: SectionInfo[]; + attribution: Attribution; +} +/** article(title, { sections: true }): every section with its sanitised HTML. */ +export interface FullArticle extends Article { + sections: (SectionInfo & { html: string })[]; +} +export interface Section extends SectionInfo { + title: string; + revisionId: number; + html: string; + attribution: Attribution; +} + +// ---- configuration ---- + +const DEFAULT_LANG = "en"; +const TITLES_PER_REQUEST = 50; +const DAY = 24 * 3600 * 1000; +const TTL = { + found: 30 * DAY, + missing: 3 * DAY, + invalid: 30 * DAY, + senses: 14 * DAY, + summary: 14 * DAY, + article: 7 * DAY, + suggest: 1 * DAY, + search: 1 * DAY, +}; +/** Spacing with a recognised contact in the User-Agent: 1 request/s, well under 200/min. */ +const SPACING_IDENTIFIED_MS = 1000; +/** Without one the gateway may treat us as "unidentified" (10/min): stay under it. */ +const SPACING_ANONYMOUS_MS = 6500; +/** After a network failure, answer "offline" without trying again for this long. */ +const OFFLINE_HOLD_MS = 30_000; +const REQUEST_TIMEOUT_MS = 15_000; +const MAX_ATTEMPTS = 3; +const MAX_WAIT: Record = { interactive: 8_000, bulk: 120_000, scan: 120_000 }; + +/** + * A contact the gateway can recognise: an email address, an http(s) URL, or a wiki user + * ("User:Name"), with no spaces or parentheses. Anything else is ignored. + */ +export function validContact(contact: string | undefined): string | null { + const c = contact?.trim(); + if (!c || /[\s();]/.test(c) || c.length > 100) return null; + if (/^[^@]+@[^@]+\.[^@]+$/.test(c) || /^https?:\/\/[^/]+\.[^/]+/.test(c) || /^User:\S+$/.test(c)) return c; + return null; +} + +/** The User-Agent: generic by default; never the owner's name, host or paths unless they supply a contact. */ +export function userAgent(contact: string | null): string { + return contact ? `Infinispand/0.1 (${contact})` : "Infinispand/0.1 (personal knowledge tool)"; +} + +interface WikiOptions { + dataDir?: string; + lang?: string; + contact?: string; + fetch?: typeof fetch; + now?: () => number; + sleep?: (ms: number, signal?: AbortSignal) => Promise; + spacingMs?: number; + /** Write the cache to disk (default true). */ + persist?: boolean; + /** How long a network failure holds the client offline (default 30 s; the mock uses 0). */ + offlineHoldMs?: number; +} + +/** A Wikipedia language code, or the default. */ +export function wikiLang(lang: string | undefined): string { + return /^[a-z][a-z0-9-]{1,15}$/.test(lang ?? "") ? lang! : DEFAULT_LANG; +} + +// ---- the queue ---- + +interface Fetched { + ok: true; + status: number; + headers: Headers; + text: string; +} +type Outcome = Fetched | Unavailable; + +interface Job { + url: string; + priority: Priority; + /** When it was queued. */ + at: number; + signal?: AbortSignal; + resolve: (o: Outcome) => void; +} + +const unavailable = (reason: UnavailableReason, message: string, retryAfter?: number): Unavailable => ({ + ok: false, + reason, + message, + ...(retryAfter !== undefined ? { retryAfter } : {}), +}); + +/** Retry-After is seconds or an HTTP date. Returns milliseconds, or null. */ +export function parseRetryAfter(value: string | null, now: number): number | null { + if (!value) return null; + if (/^\d+$/.test(value.trim())) return Number(value.trim()) * 1000; + const t = Date.parse(value); + return Number.isNaN(t) ? null : Math.max(0, t - now); +} + +const defaultSleep = (ms: number, signal?: AbortSignal) => + new Promise((done) => { + if (signal?.aborted) return done(); + const timer = setTimeout(done, ms); + signal?.addEventListener("abort", () => (clearTimeout(timer), done()), { once: true }); + }); + +/** + * One request at a time, at least `spacingMs` apart, interactive jobs first. A 429 or 503 (or an + * Action API maxlag error) pauses the whole queue for Retry-After, or 5 s doubling; a job whose + * wait would exceed its priority's patience gets "rate-limited" at once. A network failure marks + * the client offline for `offlineHoldMs` (30 s) so that typing does not hammer a dead connection. + */ +class RequestQueue { + private lanes: Record = { interactive: [], bulk: [], scan: [] }; + private busy = false; + private lastStart = -Infinity; + pausedUntil = 0; + offlineUntil = 0; + requests = 0; + + constructor( + private o: { + fetch: typeof fetch; + userAgent: string; + spacingMs: number; + offlineHoldMs: number; + now: () => number; + sleep: (ms: number, signal?: AbortSignal) => Promise; + }, + ) {} + + get spacing() { + return this.o.spacingMs; + } + + get(url: string, priority: Priority, signal?: AbortSignal): Promise { + if (signal?.aborted) return Promise.resolve(unavailable("aborted", "aborted")); + return new Promise((resolve) => { + const job: Job = { url, priority, at: this.o.now(), signal, resolve }; + this.lanes[priority].push(job); + signal?.addEventListener( + "abort", + () => { + const lane = this.lanes[priority]; + const i = lane.indexOf(job); + if (i >= 0) { + lane.splice(i, 1); + resolve(unavailable("aborted", "aborted")); + } + }, + { once: true }, + ); + void this.pump(); + }); + } + + private async pump() { + if (this.busy) return; + this.busy = true; + try { + for (;;) { + const starved = this.lanes.scan[0] && this.o.now() - this.lanes.scan[0].at > SCAN_STARVE_MS; + const job = this.lanes.interactive.shift() ?? (starved ? this.lanes.scan.shift() : undefined) ?? this.lanes.bulk.shift() ?? this.lanes.scan.shift(); + if (!job) break; + job.resolve(await this.execute(job).catch((e) => unavailable("bad-response", String(e)))); + } + } finally { + this.busy = false; + } + } + + private async execute(job: Job): Promise { + const patience = MAX_WAIT[job.priority]; + for (let attempt = 0; ; attempt++) { + const now = this.o.now(); + if (now < this.offlineUntil) { + return unavailable("offline", "Wikipedia could not be reached", Math.ceil((this.offlineUntil - now) / 1000)); + } + const paused = this.pausedUntil - now; + if (paused > patience) { + return unavailable("rate-limited", "Wikipedia asked us to slow down", Math.ceil(paused / 1000)); + } + const wait = Math.max(paused, this.lastStart + this.o.spacingMs - now, 0); + if (wait > 0) await this.o.sleep(wait, job.signal); + if (job.signal?.aborted) return unavailable("aborted", "aborted"); + this.lastStart = this.o.now(); + this.requests++; + let res: Response; + let text: string; + try { + const signals = [AbortSignal.timeout(REQUEST_TIMEOUT_MS), ...(job.signal ? [job.signal] : [])]; + res = await this.o.fetch(job.url, { + headers: { "user-agent": this.o.userAgent, "accept-encoding": "gzip", accept: "application/json, text/html" }, + signal: AbortSignal.any(signals), + }); + text = await res.text(); + } catch (e) { + if (job.signal?.aborted) return unavailable("aborted", "aborted"); + this.offlineUntil = this.o.now() + this.o.offlineHoldMs; + return unavailable("offline", `Wikipedia could not be reached: ${(e as Error).message ?? e}`, Math.ceil(this.o.offlineHoldMs / 1000)); + } + const maxlag = res.status === 200 && text.length < 2000 && /"code"\s*:\s*"maxlag"/.test(text); + if (res.status === 429 || res.status === 503 || maxlag) { + const ra = parseRetryAfter(res.headers.get("retry-after"), this.o.now()); + const backoff = ra ?? 5000 * 2 ** attempt; + this.pausedUntil = this.o.now() + backoff; + if (attempt + 1 >= MAX_ATTEMPTS || backoff > patience) { + return unavailable( + res.status === 503 && !ra ? "server" : "rate-limited", + `Wikipedia answered ${maxlag ? "maxlag" : res.status}`, + Math.ceil(backoff / 1000), + ); + } + continue; + } + return { ok: true, status: res.status, headers: res.headers, text }; + } + } +} + +// ---- disk cache ---- + +interface Entry { + v: V; + exp: number; +} + +/** A key-value map with expiry, held in memory and written to one JSON file (debounced, atomic). */ +class KvStore { + private map: Map> | null = null; + private timer: NodeJS.Timeout | null = null; + + constructor( + private file: string | null, + private now: () => number, + private maxEntries = 200_000, + ) {} + + private load(): Map> { + if (this.map) return this.map; + this.map = new Map(); + if (this.file && existsSync(this.file)) { + try { + const data = JSON.parse(readFileSync(this.file, "utf8")) as { entries: [string, Entry][] }; + for (const [k, e] of data.entries ?? []) this.map.set(k, e); + } catch { + // A damaged cache is only a cache: start again. + } + } + return this.map; + } + + get(key: string): { value: V; fresh: boolean } | undefined { + const e = this.load().get(key); + return e ? { value: e.v, fresh: e.exp > this.now() } : undefined; + } + + set(key: string, v: V, ttl: number) { + const map = this.load(); + map.delete(key); + map.set(key, { v, exp: this.now() + ttl }); + while (map.size > this.maxEntries) map.delete(map.keys().next().value as string); + this.schedule(); + } + + get size() { + return this.load().size; + } + + private schedule() { + if (!this.file || this.timer) return; + this.timer = setTimeout(() => this.flush(), 1000); + this.timer.unref?.(); + } + + flush() { + if (this.timer) clearTimeout(this.timer); + this.timer = null; + if (!this.file || !this.map) return; + writeAtomic(this.file, JSON.stringify({ version: 1, entries: [...this.map] })); + } +} + +/** Large values (whole articles), one file per key. */ +class BlobStore { + private memo = new Map>(); + constructor( + private dir: string | null, + private now: () => number, + ) {} + private path(key: string) { + return join(this.dir!, createHash("sha1").update(key).digest("hex") + ".json"); + } + get(key: string): { value: V; fresh: boolean } | undefined { + let e = this.memo.get(key); + if (!e && this.dir && existsSync(this.path(key))) { + try { + e = JSON.parse(readFileSync(this.path(key), "utf8")) as Entry; + this.remember(key, e); + } catch { + e = undefined; + } + } + return e ? { value: e.v, fresh: e.exp > this.now() } : undefined; + } + set(key: string, v: V, ttl: number) { + const e = { v, exp: this.now() + ttl }; + this.remember(key, e); + if (this.dir) writeAtomic(this.path(key), JSON.stringify(e)); + } + private remember(key: string, e: Entry) { + this.memo.delete(key); + this.memo.set(key, e); + if (this.memo.size > 50) this.memo.delete(this.memo.keys().next().value as string); + } +} + +let warnedWrite = false; +function writeAtomic(file: string, data: string) { + try { + write(file, data); + } catch (e) { + if (!warnedWrite) console.warn(`wiki cache: could not write ${file}: ${(e as Error).message}`); + warnedWrite = true; + } +} + +// ---- titles ---- + +/** Characters MediaWiki never allows in a title. */ +const ILLEGAL = /[#<>[\]|{}\u0000-\u001f\u007f�]/; + +/** The form MediaWiki would normalise a main-namespace title to (spaces, first letter). */ +export function prepareTitle(input: string): { title: string } | { invalid: string } { + const t = input.replace(/_/g, " ").replace(/\s+/g, " ").trim(); + if (!t) return { invalid: "empty" }; + if (ILLEGAL.test(t)) return { invalid: "illegal character" }; + if (Buffer.byteLength(t) > 255) return { invalid: "too long" }; + if (t.startsWith(":") || /^\.\.?(\/|$)/.test(t) || t.includes("/./") || t.includes("/../")) return { invalid: "not a page title" }; + const first = String.fromCodePoint(t.codePointAt(0)!); + return { title: first.toUpperCase() + t.slice(first.length) }; +} + +// ---- the client ---- + +type LookupValue = + | { status: "found"; title: string; pageId: number; redirect: boolean; fragment?: string; disambiguation: boolean; description: string | null } + | { status: "missing" } + | { status: "invalid"; reason: string }; + +interface CachedArticle { + title: string; + pageId: number; + revisionId: number; + /** Absent in entries cached before it was recorded: read as false. */ + disambiguation?: boolean; + lead: string; + sections: (SectionInfo & { html: string })[]; +} + +export class WikiClient { + readonly lang: string; + readonly userAgent: string; + readonly contact: string | null; + private queue: RequestQueue; + private now: () => number; + private titles: KvStore; + private small: KvStore; + private articles: BlobStore; + + constructor(o: WikiOptions = {}) { + this.lang = wikiLang(o.lang); + this.contact = validContact(o.contact); + this.userAgent = userAgent(this.contact); + this.now = o.now ?? Date.now; + const persist = o.persist !== false; + const dir = persist ? join(o.dataDir ?? dataDir(), "wiki-cache", this.lang) : null; + this.titles = new KvStore(dir && join(dir, "titles.json"), this.now); + this.small = new KvStore(dir && join(dir, "small.json"), this.now, 20_000); + this.articles = new BlobStore(dir && join(dir, "articles"), this.now); + this.queue = new RequestQueue({ + fetch: o.fetch ?? fetch, + userAgent: this.userAgent, + spacingMs: o.spacingMs ?? (this.contact ? SPACING_IDENTIFIED_MS : SPACING_ANONYMOUS_MS), + offlineHoldMs: o.offlineHoldMs ?? OFFLINE_HOLD_MS, + now: this.now, + sleep: o.sleep ?? defaultSleep, + }); + } + + /** Requests sent to Wikipedia so far. */ + get requests(): number { + return this.queue.requests; + } + + /** How many of these phrases a lookup would have to ask Wikipedia about (none fresh in the cache). */ + uncached(inputs: string[]): number { + const seen = new Set(); + for (const input of inputs) { + const p = prepareTitle(input); + if ("title" in p && !this.titles.get(p.title)?.fresh) seen.add(p.title); + } + return seen.size; + } + + /** Milliseconds the queue leaves between requests. */ + get spacingMs(): number { + return this.queue.spacing; + } + + /** Write pending cache entries now (they are otherwise written within a second). */ + flush() { + this.titles.flush(); + this.small.flush(); + } + + private get site() { + return `https://${this.lang}.wikipedia.org`; + } + articleUrl(title: string) { + return `${this.site}/wiki/${encodeURIComponent(title.replace(/ /g, "_")).replace(/%2F/g, "/").replace(/%3A/g, ":")}`; + } + private restTitle(title: string) { + return encodeURIComponent(title.replace(/ /g, "_")); + } + + attribution(title: string, revisionId: number | null, modified: string | null): Attribution { + const enc = encodeURIComponent(title.replace(/ /g, "_")); + return { + title, + url: this.articleUrl(title), + revisionId, + revisionUrl: revisionId ? `${this.site}/w/index.php?title=${enc}&oldid=${revisionId}` : null, + historyUrl: `${this.site}/w/index.php?title=${enc}&action=history`, + license: { name: "CC BY-SA 4.0", url: "https://creativecommons.org/licenses/by-sa/4.0/" }, + text: `From the Wikipedia article “${title}”${revisionId ? ` (revision ${revisionId})` : ""}, by its contributors, under CC BY-SA 4.0.${modified ? ` ${modified}` : ""}`, + modified, + }; + } + + private async getJson(url: string, o: CallOpts): Promise<{ ok: true; status: number; json: any } | Unavailable> { + const r = await this.queue.get(url, o.priority ?? "interactive", o.signal); + if (!r.ok) return r; + try { + return { ok: true, status: r.status, json: JSON.parse(r.text) }; + } catch { + if (r.status >= 500) return unavailable("server", `Wikipedia answered ${r.status}`); + return unavailable("bad-response", `Wikipedia answered ${r.status} with something other than JSON`); + } + } + + private actionUrl(params: Record, o: CallOpts) { + const p = new URLSearchParams({ action: "query", format: "json", formatversion: "2", ...params }); + // maxlag is for work nobody is waiting on (Manual:Maxlag_parameter). + if ((o.priority ?? "interactive") !== "interactive") p.set("maxlag", "5"); + return `${this.site}/w/api.php?${p}`; + } + + /** Read through the small-value cache: fresh hit, else fetch, else stale on failure. */ + private async cachedSmall(key: string, ttl: number, load: () => Promise>): Promise> { + const hit = this.small.get(key) as { value: V; fresh: boolean } | undefined; + if (hit?.fresh) return { ok: true, value: hit.value, cached: true }; + const r = await load(); + if (r.ok) this.small.set(key, r.value, ttl); + else if (r.reason !== "missing" && r.reason !== "aborted" && hit) return { ok: true, value: hit.value, cached: true, stale: true }; + return r; + } + + // -- lookup -- + + /** + * Which of these phrases are article titles. Inputs are deduplicated after normalisation; + * uncached ones are asked in batches of 50 (the Action API's limit for clients without + * apihighlimits). Found, missing and invalid answers are all cached. + */ + async lookup(inputs: string[], o: CallOpts = {}): Promise { + try { + const prepared = inputs.map((input) => ({ input, p: prepareTitle(input) })); + const answers = new Map(); + const need: string[] = []; + const stale = new Map(); + for (const { p } of prepared) { + if (!("title" in p) || answers.has(p.title) || need.includes(p.title)) continue; + const hit = this.titles.get(p.title); + if (hit?.fresh) { + answers.set(p.title, { v: hit.value, cached: true }); + } else { + if (hit) stale.set(p.title, hit.value); + need.push(p.title); + } + } + for (const batch of batches(need)) { + const r = await this.getJson( + this.actionUrl( + { titles: batch.join("|"), redirects: "1", prop: "pageprops|description", ppprop: "disambiguation" }, + o, + ), + o, + ); + const mapped = r.ok ? mapQuery(batch, r.json) : null; + for (const t of batch) { + const v = mapped?.get(t); + if (v) { + answers.set(t, { v, cached: false }); + this.titles.set(t, v, v.status === "found" ? TTL.found : v.status === "missing" ? TTL.missing : TTL.invalid); + } else if (stale.has(t)) { + answers.set(t, { v: stale.get(t)!, cached: true }); + } else { + answers.set(t, { unavailable: r.ok ? "bad-response" : r.reason }); + } + } + } + return prepared.map(({ input, p }): LookupItem => { + if (!("title" in p)) return { input, status: "invalid", reason: p.invalid, cached: true }; + const a = answers.get(p.title)!; + if ("unavailable" in a) return { input, status: "unavailable", reason: a.unavailable, cached: false }; + const v = a.v; + if (v.status === "found") return { input, ...v, url: this.articleUrl(v.title), cached: a.cached }; + return { input, ...v, cached: a.cached }; + }); + } catch (e) { + console.warn("wiki lookup:", e); + return inputs.map((input) => ({ input, status: "unavailable", reason: "bad-response", cached: false })); + } + } + + /** The main-namespace articles a disambiguation page links to, with short descriptions. */ + async senses(title: string, o: CallOpts = {}): Promise> { + const p = prepareTitle(title); + if (!("title" in p)) return { ok: false, reason: "missing", message: p.invalid }; + return this.cachedSmall(`senses:${p.title}`, TTL.senses, async () => { + const r = await this.getJson( + this.actionUrl( + { titles: p.title, redirects: "1", generator: "links", gplnamespace: "0", gpllimit: "max", prop: "description|pageprops", ppprop: "disambiguation" }, + o, + ), + o, + ); + if (!r.ok) return r; + const pages: any[] = r.json?.query?.pages ?? []; + const senses = pages + .filter((pg) => !pg.missing && !pg.invalid && pg.pageprops?.disambiguation === undefined) + .map((pg): Sense => ({ title: String(pg.title), description: pg.description ?? null, url: this.articleUrl(String(pg.title)) })); + return { ok: true, value: senses, cached: false }; + }); + } + + // -- search -- + + /** Title autocomplete: what the REST search/title endpoint is documented for ("typeahead"). */ + async suggest(prefix: string, limit = 8, o: CallOpts = {}): Promise> { + const q = prefix.replace(/\s+/g, " ").trim(); + if (!q) return { ok: true, value: [], cached: true }; + const n = clamp(limit, 1, 20); + return this.cachedSmall(`suggest:${n}:${q.toLowerCase()}`, TTL.suggest, async () => { + const r = await this.getJson(`${this.site}/w/rest.php/v1/search/title?${new URLSearchParams({ q, limit: String(n) })}`, o); + if (!r.ok) return r; + if (r.status !== 200 || !Array.isArray(r.json?.pages)) return unavailable("bad-response", `search/title answered ${r.status}`); + return { + ok: true, + cached: false, + value: r.json.pages.map((pg: any): TitleSuggestion => ({ + title: String(pg.title), + description: pg.description ?? null, + thumbnail: absolute(pg.thumbnail?.url), + url: this.articleUrl(String(pg.title)), + })), + }; + }); + } + + /** + * Full-text search (CirrusSearch). The query may use its syntax: "quoted phrases", + * intitle:, morelike:Title, -exclusions. Only the query is sent. + */ + async search(query: string, limit = 10, o: CallOpts = {}): Promise> { + const q = query.replace(/\s+/g, " ").trim(); + if (!q) return { ok: true, value: [], cached: true }; + const n = clamp(limit, 1, 50); + return this.cachedSmall(`search:${n}:${q}`, TTL.search, async () => { + const r = await this.getJson(`${this.site}/w/rest.php/v1/search/page?${new URLSearchParams({ q, limit: String(n) })}`, o); + if (!r.ok) return r; + if (r.status !== 200 || !Array.isArray(r.json?.pages)) return unavailable("bad-response", `search/page answered ${r.status}`); + return { + ok: true, + cached: false, + value: r.json.pages.map((pg: any): SearchHit => { + const s = snippet(String(pg.excerpt ?? "")); + return { + title: String(pg.title), + pageId: Number(pg.id), + description: pg.description ?? null, + snippet: s.text, + snippetHtml: s.html, + thumbnail: absolute(pg.thumbnail?.url), + url: this.articleUrl(String(pg.title)), + }; + }), + }; + }); + } + + // -- summary -- + + /** + * A preview: REST page/summary (edge-cached), falling back to the Action API if it fails. + * With cacheOnly, a cached summary (fresh or expired) or "uncached", and never a request: for + * callers that must not wait on the network, such as building a model prompt. + */ + async summary(title: string, o: CallOpts & { cacheOnly: true }): Promise | Uncached>; + async summary(title: string, o?: CallOpts & { cacheOnly?: false }): Promise>; + async summary(title: string, o: CallOpts & { cacheOnly?: boolean } = {}): Promise | Uncached> { + const p = prepareTitle(title); + if (!("title" in p)) return { ok: false, reason: "missing", message: p.invalid }; + if (o.cacheOnly) { + const hit = this.small.get(`summary:${p.title}`) as { value: Summary; fresh: boolean } | undefined; + if (!hit) return { ok: false, reason: "uncached", message: `No summary of “${p.title}” is cached` }; + return { ok: true, value: hit.value, cached: true, ...(hit.fresh ? {} : { stale: true }) }; + } + return this.cachedSmall(`summary:${p.title}`, TTL.summary, async () => { + const r = await this.getJson(`${this.site}/api/rest_v1/page/summary/${this.restTitle(p.title)}?redirect=true`, o); + if (r.ok && r.status === 404) return { ok: false, reason: "missing", message: `No article “${p.title}”` }; + if (r.ok && r.status === 200 && typeof r.json?.title === "string") { + const j = r.json; + const t = String(j.titles?.normalized ?? j.title); + const rev = j.revision ? Number(j.revision) : null; + return { + ok: true, + cached: false, + value: { + title: t, + pageId: j.pageid ?? null, + description: j.description ?? null, + extract: String(j.extract ?? ""), + thumbnail: j.thumbnail ? { url: absolute(j.thumbnail.source)!, width: j.thumbnail.width, height: j.thumbnail.height } : null, + url: j.content_urls?.desktop?.page ?? this.articleUrl(t), + revisionId: rev, + disambiguation: j.type === "disambiguation", + attribution: this.attribution(t, rev, null), + }, + }; + } + if (!r.ok && r.reason !== "bad-response" && r.reason !== "server") return r; + return this.summaryFromAction(p.title, o); + }); + } + + private async summaryFromAction(title: string, o: CallOpts): Promise> { + const r = await this.getJson( + this.actionUrl( + { + titles: title, + redirects: "1", + prop: "extracts|pageimages|description|info|pageprops", + exintro: "1", + explaintext: "1", + piprop: "thumbnail", + pithumbsize: "330", + ppprop: "disambiguation", + }, + o, + ), + o, + ); + if (!r.ok) return r; + const pg = r.json?.query?.pages?.[0]; + if (!pg) return unavailable("bad-response", "no page in answer"); + if (pg.missing || pg.invalid) return { ok: false, reason: "missing", message: `No article “${title}”` }; + const t = String(pg.title); + const rev = pg.lastrevid ?? null; + return { + ok: true, + cached: false, + value: { + title: t, + pageId: pg.pageid ?? null, + description: pg.description ?? null, + extract: String(pg.extract ?? ""), + thumbnail: pg.thumbnail ? { url: absolute(pg.thumbnail.source)!, width: pg.thumbnail.width, height: pg.thumbnail.height } : null, + url: this.articleUrl(t), + revisionId: rev, + disambiguation: pg.pageprops?.disambiguation !== undefined, + attribution: this.attribution(t, rev, null), + }, + }; + } + + // -- article -- + + private async loadArticle(title: string, o: CallOpts): Promise> { + const p = prepareTitle(title); + if (!("title" in p)) return { ok: false, reason: "missing", message: p.invalid }; + // "|0": articles were once cached with and without images; only without remains. + const key = `${p.title}|0`; + const hit = this.articles.get(key); + if (hit?.fresh) return { ok: true, value: hit.value, cached: true }; + const r = await this.getJson( + this.actionUrl( + { + action: "parse", + page: p.title, + redirects: "1", + prop: "text|tocdata|revid|displaytitle|properties", + disableeditsection: "1", + disablelimitreport: "1", + disabletoc: "1", + }, + o, + ), + o, + ); + if (!r.ok) return hit ? { ok: true, value: hit.value, cached: true, stale: true } : r; + if (r.json?.error) { + if (r.json.error.code === "missingtitle" || r.json.error.code === "invalidtitle") { + return { ok: false, reason: "missing", message: `No article “${p.title}”` }; + } + return hit ? { ok: true, value: hit.value, cached: true, stale: true } : unavailable("bad-response", String(r.json.error.info ?? r.json.error.code)); + } + const parse = r.json?.parse; + if (!parse || typeof parse.text !== "string") return unavailable("bad-response", "no text in parse answer"); + const split = splitArticle(parse.text, this.lang); + const toc: any[] = parse.tocdata?.sections ?? []; + if (toc.length === split.sections.length) split.sections.forEach((s, i) => (s.number = toc[i].number ?? null)); + const value: CachedArticle = { + title: String(parse.title), + pageId: Number(parse.pageid), + revisionId: Number(parse.revid), + disambiguation: pageProperties(parse.properties).has("disambiguation"), + ...split, + }; + this.articles.set(key, value, TTL.article); + return { ok: true, value, cached: false }; + } + + /** + * The lead and the section list. One request per article per week at most; sections then cost + * nothing. With sections: true each section carries its html too, from the same cached page. + */ + async article(title: string, o: CallOpts & { sections: true }): Promise>; + async article(title: string, o?: CallOpts & { sections?: boolean }): Promise>; + async article(title: string, o: CallOpts & { sections?: boolean } = {}): Promise> { + try { + const r = await this.loadArticle(title, o); + if (!r.ok) return r; + const a = r.value; + return { + ...r, + value: { + title: a.title, + pageId: a.pageId, + revisionId: a.revisionId, + url: this.articleUrl(a.title), + disambiguation: a.disambiguation ?? false, + lead: a.lead, + sections: o.sections ? a.sections : a.sections.map(({ html: _html, ...info }) => info), + attribution: this.attribution(a.title, a.revisionId, MODIFIED), + }, + }; + } catch (e) { + return unavailable("bad-response", String(e)); + } + } + + /** One section, by the id from article(). */ + async section(title: string, id: number, o: CallOpts = {}): Promise> { + try { + const r = await this.loadArticle(title, o); + if (!r.ok) return r; + const a = r.value; + const s = id === 0 ? { id: 0, level: 1, heading: a.title, anchor: "", number: null, parent: 0, html: a.lead } : a.sections.find((x) => x.id === id); + if (!s) return { ok: false, reason: "missing", message: `“${a.title}” has no section ${id}` }; + return { ...r, value: { ...s, title: a.title, revisionId: a.revisionId, attribution: this.attribution(a.title, a.revisionId, MODIFIED) } }; + } catch (e) { + return unavailable("bad-response", String(e)); + } + } +} + +const MODIFIED = "Adapted: references, navigation boxes, infoboxes, edit links and images removed."; + +let shared: WikiClient | null = null; +/** The server's client, configured from IE_DATA, IE_WIKI_LANG and IE_WIKI_CONTACT. */ +export function wiki(): WikiClient { + if (!shared) { + shared = new WikiClient({ lang: process.env.IE_WIKI_LANG, contact: process.env.IE_WIKI_CONTACT }); + if (process.env.IE_WIKI_CONTACT && !shared.contact) { + console.warn("IE_WIKI_CONTACT is not an email address, an http(s) URL or User:Name; sending the generic User-Agent."); + } + process.once("exit", () => shared?.flush()); + } + return shared; +} + +// ---- helpers ---- + +const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, Math.floor(Number.isFinite(n) ? n : lo))); + +/** Page properties from action=parse: an object in formatversion 2, a list of { name, "*" } before it. */ +function pageProperties(props: unknown): Set { + if (Array.isArray(props)) return new Set(props.map((p) => String(p?.name))); + if (props && typeof props === "object") return new Set(Object.keys(props)); + return new Set(); +} + +function absolute(url: unknown): string | null { + if (typeof url !== "string" || !url) return null; + if (url.startsWith("//")) return `https:${url}`; + return /^https:\/\//.test(url) ? url : null; +} + +/** Split titles into requests of at most 50, keeping each URL a sensible length. */ +export function batches(titles: string[], size = TITLES_PER_REQUEST, maxChars = 6000): string[][] { + const out: string[][] = []; + let cur: string[] = []; + let chars = 0; + for (const t of titles) { + const len = encodeURIComponent(t).length + 3; + if (cur.length && (cur.length >= size || chars + len > maxChars)) { + out.push(cur); + cur = []; + chars = 0; + } + cur.push(t); + chars += len; + } + if (cur.length) out.push(cur); + return out; +} + +/** Follow normalized → converted → redirects to the page each asked title ended at. */ +function mapQuery(asked: string[], json: any): Map | null { + const q = json?.query; + if (!q) return null; + const step = (list: any[] | undefined) => new Map((list ?? []).map((x) => [String(x.from), x])); + const normalized = step(q.normalized); + const converted = step(q.converted); + const redirects = step(q.redirects); + const interwiki = new Set((q.interwiki ?? []).map((x: any) => String(x.title))); + const pages = new Map((q.pages ?? []).map((pg: any) => [String(pg.title), pg])); + const out = new Map(); + for (const t of asked) { + let cur = t; + if (interwiki.has(cur)) { + out.set(t, { status: "invalid", reason: "interwiki" }); + continue; + } + cur = normalized.get(cur)?.to ?? cur; + if (interwiki.has(cur)) { + out.set(t, { status: "invalid", reason: "interwiki" }); + continue; + } + cur = converted.get(cur)?.to ?? cur; + const red = redirects.get(cur); + if (red) cur = red.to; + const pg = pages.get(cur); + if (!pg) continue; + if (pg.invalid) out.set(t, { status: "invalid", reason: String(pg.invalidreason ?? "invalid") }); + else if (pg.missing || pg.ns !== 0) out.set(t, pg.missing ? { status: "missing" } : { status: "invalid", reason: "not an article" }); + else + out.set(t, { + status: "found", + title: String(pg.title), + pageId: Number(pg.pageid), + redirect: Boolean(red), + ...(red?.tofragment ? { fragment: String(red.tofragment) } : {}), + disambiguation: pg.pageprops?.disambiguation !== undefined, + description: pg.description ?? null, + }); + } + return out; +} diff --git a/server/wikiHtml.ts b/server/wikiHtml.ts new file mode 100644 index 0000000..416ff50 --- /dev/null +++ b/server/wikiHtml.ts @@ -0,0 +1,243 @@ +/** + * Wikipedia's HTML made safe to show, and split into sections: an allowlist of elements and + * attributes (MathML kept; images, references, boxes and navigation dropped), with every link + * either naming an article (data-wiki) or leaving in a new tab. Used by server/wiki.ts. + */ +import { parseFragment, type DefaultTreeAdapterTypes as T } from "parse5"; +import type { SectionInfo } from "./wiki"; + +type Node = T.ChildNode; +type El = T.Element; +const MATHML = "http://www.w3.org/1998/Math/MathML"; + +const DROP_TAGS = new Set([ + "script", "style", "link", "meta", "noscript", "iframe", "object", "embed", "form", "input", "button", "select", + "textarea", "template", "svg", "audio", "video", "source", "track", "canvas", "map", "area", "base", "title", "head", +]); +const DROP_CLASSES = new Set([ + "mw-editsection", "reference", "mw-references-wrap", "references", "reflist", "refbegin", "mw-cite-backlink", + "navbox", "navbox-styles", "vertical-navbox", "sidebar", "infobox", "metadata", "ambox", "ombox", "tmbox", "cmbox", + "fmbox", "imbox", "mbox-small", "hatnote", "dablink", "rellink", "shortdescription", "noprint", "mw-empty-elt", + "Z3988", "navbar", "catlinks", "toc", "mw-jump-link", "portalbox", "sistersitebox", "side-box", "authority-control", + "mwe-math-fallback-image-inline", "mwe-math-fallback-image-display", "error", "mw-kartographer-container", +]); +const IMAGE_CLASSES = new Set(["thumb", "gallery", "mw-gallery-traditional", "tsingle", "multiimageinner"]); +const ALLOWED = new Set([ + "p", "br", "hr", "b", "strong", "i", "em", "u", "s", "sub", "sup", "code", "kbd", "var", "samp", "small", "blockquote", + "q", "ul", "ol", "li", "dl", "dt", "dd", "pre", "table", "caption", "thead", "tbody", "tfoot", "tr", "th", "td", + "abbr", "bdi", "mark", +]); +const VOID = new Set(["br", "hr"]); +const MATH_TAGS = new Set([ + "math", "semantics", "mrow", "mi", "mo", "mn", "ms", "mtext", "mspace", "msub", "msup", "msubsup", "mfrac", "msqrt", + "mroot", "mover", "munder", "munderover", "mtable", "mtr", "mtd", "mstyle", "mpadded", "mphantom", "menclose", + "merror", "mmultiscripts", "mprescripts", "none", +]); +const MATH_ATTRS = new Set([ + "display", "mathvariant", "stretchy", "displaystyle", "scriptlevel", "fence", "separator", "accent", "accentunder", + "lspace", "rspace", "linethickness", "columnalign", "rowalign", "notation", "largeop", "movablelimits", "symmetric", + "minsize", "maxsize", "width", "height", "depth", "alttext", +]); +/** Namespaces whose links are unwrapped rather than offered as articles (canonical English names and aliases). */ +const NON_ARTICLE_NS = new Set([ + "talk", "user", "user talk", "wikipedia", "wikipedia talk", "wp", "project", "file", "file talk", "image", "media", + "mediawiki", "template", "template talk", "help", "help talk", "category", "category talk", "portal", "draft", + "timedtext", "module", "special", "book", "education program", "gadget", "gadget definition", "topic", "h", "cat", + "t", "mos", "wikt", "wiktionary", "commons", "meta", "m", "s", "q", "n", "b", "v", "voy", "d", "species", "mw", +]); + +const attr = (el: El, name: string) => el.attrs.find((a) => a.name === name)?.value; +const classes = (el: El) => new Set((attr(el, "class") ?? "").split(/\s+/).filter(Boolean)); +const isEl = (n: Node): n is El => "tagName" in n; + +function escapeText(s: string) { + return s.replace(/&/g, "&").replace(//g, ">"); +} +function escapeAttr(s: string) { + return escapeText(s).replace(/"/g, """); +} + +function textOf(n: Node): string { + if (n.nodeName === "#text") return (n as T.TextNode).value; + if (isEl(n)) { + if (DROP_TAGS.has(n.tagName)) return ""; + return n.childNodes.map(textOf).join(""); + } + return ""; +} + +function open(tag: string, attrs: [string, string][]) { + return `<${tag}${attrs.map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("")}>`; +} + +function emptyHtml(s: string) { + return !s.replace(/
/g, "").trim(); +} + +function wikiLink(el: El, inner: string, lang: string): string { + const href = attr(el, "href") ?? ""; + const cls = classes(el); + if (!href || cls.has("new") || cls.has("mw-selflink") || href.includes("redlink=1")) return inner; + if (href.startsWith("#")) { + if (/^#cite[_-]/.test(href)) return ""; + return `${inner}`; + } + if (href.startsWith("/wiki/") || href.startsWith(`https://${lang}.wikipedia.org/wiki/`)) { + const path = href.slice(href.indexOf("/wiki/") + 6); + const [rawTitle, rawFrag] = path.split("#", 2); + const title = safeDecode(rawTitle).replace(/_/g, " "); + const ns = /^([^:]+):(\S)/.exec(title)?.[1]; + if (ns && (NON_ARTICLE_NS.has(ns.toLowerCase()) || (lang !== "en" && !/\s/.test(ns)))) return inner; + const attrs: [string, string][] = [["href", `https://${lang}.wikipedia.org/wiki/${rawTitle}`], ["data-wiki", title]]; + if (rawFrag) attrs.push(["data-wiki-fragment", safeDecode(rawFrag).replace(/_/g, " ")]); + return open("a", attrs) + inner + ""; + } + const abs = href.startsWith("//") ? `https:${href}` : href; + if (/^https?:\/\/[^\s]+$/i.test(abs)) { + return open("a", [["href", abs], ["rel", "noopener noreferrer nofollow"], ["target", "_blank"]]) + inner + ""; + } + return inner; +} + +function safeDecode(s: string) { + try { + return decodeURIComponent(s); + } catch { + return s; + } +} + +function render(nodes: Node[], lang: string): string { + let out = ""; + for (const n of nodes) out += renderNode(n, lang); + return out; +} + +function renderNode(n: Node, lang: string): string { + if (n.nodeName === "#text") return escapeText((n as T.TextNode).value); + if (!isEl(n)) return ""; + const tag = n.tagName.toLowerCase(); + if (DROP_TAGS.has(tag)) return ""; + const cls = classes(n); + for (const c of cls) if (DROP_CLASSES.has(c) || c.startsWith("mbox-") || c.startsWith("box-")) return ""; + if (/display\s*:\s*none/i.test(attr(n, "style") ?? "")) return ""; + if (attr(n, "role") === "navigation") return ""; + if (n.namespaceURI === MATHML) { + if (!MATH_TAGS.has(tag)) return ""; + const attrs = n.attrs.filter((a) => MATH_ATTRS.has(a.name)).map((a): [string, string] => [a.name, a.value]); + return open(tag, attrs) + render(n.childNodes, lang) + ``; + } + // Images each carry their own licence and would load from upload.wikimedia.org: never kept. + if (tag === "figure" || tag === "img" || tag === "picture" || [...cls].some((c) => IMAGE_CLASSES.has(c))) return ""; + switch (tag) { + case "a": + return wikiLink(n, render(n.childNodes, lang), lang); + case "table": + if (!cls.has("wikitable")) return ""; + return `${render(n.childNodes, lang)}
`; + case "h1": + case "h2": + case "h3": + case "h4": + case "h5": + case "h6": { + const inner = render(n.childNodes, lang); + return emptyHtml(inner) ? "" : `

${inner}

`; + } + } + if (ALLOWED.has(tag)) { + const attrs: [string, string][] = []; + if (tag === "td" || tag === "th") { + for (const k of ["colspan", "rowspan"]) if (/^\d{1,3}$/.test(attr(n, k) ?? "")) attrs.push([k, attr(n, k)!]); + } + if (tag === "ol" && /^-?\d{1,6}$/.test(attr(n, "start") ?? "")) attrs.push(["start", attr(n, "start")!]); + if (VOID.has(tag)) return open(tag, attrs); + const inner = render(n.childNodes, lang); + if (emptyHtml(inner) && tag !== "td" && tag !== "th") return ""; + return open(tag, attrs) + inner + ``; + } + // Anything else (span, div, section, cite…): keep the contents, drop the element. + return render(n.childNodes, lang); +} + +/** Sanitise a fragment of Wikipedia HTML to the allowlist above. Output is safe to inject. */ +export function sanitizeWikiHtml(html: string, lang: string): string { + return tidy(render(parseFragment(html).childNodes, lang)); +} + +function tidy(html: string) { + return html.replace(/\n{3,}/g, "\n\n").trim(); +} + +/** Search excerpts: keep the matches as , everything else as text. */ +export function snippet(excerpt: string): { text: string; html: string } { + let text = ""; + let html = ""; + const walk = (nodes: Node[], inMatch: boolean) => { + for (const n of nodes) { + if (n.nodeName === "#text") { + const v = (n as T.TextNode).value; + text += v; + html += escapeText(v); + } else if (isEl(n)) { + const m = !inMatch && classes(n).has("searchmatch"); + if (m) html += ""; + walk(n.childNodes, inMatch || m); + if (m) html += ""; + } + } + }; + walk(parseFragment(excerpt).childNodes, false); + return { text, html }; +} + +function headingOf(n: Node): El | null { + if (!isEl(n)) return null; + if (/^h[2-6]$/.test(n.tagName)) return n; + if (n.tagName === "div" && classes(n).has("mw-heading")) { + return (n.childNodes.find((c) => isEl(c) && /^h[2-6]$/.test(c.tagName)) as El | undefined) ?? null; + } + return null; +} + +/** Split a parsed page at its top-level headings and sanitise each part. */ +export function splitArticle(html: string, lang: string): { lead: string; sections: (SectionInfo & { html: string })[] } { + const frag = parseFragment(html); + // The parser wraps everything in
. + let top: Node[] = frag.childNodes; + const wrapper = top.find((n) => isEl(n) && classes(n).has("mw-parser-output")); + if (wrapper && isEl(wrapper)) top = wrapper.childNodes; + // Parsoid output wraps sections in
: flatten them so headings are top level. + const flat: Node[] = []; + const flatten = (nodes: Node[]) => { + for (const n of nodes) (isEl(n) && n.tagName === "section" ? flatten(n.childNodes) : flat.push(n)); + }; + flatten(top); + + const parts: { info: SectionInfo | null; nodes: Node[] }[] = [{ info: null, nodes: [] }]; + const stack: SectionInfo[] = []; + for (const n of flat) { + const h = headingOf(n); + if (!h) { + parts[parts.length - 1].nodes.push(n); + continue; + } + const level = Number(h.tagName[1]); + while (stack.length && stack[stack.length - 1].level >= level) stack.pop(); + const info: SectionInfo = { + id: parts.length, + level, + heading: textOf(h).replace(/\s+/g, " ").trim(), + anchor: attr(h, "id") ?? "", + number: null, + parent: stack.length ? stack[stack.length - 1].id : 0, + }; + stack.push(info); + parts.push({ info, nodes: [] }); + } + const [lead, ...rest] = parts; + return { + lead: tidy(render(lead.nodes, lang)), + sections: rest.map((p) => ({ ...p.info!, html: tidy(render(p.nodes, lang)) })), + }; +} diff --git a/server/wikiMock.ts b/server/wikiMock.ts new file mode 100644 index 0000000..cba04b1 --- /dev/null +++ b/server/wikiMock.ts @@ -0,0 +1,748 @@ +/** + * A stand-in Wikipedia for tests and offline work (IE_WIKI=mock). `mockWikiFetch` answers every + * URL server/wiki.ts builds, in the shapes the real APIs return (docs/wikipedia.md §2), from a + * few short articles written for the purpose. The HTML imitates action=parse output, junk + * included (reference markers, infoboxes, navboxes, hatnotes, TemplateStyles), so the real + * sanitising and splitting code runs on it. Nothing here touches the network. + * + * Some titles misbehave on purpose: + * "Offline example" the fetch throws TypeError("fetch failed"), as with no network + * "Rate limited example" 429 with Retry-After: 0 + * "Slow article" every answer about it arrives after SLOW_MS + * "Hostile article" HTML full of attacks that must not survive sanitising + * A request is about a title when it is the summary or parse of it, a query whose titles include + * it, or a search whose query is exactly that title (any case). Typing a prefix of it is normal. + */ + +/** How long "Slow article" takes to answer: long enough for the UI to say Wikipedia is slow. */ +const SLOW_MS = 2500; + +type Block = string | string[]; // a paragraph, or a bulleted list +interface Fixture { + id: number; + description: string | null; + disambiguation?: boolean; + hatnote?: string; + /** Paragraph markup: [[Target]] or [[Target|text]] for links, [ref] for a reference marker. */ + lead: Block[]; + sections?: { heading: string; level?: 3; body: Block[] }[]; + /** Raw page HTML instead of generated, with its own summary extract. */ + html?: string; + extract?: string; + behaviour?: "offline" | "rate-limited" | "slow"; +} + +const FIXTURES: Record = { + "Fixed-point combinator": { + id: 1_200_101, + description: "Higher-order function Y for which Y f = f (Y f)", + hatnote: `For fixed points of functions in general, see Fixed point (mathematics).`, + lead: [ + `In mathematics and computer science, a fixed-point combinator (or fixpoint combinator) is a higher-order function that, given a function f, returns a fixed point of f: a value x with f(x) = x.[ref] In the untyped [[Lambda calculus|lambda calculus]] such combinators exist for every term, and the best known of them, the Y combinator, is usually credited to [[Haskell Curry]]. Because a fixed-point combinator lets an anonymous function call itself, it gives a way to express [[Recursion (computer science)|recursion]] in languages that have no built-in way for a function to name itself.`, + ], + sections: [ + { + heading: "Introduction", + body: [ + `A combinator is a function with no free variables. Applied to a function f, a fixed-point combinator fix produces a value that f maps to itself, so that fix f = f (fix f). Unfolding this equation again and again gives f (f (f …)), which is how the combinator builds up a recursive computation one step at a time.`, + ], + }, + { + heading: "Y combinator", + body: [ + `The Y combinator is defined in the [[Lambda calculus|lambda calculus]] as Y=λf.(λx.f(xx))(λx.f(xx))Y=\\lambda f.(\\lambda x.f(xx))(\\lambda x.f(xx)). It works by applying a term to a copy of itself, the same trick that makes (λx.x x)(λx.x x) reduce to itself forever. Under normal-order evaluation, Y g reduces to g (Y g) for any term g.[ref]`, + ], + }, + { + heading: "Verification", + level: 3, + body: [ + `Applying Y to a function g and performing one beta reduction gives (λx.g (x x)) (λx.g (x x)). A second beta reduction turns this into g ((λx.g (x x)) (λx.g (x x))), which is g applied to the previous term. The result is therefore equal to g (Y g), as the defining equation requires.`, + ], + }, + { + heading: "Other fixed-point combinators", + body: [ + `Infinitely many terms satisfy the fixed-point equation. Alan Turing gave one, often written Θ, that reduces to its fixed point directly rather than only being equal to it. Others can be generated mechanically, for instance by composing an existing combinator with suitable auxiliary terms.`, + ], + }, + { + heading: "Strict fixed-point combinator", + level: 3, + body: [ + `In a language that evaluates arguments before calling a function, the Y combinator never returns, because Y g keeps expanding before g is ever called. The Z combinator avoids this by wrapping the self-application in an extra abstraction, λv.x x v, which delays evaluation until an argument is supplied. It is the form usually written in languages such as JavaScript or Python.`, + ], + }, + { + heading: "Typed fixed-point combinators", + body: [ + `In the simply typed lambda calculus no fixed-point combinator can be written, since every typed term has a normal form and self-application cannot be given a type. Typed languages therefore usually supply fixed points as a primitive, such as a fix operator or recursive let bindings. Alternatively a recursive type can be introduced so that a value may be applied to itself, which makes the Y combinator typable again.`, + ], + }, + ], + }, + "Lambda calculus": { + id: 1_200_102, + description: "Mathematical-logic system based on functions", + lead: [ + `Lambda calculus (also written λ-calculus) is a formal system for expressing computation through function abstraction and application, using only variable binding and substitution. It was introduced by the mathematician [[Alonzo Church]] in the 1930s as part of an investigation into the foundations of mathematics.[ref] Although it has just three kinds of term, it is a universal model of computation, and recursion can be encoded in it with a [[Fixed-point combinator|fixed-point combinator]].`, + ], + sections: [ + { + heading: "History", + body: [ + `Church first presented the calculus in the early 1930s inside a larger logical system, which was soon found to be inconsistent. He then isolated its purely computational part, the untyped lambda calculus, and in 1936 used it to show that the Entscheidungsproblem has no solution. Around the same time Alan Turing reached the same result with his machines, and the two models were shown to define the same class of functions.`, + ], + }, + { + heading: "Informal description", + body: [ + `A lambda term is a variable, an abstraction λx.M that defines an anonymous function of x with body M, or an application M N of one term to another. Functions take a single argument; a function of several arguments is written as a chain of single-argument functions, a technique known as currying.`, + ], + }, + { + heading: "Motivation", + level: 3, + body: [ + `In ordinary mathematics a function is usually given a name before it is used, as in f(x) = x + 2. The lambda calculus drops the name and writes only the rule, λx.x + 2, so that functions can be passed around and returned like any other value. This anonymity is also why recursion needs a special device: a nameless function has no direct way to refer to itself.`, + ], + }, + { + heading: "Reduction", + body: [ + `Computation in the lambda calculus proceeds by reduction. Beta reduction replaces an application (λx.M) N with the body M in which N is substituted for x, while alpha conversion renames bound variables to avoid capture. A term that admits no further beta reduction is in normal form, and by the Church–Rosser theorem a term has at most one.`, + ], + }, + ], + }, + "Alonzo Church": { + id: 1_200_103, + description: "American mathematician and logician (1903–1995)", + lead: [ + `Alonzo Church (1903–1995) was an American mathematician and logician who made major contributions to mathematical logic and the theory of computation.[ref] He is best known for the [[Lambda calculus|lambda calculus]] and for the Church–Turing thesis, which proposes that his notion of effective calculability captures every mechanical procedure.`, + ], + sections: [ + { + heading: "Career", + body: [ + `Church spent most of his career at Princeton University, where his doctoral students included Alan Turing and Stephen Kleene. He later moved to the University of California, Los Angeles. He was also a founding editor of the Journal of Symbolic Logic.`, + ], + }, + ], + }, + "Haskell Curry": { + id: 1_200_104, + description: "American mathematician and logician (1900–1982)", + lead: [ + `Haskell Brooks Curry (1900–1982) was an American mathematician and logician known for his work in combinatory logic.[ref] The programming language Haskell and the technique of currying are both named after him, although currying had been described earlier by others.`, + ], + sections: [ + { + heading: "Work", + body: [ + `Curry developed combinatory logic as a way of doing without bound variables, building every function from a small set of basic combinators. He is associated with the [[Fixed-point combinator|Y combinator]] and with the observation, later called the Curry–Howard correspondence, that proofs and programs share a common structure.`, + ], + }, + ], + }, + "Recursion (computer science)": { + id: 1_200_105, + description: "Use of functions that call themselves", + lead: [ + `In computer science, recursion is a method of solving a problem in which the solution depends on solutions to smaller instances of the same problem.[ref] Most programming languages support it by allowing a function to call itself from within its own code. Where functions cannot refer to themselves by name, a [[Fixed-point combinator|fixed-point combinator]] can provide the same effect.`, + ], + sections: [ + { + heading: "Base case", + body: [ + `A recursive definition needs at least one base case, an input whose answer is given directly, so that the chain of calls eventually stops. Without one the function calls itself until the program runs out of memory for its call stack.`, + ], + }, + { + heading: "Tail recursion", + body: [ + `A call is in tail position when nothing remains to be done after it returns. Many compilers turn such tail calls into jumps, so that a tail-recursive function runs in constant stack space, like a loop.`, + ], + }, + ], + }, + Octopus: { + id: 1_200_106, + description: "Soft-bodied eight-limbed order of molluscs", + hatnote: `For other uses, see Octopus (disambiguation).`, + lead: [ + `An octopus (plural: octopuses) is a soft-bodied, eight-limbed mollusc of the order Octopoda. Together with squids, cuttlefish and nautiloids it belongs to the class Cephalopoda, the [[Cephalopod|cephalopods]].[ref] Octopuses have no internal or external skeleton, which lets them squeeze through very small openings.`, + ], + sections: [ + { + heading: "Etymology and pluralisation", + body: [ + `The word comes through scientific Latin from the Greek oktōpous, meaning "eight-footed". In English the standard plural is octopuses. The form octopi arose from the mistaken belief that the word is a Latin second-declension noun, while octopodes follows the Greek.`, + ], + }, + { + heading: "Description", + body: [ + `An octopus has a bulbous mantle containing its organs, a head with two prominent eyes, and eight arms lined with suckers. Its skin contains specialised cells that let it change colour and texture within a fraction of a second.`, + ], + }, + { + heading: "Size", + level: 3, + body: [ + `Species range widely in size. The giant Pacific octopus is often cited as the largest, with adults commonly weighing around 15 kilograms, while the smallest species are only a few centimetres long when fully grown.`, + ], + }, + { + heading: "Nervous system and senses", + level: 3, + body: [ + `Octopuses have a large and unusual nervous system, with roughly two thirds of their neurons in the arms rather than the brain. Each arm can carry out some actions with a degree of independence. Their eyes are acute, yet most species are thought to be colour-blind.[ref]`, + ], + }, + { + heading: "Intelligence", + body: [ + `Octopuses are widely regarded as the most intelligent invertebrates. In laboratory studies they have solved mazes, unscrewed jar lids and learned by watching other octopuses. Some have been seen carrying coconut shells to use later as shelter.`, + ], + }, + ], + }, + Cephalopod: { + id: 1_200_107, + description: "Class of mollusks", + lead: [ + `A cephalopod is any member of the molluscan class Cephalopoda, which includes the squid, the cuttlefish, the nautilus and the [[Octopus|octopus]].[ref] Cephalopods are marine animals with bilateral symmetry, a prominent head, and a set of arms or tentacles derived from the ancestral mollusc foot.`, + ], + sections: [ + { + heading: "Nervous system", + body: [ + `Cephalopods have the largest nervous systems of any invertebrates, and many show complex learned behaviour. Their eyes form images in a way that closely parallels the vertebrate eye, although the two evolved independently.`, + ], + }, + ], + }, + "Hoyle state": { + id: 1_200_108, + description: "Excited state of the carbon-12 nucleus", + lead: [ + `The Hoyle state is an excited, spin-0 resonant state of the [[Carbon-12|carbon-12]] nucleus, lying about 7.65 MeV above the ground state. It is named after [[Fred Hoyle]], who argued that such a state must exist for the [[Triple-alpha process|triple-alpha process]] to produce the amount of carbon observed in the universe.[ref]`, + ], + sections: [ + { + heading: "Prediction", + body: [ + `Hoyle reasoned that without a resonance near the combined energy of beryllium-8 and helium-4, stars would make far too little carbon. In 1953 he persuaded experimenters at the California Institute of Technology to look for it, and the state was found close to the energy he had estimated.`, + ], + }, + { + heading: "Structure", + body: [ + `The Hoyle state is thought to be a loosely bound arrangement of three alpha particles rather than a compact nucleus like the ground state. Its structure is still studied, including by lattice calculations from first principles.`, + ], + }, + ], + }, + "Carbon-12": { + id: 1_200_109, + description: "Most abundant isotope of carbon", + lead: [ + `Carbon-12 (12C) is the more abundant of the two stable isotopes of carbon, making up about 98.9 percent of the element on Earth. Its nucleus contains six protons and six neutrons.[ref] Since 1961 it has been the reference for the atomic mass scale, on which one atom of carbon-12 has a mass of exactly 12 daltons.`, + ], + sections: [ + { + heading: "Formation", + body: [ + `Nearly all carbon-12 in the universe is made inside stars by the [[Triple-alpha process|triple-alpha process]], in which three helium-4 nuclei fuse. The reaction runs at a useful rate only because carbon-12 has an excited state at just the right energy, the [[Hoyle state]].`, + ], + }, + ], + }, + "Fred Hoyle": { + id: 1_200_110, + description: "British astronomer (1915–2001)", + lead: [ + `Sir Fred Hoyle (1915–2001) was an English astronomer who did influential work on how chemical elements are formed in stars.[ref] In 1953 he predicted that carbon-12 must have an excited state near 7.7 MeV, a prediction soon confirmed by experiment and now known as the [[Hoyle state]].`, + ], + sections: [ + { + heading: "Steady-state theory", + body: [ + `Hoyle was a leading advocate of the steady-state model of the universe, in which new matter is continuously created as the universe expands. He coined the name "Big Bang" for the rival theory in a 1949 radio broadcast, and never fully accepted it.`, + ], + }, + ], + }, + "Triple-alpha process": { + id: 1_200_111, + description: "Nuclear fusion of helium into carbon in stars", + lead: [ + `The triple-alpha process is a set of nuclear fusion reactions by which three helium-4 nuclei (alpha particles) are turned into [[Carbon-12|carbon-12]].[ref] It takes place in the cores of stars that have used up their hydrogen and reached temperatures of around 100 million kelvin.`, + ], + sections: [ + { + heading: "Reactions", + body: [ + `Two helium-4 nuclei first fuse into beryllium-8, which is so unstable that it decays again in about 10−16 seconds. In the dense core of a star a third helium nucleus occasionally strikes the beryllium-8 before it decays, forming carbon-12 in the excited [[Hoyle state]], which can then settle to the ground state.`, + ], + }, + ], + }, + Mercury: { + id: 1_200_112, + description: "Topics referred to by the same term", + disambiguation: true, + lead: [ + `Mercury commonly refers to:`, + [ + `[[Mercury (planet)]], the planet closest to the Sun`, + `[[Mercury (element)]], a metallic chemical element with the symbol Hg`, + `[[Mercury (mythology)]], a Roman god`, + ], + ], + sections: [{ heading: "People", body: [[`[[Freddie Mercury]] (1946–1991), British singer of the rock band Queen`]] }], + }, + "Mercury (planet)": { + id: 1_200_113, + description: "First planet from the Sun", + lead: [ + `Mercury is the smallest planet in the Solar System and the one closest to the Sun, completing an orbit every 88 days.[ref] It has almost no atmosphere, so its surface swings from about −180 °C at night to over 400 °C during the day.`, + ], + sections: [ + { + heading: "Orbit", + body: [ + `Mercury's orbit is the most eccentric of any planet in the Solar System. A small extra precession of its perihelion, which Newtonian gravity could not explain, was one of the first confirmations of general relativity.`, + ], + }, + ], + }, + "Mercury (element)": { + id: 1_200_114, + description: "Chemical element with atomic number 80", + lead: [ + `Mercury is a chemical element with the symbol Hg and atomic number 80. It is the only metal that is liquid at standard temperature and pressure.[ref] Mercury and many of its compounds are toxic, and its use in thermometers has largely been phased out.`, + ], + }, + "Mercury (mythology)": { + id: 1_200_115, + description: "Roman god of commerce and messages", + lead: [ + `Mercury is a major god of Roman religion, associated with commerce, communication, travellers and luck.[ref] He was identified with the Greek god Hermes and is often shown with winged sandals and a winged hat.`, + ], + }, + "Freddie Mercury": { + id: 1_200_116, + description: "British singer (1946–1991)", + lead: [ + `Freddie Mercury (born Farrokh Bulsara; 1946–1991) was a British singer and songwriter, famous as the lead vocalist of the rock band Queen.[ref] He was known for his wide vocal range and his flamboyant stage presence.`, + ], + }, + "Slow article": { + id: 1_200_117, + description: "Test article whose answers arrive slowly", + behaviour: "slow", + lead: [ + `The slow article is a short test page whose every answer takes a few seconds to arrive. It exists so that the interface can show what it does while Wikipedia is slow. It links to the [[Octopus|octopus]] article.`, + ], + sections: [ + { + heading: "Details", + body: [`Nothing else about it is unusual. Once fetched it is cached like any other article, so opening it a second time is immediate.`], + }, + ], + }, + "Offline example": { + id: 1_200_118, + description: "Test title for which Wikipedia cannot be reached", + behaviour: "offline", + lead: [`Never served: every request about this title fails as if the network were down.`], + }, + "Rate limited example": { + id: 1_200_119, + description: "Test title for which Wikipedia asks the client to slow down", + behaviour: "rate-limited", + lead: [`Never served: every request about this title is answered with 429 Too Many Requests.`], + }, + "Hostile article": { + id: 1_200_120, + description: "Test page whose markup must be sanitised", + extract: "The hostile article is a test page. Its markup tries every trick a sanitiser has to catch.", + lead: [], + html: `
+ + + +

The hostile article is a test page. Its markup tries every trick a sanitiser has to catch. It links to the Octopus article and to an external page.

+

Links that must lose their targets: click, mixed case, encoded colon, tab, leading space, data, vbscript.

+ +svg link +

Attacks <img src=x onerror="window.__pwned=9">

+

Math: xyz.

+
+ + +
VectorStatus
table backgroundremoved
+
A div with a click handler that covers the page.
+

a pictureForged attributes: octopus again, protocol-relative, anchor, a title that looks like a script URL.

+
detailstoggle
+ +marquee +

Text with <script>window.__pwned=19</script> written as escaped text, which must stay text.

+ +
`, + }, +}; + +/** Redirects to fixtures, as the wiki has them. */ +const REDIRECTS: Record = { + "Fixed point combinator": "Fixed-point combinator", + Octopuses: "Octopus", + Cephalopods: "Cephalopod", +}; + +const revisionOf = (f: Fixture) => 1_250_000_000 + f.id; +const wikidataOf = (f: Fixture) => `Q${90_000_000 + f.id}`; +const dbKey = (title: string) => title.replace(/ /g, "_"); + +// ---- rendering fixtures as action=parse output ---- + +const escape = (s: string) => s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +const REF = (n: number) => + `[${n}]`; + +function inline(markup: string, refs: { n: number }): string { + return markup + .replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (_, t: string, text?: string) => `${text ?? t}`) + .replace(/\[ref\]/g, () => REF(++refs.n)); +} + +function blocks(body: Block[], refs: { n: number }): string { + return body.map((b) => (typeof b === "string" ? `

${inline(b, refs)}\n

` : `
    ${b.map((li) => `
  • ${inline(li, refs)}
  • `).join("\n")}
`)).join("\n"); +} + +function pageHtml(title: string, f: Fixture): string { + if (f.html) return f.html; + const refs = { n: 0 }; + const parts = [`
`]; + if (f.description) parts.push(``); + if (f.hatnote) { + parts.push(``); + parts.push(``); + } + parts.push(`

\n

`); + if (f.disambiguation) { + parts.push(blocks(f.lead, refs)); + } else { + parts.push( + `
${escape(title)}
Summary${escape(f.description ?? "")}
`, + ); + parts.push(blocks(f.lead, refs)); + } + if (f.sections?.length) parts.push(``); + for (const s of f.sections ?? []) { + const h = s.level === 3 ? "h3" : "h2"; + parts.push(`
<${h} id="${escape(dbKey(s.heading))}">${escape(s.heading)}
`); + parts.push(blocks(s.body, refs)); + } + if (f.disambiguation) { + parts.push( + ``, + ); + } else { + const links = leadLinks(f).map((t) => `
  • ${escape(t)}
  • `); + parts.push( + ``, + ); + } + if (refs.n) { + const notes = Array.from({ length: refs.n }, (_, i) => `
  • A source.
  • `); + parts.push(`
      ${notes.join("")}
    `); + } + parts.push(`
    `); + return parts.join("\n"); +} + +/** Link targets written in the lead, in order. */ +function leadLinks(f: Fixture): string[] { + const text = f.lead.flat().join(" "); + return [...new Set([...text.matchAll(/\[\[([^\]|]+)/g)].map((m) => m[1]))]; +} + +/** Main-namespace link targets anywhere on the page, as generator=links sees them. */ +function pageLinks(title: string, f: Fixture): string[] { + const out = new Set(); + for (const m of pageHtml(title, f).matchAll(/href="\/wiki\/([^"#]+)/g)) { + const t = safeDecode(m[1]).replace(/_/g, " "); + if (!/^[^:]+:\S/.test(t)) out.add(t); + } + return [...out]; +} + +function safeDecode(s: string) { + try { + return decodeURIComponent(s); + } catch { + return s; + } +} + +/** Plain text of the given blocks: links as their text, tags and reference markers removed. */ +function plain(body: Block[]): string { + return body + .flat() + .join("\n") + .replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (_, t: string, text?: string) => text ?? t) + .replace(/\[ref\]/g, "") + .replace(//g, "") + .replace(/<[^>]+>/g, "") + .replace(/&/g, "&"); +} + +const extractOf = (f: Fixture) => f.extract ?? plain(f.lead.filter((b) => typeof b === "string")); +const fullText = (f: Fixture) => [extractOf(f), ...(f.html ? [] : (f.sections ?? []).map((s) => plain(s.body)))].join("\n"); + +function tocdata(title: string, f: Fixture) { + let h2 = 0; + let h3 = 0; + return (f.sections ?? []).map((s, i) => { + const level = s.level === 3 ? 3 : 2; + if (level === 2) (h2++, (h3 = 0)); + else h3++; + return { + tocLevel: level - 1, + hLevel: level, + line: escape(s.heading), + number: level === 2 ? String(h2) : `${h2}.${h3}`, + index: String(i + 1), + fromTitle: dbKey(title), + codepointOffset: null, + anchor: dbKey(s.heading), + linkAnchor: dbKey(s.heading), + }; + }); +} + +// ---- titles ---- + +/** MediaWiki's normalisation for the main namespace: underscores to spaces, first letter up. */ +function normalise(t: string): string { + const s = t.replace(/_/g, " ").replace(/\s+/g, " ").trim(); + return s.charAt(0).toUpperCase() + s.slice(1); +} + +function find(title: string): { title: string; f: Fixture; from?: string } | null { + const t = normalise(title); + const target = REDIRECTS[t] ?? t; + const f = FIXTURES[target]; + return f ? { title: target, f, ...(REDIRECTS[t] ? { from: t } : {}) } : null; +} + +/** The titles a request is about, for the misbehaving fixtures. */ +function subjects(url: URL): string[] { + const p = url.searchParams; + if (url.pathname.startsWith("/api/rest_v1/page/summary/")) return [safeDecode(url.pathname.slice("/api/rest_v1/page/summary/".length))]; + if (url.pathname.startsWith("/w/rest.php/v1/search/")) { + const q = (p.get("q") ?? "").trim().toLowerCase(); + return Object.keys(FIXTURES).filter((t) => t.toLowerCase() === q); + } + if (p.get("action") === "parse") return [p.get("page") ?? ""]; + return (p.get("titles") ?? "").split("|"); +} + +// ---- answers ---- + +const json = (v: unknown, status = 200, headers: Record = {}) => + new Response(JSON.stringify(v), { status, headers: { "content-type": "application/json; charset=utf-8", ...headers } }); + +function summary(url: URL): Response { + const raw = safeDecode(url.pathname.slice("/api/rest_v1/page/summary/".length)); + const hit = find(raw); + if (!hit) { + return json( + { type: "https://mediawiki.org/wiki/HyperSwitch/errors/not_found", title: "Not found.", method: "get", detail: "Page or revision not found.", uri: `/${url.host}/v1/page/summary/${raw}` }, + 404, + { "content-type": "application/problem+json" }, + ); + } + // The real endpoint answers a redirect with 302 to the target; fetch follows it, so the + // client only ever sees the target's summary. + const { title, f } = hit; + const extract = extractOf(f); + const page = `${url.origin}/wiki/${encodeURIComponent(dbKey(title))}`; + return json({ + type: f.disambiguation ? "disambiguation" : "standard", + title: dbKey(title), + displaytitle: `${escape(title)}`, + namespace: { id: 0, text: "" }, + wikibase_item: wikidataOf(f), + titles: { canonical: dbKey(title), normalized: title, display: `${escape(title)}` }, + pageid: f.id, + lang: "en", + dir: "ltr", + revision: String(revisionOf(f)), + tid: "00000000-0000-11f0-0000-000000000000", + timestamp: "2026-11-01T12:00:00Z", + ...(f.description ? { description: f.description, description_source: "local" } : {}), + content_urls: { + desktop: { page, revisions: `${page}?action=history`, edit: `${page}?action=edit`, talk: `${url.origin}/wiki/Talk:${encodeURIComponent(dbKey(title))}` }, + mobile: { page: page.replace(".wikipedia.org", ".m.wikipedia.org"), revisions: "", edit: "", talk: "" }, + }, + extract, + extract_html: extract + .split("\n") + .map((p) => `

    ${escape(p)}

    `) + .join(""), + }); +} + +/** One page object as action=query returns it, with what `prop` asked for. */ +function queryPage(title: string, props: string[]) { + const f = FIXTURES[title]; + if (!f) return { ns: 0, title, missing: true }; + const pageprops = { ...(f.disambiguation ? { disambiguation: "" } : {}), wikibase_item: wikidataOf(f) }; + return { + pageid: f.id, + ns: 0, + title, + ...(props.includes("description") && f.description ? { description: f.description, descriptionsource: "local" } : {}), + ...(props.includes("pageprops") ? { pageprops } : {}), + ...(props.includes("extracts") ? { extract: extractOf(f) } : {}), + ...(props.includes("info") ? { contentmodel: "wikitext", pagelanguage: "en", touched: "2026-11-01T12:00:00Z", lastrevid: revisionOf(f), length: fullText(f).length } : {}), + }; +} + +function query(url: URL): Response { + const p = url.searchParams; + const props = (p.get("prop") ?? "").split("|"); + const asked = (p.get("titles") ?? "").split("|").filter(Boolean); + const normalized: { fromencoded: false; from: string; to: string }[] = []; + const redirects: { from: string; to: string }[] = []; + const ended: string[] = []; + for (const t of asked) { + const n = normalise(t); + if (n !== t) normalized.push({ fromencoded: false, from: t, to: n }); + const to = REDIRECTS[n]; + if (to) redirects.push({ from: n, to }); + if (!ended.includes(to ?? n)) ended.push(to ?? n); + } + if (p.get("generator") === "links") { + // The links on the asked page(s), each as a page of its own. + const linked = ended.flatMap((t) => (FIXTURES[t] ? pageLinks(t, FIXTURES[t]) : [])); + if (!linked.length) return json({ batchcomplete: true }); + return json({ batchcomplete: true, query: { ...(redirects.length ? { redirects } : {}), pages: linked.map((t) => queryPage(t, props)) } }); + } + return json({ + batchcomplete: true, + query: { + ...(normalized.length ? { normalized } : {}), + ...(redirects.length ? { redirects } : {}), + pages: ended.map((t) => queryPage(t, props)), + }, + }); +} + +function parse(url: URL): Response { + const asked = url.searchParams.get("page") ?? ""; + const hit = find(asked); + if (!hit) { + return json( + { error: { code: "missingtitle", info: "The page you specified doesn't exist.", docref: "See https://en.wikipedia.org/w/api.php for API usage." }, servedby: "mw-api-mock" }, + 200, + { "mediawiki-api-error": "missingtitle" }, + ); + } + const { title, f, from } = hit; + return json({ + parse: { + ...(from ? { redirects: [{ from, to: title }] } : {}), + title, + pageid: f.id, + revid: revisionOf(f), + displaytitle: `${escape(title)}`, + text: pageHtml(title, f), + tocdata: { sections: f.html ? [] : tocdata(title, f) }, + properties: { ...(f.disambiguation ? { disambiguation: "" } : {}), wikibase_item: wikidataOf(f) }, + }, + }); +} + +/** search/title: case-insensitive prefix of the title or of any word in it, redirects included. */ +function searchTitle(url: URL): Response { + const q = (url.searchParams.get("q") ?? "").replace(/\s+/g, " ").trim().toLowerCase(); + const limit = Number(url.searchParams.get("limit") ?? 10) || 10; + const names = [...Object.keys(FIXTURES), ...Object.keys(REDIRECTS)]; + const rank = (name: string) => { + const n = name.toLowerCase(); + if (n.startsWith(q)) return 0; + return [" ", "(", "-"].some((sep) => n.includes(sep + q)) ? 1 : -1; + }; + const seen = new Set(); + const pages = names + .map((name) => ({ name, r: q ? rank(name) : -1 })) + .filter((x) => x.r >= 0) + .sort((a, b) => a.r - b.r) + .flatMap(({ name }) => { + const title = REDIRECTS[name] ?? name; + if (seen.has(title)) return []; + seen.add(title); + const f = FIXTURES[title]; + return [{ id: f.id, key: dbKey(title), title, excerpt: escape(title), matched_title: REDIRECTS[name] ? name : null, anchor: null, description: f.description, thumbnail: null }]; + }); + return json({ pages: pages.slice(0, limit) }); +} + +/** search/page: every word of the query in the title or text; the excerpt marks the matches. */ +function searchPage(url: URL): Response { + const q = (url.searchParams.get("q") ?? "").replace(/\bintitle:/gi, "").replace(/"/g, " "); + const limit = Number(url.searchParams.get("limit") ?? 10) || 10; + const words = q.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean); + if (!words.length) return json({ pages: [] }); + const pages = Object.entries(FIXTURES).flatMap(([title, f]) => { + const text = fullText(f); + const hay = `${title}\n${text}`.toLowerCase(); + if (!words.every((w) => hay.includes(w))) return []; + const sentence = text.split(/(?<=\.)\s+/).find((s) => words.some((w) => s.toLowerCase().includes(w))) ?? text.slice(0, 150); + const re = new RegExp(`(${words.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`, "giu"); + const excerpt = escape(sentence).replace(re, `$1`); + return [{ id: f.id, key: dbKey(title), title, excerpt, matched_title: null, anchor: null, description: f.description, thumbnail: null }]; + }); + return json({ pages: pages.slice(0, limit) }); +} + +function wait(ms: number, signal?: AbortSignal | null) { + return new Promise((done, fail) => { + const timer = setTimeout(done, ms); + signal?.addEventListener("abort", () => (clearTimeout(timer), fail(signal.reason)), { once: true }); + }); +} + +/** + * A fetch that answers like Wikipedia; `slowMs` is how long "Slow article" takes. `bulkMs` delays + * every request made for background work (those carry maxlag), so a test can watch a bulk link + * pass make progress and cancel it, as it would against the real, rate-limited Wikipedia. + */ +export function makeMockWikiFetch(slowMs = SLOW_MS, bulkMs = 0): typeof fetch { + return (async (input: string | URL | Request, init?: RequestInit) => { + const signal = init?.signal; + signal?.throwIfAborted(); + const url = new URL(input instanceof Request ? input.url : String(input)); + if (bulkMs && url.searchParams.has("maxlag")) await wait(bulkMs, signal); + const about = subjects(url).map((t) => find(t)?.f.behaviour); + if (about.includes("offline")) throw new TypeError("fetch failed"); + if (about.includes("rate-limited")) { + return json({ httpCode: 429, httpReason: "Too Many Requests" }, 429, { "retry-after": "0" }); + } + if (about.includes("slow")) await wait(slowMs, signal); + const p = url.searchParams; + if (url.pathname.startsWith("/api/rest_v1/page/summary/")) return summary(url); + if (url.pathname === "/w/rest.php/v1/search/title") return searchTitle(url); + if (url.pathname === "/w/rest.php/v1/search/page") return searchPage(url); + if (url.pathname === "/w/api.php" && p.get("action") === "parse") return parse(url); + if (url.pathname === "/w/api.php" && p.get("action") === "query") return query(url); + return json({ error: { code: "badrequest", info: `The mock does not answer ${url.pathname}` } }, 400); + }) as typeof fetch; +} + +export const mockWikiFetch: typeof fetch = makeMockWikiFetch(); diff --git a/server/wikiRoutes.ts b/server/wikiRoutes.ts new file mode 100644 index 0000000..1851747 --- /dev/null +++ b/server/wikiRoutes.ts @@ -0,0 +1,133 @@ +/** + * HTTP routes over server/wiki.ts: + * + * GET /api/wiki/lookup?titles=A|B|C or POST { titles: string[] } (≤ 200 titles) + * GET /api/wiki/suggest?q=Brou&limit=8 (q ≤ 200 chars) + * GET /api/wiki/search?q=fixed+point&limit=10 (q ≤ 300 chars) + * GET /api/wiki/summary?title=Octopus[&cached=1] + * GET /api/wiki/article?title=Octopus[&full=1] + * GET /api/wiki/section?title=Octopus&id=3 + * GET /api/wiki/senses?title=Set the articles a disambiguation page lists + * + * summary &cached=1 answers from the server's cache only, never waiting on Wikipedia (for model + * prompts): 404 { ok: false, reason: "uncached" } when it has none. article &full=1 returns every + * section's html with the section list, so a whole article is one request. + * Add &bulk=1 for background work: it queues behind interactive requests and sends maxlag. + * Answers: 200 { ok: true, ... }; 400 bad input; 404 { ok: false, reason: "missing" }; + * 503 { ok: false, reason, retryAfter } when Wikipedia is unreachable or asked us to wait. + * A request the browser abandons (a superseded keystroke) is dropped from the queue unsent. + * With IE_WIKI=off the server wires in wikiOff instead: every route answers 503 reason "off". + */ +import type { IncomingMessage, ServerResponse } from "node:http"; +import { HttpError, abortOnClose, readJson, sendJson as send } from "./util"; +import type { CallOpts, Result, Uncached, WikiClient } from "./wiki"; + +const MAX_TITLES = 200; +const MAX_TITLE = 255; +const MAX_BODY = 64 * 1024; + +const bad = (message: string) => new HttpError(400, message); + +function reply(res: ServerResponse, r: Result | Uncached, key: string) { + if (r.ok) return send(res, 200, { ok: true, cached: r.cached, ...(r.stale ? { stale: true } : {}), [key]: r.value }); + if (r.reason === "missing" || r.reason === "uncached") return send(res, 404, r); + if (r.reason === "aborted") return; // the browser has gone + return send(res, 503, r, r.retryAfter ? { "retry-after": String(r.retryAfter) } : {}); +} + +function text(url: URL, name: string, max: number, required = true): string { + const v = (url.searchParams.get(name) ?? "").trim(); + if (!v && required) throw bad(`${name} is required`); + if (v.length > max) throw bad(`${name} is longer than ${max} characters`); + return v; +} + +function int(url: URL, name: string, fallback: number, lo: number, hi: number): number { + const raw = url.searchParams.get(name); + if (raw === null || raw === "") return fallback; + const n = Number(raw); + if (!Number.isInteger(n) || n < lo || n > hi) throw bad(`${name} must be an integer from ${lo} to ${hi}`); + return n; +} + +async function readTitles(req: IncomingMessage, url: URL): Promise { + let titles: unknown; + if (req.method === "POST") { + let size = 0; + const chunks: Buffer[] = []; + for await (const c of req) { + size += (c as Buffer).length; + if (size > MAX_BODY) throw bad("body too large"); + chunks.push(c as Buffer); + } + try { + titles = (JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}") as { titles?: unknown }).titles; + } catch { + throw bad("body is not JSON"); + } + } else { + titles = text(url, "titles", MAX_TITLES * (MAX_TITLE + 1)).split("|"); + } + if (!Array.isArray(titles) || !titles.every((t) => typeof t === "string")) throw bad("titles must be a list of strings"); + if (titles.length > MAX_TITLES) throw bad(`at most ${MAX_TITLES} titles`); + if (titles.some((t) => t.length > MAX_TITLE)) throw bad(`a title is longer than ${MAX_TITLE} characters`); + return titles; +} + +/** Route /api/wiki/*. Returns false for any other path. */ +export function wikiRoutes(client: () => WikiClient) { + return async function handle(req: IncomingMessage, res: ServerResponse, url: URL): Promise { + if (!url.pathname.startsWith("/api/wiki/")) return false; + const route = url.pathname.slice("/api/wiki/".length); + const allowed = route === "lookup" ? ["GET", "POST"] : ["GET"]; + if (!allowed.includes(req.method ?? "GET")) { + send(res, 405, { ok: false, message: `use ${allowed.join(" or ")}` }, { allow: allowed.join(", ") }); + return true; + } + try { + const w = client(); + const o: CallOpts = { priority: url.searchParams.get("bulk") === "1" ? "bulk" : "interactive", signal: abortOnClose(res) }; + switch (route) { + case "lookup": { + const results = await w.lookup(await readTitles(req, url), o); + send(res, 200, { ok: true, results }); + return true; + } + case "suggest": + reply(res, await w.suggest(text(url, "q", 200), int(url, "limit", 8, 1, 20), o), "suggestions"); + return true; + case "search": + reply(res, await w.search(text(url, "q", 300), int(url, "limit", 10, 1, 50), o), "results"); + return true; + case "summary": { + const title = text(url, "title", MAX_TITLE); + reply(res, url.searchParams.get("cached") === "1" ? await w.summary(title, { ...o, cacheOnly: true }) : await w.summary(title, o), "summary"); + return true; + } + case "article": + reply(res, await w.article(text(url, "title", MAX_TITLE), { ...o, sections: url.searchParams.get("full") === "1" }), "article"); + return true; + case "section": + reply(res, await w.section(text(url, "title", MAX_TITLE), int(url, "id", 0, 0, 10_000), o), "section"); + return true; + case "senses": + reply(res, await w.senses(text(url, "title", MAX_TITLE), o), "senses"); + return true; + default: + send(res, 404, { ok: false, message: `no route /api/wiki/${route}` }); + return true; + } + } catch (e) { + if (e instanceof HttpError) send(res, e.status, { ok: false, message: e.message }); + else send(res, 500, { ok: false, message: (e as Error).message ?? String(e) }); + return true; + } + }; +} + +/** IE_WIKI=off: the routes exist, so the UI can tell "turned off" from "unreachable", but none works. */ +export async function wikiOff(_req: IncomingMessage, res: ServerResponse, url: URL): Promise { + if (!url.pathname.startsWith("/api/wiki/")) return false; + send(res, 503, { ok: false, reason: "off", message: "Wikipedia is turned off on this server (IE_WIKI=off)." }); + return true; +}