@mailwoman/resolver-wof-sqlite 12.0.0 → 12.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 (173) hide show
  1. package/lib/address/keys/build.ts +35 -0
  2. package/lib/address/keys/lookup.ts +318 -6
  3. package/lib/address/keys/open.ts +1 -0
  4. package/lib/address/keys/point-lookup.ts +61 -2
  5. package/lib/address/keys/schema.ts +37 -0
  6. package/lib/address/number-forms.ts +32 -13
  7. package/lib/address/point/interpolation.ts +23 -6
  8. package/lib/address/point/schema.ts +198 -2
  9. package/lib/address/point/scope-search.ts +179 -0
  10. package/lib/address/point.ts +365 -32
  11. package/lib/build/candidate.ts +36 -9
  12. package/lib/candidate/ancestors/sidecar.ts +73 -4
  13. package/lib/candidate/del1.ts +218 -0
  14. package/lib/candidate/lookup.ts +159 -100
  15. package/lib/candidate/schema.ts +14 -2
  16. package/lib/fst/binary-matcher.ts +9 -1
  17. package/lib/fst/builder.ts +7 -0
  18. package/lib/fst/del1-sidecar.ts +782 -0
  19. package/lib/fst/deserialize-web.ts +14 -2
  20. package/lib/fst/matcher.ts +7 -1
  21. package/lib/fst/types.ts +8 -0
  22. package/lib/fst.ts +1 -0
  23. package/lib/index.ts +22 -2
  24. package/lib/labels/street/canonical.ts +333 -0
  25. package/lib/labels/street/centroid/schema.ts +23 -1
  26. package/lib/labels/street/interpolation.ts +32 -6
  27. package/lib/labels/street/morphology/fst/builder.ts +13 -0
  28. package/lib/labels/street/morphology/fst/loader.ts +32 -2
  29. package/lib/labels/street/normalize.ts +153 -4
  30. package/lib/labels/street.ts +1 -0
  31. package/lib/landmark.ts +43 -2
  32. package/lib/lookup/types.ts +0 -6
  33. package/lib/poi/lookup.ts +148 -52
  34. package/lib/poi/schema.ts +9 -1
  35. package/lib/schema/overture-match.ts +2 -1
  36. package/lib/weights/overlay-linker.ts +6 -2
  37. package/out/address/keys/build.d.ts.map +1 -1
  38. package/out/address/keys/build.js +28 -1
  39. package/out/address/keys/build.js.map +1 -1
  40. package/out/address/keys/lookup.d.ts +42 -0
  41. package/out/address/keys/lookup.d.ts.map +1 -1
  42. package/out/address/keys/lookup.js +182 -6
  43. package/out/address/keys/lookup.js.map +1 -1
  44. package/out/address/keys/open.d.ts.map +1 -1
  45. package/out/address/keys/open.js +1 -0
  46. package/out/address/keys/open.js.map +1 -1
  47. package/out/address/keys/point-lookup.d.ts +6 -1
  48. package/out/address/keys/point-lookup.d.ts.map +1 -1
  49. package/out/address/keys/point-lookup.js +43 -1
  50. package/out/address/keys/point-lookup.js.map +1 -1
  51. package/out/address/keys/schema.d.ts +21 -0
  52. package/out/address/keys/schema.d.ts.map +1 -1
  53. package/out/address/keys/schema.js +18 -0
  54. package/out/address/keys/schema.js.map +1 -1
  55. package/out/address/number-forms.d.ts +10 -1
  56. package/out/address/number-forms.d.ts.map +1 -1
  57. package/out/address/number-forms.js +20 -11
  58. package/out/address/number-forms.js.map +1 -1
  59. package/out/address/point/interpolation.d.ts.map +1 -1
  60. package/out/address/point/interpolation.js +15 -5
  61. package/out/address/point/interpolation.js.map +1 -1
  62. package/out/address/point/schema.d.ts +45 -2
  63. package/out/address/point/schema.d.ts.map +1 -1
  64. package/out/address/point/schema.js +129 -0
  65. package/out/address/point/schema.js.map +1 -1
  66. package/out/address/point/scope-search.d.ts +77 -0
  67. package/out/address/point/scope-search.d.ts.map +1 -0
  68. package/out/address/point/scope-search.js +107 -0
  69. package/out/address/point/scope-search.js.map +1 -0
  70. package/out/address/point.d.ts +24 -1
  71. package/out/address/point.d.ts.map +1 -1
  72. package/out/address/point.js +231 -30
  73. package/out/address/point.js.map +1 -1
  74. package/out/build/candidate.d.ts +8 -0
  75. package/out/build/candidate.d.ts.map +1 -1
  76. package/out/build/candidate.js +17 -7
  77. package/out/build/candidate.js.map +1 -1
  78. package/out/candidate/ancestors/sidecar.d.ts +7 -3
  79. package/out/candidate/ancestors/sidecar.d.ts.map +1 -1
  80. package/out/candidate/ancestors/sidecar.js +56 -4
  81. package/out/candidate/ancestors/sidecar.js.map +1 -1
  82. package/out/candidate/del1.d.ts +61 -0
  83. package/out/candidate/del1.d.ts.map +1 -0
  84. package/out/candidate/del1.js +158 -0
  85. package/out/candidate/del1.js.map +1 -0
  86. package/out/candidate/lookup.d.ts +2 -14
  87. package/out/candidate/lookup.d.ts.map +1 -1
  88. package/out/candidate/lookup.js +122 -84
  89. package/out/candidate/lookup.js.map +1 -1
  90. package/out/candidate/schema.d.ts +8 -2
  91. package/out/candidate/schema.d.ts.map +1 -1
  92. package/out/candidate/schema.js +8 -2
  93. package/out/candidate/schema.js.map +1 -1
  94. package/out/fst/binary-matcher.d.ts +7 -1
  95. package/out/fst/binary-matcher.d.ts.map +1 -1
  96. package/out/fst/binary-matcher.js +7 -1
  97. package/out/fst/binary-matcher.js.map +1 -1
  98. package/out/fst/builder.d.ts +2 -0
  99. package/out/fst/builder.d.ts.map +1 -1
  100. package/out/fst/builder.js +5 -0
  101. package/out/fst/builder.js.map +1 -1
  102. package/out/fst/del1-sidecar.d.ts +158 -0
  103. package/out/fst/del1-sidecar.d.ts.map +1 -0
  104. package/out/fst/del1-sidecar.js +581 -0
  105. package/out/fst/del1-sidecar.js.map +1 -0
  106. package/out/fst/deserialize-web.d.ts +3 -1
  107. package/out/fst/deserialize-web.d.ts.map +1 -1
  108. package/out/fst/deserialize-web.js +9 -2
  109. package/out/fst/deserialize-web.js.map +1 -1
  110. package/out/fst/matcher.d.ts +6 -1
  111. package/out/fst/matcher.d.ts.map +1 -1
  112. package/out/fst/matcher.js +6 -1
  113. package/out/fst/matcher.js.map +1 -1
  114. package/out/fst/types.d.ts +7 -0
  115. package/out/fst/types.d.ts.map +1 -1
  116. package/out/fst.d.ts +1 -0
  117. package/out/fst.d.ts.map +1 -1
  118. package/out/fst.js +1 -0
  119. package/out/fst.js.map +1 -1
  120. package/out/index.d.ts +4 -3
  121. package/out/index.d.ts.map +1 -1
  122. package/out/index.js +3 -2
  123. package/out/index.js.map +1 -1
  124. package/out/labels/street/canonical.d.ts +68 -0
  125. package/out/labels/street/canonical.d.ts.map +1 -0
  126. package/out/labels/street/canonical.js +234 -0
  127. package/out/labels/street/canonical.js.map +1 -0
  128. package/out/labels/street/centroid/schema.d.ts +10 -1
  129. package/out/labels/street/centroid/schema.d.ts.map +1 -1
  130. package/out/labels/street/centroid/schema.js +12 -0
  131. package/out/labels/street/centroid/schema.js.map +1 -1
  132. package/out/labels/street/interpolation.d.ts +9 -1
  133. package/out/labels/street/interpolation.d.ts.map +1 -1
  134. package/out/labels/street/interpolation.js +8 -5
  135. package/out/labels/street/interpolation.js.map +1 -1
  136. package/out/labels/street/morphology/fst/builder.d.ts +8 -0
  137. package/out/labels/street/morphology/fst/builder.d.ts.map +1 -1
  138. package/out/labels/street/morphology/fst/builder.js +5 -0
  139. package/out/labels/street/morphology/fst/builder.js.map +1 -1
  140. package/out/labels/street/morphology/fst/loader.d.ts +12 -0
  141. package/out/labels/street/morphology/fst/loader.d.ts.map +1 -1
  142. package/out/labels/street/morphology/fst/loader.js +18 -2
  143. package/out/labels/street/morphology/fst/loader.js.map +1 -1
  144. package/out/labels/street/normalize.d.ts +8 -0
  145. package/out/labels/street/normalize.d.ts.map +1 -1
  146. package/out/labels/street/normalize.js +138 -4
  147. package/out/labels/street/normalize.js.map +1 -1
  148. package/out/labels/street.d.ts +1 -0
  149. package/out/labels/street.d.ts.map +1 -1
  150. package/out/labels/street.js +1 -0
  151. package/out/labels/street.js.map +1 -1
  152. package/out/landmark.d.ts +8 -0
  153. package/out/landmark.d.ts.map +1 -1
  154. package/out/landmark.js +25 -2
  155. package/out/landmark.js.map +1 -1
  156. package/out/lookup/types.d.ts +0 -5
  157. package/out/lookup/types.d.ts.map +1 -1
  158. package/out/poi/lookup.d.ts +9 -1
  159. package/out/poi/lookup.d.ts.map +1 -1
  160. package/out/poi/lookup.js +111 -53
  161. package/out/poi/lookup.js.map +1 -1
  162. package/out/poi/schema.d.ts +7 -2
  163. package/out/poi/schema.d.ts.map +1 -1
  164. package/out/poi/schema.js +3 -0
  165. package/out/poi/schema.js.map +1 -1
  166. package/out/schema/overture-match.d.ts +2 -1
  167. package/out/schema/overture-match.d.ts.map +1 -1
  168. package/out/schema/overture-match.js.map +1 -1
  169. package/out/weights/overlay-linker.d.ts +1 -1
  170. package/out/weights/overlay-linker.d.ts.map +1 -1
  171. package/out/weights/overlay-linker.js +5 -1
  172. package/out/weights/overlay-linker.js.map +1 -1
  173. package/package.json +12 -12
@@ -14,6 +14,7 @@
14
14
  import { tryParsingJSON } from "@mailwoman/core/values/json"
15
15
 
16
16
  import { BinaryFSTMatcher } from "#fst/binary-matcher"
17
+ import { BinaryFSTDel1Lookup } from "#fst/del1-sidecar"
17
18
  import { HEADER_SIZE, VERSION_WITH_METADATA } from "#fst/format"
18
19
  import type { FSTProvenance } from "#fst/types"
19
20
 
@@ -21,9 +22,20 @@ import type { FSTProvenance } from "#fst/types"
21
22
  * Opens an FST binary for matching, answering queries from the bytes in place.
22
23
  *
23
24
  * The matcher keeps a reference to `input`, so the caller mustn't modify it afterward.
25
+ * An optional `del1Sidecar` (raw `FD1\0` bytes or a loaded lookup) attaches fuzzy 1-edit recovery.
24
26
  */
25
- export function deserializeFSTWeb(input: ArrayBuffer | Uint8Array): BinaryFSTMatcher {
26
- return new BinaryFSTMatcher(input)
27
+ export function deserializeFSTWeb(
28
+ input: ArrayBuffer | Uint8Array,
29
+ del1Sidecar?: ArrayBuffer | Uint8Array | BinaryFSTDel1Lookup | null
30
+ ): BinaryFSTMatcher {
31
+ const lookup =
32
+ del1Sidecar == null
33
+ ? null
34
+ : del1Sidecar instanceof BinaryFSTDel1Lookup
35
+ ? del1Sidecar
36
+ : new BinaryFSTDel1Lookup(del1Sidecar)
37
+
38
+ return new BinaryFSTMatcher(input, lookup)
27
39
  }
28
40
 
29
41
  export function readFSTProvenanceWeb(input: ArrayBuffer | Uint8Array): FSTProvenance | null {
@@ -10,6 +10,7 @@
10
10
 
11
11
  import type { AncestrieMatch } from "@mailwoman/ancestrie"
12
12
 
13
+ import type { BinaryFSTDel1Lookup } from "#fst/del1-sidecar"
13
14
  import type { FSTContinuation, FSTQueryResult, PlaceEntry } from "#fst/types"
14
15
 
15
16
  interface FSTNode {
@@ -19,9 +20,14 @@ interface FSTNode {
19
20
 
20
21
  export class FSTMatcher {
21
22
  private nodes: FSTNode[]
23
+ /**
24
+ * Optional 1-delete fuzzy token sidecar paired with this matcher.
25
+ */
26
+ del1Sidecar: BinaryFSTDel1Lookup | null
22
27
 
23
- constructor(nodes: FSTNode[]) {
28
+ constructor(nodes: FSTNode[], del1Sidecar: BinaryFSTDel1Lookup | null = null) {
24
29
  this.nodes = nodes
30
+ this.del1Sidecar = del1Sidecar
25
31
  }
26
32
 
27
33
  get stateCount(): number {
package/lib/fst/types.ts CHANGED
@@ -7,6 +7,8 @@
7
7
 
8
8
  import type { PathBuilderLike } from "path-ts"
9
9
 
10
+ import type { BuildFSTDel1SidecarOpts } from "#fst/del1-sidecar"
11
+
10
12
  /**
11
13
  * One place that a token sequence in the FST accepts.
12
14
  */
@@ -169,6 +171,12 @@ export interface BuildFSTOpts {
169
171
  * A place reachable under several surfaces records each surface's own count.
170
172
  */
171
173
  surfaceCountryCounts?: ReadonlyMap<string, number>
174
+ /**
175
+ * When set, builds a companion `FD1\0` 1-delete fuzzy token sidecar from the resulting FST.
176
+ *
177
+ * Pass `true` for defaults or an options object to override thresholds.
178
+ */
179
+ buildDel1Sidecar?: boolean | BuildFSTDel1SidecarOpts
172
180
  onProgress?: (phase: string, detail?: string) => void
173
181
  }
174
182
 
package/lib/fst.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  export * from "#fst/autocomplete"
5
5
  export * from "#fst/binary-matcher"
6
6
  export * from "#fst/builder"
7
+ export * from "#fst/del1-sidecar"
7
8
  export * from "#fst/deserialize-web"
8
9
  export * from "#fst/format"
9
10
  export * from "#fst/freshness"
package/lib/index.ts CHANGED
@@ -35,6 +35,13 @@ export type {
35
35
  IntervalLabel,
36
36
  } from "#candidate/ancestors/schema"
37
37
 
38
+ export {
39
+ CANDIDATE_DEL1_TABLE,
40
+ createCandidateDel1,
41
+ type CandidateDel1Result,
42
+ type CandidateDel1Table,
43
+ } from "#candidate/del1"
44
+
38
45
  export { CANDIDATE_FTS_TABLE, createCandidateFTS } from "#candidate/fts"
39
46
 
40
47
  export {
@@ -60,8 +67,20 @@ export { SQLiteStreetNameLookup, type SQLiteStreetNameLookupOpts } from "#labels
60
67
 
61
68
  export { type GeonamesIngestProgress, ingestGeonamesAliases, purgeGeonamesAliasRange } from "#geonames/aliases"
62
69
 
63
- export { ADDRESS_POINT_COLUMNS, createAddressPointIndexes, createAddressPointTable } from "#address/point/schema"
64
- export type { AddressPointDatabase, AddressPointTable } from "#address/point/schema"
70
+ export {
71
+ ADDRESS_POINT_COLUMNS,
72
+ createAddressPointIndexes,
73
+ createAddressPointTable,
74
+ createStreetScopeIndex,
75
+ createStreetScopeIndexTable,
76
+ } from "#address/point/schema"
77
+
78
+ export type {
79
+ AddressPointDatabase,
80
+ AddressPointTable,
81
+ StreetScopeIndexHandle,
82
+ StreetScopeIndexTable,
83
+ } from "#address/point/schema"
65
84
 
66
85
  export {
67
86
  WOFPostalCityAliasLookup,
@@ -128,6 +147,7 @@ export { readLatestAddressLayerManifest, readLatestAddressLayerManifests } from
128
147
  export {
129
148
  STREET_CENTROID_COLUMNS,
130
149
  createStreetCentroidIndexes,
150
+ createStreetCentroidScopeIndex,
131
151
  createStreetCentroidTable,
132
152
  } from "#labels/street/centroid/schema"
133
153
 
@@ -0,0 +1,333 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Build-time canonical street keys and scoped 1-edit candidate filtering.
6
+ *
7
+ * Unlike `normalizeStreetForKeyLocale`, which preserves language-specific street words
8
+ * and drops apostrophes without inserting spaces, `canonicalStreetKey` maps thoroughfare types
9
+ * into semantic classes, spaces apostrophes before stripping post-type Romance connectors,
10
+ * and keeps distinct classes apart (`Calle Mayor` → `way mayor`, `Plaza Mayor` → `square mayor`).
11
+ */
12
+
13
+ import { stripLeadingStreetConnector } from "@mailwoman/codex/labels/street/connectors"
14
+ import {
15
+ isThoroughfareClass,
16
+ type ThoroughfareClass,
17
+ thoroughfareClassOf,
18
+ } from "@mailwoman/codex/labels/street/thoroughfare-classes"
19
+ import { AbbreviationToDirectional } from "@mailwoman/codex/us"
20
+ import { oneEditDistance } from "@mailwoman/match/comparators"
21
+
22
+ import {
23
+ normalizeStreetForKey,
24
+ normalizeStreetForKeyLocale,
25
+ streetKeyRulesOf,
26
+ streetLocaleForSurface,
27
+ type StreetLocale,
28
+ } from "#labels/street/normalize"
29
+
30
+ /**
31
+ * Maximum distinct streets in one postcode or locality scope that scoped 1-edit fuzzy lookup scans.
32
+ *
33
+ * Scopes above this cap abstain so lookups remain sub-millisecond.
34
+ */
35
+ export const FUZZY_SCOPE_ROW_LIMIT = 1500
36
+
37
+ /**
38
+ * Minimum character length of the proper-name core required before 1-edit fuzzy recovery activates.
39
+ *
40
+ * Below 5 characters a single edit collides with unrelated street names.
41
+ */
42
+ export const MIN_FUZZY_CORE_LENGTH = 5
43
+
44
+ /**
45
+ * Structured canonical street key derived from a raw street name and street locale.
46
+ */
47
+ export interface CanonicalStreetKey {
48
+ /**
49
+ * Build-time key stored in `street_canon`: `"<thoroughfareClass> <core>"`
50
+ * when a thoroughfare class was recognized, or `core` otherwise.
51
+ */
52
+ key: string
53
+ /**
54
+ * Semantic thoroughfare equivalence class when recognized, else `null`.
55
+ */
56
+ thoroughfareClass: ThoroughfareClass | null
57
+ /**
58
+ * Proper-name core with leading or trailing thoroughfare type and post-type
59
+ * grammatical connectors stripped.
60
+ */
61
+ core: string
62
+ }
63
+
64
+ /**
65
+ * One candidate row from `street_scope_index` or `street_alias_*` scanned during scoped 1-edit fuzzy lookup.
66
+ */
67
+ export interface ScopedStreetAliasRow {
68
+ street_canon: string
69
+ street_norm: string
70
+ }
71
+
72
+ const DIRECTIONAL_WORDS: ReadonlySet<string> = new Set(
73
+ [...AbbreviationToDirectional.values()].map((name) => name.toLowerCase().replaceAll(" ", ""))
74
+ )
75
+
76
+ /**
77
+ * Fused German and Dutch street-type suffixes, longest first, paired with their thoroughfare class.
78
+ *
79
+ * A fused suffix is split only when at least 3 characters of stem precede it,
80
+ * so standalone type words aren't reduced to empty cores.
81
+ */
82
+ const DE_NL_FUSED_SUFFIXES: ReadonlyArray<readonly [suffix: string, cls: ThoroughfareClass]> = [
83
+ ["strasse", "way"],
84
+ ["straat", "way"],
85
+ ["platz", "square"],
86
+ ["plein", "square"],
87
+ ["gasse", "alley"],
88
+ ["steeg", "alley"],
89
+ ["allee", "avenue"],
90
+ ["laan", "avenue"],
91
+ ["gracht", "promenade"],
92
+ ["singel", "promenade"],
93
+ ["kade", "promenade"],
94
+ ["dreef", "road"],
95
+ ["weg", "road"],
96
+ ["str", "way"],
97
+ ]
98
+
99
+ const MIN_FUSED_STEM_LENGTH = 3
100
+
101
+ /**
102
+ * Minimum token count for an English street name to hold a proper name, a thoroughfare type,
103
+ * and a trailing directional (`Main Street North`).
104
+ */
105
+ const MIN_TOKENS_WITH_TRAILING_DIRECTIONAL = 3
106
+
107
+ /**
108
+ * Minimum token count for a two-word leading thoroughfare type (`Rond-Point` split on its hyphen)
109
+ * followed by at least one proper-name token.
110
+ */
111
+ const MIN_TOKENS_FOR_TWO_WORD_LEAD_TYPE = 3
112
+
113
+ /**
114
+ * Folds a raw Latin street string into space-separated lowercase ASCII tokens, replacing
115
+ * apostrophes, slashes, hyphens, and punctuation with spaces before connector stripping
116
+ * so elisions such as `d'Enric` tokenize as `["d", "enric"]`.
117
+ */
118
+ function canonicalFoldTokens(streetRaw: string): string[] {
119
+ const cleaned = streetRaw
120
+ // Normalize Spanish `P.º` before stripping periods so it stays `po` (`paseo`) rather than `p o`.
121
+ .replaceAll(/([pP])\.º/gu, "$1o")
122
+ .normalize("NFKD")
123
+ .replaceAll(/[\u0300-\u036F]/gu, "")
124
+ .toLowerCase()
125
+ .replaceAll("ß", "ss")
126
+ .replaceAll("ł", "l")
127
+ .replaceAll("đ", "d")
128
+ .replaceAll("ð", "d")
129
+ .replaceAll(/['’‘`ʻʼ/.,-]+/gu, " ")
130
+ .replaceAll(/\s+/gu, " ")
131
+ .trim()
132
+
133
+ return cleaned ? cleaned.split(" ") : []
134
+ }
135
+
136
+ function canonicalFromTrailingEnglish(streetRaw: string, locale: StreetLocale): CanonicalStreetKey {
137
+ const normalized = normalizeStreetForKey(streetRaw)
138
+
139
+ if (!normalized) return { key: "", thoroughfareClass: null, core: "" }
140
+
141
+ const tokens = normalized.split(" ").filter((t) => t.length > 0)
142
+
143
+ if (!tokens.length) return { key: "", thoroughfareClass: null, core: "" }
144
+
145
+ // Check the trailing thoroughfare word (last token, or second-to-last when a directional trails).
146
+ if (tokens.length >= 2) {
147
+ const lastIdx = tokens.length - 1
148
+
149
+ const typeIdx =
150
+ tokens.length >= MIN_TOKENS_WITH_TRAILING_DIRECTIONAL && DIRECTIONAL_WORDS.has(tokens[lastIdx]!)
151
+ ? lastIdx - 1
152
+ : lastIdx
153
+
154
+ const cls = thoroughfareClassOf(tokens[typeIdx]!, locale)
155
+
156
+ if (cls) {
157
+ const remaining = tokens.filter((_, idx) => idx !== typeIdx)
158
+
159
+ if (remaining.length) {
160
+ const core = remaining.join(" ")
161
+
162
+ return { key: `${cls} ${core}`, thoroughfareClass: cls, core }
163
+ }
164
+ }
165
+ }
166
+
167
+ const core = tokens.join(" ")
168
+
169
+ return { key: core, thoroughfareClass: null, core }
170
+ }
171
+
172
+ function canonicalFromGermanic(streetRaw: string, locale: StreetLocale): CanonicalStreetKey {
173
+ const tokens = canonicalFoldTokens(streetRaw)
174
+
175
+ if (!tokens.length) return { key: "", thoroughfareClass: null, core: "" }
176
+
177
+ // Standalone leading type (`Straße des 17. Juni`).
178
+ if (tokens.length >= 2) {
179
+ const leadClass = thoroughfareClassOf(tokens[0]!, locale)
180
+
181
+ if (leadClass) {
182
+ const core = tokens.slice(1).join(" ")
183
+
184
+ return { key: `${leadClass} ${core}`, thoroughfareClass: leadClass, core }
185
+ }
186
+
187
+ // Standalone trailing type (`Teschener Weg`).
188
+ const tailClass = thoroughfareClassOf(tokens.at(-1)!, locale)
189
+
190
+ if (tailClass) {
191
+ const core = tokens.slice(0, -1).join(" ")
192
+
193
+ return { key: `${tailClass} ${core}`, thoroughfareClass: tailClass, core }
194
+ }
195
+ }
196
+
197
+ // Fused compound suffix (`Hauptstraße`, `Krankenhausstr.`, `Kalverstraat`).
198
+ const last = tokens.at(-1)!
199
+
200
+ for (const [suffix, cls] of DE_NL_FUSED_SUFFIXES) {
201
+ if (last.endsWith(suffix) && last.length - suffix.length >= MIN_FUSED_STEM_LENGTH) {
202
+ const stem = last.slice(0, -suffix.length)
203
+ const coreTokens = [...tokens.slice(0, -1), stem]
204
+ const core = coreTokens.join(" ")
205
+
206
+ return { key: `${cls} ${core}`, thoroughfareClass: cls, core }
207
+ }
208
+ }
209
+
210
+ const core = tokens.join(" ")
211
+
212
+ return { key: core, thoroughfareClass: null, core }
213
+ }
214
+
215
+ /**
216
+ * Computes the build-time canonical street key for `streetRaw` under `locale`.
217
+ *
218
+ * The function maps leading thoroughfare types to semantic classes from `@mailwoman/codex`.
219
+ * Post-type grammatical connectors are stripped only immediately after a recognized
220
+ * leading thoroughfare type and only when at least one proper-name token remains.
221
+ *
222
+ * Apostrophes are normalized to spaces before connector stripping so `Calle d'Enric Granados`
223
+ * and `Carrer d'Enric Granados` both canonicalize to `way enric granados`.
224
+ */
225
+ export function canonicalStreetKey(streetRaw: string, locale: StreetLocale): CanonicalStreetKey {
226
+ if (!streetRaw.trim()) return { key: "", thoroughfareClass: null, core: "" }
227
+
228
+ const effectiveLocale = streetLocaleForSurface(streetRaw, locale)
229
+ const { canonicalMorphology } = streetKeyRulesOf(effectiveLocale)
230
+
231
+ if (canonicalMorphology === "han") {
232
+ const folded = String(normalizeStreetForKeyLocale(streetRaw, effectiveLocale))
233
+
234
+ return { key: folded, thoroughfareClass: null, core: folded }
235
+ }
236
+
237
+ if (canonicalMorphology === "trailing-english") {
238
+ return canonicalFromTrailingEnglish(streetRaw, effectiveLocale)
239
+ }
240
+
241
+ if (canonicalMorphology === "germanic-fused") {
242
+ return canonicalFromGermanic(streetRaw, effectiveLocale)
243
+ }
244
+
245
+ const tokens = canonicalFoldTokens(streetRaw)
246
+
247
+ if (!tokens.length) return { key: "", thoroughfareClass: null, core: "" }
248
+
249
+ // Two-token hyphen-split French `Rond-Point` leading type.
250
+ if (tokens.length >= MIN_TOKENS_FOR_TWO_WORD_LEAD_TYPE && tokens[0] === "rond" && tokens[1] === "point") {
251
+ const coreTokens = stripLeadingStreetConnector(tokens.slice(2))
252
+ const core = coreTokens.join(" ")
253
+
254
+ return { key: `roundabout ${core}`, thoroughfareClass: "roundabout", core }
255
+ }
256
+
257
+ if (tokens.length >= 2) {
258
+ const leadClass = thoroughfareClassOf(tokens[0]!, effectiveLocale)
259
+
260
+ if (leadClass) {
261
+ const coreTokens = stripLeadingStreetConnector(tokens.slice(1))
262
+ const core = coreTokens.join(" ")
263
+
264
+ return { key: `${leadClass} ${core}`, thoroughfareClass: leadClass, core }
265
+ }
266
+ }
267
+
268
+ // No recognized leading thoroughfare type: preserve leading particles (`De Gaulle`).
269
+ const core = tokens.join(" ")
270
+
271
+ return { key: core, thoroughfareClass: null, core }
272
+ }
273
+
274
+ /**
275
+ * Parses a stored `street_canon` string back into its thoroughfare class and proper-name core.
276
+ *
277
+ * @public
278
+ */
279
+ export function parseCanonicalStreetKey(streetCanon: string): CanonicalStreetKey {
280
+ const trimmed = streetCanon.trim()
281
+
282
+ if (!trimmed) return { key: "", thoroughfareClass: null, core: "" }
283
+
284
+ const space = trimmed.indexOf(" ")
285
+
286
+ if (space > 0) {
287
+ const head = trimmed.slice(0, space)
288
+ const rest = trimmed.slice(space + 1)
289
+
290
+ if (rest && isThoroughfareClass(head)) {
291
+ return { key: trimmed, thoroughfareClass: head, core: rest }
292
+ }
293
+ }
294
+
295
+ return { key: trimmed, thoroughfareClass: null, core: trimmed }
296
+ }
297
+
298
+ /**
299
+ * Filters a contiguous scope scan of `street_canon` / `street_norm` rows to the
300
+ * distinct `street_norm` candidates whose proper-name core is within 1 restricted
301
+ * Damerau-Levenshtein edit of `queryCanon.core`.
302
+ *
303
+ * Abstains (returns `[]`) when `queryCanon.core.length < MIN_FUZZY_CORE_LENGTH`
304
+ * or when `scopeRows.length > FUZZY_SCOPE_ROW_LIMIT`.
305
+ * When the query stated a thoroughfare class, only candidates in the same class qualify.
306
+ */
307
+ export function findFuzzyEdit1Streets(
308
+ queryCanon: CanonicalStreetKey,
309
+ scopeRows: readonly ScopedStreetAliasRow[]
310
+ ): string[] {
311
+ if (queryCanon.core.length < MIN_FUZZY_CORE_LENGTH) return []
312
+
313
+ if (scopeRows.length > FUZZY_SCOPE_ROW_LIMIT) return []
314
+
315
+ const qCore = queryCanon.core
316
+ const qLen = qCore.length
317
+ const qClass = queryCanon.thoroughfareClass
318
+ const matched = new Set<string>()
319
+
320
+ for (const row of scopeRows) {
321
+ const cand = parseCanonicalStreetKey(row.street_canon)
322
+
323
+ if (qClass !== null && cand.thoroughfareClass !== qClass) continue
324
+
325
+ if (Math.abs(qLen - cand.core.length) > 1) continue
326
+
327
+ if (oneEditDistance(qCore, cand.core) === 1) {
328
+ matched.add(row.street_norm)
329
+ }
330
+ }
331
+
332
+ return [...matched]
333
+ }
@@ -8,7 +8,12 @@
8
8
 
9
9
  import type { Kysely } from "kysely"
10
10
 
11
- import type { NameKey, StreetKey } from "#labels/street/normalize"
11
+ import {
12
+ populateStreetScopeIndex,
13
+ type StreetScopeIndexHandle,
14
+ type StreetScopeIndexTable,
15
+ } from "#address/point/schema"
16
+ import type { NameKey, StreetKey, StreetLocale } from "#labels/street/normalize"
12
17
 
13
18
  /**
14
19
  * One row per street, postcode and commune.
@@ -83,6 +88,7 @@ export interface StreetCentroidTable {
83
88
  */
84
89
  export interface StreetCentroidDatabase {
85
90
  street_centroid: StreetCentroidTable
91
+ street_scope_index?: StreetScopeIndexTable
86
92
  }
87
93
 
88
94
  /**
@@ -147,3 +153,19 @@ export async function createStreetCentroidIndexes(db: Kysely<StreetCentroidDatab
147
153
 
148
154
  await db.schema.createIndex("idx_sc_name").on("street_centroid").columns(["name_key"]).execute()
149
155
  }
156
+
157
+ /**
158
+ * Creates and populates `street_scope_index` from `street_centroid`, keying postcode
159
+ * scopes with `addressPostcodeKey` and locality scopes from `locality_base`.
160
+ */
161
+ export async function createStreetCentroidScopeIndex(
162
+ db: StreetScopeIndexHandle,
163
+ streetLocale: StreetLocale,
164
+ options?: { country?: string }
165
+ ): Promise<void> {
166
+ await populateStreetScopeIndex(db, streetLocale, {
167
+ sourceTable: "street_centroid",
168
+ localityColumn: "locality_base",
169
+ ...options,
170
+ })
171
+ }
@@ -7,7 +7,7 @@
7
7
  * and linear interpolation along the segment polyline.
8
8
  */
9
9
 
10
- import type { InterpolationLookup } from "@mailwoman/core/resolver"
10
+ import type { InterpolationLookup, StreetMatchKind } from "@mailwoman/core/resolver"
11
11
  import { parseJSONStrict, stringifyJSON } from "@mailwoman/core/values/json"
12
12
  import { haversine } from "@mailwoman/spatial/geometries/point/distance"
13
13
  import { clampFraction, pointAlong } from "@mailwoman/spatial/polyline"
@@ -65,6 +65,16 @@ export interface InterpolatedHit {
65
65
  source: string
66
66
 
67
67
  release: string
68
+
69
+ /**
70
+ * The stored street key that answered.
71
+ */
72
+ matchedStreet: string
73
+
74
+ /**
75
+ * How {@link matchedStreet} relates to the query's primary normalized street key.
76
+ */
77
+ streetMatch: StreetMatchKind
68
78
  }
69
79
 
70
80
  export interface InterpolationQuery {
@@ -235,15 +245,15 @@ export class StreetInterpolator<
235
245
  const variants = streetKeyVariants(query.street, SEGMENT_STREET_LOCALE)
236
246
 
237
247
  // A variant advances the ladder when it produces no answer rather than merely no rows.
238
- for (const variant of variants) {
239
- const streetNorm = canonicalizeRouteKey(variant)
248
+ for (let i = 0; i < variants.length; i++) {
249
+ const streetNorm = canonicalizeRouteKey(variants[i]!)
240
250
 
241
251
  // A ZIP that scopes to no candidate is a miss rather than a statewide guess.
242
252
  const rows = query.postcode
243
253
  ? this.#byPostcode(query.postcode.trim(), streetNorm, n, n)
244
254
  : this.#byStreet(streetNorm, n, n)
245
255
 
246
- const hit = this.#answerFromRows(rows, n, query)
256
+ const hit = this.#answerFromRows(rows, n, query, streetNorm, i === 0 ? "written" : "respelled")
247
257
 
248
258
  if (hit) return hit
249
259
  }
@@ -272,13 +282,27 @@ export class StreetInterpolator<
272
282
 
273
283
  if (stored.length !== 1) return null
274
284
 
275
- return this.#answerFromRows(this.#byPostcode(postcode, stored[0]!.street_norm as RouteKey, n, n), n, query)
285
+ const matchedStreet = stored[0]!.street_norm as RouteKey
286
+
287
+ return this.#answerFromRows(
288
+ this.#byPostcode(postcode, matchedStreet, n, n),
289
+ n,
290
+ query,
291
+ matchedStreet,
292
+ "directional-relaxed"
293
+ )
276
294
  }
277
295
 
278
296
  /**
279
297
  * Resolve one key variant's covering rows to an answer, or null when the rows do not support one.
280
298
  */
281
- #answerFromRows(rows: SegmentRow[], n: number, query: InterpolationQuery): InterpolatedHit | null {
299
+ #answerFromRows(
300
+ rows: SegmentRow[],
301
+ n: number,
302
+ query: InterpolationQuery,
303
+ matchedStreet: string,
304
+ streetMatch: StreetMatchKind
305
+ ): InterpolatedHit | null {
282
306
  if (!rows.length) return null
283
307
 
284
308
  // Parity preference: exact side first, then `mixed`, then the opposite side as a flagged fallback.
@@ -325,6 +349,8 @@ export class StreetInterpolator<
325
349
  uncertaintyM: Math.round((lengthKm * 1000) / 2),
326
350
  source: best.source,
327
351
  release: best.release,
352
+ matchedStreet,
353
+ streetMatch,
328
354
  }
329
355
  }
330
356
 
@@ -35,6 +35,7 @@ import { PathBuilder, type PathBuilderLike } from "path-ts"
35
35
  import { TextSpliterator } from "spliterator"
36
36
  import { Globerator } from "spliterator/node/fs"
37
37
 
38
+ import { buildFSTDel1Sidecar, type BuildFSTDel1SidecarOpts, type BuiltFSTDel1Sidecar } from "#fst/del1-sidecar"
38
39
  import type { FSTNode } from "#fst/matcher"
39
40
  import { FSTMatcher, normalizeTokens } from "#fst/matcher"
40
41
  import type { FSTProvenance, PlaceEntry } from "#fst/types"
@@ -94,6 +95,12 @@ export interface BuildStreetMorphologyFSTOpts {
94
95
  * Canadian province abbreviations
95
96
  */
96
97
  excludedVariants?: ReadonlySet<string>
98
+ /**
99
+ * When set, builds a companion `FD1\0` 1-delete fuzzy token sidecar over the morphology FST.
100
+ *
101
+ * Pass `true` for defaults or an options object to override thresholds.
102
+ */
103
+ buildDel1Sidecar?: boolean | BuildFSTDel1SidecarOpts
97
104
  /**
98
105
  * Optional progress callback.
99
106
  */
@@ -107,6 +114,7 @@ export interface BuildStreetMorphologyFSTResult {
107
114
  variantCount: number
108
115
  insertCount: number
109
116
  locales: string[]
117
+ del1Sidecar?: BuiltFSTDel1Sidecar
110
118
  }
111
119
 
112
120
  /**
@@ -294,6 +302,10 @@ export async function buildStreetMorphologyFST(
294
302
  excludedInsertions: null,
295
303
  }
296
304
 
305
+ const del1Sidecar = opts.buildDel1Sidecar
306
+ ? buildFSTDel1Sidecar(matcher, opts.buildDel1Sidecar === true ? {} : opts.buildDel1Sidecar)
307
+ : undefined
308
+
297
309
  return {
298
310
  matcher,
299
311
  provenance,
@@ -301,5 +313,6 @@ export async function buildStreetMorphologyFST(
301
313
  variantCount,
302
314
  insertCount,
303
315
  locales,
316
+ ...(del1Sidecar ? { del1Sidecar } : {}),
304
317
  }
305
318
  }