@mailwoman/resolver-wof-sqlite 9.1.0 → 9.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 (278) hide show
  1. package/README.md +28 -9
  2. package/address-point-interpolation.ts +18 -8
  3. package/address-point-schema.ts +18 -6
  4. package/address-point.ts +111 -18
  5. package/ancestry.ts +9 -6
  6. package/build-candidate.ts +200 -163
  7. package/build-slim.ts +3 -3
  8. package/candidate/alias-bags.ts +54 -0
  9. package/candidate/ancestors-sidecar.ts +206 -0
  10. package/candidate/country-display-names.ts +79 -0
  11. package/candidate/name-roles.ts +237 -0
  12. package/candidate/own-name.ts +146 -0
  13. package/candidate/place-attrs.ts +44 -0
  14. package/candidate/shard-fold.ts +137 -0
  15. package/candidate-ancestors-schema.ts +195 -0
  16. package/candidate-fts.ts +4 -2
  17. package/candidate-importance.ts +2 -1
  18. package/candidate-lookup.ts +439 -186
  19. package/candidate-schema.ts +33 -5
  20. package/candidate-scoring.ts +268 -0
  21. package/capital-schema.ts +90 -0
  22. package/capitals.ts +148 -0
  23. package/coincident-roles.ts +69 -10
  24. package/convention-schema.ts +72 -0
  25. package/convention.ts +2 -2
  26. package/coverage-manifest-schema.ts +7 -7
  27. package/currency-backfill.ts +249 -0
  28. package/exact-match.ts +104 -0
  29. package/fst-autocomplete.ts +91 -119
  30. package/fst-builder.ts +14 -12
  31. package/fst-freshness.ts +2 -2
  32. package/fts-query.ts +1 -1
  33. package/fts.ts +4 -4
  34. package/geonames-postal.ts +2 -2
  35. package/index.ts +18 -14
  36. package/interpolation.ts +113 -19
  37. package/lookup.ts +110 -591
  38. package/name-score.ts +6 -4
  39. package/out/address-point-interpolation.d.ts.map +1 -1
  40. package/out/address-point-interpolation.js +13 -7
  41. package/out/address-point-interpolation.js.map +1 -1
  42. package/out/address-point-schema.d.ts +16 -6
  43. package/out/address-point-schema.d.ts.map +1 -1
  44. package/out/address-point-schema.js.map +1 -1
  45. package/out/address-point.d.ts.map +1 -1
  46. package/out/address-point.js +70 -14
  47. package/out/address-point.js.map +1 -1
  48. package/out/ancestry.d.ts +2 -2
  49. package/out/ancestry.d.ts.map +1 -1
  50. package/out/ancestry.js +5 -6
  51. package/out/ancestry.js.map +1 -1
  52. package/out/build-candidate.d.ts +75 -0
  53. package/out/build-candidate.d.ts.map +1 -1
  54. package/out/build-candidate.js +120 -122
  55. package/out/build-candidate.js.map +1 -1
  56. package/out/build-slim.d.ts +1 -1
  57. package/out/build-slim.js +3 -3
  58. package/out/build-slim.js.map +1 -1
  59. package/out/candidate/alias-bags.d.ts +17 -0
  60. package/out/candidate/alias-bags.d.ts.map +1 -0
  61. package/out/candidate/alias-bags.js +39 -0
  62. package/out/candidate/alias-bags.js.map +1 -0
  63. package/out/candidate/ancestors-sidecar.d.ts +33 -0
  64. package/out/candidate/ancestors-sidecar.d.ts.map +1 -0
  65. package/out/candidate/ancestors-sidecar.js +140 -0
  66. package/out/candidate/ancestors-sidecar.js.map +1 -0
  67. package/out/candidate/country-display-names.d.ts +35 -0
  68. package/out/candidate/country-display-names.d.ts.map +1 -0
  69. package/out/candidate/country-display-names.js +59 -0
  70. package/out/candidate/country-display-names.js.map +1 -0
  71. package/out/candidate/name-roles.d.ts +55 -0
  72. package/out/candidate/name-roles.d.ts.map +1 -0
  73. package/out/candidate/name-roles.js +165 -0
  74. package/out/candidate/name-roles.js.map +1 -0
  75. package/out/candidate/own-name.d.ts +50 -0
  76. package/out/candidate/own-name.d.ts.map +1 -0
  77. package/out/candidate/own-name.js +132 -0
  78. package/out/candidate/own-name.js.map +1 -0
  79. package/out/candidate/place-attrs.d.ts +43 -0
  80. package/out/candidate/place-attrs.d.ts.map +1 -0
  81. package/out/candidate/place-attrs.js +15 -0
  82. package/out/candidate/place-attrs.js.map +1 -0
  83. package/out/candidate/shard-fold.d.ts +31 -0
  84. package/out/candidate/shard-fold.d.ts.map +1 -0
  85. package/out/candidate/shard-fold.js +104 -0
  86. package/out/candidate/shard-fold.js.map +1 -0
  87. package/out/candidate-ancestors-schema.d.ts +150 -0
  88. package/out/candidate-ancestors-schema.d.ts.map +1 -0
  89. package/out/candidate-ancestors-schema.js +123 -0
  90. package/out/candidate-ancestors-schema.js.map +1 -0
  91. package/out/candidate-fts.d.ts +4 -2
  92. package/out/candidate-fts.d.ts.map +1 -1
  93. package/out/candidate-fts.js +4 -2
  94. package/out/candidate-fts.js.map +1 -1
  95. package/out/candidate-importance.d.ts.map +1 -1
  96. package/out/candidate-importance.js +1 -1
  97. package/out/candidate-importance.js.map +1 -1
  98. package/out/candidate-lookup.d.ts +22 -45
  99. package/out/candidate-lookup.d.ts.map +1 -1
  100. package/out/candidate-lookup.js +340 -135
  101. package/out/candidate-lookup.js.map +1 -1
  102. package/out/candidate-schema.d.ts +30 -6
  103. package/out/candidate-schema.d.ts.map +1 -1
  104. package/out/candidate-schema.js +3 -0
  105. package/out/candidate-schema.js.map +1 -1
  106. package/out/candidate-scoring.d.ts +34 -0
  107. package/out/candidate-scoring.d.ts.map +1 -0
  108. package/out/candidate-scoring.js +200 -0
  109. package/out/candidate-scoring.js.map +1 -0
  110. package/out/capital-schema.d.ts +51 -0
  111. package/out/capital-schema.d.ts.map +1 -0
  112. package/out/capital-schema.js +63 -0
  113. package/out/capital-schema.js.map +1 -0
  114. package/out/capitals.d.ts +69 -0
  115. package/out/capitals.d.ts.map +1 -0
  116. package/out/capitals.js +98 -0
  117. package/out/capitals.js.map +1 -0
  118. package/out/coincident-roles.d.ts +7 -0
  119. package/out/coincident-roles.d.ts.map +1 -1
  120. package/out/coincident-roles.js +42 -8
  121. package/out/coincident-roles.js.map +1 -1
  122. package/out/convention-schema.d.ts +51 -0
  123. package/out/convention-schema.d.ts.map +1 -0
  124. package/out/convention-schema.js +34 -0
  125. package/out/convention-schema.js.map +1 -0
  126. package/out/convention.d.ts +1 -1
  127. package/out/convention.js +2 -2
  128. package/out/coverage-manifest-schema.js +3 -7
  129. package/out/coverage-manifest-schema.js.map +1 -1
  130. package/out/currency-backfill.d.ts +46 -0
  131. package/out/currency-backfill.d.ts.map +1 -0
  132. package/out/currency-backfill.js +180 -0
  133. package/out/currency-backfill.js.map +1 -0
  134. package/out/exact-match.d.ts +25 -0
  135. package/out/exact-match.d.ts.map +1 -0
  136. package/out/exact-match.js +89 -0
  137. package/out/exact-match.js.map +1 -0
  138. package/out/fst-autocomplete.d.ts +11 -11
  139. package/out/fst-autocomplete.d.ts.map +1 -1
  140. package/out/fst-autocomplete.js +82 -99
  141. package/out/fst-autocomplete.js.map +1 -1
  142. package/out/fst-builder.d.ts.map +1 -1
  143. package/out/fst-builder.js +11 -12
  144. package/out/fst-builder.js.map +1 -1
  145. package/out/fst-freshness.d.ts +2 -2
  146. package/out/fst-freshness.js +2 -2
  147. package/out/fts-query.js +1 -1
  148. package/out/fts-query.js.map +1 -1
  149. package/out/fts.d.ts +4 -4
  150. package/out/fts.js +4 -4
  151. package/out/geonames-postal.d.ts +2 -2
  152. package/out/geonames-postal.js +2 -2
  153. package/out/index.d.ts +3 -2
  154. package/out/index.d.ts.map +1 -1
  155. package/out/index.js +2 -2
  156. package/out/index.js.map +1 -1
  157. package/out/interpolation.d.ts +8 -0
  158. package/out/interpolation.d.ts.map +1 -1
  159. package/out/interpolation.js +91 -19
  160. package/out/interpolation.js.map +1 -1
  161. package/out/lookup.d.ts +4 -5
  162. package/out/lookup.d.ts.map +1 -1
  163. package/out/lookup.js +94 -468
  164. package/out/lookup.js.map +1 -1
  165. package/out/name-score.d.ts +0 -10
  166. package/out/name-score.d.ts.map +1 -1
  167. package/out/name-score.js +6 -4
  168. package/out/name-score.js.map +1 -1
  169. package/out/place-importance-schema.d.ts +42 -5
  170. package/out/place-importance-schema.d.ts.map +1 -1
  171. package/out/place-importance-schema.js +54 -8
  172. package/out/place-importance-schema.js.map +1 -1
  173. package/out/poi-lookup.d.ts +1 -1
  174. package/out/poi-lookup.d.ts.map +1 -1
  175. package/out/poi-lookup.js +12 -13
  176. package/out/poi-lookup.js.map +1 -1
  177. package/out/poi-schema.d.ts +7 -3
  178. package/out/poi-schema.d.ts.map +1 -1
  179. package/out/poi-schema.js.map +1 -1
  180. package/out/polygon-schema.d.ts +37 -0
  181. package/out/polygon-schema.d.ts.map +1 -0
  182. package/out/polygon-schema.js +23 -0
  183. package/out/polygon-schema.js.map +1 -0
  184. package/out/postal-city-alias-lookup.d.ts +1 -1
  185. package/out/postal-city-alias-lookup.js +1 -1
  186. package/out/postal-city-candidate-schema.d.ts +2 -1
  187. package/out/postal-city-candidate-schema.d.ts.map +1 -1
  188. package/out/postal-city-candidate-schema.js.map +1 -1
  189. package/out/postcode-point-lookup.d.ts +1 -1
  190. package/out/postcode-point-lookup.js +1 -1
  191. package/out/primary-preference.d.ts +125 -0
  192. package/out/primary-preference.d.ts.map +1 -0
  193. package/out/primary-preference.js +138 -0
  194. package/out/primary-preference.js.map +1 -0
  195. package/out/proximity-rerank.d.ts +77 -0
  196. package/out/proximity-rerank.d.ts.map +1 -0
  197. package/out/proximity-rerank.js +86 -0
  198. package/out/proximity-rerank.js.map +1 -0
  199. package/out/region-keys.d.ts +47 -0
  200. package/out/region-keys.d.ts.map +1 -0
  201. package/out/region-keys.js +121 -0
  202. package/out/region-keys.js.map +1 -0
  203. package/out/reverse.d.ts.map +1 -1
  204. package/out/reverse.js +6 -9
  205. package/out/reverse.js.map +1 -1
  206. package/out/schema.d.ts +1 -1
  207. package/out/search-fetch.d.ts +57 -0
  208. package/out/search-fetch.d.ts.map +1 -0
  209. package/out/search-fetch.js +183 -0
  210. package/out/search-fetch.js.map +1 -0
  211. package/out/sharding.d.ts +3 -3
  212. package/out/sharding.js +1 -1
  213. package/out/sqlite-convention-source.d.ts +1 -1
  214. package/out/sqlite-convention-source.js +1 -1
  215. package/out/sqlite-utils.d.ts +19 -1
  216. package/out/sqlite-utils.d.ts.map +1 -1
  217. package/out/sqlite-utils.js +19 -1
  218. package/out/sqlite-utils.js.map +1 -1
  219. package/out/street-centroid-schema.d.ts +7 -2
  220. package/out/street-centroid-schema.d.ts.map +1 -1
  221. package/out/street-centroid-schema.js.map +1 -1
  222. package/out/street-centroid.d.ts.map +1 -1
  223. package/out/street-centroid.js +7 -7
  224. package/out/street-centroid.js.map +1 -1
  225. package/out/street-normalize.d.ts +82 -9
  226. package/out/street-normalize.d.ts.map +1 -1
  227. package/out/street-normalize.js +175 -9
  228. package/out/street-normalize.js.map +1 -1
  229. package/out/street-segment-schema.d.ts +6 -2
  230. package/out/street-segment-schema.d.ts.map +1 -1
  231. package/out/street-segment-schema.js.map +1 -1
  232. package/out/types.d.ts +35 -1
  233. package/out/types.d.ts.map +1 -1
  234. package/out/unified-schema.d.ts +1 -1
  235. package/out/unified-schema.js +1 -1
  236. package/out/uprn-lookup.d.ts +85 -0
  237. package/out/uprn-lookup.d.ts.map +1 -0
  238. package/out/uprn-lookup.js +152 -0
  239. package/out/uprn-lookup.js.map +1 -0
  240. package/out/uprn-schema.d.ts +93 -0
  241. package/out/uprn-schema.d.ts.map +1 -0
  242. package/out/uprn-schema.js +78 -0
  243. package/out/uprn-schema.js.map +1 -0
  244. package/out/weights-overlay-linker.d.ts +141 -0
  245. package/out/weights-overlay-linker.d.ts.map +1 -0
  246. package/out/weights-overlay-linker.js +259 -0
  247. package/out/weights-overlay-linker.js.map +1 -0
  248. package/package.json +288 -16
  249. package/place-importance-schema.ts +64 -15
  250. package/poi-lookup.ts +12 -13
  251. package/poi-schema.ts +8 -3
  252. package/polygon-schema.ts +47 -0
  253. package/postal-city-alias-lookup.ts +1 -1
  254. package/postal-city-candidate-schema.ts +3 -1
  255. package/postcode-point-lookup.ts +1 -1
  256. package/primary-preference.ts +207 -0
  257. package/proximity-rerank.ts +120 -0
  258. package/region-keys.ts +144 -0
  259. package/reverse.ts +17 -16
  260. package/schema.ts +1 -1
  261. package/search-fetch.ts +256 -0
  262. package/sharding.ts +3 -3
  263. package/sqlite-convention-source.ts +1 -1
  264. package/sqlite-utils.ts +43 -2
  265. package/street-centroid-schema.ts +8 -2
  266. package/street-centroid.ts +13 -8
  267. package/street-normalize.ts +252 -23
  268. package/street-segment-schema.ts +7 -2
  269. package/types.ts +35 -1
  270. package/unified-schema.ts +1 -1
  271. package/uprn-lookup.ts +210 -0
  272. package/uprn-schema.ts +124 -0
  273. package/weights-overlay-linker.ts +377 -0
  274. package/geo.ts +0 -121
  275. package/out/geo.d.ts +0 -74
  276. package/out/geo.d.ts.map +0 -1
  277. package/out/geo.js +0 -71
  278. package/out/geo.js.map +0 -1
package/out/lookup.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * `WOFSqlitePlaceLookup` — the resolver implementation backed by `node:sqlite` + a Kysely-typed
6
+ * `WOFSQLitePlaceLookup` — the resolver implementation backed by `node:sqlite` + a Kysely-typed
7
7
  * query layer where the queries are non-trivial, and raw SQL where they aren't (FTS5 MATCH, the
8
8
  * FTS index build).
9
9
  *
@@ -12,44 +12,39 @@
12
12
  import { DatabaseSync } from "node:sqlite";
13
13
  import { SqliteDialect } from "@mailwoman/core/kysley/dialect";
14
14
  import { expandPlacetypeFilter } from "@mailwoman/resolver";
15
+ import { haversineKm } from "@mailwoman/spatial";
15
16
  import { Kysely } from "kysely";
16
17
  import { ancestorLineage } from "./ancestry.js";
17
- import { COINCIDENT_ROLES_TABLE, coincidentRolesExists } from "./coincident-roles.js";
18
+ import { candidateFromSearchRow, rankCandidates } from "./candidate-scoring.js";
19
+ import { loadCoincidentLocalities } from "./coincident-roles.js";
18
20
  import { ADDRESS_CONVENTION_TABLE, resolveConvention, SeedConventionSource, } from "./convention.js";
19
21
  import { normalizePlacetypes, sanitizeFTSQuery } from "./fts-query.js";
20
- import { aliasBagExactMatch, buildPlaceSearchFTS, PLACE_BBOX_TABLE, PLACE_POPULATION_TABLE, placeBboxExists, placePopulationExists, placeSearchFTSExists, } from "./fts.js";
21
- import { bboxAround, haversineKm } from "./geo.js";
22
- import { cfNormalize, softNameScore, trigramJaccard } from "./name-score.js";
23
- import { compareReferential, encyclopedicClauses, referentialFromPopulation } from "./place-importance-schema.js";
22
+ import { buildPlaceSearchFTS, PLACE_BBOX_TABLE, PLACE_POPULATION_TABLE, PLACE_SEARCH_TABLE, placeBboxExists, placePopulationExists, placeSearchFTSExists, } from "./fts.js";
23
+ import { cfNormalize, softNameScore } from "./name-score.js";
24
+ import { encyclopedicClauses } from "./place-importance-schema.js";
24
25
  import { DEFAULT_WEIGHTS } from "./ranking-weights.js";
26
+ import { fetchSearchRows } from "./search-fetch.js";
25
27
  import { pickShardForPlacetype, pickShardsForPlacetype, resolveShards, } from "./sharding.js";
26
28
  import { SqliteConventionSource } from "./sqlite-convention-source.js";
27
- /**
28
- * Query length at or below which the FTS window is widened. A two- or three-character query is almost always a region
29
- * abbreviation, where the exact match can otherwise fall outside the window behind higher-bm25 partial hits — "NY"
30
- * losing to "New York".
31
- */
32
- const SHORT_QUERY_MAX_LENGTH = 3;
33
- /**
34
- * Over-fetch floor for SHORT (≤3-char) queries — region abbreviations like "NY"/"VT". An exact-abbrev holder's BM25 is
35
- * poor (long multilingual alt-name document), so the normal `limit * 4` window can drop it before `exactMatchTiering`
36
- * promotes it. 200 comfortably covers every same-abbrev region across the 12-country gazetteer (a 2-letter token
37
- * matches a few dozen regions at most) while staying a cheap region-placetype fetch. See the `#fuzzyNameMatch`
38
- * over-fetch comment.
39
- */
40
- const SHORT_QUERY_OVERFETCH = 200;
41
- /**
42
- * How many rows the population-ordered companion fetch (#905) adds to the candidate pool. Small on purpose: its only
43
- * job is to guarantee the FAMOUS holders of a name enter the pool at all — for "Paris"-class floods the bm25 window is
44
- * saturated by thousands of tiny same-name rows and no boost inside the bm25-based ORDER BY can rescue a candidate
45
- * whose bm25 is length-poisoned by ~15 points (see the fetch-site comment).
46
- */
47
- const POPULATION_FETCH_LIMIT = 15;
29
+ import { allRows } from "./sqlite-utils.js";
48
30
  /**
49
31
  * The coordinate-first candidate table (scripts/build-postcode-locality.ts): postcode → containing
50
32
  *
51
33
  * - Nearby localities with WOF alt-name aliases.
52
34
  */
35
+ /**
36
+ * The placetypes `pickShardsForPlacetype`'s substring rule can route by name. Not every WOF placetype — only the ones a
37
+ * purpose-built shard is ever named for — so the diagnostic below can say "this name routes nowhere" without claiming
38
+ * to enumerate the gazetteer.
39
+ */
40
+ const KNOWN_ROUTED_PLACETYPES = [
41
+ "postalcode",
42
+ "locality",
43
+ "region",
44
+ "county",
45
+ "country",
46
+ "venue",
47
+ ];
53
48
  const POSTCODE_LOCALITY_TABLE = "postcode_locality";
54
49
  /**
55
50
  * Tunables for the coordinate-first locality soft-score `Score = pc·S_pc + name·S_name + pop·S_pop` (each S in [0,1]).
@@ -64,8 +59,7 @@ const CF_PC_DECAY_KM = 8;
64
59
  * flagged, tight enough to catch a wrong city (hundreds of km).
65
60
  */
66
61
  const CF_MISMATCH_KM = 50;
67
- const CF_MISMATCH_DELTA = 0.5;
68
- export class WOFSqlitePlaceLookup {
62
+ export class WOFSQLitePlaceLookup {
69
63
  #db;
70
64
  #ownsDB;
71
65
  #kysely;
@@ -133,10 +127,10 @@ export class WOFSqlitePlaceLookup {
133
127
  #postalCityAliases;
134
128
  constructor(opts, weights) {
135
129
  if (opts.database && opts.databasePath) {
136
- throw new Error("WOFSqlitePlaceLookup: pass either `database` or `databasePath`, not both");
130
+ throw new Error("WOFSQLitePlaceLookup: pass either `database` or `databasePath`, not both");
137
131
  }
138
132
  if (!opts.database && !opts.databasePath) {
139
- throw new Error("WOFSqlitePlaceLookup: one of `database` or `databasePath` is required");
133
+ throw new Error("WOFSQLitePlaceLookup: one of `database` or `databasePath` is required");
140
134
  }
141
135
  if (opts.database) {
142
136
  this.#db = opts.database;
@@ -182,6 +176,42 @@ export class WOFSqlitePlaceLookup {
182
176
  this.#hasPopulationIndex.set(s.schemaName, this.#shardHasTable(s.schemaName, PLACE_POPULATION_TABLE));
183
177
  this.#encyclopedicClauses.set(s.schemaName, encyclopedicClauses(this.#db, s.schemaName));
184
178
  }
179
+ // Every lookup path here reaches `place_search`, and a shard without it fails in one of two ways
180
+ // that are both hard to read: an unroutable name returns zero hits (indistinguishable from "this
181
+ // country has no places") and a routable one throws mid-query from deep inside a SELECT. The
182
+ // unroutable half is the worse of the two — a shard reaches routing only through the name
183
+ // `deriveSchemaName` derives from its FILENAME, so a file spelled one letter off the placetype it
184
+ // serves answers with nothing while holding every row that was asked for.
185
+ //
186
+ // Two independent things bring a shard under the guard, and it needs both. Carrying `spr` is a
187
+ // CLAIM to be a place shard. Carrying a name that routes is an INVITATION to be queried as one, and
188
+ // it is made by the filename alone — so a database with no tables at all still gets picked, still
189
+ // answers no query, and still dies inside a SELECT. Testing only the claim lets an empty or
190
+ // truncated file past construction; testing only the name would exempt a correctly-named build
191
+ // input. A shard needs to fail neither test to be exempt.
192
+ //
193
+ // Exempt by design: `postcode-locality-<cc>.db` carries a relation table and nothing else, matches
194
+ // no routed placetype, and is part of the documented default shard list.
195
+ for (const s of this.#shards) {
196
+ if (s.schemaName === "main")
197
+ continue;
198
+ const routes = KNOWN_ROUTED_PLACETYPES.some((pt) => s.schemaName === pt || s.schemaName.startsWith(`${pt}_`) || s.schemaName.endsWith(`_${pt}`));
199
+ const claimsPlaceShard = this.#shardHasTable(s.schemaName, "spr");
200
+ if (!routes && !claimsPlaceShard)
201
+ continue;
202
+ if (this.#shardHasTable(s.schemaName, PLACE_SEARCH_TABLE))
203
+ continue;
204
+ throw new Error(`WOFSQLitePlaceLookup: ${s.path} ` +
205
+ (claimsPlaceShard
206
+ ? `carries "spr" but no "${PLACE_SEARCH_TABLE}" table, so it cannot serve a lookup.`
207
+ : `is named for a routed placetype but carries neither "spr" nor "${PLACE_SEARCH_TABLE}", so every ` +
208
+ `query routed to it would die mid-SELECT. An empty or truncated file reads exactly like this.`) +
209
+ ` Build it with the FTS index, or leave it out — it is usable as a BUILD input either way.` +
210
+ (routes
211
+ ? ""
212
+ : ` Its schema name "${s.schemaName}" also matches no routed placetype (${KNOWN_ROUTED_PLACETYPES.join(", ")}), ` +
213
+ `so it would never have been queried even with the table — check the filename's spelling.`));
214
+ }
185
215
  // #920 country-aware shard routing: probe each NON-MAIN shard's country set once at
186
216
  // construction (they're small, purpose-built shards — postcode/locality slices; main is the
187
217
  // multi-GB admin DB and is the fallback anyway, so it is deliberately NOT scanned). Feeds
@@ -299,38 +329,7 @@ export class WOFSqlitePlaceLookup {
299
329
  if (!Number.isFinite(id))
300
330
  return [];
301
331
  if (!this.#coincidentRolesCache) {
302
- const map = new Map();
303
- if (coincidentRolesExists(this.#db)) {
304
- const rows = this.#db
305
- .prepare(`SELECT cr.admin_id AS adminID, s.id AS id, s.name AS name, s.country AS country,
306
- s.latitude AS lat, s.longitude AS lon,
307
- cr.relationship_type AS relationshipType, cr.locality_population AS population,
308
- cr.distance_km AS distanceKm
309
- FROM ${COINCIDENT_ROLES_TABLE} cr JOIN spr s ON s.id = cr.locality_id`)
310
- .all();
311
- for (const r of rows) {
312
- const candidate = {
313
- id: r.id,
314
- name: r.name,
315
- placetype: "locality",
316
- country: r.country,
317
- lat: r.lat,
318
- lon: r.lon,
319
- score: 0,
320
- relationshipType: r.relationshipType,
321
- population: r.population,
322
- distanceKm: r.distanceKm,
323
- };
324
- const list = map.get(r.adminID);
325
- if (list) {
326
- list.push(candidate);
327
- }
328
- else {
329
- map.set(r.adminID, [candidate]);
330
- }
331
- }
332
- }
333
- this.#coincidentRolesCache = map;
332
+ this.#coincidentRolesCache = loadCoincidentLocalities(this.#db);
334
333
  }
335
334
  return this.#coincidentRolesCache.get(id) ?? [];
336
335
  }
@@ -368,7 +367,7 @@ export class WOFSqlitePlaceLookup {
368
367
  if (this.#warnedUnknownStrategies.has(name))
369
368
  return;
370
369
  this.#warnedUnknownStrategies.add(name);
371
- console.warn(`WOFSqlitePlaceLookup: a convention names strategy "${name}", which this build does not register ` +
370
+ console.warn(`WOFSQLitePlaceLookup: a convention names strategy "${name}", which this build does not register ` +
372
371
  `(known: ${[...this.#strategies.keys()].join(", ")}). Skipping it. If the convention asset was built ` +
373
372
  `against a newer code revision, rebuild the asset for this one.`);
374
373
  }
@@ -390,16 +389,6 @@ export class WOFSqlitePlaceLookup {
390
389
  */
391
390
  async #fuzzyNameMatch(query, forceShard) {
392
391
  const limit = query.limit ?? 10;
393
- // Over-fetch so post-scoring + exact-match tiering have room to re-rank. SHORT queries (a 2–3-char
394
- // region abbreviation like "NY"/"VT") are the danger case the `exactMatchTiering` docstring flags:
395
- // the exact-abbrev holder's BM25 is poor (its long multilingual alt-name document tanks the score),
396
- // so under the normal `limit * 4` window it drops OUT of the candidate pool BEFORE tiering can
397
- // promote it — "NY" then resolves to a token-matching foreign region (Highland, GB) instead of New
398
- // York. Widen the window for short queries so the exact match is always present to be tiered.
399
- // (Cross-country abbrev collisions — "VT" is BOTH Vermont and Viterbo — still need a country/
400
- // postcode signal to disambiguate; this only rescues the window-drop class, not genuine ambiguity.
401
- // With a `country` hint every abbrev resolves; bare + no-context lifts 7→10/15 US states.)
402
- const ftsLimit = query.text.trim().length <= SHORT_QUERY_MAX_LENGTH ? Math.max(limit * 4, SHORT_QUERY_OVERFETCH) : limit * 4;
403
392
  // Expand the placetype filter through the shared equivalence table (core/resolver): a
404
393
  // `locality` query must also reach `borough` / `localadmin` rows — Brooklyn-the-borough
405
394
  // (pop 2.5M) is a borough, not a locality, and a strict filter made it unreachable so the
@@ -446,312 +435,33 @@ export class WOFSqlitePlaceLookup {
446
435
  country: query.country,
447
436
  countriesBySchema: this.#shardCountries,
448
437
  });
449
- const sch = shard.schemaName; // bare schema name; safe to interpolate (validated at construction)
450
- // Filter out historical / superseded / deprecated places by default — they live in the same
451
- // spr table but should never win a contemporary lookup. `is_current = 0` is the only WOF
452
- // value that means "not current"; both `-1` (modern) and `1` (legacy) mean current. See #91.
453
- // Note: with schema-qualified FROM the bare `place_search` reference in MATCH resolves to
454
- // the FROM table — required by FTS5 parser, see sharding.ts header comment.
455
- const where = ["place_search MATCH ?", "spr.is_current != 0", "spr.is_deprecated = 0"];
456
- const params = [ftsQuery];
457
- if (placetypes && placetypes.length) {
458
- where.push(`spr.placetype IN (${placetypes.map(() => "?").join(", ")})`);
459
- params.push(...placetypes);
460
- }
461
- if (query.country) {
462
- where.push("spr.country = ?");
463
- params.push(query.country);
464
- }
465
- if (query.parentID !== undefined) {
466
- where.push(`(spr.parent_id = ? OR spr.id IN (SELECT id FROM ${sch}.ancestors WHERE ancestor_id = ?))`);
467
- params.push(query.parentID, query.parentID);
468
- }
469
- // Bbox + near-with-radius are SQL-level filters via the R*Tree. We only emit the JOIN when
470
- // the active shard has the R*Tree; missing-but-requested is silently treated as no-bbox-
471
- // filter so legacy DBs / shards-without-bbox don't crash.
472
- const shardHasBbox = this.#hasBboxIndex.get(sch) === true;
473
- const useBboxJoin = (query.bbox || query.near?.maxDistanceKm !== undefined) && shardHasBbox;
474
- let joinClause = `JOIN ${sch}.spr ON spr.id = place_search.wof_id`;
475
- if (useBboxJoin) {
476
- joinClause += ` JOIN ${sch}.${PLACE_BBOX_TABLE} bbox ON bbox.id = spr.id`;
477
- // AABB intersection — both bbox sides must overlap. R*Tree handles this in O(log n).
478
- const filterBox = query.bbox || bboxAround(query.near.lat, query.near.lon, query.near.maxDistanceKm);
479
- where.push("bbox.min_lat <= ? AND bbox.max_lat >= ?", "bbox.min_lon <= ? AND bbox.max_lon >= ?");
480
- params.push(filterBox.maxLat, filterBox.minLat, filterBox.maxLon, filterBox.minLon);
481
- }
482
- // LEFT JOIN the population aux table when present. Missing-on-this-shard means the SELECT
483
- // just doesn't include the population column; the post-scoring loop treats it as 0.
484
- const shardHasPopulation = this.#hasPopulationIndex.get(sch) === true;
485
- const populationSelect = shardHasPopulation
486
- ? `${PLACE_POPULATION_TABLE}.population AS population`
487
- : `NULL AS population`;
488
- const populationJoin = shardHasPopulation
489
- ? `LEFT JOIN ${sch}.${PLACE_POPULATION_TABLE} ON ${PLACE_POPULATION_TABLE}.id = spr.id`
490
- : "";
491
- // The encyclopedic score is CARRIED, never ranked on (ROAD_TO_V9 §2, ratified 2026-08-06) — it
492
- // appears in the SELECT and in no ORDER BY, here or in the companion fetch below. Gated on the
493
- // split column, so a pre-split shard emits a literal NULL and builds no join at all.
494
- const { select: encyclopedicSelect, join: encyclopedicJoin } = this.#encyclopedicClauses.get(sch);
495
- // Push the population boost into the ORDER BY when the index is available, so famous places
496
- // (whose long alt-name lists hurt BM25) actually make it into the over-fetch window. The TS
497
- // post-scoring will still compute the same boost for the final score; this just ensures the
498
- // candidate set is right.
499
- //
500
- // Formula: rank_adjusted = bm25 - populationBoost * min(1.0, log10(1 + pop) / scaleLog10)
501
- // Lower rank_adjusted = better (matches SQLite's bm25 convention of "more negative = better").
502
- //
503
- // #905 — do NOT reach for bm25 column weights here. Measured falsification (2026-07-02): FTS5's
504
- // bm25 length normalization is polluted by the row's TOTAL document size, so identical 1-token
505
- // `name` docs read −16.0 (empty alt_names) vs −0.43 (2.7 KB alt_names) EVEN with the alt_names
506
- // column weighted to zero — no weighting isolates name relevance in this schema. The famous-
507
- // holder guarantee lives in the population-ordered companion fetch below instead, and the
508
- // exact tier breaks ties by population in the post-scoring sort.
509
- const orderByExpr = shardHasPopulation
510
- ? `(bm25(place_search) - ? * MIN(1.0, COALESCE(log10(1.0 + ${PLACE_POPULATION_TABLE}.population), 0) / ?))`
511
- : "bm25(place_search)";
512
- // Schema-qualified FROM with bare-name MATCH — required syntax for FTS5 on attached schemas.
513
- // See sharding.ts header for the gotcha that drove this design.
514
- const stmt = this.#db.prepare(`
515
- SELECT
516
- spr.id AS id,
517
- spr.name,
518
- spr.placetype,
519
- spr.country,
520
- spr.parent_id,
521
- bm25(place_search) AS rank,
522
- spr.latitude AS lat,
523
- spr.longitude AS lon,
524
- spr.min_latitude, spr.max_latitude, spr.min_longitude, spr.max_longitude,
525
- ${populationSelect},
526
- ${encyclopedicSelect}
527
- FROM ${sch}.place_search
528
- ${joinClause}
529
- ${populationJoin}
530
- ${encyclopedicJoin}
531
- WHERE ${where.join(" AND ")}
532
- ORDER BY ${orderByExpr} ASC
533
- LIMIT ?
534
- `);
535
- if (shardHasPopulation) {
536
- params.push(this.#weights.populationBoost, this.#weights.populationScaleLog10);
537
- }
538
- params.push(ftsLimit);
539
- const rawRows = stmt.all(...params);
540
- // #905 companion fetch: the same MATCH, ordered by population alone. For name floods
541
- // ("Paris" matches thousands of gap-fill villages) the bm25-based window above cannot admit
542
- // the famous holder — its bm25 is length-poisoned by the row's alias bulk (measured ~15 pts,
543
- // vs a +4.0 boost cap), so FR Paris never even reaches post-scoring. This fetch makes the
544
- // prominent holders of a name pool-complete BY CONSTRUCTION; the exact-tier sort below
545
- // decides whether they win. Skipped without a population index (nothing to order by).
546
- if (shardHasPopulation) {
547
- const popStmt = this.#db.prepare(`
548
- SELECT
549
- spr.id AS id,
550
- spr.name,
551
- spr.placetype,
552
- spr.country,
553
- spr.parent_id,
554
- bm25(place_search) AS rank,
555
- spr.latitude AS lat,
556
- spr.longitude AS lon,
557
- spr.min_latitude, spr.max_latitude, spr.min_longitude, spr.max_longitude,
558
- ${populationSelect},
559
- ${encyclopedicSelect}
560
- FROM ${sch}.place_search
561
- ${joinClause}
562
- ${populationJoin}
563
- ${encyclopedicJoin}
564
- WHERE ${where.join(" AND ")}
565
- ORDER BY COALESCE(${PLACE_POPULATION_TABLE}.population, 0) DESC
566
- LIMIT ?
567
- `);
568
- const popParams = params.slice(0, -3); // drop the two boost params + ftsLimit
569
- const seen = new Set(rawRows.map((r) => r.id));
570
- for (const row of popStmt.all(...popParams, POPULATION_FETCH_LIMIT)) {
571
- if (!seen.has(row.id)) {
572
- rawRows.push(row);
573
- }
574
- }
575
- }
576
- const queryLen = query.text.length;
577
- const candidates = rawRows.map((row) => {
578
- // SQLite's bm25() returns a lower-is-better score (negative for matches). Negate so we
579
- // start from a higher-is-better baseline.
580
- let score = -row.rank;
581
- if (placetypes && placetypes.length && placetypes.includes(row.placetype)) {
582
- score += this.#weights.placetypeMatchBoost;
583
- }
584
- if (!placetypes && row.placetype === "locality") {
585
- score += this.#weights.localityImplicitBoost;
586
- }
587
- if (query.country && row.country === query.country) {
588
- score += this.#weights.countryMatchBoost;
589
- }
590
- if (query.parentID !== undefined) {
591
- score += row.parent_id === query.parentID ? this.#weights.directChildBoost : this.#weights.descendantBoost;
592
- }
593
- const extraLen = Math.max(0, row.name.length - queryLen - 3);
594
- score -= (this.#weights.lengthPenaltyWeight * extraLen) / 10;
595
- // Proximity boost: only applied when the query carries `near` AND the candidate has real
596
- // coordinates. The formula decays smoothly with distance so close-but-not-exact hits
597
- // still benefit; tunable via proximityBoost + proximityScaleKm.
598
- let distanceKm;
599
- // The best decayed-distance term over `near` + every `bias` point (each point's term is
600
- // scaled by its weight; the MAX wins — a candidate near ANY hint is "nearby"). Carried
601
- // into the exact-tier prominence sort below when hints are present.
602
- let proximityTerm = 0;
603
- if (row.lat !== null && row.lon !== null && !(row.lat === 0 && row.lon === 0)) {
604
- const hints = [];
605
- if (query.near) {
606
- hints.push({ lat: query.near.lat, lon: query.near.lon, weight: 1 });
607
- }
608
- for (const b of query.bias ?? []) {
609
- hints.push({ lat: b.lat, lon: b.lon, weight: b.weight ?? 1 });
610
- }
611
- let scoreTerm = 0;
612
- for (const h of hints) {
613
- const d = haversineKm(h.lat, h.lon, row.lat, row.lon);
614
- const decay = h.weight / (1 + d / this.#weights.proximityScaleKm);
615
- const prom = decay * this.#weights.biasBoost;
616
- if (prom > proximityTerm) {
617
- proximityTerm = prom;
618
- distanceKm = d;
619
- scoreTerm = decay * this.#weights.proximityBoost;
620
- }
621
- }
622
- score += scoreTerm;
623
- }
624
- // Population boost: capped at `populationBoost` magnitude at `10^populationScaleLog10`
625
- // people. Missing population → no contribution. Never penalizes.
626
- let popTerm = 0;
627
- if (row.population !== null && row.population > 0 && this.#weights.populationScaleLog10 > 0) {
628
- const popLog = Math.log10(1 + row.population);
629
- const popFraction = Math.min(1, popLog / this.#weights.populationScaleLog10);
630
- popTerm = this.#weights.populationBoost * popFraction;
631
- score += popTerm;
632
- }
633
- // Combined prominence for the exact-tier sort when proximity hints are present: population
634
- // and nearness in the SAME additive units, so the map view / the user's location can win a
635
- // cross-country postcode tie without a hard filter.
636
- const prominence = popTerm + proximityTerm;
637
- const candidate = {
638
- id: row.id,
639
- prominence,
640
- name: row.name,
641
- placetype: row.placetype,
642
- country: row.country ?? "",
643
- lat: row.lat ?? 0,
644
- lon: row.lon ?? 0,
645
- parent_id: row.parent_id ?? undefined,
646
- score,
647
- };
648
- if (distanceKm !== undefined) {
649
- candidate.distanceKm = distanceKm;
650
- }
651
- if (row.population !== null && row.population > 0) {
652
- candidate.population = row.population;
653
- // The named ranking key (ROAD_TO_V9 §2). DERIVED, not stored — a pure function of the
654
- // population already on this row, so it cannot drift from what the ordering uses.
655
- candidate.referential = referentialFromPopulation(row.population);
656
- }
657
- // Carried for consumers (annotations / API surfaces). No ranking site reads it.
658
- if (row.encyclopedic !== null) {
659
- candidate.encyclopedic = row.encyclopedic;
660
- }
661
- // Candidate bbox — parity with the WASM lookup (resolver-wof-wasm/lookup.ts), whose
662
- // consumers (the demo cascade's region constraint) read it. Without this the Node
663
- // backend's region→bbox constraint is dead and disambiguation falls to population
664
- // ranking (the Springfield-IL→MO failure the #524 smoke eval caught).
665
- if (row.min_latitude != null &&
666
- row.max_latitude != null &&
667
- row.min_longitude != null &&
668
- row.max_longitude != null) {
669
- candidate.bbox = {
670
- minLat: row.min_latitude,
671
- maxLat: row.max_latitude,
672
- minLon: row.min_longitude,
673
- maxLon: row.max_longitude,
674
- };
675
- }
676
- return candidate;
438
+ // bare schema name; safe to interpolate (validated at construction)
439
+ const sch = shard.schemaName;
440
+ const rawRows = fetchSearchRows({
441
+ db: this.#db,
442
+ schemaName: sch,
443
+ query,
444
+ placetypes,
445
+ ftsQuery,
446
+ limit,
447
+ hasBboxIndex: this.#hasBboxIndex,
448
+ hasPopulationIndex: this.#hasPopulationIndex,
449
+ encyclopedicClauses: this.#encyclopedicClauses,
450
+ weights: this.#weights,
451
+ });
452
+ const scoring = {
453
+ query,
454
+ placetypes,
455
+ queryLen: query.text.length,
456
+ weights: this.#weights,
457
+ };
458
+ const candidates = rawRows.map((row) => candidateFromSearchRow(row, scoring));
459
+ rankCandidates(candidates, {
460
+ db: this.#db,
461
+ schemaName: sch,
462
+ query,
463
+ weights: this.#weights,
677
464
  });
678
- // Exact-match tiering: a candidate whose name OR any alias equals the query text (case-folded)
679
- // ranks above any partial match, with the weighted-sum score (incl. population) breaking ties
680
- // WITHIN a tier. See the RankingWeights.exactMatchTiering docstring for why this aligns the
681
- // population prior rather than overriding it. One cheap indexed lookup over the candidate ids.
682
- // Runs even for a SINGLE candidate so `exactMatch` is stamped consistently (parity with the
683
- // WASM lookup) — a sole alias hit ("New York City" → New York) must still carry the flag the
684
- // demo cascade / #369 re-rank read.
685
- if (this.#weights.exactMatchTiering && candidates.length) {
686
- const exactIds = this.#exactMatchIds(sch, candidates.map((c) => c.id), query.text);
687
- // Stamp the tier onto every candidate (not just when the tiering sort fires) so a downstream
688
- // re-rank — #369's postcode-anchor country pin in `resolveTree` — can keep the country pin from
689
- // crossing the exact/partial boundary ("ME" → Maine, not the more-populous Missouri).
690
- for (const c of candidates) {
691
- c.exactMatch = exactIds.has(c.id);
692
- }
693
- if (exactIds.size) {
694
- // #905: WITHIN the exact tier, population is the PRIMARY key and the weighted score
695
- // only breaks population ties. Exactness saturates text relevance, and the bm25
696
- // residue inside `score` is length-noise (see the fetch-site comment), so letting it
697
- // order the tier is what sent unscoped "Paris" to an Ohio township. The partial tier
698
- // keeps score order — text relevance still means something there. This makes the
699
- // exactMatchTiering docstring literal: match quality primary, prominence within.
700
- //
701
- // #912 sub-tier: a NAME-exact candidate (spr.name equals the query) outranks an
702
- // ALIAS-exact one ('Paris' the place beats 'Paris Township' held via alias 'Paris').
703
- // The place's own name is a stronger identity claim than an alias — aliases exist to
704
- // widen recall, not to tie primaries. ME→Maine is untouched: 'ME' name-exact-matches
705
- // nothing, so the alias sub-tier still decides there. Population orders within each
706
- // sub-tier as before.
707
- const norm = (v) => v.toLowerCase().trim().replaceAll(/\s+/g, " ");
708
- const needle = norm(query.text);
709
- // #936 option 3: an OFFICIAL name (preferred form in an official language of the place's
710
- // country, `names.official = 1`) counts as the place's own name for the sub-tier — "Åbo" is
711
- // Turku's name, not merely its alias. Floor-gated on the holder's population (see the
712
- // RankingWeights docstring for the measured 100k boundary). officialIds ⊆ exactIds by
713
- // construction (official rows are names rows), so only the sub-tier KIND changes.
714
- const officialIds = this.#weights.officialNameExact
715
- ? this.#officialNameIds(sch, candidates
716
- .filter((c) => exactIds.has(c.id) && (c.population ?? 0) >= this.#weights.officialNameExactFloor)
717
- .map((c) => c.id), query.text)
718
- : undefined;
719
- const kind = (c) => {
720
- if (!exactIds.has(c.id))
721
- return 0;
722
- if (norm(String(c.name ?? "")) === needle)
723
- return 2;
724
- return officialIds?.has(c.id) ? 2 : 1;
725
- };
726
- // With proximity hints (near/bias), prominence (population + nearness, same units)
727
- // replaces raw population as the within-tier key — the 48026 rule: the map view or
728
- // the user's location breaks a cross-country postcode tie. Without hints, REFERENTIAL
729
- // ordering decides.
730
- //
731
- // ROAD_TO_V9 §2: this is the site that "orders namesakes", so it is the site that has to
732
- // say what it orders by. `compareReferential` is referential DESC with raw population as
733
- // the tiebreak, which is provably the SAME ORDER as the `(b.population ?? 0) - (a.population ?? 0)`
734
- // it replaces — referential is strictly increasing in population below saturation and
735
- // constant above it, and the tiebreak restores the order in the saturated tail. Measured
736
- // zero-delta, not assumed: see `place-importance-schema.test.ts` and `resolver-referential-ranking.test.ts`.
737
- // Encyclopedic importance is not, and must not become, an input here.
738
- const hasHints = !!query.near || (query.bias?.length ?? 0) > 0;
739
- candidates.sort((a, b) => {
740
- const ax = kind(a);
741
- const bx = kind(b);
742
- if (bx !== ax)
743
- return bx - ax;
744
- if (ax >= 1) {
745
- if (hasHints)
746
- return (b.prominence ?? 0) - (a.prominence ?? 0) || b.score - a.score;
747
- return compareReferential(a, b) || b.score - a.score;
748
- }
749
- return b.score - a.score;
750
- });
751
- return candidates.slice(0, limit);
752
- }
753
- }
754
- candidates.sort((a, b) => b.score - a.score);
755
465
  return candidates.slice(0, limit);
756
466
  }
757
467
  #isLocalityQuery(query) {
@@ -809,10 +519,8 @@ export class WOFSqlitePlaceLookup {
809
519
  const pc = query.postcode.trim();
810
520
  const pcWhere = query.country ? "postcode = ? AND country = ?" : "postcode = ?";
811
521
  const pcParams = query.country ? [pc, query.country] : [pc];
812
- const pcRows = this.#db
813
- .prepare(`SELECT locality_id AS id, aliases, distance_km AS dist, is_containing AS containing
814
- FROM ${sch}.${POSTCODE_LOCALITY_TABLE} WHERE ${pcWhere}`)
815
- .all(...pcParams);
522
+ const pcRows = allRows(this.#db.prepare(`SELECT locality_id AS id, aliases, distance_km AS dist, is_containing AS containing
523
+ FROM ${sch}.${POSTCODE_LOCALITY_TABLE} WHERE ${pcWhere}`), ...pcParams);
816
524
  if (!pcRows.length)
817
525
  return null;
818
526
  const limit = query.limit ?? 10;
@@ -905,12 +613,10 @@ export class WOFSqlitePlaceLookup {
905
613
  const popSelect = hasPop ? `pp.population AS population` : `NULL AS population`;
906
614
  const popJoin = hasPop ? `LEFT JOIN main.${PLACE_POPULATION_TABLE} pp ON pp.id = s.id` : "";
907
615
  const ph = ids.map(() => "?").join(", ");
908
- const rows = this.#db
909
- .prepare(`SELECT s.id AS id, s.name AS name, s.country AS country, s.parent_id AS parent_id,
616
+ const rows = allRows(this.#db.prepare(`SELECT s.id AS id, s.name AS name, s.country AS country, s.parent_id AS parent_id,
910
617
  s.latitude AS lat, s.longitude AS lon, s.placetype AS placetype, ${popSelect}
911
618
  FROM main.spr s ${popJoin}
912
- WHERE s.id IN (${ph}) AND s.is_current != 0`)
913
- .all(...ids);
619
+ WHERE s.id IN (${ph}) AND s.is_current != 0`), ...ids);
914
620
  return rows.map((row) => {
915
621
  const c = {
916
622
  id: row.id,
@@ -928,85 +634,6 @@ export class WOFSqlitePlaceLookup {
928
634
  return c;
929
635
  });
930
636
  }
931
- /**
932
- * Among `ids`, return the subset whose name OR any alias equals `text` case-insensitively — the exact-match tier for
933
- * ranking. One indexed query over `<schema>.names`. When the shard has no `names` table (a slim DB built with
934
- * `dropNames`, or a postcode-only shard), fall back to the self-contained `place_search` FTS content: its `alt_names`
935
- * column is the same alias set joined on the boundary-preserving `ALIAS_SEPARATOR` (#523), so `aliasBagExactMatch`
936
- * recovers the exact alias tier ("New York City" → New York) that the dropped `names` table used to provide.
937
- */
938
- #exactMatchIds(schemaName, ids, text) {
939
- const out = new Set();
940
- const trimmed = text.trim();
941
- if (!ids.length || !trimmed)
942
- return out;
943
- const placeholders = ids.map(() => "?").join(", ");
944
- try {
945
- const rows = this.#db
946
- .prepare(`SELECT DISTINCT id FROM ${schemaName}.names WHERE id IN (${placeholders}) AND name = ? COLLATE NOCASE`)
947
- .all(...ids, trimmed);
948
- for (const r of rows) {
949
- out.add(r.id);
950
- }
951
- return out;
952
- }
953
- catch {
954
- // No `names` table on this shard — fall through to the place_search alias bag.
955
- }
956
- try {
957
- const rows = this.#db
958
- .prepare(`SELECT wof_id AS id, name, alt_names FROM ${schemaName}.place_search WHERE wof_id IN (${placeholders})`)
959
- .all(...ids);
960
- const norm = (s) => s.toLowerCase().trim().replaceAll(/\s+/g, " ");
961
- const needle = norm(trimmed);
962
- for (const r of rows) {
963
- if (r.name !== null && norm(r.name) === needle) {
964
- out.add(r.id);
965
- }
966
- }
967
- // Alias pass via the shared bag parser (#523). Separated bags (built since #523) get a true
968
- // per-alias equality check, ungated — matching the `names`-table branch above, where an
969
- // alias match counts as exact regardless of other candidates. Legacy bags (no separator)
970
- // fall back to padded containment, gated on "no canonical exact in the pool" because their
971
- // lost boundaries would otherwise false-promote interior fragments ("York" inside the alias
972
- // "New York City") or cross-alias fragments ("York New" across "…York" + "New City…").
973
- const anyCanonicalExact = out.size > 0;
974
- for (const r of rows) {
975
- if (aliasBagExactMatch(r.alt_names, needle, anyCanonicalExact)) {
976
- out.add(r.id);
977
- }
978
- }
979
- }
980
- catch {
981
- // Shard without place_search either → no exact-match tier. Falls back to weighted-sum order.
982
- }
983
- return out;
984
- }
985
- /**
986
- * Among `ids` (already known exact matches), the subset holding `text` as an OFFICIAL name (`names.official = 1`, the
987
- * #940 ingest bit). Same COLLATE NOCASE semantics as {@link WOFSqlitePlaceLookup.#exactMatchIds} so the two probes
988
- * agree on what "equals the query" means. Fails soft on gazetteers built before #940 (no `official` column) — the
989
- * sub-tier then behaves exactly as if `officialNameExact` were off.
990
- */
991
- #officialNameIds(schemaName, ids, text) {
992
- const out = new Set();
993
- const trimmed = text.trim();
994
- if (!ids.length || !trimmed)
995
- return out;
996
- const placeholders = ids.map(() => "?").join(", ");
997
- try {
998
- const rows = this.#db
999
- .prepare(`SELECT DISTINCT id FROM ${schemaName}.names WHERE id IN (${placeholders}) AND official = 1 AND name = ? COLLATE NOCASE`)
1000
- .all(...ids, trimmed);
1001
- for (const r of rows) {
1002
- out.add(r.id);
1003
- }
1004
- }
1005
- catch {
1006
- // Pre-#940 gazetteer (no `official` column) or a names-less slim shard — feature inert.
1007
- }
1008
- return out;
1009
- }
1010
637
  close() {
1011
638
  // Destroying the Kysely instance closes the underlying connection IF we own it. If the caller
1012
639
  // passed in a pre-opened DatabaseSync (test fixture), respect their ownership.
@@ -1026,9 +653,8 @@ export class WOFSqlitePlaceLookup {
1026
653
  }
1027
654
  #assertFTSExists() {
1028
655
  if (!placeSearchFTSExists(this.#db)) {
1029
- throw new Error("WOFSqlitePlaceLookup: `place_search` FTS5 table is missing. Pass `buildFTS: true` to build it on open, or run `mailwoman gazetteer build fts <path-to-wof.db>` ahead of time (see resolver-wof-sqlite/README.md).");
656
+ throw new Error("WOFSQLitePlaceLookup: `place_search` FTS5 table is missing. Pass `buildFTS: true` to build it on open, or run `mailwoman gazetteer build fts <path-to-wof.db>` ahead of time (see resolver-wof-sqlite/README.md).");
1030
657
  }
1031
658
  }
1032
659
  }
1033
- export { trigramJaccard, trigrams } from "./name-score.js";
1034
660
  //# sourceMappingURL=lookup.js.map