@mailwoman/zoning 9.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 (82) hide show
  1. package/README.md +315 -0
  2. package/lib/index.ts +616 -0
  3. package/lib/ring-roles.ts +233 -0
  4. package/lib/rings.ts +34 -0
  5. package/lib/schema.ts +449 -0
  6. package/lib/scripts/ingest-chunk.ts +41 -0
  7. package/lib/sdk/build-zoning.ts +790 -0
  8. package/lib/sdk/cells.ts +276 -0
  9. package/lib/sdk/client.ts +335 -0
  10. package/lib/sdk/download.ts +78 -0
  11. package/lib/sdk/index.ts +15 -0
  12. package/lib/sdk/ingest-chunk.ts +360 -0
  13. package/lib/sdk/ingest.ts +402 -0
  14. package/lib/sdk/measure-resolutions.ts +100 -0
  15. package/lib/sdk/verify.ts +350 -0
  16. package/lib/test-kit.ts +207 -0
  17. package/lib/vocabulary.ts +342 -0
  18. package/out/index.d.ts +257 -0
  19. package/out/index.d.ts.map +1 -0
  20. package/out/index.js +325 -0
  21. package/out/index.js.map +1 -0
  22. package/out/ring-roles.d.ts +88 -0
  23. package/out/ring-roles.d.ts.map +1 -0
  24. package/out/ring-roles.js +151 -0
  25. package/out/ring-roles.js.map +1 -0
  26. package/out/rings.d.ts +22 -0
  27. package/out/rings.d.ts.map +1 -0
  28. package/out/rings.js +22 -0
  29. package/out/rings.js.map +1 -0
  30. package/out/schema.d.ts +325 -0
  31. package/out/schema.d.ts.map +1 -0
  32. package/out/schema.js +186 -0
  33. package/out/schema.js.map +1 -0
  34. package/out/scripts/ingest-chunk.d.ts +11 -0
  35. package/out/scripts/ingest-chunk.d.ts.map +1 -0
  36. package/out/scripts/ingest-chunk.js +36 -0
  37. package/out/scripts/ingest-chunk.js.map +1 -0
  38. package/out/sdk/build-zoning.d.ts +283 -0
  39. package/out/sdk/build-zoning.d.ts.map +1 -0
  40. package/out/sdk/build-zoning.js +462 -0
  41. package/out/sdk/build-zoning.js.map +1 -0
  42. package/out/sdk/cells.d.ts +137 -0
  43. package/out/sdk/cells.d.ts.map +1 -0
  44. package/out/sdk/cells.js +176 -0
  45. package/out/sdk/cells.js.map +1 -0
  46. package/out/sdk/client.d.ts +151 -0
  47. package/out/sdk/client.d.ts.map +1 -0
  48. package/out/sdk/client.js +239 -0
  49. package/out/sdk/client.js.map +1 -0
  50. package/out/sdk/download.d.ts +51 -0
  51. package/out/sdk/download.d.ts.map +1 -0
  52. package/out/sdk/download.js +57 -0
  53. package/out/sdk/download.js.map +1 -0
  54. package/out/sdk/index.d.ts +15 -0
  55. package/out/sdk/index.d.ts.map +1 -0
  56. package/out/sdk/index.js +15 -0
  57. package/out/sdk/index.js.map +1 -0
  58. package/out/sdk/ingest-chunk.d.ts +130 -0
  59. package/out/sdk/ingest-chunk.d.ts.map +1 -0
  60. package/out/sdk/ingest-chunk.js +206 -0
  61. package/out/sdk/ingest-chunk.js.map +1 -0
  62. package/out/sdk/ingest.d.ts +191 -0
  63. package/out/sdk/ingest.d.ts.map +1 -0
  64. package/out/sdk/ingest.js +238 -0
  65. package/out/sdk/ingest.js.map +1 -0
  66. package/out/sdk/measure-resolutions.d.ts +51 -0
  67. package/out/sdk/measure-resolutions.d.ts.map +1 -0
  68. package/out/sdk/measure-resolutions.js +64 -0
  69. package/out/sdk/measure-resolutions.js.map +1 -0
  70. package/out/sdk/verify.d.ts +176 -0
  71. package/out/sdk/verify.d.ts.map +1 -0
  72. package/out/sdk/verify.js +202 -0
  73. package/out/sdk/verify.js.map +1 -0
  74. package/out/test-kit.d.ts +97 -0
  75. package/out/test-kit.d.ts.map +1 -0
  76. package/out/test-kit.js +180 -0
  77. package/out/test-kit.js.map +1 -0
  78. package/out/vocabulary.d.ts +221 -0
  79. package/out/vocabulary.d.ts.map +1 -0
  80. package/out/vocabulary.js +299 -0
  81. package/out/vocabulary.js.map +1 -0
  82. package/package.json +245 -0
package/lib/index.ts ADDED
@@ -0,0 +1,616 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The `zoning-ireland.db` reader — what a local authority's adopted plan assigns at a coordinate, in that
7
+ * authority's own vocabulary, and on what basis.
8
+ *
9
+ * TWO READINGS, AND THE ONE THAT IS MISSING IS THE POINT.
10
+ *
11
+ * 1. `designated` — an adopted plan places the location inside a zoning polygon, and the polygon is the
12
+ * answer: the authority's own code, its own description, the plan it belongs to and that plan's stated
13
+ * window, with the Department's national generic type BESIDE the local code rather than instead of it.
14
+ * 2. `unknown` — no polygon contains the point. THAT IS NOT AN ABSENCE READING, and this layer has none.
15
+ *
16
+ * THERE IS NO `designated_absence` HERE, AND ZONING IS THE HARDEST CASE OF THE RULE. For flood zones the
17
+ * Environment Agency states England-wide coverage and the Planning Practice Guidance defines Zone 1 as the
18
+ * land outside Zones 2 and 3, so an empty answer inside England IS a designation. No such definition exists
19
+ * anywhere for zoning: a location with no zoning polygon is outside any adopted plan area, or inside one on
20
+ * land the plan does not zone, or in a jurisdiction that has never adopted zoning, or in a jurisdiction
21
+ * whose records nobody has published — and no product distinguishes them. The source itself proves the
22
+ * asymmetry: it states `UNZ - Unzoned` as a POSITIVE value on 4 of 85,330 rows, so where the authority
23
+ * means unzoned it says so, and every other absence is a row that is not there.
24
+ *
25
+ * SO THE CONSTRUCTOR REFUSES A COVERAGE ROW THAT WOULD SUPPORT AN EXCLUSION. Every row must read
26
+ * `source_present`; `supportsExclusion` must be false for all of them. That is not a convention this reader
27
+ * follows — it is a condition it checks at open time, so the day someone writes a stronger basis without
28
+ * settling the footprint question, the layer refuses to open rather than answering confidently.
29
+ *
30
+ * NEITHER READING IS A STATEMENT ABOUT WHAT MAY BE BUILT. The layer reports what a plan assigns at a
31
+ * location, which is a fact about the plan. The Department states that its data are "not published here as
32
+ * legal definitions of the current actuality with regard to Local Authority zoning or their geographic
33
+ * extents" and that "Original data should be sourced directly from the relevant Local Authority" — and
34
+ * `limits` carries the authority's own exclusions on every answer.
35
+ *
36
+ * THE PLAN IS PART OF THE CLAIM, NEVER A PARAMETER OF IT. A zone exists inside a named Development Plan or
37
+ * Local Area Plan with a stated validity window; a reading that dropped the plan would answer a question no
38
+ * authority asked. And `currentPlan = 1` means "not superseded", not "in force today": 2,363 of 85,330 rows
39
+ * carry a `validTo` already in the past, so the window travels on every reading and the comparison against a
40
+ * date is the caller's, made against a clock this reader does not own.
41
+ *
42
+ * THE PROBE IS STRUCTURE FIRST, GEOMETRY LAST. `cellToParent` up the compacted whole-cell chain answers an
43
+ * interior point with primary-key probes alone; only a cell a boundary crosses reaches the ray cast, and
44
+ * then only against the polygons `zoning_cell` already named for that cell.
45
+ *
46
+ * THE READER IS SYNCHRONOUS AND USES RAW PREPARED STATEMENTS, for the same reason the sibling layer readers
47
+ * are: it answers one point per geocode with a bounded number of primary-key probes plus a bounded geometry
48
+ * read, and the ray cast it wraps is synchronous anyway. The DDL that created these tables IS Kysely — see
49
+ * `schema.ts`.
50
+ */
51
+
52
+ import {
53
+ assertCoverageLicensesNoExclusion,
54
+ assertNoCellsFinerThanIndex,
55
+ CoverageBasis,
56
+ parseManifestRows,
57
+ type CoverageCell,
58
+ type LayerManifest,
59
+ } from "@mailwoman/core/layers"
60
+ import {
61
+ ancestorChainCells,
62
+ bboxContains,
63
+ recoverShortCellResolution,
64
+ shortCellToInt,
65
+ type H3Cell,
66
+ } from "@mailwoman/spatial"
67
+ import { readCoverageAt } from "@mailwoman/spatial/h3/coverage"
68
+ import { DatabaseClient } from "@mailwoman/sqlite/client"
69
+ import { latLngToCell } from "h3-js"
70
+
71
+ import { pointInEncodedRings } from "#rings"
72
+ import type { ZoningDatabase } from "#schema"
73
+ import { ZoningCellContainment } from "#schema"
74
+ import {
75
+ GZT_COVERAGE_LIMIT,
76
+ GZT_CROSSWALK_SCHEME,
77
+ GZT_LAYER_NAME,
78
+ GZT_PRODUCT_LIMITS,
79
+ GZT_UNZONED_LOCAL_CODE,
80
+ } from "#vocabulary"
81
+
82
+ export { GZT_LAYER_NAME, ProvenanceGrade } from "#vocabulary"
83
+
84
+ /**
85
+ * What the layer can say about a coordinate.
86
+ */
87
+ export const ZoningReadingKind = {
88
+ /**
89
+ * An adopted plan places this location inside a zoning polygon.
90
+ */
91
+ Designated: "designated",
92
+ /**
93
+ * No zoning polygon contains the point. NEVER an absence reading — see this file's header.
94
+ */
95
+ Unknown: "unknown",
96
+ } as const
97
+
98
+ export type ZoningReadingKind = (typeof ZoningReadingKind)[keyof typeof ZoningReadingKind]
99
+
100
+ /**
101
+ * How containment was established.
102
+ */
103
+ export const ZoningContainmentPath = {
104
+ /**
105
+ * The cell lies wholly inside the zone; no geometry was read.
106
+ */
107
+ WholeCell: "whole_cell",
108
+ /**
109
+ * The cell is crossed by a boundary; the point was ray-cast against the polygons named for that cell.
110
+ */
111
+ RayCast: "ray_cast",
112
+ /**
113
+ * No zone reaches this cell at all.
114
+ */
115
+ NoZoneCell: "no_zone_cell",
116
+ } as const
117
+
118
+ export type ZoningContainmentPath = (typeof ZoningContainmentPath)[keyof typeof ZoningContainmentPath]
119
+
120
+ /**
121
+ * The authority that adopted the plan.
122
+ */
123
+ export interface ZoningJurisdiction {
124
+ jurisdictionID: string
125
+ name: string
126
+ /**
127
+ * The publisher's own code, verbatim — `Fl` for Fingal, against `CL`, `CO`, `DU` for the rest.
128
+ */
129
+ sourceCode: string
130
+ country: string
131
+ }
132
+
133
+ /**
134
+ * The plan a zone belongs to, with its own stated window.
135
+ */
136
+ export interface ZoningPlan {
137
+ planID: string
138
+ name: string
139
+ /**
140
+ * `DP` Development Plan, `LAP` Local Area Plan, `SDZ` Strategic Development Zone.
141
+ */
142
+ level: string
143
+ validFrom: string | null
144
+ validTo: string | null
145
+ /**
146
+ * The publisher's `CURRENT_PLAN` flag, carried as published. `1` means NOT SUPERSEDED — not "in force today".
147
+ */
148
+ currentPlan: number
149
+ }
150
+
151
+ /**
152
+ * One zoning polygon the point falls inside, as the authority publishes it.
153
+ */
154
+ export interface ZoningDesignation {
155
+ areaID: string
156
+ /**
157
+ * The authority's own zone code, verbatim.
158
+ */
159
+ localCode: string
160
+ localDescription: string | null
161
+ localCodeURL: string | null
162
+ /**
163
+ * The publishing authority's OWN crosswalk into a shared scheme, where it publishes one. Beside the local code, never
164
+ * instead of it: 52 of 795 (authority, local code) pairs take more than one generic type, so this cannot be
165
+ * reconstructed from `localCode` and is a per-polygon fact the Department authored.
166
+ */
167
+ crosswalk?: {
168
+ scheme: string
169
+ code: string
170
+ description: string | null
171
+ /**
172
+ * A coarser code from the same authority, carried as published.
173
+ */
174
+ rollup: string | null
175
+ /**
176
+ * The publisher's own label for `code`, from its declared domain — absent for a code the publisher uses and never
177
+ * declared.
178
+ */
179
+ label?: string
180
+ /**
181
+ * `false` where the publisher uses this code without declaring it in its own domain.
182
+ */
183
+ declared: boolean
184
+ }
185
+ /**
186
+ * One of {@link ProvenanceGrade}. Every row of THIS artifact is `authoritative`; the column exists because a query
187
+ * answered from an `inferred` row may never be presented as the authority's designation.
188
+ */
189
+ provenanceGrade: string
190
+ jurisdiction: ZoningJurisdiction
191
+ plan: ZoningPlan
192
+ /**
193
+ * The authority states unzoned land POSITIVELY on a handful of rows. `true` here is the authority saying so; an
194
+ * ABSENT designation says nothing at all, which is the distinction this layer exists to keep.
195
+ */
196
+ unzoned: boolean
197
+ containment: ZoningContainmentPath
198
+ }
199
+
200
+ /**
201
+ * One reading, carrying everything a caller needs to re-derive it rather than take it.
202
+ */
203
+ export interface ZoningReading {
204
+ kind: ZoningReadingKind
205
+ /**
206
+ * Every polygon containing the point, ordered by `area_id`. Usually one; several where a Local Area Plan overlays a
207
+ * Development Plan over the same ground, which the source publishes as two rows.
208
+ */
209
+ designations: ZoningDesignation[]
210
+ containment: ZoningContainmentPath
211
+ /**
212
+ * The coverage row for the location, when the product has data in that cell. Its basis is always `source_present`, so
213
+ * it licenses PRESENCE and nothing else — an absent coverage row and a present one are both compatible with "no
214
+ * zoning polygon here", and neither says the location is unrestricted.
215
+ */
216
+ coverage?: CoverageCell & { h3CellIndex: string; resolution: number }
217
+ /**
218
+ * The index cell probed, for a receipt.
219
+ */
220
+ indexCellIndex: string
221
+ /**
222
+ * What the product does not state, in the authority's own words.
223
+ */
224
+ limits: ReadonlyArray<string>
225
+ /**
226
+ * Why this layer's coverage licenses no negative claim, in one sentence.
227
+ */
228
+ coverageLimit: string
229
+ }
230
+
231
+ /**
232
+ * The layer's identity, read once at open time.
233
+ */
234
+ export interface ZoningLayerIdentity {
235
+ manifest: LayerManifest
236
+ indexResolution: number
237
+ coverageResolution: number
238
+ /**
239
+ * Every resolution `zoning_cell` stores a row at, coarsest first — the ancestor chain a probe walks.
240
+ *
241
+ * Several, and necessarily so: each feature's whole tier is compacted parent-ward, and a polygon too large for h3's
242
+ * allocator at the index resolution was indexed coarser. A reader that probed one resolution would read every row at
243
+ * the others as an absence.
244
+ */
245
+ cellResolutions: number[]
246
+ /**
247
+ * The jurisdictions the layer holds, by id.
248
+ */
249
+ jurisdictions: ReadonlyMap<string, ZoningJurisdiction>
250
+ /**
251
+ * The crosswalk scheme this layer's rows carry, or `undefined` where the publisher ships none.
252
+ */
253
+ crosswalkScheme?: string
254
+ /**
255
+ * The authority's footprint statements. EMPTY in this edition, which is what makes `source_present` the only basis
256
+ * the coverage may carry — see `schema.ts`.
257
+ */
258
+ mappedExtents: Array<{ extentID: string; source: string; statement: string; statementURL: string }>
259
+ /**
260
+ * The coverage basis every row carries. Always `source_present` while `mappedExtents` is empty; checked at open time
261
+ * rather than assumed.
262
+ */
263
+ coverageBasis: CoverageBasis
264
+ databasePath: string
265
+ }
266
+
267
+ export interface ZoningLookupOptions {
268
+ databasePath: string
269
+ }
270
+
271
+ interface AreaRow {
272
+ area_id: string
273
+ jurisdiction_id: string
274
+ plan_id: string
275
+ local_code: string
276
+ local_description: string | null
277
+ local_code_url: string | null
278
+ crosswalk_code: string | null
279
+ crosswalk_scheme: string | null
280
+ crosswalk_description: string | null
281
+ crosswalk_rollup: string | null
282
+ provenance_grade: string
283
+ min_lat: number
284
+ min_lon: number
285
+ max_lat: number
286
+ max_lon: number
287
+ }
288
+
289
+ interface PlanRow {
290
+ plan_id: string
291
+ plan_name: string
292
+ plan_level: string
293
+ valid_from: string | null
294
+ valid_to: string | null
295
+ current_plan: number
296
+ }
297
+
298
+ /**
299
+ * Read a sealed `zoning-ireland.db`.
300
+ *
301
+ * Everything that would make the reader answer a well-formed wrong thing is refused at CONSTRUCTION rather than at
302
+ * query time: a manifest naming a different layer, a coverage table with no rows, a coverage row whose basis would
303
+ * support an exclusion, an empty jurisdiction table. Each of those would otherwise present as a reader that quietly
304
+ * always answers `unknown` — or, in the exclusion case, as a reader that confidently reports unzoned-and-unmapped land
305
+ * as free of restriction.
306
+ */
307
+ export class ZoningLookup implements Disposable {
308
+ readonly identity: ZoningLayerIdentity
309
+
310
+ readonly #database: DatabaseClient<ZoningDatabase>
311
+ readonly #selectCell: ReturnType<DatabaseClient["prepare"]>
312
+ readonly #selectArea: ReturnType<DatabaseClient["prepare"]>
313
+ readonly #selectAreaRings: ReturnType<DatabaseClient["prepare"]>
314
+ readonly #selectPlan: ReturnType<DatabaseClient["prepare"]>
315
+ readonly #selectCoverage: ReturnType<DatabaseClient["prepare"]>
316
+ readonly #crosswalkTerms: ReadonlyMap<string, { label: string; declared: boolean }>
317
+
318
+ constructor(options: ZoningLookupOptions) {
319
+ this.#database = new DatabaseClient<ZoningDatabase>(options.databasePath, { readOnly: true })
320
+
321
+ try {
322
+ this.identity = readIdentity(this.#database, options.databasePath)
323
+ this.#crosswalkTerms = readCrosswalkTerms(this.#database)
324
+ } catch (error) {
325
+ this.#database.destroy()
326
+
327
+ throw error
328
+ }
329
+
330
+ this.#selectCell = this.#database.prepare("SELECT area_id, containment FROM zoning_cell WHERE h3_cell = ?")
331
+
332
+ // TWO STATEMENTS, AND THE SPLIT IS THE POINT. The attributes and the bbox are read WITHOUT the blob, because the
333
+ // bbox is the ray cast's prefilter: pulling hundreds of thousands of vertices off disk only to reject the polygon on
334
+ // a rectangle would make the prefilter cost more than the test it replaces. A `whole` cell never reads the blob at
335
+ // all.
336
+ this.#selectArea = this.#database.prepare(
337
+ "SELECT area_id, jurisdiction_id, plan_id, local_code, local_description, local_code_url, crosswalk_code, " +
338
+ "crosswalk_scheme, crosswalk_description, crosswalk_rollup, provenance_grade, min_lat, min_lon, max_lat, max_lon " +
339
+ "FROM zoning_area WHERE area_id = ?"
340
+ )
341
+
342
+ this.#selectAreaRings = this.#database.prepare("SELECT rings FROM zoning_area WHERE area_id = ?")
343
+
344
+ this.#selectPlan = this.#database.prepare(
345
+ "SELECT plan_id, plan_name, plan_level, valid_from, valid_to, current_plan FROM zoning_plan WHERE plan_id = ?"
346
+ )
347
+
348
+ this.#selectCoverage = this.#database.prepare(
349
+ "SELECT h3_cell, completeness, basis, observed_rows FROM layer_coverage WHERE h3_cell = ?"
350
+ )
351
+ }
352
+
353
+ /**
354
+ * What an adopted plan assigns at this coordinate.
355
+ */
356
+ public lookup(latitude: number, longitude: number): ZoningReading {
357
+ const indexCell = latLngToCell(latitude, longitude, this.identity.indexResolution) as H3Cell
358
+ const coverage = this.#readCoverage(indexCell)
359
+ const resolved = this.#resolveDesignations(indexCell, latitude, longitude)
360
+
361
+ return {
362
+ kind: resolved.designations.length ? ZoningReadingKind.Designated : ZoningReadingKind.Unknown,
363
+ designations: resolved.designations,
364
+ containment: resolved.containment,
365
+ ...(coverage ? { coverage } : {}),
366
+ indexCellIndex: indexCell,
367
+ limits: GZT_PRODUCT_LIMITS,
368
+ coverageLimit: GZT_COVERAGE_LIMIT,
369
+ }
370
+ }
371
+
372
+ public [Symbol.dispose](): void {
373
+ this.#database.destroy()
374
+ }
375
+
376
+ /**
377
+ * The coverage row for the index cell's parent at the coverage resolution.
378
+ */
379
+ #readCoverage(indexCell: H3Cell): (CoverageCell & { h3CellIndex: string; resolution: number }) | undefined {
380
+ return readCoverageAt(this.#selectCoverage, indexCell, this.identity.coverageResolution)
381
+ }
382
+
383
+ /**
384
+ * Walk the index, falling through to the geometry only for a cell a boundary crosses.
385
+ */
386
+ #resolveDesignations(
387
+ indexCell: H3Cell,
388
+ latitude: number,
389
+ longitude: number
390
+ ): { designations: ZoningDesignation[]; containment: ZoningContainmentPath } {
391
+ const whole = new Set<string>()
392
+ const partial = new Set<string>()
393
+
394
+ for (const cell of ancestorChainCells(indexCell, this.identity.indexResolution, this.identity.cellResolutions)) {
395
+ const rows = this.#selectCell.all(shortCellToInt(cell)) as Array<{ area_id: string; containment: string }>
396
+
397
+ for (const row of rows) {
398
+ if (row.containment === ZoningCellContainment.Whole) {
399
+ whole.add(row.area_id)
400
+ } else {
401
+ partial.add(row.area_id)
402
+ }
403
+ }
404
+ }
405
+
406
+ const designations: ZoningDesignation[] = []
407
+
408
+ for (const areaID of [...whole].toSorted()) {
409
+ const area = this.#selectArea.get(areaID) as AreaRow | undefined
410
+
411
+ if (area) {
412
+ designations.push(this.#toDesignation(area, ZoningContainmentPath.WholeCell))
413
+ }
414
+ }
415
+
416
+ let rayCastRan = false
417
+
418
+ for (const areaID of [...partial].toSorted()) {
419
+ // A polygon that already answered `whole` higher in the chain needs no geometry read.
420
+ if (whole.has(areaID)) continue
421
+
422
+ const area = this.#selectArea.get(areaID) as AreaRow | undefined
423
+
424
+ if (!area) continue
425
+
426
+ rayCastRan = true
427
+
428
+ // The bbox is the prefilter the geometry table stores precisely so the ray cast runs on the few polygons that
429
+ // could contain the point rather than on every polygon reaching the cell.
430
+ if (!bboxContains(area, longitude, latitude)) {
431
+ continue
432
+ }
433
+
434
+ const geometry = this.#selectAreaRings.get(areaID) as { rings: Uint8Array } | undefined
435
+
436
+ if (!geometry) continue
437
+
438
+ if (pointInEncodedRings(geometry.rings, longitude, latitude)) {
439
+ designations.push(this.#toDesignation(area, ZoningContainmentPath.RayCast))
440
+ }
441
+ }
442
+
443
+ if (designations.length) {
444
+ designations.sort((left, right) => (left.areaID < right.areaID ? -1 : 1))
445
+
446
+ return {
447
+ designations,
448
+ containment: whole.size ? ZoningContainmentPath.WholeCell : ZoningContainmentPath.RayCast,
449
+ }
450
+ }
451
+
452
+ return {
453
+ designations,
454
+ containment: rayCastRan ? ZoningContainmentPath.RayCast : ZoningContainmentPath.NoZoneCell,
455
+ }
456
+ }
457
+
458
+ /**
459
+ * One stored row as a designation, with its plan and its authority attached.
460
+ */
461
+ #toDesignation(area: AreaRow, containment: ZoningContainmentPath): ZoningDesignation {
462
+ const plan = this.#selectPlan.get(area.plan_id) as PlanRow | undefined
463
+
464
+ const jurisdiction = this.identity.jurisdictions.get(area.jurisdiction_id) ?? {
465
+ jurisdictionID: area.jurisdiction_id,
466
+ name: area.jurisdiction_id,
467
+ sourceCode: area.jurisdiction_id,
468
+ country: "",
469
+ }
470
+
471
+ const term = area.crosswalk_code === null ? undefined : this.#crosswalkTerms.get(area.crosswalk_code)
472
+
473
+ return {
474
+ areaID: area.area_id,
475
+ localCode: area.local_code,
476
+ localDescription: area.local_description,
477
+ localCodeURL: area.local_code_url,
478
+ // The crosswalk travels as one object or not at all: a code without its scheme reads as a code in whichever
479
+ // vocabulary the consumer happened to assume.
480
+ ...(area.crosswalk_code === null || area.crosswalk_scheme === null
481
+ ? {}
482
+ : {
483
+ crosswalk: {
484
+ scheme: area.crosswalk_scheme,
485
+ code: area.crosswalk_code,
486
+ description: area.crosswalk_description,
487
+ rollup: area.crosswalk_rollup,
488
+ ...(term ? { label: term.label } : {}),
489
+ declared: term?.declared ?? false,
490
+ },
491
+ }),
492
+ provenanceGrade: area.provenance_grade,
493
+ jurisdiction,
494
+ plan: {
495
+ planID: area.plan_id,
496
+ name: plan?.plan_name ?? area.plan_id,
497
+ level: plan?.plan_level ?? "",
498
+ validFrom: plan?.valid_from ?? null,
499
+ validTo: plan?.valid_to ?? null,
500
+ currentPlan: plan?.current_plan ?? 0,
501
+ },
502
+ unzoned: area.local_code === GZT_UNZONED_LOCAL_CODE,
503
+ containment,
504
+ }
505
+ }
506
+ }
507
+
508
+ /**
509
+ * The publisher's crosswalk domain, by code — its label and whether the publisher DECLARED it.
510
+ */
511
+ function readCrosswalkTerms(
512
+ database: DatabaseClient<ZoningDatabase>
513
+ ): ReadonlyMap<string, { label: string; declared: boolean }> {
514
+ const rows = database
515
+ .prepare("SELECT code, label, declared FROM zoning_vocabulary WHERE scheme = ?")
516
+ .all(GZT_CROSSWALK_SCHEME) as Array<{ code: string; label: string; declared: number }>
517
+
518
+ return new Map(rows.map((row) => [row.code, { label: row.label, declared: row.declared === 1 }]))
519
+ }
520
+
521
+ /**
522
+ * Read and check the layer's identity.
523
+ */
524
+ function readIdentity(database: DatabaseClient<ZoningDatabase>, databasePath: string): ZoningLayerIdentity {
525
+ const manifest = parseManifestRows(
526
+ database.prepare("SELECT * FROM layer_manifest").all() as Array<Record<string, string | number | null>>,
527
+ GZT_LAYER_NAME,
528
+ `zoning reader: ${databasePath}`
529
+ )
530
+
531
+ const spineKeys = manifest.spineKeys
532
+
533
+ if (!spineKeys.h3) {
534
+ throw new Error(`zoning reader: ${databasePath} declares no h3 spine key`)
535
+ }
536
+
537
+ // THE EXCLUSION CHECK, AND IT IS A CONDITION RATHER THAN A CONVENTION. The Department publishes its coverage detail
538
+ // only inside a map viewer, so no row of this layer may license a claim that a location is unrestricted. A stronger
539
+ // basis reaching a caller would let an absent polygon be read as a designation of freedom to build over most of the
540
+ // map. The check itself is the contract's rather than this product's; the SENTENCE saying why is this product's.
541
+ assertCoverageLicensesNoExclusion(
542
+ (database.prepare("SELECT DISTINCT basis FROM layer_coverage").all() as Array<{ basis: string | null }>).map(
543
+ (coverageRow) => coverageRow.basis
544
+ ),
545
+ `zoning reader: ${databasePath}`,
546
+ GZT_COVERAGE_LIMIT
547
+ )
548
+
549
+ const extentRows = database.prepare("SELECT * FROM zoning_mapped_extent ORDER BY extent_id").all() as Array<
550
+ Record<string, string | number>
551
+ >
552
+
553
+ const cellResolutions = (
554
+ database.prepare("SELECT DISTINCT resolution FROM zoning_cell ORDER BY resolution").all() as Array<{
555
+ resolution: number
556
+ }>
557
+ ).map((entry) => entry.resolution)
558
+
559
+ const indexResolution = spineKeys.h3.resolution
560
+
561
+ assertNoCellsFinerThanIndex(cellResolutions, indexResolution, `zoning reader: ${databasePath}`)
562
+
563
+ const jurisdictionRows = database
564
+ .prepare("SELECT jurisdiction_id, name, source_code, country FROM zoning_jurisdiction ORDER BY jurisdiction_id")
565
+ .all() as Array<{ jurisdiction_id: string; name: string; source_code: string; country: string }>
566
+
567
+ if (!jurisdictionRows.length) {
568
+ throw new Error(
569
+ `zoning reader: ${databasePath} names no jurisdiction — a designation whose authority a reader cannot see is a designation nobody can check`
570
+ )
571
+ }
572
+
573
+ const crosswalkScheme = (
574
+ database
575
+ .prepare("SELECT DISTINCT crosswalk_scheme FROM zoning_area WHERE crosswalk_scheme IS NOT NULL")
576
+ .all() as Array<{ crosswalk_scheme: string }>
577
+ ).map((entry) => entry.crosswalk_scheme)
578
+
579
+ // THE COVERAGE RESOLUTION IS RECOVERED FROM THE CELLS, NOT DECLARED. The manifest's spine key names the INDEX
580
+ // resolution; `layer_coverage` is keyed at a coarser one, and this layer has no footprint row to carry it. Recovering
581
+ // it is exact rather than approximate — a short cell expands to a valid index at exactly one resolution — and the
582
+ // shared helper throws on a table that mixes them.
583
+ const coverageResolution = recoverShortCellResolution(
584
+ (database.prepare("SELECT h3_cell FROM layer_coverage").all() as Array<{ h3_cell: number }>).map(
585
+ (coverageRow) => coverageRow.h3_cell
586
+ ),
587
+ `zoning reader: ${databasePath}`
588
+ )
589
+
590
+ return {
591
+ manifest,
592
+ indexResolution,
593
+ coverageResolution,
594
+ cellResolutions,
595
+ jurisdictions: new Map(
596
+ jurisdictionRows.map((entry) => [
597
+ entry.jurisdiction_id,
598
+ {
599
+ jurisdictionID: entry.jurisdiction_id,
600
+ name: entry.name,
601
+ sourceCode: entry.source_code,
602
+ country: entry.country,
603
+ },
604
+ ])
605
+ ),
606
+ ...(crosswalkScheme[0] ? { crosswalkScheme: crosswalkScheme[0] } : {}),
607
+ mappedExtents: extentRows.map((extentRow) => ({
608
+ extentID: String(extentRow.extent_id),
609
+ source: String(extentRow.source),
610
+ statement: String(extentRow.statement),
611
+ statementURL: String(extentRow.statement_url),
612
+ })),
613
+ coverageBasis: CoverageBasis.SourcePresent,
614
+ databasePath,
615
+ }
616
+ }