@mailwoman/resolver-wof-sqlite 11.5.0 → 12.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 (196) hide show
  1. package/lib/address/keys/build.ts +35 -0
  2. package/lib/address/keys/lookup.ts +204 -6
  3. package/lib/address/keys/point-lookup.ts +4 -0
  4. package/lib/address/keys/schema.ts +37 -0
  5. package/lib/address/number-forms.ts +32 -13
  6. package/lib/address/point/interpolation.ts +23 -6
  7. package/lib/address/point/schema.ts +120 -2
  8. package/lib/address/point/scope-search.ts +179 -0
  9. package/lib/address/point.ts +225 -28
  10. package/lib/build/candidate.ts +222 -9
  11. package/lib/build/population-corrections.ts +11 -2
  12. package/lib/candidate/ancestors/sidecar.ts +73 -4
  13. package/lib/candidate/del1.ts +218 -0
  14. package/lib/candidate/lookup.ts +316 -113
  15. package/lib/candidate/name-roles.ts +112 -6
  16. package/lib/candidate/outcomes.ts +191 -0
  17. package/lib/candidate/schema.ts +79 -3
  18. package/lib/fst/binary-matcher.ts +9 -1
  19. package/lib/fst/builder.ts +7 -0
  20. package/lib/fst/del1-sidecar.ts +782 -0
  21. package/lib/fst/deserialize-web.ts +14 -2
  22. package/lib/fst/matcher.ts +7 -1
  23. package/lib/fst/types.ts +8 -0
  24. package/lib/fst.ts +1 -0
  25. package/lib/geonames/aliases.ts +39 -1
  26. package/lib/index.ts +22 -2
  27. package/lib/labels/street/canonical.ts +333 -0
  28. package/lib/labels/street/centroid/schema.ts +23 -1
  29. package/lib/labels/street/interpolation.ts +32 -6
  30. package/lib/labels/street/morphology/fst/builder.ts +13 -0
  31. package/lib/labels/street/morphology/fst/loader.ts +32 -2
  32. package/lib/labels/street/normalize.ts +34 -4
  33. package/lib/labels/street.ts +1 -0
  34. package/lib/landmark.ts +51 -4
  35. package/lib/lookup/types.ts +25 -6
  36. package/lib/outcome/memberships.ts +131 -0
  37. package/lib/outcome/schema.ts +147 -0
  38. package/lib/poi/lookup.ts +4 -0
  39. package/lib/poi/schema.ts +2 -1
  40. package/lib/ranking/primary-preference.ts +14 -6
  41. package/lib/schema/overture-match.ts +2 -1
  42. package/out/address/keys/build.d.ts.map +1 -1
  43. package/out/address/keys/build.js +28 -1
  44. package/out/address/keys/build.js.map +1 -1
  45. package/out/address/keys/lookup.d.ts +17 -0
  46. package/out/address/keys/lookup.d.ts.map +1 -1
  47. package/out/address/keys/lookup.js +119 -6
  48. package/out/address/keys/lookup.js.map +1 -1
  49. package/out/address/keys/point-lookup.d.ts.map +1 -1
  50. package/out/address/keys/point-lookup.js +4 -0
  51. package/out/address/keys/point-lookup.js.map +1 -1
  52. package/out/address/keys/schema.d.ts +21 -0
  53. package/out/address/keys/schema.d.ts.map +1 -1
  54. package/out/address/keys/schema.js +18 -0
  55. package/out/address/keys/schema.js.map +1 -1
  56. package/out/address/number-forms.d.ts +10 -1
  57. package/out/address/number-forms.d.ts.map +1 -1
  58. package/out/address/number-forms.js +20 -11
  59. package/out/address/number-forms.js.map +1 -1
  60. package/out/address/point/interpolation.d.ts.map +1 -1
  61. package/out/address/point/interpolation.js +15 -5
  62. package/out/address/point/interpolation.js.map +1 -1
  63. package/out/address/point/schema.d.ts +43 -2
  64. package/out/address/point/schema.d.ts.map +1 -1
  65. package/out/address/point/schema.js +73 -0
  66. package/out/address/point/schema.js.map +1 -1
  67. package/out/address/point/scope-search.d.ts +77 -0
  68. package/out/address/point/scope-search.d.ts.map +1 -0
  69. package/out/address/point/scope-search.js +107 -0
  70. package/out/address/point/scope-search.js.map +1 -0
  71. package/out/address/point.d.ts +12 -0
  72. package/out/address/point.d.ts.map +1 -1
  73. package/out/address/point.js +143 -26
  74. package/out/address/point.js.map +1 -1
  75. package/out/build/candidate.d.ts +49 -0
  76. package/out/build/candidate.d.ts.map +1 -1
  77. package/out/build/candidate.js +101 -8
  78. package/out/build/candidate.js.map +1 -1
  79. package/out/build/population-corrections.d.ts +2 -2
  80. package/out/build/population-corrections.d.ts.map +1 -1
  81. package/out/build/population-corrections.js +10 -2
  82. package/out/build/population-corrections.js.map +1 -1
  83. package/out/candidate/ancestors/sidecar.d.ts +7 -3
  84. package/out/candidate/ancestors/sidecar.d.ts.map +1 -1
  85. package/out/candidate/ancestors/sidecar.js +56 -4
  86. package/out/candidate/ancestors/sidecar.js.map +1 -1
  87. package/out/candidate/del1.d.ts +61 -0
  88. package/out/candidate/del1.d.ts.map +1 -0
  89. package/out/candidate/del1.js +158 -0
  90. package/out/candidate/del1.js.map +1 -0
  91. package/out/candidate/lookup.d.ts +16 -17
  92. package/out/candidate/lookup.d.ts.map +1 -1
  93. package/out/candidate/lookup.js +222 -92
  94. package/out/candidate/lookup.js.map +1 -1
  95. package/out/candidate/name-roles.d.ts +3 -2
  96. package/out/candidate/name-roles.d.ts.map +1 -1
  97. package/out/candidate/name-roles.js +75 -5
  98. package/out/candidate/name-roles.js.map +1 -1
  99. package/out/candidate/outcomes.d.ts +57 -0
  100. package/out/candidate/outcomes.d.ts.map +1 -0
  101. package/out/candidate/outcomes.js +109 -0
  102. package/out/candidate/outcomes.js.map +1 -0
  103. package/out/candidate/schema.d.ts +51 -3
  104. package/out/candidate/schema.d.ts.map +1 -1
  105. package/out/candidate/schema.js +40 -0
  106. package/out/candidate/schema.js.map +1 -1
  107. package/out/fst/binary-matcher.d.ts +7 -1
  108. package/out/fst/binary-matcher.d.ts.map +1 -1
  109. package/out/fst/binary-matcher.js +7 -1
  110. package/out/fst/binary-matcher.js.map +1 -1
  111. package/out/fst/builder.d.ts +2 -0
  112. package/out/fst/builder.d.ts.map +1 -1
  113. package/out/fst/builder.js +5 -0
  114. package/out/fst/builder.js.map +1 -1
  115. package/out/fst/del1-sidecar.d.ts +158 -0
  116. package/out/fst/del1-sidecar.d.ts.map +1 -0
  117. package/out/fst/del1-sidecar.js +581 -0
  118. package/out/fst/del1-sidecar.js.map +1 -0
  119. package/out/fst/deserialize-web.d.ts +3 -1
  120. package/out/fst/deserialize-web.d.ts.map +1 -1
  121. package/out/fst/deserialize-web.js +9 -2
  122. package/out/fst/deserialize-web.js.map +1 -1
  123. package/out/fst/matcher.d.ts +6 -1
  124. package/out/fst/matcher.d.ts.map +1 -1
  125. package/out/fst/matcher.js +6 -1
  126. package/out/fst/matcher.js.map +1 -1
  127. package/out/fst/types.d.ts +7 -0
  128. package/out/fst/types.d.ts.map +1 -1
  129. package/out/fst.d.ts +1 -0
  130. package/out/fst.d.ts.map +1 -1
  131. package/out/fst.js +1 -0
  132. package/out/fst.js.map +1 -1
  133. package/out/geonames/aliases.d.ts +10 -0
  134. package/out/geonames/aliases.d.ts.map +1 -1
  135. package/out/geonames/aliases.js +33 -1
  136. package/out/geonames/aliases.js.map +1 -1
  137. package/out/index.d.ts +4 -3
  138. package/out/index.d.ts.map +1 -1
  139. package/out/index.js +3 -2
  140. package/out/index.js.map +1 -1
  141. package/out/labels/street/canonical.d.ts +68 -0
  142. package/out/labels/street/canonical.d.ts.map +1 -0
  143. package/out/labels/street/canonical.js +234 -0
  144. package/out/labels/street/canonical.js.map +1 -0
  145. package/out/labels/street/centroid/schema.d.ts +10 -1
  146. package/out/labels/street/centroid/schema.d.ts.map +1 -1
  147. package/out/labels/street/centroid/schema.js +12 -0
  148. package/out/labels/street/centroid/schema.js.map +1 -1
  149. package/out/labels/street/interpolation.d.ts +9 -1
  150. package/out/labels/street/interpolation.d.ts.map +1 -1
  151. package/out/labels/street/interpolation.js +8 -5
  152. package/out/labels/street/interpolation.js.map +1 -1
  153. package/out/labels/street/morphology/fst/builder.d.ts +8 -0
  154. package/out/labels/street/morphology/fst/builder.d.ts.map +1 -1
  155. package/out/labels/street/morphology/fst/builder.js +5 -0
  156. package/out/labels/street/morphology/fst/builder.js.map +1 -1
  157. package/out/labels/street/morphology/fst/loader.d.ts +12 -0
  158. package/out/labels/street/morphology/fst/loader.d.ts.map +1 -1
  159. package/out/labels/street/morphology/fst/loader.js +18 -2
  160. package/out/labels/street/morphology/fst/loader.js.map +1 -1
  161. package/out/labels/street/normalize.d.ts +8 -0
  162. package/out/labels/street/normalize.d.ts.map +1 -1
  163. package/out/labels/street/normalize.js +24 -4
  164. package/out/labels/street/normalize.js.map +1 -1
  165. package/out/labels/street.d.ts +1 -0
  166. package/out/labels/street.d.ts.map +1 -1
  167. package/out/labels/street.js +1 -0
  168. package/out/labels/street.js.map +1 -1
  169. package/out/landmark.d.ts +15 -3
  170. package/out/landmark.d.ts.map +1 -1
  171. package/out/landmark.js +38 -3
  172. package/out/landmark.js.map +1 -1
  173. package/out/lookup/types.d.ts +21 -5
  174. package/out/lookup/types.d.ts.map +1 -1
  175. package/out/outcome/memberships.d.ts +58 -0
  176. package/out/outcome/memberships.d.ts.map +1 -0
  177. package/out/outcome/memberships.js +83 -0
  178. package/out/outcome/memberships.js.map +1 -0
  179. package/out/outcome/schema.d.ts +74 -0
  180. package/out/outcome/schema.d.ts.map +1 -0
  181. package/out/outcome/schema.js +63 -0
  182. package/out/outcome/schema.js.map +1 -0
  183. package/out/poi/lookup.d.ts +4 -0
  184. package/out/poi/lookup.d.ts.map +1 -1
  185. package/out/poi/lookup.js.map +1 -1
  186. package/out/poi/schema.d.ts +2 -1
  187. package/out/poi/schema.d.ts.map +1 -1
  188. package/out/poi/schema.js.map +1 -1
  189. package/out/ranking/primary-preference.d.ts +9 -5
  190. package/out/ranking/primary-preference.d.ts.map +1 -1
  191. package/out/ranking/primary-preference.js +11 -3
  192. package/out/ranking/primary-preference.js.map +1 -1
  193. package/out/schema/overture-match.d.ts +2 -1
  194. package/out/schema/overture-match.d.ts.map +1 -1
  195. package/out/schema/overture-match.js.map +1 -1
  196. package/package.json +15 -15
@@ -1,9 +1,18 @@
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 { Kysely } from "kysely"
4
+ import type { DatabaseClient } from "@mailwoman/sqlite/client"
5
+ import { type Kysely, sql } from "kysely"
5
6
 
6
- import type { NameKey, RouteKey, StreetKey } from "#labels/street/normalize"
7
+ import { addressPostcodeKey } from "#address/keys/postcode"
8
+ import { canonicalStreetKey } from "#labels/street/canonical"
9
+ import {
10
+ type NameKey,
11
+ type RouteKey,
12
+ type StreetKey,
13
+ streetKeyRulesOf,
14
+ type StreetLocale,
15
+ } from "#labels/street/normalize"
7
16
 
8
17
  /**
9
18
  * One rooftop address point; `(street_norm, number)` within a `postcode`
@@ -51,11 +60,25 @@ export interface AddressPointTable {
51
60
  certified: number | null
52
61
  }
53
62
 
63
+ /**
64
+ * Compact `WITHOUT ROWID` scope-to-street index for `canonical-alias` and scoped `fuzzy-edit1` lookup.
65
+ *
66
+ * Clustered on `(scope_kind, scope, street_canon, street_norm)` so a canonical alias probe is
67
+ * one B-tree seek and a scoped 1-edit scan reads contiguous pages for one postcode or locality.
68
+ */
69
+ export interface StreetScopeIndexTable {
70
+ scope_kind: "postcode" | "locality"
71
+ scope: string
72
+ street_canon: string
73
+ street_norm: StreetKey
74
+ }
75
+
54
76
  /**
55
77
  * The address-point database schema for `new DatabaseClient<AddressPointDatabase>(...)`.
56
78
  */
57
79
  export interface AddressPointDatabase {
58
80
  address_point: AddressPointTable
81
+ street_scope_index?: StreetScopeIndexTable
59
82
  }
60
83
 
61
84
  /**
@@ -64,6 +87,11 @@ export interface AddressPointDatabase {
64
87
  */
65
88
  export type AddressPointSchemaHandle = Pick<Kysely<AddressPointDatabase>, "schema">
66
89
 
90
+ /**
91
+ * The subset of a `DatabaseClient` needed to create and populate `street_scope_index`.
92
+ */
93
+ export type StreetScopeIndexHandle = Pick<DatabaseClient<AddressPointDatabase>, "schema" | "exec" | "function">
94
+
67
95
  /**
68
96
  * The `address_point` columns in insert order, from which the builder derives its positional placeholders.
69
97
  */
@@ -127,3 +155,93 @@ export async function createAddressPointIndexes(db: AddressPointSchemaHandle): P
127
155
  // so the reader scopes a `(street_norm, number)` probe by the resolved locality's bbox.
128
156
  await db.schema.createIndex("idx_ap_street").on("address_point").columns(["street_norm", "number"]).execute()
129
157
  }
158
+
159
+ /**
160
+ * Creates the empty `street_scope_index` `WITHOUT ROWID` table.
161
+ */
162
+ export async function createStreetScopeIndexTable(db: AddressPointSchemaHandle): Promise<void> {
163
+ await db.schema
164
+ .createTable("street_scope_index")
165
+ .addColumn("scope_kind", "text", (c) => c.notNull())
166
+ .addColumn("scope", "text", (c) => c.notNull())
167
+ .addColumn("street_canon", "text", (c) => c.notNull())
168
+ .addColumn("street_norm", "text", (c) => c.notNull())
169
+ .addPrimaryKeyConstraint("street_scope_index_pk", ["scope_kind", "scope", "street_canon", "street_norm"])
170
+ .modifyEnd(sql`without rowid`)
171
+ .execute()
172
+ }
173
+
174
+ /**
175
+ * Creates and populates `street_scope_index` from a table holding `postcode`,
176
+ * `street_raw`, `street_norm`, and `localityColumn`.
177
+ *
178
+ * Postcode scopes are normalized with {@link addressPostcodeKey} so spaced
179
+ * and compact postcodes share one scope key in the index.
180
+ */
181
+ export async function populateStreetScopeIndex(
182
+ db: StreetScopeIndexHandle,
183
+ streetLocale: StreetLocale,
184
+ options: {
185
+ sourceTable: "address_point" | "street_centroid"
186
+ localityColumn: "locality_norm" | "locality_base"
187
+ country?: string
188
+ }
189
+ ): Promise<void> {
190
+ await createStreetScopeIndexTable(db)
191
+
192
+ const rules = streetKeyRulesOf(streetLocale)
193
+ const { sourceTable, localityColumn, country } = options
194
+
195
+ db.function("mw_street_canon", { deterministic: true }, (streetRaw: unknown): string =>
196
+ typeof streetRaw === "string" && streetRaw ? canonicalStreetKey(streetRaw, streetLocale).key : ""
197
+ )
198
+
199
+ db.function("mw_postcode_scope", { deterministic: true }, (postcode: unknown): string => {
200
+ if (typeof postcode !== "string") return ""
201
+
202
+ return (country ? addressPostcodeKey(country, postcode) : rules.postcodeKey(postcode)) ?? ""
203
+ })
204
+
205
+ db.exec(`
206
+ INSERT OR IGNORE INTO street_scope_index (scope_kind, scope, street_canon, street_norm)
207
+ SELECT scope_kind, scope, street_canon, street_norm FROM (
208
+ SELECT 'postcode' AS scope_kind,
209
+ mw_postcode_scope(postcode) AS scope,
210
+ mw_street_canon(street_raw) AS street_canon,
211
+ street_norm
212
+ FROM (
213
+ SELECT DISTINCT postcode, street_raw, street_norm
214
+ FROM ${sourceTable}
215
+ WHERE postcode IS NOT NULL AND postcode != ''
216
+ )
217
+ UNION ALL
218
+ SELECT 'locality' AS scope_kind,
219
+ ${localityColumn} AS scope,
220
+ mw_street_canon(street_raw) AS street_canon,
221
+ street_norm
222
+ FROM (
223
+ SELECT DISTINCT ${localityColumn}, street_raw, street_norm
224
+ FROM ${sourceTable}
225
+ WHERE ${localityColumn} IS NOT NULL AND ${localityColumn} != ''
226
+ )
227
+ )
228
+ WHERE scope != '' AND street_canon != ''
229
+ ORDER BY scope_kind, scope, street_canon, street_norm
230
+ `)
231
+ }
232
+
233
+ /**
234
+ * Creates and populates `street_scope_index` from distinct `(postcode, street_raw, street_norm)`
235
+ * and `(locality_norm, street_raw, street_norm)` tuples in `address_point`.
236
+ */
237
+ export async function createStreetScopeIndex(
238
+ db: StreetScopeIndexHandle,
239
+ streetLocale: StreetLocale,
240
+ options?: { country?: string }
241
+ ): Promise<void> {
242
+ await populateStreetScopeIndex(db, streetLocale, {
243
+ sourceTable: "address_point",
244
+ localityColumn: "locality_norm",
245
+ ...options,
246
+ })
247
+ }
@@ -0,0 +1,179 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Postcode scope normalization and `street_scope_index` search helpers for `AddressPointSqliteLookup`.
6
+ *
7
+ * Kept beside `point.ts` so postcode spacing normalization, `canonical-alias` lookup,
8
+ * and scoped `fuzzy-edit1` lookup stay isolated and testable.
9
+ */
10
+
11
+ import type { DatabaseClient } from "@mailwoman/sqlite/client"
12
+
13
+ import {
14
+ canonicalStreetKey,
15
+ findFuzzyEdit1Streets,
16
+ FUZZY_SCOPE_ROW_LIMIT,
17
+ MIN_FUZZY_CORE_LENGTH,
18
+ } from "#labels/street/canonical"
19
+ import { type StreetKey, streetKeyRulesOf, type StreetLocale } from "#labels/street/normalize"
20
+ import { hasTable, prepareAll, type PreparedAll } from "#sqlite-utils"
21
+
22
+ /**
23
+ * Computes the normalized postcode scope key for `postcode` under `locale`
24
+ * (uppercased with whitespace stripped, and ZIP+4 reduced to 5 digits for `us`).
25
+ */
26
+ export function postcodeScopeKey(postcode: string | null | undefined, locale: StreetLocale): string | null {
27
+ return streetKeyRulesOf(locale).postcodeKey(postcode)
28
+ }
29
+
30
+ /**
31
+ * Returns the postcode strings to probe in `address_point`: the trimmed
32
+ * written value first, followed by the compact normalized key when it differs
33
+ * (such as `"4413 ND"` → `"4413ND"` or `"SW1A 1AA"` → `"SW1A1AA"`).
34
+ */
35
+ export function postcodeProbeForms(postcode: string, locale: StreetLocale): string[] {
36
+ const raw = postcode.trim()
37
+
38
+ if (!raw) return []
39
+
40
+ const compact = postcodeScopeKey(raw, locale)
41
+
42
+ return compact && compact !== raw ? [raw, compact] : [raw]
43
+ }
44
+
45
+ /**
46
+ * Reports whether a stored row postcode and a queried postcode normalize to
47
+ * the same postcode key under `locale`.
48
+ */
49
+ export function postcodesAgree(stored: string, queried: string, locale: StreetLocale): boolean {
50
+ return postcodeScopeKey(stored, locale) === postcodeScopeKey(queried, locale)
51
+ }
52
+
53
+ /**
54
+ * Prepared statements over `street_scope_index`, opened once when the table exists.
55
+ */
56
+ export interface StreetScopeIndexQueries {
57
+ byCanon: PreparedAll<
58
+ [scopeKind: "postcode" | "locality", scope: string, streetCanon: string],
59
+ { street_norm: StreetKey }
60
+ >
61
+ byScope: PreparedAll<
62
+ [scopeKind: "postcode" | "locality", scope: string],
63
+ { street_canon: string; street_norm: StreetKey }
64
+ >
65
+ }
66
+
67
+ /**
68
+ * Prepares the `street_scope_index` statements if the open database contains that table,
69
+ * or returns `null` for legacy extracts built without it.
70
+ */
71
+ export function prepareStreetScopeIndexQueries<DB>(db: DatabaseClient<DB>): StreetScopeIndexQueries | null {
72
+ if (!hasTable(db, "street_scope_index")) return null
73
+
74
+ return {
75
+ byCanon: prepareAll(
76
+ db,
77
+ "SELECT street_norm FROM street_scope_index WHERE scope_kind = ? AND scope = ? AND street_canon = ?"
78
+ ),
79
+ byScope: prepareAll(
80
+ db,
81
+ `SELECT street_canon, street_norm FROM street_scope_index WHERE scope_kind = ? AND scope = ? LIMIT ${FUZZY_SCOPE_ROW_LIMIT + 1}`
82
+ ),
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Result of a Step 2 (`canonical-alias`) or Step 3 (`fuzzy-edit1`) match through `street_scope_index`.
88
+ */
89
+ export interface ScopedStreetMatch<Hit> {
90
+ hit: Hit
91
+ matchedStreet: StreetKey
92
+ streetMatch: "canonical-alias" | "fuzzy-edit1"
93
+ }
94
+
95
+ /**
96
+ * Runs Step 2 (`canonical-alias`) and Step 3 (`fuzzy-edit1`) over `street_scope_index`
97
+ * after Step 1 exact lookup missed.
98
+ *
99
+ * Step 2 issues one B-tree seek per available scope on `(scope_kind, scope, street_canon)`.
100
+ * Step 3 scans contiguous scope rows up to {@link FUZZY_SCOPE_ROW_LIMIT},
101
+ * filters candidates by thoroughfare class and 1-edit Damerau-Levenshtein distance
102
+ * on the core (length `>= 5`), confirms the exact house number via `probeInScope`,
103
+ * and abstains unless exactly one distinct `street_norm` confirms.
104
+ */
105
+ export function searchStreetScopeIndex<Hit>(params: {
106
+ queries: StreetScopeIndexQueries
107
+ streetRaw: string
108
+ locale: StreetLocale
109
+ tried: ReadonlySet<string>
110
+ postcodeScope: string | null
111
+ localityScope: string | null
112
+ probeInScope: (scopeKind: "postcode" | "locality", streetNorm: StreetKey) => Hit | null
113
+ }): ScopedStreetMatch<Hit> | null {
114
+ const { queries, streetRaw, locale, tried, postcodeScope, localityScope, probeInScope } = params
115
+ const canon = canonicalStreetKey(streetRaw, locale)
116
+
117
+ if (!canon.key) return null
118
+
119
+ const scopes: Array<{ kind: "postcode" | "locality"; scope: string }> = []
120
+
121
+ if (postcodeScope) {
122
+ scopes.push({ kind: "postcode", scope: postcodeScope })
123
+ }
124
+
125
+ if (localityScope) {
126
+ scopes.push({ kind: "locality", scope: localityScope })
127
+ }
128
+
129
+ if (!scopes.length) return null
130
+
131
+ // Step 2: canonical-alias via one B-tree seek per scope.
132
+ for (const { kind, scope } of scopes) {
133
+ const aliasRows = queries.byCanon(kind, scope, canon.key)
134
+
135
+ for (const { street_norm: streetNorm } of aliasRows) {
136
+ if (tried.has(streetNorm)) continue
137
+
138
+ const hit = probeInScope(kind, streetNorm)
139
+
140
+ if (hit) {
141
+ return { hit, matchedStreet: streetNorm, streetMatch: "canonical-alias" }
142
+ }
143
+ }
144
+ }
145
+
146
+ // Step 3: scoped 1-edit fuzzy recovery, unique confirmed street only.
147
+ if (canon.core.length < MIN_FUZZY_CORE_LENGTH) return null
148
+
149
+ for (const { kind, scope } of scopes) {
150
+ const scopeRows = queries.byScope(kind, scope)
151
+ const candidates = findFuzzyEdit1Streets(canon, scopeRows)
152
+
153
+ if (!candidates.length) continue
154
+
155
+ let unique: { hit: Hit; matchedStreet: StreetKey } | null = null
156
+ let confirmedCount = 0
157
+
158
+ for (const candidate of candidates) {
159
+ const streetNorm = candidate as StreetKey
160
+ const hit = probeInScope(kind, streetNorm)
161
+
162
+ if (!hit) continue
163
+
164
+ confirmedCount++
165
+
166
+ if (confirmedCount > 1) {
167
+ return null
168
+ }
169
+
170
+ unique = { hit, matchedStreet: streetNorm }
171
+ }
172
+
173
+ if (confirmedCount === 1 && unique) {
174
+ return { hit: unique.hit, matchedStreet: unique.matchedStreet, streetMatch: "fuzzy-edit1" }
175
+ }
176
+ }
177
+
178
+ return null
179
+ }
@@ -5,14 +5,25 @@
5
5
  * @file SQLite implementation of core's `AddressPointLookup`.
6
6
  */
7
7
 
8
- import type { AddressPointHit, AddressPointLookup } from "@mailwoman/core/resolver"
8
+ import type { AddressPointHit, AddressPointLookup, StreetMatchKind } from "@mailwoman/core/resolver"
9
+ import { allRows } from "@mailwoman/core/utils"
10
+ import { haversine, shortCellToInt } from "@mailwoman/spatial"
9
11
  import { latLonBoundsContain } from "@mailwoman/spatial/bbox"
10
12
  import { DatabaseClient } from "@mailwoman/sqlite/client"
11
13
  import { indexExists } from "@mailwoman/sqlite/introspection"
14
+ import { gridDisk, latLngToCell } from "@sister.software/h3"
12
15
  import type { PathBuilderLike } from "path-ts"
13
16
 
14
- import { houseNumberForms } from "#address/number-forms"
17
+ import { type HouseNumberForm, houseNumberForms } from "#address/number-forms"
15
18
  import type { AddressPointDatabase, AddressPointTable } from "#address/point/schema"
19
+ import {
20
+ postcodeProbeForms,
21
+ postcodesAgree,
22
+ postcodeScopeKey,
23
+ prepareStreetScopeIndexQueries,
24
+ searchStreetScopeIndex,
25
+ type StreetScopeIndexQueries,
26
+ } from "#address/point/scope-search"
16
27
  import {
17
28
  normalizeHouseNumberForKey,
18
29
  type NameKey,
@@ -38,6 +49,21 @@ type AddressPointRow = Pick<AddressPointTable, "lat" | "lon" | "source" | "relea
38
49
  */
39
50
  const SELECT_COLS = "lat, lon, source, release, locality_norm, postcode"
40
51
 
52
+ /**
53
+ * H3 resolution stored in `address_point.h3_cell` by the layer sealing step.
54
+ */
55
+ const ADDRESS_POINT_H3_RESOLUTION = 9
56
+
57
+ /**
58
+ * Cell count of a hexagonal H3 1-ring (the center cell plus its six neighbors).
59
+ */
60
+ const H3_RING_1_CELL_COUNT = 7
61
+
62
+ /**
63
+ * Default search radius in meters when checking whether a street runs past a coordinate.
64
+ */
65
+ const DEFAULT_STREET_NEAR_RADIUS_M = 200
66
+
41
67
  /**
42
68
  * Finds an address point by exact normalized `(street, number)` within a postcode,
43
69
  * a locality, or a bounding box.
@@ -78,6 +104,8 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
78
104
  | PreparedGet<[street: StreetKey, number: string, tailPattern: string], AddressPointRow>
79
105
  | undefined
80
106
  readonly #hasStreetIndex: boolean = false
107
+ readonly #scopeIndex: StreetScopeIndexQueries | null = null
108
+ readonly #byH3Street: ReturnType<DatabaseClient<DB>["prepare"]> | undefined
81
109
  readonly #byBbox:
82
110
  | PreparedGet<
83
111
  [street: StreetKey, number: string, minLat: number, maxLat: number, minLon: number, maxLon: number],
@@ -147,6 +175,13 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
147
175
 
148
176
  this.#hasStreetIndex = indexExists(this.#db, "idx_ap_street")
149
177
 
178
+ if (indexExists(this.#db, "idx_ap_h3")) {
179
+ // The unary `+` keeps SQLite on `idx_ap_h3` rather than scanning a high-cardinality street name.
180
+ this.#byH3Street = this.#db.prepare(
181
+ "SELECT lat, lon FROM address_point WHERE h3_cell IN (?, ?, ?, ?, ?, ?, ?) AND +street_norm = ?"
182
+ )
183
+ }
184
+
150
185
  this.#byBbox = prepareGet(
151
186
  this.#db,
152
187
  `SELECT ${SELECT_COLS} FROM address_point
@@ -158,6 +193,8 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
158
193
  `SELECT ${SELECT_COLS} FROM address_point
159
194
  WHERE street_norm = ? AND number = ? AND locality_norm LIKE ? LIMIT 1`
160
195
  )
196
+
197
+ this.#scopeIndex = prepareStreetScopeIndexQueries(this.#db)
161
198
  }
162
199
  }
163
200
 
@@ -186,27 +223,140 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
186
223
  : { ...query, localityTail: this.#rules.localityKey(query.subregion) }
187
224
  : query
188
225
 
189
- // `streetKeyVariants` yields the literal key first.
190
- // Each variant runs the full number fallback sequence.
191
- // The first variant with a match wins.
192
- let row: AddressPointRow | null = null
226
+ // Step 1: exact / existing streetKeyVariants (zero overhead on exact hits).
227
+ const surfaceLocale = streetLocaleForSurface(query.street, this.#locale)
228
+ const variants = streetKeyVariants(query.street, surfaceLocale)
193
229
 
194
- for (const streetNorm of streetKeyVariants(query.street, streetLocaleForSurface(query.street, this.#locale))) {
195
- row = this.#findForKey(streetNorm, number, scoped)
230
+ let found: {
231
+ row: AddressPointRow
232
+ form: HouseNumberForm
233
+ matchedStreet: StreetKey
234
+ streetMatch: StreetMatchKind
235
+ } | null = null
236
+
237
+ for (let i = 0; i < variants.length; i++) {
238
+ const streetNorm = variants[i]!
239
+ const hit = this.#findForKey(streetNorm, number, scoped)
240
+
241
+ if (hit) {
242
+ found = { ...hit, matchedStreet: streetNorm, streetMatch: i === 0 ? "written" : "respelled" }
243
+
244
+ break
245
+ }
246
+ }
196
247
 
197
- if (row) break
248
+ // Steps 2 & 3: canonical-alias and scoped 1-edit fuzzy recovery via `street_scope_index`.
249
+ if (!found && this.#scopeIndex) {
250
+ const postcodeScope = scoped.postcode ? postcodeScopeKey(scoped.postcode, this.#locale) : null
251
+ const localityScope = scoped.locality ? this.#localityKey(scoped.locality) : null
252
+
253
+ const recovered = searchStreetScopeIndex({
254
+ queries: this.#scopeIndex,
255
+ streetRaw: query.street,
256
+ locale: surfaceLocale,
257
+ tried: new Set(variants),
258
+ postcodeScope,
259
+ localityScope,
260
+ probeInScope: (scopeKind, streetNorm) => this.#findForKeyInScope(scopeKind, streetNorm, number, scoped),
261
+ })
262
+
263
+ if (recovered) {
264
+ found = {
265
+ ...recovered.hit,
266
+ matchedStreet: recovered.matchedStreet,
267
+ streetMatch: recovered.streetMatch,
268
+ }
269
+ }
198
270
  }
199
271
 
200
- if (!row) return null
272
+ if (!found) return null
201
273
 
202
274
  return {
203
- lat: row.lat,
204
- lon: row.lon,
205
- source: row.source,
206
- release: row.release,
207
- localityNorm: row.locality_norm || null,
208
- postcode: row.postcode || null,
275
+ lat: found.row.lat,
276
+ lon: found.row.lon,
277
+ source: found.row.source,
278
+ release: found.row.release,
279
+ localityNorm: found.row.locality_norm || null,
280
+ postcode: found.row.postcode || null,
281
+ matchedNumber: found.form.number,
282
+ numberMatch: found.form.match,
283
+ matchedStreet: found.matchedStreet,
284
+ streetMatch: found.streetMatch,
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Probes one candidate street within a single scope (`postcode` or `locality`) using
290
+ * `houseNumberForms`, for Step 2 (`canonical-alias`) and Step 3 (`fuzzy-edit1`) confirmation.
291
+ */
292
+ #findForKeyInScope(
293
+ scopeKind: "postcode" | "locality",
294
+ streetNorm: StreetKey,
295
+ number: string,
296
+ query: {
297
+ street: string
298
+ number: string
299
+ postcode?: string
300
+ locality?: string
301
+ localityTail?: NameKey
302
+ bbox: { minLat: number; maxLat: number; minLon: number; maxLon: number } | null
303
+ }
304
+ ): { row: AddressPointRow; form: HouseNumberForm } | null {
305
+ for (const form of houseNumberForms(number, this.#locale)) {
306
+ const row =
307
+ scopeKind === "postcode"
308
+ ? this.#probePostcodeScope(streetNorm, form.number, query)
309
+ : this.#probeLocalityScope(streetNorm, form.number, query)
310
+
311
+ if (row) return { row, form }
312
+ }
313
+
314
+ return null
315
+ }
316
+
317
+ #probePostcodeScope(
318
+ streetNorm: StreetKey,
319
+ number: string,
320
+ query: {
321
+ postcode?: string
322
+ locality?: string
323
+ bbox: { minLat: number; maxLat: number; minLon: number; maxLon: number } | null
209
324
  }
325
+ ): AddressPointRow | null {
326
+ if (!query.postcode) return null
327
+
328
+ const localityKey = query.locality ? this.#localityKey(query.locality) : null
329
+ let heldBack: AddressPointRow | null = null
330
+
331
+ for (const postcode of postcodeProbeForms(query.postcode, this.#locale)) {
332
+ const agreeing = localityKey ? this.#byPostcodeLocality!(postcode, localityKey, streetNorm, number) : null
333
+ const candidate = agreeing ?? this.#byPostcode!(postcode, streetNorm, number)
334
+
335
+ if (candidate && !this.#scopeContradicts(candidate, query)) {
336
+ return candidate
337
+ }
338
+
339
+ if (!heldBack && candidate && this.#isSublocalityRow(candidate, postcode, streetNorm, number, query.bbox)) {
340
+ heldBack = candidate
341
+ }
342
+ }
343
+
344
+ return heldBack
345
+ }
346
+
347
+ #probeLocalityScope(
348
+ streetNorm: StreetKey,
349
+ number: string,
350
+ query: {
351
+ postcode?: string
352
+ locality?: string
353
+ }
354
+ ): AddressPointRow | null {
355
+ if (!query.locality) return null
356
+
357
+ const candidate = this.#byLocality!(this.#localityKey(query.locality), streetNorm, number)
358
+
359
+ return candidate && !this.#scopeContradicts(candidate, query) ? candidate : null
210
360
  }
211
361
 
212
362
  /**
@@ -224,11 +374,11 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
224
374
  localityTail?: NameKey
225
375
  bbox: { minLat: number; maxLat: number; minLon: number; maxLon: number } | null
226
376
  }
227
- ) {
377
+ ): { row: AddressPointRow; form: HouseNumberForm } | null {
228
378
  for (const form of houseNumberForms(number, this.#locale)) {
229
- const row = this.#probe(streetNorm, form, query)
379
+ const row = this.#probe(streetNorm, form.number, query)
230
380
 
231
- if (row) return row
381
+ if (row) return { row, form }
232
382
  }
233
383
 
234
384
  return null
@@ -253,19 +403,25 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
253
403
  let heldBack: AddressPointRow | null = null
254
404
 
255
405
  if (query.postcode) {
256
- const postcode = query.postcode.trim()
257
406
  const localityKey = query.locality ? this.#localityKey(query.locality) : null
258
407
 
259
408
  // One postcode can cover several places with the same street and number,
260
409
  // so a row whose locality agrees with the query is tried first.
410
+ // Probe both raw trimmed and compact normalized forms (`4413 ND` → `4413ND`).
261
411
  // The postcode-only row answers only if `#scopeContradicts` accepts it.
262
- const agreeing = localityKey ? this.#byPostcodeLocality!(postcode, localityKey, streetNorm, number) : null
263
- const candidate = agreeing ?? this.#byPostcode!(postcode, streetNorm, number)
412
+ for (const postcode of postcodeProbeForms(query.postcode, this.#locale)) {
413
+ const agreeing = localityKey ? this.#byPostcodeLocality!(postcode, localityKey, streetNorm, number) : null
414
+ const candidate = agreeing ?? this.#byPostcode!(postcode, streetNorm, number)
264
415
 
265
- if (candidate && !this.#scopeContradicts(candidate, query)) {
266
- row = candidate
267
- } else if (candidate && this.#isSublocalityRow(candidate, postcode, streetNorm, number, query.bbox)) {
268
- heldBack = candidate
416
+ if (candidate && !this.#scopeContradicts(candidate, query)) {
417
+ row = candidate
418
+
419
+ break
420
+ }
421
+
422
+ if (!heldBack && candidate && this.#isSublocalityRow(candidate, postcode, streetNorm, number, query.bbox)) {
423
+ heldBack = candidate
424
+ }
269
425
  }
270
426
  }
271
427
 
@@ -319,7 +475,7 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
319
475
  * name that OSM's `addr:city` records, and a word boundary keeps `lauta` apart from `lautabach`.
320
476
  */
321
477
  #scopeContradicts(row: AddressPointRow, query: { postcode?: string; locality?: string }): boolean {
322
- if (query.postcode && row.postcode && row.postcode.trim() !== query.postcode.trim()) return true
478
+ if (query.postcode && row.postcode && !postcodesAgree(row.postcode, query.postcode, this.#locale)) return true
323
479
 
324
480
  if (this.#localityKeys === "full" && query.locality && row.locality_norm) {
325
481
  const queryKey = this.#localityKey(query.locality)
@@ -356,7 +512,7 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
356
512
  ): boolean {
357
513
  if (this.#localityLevel !== "finest") return false
358
514
 
359
- if (row.postcode && row.postcode.trim() !== postcode) return false
515
+ if (row.postcode && !postcodesAgree(row.postcode, postcode, this.#locale)) return false
360
516
 
361
517
  if ((this.#postcodeKeyPlaces?.(postcode, streetNorm, number)?.places ?? 0) !== 1) return false
362
518
 
@@ -365,6 +521,47 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
365
521
  return latLonBoundsContain(bbox, row.lat, row.lon)
366
522
  }
367
523
 
524
+ /**
525
+ * Reports whether `query.street` sits within `query.radiusM` m of the point.
526
+ *
527
+ * Returns `false` when the extract lacks `idx_ap_h3`.
528
+ * An unindexed database therefore never falls back to a table scan.
529
+ */
530
+ hasStreetNear(query: { street: string; lat: number; lon: number; radiusM?: number }): boolean {
531
+ if (!this.#byH3Street) return false
532
+
533
+ const radiusM = query.radiusM ?? DEFAULT_STREET_NEAR_RADIUS_M
534
+ const disk = gridDisk(latLngToCell(query.lat, query.lon, ADDRESS_POINT_H3_RESOLUTION), 1).map(shortCellToInt)
535
+
536
+ if (!disk.length) return false
537
+
538
+ // A 1-ring around a pentagon holds 6 cells rather than 7.
539
+ // The loop pads with the center cell so one prepared statement serves every query.
540
+ while (disk.length < H3_RING_1_CELL_COUNT) {
541
+ disk.push(disk[0]!)
542
+ }
543
+
544
+ for (const streetNorm of streetKeyVariants(query.street, streetLocaleForSurface(query.street, this.#locale))) {
545
+ const rows = allRows<{ lat: number; lon: number }>(
546
+ this.#byH3Street,
547
+ disk[0]!,
548
+ disk[1]!,
549
+ disk[2]!,
550
+ disk[3]!,
551
+ disk[4]!,
552
+ disk[5]!,
553
+ disk[6]!,
554
+ streetNorm
555
+ )
556
+
557
+ if (rows.some((row) => haversine(query.lat, query.lon, row.lat, row.lon) * 1000 <= radiusM)) {
558
+ return true
559
+ }
560
+ }
561
+
562
+ return false
563
+ }
564
+
368
565
  [Symbol.dispose](): void {
369
566
  this.#db[Symbol.dispose]()
370
567
  }