@mailwoman/resolver 10.7.0 → 10.8.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 (47) hide show
  1. package/lib/admin/coherence-passes.ts +2 -2
  2. package/lib/admin/winner.ts +24 -4
  3. package/lib/bare-toponym-race.ts +1 -1
  4. package/lib/decorate-node.ts +6 -1
  5. package/lib/index.ts +1 -0
  6. package/lib/postcode/country-coherence.ts +4 -4
  7. package/lib/postcode/shape-coherence.ts +40 -51
  8. package/lib/resolve/passes.ts +15 -8
  9. package/lib/resolve.ts +79 -14
  10. package/lib/span-rescore.ts +3 -3
  11. package/lib/street/tier.ts +98 -7
  12. package/out/admin/coherence-passes.js +2 -2
  13. package/out/admin/coherence-passes.js.map +1 -1
  14. package/out/admin/winner.d.ts +10 -2
  15. package/out/admin/winner.d.ts.map +1 -1
  16. package/out/admin/winner.js +18 -2
  17. package/out/admin/winner.js.map +1 -1
  18. package/out/bare-toponym-race.js +1 -1
  19. package/out/bare-toponym-race.js.map +1 -1
  20. package/out/decorate-node.d.ts.map +1 -1
  21. package/out/decorate-node.js +4 -1
  22. package/out/decorate-node.js.map +1 -1
  23. package/out/index.d.ts +1 -1
  24. package/out/index.d.ts.map +1 -1
  25. package/out/index.js +1 -1
  26. package/out/index.js.map +1 -1
  27. package/out/postcode/country-coherence.d.ts.map +1 -1
  28. package/out/postcode/country-coherence.js +4 -4
  29. package/out/postcode/country-coherence.js.map +1 -1
  30. package/out/postcode/shape-coherence.d.ts +12 -16
  31. package/out/postcode/shape-coherence.d.ts.map +1 -1
  32. package/out/postcode/shape-coherence.js +31 -40
  33. package/out/postcode/shape-coherence.js.map +1 -1
  34. package/out/resolve/passes.d.ts +7 -1
  35. package/out/resolve/passes.d.ts.map +1 -1
  36. package/out/resolve/passes.js +6 -6
  37. package/out/resolve/passes.js.map +1 -1
  38. package/out/resolve.d.ts.map +1 -1
  39. package/out/resolve.js +56 -13
  40. package/out/resolve.js.map +1 -1
  41. package/out/span-rescore.js +3 -3
  42. package/out/span-rescore.js.map +1 -1
  43. package/out/street/tier.d.ts +13 -2
  44. package/out/street/tier.d.ts.map +1 -1
  45. package/out/street/tier.js +77 -6
  46. package/out/street/tier.js.map +1 -1
  47. package/package.json +9 -7
@@ -196,8 +196,8 @@ function revertResolverDecoration(node: AddressNode): void {
196
196
  const meta = { ...node.metadata }
197
197
  const priorSource = meta["classifier_source"]
198
198
  const priorSourceID = meta["classifier_source_id"]
199
- node.source = typeof priorSource === "string" ? priorSource : undefined
200
- node.sourceID = typeof priorSourceID === "string" ? priorSourceID : undefined
199
+ node.source = typeof priorSource === "string" ? priorSource : null
200
+ node.sourceID = typeof priorSourceID === "string" ? priorSourceID : null
201
201
 
202
202
  for (const key of [
203
203
  "classifier_source",
@@ -8,9 +8,9 @@
8
8
  * `PLACETYPE_SPECIFICITY` cannot express that split.
9
9
  */
10
10
 
11
- import { areaPostcodeLeadsLocality, isUnitGradePostcodeHit } from "@mailwoman/codex"
12
11
  import type { AddressNode } from "@mailwoman/core/decoder"
13
- import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
12
+ import { PLACETYPE_SPECIFICITY } from "@mailwoman/gazetteer/whosonfirst/placetypes/specificity"
13
+ import { areaPostcodeLeadsLocality, isUnitGradePostcodeHit } from "@mailwoman/postcode/systems"
14
14
 
15
15
  /**
16
16
  * The admin fallback order when the postcode leads, with the JP rungs beside their
@@ -44,6 +44,26 @@ export const ADMIN_LADDER_LOCALITY_FIRST: ReadonlyArray<string> = [
44
44
  "country",
45
45
  ]
46
46
 
47
+ /**
48
+ * The ladder with `dependent_locality` moved ahead of `locality`, for a tree whose
49
+ * dependent locality the resolver placed inside its parent (#2804).
50
+ *
51
+ * The postcode rung keeps its place, so a unit-grade postcode still answers first.
52
+ * A ladder without both rungs is returned as it is.
53
+ */
54
+ export function ladderWithContainedDependentLocality(ladder: ReadonlyArray<string>): ReadonlyArray<string> {
55
+ const dependent = ladder.indexOf("dependent_locality")
56
+ const locality = ladder.indexOf("locality")
57
+
58
+ if (dependent === -1 || locality === -1 || dependent < locality) return ladder
59
+
60
+ const moved = ladder.filter((rung) => rung !== "dependent_locality")
61
+
62
+ moved.splice(moved.indexOf("locality"), 0, "dependent_locality")
63
+
64
+ return moved
65
+ }
66
+
47
67
  /**
48
68
  * The resolved postcode a ladder decision reads.
49
69
  *
@@ -60,7 +80,7 @@ export interface ResolvedPostcodeHit {
60
80
  * It is absent when the postcode did not resolve to a country.
61
81
  * The ladder then defaults to locality-first.
62
82
  */
63
- country?: string
83
+ country?: string | null
64
84
  }
65
85
 
66
86
  /**
@@ -108,7 +128,7 @@ export interface ResolvedSpecificityInput {
108
128
  /**
109
129
  * ISO-3166 alpha-2 the resolver placed this candidate in, read only for a `postalcode`.
110
130
  */
111
- country?: string
131
+ country?: string | null
112
132
  /**
113
133
  * The parsed span.
114
134
  * Absent for a non-postcode candidate.
@@ -15,7 +15,7 @@ import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
15
15
  import type { AddressNode, AddressTree } from "@mailwoman/core/decoder"
16
16
  import { loneValueNode } from "@mailwoman/core/decoder"
17
17
  import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
18
- import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
18
+ import { PLACETYPE_SPECIFICITY } from "@mailwoman/gazetteer/whosonfirst/placetypes/specificity"
19
19
 
20
20
  /**
21
21
  * The tree's single value-containing node when it is locality-tagged, else null.
@@ -16,7 +16,12 @@ import type { CoordinateOptionalPlace } from "#postcode/prefix"
16
16
  * A resolved node has a real coordinate (placeID set + non-zero lat/lon).
17
17
  */
18
18
  export function isResolvedWithCoord(n: AddressNode): boolean {
19
- return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0))
19
+ return (
20
+ typeof n.placeID === "string" &&
21
+ typeof n.lat === "number" &&
22
+ typeof n.lon === "number" &&
23
+ (n.lat !== 0 || n.lon !== 0)
24
+ )
20
25
  }
21
26
 
22
27
  /**
package/lib/index.ts CHANGED
@@ -53,6 +53,7 @@ export {
53
53
  adminLadderFor,
54
54
  adminLadderForNodes,
55
55
  AREA_GRADE_POSTALCODE_SPECIFICITY,
56
+ ladderWithContainedDependentLocality,
56
57
  mostSpecificResolved,
57
58
  resolvedSpecificity,
58
59
  } from "#admin/winner"
@@ -4,10 +4,10 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
6
 
7
- import { candidateSystemsForPostcode } from "@mailwoman/codex"
8
7
  import { firstNodeWhere, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
9
8
  import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
10
- import { haversineKm } from "@mailwoman/spatial"
9
+ import { candidateSystemsForPostcode } from "@mailwoman/postcode/systems"
10
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
11
11
 
12
12
  /**
13
13
  * The default maximum distance, in kilometers, between a postcode and a locality
@@ -225,7 +225,7 @@ async function coherenceIn(
225
225
 
226
226
  for (const candidate of localityHits) {
227
227
  if (!candidate.exactMatch || !hasCoord(candidate)) continue
228
- const distanceKm = haversineKm(postcodePlace.lat, postcodePlace.lon, candidate.lat, candidate.lon)
228
+ const distanceKm = haversine(postcodePlace.lat, postcodePlace.lon, candidate.lat, candidate.lon)
229
229
 
230
230
  if (distanceKm > thresholdKm) continue
231
231
 
@@ -324,7 +324,7 @@ export async function findPostcodeCountryScope(
324
324
 
325
325
  const contradicted =
326
326
  ownPostcode != null &&
327
- haversineKm(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > thresholdKm
327
+ haversine(ownPostcode.lat, ownPostcode.lon, localityPlace.lat, localityPlace.lon) > thresholdKm
328
328
 
329
329
  if (country !== defaultCountry && !contradicted && !verdicts.has(country)) {
330
330
  verdicts.set(country, {
@@ -4,43 +4,49 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
6
 
7
- import { candidateSystemsForPostcode, SYSTEM_CODES } from "@mailwoman/codex"
8
- import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
9
- import { isUSStateAbbreviation } from "@mailwoman/codex/us"
10
- import { collectNodes, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
7
+ import { matchCountry, matchSubdivision, matchSubdivisionsAnywhere } from "@mailwoman/codex/country"
8
+ import { collectNodes, POSTCODE_SHAPE_EXCLUDED_KEY, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
9
+ import { acceptPostcode, postcodeSyntax } from "@mailwoman/postcode/country-formats"
11
10
 
12
- const SYSTEM_UNIVERSE: ReadonlySet<string> = new Set<string>(SYSTEM_CODES.map((system) => system.toUpperCase()))
11
+ /**
12
+ * Whether libaddressinput states a postcode syntax for `country`, so a span can be checked against it.
13
+ */
14
+ function statesSyntax(country: string): boolean {
15
+ return postcodeSyntax(country) != null
16
+ }
13
17
 
14
18
  /**
15
19
  * Records which postcode spans {@link applyPostcodeShapeCoherence} confirmed, excluded, or abstained on.
16
20
  *
17
- * It also records the postcode systems of the first confirmed span.
21
+ * It also records the countries whose syntax the first confirmed span has.
18
22
  */
19
23
  export interface PostcodeShapeVerdict {
20
24
  /**
21
- * The upper-case postcode systems of the first confirmed span, passed to
22
- * `findPostcodeCountryScope` as its candidate systems; `null` when no span was confirmed.
25
+ * The upper-case countries whose postcode syntax the first confirmed span has.
26
+ *
27
+ * `findPostcodeCountryScope` takes them as its candidates.
28
+ * The value is `null` when no span was confirmed.
23
29
  */
24
30
  narrowing: string[] | null
25
31
 
26
32
  /**
27
- * Postcode values whose shape fits a system used by a sibling country or region span.
33
+ * Postcode values that have the postcode syntax of a country a sibling country or region span names.
28
34
  */
29
35
  confirmed: string[]
30
36
 
31
37
  /**
32
- * Postcode values whose shape fits none of the systems the siblings name.
38
+ * Postcode values that have the postcode syntax of no country the siblings name.
33
39
  */
34
40
  excluded: string[]
35
41
 
36
42
  /**
37
- * Postcode values left undecided because they match no known postcode shape
38
- * or the tree names no country or region.
43
+ * Postcode values left undecided because the tree names no country
44
+ * or region with a stated postcode syntax.
39
45
  */
40
46
  abstained: string[]
41
47
  }
42
48
 
43
- function collectSiblingSystems(roots: readonly AddressNode[]): Set<string> {
49
+ function collectSiblingCountries(roots: readonly AddressNode[]): Set<string> {
44
50
  const out = new Set<string>()
45
51
 
46
52
  for (const n of walkNodes(roots)) {
@@ -51,32 +57,34 @@ function collectSiblingSystems(roots: readonly AddressNode[]): Set<string> {
51
57
  // A constituent country such as `England` tagged `country` still fixes its sovereign state.
52
58
  const sub = matchSubdivision(n.value)
53
59
 
54
- if (sub && SYSTEM_UNIVERSE.has(sub.country.toUpperCase())) {
60
+ if (sub && statesSyntax(sub.country)) {
55
61
  out.add(sub.country.toUpperCase())
56
62
  }
57
63
 
58
64
  continue
59
65
  }
60
66
 
61
- const system = isUSStateAbbreviation(matched.iso2) ? "US" : matched.iso2.toUpperCase()
67
+ // The match's ISO code is the country, even where it spells a US state abbreviation (`IN`, `DE`, `CA`).
68
+ const country = matched.iso2.toUpperCase()
62
69
 
63
- if (SYSTEM_UNIVERSE.has(system)) {
64
- out.add(system)
70
+ if (statesSyntax(country)) {
71
+ out.add(country)
65
72
  }
66
73
 
67
74
  continue
68
75
  }
69
76
 
70
77
  if (n.tag === "region") {
71
- const sub = matchSubdivision(n.value)
72
-
73
- if (sub && SYSTEM_UNIVERSE.has(sub.country.toUpperCase())) {
74
- out.add(sub.country.toUpperCase())
78
+ // An abbreviation such as `WA` names a subdivision in more than one country, and each is a candidate.
79
+ for (const sub of matchSubdivisionsAnywhere(n.value)) {
80
+ if (statesSyntax(sub.country)) {
81
+ out.add(sub.country.toUpperCase())
82
+ }
75
83
  }
76
84
 
77
85
  const hint = n.metadata?.["country_hint"]
78
86
 
79
- if (typeof hint === "string" && SYSTEM_UNIVERSE.has(hint.toUpperCase())) {
87
+ if (typeof hint === "string" && statesSyntax(hint)) {
80
88
  out.add(hint.toUpperCase())
81
89
  }
82
90
  }
@@ -86,11 +94,11 @@ function collectSiblingSystems(roots: readonly AddressNode[]): Set<string> {
86
94
  }
87
95
 
88
96
  /**
89
- * Checks each postcode span's shape against the postcode systems of the countries
97
+ * Checks each postcode span against the libaddressinput postcode syntax of the countries
90
98
  * and regions listed in the same tree, without querying a backend.
91
99
  *
92
- * A span that fits none of those systems is excluded: an all-digit span is retagged
93
- * `house_number`, and any other span is stamped `postcode_shape_excluded`.
100
+ * A span that has none of those syntaxes is excluded: it keeps its tag and text and is stamped
101
+ * `postcode_shape_excluded`, which takes it out of the result slots (`isShapeExcludedPostcode`).
94
102
  */
95
103
  export function applyPostcodeShapeCoherence(roots: readonly AddressNode[]): PostcodeShapeVerdict {
96
104
  const verdict: PostcodeShapeVerdict = { narrowing: null, confirmed: [], excluded: [], abstained: [] }
@@ -99,24 +107,16 @@ export function applyPostcodeShapeCoherence(roots: readonly AddressNode[]): Post
99
107
 
100
108
  if (!postcodes.length) return verdict
101
109
 
102
- const siblingSystems = collectSiblingSystems(roots)
110
+ const siblingCountries = collectSiblingCountries(roots)
103
111
 
104
112
  for (const node of postcodes) {
105
113
  const code = node.value.trim()
106
- const systems = candidateSystemsForPostcode(code)
107
-
108
- if (!systems.length) {
109
- verdict.abstained.push(code)
110
-
111
- continue
112
- }
113
-
114
- const intersection = systems.map((system) => system.toUpperCase()).filter((system) => siblingSystems.has(system))
114
+ const intersection = [...siblingCountries].filter((country) => acceptPostcode(code, country) != null)
115
115
 
116
116
  if (intersection.length) {
117
117
  verdict.confirmed.push(code)
118
118
 
119
- node.metadata = { ...node.metadata, postcode_shape_systems: intersection }
119
+ node.metadata = { ...node.metadata, postcode_shape_countries: intersection }
120
120
 
121
121
  if (!verdict.narrowing) {
122
122
  verdict.narrowing = intersection
@@ -125,14 +125,12 @@ export function applyPostcodeShapeCoherence(roots: readonly AddressNode[]): Post
125
125
  continue
126
126
  }
127
127
 
128
- if (siblingSystems.size) {
128
+ if (siblingCountries.size) {
129
129
  verdict.excluded.push(code)
130
130
 
131
- if (/^\d+$/.test(code)) {
132
- node.tag = "house_number"
133
- } else {
134
- node.metadata = { ...node.metadata, postcode_shape_excluded: true }
135
- }
131
+ // The span keeps its tag and text, and the stamp takes it out of the result slots.
132
+ // A retag to `house_number` would overwrite the house number the parse already found.
133
+ node.metadata = { ...node.metadata, [POSTCODE_SHAPE_EXCLUDED_KEY]: true }
136
134
 
137
135
  continue
138
136
  }
@@ -142,12 +140,3 @@ export function applyPostcodeShapeCoherence(roots: readonly AddressNode[]): Post
142
140
 
143
141
  return verdict
144
142
  }
145
-
146
- /**
147
- * Returns true for a postcode span excluded by shape coherence when it could not be retagged.
148
- *
149
- * Every postcode consumer in the resolver must skip that span.
150
- */
151
- export function isShapeExcludedPostcode(node: AddressNode): boolean {
152
- return node.tag === "postcode" && node.metadata?.["postcode_shape_excluded"] === true
153
- }
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
8
- import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
8
+ import { isShapeExcludedPostcode, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
9
9
  import {
10
10
  type CoincidentLocality,
11
11
  type DefaultCountry,
@@ -20,12 +20,11 @@ import {
20
20
  type ResolverBackend,
21
21
  type ResolveSwitches,
22
22
  } from "@mailwoman/core/resolver"
23
- import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
24
- import { haversineKm } from "@mailwoman/spatial"
23
+ import { PLACETYPE_SPECIFICITY } from "@mailwoman/gazetteer/whosonfirst/placetypes/specificity"
24
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
25
25
 
26
26
  import { decorateNode, isResolvedWithCoord } from "#decorate-node"
27
27
  import type { CoordinateOptionalPlace } from "#postcode/prefix"
28
- import { isShapeExcludedPostcode } from "#postcode/shape-coherence"
29
28
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "#span-rescore"
30
29
 
31
30
  const TRACE_CANDIDATE_CAP = 10
@@ -62,6 +61,7 @@ export interface NodeTraceRecorder {
62
61
  query: {
63
62
  country?: string
64
63
  parentID?: string | number
64
+ parentQualifierID?: number
65
65
  postcode?: string | null
66
66
  regionQualifier?: string | null
67
67
  limit?: number
@@ -156,6 +156,7 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
156
156
  query: {
157
157
  country: ctx.query.country || null,
158
158
  parentID: ctx.query.parentID ?? null,
159
+ parentQualifierID: ctx.query.parentQualifierID ?? null,
159
160
  postcode: ctx.query.postcode || null,
160
161
  regionQualifier: ctx.query.regionQualifier || null,
161
162
  limit: ctx.query.limit ?? ctx.defaultLimit,
@@ -262,7 +263,7 @@ export interface ResolutionState {
262
263
  * The callback that receives one trace record per lookup.
263
264
  * The walk records no events when it is absent.
264
265
  */
265
- traceSink?: (record: ResolveNodeTrace) => void
266
+ traceSink?: ((record: ResolveNodeTrace) => void) | null
266
267
 
267
268
  /**
268
269
  * Whether an empty lookup re-probes the other admin bands and traces which ones hold the value.
@@ -311,6 +312,12 @@ export interface ResolutionState {
311
312
  */
312
313
  adminContainmentRerank: boolean
313
314
 
315
+ /**
316
+ * Whether a `dependent_locality` node's lookup passes its resolved parent as a containment
317
+ * qualifier and a contained pick is stamped to answer ahead of the locality.
318
+ */
319
+ dependentLocalityContainment: boolean
320
+
314
321
  /**
315
322
  * The tree's first region value.
316
323
  *
@@ -444,7 +451,7 @@ async function recoverPostcodeNode(
444
451
  roots: AddressNode[],
445
452
  backend: ResolverBackend,
446
453
  country: string | null,
447
- traceSink?: (record: ResolveNodeTrace) => void
454
+ traceSink?: ((record: ResolveNodeTrace) => void) | null
448
455
  ): Promise<void> {
449
456
  for (const n of walkNodes(roots)) {
450
457
  if (n.tag === "postcode" && !n.placeID && n.value.trim()) {
@@ -504,7 +511,7 @@ async function reconcileLocalitiesToAnchor(
504
511
  const nearest = (places: readonly ResolvedPlace[]) =>
505
512
  places
506
513
  .filter((a) => a.lat !== 0 || a.lon !== 0)
507
- .map((a) => ({ a, d: haversineKm(anchor.lat, anchor.lon, a.lat, a.lon) }))
514
+ .map((a) => ({ a, d: haversine(anchor.lat, anchor.lon, a.lat, a.lon) }))
508
515
  .filter((x) => x.d <= thresholdKm)
509
516
  // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
510
517
  .sort((x, y) => x.d - y.d)[0]
@@ -512,7 +519,7 @@ async function reconcileLocalitiesToAnchor(
512
519
  for (const node of walkNodes(roots)) {
513
520
  if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node)) continue
514
521
 
515
- const gapKm = haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!)
522
+ const gapKm = haversine(anchor.lat, anchor.lon, node.lat!, node.lon!)
516
523
 
517
524
  if (gapKm <= thresholdKm) continue
518
525
 
package/lib/resolve.ts CHANGED
@@ -10,7 +10,13 @@
10
10
  import type { ComponentTag } from "@mailwoman/codex/component"
11
11
  import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
12
12
  import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/placetype-map"
13
- import { collectNodes, type AddressNode, type AddressTree, type Interpretation } from "@mailwoman/core/decoder"
13
+ import {
14
+ collectNodes,
15
+ isShapeExcludedPostcode,
16
+ type AddressNode,
17
+ type AddressTree,
18
+ type Interpretation,
19
+ } from "@mailwoman/core/decoder"
14
20
  import {
15
21
  type BackendCapabilityGap,
16
22
  type DefaultCountry,
@@ -19,9 +25,9 @@ import {
19
25
  type ResolveOpts,
20
26
  type Resolver,
21
27
  type ResolverBackend,
22
- countriesFromPostcodeFormat,
23
28
  resolveSwitches,
24
29
  } from "@mailwoman/core/resolver"
30
+ import { countriesFromPostcodeFormat } from "@mailwoman/postcode/postcode-format"
25
31
 
26
32
  import {
27
33
  applyAdminCoherence,
@@ -47,7 +53,7 @@ import {
47
53
  stampPostcodeCountryScope,
48
54
  } from "#postcode/country-coherence"
49
55
  import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "#postcode/prefix"
50
- import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "#postcode/shape-coherence"
56
+ import { applyPostcodeShapeCoherence } from "#postcode/shape-coherence"
51
57
  import {
52
58
  applyPostcodeConsistency,
53
59
  applyRooftopConsistency,
@@ -180,6 +186,7 @@ class WOFResolver implements Resolver {
180
186
  includeAncestors: opts.includeAncestors,
181
187
  // Optional admin containment rerank uses a pre-scanned region qualifier.
182
188
  adminContainmentRerank: opts.adminContainmentRerank,
189
+ dependentLocalityContainment: opts.dependentLocalityContainment,
183
190
  regionQualifier: firstRegionQualifier(tree.roots),
184
191
  ...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
185
192
  localityNodePresent: false,
@@ -264,9 +271,13 @@ class WOFResolver implements Resolver {
264
271
  await applyPostcodeConsistency(newRoots, consistencyThresholdKm, opts.postcodeConsistencyMaxMoveKm)
265
272
  }
266
273
 
274
+ // A register can key a borough's or neighborhood's addresses to an ancestor's name,
275
+ // so a miss retries the ancestors.
276
+ const ancestorsOf = this.#backend.ancestors?.bind(this.#backend)
277
+
267
278
  // Optional exact address-point tier.
268
279
  if (opts.addressPoints) {
269
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
280
+ applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
270
281
  }
271
282
 
272
283
  // Optional interpolation tier after exact points.
@@ -282,7 +293,7 @@ class WOFResolver implements Resolver {
282
293
 
283
294
  // Retry exact address-point tier once after span-rescore recovery.
284
295
  if (opts.addressPoints) {
285
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
296
+ applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
286
297
  }
287
298
 
288
299
  // A rooftop row keyed by locality name can lie in a namesake of the selected locality.
@@ -412,7 +423,12 @@ class WOFResolver implements Resolver {
412
423
  if (band === probed) continue
413
424
 
414
425
  try {
415
- const hits = await this.#backend.findPlace({ ...query, placetype: band, parentID: undefined })
426
+ const hits = await this.#backend.findPlace({
427
+ ...query,
428
+ placetype: band,
429
+ parentID: undefined,
430
+ parentQualifierID: undefined,
431
+ })
416
432
 
417
433
  if (hits.length) {
418
434
  found.push({ placetype: band, n: hits.length })
@@ -449,10 +465,7 @@ class WOFResolver implements Resolver {
449
465
  query.bias = state.bias
450
466
  }
451
467
 
452
- // Apply resolved parent scope when available.
453
- if (parentResolved && typeof parentResolved.id === "number") {
454
- query.parentID = parentResolved.id
455
- }
468
+ const parentContainment = applyParentScope(query, node, parentResolved, state)
456
469
 
457
470
  // Country scope precedence: parent -> default -> node hint -> hard country.
458
471
  const countryHint = node.metadata?.["country_hint"]
@@ -463,7 +476,7 @@ class WOFResolver implements Resolver {
463
476
  const country =
464
477
  parentResolved?.country ??
465
478
  defaultCountryForLookup ??
466
- (typeof countryHint === "string" ? countryHint : undefined) ??
479
+ (typeof countryHint === "string" ? countryHint : null) ??
467
480
  state.hardCountry
468
481
 
469
482
  if (country) {
@@ -659,7 +672,9 @@ class WOFResolver implements Resolver {
659
672
 
660
673
  // Final containment partition.
661
674
  // It reads the address's own qualifier and preserves the exact-match tier.
662
- if (containmentEligible) {
675
+ const qualifierPartition = containmentEligible || parentContainment
676
+
677
+ if (qualifierPartition) {
663
678
  ranked = partitionByContainment(
664
679
  ranked,
665
680
  (c) => c.containedByQualifier === true,
@@ -716,7 +731,7 @@ class WOFResolver implements Resolver {
716
731
 
717
732
  // Trace receipts for mechanism-level observability.
718
733
  const pickMetadata = {
719
- ...(containmentEligible ? { admin_containment: adminContainmentVerdict(ranked) } : {}),
734
+ ...containmentStamps(qualifierPartition, parentContainment, ranked, top),
720
735
  ...(top.variantAliasExempted === true ? { variant_alias_exemption: true } : {}),
721
736
  // Mark picks admitted outside resolved parent scope.
722
737
  ...((parentResolved && typeof parentResolved.id === "number" && query.parentID == null) ||
@@ -733,6 +748,56 @@ class WOFResolver implements Resolver {
733
748
  }
734
749
  }
735
750
 
751
+ /**
752
+ * Scopes a lookup to its resolved parent and reports whether the parent is a containment qualifier.
753
+ *
754
+ * A parent is a `parentID` region scope.
755
+ * A `dependent_locality` node under the `dependentLocalityContainment` switch passes
756
+ * its parent as `parentQualifierID` instead (#2804).
757
+ *
758
+ * The candidate table's region scope holds region ids, so a locality parent never satisfies it.
759
+ *
760
+ * The containment partition admits the sub-locality rows the locality band excludes.
761
+ */
762
+ function applyParentScope(
763
+ query: Parameters<ResolverBackend["findPlace"]>[0],
764
+ node: AddressNode,
765
+ parentResolved: CoordinateOptionalPlace | null,
766
+ state: ResolutionState
767
+ ): boolean {
768
+ if (!parentResolved || typeof parentResolved.id !== "number") return false
769
+
770
+ if (state.dependentLocalityContainment && node.tag === "dependent_locality") {
771
+ query.parentQualifierID = parentResolved.id
772
+
773
+ return true
774
+ }
775
+
776
+ query.parentID = parentResolved.id
777
+
778
+ return false
779
+ }
780
+
781
+ /**
782
+ * The pick metadata a containment partition writes: the tri-state verdict when a qualifier was
783
+ * read, and `contained_by_parent` when a dependent locality's pick sits inside its parent.
784
+ *
785
+ * The geocode result's admin ladder reads the second stamp to let the pick answer ahead of the locality.
786
+ */
787
+ function containmentStamps(
788
+ qualifierPartition: boolean,
789
+ parentContainment: boolean,
790
+ ranked: readonly ResolvedPlace[],
791
+ top: ResolvedPlace
792
+ ): Record<string, unknown> {
793
+ if (!qualifierPartition) return {}
794
+
795
+ return {
796
+ admin_containment: adminContainmentVerdict(ranked),
797
+ ...(parentContainment && top.containedByQualifier === true ? { contained_by_parent: true } : {}),
798
+ }
799
+ }
800
+
736
801
  /**
737
802
  * Promote capitals and stamp `capital_promotion` when the leader changes.
738
803
  * Metadata only.
@@ -740,7 +805,7 @@ class WOFResolver implements Resolver {
740
805
  function promoteCapitalsWithReceipt<
741
806
  T extends Pick<ResolvedPlace, "score" | "name" | "country" | "lat" | "lon"> &
742
807
  Partial<Pick<ResolvedPlace, "exactMatch" | "importance" | "prominence">>,
743
- >(ranked: readonly T[], level: CapitalLevelFn, node: { metadata?: Record<string, unknown> }): T[] {
808
+ >(ranked: readonly T[], level: CapitalLevelFn, node: { metadata?: Record<string, unknown> | null }): T[] {
744
809
  const promoted = promoteCapitals(ranked, level)
745
810
 
746
811
  if (promoted[0] !== ranked[0]) {
@@ -11,7 +11,7 @@
11
11
  import { firstNodeWhere, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
12
12
  import type { ResolvedPlace, ResolverBackend, WeakResolutionReading } from "@mailwoman/core/resolver"
13
13
  import { isRegionAbbreviationToken } from "@mailwoman/query-shape/region-abbreviations"
14
- import { haversineKm } from "@mailwoman/spatial"
14
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
15
15
 
16
16
  import { partitionByContainment } from "#admin/containment"
17
17
  import { foldName } from "#fold-name"
@@ -476,7 +476,7 @@ export async function findRescoreCandidate(
476
476
  : ranked
477
477
 
478
478
  const withinThreshold = (p: ResolvedPlace): boolean =>
479
- !anchor || thresholdKm <= 0 || haversineKm(anchor.lat, anchor.lon, p.lat, p.lon) <= thresholdKm
479
+ !anchor || thresholdKm <= 0 || haversine(anchor.lat, anchor.lon, p.lat, p.lon) <= thresholdKm
480
480
 
481
481
  for (const h of exact) {
482
482
  if (!withinThreshold(h)) continue
@@ -521,7 +521,7 @@ export async function findRescoreCandidate(
521
521
 
522
522
  const verified = pcHits.find((p) => p.lat !== 0 || p.lon !== 0)
523
523
 
524
- if (verified && haversineKm(verified.lat, verified.lon, h.lat, h.lon) <= thresholdKm) {
524
+ if (verified && haversine(verified.lat, verified.lon, h.lat, h.lon) <= thresholdKm) {
525
525
  // Admission uses per-candidate postcode verification.
526
526
  // The postcode already picked the country, so this pass has no remaining
527
527
  // country ambiguity to report.