@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.
Files changed (69) hide show
  1. package/README.md +1 -1
  2. package/lib/admin/coherence-passes.ts +1 -1
  3. package/lib/admin/county-designator.ts +91 -0
  4. package/lib/admin/former-division.ts +116 -0
  5. package/lib/bare-toponym-race.ts +1 -1
  6. package/lib/decorate-node.ts +103 -2
  7. package/lib/postcode/prefix.ts +7 -16
  8. package/lib/postcode/shape-coherence.ts +2 -2
  9. package/lib/remote-resolver.ts +1 -1
  10. package/lib/resolve/parent-place.ts +109 -0
  11. package/lib/resolve/passes.ts +68 -11
  12. package/lib/resolve/sibling-locality.ts +150 -0
  13. package/lib/resolve.ts +407 -78
  14. package/lib/scope-retrieval.ts +91 -0
  15. package/lib/span-rescore.ts +65 -14
  16. package/lib/toponym-prior.ts +57 -6
  17. package/out/admin/coherence-passes.js +1 -1
  18. package/out/admin/coherence-passes.js.map +1 -1
  19. package/out/admin/county-designator.d.ts +33 -0
  20. package/out/admin/county-designator.d.ts.map +1 -0
  21. package/out/admin/county-designator.js +65 -0
  22. package/out/admin/county-designator.js.map +1 -0
  23. package/out/admin/former-division.d.ts +47 -0
  24. package/out/admin/former-division.d.ts.map +1 -0
  25. package/out/admin/former-division.js +74 -0
  26. package/out/admin/former-division.js.map +1 -0
  27. package/out/bare-toponym-race.d.ts +1 -1
  28. package/out/bare-toponym-race.d.ts.map +1 -1
  29. package/out/decorate-node.d.ts +22 -3
  30. package/out/decorate-node.d.ts.map +1 -1
  31. package/out/decorate-node.js +85 -1
  32. package/out/decorate-node.js.map +1 -1
  33. package/out/postcode/prefix.d.ts +4 -2
  34. package/out/postcode/prefix.d.ts.map +1 -1
  35. package/out/postcode/prefix.js +7 -13
  36. package/out/postcode/prefix.js.map +1 -1
  37. package/out/postcode/shape-coherence.js +2 -2
  38. package/out/postcode/shape-coherence.js.map +1 -1
  39. package/out/remote-resolver.d.ts.map +1 -1
  40. package/out/remote-resolver.js +1 -1
  41. package/out/remote-resolver.js.map +1 -1
  42. package/out/resolve/parent-place.d.ts +34 -0
  43. package/out/resolve/parent-place.d.ts.map +1 -0
  44. package/out/resolve/parent-place.js +76 -0
  45. package/out/resolve/parent-place.js.map +1 -0
  46. package/out/resolve/passes.d.ts +44 -8
  47. package/out/resolve/passes.d.ts.map +1 -1
  48. package/out/resolve/passes.js +17 -6
  49. package/out/resolve/passes.js.map +1 -1
  50. package/out/resolve/sibling-locality.d.ts +34 -0
  51. package/out/resolve/sibling-locality.d.ts.map +1 -0
  52. package/out/resolve/sibling-locality.js +95 -0
  53. package/out/resolve/sibling-locality.js.map +1 -0
  54. package/out/resolve.d.ts.map +1 -1
  55. package/out/resolve.js +273 -69
  56. package/out/resolve.js.map +1 -1
  57. package/out/scope-retrieval.d.ts +44 -0
  58. package/out/scope-retrieval.d.ts.map +1 -0
  59. package/out/scope-retrieval.js +52 -0
  60. package/out/scope-retrieval.js.map +1 -0
  61. package/out/span-rescore.d.ts +15 -1
  62. package/out/span-rescore.d.ts.map +1 -1
  63. package/out/span-rescore.js +36 -9
  64. package/out/span-rescore.js.map +1 -1
  65. package/out/toponym-prior.d.ts +15 -0
  66. package/out/toponym-prior.d.ts.map +1 -1
  67. package/out/toponym-prior.js +37 -6
  68. package/out/toponym-prior.js.map +1 -1
  69. package/package.json +9 -9
@@ -1,11 +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
 
4
- import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
4
+ import type { PlacetypeMap } from "@mailwoman/codex/labels/placetype-map"
5
5
  import { isShapeExcludedPostcode, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
6
6
  import {
7
7
  type DefaultCountry,
8
8
  EMPTY_PLACE_FIELDS,
9
+ type FormerDivisionLookup,
10
+ type FormerDivisionMatch,
11
+ hardCountryOf,
12
+ type ParentPlaceScope,
9
13
  type ResolveCandidateTrace,
10
14
  type ResolveNodeTrace,
11
15
  type PostcodePrefixIndexLike,
@@ -13,11 +17,12 @@ import {
13
17
  type ResolveOpts,
14
18
  type ResolverBackend,
15
19
  type ResolveSwitches,
20
+ ScopeStrength,
16
21
  } from "@mailwoman/core/resolver"
17
22
  import { PLACETYPE_SPECIFICITY } from "@mailwoman/gazetteer/whosonfirst/placetypes/specificity"
18
23
  import { haversine } from "@mailwoman/spatial/geometries/point/distance"
19
24
 
20
- import { decorateNode, isResolvedWithCoord } from "#decorate-node"
25
+ import { decorateNode, isResolvedWithCoord, placeOfNode } from "#decorate-node"
21
26
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "#span-rescore"
22
27
 
23
28
  const TRACE_CANDIDATE_CAP = 10
@@ -134,6 +139,7 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
134
139
  country: c.country,
135
140
  placetype: c.placetype,
136
141
  score: c.score,
142
+ scoreUnmeasured: c.scoreUnmeasured ?? null,
137
143
  prominence: c.prominence ?? null,
138
144
  importance: c.importance ?? null,
139
145
  population: c.population ?? null,
@@ -167,6 +173,15 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
167
173
  /**
168
174
  * The options and mutable state that one `resolveTree` call passes through its tree walk.
169
175
  */
176
+ /**
177
+ * A caller's parent place as the walk reads it: the scope, the place's record, and its ancestors' ids.
178
+ */
179
+ export interface ResolvedParentPlace {
180
+ scope: ParentPlaceScope
181
+ place: ResolvedPlace
182
+ ancestorIDs: ReadonlySet<number>
183
+ }
184
+
170
185
  export interface ResolutionState {
171
186
  lookupsRemaining: number
172
187
  placetypeMap: PlacetypeMap
@@ -267,15 +282,28 @@ export interface ResolutionState {
267
282
  diagnoseUnreachable?: boolean
268
283
 
269
284
  /**
270
- * The locale country used as a soft prior on region and locality candidates
271
- * when no default country or anchor posterior applies.
285
+ * The soft country scope: a prior on region and locality candidates that applies
286
+ * while {@link ResolutionState.defaultCountry} is null and no anchor posterior applies.
287
+ *
288
+ * {@link ResolutionState.defaultCountry} holds only a hard scope.
289
+ */
290
+ softCountry: DefaultCountry | null
291
+
292
+ /**
293
+ * The weight of {@link ResolutionState.softCountry}, in log10-population units.
294
+ */
295
+ softCountryWeight: number
296
+
297
+ /**
298
+ * Whether a soft scope acts inside retrieval, and a hard default country
299
+ * probes for the places it excluded.
272
300
  */
273
- localeCountryPrior?: string
301
+ scopeCountryRetrieval: boolean
274
302
 
275
303
  /**
276
- * The weight of {@link ResolutionState.localeCountryPrior}, in log10-population units.
304
+ * The caller's parent place with its record and the ids of its ancestors, or null.
277
305
  */
278
- localeCountryPriorWeight: number
306
+ parentPlace: ResolvedParentPlace | null
279
307
 
280
308
  /**
281
309
  * Returns a candidate's capital level for bounded capital promotion.
@@ -305,6 +333,23 @@ export interface ResolutionState {
305
333
  */
306
334
  dependentLocalityContainment: boolean
307
335
 
336
+ /**
337
+ * Whether a `locality` node is looked up as its region's WOF `county` when no locality in
338
+ * the region matches it and its value is written with its country's county designator.
339
+ */
340
+ countyDesignatorFallback: boolean
341
+
342
+ /**
343
+ * The former divisions a `subregion` or `region` value is checked against when no
344
+ * current division answers it, present only under the `formerDivisions` switch.
345
+ */
346
+ formerDivisionLookup?: FormerDivisionLookup
347
+
348
+ /**
349
+ * The walked nodes no current division answered, with the former divisions their values name.
350
+ */
351
+ pendingFormerDivisions?: Map<AddressNode, readonly FormerDivisionMatch[]>
352
+
308
353
  /**
309
354
  * The tree's first region value.
310
355
  *
@@ -334,24 +379,36 @@ export function firstPostcodeValue(roots: readonly AddressNode[]): string | null
334
379
  * appending a resolved `locality` node on a hit.
335
380
  *
336
381
  * When no span matches, it tries the postcode node's code part.
382
+ *
383
+ * A hard default country filters the probes, and a bare whole-input span reads it as a prior.
384
+ * `softCountry` is a soft scope that acts inside retrieval: span probes read it only as a prior.
337
385
  */
338
386
  export async function applySpanRescore(
339
387
  roots: AddressNode[],
340
388
  raw: string,
341
389
  backend: ResolverBackend,
342
- opts: ResolvedOpts
390
+ opts: ResolvedOpts,
391
+ softCountry: string | null = null
343
392
  ): Promise<void> {
344
393
  if (hasResolvedPlace(roots, opts.spanRescoreWeakResolution ?? false)) return
345
394
 
395
+ const hardCountry = hardCountryOf(opts.defaultCountry)
396
+
346
397
  let hit
347
398
 
348
399
  try {
349
400
  hit = await findRescoreCandidate(raw, roots, backend, {
350
- country: opts.defaultCountry?.country,
401
+ ...(hardCountry
402
+ ? { country: hardCountry }
403
+ : softCountry
404
+ ? { country: softCountry, countryStrength: ScopeStrength.Soft }
405
+ : {}),
406
+ scopeCountryRetrieval: opts.scopeCountryRetrieval,
351
407
  postcode: firstPostcodeValue(roots),
352
408
  thresholdKm: opts.spanRescoreThresholdKm,
353
409
 
354
410
  postalCompoundRecovery: opts.postalCompoundRecovery,
411
+ ...(opts.softCountryWeight != null ? { bareToponymCountryWeight: opts.softCountryWeight } : {}),
355
412
  ...(opts.isVenueCategoryWord ? { isVenueCategoryWord: opts.isVenueCategoryWord } : {}),
356
413
  })
357
414
  } catch {
@@ -360,7 +417,7 @@ export async function applySpanRescore(
360
417
 
361
418
  if (!hit && opts.postalCompoundRecovery) {
362
419
  try {
363
- await recoverPostcodeNode(roots, backend, opts.defaultCountry?.country ?? null, opts.traceSink)
420
+ await recoverPostcodeNode(roots, backend, hardCountry, opts.traceSink)
364
421
  } catch {}
365
422
  }
366
423
 
@@ -485,7 +542,7 @@ async function reconcileLocalitiesToAnchor(
485
542
  }
486
543
 
487
544
  if (reconciling) {
488
- const displaced: ResolvedPlace = {
545
+ const displaced: ResolvedPlace = placeOfNode(node) ?? {
489
546
  ...EMPTY_PLACE_FIELDS,
490
547
  id: 0,
491
548
  name: String(node.metadata?.["resolver_name"] ?? node.value),
@@ -0,0 +1,150 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Sibling-locality containment: when a tree holds two resolved `locality` spans
6
+ * and the gazetteer places a candidate of one inside the other's place, the inner
7
+ * span resolves inside the outer place as a dependent locality.
8
+ *
9
+ * `Kensington, London` can decode as two localities.
10
+ * Resolved apart, `Kensington` takes the largest namesake, Kensington, California, beside London.
11
+ *
12
+ * The gazetteer's containment decides which span is inner, so `London, Kensington` reads the same.
13
+ */
14
+
15
+ import { collectNodes, type AddressNode } from "@mailwoman/core/decoder"
16
+ import type { ResolvedPlace, ResolveNodeTrace, ResolverBackend } from "@mailwoman/core/resolver"
17
+
18
+ import { adminContainmentVerdict, partitionByContainment } from "#admin/containment"
19
+ import { decorateNode } from "#decorate-node"
20
+ import { createNodeTraceRecorder } from "#resolve/passes"
21
+ import { rankByImportance } from "#toponym-prior"
22
+
23
+ /**
24
+ * The metadata stamp naming the outer place a sibling span resolved inside.
25
+ */
26
+ export const SIBLING_LOCALITY_CONTAINMENT = "sibling_locality_containment"
27
+
28
+ /**
29
+ * The most locality spans the pass pairs, because each ordered pair costs one lookup.
30
+ */
31
+ const MAX_SIBLING_LOCALITIES = 3
32
+
33
+ interface SiblingLocalityOptions {
34
+ /**
35
+ * The resolver placetype a `locality` span looks up.
36
+ */
37
+ placetype: string
38
+ limit: number
39
+ traceSink: ((record: ResolveNodeTrace) => void) | null
40
+ }
41
+
42
+ /**
43
+ * One ordered pair's reading: the inner span's candidates ranked with the outer place as their qualifier.
44
+ */
45
+ interface ContainmentReading {
46
+ inner: AddressNode
47
+ outer: AddressNode
48
+ outerID: number
49
+ ranked: ResolvedPlace[]
50
+ }
51
+
52
+ function wofID(node: AddressNode): number | null {
53
+ const id = node.placeID?.startsWith("wof:") ? Number(node.placeID.slice(4)) : Number.NaN
54
+
55
+ return Number.isInteger(id) && id > 0 ? id : null
56
+ }
57
+
58
+ /**
59
+ * The inner span's candidates looked up with the outer place as the containment qualifier,
60
+ * contained first, or null when none lies inside the outer place.
61
+ */
62
+ async function readContainment(
63
+ inner: AddressNode,
64
+ outer: AddressNode,
65
+ outerID: number,
66
+ backend: ResolverBackend,
67
+ opts: SiblingLocalityOptions
68
+ ): Promise<ContainmentReading | null> {
69
+ const country = outer.metadata?.["resolver_country"]
70
+
71
+ const hits = await backend.findPlace({
72
+ text: inner.value,
73
+ placetype: opts.placetype,
74
+ parentQualifierID: outerID,
75
+ ...(typeof country === "string" && country ? { country } : {}),
76
+ limit: opts.limit,
77
+ })
78
+
79
+ const inside = (c: ResolvedPlace) => c.containedByQualifier === true && Number(c.id) !== outerID
80
+
81
+ if (!hits.some(inside)) return null
82
+
83
+ const ranked = partitionByContainment(rankByImportance(hits), inside, (c) => c.exactMatch === true)
84
+
85
+ return { inner, outer, outerID, ranked }
86
+ }
87
+
88
+ /**
89
+ * Resolves each inner `locality` span inside its sibling's place and retags it `dependent_locality`.
90
+ *
91
+ * A pair is read in both orders.
92
+ * A pair whose spans each hold a candidate inside the other, or that resolved
93
+ * to one place, is left as it was.
94
+ */
95
+ export async function applySiblingLocalityContainment(
96
+ roots: readonly AddressNode[],
97
+ backend: ResolverBackend,
98
+ opts: SiblingLocalityOptions
99
+ ): Promise<void> {
100
+ const localities = collectNodes(roots, (n) => n.tag === "locality" && wofID(n) != null).slice(
101
+ 0,
102
+ MAX_SIBLING_LOCALITIES
103
+ )
104
+
105
+ if (localities.length < 2) return
106
+
107
+ const retagged = new Set<AddressNode>()
108
+
109
+ for (const [i, a] of localities.entries()) {
110
+ for (const b of localities.slice(i + 1)) {
111
+ if (retagged.has(a) || retagged.has(b)) continue
112
+
113
+ const aID = wofID(a)!
114
+ const bID = wofID(b)!
115
+
116
+ if (aID === bID) continue
117
+
118
+ const aInB = await readContainment(a, b, bID, backend, opts)
119
+ const bInA = await readContainment(b, a, aID, backend, opts)
120
+
121
+ // The gazetteer must order the pair one way only.
122
+ const reading = aInB && !bInA ? aInB : bInA && !aInB ? bInA : null
123
+
124
+ if (!reading) continue
125
+
126
+ const [top, ...alternatives] = reading.ranked
127
+
128
+ decorateNode(reading.inner, top!, alternatives)
129
+ reading.inner.tag = "dependent_locality"
130
+
131
+ reading.inner.metadata = {
132
+ ...reading.inner.metadata,
133
+ admin_containment: adminContainmentVerdict(reading.ranked),
134
+ contained_by_parent: true,
135
+ [SIBLING_LOCALITY_CONTAINMENT]: `wof:${reading.outerID}`,
136
+ }
137
+
138
+ retagged.add(reading.inner)
139
+
140
+ if (opts.traceSink) {
141
+ const rec = createNodeTraceRecorder(opts.traceSink)
142
+
143
+ rec.bind(reading.inner, opts.placetype, { parentQualifierID: reading.outerID, limit: opts.limit }, opts.limit)
144
+ rec.check(SIBLING_LOCALITY_CONTAINMENT)
145
+ rec.stage("sibling_containment", reading.ranked)
146
+ rec.emit({ id: top!.id, name: top!.name, source: "sibling_locality_containment" })
147
+ }
148
+ }
149
+ }
150
+ }