@mailwoman/photon 9.4.0 → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +2 -2
  2. package/{lib/cli.ts → cli/main.ts} +40 -54
  3. package/lib/app.ts +13 -18
  4. package/lib/engine.ts +13 -5
  5. package/lib/index.ts +6 -11
  6. package/lib/locality-postcode.ts +9 -13
  7. package/lib/projection.ts +60 -55
  8. package/lib/routes.ts +9 -21
  9. package/lib/schema.ts +31 -24
  10. package/out/app.d.ts +13 -14
  11. package/out/app.d.ts.map +1 -1
  12. package/out/app.js +4 -11
  13. package/out/app.js.map +1 -1
  14. package/out/cli/main.d.ts +12 -0
  15. package/out/cli/main.d.ts.map +1 -0
  16. package/out/{cli.js → cli/main.js} +40 -54
  17. package/out/cli/main.js.map +1 -0
  18. package/out/engine.d.ts +13 -5
  19. package/out/engine.d.ts.map +1 -1
  20. package/out/engine.js +2 -2
  21. package/out/engine.js.map +1 -1
  22. package/out/index.d.ts +6 -11
  23. package/out/index.d.ts.map +1 -1
  24. package/out/index.js +6 -11
  25. package/out/index.js.map +1 -1
  26. package/out/locality-postcode.d.ts +4 -7
  27. package/out/locality-postcode.d.ts.map +1 -1
  28. package/out/locality-postcode.js +8 -12
  29. package/out/locality-postcode.js.map +1 -1
  30. package/out/projection.d.ts +48 -38
  31. package/out/projection.d.ts.map +1 -1
  32. package/out/projection.js +37 -35
  33. package/out/projection.js.map +1 -1
  34. package/out/routes.d.ts +2 -2
  35. package/out/routes.d.ts.map +1 -1
  36. package/out/routes.js +9 -21
  37. package/out/routes.js.map +1 -1
  38. package/out/schema.d.ts +29 -22
  39. package/out/schema.d.ts.map +1 -1
  40. package/out/schema.js +31 -24
  41. package/out/schema.js.map +1 -1
  42. package/package.json +47 -31
  43. package/out/cli.d.ts +0 -17
  44. package/out/cli.d.ts.map +0 -1
  45. package/out/cli.js.map +0 -1
package/README.md CHANGED
@@ -8,7 +8,7 @@ MAILWOMAN_DATA_ROOT="${MAILWOMAN_DATA_ROOT:-/tmp/mailwoman-data}" npx mailwoman
8
8
 
9
9
  MAILWOMAN_DATA_ROOT="${MAILWOMAN_DATA_ROOT:-/tmp/mailwoman-data}" \
10
10
  npx @mailwoman/photon serve --port 2322
11
- # The pulled candidate.db is auto-detected at $MAILWOMAN_DATA_ROOT/wof/candidate.db — no export needed.
11
+ # The pulled candidate.db is auto-detected at $MAILWOMAN_DATA_ROOT/db/wof/candidate.db — no export needed.
12
12
  # Or point at your own data: --candidate-db <path> / $MAILWOMAN_CANDIDATE_DB
13
13
  ```
14
14
 
@@ -22,7 +22,7 @@ curl "http://localhost:2322/reverse?lat=38.8977&lon=-77.0365"
22
22
 
23
23
  ## Endpoints
24
24
 
25
- | Endpoint | Photon contract |
25
+ | Endpoint | Photon interface |
26
26
  | --------------- | ---------------------------------------------------- |
27
27
  | `/` | HTML landing page (endpoint index + example queries) |
28
28
  | `/api` | forward / autocomplete → GeoJSON FeatureCollection |
@@ -4,21 +4,15 @@
4
4
  * @license AGPL-3.0
5
5
  * @author Teffen Ellis, et al.
6
6
  *
7
- * `mailwoman-photon` — boot a Photon-compatible autocomplete endpoint via the `serve` command.
8
- * Usage
9
- *
10
- * - Examples live in the package README.
11
- *
12
- * Wires the real engine: `/api` over `geocodeAddress` (parse → resolve), `/reverse` over
13
- * `WOFReverseGeocoder`, projecting results into Photon's GeoJSON FeatureCollection. The FST
14
- * autocomplete tier is the eventual front for `/api`; geocode resolution is the MVP path.
7
+ * `mailwoman-photon` — boot a Photon-compatible autocomplete endpoint via the `serve` command, wiring
8
+ * `/api` over `geocodeAddress` (parse → resolve) and `/reverse` over `WOFReverseGeocoder` into Photon's
9
+ * GeoJSON FeatureCollection.
15
10
  */
16
11
 
17
12
  import { serveNode } from "@mailwoman/api-kit"
18
13
  import { matchCountry } from "@mailwoman/codex/country"
19
- import { pyTitle } from "@mailwoman/core"
14
+ import { dataRootPath } from "@mailwoman/core/data-root"
20
15
  import { parseArguments } from "@mailwoman/core/scripting/arguments"
21
- import { mailwomanDataRoot } from "@mailwoman/core/utils"
22
16
  import { createWOFResolver } from "@mailwoman/resolver"
23
17
  import {
24
18
  corsBannerLine,
@@ -27,10 +21,11 @@ import {
27
21
  openAPICommand,
28
22
  resolveGazetteerOrExit,
29
23
  runDropInCLI,
30
- } from "mailwoman/cli-kit/dropin"
31
- import type { ResolvedEngineStamp } from "mailwoman/cli-kit/engine-stamp"
32
- import { geocodeAddress, RegionDatabaseProvider } from "mailwoman/geocode"
24
+ } from "mailwoman/cli/kit/dropin"
25
+ import type { ResolvedEngineStamp } from "mailwoman/cli/kit/engine-stamp"
26
+ import { geocodeAddress, USStateDatabaseProvider } from "mailwoman/geocode"
33
27
  import { createResolverBackend } from "mailwoman/resolver-backend"
28
+ import { titleCase } from "spliterator"
34
29
 
35
30
  import {
36
31
  createPhotonApp,
@@ -58,7 +53,9 @@ const PLACETYPE_TO_KEY: Record<string, keyof PhotonProperties> = {
58
53
  }
59
54
 
60
55
  /**
61
- * A real address fits comfortably; longer is malformed input (and would exceed the model's window).
56
+ * A real address fits comfortably.
57
+ *
58
+ * Longer input is malformed and would exceed the model's window.
62
59
  */
63
60
  const MAX_QUERY_LEN = 512
64
61
 
@@ -70,8 +67,8 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
70
67
  port: { type: "string", default: "2322" },
71
68
  host: { type: "string", default: "0.0.0.0" },
72
69
  "candidate-db": { type: "string" },
73
- // Permissive CORS is on by default (upstream Photon parity — browser widgets need it). `--no-cors`
74
- // turns it off for deployments where a reverse proxy already sets the headers.
70
+ // Permissive CORS is on by default for upstream Photon parity; `--no-cors` turns it off
71
+ // where a reverse proxy already sets the headers.
75
72
  cors: { type: "boolean", default: true },
76
73
  },
77
74
  allowNegative: true,
@@ -88,74 +85,64 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
88
85
 
89
86
  const backend = await createResolverBackend(resolverMod, { wofPaths, candidateDB })
90
87
  const resolver = createWOFResolver(backend)
91
- const extracts = await RegionDatabaseProvider.create(resolverMod, mailwomanDataRoot())
88
+ const extracts = await USStateDatabaseProvider.create(resolverMod, dataRootPath())
92
89
  const postcodeOfLocality = await createLocalityPostcodeLookup()
93
- // National open-register rooftop tier (#1012): BAN-FR ahead of the OSM tier for a non-US parse. A no-op
94
- // when the extract isn't on disk (conditioned on existsSync inside the provider), so the endpoint degrades cleanly.
95
- const { BANRegionDatabaseProvider } = await import("@mailwoman/ban/sdk")
96
- const banExtracts = await BANRegionDatabaseProvider.create(mailwomanDataRoot())
90
+ // National open-register rooftop tier: BAN-FR ahead of the OSM tier for a non-US parse,
91
+ // a no-op when the extract is absent.
92
+ const { BANRegionDatabaseProvider } = await import("@mailwoman/ban/region-database-provider")
93
+ const banExtracts = await BANRegionDatabaseProvider.create(dataRootPath())
97
94
  const reverseGeo = adminDBPath ? new resolverMod.WOFReverseGeocoder({ adminDBPath }) : undefined
98
95
 
99
96
  const engine: PhotonEngine = {
100
97
  async search(params) {
101
- // Empty/whitespace → no query; absurdly long → not an address (and would blow the model's input).
102
98
  const query = params.q?.trim()
103
99
 
104
100
  if (!query || query.length > MAX_QUERY_LEN) return photonCollection([])
105
- // #1016: forward the client's viewport/user location as a proximity bias — a SOFT re-rank the resolver
106
- // folds into candidate scoring (Springfield near the map center wins). Only when both coords are present.
101
+ // Forward the client's viewport as a proximity bias, a soft re-rank the resolver
102
+ // folds into candidate scoring, only when both coords are present.
107
103
  const bias = params.lat != null && params.lon != null ? [{ lat: params.lat, lon: params.lon }] : undefined
108
104
 
109
- // No country constraint: the default-on #244 placer routes the query's country (Berlin→DE,
110
- // Boston→US). Forcing "US" here is a HARD override (geocode-core.ts:102) that resolved every
111
- // non-US query to its US namesake — wrong for a global autocomplete front.
105
+ // No country constraint lets the placer route the query's own country.
106
+ // A hard-coded `US` value here would resolve every non-US query to its US namesake.
112
107
  const result = await geocodeAddress(query, {
113
108
  classifier,
114
109
  resolver,
115
110
  databases: extracts.for,
116
111
  nationalDatabases: banExtracts.for,
117
112
  bias,
118
- // Decision A endpoint default: Photon is an autocomplete front — a human typing fragments.
113
+ // Photon is an autocomplete front where a human types fragments.
119
114
  inputMode: "fragmented",
120
115
  })
121
116
 
122
117
  if (result.lat == null || result.lon == null) return photonCollection([])
123
- // #1014: decorate from the RESOLVED gazetteer place — proper-cased ancestry names (`hierarchy[].name`,
124
- // not the parsed span) + the resolved country (ISO2 → canonical name via codex) + osm_key/value/type so
125
- // Photon clients don't TypeError. The candidate backend fills only the locality (no ancestors() table),
126
- // so state/county come through only on an ancestry-capable backend — country still lands from the code.
118
+ // Decorate from the resolved place using proper-cased ancestry names,
119
+ // the resolved country and osm_key/value/type.
120
+ // Include state/county only on an ancestry-capable backend.
127
121
  const country = matchCountry(result.countryCode)
128
122
 
129
- // #1041: a rooftop (`address_point`) or house-number-estimate (`interpolated`) tier is HOUSE-GRADE — carry the
130
- // parsed housenumber + street so photonForwardProperties decorates it `type: house` (matching upstream Photon)
131
- // instead of inheriting the admin locality's `type: city`. The admin tier (a locality centroid) never does.
123
+ // A rooftop or interpolated tier is house-grade: include the parsed housenumber
124
+ // and street so photonForwardProperties decorates it `type: house`
125
+ // rather than the admin locality's `type: city`.
132
126
  const houseGrade =
133
127
  result.resolution_tier === "address_point" ||
134
128
  result.resolution_tier === "interpolated" ||
135
129
  result.resolution_tier === "plus_code"
136
130
 
137
- // #1050: the street-centroid tier is STREET-GRADE — full assembled street name in `name`,
138
- // highway/street osm tags (the parallel of the #1041 house treatment).
131
+ // The street-centroid tier is street-grade: the full assembled street name
132
+ // in `name` plus highway/street osm tags.
139
133
  const streetGrade = result.resolution_tier === "street"
140
134
 
141
- // The register row's own scope tags (result.rooftop) decorate a house-grade answer whose
142
- // hierarchy carries no locality/postcode — the register ATTESTS the rooftop's commune and
143
- // postcode even when the query never named them, and #1014's decorate-from-the-resolved-place
144
- // doctrine covers register attestations exactly as it covers gazetteer rows. The key form is
145
- // normalized; title-case it for display (the extracts store no display-cased locality).
135
+ // The register row's own locality decorates a house-grade answer whose hierarchy
136
+ // has no locality, title-cased because extracts store no display-cased locality.
146
137
  const places = result.hierarchy.map((h) => ({ tag: h.tag, name: h.name }))
147
138
 
148
139
  if (result.rooftop?.localityNorm && !places.some((p) => p.tag === "locality")) {
149
- // The key form is normalized lowercase (the extracts store no display-cased locality);
150
- // pyTitle display-cases it particle-and-apostrophe-aware.
151
- places.push({ tag: "locality", name: pyTitle(result.rooftop.localityNorm) })
140
+ places.push({ tag: "locality", name: titleCase(result.rooftop.localityNorm) })
152
141
  }
153
142
 
154
- // Locality→postcode enrichment: an admin answer for a place whose CONTAINING postcode is
155
- // unambiguous (exactly one) carries that postcode — the register/WOF attests it, the query
156
- // simply never said it. Multi-postcode cities (Paris) get NOTHING: the exactly-one rule is
157
- // the abstention, per the registry doctrine. Keyed by the resolved place's WOF id, so no
158
- // name matching is involved.
143
+ // Locality→postcode enrichment: an admin answer whose containing postcode is
144
+ // unambiguous (exactly one, keyed by the resolved place's WOF ID) includes it.
145
+ // A multi-postcode city gets no postcode.
159
146
  let enrichedPostcode: string | undefined
160
147
 
161
148
  if (!result.postcode && !result.rooftop?.postcode) {
@@ -178,8 +165,8 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
178
165
  ...(streetGrade ? { street: { name: result.street } } : {}),
179
166
  }
180
167
 
181
- // #1016: candidates[0] is the primary itself; its ranked alternatives (Springfield MA/IL/…) become the
182
- // extra features, up to the requested `limit`. Each alternative is a single resolved place.
168
+ // candidates[0] is the primary.
169
+ // Its ranked alternatives become extra features up to the requested `limit`.
183
170
  const alternatives = result.candidates.slice(1).map((c) => {
184
171
  const cc = matchCountry(c.countryCode)
185
172
 
@@ -201,8 +188,7 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
201
188
  if (!hierarchy.length) return photonCollection([])
202
189
  const deepest = hierarchy[0]!
203
190
 
204
- // #1014: carry osm_key/osm_value/type (from the deepest placetype) so /reverse matches /api's schema —
205
- // no Photon client should dereference an undefined osm_key on a reverse result either.
191
+ // Include osm_key/osm_value/type from the deepest placetype so `/reverse` matches `/api`'s schema.
206
192
  const properties: PhotonProperties = {
207
193
  name: deepest.name,
208
194
  countrycode: deepest.country?.toLowerCase(),
package/lib/app.ts CHANGED
@@ -2,9 +2,6 @@
2
2
  * @copyright Sister Software
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
- *
6
- * The Photon-compatible Hono app: CORS + error safety net + routes + the emitted OpenAPI
7
- * document. Engine-agnostic — the CLI wires the real engine; tests inject fixtures.
8
5
  */
9
6
 
10
7
  import { OpenAPIHono } from "@hono/zod-openapi"
@@ -20,25 +17,27 @@ import { registerPhotonRoutes } from "#routes"
20
17
  */
21
18
  export interface PhotonAppOptions {
22
19
  /**
23
- * Emit permissive CORS headers (`Access-Control-Allow-Origin: *`) on every response and answer preflight `OPTIONS`
24
- * with `204`. Default `true` — upstream komoot/photon serves permissive CORS, and the map-widget use case
25
- * (leaflet-control-geocoder, @openrunner/photon-geocoder, …) needs it: a browser's cross-origin XHR is blocked
26
- * without it (#1017). Set `false` when a reverse proxy already owns the CORS headers.
20
+ * Whether to send permissive CORS headers and answer preflight `OPTIONS` requests.
21
+ *
22
+ * It defaults to true because browser map widgets call Photon from other origins.
23
+ * Set it to `false` when a reverse proxy already sets the CORS headers.
27
24
  */
28
25
  cors?: boolean
29
26
 
30
27
  /**
31
- * The engine stamp to carry on every response: `engine` as a foreign member of each FeatureCollection, and the
32
- * `Server` + `Link: rel="license"` headers everywhere. Absent when an embedding application builds the app without
33
- * the `mailwoman` package; the `photon` bin always passes one.
28
+ * The engine stamp added to every FeatureCollection and sent in the `Server`
29
+ * and `Link: rel="license"` headers.
30
+ *
31
+ * The `photon` command always passes one.
32
+ * An embedding application may omit it.
34
33
  */
35
34
  engine?: EngineStamp
36
35
  }
37
36
 
38
37
  /**
39
- * The document info stamped into the emitted OpenAPI document. Exported (not inlined) so the CLI's `openapi` subcommand
40
- * can call `emitOpenAPIDocuments` with the SAME info the mounted `/openapi.json` route (below, via
41
- * {@link attachOpenAPIDocs}) uses — one source of truth, no risk of the two drifting.
38
+ * The OpenAPI document info for the Photon API.
39
+ *
40
+ * The served `/openapi.json` route and the CLI's `openapi` subcommand both use it.
42
41
  */
43
42
  export const PHOTON_DOC_INFO: OpenAPIDocInfo = {
44
43
  ...(await readServedDocumentInfo(import.meta.url, "@mailwoman/photon")),
@@ -62,13 +61,11 @@ export const PHOTON_DOC_INFO: OpenAPIDocInfo = {
62
61
  }
63
62
 
64
63
  /**
65
- * Build the Photon-compatible app around an injected {@link PhotonEngine}.
64
+ * Builds the Photon-compatible app around the given {@link PhotonEngine}.
66
65
  */
67
66
  export function createPhotonApp(engine: PhotonEngine, options: PhotonAppOptions = {}): OpenAPIHono {
68
67
  const app = new OpenAPIHono()
69
68
 
70
- // Browser-embedded widgets need CORS or their cross-origin XHR is blocked before the request completes (#1017).
71
- // GET-only — photon has no mutating routes, so unlike libpostal's CORS there is no POST in the methods list.
72
69
  if (options.cors !== false) {
73
70
  app.use(cors({ origin: "*", allowMethods: ["GET", "OPTIONS"], allowHeaders: ["*"], maxAge: 86_400 }))
74
71
  }
@@ -77,8 +74,6 @@ export function createPhotonApp(engine: PhotonEngine, options: PhotonAppOptions
77
74
  app.use(engineHeaders(options.engine))
78
75
  }
79
76
 
80
- // Safety net: malformed input or an engine fault returns an empty FeatureCollection, never a crash (photon's
81
- // envelope — NOT `{error}`, which is the libpostal/nominatim shape).
82
77
  app.onError((_error, c) => c.json({ type: "FeatureCollection", features: [], message: "internal error" }, 500))
83
78
 
84
79
  registerPhotonRoutes(app, engine, options.engine)
package/lib/engine.ts CHANGED
@@ -3,14 +3,17 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * The Photon engine contract + wire types the router delegates to. Feature/collection
6
+ * The Photon engine interface + wire types the router delegates to. Feature/collection
7
7
  * construction lives here too (`photonFeature`, `photonCollection`) since every projection
8
- * builds on them; the RESOLVED-place → {@link PhotonProperties} projection itself lives in
8
+ * builds on them. the resolved-place → {@link PhotonProperties} projection itself lives in
9
9
  * `projection.ts`.
10
10
  */
11
11
 
12
12
  /**
13
- * Photon feature properties — OSM-derived tag names, populated from Mailwoman's `ComponentTag` / resolved place.
13
+ * Photon feature properties.
14
+ *
15
+ * OSM-derived tag names, populated from Mailwoman's `ComponentTag` / resolved place.
16
+ *
14
17
  * `extent` is `[minLon, maxLat, maxLon, minLat]` per Photon's convention.
15
18
  */
16
19
  export interface PhotonProperties {
@@ -82,8 +85,13 @@ export interface PhotonReverseParams {
82
85
  }
83
86
 
84
87
  /**
85
- * The engine the router delegates to. Each method is optional; a missing one answers `501`. The real implementation
86
- * backs `/api` with the FST autocomplete tier + parse→resolve, and `/reverse` with the `WOFReverseGeocoder`.
88
+ * The engine the router delegates to.
89
+ *
90
+ * Each method is optional.
91
+ * A missing one answers `501`.
92
+ *
93
+ * The real implementation backs `/api` with the FST autocomplete tier + parse→resolve.
94
+ * and `/reverse` with the `WOFReverseGeocoder`.
87
95
  */
88
96
  export interface PhotonEngine {
89
97
  search?(params: PhotonSearchParams): Promise<PhotonFeatureCollection>
package/lib/index.ts CHANGED
@@ -3,20 +3,15 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * `@mailwoman/photon` — a Photon-compatible autocomplete / type-ahead geocoding API over the
6
+ * `@mailwoman/photon` is a Photon-compatible autocomplete / type-ahead geocoding API over the
7
7
  * Mailwoman engine. Where `@mailwoman/nominatim` is structured lookup, Photon is
8
8
  * search-as-you-type: a GeoJSON `FeatureCollection` per query, biased by location, ranked for
9
- * prefixes. It maps onto Mailwoman's shipped FST autocomplete tier (#190/#587) + parse →
10
- * resolve.
9
+ * prefixes. It maps onto Mailwoman's shipped FST autocomplete tier and the parse then resolve
10
+ * path.
11
11
  *
12
- * Like its siblings, the package is engine-agnostic: {@link createPhotonApp} takes a
13
- * {@link PhotonEngine}; the CLI wires the real engine. Implementation is staged on the epic (#801
14
- * / the Photon child); routes whose engine method is absent answer `501`.
15
- *
16
- * The Hono app (CORS + error envelope + the emitted OpenAPI document) lives in `app.ts`; route
17
- * definitions + handlers in `routes.ts`; wire types + the engine contract in `engine.ts`; the
18
- * resolved-place → Photon-schema projection in `projection.ts`; the zod wire schemas in
19
- * `schema.ts`.
12
+ * Like its siblings, the package is engine-agnostic. {@link createPhotonApp} takes a
13
+ * {@link PhotonEngine}, and the CLI wires the real engine. Routes whose engine method is absent
14
+ * answer `501`.
20
15
  */
21
16
 
22
17
  export * from "#app"
@@ -3,20 +3,17 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * Reverse lookup over the `postcode-locality-*.db` artifacts: the CONTAINING postcode of a
7
- * resolved locality, keyed by its WOF id — no name matching. Serves the drop-ins' answer
8
- * enrichment: a village answer carries the postcode the gazetteer attests for it.
6
+ * Reverse lookup over the `postcode-locality-*.db` artifacts: the containing postcode of a
7
+ * resolved locality, keyed by its WOF id.
9
8
  *
10
- * The exactly-one rule is the abstention: a locality contained by several postcodes (any real
11
- * city) gets NOTHING — emitting one of many would state a precision the evidence doesn't hold.
12
- * Tolerate-and-degrade like every optional artifact: a machine without the DBs answers undefined
13
- * everywhere and the consumer simply doesn't decorate.
9
+ * The exactly-one rule is the abstention: a locality contained by several postcodes (any real city) gets
10
+ * no postcode. A machine without the DBs degrades to no enrichment.
14
11
  */
15
12
 
16
- import { dataRootPath } from "@mailwoman/core/data-root"
17
13
  import { pathExists } from "@mailwoman/core/fs/readers"
14
+ import { wofDatabasePath } from "@mailwoman/resolver-wof-sqlite/paths"
18
15
  import { DatabaseClient } from "@mailwoman/sqlite/client"
19
- import type { PostcodeLocalityDatabase } from "mailwoman/gazetteer-pipeline/postcode-locality/schema"
16
+ import type { PostcodeLocalityDatabase } from "mailwoman/locality-postcode-schema"
20
17
 
21
18
  /**
22
19
  * The per-country artifacts, probed in caller-country order with `intl` as the shared fallback.
@@ -29,16 +26,15 @@ export async function createLocalityPostcodeLookup(): Promise<LocalityPostcodeLo
29
26
  const statements = new Map<string, ReturnType<DatabaseClient["prepare"]>>()
30
27
 
31
28
  for (const suffix of POSTCODE_LOCALITY_SUFFIXES) {
32
- const path = String(dataRootPath("wof", `postcode-locality-${suffix}.db`))
29
+ const path = wofDatabasePath(`postcode-locality-${suffix}.db`)
33
30
 
34
31
  if (!(await pathExists(path))) continue
35
32
 
36
33
  try {
37
34
  const db = new DatabaseClient<PostcodeLocalityDatabase>(path, { readOnly: true })
38
35
 
39
- // No `is_containing` filter: villages routinely carry 0 (the builder's containment test is
40
- // distance-classified, and a village near its postcode centroid still has exactly one code).
41
- // The exactly-one DISTINCT rule below is the entire ambiguity guard.
36
+ // No `is_containing` filter: villages routinely have 0, so the exactly-one
37
+ // distinct rule below is the entire ambiguity guard.
42
38
  statements.set(
43
39
  suffix,
44
40
  db.prepare(`SELECT DISTINCT postcode FROM postcode_locality WHERE locality_id = ? LIMIT 2`)
package/lib/projection.ts CHANGED
@@ -3,10 +3,9 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * The RESOLVED-place → Photon-schema projection: decorating a resolved gazetteer place (proper-
7
- * cased names + ancestry + country, house/street grade overrides) into {@link PhotonProperties},
8
- * plus the `format=jsonld` schema.org re-serialization. Wire types + feature/collection
9
- * construction live in `engine.ts`.
6
+ * The resolved-place → Photon-schema projection: decorating a resolved gazetteer place (proper-
7
+ * cased names, ancestry, country, house and street grade overrides) into {@link PhotonProperties},
8
+ * plus the `format=jsonld` schema.org re-serialization.
10
9
  */
11
10
 
12
11
  import { composeStreetAddress, type SchemaOrgPlace, toSchemaOrg } from "@mailwoman/annotations"
@@ -20,9 +19,11 @@ import {
20
19
  } from "#engine"
21
20
 
22
21
  /**
23
- * The resolved-place info a forward `/api` result carries: the admin ladder (MOST-SPECIFIC first) with GAZETTEER names,
24
- * the coordinate, the resolved country, and the postcode. {@link photonForwardProperties} projects it onto Photon's
25
- * schema. #1014 — decorate from the resolved place, not the parsed input span.
22
+ * The resolved-place info in a forward `/api` result: the admin ladder (most-specific first)
23
+ * with gazetteer names, the coordinate, the resolved country and the postcode.
24
+ * {@link photonForwardProperties} projects it onto Photon's schema.
25
+ *
26
+ * Decorate from the resolved place rather than the parsed input span.
26
27
  */
27
28
  export interface PhotonForwardInput {
28
29
  lat: number
@@ -33,34 +34,36 @@ export interface PhotonForwardInput {
33
34
  */
34
35
  country?: { name?: string; code?: string } | null
35
36
  /**
36
- * Resolved admin ancestry, most-specific first, each carrying the gazetteer's canonical name (not the parsed span).
37
+ * Resolved admin ancestry, most-specific first, each carrying the gazetteer's
38
+ * canonical name rather than the parsed span.
37
39
  */
38
40
  places: ReadonlyArray<{ tag: string; name: string }>
39
41
  /**
40
- * A HOUSE-GRADE result (#1041): set only when the resolver produced a specific building coordinate — the
41
- * `address_point` (rooftop) or `interpolated` tier fired, NOT an admin centroid. {@link photonForwardProperties} then
42
- * re-tags the schema `osm_key: place` / `osm_value: house` / `type: house` and surfaces the parsed `housenumber` +
43
- * `street`, matching upstream komoot/photon's own bare-address-point shape (verified against `photon.komoot.io`: a
44
- * residential rooftop returns `{osm_key:"place", osm_value:"house", type:"house", housenumber, street}` with NO
45
- * `name`). Absent → the result keeps its admin-ancestry schema. Without it a rooftop reads as `type: city` and a
46
- * client zooms to city scale (or paints a city marker) on a doorstep match — the #1041 regression.
42
+ * A house-grade result: set only when the resolver produced a specific building coordinate,
43
+ * the `address_point` (rooftop) or `interpolated` tier rather than an admin centroid.
44
+ * {@link photonForwardProperties} then re-tags the schema `osm_key: place` /
45
+ * `osm_value: house` / `type: house` and surfaces the parsed `housenumber` + `street`,
46
+ * matching upstream komoot/photon's bare-address-point shape.
47
+ *
48
+ * Absent means the result keeps its admin-ancestry schema.
47
49
  */
48
50
  house?: { number?: string | null; street?: string | null } | null
49
51
  /**
50
- * A STREET-GRADE result (#1050): set when the street-centroid tier (#1042/#1046) fired — a street-level coordinate,
51
- * below rooftop/interp, above admin. {@link photonForwardProperties} re-tags it `osm_key: highway` / `osm_value:
52
- * residential` / `type: street` with the FULL assembled street name in `name` — matching upstream komoot's street
53
- * results (verified live 2026-07-10: a street primary returns `{osm_key:"highway", osm_value:<class>, type:"street",
54
- * name:"Rue de la République", city, …}`; the street name rides `name`, not `street`). Without it a street centroid
55
- * reads `type: city` with the city's name — the #1050 regression. `house` wins when both are set (a numbered query
56
- * never street-tiers).
52
+ * A street-grade result: set when the street-centroid tier fired, a street-level
53
+ * coordinate below rooftop/interp and above admin. {@link photonForwardProperties}
54
+ * re-tags it `osm_key: highway` / `osm_value: residential` / `type: street` with the
55
+ * full assembled street name in `name`, matching upstream komoot's street results.
56
+ *
57
+ * `house` wins when both are set, since a numbered query never street-tiers.
57
58
  */
58
59
  street?: { name?: string | null } | null
59
60
  }
60
61
 
61
62
  /**
62
- * How a resolved tag projects onto Photon's schema: the property key that holds its name, plus the OSM `key`/`value`/
63
- * `type` a Photon client reads. Kept close to komoot Photon's own values so client label-builders behave.
63
+ * How a resolved tag projects onto Photon's schema: the property key that holds its name,
64
+ * plus the OSM `key`/`value`/ `type` a Photon client reads.
65
+ *
66
+ * Kept close to komoot Photon's own values so client label-builders behave.
64
67
  */
65
68
  const FORWARD_TAG_PROJECTION: Record<
66
69
  string,
@@ -70,18 +73,17 @@ const FORWARD_TAG_PROJECTION: Record<
70
73
  house: { key: "name", osmKey: "building", osmValue: "yes", type: "house" },
71
74
  street: { key: "street", osmKey: "highway", osmValue: "residential", type: "street" },
72
75
  neighbourhood: { key: "district", osmKey: "place", osmValue: "suburb", type: "district" },
73
- // The finest tier the /reverse descent ladder (resolver-wof-sqlite `DESCENT_TIERS`) can return — without a row
74
- // here a microhood-deepest reverse result fell through to the `place/yes/other` default. #1041 close-out.
76
+ // The finest tier the /reverse descent ladder (resolver-wof-sqlite `DESCENT_TIERS`) can return.
75
77
  microhood: { key: "district", osmKey: "place", osmValue: "neighbourhood", type: "district" },
76
78
  dependent_locality: { key: "district", osmKey: "place", osmValue: "suburb", type: "district" },
77
79
  borough: { key: "district", osmKey: "place", osmValue: "borough", type: "district" },
78
80
  locality: { key: "city", osmKey: "place", osmValue: "city", type: "city" },
79
- // The JP tiers the character-path model emits (#2164): a municipality is Photon's city, a prefecture its state, a
80
- // district (大字 / 町名) its district — the same keys Nominatim assigns those ranks.
81
+ // The JP tiers the character-path model emits: a municipality is Photon's city, a prefecture
82
+ // its state, a district (大字 / 町名) its district, the same keys Nominatim assigns those ranks.
81
83
  municipality: { key: "city", osmKey: "place", osmValue: "city", type: "city" },
82
84
  prefecture: { key: "state", osmKey: "place", osmValue: "state", type: "state" },
83
85
  district: { key: "district", osmKey: "place", osmValue: "suburb", type: "district" },
84
- // WOF placetypes the /reverse hierarchy uses (so both endpoints derive osm tags from ONE table).
86
+ // WOF placetypes the /reverse hierarchy uses (so both endpoints derive osm tags from one table).
85
87
  localadmin: { key: "city", osmKey: "place", osmValue: "city", type: "city" },
86
88
  subregion: { key: "county", osmKey: "place", osmValue: "county", type: "county" },
87
89
  county: { key: "county", osmKey: "place", osmValue: "county", type: "county" },
@@ -91,14 +93,17 @@ const FORWARD_TAG_PROJECTION: Record<
91
93
  }
92
94
 
93
95
  /**
94
- * Fallback OSM tags — a Photon client reads `osm_key`/`osm_value`/`type` unconditionally, so they must never be absent.
96
+ * Fallback OSM tags.
97
+ *
98
+ * A Photon client reads `osm_key`/`osm_value`/`type` unconditionally, so they must never be absent.
95
99
  */
96
100
  const DEFAULT_OSM_TAGS = { osm_key: "place", osm_value: "yes", type: "other" } as const
97
101
 
98
102
  /**
99
- * The Photon `osm_key`/`osm_value`/`type` for a resolved tag or WOF placetype (`locality`, `region`, `country`, …),
100
- * falling back to a safe default so the fields are always present. Shared by the forward projection and `/reverse` so
101
- * the two endpoints report a place the SAME way. #1014.
103
+ * The Photon `osm_key`/`osm_value`/`type` for a resolved tag or WOF placetype
104
+ * (`locality`, `region`, `country`, …), falling back to a safe default so the fields are always present.
105
+ *
106
+ * Shared by the forward projection and `/reverse` so the two endpoints report a place the same way.
102
107
  */
103
108
  export function photonOSMTags(tagOrPlacetype: string): { osm_key: string; osm_value: string; type: string } {
104
109
  const proj = FORWARD_TAG_PROJECTION[tagOrPlacetype]
@@ -107,12 +112,13 @@ export function photonOSMTags(tagOrPlacetype: string): { osm_key: string; osm_va
107
112
  }
108
113
 
109
114
  /**
110
- * Project a resolved forward result into Photon properties — decorating from the RESOLVED gazetteer place (proper-cased
111
- * names + ancestry + country), NOT the parsed input span, and ALWAYS emitting `osm_key`/`osm_value`/`type` so Photon
112
- * client libraries (leaflet-control-geocoder, @openrunner/photon-geocoder) never dereference undefined. #1014.
115
+ * Project a resolved forward result into Photon properties, decorating from the resolved
116
+ * gazetteer place (proper-cased names, ancestry, country) rather than the parsed input span.
117
+ *
118
+ * Always emit `osm_key`/`osm_value`/`type` so Photon client libraries
119
+ * (leaflet-control-geocoder, @openrunner/photon-geocoder) never dereference undefined.
113
120
  */
114
121
  export function photonForwardProperties(input: PhotonForwardInput): PhotonProperties {
115
- // Safe defaults: a Photon client reads osm_key/osm_value/type unconditionally, so they must never be undefined.
116
122
  const props: PhotonProperties = { ...DEFAULT_OSM_TAGS }
117
123
  const [primary] = input.places
118
124
 
@@ -141,19 +147,12 @@ export function photonForwardProperties(input: PhotonForwardInput): PhotonProper
141
147
  props.countrycode = input.country.code.toLowerCase()
142
148
  }
143
149
 
144
- // #1041: house-grade override. A rooftop / interpolated coordinate is a BUILDING, not the admin locality the
145
- // ancestry above would label it — re-tag the schema so a Photon client renders (and zooms to) a house, and surface
146
- // the parsed housenumber + street. Matches upstream komoot/photon's bare address point (osm_key:place, osm_value:
147
- // house, type:house, with housenumber + street and NO name). Drop the admin-derived `name` — else the QGIS FLF label
148
- // (name + housenumber + street + city + postcode) doubles the city ("Paris 8 Boulevard du Palais Paris 75001"). The
149
- // city/state/postcode/country the ancestry filled stay put (upstream carries them on a house result too).
150
- // #1050: street-grade — the street-centroid tier fired. Re-tag per upstream's street shape (full
151
- // name in `name`, highway/street osm tags); the admin ancestry (city/state/…) stays as context.
152
150
  if (input.street?.name && !input.house) {
153
151
  props.name = input.street.name
154
152
  Object.assign(props, { osm_key: "highway", osm_value: "residential", type: "street" })
155
153
  }
156
154
 
155
+ // Drop the admin-derived `name`, or a QGIS FLF label doubles the city.
157
156
  if (input.house) {
158
157
  props.osm_key = "place"
159
158
  props.osm_value = "house"
@@ -175,14 +174,14 @@ export function photonForwardProperties(input: PhotonForwardInput): PhotonProper
175
174
  }
176
175
 
177
176
  /**
178
- * {@link photonForwardProperties}, wrapped as a Photon Point `Feature` at the resolved coordinate. #1014.
177
+ * {@link photonForwardProperties}, wrapped as a Photon Point `Feature` at the resolved coordinate.
179
178
  */
180
179
  export function photonForwardFeature(input: PhotonForwardInput): PhotonFeature {
181
180
  return photonFeature(input.lon, input.lat, photonForwardProperties(input))
182
181
  }
183
182
 
184
183
  /**
185
- * The winning place plus its ranked alternatives — the input to {@link photonForwardCollection}. #1016.
184
+ * The winning place plus its ranked alternatives, the input to {@link photonForwardCollection}.
186
185
  */
187
186
  export interface PhotonForwardResult {
188
187
  /**
@@ -190,14 +189,17 @@ export interface PhotonForwardResult {
190
189
  */
191
190
  primary: PhotonForwardInput
192
191
  /**
193
- * Ranked alternative places (Springfield MA / IL / …), each a single-place input; excludes the primary.
192
+ * Ranked alternative places (Springfield MA / IL / …), each a single-place input.
193
+ * Excludes the primary.
194
194
  */
195
195
  alternatives: PhotonForwardInput[]
196
196
  }
197
197
 
198
198
  /**
199
- * Assemble a Photon `FeatureCollection` honoring `limit` (#1016): the primary feature first, then ranked alternatives,
200
- * capped at `limit`. `limit` floors to 1 (Photon always returns at least the best match).
199
+ * Assemble a Photon `FeatureCollection` honoring `limit`: the primary feature first,
200
+ * then ranked alternatives, capped at `limit`.
201
+ *
202
+ * `limit` floors to 1, since Photon always returns at least the best match.
201
203
  */
202
204
  export function photonForwardCollection(result: PhotonForwardResult, limit: number): PhotonFeatureCollection {
203
205
  const cap = Math.max(1, Math.floor(limit) || 1)
@@ -212,10 +214,13 @@ export function photonForwardCollection(result: PhotonForwardResult, limit: numb
212
214
  }
213
215
 
214
216
  /**
215
- * Project a Photon `Feature` into a schema.org `Place` JSON-LD object (`format=jsonld`, #1052) — the OUTPUT-format
216
- * projection. Reads the feature's already-decorated {@link PhotonProperties} (housenumber/street/city/state/postcode/
217
- * countrycode + the coordinate), so it stays a pure re-serialization of the SAME resolved place the FeatureCollection
218
- * carries. `streetAddress` is the plain house-number-first join (the light router has no locale formatter).
217
+ * Project a Photon `Feature` into a schema.org `Place` JSON-LD object (`format=jsonld`),
218
+ * the output-format projection.
219
+ *
220
+ * Reads the feature's already-decorated {@link PhotonProperties}
221
+ * (housenumber/street/city/state/postcode/countrycode and the coordinate), so it stays a
222
+ * pure re-serialization of the same resolved place included in the FeatureCollection.
223
+ * `streetAddress` is the plain house-number-first join, since the light router has no locale formatter.
219
224
  */
220
225
  export function photonFeatureToSchemaOrg(feature: PhotonFeature): SchemaOrgPlace {
221
226
  const p = feature.properties
@@ -235,7 +240,7 @@ export function photonFeatureToSchemaOrg(feature: PhotonFeature): SchemaOrgPlace
235
240
  }
236
241
 
237
242
  /**
238
- * Project a whole Photon `FeatureCollection` into an array of schema.org `Place` objects (`format=jsonld`). #1052.
243
+ * Project a whole Photon `FeatureCollection` into an array of schema.org `Place` objects (`format=jsonld`).
239
244
  */
240
245
  export function photonToSchemaOrg(collection: PhotonFeatureCollection): SchemaOrgPlace[] {
241
246
  return collection.features.map(photonFeatureToSchemaOrg)