@mailwoman/resolver-wof-sqlite 8.1.0 → 8.3.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 (217) hide show
  1. package/address-point-interpolation.ts +9 -3
  2. package/address-point-schema.ts +32 -10
  3. package/address-point.ts +3 -0
  4. package/ancestry-backfill.ts +18 -5
  5. package/ancestry.ts +7 -2
  6. package/build-candidate.ts +29 -6
  7. package/build-slim.ts +40 -11
  8. package/candidate-fts.ts +1 -0
  9. package/candidate-lookup.ts +36 -14
  10. package/candidate-schema.ts +35 -11
  11. package/coincident-roles.ts +28 -6
  12. package/convention.ts +3 -1
  13. package/coverage-manifest-schema.ts +49 -16
  14. package/fst-autocomplete.ts +15 -9
  15. package/fst-builder.ts +29 -5
  16. package/fst-deserialize-web.ts +46 -9
  17. package/fst-matcher.ts +12 -5
  18. package/fst-serialize.ts +83 -9
  19. package/fst-types.ts +26 -3
  20. package/fts-query.ts +84 -0
  21. package/fts.ts +35 -9
  22. package/geo.ts +9 -3
  23. package/geonames-aliases.ts +116 -79
  24. package/geonames-postal.ts +25 -5
  25. package/index.ts +10 -0
  26. package/interpolation.ts +33 -55
  27. package/lookup.ts +103 -292
  28. package/name-score.ts +76 -0
  29. package/out/address-point-interpolation.d.ts.map +1 -1
  30. package/out/address-point-interpolation.js +4 -2
  31. package/out/address-point-interpolation.js.map +1 -1
  32. package/out/address-point-schema.d.ts +30 -10
  33. package/out/address-point-schema.d.ts.map +1 -1
  34. package/out/address-point-schema.js +6 -2
  35. package/out/address-point-schema.js.map +1 -1
  36. package/out/address-point.d.ts.map +1 -1
  37. package/out/address-point.js.map +1 -1
  38. package/out/ancestry-backfill.d.ts +6 -2
  39. package/out/ancestry-backfill.d.ts.map +1 -1
  40. package/out/ancestry-backfill.js +7 -3
  41. package/out/ancestry-backfill.js.map +1 -1
  42. package/out/ancestry.d.ts +6 -2
  43. package/out/ancestry.d.ts.map +1 -1
  44. package/out/ancestry.js +3 -1
  45. package/out/ancestry.js.map +1 -1
  46. package/out/build-candidate.d.ts +9 -3
  47. package/out/build-candidate.d.ts.map +1 -1
  48. package/out/build-candidate.js +5 -3
  49. package/out/build-candidate.js.map +1 -1
  50. package/out/build-slim.d.ts +15 -5
  51. package/out/build-slim.d.ts.map +1 -1
  52. package/out/build-slim.js +11 -5
  53. package/out/build-slim.js.map +1 -1
  54. package/out/candidate-fts.d.ts.map +1 -1
  55. package/out/candidate-fts.js.map +1 -1
  56. package/out/candidate-lookup.d.ts +9 -3
  57. package/out/candidate-lookup.d.ts.map +1 -1
  58. package/out/candidate-lookup.js +16 -11
  59. package/out/candidate-lookup.js.map +1 -1
  60. package/out/candidate-schema.d.ts +33 -11
  61. package/out/candidate-schema.d.ts.map +1 -1
  62. package/out/candidate-schema.js.map +1 -1
  63. package/out/coincident-roles.d.ts +16 -4
  64. package/out/coincident-roles.d.ts.map +1 -1
  65. package/out/coincident-roles.js +9 -3
  66. package/out/coincident-roles.js.map +1 -1
  67. package/out/convention.d.ts +3 -1
  68. package/out/convention.d.ts.map +1 -1
  69. package/out/convention.js.map +1 -1
  70. package/out/coverage-manifest-schema.d.ts +45 -14
  71. package/out/coverage-manifest-schema.d.ts.map +1 -1
  72. package/out/coverage-manifest-schema.js +14 -5
  73. package/out/coverage-manifest-schema.js.map +1 -1
  74. package/out/fst-autocomplete.d.ts +1 -1
  75. package/out/fst-autocomplete.d.ts.map +1 -1
  76. package/out/fst-autocomplete.js +11 -9
  77. package/out/fst-autocomplete.js.map +1 -1
  78. package/out/fst-builder.d.ts.map +1 -1
  79. package/out/fst-builder.js +15 -5
  80. package/out/fst-builder.js.map +1 -1
  81. package/out/fst-deserialize-web.d.ts.map +1 -1
  82. package/out/fst-deserialize-web.js +34 -9
  83. package/out/fst-deserialize-web.js.map +1 -1
  84. package/out/fst-matcher.d.ts +6 -2
  85. package/out/fst-matcher.d.ts.map +1 -1
  86. package/out/fst-matcher.js +9 -5
  87. package/out/fst-matcher.js.map +1 -1
  88. package/out/fst-serialize.d.ts.map +1 -1
  89. package/out/fst-serialize.js +62 -9
  90. package/out/fst-serialize.js.map +1 -1
  91. package/out/fst-types.d.ts +26 -3
  92. package/out/fst-types.d.ts.map +1 -1
  93. package/out/fts-query.d.ts +41 -0
  94. package/out/fts-query.d.ts.map +1 -0
  95. package/out/fts-query.js +75 -0
  96. package/out/fts-query.js.map +1 -0
  97. package/out/fts.d.ts +21 -7
  98. package/out/fts.d.ts.map +1 -1
  99. package/out/fts.js +10 -4
  100. package/out/fts.js.map +1 -1
  101. package/out/geo.d.ts +6 -2
  102. package/out/geo.d.ts.map +1 -1
  103. package/out/geo.js +3 -1
  104. package/out/geo.js.map +1 -1
  105. package/out/geonames-aliases.d.ts +12 -4
  106. package/out/geonames-aliases.d.ts.map +1 -1
  107. package/out/geonames-aliases.js +72 -67
  108. package/out/geonames-aliases.js.map +1 -1
  109. package/out/geonames-postal.d.ts +9 -3
  110. package/out/geonames-postal.d.ts.map +1 -1
  111. package/out/geonames-postal.js +7 -2
  112. package/out/geonames-postal.js.map +1 -1
  113. package/out/index.d.ts.map +1 -1
  114. package/out/index.js.map +1 -1
  115. package/out/interpolation.d.ts +18 -6
  116. package/out/interpolation.d.ts.map +1 -1
  117. package/out/interpolation.js +11 -40
  118. package/out/interpolation.js.map +1 -1
  119. package/out/lookup.d.ts +3 -97
  120. package/out/lookup.d.ts.map +1 -1
  121. package/out/lookup.js +52 -184
  122. package/out/lookup.js.map +1 -1
  123. package/out/name-score.d.ts +28 -0
  124. package/out/name-score.d.ts.map +1 -0
  125. package/out/name-score.js +67 -0
  126. package/out/name-score.js.map +1 -0
  127. package/out/poi-lookup.d.ts +24 -8
  128. package/out/poi-lookup.d.ts.map +1 -1
  129. package/out/poi-lookup.js +27 -13
  130. package/out/poi-lookup.js.map +1 -1
  131. package/out/poi-schema.d.ts +42 -13
  132. package/out/poi-schema.d.ts.map +1 -1
  133. package/out/poi-schema.js +12 -3
  134. package/out/poi-schema.js.map +1 -1
  135. package/out/postal-city-alias-lookup.d.ts +18 -6
  136. package/out/postal-city-alias-lookup.d.ts.map +1 -1
  137. package/out/postal-city-alias-lookup.js.map +1 -1
  138. package/out/postal-city-alias-schema.d.ts +27 -9
  139. package/out/postal-city-alias-schema.d.ts.map +1 -1
  140. package/out/postal-city-alias-schema.js +3 -1
  141. package/out/postal-city-alias-schema.js.map +1 -1
  142. package/out/postal-city-candidate-schema.d.ts +15 -5
  143. package/out/postal-city-candidate-schema.d.ts.map +1 -1
  144. package/out/postal-city-candidate-schema.js +3 -1
  145. package/out/postal-city-candidate-schema.js.map +1 -1
  146. package/out/postcode-point-lookup.d.ts +6 -2
  147. package/out/postcode-point-lookup.d.ts.map +1 -1
  148. package/out/postcode-point-lookup.js +6 -2
  149. package/out/postcode-point-lookup.js.map +1 -1
  150. package/out/ranking-weights.d.ts +118 -0
  151. package/out/ranking-weights.d.ts.map +1 -0
  152. package/out/ranking-weights.js +44 -0
  153. package/out/ranking-weights.js.map +1 -0
  154. package/out/reverse.d.ts +9 -3
  155. package/out/reverse.d.ts.map +1 -1
  156. package/out/reverse.js +20 -6
  157. package/out/reverse.js.map +1 -1
  158. package/out/sharding.d.ts +3 -1
  159. package/out/sharding.d.ts.map +1 -1
  160. package/out/sharding.js +7 -5
  161. package/out/sharding.js.map +1 -1
  162. package/out/sqlite-convention-source.d.ts.map +1 -1
  163. package/out/sqlite-convention-source.js +3 -1
  164. package/out/sqlite-convention-source.js.map +1 -1
  165. package/out/street-centroid-schema.d.ts +33 -11
  166. package/out/street-centroid-schema.d.ts.map +1 -1
  167. package/out/street-centroid-schema.js +3 -1
  168. package/out/street-centroid-schema.js.map +1 -1
  169. package/out/street-centroid.d.ts.map +1 -1
  170. package/out/street-centroid.js +6 -2
  171. package/out/street-centroid.js.map +1 -1
  172. package/out/street-morphology-fst-builder.d.ts +6 -2
  173. package/out/street-morphology-fst-builder.d.ts.map +1 -1
  174. package/out/street-morphology-fst-builder.js +8 -7
  175. package/out/street-morphology-fst-builder.js.map +1 -1
  176. package/out/street-morphology-fst-loader.d.ts +24 -8
  177. package/out/street-morphology-fst-loader.d.ts.map +1 -1
  178. package/out/street-morphology-fst-loader.js +11 -5
  179. package/out/street-morphology-fst-loader.js.map +1 -1
  180. package/out/street-name-lookup.d.ts +9 -3
  181. package/out/street-name-lookup.d.ts.map +1 -1
  182. package/out/street-name-lookup.js +9 -7
  183. package/out/street-name-lookup.js.map +1 -1
  184. package/out/street-normalize.d.ts +3 -1
  185. package/out/street-normalize.d.ts.map +1 -1
  186. package/out/street-normalize.js +23 -13
  187. package/out/street-normalize.js.map +1 -1
  188. package/out/street-segment-schema.d.ts +48 -16
  189. package/out/street-segment-schema.d.ts.map +1 -1
  190. package/out/street-segment-schema.js +6 -2
  191. package/out/street-segment-schema.js.map +1 -1
  192. package/out/types.d.ts +18 -6
  193. package/out/types.d.ts.map +1 -1
  194. package/out/unified-schema.d.ts +1 -1
  195. package/out/unified-schema.d.ts.map +1 -1
  196. package/out/unified-schema.js +2 -2
  197. package/out/unified-schema.js.map +1 -1
  198. package/package.json +5 -5
  199. package/poi-lookup.ts +53 -21
  200. package/poi-schema.ts +43 -13
  201. package/postal-city-alias-lookup.ts +20 -6
  202. package/postal-city-alias-schema.ts +28 -9
  203. package/postal-city-candidate-schema.ts +15 -5
  204. package/postcode-point-lookup.ts +6 -2
  205. package/ranking-weights.ts +148 -0
  206. package/reverse.ts +47 -10
  207. package/sharding.ts +13 -6
  208. package/sqlite-convention-source.ts +4 -1
  209. package/street-centroid-schema.ts +35 -11
  210. package/street-centroid.ts +10 -3
  211. package/street-morphology-fst-builder.ts +25 -9
  212. package/street-morphology-fst-loader.ts +26 -10
  213. package/street-name-lookup.ts +19 -7
  214. package/street-normalize.ts +28 -13
  215. package/street-segment-schema.ts +50 -16
  216. package/types.ts +18 -6
  217. package/unified-schema.ts +11 -2
@@ -37,13 +37,17 @@ export class WOFPostcodeLookup {
37
37
  readonly #dbs: DatabaseSync[]
38
38
  readonly #stmts: ReturnType<DatabaseSync["prepare"]>[]
39
39
 
40
- /** Open each shard read-only and prepare its exact-match statement. */
40
+ /**
41
+ * Open each shard read-only and prepare its exact-match statement.
42
+ */
41
43
  constructor(dbPaths: readonly string[]) {
42
44
  this.#dbs = dbPaths.map((p) => new DatabaseSync(p, { readOnly: true }))
43
45
  this.#stmts = this.#dbs.map((db) => db.prepare(LOOKUP_SQL))
44
46
  }
45
47
 
46
- /** Exact-match the postcode across every shard and union the rows. */
48
+ /**
49
+ * Exact-match the postcode across every shard and union the rows.
50
+ */
47
51
  lookup(postcode: string): PostcodePlace[] {
48
52
  const out: PostcodePlace[] = []
49
53
 
@@ -0,0 +1,148 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The locality-ranking weights and their shipped defaults. Its own module because every value here is
7
+ * a measured tuning decision with its rationale attached — the block reads as a reference table, not
8
+ * as part of the lookup's control flow, and the tests import it directly to pin one lever at a time.
9
+ */
10
+
11
+ /**
12
+ * Ranking weights for `findPlace`. Tweakable per-instance but defaults match the values declared in the Phase 4.2 plan
13
+ * doc.
14
+ */
15
+ export interface RankingWeights {
16
+ /**
17
+ * Boost when the candidate's placetype matches an explicit `placetype` filter.
18
+ */
19
+ placetypeMatchBoost: number
20
+ /**
21
+ * Boost when the candidate is a locality and no explicit placetype was requested.
22
+ */
23
+ localityImplicitBoost: number
24
+ /**
25
+ * Boost when the candidate's country matches an explicit `country` filter.
26
+ */
27
+ countryMatchBoost: number
28
+ /**
29
+ * Boost when the candidate is a direct child of the requested `parentID`.
30
+ */
31
+ directChildBoost: number
32
+ /**
33
+ * Boost when the candidate is a transitive descendant of the requested `parentID`.
34
+ */
35
+ descendantBoost: number
36
+ /**
37
+ * Multiplier on the length-penalty term (penalizes much-longer-than-query names).
38
+ */
39
+ lengthPenaltyWeight: number
40
+ /**
41
+ * Magnitude of the proximity boost when the query carries `near`. The contribution is `proximityBoost / (1 +
42
+ * distanceKm / proximityScaleKm)` — at distance 0 the boost is full magnitude, at `proximityScaleKm` it's half,
43
+ * decaying further with distance. Default tuned so proximity can overcome a typical FTS rank tie but not dominate a
44
+ * strong text match.
45
+ */
46
+ proximityBoost: number
47
+ /**
48
+ * Magnitude of the bias-hint term inside the exact-tier PROMINENCE sort (the `bias`/viewport path). Deliberately
49
+ * population-scale (default = populationBoost) so a candidate near the map view / the user beats a distant-but-bigger
50
+ * namesake — "the map view wins" is the feature; same-region ties (all candidates far from every hint) still fall to
51
+ * population.
52
+ */
53
+ biasBoost: number
54
+ /**
55
+ * Distance (km) at which the proximity boost halves. Tune to the typical query radius.
56
+ */
57
+ proximityScaleKm: number
58
+ /**
59
+ * Magnitude of the population boost when the candidate has a known `wof:population`. The contribution is
60
+ * `populationBoost * log10(1 + population) / populationScaleLog10`, capped at `populationBoost`. WOF only carries
61
+ * population for ~15% of localities (mostly larger ones); places without it get +0 (never a penalty). Default tuned
62
+ * so the famous Springfield, IL (pop ~112k) gets ~0.42 boost — enough to nudge past tiny same-name peers.
63
+ */
64
+ populationBoost: number
65
+ /**
66
+ * Population (in log10) at which the boost reaches its full magnitude. Default 6 — i.e. a population of 1,000,000
67
+ * gives `populationBoost` exactly. Larger populations cap at the same value (no compounding effect for megacities).
68
+ */
69
+ populationScaleLog10: number
70
+ /**
71
+ * Tier candidates with an EXACT name/alias match above candidates that only match partially, BEFORE the weighted-sum
72
+ * score is consulted. Default true.
73
+ *
74
+ * Why this is needed (and why it ALIGNS with — rather than overrides — the population/importance signal): the
75
+ * weighted sum adds population as a large additive boost (`populationBoost`, up to +4) so that famous places surface
76
+ * for unambiguous full-name queries. But population is a _prominence prior_ — its job is to break ties among
77
+ * candidates that match the query EQUALLY WELL (e.g. "Springfield" → Springfield IL over Springfield MA, both exact
78
+ * name matches). It was never meant to promote a place that matches the query WORSE. For a 2-letter region
79
+ * abbreviation that backfires: querying "ME" returns Maine (which has the exact alias `ME`) AND Missouri/
80
+ * Michigan/etc. (which do not), and Missouri's larger population (+4) overcomes Maine's bm25 edge — so "Portland, ME"
81
+ * resolves its region to Missouri and the locality then cascades to the wrong state. Tiering restores the intended
82
+ * ordering: **match quality is the primary key, prominence (population) the secondary key WITHIN a tier.**
83
+ * Springfield-IL-over-MA still works (both exact → same tier → population decides); ME→Maine now works (only Maine is
84
+ * exact → higher tier → population never gets to override it). See
85
+ * docs/articles/evals/resolver-geo/2026-05-30-resolver-exact-match.md.
86
+ *
87
+ * Note: tiering re-ranks within the over-fetched candidate window (`limit * 4`); a pathological exact match that
88
+ * falls outside that window is not rescued. For the region-abbrev case the window is comfortably sufficient (a
89
+ * handful of states match a 2-letter query).
90
+ */
91
+ exactMatchTiering: boolean
92
+ /**
93
+ * #936 option 3 — official-language names ARE names. When true, a candidate holding the query as an OFFICIAL name
94
+ * (`names.official = 1`: a preferred-form name in an official language of its country, stamped at ingest) joins the
95
+ * NAME-exact sub-tier rather than the alias-exact one, provided its population clears {@link officialNameExactFloor}.
96
+ * Fixes unscoped "Åbo" → Turku (its official Swedish name) over a hamlet literally named Åbo; population still orders
97
+ * within the sub-tier, so Paris → Paris FR is untouched.
98
+ *
99
+ * Default true (operator-promoted 2026-07-03 after the pre-registered gate battery: four intended exonym flips —
100
+ * Berne→Bern, Bruges→Brugge, Roma→Rome, Åbo→Turku — with the namesake/abbreviation rows and the US/FI panels
101
+ * byte-identical). Requires a gazetteer carrying the #940 ingest bit — on older DBs without the `official` column the
102
+ * probe fails soft and behavior is identical to the flag being off.
103
+ */
104
+ officialNameExact: boolean
105
+ /**
106
+ * Minimum population for a candidate's official names to join the name-exact sub-tier. The #936 review's no-floor
107
+ * census measured the boundary: ≥100k holders are the famous-exonym class (757 flips, intent-correct; 7 collisions,
108
+ * none harmful) while 10k–100k holders are junk-dominated (3,481 flips led by short-form mis-tags — Villeneuve-Loubet
109
+ * carrying "villeneuve" would bury five real villages of that name). Rank-time knob: tunable without re-ingest;
110
+ * below-floor official names simply stay alias-tier (today's behavior).
111
+ */
112
+ officialNameExactFloor: number
113
+ }
114
+
115
+ /**
116
+ * The shipped weights. Every value is a measured decision — change one and re-run the resolver eval; the per-field docs
117
+ * on {@link RankingWeights} say what each lever moves and what motivated its current value.
118
+ */
119
+ export const DEFAULT_WEIGHTS: RankingWeights = {
120
+ placetypeMatchBoost: 0.5,
121
+ localityImplicitBoost: 0.2,
122
+ countryMatchBoost: 0.3,
123
+ directChildBoost: 0.5,
124
+ descendantBoost: 0.2,
125
+ lengthPenaltyWeight: 0.1,
126
+ proximityBoost: 0.8,
127
+ proximityScaleKm: 100,
128
+ biasBoost: 4,
129
+ // populationBoost is intentionally large — empirical tuning against real WOF showed BM25 gaps
130
+ // of 1.5-3.0 between famous places and tiny same-name peers (because the famous ones have
131
+ // hundreds of alt-name entries that hurt their FTS document score). To consistently surface
132
+ // "the famous one" for unambiguous queries like "New York" or "Chicago", the population signal
133
+ // needs to dominate. Callers wanting a more conservative balance can drop this in the
134
+ // RankingWeights override.
135
+ //
136
+ // Note: this resolver uses `place_population` directly. The separate `place_importance` table
137
+ // (Wikipedia-derived) is consumed by the FST layer, not here. See
138
+ // docs/articles/concepts/importance-vs-population.md for the two-signal contract.
139
+ populationBoost: 4,
140
+ populationScaleLog10: 6,
141
+ // Exact name/alias match outranks partial match before the weighted sum (incl. population) is
142
+ // consulted — keeps population as an intra-tier prominence tiebreaker, not a cross-tier promoter.
143
+ // Fixes the 2-letter-region-abbrev bug ("ME" → Maine, not the more-populous Missouri).
144
+ exactMatchTiering: true,
145
+ // #936 option 3 — promoted default-ON 2026-07-03 (gate battery PASS; see the RankingWeights docstring).
146
+ officialNameExact: true,
147
+ officialNameExactFloor: 100_000,
148
+ }
package/reverse.ts CHANGED
@@ -35,6 +35,16 @@ import { PLACE_BBOX_TABLE } from "./fts.ts"
35
35
  import { geometryContains, haversineKm, type GeojsonGeometry } from "./geo.ts"
36
36
  import type { PlaceCandidate, WOFPlacetype } from "./types.ts"
37
37
 
38
+ /**
39
+ * Largest absolute latitude in WGS-84 degrees.
40
+ */
41
+ const MAX_ABS_LATITUDE = 90
42
+
43
+ /**
44
+ * Largest absolute longitude in WGS-84 degrees.
45
+ */
46
+ const MAX_ABS_LONGITUDE = 180
47
+
38
48
  /**
39
49
  * How the deepest returned place was confirmed:
40
50
  *
@@ -52,7 +62,9 @@ export interface ReverseGeocodeResult {
52
62
  * ocean, or outside the gazetteer's coverage).
53
63
  */
54
64
  hierarchy: PlaceCandidate[]
55
- /** Containment kind of the DEEPEST place in `hierarchy` (see {@link ContainmentKind}). */
65
+ /**
66
+ * Containment kind of the DEEPEST place in `hierarchy` (see {@link ContainmentKind}).
67
+ */
56
68
  containment: ContainmentKind
57
69
  }
58
70
 
@@ -62,14 +74,18 @@ export interface WOFReverseGeocoderOpts {
62
74
  * package-built `place_bbox` R*Tree (`mailwoman gazetteer build fts`). Mutually exclusive with `adminDatabase`.
63
75
  */
64
76
  adminDBPath?: string
65
- /** Pre-opened admin DB — primarily for tests against an inline fixture. */
77
+ /**
78
+ * Pre-opened admin DB — primarily for tests against an inline fixture.
79
+ */
66
80
  adminDatabase?: DatabaseSync
67
81
  /**
68
82
  * Path to the polygon sidecar DB (`wof-polygons.db`, table `polygons(id, geom)`). OPTIONAL — without it every result
69
83
  * is `containment: "approximate"` (centroid-only mode). Mutually exclusive with `polygonDatabase`.
70
84
  */
71
85
  polygonDBPath?: string
72
- /** Pre-opened polygon DB — primarily for tests. */
86
+ /**
87
+ * Pre-opened polygon DB — primarily for tests.
88
+ */
73
89
  polygonDatabase?: DatabaseSync
74
90
  }
75
91
 
@@ -108,7 +124,9 @@ const DESCENT_TIERS: readonly WOFPlacetype[] = [
108
124
  "microhood",
109
125
  ]
110
126
 
111
- /** Internal candidate row off `spr` (+ optional bbox area / centroid distance bookkeeping). */
127
+ /**
128
+ * Internal candidate row off `spr` (+ optional bbox area / centroid distance bookkeeping).
129
+ */
112
130
  interface CandidateRow {
113
131
  id: number
114
132
  name: string
@@ -167,8 +185,10 @@ export class WOFReverseGeocoder implements Disposable {
167
185
 
168
186
  this.#admin = opts.adminDatabase ?? new DatabaseSync(opts.adminDBPath!, { readOnly: true })
169
187
  this.#ownsAdmin = !opts.adminDatabase
188
+
170
189
  this.#polygons =
171
190
  opts.polygonDatabase ?? (opts.polygonDBPath ? new DatabaseSync(opts.polygonDBPath, { readOnly: true }) : null)
191
+
172
192
  this.#ownsPolygons = !opts.polygonDatabase && Boolean(opts.polygonDBPath)
173
193
 
174
194
  // Fail loudly up front — the R*Tree is a build artifact, not part of the upstream WOF
@@ -213,9 +233,15 @@ export class WOFReverseGeocoder implements Disposable {
213
233
  * whose `POIIntentOutcome` return type is synchronous by contract — see `poi-intent.ts`'s `deps.execute`).
214
234
  */
215
235
  reverseGeocodeSync(lat: number, lon: number, opts: ReverseGeocodeOpts = {}): ReverseGeocodeResult {
216
- if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) {
236
+ if (
237
+ !Number.isFinite(lat) ||
238
+ !Number.isFinite(lon) ||
239
+ Math.abs(lat) > MAX_ABS_LATITUDE ||
240
+ Math.abs(lon) > MAX_ABS_LONGITUDE
241
+ ) {
217
242
  throw new RangeError(`WOFReverseGeocoder.reverseGeocode: (${lat}, ${lon}) is not a WGS-84 coordinate`)
218
243
  }
244
+
219
245
  const maxApproximateKm = opts.maxApproximateKm ?? DEFAULT_MAX_APPROXIMATE_KM
220
246
  const candidates = this.#bboxCandidates(lat, lon, opts)
221
247
 
@@ -231,6 +257,7 @@ export class WOFReverseGeocoder implements Disposable {
231
257
  if (contains === true) {
232
258
  winner = c
233
259
  winnerConfirmed = true
260
+
234
261
  break
235
262
  }
236
263
 
@@ -277,6 +304,7 @@ export class WOFReverseGeocoder implements Disposable {
277
304
  next = k
278
305
  nextConfirmed = true
279
306
  nextKm = undefined
307
+
280
308
  break
281
309
  }
282
310
 
@@ -302,8 +330,7 @@ export class WOFReverseGeocoder implements Disposable {
302
330
  // Hierarchy assembly via the shared ancestor walk. If the descent crossed an ancestry gap
303
331
  // (the deepest place's recorded lineage misses the PIP root), merge the root's own chain so
304
332
  // region/country are always present when a polygon confirmed them.
305
- const byID = new Map<number, PlaceCandidate>()
306
- byID.set(current.id, toPlaceCandidate(current, currentDistanceKm))
333
+ const byID = new Map<number, PlaceCandidate>([[current.id, toPlaceCandidate(current, currentDistanceKm)]])
307
334
 
308
335
  for (const a of ancestorLineage(this.#admin, current.id)) {
309
336
  if (!byID.has(a.id)) {
@@ -320,6 +347,7 @@ export class WOFReverseGeocoder implements Disposable {
320
347
  }
321
348
  }
322
349
  }
350
+
323
351
  const hierarchy = [...byID.values()]
324
352
 
325
353
  if (opts.placetypes) {
@@ -331,12 +359,15 @@ export class WOFReverseGeocoder implements Disposable {
331
359
  }
332
360
  }
333
361
  }
362
+
334
363
  hierarchy.sort((a, b) => placetypeDepth(b.placetype) - placetypeDepth(a.placetype))
335
364
 
336
365
  return { hierarchy, containment: currentConfirmed ? "polygon" : "approximate" }
337
366
  }
338
367
 
339
- /** Bbox candidates containing the point, smallest-area-first, via the `place_bbox` R*Tree. */
368
+ /**
369
+ * Bbox candidates containing the point, smallest-area-first, via the `place_bbox` R*Tree.
370
+ */
340
371
  #bboxCandidates(lat: number, lon: number, opts: ReverseGeocodeOpts): CandidateRow[] {
341
372
  const where: string[] = [
342
373
  "bbox.min_lat <= ?",
@@ -346,12 +377,14 @@ export class WOFReverseGeocoder implements Disposable {
346
377
  "spr.is_current != 0",
347
378
  "spr.is_deprecated = 0",
348
379
  ]
380
+
349
381
  const params: Array<number | string> = [lat, lat, lon, lon]
350
382
 
351
- if (opts.placetypes && opts.placetypes.length > 0) {
383
+ if (opts.placetypes && opts.placetypes.length) {
352
384
  where.push(`spr.placetype IN (${opts.placetypes.map(() => "?").join(", ")})`)
353
385
  params.push(...opts.placetypes)
354
386
  }
387
+
355
388
  params.push(opts.maxCandidates ?? DEFAULT_MAX_CANDIDATES)
356
389
 
357
390
  return this.#admin
@@ -398,7 +431,9 @@ export class WOFReverseGeocoder implements Disposable {
398
431
  ) as unknown as CandidateRow[]
399
432
  }
400
433
 
401
- /** Parsed GeoJSON geometry for a WOF id, or null when absent / unparseable / no polygon DB. */
434
+ /**
435
+ * Parsed GeoJSON geometry for a WOF id, or null when absent / unparseable / no polygon DB.
436
+ */
402
437
  #geometry(id: number): GeojsonGeometry | null {
403
438
  if (!this.#polygons) return null
404
439
  const cached = this.#geometryCache.get(id)
@@ -408,6 +443,7 @@ export class WOFReverseGeocoder implements Disposable {
408
443
  if (this.#geometryCache.size >= WOFReverseGeocoder.#GEOMETRY_CACHE_CAP) {
409
444
  this.#geometryCache.clear()
410
445
  }
446
+
411
447
  const row = this.#polygons.prepare(`SELECT geom FROM polygons WHERE id = ?`).get(id) as { geom: string } | undefined
412
448
  let geometry: GeojsonGeometry | null = null
413
449
 
@@ -418,6 +454,7 @@ export class WOFReverseGeocoder implements Disposable {
418
454
  geometry = null // malformed row — treat as no-polygon rather than failing the query
419
455
  }
420
456
  }
457
+
421
458
  this.#geometryCache.set(id, geometry)
422
459
 
423
460
  return geometry
package/sharding.ts CHANGED
@@ -47,7 +47,7 @@ export function deriveSchemaName(path: string): string {
47
47
  .replace(/^whosonfirst-data-/u, "")
48
48
  .replace(/-latest\.db$/u, "")
49
49
  .replace(/\.db$/u, "")
50
- .replace(/[^a-zA-Z0-9_]/g, "_")
50
+ .replaceAll(/[^a-zA-Z0-9_]/g, "_")
51
51
 
52
52
  if (!stem) {
53
53
  throw new Error(`deriveSchemaName: could not derive a SQL schema name from path ${JSON.stringify(path)}`)
@@ -86,7 +86,9 @@ export interface ResolvedShard {
86
86
  placetypes: readonly string[]
87
87
  }
88
88
 
89
- /** SQLite identifier regex — `[A-Za-z_][A-Za-z0-9_]*`. */
89
+ /**
90
+ * SQLite identifier regex — `[A-Za-z_][A-Za-z0-9_]*`.
91
+ */
90
92
  const SQLITE_IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/u
91
93
 
92
94
  /**
@@ -99,7 +101,7 @@ const SQLITE_IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/u
99
101
  export function resolveShards(input: string | ReadonlyArray<string | ShardConfig>): ResolvedShard[] {
100
102
  const list = typeof input === "string" ? [input] : input
101
103
 
102
- if (list.length === 0) throw new Error("resolveShards: at least one shard is required")
104
+ if (!list.length) throw new Error("resolveShards: at least one shard is required")
103
105
 
104
106
  const seen = new Set<string>()
105
107
  const out: ResolvedShard[] = []
@@ -116,6 +118,7 @@ export function resolveShards(input: string | ReadonlyArray<string | ShardConfig
116
118
  `{ path, schemaName } to override.`
117
119
  )
118
120
  }
121
+
119
122
  // The first shard is always main per SQLite semantics — its derived name is informational
120
123
  // only. Subsequent shards must have unique non-main names.
121
124
  const schemaName = i === 0 ? "main" : derived
@@ -126,7 +129,9 @@ export function resolveShards(input: string | ReadonlyArray<string | ShardConfig
126
129
  `(either with "main" or another shard). Pass an explicit { path, schemaName }.`
127
130
  )
128
131
  }
132
+
129
133
  seen.add(schemaName)
134
+
130
135
  out.push({
131
136
  path: cfg.path,
132
137
  schemaName,
@@ -179,7 +184,7 @@ export function pickShardsForPlacetype(shards: ResolvedShard[], placetype: strin
179
184
  }
180
185
  }
181
186
 
182
- return matches.length > 0 ? matches : [shards[0]!]
187
+ return matches.length ? matches : [shards[0]!]
183
188
  }
184
189
 
185
190
  export function pickShardForPlacetype(
@@ -194,7 +199,9 @@ export function pickShardForPlacetype(
194
199
  * order remains the tiebreak when no shard claims the country (or none was probed).
195
200
  */
196
201
  country?: string
197
- /** Per-schema probed country sets (see `WOFSqlitePlaceLookup`'s construction probe). */
202
+ /**
203
+ * Per-schema probed country sets (see `WOFSqlitePlaceLookup`'s construction probe).
204
+ */
198
205
  countriesBySchema?: ReadonlyMap<string, ReadonlySet<string>>
199
206
  }
200
207
  ): ResolvedShard {
@@ -223,7 +230,7 @@ export function pickShardForPlacetype(
223
230
  }
224
231
  }
225
232
 
226
- if (matches.length === 0) return shards[0]!
233
+ if (!matches.length) return shards[0]!
227
234
 
228
235
  if (opts?.country && opts.countriesBySchema) {
229
236
  for (const s of matches) {
@@ -22,7 +22,9 @@ import { ADDRESS_CONVENTION_TABLE, type Convention, type ConventionSource } from
22
22
  export class SqliteConventionSource implements ConventionSource {
23
23
  readonly #db: DatabaseSync
24
24
  readonly #schema: string
25
- /** Memoize per-id lookups (including misses, as `null`) so a hot ancestor chain is queried once. */
25
+ /**
26
+ * Memoize per-id lookups (including misses, as `null`) so a hot ancestor chain is queried once.
27
+ */
26
28
  readonly #cache = new Map<number, Convention | null>()
27
29
 
28
30
  /**
@@ -54,6 +56,7 @@ export class SqliteConventionSource implements ConventionSource {
54
56
  // WORLD_DEFAULT). The build script validates structure, so this is purely defensive.
55
57
  value = null
56
58
  }
59
+
57
60
  this.#cache.set(wofID, value)
58
61
 
59
62
  return value ?? undefined
@@ -29,27 +29,45 @@ import type { Kysely } from "kysely"
29
29
  * bbox diagonal into an honest `uncertainty_m`).
30
30
  */
31
31
  export interface StreetCentroidTable {
32
- /** Shared `normalizeStreetForKeyLocale` of the street — the build/query-consistent probe key. */
32
+ /**
33
+ * Shared `normalizeStreetForKeyLocale` of the street — the build/query-consistent probe key.
34
+ */
33
35
  street_norm: string
34
- /** The 5-digit postcode of this group, or null when the source row carried none. */
36
+ /**
37
+ * The 5-digit postcode of this group, or null when the source row carried none.
38
+ */
35
39
  postcode: string | null
36
- /** Arrondissement-stripped commune (`stripArrondissement(normalizeLocalityForKey(commune))`) — the fallback scope. */
40
+ /**
41
+ * Arrondissement-stripped commune (`stripArrondissement(normalizeLocalityForKey(commune))`) — the fallback scope.
42
+ */
37
43
  locality_base: string
38
- /** Weighted-mean centroid latitude of the street's member points. */
44
+ /**
45
+ * Weighted-mean centroid latitude of the street's member points.
46
+ */
39
47
  lat: number
40
- /** Weighted-mean centroid longitude of the street's member points. */
48
+ /**
49
+ * Weighted-mean centroid longitude of the street's member points.
50
+ */
41
51
  lon: number
42
52
  min_lat: number
43
53
  max_lat: number
44
54
  min_lon: number
45
55
  max_lon: number
46
- /** Member address-point count — the weight for a cross-group centroid aggregate. */
56
+ /**
57
+ * Member address-point count — the weight for a cross-group centroid aggregate.
58
+ */
47
59
  point_count: number
48
- /** A representative street name as it appeared in the source (display / debugging). */
60
+ /**
61
+ * A representative street name as it appeared in the source (display / debugging).
62
+ */
49
63
  street_raw: string
50
- /** Provenance: the register this street was derived from (e.g. `ban:fr`). */
64
+ /**
65
+ * Provenance: the register this street was derived from (e.g. `ban:fr`).
66
+ */
51
67
  source: string
52
- /** The pinned data release the underlying points came from. */
68
+ /**
69
+ * The pinned data release the underlying points came from.
70
+ */
53
71
  release: string
54
72
  /**
55
73
  * #727 phase-4c: `foldStreetSurface(street_raw)` — the contract-fold street-NAME existence key for
@@ -61,7 +79,9 @@ export interface StreetCentroidTable {
61
79
  name_key: string
62
80
  }
63
81
 
64
- /** The street-centroid database schema for `new DatabaseClient<StreetCentroidDatabase>(...)`. */
82
+ /**
83
+ * The street-centroid database schema for `new DatabaseClient<StreetCentroidDatabase>(...)`.
84
+ */
65
85
  export interface StreetCentroidDatabase {
66
86
  street_centroid: StreetCentroidTable
67
87
  }
@@ -87,7 +107,9 @@ export const STREET_CENTROID_COLUMNS = [
87
107
  "name_key",
88
108
  ] as const
89
109
 
90
- /** Create the `street_centroid` table — called before the streaming bulk load. */
110
+ /**
111
+ * Create the `street_centroid` table — called before the streaming bulk load.
112
+ */
91
113
  export async function createStreetCentroidTable(db: Kysely<StreetCentroidDatabase>): Promise<void> {
92
114
  await db.schema
93
115
  .createTable("street_centroid")
@@ -115,10 +137,12 @@ export async function createStreetCentroidTable(db: Kysely<StreetCentroidDatabas
115
137
  */
116
138
  export async function createStreetCentroidIndexes(db: Kysely<StreetCentroidDatabase>): Promise<void> {
117
139
  await db.schema.createIndex("idx_sc_postcode").on("street_centroid").columns(["postcode", "street_norm"]).execute()
140
+
118
141
  await db.schema
119
142
  .createIndex("idx_sc_locality")
120
143
  .on("street_centroid")
121
144
  .columns(["locality_base", "street_norm"])
122
145
  .execute()
146
+
123
147
  await db.schema.createIndex("idx_sc_name").on("street_centroid").columns(["name_key"]).execute()
124
148
  }
@@ -31,7 +31,9 @@ import {
31
31
  stripArrondissement,
32
32
  } from "./street-normalize.ts"
33
33
 
34
- /** The weighted-centroid + extent + provenance an aggregate probe projects. `lat` is null when nothing matched. */
34
+ /**
35
+ * The weighted-centroid + extent + provenance an aggregate probe projects. `lat` is null when nothing matched.
36
+ */
35
37
  interface AggRow {
36
38
  lat: number | null
37
39
  lon: number | null
@@ -43,14 +45,18 @@ interface AggRow {
43
45
  release: string | null
44
46
  }
45
47
 
46
- /** Weighted-centroid aggregate over a WHERE-filtered set. `SUM(coord*n)/SUM(n)` reconstructs the grand centroid. */
48
+ /**
49
+ * Weighted-centroid aggregate over a WHERE-filtered set. `SUM(coord*n)/SUM(n)` reconstructs the grand centroid.
50
+ */
47
51
  const AGG_SELECT =
48
52
  "SUM(lat * point_count) / SUM(point_count) AS lat, " +
49
53
  "SUM(lon * point_count) / SUM(point_count) AS lon, " +
50
54
  "MIN(min_lat) AS min_lat, MAX(max_lat) AS max_lat, MIN(min_lon) AS min_lon, MAX(max_lon) AS max_lon, " +
51
55
  "MAX(source) AS source, MAX(release) AS release"
52
56
 
53
- /** Half the bbox diagonal, in METERS — an honest coarse radius for a street centroid. */
57
+ /**
58
+ * Half the bbox diagonal, in METERS — an honest coarse radius for a street centroid.
59
+ */
54
60
  function extentRadiusM(minLat: number, maxLat: number, minLon: number, maxLon: number): number {
55
61
  const R = 6_371_000
56
62
  const toRad = (d: number): number => (d * Math.PI) / 180
@@ -84,6 +90,7 @@ export class StreetCentroidSqliteLookup implements StreetCentroidLookup {
84
90
  this.#byPostcode = this.#db.prepare(
85
91
  `SELECT ${AGG_SELECT} FROM street_centroid WHERE postcode = ? AND street_norm = ?`
86
92
  )
93
+
87
94
  this.#byLocality = this.#db.prepare(
88
95
  `SELECT ${AGG_SELECT} FROM street_centroid WHERE locality_base = ? AND street_norm = ?`
89
96
  )