@mailwoman/ogc 0.0.0-stage → 11.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +288 -2
  2. package/cli/geocoder.ts +50 -0
  3. package/cli/main.ts +407 -0
  4. package/lib/app.ts +107 -0
  5. package/lib/bbox.ts +69 -0
  6. package/lib/collections.ts +213 -0
  7. package/lib/engine.ts +143 -0
  8. package/lib/format.ts +46 -0
  9. package/lib/html.ts +298 -0
  10. package/lib/index.ts +24 -0
  11. package/lib/items.ts +169 -0
  12. package/lib/projection.ts +226 -0
  13. package/lib/provenance.ts +86 -0
  14. package/lib/refusal.ts +34 -0
  15. package/lib/routes.ts +852 -0
  16. package/lib/schema.ts +457 -0
  17. package/out/app.d.ts +41 -0
  18. package/out/app.d.ts.map +1 -0
  19. package/out/app.js +67 -0
  20. package/out/app.js.map +1 -0
  21. package/out/bbox.d.ts +23 -0
  22. package/out/bbox.d.ts.map +1 -0
  23. package/out/bbox.js +54 -0
  24. package/out/bbox.js.map +1 -0
  25. package/out/cli/geocoder.d.ts +24 -0
  26. package/out/cli/geocoder.d.ts.map +1 -0
  27. package/out/cli/geocoder.js +28 -0
  28. package/out/cli/geocoder.js.map +1 -0
  29. package/out/cli/main.d.ts +3 -0
  30. package/out/cli/main.d.ts.map +1 -0
  31. package/out/cli/main.js +297 -0
  32. package/out/cli/main.js.map +1 -0
  33. package/out/collections.d.ts +99 -0
  34. package/out/collections.d.ts.map +1 -0
  35. package/out/collections.js +132 -0
  36. package/out/collections.js.map +1 -0
  37. package/out/engine.d.ts +133 -0
  38. package/out/engine.d.ts.map +1 -0
  39. package/out/engine.js +4 -0
  40. package/out/engine.js.map +1 -0
  41. package/out/format.d.ts +18 -0
  42. package/out/format.d.ts.map +1 -0
  43. package/out/format.js +31 -0
  44. package/out/format.js.map +1 -0
  45. package/out/html.d.ts +52 -0
  46. package/out/html.d.ts.map +1 -0
  47. package/out/html.js +200 -0
  48. package/out/html.js.map +1 -0
  49. package/out/index.d.ts +21 -0
  50. package/out/index.d.ts.map +1 -0
  51. package/out/index.js +23 -0
  52. package/out/index.js.map +1 -0
  53. package/out/items.d.ts +38 -0
  54. package/out/items.d.ts.map +1 -0
  55. package/out/items.js +136 -0
  56. package/out/items.js.map +1 -0
  57. package/out/projection.d.ts +40 -0
  58. package/out/projection.d.ts.map +1 -0
  59. package/out/projection.js +181 -0
  60. package/out/projection.js.map +1 -0
  61. package/out/provenance.d.ts +41 -0
  62. package/out/provenance.d.ts.map +1 -0
  63. package/out/provenance.js +60 -0
  64. package/out/provenance.js.map +1 -0
  65. package/out/refusal.d.ts +18 -0
  66. package/out/refusal.d.ts.map +1 -0
  67. package/out/refusal.js +30 -0
  68. package/out/refusal.js.map +1 -0
  69. package/out/routes.d.ts +95 -0
  70. package/out/routes.d.ts.map +1 -0
  71. package/out/routes.js +624 -0
  72. package/out/routes.js.map +1 -0
  73. package/out/schema.d.ts +422 -0
  74. package/out/schema.d.ts.map +1 -0
  75. package/out/schema.js +378 -0
  76. package/out/schema.js.map +1 -0
  77. package/out/tools/ets.run.d.ts +2 -0
  78. package/out/tools/ets.run.d.ts.map +1 -0
  79. package/out/tools/ets.run.js +187 -0
  80. package/out/tools/ets.run.js.map +1 -0
  81. package/package.json +120 -3
  82. package/tools/ets.run.ts +258 -0
package/cli/main.ts ADDED
@@ -0,0 +1,407 @@
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 type { LayerTerms } from "@mailwoman/core/layers/provenance"
17
+ import { parseArguments } from "@mailwoman/core/scripting/arguments"
18
+ import { parseObligationRefusals } from "@mailwoman/license/refusals"
19
+ import {
20
+ PostcodePlaceBrowser,
21
+ wofDatabaseHoldsPostcodes,
22
+ } from "@mailwoman/resolver-wof-sqlite/candidate/postcode-browse"
23
+ import { WOFPlaceBrowser } from "@mailwoman/resolver-wof-sqlite/lookup/browse"
24
+ import {
25
+ corsBannerLine,
26
+ type GazetteerPaths,
27
+ gazetteerBannerLines,
28
+ gazetteerFreshness,
29
+ openAPICommand,
30
+ readListenPort,
31
+ runDropInCLI,
32
+ } from "mailwoman/cli/kit/dropin"
33
+ import type { ResolvedEngineStamp } from "mailwoman/cli/kit/engine-stamp"
34
+ import { readSourceLocations, type SourceLocations } from "mailwoman/data/terms/source-locations"
35
+ import { type ArtifactFreshness, ManifestState, readFreshness } from "mailwoman/diagnostics/freshness"
36
+ import { $public } from "mailwoman/env"
37
+
38
+ import { openOGCGeocoder } from "#cli/geocoder"
39
+ import {
40
+ type AncestorsOf,
41
+ createOGCApp,
42
+ geocodeSearchHits,
43
+ OGC_COLLECTION_CATALOG,
44
+ OGC_DEFAULT_PORT,
45
+ OGC_DOC_INFO,
46
+ OGCCollectionID,
47
+ type OGCEngine,
48
+ itemsRefusal,
49
+ type OGCItemSource,
50
+ type OGCServedCollection,
51
+ placeItemSource,
52
+ regionLayerFiles,
53
+ type RegionLayerProbe,
54
+ servedCollections,
55
+ } from "#index"
56
+
57
+ const BINARY_NAME = "mailwoman-ogc"
58
+
59
+ /**
60
+ * The engine the `openapi` command documents.
61
+ *
62
+ * It lists every collection the surface can serve, so the printed definition
63
+ * declares each collection's `/search` parameters.
64
+ */
65
+ const DOCUMENTED_ENGINE: OGCEngine = {
66
+ collections: Object.keys(OGC_COLLECTION_CATALOG).map((id) => ({ id: id as OGCCollectionID, regions: null })),
67
+ search: async () => [],
68
+ }
69
+
70
+ /**
71
+ * The `places` collection's item source and the banner lines that state where it reads and on what terms.
72
+ */
73
+ interface PlaceItems {
74
+ source: OGCItemSource | null
75
+ bannerLines: string[]
76
+ }
77
+
78
+ /**
79
+ * The terms an opened artifact's manifest records, under the layer name the manifest gives it.
80
+ *
81
+ * An artifact without a readable manifest keeps the role the server opened it for and records no terms.
82
+ */
83
+ function layerTermsOf(artifact: ArtifactFreshness): LayerTerms {
84
+ return {
85
+ name: artifact.version?.split("@")[0] ?? artifact.name,
86
+ license: artifact.license,
87
+ attribution: artifact.attribution,
88
+ source: artifact.sources?.[0] ?? null,
89
+ }
90
+ }
91
+
92
+ /**
93
+ * The manifest terms of the region files each street-tier collection reads,
94
+ * and its regions without a readable manifest.
95
+ *
96
+ * A collection lists a layer's terms once, whatever the count of regions that
97
+ * record the same license and source.
98
+ * A file whose `layer_manifest` is absent or unreadable contributes no terms,
99
+ * and its region is counted as unread.
100
+ *
101
+ * @param sourceLocations Every owner's source table, under the provider's own table for each file.
102
+ */
103
+ async function regionLayerTerms(
104
+ probes: readonly RegionLayerProbe[],
105
+ sourceLocations: SourceLocations["table"]
106
+ ): Promise<Map<OGCCollectionID, Pick<OGCServedCollection, "layers" | "unreadRegions">>> {
107
+ const files = regionLayerFiles(probes)
108
+ const paths = [...new Set(files.map(({ path }) => path))]
109
+ const { artifacts } = await readFreshness(paths.map((path) => ({ name: path, path })))
110
+ const byPath = new Map(artifacts.map((artifact) => [artifact.path, artifact]))
111
+ const terms = new Map<OGCCollectionID, { layers: Map<string, LayerTerms>; unread: Set<string> }>()
112
+
113
+ for (const file of files) {
114
+ const entry = terms.get(file.collection) ?? { layers: new Map(), unread: new Set() }
115
+ const artifact = byPath.get(file.path)
116
+
117
+ terms.set(file.collection, entry)
118
+
119
+ if (artifact?.manifest !== ManifestState.Present) {
120
+ entry.unread.add(file.region)
121
+
122
+ continue
123
+ }
124
+
125
+ const layer = { ...layerTermsOf(artifact), sourceLocations: { ...sourceLocations, ...file.sourceLocations } }
126
+ const key = `${layer.license} ${layer.source?.split(":")[0]} ${layer.attribution}`
127
+
128
+ if (!entry.layers.has(key)) {
129
+ entry.layers.set(key, layer)
130
+ }
131
+ }
132
+
133
+ return new Map(
134
+ [...terms].map(([collection, { layers, unread }]) => [
135
+ collection,
136
+ { layers: [...layers.values()], ...(unread.size ? { unreadRegions: unread.size } : {}) },
137
+ ])
138
+ )
139
+ }
140
+
141
+ /**
142
+ * Open the admin gazetteer as the `places` collection's item source, when the operator asked for items.
143
+ *
144
+ * The items routes serve the gazetteer in pages, so the operator's `MAILWOMAN_REFUSE_OBLIGATIONS`
145
+ * applies to them as it applies to an OpenStreetMap layer: a refused class in the database's
146
+ * recorded license leaves `places` without items, and the banner states the refusal.
147
+ * A database without the `place_bbox` R*Tree can't answer a box page, so it serves no items either.
148
+ */
149
+ async function openPlaceItems(
150
+ serveItems: boolean,
151
+ admin: ArtifactFreshness | undefined,
152
+ ancestorsOf: AncestorsOf | undefined
153
+ ): Promise<PlaceItems> {
154
+ if (!serveItems) {
155
+ return {
156
+ source: null,
157
+ bannerLines: [" items: off, because bulk browsing is opt-in; pass --serve-items to serve them"],
158
+ }
159
+ }
160
+
161
+ if (!admin) {
162
+ return { source: null, bannerLines: [" places items: none, because no admin gazetteer database was found"] }
163
+ }
164
+
165
+ const adminDBPath = admin.path
166
+ const license = admin.license
167
+ const refusal = itemsRefusal(license, parseObligationRefusals([$public.MAILWOMAN_REFUSE_OBLIGATIONS ?? ""]))
168
+
169
+ if (refusal) {
170
+ return { source: null, bannerLines: [` places items: none, because ${refusal} in ${adminDBPath}`] }
171
+ }
172
+
173
+ try {
174
+ const browser = new WOFPlaceBrowser({ databasePath: adminDBPath })
175
+
176
+ return {
177
+ source: placeItemSource(browser, ancestorsOf),
178
+ bannerLines: [` places items: ${adminDBPath} (${license ?? "license unrecorded in layer_manifest"})`],
179
+ }
180
+ } catch (error) {
181
+ return {
182
+ source: null,
183
+ bannerLines: [
184
+ ` places items: none, because ${adminDBPath} can't be paged: ${error instanceof Error ? error.message : String(error)}`,
185
+ ],
186
+ }
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Whether the gazetteer holds postcode places, and the `postcodes` collection's item source.
192
+ */
193
+ interface PostcodeItems {
194
+ held: boolean
195
+ source: OGCItemSource | null
196
+ bannerLines: string[]
197
+ }
198
+
199
+ /**
200
+ * Check whether the gazetteer that `/search` uses holds postcode places.
201
+ *
202
+ * When the operator enables items, open a candidate gazetteer as the `postcodes` collection's item source.
203
+ *
204
+ * The candidate gazetteer holds the postcode places when the server resolves against it.
205
+ * Otherwise they come from the WOF databases it opened.
206
+ * Those databases serve no items.
207
+ *
208
+ * The obligation refusal applies as it does to `places`, from the candidate gazetteer's recorded license.
209
+ */
210
+ function openPostcodeItems(
211
+ serveItems: boolean,
212
+ gazetteer: GazetteerPaths,
213
+ candidate: ArtifactFreshness | undefined,
214
+ ancestorsOf: AncestorsOf | undefined
215
+ ): PostcodeItems {
216
+ if (!gazetteer.candidateDB) {
217
+ const held = gazetteer.wofPaths.some((path) => wofDatabaseHoldsPostcodes(path))
218
+
219
+ return {
220
+ held,
221
+ source: null,
222
+ bannerLines: serveItems && held ? [" postcodes items: none, because no candidate gazetteer was opened"] : [],
223
+ }
224
+ }
225
+
226
+ let browser: PostcodePlaceBrowser
227
+
228
+ try {
229
+ browser = new PostcodePlaceBrowser({ databasePath: gazetteer.candidateDB })
230
+ } catch (error) {
231
+ // The gazetteer records postcode places but can't page them, so `/search` still answers postcodes.
232
+ return {
233
+ held: true,
234
+ source: null,
235
+ bannerLines: serveItems
236
+ ? [
237
+ ` postcodes items: none, because ${gazetteer.candidateDB} can't be paged: ${error instanceof Error ? error.message : String(error)}`,
238
+ ]
239
+ : [],
240
+ }
241
+ }
242
+
243
+ const held = browser.holdsPostcodes()
244
+
245
+ if (!serveItems || !held) {
246
+ browser[Symbol.dispose]()
247
+
248
+ return { held, source: null, bannerLines: [] }
249
+ }
250
+
251
+ const license = candidate?.license ?? null
252
+ const refusal = itemsRefusal(license, parseObligationRefusals([$public.MAILWOMAN_REFUSE_OBLIGATIONS ?? ""]))
253
+
254
+ if (refusal) {
255
+ browser[Symbol.dispose]()
256
+
257
+ return {
258
+ held,
259
+ source: null,
260
+ bannerLines: [` postcodes items: none, because ${refusal} in ${gazetteer.candidateDB}`],
261
+ }
262
+ }
263
+
264
+ return {
265
+ held,
266
+ source: placeItemSource(browser, ancestorsOf),
267
+ bannerLines: [` postcodes items: ${gazetteer.candidateDB} (${license ?? "license unrecorded in layer_manifest"})`],
268
+ }
269
+ }
270
+
271
+ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
272
+ const { values } = parseArguments({
273
+ options: {
274
+ port: { type: "string", default: String(OGC_DEFAULT_PORT) },
275
+ host: { type: "string", default: "0.0.0.0" },
276
+ // The public base URL that link hrefs resolve against, for a deployment behind a reverse proxy.
277
+ "base-url": { type: "string" },
278
+ "candidate-db": { type: "string" },
279
+ // Permissive CORS is on by default because OGC API clients run in browsers too.
280
+ // `--no-cors` turns it off where a reverse proxy already sets the headers.
281
+ cors: { type: "boolean", default: true },
282
+ // Serve the `places` collection's items for bulk browsing.
283
+ // Off by default.
284
+ "serve-items": { type: "boolean", default: false },
285
+ },
286
+ allowNegative: true,
287
+ allowPositionals: true,
288
+ })
289
+
290
+ const port = readListenPort(values.port)
291
+ const host = values.host ?? "0.0.0.0"
292
+ const baseURL = values["base-url"]
293
+
294
+ const { gazetteer, session, geocode } = await openOGCGeocoder(values["candidate-db"] ?? null)
295
+ // The session owns the gazetteer backend and every provider read below, and closes them with itself.
296
+ const { lookup, regionDatabases, nationalSources, osm } = session.services
297
+ // The gazetteer's own ancestry reader labels each place match with its region and county.
298
+ const ancestorsOf = lookup.ancestors?.bind(lookup)
299
+ const countries = worldCountries()
300
+ const countryCodeOf = (code: string): string => code.toUpperCase()
301
+
302
+ const probes: RegionLayerProbe[] = [
303
+ // The region provider's keys are the ISO 3166-2 codes of the regions it has a file for.
304
+ { provider: regionDatabases, keys: regionDatabases.regions(), regionOf: countryCodeOf },
305
+ ...nationalSources.map((provider) => ({ provider, keys: countries, regionOf: countryCodeOf })),
306
+ ...(osm ? [{ provider: osm, keys: countries, regionOf: countryCodeOf }] : []),
307
+ ]
308
+
309
+ // The manifests of the gazetteer databases this process opened: the ones `/search` reads,
310
+ // and the admin gazetteer they derive from.
311
+ // The admin gazetteer also serves the `places` items.
312
+ const { artifacts } = await gazetteerFreshness(gazetteer)
313
+ const admin = artifacts.find((artifact) => artifact.path === gazetteer.adminDBPath)
314
+ const searchLayers = artifacts.filter((artifact) => artifact.name !== "reverse-admin").map(layerTermsOf)
315
+ const placeLayers = artifacts.map(layerTermsOf)
316
+ const placeItems = await openPlaceItems(values["serve-items"], admin, ancestorsOf)
317
+ const candidate = artifacts.find((artifact) => artifact.path === gazetteer.candidateDB)
318
+ const postcodeItems = openPostcodeItems(values["serve-items"], gazetteer, candidate, ancestorsOf)
319
+
320
+ const itemsOf = (id: OGCCollectionID): OGCItemSource | null => {
321
+ if (id === OGCCollectionID.Places) return placeItems.source
322
+
323
+ if (id === OGCCollectionID.Postcodes) return postcodeItems.source
324
+
325
+ return null
326
+ }
327
+
328
+ // The gazetteer collections read the manifests above, and the address and street
329
+ // collections read the manifests of the region files their providers report.
330
+ // Plus codes have no layer.
331
+ const regional = await regionLayerTerms(probes, (await readSourceLocations()).table)
332
+
333
+ const layersOf = (id: OGCCollectionID): Pick<OGCServedCollection, "layers" | "unreadRegions"> => {
334
+ switch (id) {
335
+ case OGCCollectionID.Places:
336
+ return { layers: placeLayers }
337
+ case OGCCollectionID.Postcodes:
338
+ return { layers: searchLayers }
339
+ case OGCCollectionID.PlusCodes:
340
+ return { layers: [] }
341
+ case OGCCollectionID.Addresses:
342
+ case OGCCollectionID.Streets:
343
+ return regional.get(id) ?? { layers: [] }
344
+ }
345
+ }
346
+
347
+ const engine: OGCEngine = {
348
+ collections: servedCollections(probes, { postcodes: postcodeItems.held }).map((collection) => {
349
+ const items = itemsOf(collection.id)
350
+
351
+ return { ...collection, ...layersOf(collection.id), ...(items ? { items } : {}) }
352
+ }),
353
+ async search(q) {
354
+ return geocodeSearchHits(await geocode(q), ancestorsOf)
355
+ },
356
+ }
357
+
358
+ const app = createOGCApp(engine, {
359
+ cors: values.cors,
360
+ engine: engineStamp.stamp,
361
+ baseURL,
362
+ serveItems: placeItems.source != null || postcodeItems.source != null,
363
+ })
364
+
365
+ await serveNode({
366
+ fetch: app.fetch,
367
+ port,
368
+ hostname: host,
369
+ onListen: (info) => {
370
+ console.error(`[@mailwoman/ogc] listening on http://${host}:${info.port}`)
371
+ console.error(` base URL: ${baseURL ?? "(the request's own origin)"}`)
372
+
373
+ for (const line of gazetteerBannerLines(gazetteer)) {
374
+ console.error(line)
375
+ }
376
+
377
+ for (const { id, regions, items } of engine.collections) {
378
+ console.error(
379
+ ` collection ${id}: ${regions ? regions.join(" ") : "worldwide"}${items ? ", serves items" : ""}`
380
+ )
381
+ }
382
+
383
+ for (const line of [...placeItems.bannerLines, ...postcodeItems.bannerLines]) {
384
+ console.error(line)
385
+ }
386
+
387
+ const itemRoutes = engine.collections
388
+ .filter(({ items }) => items)
389
+ .map(({ id }) => ` GET /collections/${id}/items GET /collections/${id}/items/{featureId}`)
390
+
391
+ console.error(corsBannerLine(values.cors))
392
+ console.error(
393
+ ` endpoints: GET / GET /conformance GET /api GET /collections GET /search GET /openapi.json${itemRoutes.join("")}`
394
+ )
395
+ },
396
+ })
397
+ }
398
+
399
+ await runDropInCLI({
400
+ binaryName: BINARY_NAME,
401
+ openapi: openAPICommand(BINARY_NAME, createOGCApp, OGC_DOC_INFO, DOCUMENTED_ENGINE),
402
+ serve,
403
+ usage: [
404
+ " serve [--port 8090] [--host 0.0.0.0] [--base-url <url>] [--candidate-db <path>] [--no-cors] [--serve-items]",
405
+ " openapi [--flavor 3.1|3.0] [--out <path>]",
406
+ ],
407
+ })
package/lib/app.ts ADDED
@@ -0,0 +1,107 @@
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
+ * Serve the items routes for the collections whose engine entry has an item source.
62
+ *
63
+ * Bulk browsing is opt-in, so the default leaves every collection without items.
64
+ *
65
+ * @defaultValue `false`
66
+ */
67
+ serveItems?: boolean
68
+ }
69
+
70
+ /**
71
+ * Builds the OGC API app around the given {@link OGCEngine}: the landing page at `/`,
72
+ * the conformance declaration at `/conformance`, the OpenAPI 3.0 definition at `/api`,
73
+ * the collections at `/collections`, forward geocoding at `/search`, and the OpenAPI
74
+ * 3.1 document at `/openapi.json` that every Mailwoman surface serves.
75
+ */
76
+ export function createOGCApp(engine: OGCEngine, options: OGCAppOptions = {}): OpenAPIHono {
77
+ const app = new OpenAPIHono({
78
+ defaultHook: (result, c) => {
79
+ if (result.success) return
80
+
81
+ const detail = result.error.issues
82
+ .map((issue) => (issue.path.length ? `${issue.path.join(".")}: ${issue.message}` : issue.message))
83
+ .join("; ")
84
+
85
+ return errorResponse(c, 400, "invalid query parameter", detail)
86
+ },
87
+ })
88
+
89
+ if (options.cors !== false) {
90
+ app.use(cors({ origin: "*", allowMethods: ["GET", "OPTIONS"], allowHeaders: ["*"], maxAge: 86_400 }))
91
+ }
92
+
93
+ if (options.engine) {
94
+ app.use(engineHeaders(options.engine))
95
+ }
96
+
97
+ app.onError((_error, c) => errorResponse(c, 500, "internal error"))
98
+
99
+ const docInfo: OpenAPIDocInfo = options.baseURL
100
+ ? { ...OGC_DOC_INFO, servers: [{ url: options.baseURL }] }
101
+ : OGC_DOC_INFO
102
+
103
+ registerOGCRoutes(app, engine, { baseURL: options.baseURL, docInfo, serveItems: options.serveItems === true })
104
+ attachOpenAPIDocs(app, docInfo)
105
+
106
+ return app
107
+ }
package/lib/bbox.ts ADDED
@@ -0,0 +1,69 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The `bbox` parameter `/search` and `/collections/{collectionId}/items` share.
6
+ */
7
+
8
+ import { isValidLatitude, isValidLongitude } from "@mailwoman/spatial/coordinate/bounds"
9
+
10
+ /**
11
+ * A `[minLon, minLat, maxLon, maxLat]` box in WGS 84 degrees.
12
+ */
13
+ export type OGCBBox = readonly [number, number, number, number]
14
+
15
+ /**
16
+ * The count of numbers in a two-dimensional `bbox`: two longitudes and two latitudes.
17
+ */
18
+ const BBOX_CORNERS = 4
19
+
20
+ /**
21
+ * The count of numbers in a three-dimensional `bbox`, which adds a minimum and maximum height.
22
+ */
23
+ const BBOX_CORNERS_WITH_HEIGHT = 6
24
+
25
+ /**
26
+ * Parse a `bbox` value.
27
+ *
28
+ * @param options.withHeight Admit the six-number form of OGC API Features Part 1,
29
+ * Requirement 23 D: `minLon,minLat,minHeight,maxLon,maxLat,maxHeight`.
30
+ * Every feature here is a point without a height, so the returned box keeps the
31
+ * longitudes and latitudes and drops the heights.
32
+ * @returns The box, or a message that states the problem with the value.
33
+ */
34
+ export function parseBBox(raw: string, options: { withHeight?: boolean } = {}): OGCBBox | string {
35
+ const parts = raw.split(",").map((part) => part.trim())
36
+ const numbers = parts.map((part) => (part === "" ? Number.NaN : Number(part)))
37
+ const sixNumbers = options.withHeight === true && numbers.length === BBOX_CORNERS_WITH_HEIGHT
38
+
39
+ if ((numbers.length !== BBOX_CORNERS && !sixNumbers) || !numbers.every(Number.isFinite)) {
40
+ return options.withHeight
41
+ ? "bbox: four or six comma-separated numbers are required, minLon,minLat,maxLon,maxLat or minLon,minLat,minHeight,maxLon,maxLat,maxHeight"
42
+ : "bbox: four comma-separated numbers are required, minLon,minLat,maxLon,maxLat"
43
+ }
44
+
45
+ if (sixNumbers && numbers[2]! > numbers[5]!) return "bbox: the minimum height exceeds the maximum"
46
+
47
+ const [minLon, minLat, maxLon, maxLat] = (
48
+ sixNumbers ? [numbers[0], numbers[1], numbers[3], numbers[4]] : numbers
49
+ ) as [number, number, number, number]
50
+
51
+ if (!isValidLongitude(minLon) || !isValidLongitude(maxLon)) return "bbox: longitudes must lie in [-180, 180]"
52
+
53
+ if (!isValidLatitude(minLat) || !isValidLatitude(maxLat)) return "bbox: latitudes must lie in [-90, 90]"
54
+
55
+ if (minLat > maxLat) return "bbox: the minimum latitude exceeds the maximum"
56
+
57
+ return [minLon, minLat, maxLon, maxLat]
58
+ }
59
+
60
+ /**
61
+ * Whether a point lies inside the box, edges included.
62
+ *
63
+ * A box whose minimum longitude exceeds its maximum crosses the antimeridian, as OGC API boxes may.
64
+ */
65
+ export function searchBoxContains([minLon, minLat, maxLon, maxLat]: OGCBBox, lon: number, lat: number): boolean {
66
+ if (lat < minLat || lat > maxLat) return false
67
+
68
+ return minLon <= maxLon ? lon >= minLon && lon <= maxLon : lon >= minLon || lon <= maxLon
69
+ }