// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Checks a row's component values against its country's rules and against its own other components. * * A row that aligns can still hold a wrong value: a postcode that's a state code (`1811 Hayes Avenue, Hull, IA IA`), * a street line repeated where the city belongs (`56 East Chase Street, 56 East Chase Street, FL 32502`), or a * street that ends in the row's own postcode (`655 MAPLE AVE # 90014, LOS ANGELES, CA 900142211`). Every rule reads * per-country data or the row itself, so the same rules hold in every country. */ import { acceptPostcode, statesPostcodeSyntax } from "@mailwoman/postcode/country-formats" import type { UnitSplitter } from "#adapters/street/unit" import { writtenSubdivisionCode } from "#adapters/wof/admin/json/region-codes" import type { RegionNames } from "#build/region/names" import type { CanonicalRow } from "#types" /** * The rules a component value can fail, as the `:` tail of a `component-invalid` reason. */ export const ComponentRule = { /** * The postcode doesn't have the form the country's postcode syntax states. */ PostcodeFormat: "postcode:format", /** * The street ends in the row's own postcode. */ StreetRepeatsPostcode: "street:repeats-postcode", /** * The street ends in the row's own locality and region, and its postcode where the row has one. */ StreetHoldsPlace: "street:holds-place", /** * The locality holds the row's house number and street: the publisher filled * the city with the street line. */ LocalityHoldsStreet: "locality:holds-street", /** * The postcode is the row's own region (`1811 Hayes Avenue, Hull, IA IA`). */ PostcodeRepeatsRegion: "postcode:repeats-region", /** * The locality is the code the row's country writes for the row's own region * (`BELLVILLE, TX, TX 77418` read with `TX` as the city). */ LocalityRepeatsRegion: "locality:repeats-region", /** * The street still ends in a unit designator and identifier of the row's * country (`Avenue des Armieres Entree 13`). */ StreetTrailingUnit: "street:trailing-unit", /** * The region is no name or abbreviation of a region or macroregion of the row's country * in the WOF admin database, in a country where that database holds regions. */ RegionUnknown: "region:unknown", } as const export type ComponentRule = (typeof ComponentRule)[keyof typeof ComponentRule] /** * The rules a build quarantines a row for. * * `postcode:format` is reported but not enforced. * The v0.8.9 dry run (#2898) found 522,089 rows failing it, among them legitimate partial * postcodes (WOF's Dutch `3704`) and spaced written forms (`31 261` in Kraków), beside the defects * it is meant for (NAD's 425,667 short ZIP Codes and Overture Brazil's dropped leading zeros). * * `locality:repeats-region` is reported but not enforced, because a publisher's own `NY` for * New York City (`150 E 71 ST, NY, NY 10021`) fails it beside the rows whose city was lost. * * `street:trailing-unit` is reported but not enforced, because some streets end in a * word a country also writes as a unit (`Morning Side`, `Skijor Steppe Upper`). * * `region:unknown` is reported but not enforced, because neither source holds every * form addresses write: Swiss canton codes (`TG`), Latvia's post-2021 municipalities * (`Valmieras nov.`), Bangkok's short `กรุงเทพ`. */ export const ENFORCED_COMPONENT_RULES: ReadonlySet = new Set([ ComponentRule.StreetRepeatsPostcode, ComponentRule.StreetHoldsPlace, ComponentRule.LocalityHoldsStreet, ComponentRule.PostcodeRepeatsRegion, ]) /** * One rule a row fails, with the component values that fail it. */ export interface ComponentFinding { rule: ComponentRule values: string[] } /** * Rows failing each rule, per `source` then rule. */ export type ComponentFindingCounts = Map> /** * {@linkcode ComponentFindingCounts} as a JSON object, in the order each source and rule was first counted. */ export function componentFindingsRecord(counts: ComponentFindingCounts): Record> { return Object.fromEntries([...counts].map(([source, rules]) => [source, Object.fromEntries(rules)])) } /** * The key under which a row's region value is counted: its country and the value as the row writes it. */ export function regionValueKey(country: string, region: string): string { return `${country}\u001E${region}` } /** * The `region:unknown` count of rows counted per {@linkcode regionValueKey}, under `regions`. * * It applies the rule's own test, so it equals the count an align under `regions` would write. */ export function countRegionUnknown( values: Iterable, regions: RegionNames ): number { let unknown = 0 for (const [key, rows] of values) { const separator = key.indexOf("\u001E") if (regions.holds(key.slice(0, separator), key.slice(separator + 1)) === false) { unknown += rows } } return unknown } /** * The fewest digits a street's ending needs before it is compared with the row's postcode. */ const SHORTEST_POSTCODE_DIGITS = 4 const fold = (text: string) => text .normalize("NFC") .toLowerCase() .replaceAll(/[\s,.]+/gu, " ") .trim() /** * What the rules read beyond the row. */ export interface ComponentCheckContext { /** * The unit vocabulary `street:trailing-unit` reads. * Without it the rule isn't checked. */ units?: UnitSplitter | null /** * The WOF region names `region:unknown` reads. * Without them the rule isn't checked. */ regions?: RegionNames | null /** * Answers already computed for a (country, value) pair, from {@linkcode createComponentCheckMemo}. * * A source repeats one postcode or region on every row of a place. * Each answer reads only the country and the value. */ memo?: ComponentCheckMemo | null } /** * The postcode and region answers one aligner has computed, keyed by country and value. */ export interface ComponentCheckMemo { readonly postcodeRejected: Map readonly regionUnknown: Map } /** * Entries the postcode table holds before it starts again empty. * * NAD writes ZIP+4 forms, millions of distinct values, and an align worker's heap is 1.5 GiB. * Regions take a few thousand values per country, so their table needs no bound. */ const POSTCODE_MEMO_ENTRIES = 200_000 /** * An empty memo for one aligner. */ export function createComponentCheckMemo(): ComponentCheckMemo { return { postcodeRejected: new Map(), regionUnknown: new Map() } } function memoized( table: Map, key: string, compute: () => boolean, bound = Number.POSITIVE_INFINITY ): boolean { const known = table.get(key) if (known !== undefined) return known if (table.size >= bound) { table.clear() } const answer = compute() table.set(key, answer) return answer } /** * The rules `components` fails for a row of `country`, in rule order. */ export function componentFindings( components: CanonicalRow["components"], country: string, context: ComponentCheckContext = {} ): ComponentFinding[] { const findings: ComponentFinding[] = [] const { postcode, street, locality, region } = components const postcodeRejected = (value: string): boolean => { const compute = () => statesPostcodeSyntax(country) && acceptPostcode(value, country) == null return context.memo ? memoized(context.memo.postcodeRejected, `${country}\u001E${value}`, compute, POSTCODE_MEMO_ENTRIES) : compute() } const regionUnknown = (value: string): boolean => { const compute = () => context.regions?.holds(country, value) === false return context.memo ? memoized(context.memo.regionUnknown, `${country}\u001E${value}`, compute) : compute() } if (postcode && postcodeRejected(postcode)) { findings.push({ rule: ComponentRule.PostcodeFormat, values: [postcode] }) } if (street && postcode) { const postcodeDigits = postcode.replaceAll(/\D/gu, "") const tail = /(\d[\d-]*)\s*$/u.exec(street)?.[1]?.replaceAll(/\D/gu, "") ?? "" if (tail.length >= SHORTEST_POSTCODE_DIGITS && postcodeDigits.startsWith(tail)) { findings.push({ rule: ComponentRule.StreetRepeatsPostcode, values: [street, postcode] }) } } if (street && locality && region) { const foldedStreet = fold(street) // Comparison keys over the row's own values, in the order a street line runs into them. const place = fold([locality, region].join(" ")) const withPostcode = postcode ? fold([locality, region, postcode].join(" ")) : null if ( foldedStreet !== place && (foldedStreet.endsWith(` ${place}`) || (withPostcode != null && foldedStreet.endsWith(` ${withPostcode}`))) ) { findings.push({ rule: ComponentRule.StreetHoldsPlace, values: [street, locality, region] }) } } // A locality may share words with its street (`Fox Park CDP` for `Fox Park Road`, // a village whose only street has the village's name). // A locality that holds the row's house number and street is the street line itself // (`56 East Chase Street` as the city of `56 East Chase Street`). const houseNumber = components.house_number if (street && locality && houseNumber) { const line = fold([houseNumber, street].join(" ")) if (` ${fold(locality)} `.includes(` ${line} `)) { findings.push({ rule: ComponentRule.LocalityHoldsStreet, values: [locality, houseNumber, street] }) } } if (postcode && region && fold(postcode) === fold(region)) { findings.push({ rule: ComponentRule.PostcodeRepeatsRegion, values: [postcode, region] }) } // A city may share its region's name (`Berlin, Berlin`, `أبو ظبي, أبو ظبي`), // but no city is written as its region's code. libaddressinput's keys and ISO ids state // which codes a country's addresses write. if (locality && region) { const regionCode = writtenSubdivisionCode(country, region) if (regionCode != null && fold(locality) === fold(regionCode)) { findings.push({ rule: ComponentRule.LocalityRepeatsRegion, values: [locality, region] }) } } if (street && context.units) { const trailing = context.units.trailingUnit(street, { country, ...(locality ? { locality } : {}), ...(postcode ? { postcode } : {}), }) if (trailing) { findings.push({ rule: ComponentRule.StreetTrailingUnit, values: [street, trailing.unit] }) } } if (region && regionUnknown(region)) { findings.push({ rule: ComponentRule.RegionUnknown, values: [region] }) } return findings }