@mailwoman/resolver 11.0.0 → 11.2.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 (142) hide show
  1. package/README.md +4 -4
  2. package/lib/admin/coherence-passes.ts +14 -20
  3. package/lib/admin/containment.ts +6 -5
  4. package/lib/admin/county-designator.ts +91 -0
  5. package/lib/admin/jp-municipality.ts +3 -3
  6. package/lib/admin/winner.ts +5 -5
  7. package/lib/admin.ts +2 -5
  8. package/lib/bare-toponym-race.ts +12 -10
  9. package/lib/decorate-node.ts +51 -8
  10. package/lib/fold-name.ts +8 -8
  11. package/lib/index.ts +11 -8
  12. package/lib/plausibility.ts +2 -5
  13. package/lib/postcode/country-coherence.ts +4 -7
  14. package/lib/postcode/prefix.ts +4 -7
  15. package/lib/postcode/shape-coherence.ts +5 -8
  16. package/lib/postcode.ts +2 -5
  17. package/lib/remote-resolver.ts +2 -5
  18. package/lib/rerank.ts +7 -8
  19. package/lib/resolve/country-code.ts +22 -18
  20. package/lib/resolve/landmark.ts +19 -12
  21. package/lib/resolve/passes.ts +19 -9
  22. package/lib/resolve/region-city.ts +192 -8
  23. package/lib/resolve/whole-input.ts +49 -0
  24. package/lib/resolve.ts +197 -48
  25. package/lib/span-rescore.ts +61 -28
  26. package/lib/street/evidence.ts +2 -5
  27. package/lib/street/tier.ts +9 -12
  28. package/lib/street.ts +2 -5
  29. package/lib/toponym-prior.ts +4 -7
  30. package/out/admin/coherence-passes.d.ts +2 -7
  31. package/out/admin/coherence-passes.d.ts.map +1 -1
  32. package/out/admin/coherence-passes.js +14 -20
  33. package/out/admin/coherence-passes.js.map +1 -1
  34. package/out/admin/containment.d.ts +3 -5
  35. package/out/admin/containment.d.ts.map +1 -1
  36. package/out/admin/containment.js +5 -5
  37. package/out/admin/containment.js.map +1 -1
  38. package/out/admin/county-designator.d.ts +33 -0
  39. package/out/admin/county-designator.d.ts.map +1 -0
  40. package/out/admin/county-designator.js +65 -0
  41. package/out/admin/county-designator.js.map +1 -0
  42. package/out/admin/jp-municipality.d.ts +0 -3
  43. package/out/admin/jp-municipality.d.ts.map +1 -1
  44. package/out/admin/jp-municipality.js +2 -15
  45. package/out/admin/jp-municipality.js.map +1 -1
  46. package/out/admin/winner.d.ts +2 -5
  47. package/out/admin/winner.d.ts.map +1 -1
  48. package/out/admin/winner.js +2 -9
  49. package/out/admin/winner.js.map +1 -1
  50. package/out/admin.d.ts +0 -5
  51. package/out/admin.d.ts.map +1 -1
  52. package/out/admin.js +2 -5
  53. package/out/admin.js.map +1 -1
  54. package/out/bare-toponym-race.d.ts +0 -11
  55. package/out/bare-toponym-race.d.ts.map +1 -1
  56. package/out/bare-toponym-race.js +3 -12
  57. package/out/bare-toponym-race.js.map +1 -1
  58. package/out/decorate-node.d.ts +14 -6
  59. package/out/decorate-node.d.ts.map +1 -1
  60. package/out/decorate-node.js +46 -10
  61. package/out/decorate-node.js.map +1 -1
  62. package/out/fold-name.d.ts +5 -8
  63. package/out/fold-name.d.ts.map +1 -1
  64. package/out/fold-name.js +7 -8
  65. package/out/fold-name.js.map +1 -1
  66. package/out/index.d.ts +8 -8
  67. package/out/index.d.ts.map +1 -1
  68. package/out/index.js +10 -8
  69. package/out/index.js.map +1 -1
  70. package/out/plausibility.d.ts +0 -5
  71. package/out/plausibility.d.ts.map +1 -1
  72. package/out/plausibility.js +2 -5
  73. package/out/plausibility.js.map +1 -1
  74. package/out/postcode/country-coherence.d.ts +2 -7
  75. package/out/postcode/country-coherence.d.ts.map +1 -1
  76. package/out/postcode/country-coherence.js +3 -6
  77. package/out/postcode/country-coherence.js.map +1 -1
  78. package/out/postcode/prefix.d.ts +2 -7
  79. package/out/postcode/prefix.d.ts.map +1 -1
  80. package/out/postcode/prefix.js +3 -6
  81. package/out/postcode/prefix.js.map +1 -1
  82. package/out/postcode/shape-coherence.d.ts +1 -6
  83. package/out/postcode/shape-coherence.d.ts.map +1 -1
  84. package/out/postcode/shape-coherence.js +4 -7
  85. package/out/postcode/shape-coherence.js.map +1 -1
  86. package/out/postcode.d.ts +0 -5
  87. package/out/postcode.d.ts.map +1 -1
  88. package/out/postcode.js +2 -5
  89. package/out/postcode.js.map +1 -1
  90. package/out/remote-resolver.d.ts +0 -5
  91. package/out/remote-resolver.d.ts.map +1 -1
  92. package/out/remote-resolver.js +2 -5
  93. package/out/remote-resolver.js.map +1 -1
  94. package/out/rerank.d.ts +3 -7
  95. package/out/rerank.d.ts.map +1 -1
  96. package/out/rerank.js +3 -10
  97. package/out/rerank.js.map +1 -1
  98. package/out/resolve/country-code.d.ts +3 -24
  99. package/out/resolve/country-code.d.ts.map +1 -1
  100. package/out/resolve/country-code.js +21 -18
  101. package/out/resolve/country-code.js.map +1 -1
  102. package/out/resolve/landmark.d.ts +10 -11
  103. package/out/resolve/landmark.d.ts.map +1 -1
  104. package/out/resolve/landmark.js +18 -12
  105. package/out/resolve/landmark.js.map +1 -1
  106. package/out/resolve/passes.d.ts +7 -7
  107. package/out/resolve/passes.d.ts.map +1 -1
  108. package/out/resolve/passes.js +11 -8
  109. package/out/resolve/passes.js.map +1 -1
  110. package/out/resolve/region-city.d.ts +34 -7
  111. package/out/resolve/region-city.d.ts.map +1 -1
  112. package/out/resolve/region-city.js +159 -8
  113. package/out/resolve/region-city.js.map +1 -1
  114. package/out/resolve/whole-input.d.ts +14 -0
  115. package/out/resolve/whole-input.d.ts.map +1 -0
  116. package/out/resolve/whole-input.js +37 -0
  117. package/out/resolve/whole-input.js.map +1 -0
  118. package/out/resolve.d.ts +0 -8
  119. package/out/resolve.d.ts.map +1 -1
  120. package/out/resolve.js +124 -46
  121. package/out/resolve.js.map +1 -1
  122. package/out/span-rescore.d.ts +12 -16
  123. package/out/span-rescore.d.ts.map +1 -1
  124. package/out/span-rescore.js +46 -19
  125. package/out/span-rescore.js.map +1 -1
  126. package/out/street/evidence.d.ts +0 -5
  127. package/out/street/evidence.d.ts.map +1 -1
  128. package/out/street/evidence.js +2 -5
  129. package/out/street/evidence.js.map +1 -1
  130. package/out/street/tier.d.ts +3 -8
  131. package/out/street/tier.d.ts.map +1 -1
  132. package/out/street/tier.js +7 -10
  133. package/out/street/tier.js.map +1 -1
  134. package/out/street.d.ts +0 -5
  135. package/out/street.d.ts.map +1 -1
  136. package/out/street.js +2 -5
  137. package/out/street.js.map +1 -1
  138. package/out/toponym-prior.d.ts +2 -7
  139. package/out/toponym-prior.d.ts.map +1 -1
  140. package/out/toponym-prior.js +4 -7
  141. package/out/toponym-prior.js.map +1 -1
  142. package/package.json +9 -9
@@ -1,23 +1,27 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
5
  * Reads a country written as a code of three or more capitals: `USA`, `RUS`, `RMI`.
7
6
  *
8
7
  * Two-letter codes stay out, because `CA`, `IN` and `LA` are also regions and cities.
9
8
  *
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`.
9
+ * The codes a country claims are its ISO 3166-1 alpha-3 code and the abbreviations
10
+ * the codex curates: `COUNTRY_ABBREVIATIONS` (`UAE`, `PNG`, `RMI`) and the
11
+ * 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
13
+ * in Papua New Guinea with one Wikipedia edition, because IATA assigns that code too.
14
+ *
15
+ * The abbreviation table records what a country's own users write, and a code written
16
+ * for a country is read as that country wherever it is written: as a whole input here,
17
+ * and as a region in `readRegionCodeAsCountry`.
18
+ *
19
+ * A code a country claims answers the country ahead of any airport holding the same IATA code.
20
+ * Of the 249 alpha-3 codes, 191 are also an airport's code in Wikidata's P238 file:
21
+ * `AUS` (Austin–Bergstrom), `FRA` (Frankfurt), `HND` (Tokyo Haneda), `USA` (Concord Regional).
16
22
  *
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`.
23
+ * `applyLandmark` lists that airport as the country's alternative.
24
+ * A code no country claims answers the airport: `SFO`, `LHR`, `DTW`.
21
25
  */
22
26
 
23
27
  import { COUNTRY_ABBREVIATIONS, matchCountry, matchSubdivision } from "@mailwoman/codex/country"
@@ -37,8 +41,8 @@ const ABBREVIATIONS: ReadonlySet<string> = new Set(Object.values(COUNTRY_ABBREVI
37
41
  * `SFO`, `Aus` and `IN` are not.
38
42
  *
39
43
  * 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.
44
+ * The registry's country records stay out of this module, because they'd add 51
45
+ * KB to every browser bundle that holds the resolver.
42
46
  */
43
47
  export function writtenCountryCode(written: string): string | null {
44
48
  const value = written.trim()
@@ -70,7 +74,7 @@ export function readRegionCodeAsCountry(tree: AddressTree): AddressTree {
70
74
  }
71
75
 
72
76
  /**
73
- * Answers an input that is only a country code with that country, ahead of any reading the parse gave it.
77
+ * Answers an input that's only a country code with that country, ahead of any reading the parse gave it.
74
78
  */
75
79
  export async function applyCountryCode(roots: AddressNode[], raw: string, backend: ResolverBackend): Promise<void> {
76
80
  const written = raw.trim()
@@ -78,7 +82,7 @@ export async function applyCountryCode(roots: AddressNode[], raw: string, backen
78
82
 
79
83
  if (!iso2) return
80
84
 
81
- // The gazetteer does not hold every code, so the country's English names follow the written form.
85
+ // The gazetteer doesn't hold every code, so the country's English names follow the written form.
82
86
  for (const text of [written, ...countryDisplayNames(iso2, ["en"])]) {
83
87
  const places = await backend.findPlace({ text, placetype: "country", country: iso2 })
84
88
  const place = places.find((candidate) => candidate.country === iso2)
@@ -1,18 +1,20 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
+ * Answers a query that's a place's name, with no street or postcode, from the landmark layer.
5
6
  *
6
- * Answers a query that is a place's name, with no street or postcode, from the landmark layer.
7
+ * The place of that name with the most Wikipedia language editions answers,
8
+ * and the others stay as alternatives.
9
+ * A prominence of log10(sitelinks) puts the lead on the scale the admin tier's `declared_ambiguity`
10
+ * margin reads, so a close call is declared by the same rule that declares one between two towns.
7
11
  *
8
- * The place of that name with the most Wikipedia language editions answers, and the others stay as alternatives. A
9
- * prominence of log10(sitelinks) puts the lead on the scale the admin tier's `declared_ambiguity` margin reads, so a
10
- * close call is declared by the same rule that declares one between two towns.
12
+ * A code written in capitals reads by one rule.
13
+ * A code a country is written as answers the country, and the airport holding the same
14
+ * IATA code is listed as an alternative: `AUS` is Australia, then Austin–Bergstrom.
11
15
  *
12
- * A code written in capitals reads by one rule. A code a country is written as answers the country, and the airport
13
- * holding the same IATA code is listed as an alternative: `AUS` is Australia, then Austin–Bergstrom. Every other code
14
- * answers the place holding it: `SFO`, `LHR` and `DTW` are airports. `writtenCountryCode` states which codes a country
15
- * claims.
16
+ * Every other code answers the place holding it: `SFO`, `LHR` and `DTW` are airports.
17
+ * `writtenCountryCode` states which codes a country claims.
16
18
  */
17
19
 
18
20
  import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
@@ -102,7 +104,7 @@ function placeOf(hit: LandmarkHit): ResolvedPlace {
102
104
  * `AUS` answers Australia, and Austin–Bergstrom International Airport is the
103
105
  * reading a caller can pick instead.
104
106
  * A word spelled like the code, such as the town of Usa under `USA`,
105
- * is not a holder of the code and stays out.
107
+ * isn't a holder of the code and stays out.
106
108
  *
107
109
  * The list sits on a resolved country node, so a country the gazetteer left unresolved keeps its parse.
108
110
  *
@@ -185,6 +187,11 @@ export async function applyLandmark(roots: AddressNode[], raw: string, landmarks
185
187
  // OpenStreetMap holds a place spelled like a street in some other town: `Wall Street` also answers in Utah.
186
188
  if (readsAsStreet) return
187
189
 
190
+ // A bare name that several OpenStreetMap places hold names none of them: `bus stop`
191
+ // is held in India and Kiribati, and `The Big Apple` in South Carolina and Australia.
192
+ // With no context to choose, the layer abstains.
193
+ if (!hasContext && candidates.length > 1) return
194
+
188
195
  // A school or a park in OpenStreetMap can share its town's name,
189
196
  // so a place holding the whole name keeps it.
190
197
  // A park reading beats a row with no measured population, as `Piedmont Park`
@@ -1,8 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
8
5
  import { isShapeExcludedPostcode, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
@@ -308,10 +305,16 @@ export interface ResolutionState {
308
305
  */
309
306
  dependentLocalityContainment: boolean
310
307
 
308
+ /**
309
+ * Whether a `locality` node is looked up as its region's WOF `county` when no locality in
310
+ * the region matches it and its value is written with its country's county designator.
311
+ */
312
+ countyDesignatorFallback: boolean
313
+
311
314
  /**
312
315
  * The tree's first region value.
313
316
  *
314
- * The region and locality nodes are siblings, so the walk would not otherwise
317
+ * The region and locality nodes are siblings, so the walk wouldn't otherwise
315
318
  * pass the region to the locality lookup.
316
319
  * It applies only with {@link ResolutionState.adminContainmentRerank}
317
320
  * and no caller-supplied default country.
@@ -355,7 +358,6 @@ export async function applySpanRescore(
355
358
  thresholdKm: opts.spanRescoreThresholdKm,
356
359
 
357
360
  postalCompoundRecovery: opts.postalCompoundRecovery,
358
- spanRescoreRequireContextRemainder: opts.spanRescoreRequireContextRemainder,
359
361
  ...(opts.isVenueCategoryWord ? { isVenueCategoryWord: opts.isVenueCategoryWord } : {}),
360
362
  })
361
363
  } catch {
@@ -382,7 +384,15 @@ export async function applySpanRescore(
382
384
 
383
385
  decorateNode(node, hit.place, hit.alternatives)
384
386
 
385
- node.metadata = { ...node.metadata, span_rescore: true, rescore_postcode_verified: hit.postcodeVerified }
387
+ // `rescore_drops_name` tells the geocode that this locality may scope a venue lookup.
388
+ // It answers only when a venue answers near it.
389
+ node.metadata = {
390
+ ...node.metadata,
391
+ span_rescore: true,
392
+ rescore_postcode_verified: hit.postcodeVerified,
393
+ rescore_drops_name: hit.dropsName,
394
+ }
395
+
386
396
  roots.push(node)
387
397
 
388
398
  if (opts.traceSink) {
@@ -519,7 +529,7 @@ const ROOFTOP_NAMESAKE_LIMIT = 25
519
529
  *
520
530
  * A rooftop row is an observed point, so an unreconciled locality is never moved onto it.
521
531
  * The node records the distance as `rooftop_outside_locality_km`, and the result
522
- * reports the locality as a component the answer did not follow.
532
+ * reports the locality as a component the answer didn't follow.
523
533
  */
524
534
  export async function applyRooftopConsistency(
525
535
  roots: readonly AddressNode[],
@@ -1,11 +1,9 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
8
5
  import type { ResolverBackend } from "@mailwoman/core/resolver"
6
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
9
7
 
10
8
  import { decorateNode } from "#decorate-node"
11
9
  import { streetNumberPairs } from "#street/tier"
@@ -20,13 +18,22 @@ import { streetNumberPairs } from "#street/tier"
20
18
  *
21
19
  * A place held at both levels occurs wherever a city is its own province, so the test reads the hierarchy.
22
20
  *
23
- * A bare region stays a region, because only a street and number say the input
24
- * means somewhere a street can be.
21
+ * `Altona, Hamburg` and `Triana, Sevilla` state a resolved district, and a district also sits inside a city.
22
+ *
23
+ * A bare region stays a region, because only a street and number or a district
24
+ * say the input means somewhere inside a city.
25
+ *
26
+ * A locality the gazetteer didn't resolve leaves the region as the only place,
27
+ * and Bristol's region point lies in the Bristol Channel, so the city answers there too.
25
28
  */
26
29
  export async function applyRegionCity(roots: AddressNode[], backend: ResolverBackend): Promise<void> {
27
30
  const nodes = [...walkNodes(roots)]
28
31
 
29
- if (nodes.some((node) => node.tag === "locality") || !streetNumberPairs(roots).length) return
32
+ // A street with a number, or a resolved district, places the input inside a city.
33
+ const insideACity =
34
+ streetNumberPairs(roots).length > 0 || nodes.some((node) => node.tag === "dependent_locality" && node.placeID)
35
+
36
+ if (nodes.some((node) => node.tag === "locality" && node.placeID) || !insideACity) return
30
37
 
31
38
  const region = nodes.find((node) => node.tag === "region" && node.placeID?.startsWith("wof:"))
32
39
 
@@ -44,6 +51,24 @@ export async function applyRegionCity(roots: AddressNode[], backend: ResolverBac
44
51
  region.tag = "locality"
45
52
  decorateNode(region, city, others)
46
53
  region.metadata = { ...region.metadata, region_city: true }
54
+
55
+ // A district inside the city's box answers ahead of the city, as the walk's containment stamp lets it.
56
+ for (const district of nodes) {
57
+ if (district.tag !== "dependent_locality" || !district.placeID || district.lat == null || district.lon == null)
58
+ continue
59
+
60
+ const box = city.bbox
61
+
62
+ if (
63
+ box &&
64
+ district.lat >= box.minLat &&
65
+ district.lat <= box.maxLat &&
66
+ district.lon >= box.minLon &&
67
+ district.lon <= box.maxLon
68
+ ) {
69
+ district.metadata = { ...district.metadata, contained_by_parent: true }
70
+ }
71
+ }
47
72
  }
48
73
 
49
74
  /**
@@ -69,3 +94,162 @@ export async function applyLocalityAsRegion(
69
94
  locality.tag = "region"
70
95
  decorateNode(locality, region, others)
71
96
  }
97
+
98
+ /**
99
+ * Reads a country as the region of the same name when only that region holds the stated town.
100
+ *
101
+ * `Savannah, Georgia` parses `Georgia` as the country, and the country holds no Savannah.
102
+ * `Tbilisi, Georgia` keeps the country, because the country holds Tbilisi.
103
+ *
104
+ * A caller's US scope leaves the country of Georgia unresolved, so that node has no country to test against.
105
+ */
106
+ export async function applyCountryAsRegion(roots: AddressNode[], backend: ResolverBackend): Promise<void> {
107
+ const nodes = [...walkNodes(roots)]
108
+ const country = nodes.find((node) => node.tag === "country" && node.value.trim())
109
+ const locality = nodes.find((node) => node.tag === "locality" && node.value.trim())
110
+
111
+ if (!country || !locality || nodes.some((node) => node.tag === "region")) return
112
+
113
+ const stated = country.metadata?.["resolver_country"]
114
+
115
+ if (typeof stated === "string") {
116
+ const [local] = await backend.findPlace({ text: locality.value, placetype: "locality", country: stated })
117
+
118
+ if (local?.exactMatch) return
119
+ }
120
+
121
+ for (const region of await backend.findPlace({ text: country.value, placetype: "region" })) {
122
+ if (!region.exactMatch) continue
123
+
124
+ const [city, ...others] = await backend.findPlace({
125
+ text: locality.value,
126
+ placetype: "locality",
127
+ parentID: region.id,
128
+ })
129
+
130
+ if (!city?.exactMatch || city.regionScopeMiss) continue
131
+
132
+ country.tag = "region"
133
+ decorateNode(country, region, [])
134
+ decorateNode(locality, city, others)
135
+
136
+ return
137
+ }
138
+ }
139
+
140
+ /**
141
+ * The tags whose spans together write a street's name.
142
+ */
143
+ const STREET_PART_TAGS: ReadonlySet<string> = new Set([
144
+ "street_prefix",
145
+ "street_prefix_particle",
146
+ "street",
147
+ "street_suffix",
148
+ ])
149
+
150
+ /**
151
+ * How far a town may sit from the stated postcode's point and still be the place the postcode serves.
152
+ */
153
+ const TOWN_POSTCODE_REACH_KM = 15
154
+
155
+ /**
156
+ * Removes the given nodes wherever they sit in the tree.
157
+ */
158
+ function removeNodes(list: AddressNode[], drop: ReadonlySet<AddressNode>): void {
159
+ for (let index = list.length - 1; index >= 0; index--) {
160
+ const node = list[index]!
161
+
162
+ if (drop.has(node)) {
163
+ list.splice(index, 1)
164
+ } else if (node.children?.length) {
165
+ removeNodes(node.children, drop)
166
+ }
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Reads an unnumbered street as the town of that name when the town holds the stated postcode.
172
+ *
173
+ * `Alameda, CA 94501` and `Crocketts Bluff, AR 72038` parse the town as a street,
174
+ * because a name before a region and postcode is where a street sits in a full address.
175
+ * A street name and a town name agree this close to the postcode's point only when they
176
+ * name one place, so a real street such as `Main Street, CA 94501` keeps its tag.
177
+ */
178
+ export async function applyStreetAsTown(roots: AddressNode[], backend: ResolverBackend): Promise<void> {
179
+ const nodes = [...walkNodes(roots)]
180
+ const parts = nodes.filter((node) => STREET_PART_TAGS.has(node.tag)).toSorted((a, b) => a.start - b.start)
181
+ const postcode = nodes.find((node) => node.tag === "postcode" && node.lat != null && node.lon != null)
182
+
183
+ if (!parts.some((node) => node.tag === "street") || !postcode) return
184
+
185
+ if (nodes.some((node) => node.tag === "house_number" || node.tag === "locality" || node.tag === "venue")) return
186
+
187
+ const region = nodes.find((node) => node.tag === "region" && node.placeID?.startsWith("wof:"))
188
+ const country = postcode.metadata?.["resolver_country"]
189
+
190
+ if (!region && typeof country !== "string") return
191
+
192
+ const name = parts.map((node) => node.value.trim()).join(" ")
193
+
194
+ const [town, ...others] = await backend.findPlace({
195
+ text: name,
196
+ placetype: "locality",
197
+ ...(region ? { parentID: Number(region.placeID!.slice("wof:".length)) } : { country: country as string }),
198
+ })
199
+
200
+ if (!town?.exactMatch || town.regionScopeMiss || town.lat == null || town.lon == null) return
201
+
202
+ if (haversine(postcode.lat!, postcode.lon!, town.lat, town.lon, "km") > TOWN_POSTCODE_REACH_KM) return
203
+
204
+ const [first, ...rest] = parts
205
+
206
+ first!.tag = "locality"
207
+ first!.value = name
208
+ first!.end = parts.at(-1)!.end
209
+ removeNodes(roots, new Set(rest))
210
+ decorateNode(first!, town, others)
211
+ first!.metadata = { ...first!.metadata, street_as_town: true }
212
+ }
213
+
214
+ /**
215
+ * Reads a venue as a town when the input states only a country beside it
216
+ * and the country holds a town of that name.
217
+ *
218
+ * `Road Town, British Virgin Islands` parses the town as a venue.
219
+ * This runs ahead of the landmark layer, so an airport alias under `Biggin Hill`
220
+ * yields to the town that holds the name.
221
+ */
222
+ export async function applyVenueAsTown(roots: AddressNode[], backend: ResolverBackend): Promise<void> {
223
+ const nodes = [...walkNodes(roots)]
224
+ const venue = nodes.find((node) => node.tag === "venue" && !node.placeID && node.value.trim())
225
+
226
+ const country = nodes.find(
227
+ (node) => node.tag === "country" && typeof node.metadata?.["resolver_country"] === "string"
228
+ )
229
+
230
+ if (!venue || !country || nodes.some((node) => node !== venue && node !== country)) return
231
+
232
+ // A name written in two forms, `Derry/Londonderry` or `Biel/Bienne`, is read whole and then as each form.
233
+ const forms = [venue.value, ...venue.value.split("/").map((form) => form.trim())].filter(
234
+ (form, index, all) => form && all.indexOf(form) === index
235
+ )
236
+
237
+ let found: Awaited<ReturnType<ResolverBackend["findPlace"]>> = []
238
+
239
+ for (const form of forms) {
240
+ found = await backend.findPlace({
241
+ text: form,
242
+ placetype: "locality",
243
+ country: country.metadata!["resolver_country"] as string,
244
+ })
245
+
246
+ if (found[0]?.exactMatch) break
247
+ }
248
+
249
+ const [town, ...others] = found
250
+
251
+ if (!town?.exactMatch) return
252
+
253
+ venue.tag = "locality"
254
+ decorateNode(venue, town, others)
255
+ }
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
5
+ import type { ResolverBackend } from "@mailwoman/core/resolver"
6
+
7
+ import { decorateNode } from "#decorate-node"
8
+
9
+ /**
10
+ * A character that separates the parts of an address in some script.
11
+ */
12
+ const SEPARATOR = /[\s,,、;;/|·・]/u
13
+
14
+ /**
15
+ * Reads an input as one place when its whole text names that place and the parse resolved none of its parts.
16
+ *
17
+ * `ミュンヘン` and `裕廊东` hold no separator.
18
+ * The en-US parser reads them as a venue, or splits them into fragments the
19
+ * gazetteer doesn't key, while it keys both whole names.
20
+ *
21
+ * An unspaced address whose parts resolve, or whose whole text identifies no place, keeps its parse.
22
+ * This runs after the landmark layer, so a venue the landmark layer knows keeps that answer.
23
+ */
24
+ export async function applyWholeInputPlace(
25
+ roots: AddressNode[],
26
+ written: string,
27
+ backend: ResolverBackend,
28
+ country: string | null
29
+ ): Promise<void> {
30
+ const text = written.trim()
31
+ const nodes = [...walkNodes(roots)]
32
+
33
+ if (!text || SEPARATOR.test(text) || nodes.some((node) => node.placeID)) return
34
+
35
+ // A lone admin span already looked up its whole text, under the placetype and scope the walk applies.
36
+ // Fragments and a venue span didn't.
37
+ if (nodes.length < 2 && nodes[0]?.tag !== "venue") return
38
+
39
+ const found = await backend.findPlace({ text, ...(country ? { country } : {}) }).catch(() => [])
40
+ const [place, ...others] = found
41
+
42
+ if (!place?.exactMatch) return
43
+
44
+ const whole = { tag: "locality", value: text, start: 0, end: text.length, confidence: 1, children: [] } as AddressNode
45
+
46
+ decorateNode(whole, place, others)
47
+ whole.metadata = { ...whole.metadata, whole_input_place: true }
48
+ roots.splice(0, roots.length, whole)
49
+ }