// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * `trailing-region` — the `«locality», «region»[, «country»]` admin tail, * built from real `(locality, region)` WOF ancestor pairs. * * A tuple's `postcodePlacement` selects where the postcode sits: `leading`, * `after_locality`, or `after_region`. * When absent, placement is inferred from the country's codex layout and postcode format * (defaulting to `leading` when unknown, so tuples files written before the field existed are unchanged). * * For `after_locality` tuples (for example `Barcelona 6001, Venezuela` * and `Barcelona 6001, Anzoátegui, Venezuela`), the recipe emits rows both with * and without a region, omits synthetic house numbers so the locality-postcode pair * is never confused with a street-number tail, and adds anchor-varied contrast * rows for non-US four-digit postcode countries (#1821). * * For `before_locality` countries (`PL`, `CZ`, `DE`, `FR`, `IT`, `ES`, and peers), * one tuple in {@linkcode LOCALITY_FIRST_LEADING_MODULUS} (16.7%) renders in locality-first * order (`Warszawa 00-002, Poland`, `Praha 100 00, Czechia`, and with-region counterparts) * without a synthetic house number (#3646). * * A bare `«region»` form is deliberately absent: teaching it as `region` would fight * the locality/region ambiguity the dominance race arbitrates. * A `dependentLocality`, when present, becomes `«dep_locality», «locality»…`; without it every * row begins with the locality and teaches the model that the first segment is the locality. */ import { formatAddress } from "@mailwoman/codex/address/format" import { lookupCanadianProvince } from "@mailwoman/codex/ca" import { ISO2_TO_NAME } from "@mailwoman/codex/country" import { lookupUSState, US_STATE_BY_ABBREVIATION } from "@mailwoman/codex/us" import { mulberry32 as makeMulberry32 } from "@mailwoman/core/utils" import { hasPostcodeForm, postcodePlacement as codexPostcodePlacement, postcodeSyntaxCountries, } from "@mailwoman/postcode/country-formats" import { alignAndWrite, type PostcodePlacement, readTuples, requireRegister, type CorpusRecipe, recipeSourceID, } from "#recipes/scaffold" import { defaultRecipeSource } from "#recipes/sources" import { SurfaceOrigin } from "#types" const US_CONTRAST_REGIONS: readonly string[] = Object.values(US_STATE_BY_ABBREVIATION) // country-branch: #1821 anchor contrasts test the US country frame independently of the region anchor. const US_COUNTRY_NAME = ISO2_TO_NAME.get("US") ?? "United States" /** * Deterministic cadence (1 in 6 = 16.7%) for rendering `before_locality` countries in * locality-first ` [, ], ` order (#3646). */ const LOCALITY_FIRST_LEADING_MODULUS = 6 /** * Infers a country's postcode placement inside the admin tail from its codex * address layout and libaddressinput postcode placement, defaulting to `leading` * when the country is unknown or prints postcodes before the locality. */ function inferPostcodePlacement(cc: string): PostcodePlacement { const country = cc.trim().toUpperCase() if (!country || codexPostcodePlacement(country) !== "after_locality") return "leading" const probe = formatAddress({ locality: "__LOC__", region: "__REG__", postcode: "__PC__" }, country, { singleLine: true, }) if (probe) { const regionAt = probe.indexOf("__REG__") const postcodeAt = probe.indexOf("__PC__") if (regionAt !== -1 && postcodeAt !== -1 && regionAt < postcodeAt) { return "after_region" } } return "after_locality" } /** * Non-US countries whose postcode syntax accepts a four-digit numeric postcode, * derived from `@mailwoman/postcode` rather than a static country list. */ function nonUSFourDigitPostcodeCountries(): readonly string[] { // country-branch: #1821 targets non-US four-digit postcode countries whose locality-postcode // tails collapse to street + house_number outside the US country frame. return postcodeSyntaxCountries().filter((cc) => cc !== "US" && hasPostcodeForm("6001", cc)) } const FOUR_DIGIT_NON_US_COUNTRIES: ReadonlySet = new Set(nonUSFourDigitPostcodeCountries()) /** * The region code an address line in this country writes, or `null` where the region name is written out. * * A subdivision belongs here only when its code is a posted surface: Canadian province * and US state codes are, a Bundesland or a région isn't. * * Several Canadian codes collide with ISO alpha-2 country codes (`NL`, `PE`), * so a code left unattested here reads as the country. */ function regionCodeSurface(cc: string, region: string): string | null { const country = cc.toUpperCase() // country-branch: the codex holds region codes for CA and US only. // The WOF admin database's `place_abbr` holds codes for ten countries // (IT, US, ES, MX, BR, CA, AU, AE, UA, AD), and an ISO 3166-2 table would cover every country. // The tree holds neither as a lookup yet. if (country === "CA") return lookupCanadianProvince(region) // country-branch: see the CA branch above. return country === "US" ? lookupUSState(region) : null } /** * Recipe registered with the corpus builder. */ export const trailingRegionRecipe: CorpusRecipe = { name: "trailing-region", description: "Admin tails (Portopetro class): '«locality», «region»[, «country»]' from WOF ancestor pairs", mode: "tuples", async run(opts, write) { makeMulberry32(opts.seed) const structuredSource = opts.sourceName ?? defaultRecipeSource("synth-trailing-region-structured") const bareSource = opts.sourceName ? `${opts.sourceName}-bare` : defaultRecipeSource("synth-trailing-region") let read = 0 let emitted = 0 let skipped = 0 const TRAILING_REGION_PROVENANCE = { register: requireRegister(opts, "trailing-region"), surface: SurfaceOrigin.Composed, } for await (const t of readTuples(opts.input!)) { read++ const locality = String(t.locality ?? "").trim() const region = String(t.region ?? "").trim() const country = String(t.country ?? "").trim() const dependentLocality = String(t.dependentLocality ?? "").trim() const postcode = String(t.postcode ?? "").trim() const cc = String(t.cc ?? "") .trim() .toUpperCase() const placement = (t.postcodePlacement as PostcodePlacement | undefined) ?? inferPostcodePlacement(cc) const allowRegionlessAfterLocality = placement === "after_locality" && postcode.length > 0 && country.length > 0 // A pair whose region equals its locality provides no signal about the boundary this recipe teaches. // Region-less tuples are admitted only for `after_locality` postcode tails with a country // (e.g. `Barcelona 6001, Venezuela`), where the postcode separates locality from country. if (!locality || (region && locality === region) || (!region && !allowRegionlessAfterLocality)) { skipped++ continue } const withCountry = !region ? true : read % 2 === 0 && country.length > 0 // #3646: emit a deterministic 16.7% (1-in-6) locality-first variant for `before_locality` // countries (`Warszawa 00-002, Poland`, `Praha 100 00, Czechia`), alternating // regionless and with-region tails without synthetic house numbers. const localityFirstVariant = placement === "leading" && postcode.length > 0 && country.length > 0 && codexPostcodePlacement(cc) === "before_locality" && read % LOCALITY_FIRST_LEADING_MODULUS === 0 const effectivePlacement: PostcodePlacement = localityFirstVariant ? "after_locality" : placement // For `after_locality` rows with a region and country, alternate between // `«locality» «postcode», «region», «country»` and `«locality» «postcode», «country»`. // For locality-first variants of `before_locality` countries, alternate the same way // across every second hit (`read % 12 === 6` regionless, `read % 12 === 0` with region). const includeRegion = Boolean(region) && !(allowRegionlessAfterLocality && withCountry && read % 4 === 0) && !(localityFirstVariant && read % (LOCALITY_FIRST_LEADING_MODULUS * 2) !== 0) // The house number is the second trigger for `leading` / `after_region` rows: // the postcode discards the region, and the house number then displaces the locality. // `after_locality` rows (including locality-first variants) omit synthetic house numbers // so `«locality» «postcode»` never co-occurs with a house number on a streetless tail. const withHouseNumber = postcode.length > 0 && effectivePlacement !== "after_locality" && read % 4 === 1 const houseNumber = withHouseNumber ? String((read % 97) + 1) : "" const components: Record = { locality } if (dependentLocality && dependentLocality !== locality) { components["dependent_locality"] = dependentLocality } if (includeRegion) { components["region"] = region } if (withCountry) { components["country"] = country } if (postcode) { components["postcode"] = postcode } if (withHouseNumber) { components["house_number"] = houseNumber } const bareLocality = postcode && effectivePlacement === "after_locality" ? `${locality} ${postcode}` : locality const localitySegment = components["dependent_locality"] ? `${dependentLocality}, ${bareLocality}` : bareLocality // The code alternates with the region name rather than replacing it: // both forms are posted and the resolver matches on the name. const regionCode = includeRegion && read % 3 === 2 ? regionCodeSurface(cc, region) : null const regionSurface = regionCode ?? region if (includeRegion && regionCode) { components["region"] = regionCode } const regionSegment = postcode && effectivePlacement === "after_region" ? `${regionSurface} ${postcode}` : regionSurface const tail = includeRegion ? withCountry ? `${localitySegment}, ${regionSegment}, ${country}` : `${localitySegment}, ${regionSegment}` : `${localitySegment}, ${country}` const leadingPostcode = postcode && effectivePlacement === "leading" ? `${postcode} ` : "" const head = withHouseNumber ? `${houseNumber}, ${leadingPostcode}` : leadingPostcode const raw = `${head}${tail}` // A distinct source for the structured rows: the sampler buckets by `source`, // so pooling them with the bare rows would make their weight unsettable. const sourceLabel = postcode ? structuredSource : bareSource const source_id = recipeSourceID(sourceLabel, { ...components, v: String(read) }) const canonical = { raw, components, country: cc || "und", locale: String(t.locale ?? "und"), source: sourceLabel, source_id, license: "Synthetic — trailing-region; (locality, region) ancestor pairs from WOF (CC0/ODC-By per source)", } // Per row, because the id identifies this tuple's record. // A tuples file written before `sourceID` existed contains no id. // and `null` means the recipe had no id to forward. if ( alignAndWrite(write, canonical, "trailing-region", { ...TRAILING_REGION_PROVENANCE, baseSourceID: t.sourceID ?? null, }) ) { emitted++ } else { skipped++ } // #1821 anchor contrasts: US competence on `«locality» «postcode», «region», «country»` // requires both a US region and `United States`. // These contrast pairs vary each anchor independently so neither anchor by // itself decides the locality-postcode boundary. if ( placement === "after_locality" && includeRegion && withCountry && read % 8 === 2 && FOUR_DIGIT_NON_US_COUNTRIES.has(cc) && /^\d{4}$/u.test(postcode) ) { const usRegion = US_CONTRAST_REGIONS[read % US_CONTRAST_REGIONS.length]! const contrastRows: Array<{ suffix: string; regionValue: string; countryValue: string }> = [ { suffix: "contrast-us-region", regionValue: usRegion, countryValue: country }, { suffix: "contrast-us-country", regionValue: regionSurface, countryValue: US_COUNTRY_NAME }, ] for (const contrast of contrastRows) { const contrastComponents: Record = { locality, postcode, region: contrast.regionValue, country: contrast.countryValue, } if (components["dependent_locality"]) { contrastComponents["dependent_locality"] = components["dependent_locality"] } const contrastCanonical = { raw: `${localitySegment}, ${contrast.regionValue}, ${contrast.countryValue}`, components: contrastComponents, country: cc, locale: String(t.locale ?? "und"), source: sourceLabel, source_id: recipeSourceID(sourceLabel, { ...contrastComponents, v: `${read}-${contrast.suffix}` }), license: canonical.license, } if ( alignAndWrite(write, contrastCanonical, `trailing-region:${contrast.suffix}`, { ...TRAILING_REGION_PROVENANCE, baseSourceID: t.sourceID ?? null, }) ) { emitted++ } else { skipped++ } } } } return { read, emitted, skipped } }, }