@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
@@ -0,0 +1,790 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Build `zoning-ireland.db` — the sealed two-tier polygon layer, from the Department's bulk export.
7
+ *
8
+ * THE COVERAGE IS `source_present` AND THE TIER IS `build-local`, AND THE TWO ARE INDEPENDENT REFUSALS.
9
+ * The coverage basis is about what the source can support: the Department publishes its coverage detail only
10
+ * inside a map viewer, so an absent zoning polygon is one of at least four different things and
11
+ * {@linkcode assertNoNegativeClaim} refuses anything stronger before a row is written. The tier is about
12
+ * what the LICENCE supports: three published statements disagree about the grant, so
13
+ * {@linkcode assertTierMatchesLicense} refuses a `shipped` build. Resolving either one does not resolve the
14
+ * other.
15
+ *
16
+ * THE AREA CHECK IS THE HOLE CHECK AND THE ONE THING HERE THAT IS EXACT. The service encodes hole
17
+ * roles by ring orientation, and reading them wrong is silent — a hole read as an exterior produces a
18
+ * well-formed polygon that answers "inside" for every location the plan carved out. Measured over the whole
19
+ * national export: the rings read WITH their holes total 5,444.5 km² and the Department's own `Shape__Area`
20
+ * sums to 5,444.5 km²; the same rings read WITHOUT their holes total 5,666.6 km². The publisher's figure has
21
+ * to come from the live service, because the bulk export drops the column — which is what makes this a
22
+ * two-path check rather than the archive agreeing with itself.
23
+ *
24
+ * THERE IS NO BUILD-TIME TOUCH TABLE. A zoning cell row names ONE POLYGON, so it is final the moment that
25
+ * polygon is classified. The rows go straight in, and memory stays flat in row count with nothing to resolve
26
+ * afterwards.
27
+ *
28
+ * THE INGEST IS BOUNDED ANYWAY. h3's WASM heap cannot be reset from JavaScript and does not survive an
29
+ * unbounded number of polyfill calls; a sibling product died twice on that, after roughly 510,000 and
30
+ * 798,000 features. This product holds 85,330, so the whole country fits inside the 100,000-id default with
31
+ * room to spare — and the bound still ships, because a build that stays inside a ceiling by luck is not the
32
+ * same fact as one that cannot cross it.
33
+ *
34
+ * THE JURISDICTION, PLAN AND VOCABULARY ROWS ARE WRITTEN BY THE PARENT, once, from the merged chunk
35
+ * reports. They are the only tables whose rows are partials across chunks — an authority and a plan appear
36
+ * in every chunk that touches them — and merging them in the parent is what keeps the chunk append-only.
37
+ */
38
+
39
+ import { readFileSize } from "@mailwoman/core/fs/readers"
40
+ import {
41
+ areaAgreementFrom,
42
+ assertNoNegativeClaim as assertCoverageNoNegativeClaim,
43
+ CoverageBasis,
44
+ createLayerCoverageTable,
45
+ createLayerManifestTable,
46
+ LayerTier,
47
+ polygonLayerManifest,
48
+ sourcePresentCoverageCells,
49
+ writeLayerCoverage,
50
+ writeLayerManifest,
51
+ type AreaAgreementReading,
52
+ type CoverageCell,
53
+ } from "@mailwoman/core/layers"
54
+ import { resolveModulePath } from "@mailwoman/core/module/resolvers"
55
+ import { ingestChunkArguments, mergeCountsInto, runChunkProcess } from "@mailwoman/core/utils"
56
+ import { M2_PER_KM2 } from "@mailwoman/spatial"
57
+ import type { DatabaseClient } from "@mailwoman/sqlite/client"
58
+ import { buildSealedArtifact } from "@mailwoman/sqlite/sealed-build"
59
+
60
+ import { createZoningTables, type ZoningDatabase } from "#schema"
61
+ import type { ZoningFeatureSource } from "#sdk/ingest"
62
+ import type { CrosswalkPair, ObservedTerm, ZoningChunkResult } from "#sdk/ingest-chunk"
63
+ import { ingestZoningChunk } from "#sdk/ingest-chunk"
64
+ import {
65
+ assertTierMatchesLicense,
66
+ GZT_ATTRIBUTION,
67
+ GZT_COVERAGE_LIMIT,
68
+ GZT_CROSSWALK_SCHEME,
69
+ GZT_DECLARED_CODES,
70
+ GZT_DECLARED_CODE_SET,
71
+ GZT_ITEM_ID,
72
+ GZT_LAYER_NAME,
73
+ GZT_LICENSE,
74
+ GZT_PLAN_LEVELS,
75
+ } from "#vocabulary"
76
+
77
+ /**
78
+ * Schema version of the domain tables. Bumped when a column changes meaning, never for an added column a reader can
79
+ * ignore.
80
+ */
81
+ export const ZONING_SCHEMA_VERSION = 1
82
+
83
+ /**
84
+ * The plan-level vocabulary scheme.
85
+ */
86
+ export const PLAN_LEVEL_SCHEME = "IE-PLAN-LEVEL"
87
+
88
+ /**
89
+ * Feature ids per chunk process.
90
+ *
91
+ * Sized against the measured ceiling on a sibling product rather than guessed: single-process runs over that layer died
92
+ * after roughly 510,000 and 798,000 features as h3's WASM heap fragmented. This product holds 85,330 features, so this
93
+ * default puts the whole country in one process — and it is the ceiling that makes the build reproducible rather than
94
+ * the fact that this product happens to sit below it.
95
+ *
96
+ * A SMALLER CHUNK COSTS A FULL PASS EACH. The source is one 247 MB GeoJSON document rather than an indexed store, so
97
+ * ogr2ogr scans all of it per range: measured at 13.2 s per pass on this lab.
98
+ */
99
+ export const DEFAULT_CHUNK_SIZE = 100_000
100
+
101
+ /**
102
+ * Where a build gets its features, and — for a real one — how it bounds each process's share of them.
103
+ */
104
+ export type BuildZoningInput =
105
+ | {
106
+ /**
107
+ * A feature source consumed IN THIS PROCESS. Correct for a fixture and for anything small; it is what the batched
108
+ * form falls back to per chunk, so the two share one implementation.
109
+ */
110
+ source: ZoningFeatureSource
111
+ }
112
+ | {
113
+ /**
114
+ * The bulk export, ingested in bounded chunks — one child process per range of the authority's own feature ids.
115
+ */
116
+ batched: {
117
+ exportPath: string
118
+ /**
119
+ * Feature ids per chunk. See {@link DEFAULT_CHUNK_SIZE}.
120
+ */
121
+ chunkSize?: number
122
+ /**
123
+ * The feature count the whole build should yield.
124
+ */
125
+ declaredFeatureCount: number
126
+ }
127
+ }
128
+
129
+ export type BuildZoningOptions = BuildZoningInput & {
130
+ /**
131
+ * Where the sealed artifact lands. The build writes beside it and swaps.
132
+ */
133
+ out: string
134
+ /**
135
+ * The product vintage — `layer_manifest.version` and `source_vintage`.
136
+ */
137
+ sourceVintage: string
138
+ buildCmd: string
139
+ buildSHA: string
140
+ /**
141
+ * ISO-8601, supplied by the caller. Never generated here: the contract says so, and a library-generated timestamp
142
+ * makes two builds of the same inputs differ.
143
+ */
144
+ createdAt: string
145
+ /**
146
+ * The resolution the cell index is built at — chosen from the candidates-per-cell and zero-cell measurement.
147
+ */
148
+ indexResolution: number
149
+ /**
150
+ * The resolution `layer_coverage` rows are keyed at. Must be coarser than the index resolution.
151
+ */
152
+ coverageResolution: number
153
+ /**
154
+ * The publisher's OWN area figure for the whole product, in square metres — its `Shape__Area` sum, read from the live
155
+ * service. Supplied, the build asserts the rings it encoded agree with it.
156
+ */
157
+ expectedSourceAreaM2?: number
158
+ /**
159
+ * The feature count the live service reports. Supplied, the build asserts its own streamed total against it.
160
+ */
161
+ expectedFeatureCount?: number
162
+ /**
163
+ * The tier to stamp. `build-local` unless the licence contradiction is resolved — see
164
+ * {@link assertTierMatchesLicense}.
165
+ */
166
+ tier?: LayerTier
167
+ onProgress?: (message: string) => void
168
+ }
169
+
170
+ export interface BuildZoningResult {
171
+ out: string
172
+ features: number
173
+ jurisdictions: number
174
+ plans: number
175
+ indexResolution: number
176
+ coverageResolution: number
177
+ wholeCellRows: number
178
+ partialCellRows: number
179
+ /**
180
+ * `partialCellRows / (wholeCellRows + partialCellRows)` over the STORED rows — the whole side is compacted per
181
+ * feature, so this is not the same number the resolution was chosen on and is reported separately.
182
+ */
183
+ storedPartialShare: number
184
+ /**
185
+ * Features whose bounding box forced a resolution coarser than `indexResolution`, and the resolutions the stored cell
186
+ * rows are actually at. Both are reported rather than smoothed over: a reader that assumed one resolution would probe
187
+ * at the wrong one and read every coarsened feature as an absence.
188
+ */
189
+ coarsenedFeatures: number
190
+ storedResolutions: number[]
191
+ coverageCells: number
192
+ /**
193
+ * The basis every coverage row carries. `source_present`, always, while `zoning_mapped_extent` is empty.
194
+ */
195
+ coverageBasis: CoverageBasis
196
+ tier: LayerTier
197
+ license: string
198
+ /**
199
+ * The ring-role census: how many rings, how many the orientation read as exteriors and holes, and how many holes were
200
+ * placed on their parent's boundary rather than inside it.
201
+ */
202
+ rings: {
203
+ total: number
204
+ exteriors: number
205
+ holes: number
206
+ nestedHoles: number
207
+ adjacentHoles: number
208
+ /**
209
+ * Features whose exterior was chosen by MAGNITUDE because no ring read as one by orientation. Measured at ONE of
210
+ * 85,330 — a three-vertex sliver enclosing 3.0 × 10⁻⁷ m², where a ring's winding is floating-point noise rather
211
+ * than something the publisher stated. Reported rather than implied to be zero.
212
+ */
213
+ exteriorByMagnitude: number
214
+ }
215
+ /**
216
+ * The area totals in square kilometres — what the publisher says, what the encoded rings say read with their holes,
217
+ * and what they would say read without — with the witness stated, plus this product's own signed ring sum. The
218
+ * publisher's figure is never defaulted to this build's own reading: a receipt printing "publisher 205.4 km², 0.000%
219
+ * apart" when nobody asked the publisher is a check reporting itself as passed.
220
+ */
221
+ area: AreaAgreementReading & { signedKM2: number }
222
+ /**
223
+ * The vocabulary census, per scheme: how many codes the artifact holds and how many of them the publisher never
224
+ * declared.
225
+ */
226
+ vocabulary: Array<{ scheme: string; codes: number; undeclared: number; undeclaredCodes: string[] }>
227
+ /**
228
+ * (authority, local code) pairs, and how many of them take MORE THAN ONE generic type — the measurement that keeps
229
+ * `zoning_crosswalk_edge` empty.
230
+ */
231
+ crosswalk: {
232
+ pairs: number
233
+ nonFunctionalPairs: number
234
+ /**
235
+ * The worst offenders, most generic types first, for the receipt.
236
+ */
237
+ worst: Array<{ authorityCode: string; localCode: string; crosswalkCodes: string[] }>
238
+ }
239
+ sizeBytes: number
240
+ }
241
+
242
+ /**
243
+ * The relative gap between the two area readings that fails the build.
244
+ *
245
+ * The comparison is a SPHERICAL ring area against the publisher's PLANAR figure in Irish Transverse Mercator, so the
246
+ * two never agree exactly: ITM's scale factor runs 0.99982 at its central meridian and above 1 towards the edges of the
247
+ * island, which contributes a few tenths of a percent to an area, and the spherical approximation contributes a similar
248
+ * amount against the ellipsoid. Measured on the largest feature in the country: 2,223.1 km² spherical against the
249
+ * Department's 2,232.1 km², 0.40% apart. One percent leaves that comfortably inside the tolerance while sitting well
250
+ * below the 4.1% a hole-blind read produces over the same set.
251
+ */
252
+ const AREA_TOLERANCE = 0.01
253
+
254
+ /**
255
+ * How many non-functional crosswalk pairs the receipt names.
256
+ */
257
+ const WORST_PAIRS_REPORTED = 8
258
+
259
+ /**
260
+ * Build the layer.
261
+ *
262
+ * @throws {Error} On a feature that reaches no cell, a feature count that disagrees with the source's own declaration,
263
+ * an area total that disagrees with the publisher's, a coverage row that would license a negative claim, a crosswalk
264
+ * edge table written while the mapping is not a function, or a `shipped` tier asked for under an unresolved licence.
265
+ */
266
+ export async function buildZoningDatabase(options: BuildZoningOptions): Promise<BuildZoningResult> {
267
+ const tier = options.tier ?? LayerTier.BuildLocal
268
+
269
+ assertTierMatchesLicense(tier, GZT_LICENSE)
270
+
271
+ if (options.coverageResolution >= options.indexResolution) {
272
+ throw new Error(
273
+ `zoning build: the coverage resolution (${options.coverageResolution}) must be coarser than the index resolution (${options.indexResolution}) — a row's coverage cell is the PARENT of its index cell`
274
+ )
275
+ }
276
+
277
+ const batched = "batched" in options ? options.batched : undefined
278
+ const source = "batched" in options ? undefined : options.source
279
+ const declaredFeatureCount = batched ? batched.declaredFeatureCount : source!.declaredFeatureCount
280
+
281
+ options.onProgress?.(
282
+ batched
283
+ ? `source: ${batched.exportPath} · ${declaredFeatureCount.toLocaleString()} features`
284
+ : `source: EPSG:${source!.epsg} · ${declaredFeatureCount.toLocaleString()} features · ${source!.origin}`
285
+ )
286
+
287
+ const built = await buildSealedArtifact<ZoningDatabase, StreamResult, Omit<BuildZoningResult, "sizeBytes">>({
288
+ out: options.out,
289
+ createTables: async (kdb) => {
290
+ await createZoningTables(kdb)
291
+ await createLayerManifestTable(kdb)
292
+ await createLayerCoverageTable(kdb)
293
+ },
294
+ ingest: async (kdb) => {
295
+ if (!source) return undefined
296
+
297
+ return aggregateChunks([
298
+ await ingestZoningChunk(kdb, {
299
+ source,
300
+ indexResolution: options.indexResolution,
301
+ coverageResolution: options.coverageResolution,
302
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
303
+ }),
304
+ ])
305
+ },
306
+ ...(batched ? { batched: (tmpPath: string) => runBatchedIngest(tmpPath, options, batched) } : {}),
307
+ finish: async (kdb, ingested) => buildZoningResult(kdb, options, tier, declaredFeatureCount, ingested),
308
+ })
309
+
310
+ return { ...built, sizeBytes: await readFileSize(options.out) }
311
+ }
312
+
313
+ /**
314
+ * The post-ingest half of the build, under the second handle: the assertions over what was streamed, then every
315
+ * artifact table beyond the truth tables.
316
+ */
317
+ async function buildZoningResult(
318
+ kdb: DatabaseClient<ZoningDatabase>,
319
+ options: BuildZoningOptions,
320
+ tier: LayerTier,
321
+ declaredFeatureCount: number,
322
+ ingested: StreamResult
323
+ ): Promise<Omit<BuildZoningResult, "sizeBytes">> {
324
+ if (ingested.features !== declaredFeatureCount) {
325
+ throw new Error(
326
+ `zoning build: streamed ${ingested.features} features, the source declares ${declaredFeatureCount} — a short read builds a smaller country and reports success`
327
+ )
328
+ }
329
+
330
+ if (options.expectedFeatureCount !== undefined && ingested.features !== options.expectedFeatureCount) {
331
+ throw new Error(
332
+ `zoning build: streamed ${ingested.features} features and the live service reports ${options.expectedFeatureCount} — the archive is a different vintage from the one the service is publishing`
333
+ )
334
+ }
335
+
336
+ const area = assertAreaAgreement(ingested, options.expectedSourceAreaM2)
337
+
338
+ // THE CROSSWALK IS NOT A TABLE, AND THE BUILD CHECKS IT RATHER THAN ASSUMING IT. Writing no edges while the mapping
339
+ // happens not to be a function would be an accident; refusing to write them while it is not is a statement.
340
+ const nonFunctional = nonFunctionalPairs(ingested.crosswalkPairs)
341
+
342
+ assertCrosswalkIsNotATable(ingested.crosswalkPairs, 0)
343
+
344
+ options.onProgress?.(
345
+ `${ingested.features.toLocaleString()} zoning polygons written · ${ingested.rings.total.toLocaleString()} rings ` +
346
+ `(${ingested.rings.exteriors.toLocaleString()} exterior, ${ingested.rings.holes.toLocaleString()} hole)`
347
+ )
348
+
349
+ writeJurisdictionRows(kdb, ingested.jurisdictions)
350
+ writePlanRows(kdb, ingested.plans)
351
+
352
+ const vocabulary = writeVocabularyRows(kdb, ingested.vocabulary)
353
+
354
+ const coverage = sourcePresentCoverageCells(ingested.observedByCoverageCell)
355
+
356
+ assertNoNegativeClaim(coverage)
357
+
358
+ await writeLayerCoverage(kdb, coverage)
359
+
360
+ await writeLayerManifest(
361
+ kdb,
362
+ polygonLayerManifest(options, {
363
+ name: GZT_LAYER_NAME,
364
+ schemaVersion: ZONING_SCHEMA_VERSION,
365
+ license: GZT_LICENSE,
366
+ attribution: GZT_ATTRIBUTION,
367
+ source: `arcgis.com item ${GZT_ITEM_ID}`,
368
+ cellColumn: "zoning_cell.h3_cell",
369
+ tier,
370
+ })
371
+ )
372
+
373
+ const storedResolutions = (
374
+ kdb.prepare("SELECT DISTINCT resolution FROM zoning_cell ORDER BY resolution").all() as Array<{
375
+ resolution: number
376
+ }>
377
+ ).map((row) => row.resolution)
378
+
379
+ // NO SECONDARY INDEXES, AND THAT IS A DECISION RATHER THAN AN OMISSION. Both probes this artifact serves are already
380
+ // primary-key probes: the cell table's `(h3_cell, area_id)` key answers `WHERE h3_cell = ?` as a range scan of a
381
+ // handful of rows, and the geometry table is probed by `area_id`, its own key. An index over a `WITHOUT ROWID` table
382
+ // carries the primary key in every entry, so it would roughly double the cell tier to serve a scan that is already
383
+ // short.
384
+ const totalCellRows = ingested.wholeCellRows + ingested.partialCellRows
385
+
386
+ return {
387
+ out: options.out,
388
+ features: ingested.features,
389
+ jurisdictions: ingested.jurisdictions.length,
390
+ plans: ingested.plans.length,
391
+ indexResolution: options.indexResolution,
392
+ coverageResolution: options.coverageResolution,
393
+ wholeCellRows: ingested.wholeCellRows,
394
+ partialCellRows: ingested.partialCellRows,
395
+ storedPartialShare: totalCellRows ? ingested.partialCellRows / totalCellRows : 0,
396
+ coarsenedFeatures: ingested.coarsened,
397
+ storedResolutions,
398
+ coverageCells: coverage.length,
399
+ coverageBasis: CoverageBasis.SourcePresent,
400
+ tier,
401
+ license: GZT_LICENSE,
402
+ rings: ingested.rings,
403
+ area,
404
+ vocabulary,
405
+ crosswalk: {
406
+ pairs: ingested.crosswalkPairs.length,
407
+ nonFunctionalPairs: nonFunctional.length,
408
+ worst: nonFunctional
409
+ .toSorted((left, right) => right[2].length - left[2].length)
410
+ .slice(0, WORST_PAIRS_REPORTED)
411
+ .map(([authorityCode, localCode, crosswalkCodes]) => ({ authorityCode, localCode, crosswalkCodes })),
412
+ },
413
+ }
414
+ }
415
+
416
+ /**
417
+ * What the whole ingest produced, however many processes it took.
418
+ */
419
+ interface StreamResult {
420
+ features: number
421
+ coarsened: number
422
+ wholeCellRows: number
423
+ partialCellRows: number
424
+ observedByCoverageCell: Map<number, number>
425
+ area: { signedM2: number; nestedM2: number; allExteriorM2: number }
426
+ rings: {
427
+ total: number
428
+ exteriors: number
429
+ holes: number
430
+ nestedHoles: number
431
+ adjacentHoles: number
432
+ /**
433
+ * Features whose exterior was chosen by MAGNITUDE because no ring read as one by orientation. Measured at ONE of
434
+ * 85,330 — a three-vertex sliver enclosing 3.0 × 10⁻⁷ m², where a ring's winding is floating-point noise rather
435
+ * than something the publisher stated. Reported rather than implied to be zero.
436
+ */
437
+ exteriorByMagnitude: number
438
+ }
439
+ jurisdictions: Array<[string, string]>
440
+ plans: ZoningChunkResult["plans"]
441
+ vocabulary: ObservedTerm[]
442
+ crosswalkPairs: CrosswalkPair[]
443
+ }
444
+
445
+ /**
446
+ * Add up what the chunks reported.
447
+ *
448
+ * Exported for its own test: the coverage-cell arithmetic and the crosswalk-pair merge are the parts of the batched
449
+ * path a fixture build cannot reach, and getting either wrong produces a well-formed artifact — one that under-reports
450
+ * how many polygons a cell holds, or one that reports a mapping as a function because no single chunk saw it break.
451
+ */
452
+ export function aggregateChunks(chunks: ReadonlyArray<ZoningChunkResult>): StreamResult {
453
+ const observedByCoverageCell = new Map<number, number>()
454
+ const jurisdictions = new Map<string, string>()
455
+ const plans = new Map<string, ZoningChunkResult["plans"][number]>()
456
+ const vocabulary = new Map<string, ObservedTerm>()
457
+ const crosswalkPairs = new Map<string, Set<string>>()
458
+ const pairNames = new Map<string, [string, string]>()
459
+
460
+ let features = 0
461
+ let coarsened = 0
462
+ let wholeCellRows = 0
463
+ let partialCellRows = 0
464
+ let signedArea = 0
465
+ let nestedArea = 0
466
+ let allExteriorArea = 0
467
+ let ringsTotal = 0
468
+ let exteriors = 0
469
+ let holes = 0
470
+ let nestedHoles = 0
471
+ let adjacentHoles = 0
472
+ let exteriorByMagnitude = 0
473
+
474
+ for (const chunk of chunks) {
475
+ features += chunk.features
476
+ coarsened += chunk.coarsened
477
+ wholeCellRows += chunk.wholeCellRows
478
+ partialCellRows += chunk.partialCellRows
479
+ signedArea += chunk.area.signedM2
480
+ nestedArea += chunk.area.nestedM2
481
+ allExteriorArea += chunk.area.allExteriorM2
482
+ ringsTotal += chunk.rings.total
483
+ exteriors += chunk.rings.exteriors
484
+ holes += chunk.rings.holes
485
+ nestedHoles += chunk.rings.nestedHoles
486
+ adjacentHoles += chunk.rings.adjacentHoles
487
+ exteriorByMagnitude += chunk.rings.exteriorByMagnitude
488
+
489
+ // A coverage cell straddles chunk boundaries, so the counts ADD rather than replace. Taking the last chunk's value
490
+ // would report a cell as holding only the last chunk's polygons.
491
+ mergeCountsInto(observedByCoverageCell, chunk.observedByCoverageCell)
492
+
493
+ for (const [code, name] of chunk.jurisdictions) {
494
+ jurisdictions.set(code, name)
495
+ }
496
+
497
+ for (const plan of chunk.plans) {
498
+ if (!plans.has(plan.planID)) {
499
+ plans.set(plan.planID, plan)
500
+ }
501
+ }
502
+
503
+ for (const [scheme, code, label, rows] of chunk.vocabulary) {
504
+ const key = `${scheme}\u0000${code}`
505
+ const existing = vocabulary.get(key)
506
+
507
+ vocabulary.set(key, existing ? [scheme, code, existing[2], existing[3] + rows] : [scheme, code, label, rows])
508
+ }
509
+
510
+ // THE PAIRS MERGE AS A UNION, and that is the whole point of doing it here. A mapping that is not a function can look
511
+ // like one inside any single chunk: Cork's `Special Policy Area` takes 14 generic types across the county, and a
512
+ // chunk holding a prefix of its feature ids may well have seen only one of them.
513
+ for (const [authorityCode, localCode, codes] of chunk.crosswalkPairs) {
514
+ const key = `${authorityCode}\u0000${localCode}`
515
+ const existing = crosswalkPairs.get(key)
516
+
517
+ pairNames.set(key, [authorityCode, localCode])
518
+
519
+ if (existing) {
520
+ for (const code of codes) {
521
+ existing.add(code)
522
+ }
523
+ } else {
524
+ crosswalkPairs.set(key, new Set(codes))
525
+ }
526
+ }
527
+ }
528
+
529
+ return {
530
+ features,
531
+ coarsened,
532
+ wholeCellRows,
533
+ partialCellRows,
534
+ observedByCoverageCell,
535
+ area: { signedM2: signedArea, nestedM2: nestedArea, allExteriorM2: allExteriorArea },
536
+ rings: { total: ringsTotal, exteriors, holes, nestedHoles, adjacentHoles, exteriorByMagnitude },
537
+ jurisdictions: [...jurisdictions],
538
+ plans: [...plans.values()],
539
+ vocabulary: [...vocabulary.values()],
540
+ crosswalkPairs: [...crosswalkPairs].map(([key, codes]) => {
541
+ const [authorityCode, localCode] = pairNames.get(key)!
542
+
543
+ return [authorityCode, localCode, [...codes].toSorted()] satisfies CrosswalkPair
544
+ }),
545
+ }
546
+ }
547
+
548
+ /**
549
+ * The (authority, local code) pairs that take more than one generic type.
550
+ */
551
+ export function nonFunctionalPairs(pairs: ReadonlyArray<CrosswalkPair>): CrosswalkPair[] {
552
+ return pairs.filter((pair) => pair[2].length > 1)
553
+ }
554
+
555
+ /**
556
+ * Refuse a crosswalk EDGE TABLE while the publisher's mapping is not a function of the (authority, code) pair.
557
+ *
558
+ * An edge table asserts that a code determines a type. Measured nationally, 52 of 795 pairs take more than one — Cork
559
+ * County Council's `Special Policy Area` takes 14 — so an edge table built from this data would have to pick one type
560
+ * per pair and would be this package's invention rather than the Department's mapping. The mapping lives per polygon,
561
+ * on `zoning_area`, where the Department put it.
562
+ *
563
+ * @throws {Error} When edges would be written while any pair is non-functional.
564
+ */
565
+ export function assertCrosswalkIsNotATable(pairs: ReadonlyArray<CrosswalkPair>, edgeCount: number): void {
566
+ if (!edgeCount) return
567
+
568
+ const broken = nonFunctionalPairs(pairs)
569
+
570
+ if (!broken.length) return
571
+
572
+ const worst = broken.toSorted((left, right) => right[2].length - left[2].length)[0]!
573
+
574
+ throw new Error(
575
+ `zoning build: ${edgeCount} crosswalk edge(s) would be written while ${broken.length} of ${pairs.length} ` +
576
+ `(authority, local code) pairs take more than one generic type — ${worst[0]} ${JSON.stringify(worst[1])} takes ` +
577
+ `${worst[2].length} (${worst[2].join(", ")}). An edge table asserts that a code determines a type, and this ` +
578
+ "publisher assigns the type per polygon, so the table would be this build's invention rather than the authority's mapping"
579
+ )
580
+ }
581
+
582
+ /**
583
+ * Refuse an artifact whose rings do not add up to the area the publisher itself reports.
584
+ *
585
+ * The message carries the hole-blind total beside the nested one, because the gap between them is the diagnosis: a hole
586
+ * read as an exterior ring answers "inside" for every point in it.
587
+ */
588
+ function assertAreaAgreement(
589
+ streamed: StreamResult,
590
+ expectedSourceAreaM2: number | undefined
591
+ ): BuildZoningResult["area"] {
592
+ const signedKM2 = streamed.area.signedM2 / M2_PER_KM2
593
+
594
+ // THE PUBLISHER'S FIGURE IS ABSENT RATHER THAN DEFAULTED — the reading's own type says so. Filling it with this
595
+ // build's own reading would make the receipt print "0.000% apart" for a check that never ran, which is the one shape
596
+ // a reader cannot tell from a pass.
597
+ const reading = areaAgreementFrom(
598
+ { nestedM2: streamed.area.nestedM2, allExteriorM2: streamed.area.allExteriorM2 },
599
+ expectedSourceAreaM2
600
+ )
601
+
602
+ const area: BuildZoningResult["area"] = { ...reading, signedKM2 }
603
+
604
+ if (reading.witness === "absent" || reading.relativeGap <= AREA_TOLERANCE) return area
605
+
606
+ throw new Error(
607
+ `zoning build: the encoded rings total ${reading.nestedKM2.toFixed(1)} km² against the publisher's ${reading.sourceKM2.toFixed(1)} km² ` +
608
+ `(${(reading.relativeGap * 100).toFixed(2)}% apart, tolerance ${(AREA_TOLERANCE * 100).toFixed(0)}%). Read without their holes the same rings total ` +
609
+ `${reading.allExteriorKM2.toFixed(1)} km², so compare the two: a hole-blind read answers "inside" for every point in a hole`
610
+ )
611
+ }
612
+
613
+ /**
614
+ * Run the ingest as a sequence of bounded child processes, over ranges of the authority's own feature ids.
615
+ *
616
+ * THE PARENT HOLDS NO HANDLE WHILE THEY RUN — its caller closed one before this and opens another after. Each child
617
+ * opens the same file and appends; chunks run one at a time, so there is exactly one writer at every instant and no
618
+ * locking to reason about.
619
+ *
620
+ * @throws {Error} When a chunk exits non-zero, or prints no result line — a chunk that died mid-range has written a
621
+ * partial set of rows, and continuing would seal an artifact missing features nobody could name.
622
+ */
623
+ async function runBatchedIngest(
624
+ tmpPath: string,
625
+ options: BuildZoningOptions,
626
+ batched: Extract<BuildZoningInput, { batched: unknown }>["batched"]
627
+ ): Promise<StreamResult> {
628
+ const chunkSize = batched.chunkSize ?? DEFAULT_CHUNK_SIZE
629
+ const script = resolveModulePath("@mailwoman/zoning/scripts/ingest-chunk")
630
+ const chunks: ZoningChunkResult[] = []
631
+
632
+ // The upper bound is deliberately open — the source reports a count, not a maximum id, and a range that stopped at the
633
+ // count would drop every feature past a gap in the numbering.
634
+ let from = 1
635
+
636
+ for (;;) {
637
+ const to = from + chunkSize - 1
638
+
639
+ options.onProgress?.(`chunk OBJECTID ${from}–${to}`)
640
+
641
+ const result = await runChunkProcess<ZoningChunkResult>({
642
+ script,
643
+ context: "zoning build",
644
+ args: ingestChunkArguments({
645
+ database: tmpPath,
646
+ args: ["--export", batched.exportPath, "--object-id-from", String(from), "--object-id-to", String(to)],
647
+ indexResolution: options.indexResolution,
648
+ coverageResolution: options.coverageResolution,
649
+ }),
650
+ })
651
+
652
+ chunks.push(result)
653
+
654
+ if (!result.features) break
655
+
656
+ from = to + 1
657
+ }
658
+
659
+ return aggregateChunks(chunks)
660
+ }
661
+
662
+ /**
663
+ * Refuse a coverage row that would license a negative claim.
664
+ *
665
+ * THIS IS THE CHECK THE MEANING-OF-ZERO RULE TURNS ON, and it is a condition rather than a convention. The Department
666
+ * publishes its coverage detail only inside a map viewer, so no row of this layer may support an exclusion — a
667
+ * `designated` or `surveyed` basis here would let an absent zoning polygon be read as a statement that no restriction
668
+ * applies, over most of the map. The reader checks the same thing at open time, so an artifact built by some other path
669
+ * cannot get past it either.
670
+ */
671
+ export function assertNoNegativeClaim(cells: ReadonlyArray<CoverageCell>): void {
672
+ assertCoverageNoNegativeClaim("zoning build", cells, GZT_COVERAGE_LIMIT)
673
+ }
674
+
675
+ /**
676
+ * Insert the authorities.
677
+ */
678
+ function writeJurisdictionRows(
679
+ database: DatabaseClient<ZoningDatabase>,
680
+ jurisdictions: ReadonlyArray<[string, string]>
681
+ ): void {
682
+ const insert = database.prepare(
683
+ "INSERT INTO zoning_jurisdiction (jurisdiction_id, name, source_code, country) VALUES (?, ?, ?, ?)"
684
+ )
685
+
686
+ for (const [code, name] of jurisdictions.toSorted((left, right) => (left[0] < right[0] ? -1 : 1))) {
687
+ // The id IS the publisher's own code. `Fl` for Fingal against `CL`, `CO`, `DU` for the rest — carried in both
688
+ // columns rather than repaired in one, because a repaired code is this package's spelling in a column that claims to
689
+ // be the publisher's.
690
+ insert.run(code, name, code, "IE")
691
+ }
692
+ }
693
+
694
+ /**
695
+ * Insert the plans.
696
+ */
697
+ function writePlanRows(database: DatabaseClient<ZoningDatabase>, plans: ZoningChunkResult["plans"]): void {
698
+ const insert = database.prepare(
699
+ "INSERT INTO zoning_plan (plan_id, jurisdiction_id, plan_name, plan_level, valid_from, valid_to, current_plan) " +
700
+ "VALUES (?, ?, ?, ?, ?, ?, ?)"
701
+ )
702
+
703
+ for (const plan of plans.toSorted((left, right) => (left.planID < right.planID ? -1 : 1))) {
704
+ insert.run(plan.planID, plan.authorityCode, plan.name, plan.level, plan.from, plan.to, plan.currentPlan)
705
+ }
706
+ }
707
+
708
+ /**
709
+ * Insert the vocabulary: every code the publisher DECLARES, plus every code the DATA uses, with the difference recorded
710
+ * rather than folded away.
711
+ *
712
+ * A declared code the data never uses is kept at `observed_rows = 0`, because the domain is the publisher's statement
713
+ * of what a value may be rather than a census of what it is — Ireland's `SDZ` plan level is exactly that. A used code
714
+ * the publisher never declared is kept at `declared = 0`, because inventing a declaration would make a source-schema
715
+ * change indistinguishable from the publisher's own vocabulary.
716
+ */
717
+ function writeVocabularyRows(
718
+ database: DatabaseClient<ZoningDatabase>,
719
+ observed: ReadonlyArray<ObservedTerm>
720
+ ): BuildZoningResult["vocabulary"] {
721
+ const insert = database.prepare(
722
+ "INSERT INTO zoning_vocabulary (scheme, code, label, definition, definition_url, declared, observed_rows) " +
723
+ "VALUES (?, ?, ?, ?, ?, ?, ?)"
724
+ )
725
+
726
+ const rows = new Map<
727
+ string,
728
+ { scheme: string; code: string; label: string; declared: number; observedRows: number }
729
+ >()
730
+
731
+ const declare = (scheme: string, code: string, label: string): void => {
732
+ rows.set(`${scheme}\u0000${code}`, { scheme, code, label, declared: 1, observedRows: 0 })
733
+ }
734
+
735
+ for (const term of GZT_DECLARED_CODES) {
736
+ declare(GZT_CROSSWALK_SCHEME, term.code, term.label)
737
+ }
738
+
739
+ for (const term of GZT_PLAN_LEVELS) {
740
+ declare(PLAN_LEVEL_SCHEME, term.code, term.label)
741
+ }
742
+
743
+ for (const [scheme, code, label, observedRows] of observed) {
744
+ const key = `${scheme}\u0000${code}`
745
+ const existing = rows.get(key)
746
+
747
+ if (existing) {
748
+ existing.observedRows += observedRows
749
+
750
+ continue
751
+ }
752
+
753
+ rows.set(key, {
754
+ scheme,
755
+ code,
756
+ label,
757
+ // DECLARED IS A PROPERTY OF THE PUBLISHER'S DOMAIN, NOT OF THE SCHEME. A local authority's own codes are observed
758
+ // rather than declared — the Department publishes no domain for them — and an undeclared generic type is the event
759
+ // this column exists to make visible.
760
+ declared: scheme === GZT_CROSSWALK_SCHEME && GZT_DECLARED_CODE_SET.has(code) ? 1 : 0,
761
+ observedRows,
762
+ })
763
+ }
764
+
765
+ const bySchema = new Map<string, { codes: number; undeclared: number; undeclaredCodes: string[] }>()
766
+
767
+ for (const row of [...rows.values()].toSorted((left, right) =>
768
+ left.scheme === right.scheme ? (left.code < right.code ? -1 : 1) : left.scheme < right.scheme ? -1 : 1
769
+ )) {
770
+ // NULL, not a plausible URL. Every one of the 85,330 rows links its generic type's definition to `viewer.myplan.ie`,
771
+ // which has no DNS record, and three candidate replacements on the live host answer HTTP 404 — so the definitions
772
+ // behind the code-to-label pairs were not retrievable and this column says so by being empty.
773
+ insert.run(row.scheme, row.code, row.label, null, null, row.declared, row.observedRows)
774
+
775
+ const census = bySchema.get(row.scheme) ?? { codes: 0, undeclared: 0, undeclaredCodes: [] }
776
+
777
+ census.codes++
778
+
779
+ // A LOCAL SCHEME IS UNDECLARED BY CONSTRUCTION and reporting it as such would bury the one that matters. The census
780
+ // counts an undeclared code only where the publisher DOES publish a domain to be outside of.
781
+ if (!row.declared && row.scheme === GZT_CROSSWALK_SCHEME) {
782
+ census.undeclared++
783
+ census.undeclaredCodes.push(row.code)
784
+ }
785
+
786
+ bySchema.set(row.scheme, census)
787
+ }
788
+
789
+ return [...bySchema].map(([scheme, census]) => ({ scheme, ...census }))
790
+ }