@mailwoman/resolver 10.7.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +1 -5
  2. package/lib/admin/coherence-passes.ts +2 -2
  3. package/lib/admin/winner.ts +24 -4
  4. package/lib/bare-toponym-race.ts +1 -1
  5. package/lib/decorate-node.ts +19 -3
  6. package/lib/index.ts +1 -0
  7. package/lib/postcode/country-coherence.ts +4 -4
  8. package/lib/postcode/shape-coherence.ts +40 -51
  9. package/lib/remote-resolver.ts +1 -2
  10. package/lib/resolve/country-code.ts +102 -0
  11. package/lib/resolve/landmark.ts +227 -0
  12. package/lib/resolve/passes.ts +16 -60
  13. package/lib/resolve/region-city.ts +71 -0
  14. package/lib/resolve.ts +96 -67
  15. package/lib/span-rescore.ts +34 -3
  16. package/lib/street/tier.ts +117 -8
  17. package/out/admin/coherence-passes.js +2 -2
  18. package/out/admin/coherence-passes.js.map +1 -1
  19. package/out/admin/winner.d.ts +10 -2
  20. package/out/admin/winner.d.ts.map +1 -1
  21. package/out/admin/winner.js +18 -2
  22. package/out/admin/winner.js.map +1 -1
  23. package/out/bare-toponym-race.js +1 -1
  24. package/out/bare-toponym-race.js.map +1 -1
  25. package/out/decorate-node.d.ts.map +1 -1
  26. package/out/decorate-node.js +15 -3
  27. package/out/decorate-node.js.map +1 -1
  28. package/out/index.d.ts +1 -1
  29. package/out/index.d.ts.map +1 -1
  30. package/out/index.js +1 -1
  31. package/out/index.js.map +1 -1
  32. package/out/postcode/country-coherence.d.ts.map +1 -1
  33. package/out/postcode/country-coherence.js +4 -4
  34. package/out/postcode/country-coherence.js.map +1 -1
  35. package/out/postcode/shape-coherence.d.ts +12 -16
  36. package/out/postcode/shape-coherence.d.ts.map +1 -1
  37. package/out/postcode/shape-coherence.js +31 -40
  38. package/out/postcode/shape-coherence.js.map +1 -1
  39. package/out/remote-resolver.d.ts +1 -2
  40. package/out/remote-resolver.d.ts.map +1 -1
  41. package/out/remote-resolver.js +0 -1
  42. package/out/remote-resolver.js.map +1 -1
  43. package/out/resolve/country-code.d.ts +49 -0
  44. package/out/resolve/country-code.d.ts.map +1 -0
  45. package/out/resolve/country-code.js +88 -0
  46. package/out/resolve/country-code.js.map +1 -0
  47. package/out/resolve/landmark.d.ts +26 -0
  48. package/out/resolve/landmark.d.ts.map +1 -0
  49. package/out/resolve/landmark.js +181 -0
  50. package/out/resolve/landmark.js.map +1 -0
  51. package/out/resolve/passes.d.ts +8 -30
  52. package/out/resolve/passes.d.ts.map +1 -1
  53. package/out/resolve/passes.js +8 -28
  54. package/out/resolve/passes.js.map +1 -1
  55. package/out/resolve/region-city.d.ts +29 -0
  56. package/out/resolve/region-city.d.ts.map +1 -0
  57. package/out/resolve/region-city.js +58 -0
  58. package/out/resolve/region-city.js.map +1 -0
  59. package/out/resolve.d.ts.map +1 -1
  60. package/out/resolve.js +74 -60
  61. package/out/resolve.js.map +1 -1
  62. package/out/span-rescore.d.ts +5 -0
  63. package/out/span-rescore.d.ts.map +1 -1
  64. package/out/span-rescore.js +26 -3
  65. package/out/span-rescore.js.map +1 -1
  66. package/out/street/tier.d.ts +13 -2
  67. package/out/street/tier.d.ts.map +1 -1
  68. package/out/street/tier.js +94 -7
  69. package/out/street/tier.js.map +1 -1
  70. package/package.json +10 -7
  71. package/lib/backend-capabilities.ts +0 -89
  72. package/out/backend-capabilities.d.ts +0 -36
  73. package/out/backend-capabilities.d.ts.map +0 -1
  74. package/out/backend-capabilities.js +0 -77
  75. package/out/backend-capabilities.js.map +0 -1
package/README.md CHANGED
@@ -28,10 +28,6 @@ const decorated = await resolver.resolveTree(tree)
28
28
 
29
29
  `createWOFResolver` takes a `ResolverBackend` — a structural interface rather than a class. `@mailwoman/resolver-wof-sqlite` implements it over `node:sqlite`, `@mailwoman/resolver-wof-wasm` over `@sqlite.org/sqlite-wasm` in a browser, and `RemoteResolver` over HTTP. This package imports none of them.
30
30
 
31
- Backends differ in what they can answer. `describeCapabilityGaps(backend)` reports missing optional
32
- methods. A default-on feature that no-ops without logging on your backend reports that condition instead
33
- of looking like a bad result.
34
-
35
31
  ## Absence is a value
36
32
 
37
33
  Two rules run through this package, and both exist because their opposites shipped bugs.
@@ -82,7 +78,7 @@ A span ranked in isolation gets Portland, Maine to Messina, Italy. These checks
82
78
 
83
79
  Import the barrel for the whole surface, or a subpath to take one piece without the rest:
84
80
 
85
- `./resolve` · `./admin-winner` · `./decorate-node` · `./plausibility` · `./postcode-prefix` · `./postcode-country-coherence` · `./postcode-shape-coherence` · `./admin-containment` · `./span-rescore` · `./street-evidence` · `./toponym-prior` · `./rerank` · `./remote-resolver` · `./backend-capabilities`
81
+ `./resolve` · `./admin-winner` · `./decorate-node` · `./plausibility` · `./postcode-prefix` · `./postcode-country-coherence` · `./postcode-shape-coherence` · `./admin-containment` · `./span-rescore` · `./street-evidence` · `./toponym-prior` · `./rerank` · `./remote-resolver`
86
82
 
87
83
  The type interface (`ResolverBackend`, `ResolveOpts`, `ResolvedPlace`) lives in `@mailwoman/core/resolver` so that `core` stays a leaf, and is re-exported here — `@mailwoman/resolver` is the complete surface.
88
84
 
@@ -196,8 +196,8 @@ function revertResolverDecoration(node: AddressNode): void {
196
196
  const meta = { ...node.metadata }
197
197
  const priorSource = meta["classifier_source"]
198
198
  const priorSourceID = meta["classifier_source_id"]
199
- node.source = typeof priorSource === "string" ? priorSource : undefined
200
- node.sourceID = typeof priorSourceID === "string" ? priorSourceID : undefined
199
+ node.source = typeof priorSource === "string" ? priorSource : null
200
+ node.sourceID = typeof priorSourceID === "string" ? priorSourceID : null
201
201
 
202
202
  for (const key of [
203
203
  "classifier_source",
@@ -8,9 +8,9 @@
8
8
  * `PLACETYPE_SPECIFICITY` cannot express that split.
9
9
  */
10
10
 
11
- import { areaPostcodeLeadsLocality, isUnitGradePostcodeHit } from "@mailwoman/codex"
12
11
  import type { AddressNode } from "@mailwoman/core/decoder"
13
- import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
12
+ import { PLACETYPE_SPECIFICITY } from "@mailwoman/gazetteer/whosonfirst/placetypes/specificity"
13
+ import { areaPostcodeLeadsLocality, isUnitGradePostcodeHit } from "@mailwoman/postcode/systems"
14
14
 
15
15
  /**
16
16
  * The admin fallback order when the postcode leads, with the JP rungs beside their
@@ -44,6 +44,26 @@ export const ADMIN_LADDER_LOCALITY_FIRST: ReadonlyArray<string> = [
44
44
  "country",
45
45
  ]
46
46
 
47
+ /**
48
+ * The ladder with `dependent_locality` moved ahead of `locality`, for a tree whose
49
+ * dependent locality the resolver placed inside its parent (#2804).
50
+ *
51
+ * The postcode rung keeps its place, so a unit-grade postcode still answers first.
52
+ * A ladder without both rungs is returned as it is.
53
+ */
54
+ export function ladderWithContainedDependentLocality(ladder: ReadonlyArray<string>): ReadonlyArray<string> {
55
+ const dependent = ladder.indexOf("dependent_locality")
56
+ const locality = ladder.indexOf("locality")
57
+
58
+ if (dependent === -1 || locality === -1 || dependent < locality) return ladder
59
+
60
+ const moved = ladder.filter((rung) => rung !== "dependent_locality")
61
+
62
+ moved.splice(moved.indexOf("locality"), 0, "dependent_locality")
63
+
64
+ return moved
65
+ }
66
+
47
67
  /**
48
68
  * The resolved postcode a ladder decision reads.
49
69
  *
@@ -60,7 +80,7 @@ export interface ResolvedPostcodeHit {
60
80
  * It is absent when the postcode did not resolve to a country.
61
81
  * The ladder then defaults to locality-first.
62
82
  */
63
- country?: string
83
+ country?: string | null
64
84
  }
65
85
 
66
86
  /**
@@ -108,7 +128,7 @@ export interface ResolvedSpecificityInput {
108
128
  /**
109
129
  * ISO-3166 alpha-2 the resolver placed this candidate in, read only for a `postalcode`.
110
130
  */
111
- country?: string
131
+ country?: string | null
112
132
  /**
113
133
  * The parsed span.
114
134
  * Absent for a non-postcode candidate.
@@ -15,7 +15,7 @@ import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
15
15
  import type { AddressNode, AddressTree } from "@mailwoman/core/decoder"
16
16
  import { loneValueNode } from "@mailwoman/core/decoder"
17
17
  import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
18
- import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
18
+ import { PLACETYPE_SPECIFICITY } from "@mailwoman/gazetteer/whosonfirst/placetypes/specificity"
19
19
 
20
20
  /**
21
21
  * The tree's single value-containing node when it is locality-tagged, else null.
@@ -12,11 +12,21 @@ import type { ResolvedPlace } from "@mailwoman/core/resolver"
12
12
 
13
13
  import type { CoordinateOptionalPlace } from "#postcode/prefix"
14
14
 
15
+ /**
16
+ * The widest stored extent, in degrees, that is a single point: about 10 meters, narrower than any place.
17
+ */
18
+ const POINT_EXTENT_DEGREES = 0.0001
19
+
15
20
  /**
16
21
  * A resolved node has a real coordinate (placeID set + non-zero lat/lon).
17
22
  */
18
23
  export function isResolvedWithCoord(n: AddressNode): boolean {
19
- return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0))
24
+ return (
25
+ typeof n.placeID === "string" &&
26
+ typeof n.lat === "number" &&
27
+ typeof n.lon === "number" &&
28
+ (n.lat !== 0 || n.lon !== 0)
29
+ )
20
30
  }
21
31
 
22
32
  /**
@@ -85,10 +95,16 @@ export function decorateNode(
85
95
  node.metadata["resolver_importance"] = resolved.importance
86
96
  }
87
97
 
88
- // A point-only row stores its coordinate as both corners, so only an extent with area measures the place's size.
98
+ if (resolved.matchedAlias) {
99
+ node.metadata["resolver_matched_alias"] = true
100
+ }
101
+
102
+ // A point-only row stores its coordinate as both corners, and a row stored
103
+ // in single precision can hold them a few millionths of a degree apart,
104
+ // so only an extent wider than that measures the place's size.
89
105
  const bbox = resolved.bbox
90
106
 
91
- if (bbox && (bbox.minLat !== bbox.maxLat || bbox.minLon !== bbox.maxLon)) {
107
+ if (bbox && (bbox.maxLat - bbox.minLat > POINT_EXTENT_DEGREES || bbox.maxLon - bbox.minLon > POINT_EXTENT_DEGREES)) {
92
108
  node.metadata["resolver_bbox"] = bbox
93
109
  }
94
110
 
package/lib/index.ts CHANGED
@@ -53,6 +53,7 @@ export {
53
53
  adminLadderFor,
54
54
  adminLadderForNodes,
55
55
  AREA_GRADE_POSTALCODE_SPECIFICITY,
56
+ ladderWithContainedDependentLocality,
56
57
  mostSpecificResolved,
57
58
  resolvedSpecificity,
58
59
  } from "#admin/winner"
@@ -4,10 +4,10 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
6
 
7
- import { candidateSystemsForPostcode } from "@mailwoman/codex"
8
7
  import { firstNodeWhere, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
9
8
  import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
10
- import { haversineKm } from "@mailwoman/spatial"
9
+ import { candidateSystemsForPostcode } from "@mailwoman/postcode/systems"
10
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
11
11
 
12
12
  /**
13
13
  * The default maximum distance, in kilometers, between a postcode and a locality
@@ -225,7 +225,7 @@ async function coherenceIn(
225
225
 
226
226
  for (const candidate of localityHits) {
227
227
  if (!candidate.exactMatch || !hasCoord(candidate)) continue
228
- const distanceKm = haversineKm(postcodePlace.lat, postcodePlace.lon, candidate.lat, candidate.lon)
228
+ const distanceKm = haversine(postcodePlace.lat, postcodePlace.lon, candidate.lat, candidate.lon)
229
229
 
230
230
  if (distanceKm > thresholdKm) continue
231
231
 
@@ -324,7 +324,7 @@ export async function findPostcodeCountryScope(
324
324
 
325
325
  const contradicted =
326
326
  ownPostcode != null &&
327
- haversineKm(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > thresholdKm
327
+ haversine(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > thresholdKm
328
328
 
329
329
  if (country !== defaultCountry && !contradicted && !verdicts.has(country)) {
330
330
  verdicts.set(country, {
@@ -4,43 +4,49 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
6
 
7
- import { candidateSystemsForPostcode, SYSTEM_CODES } from "@mailwoman/codex"
8
- import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
9
- import { isUSStateAbbreviation } from "@mailwoman/codex/us"
10
- import { collectNodes, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
7
+ import { matchCountry, matchSubdivision, matchSubdivisionsAnywhere } from "@mailwoman/codex/country"
8
+ import { collectNodes, POSTCODE_SHAPE_EXCLUDED_KEY, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
9
+ import { acceptPostcode, postcodeSyntax } from "@mailwoman/postcode/country-formats"
11
10
 
12
- const SYSTEM_UNIVERSE: ReadonlySet<string> = new Set<string>(SYSTEM_CODES.map((system) => system.toUpperCase()))
11
+ /**
12
+ * Whether libaddressinput states a postcode syntax for `country`, so a span can be checked against it.
13
+ */
14
+ function statesSyntax(country: string): boolean {
15
+ return postcodeSyntax(country) != null
16
+ }
13
17
 
14
18
  /**
15
19
  * Records which postcode spans {@link applyPostcodeShapeCoherence} confirmed, excluded, or abstained on.
16
20
  *
17
- * It also records the postcode systems of the first confirmed span.
21
+ * It also records the countries whose syntax the first confirmed span has.
18
22
  */
19
23
  export interface PostcodeShapeVerdict {
20
24
  /**
21
- * The upper-case postcode systems of the first confirmed span, passed to
22
- * `findPostcodeCountryScope` as its candidate systems; `null` when no span was confirmed.
25
+ * The upper-case countries whose postcode syntax the first confirmed span has.
26
+ *
27
+ * `findPostcodeCountryScope` takes them as its candidates.
28
+ * The value is `null` when no span was confirmed.
23
29
  */
24
30
  narrowing: string[] | null
25
31
 
26
32
  /**
27
- * Postcode values whose shape fits a system used by a sibling country or region span.
33
+ * Postcode values that have the postcode syntax of a country a sibling country or region span names.
28
34
  */
29
35
  confirmed: string[]
30
36
 
31
37
  /**
32
- * Postcode values whose shape fits none of the systems the siblings name.
38
+ * Postcode values that have the postcode syntax of no country the siblings name.
33
39
  */
34
40
  excluded: string[]
35
41
 
36
42
  /**
37
- * Postcode values left undecided because they match no known postcode shape
38
- * or the tree names no country or region.
43
+ * Postcode values left undecided because the tree names no country
44
+ * or region with a stated postcode syntax.
39
45
  */
40
46
  abstained: string[]
41
47
  }
42
48
 
43
- function collectSiblingSystems(roots: readonly AddressNode[]): Set<string> {
49
+ function collectSiblingCountries(roots: readonly AddressNode[]): Set<string> {
44
50
  const out = new Set<string>()
45
51
 
46
52
  for (const n of walkNodes(roots)) {
@@ -51,32 +57,34 @@ function collectSiblingSystems(roots: readonly AddressNode[]): Set<string> {
51
57
  // A constituent country such as `England` tagged `country` still fixes its sovereign state.
52
58
  const sub = matchSubdivision(n.value)
53
59
 
54
- if (sub && SYSTEM_UNIVERSE.has(sub.country.toUpperCase())) {
60
+ if (sub && statesSyntax(sub.country)) {
55
61
  out.add(sub.country.toUpperCase())
56
62
  }
57
63
 
58
64
  continue
59
65
  }
60
66
 
61
- const system = isUSStateAbbreviation(matched.iso2) ? "US" : matched.iso2.toUpperCase()
67
+ // The match's ISO code is the country, even where it spells a US state abbreviation (`IN`, `DE`, `CA`).
68
+ const country = matched.iso2.toUpperCase()
62
69
 
63
- if (SYSTEM_UNIVERSE.has(system)) {
64
- out.add(system)
70
+ if (statesSyntax(country)) {
71
+ out.add(country)
65
72
  }
66
73
 
67
74
  continue
68
75
  }
69
76
 
70
77
  if (n.tag === "region") {
71
- const sub = matchSubdivision(n.value)
72
-
73
- if (sub && SYSTEM_UNIVERSE.has(sub.country.toUpperCase())) {
74
- out.add(sub.country.toUpperCase())
78
+ // An abbreviation such as `WA` names a subdivision in more than one country, and each is a candidate.
79
+ for (const sub of matchSubdivisionsAnywhere(n.value)) {
80
+ if (statesSyntax(sub.country)) {
81
+ out.add(sub.country.toUpperCase())
82
+ }
75
83
  }
76
84
 
77
85
  const hint = n.metadata?.["country_hint"]
78
86
 
79
- if (typeof hint === "string" && SYSTEM_UNIVERSE.has(hint.toUpperCase())) {
87
+ if (typeof hint === "string" && statesSyntax(hint)) {
80
88
  out.add(hint.toUpperCase())
81
89
  }
82
90
  }
@@ -86,11 +94,11 @@ function collectSiblingSystems(roots: readonly AddressNode[]): Set<string> {
86
94
  }
87
95
 
88
96
  /**
89
- * Checks each postcode span's shape against the postcode systems of the countries
97
+ * Checks each postcode span against the libaddressinput postcode syntax of the countries
90
98
  * and regions listed in the same tree, without querying a backend.
91
99
  *
92
- * A span that fits none of those systems is excluded: an all-digit span is retagged
93
- * `house_number`, and any other span is stamped `postcode_shape_excluded`.
100
+ * A span that has none of those syntaxes is excluded: it keeps its tag and text and is stamped
101
+ * `postcode_shape_excluded`, which takes it out of the result slots (`isShapeExcludedPostcode`).
94
102
  */
95
103
  export function applyPostcodeShapeCoherence(roots: readonly AddressNode[]): PostcodeShapeVerdict {
96
104
  const verdict: PostcodeShapeVerdict = { narrowing: null, confirmed: [], excluded: [], abstained: [] }
@@ -99,24 +107,16 @@ export function applyPostcodeShapeCoherence(roots: readonly AddressNode[]): Post
99
107
 
100
108
  if (!postcodes.length) return verdict
101
109
 
102
- const siblingSystems = collectSiblingSystems(roots)
110
+ const siblingCountries = collectSiblingCountries(roots)
103
111
 
104
112
  for (const node of postcodes) {
105
113
  const code = node.value.trim()
106
- const systems = candidateSystemsForPostcode(code)
107
-
108
- if (!systems.length) {
109
- verdict.abstained.push(code)
110
-
111
- continue
112
- }
113
-
114
- const intersection = systems.map((system) => system.toUpperCase()).filter((system) => siblingSystems.has(system))
114
+ const intersection = [...siblingCountries].filter((country) => acceptPostcode(code, country) != null)
115
115
 
116
116
  if (intersection.length) {
117
117
  verdict.confirmed.push(code)
118
118
 
119
- node.metadata = { ...node.metadata, postcode_shape_systems: intersection }
119
+ node.metadata = { ...node.metadata, postcode_shape_countries: intersection }
120
120
 
121
121
  if (!verdict.narrowing) {
122
122
  verdict.narrowing = intersection
@@ -125,14 +125,12 @@ export function applyPostcodeShapeCoherence(roots: readonly AddressNode[]): Post
125
125
  continue
126
126
  }
127
127
 
128
- if (siblingSystems.size) {
128
+ if (siblingCountries.size) {
129
129
  verdict.excluded.push(code)
130
130
 
131
- if (/^\d+$/.test(code)) {
132
- node.tag = "house_number"
133
- } else {
134
- node.metadata = { ...node.metadata, postcode_shape_excluded: true }
135
- }
131
+ // The span keeps its tag and text, and the stamp takes it out of the result slots.
132
+ // A retag to `house_number` would overwrite the house number the parse already found.
133
+ node.metadata = { ...node.metadata, [POSTCODE_SHAPE_EXCLUDED_KEY]: true }
136
134
 
137
135
  continue
138
136
  }
@@ -142,12 +140,3 @@ export function applyPostcodeShapeCoherence(roots: readonly AddressNode[]): Post
142
140
 
143
141
  return verdict
144
142
  }
145
-
146
- /**
147
- * Returns true for a postcode span excluded by shape coherence when it could not be retagged.
148
- *
149
- * Every postcode consumer in the resolver must skip that span.
150
- */
151
- export function isShapeExcludedPostcode(node: AddressNode): boolean {
152
- return node.tag === "postcode" && node.metadata?.["postcode_shape_excluded"] === true
153
- }
@@ -6,7 +6,7 @@
6
6
 
7
7
  import type { AddressTree } from "@mailwoman/core/decoder"
8
8
  import { stringifyJSON } from "@mailwoman/core/json"
9
- import type { BackendCapabilityGap, GazetteerArtifactCoverage, ResolveOpts, Resolver } from "@mailwoman/core/resolver"
9
+ import type { GazetteerArtifactCoverage, ResolveOpts, Resolver } from "@mailwoman/core/resolver"
10
10
 
11
11
  /**
12
12
  * Describes the `ResolveOpts` sent over the wire.
@@ -91,7 +91,6 @@ export class RemoteResolver implements Resolver {
91
91
  readonly #timeoutMs: number
92
92
  readonly #headers: Record<string, string>
93
93
  readonly artifactCoverage: GazetteerArtifactCoverage | null = null
94
- readonly capabilityGaps: readonly BackendCapabilityGap[] | null = null
95
94
 
96
95
  constructor(opts: RemoteResolverOpts) {
97
96
  if (!opts.endpoint) throw new Error("RemoteResolver: `endpoint` is required")
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Reads a country written as a code of three or more capitals: `USA`, `RUS`, `RMI`.
7
+ *
8
+ * Two-letter codes stay out, because `CA`, `IN` and `LA` are also regions and cities.
9
+ *
10
+ * The codes a country claims are its ISO 3166-1 alpha-3 code and the abbreviations the codex curates:
11
+ * `COUNTRY_ABBREVIATIONS` (`UAE`, `PNG`, `RMI`) and the capitalized entries of `COUNTRY_SURFACE_FORMS` (`GER`, `ROM`).
12
+ * With the ISO codes as the only claimed set, `UAE` would read as Mount Aue, an aerodrome in Papua New Guinea with
13
+ * one Wikipedia edition, because IATA assigns that code too. The abbreviation table records what a country's own users write, and a code
14
+ * written for a country is read as that country wherever it is written: as a whole input here, and as a region in
15
+ * `readRegionCodeAsCountry`.
16
+ *
17
+ * A code a country claims answers the country ahead of any airport holding the same IATA code. Of the 249 alpha-3
18
+ * codes, 191 are also an airport's code in Wikidata's P238 file: `AUS` (Austin–Bergstrom), `FRA` (Frankfurt), `HND`
19
+ * (Tokyo Haneda), `USA` (Concord Regional). `applyLandmark` lists that airport as the country's alternative. A code
20
+ * no country claims answers the airport: `SFO`, `LHR`, `DTW`.
21
+ */
22
+
23
+ import { COUNTRY_ABBREVIATIONS, matchCountry, matchSubdivision } from "@mailwoman/codex/country"
24
+ import { countryDisplayNames } from "@mailwoman/codex/country/display-names"
25
+ import { firstNodeWhere, type AddressNode, type AddressTree } from "@mailwoman/core/decoder"
26
+ import type { ResolverBackend } from "@mailwoman/core/resolver"
27
+
28
+ import { decorateNode } from "#decorate-node"
29
+
30
+ const ABBREVIATIONS: ReadonlySet<string> = new Set(Object.values(COUNTRY_ABBREVIATIONS).flat())
31
+
32
+ /**
33
+ * Returns the alpha-2 code of a country written as a code, or null for any other text.
34
+ *
35
+ * The text has to be the whole code in capitals, three or more characters, and not a subdivision code.
36
+ * `AUS`, `HND` and `UAE` are countries.
37
+ * `SFO`, `Aus` and `IN` are not.
38
+ *
39
+ * The codex holds the ISO 3166-1 alpha-3 codes and the curated abbreviations.
40
+ * The registry's country records stay out of this module, because they would add
41
+ * 51 KB to every browser bundle that holds the resolver.
42
+ */
43
+ export function writtenCountryCode(written: string): string | null {
44
+ const value = written.trim()
45
+
46
+ if (!/^[\p{Lu}.]{3,}$/u.test(value) || matchSubdivision(value)) return null
47
+
48
+ return matchCountry(value)?.iso2 ?? null
49
+ }
50
+
51
+ /**
52
+ * Reads a region written as a country abbreviation as the country, so the walk is scoped to that country.
53
+ *
54
+ * `Anal Island, Likiep Atoll, RMI` parses `RMI` as a region.
55
+ * The parse stays unchanged for the caller, so the change applies to a copy of the tree.
56
+ *
57
+ * An ISO code stays a region here, because `Fort Wayne, IND` and `Denver, COL` abbreviate US states.
58
+ */
59
+ export function readRegionCodeAsCountry(tree: AddressTree): AddressTree {
60
+ const isCountry = (node: AddressNode) => node.tag === "country"
61
+ const isCode = (node: AddressNode) => node.tag === "region" && ABBREVIATIONS.has(node.value.trim())
62
+
63
+ if (firstNodeWhere(tree.roots, isCountry) || !firstNodeWhere(tree.roots, isCode)) return tree
64
+
65
+ const copy = structuredClone(tree)
66
+
67
+ firstNodeWhere(copy.roots, isCode)!.tag = "country"
68
+
69
+ return copy
70
+ }
71
+
72
+ /**
73
+ * Answers an input that is only a country code with that country, ahead of any reading the parse gave it.
74
+ */
75
+ export async function applyCountryCode(roots: AddressNode[], raw: string, backend: ResolverBackend): Promise<void> {
76
+ const written = raw.trim()
77
+ const iso2 = writtenCountryCode(written)
78
+
79
+ if (!iso2) return
80
+
81
+ // The gazetteer does not hold every code, so the country's English names follow the written form.
82
+ for (const text of [written, ...countryDisplayNames(iso2, ["en"])]) {
83
+ const places = await backend.findPlace({ text, placetype: "country", country: iso2 })
84
+ const place = places.find((candidate) => candidate.country === iso2)
85
+
86
+ if (!place) continue
87
+
88
+ const node: AddressNode = {
89
+ tag: "country",
90
+ value: written,
91
+ start: 0,
92
+ end: written.length,
93
+ confidence: 1,
94
+ children: [],
95
+ }
96
+
97
+ decorateNode(node, place, [])
98
+ roots.splice(0, roots.length, node)
99
+
100
+ return
101
+ }
102
+ }