@mailwoman/ogc 11.2.0 → 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 (73) hide show
  1. package/README.md +167 -28
  2. package/cli/geocoder.ts +50 -0
  3. package/cli/main.ts +303 -49
  4. package/lib/app.ts +9 -1
  5. package/lib/bbox.ts +69 -0
  6. package/lib/collections.ts +63 -9
  7. package/lib/engine.ts +72 -0
  8. package/lib/html.ts +64 -2
  9. package/lib/index.ts +4 -0
  10. package/lib/items.ts +169 -0
  11. package/lib/projection.ts +28 -8
  12. package/lib/provenance.ts +86 -0
  13. package/lib/refusal.ts +34 -0
  14. package/lib/routes.ts +326 -61
  15. package/lib/schema.ts +164 -3
  16. package/out/app.d.ts +8 -0
  17. package/out/app.d.ts.map +1 -1
  18. package/out/app.js +1 -1
  19. package/out/app.js.map +1 -1
  20. package/out/bbox.d.ts +23 -0
  21. package/out/bbox.d.ts.map +1 -0
  22. package/out/bbox.js +54 -0
  23. package/out/bbox.js.map +1 -0
  24. package/out/cli/geocoder.d.ts +24 -0
  25. package/out/cli/geocoder.d.ts.map +1 -0
  26. package/out/cli/geocoder.js +28 -0
  27. package/out/cli/geocoder.js.map +1 -0
  28. package/out/cli/main.js +225 -46
  29. package/out/cli/main.js.map +1 -1
  30. package/out/collections.d.ts +31 -4
  31. package/out/collections.d.ts.map +1 -1
  32. package/out/collections.js +32 -3
  33. package/out/collections.js.map +1 -1
  34. package/out/engine.d.ts +68 -0
  35. package/out/engine.d.ts.map +1 -1
  36. package/out/html.d.ts +11 -1
  37. package/out/html.d.ts.map +1 -1
  38. package/out/html.js +49 -2
  39. package/out/html.js.map +1 -1
  40. package/out/index.d.ts +4 -0
  41. package/out/index.d.ts.map +1 -1
  42. package/out/index.js +4 -0
  43. package/out/index.js.map +1 -1
  44. package/out/items.d.ts +38 -0
  45. package/out/items.d.ts.map +1 -0
  46. package/out/items.js +136 -0
  47. package/out/items.js.map +1 -0
  48. package/out/projection.d.ts +15 -1
  49. package/out/projection.d.ts.map +1 -1
  50. package/out/projection.js +21 -8
  51. package/out/projection.js.map +1 -1
  52. package/out/provenance.d.ts +41 -0
  53. package/out/provenance.d.ts.map +1 -0
  54. package/out/provenance.js +60 -0
  55. package/out/provenance.js.map +1 -0
  56. package/out/refusal.d.ts +18 -0
  57. package/out/refusal.d.ts.map +1 -0
  58. package/out/refusal.js +30 -0
  59. package/out/refusal.js.map +1 -0
  60. package/out/routes.d.ts +24 -22
  61. package/out/routes.d.ts.map +1 -1
  62. package/out/routes.js +246 -51
  63. package/out/routes.js.map +1 -1
  64. package/out/schema.d.ts +157 -2
  65. package/out/schema.d.ts.map +1 -1
  66. package/out/schema.js +140 -3
  67. package/out/schema.js.map +1 -1
  68. package/out/tools/ets.run.d.ts +2 -0
  69. package/out/tools/ets.run.d.ts.map +1 -0
  70. package/out/tools/ets.run.js +187 -0
  71. package/out/tools/ets.run.js.map +1 -0
  72. package/package.json +32 -10
  73. package/tools/ets.run.ts +258 -0
package/cli/main.ts CHANGED
@@ -13,31 +13,43 @@
13
13
 
14
14
  import { serveNode } from "@mailwoman/api-kit"
15
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"
16
+ import type { LayerTerms } from "@mailwoman/core/layers/provenance"
18
17
  import { parseArguments } from "@mailwoman/core/scripting/arguments"
19
- import { createWOFResolver } from "@mailwoman/resolver"
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"
20
24
  import {
21
25
  corsBannerLine,
26
+ type GazetteerPaths,
22
27
  gazetteerBannerLines,
23
- loadClassifierOrExit,
28
+ gazetteerFreshness,
24
29
  openAPICommand,
25
- resolveGazetteerOrExit,
30
+ readListenPort,
26
31
  runDropInCLI,
27
32
  } from "mailwoman/cli/kit/dropin"
28
33
  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"
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"
32
37
 
38
+ import { openOGCGeocoder } from "#cli/geocoder"
33
39
  import {
40
+ type AncestorsOf,
34
41
  createOGCApp,
35
42
  geocodeSearchHits,
36
43
  OGC_COLLECTION_CATALOG,
37
44
  OGC_DEFAULT_PORT,
38
45
  OGC_DOC_INFO,
39
- type OGCCollectionID,
46
+ OGCCollectionID,
40
47
  type OGCEngine,
48
+ itemsRefusal,
49
+ type OGCItemSource,
50
+ type OGCServedCollection,
51
+ placeItemSource,
52
+ regionLayerFiles,
41
53
  type RegionLayerProbe,
42
54
  servedCollections,
43
55
  } from "#index"
@@ -55,6 +67,207 @@ const DOCUMENTED_ENGINE: OGCEngine = {
55
67
  search: async () => [],
56
68
  }
57
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
+
58
271
  async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
59
272
  const { values } = parseArguments({
60
273
  options: {
@@ -66,78 +279,119 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
66
279
  // Permissive CORS is on by default because OGC API clients run in browsers too.
67
280
  // `--no-cors` turns it off where a reverse proxy already sets the headers.
68
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 },
69
285
  },
70
286
  allowNegative: true,
71
287
  allowPositionals: true,
72
288
  })
73
289
 
74
- const port = Number(values.port) || OGC_DEFAULT_PORT
290
+ const port = readListenPort(values.port)
75
291
  const host = values.host ?? "0.0.0.0"
76
292
  const baseURL = values["base-url"]
77
293
 
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)
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
85
297
  // 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())
298
+ const ancestorsOf = lookup.ancestors?.bind(lookup)
91
299
  const countries = worldCountries()
300
+ const countryCodeOf = (code: string): string => code.toUpperCase()
92
301
 
93
302
  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
- : []),
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 }] : []),
103
307
  ]
104
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
+
105
347
  const engine: OGCEngine = {
106
- collections: servedCollections(probes),
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
+ }),
107
353
  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)
354
+ return geocodeSearchHits(await geocode(q), ancestorsOf)
118
355
  },
119
356
  }
120
357
 
121
- const app = createOGCApp(engine, { cors: values.cors, engine: engineStamp.stamp, baseURL })
358
+ const app = createOGCApp(engine, {
359
+ cors: values.cors,
360
+ engine: engineStamp.stamp,
361
+ baseURL,
362
+ serveItems: placeItems.source != null || postcodeItems.source != null,
363
+ })
122
364
 
123
365
  await serveNode({
124
366
  fetch: app.fetch,
125
367
  port,
126
368
  hostname: host,
127
- onListen: () => {
128
- console.error(`[@mailwoman/ogc] listening on http://${host}:${port}`)
369
+ onListen: (info) => {
370
+ console.error(`[@mailwoman/ogc] listening on http://${host}:${info.port}`)
129
371
  console.error(` base URL: ${baseURL ?? "(the request's own origin)"}`)
130
372
 
131
373
  for (const line of gazetteerBannerLines(gazetteer)) {
132
374
  console.error(line)
133
375
  }
134
376
 
135
- for (const { id, regions } of engine.collections) {
136
- console.error(` collection ${id}: ${regions ? regions.join(" ") : "worldwide"}`)
377
+ for (const { id, regions, items } of engine.collections) {
378
+ console.error(
379
+ ` collection ${id}: ${regions ? regions.join(" ") : "worldwide"}${items ? ", serves items" : ""}`
380
+ )
137
381
  }
138
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
+
139
391
  console.error(corsBannerLine(values.cors))
140
- console.error(` endpoints: GET / GET /conformance GET /api GET /collections GET /search GET /openapi.json`)
392
+ console.error(
393
+ ` endpoints: GET / GET /conformance GET /api GET /collections GET /search GET /openapi.json${itemRoutes.join("")}`
394
+ )
141
395
  },
142
396
  })
143
397
  }
@@ -147,7 +401,7 @@ await runDropInCLI({
147
401
  openapi: openAPICommand(BINARY_NAME, createOGCApp, OGC_DOC_INFO, DOCUMENTED_ENGINE),
148
402
  serve,
149
403
  usage: [
150
- " serve [--port 8090] [--host 0.0.0.0] [--base-url <url>] [--candidate-db <path>] [--no-cors]",
404
+ " serve [--port 8090] [--host 0.0.0.0] [--base-url <url>] [--candidate-db <path>] [--no-cors] [--serve-items]",
151
405
  " openapi [--flavor 3.1|3.0] [--out <path>]",
152
406
  ],
153
407
  })
package/lib/app.ts CHANGED
@@ -57,6 +57,14 @@ export interface OGCAppOptions extends CompatibilityAppOptions {
57
57
  * @defaultValue The request's own origin.
58
58
  */
59
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
60
68
  }
61
69
 
62
70
  /**
@@ -92,7 +100,7 @@ export function createOGCApp(engine: OGCEngine, options: OGCAppOptions = {}): Op
92
100
  ? { ...OGC_DOC_INFO, servers: [{ url: options.baseURL }] }
93
101
  : OGC_DOC_INFO
94
102
 
95
- registerOGCRoutes(app, engine, { baseURL: options.baseURL, docInfo })
103
+ registerOGCRoutes(app, engine, { baseURL: options.baseURL, docInfo, serveItems: options.serveItems === true })
96
104
  attachOpenAPIDocs(app, docInfo)
97
105
 
98
106
  return app
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
+ }
@@ -12,7 +12,7 @@
12
12
  */
13
13
 
14
14
  import type { GeocodeResult } from "@mailwoman/core/geocode"
15
- import type { RegionDatabaseProvider } from "@mailwoman/core/resolver"
15
+ import type { RegionDatabaseProvider, RegionLayerDatabase } from "@mailwoman/core/resolver"
16
16
 
17
17
  import type { OGCServedCollection } from "#engine"
18
18
 
@@ -100,7 +100,7 @@ export function collectionOfPlacetype(placetype: string): OGCCollectionID {
100
100
  * One region-keyed provider of street-tier layers, and the keys to ask it for.
101
101
  */
102
102
  export interface RegionLayerProbe {
103
- provider: Pick<RegionDatabaseProvider, "for">
103
+ provider: Pick<RegionDatabaseProvider, "for" | "layerDatabases">
104
104
  keys: Iterable<string>
105
105
  /**
106
106
  * The region code a key names in a collection description, such as `US-TX` for the key `tx`.
@@ -108,11 +108,62 @@ export interface RegionLayerProbe {
108
108
  regionOf: (key: string) => string
109
109
  }
110
110
 
111
+ /**
112
+ * One database file a region's layer reads, and the collection it serves.
113
+ */
114
+ export interface RegionLayerFile extends RegionLayerDatabase {
115
+ collection: OGCCollectionID
116
+ /**
117
+ * The region code, such as `US-TX`.
118
+ */
119
+ region: string
120
+ }
121
+
122
+ /**
123
+ * The collection each street-tier database serves.
124
+ */
125
+ const COLLECTION_OF_TIER: Readonly<Record<RegionLayerDatabase["tier"], OGCCollectionID>> = {
126
+ addressPoints: OGCCollectionID.Addresses,
127
+ interpolation: OGCCollectionID.Addresses,
128
+ streetCentroids: OGCCollectionID.Streets,
129
+ }
130
+
131
+ /**
132
+ * The database files every probed region reads, from providers that report them.
133
+ *
134
+ * A provider without `layerDatabases` reports none, and its regions count as unread.
135
+ */
136
+ export function regionLayerFiles(probes: readonly RegionLayerProbe[]): RegionLayerFile[] {
137
+ const files: RegionLayerFile[] = []
138
+
139
+ for (const { provider, keys, regionOf } of probes) {
140
+ for (const key of keys) {
141
+ for (const database of provider.layerDatabases?.(key) ?? []) {
142
+ files.push({ ...database, collection: COLLECTION_OF_TIER[database.tier], region: regionOf(key) })
143
+ }
144
+ }
145
+ }
146
+
147
+ return files
148
+ }
149
+
150
+ /**
151
+ * What the opened gazetteer holds, for the collections it backs.
152
+ */
153
+ export interface GazetteerHoldings {
154
+ /**
155
+ * Whether the gazetteer holds at least one postcode place.
156
+ */
157
+ postcodes: boolean
158
+ }
159
+
111
160
  /**
112
161
  * The collections an engine serves, from the layers its providers opened.
113
162
  *
114
163
  * The gazetteer is always open, because the engine refuses to start without one,
115
- * so places, postcodes and plus codes are always served.
164
+ * so places and plus codes are always served.
165
+ * Postcodes are served when the gazetteer holds postcode places.
166
+ *
116
167
  * Addresses and streets are served when some region has an address-point, interpolation
117
168
  * or street-centroid layer, and their descriptions name those regions.
118
169
  *
@@ -121,7 +172,10 @@ export interface RegionLayerProbe {
121
172
  * A provider opens a region's layers when asked for the region.
122
173
  * A query for that region would open them as well.
123
174
  */
124
- export function servedCollections(probes: readonly RegionLayerProbe[]): OGCServedCollection[] {
175
+ export function servedCollections(
176
+ probes: readonly RegionLayerProbe[],
177
+ gazetteer: GazetteerHoldings
178
+ ): OGCServedCollection[] {
125
179
  const addressRegions = new Set<string>()
126
180
  const streetRegions = new Set<string>()
127
181
 
@@ -149,11 +203,11 @@ export function servedCollections(probes: readonly RegionLayerProbe[]): OGCServe
149
203
  served.push({ id: OGCCollectionID.Streets, regions: [...streetRegions].toSorted() })
150
204
  }
151
205
 
152
- served.push(
153
- { id: OGCCollectionID.Postcodes, regions: null },
154
- { id: OGCCollectionID.Places, regions: null },
155
- { id: OGCCollectionID.PlusCodes, regions: null }
156
- )
206
+ if (gazetteer.postcodes) {
207
+ served.push({ id: OGCCollectionID.Postcodes, regions: null })
208
+ }
209
+
210
+ served.push({ id: OGCCollectionID.Places, regions: null }, { id: OGCCollectionID.PlusCodes, regions: null })
157
211
 
158
212
  return served
159
213
  }