@mailwoman/photon 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 ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
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
+ */
9
+
10
+ import { OpenAPIHono } from "@hono/zod-openapi"
11
+ import { attachOpenAPIDocs, type OpenAPIDocInfo } from "@mailwoman/api-kit"
12
+ import packageJson from "@mailwoman/photon/package.json" with { type: "json" }
13
+ import { cors } from "hono/cors"
14
+
15
+ import type { PhotonEngine } from "./engine.ts"
16
+ import { registerPhotonRoutes } from "./routes.ts"
17
+
18
+ /** Options for {@link createPhotonApp}. */
19
+ export interface PhotonAppOptions {
20
+ /**
21
+ * Emit permissive CORS headers (`Access-Control-Allow-Origin: *`) on every response and answer preflight `OPTIONS`
22
+ * with `204`. Default `true` — upstream komoot/photon serves permissive CORS, and the map-widget use case
23
+ * (leaflet-control-geocoder, @openrunner/photon-geocoder, …) needs it: a browser's cross-origin XHR is blocked
24
+ * without it (#1017). Set `false` when a reverse proxy already owns the CORS headers.
25
+ */
26
+ cors?: boolean
27
+ }
28
+
29
+ /**
30
+ * The document info stamped into the emitted OpenAPI document. Exported (not inlined) so the CLI's `openapi` subcommand
31
+ * can call `emitOpenAPIDocuments` with the SAME info the mounted `/openapi.json` route (below, via
32
+ * {@link attachOpenAPIDocs}) uses — one source of truth, no risk of the two drifting.
33
+ */
34
+ export const PHOTON_DOC_INFO: OpenAPIDocInfo = {
35
+ title: packageJson.name,
36
+ version: packageJson.version,
37
+ description: packageJson.description,
38
+ license: { name: "AGPL-3.0-only OR LicenseRef-Commercial", identifier: "AGPL-3.0-only" },
39
+ contact: { name: "Sister Software", url: "https://mailwoman.sister.software" },
40
+ externalDocs: {
41
+ description: "Switching from Photon",
42
+ url: "https://mailwoman.sister.software/docs/concepts/switching-from-photon",
43
+ },
44
+ servers: [
45
+ {
46
+ url: "http://{host}:{port}",
47
+ variables: { host: { default: "127.0.0.1" }, port: { default: "2322" } },
48
+ },
49
+ ],
50
+ security: [],
51
+ tags: [
52
+ { name: "geocoding", description: "Forward autocomplete and reverse geocoding." },
53
+ { name: "meta", description: "Health and deploy-time operations." },
54
+ ],
55
+ }
56
+
57
+ /** Build the Photon-compatible app around an injected {@link PhotonEngine}. */
58
+ export function createPhotonApp(engine: PhotonEngine, options: PhotonAppOptions = {}): OpenAPIHono {
59
+ const app = new OpenAPIHono()
60
+
61
+ // Browser-embedded widgets need CORS or their cross-origin XHR is blocked before the request completes (#1017).
62
+ // GET-only — photon has no mutating routes, so unlike libpostal's CORS there is no POST in the methods list.
63
+ if (options.cors !== false) {
64
+ app.use(cors({ origin: "*", allowMethods: ["GET", "OPTIONS"], allowHeaders: ["*"], maxAge: 86400 }))
65
+ }
66
+
67
+ // Safety net: malformed input or an engine fault returns an empty FeatureCollection, never a crash (photon's
68
+ // envelope — NOT `{error}`, which is the libpostal/nominatim shape).
69
+ app.onError((_error, c) => c.json({ type: "FeatureCollection", features: [], message: "internal error" }, 500))
70
+
71
+ registerPhotonRoutes(app, engine)
72
+ attachOpenAPIDocs(app, PHOTON_DOC_INFO)
73
+
74
+ return app
75
+ }
package/cli.ts ADDED
@@ -0,0 +1,278 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @copyright Sister Software
4
+ * @license AGPL-3.0
5
+ * @author Teffen Ellis, et al.
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.
15
+ */
16
+
17
+ import { existsSync } from "node:fs"
18
+ import { join } from "node:path"
19
+ import { parseArgs } from "node:util"
20
+
21
+ import { printOpenAPIDocument, serveNode } from "@mailwoman/api-kit"
22
+ import { matchCountry } from "@mailwoman/codex/country"
23
+ import { NeuralAddressClassifier } from "@mailwoman/neural"
24
+ import { createWOFResolver } from "@mailwoman/resolver"
25
+ import { geocodeAddress, ShardProvider } from "mailwoman/geocode-core"
26
+ import {
27
+ createResolverBackend,
28
+ mailwomanDataRoot,
29
+ resolveCandidateDBPath,
30
+ wofShardPaths,
31
+ } from "mailwoman/resolver-backend"
32
+
33
+ import {
34
+ createPhotonApp,
35
+ PHOTON_DOC_INFO,
36
+ photonCollection,
37
+ photonFeature,
38
+ photonForwardCollection,
39
+ type PhotonForwardInput,
40
+ photonOSMTags,
41
+ type PhotonEngine,
42
+ type PhotonProperties,
43
+ } from "./index.ts"
44
+
45
+ /** WOF placetype → Photon property key. */
46
+ const PLACETYPE_TO_KEY: Record<string, keyof PhotonProperties> = {
47
+ street: "street",
48
+ locality: "city",
49
+ localadmin: "city",
50
+ county: "county",
51
+ region: "state",
52
+ country: "country",
53
+ }
54
+
55
+ /** A real address fits comfortably; longer is malformed input (and would exceed the model's window). */
56
+ const MAX_QUERY_LEN = 512
57
+
58
+ async function serve(): Promise<void> {
59
+ const { values } = parseArgs({
60
+ options: {
61
+ port: { type: "string", default: "2322" },
62
+ host: { type: "string", default: "0.0.0.0" },
63
+ "candidate-db": { type: "string" },
64
+ // Permissive CORS is on by default (upstream Photon parity — browser widgets need it). `--no-cors`
65
+ // turns it off for deployments where a reverse proxy already sets the headers.
66
+ cors: { type: "boolean", default: true },
67
+ },
68
+ allowNegative: true,
69
+ allowPositionals: true,
70
+ })
71
+
72
+ const port = Number(values.port) || 2322
73
+ const host = values.host ?? "0.0.0.0"
74
+
75
+ const resolverMod = await import("@mailwoman/resolver-wof-sqlite")
76
+ const wofPaths = wofShardPaths().filter(existsSync)
77
+ const adminDBPath = wofPaths[0]
78
+
79
+ // Candidate gazetteer = worldwide resolution (see @mailwoman/nominatim). --candidate-db /
80
+ // $MAILWOMAN_CANDIDATE_DB, else auto-use one fetched to `<data-root>/wof/candidate.db`; absent → admin-only.
81
+ const conventionCandidate = join(mailwomanDataRoot(), "wof", "candidate.db")
82
+
83
+ // #1009 kin: an EXPLICIT --candidate-db that doesn't exist must error loudly, not silently fall
84
+ // back to whatever ambient data-root file happens to be present (a typo'd path would serve the
85
+ // wrong gazetteer without a word).
86
+ if (values["candidate-db"] && !existsSync(values["candidate-db"])) {
87
+ console.error(`✗ --candidate-db not found: ${values["candidate-db"]}`)
88
+ process.exit(1)
89
+ }
90
+ const candidateDb =
91
+ resolveCandidateDBPath(values["candidate-db"]) ??
92
+ (existsSync(conventionCandidate) ? conventionCandidate : undefined)
93
+
94
+ // #1009: fail FRIENDLY before the resolver throws its internal "resolveShards: at least one shard
95
+ // is required" — a stranger's first `npx @mailwoman/photon serve` must say exactly what data is
96
+ // missing and the one command that fixes it. Kept in sync with the docs' hosted-artifact layout
97
+ // (mailwoman.sister.software/docs/switching/photon — the maintained pointer).
98
+ if (!candidateDb && wofPaths.length === 0) {
99
+ console.error(
100
+ [
101
+ "✗ no gazetteer data found — the endpoint needs a resolver database to answer queries.",
102
+ "",
103
+ " Fastest path (worldwide resolution, ~1.4 GB, byte-range friendly):",
104
+ ` mkdir -p ${join(mailwomanDataRoot(), "wof")}`,
105
+ ` curl -fSL https://public.sister.software/mailwoman/gazetteer/2026-07-07a/candidate.db \\`,
106
+ ` -o ${conventionCandidate}`,
107
+ "",
108
+ " Then re-run `serve` (the file is auto-detected at that path), or point at your own:",
109
+ " --candidate-db <path> / $MAILWOMAN_CANDIDATE_DB (candidate gazetteer)",
110
+ " $MAILWOMAN_WOF_DB / <data-root>/wof/*.db (admin WOF distribution)",
111
+ "",
112
+ " Docs: https://mailwoman.sister.software/docs/switching/photon",
113
+ ].join("\n")
114
+ )
115
+ process.exit(1)
116
+ }
117
+
118
+ const classifier = await NeuralAddressClassifier.loadFromWeights({ locale: "en-US" })
119
+ const backend = createResolverBackend(resolverMod, { wofPaths, candidateDb })
120
+ const resolver = createWOFResolver(backend)
121
+ const shards = new ShardProvider(resolverMod, mailwomanDataRoot())
122
+ // National open-register rooftop tier (#1012): BAN-FR ahead of the OSM tier for a non-US parse. A no-op
123
+ // when the shard isn't on disk (existsSync-gated inside the provider), so the endpoint degrades cleanly.
124
+ const { BANShardProvider } = await import("@mailwoman/ban/sdk")
125
+ const banShards = new BANShardProvider(mailwomanDataRoot())
126
+ const reverseGeo = adminDBPath ? new resolverMod.WOFReverseGeocoder({ adminDBPath }) : undefined
127
+
128
+ const engine: PhotonEngine = {
129
+ async search(params) {
130
+ // Empty/whitespace → no query; absurdly long → not an address (and would blow the model's input).
131
+ const query = params.q?.trim()
132
+
133
+ if (!query || query.length > MAX_QUERY_LEN) return photonCollection([])
134
+ // #1016: forward the client's viewport/user location as a proximity bias — a SOFT re-rank the resolver
135
+ // folds into candidate scoring (Springfield near the map center wins). Only when both coords are present.
136
+ const bias = params.lat != null && params.lon != null ? [{ lat: params.lat, lon: params.lon }] : undefined
137
+ // No country constraint: the default-on #244 placer routes the query's country (Berlin→DE,
138
+ // Boston→US). Forcing "US" here is a HARD override (geocode-core.ts:102) that resolved every
139
+ // non-US query to its US namesake — wrong for a global autocomplete front.
140
+ const result = await geocodeAddress(query, {
141
+ classifier,
142
+ resolver,
143
+ shards: shards.for,
144
+ nationalShards: banShards.for,
145
+ bias,
146
+ })
147
+
148
+ if (result.lat == null || result.lon == null) return photonCollection([])
149
+ // #1014: decorate from the RESOLVED gazetteer place — proper-cased ancestry names (`hierarchy[].name`,
150
+ // not the parsed span) + the resolved country (ISO2 → canonical name via codex) + osm_key/value/type so
151
+ // Photon clients don't TypeError. The candidate backend fills only the locality (no ancestors() table),
152
+ // so state/county come through only on an ancestry-capable backend — country still lands from the code.
153
+ const country = matchCountry(result.countryCode)
154
+ // #1041: a rooftop (`address_point`) or house-number-estimate (`interpolated`) tier is HOUSE-GRADE — carry the
155
+ // parsed housenumber + street so photonForwardProperties decorates it `type: house` (matching upstream Photon)
156
+ // instead of inheriting the admin locality's `type: city`. The admin tier (a locality centroid) never does.
157
+ const houseGrade = result.resolution_tier === "address_point" || result.resolution_tier === "interpolated"
158
+ // #1050: the street-centroid tier is STREET-GRADE — full assembled street name in `name`,
159
+ // highway/street osm tags (the parallel of the #1041 house treatment).
160
+ const streetGrade = result.resolution_tier === "street"
161
+ const primary: PhotonForwardInput = {
162
+ lat: result.lat,
163
+ lon: result.lon,
164
+ postcode: result.postcode,
165
+ country: country ? { name: country.canonical, code: country.iso2 } : undefined,
166
+ places: result.hierarchy.map((h) => ({ tag: h.tag, name: h.name })),
167
+ ...(houseGrade ? { house: { number: result.house_number, street: result.street } } : {}),
168
+ ...(streetGrade ? { street: { name: result.street } } : {}),
169
+ }
170
+ // #1016: candidates[0] is the primary itself; its ranked alternatives (Springfield MA/IL/…) become the
171
+ // extra features, up to the requested `limit`. Each alternative is a single resolved place.
172
+ const alternatives = result.candidates.slice(1).map((c) => {
173
+ const cc = matchCountry(c.countryCode)
174
+
175
+ return {
176
+ lat: c.lat,
177
+ lon: c.lon,
178
+ country: cc ? { name: cc.canonical, code: cc.iso2 } : undefined,
179
+ places: [{ tag: c.tag, name: c.name }],
180
+ }
181
+ })
182
+
183
+ return photonForwardCollection({ primary, alternatives }, params.limit)
184
+ },
185
+
186
+ async reverse(params) {
187
+ if (!reverseGeo) return photonCollection([])
188
+ const { hierarchy } = await reverseGeo.reverseGeocode(params.lat, params.lon)
189
+
190
+ if (hierarchy.length === 0) return photonCollection([])
191
+ const deepest = hierarchy[0]!
192
+ // #1014: carry osm_key/osm_value/type (from the deepest placetype) so /reverse matches /api's schema —
193
+ // no Photon client should dereference an undefined osm_key on a reverse result either.
194
+ const properties: PhotonProperties = {
195
+ name: deepest.name,
196
+ countrycode: deepest.country?.toLowerCase(),
197
+ ...photonOSMTags(deepest.placetype),
198
+ }
199
+
200
+ for (const place of hierarchy) {
201
+ const key = PLACETYPE_TO_KEY[place.placetype]
202
+
203
+ if (key && properties[key] == null) {
204
+ properties[key] = place.name
205
+ }
206
+ }
207
+
208
+ return photonCollection([photonFeature(deepest.lon, deepest.lat, properties)])
209
+ },
210
+ }
211
+
212
+ const app = createPhotonApp(engine, { cors: values.cors })
213
+
214
+ serveNode({
215
+ fetch: app.fetch,
216
+ port,
217
+ hostname: host,
218
+ onListen: () => {
219
+ console.error(`[@mailwoman/photon] listening on http://${host}:${port}`)
220
+ console.error(` wof: ${adminDBPath ?? "(none found — set MAILWOMAN_WOF_DB)"}`)
221
+ console.error(
222
+ candidateDb
223
+ ? ` resolver: candidate gazetteer (worldwide) — ${candidateDb}`
224
+ : ` resolver: admin-only (US-optimized) — point --candidate-db / $MAILWOMAN_CANDIDATE_DB at a candidate gazetteer for worldwide`
225
+ )
226
+ console.error(` cors: ${values.cors ? "enabled (Access-Control-Allow-Origin: *)" : "disabled (--no-cors)"}`)
227
+ console.error(` endpoints: GET / GET /api GET /reverse GET /openapi.json`)
228
+ },
229
+ })
230
+ }
231
+
232
+ /**
233
+ * `openapi` — print (or `--out`-write) the emitted OpenAPI document for this surface. Builds the app around an
234
+ * all-optional stub {@link PhotonEngine} (`{}` — every route answers 501 under this stub, but the document itself only
235
+ * reflects the ROUTE TABLE, not handler behavior) so this NEVER boots the neural classifier or opens a gazetteer DB:
236
+ * pure route-table introspection, fast regardless of data-root state. `--flavor 3.0` prints the 3.0.3 diet instead of
237
+ * the default 3.1.0.
238
+ */
239
+ function openapi(): void {
240
+ const { values } = parseArgs({
241
+ options: {
242
+ flavor: { type: "string", default: "3.1" },
243
+ out: { type: "string" },
244
+ },
245
+ allowPositionals: true,
246
+ })
247
+
248
+ if (values.flavor !== "3.1" && values.flavor !== "3.0") {
249
+ console.error(`✗ --flavor must be "3.1" or "3.0" (got "${values.flavor}")`)
250
+ console.error("Usage: mailwoman-photon openapi [--flavor 3.1|3.0] [--out <path>]")
251
+ process.exit(1)
252
+ }
253
+
254
+ const app = createPhotonApp({})
255
+
256
+ printOpenAPIDocument(app, PHOTON_DOC_INFO, values)
257
+ }
258
+
259
+ // Subcommand dispatch via parseArgs (strict:false — the per-command parsers own their flags).
260
+ const command = parseArgs({ strict: false, allowPositionals: true }).positionals[0]
261
+
262
+ switch (command) {
263
+ case "serve":
264
+ await serve()
265
+ break
266
+ case "openapi":
267
+ openapi()
268
+ break
269
+ default:
270
+ console.error(
271
+ [
272
+ "Usage: mailwoman-photon <command>",
273
+ " serve [--port 2322] [--host 0.0.0.0] [--candidate-db <path>] [--no-cors]",
274
+ " openapi [--flavor 3.1|3.0] [--out <path>]",
275
+ ].join("\n")
276
+ )
277
+ process.exit(command ? 1 : 0)
278
+ }
package/engine.ts ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The Photon engine contract + wire types the router delegates to. Feature/collection
7
+ * construction lives here too (`photonFeature`, `photonCollection`) since every projection
8
+ * builds on them; the RESOLVED-place → {@link PhotonProperties} projection itself lives in
9
+ * `projection.ts`.
10
+ */
11
+
12
+ /**
13
+ * Photon feature properties — OSM-derived tag names, populated from Mailwoman's `ComponentTag` / resolved place.
14
+ * `extent` is `[minLon, maxLat, maxLon, minLat]` per Photon's convention.
15
+ */
16
+ export interface PhotonProperties {
17
+ osm_id?: number | string
18
+ osm_type?: string
19
+ osm_key?: string
20
+ osm_value?: string
21
+ type?: string
22
+ name?: string
23
+ housenumber?: string
24
+ street?: string
25
+ postcode?: string
26
+ city?: string
27
+ district?: string
28
+ county?: string
29
+ state?: string
30
+ country?: string
31
+ countrycode?: string
32
+ extent?: [number, number, number, number]
33
+ [key: string]: unknown
34
+ }
35
+
36
+ /** A Photon result feature: a GeoJSON Point with {@link PhotonProperties}. */
37
+ export interface PhotonFeature {
38
+ type: "Feature"
39
+ geometry: {
40
+ type: "Point"
41
+ coordinates: [number, number]
42
+ }
43
+ properties: PhotonProperties
44
+ }
45
+
46
+ /** The Photon response envelope — a GeoJSON FeatureCollection. */
47
+ export interface PhotonFeatureCollection {
48
+ type: "FeatureCollection"
49
+ features: PhotonFeature[]
50
+ }
51
+
52
+ /** Parsed `/api` (forward / autocomplete) parameters. */
53
+ export interface PhotonSearchParams {
54
+ q: string
55
+ limit: number
56
+ lang?: string
57
+ /** Location bias. */
58
+ lat?: number
59
+ lon?: number
60
+ bbox?: [number, number, number, number]
61
+ osmTag?: string[]
62
+ layer?: string[]
63
+ }
64
+
65
+ /** Parsed `/reverse` parameters. */
66
+ export interface PhotonReverseParams {
67
+ lat: number
68
+ lon: number
69
+ limit: number
70
+ lang?: string
71
+ radius?: number
72
+ }
73
+
74
+ /**
75
+ * The engine the router delegates to. Each method is optional; a missing one answers `501`. The real implementation
76
+ * backs `/api` with the FST autocomplete tier + parse→resolve, and `/reverse` with the `WOFReverseGeocoder`.
77
+ */
78
+ export interface PhotonEngine {
79
+ search?(params: PhotonSearchParams): Promise<PhotonFeatureCollection>
80
+ reverse?(params: PhotonReverseParams): Promise<PhotonFeatureCollection>
81
+ }
82
+
83
+ /** Build a Photon `Feature` from a coordinate + properties. */
84
+ export function photonFeature(lon: number, lat: number, properties: PhotonProperties): PhotonFeature {
85
+ return { type: "Feature", geometry: { type: "Point", coordinates: [lon, lat] }, properties }
86
+ }
87
+
88
+ /** Wrap features in a Photon `FeatureCollection`. */
89
+ export function photonCollection(features: PhotonFeature[]): PhotonFeatureCollection {
90
+ return { type: "FeatureCollection", features }
91
+ }
package/index.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * `@mailwoman/photon` — a Photon-compatible autocomplete / type-ahead geocoding API over the
7
+ * Mailwoman engine. Where `@mailwoman/nominatim` is structured lookup, Photon is
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.
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`.
20
+ */
21
+
22
+ export * from "./app.ts"
23
+ export * from "./engine.ts"
24
+ export * from "./projection.ts"
25
+ export * from "./schema.ts"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mailwoman/photon",
3
- "version": "7.2.0",
3
+ "version": "7.2.1",
4
4
  "description": "Photon drop-in — a Photon-compatible autocomplete/type-ahead geocoding API (GeoJSON FeatureCollection over /api + /reverse) on the Mailwoman engine. Run it with `npx @mailwoman/photon serve`.",
5
5
  "license": "AGPL-3.0-only OR LicenseRef-Commercial",
6
6
  "repository": {
@@ -14,32 +14,46 @@
14
14
  "out/**/*.js.map",
15
15
  "out/**/*.d.ts",
16
16
  "out/**/*.d.ts.map",
17
- "README.md"
17
+ "README.md",
18
+ "*.ts",
19
+ "*.tsx",
20
+ "**/*.ts",
21
+ "**/*.tsx",
22
+ "!*.test.ts",
23
+ "!*.test.tsx",
24
+ "!**/*.test.ts",
25
+ "!**/*.test.tsx"
18
26
  ],
19
27
  "type": "module",
20
28
  "exports": {
21
29
  "./package.json": "./package.json",
22
30
  ".": {
23
- "node": "./index.ts",
24
- "default": "./out/index.js",
25
- "types": "./out/index.d.ts"
31
+ "types": "./out/index.d.ts",
32
+ "default": "./out/index.js"
26
33
  }
27
34
  },
28
35
  "publishConfig": {
29
- "access": "public"
36
+ "access": "public",
37
+ "exports": {
38
+ "./package.json": "./package.json",
39
+ ".": {
40
+ "types": "./out/index.d.ts",
41
+ "default": "./out/index.js"
42
+ }
43
+ }
30
44
  },
31
45
  "dependencies": {
32
46
  "@hono/zod-openapi": "^1.4.0",
33
- "@mailwoman/annotations": "7.2.0",
34
- "@mailwoman/api-kit": "7.2.0",
35
- "@mailwoman/ban": "7.2.0",
36
- "@mailwoman/codex": "7.2.0",
37
- "@mailwoman/neural": "7.2.0",
38
- "@mailwoman/neural-weights-en-us": "7.2.0",
39
- "@mailwoman/resolver": "7.2.0",
40
- "@mailwoman/resolver-wof-sqlite": "7.2.0",
47
+ "@mailwoman/annotations": "7.2.1",
48
+ "@mailwoman/api-kit": "7.2.1",
49
+ "@mailwoman/ban": "7.2.1",
50
+ "@mailwoman/codex": "7.2.1",
51
+ "@mailwoman/neural": "7.2.1",
52
+ "@mailwoman/neural-weights-en-us": "7.2.1",
53
+ "@mailwoman/resolver": "7.2.1",
54
+ "@mailwoman/resolver-wof-sqlite": "7.2.1",
41
55
  "hono": "^4.12.29",
42
- "mailwoman": "7.2.0",
56
+ "mailwoman": "7.2.1",
43
57
  "zod": "^4.4.3"
44
58
  }
45
59
  }
package/projection.ts ADDED
@@ -0,0 +1,218 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
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`.
10
+ */
11
+
12
+ import { composeStreetAddress, type SchemaOrgPlace, toSchemaOrg } from "@mailwoman/annotations"
13
+
14
+ import {
15
+ type PhotonFeature,
16
+ type PhotonFeatureCollection,
17
+ photonCollection,
18
+ photonFeature,
19
+ type PhotonProperties,
20
+ } from "./engine.ts"
21
+
22
+ /**
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.
26
+ */
27
+ export interface PhotonForwardInput {
28
+ lat: number
29
+ lon: number
30
+ postcode?: string | null
31
+ /** The resolved country, mapped by the caller (ISO2 → canonical name via `@mailwoman/codex`). */
32
+ country?: { name?: string; code?: string } | null
33
+ /** Resolved admin ancestry, most-specific first, each carrying the gazetteer's canonical name (not the parsed span). */
34
+ places: ReadonlyArray<{ tag: string; name: string }>
35
+ /**
36
+ * A HOUSE-GRADE result (#1041): set only when the resolver produced a specific building coordinate — the
37
+ * `address_point` (rooftop) or `interpolated` tier fired, NOT an admin centroid. {@link photonForwardProperties} then
38
+ * re-tags the schema `osm_key: place` / `osm_value: house` / `type: house` and surfaces the parsed `housenumber` +
39
+ * `street`, matching upstream komoot/photon's own bare-address-point shape (verified against `photon.komoot.io`: a
40
+ * residential rooftop returns `{osm_key:"place", osm_value:"house", type:"house", housenumber, street}` with NO
41
+ * `name`). Absent → the result keeps its admin-ancestry schema. Without it a rooftop reads as `type: city` and a
42
+ * client zooms to city scale (or paints a city marker) on a doorstep match — the #1041 regression.
43
+ */
44
+ house?: { number?: string | null; street?: string | null } | null
45
+ /**
46
+ * A STREET-GRADE result (#1050): set when the street-centroid tier (#1042/#1046) fired — a street-level coordinate,
47
+ * below rooftop/interp, above admin. {@link photonForwardProperties} re-tags it `osm_key: highway` / `osm_value:
48
+ * residential` / `type: street` with the FULL assembled street name in `name` — matching upstream komoot's street
49
+ * results (verified live 2026-07-10: a street primary returns `{osm_key:"highway", osm_value:<class>, type:"street",
50
+ * name:"Rue de la République", city, …}`; the street name rides `name`, not `street`). Without it a street centroid
51
+ * reads `type: city` with the city's name — the #1050 regression. `house` wins when both are set (a numbered query
52
+ * never street-tiers).
53
+ */
54
+ street?: { name?: string | null } | null
55
+ }
56
+
57
+ /**
58
+ * How a resolved tag projects onto Photon's schema: the property key that holds its name, plus the OSM `key`/`value`/
59
+ * `type` a Photon client reads. Kept close to komoot Photon's own values so client label-builders behave.
60
+ */
61
+ const FORWARD_TAG_PROJECTION: Record<
62
+ string,
63
+ { key: keyof PhotonProperties; osmKey: string; osmValue: string; type: string }
64
+ > = {
65
+ venue: { key: "name", osmKey: "amenity", osmValue: "yes", type: "house" },
66
+ house: { key: "name", osmKey: "building", osmValue: "yes", type: "house" },
67
+ street: { key: "street", osmKey: "highway", osmValue: "residential", type: "street" },
68
+ neighbourhood: { key: "district", osmKey: "place", osmValue: "suburb", type: "district" },
69
+ dependent_locality: { key: "district", osmKey: "place", osmValue: "suburb", type: "district" },
70
+ borough: { key: "district", osmKey: "place", osmValue: "borough", type: "district" },
71
+ locality: { key: "city", osmKey: "place", osmValue: "city", type: "city" },
72
+ // WOF placetypes the /reverse hierarchy uses (so both endpoints derive osm tags from ONE table).
73
+ localadmin: { key: "city", osmKey: "place", osmValue: "city", type: "city" },
74
+ subregion: { key: "county", osmKey: "place", osmValue: "county", type: "county" },
75
+ county: { key: "county", osmKey: "place", osmValue: "county", type: "county" },
76
+ region: { key: "state", osmKey: "place", osmValue: "state", type: "state" },
77
+ macroregion: { key: "state", osmKey: "place", osmValue: "state", type: "state" },
78
+ country: { key: "country", osmKey: "place", osmValue: "country", type: "country" },
79
+ }
80
+
81
+ /** Fallback OSM tags — a Photon client reads `osm_key`/`osm_value`/`type` unconditionally, so they must never be absent. */
82
+ const DEFAULT_OSM_TAGS = { osm_key: "place", osm_value: "yes", type: "other" } as const
83
+
84
+ /**
85
+ * The Photon `osm_key`/`osm_value`/`type` for a resolved tag or WOF placetype (`locality`, `region`, `country`, …),
86
+ * falling back to a safe default so the fields are always present. Shared by the forward projection and `/reverse` so
87
+ * the two endpoints report a place the SAME way. #1014.
88
+ */
89
+ export function photonOSMTags(tagOrPlacetype: string): { osm_key: string; osm_value: string; type: string } {
90
+ const proj = FORWARD_TAG_PROJECTION[tagOrPlacetype]
91
+
92
+ return proj ? { osm_key: proj.osmKey, osm_value: proj.osmValue, type: proj.type } : { ...DEFAULT_OSM_TAGS }
93
+ }
94
+
95
+ /**
96
+ * Project a resolved forward result into Photon properties — decorating from the RESOLVED gazetteer place (proper-cased
97
+ * names + ancestry + country), NOT the parsed input span, and ALWAYS emitting `osm_key`/`osm_value`/`type` so Photon
98
+ * client libraries (leaflet-control-geocoder, @openrunner/photon-geocoder) never dereference undefined. #1014.
99
+ */
100
+ export function photonForwardProperties(input: PhotonForwardInput): PhotonProperties {
101
+ // Safe defaults: a Photon client reads osm_key/osm_value/type unconditionally, so they must never be undefined.
102
+ const props: PhotonProperties = { ...DEFAULT_OSM_TAGS }
103
+ const [primary] = input.places
104
+
105
+ if (primary) {
106
+ props.name = primary.name
107
+ Object.assign(props, photonOSMTags(primary.tag))
108
+ }
109
+
110
+ for (const place of input.places) {
111
+ const proj = FORWARD_TAG_PROJECTION[place.tag]
112
+
113
+ if (proj && props[proj.key] == null) {
114
+ props[proj.key] = place.name
115
+ }
116
+ }
117
+
118
+ if (input.postcode) {
119
+ props.postcode = input.postcode
120
+ }
121
+
122
+ if (input.country?.name && props.country == null) {
123
+ props.country = input.country.name
124
+ }
125
+
126
+ if (input.country?.code) {
127
+ props.countrycode = input.country.code.toLowerCase()
128
+ }
129
+
130
+ // #1041: house-grade override. A rooftop / interpolated coordinate is a BUILDING, not the admin locality the
131
+ // ancestry above would label it — re-tag the schema so a Photon client renders (and zooms to) a house, and surface
132
+ // the parsed housenumber + street. Matches upstream komoot/photon's bare address point (osm_key:place, osm_value:
133
+ // house, type:house, with housenumber + street and NO name). Drop the admin-derived `name` — else the QGIS FLF label
134
+ // (name + housenumber + street + city + postcode) doubles the city ("Paris 8 Boulevard du Palais Paris 75001"). The
135
+ // city/state/postcode/country the ancestry filled stay put (upstream carries them on a house result too).
136
+ // #1050: street-grade — the street-centroid tier fired. Re-tag per upstream's street shape (full
137
+ // name in `name`, highway/street osm tags); the admin ancestry (city/state/…) stays as context.
138
+ if (input.street?.name && !input.house) {
139
+ props.name = input.street.name
140
+ Object.assign(props, { osm_key: "highway", osm_value: "residential", type: "street" })
141
+ }
142
+
143
+ if (input.house) {
144
+ props.osm_key = "place"
145
+ props.osm_value = "house"
146
+ props.type = "house"
147
+ delete props.name
148
+ const number = input.house.number?.trim()
149
+ const street = input.house.street?.trim()
150
+
151
+ if (number) {
152
+ props.housenumber = number
153
+ }
154
+
155
+ if (street) {
156
+ props.street = street
157
+ }
158
+ }
159
+
160
+ return props
161
+ }
162
+
163
+ /** {@link photonForwardProperties}, wrapped as a Photon Point `Feature` at the resolved coordinate. #1014. */
164
+ export function photonForwardFeature(input: PhotonForwardInput): PhotonFeature {
165
+ return photonFeature(input.lon, input.lat, photonForwardProperties(input))
166
+ }
167
+
168
+ /** The winning place plus its ranked alternatives — the input to {@link photonForwardCollection}. #1016. */
169
+ export interface PhotonForwardResult {
170
+ /** The winning place, with full admin ancestry (from the resolved hierarchy). */
171
+ primary: PhotonForwardInput
172
+ /** Ranked alternative places (Springfield MA / IL / …), each a single-place input; excludes the primary. */
173
+ alternatives: PhotonForwardInput[]
174
+ }
175
+
176
+ /**
177
+ * Assemble a Photon `FeatureCollection` honoring `limit` (#1016): the primary feature first, then ranked alternatives,
178
+ * capped at `limit`. `limit` floors to 1 (Photon always returns at least the best match).
179
+ */
180
+ export function photonForwardCollection(result: PhotonForwardResult, limit: number): PhotonFeatureCollection {
181
+ const cap = Math.max(1, Math.floor(limit) || 1)
182
+ const features = [photonForwardFeature(result.primary)]
183
+
184
+ for (const alt of result.alternatives) {
185
+ if (features.length >= cap) break
186
+ features.push(photonForwardFeature(alt))
187
+ }
188
+
189
+ return photonCollection(features)
190
+ }
191
+
192
+ /**
193
+ * Project a Photon `Feature` into a schema.org `Place` JSON-LD object (`format=jsonld`, #1052) — the OUTPUT-format
194
+ * projection. Reads the feature's already-decorated {@link PhotonProperties} (housenumber/street/city/state/postcode/
195
+ * countrycode + the coordinate), so it stays a pure re-serialization of the SAME resolved place the FeatureCollection
196
+ * carries. `streetAddress` is the plain house-number-first join (the light router has no locale formatter).
197
+ */
198
+ export function photonFeatureToSchemaOrg(feature: PhotonFeature): SchemaOrgPlace {
199
+ const p = feature.properties
200
+ const [lon, lat] = feature.geometry.coordinates
201
+ const streetAddress = composeStreetAddress({ houseNumber: p.housenumber, street: p.street })
202
+
203
+ return toSchemaOrg({
204
+ lat,
205
+ lon,
206
+ name: p.name,
207
+ streetAddress: streetAddress || undefined,
208
+ locality: p.city,
209
+ region: p.state,
210
+ postalCode: p.postcode,
211
+ countryCode: p.countrycode,
212
+ })
213
+ }
214
+
215
+ /** Project a whole Photon `FeatureCollection` into an array of schema.org `Place` objects (`format=jsonld`). #1052. */
216
+ export function photonToSchemaOrg(collection: PhotonFeatureCollection): SchemaOrgPlace[] {
217
+ return collection.features.map(photonFeatureToSchemaOrg)
218
+ }
package/routes.ts ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Route definitions + handlers for the Photon-compatible surface. The OpenAPI document is
7
+ * emitted from these definitions — no handwritten spec. Handlers parse params from the
8
+ * `legacyQuery` express-shaped view; the zod query schemas drive only the emitted document.
9
+ */
10
+
11
+ import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi"
12
+ import type { Context } from "hono"
13
+
14
+ import {
15
+ type PhotonEngine,
16
+ type PhotonFeatureCollection,
17
+ type PhotonReverseParams,
18
+ type PhotonSearchParams,
19
+ } from "./engine.ts"
20
+ import { photonToSchemaOrg } from "./projection.ts"
21
+ import { PhotonMessageCollectionSchema, PhotonResponseSchema, reverseQueryParams, searchQueryParams } from "./schema.ts"
22
+
23
+ const DEFAULT_LIMIT = 15
24
+
25
+ const EMPTY: PhotonFeatureCollection = { type: "FeatureCollection", features: [] }
26
+
27
+ function asString(raw: unknown): string | undefined {
28
+ return typeof raw === "string" && raw.length > 0 ? raw : undefined
29
+ }
30
+
31
+ function asStringArray(raw: unknown): string[] | undefined {
32
+ if (Array.isArray(raw)) return raw.filter((v): v is string => typeof v === "string")
33
+ const s = asString(raw)
34
+
35
+ return s ? [s] : undefined
36
+ }
37
+
38
+ /**
39
+ * Express's `req.query` shape: `string` for a single value, `string[]` for repeats. The legacy parsing helpers
40
+ * (`asString`, `asStringArray`, `Number(...)`) — and their observable degenerate behaviors (repeated `q` → 400,
41
+ * repeated `lat` → NaN → 400) — key off exactly this shape, so the handlers consume it unchanged. Do NOT dedup or
42
+ * canonicalize here: photon's repeatable params (`osm_tag`, `layer`) are contract, and its duplicate-param 400s are
43
+ * contract too (unlike libpostal, where duplicates were never-contract — see the phase-1 adjudications).
44
+ * Null-prototype, matching express-simple's req.query shape (a repeated `?__proto__=` param must create an own
45
+ * property, not reparent the object).
46
+ */
47
+ function legacyQuery(c: Context): Record<string, string | string[]> {
48
+ const out: Record<string, string | string[]> = Object.create(null)
49
+
50
+ for (const [key, values] of Object.entries(c.req.queries())) {
51
+ out[key] = values.length === 1 ? values[0]! : values
52
+ }
53
+
54
+ return out
55
+ }
56
+
57
+ /**
58
+ * A friendly HTML landing page for `GET /` (#1022). Upstream komoot/photon serves no root page, so there's no wire
59
+ * contract to match — this is pure courtesy: a browser visitor (or an evaluator kicking the tires) who pastes the bare
60
+ * host in gets a one-glance orientation with clickable example queries instead of Express's `Cannot GET /` 404, which
61
+ * reads as "the service is broken". Relative example URLs so they resolve against whatever host/port serves this.
62
+ */
63
+ const ROOT_HTML = `<!doctype html>
64
+ <html lang="en">
65
+ <head>
66
+ <meta charset="utf-8">
67
+ <meta name="viewport" content="width=device-width, initial-scale=1">
68
+ <title>@mailwoman/photon</title>
69
+ <style>
70
+ :root { color-scheme: light dark }
71
+ body { font: 16px/1.6 system-ui, -apple-system, sans-serif; max-width: 42rem; margin: 3rem auto; padding: 0 1.25rem }
72
+ h1 { font-size: 1.3rem; margin: 0 0 .5rem }
73
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace }
74
+ ul { padding-left: 1.2rem }
75
+ li { margin: .4rem 0 }
76
+ a { color: #2563eb }
77
+ .q { font-family: ui-monospace, SFMono-Regular, Menlo, monospace }
78
+ footer { margin-top: 2rem; font-size: .9rem; opacity: .8 }
79
+ </style>
80
+ </head>
81
+ <body>
82
+ <h1>@mailwoman/photon</h1>
83
+ <p>A Photon-compatible autocomplete geocoding API — the same <code>/api</code> and <code>/reverse</code> contract, served from a SQLite gazetteer instead of an Elasticsearch cluster.</p>
84
+ <p>Try a query:</p>
85
+ <ul>
86
+ <li><a class="q" href="/api?q=berlin&amp;limit=3">/api?q=berlin&amp;limit=3</a></li>
87
+ <li><a class="q" href="/api?q=1600+pennsylvania+ave&amp;limit=1">/api?q=1600+pennsylvania+ave&amp;limit=1</a></li>
88
+ <li><a class="q" href="/reverse?lat=52.52&amp;lon=13.405">/reverse?lat=52.52&amp;lon=13.405</a></li>
89
+ </ul>
90
+ <footer><a href="https://mailwoman.sister.software/docs/concepts/switching-from-photon">Switching from Photon</a> &middot; <a href="https://mailwoman.sister.software/demo">Live demo</a></footer>
91
+ </body>
92
+ </html>
93
+ `
94
+
95
+ const messageContent = (description: string) => ({
96
+ description,
97
+ content: { "application/json": { schema: PhotonMessageCollectionSchema } },
98
+ })
99
+
100
+ const collectionResponses = {
101
+ 200: {
102
+ description: "A GeoJSON FeatureCollection (or schema.org Place[] when format=jsonld).",
103
+ content: { "application/json": { schema: PhotonResponseSchema } },
104
+ },
105
+ 400: messageContent("A required or malformed parameter."),
106
+ 500: messageContent("An unexpected engine fault. An empty FeatureCollection with a message, never a crash."),
107
+ 501: messageContent("The backing engine method is not wired for this deployment."),
108
+ }
109
+
110
+ const rootRoute = createRoute({
111
+ method: "get",
112
+ path: "/",
113
+ operationId: "getRoot",
114
+ summary: "Landing page",
115
+ tags: ["meta"],
116
+ responses: { 200: { description: "HTML landing page.", content: { "text/html": { schema: z.string() } } } },
117
+ })
118
+
119
+ const searchRoute = createRoute({
120
+ method: "get",
121
+ path: "/api",
122
+ operationId: "search",
123
+ summary: "Forward / autocomplete geocoding",
124
+ tags: ["geocoding"],
125
+ request: { query: searchQueryParams },
126
+ responses: collectionResponses,
127
+ })
128
+
129
+ const reverseRoute = createRoute({
130
+ method: "get",
131
+ path: "/reverse",
132
+ operationId: "reverse",
133
+ summary: "Reverse geocoding",
134
+ tags: ["geocoding"],
135
+ request: { query: reverseQueryParams },
136
+ responses: collectionResponses,
137
+ })
138
+
139
+ /** Register the Photon-compatible routes against an injected engine. */
140
+ export function registerPhotonRoutes(app: OpenAPIHono, engine: PhotonEngine): void {
141
+ app.openapi(rootRoute, (c) => c.html(ROOT_HTML))
142
+
143
+ app.openapi(searchRoute, async (c) => {
144
+ if (!engine.search) return c.json({ ...EMPTY, message: "search not implemented" }, 501)
145
+ const q = legacyQuery(c)
146
+ const query = asString(q["q"])
147
+
148
+ if (!query) return c.json({ ...EMPTY, message: "q is required" }, 400)
149
+ const params: PhotonSearchParams = {
150
+ q: query,
151
+ limit: Number(q["limit"] ?? DEFAULT_LIMIT) || DEFAULT_LIMIT,
152
+ lang: asString(q["lang"]),
153
+ lat: q["lat"] != null ? Number(q["lat"]) : undefined,
154
+ lon: q["lon"] != null ? Number(q["lon"]) : undefined,
155
+ osmTag: asStringArray(q["osm_tag"]),
156
+ layer: asStringArray(q["layer"]),
157
+ }
158
+ const collection = await engine.search(params)
159
+
160
+ // #1052: `format=jsonld` re-serializes the SAME FeatureCollection as schema.org `Place[]` JSON-LD. The
161
+ // declared 200 schema documents only the FeatureCollection shape (matching the legacy yaml — see the
162
+ // Task 4 adjudication); the jsonld branch's differing runtime shape is a local cast at the boundary,
163
+ // never a wire-behavior change (api-kit's `openapi.ts` sets the precedent for this idiom).
164
+ if (asString(q["format"]) === "jsonld") {
165
+ return c.json(photonToSchemaOrg(collection) as never, 200)
166
+ }
167
+
168
+ return c.json(collection, 200)
169
+ })
170
+
171
+ app.openapi(reverseRoute, async (c) => {
172
+ if (!engine.reverse) return c.json({ ...EMPTY, message: "reverse not implemented" }, 501)
173
+ const q = legacyQuery(c)
174
+ const lat = Number(q["lat"])
175
+ const lon = Number(q["lon"])
176
+
177
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
178
+ return c.json({ ...EMPTY, message: "lat and lon are required" }, 400)
179
+ }
180
+
181
+ if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
182
+ return c.json({ ...EMPTY, message: "lat must be in [-90, 90] and lon in [-180, 180]" }, 400)
183
+ }
184
+ const params: PhotonReverseParams = {
185
+ lat,
186
+ lon,
187
+ limit: Number(q["limit"] ?? DEFAULT_LIMIT) || DEFAULT_LIMIT,
188
+ lang: asString(q["lang"]),
189
+ radius: q["radius"] != null ? Number(q["radius"]) : undefined,
190
+ }
191
+ const collection = await engine.reverse(params)
192
+
193
+ // #1052: `format=jsonld` re-serializes the reverse FeatureCollection as schema.org `Place[]` JSON-LD. See
194
+ // the search handler's comment above for why this is a local cast, not a wire-behavior change.
195
+ if (asString(q["format"]) === "jsonld") {
196
+ return c.json(photonToSchemaOrg(collection) as never, 200)
197
+ }
198
+
199
+ return c.json(collection, 200)
200
+ })
201
+ }
package/schema.ts ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Zod wire schemas for the Photon-compatible surface. Key names and envelopes are the vendor
7
+ * contract — immutable. Query schemas are validator-proof by construction (unions accepting
8
+ * string or repeated values) with doc-exact `.openapi()` overrides: validation can never fail,
9
+ * and every wire decision stays in the handlers (see routes.ts's legacyQuery adapter).
10
+ */
11
+
12
+ import { z } from "@hono/zod-openapi"
13
+ import { featureCollectionSchema, featureSchema } from "@mailwoman/api-kit"
14
+
15
+ /** Photon feature properties — OSM-derived keys; tolerant of extras (`[key: string]: unknown` on the wire type). */
16
+ export const PhotonPropertiesSchema = z
17
+ .object({
18
+ osm_id: z.union([z.number(), z.string()]).optional(),
19
+ osm_type: z.string().optional(),
20
+ osm_key: z.string().optional(),
21
+ osm_value: z.string().optional(),
22
+ type: z.string().optional(),
23
+ name: z.string().optional(),
24
+ housenumber: z.string().optional(),
25
+ street: z.string().optional(),
26
+ postcode: z.string().optional(),
27
+ city: z.string().optional(),
28
+ district: z.string().optional(),
29
+ county: z.string().optional(),
30
+ state: z.string().optional(),
31
+ country: z.string().optional(),
32
+ countrycode: z.string().optional(),
33
+ extent: z.tuple([z.number(), z.number(), z.number(), z.number()]).optional(),
34
+ })
35
+ .loose()
36
+ .openapi("PhotonProperties")
37
+
38
+ export const PhotonFeatureSchema = featureSchema(PhotonPropertiesSchema).openapi("PhotonFeature")
39
+
40
+ export const PhotonFeatureCollectionSchema =
41
+ featureCollectionSchema(PhotonFeatureSchema).openapi("PhotonFeatureCollection")
42
+
43
+ /** The error/degenerate envelope: an EMPTY FeatureCollection carrying a message. Never `{error}` on this surface. */
44
+ export const PhotonMessageCollectionSchema = z
45
+ .object({
46
+ type: z.literal("FeatureCollection"),
47
+ features: z.array(PhotonFeatureSchema),
48
+ message: z.string(),
49
+ })
50
+ .openapi("PhotonMessageCollection")
51
+
52
+ /**
53
+ * The schema.org [`GeoCoordinates`](https://schema.org/GeoCoordinates) node — mirrors `@mailwoman/annotations`'s
54
+ * `SchemaOrgGeoCoordinates` interface. Hand-modeled locally (no import from `@mailwoman/annotations`) matching this
55
+ * package's existing wire-schema convention: each surface owns its own doc-accuracy schemas rather than sharing a
56
+ * schema across the package boundary.
57
+ */
58
+ export const SchemaOrgGeoCoordinatesSchema = z
59
+ .object({
60
+ "@type": z.literal("GeoCoordinates"),
61
+ latitude: z.number(),
62
+ longitude: z.number(),
63
+ })
64
+ .openapi("SchemaOrgGeoCoordinates")
65
+
66
+ /** The schema.org [`PostalAddress`](https://schema.org/PostalAddress) node — mirrors `SchemaOrgPostalAddress`. */
67
+ export const SchemaOrgPostalAddressSchema = z
68
+ .object({
69
+ "@type": z.literal("PostalAddress"),
70
+ streetAddress: z.string().optional(),
71
+ postOfficeBoxNumber: z.string().optional(),
72
+ addressLocality: z.string().optional(),
73
+ addressRegion: z.string().optional(),
74
+ postalCode: z.string().optional(),
75
+ addressCountry: z.string().optional(),
76
+ })
77
+ .openapi("SchemaOrgPostalAddress")
78
+
79
+ /**
80
+ * The `format=jsonld` re-serialization (#1052) — mirrors `@mailwoman/annotations`'s `SchemaOrgPlace` interface, the
81
+ * shape `photonToSchemaOrg` actually produces.
82
+ */
83
+ export const SchemaOrgPlaceSchema = z
84
+ .object({
85
+ "@context": z.literal("https://schema.org"),
86
+ "@type": z.literal("Place"),
87
+ name: z.string().optional(),
88
+ geo: SchemaOrgGeoCoordinatesSchema.optional(),
89
+ address: SchemaOrgPostalAddressSchema.optional(),
90
+ })
91
+ .openapi("SchemaOrgPlace")
92
+
93
+ /**
94
+ * The real `/api` + `/reverse` 200 response union (#1052 doc accuracy): a GeoJSON FeatureCollection by default, or an
95
+ * array of schema.org `Place` JSON-LD objects when `format=jsonld` — see `routes.ts`'s handlers (`photonToSchemaOrg`).
96
+ * Doc-only; the wire behavior is unchanged.
97
+ */
98
+ export const PhotonResponseSchema = z
99
+ .union([PhotonFeatureCollectionSchema, z.array(SchemaOrgPlaceSchema)])
100
+ .openapi("PhotonResponse")
101
+
102
+ /**
103
+ * A query param that may legally repeat (or that a client may repeat without the validator being allowed to answer for
104
+ * us). Validator-proof: accepts one value or many; the doc override keeps the emitted parameter schema exact.
105
+ */
106
+ const tolerantParam = z.union([z.string(), z.array(z.string())]).optional()
107
+
108
+ /** `GET /api` query — documented shape; presence/parsing enforced in-handler. */
109
+ export const searchQueryParams = z.object({
110
+ q: tolerantParam.openapi({ type: "string", description: "The query string to search for." }),
111
+ limit: tolerantParam.openapi({ type: "integer", description: "Maximum results (default 15)." }),
112
+ lang: tolerantParam.openapi({ type: "string", description: "Preferred language." }),
113
+ lat: tolerantParam.openapi({ type: "number", description: "Location-bias latitude." }),
114
+ lon: tolerantParam.openapi({ type: "number", description: "Location-bias longitude." }),
115
+ osm_tag: tolerantParam.openapi({
116
+ type: "array",
117
+ items: { type: "string" },
118
+ description: "OSM tag filter; repeatable.",
119
+ }),
120
+ layer: tolerantParam.openapi({ type: "array", items: { type: "string" }, description: "Layer filter; repeatable." }),
121
+ format: tolerantParam.openapi({ type: "string", enum: ["geojson", "jsonld"], description: "Output format." }),
122
+ })
123
+
124
+ /** `GET /reverse` query. */
125
+ export const reverseQueryParams = z.object({
126
+ lat: tolerantParam.openapi({ type: "number", description: "Latitude." }),
127
+ lon: tolerantParam.openapi({ type: "number", description: "Longitude." }),
128
+ limit: tolerantParam.openapi({ type: "integer", description: "Maximum results (default 15)." }),
129
+ lang: tolerantParam.openapi({ type: "string", description: "Preferred language." }),
130
+ radius: tolerantParam.openapi({ type: "number", description: "Search radius in km." }),
131
+ format: tolerantParam.openapi({ type: "string", enum: ["geojson", "jsonld"], description: "Output format." }),
132
+ })