@mailwoman/nominatim 7.2.0 → 7.2.1
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.
- package/app.ts +74 -0
- package/cli.ts +385 -0
- package/dev-tools/capture-search-golden.run.ts +81 -0
- package/engine.ts +114 -0
- package/format.ts +150 -0
- package/index.ts +29 -0
- package/package.json +33 -19
- package/routes.ts +281 -0
- package/schema.ts +222 -0
package/app.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The Nominatim-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
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { OpenAPIHono } from "@hono/zod-openapi"
|
|
11
|
+
import { attachOpenAPIDocs, type OpenAPIDocInfo } from "@mailwoman/api-kit"
|
|
12
|
+
import packageJson from "@mailwoman/nominatim/package.json" with { type: "json" }
|
|
13
|
+
import { cors } from "hono/cors"
|
|
14
|
+
|
|
15
|
+
import type { NominatimEngine } from "./engine.ts"
|
|
16
|
+
import { registerNominatimRoutes } from "./routes.ts"
|
|
17
|
+
|
|
18
|
+
/** Options for {@link createNominatimApp}. */
|
|
19
|
+
export interface NominatimAppOptions {
|
|
20
|
+
/**
|
|
21
|
+
* Emit permissive CORS headers (`Access-Control-Allow-Origin: *`) on every response and answer preflight `OPTIONS`
|
|
22
|
+
* with `204`. Default `true` — browser-embedded geocoder clients need it: a cross-origin XHR is blocked without it
|
|
23
|
+
* (#1017). Set `false` when a reverse proxy already owns the CORS headers.
|
|
24
|
+
*/
|
|
25
|
+
cors?: boolean
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The document info stamped into the emitted OpenAPI document. Exported (not inlined) so the CLI's `openapi` subcommand
|
|
30
|
+
* can call `emitOpenAPIDocuments` with the SAME info the mounted `/openapi.json` route (below, via
|
|
31
|
+
* {@link attachOpenAPIDocs}) uses — one source of truth, no risk of the two drifting.
|
|
32
|
+
*/
|
|
33
|
+
export const NOMINATIM_DOC_INFO: OpenAPIDocInfo = {
|
|
34
|
+
title: packageJson.name,
|
|
35
|
+
version: packageJson.version,
|
|
36
|
+
description: packageJson.description,
|
|
37
|
+
license: { name: "AGPL-3.0-only OR LicenseRef-Commercial", identifier: "AGPL-3.0-only" },
|
|
38
|
+
contact: { name: "Sister Software", url: "https://mailwoman.sister.software" },
|
|
39
|
+
externalDocs: {
|
|
40
|
+
description: "Switching from Nominatim",
|
|
41
|
+
url: "https://mailwoman.sister.software/docs/concepts/switching-from-nominatim",
|
|
42
|
+
},
|
|
43
|
+
servers: [
|
|
44
|
+
{
|
|
45
|
+
url: "http://{host}:{port}",
|
|
46
|
+
variables: { host: { default: "127.0.0.1" }, port: { default: "8080" } },
|
|
47
|
+
},
|
|
48
|
+
],
|
|
49
|
+
security: [],
|
|
50
|
+
tags: [
|
|
51
|
+
{ name: "geocoding", description: "Forward geocoding, reverse geocoding, and OSM id lookup." },
|
|
52
|
+
{ name: "meta", description: "Health and deploy-time operations." },
|
|
53
|
+
],
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Build the Nominatim-compatible app around an injected {@link NominatimEngine}. */
|
|
57
|
+
export function createNominatimApp(engine: NominatimEngine, options: NominatimAppOptions = {}): OpenAPIHono {
|
|
58
|
+
const app = new OpenAPIHono()
|
|
59
|
+
|
|
60
|
+
// Browser-embedded geocoder clients need CORS or their cross-origin XHR is blocked before completing (#1017).
|
|
61
|
+
// GET-only — nominatim has no mutating routes, so unlike libpostal's CORS there is no POST in the methods list.
|
|
62
|
+
if (options.cors !== false) {
|
|
63
|
+
app.use(cors({ origin: "*", allowMethods: ["GET", "OPTIONS"], allowHeaders: ["*"], maxAge: 86400 }))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Safety net: a malformed query or an engine fault must never crash the process into a stack-trace 500 — the
|
|
67
|
+
// clean legacy JSON error instead (`{error}` — NOT photon's FeatureCollection+message envelope).
|
|
68
|
+
app.onError((_error, c) => c.json({ error: "internal error" }, 500))
|
|
69
|
+
|
|
70
|
+
registerNominatimRoutes(app, engine)
|
|
71
|
+
attachOpenAPIDocs(app, NOMINATIM_DOC_INFO)
|
|
72
|
+
|
|
73
|
+
return app
|
|
74
|
+
}
|
package/cli.ts
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* @copyright Sister Software
|
|
4
|
+
* @license AGPL-3.0
|
|
5
|
+
* @author Teffen Ellis, et al.
|
|
6
|
+
*
|
|
7
|
+
* `mailwoman-nominatim` — boot a Nominatim-compatible endpoint via the `serve` command. Usage +
|
|
8
|
+
* examples live in the package README.
|
|
9
|
+
*
|
|
10
|
+
* Wires the real engine: `/search` over `geocodeAddress` (parse → resolve), `/reverse` over
|
|
11
|
+
* `WOFReverseGeocoder` (point-in-polygon over WOF admin polygons), reusing the same
|
|
12
|
+
* resolver-backend selector GeocodeRouter uses. Results carry the OpenCage-style `annotations`
|
|
13
|
+
* block — coordinate formats, flag, calling code, currency, and (when their DBs are present)
|
|
14
|
+
* timezone, UN/LOCODE, NUTS — composed from the `@mailwoman/*` annotators.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { existsSync } from "node:fs"
|
|
18
|
+
import { join } from "node:path"
|
|
19
|
+
import { parseArgs } from "node:util"
|
|
20
|
+
|
|
21
|
+
import { composeAnnotators, toOpenCage } from "@mailwoman/annotations"
|
|
22
|
+
import { printOpenAPIDocument, serveNode } from "@mailwoman/api-kit"
|
|
23
|
+
import { countryReferenceAnnotator, matchCountry } from "@mailwoman/codex/country"
|
|
24
|
+
import { NeuralAddressClassifier } from "@mailwoman/neural"
|
|
25
|
+
import { makeNutsAnnotator, NutsLookup } from "@mailwoman/nuts-lookup"
|
|
26
|
+
import { createWOFResolver } from "@mailwoman/resolver"
|
|
27
|
+
import { coordinateFormatAnnotator } from "@mailwoman/spatial"
|
|
28
|
+
import { makeTimezoneAnnotator, TimezoneLookup } from "@mailwoman/timezone-lookup"
|
|
29
|
+
import { makeUnLocodeAnnotator, UnLocodeLookup } from "@mailwoman/un-locode-lookup"
|
|
30
|
+
import { geocodeAddress, type GeocodeResult, ShardProvider } from "mailwoman/geocode-core"
|
|
31
|
+
import {
|
|
32
|
+
createResolverBackend,
|
|
33
|
+
mailwomanDataRoot,
|
|
34
|
+
resolveCandidateDBPath,
|
|
35
|
+
wofShardPaths,
|
|
36
|
+
} from "mailwoman/resolver-backend"
|
|
37
|
+
|
|
38
|
+
import {
|
|
39
|
+
createNominatimApp,
|
|
40
|
+
type NominatimAddressDetails,
|
|
41
|
+
type NominatimEngine,
|
|
42
|
+
NOMINATIM_DOC_INFO,
|
|
43
|
+
type ResolvedAddress,
|
|
44
|
+
toNominatimResult,
|
|
45
|
+
} from "./index.ts"
|
|
46
|
+
|
|
47
|
+
/** WOF placetype → Nominatim address key. */
|
|
48
|
+
const PLACETYPE_TO_KEY: Record<string, keyof NominatimAddressDetails> = {
|
|
49
|
+
venue: "road",
|
|
50
|
+
street: "road",
|
|
51
|
+
locality: "city",
|
|
52
|
+
localadmin: "city",
|
|
53
|
+
borough: "city_district",
|
|
54
|
+
neighbourhood: "suburb",
|
|
55
|
+
county: "county",
|
|
56
|
+
region: "state",
|
|
57
|
+
macroregion: "state",
|
|
58
|
+
country: "country",
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* A real address fits comfortably; anything longer is malformed input (and would exceed the model's input window). Cap
|
|
63
|
+
* defensively so a giant query returns no results instead of faulting.
|
|
64
|
+
*/
|
|
65
|
+
const MAX_QUERY_LEN = 512
|
|
66
|
+
|
|
67
|
+
function joinNonEmpty(...parts: Array<string | undefined>): string {
|
|
68
|
+
return parts.filter(Boolean).join(", ")
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Map a forward geocode result (admin + coordinate) into the formatter's neutral shape. */
|
|
72
|
+
function forwardToResolved(r: GeocodeResult): ResolvedAddress {
|
|
73
|
+
const address: NominatimAddressDetails = {}
|
|
74
|
+
|
|
75
|
+
if (r.locality) {
|
|
76
|
+
address.city = r.locality
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (r.region) {
|
|
80
|
+
address.state = r.region
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (r.postcode) {
|
|
84
|
+
address.postcode = r.postcode
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
for (const h of r.hierarchy) {
|
|
88
|
+
if (h.tag === "country") {
|
|
89
|
+
address.country = h.value
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
lat: r.lat,
|
|
95
|
+
lon: r.lon,
|
|
96
|
+
address,
|
|
97
|
+
displayName: joinNonEmpty(address.city, address.state, address.postcode, address.country) || r.input,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function serve(): Promise<void> {
|
|
102
|
+
const { values } = parseArgs({
|
|
103
|
+
options: {
|
|
104
|
+
port: { type: "string", default: "8080" },
|
|
105
|
+
host: { type: "string", default: "0.0.0.0" },
|
|
106
|
+
"candidate-db": { type: "string" },
|
|
107
|
+
// Permissive CORS is on by default (browser geocoder clients need it). `--no-cors` turns it off for
|
|
108
|
+
// deployments where a reverse proxy already sets the headers.
|
|
109
|
+
cors: { type: "boolean", default: true },
|
|
110
|
+
},
|
|
111
|
+
allowNegative: true,
|
|
112
|
+
allowPositionals: true,
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
const port = Number(values.port) || 8080
|
|
116
|
+
const host = values.host ?? "0.0.0.0"
|
|
117
|
+
|
|
118
|
+
const resolverMod = await import("@mailwoman/resolver-wof-sqlite")
|
|
119
|
+
const wofPaths = wofShardPaths().filter(existsSync)
|
|
120
|
+
const adminDBPath = wofPaths[0]
|
|
121
|
+
|
|
122
|
+
// Candidate gazetteer = worldwide resolution (population-first ranking + global coverage + the
|
|
123
|
+
// FTS5-trigram typo fallback). Resolve it from --candidate-db / $MAILWOMAN_CANDIDATE_DB, else auto-use
|
|
124
|
+
// one already fetched to the data root (`mailwoman fetch-gazetteer` writes `<data-root>/wof/candidate.db`).
|
|
125
|
+
// Absent → admin-only (US-optimized) — the no-download default.
|
|
126
|
+
const conventionCandidate = join(mailwomanDataRoot(), "wof", "candidate.db")
|
|
127
|
+
|
|
128
|
+
// #1009 kin: an EXPLICIT --candidate-db that doesn't exist must error loudly, not silently fall
|
|
129
|
+
// back to ambient data.
|
|
130
|
+
if (values["candidate-db"] && !existsSync(values["candidate-db"])) {
|
|
131
|
+
console.error(`✗ --candidate-db not found: ${values["candidate-db"]}`)
|
|
132
|
+
process.exit(1)
|
|
133
|
+
}
|
|
134
|
+
const candidateDb =
|
|
135
|
+
resolveCandidateDBPath(values["candidate-db"]) ??
|
|
136
|
+
(existsSync(conventionCandidate) ? conventionCandidate : undefined)
|
|
137
|
+
|
|
138
|
+
// #1009: fail FRIENDLY before the resolver's internal shard error — same message shape as
|
|
139
|
+
// @mailwoman/photon's pre-flight (kept in lockstep; docs/switching pages are the maintained pointer).
|
|
140
|
+
if (!candidateDb && wofPaths.length === 0) {
|
|
141
|
+
console.error(
|
|
142
|
+
[
|
|
143
|
+
"✗ no gazetteer data found — the endpoint needs a resolver database to answer queries.",
|
|
144
|
+
"",
|
|
145
|
+
" Fastest path (worldwide resolution, ~1.4 GB, byte-range friendly):",
|
|
146
|
+
` mkdir -p ${join(mailwomanDataRoot(), "wof")}`,
|
|
147
|
+
` curl -fSL https://public.sister.software/mailwoman/gazetteer/2026-07-07a/candidate.db \\`,
|
|
148
|
+
` -o ${conventionCandidate}`,
|
|
149
|
+
"",
|
|
150
|
+
" Then re-run `serve` (the file is auto-detected at that path), or point at your own:",
|
|
151
|
+
" --candidate-db <path> / $MAILWOMAN_CANDIDATE_DB (candidate gazetteer)",
|
|
152
|
+
" $MAILWOMAN_WOF_DB / <data-root>/wof/*.db (admin WOF distribution)",
|
|
153
|
+
"",
|
|
154
|
+
" Docs: https://mailwoman.sister.software/docs/switching/nominatim",
|
|
155
|
+
].join("\n")
|
|
156
|
+
)
|
|
157
|
+
process.exit(1)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const classifier = await NeuralAddressClassifier.loadFromWeights({ locale: "en-US" })
|
|
161
|
+
const backend = createResolverBackend(resolverMod, { wofPaths, candidateDb })
|
|
162
|
+
const resolver = createWOFResolver(backend)
|
|
163
|
+
const shards = new ShardProvider(resolverMod, mailwomanDataRoot())
|
|
164
|
+
// National open-register rooftop tier (#1012): BAN-FR ahead of the OSM tier for a non-US parse. A no-op
|
|
165
|
+
// when the shard isn't on disk (existsSync-gated inside the provider), so the endpoint degrades cleanly.
|
|
166
|
+
const { BANShardProvider } = await import("@mailwoman/ban/sdk")
|
|
167
|
+
const banShards = new BANShardProvider(mailwomanDataRoot())
|
|
168
|
+
// NOT a geocode country constraint. The default-on #244 placer already routes the query's country
|
|
169
|
+
// (Berlin→DE, Boston→US) and `defaultCountry` is a HARD override that beats it (geocode-core.ts:102),
|
|
170
|
+
// so forcing "US" resolved every non-US query to its US namesake (Berlin→Berlin NH). We let the
|
|
171
|
+
// placer decide instead. This is the fallback used ONLY to annotate the flag/currency/calling-code
|
|
172
|
+
// when the resolved hierarchy omits the country tag — which on US-centric data (no candidate DB)
|
|
173
|
+
// happens for US results, where "US" is the right guess. Non-US results carry the country tag, so
|
|
174
|
+
// the fallback never mislabels them.
|
|
175
|
+
const annotationCountryFallback = candidateDb ? undefined : "US"
|
|
176
|
+
const reverseGeo = adminDBPath ? new resolverMod.WOFReverseGeocoder({ adminDBPath }) : undefined
|
|
177
|
+
const annotators = [coordinateFormatAnnotator, countryReferenceAnnotator]
|
|
178
|
+
const tzDBPath = join(mailwomanDataRoot(), "timezone", "timezone.db")
|
|
179
|
+
|
|
180
|
+
if (existsSync(tzDBPath)) {
|
|
181
|
+
annotators.push(makeTimezoneAnnotator(new TimezoneLookup({ databasePath: tzDBPath })))
|
|
182
|
+
}
|
|
183
|
+
const ulDBPath = join(mailwomanDataRoot(), "un-locode", "un-locode.db")
|
|
184
|
+
|
|
185
|
+
if (existsSync(ulDBPath)) {
|
|
186
|
+
annotators.push(makeUnLocodeAnnotator(new UnLocodeLookup({ databasePath: ulDBPath })))
|
|
187
|
+
}
|
|
188
|
+
const nutsDBPath = join(mailwomanDataRoot(), "nuts", "nuts.db")
|
|
189
|
+
|
|
190
|
+
if (existsSync(nutsDBPath)) {
|
|
191
|
+
annotators.push(makeNutsAnnotator(new NutsLookup({ databasePath: nutsDBPath })))
|
|
192
|
+
}
|
|
193
|
+
const annotate = composeAnnotators(annotators)
|
|
194
|
+
|
|
195
|
+
const engine: NominatimEngine = {
|
|
196
|
+
async search(params) {
|
|
197
|
+
const query = (
|
|
198
|
+
params.q ?? joinNonEmpty(params.street, params.city, params.state, params.postalcode, params.country)
|
|
199
|
+
)?.trim()
|
|
200
|
+
|
|
201
|
+
// Empty/whitespace → no query; absurdly long → not an address (and would blow the model's input).
|
|
202
|
+
if (!query || query.length > MAX_QUERY_LEN) return []
|
|
203
|
+
// A caller-supplied `countrycodes` is an explicit hard restriction (Nominatim semantics): honor
|
|
204
|
+
// it as the country constraint, even to the point of no result. It doubles as the manual override
|
|
205
|
+
// for the #822 placer frontier — `countrycodes=au` lands Sydney in Australia. One country is the
|
|
206
|
+
// common (geopy) case; for a list we apply the first.
|
|
207
|
+
const userCountry = params.countrycodes?.[0]?.toUpperCase()
|
|
208
|
+
const result = await geocodeAddress(query, {
|
|
209
|
+
classifier,
|
|
210
|
+
resolver,
|
|
211
|
+
shards: shards.for,
|
|
212
|
+
nationalShards: banShards.for,
|
|
213
|
+
defaultCountry: userCountry,
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
if (result.lat == null || result.lon == null) return []
|
|
217
|
+
const resolved = forwardToResolved(result)
|
|
218
|
+
|
|
219
|
+
// #1041: a rooftop (`address_point`) / house-number-estimate (`interpolated`) tier is HOUSE-GRADE — tag the
|
|
220
|
+
// result `class: place` / `type: house` (upstream Nominatim's own class/type for a house), so a client that
|
|
221
|
+
// keys on `class`/`type`/`addresstype` treats it as a building, not an untyped admin hit. The admin tier
|
|
222
|
+
// (a locality centroid) carries no class/type here, as before.
|
|
223
|
+
if (result.resolution_tier === "address_point" || result.resolution_tier === "interpolated") {
|
|
224
|
+
resolved.category = "place"
|
|
225
|
+
resolved.type = "house"
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// The geocode result already carries the parse's street spans (#1041) — no second parse.
|
|
229
|
+
if (result.house_number) {
|
|
230
|
+
resolved.address.house_number = result.house_number
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (result.street) {
|
|
234
|
+
resolved.address.road = result.street
|
|
235
|
+
}
|
|
236
|
+
// The country tag isn't always in the hierarchy (US admin results omit it); backfill from the
|
|
237
|
+
// US-centric-data default so the address, display_name, and flag/currency/calling-code agree.
|
|
238
|
+
const countryName = result.hierarchy.find((h) => h.tag === "country")?.value ?? annotationCountryFallback
|
|
239
|
+
const country = matchCountry(countryName)
|
|
240
|
+
|
|
241
|
+
if (country) {
|
|
242
|
+
if (!resolved.address.country) {
|
|
243
|
+
resolved.address.country = country.canonical
|
|
244
|
+
}
|
|
245
|
+
resolved.address.country_code = country.iso2.toLowerCase()
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (result.house_number || result.street) {
|
|
249
|
+
resolved.displayName =
|
|
250
|
+
joinNonEmpty(
|
|
251
|
+
result.house_number ?? undefined,
|
|
252
|
+
result.street ?? undefined,
|
|
253
|
+
resolved.address.city,
|
|
254
|
+
resolved.address.state,
|
|
255
|
+
resolved.address.postcode,
|
|
256
|
+
resolved.address.country
|
|
257
|
+
) || resolved.displayName
|
|
258
|
+
}
|
|
259
|
+
const out = toNominatimResult(resolved, { addressdetails: params.addressdetails })
|
|
260
|
+
out.annotations = toOpenCage(
|
|
261
|
+
await annotate({
|
|
262
|
+
lat: result.lat,
|
|
263
|
+
lon: result.lon,
|
|
264
|
+
countryCode: country?.iso2,
|
|
265
|
+
placeName: result.locality ?? undefined,
|
|
266
|
+
})
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
return [out].slice(0, params.limit)
|
|
270
|
+
},
|
|
271
|
+
|
|
272
|
+
async reverse(params) {
|
|
273
|
+
if (!reverseGeo) return null
|
|
274
|
+
const { hierarchy } = await reverseGeo.reverseGeocode(params.lat, params.lon)
|
|
275
|
+
|
|
276
|
+
if (hierarchy.length === 0) return null
|
|
277
|
+
const address: NominatimAddressDetails = {}
|
|
278
|
+
|
|
279
|
+
for (const place of hierarchy) {
|
|
280
|
+
const key = PLACETYPE_TO_KEY[place.placetype]
|
|
281
|
+
|
|
282
|
+
if (key && !address[key]) {
|
|
283
|
+
address[key] = place.name
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const deepest = hierarchy[0]!
|
|
287
|
+
|
|
288
|
+
if (deepest.country) {
|
|
289
|
+
address.country_code = deepest.country.toLowerCase()
|
|
290
|
+
}
|
|
291
|
+
const resolved: ResolvedAddress = {
|
|
292
|
+
lat: params.lat,
|
|
293
|
+
lon: params.lon,
|
|
294
|
+
address,
|
|
295
|
+
displayName: hierarchy.map((p) => p.name).join(", "),
|
|
296
|
+
placeID: deepest.id,
|
|
297
|
+
boundingbox: deepest.bbox
|
|
298
|
+
? [
|
|
299
|
+
String(deepest.bbox.minLat),
|
|
300
|
+
String(deepest.bbox.maxLat),
|
|
301
|
+
String(deepest.bbox.minLon),
|
|
302
|
+
String(deepest.bbox.maxLon),
|
|
303
|
+
]
|
|
304
|
+
: undefined,
|
|
305
|
+
}
|
|
306
|
+
const out = toNominatimResult(resolved, { addressdetails: params.addressdetails })
|
|
307
|
+
out.annotations = toOpenCage(
|
|
308
|
+
await annotate({ lat: params.lat, lon: params.lon, countryCode: address.country_code })
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
return out
|
|
312
|
+
},
|
|
313
|
+
|
|
314
|
+
async status() {
|
|
315
|
+
return { status: 0, message: "OK" }
|
|
316
|
+
},
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const app = createNominatimApp(engine, { cors: values.cors })
|
|
320
|
+
|
|
321
|
+
serveNode({
|
|
322
|
+
fetch: app.fetch,
|
|
323
|
+
port,
|
|
324
|
+
hostname: host,
|
|
325
|
+
onListen: () => {
|
|
326
|
+
console.error(`[@mailwoman/nominatim] listening on http://${host}:${port}`)
|
|
327
|
+
console.error(` wof: ${adminDBPath ?? "(none found — set MAILWOMAN_WOF_DB)"}`)
|
|
328
|
+
console.error(
|
|
329
|
+
candidateDb
|
|
330
|
+
? ` resolver: candidate gazetteer (worldwide) — ${candidateDb}`
|
|
331
|
+
: ` resolver: admin-only (US-optimized) — point --candidate-db / $MAILWOMAN_CANDIDATE_DB at a candidate gazetteer for worldwide`
|
|
332
|
+
)
|
|
333
|
+
console.error(` cors: ${values.cors ? "enabled (Access-Control-Allow-Origin: *)" : "disabled (--no-cors)"}`)
|
|
334
|
+
console.error(` endpoints: GET / GET /search GET /reverse GET /lookup GET /status GET /openapi.json`)
|
|
335
|
+
},
|
|
336
|
+
})
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* `openapi` — print (or `--out`-write) the emitted OpenAPI document for this surface. Builds the app around an
|
|
341
|
+
* all-optional stub {@link NominatimEngine} (`{}` — every route answers 501 under this stub, but the document itself
|
|
342
|
+
* only reflects the ROUTE TABLE, not handler behavior) so this NEVER boots the neural classifier or opens a gazetteer
|
|
343
|
+
* DB: pure route-table introspection, fast regardless of data-root state. `--flavor 3.0` prints the 3.0.3 diet instead
|
|
344
|
+
* of the default 3.1.0.
|
|
345
|
+
*/
|
|
346
|
+
function openapi(): void {
|
|
347
|
+
const { values } = parseArgs({
|
|
348
|
+
options: {
|
|
349
|
+
flavor: { type: "string", default: "3.1" },
|
|
350
|
+
out: { type: "string" },
|
|
351
|
+
},
|
|
352
|
+
allowPositionals: true,
|
|
353
|
+
})
|
|
354
|
+
|
|
355
|
+
if (values.flavor !== "3.1" && values.flavor !== "3.0") {
|
|
356
|
+
console.error(`✗ --flavor must be "3.1" or "3.0" (got "${values.flavor}")`)
|
|
357
|
+
console.error("Usage: mailwoman-nominatim openapi [--flavor 3.1|3.0] [--out <path>]")
|
|
358
|
+
process.exit(1)
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const app = createNominatimApp({})
|
|
362
|
+
|
|
363
|
+
printOpenAPIDocument(app, NOMINATIM_DOC_INFO, values)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// Subcommand dispatch via parseArgs (strict:false — the per-command parsers own their flags).
|
|
367
|
+
const command = parseArgs({ strict: false, allowPositionals: true }).positionals[0]
|
|
368
|
+
|
|
369
|
+
switch (command) {
|
|
370
|
+
case "serve":
|
|
371
|
+
await serve()
|
|
372
|
+
break
|
|
373
|
+
case "openapi":
|
|
374
|
+
openapi()
|
|
375
|
+
break
|
|
376
|
+
default:
|
|
377
|
+
console.error(
|
|
378
|
+
[
|
|
379
|
+
"Usage: mailwoman-nominatim <command>",
|
|
380
|
+
" serve [--port 8080] [--host 0.0.0.0] [--candidate-db <path>] [--no-cors]",
|
|
381
|
+
" openapi [--flavor 3.1|3.0] [--out <path>]",
|
|
382
|
+
].join("\n")
|
|
383
|
+
)
|
|
384
|
+
process.exit(command ? 1 : 0)
|
|
385
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Phase-0: golden `/search` wire responses from the CURRENT nominatim drop-in (neural geocode +
|
|
7
|
+
* rules streetParts recovery). Spawns its own server child on a scratch port and kills ONLY that
|
|
8
|
+
* PID (house rule: never kill by pattern). Needs the lab data-root (weights + gazetteer).
|
|
9
|
+
* Run from the repo root AFTER `yarn compile`:
|
|
10
|
+
* `node nominatim/dev-tools/capture-search-golden.run.ts`
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { spawn } from "node:child_process"
|
|
14
|
+
import { readFileSync, writeFileSync } from "node:fs"
|
|
15
|
+
|
|
16
|
+
const PORT = 8199
|
|
17
|
+
const BASE = `http://127.0.0.1:${PORT}`
|
|
18
|
+
const PARITY_PATH = "mailwoman/test-fixtures/legacy-golden/parity-inputs.jsonl"
|
|
19
|
+
const SYNTHETIC_PATH = "mailwoman/test-fixtures/legacy-golden/synthetic-inputs.txt"
|
|
20
|
+
const OUT_PATH = "nominatim/test-fixtures/search-golden.jsonl"
|
|
21
|
+
|
|
22
|
+
interface ParityRow {
|
|
23
|
+
input: string
|
|
24
|
+
expected: Array<Record<string, unknown> | string>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const parity = readFileSync(PARITY_PATH, "utf8")
|
|
28
|
+
.split("\n")
|
|
29
|
+
.filter(Boolean)
|
|
30
|
+
.map((line) => JSON.parse(line) as ParityRow)
|
|
31
|
+
|
|
32
|
+
// The streetParts leg only fires when a house number is in play — feed it the cases that have one.
|
|
33
|
+
const withHouseNumber = parity
|
|
34
|
+
.filter((row) =>
|
|
35
|
+
row.expected.some((record) => typeof record === "object" && record !== null && "house_number" in record)
|
|
36
|
+
)
|
|
37
|
+
.map((row) => row.input)
|
|
38
|
+
|
|
39
|
+
const syntheticInputs = readFileSync(SYNTHETIC_PATH, "utf8")
|
|
40
|
+
.split("\n")
|
|
41
|
+
.map((line) => line.trim())
|
|
42
|
+
.filter(Boolean)
|
|
43
|
+
|
|
44
|
+
const queries = [...new Set([...withHouseNumber.slice(0, 172), ...syntheticInputs])]
|
|
45
|
+
|
|
46
|
+
const child = spawn("node", ["nominatim/out/cli.js", "serve", "--port", String(PORT)], {
|
|
47
|
+
stdio: ["ignore", "inherit", "inherit"],
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
const deadline = Date.now() + 180_000
|
|
52
|
+
|
|
53
|
+
// Model + gazetteer boot takes a while; poll /status until the server answers.
|
|
54
|
+
for (;;) {
|
|
55
|
+
try {
|
|
56
|
+
const res = await fetch(`${BASE}/status`)
|
|
57
|
+
|
|
58
|
+
if (res.ok) break
|
|
59
|
+
} catch {
|
|
60
|
+
// Not listening yet.
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (Date.now() > deadline) throw new Error("nominatim serve did not become ready within 180s")
|
|
64
|
+
await new Promise((resolve) => setTimeout(resolve, 1000))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const rows: string[] = []
|
|
68
|
+
|
|
69
|
+
for (const query of queries) {
|
|
70
|
+
const res = await fetch(`${BASE}/search?q=${encodeURIComponent(query)}&format=jsonv2&addressdetails=1`)
|
|
71
|
+
|
|
72
|
+
rows.push(JSON.stringify({ query, status: res.status, body: await res.json() }))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
writeFileSync(OUT_PATH, rows.join("\n") + "\n")
|
|
76
|
+
console.error(
|
|
77
|
+
`captured ${rows.length} /search responses (${withHouseNumber.length} house-number parity cases available)`
|
|
78
|
+
)
|
|
79
|
+
} finally {
|
|
80
|
+
child.kill("SIGTERM")
|
|
81
|
+
}
|
package/engine.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The Nominatim engine contract + wire types the router delegates to. The RESOLVED-address →
|
|
7
|
+
* {@link NominatimResult} formatter (`toNominatimResult`, `toFeatureCollection`,
|
|
8
|
+
* `nominatimResultToSchemaOrg`) lives in `format.ts`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { OpenCageAnnotations } from "@mailwoman/annotations"
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Output serialization formats Nominatim supports. `jsonv2` is the modern default. `jsonld` is the Mailwoman extension
|
|
15
|
+
* (#1052) — schema.org `Place` JSON-LD, not part of upstream Nominatim.
|
|
16
|
+
*/
|
|
17
|
+
export type NominatimFormat = "jsonv2" | "json" | "geojson" | "jsonld"
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The structured address breakdown returned under `address` when `addressdetails=1`. Keys mirror Nominatim's
|
|
21
|
+
* OSM-derived tag names; populated from Mailwoman's `ComponentTag` / resolved ancestor lineage (mapping owned by
|
|
22
|
+
* #804).
|
|
23
|
+
*/
|
|
24
|
+
export interface NominatimAddressDetails {
|
|
25
|
+
house_number?: string
|
|
26
|
+
road?: string
|
|
27
|
+
neighbourhood?: string
|
|
28
|
+
suburb?: string
|
|
29
|
+
city?: string
|
|
30
|
+
town?: string
|
|
31
|
+
village?: string
|
|
32
|
+
county?: string
|
|
33
|
+
state?: string
|
|
34
|
+
postcode?: string
|
|
35
|
+
country?: string
|
|
36
|
+
country_code?: string
|
|
37
|
+
[key: string]: string | undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A single Nominatim result object (the shape geopy and friends parse). */
|
|
41
|
+
export interface NominatimResult {
|
|
42
|
+
place_id: number | string
|
|
43
|
+
licence: string
|
|
44
|
+
osm_type?: string
|
|
45
|
+
osm_id?: number | string
|
|
46
|
+
lat: string
|
|
47
|
+
lon: string
|
|
48
|
+
display_name: string
|
|
49
|
+
/** `[south, north, west, east]` as strings, per Nominatim. */
|
|
50
|
+
boundingbox?: [string, string, string, string]
|
|
51
|
+
class?: string
|
|
52
|
+
type?: string
|
|
53
|
+
importance?: number
|
|
54
|
+
place_rank?: number
|
|
55
|
+
address?: NominatimAddressDetails
|
|
56
|
+
/** Present when `format=geojson` or `polygon_geojson=1`. */
|
|
57
|
+
geojson?: unknown
|
|
58
|
+
/** OpenCage-style enrichment block (timezone, coordinate formats, …); attached by the engine. */
|
|
59
|
+
annotations?: OpenCageAnnotations
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Parsed `/search` parameters (free-text OR structured; never both). */
|
|
63
|
+
export interface NominatimSearchParams {
|
|
64
|
+
q?: string
|
|
65
|
+
street?: string
|
|
66
|
+
city?: string
|
|
67
|
+
county?: string
|
|
68
|
+
state?: string
|
|
69
|
+
country?: string
|
|
70
|
+
postalcode?: string
|
|
71
|
+
countrycodes?: string[]
|
|
72
|
+
limit: number
|
|
73
|
+
viewbox?: [number, number, number, number]
|
|
74
|
+
bounded?: boolean
|
|
75
|
+
addressdetails?: boolean
|
|
76
|
+
format: NominatimFormat
|
|
77
|
+
acceptLanguage?: string
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Parsed `/reverse` parameters. */
|
|
81
|
+
export interface NominatimReverseParams {
|
|
82
|
+
lat: number
|
|
83
|
+
lon: number
|
|
84
|
+
zoom?: number
|
|
85
|
+
addressdetails?: boolean
|
|
86
|
+
format: NominatimFormat
|
|
87
|
+
acceptLanguage?: string
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Parsed `/lookup` parameters. */
|
|
91
|
+
export interface NominatimLookupParams {
|
|
92
|
+
osmIds: string[]
|
|
93
|
+
addressdetails?: boolean
|
|
94
|
+
format: NominatimFormat
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Nominatim `/status` payload. */
|
|
98
|
+
export interface NominatimStatus {
|
|
99
|
+
status: number
|
|
100
|
+
message: string
|
|
101
|
+
data_updated?: string
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The geocoding engine the router delegates to. Each method is optional; a route whose method is not provided answers
|
|
106
|
+
* `501 Not Implemented`. The real implementation (Mailwoman parse → resolve, plus `WOFReverseGeocoder`) is wired by the
|
|
107
|
+
* CLI and fleshed out across #802–#805.
|
|
108
|
+
*/
|
|
109
|
+
export interface NominatimEngine {
|
|
110
|
+
search?(params: NominatimSearchParams): Promise<NominatimResult[]>
|
|
111
|
+
reverse?(params: NominatimReverseParams): Promise<NominatimResult | null>
|
|
112
|
+
lookup?(params: NominatimLookupParams): Promise<NominatimResult[]>
|
|
113
|
+
status?(): Promise<NominatimStatus>
|
|
114
|
+
}
|