// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Deterministic canonical-row emission shared by WOF GeoJSON adapters. */ import { adminRunJoinForCountry, isLargestFirstSystem, lineJoinForCountry, type AddressScript, } from "@mailwoman/codex/address/layouts" import type { ComponentTag } from "@mailwoman/codex/component" import { isPresent } from "@mailwoman/core/values/objects" import { textScript } from "@mailwoman/recognizer/query-shape/script-run" import type { RowSampler, SampledRow } from "#adapters/wof/sample" import { formatCorpusRow } from "#surfaces/corpus-row" import type { AdapterOptions, CanonicalRow } from "#types" import { nameValues, normalizeNameKey, type WOFRecord } from "#utils" /** * The order an admin hierarchy is written in, smallest unit first. * * A country that writes largest-first reverses it. */ const HIERARCHY_ORDER: readonly ComponentTag[] = [ "postcode", "dependent_locality", "locality", "subregion", "region", "country", ] /** * Render an admin-hierarchy variant: the components it contains, in hierarchy order, * joined the way the country joins a line. * * This adapter emits a gazetteer query. * It follows the gazetteer path without a postal layout. * * A country whose postal layout drops the region would collapse `Paris, Île-de-France` back into `Paris`. */ export function renderHierarchy( components: Partial>, country: string ): { raw: string; components: Partial> } | null { const script = hierarchyScript(Object.values(components).filter(isPresent)) // A largest-first country writes its own script largest first and a romanized address // smallest first: `東京都渋谷区` against `Shibuya, Tokyo, Japan`. const order = isLargestFirstSystem(country, script) ? [...HIERARCHY_ORDER].toReversed() : HIERARCHY_ORDER const present: Partial> = {} const parts: Array<{ tag: ComponentTag; value: string }> = [] for (const tag of order) { const value = components[tag]?.trim() if (!value) continue present[tag] = value parts.push({ tag, value }) } if (!parts.length) return null const lineJoin = lineJoinForCountry(country, script) const adminJoin = adminRunJoinForCountry(country, script) // Two adjacent admin units share a line and take the admin-run join. // The postcode and the country sit on lines of their own. const raw = parts .map((part, index) => { if (!index) return part.value const shared = ADMIN_RUN_TAGS.has(part.tag) && ADMIN_RUN_TAGS.has(parts[index - 1]!.tag) return (shared ? adminJoin : lineJoin) + part.value }) .join("") return { raw, components: present } } /** * The hierarchy tags a layout prints together on its admin line. */ const ADMIN_RUN_TAGS: ReadonlySet = new Set(["dependent_locality", "locality", "subregion", "region"]) /** * Scripts whose addresses join their units without a separator or with a single space. */ const CJK_SCRIPTS: ReadonlySet = new Set(["Hani", "Hira", "Kana", "Hang"]) /** * Chooses the join script for a hierarchy from the names being joined. * * A country's local join, such as China's empty separator, belongs to names written in its CJK script. * A romanized or other non-CJK name joined that way runs into its neighbor (`HEBEICHAOZHITUN`). * * A part with no script letters, such as a number, leaves the choice to the other parts. */ function hierarchyScript(parts: readonly string[]): AddressScript { const allCJK = parts.every((part) => { const script = textScript(part) return script === "Zyyy" || CJK_SCRIPTS.has(script) }) return allCJK ? "local" : "latin" } /** * Display name for the country, keyed by ISO 3166-1 alpha-2. * * Must be the **OpenCage-canonical** surface form: the `address-formatter` library expands some * country names en route to its output (e.g. `"United States"` → `"United States of America"`). * If `components.country` and the formatted `raw` disagree, alignment will fail downstream. * * The canonical form keeps the two in lockstep. * * Phase 1 US + FR only. * Extend as new locales come online. * * A missing country uses the country row's `wof:name`; this preserves the * alignment risk for non-canonicalized names. */ export const COUNTRY_DISPLAY_NAME: Record = { US: "United States of America", FR: "France", } /** * BCP-47 locale defaulting for the corpus row's `locale` field. * * Defaulted by country. */ export const LOCALE_BY_COUNTRY: Record = { US: "en-US", FR: "fr-FR", } export interface WOFVariantSpec { suffix: string components: Partial> /** * Render this variant as an admin hierarchy rather than as a postal address. * * A hierarchy variant is a query — `Paris`, then `Paris, Île-de-France`, then * `Paris, Île-de-France, France` — and several of its steps are not addresses at all. * France's postal layout has no region, so rendering `{ locality, region }` through * it prints `Paris` and the whole variant collapses into the one below it. * * So the hierarchy is joined in its own order: smallest unit first, or largest first * for the systems that write that way, with the country's own separator. */ hierarchy?: boolean /** * The country whose hierarchy order and line join render this variant, * when it differs from the record's own. */ layoutCountry?: string } export interface NameSlotOptions { /** * Canonical surface for the record's own `"default"` slot. * * The admin adapter substitutes the OpenCage-canonical {@link COUNTRY_DISPLAY_NAME} for country records. * * @defaultValue `rec.name` verbatim. */ canonicalName?: (rec: WOFRecord) => string /** * Ranks a preferred-name language for one record, lower first. * * The adapter visits keys in rank order. * If two keys share a value, the first key's rank decides which language renders the name. * * Brooklyn's `name:wuu_x_preferred` and `name:zho_x_preferred` both hold 布鲁克林区, * and in source order `wuu` would claim it. * * Keys without a preferred-name language follow the ranked ones in source order. * * @defaultValue Source order. */ languageRank?: (language: string) => number } /** * One name a record's rows are rendered from. */ export interface NameSlot { /** * The `source_id` fragment: `default`, a normalized `name:*` key, or that key * with `-2`, `-3`… for a key's later values. */ key: string value: string /** * The ISO 639-3 language of a `name:_x_preferred` slot. * The admin adapter uses it to render a localized hierarchy. */ language?: string } const PREFERRED_KEY = /^name:([a-z]{3})_x_preferred$/ /** * Build the per-record name-slot list: the canonical `"default"` slot, * then every value of every `name:*` variant, deduplicated so a redundant * `"default"`-equivalent row isn't emitted under a localized key. */ export function nameSlotsFor(rec: WOFRecord, options: NameSlotOptions = {}): NameSlot[] { const canonicalSelfName = options.canonicalName?.(rec) ?? rec.name const seen = new Set([canonicalSelfName]) const slots: NameSlot[] = [{ key: "default", value: canonicalSelfName }] const rank = options.languageRank const keyRank = (rawKey: string): number => { const language = PREFERRED_KEY.exec(rawKey)?.[1] return rank && language ? rank(language) : Number.POSITIVE_INFINITY } const entries = rank ? [...rec.nameVariants].toSorted(([a], [b]) => keyRank(a) - keyRank(b) || 0) : rec.nameVariants for (const [rawKey, variant] of entries) { const values = nameValues(variant) const language = PREFERRED_KEY.exec(rawKey)?.[1] for (const [position, value] of values.entries()) { if (seen.has(value)) continue seen.add(value) const key = position ? `${normalizeNameKey(rawKey)}-${position + 1}` : normalizeNameKey(rawKey) slots.push(language && !position ? { key, value, language } : { key, value }) } } return slots } /** * One record and the ancestors its variants read: names for `wof-postalcode`, records for `wof-admin`. */ export interface WOFRecordEntry { record: WOFRecord ancestors: A } interface EmitWOFJSONRowsOptions { /** * The records to render, in ascending WOF-id order. */ records: Iterable> adapterOptions: AdapterOptions adapterID: string localeByCountry: Readonly> shouldEmit?: (record: WOFRecord) => boolean nameSlotsFor: (record: WOFRecord) => NameSlot[] variantsFor: (record: WOFRecord, ancestry: A, slot: NameSlot) => WOFVariantSpec[] /** * Chooses the rows to emit when the adapter options include a sample. * * The emitter renders every row once into it, then emits the rows it keeps, in WOF-id order. * The caller reads its cell counts afterwards. */ sampler?: RowSampler /** * Rows the adapter refuses or requires whatever the sample keeps. */ rowRule?: WOFRowRule /** * Whether a place keeps one row of a name slot whatever the sample keeps, * read from the row's country and slot key. * * Of a kept slot's rows, the one with the most components is emitted while the * records are rendered, so the sampler holds no payload for it. */ placeSlot?: (country: string, slotKey: string) => boolean } /** * An adapter's decision about single rendered rows, applied on top of the sample. */ export interface WOFRowRule { /** * Whether the row is left out of the output. * * A sampled run still observes the row, so leaving it out moves no other row's keep decision. */ drops: (row: CanonicalRow) => boolean /** * Whether a sampled run keeps the row whatever its hash. */ requires: (row: CanonicalRow) => boolean } /** * Emit aligned rows in WOF-id order, enforcing the adapter limit across all name and hierarchy variants. * * A variant's `country` renders it in another country's order and join * (a Japanese hierarchy of a US place is written largest first with no separator), * while the row keeps the record's own country. */ export function* emitWOFJSONRows(options: EmitWOFJSONRowsOptions): Generator { const { adapterOptions, sampler, rowRule, placeSlot } = options const limit = adapterOptions.limit let emitted = 0 if (sampler) { for (const place of rowsByRecord(renderWOFRows(options))) { const placeRows = placeSlot ? fullestRowPerSlot(place, placeSlot, rowRule) : new Set() for (const { row, slotKey } of place) { const sampled = sampledRow(row, slotKey) if (placeRows.has(row)) { if (!sampler.observeEmitted(sampled, row)) continue if (typeof limit === "number" && emitted >= limit) return yield row emitted++ continue } sampler.observe(sampled, row, rowRule?.requires(row) ?? false) } } } const rows = sampler ? sampler.kept() : (function* () { for (const { row } of renderWOFRows(options)) { yield row } })() for (const row of rows) { if (typeof limit === "number" && emitted >= limit) return if (rowRule?.drops(row)) continue yield row emitted++ } } /** * The rendered rows grouped by record, one group per record in the order rendered. * * The renderer writes all of a record's rows before the next record's, * so a group closes when the record id changes. */ function* rowsByRecord( rows: Iterable<{ row: CanonicalRow; slotKey: string; recordID: number }> ): Generator> { let group: Array<{ row: CanonicalRow; slotKey: string }> = [] let current: number | null = null for (const { row, slotKey, recordID } of rows) { if (recordID !== current && group.length) { yield group group = [] } current = recordID group.push({ row, slotKey }) } if (group.length) { yield group } } /** * Of each name slot `placeSlot` keeps, the row with the most components, leaving out a row `rowRule` drops. * A tie keeps the row rendered first. */ function fullestRowPerSlot( place: ReadonlyArray<{ row: CanonicalRow; slotKey: string }>, placeSlot: (country: string, slotKey: string) => boolean, rowRule: WOFRowRule | undefined ): Set { const fullest = new Map() for (const { row, slotKey } of place) { if (!placeSlot(row.country, slotKey) || rowRule?.drops(row)) continue const held = fullest.get(slotKey) if (!held || Object.keys(row.components).length > Object.keys(held.components).length) { fullest.set(slotKey, row) } } return new Set(fullest.values()) } function sampledRow(row: CanonicalRow, slotKey: string): SampledRow { return { sourceID: row.source_id, country: row.country, slotKey, raw: row.raw, components: row.components } } /** * Every row the records render, in WOF-id order, each with the name-slot key * and the record id it came from. */ function* renderWOFRows( options: EmitWOFJSONRowsOptions ): Generator<{ row: CanonicalRow; slotKey: string; recordID: number }> { const { records, adapterOptions, adapterID, localeByCountry, shouldEmit = () => true, nameSlotsFor: slotsForRecord, variantsFor, } = options for (const { record, ancestors } of records) { if (adapterOptions.signal?.aborted) return if (!shouldEmit(record)) continue for (const slot of slotsForRecord(record)) { for (const variant of variantsFor(record, ancestors, slot)) { const rendered = variant.hierarchy ? renderHierarchy(variant.components, variant.layoutCountry ?? record.country) : formatCorpusRow(variant.components, record.country, { singleLine: true }) if (!rendered) continue const { raw, components } = rendered yield { slotKey: slot.key, recordID: record.id, row: { raw, components, country: record.country, locale: localeByCountry[record.country], source: adapterID, source_id: `${adapterID}-${record.id}-${slot.key}-${variant.suffix}`, license: "CC0-1.0", }, } } } } }