@mailwoman/resolver 10.8.0 → 11.1.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 -8
  2. package/lib/admin/coherence-passes.ts +14 -20
  3. package/lib/admin/containment.ts +6 -5
  4. package/lib/admin/jp-municipality.ts +3 -3
  5. package/lib/admin/winner.ts +5 -5
  6. package/lib/admin.ts +2 -5
  7. package/lib/bare-toponym-race.ts +12 -10
  8. package/lib/decorate-node.ts +62 -9
  9. package/lib/fold-name.ts +8 -8
  10. package/lib/index.ts +11 -8
  11. package/lib/plausibility.ts +2 -5
  12. package/lib/postcode/country-coherence.ts +4 -7
  13. package/lib/postcode/prefix.ts +4 -7
  14. package/lib/postcode/shape-coherence.ts +3 -6
  15. package/lib/postcode.ts +2 -5
  16. package/lib/remote-resolver.ts +3 -7
  17. package/lib/rerank.ts +7 -8
  18. package/lib/resolve/country-code.ts +106 -0
  19. package/lib/resolve/landmark.ts +234 -0
  20. package/lib/resolve/passes.ts +14 -61
  21. package/lib/resolve/region-city.ts +255 -0
  22. package/lib/resolve/whole-input.ts +49 -0
  23. package/lib/resolve.ts +62 -65
  24. package/lib/span-rescore.ts +90 -26
  25. package/lib/street/evidence.ts +2 -5
  26. package/lib/street/tier.ts +28 -13
  27. package/lib/street.ts +2 -5
  28. package/lib/toponym-prior.ts +4 -7
  29. package/out/admin/coherence-passes.d.ts +2 -7
  30. package/out/admin/coherence-passes.d.ts.map +1 -1
  31. package/out/admin/coherence-passes.js +14 -20
  32. package/out/admin/coherence-passes.js.map +1 -1
  33. package/out/admin/containment.d.ts +3 -5
  34. package/out/admin/containment.d.ts.map +1 -1
  35. package/out/admin/containment.js +5 -5
  36. package/out/admin/containment.js.map +1 -1
  37. package/out/admin/jp-municipality.d.ts +0 -3
  38. package/out/admin/jp-municipality.d.ts.map +1 -1
  39. package/out/admin/jp-municipality.js +2 -15
  40. package/out/admin/jp-municipality.js.map +1 -1
  41. package/out/admin/winner.d.ts +2 -5
  42. package/out/admin/winner.d.ts.map +1 -1
  43. package/out/admin/winner.js +2 -9
  44. package/out/admin/winner.js.map +1 -1
  45. package/out/admin.d.ts +0 -5
  46. package/out/admin.d.ts.map +1 -1
  47. package/out/admin.js +2 -5
  48. package/out/admin.js.map +1 -1
  49. package/out/bare-toponym-race.d.ts +0 -11
  50. package/out/bare-toponym-race.d.ts.map +1 -1
  51. package/out/bare-toponym-race.js +3 -12
  52. package/out/bare-toponym-race.js.map +1 -1
  53. package/out/decorate-node.d.ts +14 -6
  54. package/out/decorate-node.d.ts.map +1 -1
  55. package/out/decorate-node.js +53 -9
  56. package/out/decorate-node.js.map +1 -1
  57. package/out/fold-name.d.ts +5 -8
  58. package/out/fold-name.d.ts.map +1 -1
  59. package/out/fold-name.js +7 -8
  60. package/out/fold-name.js.map +1 -1
  61. package/out/index.d.ts +8 -8
  62. package/out/index.d.ts.map +1 -1
  63. package/out/index.js +10 -8
  64. package/out/index.js.map +1 -1
  65. package/out/plausibility.d.ts +0 -5
  66. package/out/plausibility.d.ts.map +1 -1
  67. package/out/plausibility.js +2 -5
  68. package/out/plausibility.js.map +1 -1
  69. package/out/postcode/country-coherence.d.ts +2 -7
  70. package/out/postcode/country-coherence.d.ts.map +1 -1
  71. package/out/postcode/country-coherence.js +3 -6
  72. package/out/postcode/country-coherence.js.map +1 -1
  73. package/out/postcode/prefix.d.ts +2 -7
  74. package/out/postcode/prefix.d.ts.map +1 -1
  75. package/out/postcode/prefix.js +3 -6
  76. package/out/postcode/prefix.js.map +1 -1
  77. package/out/postcode/shape-coherence.d.ts +1 -6
  78. package/out/postcode/shape-coherence.d.ts.map +1 -1
  79. package/out/postcode/shape-coherence.js +2 -5
  80. package/out/postcode/shape-coherence.js.map +1 -1
  81. package/out/postcode.d.ts +0 -5
  82. package/out/postcode.d.ts.map +1 -1
  83. package/out/postcode.js +2 -5
  84. package/out/postcode.js.map +1 -1
  85. package/out/remote-resolver.d.ts +1 -7
  86. package/out/remote-resolver.d.ts.map +1 -1
  87. package/out/remote-resolver.js +2 -6
  88. package/out/remote-resolver.js.map +1 -1
  89. package/out/rerank.d.ts +3 -7
  90. package/out/rerank.d.ts.map +1 -1
  91. package/out/rerank.js +3 -10
  92. package/out/rerank.js.map +1 -1
  93. package/out/resolve/country-code.d.ts +28 -0
  94. package/out/resolve/country-code.d.ts.map +1 -0
  95. package/out/resolve/country-code.js +91 -0
  96. package/out/resolve/country-code.js.map +1 -0
  97. package/out/resolve/landmark.d.ts +25 -0
  98. package/out/resolve/landmark.d.ts.map +1 -0
  99. package/out/resolve/landmark.js +187 -0
  100. package/out/resolve/landmark.js.map +1 -0
  101. package/out/resolve/passes.d.ts +3 -36
  102. package/out/resolve/passes.d.ts.map +1 -1
  103. package/out/resolve/passes.js +13 -30
  104. package/out/resolve/passes.js.map +1 -1
  105. package/out/resolve/region-city.d.ts +56 -0
  106. package/out/resolve/region-city.d.ts.map +1 -0
  107. package/out/resolve/region-city.js +209 -0
  108. package/out/resolve/region-city.js.map +1 -0
  109. package/out/resolve/whole-input.d.ts +14 -0
  110. package/out/resolve/whole-input.d.ts.map +1 -0
  111. package/out/resolve/whole-input.js +37 -0
  112. package/out/resolve/whole-input.js.map +1 -0
  113. package/out/resolve.d.ts +0 -8
  114. package/out/resolve.d.ts.map +1 -1
  115. package/out/resolve.js +42 -59
  116. package/out/resolve.js.map +1 -1
  117. package/out/span-rescore.d.ts +16 -15
  118. package/out/span-rescore.d.ts.map +1 -1
  119. package/out/span-rescore.js +68 -18
  120. package/out/span-rescore.js.map +1 -1
  121. package/out/street/evidence.d.ts +0 -5
  122. package/out/street/evidence.d.ts.map +1 -1
  123. package/out/street/evidence.js +2 -5
  124. package/out/street/evidence.js.map +1 -1
  125. package/out/street/tier.d.ts +3 -8
  126. package/out/street/tier.d.ts.map +1 -1
  127. package/out/street/tier.js +24 -11
  128. package/out/street/tier.js.map +1 -1
  129. package/out/street.d.ts +0 -5
  130. package/out/street.d.ts.map +1 -1
  131. package/out/street.js +2 -5
  132. package/out/street.js.map +1 -1
  133. package/out/toponym-prior.d.ts +2 -7
  134. package/out/toponym-prior.d.ts.map +1 -1
  135. package/out/toponym-prior.js +4 -7
  136. package/out/toponym-prior.js.map +1 -1
  137. package/package.json +9 -8
  138. package/lib/backend-capabilities.ts +0 -89
  139. package/out/backend-capabilities.d.ts +0 -36
  140. package/out/backend-capabilities.d.ts.map +0 -1
  141. package/out/backend-capabilities.js +0 -77
  142. package/out/backend-capabilities.js.map +0 -1
package/lib/resolve.ts CHANGED
@@ -1,24 +1,17 @@
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
 
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, isShapeExcludedPostcode, type AddressNode, type AddressTree } from "@mailwoman/core/decoder"
13
14
  import {
14
- collectNodes,
15
- isShapeExcludedPostcode,
16
- type AddressNode,
17
- type AddressTree,
18
- type Interpretation,
19
- } from "@mailwoman/core/decoder"
20
- import {
21
- type BackendCapabilityGap,
22
15
  type DefaultCountry,
23
16
  type ResolveNodeTrace,
24
17
  type ResolvedPlace,
@@ -37,7 +30,6 @@ import {
37
30
  } from "#admin/coherence-passes"
38
31
  import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "#admin/containment"
39
32
  import { resolveCompoundMunicipality } from "#admin/jp-municipality"
40
- import { describeCapabilityGaps, reportCapabilityGaps } from "#backend-capabilities"
41
33
  import {
42
34
  BARE_REGION_DOMINANCE_LOG10,
43
35
  bareCountryCandidate,
@@ -54,6 +46,8 @@ import {
54
46
  } from "#postcode/country-coherence"
55
47
  import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "#postcode/prefix"
56
48
  import { applyPostcodeShapeCoherence } from "#postcode/shape-coherence"
49
+ import { applyCountryCode, readRegionCodeAsCountry } from "#resolve/country-code"
50
+ import { applyLandmark } from "#resolve/landmark"
57
51
  import {
58
52
  applyPostcodeConsistency,
59
53
  applyRooftopConsistency,
@@ -62,10 +56,17 @@ import {
62
56
  DIAGNOSTIC_BANDS,
63
57
  firstPostcodeValue,
64
58
  NOOP_TRACE_RECORDER,
65
- pickCompletion,
66
59
  type ResolutionState,
67
60
  type ResolvedOpts,
68
61
  } from "#resolve/passes"
62
+ import {
63
+ applyCountryAsRegion,
64
+ applyLocalityAsRegion,
65
+ applyRegionCity,
66
+ applyStreetAsTown,
67
+ applyVenueAsTown,
68
+ } from "#resolve/region-city"
69
+ import { applyWholeInputPlace } from "#resolve/whole-input"
69
70
  import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier"
70
71
  import {
71
72
  type CapitalLevelFn,
@@ -128,16 +129,10 @@ class WOFResolver implements Resolver {
128
129
  * Coverage metadata surfaced from the backend artifact.
129
130
  */
130
131
  readonly artifactCoverage: Resolver["artifactCoverage"]
131
- /**
132
- * Optional backend capabilities that the implementation lacks.
133
- */
134
- readonly capabilityGaps: readonly BackendCapabilityGap[]
135
132
 
136
133
  constructor(backend: ResolverBackend) {
137
134
  this.#backend = backend
138
135
  this.artifactCoverage = backend.artifactCoverage ?? null
139
- this.capabilityGaps = describeCapabilityGaps(backend)
140
- reportCapabilityGaps(this.capabilityGaps)
141
136
  }
142
137
 
143
138
  /**
@@ -145,9 +140,12 @@ class WOFResolver implements Resolver {
145
140
  */
146
141
  findPlace: Resolver["findPlace"] = (query) => this.#backend.findPlace(query)
147
142
 
148
- async resolveTree(tree: AddressTree, callerOpts: ResolveOpts = {}): Promise<AddressTree> {
143
+ async resolveTree(parsed: AddressTree, callerOpts: ResolveOpts = {}): Promise<AddressTree> {
144
+ const tree = readRegionCodeAsCountry(parsed)
145
+
149
146
  // Every on/off switch resolves against the one defaults table, so the reads below are plain truthiness.
150
147
  const opts: ResolvedOpts = { ...callerOpts, ...resolveSwitches(callerOpts) }
148
+
151
149
  // Optional early postcode-shape pass.
152
150
  // Runs sync and can only narrow candidates.
153
151
  const shapeVerdict = opts.postcodeShapeCoherence ? applyPostcodeShapeCoherence(tree.roots) : null
@@ -181,17 +179,12 @@ class WOFResolver implements Resolver {
181
179
  localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
182
180
  capitalLevel: opts.capitalLevel,
183
181
  hardCountry: opts.hardCountry,
184
- // Dual-role hierarchy completion (default on, backend-dependent).
185
- hierarchyCompletion: opts.hierarchyCompletion,
186
182
  includeAncestors: opts.includeAncestors,
187
183
  // Optional admin containment rerank uses a pre-scanned region qualifier.
188
184
  adminContainmentRerank: opts.adminContainmentRerank,
189
185
  dependentLocalityContainment: opts.dependentLocalityContainment,
190
186
  regionQualifier: firstRegionQualifier(tree.roots),
191
187
  ...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
192
- localityNodePresent: false,
193
- resolvedRegion: null,
194
- resolvedRegionNode: null,
195
188
  }
196
189
 
197
190
  // Optional pre-walk postcode-country coherence pass.
@@ -233,6 +226,9 @@ class WOFResolver implements Resolver {
233
226
  newRoots.push(await this.#walk(root, /* parentResolved */ null, state))
234
227
  }
235
228
 
229
+ // A later pass that gives one of these nodes a different place removes the walk's ancestors with the old place.
230
+ const walkedWithAncestors = collectNodes(newRoots, (n) => n.metadata?.["ancestors"] != null)
231
+
236
232
  // Stamp metadata for postcode-country override.
237
233
  if (postcodeScope) {
238
234
  stampPostcodeCountryScope(newRoots, postcodeScope)
@@ -247,11 +243,6 @@ class WOFResolver implements Resolver {
247
243
  }
248
244
  }
249
245
 
250
- // If enabled, add a dropped dual-role locality as a region interpretation.
251
- if (state.hierarchyCompletion && state.resolvedRegion && state.resolvedRegionNode && !state.localityNodePresent) {
252
- this.#completeRegionRole(state.resolvedRegion, state.resolvedRegionNode)
253
- }
254
-
255
246
  // Admin coherence passes (default on).
256
247
  if (opts.adminCoherence) {
257
248
  // Clear contradictory parent-fallback picks before coherence passes.
@@ -261,6 +252,29 @@ class WOFResolver implements Resolver {
261
252
  await applyExplicitCountryCoherence(newRoots, this.#backend)
262
253
  // Re-resolve foreign region/locality pairs blocked by locale scope.
263
254
  await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry?.country ?? null)
255
+ await applyRegionCity(newRoots, this.#backend)
256
+ await applyCountryAsRegion(newRoots, this.#backend)
257
+ await applyVenueAsTown(newRoots, this.#backend)
258
+ await applyStreetAsTown(newRoots, this.#backend)
259
+
260
+ if (isCallerScope(state.defaultCountry)) {
261
+ await applyLocalityAsRegion(newRoots, this.#backend, state.defaultCountry!.country)
262
+ }
263
+
264
+ await applyCountryCode(newRoots, opts.writtenInput ?? tree.raw, this.#backend)
265
+ }
266
+
267
+ if (opts.landmarks) {
268
+ await applyLandmark(newRoots, opts.writtenInput ?? tree.raw, opts.landmarks)
269
+ }
270
+
271
+ if (opts.adminCoherence) {
272
+ await applyWholeInputPlace(
273
+ newRoots,
274
+ opts.writtenInput ?? tree.raw,
275
+ this.#backend,
276
+ isCallerScope(state.defaultCountry) ? state.defaultCountry!.country : null
277
+ )
264
278
  }
265
279
 
266
280
  // The postcode and rooftop passes hold a locality to the same distance from their point.
@@ -277,7 +291,7 @@ class WOFResolver implements Resolver {
277
291
 
278
292
  // Optional exact address-point tier.
279
293
  if (opts.addressPoints) {
280
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
294
+ await applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
281
295
  }
282
296
 
283
297
  // Optional interpolation tier after exact points.
@@ -291,9 +305,14 @@ class WOFResolver implements Resolver {
291
305
  await applySpanRescore(newRoots, tree.raw, this.#backend, opts)
292
306
  }
293
307
 
308
+ // OpenStreetMap places answer after span rescore, so a town that holds the whole name keeps it.
309
+ if (opts.osmPlaces) {
310
+ await applyLandmark(newRoots, opts.writtenInput ?? tree.raw, opts.osmPlaces)
311
+ }
312
+
294
313
  // Retry exact address-point tier once after span-rescore recovery.
295
314
  if (opts.addressPoints) {
296
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
315
+ await applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback, ancestorsOf)
297
316
  }
298
317
 
299
318
  // A rooftop row keyed by locality name can lie in a namesake of the selected locality.
@@ -306,29 +325,18 @@ class WOFResolver implements Resolver {
306
325
  applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
307
326
  }
308
327
 
309
- return { raw: tree.raw, roots: newRoots }
310
- }
311
-
312
- /**
313
- * Add a dropped dual-role locality as a `locality` interpretation on a resolved region node.
314
- */
315
- #completeRegionRole(region: CoordinateOptionalPlace, regionNode: AddressNode): void {
316
- if (typeof region.id !== "number" || !this.#backend.coincidentLocalitiesFor) return
317
- const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id))
318
-
319
- if (!loc) return
328
+ // The walk's ancestors are read again for the place that replaced its pick.
329
+ if (this.#backend.ancestors) {
330
+ for (const node of walkedWithAncestors) {
331
+ const id = node.placeID?.startsWith("wof:") ? Number(node.placeID.slice(4)) : Number.NaN
320
332
 
321
- const interpretation: Interpretation = {
322
- tag: "locality",
323
- placeID: `wof:${loc.id}`,
324
- sourceID: `${loc.placetype}:${loc.id}`,
325
- lat: loc.lat,
326
- lon: loc.lon,
327
- confidence: 0,
328
- metadata: { relationship_type: loc.relationshipType, resolver_completed: true, resolver_name: loc.name },
333
+ if (node.metadata?.["ancestors"] == null && Number.isInteger(id)) {
334
+ node.metadata = { ...node.metadata, ancestors: this.#backend.ancestors(id) }
335
+ }
336
+ }
329
337
  }
330
338
 
331
- regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation]
339
+ return { raw: tree.raw, roots: newRoots }
332
340
  }
333
341
 
334
342
  async #walk(
@@ -342,11 +350,6 @@ class WOFResolver implements Resolver {
342
350
 
343
351
  const placetype = state.placetypeMap[node.tag as ComponentTag]
344
352
 
345
- // Track whether a locality node exists for hierarchy completion.
346
- if (placetype === "locality") {
347
- state.localityNodePresent = true
348
- }
349
-
350
353
  let resolved: CoordinateOptionalPlace | null = null
351
354
 
352
355
  // Skip lookup for shape-excluded postcode spans.
@@ -391,12 +394,6 @@ class WOFResolver implements Resolver {
391
394
  if (state.includeAncestors && this.#backend.ancestors) {
392
395
  decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) }
393
396
  }
394
-
395
- // Capture first resolved region for hierarchy completion.
396
- if (placetype === "region" && state.resolvedRegion === null) {
397
- state.resolvedRegion = picked.top
398
- state.resolvedRegionNode = decorated
399
- }
400
397
  }
401
398
  }
402
399
 
@@ -565,7 +562,7 @@ class WOFResolver implements Resolver {
565
562
  rec.reachable(await this.#probeOtherBands(query, placetype))
566
563
  }
567
564
  } catch (error) {
568
- // Defensive: backend errors should not abort the whole tree walk.
565
+ // Defensive: backend errors shouldn't abort the whole tree walk.
569
566
  rec.check(`backend_error: ${(error as Error).message}`)
570
567
  rec.emit(null)
571
568
 
@@ -1,11 +1,11 @@
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"
@@ -14,6 +14,7 @@ import { isRegionAbbreviationToken } from "@mailwoman/query-shape/region-abbrevi
14
14
  import { haversine } from "@mailwoman/spatial/geometries/point/distance"
15
15
 
16
16
  import { partitionByContainment } from "#admin/containment"
17
+ import { bareSublocalityCandidate } from "#bare-toponym-race"
17
18
  import { foldName } from "#fold-name"
18
19
  import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "#toponym-prior"
19
20
 
@@ -58,6 +59,11 @@ export interface SpanRescoreOptions {
58
59
  * @defaultValue `false`
59
60
  */
60
61
  postalCompoundRecovery?: boolean
62
+ /**
63
+ * Returns whether a word is a POI category, so a venue's last word isn't re-read as a locality.
64
+ * A caller without the taxonomy leaves every span eligible.
65
+ */
66
+ isVenueCategoryWord?: (word: string) => boolean
61
67
  /**
62
68
  * When the span covers the whole unqualified input, treat {@link country} as an additive prior
63
69
  * instead of a hard gazetteer filter; `false` restores the hard filter byte-for-byte.
@@ -71,14 +77,6 @@ export interface SpanRescoreOptions {
71
77
  * @defaultValue {@linkcode DEFAULT_COUNTRY_PRIOR_WEIGHT} (2), and 0 removes the locale's say entirely.
72
78
  */
73
79
  bareToponymCountryWeight?: number
74
- /**
75
- * Admit a proper sub-span only when every token it leaves behind is a subdivision code or a number.
76
- *
77
- * See `remainderIsContext` for the rule.
78
- *
79
- * @defaultValue `false`
80
- */
81
- spanRescoreRequireContextRemainder?: boolean
82
80
  }
83
81
 
84
82
  /**
@@ -110,6 +108,13 @@ export interface RescoreCandidate {
110
108
  * so the top-1-vs-top-2 dominance margin stays computable.
111
109
  */
112
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
113
118
  }
114
119
 
115
120
  interface RawTok {
@@ -152,7 +157,7 @@ export function postcodeCodeSubset(postcode: string): string {
152
157
  const BARE_TOPONYM_FETCH = 20
153
158
 
154
159
  /**
155
- * 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,
156
161
  * postcode or house number the parser read out of the input — so the soft-country
157
162
  * prior stands down and the hard filter keeps its say.
158
163
  */
@@ -188,7 +193,7 @@ function resolvedWeakly(node: AddressNode, reading: WeakResolutionReading): bool
188
193
 
189
194
  /**
190
195
  * True if any node in the tree already has a resolved place id — the brake on span rescore.
191
- * with `weakReading`, a node whose resolution is weak under that reading does not hold it.
196
+ * with `weakReading`, a node whose resolution is weak under that reading doesn't hold it.
192
197
  */
193
198
  export function hasResolvedPlace(
194
199
  roots: readonly AddressNode[],
@@ -203,7 +208,7 @@ export function hasResolvedPlace(
203
208
  *
204
209
  * The whole span stays probeable.
205
210
  * Single-token spans are excluded.
206
- * The guard does not depend on confidence.
211
+ * The guard doesn't depend on confidence.
207
212
  */
208
213
  function multiTokenNameInteriors(roots: readonly AddressNode[], raw: string): Array<[number, number]> {
209
214
  const out: Array<[number, number]> = []
@@ -225,7 +230,7 @@ function multiTokenNameInteriors(roots: readonly AddressNode[], raw: string): Ar
225
230
  /**
226
231
  * The confident ranges split by what a span containing one means: `hard`
227
232
  * (house number, postcode, street body) refuses any overlap, while `affix` refuses
228
- * a span only when it does not strictly contain the affix.
233
+ * a span only when it doesn't strictly contain the affix.
229
234
  */
230
235
  interface ConfidentRanges {
231
236
  hard: Array<[number, number]>
@@ -234,7 +239,7 @@ interface ConfidentRanges {
234
239
 
235
240
  /**
236
241
  * The character ranges the parse read as street material, context only
237
- * when the range does not overlap the span under test.
242
+ * when the range doesn't overlap the span under test.
238
243
  */
239
244
  function streetRanges(roots: readonly AddressNode[]): Array<[number, number]> {
240
245
  const out: Array<[number, number]> = []
@@ -399,12 +404,22 @@ export async function findRescoreCandidate(
399
404
  /**
400
405
  * Whether every token a sub-span leaves behind is context rather than identity,
401
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.
402
412
  */
403
413
  const remainderIsContext = (span: { start: number; end: number }): boolean => {
404
414
  const outside = toks.filter((t) => t.end <= span.start || t.start >= span.end)
405
415
 
406
416
  if (!outside.length) return true
407
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
+
408
423
  const streetContext = streets.filter(([start, end]) => end <= span.start || start >= span.end)
409
424
 
410
425
  return outside.every(
@@ -420,6 +435,14 @@ export async function findRescoreCandidate(
420
435
  const qualified = !!postcode || hasAdminQualifier(roots)
421
436
  const wholeInput = toks.length ? { start: toks[0]!.start, end: toks.at(-1)!.end } : null
422
437
  const softCountryEligible = softCountry && !!country && !qualified && !!wholeInput
438
+ const venue = firstNodeWhere(roots, (n) => n.tag === "venue")
439
+
440
+ const venueCoversInput = !!venue && !!wholeInput && venue.start <= wholeInput.start && wholeInput.end <= venue.end
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
423
446
 
424
447
  for (const sp of spans) {
425
448
  const key = foldName(sp.text)
@@ -429,9 +452,14 @@ export async function findRescoreCandidate(
429
452
  // also needs an unqualified tree and a caller country.
430
453
  const wholeSpan = !!wholeInput && sp.start === wholeInput.start && sp.end === wholeInput.end
431
454
 
432
- // A sub-span that drops a word of the name is a corruption rather than a
433
- // recovery. see `remainderIsContext`.
434
- if (opts.spanRescoreRequireContextRemainder && !wholeSpan && !remainderIsContext(sp)) continue
455
+ // A category word ending a multi-word venue states what the place is, as `Airport`
456
+ // in `Narita Airport`, so a locality of that name is a coincidence of spelling.
457
+ // Another last word can state the location, as `London` in `Tower of London`.
458
+ if (venue && sp.end === venue.end && sp.start > venue.start && opts.isVenueCategoryWord?.(sp.text)) continue
459
+
460
+ const dropsName = !wholeSpan && !remainderIsContext(sp)
461
+
462
+ if (nameDropping && dropsName) continue
435
463
 
436
464
  const bare = softCountryEligible && wholeSpan
437
465
  const qualifier = wholeSpan ? null : qualifierRemainder(sp)
@@ -478,22 +506,49 @@ export async function findRescoreCandidate(
478
506
  const withinThreshold = (p: ResolvedPlace): boolean =>
479
507
  !anchor || thresholdKm <= 0 || haversine(anchor.lat, anchor.lon, p.lat, p.lon) <= thresholdKm
480
508
 
481
- for (const h of exact) {
482
- if (!withinThreshold(h)) continue
509
+ const h = exact.find(withinThreshold)
483
510
 
511
+ if (h) {
484
512
  // `postcodeVerified` is true only when an anchor existed and validated this match within
485
513
  // `thresholdKm`; otherwise the match is returned unrestricted but flagged lower-precision.
486
- return {
514
+ const candidate: RescoreCandidate = {
487
515
  text: sp.text,
488
516
  start: sp.start,
489
517
  end: sp.end,
490
518
  place: h,
491
519
  postcodeVerified: anchor !== null,
492
520
  alternatives: exact.filter((a) => a !== h && withinThreshold(a)),
521
+ dropsName,
522
+ }
523
+
524
+ if (!dropsName) return candidate
525
+
526
+ nameDropping = candidate
527
+
528
+ continue
529
+ }
530
+
531
+ // A whole-input venue can be a sub-locality row, as `Golden Gate Park` is a neighborhood,
532
+ // and that row states the whole name where a shorter span would state part of it.
533
+ if (wholeSpan && venueCoversInput) {
534
+ const sublocality = await bareSublocalityCandidate(backend, sp.text, country)
535
+
536
+ if (sublocality && withinThreshold(sublocality)) {
537
+ return {
538
+ text: sp.text,
539
+ start: sp.start,
540
+ end: sp.end,
541
+ place: sublocality,
542
+ postcodeVerified: anchor !== null,
543
+ alternatives: [],
544
+ dropsName,
545
+ }
493
546
  }
494
547
  }
495
548
  }
496
549
 
550
+ if (nameDropping) return nameDropping
551
+
497
552
  // Joint country recovery: when the scoped pass finds no match and a postcode
498
553
  // is present, re-probe unscoped and accept a cross-country promotion only
499
554
  // when its code subset resolves postcode-verified within the radius.
@@ -525,7 +580,16 @@ export async function findRescoreCandidate(
525
580
  // Admission uses per-candidate postcode verification.
526
581
  // The postcode already picked the country, so this pass has no remaining
527
582
  // country ambiguity to report.
528
- 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
+ }
529
593
  }
530
594
  }
531
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")
@@ -148,21 +145,39 @@ export function applyAddressPoint(
148
145
 
149
146
  let bbox: { minLat: number; maxLat: number; minLon: number; maxLon: number } | null = null
150
147
 
148
+ // A row stating no locality or postcode matches on its street and number,
149
+ // and the box keeps it in the stated place.
150
+ // The box is the town's own extent where the gazetteer holds one, because `W 1st St`
151
+ // repeats in the next town inside any fixed radius.
152
+ // A stated postcode adds the radius to it, because a rural ZIP Code's mailing town covers
153
+ // addresses far outside that town's own extent, and a row stating another postcode stays refused.
151
154
  if (bboxFallback && localityNode?.lat != null && localityNode.lon != null) {
152
- bbox = {
155
+ const extent = resolvedExtent(localityNode)
156
+
157
+ const radius = {
153
158
  minLat: localityNode.lat - LOCALITY_BBOX_RADIUS_DEG,
154
159
  maxLat: localityNode.lat + LOCALITY_BBOX_RADIUS_DEG,
155
160
  minLon: localityNode.lon - LOCALITY_BBOX_RADIUS_DEG,
156
161
  maxLon: localityNode.lon + LOCALITY_BBOX_RADIUS_DEG,
157
162
  }
163
+
164
+ bbox =
165
+ extent && postcode
166
+ ? {
167
+ minLat: Math.min(extent.minLat, radius.minLat),
168
+ maxLat: Math.max(extent.maxLat, radius.maxLat),
169
+ minLon: Math.min(extent.minLon, radius.minLon),
170
+ maxLon: Math.max(extent.maxLon, radius.maxLon),
171
+ }
172
+ : (extent ?? radius)
158
173
  }
159
174
 
160
175
  let street: AddressNode | null = null
161
176
  let houseNumber: AddressNode | null = null
162
- let hit: ReturnType<AddressPointLookup["find"]> | null = null
177
+ let hit: Awaited<ReturnType<AddressPointLookup["find"]>> = null
163
178
 
164
179
  for (const pair of pairs) {
165
- hit = lookup.find({
180
+ hit = await lookup.find({
166
181
  street: assembleStreetValue(pair.street, directionalUnit),
167
182
  number: pair.houseNumber.value,
168
183
  postcode: postcode ?? null,
@@ -186,7 +201,7 @@ export function applyAddressPoint(
186
201
  if (!hit && locality && extent) {
187
202
  retry: for (const name of ancestorLocalityNames(localityNode, ancestorsOf)) {
188
203
  for (const pair of pairs) {
189
- const candidate = lookup.find({
204
+ const candidate = await lookup.find({
190
205
  street: assembleStreetValue(pair.street, directionalUnit),
191
206
  number: pair.houseNumber.value,
192
207
  postcode: postcode ?? null,
@@ -229,14 +244,14 @@ export function applyAddressPoint(
229
244
 
230
245
  /**
231
246
  * Stamps the street with an interpolated house-number coordinate when the
232
- * address-point tier did not already place it.
247
+ * address-point tier didn't already place it.
233
248
  *
234
249
  * It writes `interpolated_point` rather than `address_point`, so an estimate
235
250
  * never overwrites a real situs point.
236
251
  *
237
252
  * A query without a postcode is scoped only by its locality, so its estimate must lie inside the resolved
238
253
  * locality's bounding box, and an estimate outside it is refused as a namesake street elsewhere.
239
- * 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
240
255
  * can reach past the WOF place's extent.
241
256
  */
242
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"
@@ -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 { ResolvedPlace } from "@mailwoman/core/resolver"
8
5
 
@@ -195,8 +192,8 @@ const PROMOTABLE_CAPITAL_LEVEL = 2
195
192
  export const NATIONAL_CAPITAL_MARGIN_LOG10 = 2
196
193
 
197
194
  /**
198
- * Moves the first national capital in the leading match tier above each preceding row that
199
- * is at most {@link NATIONAL_CAPITAL_MARGIN_LOG10} larger, stopping at another capital.
195
+ * Moves the first national capital in the leading match tier above each preceding row
196
+ * that's at most {@link NATIONAL_CAPITAL_MARGIN_LOG10} larger, stopping at another capital.
200
197
  *
201
198
  * It runs after {@link rankByImportance} and never moves a capital across the exact-match boundary.
202
199
  */
@@ -1,15 +1,10 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
6
1
  import type { AddressNode } from "@mailwoman/core/decoder";
7
2
  import type { ResolverBackend } from "@mailwoman/core/resolver";
8
3
  /**
9
4
  * Un-resolves a parent-fallback pick whose stamped ancestors name a region other than
10
5
  * the resolved region above it, marking it `parent_fallback_refused`.
11
6
  *
12
- * A pick whose ancestor chain names no region is kept, because the fallback
7
+ * A pick whose ancestor chain identifies no region is kept, because the fallback
13
8
  * exists for places with incomplete hierarchies.
14
9
  */
15
10
  export declare function applyParentFallbackContradiction(roots: readonly AddressNode[]): void;
@@ -26,7 +21,7 @@ export declare function applyAdminCoherence(roots: readonly AddressNode[], backe
26
21
  * Re-picks a locality to the place with the same name inside the country specified in
27
22
  * the address, when that country is the locality's nearest admin context.
28
23
  *
29
- * It leaves the locality unchanged when it already resolved to that place or
24
+ * It leaves the locality unchanged when it already resolved inside that country or
30
25
  * when that country has no locality with the same name.
31
26
  */
32
27
  export declare function applyExplicitCountryCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"coherence-passes.d.ts","sourceRoot":"","sources":["../../lib/admin/coherence-passes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,KAAK,EAAiB,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAY9E;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,GAAG,IAAI,CAuCpF;AAED;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAqBhH;AA4HD;;;;;;GAMG;AACH,wBAAsB,6BAA6B,CAClD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,GACtB,OAAO,CAAC,IAAI,CAAC,CAkBf;AAmCD;;;;;;GAMG;AACH,wBAAsB,2BAA2B,CAChD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,EACxB,cAAc,EAAE,MAAM,GAAG,IAAI,GAC3B,OAAO,CAAC,IAAI,CAAC,CAuBf"}
1
+ {"version":3,"file":"coherence-passes.d.ts","sourceRoot":"","sources":["../../lib/admin/coherence-passes.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,KAAK,EAAiB,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAY9E;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,GAAG,IAAI,CAuCpF;AAED;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAqBhH;AAmHD;;;;;;GAMG;AACH,wBAAsB,6BAA6B,CAClD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,GACtB,OAAO,CAAC,IAAI,CAAC,CAkBf;AAyCD;;;;;;GAMG;AACH,wBAAsB,2BAA2B,CAChD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,EACxB,cAAc,EAAE,MAAM,GAAG,IAAI,GAC3B,OAAO,CAAC,IAAI,CAAC,CAuBf"}