@mailwoman/resolver 10.0.0 → 10.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.
- package/README.md +9 -7
- package/lib/admin/coherence-passes.ts +31 -172
- package/lib/admin/containment.ts +15 -33
- package/lib/admin/jp-municipality.ts +21 -14
- package/lib/admin/winner.ts +37 -69
- package/lib/backend-capabilities.ts +28 -27
- package/lib/bare-toponym-race.ts +69 -37
- package/lib/decorate-node.ts +25 -49
- package/lib/fold-name.ts +5 -18
- package/lib/index.ts +5 -9
- package/lib/plausibility.ts +41 -68
- package/lib/postcode/country-coherence.ts +92 -296
- package/lib/postcode/prefix.ts +24 -86
- package/lib/postcode/shape-coherence.ts +26 -116
- package/lib/remote-resolver.ts +38 -33
- package/lib/rerank.ts +41 -54
- package/lib/resolve/passes.ts +188 -177
- package/lib/resolve.ts +744 -0
- package/lib/span-rescore.ts +219 -175
- package/lib/street/evidence.ts +65 -73
- package/lib/street/tier.ts +51 -194
- package/lib/toponym-prior.ts +54 -180
- package/out/admin/coherence-passes.d.ts +18 -69
- package/out/admin/coherence-passes.d.ts.map +1 -1
- package/out/admin/coherence-passes.js +24 -166
- package/out/admin/coherence-passes.js.map +1 -1
- package/out/admin/containment.d.ts +13 -31
- package/out/admin/containment.d.ts.map +1 -1
- package/out/admin/containment.js +13 -31
- package/out/admin/containment.js.map +1 -1
- package/out/admin/jp-municipality.d.ts +21 -14
- package/out/admin/jp-municipality.d.ts.map +1 -1
- package/out/admin/jp-municipality.js +18 -12
- package/out/admin/jp-municipality.js.map +1 -1
- package/out/admin/winner.d.ts +32 -64
- package/out/admin/winner.d.ts.map +1 -1
- package/out/admin/winner.js +23 -56
- package/out/admin/winner.js.map +1 -1
- package/out/{admin/index.d.ts → admin.d.ts} +1 -1
- package/out/admin.d.ts.map +1 -0
- package/out/{admin/index.js → admin.js} +1 -1
- package/out/admin.js.map +1 -0
- package/out/backend-capabilities.d.ts +19 -20
- package/out/backend-capabilities.d.ts.map +1 -1
- package/out/backend-capabilities.js +28 -26
- package/out/backend-capabilities.js.map +1 -1
- package/out/bare-toponym-race.d.ts +54 -27
- package/out/bare-toponym-race.d.ts.map +1 -1
- package/out/bare-toponym-race.js +69 -37
- package/out/bare-toponym-race.js.map +1 -1
- package/out/decorate-node.d.ts +6 -8
- package/out/decorate-node.d.ts.map +1 -1
- package/out/decorate-node.js +25 -49
- package/out/decorate-node.js.map +1 -1
- package/out/fold-name.d.ts +5 -18
- package/out/fold-name.d.ts.map +1 -1
- package/out/fold-name.js +5 -18
- package/out/fold-name.js.map +1 -1
- package/out/index.d.ts +5 -6
- package/out/index.d.ts.map +1 -1
- package/out/index.js +5 -8
- package/out/index.js.map +1 -1
- package/out/plausibility.d.ts +30 -60
- package/out/plausibility.d.ts.map +1 -1
- package/out/plausibility.js +19 -52
- package/out/plausibility.js.map +1 -1
- package/out/postcode/country-coherence.d.ts +53 -167
- package/out/postcode/country-coherence.d.ts.map +1 -1
- package/out/postcode/country-coherence.js +42 -259
- package/out/postcode/country-coherence.js.map +1 -1
- package/out/postcode/prefix.d.ts +18 -69
- package/out/postcode/prefix.d.ts.map +1 -1
- package/out/postcode/prefix.js +11 -78
- package/out/postcode/prefix.js.map +1 -1
- package/out/postcode/shape-coherence.d.ts +18 -85
- package/out/postcode/shape-coherence.d.ts.map +1 -1
- package/out/postcode/shape-coherence.js +11 -107
- package/out/postcode/shape-coherence.js.map +1 -1
- package/out/{postcode/index.d.ts → postcode.d.ts} +1 -1
- package/out/postcode.d.ts.map +1 -0
- package/out/{postcode/index.js → postcode.js} +1 -1
- package/out/postcode.js.map +1 -0
- package/out/remote-resolver.d.ts +32 -31
- package/out/remote-resolver.d.ts.map +1 -1
- package/out/remote-resolver.js +12 -20
- package/out/remote-resolver.js.map +1 -1
- package/out/rerank.d.ts +32 -46
- package/out/rerank.d.ts.map +1 -1
- package/out/rerank.js +16 -41
- package/out/rerank.js.map +1 -1
- package/out/resolve/passes.d.ts +108 -95
- package/out/resolve/passes.d.ts.map +1 -1
- package/out/resolve/passes.js +67 -126
- package/out/resolve/passes.js.map +1 -1
- package/out/resolve.d.ts +15 -0
- package/out/resolve.d.ts.map +1 -0
- package/out/resolve.js +557 -0
- package/out/resolve.js.map +1 -0
- package/out/span-rescore.d.ts +56 -65
- package/out/span-rescore.d.ts.map +1 -1
- package/out/span-rescore.js +134 -132
- package/out/span-rescore.js.map +1 -1
- package/out/street/evidence.d.ts +56 -61
- package/out/street/evidence.d.ts.map +1 -1
- package/out/street/evidence.js +22 -46
- package/out/street/evidence.js.map +1 -1
- package/out/street/tier.d.ts +18 -30
- package/out/street/tier.d.ts.map +1 -1
- package/out/street/tier.js +43 -191
- package/out/street/tier.js.map +1 -1
- package/out/{street/index.d.ts → street.d.ts} +1 -1
- package/out/street.d.ts.map +1 -0
- package/out/{street/index.js → street.js} +1 -1
- package/out/street.js.map +1 -0
- package/out/toponym-prior.d.ts +22 -110
- package/out/toponym-prior.d.ts.map +1 -1
- package/out/toponym-prior.js +41 -170
- package/out/toponym-prior.js.map +1 -1
- package/package.json +44 -147
- package/lib/resolve/index.ts +0 -989
- package/out/admin/index.d.ts.map +0 -1
- package/out/admin/index.js.map +0 -1
- package/out/postcode/index.d.ts.map +0 -1
- package/out/postcode/index.js.map +0 -1
- package/out/resolve/index.d.ts +0 -20
- package/out/resolve/index.d.ts.map +0 -1
- package/out/resolve/index.js +0 -808
- package/out/resolve/index.js.map +0 -1
- package/out/street/index.d.ts.map +0 -1
- package/out/street/index.js.map +0 -1
- package/vitest.config.ts +0 -38
- /package/lib/{admin/index.ts → admin.ts} +0 -0
- /package/lib/{postcode/index.ts → postcode.ts} +0 -0
- /package/lib/{street/index.ts → street.ts} +0 -0
package/lib/span-rescore.ts
CHANGED
|
@@ -3,32 +3,17 @@
|
|
|
3
3
|
* @license AGPL-3.0
|
|
4
4
|
* @author Teffen Ellis, et al.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* the address comes back with no coordinate. But the whole word sits intact in the raw input — a
|
|
10
|
-
* whitespace tokenizer sees it where the model's subword tokenizer didn't.
|
|
11
|
-
*
|
|
12
|
-
* This module is the PURE, backend-agnostic core: enumerate contiguous raw-token spans, exact-match
|
|
13
|
-
* them against the same-country gazetteer, and return the best locality candidate. The resolver
|
|
14
|
-
* (`resolve.ts` → `applySpanRescore`) owns the integration: it runs this ONLY on an unresolved
|
|
15
|
-
* tree (the #685 brake — never second-guess a working coordinate) and injects the recovered
|
|
16
|
-
* locality as a resolved node. Default-ON (#370, promoted 2026-06-25 — same-harness EU+AU +1pp
|
|
17
|
-
* @25km, zero regressions); explicit opt-out via `ResolveOpts.spanRescore: false`, byte-stable then.
|
|
18
|
-
*
|
|
19
|
-
* The design + thresholds are validated on a 7-locale coordinate panel
|
|
20
|
-
* (`scripts/eval/span-rescore-validate.ts`, eval
|
|
21
|
-
* `docs/articles/evals/experiments/2026-06-23-370-span-rescore.mdx`): longest-exact-match-wins (the gold
|
|
22
|
-
* locality is usually the LONGER, more-specific name — shortest- wins grabs the ambiguous prefix
|
|
23
|
-
* "Tomaszów" of "Tomaszów Mazowiecki", 135 km off), and a postcode- consistency check that rejects
|
|
24
|
-
* a match far from where the postcode resolves (kills coverage-gap false-positives where the
|
|
25
|
-
* backend has postcode coverage).
|
|
6
|
+
* Recover a dropped or fragmented locality from the raw text when a parse fails to resolve, by
|
|
7
|
+
* matching contiguous raw-token spans against the same-country gazetteer. Default-on with an
|
|
8
|
+
* explicit `ResolveOpts.spanRescore: false` opt-out.
|
|
26
9
|
*/
|
|
27
10
|
|
|
28
11
|
import { firstNodeWhere, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
|
|
29
|
-
import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
|
|
12
|
+
import type { ResolvedPlace, ResolverBackend, WeakResolutionReading } from "@mailwoman/core/resolver"
|
|
13
|
+
import { isRegionAbbreviationToken } from "@mailwoman/query-shape/region-abbreviations"
|
|
30
14
|
import { haversineKm } from "@mailwoman/spatial"
|
|
31
15
|
|
|
16
|
+
import { partitionByContainment } from "#admin/containment"
|
|
32
17
|
import { foldName } from "#fold-name"
|
|
33
18
|
import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "#toponym-prior"
|
|
34
19
|
|
|
@@ -38,42 +23,62 @@ export interface SpanRescoreOptions {
|
|
|
38
23
|
*/
|
|
39
24
|
country?: string
|
|
40
25
|
/**
|
|
41
|
-
*
|
|
26
|
+
* The sibling postcode serves as the backend disambiguation hint and the consistency-check anchor.
|
|
42
27
|
*/
|
|
43
|
-
postcode?: string
|
|
28
|
+
postcode?: string | null
|
|
44
29
|
/**
|
|
45
|
-
* Reject a candidate whose coordinate is farther than this (km) from the postcode anchor.
|
|
46
|
-
*
|
|
47
|
-
*
|
|
30
|
+
* Reject a candidate whose coordinate is farther than this (km) from the postcode anchor.
|
|
31
|
+
*
|
|
32
|
+
* The check fires only when the postcode resolves to a point.
|
|
33
|
+
* A backend without postcode coverage receives no penalty.
|
|
34
|
+
*
|
|
35
|
+
* A value of 0 disables the check.
|
|
36
|
+
*
|
|
37
|
+
* @defaultValue `50`
|
|
48
38
|
*/
|
|
49
39
|
thresholdKm?: number
|
|
50
40
|
/**
|
|
51
|
-
* Max contiguous raw tokens to treat as one locality span.
|
|
41
|
+
* Max contiguous raw tokens to treat as one locality span.
|
|
42
|
+
*
|
|
43
|
+
* @defaultValue `4`
|
|
52
44
|
*/
|
|
53
45
|
maxSpanTokens?: number
|
|
54
46
|
/**
|
|
55
|
-
* Min confidence for a street/house_number/postcode node to count as a span-blocking constituent.
|
|
47
|
+
* Min confidence for a street/house_number/postcode node to count as a span-blocking constituent.
|
|
48
|
+
*
|
|
49
|
+
* @defaultValue `0.7`
|
|
56
50
|
*/
|
|
57
51
|
confidentThreshold?: number
|
|
58
52
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
53
|
+
* When on, the anchor retries with the postcode's code-shaped token subset and an unresolved
|
|
54
|
+
* postcode node blocks only those code tokens, leaving the residual name tokens as span material.
|
|
55
|
+
*
|
|
56
|
+
* Street/affix blocking is untouched.
|
|
57
|
+
*
|
|
58
|
+
* @defaultValue `false`
|
|
64
59
|
*/
|
|
65
60
|
postalCompoundRecovery?: boolean
|
|
66
61
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
62
|
+
* When the span covers the whole unqualified input, treat {@link country} as an additive prior
|
|
63
|
+
* instead of a hard gazetteer filter; `false` restores the hard filter byte-for-byte.
|
|
64
|
+
*
|
|
65
|
+
* @defaultValue `true`
|
|
70
66
|
*/
|
|
71
67
|
bareToponymSoftCountry?: boolean
|
|
72
68
|
/**
|
|
73
|
-
* Weight of that prior, in log10-population units.
|
|
74
|
-
*
|
|
69
|
+
* Weight of that prior, in log10-population units.
|
|
70
|
+
*
|
|
71
|
+
* @defaultValue {@linkcode DEFAULT_COUNTRY_PRIOR_WEIGHT} (2), and 0 removes the locale's say entirely.
|
|
75
72
|
*/
|
|
76
73
|
bareToponymCountryWeight?: number
|
|
74
|
+
/**
|
|
75
|
+
* Admit a proper sub-span only when every token it leaves behind is a subdivision code or a number.
|
|
76
|
+
*
|
|
77
|
+
* See `remainderIsContext` for the rule.
|
|
78
|
+
*
|
|
79
|
+
* @defaultValue `false`
|
|
80
|
+
*/
|
|
81
|
+
spanRescoreRequireContextRemainder?: boolean
|
|
77
82
|
}
|
|
78
83
|
|
|
79
84
|
/**
|
|
@@ -94,29 +99,15 @@ export interface RescoreCandidate {
|
|
|
94
99
|
*/
|
|
95
100
|
place: ResolvedPlace
|
|
96
101
|
/**
|
|
97
|
-
* Whether the postcode-consistency check
|
|
98
|
-
* match was validated within `thresholdKm`
|
|
99
|
-
*
|
|
100
|
-
* case). The caller surfaces this as `metadata.rescore_postcode_verified` so a consumer can threshold on it WITHOUT a
|
|
101
|
-
* hidden per-country coverage map. Deliberately NOT folded into the calibrated `confidence` — that would break the
|
|
102
|
-
* isotonic guarantee (a true calibrated 0.83 must not be confused with a rescore plug-in estimate).
|
|
102
|
+
* Whether the postcode-consistency check fired — the postcode resolved to a point
|
|
103
|
+
* and the match was validated within `thresholdKm` — deliberately kept out of the
|
|
104
|
+
* calibrated `confidence` so the isotonic fit stays monotone.
|
|
103
105
|
*/
|
|
104
106
|
postcodeVerified: boolean
|
|
105
107
|
/**
|
|
106
|
-
* The
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
* #1537: these were being discarded. A name the model reads as a `street` ("Springfield", "Berlin", "Manchester",
|
|
111
|
-
* "Moscow", "Fulda") never reaches the admin walk, so the whole tree comes back unresolved and THIS tier is what
|
|
112
|
-
* recovers it — and it decorated the injected node with no alternatives at all. The result was that the geocode
|
|
113
|
-
* path's `candidates` array held one entry, and the top-1-vs-top-2 dominance margin that `declared_ambiguity` reads
|
|
114
|
-
* was uncomputable, for exactly the famous-homonym class that marker exists for. Measured on the shipped candidate
|
|
115
|
-
* backend, 2026-08-07: those five queries returned 1 candidate each while `Cambridge`/`Athens`/`Paris` — the same
|
|
116
|
-
* class, but parsed as `locality` — returned 4-5.
|
|
117
|
-
*
|
|
118
|
-
* The winner is unchanged by their presence: the pick is still the first check-passing exact match, and these are the
|
|
119
|
-
* ones that came after it. This costs no extra query — they were in the same `findPlace` response.
|
|
108
|
+
* The same-span namesake runner-ups this recovery's own lookup already returned,
|
|
109
|
+
* in backend rank order, minus the winner and anything the postcode check rejected,
|
|
110
|
+
* so the top-1-vs-top-2 dominance margin stays computable.
|
|
120
111
|
*/
|
|
121
112
|
alternatives: ResolvedPlace[]
|
|
122
113
|
}
|
|
@@ -135,7 +126,7 @@ function tokenizeRaw(raw: string): RawTok[] {
|
|
|
135
126
|
const re = /[^\s,;/]+/g
|
|
136
127
|
let m: RegExpExecArray | null
|
|
137
128
|
|
|
138
|
-
while ((m = re.exec(raw))
|
|
129
|
+
while ((m = re.exec(raw))) {
|
|
139
130
|
toks.push({ text: m[0], start: m.index, end: m.index + m[0].length })
|
|
140
131
|
}
|
|
141
132
|
|
|
@@ -143,9 +134,8 @@ function tokenizeRaw(raw: string): RawTok[] {
|
|
|
143
134
|
}
|
|
144
135
|
|
|
145
136
|
/**
|
|
146
|
-
* The code-shaped (digit-
|
|
147
|
-
*
|
|
148
|
-
* Empty string when no token carries a digit.
|
|
137
|
+
* The code-shaped (digit-containing) token subset of a postcode string — "1382 Kožljek"
|
|
138
|
+
* → "1382" — and an empty string when no token contains a digit.
|
|
149
139
|
*/
|
|
150
140
|
export function postcodeCodeSubset(postcode: string): string {
|
|
151
141
|
return postcode
|
|
@@ -156,17 +146,15 @@ export function postcodeCodeSubset(postcode: string): string {
|
|
|
156
146
|
}
|
|
157
147
|
|
|
158
148
|
/**
|
|
159
|
-
* Over-fetch for the
|
|
160
|
-
* often all in one country,
|
|
161
|
-
* five US rows ahead of Warwick, Warwickshire. The backend orders by the same population key either way, so a wider
|
|
162
|
-
* window only admits more of the same list.
|
|
149
|
+
* Over-fetch for the bare-toponym probe: without a country filter the top 5 worldwide bearers of a
|
|
150
|
+
* common name are often all in one country, with the candidate the soft prior promotes below the fold.
|
|
163
151
|
*/
|
|
164
152
|
const BARE_TOPONYM_FETCH = 20
|
|
165
153
|
|
|
166
154
|
/**
|
|
167
|
-
* True when the tree names its
|
|
168
|
-
*
|
|
169
|
-
* the hard filter keeps its say
|
|
155
|
+
* True when the tree names its own admin context — a region, subregion, country,
|
|
156
|
+
* postcode or house number the parser read out of the input — so the soft-country
|
|
157
|
+
* prior stands down and the hard filter keeps its say.
|
|
170
158
|
*/
|
|
171
159
|
function hasAdminQualifier(roots: readonly AddressNode[]): boolean {
|
|
172
160
|
return (
|
|
@@ -179,35 +167,43 @@ function hasAdminQualifier(roots: readonly AddressNode[]): boolean {
|
|
|
179
167
|
n.tag === "postcode" ||
|
|
180
168
|
n.tag === "house_number") &&
|
|
181
169
|
n.value.trim().length > 0
|
|
182
|
-
)
|
|
170
|
+
) != null
|
|
183
171
|
)
|
|
184
172
|
}
|
|
185
173
|
|
|
186
174
|
/**
|
|
187
|
-
*
|
|
175
|
+
* Whether one node's resolution rests on evidence thin enough to re-open, under `reading`.
|
|
188
176
|
*/
|
|
189
|
-
|
|
190
|
-
|
|
177
|
+
function resolvedWeakly(node: AddressNode, reading: WeakResolutionReading): boolean {
|
|
178
|
+
const metadata = node.metadata ?? {}
|
|
179
|
+
const weakScore = metadata["resolver_score"] === 0
|
|
180
|
+
const weakContainment = metadata["admin_containment"] === "no_contained_candidate"
|
|
181
|
+
|
|
182
|
+
if (reading === "score") return weakScore
|
|
183
|
+
|
|
184
|
+
if (reading === "containment") return weakContainment
|
|
185
|
+
|
|
186
|
+
return weakScore || weakContainment
|
|
191
187
|
}
|
|
192
188
|
|
|
193
189
|
/**
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
* NY" is a street suffix, not a locality, and without this guard the recovery exact-matches it against a same-named
|
|
197
|
-
* place ("Ave", France) and injects a bogus locality.
|
|
190
|
+
* True if any node in the tree already has a resolved place id — the brake on span rescore.
|
|
191
|
+
* with `weakReading`, a node whose resolution is weak under that reading does not hold it.
|
|
198
192
|
*/
|
|
193
|
+
export function hasResolvedPlace(
|
|
194
|
+
roots: readonly AddressNode[],
|
|
195
|
+
weakReading: WeakResolutionReading | false = false
|
|
196
|
+
): boolean {
|
|
197
|
+
return firstNodeWhere(roots, (n) => Boolean(n.placeID) && !(weakReading && resolvedWeakly(n, weakReading))) != null
|
|
198
|
+
}
|
|
199
|
+
|
|
199
200
|
/**
|
|
200
|
-
* Ranges of
|
|
201
|
-
*
|
|
202
|
-
*
|
|
203
|
-
* The parse grouping is the claim: when the model binds `Papua`, `New` and `Guinea` into one country span, `New` is a
|
|
204
|
-
* modifier inside a name, not a name. Probing it anyway matches a real US place (`New`, wof:1276997945) and pins the
|
|
205
|
-
* address to Kentucky — an answer strictly worse than none, because it is confident and wrong.
|
|
201
|
+
* Ranges of multi-token `country` / `region` spans, used to block their interior
|
|
202
|
+
* tokens from being re-read as standalone places.
|
|
206
203
|
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
210
|
-
* excluded — there is no interior to protect.
|
|
204
|
+
* The whole span stays probeable.
|
|
205
|
+
* Single-token spans are excluded.
|
|
206
|
+
* The guard does not depend on confidence.
|
|
211
207
|
*/
|
|
212
208
|
function multiTokenNameInteriors(roots: readonly AddressNode[], raw: string): Array<[number, number]> {
|
|
213
209
|
const out: Array<[number, number]> = []
|
|
@@ -226,13 +222,44 @@ function multiTokenNameInteriors(roots: readonly AddressNode[], raw: string): Ar
|
|
|
226
222
|
return out
|
|
227
223
|
}
|
|
228
224
|
|
|
225
|
+
/**
|
|
226
|
+
* The confident ranges split by what a span containing one means: `hard`
|
|
227
|
+
* (house number, postcode, street body) refuses any overlap, while `affix` refuses
|
|
228
|
+
* a span only when it does not strictly contain the affix.
|
|
229
|
+
*/
|
|
230
|
+
interface ConfidentRanges {
|
|
231
|
+
hard: Array<[number, number]>
|
|
232
|
+
affix: Array<[number, number]>
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* The character ranges the parse read as street material, context only
|
|
237
|
+
* when the range does not overlap the span under test.
|
|
238
|
+
*/
|
|
239
|
+
function streetRanges(roots: readonly AddressNode[]): Array<[number, number]> {
|
|
240
|
+
const out: Array<[number, number]> = []
|
|
241
|
+
|
|
242
|
+
for (const n of walkNodes(roots)) {
|
|
243
|
+
if (
|
|
244
|
+
(n.tag === "street" || n.tag === "street_prefix" || n.tag === "street_suffix") &&
|
|
245
|
+
Number.isFinite(n.start) &&
|
|
246
|
+
Number.isFinite(n.end)
|
|
247
|
+
) {
|
|
248
|
+
out.push([n.start, n.end])
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return out
|
|
253
|
+
}
|
|
254
|
+
|
|
229
255
|
function confidentRanges(
|
|
230
256
|
roots: readonly AddressNode[],
|
|
231
257
|
threshold: number,
|
|
232
258
|
raw: string,
|
|
233
259
|
postalCompoundRecovery: boolean
|
|
234
|
-
):
|
|
260
|
+
): ConfidentRanges {
|
|
235
261
|
const out: Array<[number, number]> = []
|
|
262
|
+
const affix: Array<[number, number]> = []
|
|
236
263
|
|
|
237
264
|
for (const n of walkNodes(roots)) {
|
|
238
265
|
if (
|
|
@@ -245,27 +272,30 @@ function confidentRanges(
|
|
|
245
272
|
Number.isFinite(n.start) &&
|
|
246
273
|
Number.isFinite(n.end)
|
|
247
274
|
) {
|
|
248
|
-
//
|
|
249
|
-
//
|
|
250
|
-
// street family keep the full-range block (the "Ave, France" guard).
|
|
275
|
+
// An unresolved postcode span blocks only its code-shaped tokens.
|
|
276
|
+
// Resolved postcodes and the street family keep the full-range block.
|
|
251
277
|
if (postalCompoundRecovery && n.tag === "postcode" && !n.placeID) {
|
|
252
278
|
for (const t of tokenizeRaw(raw.slice(n.start, n.end))) {
|
|
253
279
|
if (/\d/.test(t.text)) {
|
|
254
280
|
out.push([n.start + t.start, n.start + t.end])
|
|
255
281
|
}
|
|
256
282
|
}
|
|
283
|
+
} else if (n.tag === "street_prefix" || n.tag === "street_suffix") {
|
|
284
|
+
affix.push([n.start, n.end])
|
|
257
285
|
} else {
|
|
258
286
|
out.push([n.start, n.end])
|
|
259
287
|
}
|
|
260
288
|
}
|
|
261
289
|
}
|
|
262
290
|
|
|
263
|
-
return out
|
|
291
|
+
return { hard: out, affix }
|
|
264
292
|
}
|
|
265
293
|
|
|
266
294
|
/**
|
|
267
|
-
* Find the best locality the raw text
|
|
268
|
-
*
|
|
295
|
+
* Find the best locality that the raw text exactly matches in the gazetteer.
|
|
296
|
+
*
|
|
297
|
+
* Return `null` when no entry matches or the postcode check rejects every match.
|
|
298
|
+
* Callers test `hasResolvedPlace` first.
|
|
269
299
|
*/
|
|
270
300
|
export async function findRescoreCandidate(
|
|
271
301
|
raw: string,
|
|
@@ -279,15 +309,13 @@ export async function findRescoreCandidate(
|
|
|
279
309
|
const country = opts.country
|
|
280
310
|
const postcode = opts.postcode?.trim() || undefined
|
|
281
311
|
|
|
282
|
-
//
|
|
283
|
-
//
|
|
312
|
+
// The postcode-consistency anchor.
|
|
313
|
+
// No candidate leaves it null, so the check cannot fire and the match is accepted.
|
|
284
314
|
let anchor: { lat: number; lon: number } | null = null
|
|
285
315
|
|
|
286
316
|
if (postcode && thresholdKm > 0) {
|
|
287
|
-
//
|
|
288
|
-
//
|
|
289
|
-
// false anchor then EXCLUDES the true village. A typed miss leaves anchor=null → the match is
|
|
290
|
-
// accepted unrestricted, which is the correct degradation for an unverifiable code.
|
|
317
|
+
// Both anchor probes are `postalcode`-typed: an untyped truncated code fragment
|
|
318
|
+
// name-matches arbitrary places and the false anchor then excludes the true village.
|
|
291
319
|
const pcHits = await backend.findPlace({ text: postcode, country, placetype: "postalcode", limit: 2 })
|
|
292
320
|
const a = pcHits.find((h) => h.lat !== 0 || h.lon !== 0)
|
|
293
321
|
|
|
@@ -295,8 +323,7 @@ export async function findRescoreCandidate(
|
|
|
295
323
|
anchor = { lat: a.lat, lon: a.lon }
|
|
296
324
|
}
|
|
297
325
|
|
|
298
|
-
//
|
|
299
|
-
// the code-shaped token subset so the consistency check can validate the recovered city.
|
|
326
|
+
// The globbed compound matches no bare-code row, so retry the anchor with the code-shaped token subset.
|
|
300
327
|
if (!anchor && opts.postalCompoundRecovery) {
|
|
301
328
|
const code = postcodeCodeSubset(postcode)
|
|
302
329
|
|
|
@@ -313,20 +340,28 @@ export async function findRescoreCandidate(
|
|
|
313
340
|
|
|
314
341
|
const toks = tokenizeRaw(raw)
|
|
315
342
|
const avoid = confidentRanges(roots, threshold, raw, opts.postalCompoundRecovery ?? false)
|
|
316
|
-
const
|
|
317
|
-
|
|
343
|
+
const streets = streetRanges(roots)
|
|
344
|
+
|
|
345
|
+
const overlapsAvoid = (s: number, e: number) =>
|
|
346
|
+
avoid.hard.some(([as, ae]) => s < ae && as < e) ||
|
|
347
|
+
avoid.affix.some(([as, ae]) => {
|
|
348
|
+
if (e <= as || ae <= s) return false // disjoint — the affix has no say
|
|
349
|
+
const strictlyContains = s <= as && ae <= e && e - s > ae - as
|
|
350
|
+
|
|
351
|
+
return !strictlyContains
|
|
352
|
+
})
|
|
353
|
+
|
|
318
354
|
const nameInteriors = multiTokenNameInteriors(roots, raw)
|
|
319
355
|
|
|
320
356
|
const isNameInterior = (s: number, e: number) =>
|
|
321
357
|
nameInteriors.some(([ns, ne]) => s >= ns && e <= ne && !(s === ns && e === ne))
|
|
322
358
|
|
|
323
|
-
// Enumerate contiguous
|
|
324
|
-
//
|
|
359
|
+
// Enumerate contiguous token windows up to `maxSpan` and probe them longest first by
|
|
360
|
+
// character extent, so a region code and a locality of equal token count order by extent.
|
|
325
361
|
interface Span {
|
|
326
362
|
text: string
|
|
327
363
|
start: number
|
|
328
364
|
end: number
|
|
329
|
-
len: number
|
|
330
365
|
}
|
|
331
366
|
|
|
332
367
|
const spans: Span[] = []
|
|
@@ -339,48 +374,67 @@ export async function findRescoreCandidate(
|
|
|
339
374
|
if (overlapsAvoid(start, end)) continue
|
|
340
375
|
|
|
341
376
|
if (isNameInterior(start, end)) continue
|
|
342
|
-
spans.push({ text: raw.slice(start, end), start, end
|
|
377
|
+
spans.push({ text: raw.slice(start, end), start, end })
|
|
343
378
|
}
|
|
344
379
|
}
|
|
345
380
|
|
|
346
|
-
spans.sort((a, b) => b.
|
|
347
|
-
|
|
348
|
-
//
|
|
349
|
-
//
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
381
|
+
spans.sort((a, b) => b.end - b.start - (a.end - a.start) || a.start - b.start)
|
|
382
|
+
|
|
383
|
+
// For a bare toponym the caller's `country` is a locale default rather than knowledge, so the hard
|
|
384
|
+
// filter is demoted to an additive prior and the span must cover the whole unqualified input.
|
|
385
|
+
/**
|
|
386
|
+
* The token a sub-span probe leaves behind when it reads as an administrative qualifier: one token
|
|
387
|
+
* of 2 or 3 uppercase ASCII letters, shaped as a subdivision code rather than looked up in a table.
|
|
388
|
+
*/
|
|
389
|
+
const qualifierRemainder = (span: { start: number; end: number }): string | null => {
|
|
390
|
+
const outside = toks.filter((t) => t.end <= span.start || t.start >= span.end)
|
|
391
|
+
|
|
392
|
+
if (outside.length !== 1) return null
|
|
393
|
+
|
|
394
|
+
const token = outside[0]!.text
|
|
395
|
+
|
|
396
|
+
return isRegionAbbreviationToken(token, { maxLetters: 3 }) ? token : null
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Whether every token a sub-span leaves behind is context rather than identity,
|
|
401
|
+
* testing the remainder's shape rather than the span being proper.
|
|
402
|
+
*/
|
|
403
|
+
const remainderIsContext = (span: { start: number; end: number }): boolean => {
|
|
404
|
+
const outside = toks.filter((t) => t.end <= span.start || t.start >= span.end)
|
|
405
|
+
|
|
406
|
+
if (!outside.length) return true
|
|
407
|
+
|
|
408
|
+
const streetContext = streets.filter(([start, end]) => end <= span.start || start >= span.end)
|
|
409
|
+
|
|
410
|
+
return outside.every(
|
|
411
|
+
(t) =>
|
|
412
|
+
isRegionAbbreviationToken(t.text, { maxLetters: 3 }) ||
|
|
413
|
+
/^\d+[\d-]*$/.test(t.text) ||
|
|
414
|
+
streetContext.some(([start, end]) => t.start >= start && t.end <= end)
|
|
415
|
+
)
|
|
416
|
+
}
|
|
417
|
+
|
|
366
418
|
const softCountry = opts.bareToponymSoftCountry !== false
|
|
367
419
|
const countryWeight = opts.bareToponymCountryWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT
|
|
368
420
|
const qualified = !!postcode || hasAdminQualifier(roots)
|
|
369
421
|
const wholeInput = toks.length ? { start: toks[0]!.start, end: toks.at(-1)!.end } : null
|
|
370
|
-
// Everything the prior needs EXCEPT the span itself — hoisted so the per-span test is one comparison.
|
|
371
422
|
const softCountryEligible = softCountry && !!country && !qualified && !!wholeInput
|
|
372
423
|
|
|
373
424
|
for (const sp of spans) {
|
|
374
425
|
const key = foldName(sp.text)
|
|
375
426
|
|
|
376
427
|
if (key.length < 2 || /^\d+$/.test(key)) continue // skip bare numbers / empties
|
|
377
|
-
//
|
|
378
|
-
// needs an unqualified tree
|
|
379
|
-
// a scope-less bare "Riyadh"/"Frankfurt" is still a NAMING (their Latin surfaces live in alias
|
|
380
|
-
// rows: الرياض / Frankfurt am Main), and conflating the two checks cost exactly those rows on the
|
|
381
|
-
// 2026-08-15 board before this line split them.
|
|
428
|
+
// `wholeSpan` by itself decides the alias tier, while the soft-country prior
|
|
429
|
+
// also needs an unqualified tree and a caller country.
|
|
382
430
|
const wholeSpan = !!wholeInput && sp.start === wholeInput.start && sp.end === wholeInput.end
|
|
431
|
+
|
|
432
|
+
// A sub-span that drops a word of the name is a corruption rather than a
|
|
433
|
+
// recovery. see `remainderIsContext`.
|
|
434
|
+
if (opts.spanRescoreRequireContextRemainder && !wholeSpan && !remainderIsContext(sp)) continue
|
|
435
|
+
|
|
383
436
|
const bare = softCountryEligible && wholeSpan
|
|
437
|
+
const qualifier = wholeSpan ? null : qualifierRemainder(sp)
|
|
384
438
|
|
|
385
439
|
const hits = bare
|
|
386
440
|
? rankByCountryPrior(
|
|
@@ -389,9 +443,8 @@ export async function findRescoreCandidate(
|
|
|
389
443
|
countryWeight
|
|
390
444
|
)
|
|
391
445
|
: // A SUB-span probe is a RE-READING of a token the parse classified into a longer span — it
|
|
392
|
-
// never
|
|
393
|
-
//
|
|
394
|
-
// Москва/Riyadh-class exonym recall, #1546).
|
|
446
|
+
// never included an alias, so alias-keyed rows are off for it (`primaryOnly`); a whole-input
|
|
447
|
+
// span keeps the alias tier regardless of scope.
|
|
395
448
|
await backend.findPlace({
|
|
396
449
|
text: sp.text,
|
|
397
450
|
country,
|
|
@@ -399,23 +452,28 @@ export async function findRescoreCandidate(
|
|
|
399
452
|
placetype: "locality",
|
|
400
453
|
limit: 5,
|
|
401
454
|
...(wholeSpan ? {} : { primaryOnly: true }),
|
|
455
|
+
// The qualifier the sub-span left behind.
|
|
456
|
+
// A backend without the ancestors sidecar ignores this qualifier.
|
|
457
|
+
// That matches a query without one.
|
|
458
|
+
...(qualifier ? { regionQualifier: qualifier } : {}),
|
|
402
459
|
})
|
|
403
460
|
|
|
404
|
-
//
|
|
405
|
-
//
|
|
406
|
-
// equals it. Re-comparing only the PRIMARY name folded to [a-z0-9 ] excluded exactly the
|
|
407
|
-
// non-Latin-primary class: Москва folds to "" and could never equal "moscow", so Moscow RU never
|
|
408
|
-
// entered the list and Moscow, Idaho won by default among the Latin-named bearers — population-
|
|
409
|
-
// first ranking starved, not violated. The alias surface is the recall; ranking then does its job.
|
|
410
|
-
// The postcode check below still applies to every admitted candidate, Moscow RU included.
|
|
461
|
+
// No primary-name re-check: `exactMatch` is name-or-alias, so re-comparing only
|
|
462
|
+
// the primary name would exclude the non-Latin-primary class.
|
|
411
463
|
//
|
|
412
|
-
//
|
|
413
|
-
//
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
//
|
|
417
|
-
//
|
|
418
|
-
const exact =
|
|
464
|
+
// Importance-first within the admitted set.
|
|
465
|
+
// It abstains on an artifact predating the column and so changes no pick.
|
|
466
|
+
const ranked = rankByImportance(hits.filter((h) => h.exactMatch && (h.lat !== 0 || h.lon !== 0)))
|
|
467
|
+
|
|
468
|
+
// The same partition the walk applies: tier-safe, stable and positive-evidence-only,
|
|
469
|
+
// so a backend that ignored `regionQualifier` is byte-stable.
|
|
470
|
+
const exact = qualifier
|
|
471
|
+
? partitionByContainment(
|
|
472
|
+
ranked,
|
|
473
|
+
(c) => c.containedByQualifier === true,
|
|
474
|
+
(c) => c.exactMatch === true
|
|
475
|
+
)
|
|
476
|
+
: ranked
|
|
419
477
|
|
|
420
478
|
const withinThreshold = (p: ResolvedPlace): boolean =>
|
|
421
479
|
!anchor || thresholdKm <= 0 || haversineKm(anchor.lat, anchor.lon, p.lat, p.lon) <= thresholdKm
|
|
@@ -423,12 +481,8 @@ export async function findRescoreCandidate(
|
|
|
423
481
|
for (const h of exact) {
|
|
424
482
|
if (!withinThreshold(h)) continue
|
|
425
483
|
|
|
426
|
-
//
|
|
427
|
-
//
|
|
428
|
-
//
|
|
429
|
-
// #1537: carry the rest of the SAME lookup's exact matches as the namesake runner-ups. Check-filtered on the
|
|
430
|
-
// same rule as the winner — a candidate the postcode check rejected is not a namesake worth offering, it is a
|
|
431
|
-
// place the evidence already excluded. Rank order is the backend's, preserved by `filter`.
|
|
484
|
+
// `postcodeVerified` is true only when an anchor existed and validated this match within
|
|
485
|
+
// `thresholdKm`; otherwise the match is returned unrestricted but flagged lower-precision.
|
|
432
486
|
return {
|
|
433
487
|
text: sp.text,
|
|
434
488
|
start: sp.start,
|
|
@@ -440,15 +494,9 @@ export async function findRescoreCandidate(
|
|
|
440
494
|
}
|
|
441
495
|
}
|
|
442
496
|
|
|
443
|
-
//
|
|
444
|
-
//
|
|
445
|
-
//
|
|
446
|
-
// scoped pass finds nothing and a postcode is present, re-probe the spans UNSCOPED (the admin
|
|
447
|
-
// gazetteer is one extract, all countries), then verify each exact candidate against the postcode's
|
|
448
|
-
// code subset resolved in the CANDIDATE's own country (postcode extracts route by country). A
|
|
449
|
-
// cross-country promotion is accepted ONLY postcode-verified within the radius — never unverified —
|
|
450
|
-
// so a US-shaped query can't wander abroad on a name coincidence (the 48026 guard: resolved
|
|
451
|
-
// trees never reach this code, and unresolved ones must pass the joint postcode check).
|
|
497
|
+
// Joint country recovery: when the scoped pass finds no match and a postcode
|
|
498
|
+
// is present, re-probe unscoped and accept a cross-country promotion only
|
|
499
|
+
// when its code subset resolves postcode-verified within the radius.
|
|
452
500
|
if (opts.postalCompoundRecovery && postcode && thresholdKm > 0) {
|
|
453
501
|
const code = postcodeCodeSubset(postcode) || postcode.trim()
|
|
454
502
|
|
|
@@ -457,15 +505,13 @@ export async function findRescoreCandidate(
|
|
|
457
505
|
|
|
458
506
|
if (key.length < 2 || /^\d+$/.test(key)) continue
|
|
459
507
|
const hits = await backend.findPlace({ text: sp.text, placetype: "locality", limit: 5 })
|
|
460
|
-
//
|
|
461
|
-
//
|
|
462
|
-
// per-candidate postcode verification below remains the sole admission bar.
|
|
508
|
+
// Same alias-surface admission as the scoped pass.
|
|
509
|
+
// The per-candidate postcode verification below is the sole admission bar.
|
|
463
510
|
const exact = hits.filter((h) => h.exactMatch && (h.lat !== 0 || h.lon !== 0))
|
|
464
511
|
|
|
465
512
|
for (const h of exact) {
|
|
466
513
|
if (!h.country || h.country === country) continue
|
|
467
514
|
|
|
468
|
-
// the scoped pass already covered `country`
|
|
469
515
|
const pcHits = await backend.findPlace({
|
|
470
516
|
text: code,
|
|
471
517
|
country: h.country,
|
|
@@ -476,11 +522,9 @@ export async function findRescoreCandidate(
|
|
|
476
522
|
const verified = pcHits.find((p) => p.lat !== 0 || p.lon !== 0)
|
|
477
523
|
|
|
478
524
|
if (verified && haversineKm(verified.lat, verified.lon, h.lat, h.lon) <= thresholdKm) {
|
|
479
|
-
//
|
|
480
|
-
//
|
|
481
|
-
//
|
|
482
|
-
// ambiguous left to declare. The bare-toponym queries #1537 is about never reach this branch (it
|
|
483
|
-
// requires a postcode).
|
|
525
|
+
// Admission uses per-candidate postcode verification.
|
|
526
|
+
// The postcode already picked the country, so this pass has no remaining
|
|
527
|
+
// country ambiguity to report.
|
|
484
528
|
return { text: sp.text, start: sp.start, end: sp.end, place: h, postcodeVerified: true, alternatives: [] }
|
|
485
529
|
}
|
|
486
530
|
}
|