@mailwoman/resolver 10.8.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 (49) hide show
  1. package/README.md +1 -5
  2. package/lib/decorate-node.ts +13 -2
  3. package/lib/remote-resolver.ts +1 -2
  4. package/lib/resolve/country-code.ts +102 -0
  5. package/lib/resolve/landmark.ts +227 -0
  6. package/lib/resolve/passes.ts +1 -52
  7. package/lib/resolve/region-city.ts +71 -0
  8. package/lib/resolve.ts +24 -60
  9. package/lib/span-rescore.ts +31 -0
  10. package/lib/street/tier.ts +19 -1
  11. package/out/decorate-node.d.ts.map +1 -1
  12. package/out/decorate-node.js +11 -2
  13. package/out/decorate-node.js.map +1 -1
  14. package/out/remote-resolver.d.ts +1 -2
  15. package/out/remote-resolver.d.ts.map +1 -1
  16. package/out/remote-resolver.js +0 -1
  17. package/out/remote-resolver.js.map +1 -1
  18. package/out/resolve/country-code.d.ts +49 -0
  19. package/out/resolve/country-code.d.ts.map +1 -0
  20. package/out/resolve/country-code.js +88 -0
  21. package/out/resolve/country-code.js.map +1 -0
  22. package/out/resolve/landmark.d.ts +26 -0
  23. package/out/resolve/landmark.d.ts.map +1 -0
  24. package/out/resolve/landmark.js +181 -0
  25. package/out/resolve/landmark.js.map +1 -0
  26. package/out/resolve/passes.d.ts +1 -29
  27. package/out/resolve/passes.d.ts.map +1 -1
  28. package/out/resolve/passes.js +2 -22
  29. package/out/resolve/passes.js.map +1 -1
  30. package/out/resolve/region-city.d.ts +29 -0
  31. package/out/resolve/region-city.d.ts.map +1 -0
  32. package/out/resolve/region-city.js +58 -0
  33. package/out/resolve/region-city.js.map +1 -0
  34. package/out/resolve.d.ts.map +1 -1
  35. package/out/resolve.js +19 -48
  36. package/out/resolve.js.map +1 -1
  37. package/out/span-rescore.d.ts +5 -0
  38. package/out/span-rescore.d.ts.map +1 -1
  39. package/out/span-rescore.js +23 -0
  40. package/out/span-rescore.js.map +1 -1
  41. package/out/street/tier.d.ts.map +1 -1
  42. package/out/street/tier.js +17 -1
  43. package/out/street/tier.js.map +1 -1
  44. package/package.json +9 -8
  45. package/lib/backend-capabilities.ts +0 -89
  46. package/out/backend-capabilities.d.ts +0 -36
  47. package/out/backend-capabilities.d.ts.map +0 -1
  48. package/out/backend-capabilities.js +0 -77
  49. 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
 
@@ -12,6 +12,11 @@ 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
  */
@@ -90,10 +95,16 @@ export function decorateNode(
90
95
  node.metadata["resolver_importance"] = resolved.importance
91
96
  }
92
97
 
93
- // 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.
94
105
  const bbox = resolved.bbox
95
106
 
96
- 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)) {
97
108
  node.metadata["resolver_bbox"] = bbox
98
109
  }
99
110
 
@@ -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
+ }
@@ -0,0 +1,227 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Answers a query that is a place's name, with no street or postcode, from the landmark layer.
7
+ *
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.
11
+ *
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
+ */
17
+
18
+ import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
19
+ import {
20
+ EMPTY_PLACE_FIELDS,
21
+ landmarkPlaceID,
22
+ OSM_LANDMARK_PREFIX,
23
+ type LandmarkHit,
24
+ type LandmarkLookup,
25
+ type ResolvedPlace,
26
+ } from "@mailwoman/core/resolver"
27
+ import { isCountryAirportCollision } from "@mailwoman/registry/overlap/country-airport"
28
+ import { isLatLonBounds, latLonBoundsContain } from "@mailwoman/spatial/bbox"
29
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
30
+
31
+ import { decorateNode } from "#decorate-node"
32
+ import { foldName } from "#fold-name"
33
+ import { writtenCountryCode } from "#resolve/country-code"
34
+
35
+ /**
36
+ * The tags that make an input an address.
37
+ * A landmark name cannot answer an address.
38
+ */
39
+ const ADDRESS_TAGS: ReadonlySet<string> = new Set(["house_number", "postcode", "unit", "po_box"])
40
+
41
+ /**
42
+ * The namesakes a landmark answer lists: OpenStreetMap can hold hundreds of parks under one name.
43
+ */
44
+ const LISTED_ALTERNATIVES = 8
45
+
46
+ /**
47
+ * The farthest a landmark may lie from a locality the input states, matching span rescore's postcode radius.
48
+ */
49
+ const STATED_LOCALITY_RADIUS_KM = 50
50
+
51
+ /**
52
+ * Keeps the hits an input's stated context permits: its country, and the surroundings of its locality.
53
+ */
54
+ function hitsInContext(hits: readonly LandmarkHit[], context: readonly AddressNode[]): LandmarkHit[] {
55
+ const nodes = [...walkNodes(context)]
56
+
57
+ const country = nodes
58
+ .map((node) => node.metadata?.["resolver_country"])
59
+ .find((code): code is string => typeof code === "string")
60
+
61
+ const locality = nodes.find((node) => node.tag === "locality" && node.lat != null && node.lon != null)
62
+ const extent = locality?.metadata?.["resolver_bbox"]
63
+
64
+ const distance = (hit: LandmarkHit) => (locality ? haversine(locality.lat!, locality.lon!, hit.lat, hit.lon) : 0)
65
+
66
+ // OpenStreetMap holds a St Mary's in every village, so a stated town's own extent
67
+ // bounds its places where the gazetteer holds one.
68
+ // Wikipedia editions separate famous namesakes, so a Wikidata place keeps the wider radius.
69
+ const inLocality = (hit: LandmarkHit) =>
70
+ hit.qid.startsWith(OSM_LANDMARK_PREFIX) && isLatLonBounds(extent)
71
+ ? latLonBoundsContain(extent, hit.lat, hit.lon)
72
+ : distance(hit) <= STATED_LOCALITY_RADIUS_KM
73
+
74
+ const kept = hits.filter((hit) => hit.country === country && inLocality(hit))
75
+
76
+ return kept.every((hit) => hit.qid.startsWith(OSM_LANDMARK_PREFIX))
77
+ ? kept.toSorted((a, b) => distance(a) - distance(b))
78
+ : kept
79
+ }
80
+
81
+ function placeOf(hit: LandmarkHit): ResolvedPlace {
82
+ const prominence = hit.importance ?? Math.log10(hit.sitelinks + 1)
83
+
84
+ return {
85
+ ...EMPTY_PLACE_FIELDS,
86
+ id: hit.qid,
87
+ name: hit.name,
88
+ placetype: "venue",
89
+ country: hit.country,
90
+ lat: hit.lat,
91
+ lon: hit.lon,
92
+ parent_id: null,
93
+ score: prominence,
94
+ prominence,
95
+ exactMatch: true,
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Lists every landmark that holds the written code on the resolved country node, as its alternatives.
101
+ *
102
+ * `AUS` answers Australia, and Austin–Bergstrom International Airport is the
103
+ * reading a caller can pick instead.
104
+ * 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.
106
+ *
107
+ * The list sits on a resolved country node, so a country the gazetteer left unresolved keeps its parse.
108
+ *
109
+ * The node also records `code_collision`, the identifier registry's verdict on whether the written
110
+ * code is both an officially assigned ISO 3166-1 alpha-3 code and an IATA airport code in its profile.
111
+ * The registry and the landmark layer read different sources, so the flag
112
+ * and the listed holders can disagree, and both are kept.
113
+ */
114
+ function listCodeHoldersOnCountry(roots: AddressNode[], code: string, hits: readonly LandmarkHit[]): void {
115
+ const country = roots.find((root) => root.tag === "country" && typeof root.placeID === "string")
116
+
117
+ if (!country) return
118
+
119
+ country.metadata = { ...country.metadata, code_collision: isCountryAirportCollision(code) }
120
+
121
+ const holders = hits.filter((hit) => hit.code && hit.kind === "venue")
122
+
123
+ if (!holders.length) return
124
+
125
+ const listed = (country.alternatives as ResolvedPlace[] | undefined) ?? []
126
+
127
+ country.alternatives = [...listed, ...holders.map(placeOf)]
128
+ }
129
+
130
+ /**
131
+ * Replaces the parse's reading of a landmark name with a venue node that holds the answer.
132
+ *
133
+ * The first comma-separated part is the name, and any other part is context that has to have resolved.
134
+ * A settlement that leads the name stays with the admin ladder, because the ladder ranks settlements.
135
+ */
136
+ export async function applyLandmark(roots: AddressNode[], raw: string, landmarks: LandmarkLookup): Promise<void> {
137
+ const nodes = [...walkNodes(roots)]
138
+
139
+ if (nodes.some((node) => ADDRESS_TAGS.has(node.tag))) return
140
+
141
+ const name = raw.split(",", 1)[0]!.trim()
142
+
143
+ if (!name) return
144
+
145
+ const hits = await landmarks.find(name)
146
+ const hasContext = raw.trim().length > name.length
147
+
148
+ // A bare country code answers the country, and the airport holding the same code is listed beside it.
149
+ // The registry's collision verdict is stamped whether or not the landmark layer holds the code.
150
+ // With context, `FRA, Germany` can still reach the airport.
151
+ if (!hasContext && writtenCountryCode(name)) {
152
+ listCodeHoldersOnCountry(roots, name, hits)
153
+
154
+ return
155
+ }
156
+
157
+ if (!hits.length) return
158
+
159
+ const nameEnd = raw.indexOf(name) + name.length
160
+ const context = roots.filter((node) => node.start >= nameEnd && typeof node.placeID === "string")
161
+
162
+ if (hasContext && !context.length) return
163
+
164
+ const candidates = hasContext ? hitsInContext(hits, context) : hits
165
+ const leader = candidates[0]
166
+
167
+ if (!leader || leader.kind !== "venue") return
168
+
169
+ // A translation or alias is the weakest claim on a name, so it answers only where the
170
+ // gazetteer holds none: `Hamburg` is an alias of Hamburg Airport and the name of a city.
171
+ const resolved = roots.filter((root) => typeof root.placeID === "string")
172
+ const fromOSM = leader.qid.startsWith(OSM_LANDMARK_PREFIX)
173
+
174
+ // The parser reads `Wall Street` and `Times Square` as streets, and `Central Park` as a venue.
175
+ // It also reads some parks as a street with the suffix `Park`, and those stay places.
176
+ const inName = (node: AddressNode) => node.start < nameEnd
177
+
178
+ const readsAsPark = nodes.some(
179
+ (node) => node.tag === "street_suffix" && inName(node) && foldName(node.value) === "park"
180
+ )
181
+
182
+ const readsAsStreet = !readsAsPark && nodes.some((node) => node.tag === "street" && inName(node))
183
+
184
+ if (fromOSM) {
185
+ // OpenStreetMap holds a place spelled like a street in some other town: `Wall Street` also answers in Utah.
186
+ if (readsAsStreet) return
187
+
188
+ // A school or a park in OpenStreetMap can share its town's name,
189
+ // so a place holding the whole name keeps it.
190
+ // A park reading beats a row with no measured population, as `Piedmont Park`
191
+ // in South Carolina yields to the park in Atlanta.
192
+ const holdsName = (node: AddressNode) =>
193
+ typeof node.placeID === "string" &&
194
+ foldName(node.value) === foldName(name) &&
195
+ (!readsAsPark || Number(node.metadata?.["resolver_score"] ?? 0) > 0)
196
+
197
+ if (nodes.some(holdsName)) return
198
+ } else {
199
+ const nameResolved = resolved.some(
200
+ (root) => root.start < nameEnd || root.value.toLowerCase() === name.toLowerCase()
201
+ )
202
+
203
+ // `Baker Street` is an alias of the tube station, and the street keeps its name.
204
+ if (!leader.primary && !leader.code && (nameResolved || readsAsStreet)) return
205
+ }
206
+
207
+ const node: AddressNode = {
208
+ // A famous street answers from Wikidata and stays a street: `Downing Street` holds a coordinate and a street.
209
+ tag: readsAsStreet ? "street" : "venue",
210
+ value: name.normalize("NFC").replaceAll(/\s+/gu, " "),
211
+ start: raw.indexOf(name),
212
+ end: nameEnd,
213
+ confidence: 1,
214
+ children: [],
215
+ }
216
+
217
+ decorateNode(node, placeOf(leader), candidates.slice(1, LISTED_ALTERNATIVES + 1).map(placeOf))
218
+ node.placeID = landmarkPlaceID(leader.qid)
219
+
220
+ node.metadata = {
221
+ ...node.metadata,
222
+ landmark_sitelinks: leader.sitelinks,
223
+ ...(fromOSM ? { landmark_source: "openstreetmap:planet" } : {}),
224
+ }
225
+
226
+ roots.splice(0, roots.length, node, ...context)
227
+ }
@@ -7,14 +7,11 @@
7
7
  import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
8
8
  import { isShapeExcludedPostcode, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
9
9
  import {
10
- type CoincidentLocality,
11
10
  type DefaultCountry,
12
11
  EMPTY_PLACE_FIELDS,
13
- compareReferential,
14
12
  type ResolveCandidateTrace,
15
13
  type ResolveNodeTrace,
16
14
  type PostcodePrefixIndexLike,
17
- referentialFromPopulation,
18
15
  type ResolvedPlace,
19
16
  type ResolveOpts,
20
17
  type ResolverBackend,
@@ -24,7 +21,6 @@ import { PLACETYPE_SPECIFICITY } from "@mailwoman/gazetteer/whosonfirst/placetyp
24
21
  import { haversine } from "@mailwoman/spatial/geometries/point/distance"
25
22
 
26
23
  import { decorateNode, isResolvedWithCoord } from "#decorate-node"
27
- import type { CoordinateOptionalPlace } from "#postcode/prefix"
28
24
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "#span-rescore"
29
25
 
30
26
  const TRACE_CANDIDATE_CAP = 10
@@ -295,12 +291,6 @@ export interface ResolutionState {
295
291
  */
296
292
  hardCountry?: string
297
293
 
298
- /**
299
- * Whether a resolved region gains its coincident locality of the same name as an
300
- * interpretation when the tree has no locality node.
301
- */
302
- hierarchyCompletion: boolean
303
-
304
294
  /**
305
295
  * Whether each resolved node gets its ancestor lineage in metadata, when the backend supports it.
306
296
  */
@@ -327,48 +317,6 @@ export interface ResolutionState {
327
317
  * and no caller-supplied default country.
328
318
  */
329
319
  regionQualifier?: string | null
330
-
331
- /**
332
- * Whether any node maps to the `locality` placetype.
333
- * Hierarchy completion runs only when this is false.
334
- */
335
- localityNodePresent: boolean
336
-
337
- /**
338
- * The first resolved region place, used to look up its coincident locality.
339
- */
340
- resolvedRegion: CoordinateOptionalPlace | null
341
-
342
- /**
343
- * The decorated node for {@link ResolutionState.resolvedRegion}.
344
- *
345
- * Hierarchy completion adds the locality interpretation to it in place.
346
- */
347
- resolvedRegionNode: AddressNode | null
348
- }
349
-
350
- /**
351
- * Picks the completion locality among coincident candidates of the same name.
352
- *
353
- * It prefers the most populous candidate, then the nearest candidate.
354
- * It returns `null` on an exact tie.
355
- */
356
- export function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
357
- if (!candidates.length) return null
358
-
359
- if (candidates.length === 1) return candidates[0]!
360
-
361
- const ranked = [...candidates]
362
- .map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
363
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
364
- .sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
365
- .map((x) => x.c)
366
-
367
- const [first, second] = ranked
368
-
369
- if (first!.population === second!.population && first!.distanceKm === second!.distanceKm) return null
370
-
371
- return first!
372
320
  }
373
321
 
374
322
  /**
@@ -408,6 +356,7 @@ export async function applySpanRescore(
408
356
 
409
357
  postalCompoundRecovery: opts.postalCompoundRecovery,
410
358
  spanRescoreRequireContextRemainder: opts.spanRescoreRequireContextRemainder,
359
+ ...(opts.isVenueCategoryWord ? { isVenueCategoryWord: opts.isVenueCategoryWord } : {}),
411
360
  })
412
361
  } catch {
413
362
  return
@@ -0,0 +1,71 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
8
+ import type { ResolverBackend } from "@mailwoman/core/resolver"
9
+
10
+ import { decorateNode } from "#decorate-node"
11
+ import { streetNumberPairs } from "#street/tier"
12
+
13
+ /**
14
+ * Reads a street address's region as the city of the same name when the
15
+ * gazetteer holds one inside that region.
16
+ *
17
+ * `34 Lê Duẩn, Sài Gòn, Hồ Chí Minh, Vietnam` parses with a region and no locality.
18
+ * The region's point can lie far from the street, and the address-point lookup
19
+ * has no locality to search around.
20
+ *
21
+ * A place held at both levels occurs wherever a city is its own province, so the test reads the hierarchy.
22
+ *
23
+ * A bare region stays a region, because only a street and number say the input
24
+ * means somewhere a street can be.
25
+ */
26
+ export async function applyRegionCity(roots: AddressNode[], backend: ResolverBackend): Promise<void> {
27
+ const nodes = [...walkNodes(roots)]
28
+
29
+ if (nodes.some((node) => node.tag === "locality") || !streetNumberPairs(roots).length) return
30
+
31
+ const region = nodes.find((node) => node.tag === "region" && node.placeID?.startsWith("wof:"))
32
+
33
+ if (!region) return
34
+
35
+ const [city, ...others] = await backend.findPlace({
36
+ text: region.value,
37
+ placetype: "locality",
38
+ parentID: Number(region.placeID!.slice("wof:".length)),
39
+ })
40
+
41
+ // A lookup that finds the name only outside the parent answers with that place and marks the miss.
42
+ if (!city?.exactMatch || city.regionScopeMiss) return
43
+
44
+ region.tag = "locality"
45
+ decorateNode(region, city, others)
46
+ region.metadata = { ...region.metadata, region_city: true }
47
+ }
48
+
49
+ /**
50
+ * Reads a locality the gazetteer holds only as a region, inside a country the input states.
51
+ *
52
+ * `Likiep Atoll, RMI` parses the atoll as a locality, and the Marshall Islands hold it as a region.
53
+ * This runs after the locality band missed, so a place with a locality row keeps it.
54
+ */
55
+ export async function applyLocalityAsRegion(
56
+ roots: AddressNode[],
57
+ backend: ResolverBackend,
58
+ country: string
59
+ ): Promise<void> {
60
+ const nodes = [...walkNodes(roots)]
61
+ const locality = nodes.find((node) => node.tag === "locality" && !node.placeID && node.value.trim())
62
+
63
+ if (!locality || nodes.some((node) => node.tag === "region" && node.placeID)) return
64
+
65
+ const [region, ...others] = await backend.findPlace({ text: locality.value, placetype: "region", country })
66
+
67
+ if (!region?.exactMatch || region.country !== country) return
68
+
69
+ locality.tag = "region"
70
+ decorateNode(locality, region, others)
71
+ }