@mailwoman/resolver 11.0.0 → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +4 -4
  2. package/lib/admin/coherence-passes.ts +14 -20
  3. package/lib/admin/containment.ts +6 -5
  4. package/lib/admin/county-designator.ts +91 -0
  5. package/lib/admin/jp-municipality.ts +3 -3
  6. package/lib/admin/winner.ts +5 -5
  7. package/lib/admin.ts +2 -5
  8. package/lib/bare-toponym-race.ts +12 -10
  9. package/lib/decorate-node.ts +51 -8
  10. package/lib/fold-name.ts +8 -8
  11. package/lib/index.ts +11 -8
  12. package/lib/plausibility.ts +2 -5
  13. package/lib/postcode/country-coherence.ts +4 -7
  14. package/lib/postcode/prefix.ts +4 -7
  15. package/lib/postcode/shape-coherence.ts +5 -8
  16. package/lib/postcode.ts +2 -5
  17. package/lib/remote-resolver.ts +2 -5
  18. package/lib/rerank.ts +7 -8
  19. package/lib/resolve/country-code.ts +22 -18
  20. package/lib/resolve/landmark.ts +19 -12
  21. package/lib/resolve/passes.ts +19 -9
  22. package/lib/resolve/region-city.ts +192 -8
  23. package/lib/resolve/whole-input.ts +49 -0
  24. package/lib/resolve.ts +197 -48
  25. package/lib/span-rescore.ts +61 -28
  26. package/lib/street/evidence.ts +2 -5
  27. package/lib/street/tier.ts +9 -12
  28. package/lib/street.ts +2 -5
  29. package/lib/toponym-prior.ts +4 -7
  30. package/out/admin/coherence-passes.d.ts +2 -7
  31. package/out/admin/coherence-passes.d.ts.map +1 -1
  32. package/out/admin/coherence-passes.js +14 -20
  33. package/out/admin/coherence-passes.js.map +1 -1
  34. package/out/admin/containment.d.ts +3 -5
  35. package/out/admin/containment.d.ts.map +1 -1
  36. package/out/admin/containment.js +5 -5
  37. package/out/admin/containment.js.map +1 -1
  38. package/out/admin/county-designator.d.ts +33 -0
  39. package/out/admin/county-designator.d.ts.map +1 -0
  40. package/out/admin/county-designator.js +65 -0
  41. package/out/admin/county-designator.js.map +1 -0
  42. package/out/admin/jp-municipality.d.ts +0 -3
  43. package/out/admin/jp-municipality.d.ts.map +1 -1
  44. package/out/admin/jp-municipality.js +2 -15
  45. package/out/admin/jp-municipality.js.map +1 -1
  46. package/out/admin/winner.d.ts +2 -5
  47. package/out/admin/winner.d.ts.map +1 -1
  48. package/out/admin/winner.js +2 -9
  49. package/out/admin/winner.js.map +1 -1
  50. package/out/admin.d.ts +0 -5
  51. package/out/admin.d.ts.map +1 -1
  52. package/out/admin.js +2 -5
  53. package/out/admin.js.map +1 -1
  54. package/out/bare-toponym-race.d.ts +0 -11
  55. package/out/bare-toponym-race.d.ts.map +1 -1
  56. package/out/bare-toponym-race.js +3 -12
  57. package/out/bare-toponym-race.js.map +1 -1
  58. package/out/decorate-node.d.ts +14 -6
  59. package/out/decorate-node.d.ts.map +1 -1
  60. package/out/decorate-node.js +46 -10
  61. package/out/decorate-node.js.map +1 -1
  62. package/out/fold-name.d.ts +5 -8
  63. package/out/fold-name.d.ts.map +1 -1
  64. package/out/fold-name.js +7 -8
  65. package/out/fold-name.js.map +1 -1
  66. package/out/index.d.ts +8 -8
  67. package/out/index.d.ts.map +1 -1
  68. package/out/index.js +10 -8
  69. package/out/index.js.map +1 -1
  70. package/out/plausibility.d.ts +0 -5
  71. package/out/plausibility.d.ts.map +1 -1
  72. package/out/plausibility.js +2 -5
  73. package/out/plausibility.js.map +1 -1
  74. package/out/postcode/country-coherence.d.ts +2 -7
  75. package/out/postcode/country-coherence.d.ts.map +1 -1
  76. package/out/postcode/country-coherence.js +3 -6
  77. package/out/postcode/country-coherence.js.map +1 -1
  78. package/out/postcode/prefix.d.ts +2 -7
  79. package/out/postcode/prefix.d.ts.map +1 -1
  80. package/out/postcode/prefix.js +3 -6
  81. package/out/postcode/prefix.js.map +1 -1
  82. package/out/postcode/shape-coherence.d.ts +1 -6
  83. package/out/postcode/shape-coherence.d.ts.map +1 -1
  84. package/out/postcode/shape-coherence.js +4 -7
  85. package/out/postcode/shape-coherence.js.map +1 -1
  86. package/out/postcode.d.ts +0 -5
  87. package/out/postcode.d.ts.map +1 -1
  88. package/out/postcode.js +2 -5
  89. package/out/postcode.js.map +1 -1
  90. package/out/remote-resolver.d.ts +0 -5
  91. package/out/remote-resolver.d.ts.map +1 -1
  92. package/out/remote-resolver.js +2 -5
  93. package/out/remote-resolver.js.map +1 -1
  94. package/out/rerank.d.ts +3 -7
  95. package/out/rerank.d.ts.map +1 -1
  96. package/out/rerank.js +3 -10
  97. package/out/rerank.js.map +1 -1
  98. package/out/resolve/country-code.d.ts +3 -24
  99. package/out/resolve/country-code.d.ts.map +1 -1
  100. package/out/resolve/country-code.js +21 -18
  101. package/out/resolve/country-code.js.map +1 -1
  102. package/out/resolve/landmark.d.ts +10 -11
  103. package/out/resolve/landmark.d.ts.map +1 -1
  104. package/out/resolve/landmark.js +18 -12
  105. package/out/resolve/landmark.js.map +1 -1
  106. package/out/resolve/passes.d.ts +7 -7
  107. package/out/resolve/passes.d.ts.map +1 -1
  108. package/out/resolve/passes.js +11 -8
  109. package/out/resolve/passes.js.map +1 -1
  110. package/out/resolve/region-city.d.ts +34 -7
  111. package/out/resolve/region-city.d.ts.map +1 -1
  112. package/out/resolve/region-city.js +159 -8
  113. package/out/resolve/region-city.js.map +1 -1
  114. package/out/resolve/whole-input.d.ts +14 -0
  115. package/out/resolve/whole-input.d.ts.map +1 -0
  116. package/out/resolve/whole-input.js +37 -0
  117. package/out/resolve/whole-input.js.map +1 -0
  118. package/out/resolve.d.ts +0 -8
  119. package/out/resolve.d.ts.map +1 -1
  120. package/out/resolve.js +124 -46
  121. package/out/resolve.js.map +1 -1
  122. package/out/span-rescore.d.ts +12 -16
  123. package/out/span-rescore.d.ts.map +1 -1
  124. package/out/span-rescore.js +46 -19
  125. package/out/span-rescore.js.map +1 -1
  126. package/out/street/evidence.d.ts +0 -5
  127. package/out/street/evidence.d.ts.map +1 -1
  128. package/out/street/evidence.js +2 -5
  129. package/out/street/evidence.js.map +1 -1
  130. package/out/street/tier.d.ts +3 -8
  131. package/out/street/tier.d.ts.map +1 -1
  132. package/out/street/tier.js +7 -10
  133. package/out/street/tier.js.map +1 -1
  134. package/out/street.d.ts +0 -5
  135. package/out/street.d.ts.map +1 -1
  136. package/out/street.js +2 -5
  137. package/out/street.js.map +1 -1
  138. package/out/toponym-prior.d.ts +2 -7
  139. package/out/toponym-prior.d.ts.map +1 -1
  140. package/out/toponym-prior.js +4 -7
  141. package/out/toponym-prior.js.map +1 -1
  142. package/package.json +9 -9
package/lib/resolve.ts CHANGED
@@ -1,9 +1,9 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
5
  * `resolveTree` walks an `AddressTree` top-down and decorates matched nodes.
6
+ *
7
7
  * Child lookups are scoped by resolved parents to reduce ambiguity.
8
8
  */
9
9
 
@@ -29,6 +29,7 @@ import {
29
29
  applyRegionCountryCoherence,
30
30
  } from "#admin/coherence-passes"
31
31
  import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "#admin/containment"
32
+ import { COUNTY_DESIGNATOR_FALLBACK, countyFromDesignatedLocality } from "#admin/county-designator"
32
33
  import { resolveCompoundMunicipality } from "#admin/jp-municipality"
33
34
  import {
34
35
  BARE_REGION_DOMINANCE_LOG10,
@@ -56,10 +57,18 @@ import {
56
57
  DIAGNOSTIC_BANDS,
57
58
  firstPostcodeValue,
58
59
  NOOP_TRACE_RECORDER,
60
+ type NodeTraceRecorder,
59
61
  type ResolutionState,
60
62
  type ResolvedOpts,
61
63
  } from "#resolve/passes"
62
- import { applyLocalityAsRegion, applyRegionCity } from "#resolve/region-city"
64
+ import {
65
+ applyCountryAsRegion,
66
+ applyLocalityAsRegion,
67
+ applyRegionCity,
68
+ applyStreetAsTown,
69
+ applyVenueAsTown,
70
+ } from "#resolve/region-city"
71
+ import { applyWholeInputPlace } from "#resolve/whole-input"
63
72
  import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier"
64
73
  import {
65
74
  type CapitalLevelFn,
@@ -78,6 +87,15 @@ export function createWOFResolver(backend: ResolverBackend): Resolver {
78
87
  return new WOFResolver(backend)
79
88
  }
80
89
 
90
+ /**
91
+ * One lookup's pick: the place, its runners-up, and the metadata the walk stamps on the node.
92
+ */
93
+ interface LookupPick {
94
+ top: CoordinateOptionalPlace
95
+ alternatives: ResolvedPlace[]
96
+ metadata?: Record<string, unknown>
97
+ }
98
+
81
99
  /**
82
100
  * Return an explicit country scope from the tree when it is unambiguous.
83
101
  *
@@ -176,6 +194,7 @@ class WOFResolver implements Resolver {
176
194
  // Optional admin containment rerank uses a pre-scanned region qualifier.
177
195
  adminContainmentRerank: opts.adminContainmentRerank,
178
196
  dependentLocalityContainment: opts.dependentLocalityContainment,
197
+ countyDesignatorFallback: opts.countyDesignatorFallback,
179
198
  regionQualifier: firstRegionQualifier(tree.roots),
180
199
  ...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
181
200
  }
@@ -219,6 +238,9 @@ class WOFResolver implements Resolver {
219
238
  newRoots.push(await this.#walk(root, /* parentResolved */ null, state))
220
239
  }
221
240
 
241
+ // A later pass that gives one of these nodes a different place removes the walk's ancestors with the old place.
242
+ const walkedWithAncestors = collectNodes(newRoots, (n) => n.metadata?.["ancestors"] != null)
243
+
222
244
  // Stamp metadata for postcode-country override.
223
245
  if (postcodeScope) {
224
246
  stampPostcodeCountryScope(newRoots, postcodeScope)
@@ -243,6 +265,9 @@ class WOFResolver implements Resolver {
243
265
  // Re-resolve foreign region/locality pairs blocked by locale scope.
244
266
  await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry?.country ?? null)
245
267
  await applyRegionCity(newRoots, this.#backend)
268
+ await applyCountryAsRegion(newRoots, this.#backend)
269
+ await applyVenueAsTown(newRoots, this.#backend)
270
+ await applyStreetAsTown(newRoots, this.#backend)
246
271
 
247
272
  if (isCallerScope(state.defaultCountry)) {
248
273
  await applyLocalityAsRegion(newRoots, this.#backend, state.defaultCountry!.country)
@@ -255,6 +280,15 @@ class WOFResolver implements Resolver {
255
280
  await applyLandmark(newRoots, opts.writtenInput ?? tree.raw, opts.landmarks)
256
281
  }
257
282
 
283
+ if (opts.adminCoherence) {
284
+ await applyWholeInputPlace(
285
+ newRoots,
286
+ opts.writtenInput ?? tree.raw,
287
+ this.#backend,
288
+ isCallerScope(state.defaultCountry) ? state.defaultCountry!.country : null
289
+ )
290
+ }
291
+
258
292
  // The postcode and rooftop passes hold a locality to the same distance from their point.
259
293
  const consistencyThresholdKm = opts.postcodeConsistencyThresholdKm ?? 50
260
294
 
@@ -269,7 +303,7 @@ class WOFResolver implements Resolver {
269
303
 
270
304
  // Optional exact address-point tier.
271
305
  if (opts.addressPoints) {
272
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
306
+ await applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
273
307
  }
274
308
 
275
309
  // Optional interpolation tier after exact points.
@@ -290,7 +324,7 @@ class WOFResolver implements Resolver {
290
324
 
291
325
  // Retry exact address-point tier once after span-rescore recovery.
292
326
  if (opts.addressPoints) {
293
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
327
+ await applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
294
328
  }
295
329
 
296
330
  // A rooftop row keyed by locality name can lie in a namesake of the selected locality.
@@ -303,6 +337,17 @@ class WOFResolver implements Resolver {
303
337
  applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
304
338
  }
305
339
 
340
+ // The walk's ancestors are read again for the place that replaced its pick.
341
+ if (this.#backend.ancestors) {
342
+ for (const node of walkedWithAncestors) {
343
+ const id = node.placeID?.startsWith("wof:") ? Number(node.placeID.slice(4)) : Number.NaN
344
+
345
+ if (node.metadata?.["ancestors"] == null && Number.isInteger(id)) {
346
+ node.metadata = { ...node.metadata, ancestors: this.#backend.ancestors(id) }
347
+ }
348
+ }
349
+ }
350
+
306
351
  return { raw: tree.raw, roots: newRoots }
307
352
  }
308
353
 
@@ -355,6 +400,8 @@ class WOFResolver implements Resolver {
355
400
  decorated.tag = "country"
356
401
  } else if (decorated.metadata?.["bare_region_repick"]) {
357
402
  decorated.tag = "region"
403
+ } else if (decorated.metadata?.[COUNTY_DESIGNATOR_FALLBACK]) {
404
+ decorated.tag = "subregion"
358
405
  }
359
406
 
360
407
  // Optional lineage attachment.
@@ -406,6 +453,91 @@ class WOFResolver implements Resolver {
406
453
  return found
407
454
  }
408
455
 
456
+ /**
457
+ * The county of a designated `locality` value's name in its region, when the locality
458
+ * lookup found no locality known to be inside that region.
459
+ *
460
+ * A candidate is known inside when the lookup was scoped by the region and kept it,
461
+ * or when the qualifier containment partition marked it contained.
462
+ * A candidate whose containment neither the region scope nor the partition
463
+ * computed keeps the locality pick.
464
+ *
465
+ * A `locality` lookup is region-scoped exactly when its resolved parent has
466
+ * a numeric id (`applyParentScope`).
467
+ */
468
+ async #countyDesignatorPick(
469
+ node: AddressNode,
470
+ placetype: string,
471
+ country: string | undefined,
472
+ candidates: readonly ResolvedPlace[],
473
+ parentResolved: CoordinateOptionalPlace | null,
474
+ state: ResolutionState,
475
+ rec: NodeTraceRecorder
476
+ ): Promise<LookupPick | null> {
477
+ if (!state.countyDesignatorFallback || placetype !== "locality" || node.tag !== "locality" || !country) return null
478
+
479
+ const regionScoped = typeof parentResolved?.id === "number"
480
+
481
+ const inRegion = candidates.some(
482
+ (c) => c.containedByQualifier === true || (regionScoped && c.regionScopeMiss !== true)
483
+ )
484
+
485
+ const unplaced = candidates.some((c) => c.containedByQualifier == null && !regionScoped)
486
+
487
+ if (inRegion || unplaced) return null
488
+
489
+ const parentIsRegion = parentResolved?.placetype === "region" || parentResolved?.placetype === "macroregion"
490
+
491
+ const county = await countyFromDesignatedLocality(this.#backend, node.value, {
492
+ country,
493
+ regionID: parentIsRegion && typeof parentResolved.id === "number" ? parentResolved.id : null,
494
+ regionQualifier: state.regionQualifier ?? null,
495
+ limit: state.candidatesPerLookup,
496
+ })
497
+
498
+ if (!county) return null
499
+
500
+ rec.check(COUNTY_DESIGNATOR_FALLBACK)
501
+ rec.emit({ id: county.top.id, name: county.top.name, source: COUNTY_DESIGNATOR_FALLBACK })
502
+
503
+ return { ...county, metadata: { [COUNTY_DESIGNATOR_FALLBACK]: true } }
504
+ }
505
+
506
+ /**
507
+ * The postcode-prefix prior's pick for a `postalcode` lookup that missed,
508
+ * when the prior is on and the prefix index holds the code's prefix.
509
+ */
510
+ #postcodePrefixPick(
511
+ node: AddressNode,
512
+ placetype: string,
513
+ country: string | undefined,
514
+ candidates: readonly ResolvedPlace[],
515
+ state: ResolutionState,
516
+ rec: NodeTraceRecorder
517
+ ): LookupPick | null {
518
+ if (candidates.length || placetype !== "postalcode" || !state.postcodePrefixPrior || !state.postcodePrefixIndex) {
519
+ return null
520
+ }
521
+
522
+ const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, country)
523
+
524
+ if (!probe) return null
525
+
526
+ const metadata: Record<string, unknown> = {
527
+ postcode_prefix: probe.prefix,
528
+ postcode_prefix_ancestors: probe.node.ancestors,
529
+ ...(probe.node.radiusP95Km != null ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
530
+ ...(probe.node.lat != null && probe.node.lon != null ? { coordinate_source: "postcode_prefix" } : {}),
531
+ }
532
+
533
+ rec.check("postcode_prefix_prior")
534
+ const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
535
+
536
+ rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
537
+
538
+ return { top: prefixPlace, alternatives: [], metadata }
539
+ }
540
+
409
541
  async #lookupAndPick(
410
542
  node: AddressNode,
411
543
  placetype: string,
@@ -529,7 +661,7 @@ class WOFResolver implements Resolver {
529
661
  rec.reachable(await this.#probeOtherBands(query, placetype))
530
662
  }
531
663
  } catch (error) {
532
- // Defensive: backend errors should not abort the whole tree walk.
664
+ // Defensive: backend errors shouldn't abort the whole tree walk.
533
665
  rec.check(`backend_error: ${(error as Error).message}`)
534
666
  rec.emit(null)
535
667
 
@@ -537,30 +669,12 @@ class WOFResolver implements Resolver {
537
669
  }
538
670
  }
539
671
 
540
- // Optional postcode-prefix prior when postcode lookup misses.
541
- if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
542
- const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country)
672
+ // A designated county span resolves as its region's county, and a missed postcode takes the prefix prior.
673
+ const recovered =
674
+ (await this.#countyDesignatorPick(node, placetype, query.country, candidates, parentResolved, state, rec)) ??
675
+ this.#postcodePrefixPick(node, placetype, query.country, candidates, state, rec)
543
676
 
544
- if (probe) {
545
- const metadata: Record<string, unknown> = {
546
- postcode_prefix: probe.prefix,
547
- postcode_prefix_ancestors: probe.node.ancestors,
548
- ...(probe.node.radiusP95Km != null ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
549
- ...(probe.node.lat != null && probe.node.lon != null ? { coordinate_source: "postcode_prefix" } : {}),
550
- }
551
-
552
- rec.check("postcode_prefix_prior")
553
- const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
554
-
555
- rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
556
-
557
- return {
558
- top: prefixPlace,
559
- alternatives: [],
560
- metadata,
561
- }
562
- }
563
- }
677
+ if (recovered) return recovered
564
678
 
565
679
  // Bare-toponym race: locality-tagged single spans also probe country/region.
566
680
  const isBareRace = placetype === "locality" && node === state.bareLocalityNode
@@ -596,23 +710,10 @@ class WOFResolver implements Resolver {
596
710
  let ranked = candidates
597
711
 
598
712
  if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
599
- const post = state.anchorPosterior
600
- const w = state.anchorWeight
601
-
602
- // Within-tier key uses prominence (fallback score) plus posterior boost.
603
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
604
- ranked = [...candidates].sort((a, b) => {
605
- const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
606
-
607
- if (tier !== 0) return tier
608
- // Unknown-country candidates get zero posterior mass.
609
- const aKey = (a.prominence ?? a.score) + w * (a.country ? (post[a.country] ?? 0) : 0)
610
- const bKey = (b.prominence ?? b.score) + w * (b.country ? (post[b.country] ?? 0) : 0)
611
-
612
- return bKey - aKey || b.score - a.score
613
- })
614
-
713
+ ranked = rankByAnchorPosterior(candidates, state.anchorPosterior, state.anchorWeight)
615
714
  rec.stage("anchor", ranked)
715
+ ranked = rankWithinPosteriorCountry(ranked, state.capitalLevel, node)
716
+ rec.stage("importance", ranked)
616
717
  }
617
718
 
618
719
  // Optional locale-country soft prior adds to candidate scores while retaining every candidate.
@@ -622,7 +723,7 @@ class WOFResolver implements Resolver {
622
723
  rec.stage("locale_prior", ranked)
623
724
  }
624
725
 
625
- // Importance-first rerank (skipped when anchor posterior exists).
726
+ // Importance-first rerank (the posterior branch above runs its own, within the winning country).
626
727
  if (!state.anchorPosterior) {
627
728
  ranked = rankByImportance(ranked)
628
729
  rec.stage("importance", ranked)
@@ -762,6 +863,54 @@ function containmentStamps(
762
863
  }
763
864
  }
764
865
 
866
+ /**
867
+ * Sorts candidates by the postcode country posterior, exact matches first.
868
+ *
869
+ * Within a match tier, the key is a candidate's prominence (its score when it has none)
870
+ * plus `weight` times its country's posterior mass.
871
+ * A candidate with no country gets no posterior mass.
872
+ */
873
+ function rankByAnchorPosterior<
874
+ T extends Pick<ResolvedPlace, "score" | "country"> & Partial<Pick<ResolvedPlace, "exactMatch" | "prominence">>,
875
+ >(candidates: readonly T[], posterior: Readonly<Record<string, number>>, weight: number): T[] {
876
+ const key = (c: T) => (c.prominence ?? c.score) + weight * (c.country ? (posterior[c.country] ?? 0) : 0)
877
+
878
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
879
+ return [...candidates].sort(
880
+ (a, b) => Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false) || key(b) - key(a) || b.score - a.score
881
+ )
882
+ }
883
+
884
+ /**
885
+ * Reorders the posterior-ranked leader's peers, the candidates in its country and exact-match
886
+ * tier, by importance and capital promotion, as the path without a posterior ranks them.
887
+ *
888
+ * The posterior decides the country.
889
+ * Within that country this order makes a venue query (`Clayton Post Office, Clayton, WI`)
890
+ * pick the same locality as its bare form (`Clayton, WI`).
891
+ */
892
+ function rankWithinPosteriorCountry<
893
+ T extends Pick<ResolvedPlace, "score" | "name" | "country" | "lat" | "lon"> &
894
+ Partial<Pick<ResolvedPlace, "exactMatch" | "importance" | "prominence">>,
895
+ >(
896
+ ranked: readonly T[],
897
+ capitalLevel: CapitalLevelFn | null | undefined,
898
+ node: { metadata?: Record<string, unknown> | null }
899
+ ): T[] {
900
+ const leader = ranked[0]
901
+
902
+ if (!leader?.country) return [...ranked]
903
+
904
+ const isPeer = (c: T) => c.country === leader.country && (c.exactMatch === true) === (leader.exactMatch === true)
905
+ let peers = rankByImportance(ranked.filter(isPeer))
906
+
907
+ if (capitalLevel) {
908
+ peers = promoteCapitalsWithReceipt(peers, capitalLevel, node)
909
+ }
910
+
911
+ return [...peers, ...ranked.filter((c) => !isPeer(c))]
912
+ }
913
+
765
914
  /**
766
915
  * Promote capitals and stamp `capital_promotion` when the leader changes.
767
916
  * Metadata only.
@@ -1,16 +1,16 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
1
4
  /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
+ * Recover a dropped or fragmented locality from the raw text when a parse fails to resolve,
6
+ * by matching contiguous raw-token spans against the same-country gazetteer.
5
7
  *
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.
8
+ * Default-on with an explicit `ResolveOpts.spanRescore: false` opt-out.
9
9
  */
10
10
 
11
11
  import { firstNodeWhere, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
12
12
  import type { ResolvedPlace, ResolverBackend, WeakResolutionReading } from "@mailwoman/core/resolver"
13
- import { isRegionAbbreviationToken } from "@mailwoman/query-shape/region-abbreviations"
13
+ import { isRegionAbbreviationToken } from "@mailwoman/recognizer/region-abbreviation"
14
14
  import { haversine } from "@mailwoman/spatial/geometries/point/distance"
15
15
 
16
16
  import { partitionByContainment } from "#admin/containment"
@@ -60,7 +60,7 @@ export interface SpanRescoreOptions {
60
60
  */
61
61
  postalCompoundRecovery?: boolean
62
62
  /**
63
- * Returns whether a word is a POI category, so a venue's last word is not re-read as a locality.
63
+ * Returns whether a word is a POI category, so a venue's last word isn't re-read as a locality.
64
64
  * A caller without the taxonomy leaves every span eligible.
65
65
  */
66
66
  isVenueCategoryWord?: (word: string) => boolean
@@ -77,14 +77,6 @@ export interface SpanRescoreOptions {
77
77
  * @defaultValue {@linkcode DEFAULT_COUNTRY_PRIOR_WEIGHT} (2), and 0 removes the locale's say entirely.
78
78
  */
79
79
  bareToponymCountryWeight?: number
80
- /**
81
- * Admit a proper sub-span only when every token it leaves behind is a subdivision code or a number.
82
- *
83
- * See `remainderIsContext` for the rule.
84
- *
85
- * @defaultValue `false`
86
- */
87
- spanRescoreRequireContextRemainder?: boolean
88
80
  }
89
81
 
90
82
  /**
@@ -116,6 +108,13 @@ export interface RescoreCandidate {
116
108
  * so the top-1-vs-top-2 dominance margin stays computable.
117
109
  */
118
110
  alternatives: ResolvedPlace[]
111
+ /**
112
+ * Whether the span is a proper sub-span that leaves a word of the name behind,
113
+ * as `Manchester` leaves `The` and `Art Gallery` in `The Manchester Art Gallery`.
114
+ *
115
+ * Such a span may scope a venue lookup, but it isn't by itself an answer to the input.
116
+ */
117
+ dropsName: boolean
119
118
  }
120
119
 
121
120
  interface RawTok {
@@ -158,7 +157,7 @@ export function postcodeCodeSubset(postcode: string): string {
158
157
  const BARE_TOPONYM_FETCH = 20
159
158
 
160
159
  /**
161
- * True when the tree names its own admin context — a region, subregion, country,
160
+ * True when the tree identifies its own admin context — a region, subregion, country,
162
161
  * postcode or house number the parser read out of the input — so the soft-country
163
162
  * prior stands down and the hard filter keeps its say.
164
163
  */
@@ -194,7 +193,7 @@ function resolvedWeakly(node: AddressNode, reading: WeakResolutionReading): bool
194
193
 
195
194
  /**
196
195
  * True if any node in the tree already has a resolved place id — the brake on span rescore.
197
- * with `weakReading`, a node whose resolution is weak under that reading does not hold it.
196
+ * with `weakReading`, a node whose resolution is weak under that reading doesn't hold it.
198
197
  */
199
198
  export function hasResolvedPlace(
200
199
  roots: readonly AddressNode[],
@@ -209,7 +208,7 @@ export function hasResolvedPlace(
209
208
  *
210
209
  * The whole span stays probeable.
211
210
  * Single-token spans are excluded.
212
- * The guard does not depend on confidence.
211
+ * The guard doesn't depend on confidence.
213
212
  */
214
213
  function multiTokenNameInteriors(roots: readonly AddressNode[], raw: string): Array<[number, number]> {
215
214
  const out: Array<[number, number]> = []
@@ -231,7 +230,7 @@ function multiTokenNameInteriors(roots: readonly AddressNode[], raw: string): Ar
231
230
  /**
232
231
  * The confident ranges split by what a span containing one means: `hard`
233
232
  * (house number, postcode, street body) refuses any overlap, while `affix` refuses
234
- * a span only when it does not strictly contain the affix.
233
+ * a span only when it doesn't strictly contain the affix.
235
234
  */
236
235
  interface ConfidentRanges {
237
236
  hard: Array<[number, number]>
@@ -240,7 +239,7 @@ interface ConfidentRanges {
240
239
 
241
240
  /**
242
241
  * The character ranges the parse read as street material, context only
243
- * when the range does not overlap the span under test.
242
+ * when the range doesn't overlap the span under test.
244
243
  */
245
244
  function streetRanges(roots: readonly AddressNode[]): Array<[number, number]> {
246
245
  const out: Array<[number, number]> = []
@@ -405,12 +404,22 @@ export async function findRescoreCandidate(
405
404
  /**
406
405
  * Whether every token a sub-span leaves behind is context rather than identity,
407
406
  * testing the remainder's shape rather than the span being proper.
407
+ *
408
+ * A span that's its own comma-separated segment states the location,
409
+ * as `Kalkaska` does in `Evergreen Cemetery, Kalkaska`.
410
+ * Otherwise each remaining token must be a subdivision code, a number,
411
+ * or part of a street the parse read beside the span.
408
412
  */
409
413
  const remainderIsContext = (span: { start: number; end: number }): boolean => {
410
414
  const outside = toks.filter((t) => t.end <= span.start || t.start >= span.end)
411
415
 
412
416
  if (!outside.length) return true
413
417
 
418
+ const before = raw.slice(0, span.start).trimEnd()
419
+ const after = raw.slice(span.end).trimStart()
420
+
421
+ if ((!before || before.endsWith(",")) && (!after || after.startsWith(","))) return true
422
+
414
423
  const streetContext = streets.filter(([start, end]) => end <= span.start || start >= span.end)
415
424
 
416
425
  return outside.every(
@@ -430,6 +439,11 @@ export async function findRescoreCandidate(
430
439
 
431
440
  const venueCoversInput = !!venue && !!wholeInput && venue.start <= wholeInput.start && wholeInput.end <= venue.end
432
441
 
442
+ // The first hit whose span drops a word of the name.
443
+ // A later span that keeps the name answers ahead of it, as `Kalkaska` does over
444
+ // `Evergreen` in `Evergreen Cemetery, Kalkaska`.
445
+ let nameDropping: RescoreCandidate | null = null
446
+
433
447
  for (const sp of spans) {
434
448
  const key = foldName(sp.text)
435
449
 
@@ -443,9 +457,9 @@ export async function findRescoreCandidate(
443
457
  // Another last word can state the location, as `London` in `Tower of London`.
444
458
  if (venue && sp.end === venue.end && sp.start > venue.start && opts.isVenueCategoryWord?.(sp.text)) continue
445
459
 
446
- // A sub-span that drops a word of the name is a corruption rather than a
447
- // recovery. see `remainderIsContext`.
448
- if (opts.spanRescoreRequireContextRemainder && !wholeSpan && !remainderIsContext(sp)) continue
460
+ const dropsName = !wholeSpan && !remainderIsContext(sp)
461
+
462
+ if (nameDropping && dropsName) continue
449
463
 
450
464
  const bare = softCountryEligible && wholeSpan
451
465
  const qualifier = wholeSpan ? null : qualifierRemainder(sp)
@@ -492,19 +506,26 @@ export async function findRescoreCandidate(
492
506
  const withinThreshold = (p: ResolvedPlace): boolean =>
493
507
  !anchor || thresholdKm <= 0 || haversine(anchor.lat, anchor.lon, p.lat, p.lon) <= thresholdKm
494
508
 
495
- for (const h of exact) {
496
- if (!withinThreshold(h)) continue
509
+ const h = exact.find(withinThreshold)
497
510
 
511
+ if (h) {
498
512
  // `postcodeVerified` is true only when an anchor existed and validated this match within
499
513
  // `thresholdKm`; otherwise the match is returned unrestricted but flagged lower-precision.
500
- return {
514
+ const candidate: RescoreCandidate = {
501
515
  text: sp.text,
502
516
  start: sp.start,
503
517
  end: sp.end,
504
518
  place: h,
505
519
  postcodeVerified: anchor !== null,
506
520
  alternatives: exact.filter((a) => a !== h && withinThreshold(a)),
521
+ dropsName,
507
522
  }
523
+
524
+ if (!dropsName) return candidate
525
+
526
+ nameDropping = candidate
527
+
528
+ continue
508
529
  }
509
530
 
510
531
  // A whole-input venue can be a sub-locality row, as `Golden Gate Park` is a neighborhood,
@@ -520,11 +541,14 @@ export async function findRescoreCandidate(
520
541
  place: sublocality,
521
542
  postcodeVerified: anchor !== null,
522
543
  alternatives: [],
544
+ dropsName,
523
545
  }
524
546
  }
525
547
  }
526
548
  }
527
549
 
550
+ if (nameDropping) return nameDropping
551
+
528
552
  // Joint country recovery: when the scoped pass finds no match and a postcode
529
553
  // is present, re-probe unscoped and accept a cross-country promotion only
530
554
  // when its code subset resolves postcode-verified within the radius.
@@ -556,7 +580,16 @@ export async function findRescoreCandidate(
556
580
  // Admission uses per-candidate postcode verification.
557
581
  // The postcode already picked the country, so this pass has no remaining
558
582
  // country ambiguity to report.
559
- return { text: sp.text, start: sp.start, end: sp.end, place: h, postcodeVerified: true, alternatives: [] }
583
+ // The postcode verified the place, so the span answers even when it drops a word of the name.
584
+ return {
585
+ text: sp.text,
586
+ start: sp.start,
587
+ end: sp.end,
588
+ place: h,
589
+ postcodeVerified: true,
590
+ alternatives: [],
591
+ dropsName: false,
592
+ }
560
593
  }
561
594
  }
562
595
  }
@@ -1,8 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import type { Exclusion } from "@mailwoman/evidence"
8
5
 
@@ -1,8 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import { isFrenchStreetWord } from "@mailwoman/codex/fr"
8
5
  import { isStreetDirectionalToken } from "@mailwoman/codex/us"
@@ -127,12 +124,12 @@ function firstOfTag(roots: readonly AddressNode[], tag: AddressNode["tag"]): Add
127
124
  * because the ancestor key also matches the same street and number in the ancestor's other parts.
128
125
  * A locality without a bounding box gets no retry.
129
126
  */
130
- export function applyAddressPoint(
127
+ export async function applyAddressPoint(
131
128
  roots: AddressNode[],
132
129
  lookup: AddressPointLookup,
133
130
  bboxFallback?: boolean,
134
131
  ancestorsOf?: (id: number | string) => Ancestor[]
135
- ): void {
132
+ ): Promise<void> {
136
133
  const pairs = streetNumberPairs(roots)
137
134
  const directionalUnit = [...walkNodes(roots)].find((n) => n.tag === "unit" && isDirectionalUnit(n.value))
138
135
  const localityNode = firstOfTag(roots, "locality")
@@ -177,10 +174,10 @@ export function applyAddressPoint(
177
174
 
178
175
  let street: AddressNode | null = null
179
176
  let houseNumber: AddressNode | null = null
180
- let hit: ReturnType<AddressPointLookup["find"]> | null = null
177
+ let hit: Awaited<ReturnType<AddressPointLookup["find"]>> = null
181
178
 
182
179
  for (const pair of pairs) {
183
- hit = lookup.find({
180
+ hit = await lookup.find({
184
181
  street: assembleStreetValue(pair.street, directionalUnit),
185
182
  number: pair.houseNumber.value,
186
183
  postcode: postcode ?? null,
@@ -204,7 +201,7 @@ export function applyAddressPoint(
204
201
  if (!hit && locality && extent) {
205
202
  retry: for (const name of ancestorLocalityNames(localityNode, ancestorsOf)) {
206
203
  for (const pair of pairs) {
207
- const candidate = lookup.find({
204
+ const candidate = await lookup.find({
208
205
  street: assembleStreetValue(pair.street, directionalUnit),
209
206
  number: pair.houseNumber.value,
210
207
  postcode: postcode ?? null,
@@ -247,14 +244,14 @@ export function applyAddressPoint(
247
244
 
248
245
  /**
249
246
  * Stamps the street with an interpolated house-number coordinate when the
250
- * address-point tier did not already place it.
247
+ * address-point tier didn't already place it.
251
248
  *
252
249
  * It writes `interpolated_point` rather than `address_point`, so an estimate
253
250
  * never overwrites a real situs point.
254
251
  *
255
252
  * A query without a postcode is scoped only by its locality, so its estimate must lie inside the resolved
256
253
  * locality's bounding box, and an estimate outside it is refused as a namesake street elsewhere.
257
- * A postcode-scoped estimate is not checked, because a mailing city's postcode
254
+ * A postcode-scoped estimate isn't checked, because a mailing city's postcode
258
255
  * can reach past the WOF place's extent.
259
256
  */
260
257
  export function applyInterpolation(
package/lib/street.ts CHANGED
@@ -1,8 +1,5 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  export * from "#street/evidence"
8
5
  export * from "#street/tier"