@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
@@ -33,6 +33,7 @@ import {
33
33
  import { addressPostcodeKey } from "#address/keys/postcode"
34
34
  import {
35
35
  ADDRESS_SCOPED_KEY_TABLES,
36
+ ADDRESS_STREET_ALIAS_TABLES,
36
37
  ADDRESS_STREET_TABLES,
37
38
  type AddressDetailDatabase,
38
39
  type AddressLookupDatabase,
@@ -41,10 +42,13 @@ import {
41
42
  createAddressRegionKeyTable,
42
43
  createAddressScopedKeyTable,
43
44
  createAddressSourceTable,
45
+ createAddressStreetAliasTable,
44
46
  createAddressStreetTable,
45
47
  } from "#address/keys/schema"
46
48
  import type { AddressRecord } from "#address/record"
47
49
  import { addressPointStacksSQL } from "#address/stack"
50
+ import { canonicalStreetKey } from "#labels/street/canonical"
51
+ import { streetLocaleForCountry } from "#labels/street/locale"
48
52
 
49
53
  /**
50
54
  * The SQLite page size of both files.
@@ -646,10 +650,22 @@ async function writeLookup(
646
650
  for (const table of ADDRESS_STREET_TABLES) {
647
651
  await createAddressStreetTable(db, table)
648
652
  }
653
+
654
+ for (const table of ADDRESS_STREET_ALIAS_TABLES) {
655
+ await createAddressStreetAliasTable(db, table)
656
+ }
649
657
  },
650
658
  ingest: async (db) => {
651
659
  db.exec(`ATTACH DATABASE '${stagingPath.replaceAll("'", "''")}' AS staged`)
652
660
 
661
+ db.function("canonical_street_key", { deterministic: true }, (streetRaw: unknown, country: unknown): string => {
662
+ if (typeof streetRaw !== "string" || !streetRaw) return ""
663
+
664
+ const locale = streetLocaleForCountry(typeof country === "string" ? country : "")
665
+
666
+ return canonicalStreetKey(streetRaw, locale).key
667
+ })
668
+
653
669
  const insertSource = db.prepare("INSERT INTO source VALUES (?, ?, ?, ?, ?)")
654
670
 
655
671
  const ids = db.prepare("SELECT name, source_id FROM staged.source_ids ORDER BY source_id").all() as Array<{
@@ -687,6 +703,25 @@ async function writeLookup(
687
703
  )
688
704
  }
689
705
 
706
+ for (const [table, level] of [
707
+ ["street_alias_postcode", "key_postcode"],
708
+ ["street_alias_locality", "key_locality"],
709
+ ] as const) {
710
+ db.exec(
711
+ `INSERT OR IGNORE INTO ${table} (scope, street_canon, street)
712
+ SELECT scope, street_canon, street FROM (
713
+ SELECT scope, canonical_street_key(street_raw, country) AS street_canon, street
714
+ FROM (
715
+ SELECT DISTINCT s.scope, s.street, a.street_raw, a.country
716
+ FROM staged.stage s JOIN staged.address a USING (address_id)
717
+ WHERE s.level = '${level}'
718
+ )
719
+ )
720
+ WHERE street_canon != ''
721
+ ORDER BY scope, street_canon, street`
722
+ )
723
+ }
724
+
690
725
  db.exec("DETACH DATABASE staged")
691
726
 
692
727
  return true
@@ -10,8 +10,18 @@
10
10
  * so the three runtimes share one read order.
11
11
  */
12
12
 
13
+ import { memoizeResettable } from "@mailwoman/core/async/memoize"
14
+ import type { NumberMatchKind, StreetMatchKind } from "@mailwoman/core/resolver"
15
+
13
16
  import { addressPostcodeKey } from "#address/keys/postcode"
14
17
  import { houseNumberForms } from "#address/number-forms"
18
+ import {
19
+ canonicalStreetKey,
20
+ findFuzzyEdit1Streets,
21
+ FUZZY_SCOPE_ROW_LIMIT,
22
+ MIN_FUZZY_CORE_LENGTH,
23
+ type ScopedStreetAliasRow,
24
+ } from "#labels/street/canonical"
15
25
  import { streetLocaleForCountry } from "#labels/street/locale"
16
26
  import {
17
27
  normalizeHouseNumberForKey,
@@ -51,6 +61,21 @@ export interface AddressKeyHit {
51
61
  level: AddressKeyLevel
52
62
  }
53
63
 
64
+ /**
65
+ * One precomputed street aggregate row from `street_postcode` or `street_locality`.
66
+ */
67
+ export interface AddressStreetHit {
68
+ lat: number
69
+ lon: number
70
+ minLat: number
71
+ maxLat: number
72
+ minLon: number
73
+ maxLon: number
74
+ points: number
75
+ level: typeof AddressKeyLevel.Postcode | typeof AddressKeyLevel.Locality
76
+ matchedStreet: string
77
+ }
78
+
54
79
  /**
55
80
  * What a parse resolved, in the encoder's terms.
56
81
  */
@@ -75,6 +100,22 @@ export interface AddressKeyQuery {
75
100
  export interface AddressKeyAnswer {
76
101
  level: AddressKeyLevel
77
102
  hits: AddressKeyHit[]
103
+ /**
104
+ * The stored house-number key that answered.
105
+ */
106
+ matchedNumber: string
107
+ /**
108
+ * How {@link matchedNumber} relates to the query's normalized house number.
109
+ */
110
+ numberMatch: NumberMatchKind
111
+ /**
112
+ * The stored street key that answered.
113
+ */
114
+ matchedStreet: string
115
+ /**
116
+ * How {@link matchedStreet} relates to the query's primary normalized street key.
117
+ */
118
+ streetMatch: StreetMatchKind
78
119
  }
79
120
 
80
121
  export interface AddressKeyLookupOptions {
@@ -98,9 +139,22 @@ interface KeyRow {
98
139
  source_id: number
99
140
  }
100
141
 
142
+ interface StreetRow {
143
+ lat: number
144
+ lon: number
145
+ min_lat: number
146
+ max_lat: number
147
+ min_lon: number
148
+ max_lon: number
149
+ points: number
150
+ }
151
+
101
152
  const SELECT_SCOPED = (table: string, cap: number) =>
102
153
  `SELECT lat, lon, address_id, source_id FROM ${table} WHERE scope = ? AND street = ? AND number = ? LIMIT ${cap}`
103
154
 
155
+ const SELECT_STREET = (table: "street_postcode" | "street_locality") =>
156
+ `SELECT lat, lon, min_lat, max_lat, min_lon, max_lon, points FROM ${table} WHERE scope = ? AND street = ? LIMIT 1`
157
+
104
158
  /**
105
159
  * Finds address points by the most precise level a parse states: postcode,
106
160
  * then each locality name, then the subregion, then the file's whole region.
@@ -115,6 +169,20 @@ export class AddressKeyLookup {
115
169
  readonly #locale: StreetLocale
116
170
  readonly #cap: number
117
171
 
172
+ /**
173
+ * Checks once (lazily, on the first exact miss) which alias and street-aggregate
174
+ * tables exist in `lookup.db`, so legacy files built without `street_alias_*` keep
175
+ * answering without throwing and exact Step 1 hits issue zero extra queries.
176
+ */
177
+ readonly #optionalTables = memoizeResettable(async (): Promise<ReadonlySet<string>> => {
178
+ const rows = await this.#runner.query<{ name: string }>(
179
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('street_alias_postcode', 'street_alias_locality', 'street_postcode', 'street_locality')",
180
+ []
181
+ )
182
+
183
+ return new Set(rows.map((row) => String(row.name)))
184
+ })
185
+
118
186
  constructor(runner: AddressStatementRunner, options: AddressKeyLookupOptions) {
119
187
  this.#runner = runner
120
188
  this.#country = options.country.toUpperCase()
@@ -130,22 +198,248 @@ export class AddressKeyLookup {
130
198
 
131
199
  if (!number) return null
132
200
 
133
- // Every street variant runs every number form, and every form runs the level ladder,
134
- // so the literal street and written number answer first.
135
- for (const street of streetKeyVariants(query.street, streetLocaleForSurface(query.street, this.#locale))) {
201
+ const surfaceLocale = streetLocaleForSurface(query.street, this.#locale)
202
+ const variants = streetKeyVariants(query.street, surfaceLocale)
203
+
204
+ // Step 1: exact / existing streetKeyVariants (zero extra queries on exact hits).
205
+ for (let i = 0; i < variants.length; i++) {
206
+ const street = variants[i]!
207
+
136
208
  if (!street) continue
137
209
 
138
210
  for (const form of houseNumberForms(number, this.#locale)) {
139
- const answer = await this.#ladder(query, street, form)
211
+ const answer = await this.#ladder(query, street, form.number)
212
+
213
+ if (answer) {
214
+ return {
215
+ ...answer,
216
+ matchedNumber: form.number,
217
+ numberMatch: form.match,
218
+ matchedStreet: street,
219
+ streetMatch: i === 0 ? "written" : "respelled",
220
+ }
221
+ }
222
+ }
223
+ }
224
+
225
+ const canon = canonicalStreetKey(query.street, surfaceLocale)
226
+
227
+ if (!canon.key) return null
228
+
229
+ const scopes = this.#aliasScopes(query)
230
+
231
+ if (!scopes.length) return null
232
+
233
+ const tables = await this.#optionalTables()
234
+ const tried = new Set<string>(variants)
235
+
236
+ // Step 2: canonical-alias via one B-tree seek on `street_alias_postcode` / `street_alias_locality`.
237
+ for (const scope of scopes) {
238
+ if (!tables.has(scope.aliasTable)) continue
239
+
240
+ const aliasRows = await this.#runner.query<{ street: string }>(
241
+ `SELECT street FROM ${scope.aliasTable} WHERE scope = ? AND street_canon = ?`,
242
+ [scope.value, canon.key]
243
+ )
244
+
245
+ for (const { street } of aliasRows) {
246
+ if (tried.has(street)) continue
247
+
248
+ const hit = await this.#probeScopedNumberForms(scope.keyTable, scope.level, scope.value, street, number)
249
+
250
+ if (hit) {
251
+ return { ...hit, matchedStreet: street, streetMatch: "canonical-alias" }
252
+ }
253
+ }
254
+ }
255
+
256
+ // Step 3: scoped 1-edit fuzzy recovery, unique confirmed street only.
257
+ if (canon.core.length < MIN_FUZZY_CORE_LENGTH) return null
258
+
259
+ for (const scope of scopes) {
260
+ let scopeRows: ScopedStreetAliasRow[]
261
+
262
+ if (tables.has(scope.aliasTable)) {
263
+ scopeRows = await this.#runner.query<ScopedStreetAliasRow>(
264
+ `SELECT street_canon, street AS street_norm FROM ${scope.aliasTable} WHERE scope = ? LIMIT ${FUZZY_SCOPE_ROW_LIMIT + 1}`,
265
+ [scope.value]
266
+ )
267
+ } else if (tables.has(scope.streetTable)) {
268
+ const rawRows = await this.#runner.query<{ street: string }>(
269
+ `SELECT street FROM ${scope.streetTable} WHERE scope = ? LIMIT ${FUZZY_SCOPE_ROW_LIMIT + 1}`,
270
+ [scope.value]
271
+ )
272
+
273
+ scopeRows = rawRows.map((row) => ({
274
+ street_canon: canonicalStreetKey(row.street, surfaceLocale).key,
275
+ street_norm: row.street,
276
+ }))
277
+ } else {
278
+ continue
279
+ }
280
+
281
+ const candidates = findFuzzyEdit1Streets(canon, scopeRows)
282
+
283
+ if (!candidates.length) continue
284
+
285
+ let unique: (Omit<AddressKeyAnswer, "matchedStreet" | "streetMatch"> & { matchedStreet: string }) | null = null
286
+ let confirmedCount = 0
287
+
288
+ for (const candidate of candidates) {
289
+ const hit = await this.#probeScopedNumberForms(scope.keyTable, scope.level, scope.value, candidate, number)
290
+
291
+ if (!hit) continue
292
+
293
+ confirmedCount++
140
294
 
141
- if (answer) return answer
295
+ if (confirmedCount > 1) return null
296
+
297
+ unique = { ...hit, matchedStreet: candidate }
298
+ }
299
+
300
+ if (confirmedCount === 1 && unique) {
301
+ return { ...unique, streetMatch: "fuzzy-edit1" }
142
302
  }
143
303
  }
144
304
 
145
305
  return null
146
306
  }
147
307
 
148
- async #ladder(query: AddressKeyQuery, street: string, number: string): Promise<AddressKeyAnswer | null> {
308
+ /**
309
+ * Finds the precomputed street aggregate row inside a postcode or locality.
310
+ *
311
+ * When `query.postcode` is supplied, only `street_postcode` is queried.
312
+ * When `query.postcode` is absent, `street_locality` is queried for each locality.
313
+ */
314
+ async findStreet(query: {
315
+ street: string
316
+ postcode?: string | null
317
+ localities?: readonly string[]
318
+ }): Promise<AddressStreetHit | null> {
319
+ const postcodeRaw = query.postcode?.trim() || null
320
+ const postcode = postcodeRaw ? addressPostcodeKey(this.#country, postcodeRaw) : ""
321
+
322
+ const localities = (query.localities ?? [])
323
+ .map((locality) => normalizeLocalityForKey(locality))
324
+ .filter((key) => key.length > 0)
325
+
326
+ if (postcodeRaw && !postcode) return null
327
+
328
+ if (!postcode && !localities.length) return null
329
+
330
+ const tables = await this.#optionalTables()
331
+ const streetTable: "street_postcode" | "street_locality" = postcode ? "street_postcode" : "street_locality"
332
+
333
+ if (!tables.has(streetTable)) return null
334
+
335
+ const aliasTable: "street_alias_postcode" | "street_alias_locality" = postcode
336
+ ? "street_alias_postcode"
337
+ : "street_alias_locality"
338
+
339
+ const level = postcode ? AddressKeyLevel.Postcode : AddressKeyLevel.Locality
340
+ const scopeValues = postcode ? [postcode] : localities
341
+ const surfaceLocale = streetLocaleForSurface(query.street, this.#locale)
342
+ const variants = streetKeyVariants(query.street, surfaceLocale).filter((key) => key.length > 0)
343
+
344
+ for (const scope of scopeValues) {
345
+ for (const street of variants) {
346
+ const [row] = await this.#runner.query<StreetRow>(SELECT_STREET(streetTable), [scope, street])
347
+
348
+ if (row && Number(row.points) > 0) {
349
+ return toStreetHit(row, level, street)
350
+ }
351
+ }
352
+
353
+ if (!tables.has(aliasTable)) continue
354
+
355
+ const canon = canonicalStreetKey(query.street, surfaceLocale)
356
+
357
+ if (!canon.key) continue
358
+
359
+ const aliasRows = await this.#runner.query<{ street: string }>(
360
+ `SELECT street FROM ${aliasTable} WHERE scope = ? AND street_canon = ?`,
361
+ [scope, canon.key]
362
+ )
363
+
364
+ for (const { street } of aliasRows) {
365
+ const [row] = await this.#runner.query<StreetRow>(SELECT_STREET(streetTable), [scope, street])
366
+
367
+ if (row && Number(row.points) > 0) {
368
+ return toStreetHit(row, level, street)
369
+ }
370
+ }
371
+ }
372
+
373
+ return null
374
+ }
375
+
376
+ #aliasScopes(query: AddressKeyQuery): Array<{
377
+ level: AddressKeyLevel
378
+ keyTable: "key_postcode" | "key_locality"
379
+ aliasTable: "street_alias_postcode" | "street_alias_locality"
380
+ streetTable: "street_postcode" | "street_locality"
381
+ value: string
382
+ }> {
383
+ const scopes: Array<{
384
+ level: AddressKeyLevel
385
+ keyTable: "key_postcode" | "key_locality"
386
+ aliasTable: "street_alias_postcode" | "street_alias_locality"
387
+ streetTable: "street_postcode" | "street_locality"
388
+ value: string
389
+ }> = []
390
+
391
+ const postcode = addressPostcodeKey(this.#country, query.postcode)
392
+
393
+ if (postcode) {
394
+ scopes.push({
395
+ level: AddressKeyLevel.Postcode,
396
+ keyTable: "key_postcode",
397
+ aliasTable: "street_alias_postcode",
398
+ streetTable: "street_postcode",
399
+ value: postcode,
400
+ })
401
+ }
402
+
403
+ for (const locality of query.localities ?? []) {
404
+ const key = normalizeLocalityForKey(locality)
405
+
406
+ if (!key) continue
407
+
408
+ scopes.push({
409
+ level: AddressKeyLevel.Locality,
410
+ keyTable: "key_locality",
411
+ aliasTable: "street_alias_locality",
412
+ streetTable: "street_locality",
413
+ value: key,
414
+ })
415
+ }
416
+
417
+ return scopes
418
+ }
419
+
420
+ async #probeScopedNumberForms(
421
+ table: "key_postcode" | "key_locality",
422
+ level: AddressKeyLevel,
423
+ scope: string,
424
+ street: string,
425
+ number: string
426
+ ): Promise<Omit<AddressKeyAnswer, "matchedStreet" | "streetMatch"> | null> {
427
+ for (const form of houseNumberForms(number, this.#locale)) {
428
+ const hits = await this.#scoped(table, level, scope, street, form.number)
429
+
430
+ if (hits.length) {
431
+ return { level, hits, matchedNumber: form.number, numberMatch: form.match }
432
+ }
433
+ }
434
+
435
+ return null
436
+ }
437
+
438
+ async #ladder(
439
+ query: AddressKeyQuery,
440
+ street: string,
441
+ number: string
442
+ ): Promise<{ level: AddressKeyLevel; hits: AddressKeyHit[] } | null> {
149
443
  const postcode = addressPostcodeKey(this.#country, query.postcode)
150
444
 
151
445
  if (postcode) {
@@ -203,3 +497,21 @@ function toHit(row: KeyRow, level: AddressKeyLevel): AddressKeyHit {
203
497
  level,
204
498
  }
205
499
  }
500
+
501
+ function toStreetHit(
502
+ row: StreetRow,
503
+ level: typeof AddressKeyLevel.Postcode | typeof AddressKeyLevel.Locality,
504
+ matchedStreet: string
505
+ ): AddressStreetHit {
506
+ return {
507
+ lat: Number(row.lat),
508
+ lon: Number(row.lon),
509
+ minLat: Number(row.min_lat),
510
+ maxLat: Number(row.max_lat),
511
+ minLon: Number(row.min_lon),
512
+ maxLon: Number(row.max_lon),
513
+ points: Number(row.points),
514
+ level,
515
+ matchedStreet,
516
+ }
517
+ }
@@ -25,6 +25,7 @@ export function openAddressLayerLookup(lookupPath: PathBuilderLike, country: str
25
25
 
26
26
  return {
27
27
  find: (query) => lookup.find(query),
28
+ findStreetCentroid: (query) => lookup.findStreetCentroid(query),
28
29
  [Symbol.dispose]: () => {
29
30
  db[Symbol.dispose]()
30
31
  detail[Symbol.dispose]()
@@ -7,8 +7,9 @@
7
7
  */
8
8
 
9
9
  import { memoizeResettable } from "@mailwoman/core/async/memoize"
10
- import type { AddressPointHit, AddressPointLookup } from "@mailwoman/core/resolver"
10
+ import type { AddressPointHit, AddressPointLookup, StreetCentroidHit } from "@mailwoman/core/resolver"
11
11
  import { parseJSONStrict } from "@mailwoman/core/values/json"
12
+ import { haversine } from "@mailwoman/spatial"
12
13
  import { type LatLonBounds, latLonBoundsContain } from "@mailwoman/spatial/bbox"
13
14
 
14
15
  import {
@@ -93,6 +94,28 @@ export class AddressKeyPointLookup implements AddressPointLookup {
93
94
  return undefined
94
95
  }
95
96
 
97
+ /**
98
+ * Selects the first hit whose `detail.db` record has no sub-unit (`unit IS NULL OR unit = ''`),
99
+ * so a base building beats a sub-unit outbuilding (`FUEL CENTE`, `APT 2`)
100
+ * when multiple records share `(scope, street, number)`.
101
+ */
102
+ async #preferBaseBuilding(hits: readonly AddressKeyHit[]): Promise<AddressKeyHit | undefined> {
103
+ const first = hits[0]
104
+
105
+ if (!first || hits.length <= 1 || !this.#detail) return first
106
+
107
+ const placeholders = hits.map(() => "?").join(", ")
108
+
109
+ const rows = await this.#detail.query<{ address_id: number }>(
110
+ `SELECT address_id FROM address WHERE address_id IN (${placeholders}) AND (unit IS NULL OR unit = '')`,
111
+ hits.map((hit) => hit.addressID)
112
+ )
113
+
114
+ const baseIDs = new Set(rows.map((row) => Number(row.address_id)))
115
+
116
+ return hits.find((hit) => baseIDs.has(hit.addressID)) ?? first
117
+ }
118
+
96
119
  async find(query: Parameters<AddressPointLookup["find"]>[0]): Promise<AddressPointHit | null> {
97
120
  const answer = await this.#lookup.find({
98
121
  street: query.street,
@@ -109,7 +132,7 @@ export class AddressKeyPointLookup implements AddressPointLookup {
109
132
  ? query.bbox
110
133
  ? await this.#unscopedInside(answer.hits, query.bbox)
111
134
  : undefined
112
- : answer.hits[0]
135
+ : await this.#preferBaseBuilding(answer.hits)
113
136
 
114
137
  if (!hit) return null
115
138
 
@@ -125,6 +148,42 @@ export class AddressKeyPointLookup implements AddressPointLookup {
125
148
  release,
126
149
  localityNorm: null,
127
150
  postcode: answer.level === AddressKeyLevel.Postcode ? (query.postcode?.trim() ?? null) : null,
151
+ matchedNumber: answer.matchedNumber,
152
+ numberMatch: answer.numberMatch,
153
+ matchedStreet: answer.matchedStreet,
154
+ streetMatch: answer.streetMatch,
155
+ }
156
+ }
157
+
158
+ async findStreetCentroid(query: {
159
+ street: string
160
+ postcode?: string
161
+ locality?: string
162
+ }): Promise<StreetCentroidHit | null> {
163
+ const hit = await this.#lookup.findStreet({
164
+ street: query.street,
165
+ postcode: query.postcode ?? null,
166
+ localities: query.locality ? [query.locality] : [],
167
+ })
168
+
169
+ if (!hit) return null
170
+
171
+ const spanKm = haversine(hit.minLat, hit.minLon, hit.maxLat, hit.maxLon)
172
+
173
+ if (!Number.isFinite(spanKm) || spanKm > MAX_STREET_CENTROID_SPAN_KM) return null
174
+
175
+ const [sources, release] = await Promise.all([this.#sourceNames(), this.#releaseVersion()])
176
+ const source = sources.size === 1 ? ([...sources.values()][0] ?? "address-layer") : "address-layer"
177
+
178
+ return {
179
+ lat: hit.lat,
180
+ lon: hit.lon,
181
+ uncertaintyM: Math.max(MIN_STREET_CENTROID_UNCERTAINTY_M, Math.round((spanKm * 1000) / 2)),
182
+ source,
183
+ release,
128
184
  }
129
185
  }
130
186
  }
187
+
188
+ const MAX_STREET_CENTROID_SPAN_KM = 25
189
+ const MIN_STREET_CENTROID_UNCERTAINTY_M = 50
@@ -82,6 +82,16 @@ export interface AddressStreetTable {
82
82
  points: number
83
83
  }
84
84
 
85
+ /**
86
+ * One canonical street alias under one scope, mapping a build-time `street_canon` key
87
+ * to the stored normalized `street` key in `key_postcode` or `key_locality`.
88
+ */
89
+ export interface AddressStreetAliasTable {
90
+ scope: string
91
+ street_canon: string
92
+ street: string
93
+ }
94
+
85
95
  /**
86
96
  * The `lookup.db` schema, for `new DatabaseClient<AddressLookupDatabase>(...)`,
87
97
  * with the layer interface's `layer_manifest` and `layer_coverage` tables.
@@ -95,6 +105,8 @@ export interface AddressLookupDatabase extends layerschemadatabase {
95
105
  key_region: AddressRegionKeyTable
96
106
  street_postcode: AddressStreetTable
97
107
  street_locality: AddressStreetTable
108
+ street_alias_postcode: AddressStreetAliasTable
109
+ street_alias_locality: AddressStreetAliasTable
98
110
  }
99
111
 
100
112
  /**
@@ -111,6 +123,14 @@ export const ADDRESS_STREET_TABLES = ["street_postcode", "street_locality"] as c
111
123
 
112
124
  export type AddressStreetTableName = (typeof ADDRESS_STREET_TABLES)[number]
113
125
 
126
+ /**
127
+ * The canonical street alias tables, one per scoped level used for `canonical-alias`
128
+ * and scoped `fuzzy-edit1` lookup.
129
+ */
130
+ export const ADDRESS_STREET_ALIAS_TABLES = ["street_alias_postcode", "street_alias_locality"] as const
131
+
132
+ export type AddressStreetAliasTableName = (typeof ADDRESS_STREET_ALIAS_TABLES)[number]
133
+
114
134
  /**
115
135
  * One address point's full record, kept apart from the lookup file.
116
136
  */
@@ -238,6 +258,23 @@ export async function createAddressStreetTable(
238
258
  .execute()
239
259
  }
240
260
 
261
+ /**
262
+ * Creates one canonical street alias table, clustered on `(scope, street_canon, street)`.
263
+ */
264
+ export async function createAddressStreetAliasTable(
265
+ db: Kysely<AddressLookupDatabase>,
266
+ table: AddressStreetAliasTableName
267
+ ): Promise<void> {
268
+ await db.schema
269
+ .createTable(table)
270
+ .addColumn("scope", "text", (c) => c.notNull())
271
+ .addColumn("street_canon", "text", (c) => c.notNull())
272
+ .addColumn("street", "text", (c) => c.notNull())
273
+ .addPrimaryKeyConstraint(`${table}_pk`, ["scope", "street_canon", "street"])
274
+ .modifyEnd(sql`without rowid`)
275
+ .execute()
276
+ }
277
+
241
278
  /**
242
279
  * Creates the `address` detail table, keyed by `address_id`.
243
280
  *