// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * Renders real address tuples into locale-specific surface strings. * * Public address registers supply inputs such as OA, HM Land Registry and CNIG. * LINZ-derived extracts also supply inputs. * * The module applies OpenCage templates to choose ordering and punctuation by country. * * Keep the emitted source ids stable: they're persisted in built corpora * and referenced by training configs. * `recipes/sources.ts` records each one under its operation spelling (`rendered-de`) * and the `synth-*` spelling it retired on 2026-09-26. */ import { writtenPostcode } from "@mailwoman/codex/labels/postcode/written-groups" import { mulberry32 } from "@mailwoman/core/utils" import { formatCorpusRow } from "#surfaces/corpus-row" import type { CanonicalRow } from "#types" /* oxlint-disable sister-software/no-unnamed-threshold -- the bare decimals below are weighted-sampler weights. We keep them inline so the output distribution is easy to read. */ /** * Real address tuple (for example one OpenAddresses row). * * Street and locality are required. * Other tuple fields are optional. */ export interface LocaleBaseTuple { house_number?: string street: string locality: string /** * Sub-locality below locality (for example suburb/district). * When present, it is rendered between street and locality. */ dependent_locality?: string region?: string postcode?: string } /** * @deprecated Alias — use LocaleBaseTuple. */ export type GermanBaseTuple = LocaleBaseTuple export interface RenderedLocaleRow { raw: string components: CanonicalRow["components"] locale: string } /** * @deprecated Alias — use RenderedLocaleRow. */ export type RenderedGermanRow = RenderedLocaleRow export interface LocaleRenderOpts { random?: () => number /** * Postcode surface shape. * * `"conventional"` (default) canonicalizes to the country's rendered form * (NL: OA's glued `1011AB` → the spaced `1011 AB`). * `"as-source"` keeps the source's own surface. * * Today, only NL differs between these modes. */ postcodeShape?: "conventional" | "as-source" /** * How the native-order render joins street and house number. * * The OpenCage ES template comma-joins (`Calle Mayor, 12`, the official Spanish convention). * OA-derived feeds and our ES eval space-join (`calle mayor 12`, the observed form on all 3,000 eval rows). * * `"template"` (default) keeps the template's own join. * `"space"` collapses `, ` → ` ` after rendering. */ nativeHouseJoin?: "template" | "space" /** * The string between rendered address lines. * * `", "` (default) is the template's own join. * `" "` renders the comma-free single-line register for dictation or a copy out of a * one-field form, as in `Neusser Str. 12 Nippes 50733 Köln` for the same components. */ separator?: ", " | " " /** * Write the tuple's region where the country writes one (`regionLayoutForCountry` in the codex). * * The option draws no random number, so the rest of a seeded run is unchanged. * A row whose region cannot be placed or aligned renders without it. */ withRegion?: boolean } /** * @deprecated Alias — use LocaleRenderOpts. */ export type GermanRenderOpts = LocaleRenderOpts /** * ISO-3166 alpha-2 → BCP-47 tag for the emitted rows (primary language per country). */ const LOCALE_TAG: Record = { DE: "de-DE", ES: "es-ES", IT: "it-IT", NL: "nl-NL", GB: "en-GB", FR: "fr-FR", US: "en-US", NZ: "en-NZ", } /** * True when `value` appears verbatim and as a standalone token. */ function tokenPresent(raw: string, value: string): boolean { if (!raw.includes(value)) return false // Reject numeric substring collisions (for example house "2" inside postcode "12623"). const i = raw.indexOf(value) const before = raw[i - 1] const after = raw[i + value.length] const isDigit = (c: string | undefined) => c && c >= "0" && c <= "9" if (/^\d+$/.test(value) && (isDigit(before) || isDigit(after))) return false return true } /** * Render one tuple into a locale-ordered `{raw, components}` row via OpenCage templates, * with light variation (house number and postcode may be dropped). * * Returns `null` when the tuple is too thin or a component wouldn't align to an exact span. * The row prints the tuple's region only when {@linkcode LocaleRenderOpts.withRegion} asks for it. */ export function renderLocaleRow( base: LocaleBaseTuple, country: string, opts: LocaleRenderOpts = {} ): RenderedLocaleRow | null { const random = opts.random ?? Math.random if (!base.street || !base.locality) return null const components: CanonicalRow["components"] = { street: base.street, locality: base.locality } // Sub-locality is part of the address body. // If the template doesn't surface it verbatim, the row is dropped below. if (base.dependent_locality) { components.dependent_locality = base.dependent_locality } // The sampler keeps the house number in about 80% of rows. // The remaining rows use street-only forms. if (base.house_number && random() < 0.8) { components.house_number = base.house_number } // ~85% keep postcode. // Canonicalization uses the country's rendered form. // `postcodeShape: "as-source"` is applied after rendering. if (base.postcode && random() < 0.85) { // The written form aligns verbatim against `raw`: OA may store `1011AB` where the NL template writes `1011 AB`. components.postcode = writtenPostcode(base.postcode, country) } // The region costs no random draw, so a row without one renders exactly as before. // A region the country's layout cannot place, or that doesn't align, falls back to the row without it. // A region that's the locality itself, as the city-state Berlin is, would write the name twice. // Such a row (`12347 Berlin, Berlin`) renders without it. if ( opts.withRegion && base.region && base.region.localeCompare(base.locality, undefined, { sensitivity: "base" }) !== 0 ) { const withRegion = finishLocaleRow({ ...components, region: base.region }, base, country, opts) if (withRegion) return withRegion } return finishLocaleRow(components, base, country, opts) } /** * Render already-drawn components and check that each one aligns, drawing no random numbers. */ function finishLocaleRow( components: CanonicalRow["components"], base: LocaleBaseTuple, country: string, opts: LocaleRenderOpts ): RenderedLocaleRow | null { const separator = opts.separator ?? ", " const rendered = formatCorpusRow(components, country, { separator, withRegion: Boolean(components.region) }) if (!rendered?.raw) return null let raw = rendered.raw // The postcode is labeled as the layout printed it: `HR-10000` with its prefix, or the bare domestic `10000`. if (components.postcode && rendered.components.postcode) { components.postcode = rendered.components.postcode } // Optional rewrite: `, ` -> ` `. if (separator === ", " && opts.nativeHouseJoin === "space" && components.house_number) { raw = raw.replace( `${components.street}, ${components.house_number}`, `${components.street} ${components.house_number}` ) } // `postcodeShape: "as-source"`: rewrite both raw and component to source form. // Done post-render because templates may normalize the postcode. if (opts.postcodeShape === "as-source" && components.postcode && base.postcode) { const sourceForm = base.postcode.trim() if (sourceForm && sourceForm !== components.postcode && raw.includes(components.postcode)) { raw = raw.replace(components.postcode, sourceForm) components.postcode = sourceForm } } // The row is dropped if any component is absent from the rendered address. for (const value of Object.values(components)) { if (!value || !tokenPresent(raw, value)) return null } return { raw, components, locale: LOCALE_TAG[country] ?? country.toLowerCase() } } /** * The generator a seeded recipe draws {@linkcode LocaleRenderOpts.withRegion} from. * * It is separate from the rendering generator, so choosing which rows print a region * leaves every other draw of the run, and every row without a region, as it was. */ export function regionDrawRandom(seed: number): () => number { return mulberry32((seed ^ 0x52_45_47_4e) >>> 0) } /** * German wrapper over {@link renderLocaleRow}. * * Kept for the `german` recipe (`de/recipes/locale.ts`) and tests. */ export function renderGermanRow(base: LocaleBaseTuple, opts: LocaleRenderOpts = {}): RenderedLocaleRow | null { return renderLocaleRow(base, "DE", opts) }