@mailwoman/ogc 0.0.0-stage → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +149 -2
  2. package/cli/main.ts +153 -0
  3. package/lib/app.ts +99 -0
  4. package/lib/collections.ts +159 -0
  5. package/lib/engine.ts +71 -0
  6. package/lib/format.ts +46 -0
  7. package/lib/html.ts +236 -0
  8. package/lib/index.ts +20 -0
  9. package/lib/projection.ts +206 -0
  10. package/lib/routes.ts +587 -0
  11. package/lib/schema.ts +296 -0
  12. package/out/app.d.ts +33 -0
  13. package/out/app.d.ts.map +1 -0
  14. package/out/app.js +67 -0
  15. package/out/app.js.map +1 -0
  16. package/out/cli/main.d.ts +3 -0
  17. package/out/cli/main.d.ts.map +1 -0
  18. package/out/cli/main.js +118 -0
  19. package/out/cli/main.js.map +1 -0
  20. package/out/collections.d.ts +72 -0
  21. package/out/collections.d.ts.map +1 -0
  22. package/out/collections.js +103 -0
  23. package/out/collections.js.map +1 -0
  24. package/out/engine.d.ts +65 -0
  25. package/out/engine.d.ts.map +1 -0
  26. package/out/engine.js +4 -0
  27. package/out/engine.js.map +1 -0
  28. package/out/format.d.ts +18 -0
  29. package/out/format.d.ts.map +1 -0
  30. package/out/format.js +31 -0
  31. package/out/format.js.map +1 -0
  32. package/out/html.d.ts +42 -0
  33. package/out/html.d.ts.map +1 -0
  34. package/out/html.js +153 -0
  35. package/out/html.js.map +1 -0
  36. package/out/index.d.ts +17 -0
  37. package/out/index.d.ts.map +1 -0
  38. package/out/index.js +19 -0
  39. package/out/index.js.map +1 -0
  40. package/out/projection.d.ts +26 -0
  41. package/out/projection.d.ts.map +1 -0
  42. package/out/projection.js +168 -0
  43. package/out/projection.js.map +1 -0
  44. package/out/routes.d.ts +93 -0
  45. package/out/routes.d.ts.map +1 -0
  46. package/out/routes.js +429 -0
  47. package/out/routes.js.map +1 -0
  48. package/out/schema.d.ts +267 -0
  49. package/out/schema.d.ts.map +1 -0
  50. package/out/schema.js +241 -0
  51. package/out/schema.js.map +1 -0
  52. package/package.json +98 -3
package/README.md CHANGED
@@ -1,3 +1,150 @@
1
- # Temporary Holding Version
1
+ # @mailwoman/ogc
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [OGC API](https://ogcapi.ogc.org) adapter for the [Mailwoman](https://mailwoman.post) engine. OGC API clients
4
+ such as QGIS, GDAL/OGR and OWSLib start from a service's landing page and its conformance declaration. This
5
+ package serves both, the API definition they link to, as described in
6
+ [OGC API Common Part 1](https://docs.ogc.org/is/19-072/19-072.html), and the collections of
7
+ [OGC API Common Part 2](https://www.opengis.net/doc/is/ogcapi-common-2/1.0). Forward geocoding is served at `/search`, in the
8
+ form of the [PDOK Location API](https://api.pdok.nl/kadaster/location-api/v1/).
9
+
10
+ ```sh
11
+ npx @mailwoman/ogc serve --port 8090
12
+ curl "http://localhost:8090/collections"
13
+ curl "http://localhost:8090/search?q=Dam%201%2C%201012JS%20Amsterdam&limit=2"
14
+ ```
15
+
16
+ `serve` loads the same engine as `@mailwoman/photon` and `@mailwoman/nominatim`: the en-US classifier, the
17
+ gazetteer, and the address-point, interpolation and street-centroid layers under `$MAILWOMAN_DATA_ROOT`. It
18
+ exits with a message naming the missing data when no gazetteer is found. Pass `--candidate-db <path>` to choose
19
+ a candidate gazetteer.
20
+
21
+ ## Endpoints
22
+
23
+ | Endpoint | What it returns |
24
+ | ----------------------------- | ---------------------------------------------------------------------------------- |
25
+ | `/` | The landing page: a title, a description and links to every resource below |
26
+ | `/conformance` | `{ "conformsTo": [...] }`, the conformance classes the routes implement |
27
+ | `/api` | The API definition as OpenAPI 3.0 (`application/vnd.oai.openapi+json;version=3.0`) |
28
+ | `/collections` | `{ "links": [...], "collections": [...] }`, the collections the engine serves |
29
+ | `/collections/{collectionId}` | One collection, as `/collections` lists it, or a 404 for an unknown id |
30
+ | `/search` | Forward geocoding, as a GeoJSON FeatureCollection (`application/geo+json`) |
31
+ | `/openapi.json` | The same routes as OpenAPI 3.1, the document every Mailwoman HTTP surface serves |
32
+
33
+ Every resource accepts `f=json` or `f=html`. Without `f`, the `Accept` header decides, and JSON answers a
34
+ request that names neither. Any other `f` value, a query parameter the API definition doesn't name, or an
35
+ invalid value returns a 400 with the native error body, `{ "error": "invalid query parameter", "detail": "..." }`.
36
+
37
+ ## Collections
38
+
39
+ A collection groups the answers one kind of layer produces. The geocoder reports which tier placed each
40
+ coordinate, and the tier decides the collection:
41
+
42
+ | Collection | Tier | Served when |
43
+ | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------- |
44
+ | `addresses` | `address_point`, `interpolated` | a region has an address-point or interpolation layer |
45
+ | `streets` | `street` | a region has a street-centroid layer |
46
+ | `postcodes` | `postcode`, and postcode places | always, because postcode places come from the gazetteer |
47
+ | `places` | `admin`, and the other gazetteer places the resolver weighed | always |
48
+ | `plus-codes` | `plus_code` | always, because the engine decodes plus codes without a layer |
49
+
50
+ At startup the server asks each layer provider for every region it serves and lists `addresses` and `streets`
51
+ only when some region has a layer. Their descriptions name those regions, such as `FR` or `US-TX`, and the
52
+ startup banner prints them. A region absent from the list has no layer the engine opened. Its addresses may
53
+ still exist, and the list makes no claim about them.
54
+
55
+ Each collection reports `version: 1` and `geometryDimension: 0`, since every feature is a point. `itemType`
56
+ and the `items` link are absent because the server doesn't serve `/collections/{collectionId}/items`.
57
+
58
+ ## Search
59
+
60
+ | Parameter | Meaning |
61
+ | --------------------------- | -------------------------------------------------------------------------------------- |
62
+ | `q` | The address or place to search for. Required. |
63
+ | `<collectionId>[version]=1` | Restrict the search to the named collections. Repeat it for each collection. |
64
+ | `<collectionId>[relevance]` | A number from 0 to 1. It also selects the collection, and doesn't change the ranking. |
65
+ | `limit` | The most features to return, from 1 to 50. The default is 10. |
66
+ | `bbox` | `minLon,minLat,maxLon,maxLat`. Only features whose point lies inside the box are kept. |
67
+ | `f` | `json` (GeoJSON) or `html`. |
68
+
69
+ The response carries `timeStamp`, `links` (`self` and `alternate`) and `numberReturned` beside `features`.
70
+ Each feature's properties are:
71
+
72
+ - `display_name`: a one-line label, in the country's address order for an address or a street.
73
+ - `score`: the engine's ranking score for the match, larger ranking higher. Scores compare candidates for
74
+ one part of the input and have no unit across collections. A match the engine measured no score for, such as
75
+ an address point or a place without a recorded population, has `score: null`, and `score_unmeasured` names the
76
+ reason.
77
+ - `collection_id`: the collection the feature belongs to.
78
+ - `place_id` and `placetype`: the gazetteer place ID, such as `wof:85975673`, and placetype, such as `locality`
79
+ or `localadmin`, of a place or postcode. Two places that share a label, such as a locality and the
80
+ local-government area of the same name, differ here. Both are absent for an address, a street and a plus code,
81
+ and `place_id` is absent for a place the gazetteer gave no ID.
82
+
83
+ A place's `display_name` is its name, then the ancestors the gazetteer records between it and its country, most
84
+ specific first, then the country, such as `Camden, Ouachita, Arkansas, United States`. An ancestor that repeats
85
+ the place's name appears once. A place without a WOF place ID, or without a recorded ancestry, keeps its name and
86
+ country.
87
+
88
+ The first feature is the engine's answer. The places the resolver weighed for the same part of the input
89
+ follow. A box whose minimum longitude exceeds its maximum crosses the antimeridian. `f=html` without `q`
90
+ serves a search form, which the landing page links as `search`.
91
+
92
+ ### Differences from PDOK
93
+
94
+ - A `q` without a collection parameter searches every collection and returns 200. PDOK answers 400, because
95
+ its index needs the collection. The engine has no such need.
96
+ - `<collectionId>[relevance]` is accepted so a PDOK client works unchanged, but it doesn't reweight the
97
+ ranking, because the engine's scores don't compare across collections.
98
+ - Features carry no `href` to an item yet. The link arrives with `/collections/{collectionId}/items` in #3142.
99
+ - PDOK defines no reverse operation, so reverse geocoding stays on `@mailwoman/photon` and `@mailwoman/nominatim`.
100
+
101
+ ## Conformance
102
+
103
+ The declaration lists five OGC API Common Part 1 classes, each under
104
+ `http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/`, and one Part 2 class:
105
+
106
+ - `core`: HTTP 1.1, and a 400 for an unknown query parameter or an invalid value.
107
+ - `landing-page`: the landing page links the API definition (`service-desc` and `service-doc`) and the
108
+ conformance declaration, and each link resolves.
109
+ - `json`: the landing page, conformance declaration and collections as `application/json`.
110
+ - `html`: the same resources as HTML5, each link an `<a>` element.
111
+ - `oas30`: an OpenAPI 3.0 definition as `service-desc` and its HTML form as `service-doc`.
112
+ - `http://www.opengis.net/spec/ogcapi-common-2/1.0/conf/collections`: the landing page links `/collections`
113
+ as `data`, and `/collections` and each `/collections/{collectionId}` carry `self` and `alternate` links with
114
+ a `type`.
115
+
116
+ `/search` is PDOK's convention. OGC publishes no conformance class for it, so the declaration names none.
117
+
118
+ ## Link hrefs behind a proxy
119
+
120
+ Link hrefs are absolute and resolve against the request's own origin. Behind a reverse proxy that rewrites
121
+ the host or mounts the service under a path, pass the public URL:
122
+
123
+ ```sh
124
+ npx @mailwoman/ogc serve --base-url https://example.org/ogc/
125
+ ```
126
+
127
+ ## Library use
128
+
129
+ `createOGCApp` takes an `OGCEngine`: the collections it serves and a `search(q)` that returns its matches.
130
+ `geocodeSearchHits` projects a `geocodeAddress` result to those matches.
131
+
132
+ ```ts
133
+ import { serveNode } from "@mailwoman/api-kit"
134
+ import { createOGCApp, geocodeSearchHits, OGCCollectionID } from "@mailwoman/ogc"
135
+
136
+ const app = createOGCApp(
137
+ {
138
+ collections: [{ id: OGCCollectionID.Places, regions: null }],
139
+ search: async (q) => geocodeSearchHits(await geocode(q)),
140
+ },
141
+ { baseURL: "https://example.org/ogc/" }
142
+ )
143
+
144
+ serveNode({ fetch: app.fetch, port: 8090, hostname: "0.0.0.0" })
145
+ ```
146
+
147
+ ## CORS
148
+
149
+ The server sends `Access-Control-Allow-Origin: *` and answers preflight `OPTIONS` by default. Turn it off
150
+ with `--no-cors`, or `createOGCApp(engine, { cors: false })`, where a reverse proxy already sets the headers.
package/cli/main.ts ADDED
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
3
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
4
+
5
+ /**
6
+ * `mailwoman-ogc` boots the OGC API surface through the `serve` command
7
+ * and prints its API definition through the `openapi` command.
8
+ *
9
+ * `serve` wires `/search` over `geocodeAddress` (parse, then resolve) with the same
10
+ * gazetteer, classifier and rooftop providers the Photon and Nominatim servers attach,
11
+ * and lists as collections the layers those providers opened.
12
+ */
13
+
14
+ import { serveNode } from "@mailwoman/api-kit"
15
+ import { worldCountries } from "@mailwoman/codex/country/sets"
16
+ import { US_STATE_BY_ABBREVIATION } from "@mailwoman/codex/us"
17
+ import { dataRootPath } from "@mailwoman/core/data-root"
18
+ import { parseArguments } from "@mailwoman/core/scripting/arguments"
19
+ import { createWOFResolver } from "@mailwoman/resolver"
20
+ import {
21
+ corsBannerLine,
22
+ gazetteerBannerLines,
23
+ loadClassifierOrExit,
24
+ openAPICommand,
25
+ resolveGazetteerOrExit,
26
+ runDropInCLI,
27
+ } from "mailwoman/cli/kit/dropin"
28
+ import type { ResolvedEngineStamp } from "mailwoman/cli/kit/engine-stamp"
29
+ import { geocodeAddress, USStateDatabaseProvider } from "mailwoman/geocode"
30
+ import { openServingRooftopProviders } from "mailwoman/geocode/serving-layers"
31
+ import { createResolverBackend } from "mailwoman/resolver-backend"
32
+
33
+ import {
34
+ createOGCApp,
35
+ geocodeSearchHits,
36
+ OGC_COLLECTION_CATALOG,
37
+ OGC_DEFAULT_PORT,
38
+ OGC_DOC_INFO,
39
+ type OGCCollectionID,
40
+ type OGCEngine,
41
+ type RegionLayerProbe,
42
+ servedCollections,
43
+ } from "#index"
44
+
45
+ const BINARY_NAME = "mailwoman-ogc"
46
+
47
+ /**
48
+ * The engine the `openapi` command documents.
49
+ *
50
+ * It lists every collection the surface can serve, so the printed definition
51
+ * declares each collection's `/search` parameters.
52
+ */
53
+ const DOCUMENTED_ENGINE: OGCEngine = {
54
+ collections: Object.keys(OGC_COLLECTION_CATALOG).map((id) => ({ id: id as OGCCollectionID, regions: null })),
55
+ search: async () => [],
56
+ }
57
+
58
+ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
59
+ const { values } = parseArguments({
60
+ options: {
61
+ port: { type: "string", default: String(OGC_DEFAULT_PORT) },
62
+ host: { type: "string", default: "0.0.0.0" },
63
+ // The public base URL that link hrefs resolve against, for a deployment behind a reverse proxy.
64
+ "base-url": { type: "string" },
65
+ "candidate-db": { type: "string" },
66
+ // Permissive CORS is on by default because OGC API clients run in browsers too.
67
+ // `--no-cors` turns it off where a reverse proxy already sets the headers.
68
+ cors: { type: "boolean", default: true },
69
+ },
70
+ allowNegative: true,
71
+ allowPositionals: true,
72
+ })
73
+
74
+ const port = Number(values.port) || OGC_DEFAULT_PORT
75
+ const host = values.host ?? "0.0.0.0"
76
+ const baseURL = values["base-url"]
77
+
78
+ const resolverMod = await import("@mailwoman/resolver-wof-sqlite")
79
+ const gazetteer = await resolveGazetteerOrExit(values["candidate-db"] ?? null)
80
+ const { candidateDB, wofPaths } = gazetteer
81
+ const classifier = await loadClassifierOrExit()
82
+
83
+ const backend = await createResolverBackend(resolverMod, { wofPaths, candidateDB })
84
+ const resolver = createWOFResolver(backend)
85
+ // The gazetteer's own ancestry reader labels each place match with its region and county.
86
+ const ancestorsOf = backend.ancestors?.bind(backend)
87
+ const extracts = await USStateDatabaseProvider.create(resolverMod, dataRootPath())
88
+ // The national open register ahead of the OpenStreetMap tier, read from one generation
89
+ // of the active selection, as the Photon and Nominatim servers read them.
90
+ const rooftops = await openServingRooftopProviders(dataRootPath())
91
+ const countries = worldCountries()
92
+
93
+ const probes: RegionLayerProbe[] = [
94
+ {
95
+ provider: extracts,
96
+ keys: Object.keys(US_STATE_BY_ABBREVIATION).map((abbreviation) => abbreviation.toLowerCase()),
97
+ regionOf: (slug) => `US-${slug.toUpperCase()}`,
98
+ },
99
+ { provider: rooftops.national, keys: countries, regionOf: (code) => code.toUpperCase() },
100
+ ...(rooftops.osm
101
+ ? [{ provider: rooftops.osm, keys: countries, regionOf: (code: string) => code.toUpperCase() }]
102
+ : []),
103
+ ]
104
+
105
+ const engine: OGCEngine = {
106
+ collections: servedCollections(probes),
107
+ async search(q) {
108
+ // The call sets no country constraint, so the placer routes the query to its own country.
109
+ const result = await geocodeAddress(q, {
110
+ classifier,
111
+ resolver,
112
+ databases: extracts.for,
113
+ nationalDatabases: rooftops.national.for,
114
+ ...(rooftops.osm ? { osmDatabases: rooftops.osm.for } : {}),
115
+ })
116
+
117
+ return geocodeSearchHits(result, ancestorsOf)
118
+ },
119
+ }
120
+
121
+ const app = createOGCApp(engine, { cors: values.cors, engine: engineStamp.stamp, baseURL })
122
+
123
+ await serveNode({
124
+ fetch: app.fetch,
125
+ port,
126
+ hostname: host,
127
+ onListen: () => {
128
+ console.error(`[@mailwoman/ogc] listening on http://${host}:${port}`)
129
+ console.error(` base URL: ${baseURL ?? "(the request's own origin)"}`)
130
+
131
+ for (const line of gazetteerBannerLines(gazetteer)) {
132
+ console.error(line)
133
+ }
134
+
135
+ for (const { id, regions } of engine.collections) {
136
+ console.error(` collection ${id}: ${regions ? regions.join(" ") : "worldwide"}`)
137
+ }
138
+
139
+ console.error(corsBannerLine(values.cors))
140
+ console.error(` endpoints: GET / GET /conformance GET /api GET /collections GET /search GET /openapi.json`)
141
+ },
142
+ })
143
+ }
144
+
145
+ await runDropInCLI({
146
+ binaryName: BINARY_NAME,
147
+ openapi: openAPICommand(BINARY_NAME, createOGCApp, OGC_DOC_INFO, DOCUMENTED_ENGINE),
148
+ serve,
149
+ usage: [
150
+ " serve [--port 8090] [--host 0.0.0.0] [--base-url <url>] [--candidate-db <path>] [--no-cors]",
151
+ " openapi [--flavor 3.1|3.0] [--out <path>]",
152
+ ],
153
+ })
package/lib/app.ts ADDED
@@ -0,0 +1,99 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ import { OpenAPIHono } from "@hono/zod-openapi"
5
+ import {
6
+ attachOpenAPIDocs,
7
+ type CompatibilityAppOptions,
8
+ engineHeaders,
9
+ errorResponse,
10
+ type OpenAPIDocInfo,
11
+ readServedDocumentInfo,
12
+ } from "@mailwoman/api-kit"
13
+ import { cors } from "hono/cors"
14
+
15
+ import type { OGCEngine } from "#engine"
16
+ import { registerOGCRoutes } from "#routes"
17
+
18
+ /**
19
+ * The port `mailwoman-ogc serve` listens on unless told otherwise.
20
+ */
21
+ export const OGC_DEFAULT_PORT = 8090
22
+
23
+ /**
24
+ * The document info for the OGC API surface.
25
+ *
26
+ * The landing page reads its title and description from it, and both API definitions include it.
27
+ */
28
+ export const OGC_DOC_INFO: OpenAPIDocInfo = {
29
+ ...(await readServedDocumentInfo(import.meta.url, "@mailwoman/ogc")),
30
+ license: { name: "AGPL-3.0-only OR LicenseRef-Commercial", identifier: "AGPL-3.0-only" },
31
+ contact: { name: "Sister Software", url: "https://mailwoman.post" },
32
+ externalDocs: {
33
+ description: "What Mailwoman is",
34
+ url: "https://mailwoman.post/product",
35
+ },
36
+ servers: [
37
+ {
38
+ url: "http://{host}:{port}",
39
+ variables: { host: { default: "127.0.0.1" }, port: { default: String(OGC_DEFAULT_PORT) } },
40
+ },
41
+ ],
42
+ security: [],
43
+ tags: [
44
+ { name: "capabilities", description: "The OGC API Common landing page, conformance and API definition." },
45
+ { name: "data", description: "The collections and the forward geocoding search." },
46
+ ],
47
+ }
48
+
49
+ /**
50
+ * Options for {@link createOGCApp}.
51
+ */
52
+ export interface OGCAppOptions extends CompatibilityAppOptions {
53
+ /**
54
+ * The service's public base URL.
55
+ * Link hrefs and the API definition's `servers` entry use it.
56
+ *
57
+ * @defaultValue The request's own origin.
58
+ */
59
+ baseURL?: string
60
+ }
61
+
62
+ /**
63
+ * Builds the OGC API app around the given {@link OGCEngine}: the landing page at `/`,
64
+ * the conformance declaration at `/conformance`, the OpenAPI 3.0 definition at `/api`,
65
+ * the collections at `/collections`, forward geocoding at `/search`, and the OpenAPI
66
+ * 3.1 document at `/openapi.json` that every Mailwoman surface serves.
67
+ */
68
+ export function createOGCApp(engine: OGCEngine, options: OGCAppOptions = {}): OpenAPIHono {
69
+ const app = new OpenAPIHono({
70
+ defaultHook: (result, c) => {
71
+ if (result.success) return
72
+
73
+ const detail = result.error.issues
74
+ .map((issue) => (issue.path.length ? `${issue.path.join(".")}: ${issue.message}` : issue.message))
75
+ .join("; ")
76
+
77
+ return errorResponse(c, 400, "invalid query parameter", detail)
78
+ },
79
+ })
80
+
81
+ if (options.cors !== false) {
82
+ app.use(cors({ origin: "*", allowMethods: ["GET", "OPTIONS"], allowHeaders: ["*"], maxAge: 86_400 }))
83
+ }
84
+
85
+ if (options.engine) {
86
+ app.use(engineHeaders(options.engine))
87
+ }
88
+
89
+ app.onError((_error, c) => errorResponse(c, 500, "internal error"))
90
+
91
+ const docInfo: OpenAPIDocInfo = options.baseURL
92
+ ? { ...OGC_DOC_INFO, servers: [{ url: options.baseURL }] }
93
+ : OGC_DOC_INFO
94
+
95
+ registerOGCRoutes(app, engine, { baseURL: options.baseURL, docInfo })
96
+ attachOpenAPIDocs(app, docInfo)
97
+
98
+ return app
99
+ }
@@ -0,0 +1,159 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The collections the OGC surface can describe, and the engine output each one holds.
6
+ *
7
+ * A collection groups the answers one kind of serving layer produces.
8
+ * The geocoder reports which tier placed a coordinate, so the tier decides the collection.
9
+ *
10
+ * The running engine lists only the collections whose layers it opened,
11
+ * and `/collections` serves that list.
12
+ */
13
+
14
+ import type { GeocodeResult } from "@mailwoman/core/geocode"
15
+ import type { RegionDatabaseProvider } from "@mailwoman/core/resolver"
16
+
17
+ import type { OGCServedCollection } from "#engine"
18
+
19
+ type ResolutionTier = GeocodeResult["resolution_tier"]
20
+
21
+ /**
22
+ * The table maps each collection's name to its id.
23
+ */
24
+ export const OGCCollectionID = {
25
+ Addresses: "addresses",
26
+ Streets: "streets",
27
+ Postcodes: "postcodes",
28
+ Places: "places",
29
+ PlusCodes: "plus-codes",
30
+ } as const
31
+
32
+ export type OGCCollectionID = (typeof OGCCollectionID)[keyof typeof OGCCollectionID]
33
+
34
+ /**
35
+ * The fixed title and description of one collection.
36
+ */
37
+ export interface OGCCollectionEntry {
38
+ title: string
39
+ description: string
40
+ }
41
+
42
+ /**
43
+ * The title and description of every collection.
44
+ */
45
+ export const OGC_COLLECTION_CATALOG: Readonly<Record<OGCCollectionID, OGCCollectionEntry>> = {
46
+ [OGCCollectionID.Addresses]: {
47
+ title: "Addresses",
48
+ description:
49
+ "House-grade coordinates: a matched address point, or a point interpolated along a street's address range.",
50
+ },
51
+ [OGCCollectionID.Streets]: {
52
+ title: "Streets",
53
+ description: "Street centroids, answering a street named without a house number.",
54
+ },
55
+ [OGCCollectionID.Postcodes]: {
56
+ title: "Postcodes",
57
+ description: "Postcode places from the gazetteer, located at the postcode's own coordinate.",
58
+ },
59
+ [OGCCollectionID.Places]: {
60
+ title: "Places",
61
+ description: "Gazetteer places: localities, districts, counties, regions and countries.",
62
+ },
63
+ [OGCCollectionID.PlusCodes]: {
64
+ title: "Plus codes",
65
+ description: "Open Location Codes the engine decodes to the center of their area. No data layer backs it.",
66
+ },
67
+ }
68
+
69
+ /**
70
+ * The collection that holds an answer the geocoder placed at `tier`.
71
+ *
72
+ * @returns Null for a tier no collection holds, such as `venue`, whose layer the OGC engine doesn't open.
73
+ */
74
+ export function collectionOfTier(tier: ResolutionTier): OGCCollectionID | null {
75
+ switch (tier) {
76
+ case "address_point":
77
+ case "interpolated":
78
+ return OGCCollectionID.Addresses
79
+ case "street":
80
+ return OGCCollectionID.Streets
81
+ case "postcode":
82
+ return OGCCollectionID.Postcodes
83
+ case "admin":
84
+ return OGCCollectionID.Places
85
+ case "plus_code":
86
+ return OGCCollectionID.PlusCodes
87
+ case "venue":
88
+ return null
89
+ }
90
+ }
91
+
92
+ /**
93
+ * The collection that holds a gazetteer place of `placetype`.
94
+ */
95
+ export function collectionOfPlacetype(placetype: string): OGCCollectionID {
96
+ return placetype === "postalcode" ? OGCCollectionID.Postcodes : OGCCollectionID.Places
97
+ }
98
+
99
+ /**
100
+ * One region-keyed provider of street-tier layers, and the keys to ask it for.
101
+ */
102
+ export interface RegionLayerProbe {
103
+ provider: Pick<RegionDatabaseProvider, "for">
104
+ keys: Iterable<string>
105
+ /**
106
+ * The region code a key names in a collection description, such as `US-TX` for the key `tx`.
107
+ */
108
+ regionOf: (key: string) => string
109
+ }
110
+
111
+ /**
112
+ * The collections an engine serves, from the layers its providers opened.
113
+ *
114
+ * The gazetteer is always open, because the engine refuses to start without one,
115
+ * so places, postcodes and plus codes are always served.
116
+ * Addresses and streets are served when some region has an address-point, interpolation
117
+ * or street-centroid layer, and their descriptions name those regions.
118
+ *
119
+ * A collection no region has a layer for is left out of the list.
120
+ *
121
+ * A provider opens a region's layers when asked for the region.
122
+ * A query for that region would open them as well.
123
+ */
124
+ export function servedCollections(probes: readonly RegionLayerProbe[]): OGCServedCollection[] {
125
+ const addressRegions = new Set<string>()
126
+ const streetRegions = new Set<string>()
127
+
128
+ for (const { provider, keys, regionOf } of probes) {
129
+ for (const key of keys) {
130
+ const databases = provider.for(key)
131
+
132
+ if (databases.addressPoints || databases.interpolation) {
133
+ addressRegions.add(regionOf(key))
134
+ }
135
+
136
+ if (databases.streetCentroids) {
137
+ streetRegions.add(regionOf(key))
138
+ }
139
+ }
140
+ }
141
+
142
+ const served: OGCServedCollection[] = []
143
+
144
+ if (addressRegions.size) {
145
+ served.push({ id: OGCCollectionID.Addresses, regions: [...addressRegions].toSorted() })
146
+ }
147
+
148
+ if (streetRegions.size) {
149
+ served.push({ id: OGCCollectionID.Streets, regions: [...streetRegions].toSorted() })
150
+ }
151
+
152
+ served.push(
153
+ { id: OGCCollectionID.Postcodes, regions: null },
154
+ { id: OGCCollectionID.Places, regions: null },
155
+ { id: OGCCollectionID.PlusCodes, regions: null }
156
+ )
157
+
158
+ return served
159
+ }
package/lib/engine.ts ADDED
@@ -0,0 +1,71 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The engine the OGC routes delegate to.
6
+ *
7
+ * The routes own validation, the collection and `bbox` filters, `limit` and the response envelope.
8
+ * The engine answers one query with every match it found, and lists the
9
+ * collections its opened layers serve.
10
+ */
11
+
12
+ import type { OGCCollectionID } from "#collections"
13
+
14
+ /**
15
+ * A collection the engine serves, and the regions its layers cover.
16
+ */
17
+ export interface OGCServedCollection {
18
+ id: OGCCollectionID
19
+ /**
20
+ * The regions that have a layer the engine opened for this collection, such as `FR` or `US-TX`.
21
+ *
22
+ * Null when the collection isn't divided by region, as for the worldwide gazetteer.
23
+ */
24
+ regions: readonly string[] | null
25
+ }
26
+
27
+ /**
28
+ * One match for a `/search` query.
29
+ */
30
+ export interface OGCSearchHit {
31
+ collectionID: OGCCollectionID
32
+ lon: number
33
+ lat: number
34
+ displayName: string
35
+ /**
36
+ * The engine's ranking score for the match, or null when the engine measured none.
37
+ */
38
+ score: number | null
39
+ /**
40
+ * Why `score` is null, absent when it holds a value.
41
+ */
42
+ scoreUnmeasured?: string
43
+ /**
44
+ * The gazetteer place ID of a place match, such as `wof:85975673`.
45
+ *
46
+ * Absent for an address, a street or a plus code, and for a place the gazetteer gave no ID.
47
+ */
48
+ placeID?: string
49
+ /**
50
+ * The gazetteer placetype of a place match, such as `locality` or `postalcode`.
51
+ *
52
+ * Absent for an address, a street or a plus code.
53
+ */
54
+ placetype?: string
55
+ }
56
+
57
+ /**
58
+ * The engine behind the OGC routes.
59
+ */
60
+ export interface OGCEngine {
61
+ /**
62
+ * The collections the engine serves, in the order `/collections` lists them.
63
+ */
64
+ readonly collections: readonly OGCServedCollection[]
65
+ /**
66
+ * Every match for `q`, best first.
67
+ *
68
+ * An empty array means the engine found no match.
69
+ */
70
+ search(q: string): Promise<OGCSearchHit[]>
71
+ }
package/lib/format.ts ADDED
@@ -0,0 +1,46 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Response encoding negotiation for the OGC API surface.
6
+ *
7
+ * OGC API Common negotiates the encoding through HTTP content negotiation
8
+ * and admits a query parameter that overrides it.
9
+ * The `f` parameter decides when present.
10
+ *
11
+ * Otherwise the `Accept` header decides, and JSON answers a request that names neither encoding.
12
+ */
13
+
14
+ import type { Context } from "hono"
15
+ import { accepts } from "hono/accepts"
16
+
17
+ import { OGCFormat, OGCMediaType } from "#schema"
18
+
19
+ /**
20
+ * The JSON media types a request may name in `Accept`, beside `text/html`.
21
+ *
22
+ * `/api` serves the OpenAPI media type and answers a request for plain JSON with it too,
23
+ * and `/search` serves GeoJSON the same way.
24
+ */
25
+ const JSON_MEDIA_TYPES: readonly string[] = [
26
+ OGCMediaType.JSON,
27
+ OGCMediaType.GeoJSON,
28
+ "application/vnd.oai.openapi+json",
29
+ ]
30
+
31
+ /**
32
+ * The encoding a request asks for.
33
+ *
34
+ * @param f The validated `f` query parameter, absent when the request didn't send one.
35
+ */
36
+ export function negotiateFormat(c: Context, f: OGCFormat | undefined): OGCFormat {
37
+ if (f) return f
38
+
39
+ const matched = accepts(c, {
40
+ header: "Accept",
41
+ supports: [...JSON_MEDIA_TYPES, OGCMediaType.HTML],
42
+ default: OGCMediaType.JSON,
43
+ })
44
+
45
+ return matched === OGCMediaType.HTML ? OGCFormat.HTML : OGCFormat.JSON
46
+ }