@mailwoman/resolver 11.1.0 → 11.3.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 +1 -1
- package/lib/admin/coherence-passes.ts +1 -1
- package/lib/admin/county-designator.ts +91 -0
- package/lib/admin/former-division.ts +116 -0
- package/lib/bare-toponym-race.ts +1 -1
- package/lib/decorate-node.ts +103 -2
- package/lib/postcode/prefix.ts +7 -16
- package/lib/postcode/shape-coherence.ts +2 -2
- package/lib/remote-resolver.ts +1 -1
- package/lib/resolve/parent-place.ts +109 -0
- package/lib/resolve/passes.ts +68 -11
- package/lib/resolve/sibling-locality.ts +150 -0
- package/lib/resolve.ts +407 -78
- package/lib/scope-retrieval.ts +91 -0
- package/lib/span-rescore.ts +65 -14
- package/lib/toponym-prior.ts +57 -6
- package/out/admin/coherence-passes.js +1 -1
- package/out/admin/coherence-passes.js.map +1 -1
- package/out/admin/county-designator.d.ts +33 -0
- package/out/admin/county-designator.d.ts.map +1 -0
- package/out/admin/county-designator.js +65 -0
- package/out/admin/county-designator.js.map +1 -0
- package/out/admin/former-division.d.ts +47 -0
- package/out/admin/former-division.d.ts.map +1 -0
- package/out/admin/former-division.js +74 -0
- package/out/admin/former-division.js.map +1 -0
- package/out/bare-toponym-race.d.ts +1 -1
- package/out/bare-toponym-race.d.ts.map +1 -1
- package/out/decorate-node.d.ts +22 -3
- package/out/decorate-node.d.ts.map +1 -1
- package/out/decorate-node.js +85 -1
- package/out/decorate-node.js.map +1 -1
- package/out/postcode/prefix.d.ts +4 -2
- package/out/postcode/prefix.d.ts.map +1 -1
- package/out/postcode/prefix.js +7 -13
- package/out/postcode/prefix.js.map +1 -1
- package/out/postcode/shape-coherence.js +2 -2
- package/out/postcode/shape-coherence.js.map +1 -1
- package/out/remote-resolver.d.ts.map +1 -1
- package/out/remote-resolver.js +1 -1
- package/out/remote-resolver.js.map +1 -1
- package/out/resolve/parent-place.d.ts +34 -0
- package/out/resolve/parent-place.d.ts.map +1 -0
- package/out/resolve/parent-place.js +76 -0
- package/out/resolve/parent-place.js.map +1 -0
- package/out/resolve/passes.d.ts +44 -8
- package/out/resolve/passes.d.ts.map +1 -1
- package/out/resolve/passes.js +17 -6
- package/out/resolve/passes.js.map +1 -1
- package/out/resolve/sibling-locality.d.ts +34 -0
- package/out/resolve/sibling-locality.d.ts.map +1 -0
- package/out/resolve/sibling-locality.js +95 -0
- package/out/resolve/sibling-locality.js.map +1 -0
- package/out/resolve.d.ts.map +1 -1
- package/out/resolve.js +273 -69
- package/out/resolve.js.map +1 -1
- package/out/scope-retrieval.d.ts +44 -0
- package/out/scope-retrieval.d.ts.map +1 -0
- package/out/scope-retrieval.js +52 -0
- package/out/scope-retrieval.js.map +1 -0
- package/out/span-rescore.d.ts +15 -1
- package/out/span-rescore.d.ts.map +1 -1
- package/out/span-rescore.js +36 -9
- package/out/span-rescore.js.map +1 -1
- package/out/toponym-prior.d.ts +15 -0
- package/out/toponym-prior.d.ts.map +1 -1
- package/out/toponym-prior.js +37 -6
- package/out/toponym-prior.js.map +1 -1
- package/package.json +9 -9
package/out/resolve.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
3
|
import { matchCountry, matchSubdivision } from "@mailwoman/codex/country";
|
|
4
|
-
import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/placetype-map";
|
|
4
|
+
import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/labels/placetype-map";
|
|
5
5
|
import { collectNodes, isShapeExcludedPostcode } from "@mailwoman/core/decoder";
|
|
6
|
-
import { resolveSwitches, } from "@mailwoman/core/resolver";
|
|
6
|
+
import { hardCountryOf, ScopeStrength, resolveSwitches, } from "@mailwoman/core/resolver";
|
|
7
|
+
import { isPresent } from "@mailwoman/core/values/objects";
|
|
7
8
|
import { countriesFromPostcodeFormat } from "@mailwoman/postcode/postcode-format";
|
|
8
9
|
import { applyAdminCoherence, applyExplicitCountryCoherence, applyParentFallbackContradiction, applyRegionCountryCoherence, } from "#admin/coherence-passes";
|
|
9
10
|
import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "#admin/containment";
|
|
11
|
+
import { COUNTY_DESIGNATOR_FALLBACK, countyFromDesignatedLocality } from "#admin/county-designator";
|
|
12
|
+
import { acceptFormerDivisions, FORMER_DIVISION_TAGS } from "#admin/former-division";
|
|
10
13
|
import { resolveCompoundMunicipality } from "#admin/jp-municipality";
|
|
11
14
|
import { BARE_REGION_DOMINANCE_LOG10, bareCountryCandidate, bareRegionCandidate, emptyLocalityPick, logPopulation, loneBareLocalityNode, } from "#bare-toponym-race";
|
|
12
15
|
import { decorateNode } from "#decorate-node";
|
|
@@ -15,9 +18,12 @@ import { postcodePrefixResolvedPlace, probePostcodePrefix } from "#postcode/pref
|
|
|
15
18
|
import { applyPostcodeShapeCoherence } from "#postcode/shape-coherence";
|
|
16
19
|
import { applyCountryCode, readRegionCodeAsCountry } from "#resolve/country-code";
|
|
17
20
|
import { applyLandmark } from "#resolve/landmark";
|
|
21
|
+
import { agreesWithParent, applyCallerParentQualifier, applyParentPlaceCountry, readParentPlace, } from "#resolve/parent-place";
|
|
18
22
|
import { applyPostcodeConsistency, applyRooftopConsistency, applySpanRescore, createNodeTraceRecorder, DIAGNOSTIC_BANDS, firstPostcodeValue, NOOP_TRACE_RECORDER, } from "#resolve/passes";
|
|
19
23
|
import { applyCountryAsRegion, applyLocalityAsRegion, applyRegionCity, applyStreetAsTown, applyVenueAsTown, } from "#resolve/region-city";
|
|
24
|
+
import { applySiblingLocalityContainment } from "#resolve/sibling-locality";
|
|
20
25
|
import { applyWholeInputPlace } from "#resolve/whole-input";
|
|
26
|
+
import { placesOutsideCountryScope, promoteSoftCountry, retrieveWithSoftCountry, softScopeRetrieves, } from "#scope-retrieval";
|
|
21
27
|
import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier";
|
|
22
28
|
import { DEFAULT_COUNTRY_PRIOR_WEIGHT, promoteCapitals, rankByCountryPrior, rankByImportance, } from "#toponym-prior";
|
|
23
29
|
/**
|
|
@@ -88,7 +94,12 @@ class WOFResolver {
|
|
|
88
94
|
minWinningScore: opts.minWinningScore ?? 0,
|
|
89
95
|
minScoreRefusals: 0,
|
|
90
96
|
candidatesPerLookup: opts.candidatesPerLookup ?? 5,
|
|
91
|
-
|
|
97
|
+
// One scope value: a hard scope filters, and a soft one ranks.
|
|
98
|
+
defaultCountry: hardCountryOf(opts.defaultCountry) ? opts.defaultCountry : null,
|
|
99
|
+
softCountry: opts.defaultCountry?.strength === ScopeStrength.Soft ? opts.defaultCountry : null,
|
|
100
|
+
softCountryWeight: opts.softCountryWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
|
|
101
|
+
scopeCountryRetrieval: opts.scopeCountryRetrieval,
|
|
102
|
+
parentPlace: opts.parentPlace ? readParentPlace(this.#backend, opts.parentPlace) : null,
|
|
92
103
|
bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
|
|
93
104
|
parentFallback: opts.parentFallback,
|
|
94
105
|
// Only enable unreachable diagnostics when a trace sink exists.
|
|
@@ -105,17 +116,20 @@ class WOFResolver {
|
|
|
105
116
|
bias: opts.bias,
|
|
106
117
|
anchorPosterior: opts.anchorPosterior,
|
|
107
118
|
anchorWeight: opts.anchorWeight ?? 2,
|
|
108
|
-
localeCountryPrior: opts.localeCountryPrior,
|
|
109
|
-
localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
|
|
110
119
|
capitalLevel: opts.capitalLevel,
|
|
111
120
|
hardCountry: opts.hardCountry,
|
|
112
121
|
includeAncestors: opts.includeAncestors,
|
|
113
122
|
// Optional admin containment rerank uses a pre-scanned region qualifier.
|
|
114
123
|
adminContainmentRerank: opts.adminContainmentRerank,
|
|
115
124
|
dependentLocalityContainment: opts.dependentLocalityContainment,
|
|
125
|
+
countyDesignatorFallback: opts.countyDesignatorFallback,
|
|
126
|
+
...(opts.formerDivisions && opts.formerDivisionLookup
|
|
127
|
+
? { formerDivisionLookup: opts.formerDivisionLookup, pendingFormerDivisions: new Map() }
|
|
128
|
+
: {}),
|
|
116
129
|
regionQualifier: firstRegionQualifier(tree.roots),
|
|
117
130
|
...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
|
|
118
131
|
};
|
|
132
|
+
applyParentPlaceCountry(state);
|
|
119
133
|
// Optional pre-walk postcode-country coherence pass.
|
|
120
134
|
// This is the only pass allowed to override `defaultCountry`.
|
|
121
135
|
let postcodeScope = null;
|
|
@@ -149,6 +163,13 @@ class WOFResolver {
|
|
|
149
163
|
}
|
|
150
164
|
// A later pass that gives one of these nodes a different place removes the walk's ancestors with the old place.
|
|
151
165
|
const walkedWithAncestors = collectNodes(newRoots, (n) => n.metadata?.["ancestors"] != null);
|
|
166
|
+
if (opts.siblingLocalityContainment) {
|
|
167
|
+
await applySiblingLocalityContainment(newRoots, this.#backend, {
|
|
168
|
+
placetype: state.placetypeMap.locality ?? "locality",
|
|
169
|
+
limit: state.candidatesPerLookup,
|
|
170
|
+
traceSink: state.traceSink ?? null,
|
|
171
|
+
});
|
|
172
|
+
}
|
|
152
173
|
// Stamp metadata for postcode-country override.
|
|
153
174
|
if (postcodeScope) {
|
|
154
175
|
stampPostcodeCountryScope(newRoots, postcodeScope);
|
|
@@ -205,7 +226,9 @@ class WOFResolver {
|
|
|
205
226
|
// Span-rescore fallback tier (default on).
|
|
206
227
|
// Skip when a min-score refusal already occurred.
|
|
207
228
|
if (opts.spanRescore && state.minScoreRefusals === 0) {
|
|
208
|
-
await applySpanRescore(newRoots, tree.raw, this.#backend,
|
|
229
|
+
await applySpanRescore(newRoots, tree.raw, this.#backend,
|
|
230
|
+
// A hard parent's country filters the probes as a caller's default country does.
|
|
231
|
+
state.parentPlace && state.defaultCountry ? { ...opts, defaultCountry: state.defaultCountry } : opts, !state.defaultCountry && softScopeRetrieves(state) ? state.softCountry.country : null);
|
|
209
232
|
}
|
|
210
233
|
// OpenStreetMap places answer after span rescore, so a town that holds the whole name keeps it.
|
|
211
234
|
if (opts.osmPlaces) {
|
|
@@ -223,6 +246,10 @@ class WOFResolver {
|
|
|
223
246
|
if (opts.streetCentroids) {
|
|
224
247
|
applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? []);
|
|
225
248
|
}
|
|
249
|
+
// A value no current division answered is accepted when a former division of that name covered the settlement.
|
|
250
|
+
if (state.pendingFormerDivisions?.size && this.#backend.ancestors) {
|
|
251
|
+
acceptFormerDivisions(newRoots, state.pendingFormerDivisions, this.#backend.ancestors.bind(this.#backend));
|
|
252
|
+
}
|
|
226
253
|
// The walk's ancestors are read again for the place that replaced its pick.
|
|
227
254
|
if (this.#backend.ancestors) {
|
|
228
255
|
for (const node of walkedWithAncestors) {
|
|
@@ -258,7 +285,7 @@ class WOFResolver {
|
|
|
258
285
|
}
|
|
259
286
|
if (picked) {
|
|
260
287
|
resolved = picked.top;
|
|
261
|
-
decorateNode(decorated, picked.top, picked.alternatives);
|
|
288
|
+
decorateNode(decorated, picked.top, picked.alternatives, picked.considered);
|
|
262
289
|
if (picked.metadata) {
|
|
263
290
|
decorated.metadata = { ...decorated.metadata, ...picked.metadata };
|
|
264
291
|
}
|
|
@@ -269,11 +296,22 @@ class WOFResolver {
|
|
|
269
296
|
else if (decorated.metadata?.["bare_region_repick"]) {
|
|
270
297
|
decorated.tag = "region";
|
|
271
298
|
}
|
|
299
|
+
else if (decorated.metadata?.[COUNTY_DESIGNATOR_FALLBACK]) {
|
|
300
|
+
decorated.tag = "subregion";
|
|
301
|
+
}
|
|
272
302
|
// Optional lineage attachment.
|
|
273
303
|
if (state.includeAncestors && this.#backend.ancestors) {
|
|
274
304
|
decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) };
|
|
275
305
|
}
|
|
276
306
|
}
|
|
307
|
+
else if (state.formerDivisionLookup && FORMER_DIVISION_TAGS.has(node.tag)) {
|
|
308
|
+
// No current division answered, so the value may name a former one, checked after the walk.
|
|
309
|
+
const country = parentResolved?.country ?? state.defaultCountry?.country ?? null;
|
|
310
|
+
const matches = state.formerDivisionLookup.divisionsNamed(node.value, country);
|
|
311
|
+
if (matches.length) {
|
|
312
|
+
state.pendingFormerDivisions.set(decorated, matches);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
277
315
|
}
|
|
278
316
|
const carryParent = resolved ?? parentResolved;
|
|
279
317
|
for (const child of node.children) {
|
|
@@ -308,6 +346,113 @@ class WOFResolver {
|
|
|
308
346
|
}
|
|
309
347
|
return found;
|
|
310
348
|
}
|
|
349
|
+
/**
|
|
350
|
+
* A soft scope's own rows merged into an unscoped lookup's candidates, under scope retrieval.
|
|
351
|
+
*
|
|
352
|
+
* It returns `candidates` unchanged without a soft country, when the lookup already
|
|
353
|
+
* has a country, or when the soft scope ranks only.
|
|
354
|
+
*/
|
|
355
|
+
async #withSoftCountryRows(query, candidates, softCountry, state, rec) {
|
|
356
|
+
if (!softCountry || query.country || !softScopeRetrieves(state))
|
|
357
|
+
return candidates;
|
|
358
|
+
rec.check("soft_country_retrieval");
|
|
359
|
+
const merged = await retrieveWithSoftCountry(this.#backend, query, candidates, softCountry);
|
|
360
|
+
rec.stage("soft_country", merged);
|
|
361
|
+
return merged;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* A hard caller parent's split of the ranked candidates into those its lineage agrees with
|
|
365
|
+
* and the excluded rest, each marked `outsideScope`.
|
|
366
|
+
*
|
|
367
|
+
* Without a hard parent or an ancestors lookup, every candidate is kept.
|
|
368
|
+
*/
|
|
369
|
+
#applyHardParent(ranked, qualifierIsParent, state, rec) {
|
|
370
|
+
const parent = state.parentPlace;
|
|
371
|
+
if (parent?.scope.strength !== ScopeStrength.Hard || !this.#backend.ancestors)
|
|
372
|
+
return { kept: ranked, excluded: [] };
|
|
373
|
+
const ancestors = this.#backend.ancestors.bind(this.#backend);
|
|
374
|
+
const agrees = (c) => agreesWithParent(c, parent, ancestors, qualifierIsParent);
|
|
375
|
+
const kept = ranked.filter(agrees);
|
|
376
|
+
rec.stage("parent_scope", kept);
|
|
377
|
+
return {
|
|
378
|
+
kept,
|
|
379
|
+
excluded: ranked.filter((c) => !agrees(c)).map((c) => ({ ...c, outsideScope: true })),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* The same-name places outside a hard default country, for the node's
|
|
384
|
+
* `considered` list, under scope retrieval.
|
|
385
|
+
*
|
|
386
|
+
* The probe changes no pick, so a backend error is traced and answers no places.
|
|
387
|
+
*/
|
|
388
|
+
async #placesOutsideScope(query, state, rec) {
|
|
389
|
+
if (!state.scopeCountryRetrieval || !query.country)
|
|
390
|
+
return [];
|
|
391
|
+
try {
|
|
392
|
+
const outside = await placesOutsideCountryScope(this.#backend, query, query.country);
|
|
393
|
+
rec.check(`outside_scope: ${outside.length}`);
|
|
394
|
+
return outside;
|
|
395
|
+
}
|
|
396
|
+
catch (error) {
|
|
397
|
+
rec.check(`outside_scope_error: ${error.message}`);
|
|
398
|
+
return [];
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* The county of a designated `locality` value's name in its region, when the locality
|
|
403
|
+
* lookup found no locality known to be inside that region.
|
|
404
|
+
*
|
|
405
|
+
* A candidate is known inside when the lookup was scoped by the region and kept it,
|
|
406
|
+
* or when the qualifier containment partition marked it contained.
|
|
407
|
+
* A candidate whose containment neither the region scope nor the partition
|
|
408
|
+
* computed keeps the locality pick.
|
|
409
|
+
*
|
|
410
|
+
* A `locality` lookup is region-scoped exactly when its resolved parent has
|
|
411
|
+
* a numeric id (`applyParentScope`).
|
|
412
|
+
*/
|
|
413
|
+
async #countyDesignatorPick(node, placetype, country, candidates, parentResolved, state, rec) {
|
|
414
|
+
if (!state.countyDesignatorFallback || placetype !== "locality" || node.tag !== "locality" || !country)
|
|
415
|
+
return null;
|
|
416
|
+
const regionScoped = typeof parentResolved?.id === "number";
|
|
417
|
+
const inRegion = candidates.some((c) => c.containedByQualifier === true || (regionScoped && c.regionScopeMiss !== true));
|
|
418
|
+
const unplaced = candidates.some((c) => c.containedByQualifier == null && !regionScoped);
|
|
419
|
+
if (inRegion || unplaced)
|
|
420
|
+
return null;
|
|
421
|
+
const parentIsRegion = parentResolved?.placetype === "region" || parentResolved?.placetype === "macroregion";
|
|
422
|
+
const county = await countyFromDesignatedLocality(this.#backend, node.value, {
|
|
423
|
+
country,
|
|
424
|
+
regionID: parentIsRegion && typeof parentResolved.id === "number" ? parentResolved.id : null,
|
|
425
|
+
regionQualifier: state.regionQualifier ?? null,
|
|
426
|
+
limit: state.candidatesPerLookup,
|
|
427
|
+
});
|
|
428
|
+
if (!county)
|
|
429
|
+
return null;
|
|
430
|
+
rec.check(COUNTY_DESIGNATOR_FALLBACK);
|
|
431
|
+
rec.emit({ id: county.top.id, name: county.top.name, source: COUNTY_DESIGNATOR_FALLBACK });
|
|
432
|
+
return { ...county, metadata: { [COUNTY_DESIGNATOR_FALLBACK]: true } };
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* The postcode-prefix prior's pick for a `postalcode` lookup that missed,
|
|
436
|
+
* when the prior is on and the prefix index holds the code's prefix.
|
|
437
|
+
*/
|
|
438
|
+
#postcodePrefixPick(node, placetype, country, candidates, state, rec) {
|
|
439
|
+
if (candidates.length || placetype !== "postalcode" || !state.postcodePrefixPrior || !state.postcodePrefixIndex) {
|
|
440
|
+
return null;
|
|
441
|
+
}
|
|
442
|
+
const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, country);
|
|
443
|
+
if (!probe)
|
|
444
|
+
return null;
|
|
445
|
+
const metadata = {
|
|
446
|
+
postcode_prefix: probe.prefix,
|
|
447
|
+
postcode_prefix_ancestors: probe.node.ancestors,
|
|
448
|
+
...(probe.node.radiusP95Km != null ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
|
|
449
|
+
...(probe.node.lat != null && probe.node.lon != null ? { coordinate_source: "postcode_prefix" } : {}),
|
|
450
|
+
};
|
|
451
|
+
rec.check("postcode_prefix_prior");
|
|
452
|
+
const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex);
|
|
453
|
+
rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" });
|
|
454
|
+
return { top: prefixPlace, alternatives: [], metadata };
|
|
455
|
+
}
|
|
311
456
|
async #lookupAndPick(node, placetype, parentResolved, state) {
|
|
312
457
|
state.lookupsRemaining--;
|
|
313
458
|
const query = {
|
|
@@ -320,6 +465,7 @@ class WOFResolver {
|
|
|
320
465
|
query.bias = state.bias;
|
|
321
466
|
}
|
|
322
467
|
const parentContainment = applyParentScope(query, node, parentResolved, state);
|
|
468
|
+
const callerParentQualifies = applyCallerParentQualifier(query, state);
|
|
323
469
|
// Country scope precedence: parent -> default -> node hint -> hard country.
|
|
324
470
|
const countryHint = node.metadata?.["country_hint"];
|
|
325
471
|
// Do not apply inferred default-country filtering to country lookups.
|
|
@@ -339,7 +485,9 @@ class WOFResolver {
|
|
|
339
485
|
const containmentEligible = state.adminContainmentRerank &&
|
|
340
486
|
placetype === "locality" &&
|
|
341
487
|
state.regionQualifier != null &&
|
|
342
|
-
!isCallerScope(state.defaultCountry)
|
|
488
|
+
!isCallerScope(state.defaultCountry) &&
|
|
489
|
+
// The backend reads one qualifier, and the caller's parent outranks the parsed region.
|
|
490
|
+
!state.parentPlace;
|
|
343
491
|
if (containmentEligible) {
|
|
344
492
|
query.regionQualifier = state.regionQualifier;
|
|
345
493
|
}
|
|
@@ -355,14 +503,24 @@ class WOFResolver {
|
|
|
355
503
|
// Bind a snapshot so later query mutations do not affect trace history.
|
|
356
504
|
rec.bind(node, placetype, { ...query }, state.candidatesPerLookup);
|
|
357
505
|
let candidates;
|
|
506
|
+
// The anchor posterior and both country scopes act on region and locality lookups only.
|
|
507
|
+
const anchorEligible = placetype === "region" || placetype === "locality";
|
|
508
|
+
// A soft scope ranks a lookup no hard country, tree parent or anchor posterior already scopes.
|
|
509
|
+
const softCountry = anchorEligible && !state.defaultCountry && !state.anchorPosterior ? (state.softCountry?.country ?? null) : null;
|
|
510
|
+
// The places a hard scope excluded, reported on `considered`.
|
|
511
|
+
let outsideScope = [];
|
|
358
512
|
// For unconstrained postalcodes, probe format-implied countries only.
|
|
359
513
|
if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
|
|
360
514
|
rec.check("postcode_format_probe");
|
|
361
515
|
let best = null;
|
|
516
|
+
const countryWinners = [];
|
|
362
517
|
for (const impliedCountry of state.postcodeFormatCountries) {
|
|
363
518
|
try {
|
|
364
519
|
const hits = await this.#backend.findPlace({ ...query, country: impliedCountry });
|
|
365
520
|
const top = hits[0];
|
|
521
|
+
if (top) {
|
|
522
|
+
countryWinners.push(top);
|
|
523
|
+
}
|
|
366
524
|
// Keep the best per-country winner by score.
|
|
367
525
|
if (top && (!best || top.score > best.score)) {
|
|
368
526
|
best = top;
|
|
@@ -374,7 +532,7 @@ class WOFResolver {
|
|
|
374
532
|
}
|
|
375
533
|
if (best) {
|
|
376
534
|
rec.emit({ id: best.id, name: best.name, source: "postcode_format_probe" });
|
|
377
|
-
return { top: best, alternatives: [] };
|
|
535
|
+
return { top: best, alternatives: [], considered: countryWinners.filter((c) => c !== best) };
|
|
378
536
|
}
|
|
379
537
|
candidates = [];
|
|
380
538
|
}
|
|
@@ -393,6 +551,10 @@ class WOFResolver {
|
|
|
393
551
|
candidates = await this.#backend.findPlace(query);
|
|
394
552
|
rec.stage("parent_fallback", candidates);
|
|
395
553
|
}
|
|
554
|
+
candidates = await this.#withSoftCountryRows(query, candidates, softCountry, state, rec);
|
|
555
|
+
// Only a lookup the default country filtered reports the same-name places outside it.
|
|
556
|
+
const filteredByDefault = anchorEligible && !parentResolved && query.country != null && query.country === defaultCountryForLookup;
|
|
557
|
+
outsideScope = filteredByDefault ? await this.#placesOutsideScope(query, state, rec) : [];
|
|
396
558
|
// Optional diagnostics: record other bands that can resolve this value.
|
|
397
559
|
if (!candidates.length && state.diagnoseUnreachable) {
|
|
398
560
|
rec.reachable(await this.#probeOtherBands(query, placetype));
|
|
@@ -405,26 +567,11 @@ class WOFResolver {
|
|
|
405
567
|
return null;
|
|
406
568
|
}
|
|
407
569
|
}
|
|
408
|
-
//
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
postcode_prefix: probe.prefix,
|
|
414
|
-
postcode_prefix_ancestors: probe.node.ancestors,
|
|
415
|
-
...(probe.node.radiusP95Km != null ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
|
|
416
|
-
...(probe.node.lat != null && probe.node.lon != null ? { coordinate_source: "postcode_prefix" } : {}),
|
|
417
|
-
};
|
|
418
|
-
rec.check("postcode_prefix_prior");
|
|
419
|
-
const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex);
|
|
420
|
-
rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" });
|
|
421
|
-
return {
|
|
422
|
-
top: prefixPlace,
|
|
423
|
-
alternatives: [],
|
|
424
|
-
metadata,
|
|
425
|
-
};
|
|
426
|
-
}
|
|
427
|
-
}
|
|
570
|
+
// A designated county span resolves as its region's county, and a missed postcode takes the prefix prior.
|
|
571
|
+
const recovered = (await this.#countyDesignatorPick(node, placetype, query.country, candidates, parentResolved, state, rec)) ??
|
|
572
|
+
this.#postcodePrefixPick(node, placetype, query.country, candidates, state, rec);
|
|
573
|
+
if (recovered)
|
|
574
|
+
return recovered;
|
|
428
575
|
// Bare-toponym race: locality-tagged single spans also probe country/region.
|
|
429
576
|
const isBareRace = placetype === "locality" && node === state.bareLocalityNode;
|
|
430
577
|
if (isBareRace) {
|
|
@@ -432,6 +579,8 @@ class WOFResolver {
|
|
|
432
579
|
}
|
|
433
580
|
const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null;
|
|
434
581
|
const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null;
|
|
582
|
+
// The race probes a pick passes over, kept for the geocode result's candidate list.
|
|
583
|
+
const raceLosers = (picked) => [bareCountry, bareRegion].filter(isPresent).filter((probe) => probe !== picked);
|
|
435
584
|
if (!candidates.length) {
|
|
436
585
|
// With no locality candidates, a bare name takes an admin or sub-locality namesake.
|
|
437
586
|
const pick = isBareRace
|
|
@@ -440,50 +589,21 @@ class WOFResolver {
|
|
|
440
589
|
if (pick) {
|
|
441
590
|
rec.check(pick.check);
|
|
442
591
|
rec.emit({ id: pick.place.id, name: pick.place.name, source: pick.source });
|
|
443
|
-
return {
|
|
592
|
+
return {
|
|
593
|
+
top: pick.place,
|
|
594
|
+
alternatives: [],
|
|
595
|
+
considered: [...raceLosers(pick.place), ...outsideScope],
|
|
596
|
+
metadata: pick.metadata,
|
|
597
|
+
};
|
|
444
598
|
}
|
|
445
599
|
rec.emit(null);
|
|
446
600
|
return null;
|
|
447
601
|
}
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
const anchorEligible = placetype === "region" || placetype === "locality";
|
|
451
|
-
let ranked = candidates;
|
|
452
|
-
if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
|
|
453
|
-
const post = state.anchorPosterior;
|
|
454
|
-
const w = state.anchorWeight;
|
|
455
|
-
// Within-tier key uses prominence (fallback score) plus posterior boost.
|
|
456
|
-
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
|
|
457
|
-
ranked = [...candidates].sort((a, b) => {
|
|
458
|
-
const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false);
|
|
459
|
-
if (tier !== 0)
|
|
460
|
-
return tier;
|
|
461
|
-
// Unknown-country candidates get zero posterior mass.
|
|
462
|
-
const aKey = (a.prominence ?? a.score) + w * (a.country ? (post[a.country] ?? 0) : 0);
|
|
463
|
-
const bKey = (b.prominence ?? b.score) + w * (b.country ? (post[b.country] ?? 0) : 0);
|
|
464
|
-
return bKey - aKey || b.score - a.score;
|
|
465
|
-
});
|
|
466
|
-
rec.stage("anchor", ranked);
|
|
467
|
-
}
|
|
468
|
-
// Optional locale-country soft prior adds to candidate scores while retaining every candidate.
|
|
469
|
-
// Disabled when default country or anchor posterior is present.
|
|
470
|
-
if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
|
|
471
|
-
ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight);
|
|
472
|
-
rec.stage("locale_prior", ranked);
|
|
473
|
-
}
|
|
474
|
-
// Importance-first rerank (skipped when anchor posterior exists).
|
|
475
|
-
if (!state.anchorPosterior) {
|
|
476
|
-
ranked = rankByImportance(ranked);
|
|
477
|
-
rec.stage("importance", ranked);
|
|
478
|
-
// Optional bounded capital promotion.
|
|
479
|
-
if (state.capitalLevel) {
|
|
480
|
-
ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node);
|
|
481
|
-
rec.stage("capital", ranked);
|
|
482
|
-
}
|
|
483
|
-
}
|
|
602
|
+
const softPromotion = rankByPriors(candidates, anchorEligible, softCountry, node, state, rec);
|
|
603
|
+
let ranked = softPromotion.ranked;
|
|
484
604
|
// Final containment partition.
|
|
485
605
|
// It reads the address's own qualifier and preserves the exact-match tier.
|
|
486
|
-
const qualifierPartition = containmentEligible || parentContainment;
|
|
606
|
+
const qualifierPartition = containmentEligible || parentContainment || callerParentQualifies;
|
|
487
607
|
if (qualifierPartition) {
|
|
488
608
|
ranked = partitionByContainment(ranked, (c) => c.containedByQualifier === true, (c) => c.exactMatch === true);
|
|
489
609
|
rec.stage("containment", ranked);
|
|
@@ -497,6 +617,14 @@ class WOFResolver {
|
|
|
497
617
|
];
|
|
498
618
|
rec.stage("exact_type", ranked);
|
|
499
619
|
}
|
|
620
|
+
const parentScoped = this.#applyHardParent(ranked, callerParentQualifies, state, rec);
|
|
621
|
+
ranked = parentScoped.kept;
|
|
622
|
+
outsideScope = [...parentScoped.excluded, ...outsideScope];
|
|
623
|
+
if (!ranked.length) {
|
|
624
|
+
rec.check("parent_scope_excluded_all");
|
|
625
|
+
rec.emit(null);
|
|
626
|
+
return null;
|
|
627
|
+
}
|
|
500
628
|
const top = ranked[0];
|
|
501
629
|
if (top.score < state.minWinningScore) {
|
|
502
630
|
state.minScoreRefusals++;
|
|
@@ -508,12 +636,22 @@ class WOFResolver {
|
|
|
508
636
|
if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
|
|
509
637
|
rec.check("bare_country_repick");
|
|
510
638
|
rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" });
|
|
511
|
-
return {
|
|
639
|
+
return {
|
|
640
|
+
top: bareCountry,
|
|
641
|
+
alternatives: ranked,
|
|
642
|
+
considered: [...raceLosers(bareCountry), ...outsideScope],
|
|
643
|
+
metadata: { bare_country_repick: true },
|
|
644
|
+
};
|
|
512
645
|
}
|
|
513
646
|
if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
|
|
514
647
|
rec.check("bare_region_repick");
|
|
515
648
|
rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" });
|
|
516
|
-
return {
|
|
649
|
+
return {
|
|
650
|
+
top: bareRegion,
|
|
651
|
+
alternatives: ranked,
|
|
652
|
+
considered: [...raceLosers(bareRegion), ...outsideScope],
|
|
653
|
+
metadata: { bare_region_repick: true },
|
|
654
|
+
};
|
|
517
655
|
}
|
|
518
656
|
// Stamp fallback quality when a macro-type winner stands in.
|
|
519
657
|
if (isPlacetypeFallback(placetype, top.placetype)) {
|
|
@@ -525,6 +663,8 @@ class WOFResolver {
|
|
|
525
663
|
const pickMetadata = {
|
|
526
664
|
...containmentStamps(qualifierPartition, parentContainment, ranked, top),
|
|
527
665
|
...(top.variantAliasExempted === true ? { variant_alias_exemption: true } : {}),
|
|
666
|
+
// The soft scope's promotion moved this place ahead of a larger namesake.
|
|
667
|
+
...(top === softPromotion.promoted ? { soft_country_promotion: softCountry } : {}),
|
|
528
668
|
// Mark picks admitted outside resolved parent scope.
|
|
529
669
|
...((parentResolved && typeof parentResolved.id === "number" && query.parentID == null) ||
|
|
530
670
|
top.regionScopeMiss === true
|
|
@@ -534,6 +674,7 @@ class WOFResolver {
|
|
|
534
674
|
return {
|
|
535
675
|
top,
|
|
536
676
|
alternatives: ranked.slice(1),
|
|
677
|
+
considered: [...raceLosers(null), ...outsideScope],
|
|
537
678
|
...(Object.keys(pickMetadata).length ? { metadata: pickMetadata } : {}),
|
|
538
679
|
};
|
|
539
680
|
}
|
|
@@ -573,6 +714,69 @@ function containmentStamps(qualifierPartition, parentContainment, ranked, top) {
|
|
|
573
714
|
...(parentContainment && top.containedByQualifier === true ? { contained_by_parent: true } : {}),
|
|
574
715
|
};
|
|
575
716
|
}
|
|
717
|
+
/**
|
|
718
|
+
* Ranks a lookup's candidates by its priors in order: the postcode anchor posterior,
|
|
719
|
+
* the ranking-only soft scope, importance with capital promotion, then the retrieval soft scope.
|
|
720
|
+
*
|
|
721
|
+
* `promoted` is the place the retrieval soft scope moved to the lead, or null.
|
|
722
|
+
*/
|
|
723
|
+
function rankByPriors(candidates, anchorEligible, softCountry, node, state, rec) {
|
|
724
|
+
let ranked = candidates;
|
|
725
|
+
// Optional anchor-based rerank using postcode country posterior, kept tier-safe by exact-match first.
|
|
726
|
+
if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
|
|
727
|
+
ranked = rankByAnchorPosterior(candidates, state.anchorPosterior, state.anchorWeight);
|
|
728
|
+
rec.stage("anchor", ranked);
|
|
729
|
+
ranked = rankWithinPosteriorCountry(ranked, state.capitalLevel, node);
|
|
730
|
+
rec.stage("importance", ranked);
|
|
731
|
+
}
|
|
732
|
+
// Without scope retrieval, the soft scope adds to candidate scores ahead of the importance rerank.
|
|
733
|
+
if (softCountry && !softScopeRetrieves(state)) {
|
|
734
|
+
ranked = rankByCountryPrior(ranked, softCountry, state.softCountryWeight);
|
|
735
|
+
rec.stage("locale_prior", ranked);
|
|
736
|
+
}
|
|
737
|
+
// Importance-first rerank (the posterior branch above runs its own, within the winning country).
|
|
738
|
+
if (!state.anchorPosterior) {
|
|
739
|
+
ranked = rankByImportance(ranked);
|
|
740
|
+
rec.stage("importance", ranked);
|
|
741
|
+
// Optional bounded capital promotion.
|
|
742
|
+
if (state.capitalLevel) {
|
|
743
|
+
ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node);
|
|
744
|
+
rec.stage("capital", ranked);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
return promoteSoftCountry(ranked, softCountry, state, rec);
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Sorts candidates by the postcode country posterior, exact matches first.
|
|
751
|
+
*
|
|
752
|
+
* Within a match tier, the key is a candidate's prominence (its score when it has none)
|
|
753
|
+
* plus `weight` times its country's posterior mass.
|
|
754
|
+
* A candidate with no country gets no posterior mass.
|
|
755
|
+
*/
|
|
756
|
+
function rankByAnchorPosterior(candidates, posterior, weight) {
|
|
757
|
+
const key = (c) => (c.prominence ?? c.score) + weight * (c.country ? (posterior[c.country] ?? 0) : 0);
|
|
758
|
+
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
|
|
759
|
+
return [...candidates].sort((a, b) => Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false) || key(b) - key(a) || b.score - a.score);
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Reorders the posterior-ranked leader's peers, the candidates in its country and exact-match
|
|
763
|
+
* tier, by importance and capital promotion, as the path without a posterior ranks them.
|
|
764
|
+
*
|
|
765
|
+
* The posterior decides the country.
|
|
766
|
+
* Within that country this order makes a venue query (`Clayton Post Office, Clayton, WI`)
|
|
767
|
+
* pick the same locality as its bare form (`Clayton, WI`).
|
|
768
|
+
*/
|
|
769
|
+
function rankWithinPosteriorCountry(ranked, capitalLevel, node) {
|
|
770
|
+
const leader = ranked[0];
|
|
771
|
+
if (!leader?.country)
|
|
772
|
+
return [...ranked];
|
|
773
|
+
const isPeer = (c) => c.country === leader.country && (c.exactMatch === true) === (leader.exactMatch === true);
|
|
774
|
+
let peers = rankByImportance(ranked.filter(isPeer));
|
|
775
|
+
if (capitalLevel) {
|
|
776
|
+
peers = promoteCapitalsWithReceipt(peers, capitalLevel, node);
|
|
777
|
+
}
|
|
778
|
+
return [...peers, ...ranked.filter((c) => !isPeer(c))];
|
|
779
|
+
}
|
|
576
780
|
/**
|
|
577
781
|
* Promote capitals and stamp `capital_promotion` when the leader changes.
|
|
578
782
|
* Metadata only.
|