@mailwoman/zoning 9.4.0 → 10.1.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 (98) hide show
  1. package/README.md +169 -163
  2. package/lib/index.ts +89 -120
  3. package/lib/paths.ts +24 -0
  4. package/lib/ring-roles.ts +30 -71
  5. package/lib/rings.ts +2 -13
  6. package/lib/schema.ts +96 -114
  7. package/lib/vocabulary.ts +52 -130
  8. package/out/index.d.ts +75 -95
  9. package/out/index.d.ts.map +1 -1
  10. package/out/index.js +25 -82
  11. package/out/index.js.map +1 -1
  12. package/out/paths.d.ts +19 -0
  13. package/out/paths.d.ts.map +1 -0
  14. package/out/paths.js +21 -0
  15. package/out/paths.js.map +1 -0
  16. package/out/ring-roles.d.ts +16 -50
  17. package/out/ring-roles.d.ts.map +1 -1
  18. package/out/ring-roles.js +18 -51
  19. package/out/ring-roles.js.map +1 -1
  20. package/out/rings.d.ts +2 -13
  21. package/out/rings.d.ts.map +1 -1
  22. package/out/rings.js +2 -13
  23. package/out/rings.js.map +1 -1
  24. package/out/schema.d.ts +93 -108
  25. package/out/schema.d.ts.map +1 -1
  26. package/out/schema.js +16 -44
  27. package/out/schema.js.map +1 -1
  28. package/out/sdk/build-zoning.d.ts +58 -111
  29. package/out/sdk/build-zoning.d.ts.map +1 -1
  30. package/out/sdk/build-zoning.js +48 -137
  31. package/out/sdk/build-zoning.js.map +1 -1
  32. package/out/sdk/cells.d.ts +20 -61
  33. package/out/sdk/cells.d.ts.map +1 -1
  34. package/out/sdk/cells.js +13 -50
  35. package/out/sdk/cells.js.map +1 -1
  36. package/out/sdk/client.d.ts +23 -67
  37. package/out/sdk/client.d.ts.map +1 -1
  38. package/out/sdk/client.js +29 -77
  39. package/out/sdk/client.js.map +1 -1
  40. package/out/sdk/download.d.ts +7 -27
  41. package/out/sdk/download.d.ts.map +1 -1
  42. package/out/sdk/download.js +7 -27
  43. package/out/sdk/download.js.map +1 -1
  44. package/out/sdk/ingest/chunk.d.ts +106 -0
  45. package/out/sdk/ingest/chunk.d.ts.map +1 -0
  46. package/out/sdk/{ingest-chunk.js → ingest/chunk.js} +17 -50
  47. package/out/sdk/ingest/chunk.js.map +1 -0
  48. package/out/sdk/ingest/worker.d.ts +9 -0
  49. package/out/sdk/ingest/worker.d.ts.map +1 -0
  50. package/out/{scripts/ingest-chunk.js → sdk/ingest/worker.js} +5 -7
  51. package/out/sdk/ingest/worker.js.map +1 -0
  52. package/out/sdk/ingest.d.ts +54 -77
  53. package/out/sdk/ingest.d.ts.map +1 -1
  54. package/out/sdk/ingest.js +50 -87
  55. package/out/sdk/ingest.js.map +1 -1
  56. package/out/sdk/measure-resolutions.d.ts +6 -23
  57. package/out/sdk/measure-resolutions.d.ts.map +1 -1
  58. package/out/sdk/measure-resolutions.js +4 -21
  59. package/out/sdk/measure-resolutions.js.map +1 -1
  60. package/out/sdk/test-kit.d.ts +75 -0
  61. package/out/sdk/test-kit.d.ts.map +1 -0
  62. package/out/{test-kit.js → sdk/test-kit.js} +20 -43
  63. package/out/sdk/test-kit.js.map +1 -0
  64. package/out/sdk/verify.d.ts +74 -56
  65. package/out/sdk/verify.d.ts.map +1 -1
  66. package/out/sdk/verify.js +70 -57
  67. package/out/sdk/verify.js.map +1 -1
  68. package/out/vocabulary.d.ts +52 -120
  69. package/out/vocabulary.d.ts.map +1 -1
  70. package/out/vocabulary.js +47 -125
  71. package/out/vocabulary.js.map +1 -1
  72. package/package.json +37 -161
  73. package/{lib/sdk → sdk}/build-zoning.ts +100 -186
  74. package/{lib/sdk → sdk}/cells.ts +24 -63
  75. package/{lib/sdk → sdk}/client.ts +34 -82
  76. package/sdk/download.ts +58 -0
  77. package/{lib/sdk/ingest-chunk.ts → sdk/ingest/chunk.ts} +32 -61
  78. package/{lib/scripts/ingest-chunk.ts → sdk/ingest/worker.ts} +4 -6
  79. package/sdk/ingest.ts +366 -0
  80. package/{lib/sdk → sdk}/measure-resolutions.ts +8 -25
  81. package/{lib → sdk}/test-kit.ts +20 -43
  82. package/{lib/sdk → sdk}/verify.ts +102 -75
  83. package/lib/sdk/download.ts +0 -78
  84. package/lib/sdk/index.ts +0 -15
  85. package/lib/sdk/ingest.ts +0 -398
  86. package/out/scripts/ingest-chunk.d.ts +0 -11
  87. package/out/scripts/ingest-chunk.d.ts.map +0 -1
  88. package/out/scripts/ingest-chunk.js.map +0 -1
  89. package/out/sdk/index.d.ts +0 -15
  90. package/out/sdk/index.d.ts.map +0 -1
  91. package/out/sdk/index.js +0 -15
  92. package/out/sdk/index.js.map +0 -1
  93. package/out/sdk/ingest-chunk.d.ts +0 -130
  94. package/out/sdk/ingest-chunk.d.ts.map +0 -1
  95. package/out/sdk/ingest-chunk.js.map +0 -1
  96. package/out/test-kit.d.ts +0 -96
  97. package/out/test-kit.d.ts.map +0 -1
  98. package/out/test-kit.js.map +0 -1
@@ -3,34 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * The streaming pass — every feature into `zoning_area` and into `zoning_cell` — as a unit of work that can
7
- * run over PART of the source.
8
- *
9
- * WHY THIS IS A CHUNK RATHER THAN THE WHOLE FILE. h3's WASM heap cannot be reset from JavaScript, and it
10
- * does not survive an unbounded number of polyfill calls: over a sibling product, runs died after roughly
11
- * 510,000 and 798,000 features on geometry that classifies in milliseconds in a fresh process. A build that
12
- * completes only when fragmentation happens to stay low is not a reproducible build, so the classification
13
- * is bounded BY CONSTRUCTION — one process per range of the authority's own feature ids. This product's
14
- * 85,330 features fit inside the default bound; the bound ships anyway, because determinism by construction
15
- * is not the same fact as determinism by luck.
16
- *
17
- * THE VOCABULARY IS A CENSUS, NOT A CHECK. The declared generic-type domain is closed and the source
18
- * already breaks it — `N/A` appears on 4 rows and in no domain — so an undeclared value is RECORDED as
19
- * observed-but-undeclared rather than throwing. That is the opposite of the sibling layers' rule and it is
20
- * the publisher's own doing: refusing here would refuse the Department's own data. What DOES throw is a
21
- * blank local code, because the local code is the claim.
22
- *
23
- * THE CROSSWALK PAIRS ARE COUNTED HERE BECAUSE THEY ARE THE ARGUMENT FOR THE SCHEMA. If a local code
24
- * determined a generic type, the mapping could ship as an edge table and the local column would be
25
- * redundant. It does not: measured nationally, 52 of 795 (authority, local code) pairs take more than one
26
- * generic type. The chunk reports the pairs it saw and the build refuses to write an edge table while any
27
- * such pair exists, so the empty `zoning_crosswalk_edge` is a checked consequence rather than an omission.
28
- *
29
- * THE CHUNK OWNS NO ARTIFACT. It appends rows to a database the parent created and will seal, and returns
30
- * counts the parent adds up. Chunks run one at a time against that file, so there is no concurrent writer
31
- * and no locking to reason about. The jurisdiction, plan and vocabulary rows are RETURNED rather than
32
- * written: they are per-chunk partials that have to be merged before insertion, and 30 authorities, 63
33
- * plans and about 880 vocabulary rows cross a process boundary for nothing.
6
+ * The streaming pass, bounded to one process per range of the authority's own feature ids because h3's wasm heap cannot be reset from JavaScript and a build that completes only by luck is not reproducible.
34
7
  */
35
8
 
36
9
  import {
@@ -49,19 +22,18 @@ import type { ZoningFeatureSource, ZoningSourceFeature } from "#sdk/ingest"
49
22
  import { GZT_CROSSWALK_SCHEME, GZT_PROVENANCE_GRADE, GZT_ROLLUP_SCHEME, localSchemeFor } from "#vocabulary"
50
23
 
51
24
  /**
52
- * Rows per bulk-insert transaction. Chosen for the geometry table, whose rows carry a blob: a larger transaction grows
53
- * the write-ahead file without improving throughput.
25
+ * Rows per bulk-insert transaction, chosen for the geometry table whose rows contain a blob
26
+ * because a larger transaction grows the write-ahead file without improving throughput.
54
27
  */
55
28
  const INSERT_TRANSACTION_ROWS = 5000
56
29
 
57
- /**
58
- * Features between progress reports.
59
- */
60
30
  const PROGRESS_STRIDE = 5000
61
31
 
62
32
  /**
63
- * One observed vocabulary value: which scheme, which code, the publisher's own label for it, and how many rows carry
64
- * it.
33
+ * One observed vocabulary value.
34
+ *
35
+ * It records the scheme and code.
36
+ * It also records the publisher's label and row count.
65
37
  */
66
38
  export type ObservedTerm = [scheme: string, code: string, label: string, rows: number]
67
39
 
@@ -71,8 +43,8 @@ export type ObservedTerm = [scheme: string, code: string, label: string, rows: n
71
43
  export type CrosswalkPair = [authorityCode: string, localCode: string, crosswalkCodes: string[]]
72
44
 
73
45
  /**
74
- * What one chunk produced. Every field is JSON-serializable, because a chunk normally reports across a process
75
- * boundary.
46
+ * What one chunk produced, every field JSON-serializable because a chunk normally
47
+ * reports across a process boundary.
76
48
  */
77
49
  export interface ZoningChunkResult {
78
50
  features: number
@@ -86,12 +58,17 @@ export interface ZoningChunkResult {
86
58
  wholeCellRows: number
87
59
  partialCellRows: number
88
60
  /**
89
- * `[coverageCell, polygonsReachingIt]` pairs — an array rather than a `Map` so it survives the process boundary.
61
+ * `[coverageCell, polygonsReachingIt]` pairs — an array rather than a `Map`
62
+ * so it survives the process boundary.
90
63
  */
91
64
  observedByCoverageCell: Array<[number, number]>
92
65
  /**
93
- * Square metres. `signed` is the raw ring sum as published; `nested` is the per-polygon hole-aware reading;
94
- * `allExterior` is what the same rings say read WITHOUT their holes.
66
+ * Square-meter area readings from the polygon rings.
67
+ *
68
+ * `signed` is the raw ring sum as published.
69
+ * `nested` accounts for holes in each polygon.
70
+ *
71
+ * `allExterior` reads the same rings as exterior boundaries without holes.
95
72
  */
96
73
  area: { signedM2: number; nestedM2: number; allExteriorM2: number }
97
74
  /**
@@ -104,8 +81,7 @@ export interface ZoningChunkResult {
104
81
  nestedHoles: number
105
82
  adjacentHoles: number
106
83
  /**
107
- * Features whose exterior was chosen by MAGNITUDE because no ring read as one by orientation — measured at one of
108
- * 85,330. See `ResolvedRingRoles.exteriorByMagnitude`.
84
+ * Features whose exterior was chosen by magnitude because no ring read as one by orientation.
109
85
  */
110
86
  exteriorByMagnitude: number
111
87
  }
@@ -113,9 +89,7 @@ export interface ZoningChunkResult {
113
89
  * The authorities this chunk saw, by their own code.
114
90
  */
115
91
  jurisdictions: Array<[code: string, name: string]>
116
- /**
117
- * The plans this chunk saw.
118
- */
92
+
119
93
  plans: Array<{
120
94
  planID: string
121
95
  authorityCode: string
@@ -160,9 +134,9 @@ export async function ingestZoningChunk(
160
134
  const jurisdictions = new Map<string, string>()
161
135
  const plans = new Map<string, ZoningChunkResult["plans"][number]>()
162
136
 
163
- // KEYED ON A NUL-JOINED PAIR AND NEVER SPLIT BACK APART. A local code is free text that routinely contains spaces —
164
- // `Special Policy Area`, `RA - Rural Area` — so a key a reader had to re-split would mangle exactly the vocabulary
165
- // this layer exists to carry verbatim. The parts ride on the value instead.
137
+ // Keyed on a NUL-joined pair and never split back apart, because a local code is
138
+ // free text that routinely contains spaces and a key a reader had to re-split
139
+ // would mangle the vocabulary this layer preserves verbatim.
166
140
  const vocabulary = new Map<string, { scheme: string; code: string; label: string; rows: number }>()
167
141
  const crosswalkPairs = new Map<string, { authorityCode: string; localCode: string; codes: Set<string> }>()
168
142
 
@@ -181,8 +155,8 @@ export async function ingestZoningChunk(
181
155
  let adjacentHoles = 0
182
156
 
183
157
  /**
184
- * Record one observed vocabulary value. The FIRST label wins, because a later row's description is the publisher's
185
- * word for the same code and choosing between them would be this package editing the publisher's vocabulary.
158
+ * Record one observed vocabulary value, keeping the first label so a later row's
159
+ * description leaves the publisher's vocabulary unchanged.
186
160
  */
187
161
  const observe = (scheme: string, code: string, label: string): void => {
188
162
  const key = `${scheme}\u0000${code}`
@@ -225,9 +199,9 @@ export async function ingestZoningChunk(
225
199
  feature.crosswalkCode === null ? null : GZT_CROSSWALK_SCHEME,
226
200
  feature.crosswalkDescription,
227
201
  feature.crosswalkRollup,
228
- // ONE GRADE PER CLAIM. Every row of THIS artifact is `authoritative` — a government department republishing
229
- // local authorities' adopted plans — and an observed land-use layer is a different database with a different
230
- // `layer_manifest.name`, never a row with a second grade in this table.
202
+ // One grade per claim: every row of this artifact is `authoritative`,
203
+ // and an observed land-use layer is a different database with a different
204
+ // `layer_manifest.name` rather than a row with a second grade in this table.
231
205
  GZT_PROVENANCE_GRADE,
232
206
  bbox.minLat,
233
207
  bbox.minLon,
@@ -259,10 +233,8 @@ export async function ingestZoningChunk(
259
233
  }
260
234
  }
261
235
 
262
- // COVERAGE IS DERIVED FROM THE UNCOMPACTED CLASSIFICATION, not from the stored rows. A compacted parent spans
263
- // several coverage cells and `addCoverageCells` handles that, but the fringe is where this product's cells almost
264
- // all are — so counting off the stored rows and counting off the classification agree here, and the classification
265
- // is the one that cannot be changed by a compaction decision.
236
+ // Coverage is derived from the uncompacted classification rather than the stored rows,
237
+ // since the classification is the one compaction cannot change.
266
238
  const coverageCells = new Set<number>()
267
239
 
268
240
  for (const cell of classified.whole) {
@@ -291,8 +263,7 @@ export async function ingestZoningChunk(
291
263
  })
292
264
  }
293
265
 
294
- // The local vocabulary is per AUTHORITY, because the codes collide across them: `Residential` means one thing in
295
- // Cork County Council's plan and another in Westmeath's.
266
+ // The local vocabulary is per authority, because codes collide across them.
296
267
  observe(localSchemeFor(feature.authorityCode), feature.localCode, feature.localDescription ?? feature.localCode)
297
268
 
298
269
  if (feature.crosswalkCode !== null) {
@@ -352,8 +323,8 @@ export async function ingestZoningChunk(
352
323
  }
353
324
 
354
325
  /**
355
- * One feature's own contribution, for a caller that wants the numbers without a database — the fixture rung's
356
- * arithmetic and nothing else.
326
+ * One feature's own contribution, for a caller that wants the numbers without a database —
327
+ * the fixture rung's arithmetic and no more.
357
328
  */
358
329
  export function featureAreaReadings(feature: ZoningSourceFeature): {
359
330
  signed: number
@@ -3,9 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * One chunk of the zoning ingest, as its own process — spawned by `buildZoningDatabase`, never run by
7
- * hand. The process boundary and the stdout contract live with `runIngestChunkScript`; what stays here is
8
- * only this product's flags and its feature-source constructor.
6
+ * One chunk of the zoning ingest, as its own process — spawned by `buildZoningDatabase`, never run by hand.
9
7
  */
10
8
 
11
9
  import { requiredArgument } from "@mailwoman/core/scripting/arguments"
@@ -14,7 +12,7 @@ import type { DatabaseClient } from "@mailwoman/sqlite/client"
14
12
 
15
13
  import type { ZoningDatabase } from "#schema"
16
14
  import { createExportFeatureSource } from "#sdk/ingest"
17
- import { ingestZoningChunk } from "#sdk/ingest-chunk"
15
+ import { ingestZoningChunk } from "#sdk/ingest/chunk"
18
16
 
19
17
  await runIngestChunkScript({
20
18
  context: "zoning ingest-chunk",
@@ -30,8 +28,8 @@ await runIngestChunkScript({
30
28
  exportPath: requiredArgument("zoning ingest-chunk", "export", values.export),
31
29
  ...(values["object-id-from"] === undefined ? {} : { objectIDFrom: Number(values["object-id-from"]) }),
32
30
  ...(values["object-id-to"] === undefined ? {} : { objectIDTo: Number(values["object-id-to"]) }),
33
- // A RANGE's own count is not knowable up front — the source reports a layer's total and nothing narrower — so
34
- // the chunk asserts nothing about its size and the PARENT checks the sum against the whole file.
31
+ // A range's count is not knowable up front: the source reports only the layer total,
32
+ // so the parent checks the sum against the whole file.
35
33
  declaredFeatureCount: 0,
36
34
  }),
37
35
  indexResolution: chunk.indexResolution,
package/sdk/ingest.ts ADDED
@@ -0,0 +1,366 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Streams the Department's bulk zoning export through ogr2ogr as reprojected WGS84 features.
7
+ *
8
+ * The stream uses CSV with WKT geometry because the source marks holes by ring orientation. GDAL's
9
+ * GeoJSON writer rewinds every ring to RFC 7946 order. That turns holes into zoned areas. The source is
10
+ * in EPSG:2157, declared in a legacy top-level `crs` member that GDAL honors.
11
+ */
12
+
13
+ import { declaredFeatureCount } from "@mailwoman/core/layers"
14
+ import { assertRingsInsideExtent, requireArealPolygons, type MultiPolygonRings } from "@mailwoman/spatial"
15
+ import { readOGRLayerIdentity } from "@mailwoman/spatial/tools/ogr"
16
+ import { spawnOGR2OGR } from "@mailwoman/spatial/tools/ogr/stream"
17
+ import { wellKnownGeometryToGeoJSON } from "@mailwoman/spatial/well-known-text"
18
+ import { CSVSpliterator } from "spliterator"
19
+
20
+ import { resolveRingRoles, type ResolvedRingRoles } from "#rings"
21
+ import { GZT_DECLARED_BBOX, GZT_SOURCE_EPSG } from "#vocabulary"
22
+
23
+ /**
24
+ * One zoning feature, reprojected to WGS84 with its hole roles resolved.
25
+ */
26
+ export interface ZoningSourceFeature {
27
+ /**
28
+ * The authority's `objectid` as a string.
29
+ */
30
+ areaID: string
31
+ /**
32
+ * The `LA_CODE` value, verbatim.
33
+ * Fingal's unusual `Fl` code is kept as published.
34
+ */
35
+ authorityCode: string
36
+ authorityName: string
37
+ planID: string
38
+ planName: string
39
+ planLevel: string
40
+ planFrom: string | null
41
+ planTo: string | null
42
+ currentPlan: number
43
+ /**
44
+ * The `ZONE_ORIG` value, verbatim.
45
+ *
46
+ * Case and trailing spaces are kept because some codes differ only by them.
47
+ */
48
+ localCode: string
49
+ localDescription: string | null
50
+ localCodeURL: string | null
51
+ /**
52
+ * The `ZONE_GZT` value.
53
+ *
54
+ * It is the Department's national generic type for this polygon.
55
+ */
56
+ crosswalkCode: string | null
57
+ crosswalkDescription: string | null
58
+ /**
59
+ * The `SZO` value.
60
+ * It is the coarser national code as published.
61
+ */
62
+ crosswalkRollup: string | null
63
+ /**
64
+ * The rings with hole roles resolved from their orientation, plus a record of that resolution.
65
+ */
66
+ rings: ResolvedRingRoles
67
+ }
68
+
69
+ /**
70
+ * Options for reading the bulk export.
71
+ */
72
+ export interface ZoningIngestOptions {
73
+ /**
74
+ * The path of the bulk GeoJSON export.
75
+ */
76
+ exportPath: string
77
+ /**
78
+ * The maximum number of features to read.
79
+ * Fixture and smoke runs use it.
80
+ */
81
+ limit?: number
82
+ /**
83
+ * The EPSG code that the source must declare.
84
+ * A different code means the product has changed.
85
+ */
86
+ expectEPSG?: number
87
+ /**
88
+ * The extent that every reprojected vertex must fall inside.
89
+ * The default is the Department's declared extent.
90
+ */
91
+ declaredBBox?: readonly [number, number, number, number]
92
+ /**
93
+ * The inclusive range of authority `objectid` values to read.
94
+ *
95
+ * The h3 wasm heap cannot be reset from JavaScript, so the build runs one child process per range.
96
+ * It uses `objectid` ranges because they select the same features on every run.
97
+ *
98
+ * Every range costs a full scan of the export, because the export is one GeoJSON document.
99
+ */
100
+ objectIDFrom?: number
101
+ objectIDTo?: number
102
+ /**
103
+ * Restricts the read to one local authority's `LA_CODE`, for smoke runs.
104
+ */
105
+ authorityCode?: string
106
+ }
107
+
108
+ /**
109
+ * The metadata that the source declares, read before any feature.
110
+ */
111
+ export interface ZoningSourceIdentity {
112
+ epsg: number
113
+ featureCount: number
114
+ layer: string
115
+ /**
116
+ * The source's attribute field names.
117
+ */
118
+ fields: ReadonlySet<string>
119
+ }
120
+
121
+ /**
122
+ * The number of coordinate decimals that ogr2ogr writes.
123
+ * Nine decimals is far finer than the source's precision.
124
+ */
125
+ const COORDINATE_PRECISION = 9
126
+
127
+ /**
128
+ * The distance in degrees that a vertex may fall outside the declared extent.
129
+ *
130
+ * The published extent is rounded, so an exact test would fail on valid data.
131
+ * An unprojected or axis-swapped read lands much farther away and still fails.
132
+ */
133
+ const BBOX_MARGIN_DEGREES = 0.01
134
+
135
+ /**
136
+ * The attribute columns that the ingest reads.
137
+ * Every column is required.
138
+ */
139
+ export const ZONING_SOURCE_FIELDS: ReadonlyArray<string> = [
140
+ "OBJECTID",
141
+ "LA_CODE",
142
+ "LA_NAME",
143
+ "PLAN_ID",
144
+ "PLAN_NAME",
145
+ "PLAN_LEVEL",
146
+ "PLAN_FROM",
147
+ "PLAN_TO",
148
+ "CURRENT_PLAN",
149
+ "ZONE_ORIG",
150
+ "ZONE_DESC",
151
+ "ZONE_LINK",
152
+ "ZONE_GZT",
153
+ "GZT_DESC",
154
+ "SZO",
155
+ ]
156
+
157
+ /**
158
+ * Reads the source's declared projection, feature count and field list.
159
+ *
160
+ * @throws {Error} When the export is unreadable, when its declared EPSG code differs
161
+ * from `expectEPSG`, or when it lacks a field that the ingest reads.
162
+ */
163
+ export async function readZoningSourceIdentity(options: ZoningIngestOptions): Promise<ZoningSourceIdentity> {
164
+ const identity = await readOGRLayerIdentity({
165
+ path: options.exportPath,
166
+ expectEPSG: options.expectEPSG ?? GZT_SOURCE_EPSG,
167
+ context: "zoning ingest",
168
+ areaOfUse: "Ireland",
169
+ })
170
+
171
+ const missing = ZONING_SOURCE_FIELDS.filter((field) => field !== "OBJECTID" && !identity.fields.has(field))
172
+
173
+ // Given a missing column, `-select` makes ogr2ogr write an empty column without an error.
174
+ // This check turns a source schema change into an error that lists the missing columns.
175
+ if (missing.length) {
176
+ throw new Error(
177
+ `zoning ingest: ${options.exportPath} carries no ${missing.join(", ")} column(s) — ogr2ogr writes a missing column as empty rather than refusing, so a schema change would arrive as a stream of blank codes`
178
+ )
179
+ }
180
+
181
+ return { epsg: identity.epsg, featureCount: identity.featureCount, layer: identity.layer, fields: identity.fields }
182
+ }
183
+
184
+ /**
185
+ * Returns the `-where` arguments for a bounded chunk or a one-authority smoke run.
186
+ */
187
+ function whereClause(options: ZoningIngestOptions): string[] {
188
+ const bounds: string[] = []
189
+
190
+ if (options.objectIDFrom !== undefined) {
191
+ bounds.push(`OBJECTID >= ${options.objectIDFrom}`)
192
+ }
193
+
194
+ if (options.objectIDTo !== undefined) {
195
+ bounds.push(`OBJECTID <= ${options.objectIDTo}`)
196
+ }
197
+
198
+ if (options.authorityCode !== undefined) {
199
+ bounds.push(`LA_CODE = '${options.authorityCode.replaceAll("'", "''")}'`)
200
+ }
201
+
202
+ return bounds.length ? ["-where", bounds.join(" AND ")] : []
203
+ }
204
+
205
+ /**
206
+ * Returns the value, or null when it is undefined or empty.
207
+ */
208
+ function blankToNull(value: string | undefined): string | null {
209
+ if (value === undefined) return null
210
+
211
+ return value.length ? value : null
212
+ }
213
+
214
+ /**
215
+ * Streams the export through ogr2ogr as reprojected WKT and checks every vertex against the declared extent.
216
+ *
217
+ * The extent check catches swapped coordinate axes.
218
+ * The projection check misses that error.
219
+ *
220
+ * @throws {Error} When ogr2ogr fails, when a feature has no geometry or a blank local code, when
221
+ * a reprojected vertex falls outside the declared extent, or when a feature's rings have no exterior.
222
+ */
223
+ export async function* readZoningFeatures(options: ZoningIngestOptions): AsyncGenerator<ZoningSourceFeature> {
224
+ const [minLon, minLat, maxLon, maxLat] = options.declaredBBox ?? GZT_DECLARED_BBOX
225
+
226
+ const args = [
227
+ "-f",
228
+ "CSV",
229
+ "/vsistdout/",
230
+ "-t_srs",
231
+ "EPSG:4326",
232
+ "-lco",
233
+ "GEOMETRY=AS_WKT",
234
+ "-lco",
235
+ "CREATE_CSVT=NO",
236
+ "-lco",
237
+ `COORDINATE_PRECISION=${COORDINATE_PRECISION}`,
238
+ "-select",
239
+ ZONING_SOURCE_FIELDS.join(","),
240
+ ...whereClause(options),
241
+ ...(options.limit === undefined ? [] : ["-limit", String(options.limit)]),
242
+ options.exportPath,
243
+ ]
244
+
245
+ const proc = spawnOGR2OGR(args, "zoning ingest")
246
+
247
+ try {
248
+ for await (const row of CSVSpliterator.fromAsync<Record<string, string>>(proc.stdout)) {
249
+ const areaID = row.objectid ?? ""
250
+
251
+ if (!areaID) {
252
+ throw new Error("zoning ingest: a row carries no OBJECTID — the authority's own key is the artifact's key")
253
+ }
254
+
255
+ const wkt = row.wkt
256
+
257
+ if (!wkt) {
258
+ throw new Error(`zoning ingest: feature ${areaID} carries no geometry`)
259
+ }
260
+
261
+ const polygons = normalizePolygons(wkt, `feature ${areaID}`)
262
+
263
+ assertRingsInsideExtent(
264
+ polygons,
265
+ `feature ${areaID}`,
266
+ { minLon, minLat, maxLon, maxLat },
267
+ BBOX_MARGIN_DEGREES,
268
+ "zoning ingest"
269
+ )
270
+
271
+ const localCode = row.zone_orig ?? ""
272
+
273
+ // The authority never publishes a zone without a code, so a blank code is an error.
274
+ if (!localCode) {
275
+ throw new Error(
276
+ `zoning ingest: feature ${areaID} carries a blank ZONE_ORIG — the authority's own code is the claim, so a blank is refused rather than stored`
277
+ )
278
+ }
279
+
280
+ yield {
281
+ areaID,
282
+ authorityCode: row.la_code ?? "",
283
+ authorityName: row.la_name ?? "",
284
+ planID: row.plan_id ?? "",
285
+ planName: row.plan_name ?? "",
286
+ planLevel: row.plan_level ?? "",
287
+ planFrom: blankToNull(row.plan_from),
288
+ planTo: blankToNull(row.plan_to),
289
+ currentPlan: Number(row.current_plan ?? 0),
290
+ // The code stays untrimmed because some distinct codes differ only by case or a trailing space.
291
+ localCode,
292
+ localDescription: blankToNull(row.zone_desc),
293
+ localCodeURL: blankToNull(row.zone_link),
294
+ crosswalkCode: blankToNull(row.zone_gzt),
295
+ crosswalkDescription: blankToNull(row.gzt_desc),
296
+ crosswalkRollup: blankToNull(row.szo),
297
+ rings: resolveRingRoles(polygons, areaID),
298
+ }
299
+ }
300
+ } finally {
301
+ proc.kill()
302
+ }
303
+
304
+ await proc.settled
305
+ }
306
+
307
+ /**
308
+ * Parses one WKT geometry into `MultiPolygon` rings.
309
+ *
310
+ * @throws {Error} When the geometry is neither a `Polygon` nor a `MultiPolygon`.
311
+ */
312
+ function normalizePolygons(wkt: string, label: string): MultiPolygonRings {
313
+ const geometry = wellKnownGeometryToGeoJSON<{ type: string; coordinates: unknown }>(wkt)
314
+
315
+ return requireArealPolygons(geometry, label, "zoning ingest")
316
+ }
317
+
318
+ /**
319
+ * Supplies a zoning build with its features and the source's declared identity.
320
+ *
321
+ * The builder takes this instead of a path so that fixtures can run the database
322
+ * build without network access or GDAL.
323
+ */
324
+ export interface ZoningFeatureSource {
325
+ /**
326
+ * The feature count that the source declares.
327
+ *
328
+ * The build throws when its streamed total differs from this count.
329
+ */
330
+ declaredFeatureCount: number
331
+ epsg: number
332
+ /**
333
+ * A description of where the features came from, such as the export path.
334
+ */
335
+ origin: string
336
+ features: () => AsyncIterable<ZoningSourceFeature>
337
+ }
338
+
339
+ /**
340
+ * Options for {@link createExportFeatureSource}.
341
+ */
342
+ export interface ExportSourceOptions extends ZoningIngestOptions {
343
+ declaredFeatureCount?: number
344
+ }
345
+
346
+ /**
347
+ * Creates a {@link ZoningFeatureSource} for the bulk export.
348
+ *
349
+ * It reads the export's identity immediately and streams features when asked.
350
+ */
351
+ export async function createExportFeatureSource(options: ExportSourceOptions): Promise<ZoningFeatureSource> {
352
+ const identity = await readZoningSourceIdentity(options)
353
+
354
+ return {
355
+ // The caller supplies the count for a range or one authority, because
356
+ // `ogrinfo` reports only the layer's total.
357
+ declaredFeatureCount: declaredFeatureCount({
358
+ declared: options.declaredFeatureCount,
359
+ limit: options.limit,
360
+ layerCount: identity.featureCount,
361
+ }),
362
+ epsg: identity.epsg,
363
+ origin: options.exportPath,
364
+ features: () => readZoningFeatures(options),
365
+ }
366
+ }
@@ -3,23 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * The index resolution is a MEASUREMENT this layer takes, not a number argued to — and for this subject the
7
- * inherited size contract's own statistic is not the one that decides it.
8
- *
9
- * THE `partial` SHARE CARRIES NO SIGNAL HERE, AND THAT WAS MEASURED. Computed over all 85,330 Irish
10
- * features, the median zoning polygon is 4,497 m² against an average res-9 cell of 105,333 m²: 95.7% of
11
- * them are smaller than a res-9 cell, 75.1% smaller than a res-10 cell and 34.5% smaller than a res-11 one.
12
- * So the `partial` share sits near 100% at every candidate and cannot choose between them.
13
- *
14
- * TWO NUMBERS CAN. CANDIDATES PER CELL is what a probe pays — a cell naming eight polygons is eight
15
- * bounding-box tests and up to eight ray casts — and the POLYFILL-ONLY ZERO-CELL COUNT is how many features
16
- * the obvious index would have dropped, each of which would read downstream as an absence of zoning. Both
17
- * are reported per resolution and the `partial` share rides beside them.
18
- *
19
- * ONE STREAM, EVERY RESOLUTION. Re-reading the export per candidate costs a full pass each and buys
20
- * nothing — the classification is per feature, so every candidate index folds the same feature in turn. The
21
- * cost is memory: each resolution holds its own cell sets, and the finest candidate dominates. A caller that
22
- * runs out of headroom runs the candidates in separate invocations.
6
+ * The `partial` share cannot choose between candidate resolutions, so each is reported by candidates per cell and by the polyfill-only zero-cell count.
23
7
  */
24
8
 
25
9
  import type { ResolutionMeasurementOptions } from "@mailwoman/core/layers"
@@ -30,9 +14,8 @@ import { readZoningFeatures, readZoningSourceIdentity, type ZoningIngestOptions
30
14
 
31
15
  export interface MeasureResolutionsOptions extends ZoningIngestOptions, ResolutionMeasurementOptions {
32
16
  /**
33
- * Also run a centre-in-polygon polyfill per feature per resolution, to report what a polyfill-only index would have
34
- * dropped. On by default: it is the column the resolution is chosen on, and its cost is one extra h3 call per
35
- * feature.
17
+ * Also runs a center-in-polygon polyfill per feature per resolution at the
18
+ * cost of one extra h3 call per feature.
36
19
  */
37
20
  measurePolyfill?: boolean
38
21
  }
@@ -40,7 +23,8 @@ export interface MeasureResolutionsOptions extends ZoningIngestOptions, Resoluti
40
23
  export interface ResolutionMeasurementReport {
41
24
  features: number
42
25
  /**
43
- * The count the source declares for itself. A run whose streamed total differs read a truncated file.
26
+ * The count the source declares for itself.
27
+ * A run whose streamed total differs read a truncated file.
44
28
  */
45
29
  declaredFeatureCount: number
46
30
  measurements: CellIndexMeasurement[]
@@ -51,8 +35,7 @@ const DEFAULT_PROGRESS_EVERY = 5000
51
35
  /**
52
36
  * Measure every candidate resolution over the real source.
53
37
  *
54
- * @throws {Error} When the streamed feature count does not match the count the source declares. A short read produces a
55
- * well-formed table describing a smaller country, which is the partial result that must throw.
38
+ * @throws {Error} When the streamed feature count does not match the count the source declares.
56
39
  */
57
40
  export async function measureZoningCellResolutions(
58
41
  options: MeasureResolutionsOptions
@@ -80,8 +63,8 @@ export async function measureZoningCellResolutions(
80
63
  }
81
64
  }
82
65
 
83
- // A RANGE or an authority selector narrows the population on purpose, so the declared total is only a check on a whole
84
- // pass. Narrowed runs report what they read and assert nothing about it.
66
+ // A range or authority selector narrows the population on purpose,
67
+ // so the declared total is only checked on a whole pass.
85
68
  const narrowed =
86
69
  options.limit !== undefined || options.authorityCode !== undefined || options.objectIDFrom !== undefined
87
70