@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,276 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The cell index, and the measurement the index resolution is chosen from.
7
+ *
8
+ * THE CLASSIFIER ITSELF LIVES IN `@mailwoman/spatial`, re-exported below so this package's call sites and
9
+ * its `@mailwoman/zoning/sdk/cells` subpath keep reading the same. `classifyFeatureCells`, the per-PART
10
+ * zero-cell guard and the allocator-avoiding shortcuts around it are properties of h3-js rather than of
11
+ * this product — the layer contract's polygon-builder section states them as requirements on EVERY polygon
12
+ * builder — and a second copy of the zero-cell guard is a second place for it to stop guarding.
13
+ *
14
+ * WHAT THIS LAYER ADDS IS THE NUMBER THE RESOLUTION IS ACTUALLY CHOSEN FROM, AND IT IS NOT THE `partial`
15
+ * SHARE. The inherited size contract picks a resolution from the measured `partial` share, and for this
16
+ * subject that statistic carries no signal: computed over all 85,330 Irish features, the median zoning
17
+ * polygon is 4,497 m² against an average res-9 cell of 105,333 m², so 95.7% of them are smaller than a cell
18
+ * and the `partial` share is near 100% at every candidate. Two numbers do carry signal —
19
+ * CANDIDATES PER CELL, which is how much geometry a probe reads, and the POLYFILL-ONLY ZERO-CELL COUNT,
20
+ * which is how many features a centre-in-polygon index would have dropped — so both are measured here and
21
+ * the `partial` share is reported beside them rather than in place of them.
22
+ *
23
+ * THE ZERO-CELL COUNT IS A MEASUREMENT OF THE ALTERNATIVE, NOT OF THIS INDEX. `classifyFeatureCells` takes
24
+ * overlapping containment and REFUSES a feature that reaches no cell, so this index's own zero-cell count is
25
+ * zero by construction. What the column reports is what `polygonToCells` — the centre-in-polygon polyfill a
26
+ * builder reaches for first — would have returned nothing for, and every one of those would have read
27
+ * downstream as an absence of zoning.
28
+ */
29
+
30
+ import { compactAcrossResolutions, shortCellToInt, type FeatureCells, type H3Cell } from "@mailwoman/spatial"
31
+ import { polygonToCells } from "h3-js"
32
+
33
+ import type { MultiPolygonRings } from "#rings"
34
+
35
+ export {
36
+ addCoverageCells,
37
+ CELL_ESTIMATE_BUDGET,
38
+ classifyFeatureCells,
39
+ coverageCellFor,
40
+ estimateCellCount,
41
+ featureCellRows,
42
+ MIN_INDEX_RESOLUTION,
43
+ resolutionForFeature,
44
+ type FeatureCells,
45
+ } from "@mailwoman/spatial"
46
+
47
+ /**
48
+ * Would a CENTRE-IN-POLYGON polyfill return nothing for this feature?
49
+ *
50
+ * The measurement that forced this layer's index to take cell-touches-polygon: at resolution 9 `polygonToCells` returns
51
+ * an empty set for the great majority of Irish zoning polygons, because no cell centre falls inside them. A builder
52
+ * indexing only the polyfill output would drop every one of them silently.
53
+ */
54
+ export function polyfillFindsNothing(polygons: MultiPolygonRings, resolution: number): boolean {
55
+ for (const rings of polygons) {
56
+ // `isGeoJSON = true`: the rings are already `[lon, lat]`, which is the order the ingest emits.
57
+ if (polygonToCells(rings as number[][][], resolution, true).length) return false
58
+ }
59
+
60
+ return true
61
+ }
62
+
63
+ /**
64
+ * What one resolution came out as over the whole set — the numbers the resolution choice is made from.
65
+ */
66
+ export interface CellIndexMeasurement {
67
+ resolution: number
68
+ features: number
69
+ /**
70
+ * Cells the layer reaches at all.
71
+ */
72
+ touchedCells: number
73
+ /**
74
+ * Cells answered by the index alone, before compaction.
75
+ */
76
+ wholeCells: number
77
+ /**
78
+ * Cells needing the ray cast.
79
+ */
80
+ partialCells: number
81
+ /**
82
+ * `partialCells / touchedCells`. Reported, and NOT what the resolution is chosen on — see this file's header.
83
+ */
84
+ partialShare: number
85
+ /**
86
+ * Whole cells after per-feature `compactCells` — the rows actually stored on the whole side.
87
+ */
88
+ compactedWholeCells: number
89
+ /**
90
+ * Cell rows the artifact would store at this resolution: the compacted whole rows plus the partial rows.
91
+ */
92
+ storedCellRows: number
93
+ /**
94
+ * How many polygons name a cell, over the cells the layer reaches. This is what a probe pays: a cell naming eight
95
+ * candidates is eight bounding-box tests and up to eight ray casts.
96
+ */
97
+ candidatesPerCell: { mean: number; p90: number; max: number }
98
+ /**
99
+ * Cells naming more than one polygon, and their share of the touched cells.
100
+ */
101
+ multiCandidateCells: number
102
+ multiCandidateShare: number
103
+ /**
104
+ * Features a centre-in-polygon polyfill would have returned NOTHING for — see {@link polyfillFindsNothing}.
105
+ * `undefined` where the measurement did not run it.
106
+ */
107
+ polyfillZeroCellFeatures?: number
108
+ /**
109
+ * Features whose bounding box forced a coarser resolution than the target — see `CELL_ESTIMATE_BUDGET`.
110
+ */
111
+ coarsenedFeatures: number
112
+ /**
113
+ * Features this index returned no cell for. ZERO BY CONSTRUCTION: `classifyFeatureCells` throws rather than returning
114
+ * an empty set, so a non-zero value here means the guard was bypassed.
115
+ */
116
+ zeroCellFeatures: number
117
+ }
118
+
119
+ /**
120
+ * Accumulate one resolution's cell index over a stream of features.
121
+ *
122
+ * The whole set is held as short-cell STRINGS rather than the integers the tables store, because `compactCells` is an
123
+ * h3-js function over full indexes and round-tripping at every step would cost more than the strings do. The candidate
124
+ * counter is keyed by the 48-bit INTEGER instead: it is the larger of the two at every candidate resolution, and it is
125
+ * never handed back to h3.
126
+ */
127
+ export class ZoningCellIndex {
128
+ readonly resolution: number
129
+
130
+ readonly #whole = new Set<string>()
131
+ readonly #wholeShort = new Set<number>()
132
+ readonly #candidates = new Map<number, number>()
133
+
134
+ #features = 0
135
+ #coarsened = 0
136
+ #zeroCell = 0
137
+ #polyfillZeroCell = 0
138
+ #measuredPolyfill = false
139
+
140
+ constructor(resolution: number) {
141
+ this.resolution = resolution
142
+ }
143
+
144
+ /**
145
+ * Fold one feature's classification in.
146
+ */
147
+ add(cells: FeatureCells): void {
148
+ this.#features++
149
+
150
+ if (cells.resolution !== this.resolution) {
151
+ this.#coarsened++
152
+ }
153
+
154
+ if (!cells.whole.length && !cells.partial.length) {
155
+ this.#zeroCell++
156
+ }
157
+
158
+ for (const cell of cells.whole) {
159
+ this.#whole.add(cell)
160
+ this.#wholeShort.add(shortCellToInt(cell))
161
+ this.#count(cell)
162
+ }
163
+
164
+ for (const cell of cells.partial) {
165
+ this.#count(cell)
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Record that a centre-in-polygon polyfill found nothing for one feature.
171
+ */
172
+ addPolyfillProbe(foundNothing: boolean): void {
173
+ this.#measuredPolyfill = true
174
+
175
+ if (foundNothing) {
176
+ this.#polyfillZeroCell++
177
+ }
178
+ }
179
+
180
+ /**
181
+ * The measurement.
182
+ *
183
+ * The compacted count is an approximation of what the build stores and is reported as one: the build compacts each
184
+ * FEATURE's whole set, while this compacts the union of them. The union can only compact at least as far, so this is
185
+ * a lower bound on the stored row count — the direction a size estimate should err in — and the build's own receipt
186
+ * reports the real number.
187
+ */
188
+ finish(): CellIndexMeasurement {
189
+ const compacted = compactAcrossResolutions(this.#whole).length
190
+
191
+ const counts: number[] = []
192
+ let total = 0
193
+ let max = 0
194
+ let multi = 0
195
+ let partial = 0
196
+
197
+ for (const [cell, count] of this.#candidates) {
198
+ counts.push(count)
199
+ total += count
200
+
201
+ if (count > max) {
202
+ max = count
203
+ }
204
+
205
+ if (count > 1) {
206
+ multi++
207
+ }
208
+
209
+ if (!this.#wholeShort.has(cell)) {
210
+ partial++
211
+ }
212
+ }
213
+
214
+ counts.sort((left, right) => left - right)
215
+
216
+ const touched = this.#candidates.size
217
+
218
+ return {
219
+ resolution: this.resolution,
220
+ features: this.#features,
221
+ touchedCells: touched,
222
+ wholeCells: this.#whole.size,
223
+ partialCells: partial,
224
+ partialShare: touched ? partial / touched : 0,
225
+ compactedWholeCells: compacted,
226
+ storedCellRows: compacted + partial,
227
+ candidatesPerCell: {
228
+ mean: touched ? total / touched : 0,
229
+ // Nearest-rank p90 over the candidate counts, which is the shape `@mailwoman/core/stats` uses.
230
+ p90: counts.length ? counts[Math.min(counts.length - 1, Math.ceil(0.9 * counts.length) - 1)]! : 0,
231
+ max,
232
+ },
233
+ multiCandidateCells: multi,
234
+ multiCandidateShare: touched ? multi / touched : 0,
235
+ ...(this.#measuredPolyfill ? { polyfillZeroCellFeatures: this.#polyfillZeroCell } : {}),
236
+ coarsenedFeatures: this.#coarsened,
237
+ zeroCellFeatures: this.#zeroCell,
238
+ }
239
+ }
240
+
241
+ #count(cell: H3Cell): void {
242
+ const short = shortCellToInt(cell)
243
+
244
+ this.#candidates.set(short, (this.#candidates.get(short) ?? 0) + 1)
245
+ }
246
+ }
247
+
248
+ /**
249
+ * The measurement as markdown table ROWS — what a build receipt carries, one line per element so a caller printing them
250
+ * never has to split a joined string back apart.
251
+ *
252
+ * THE ZERO-CELL COLUMN IS FIRST AFTER THE COUNTS, because it is the column the resolution is chosen on and the one a
253
+ * reader most needs to see is not zero for the alternative index.
254
+ */
255
+ export function formatResolutionRows(measurements: readonly CellIndexMeasurement[]): string[] {
256
+ return [
257
+ "| res | features | polyfill-only zero-cell | stored cell rows | touched cells | candidates/cell mean | p90 | max | cells >1 candidate | partial share | coarsened |",
258
+ "| --- | -------- | ----------------------- | ---------------- | ------------- | -------------------- | --- | --- | ------------------ | ------------- | --------- |",
259
+ ...measurements.map(
260
+ (measurement) =>
261
+ `| ${measurement.resolution} | ${measurement.features.toLocaleString()} | ` +
262
+ `${
263
+ measurement.polyfillZeroCellFeatures === undefined
264
+ ? "not measured"
265
+ : `${measurement.polyfillZeroCellFeatures.toLocaleString()} (${(
266
+ (measurement.polyfillZeroCellFeatures / Math.max(1, measurement.features)) *
267
+ 100
268
+ ).toFixed(1)}%)`
269
+ } | ` +
270
+ `${measurement.storedCellRows.toLocaleString()} | ${measurement.touchedCells.toLocaleString()} | ` +
271
+ `${measurement.candidatesPerCell.mean.toFixed(2)} | ${measurement.candidatesPerCell.p90} | ${measurement.candidatesPerCell.max} | ` +
272
+ `${measurement.multiCandidateCells.toLocaleString()} (${(measurement.multiCandidateShare * 100).toFixed(1)}%) | ` +
273
+ `${(measurement.partialShare * 100).toFixed(1)}% | ${measurement.coarsenedFeatures.toLocaleString()} |`
274
+ ),
275
+ ]
276
+ }
@@ -0,0 +1,335 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The Department's ArcGIS item, its feature service and the Hub download job, read through
7
+ * {@linkcode APIClient}.
8
+ *
9
+ * THESE ARE API REQUESTS AND THEY GO THROUGH `APIClient`. Small bodies, repeated calls, a third-party
10
+ * host — the pacing, bounded retry, response caching and `ResourceError` mapping are exactly what they
11
+ * need. The 247 MB bulk export is NOT one of them: it is a file transfer, it streams to disk on raw
12
+ * `fetch`, and `download.ts` says so in place.
13
+ *
14
+ * FOUR MEASURED CLIENT BEHAVIORS ARE ENCODED HERE RATHER THAN WRITTEN DOWN SOMEWHERE ELSE.
15
+ *
16
+ * 1. THE HUB DOWNLOAD JOB ANSWERS WITH A `resultUrl` THAT 302s. `…/api/download/v1/items/<id>/geojson?
17
+ * redirect=false&layers=0` returns `{"status":"Completed","resultUrl":…}` in 249 bytes; the result URL
18
+ * itself redirects, so the transfer needs `redirect: "follow"`. A client that took the first response as
19
+ * the file writes a redirect page to disk and reports a successful download.
20
+ * 2. THE BULK EXPORT IS EPSG:2157 UNDER A `crs` MEMBER RFC 7946 REMOVED. The file's own header carries
21
+ * `"crs":{"type":"name","properties":{"name":"EPSG:2157"}}` and its coordinates are Irish Transverse
22
+ * Mercator metres. A strict RFC 7946 reader ignores the member and places Ireland at latitude 735,435;
23
+ * GDAL honours it, which is why `sdk/ingest.ts` reads the archive through ogr2ogr and asserts the
24
+ * reprojected result lands inside the Department's own declared extent.
25
+ * 3. THE PUBLISHER'S OWN AREA STATISTIC IS NOT IN THE ARCHIVE. `Shape__Area` is a service field and the
26
+ * GeoJSON export drops it, so the area cross-check has to come from {@linkcode readShapeAreaSum} — which
27
+ * makes it a genuine two-path check rather than the archive agreeing with itself. Measured:
28
+ * 5,444,492,956.40 m² over 85,330 features.
29
+ * 4. `GZT_LINK` POINTS AT A HOST WITH NO DNS RECORD. All 85,330 rows link their generic type's definition to
30
+ * `viewer.myplan.ie`, which has no A or AAAA record, and three candidate replacements on the live host
31
+ * answer HTTP 404. So `zoning_vocabulary.definition_url` cannot be populated from it and is left NULL
32
+ * rather than filled with a plausible one.
33
+ */
34
+
35
+ import { APIClient, type APIClientConfig } from "@mailwoman/core/api"
36
+ import { createPacedCachedClient, type CreatePacedCachedClientOptions } from "@mailwoman/core/api/paced-client"
37
+ import { htmlToText } from "@mailwoman/core/html/text"
38
+
39
+ import { GZT_ATTRIBUTION, GZT_ITEM_ID, GZT_SERVICE_URL, GZT_SOURCE_EPSG } from "#vocabulary"
40
+
41
+ // Re-exported so a caller branching on this client's failures needs exactly one import.
42
+ export { isTransientResourceError } from "@mailwoman/core/api"
43
+ export { ResourceError } from "@mailwoman/core/errors"
44
+
45
+ /**
46
+ * The ArcGIS Online sharing API, where the item's licence and attribution fields are readable.
47
+ */
48
+ export const ARCGIS_ITEM_API_BASE_URL = "https://www.arcgis.com/sharing/rest/content/items"
49
+
50
+ /**
51
+ * The Hub download API, which is how the whole layer is exported in one file.
52
+ */
53
+ export const HUB_DOWNLOAD_API_BASE_URL = "https://hub.arcgis.com/api/download/v1/items"
54
+
55
+ /**
56
+ * Minimum spacing between requests to the Department's hosts, in milliseconds.
57
+ *
58
+ * The Department publishes no rate limit for this service, so this is courtesy pacing rather than a published ceiling —
59
+ * stated as such rather than dressed up as a measured limit. Two requests a second is far below anything a hosted
60
+ * ArcGIS feature service is provisioned for and costs a build nothing: the acquisition path makes single-digit numbers
61
+ * of calls and the verification a few dozen.
62
+ */
63
+ export const GZT_MIN_REQUEST_INTERVAL_MS = 500
64
+
65
+ /**
66
+ * How long a cached metadata response stays fresh.
67
+ *
68
+ * Six hours, chosen against the product's own cadence rather than a wall-clock intuition. The Department publishes no
69
+ * maintenance-frequency statement at all; what is observable is that the item's `modified` date and the data's latest
70
+ * `UPLOAD_DATE` move a handful of times a year, so a shorter TTL buys nothing.
71
+ */
72
+ const GZT_CACHE_TTL_MS = 6 * 60 * 60 * 1000
73
+
74
+ export type CreateZoningClientOptions = CreatePacedCachedClientOptions
75
+
76
+ /**
77
+ * What the item says about the product.
78
+ */
79
+ export interface ZoningItemRecord {
80
+ itemID: string
81
+ title: string
82
+ /**
83
+ * The item's `modified` timestamp as an ISO date — the product vintage, and the freshness signal.
84
+ */
85
+ modifiedDate: string
86
+ /**
87
+ * `accessInformation`, verbatim: the credit line the Department asks for.
88
+ */
89
+ accessInformation: string
90
+ /**
91
+ * `licenseInfo`, verbatim, with its markup stripped. Read rather than trusted from the constant, so a change in the
92
+ * terms is visible at build time.
93
+ */
94
+ licenseInfo: string
95
+ /**
96
+ * The extent the item declares, in CRS84 order.
97
+ */
98
+ declaredBBox: [number, number, number, number]
99
+ }
100
+
101
+ /**
102
+ * Ordinates in a CRS84 bounding box: `minLon, minLat, maxLon, maxLat`.
103
+ */
104
+ const BBOX_ORDINATES = 4
105
+
106
+ /**
107
+ * A client for the Department's item, feature service and Hub download job.
108
+ */
109
+ export class GZTClient extends APIClient<APIClientConfig> {
110
+ /**
111
+ * The item record: its vintage, its credit line, its licence text and its declared extent.
112
+ *
113
+ * @throws {Error} When the item is missing, or declares no extent.
114
+ */
115
+ public async readItemRecord(): Promise<ZoningItemRecord> {
116
+ const { data } = await this.fetch<{
117
+ id?: string
118
+ title?: string
119
+ modified?: number
120
+ accessInformation?: string | null
121
+ licenseInfo?: string | null
122
+ extent?: number[][]
123
+ }>({
124
+ method: "GET",
125
+ url: `${ARCGIS_ITEM_API_BASE_URL}/${GZT_ITEM_ID}`,
126
+ params: { f: "json" },
127
+ })
128
+
129
+ if (data.id !== GZT_ITEM_ID) {
130
+ throw new Error(
131
+ `zoning client: the item endpoint answered for ${JSON.stringify(data.id)}, expected ${GZT_ITEM_ID}`
132
+ )
133
+ }
134
+
135
+ if (typeof data.modified !== "number") {
136
+ throw new TypeError(
137
+ "zoning client: the item carries no `modified` timestamp — the product vintage cannot be read, and guessing it would stamp an artifact with a version that means nothing"
138
+ )
139
+ }
140
+
141
+ const extent = data.extent
142
+
143
+ if (!extent || extent.length < 2 || !extent[0] || !extent[1]) {
144
+ throw new TypeError("zoning client: the item declares no extent")
145
+ }
146
+
147
+ const bbox: [number, number, number, number] = [extent[0][0]!, extent[0][1]!, extent[1][0]!, extent[1][1]!]
148
+
149
+ if (bbox.some((ordinate) => !Number.isFinite(ordinate)) || bbox.length !== BBOX_ORDINATES) {
150
+ throw new TypeError(`zoning client: the item's extent is not a 2D bounding box (${JSON.stringify(extent)})`)
151
+ }
152
+
153
+ return {
154
+ itemID: data.id,
155
+ title: data.title ?? "",
156
+ modifiedDate: new Date(data.modified).toISOString().slice(0, 10),
157
+ accessInformation: data.accessInformation ?? "",
158
+ licenseInfo: htmlToText(data.licenseInfo ?? ""),
159
+ declaredBBox: bbox,
160
+ }
161
+ }
162
+
163
+ /**
164
+ * The feature count the service reports, and the EPSG code it declares.
165
+ *
166
+ * The SECOND path in the build's agreement check: the same authority, a different distribution channel. An archive
167
+ * whose feature count disagrees with the live service is not a file this build should be writing into a sealed
168
+ * artifact.
169
+ */
170
+ public async readServiceIdentity(): Promise<{ featureCount: number; epsg: number; maxRecordCount: number }> {
171
+ const { data } = await this.fetch<{
172
+ extent?: { spatialReference?: { wkid?: number; latestWkid?: number } }
173
+ maxRecordCount?: number
174
+ }>({ method: "GET", url: GZT_SERVICE_URL, params: { f: "json" } })
175
+
176
+ const epsg = data.extent?.spatialReference?.latestWkid ?? data.extent?.spatialReference?.wkid
177
+
178
+ if (epsg !== GZT_SOURCE_EPSG) {
179
+ throw new Error(
180
+ `zoning client: the service declares EPSG:${epsg}, expected EPSG:${GZT_SOURCE_EPSG} — the source's projection changed, which is a product change rather than a variation to absorb`
181
+ )
182
+ }
183
+
184
+ const { data: counted } = await this.fetch<{ count?: number }>({
185
+ method: "GET",
186
+ url: `${GZT_SERVICE_URL}/query`,
187
+ params: { where: "1=1", returnCountOnly: "true", f: "json" },
188
+ })
189
+
190
+ if (typeof counted.count !== "number") {
191
+ throw new TypeError("zoning client: the service returned no feature count")
192
+ }
193
+
194
+ return { featureCount: counted.count, epsg, maxRecordCount: data.maxRecordCount ?? 0 }
195
+ }
196
+
197
+ /**
198
+ * The sum of the Department's own `Shape__Area` column, in square metres.
199
+ *
200
+ * THE ONE NUMBER THAT SETTLES THE HOLE QUESTION, and it has to come from the service because the bulk export drops
201
+ * the column. Read with the holes the rings total 5,444.5 km²; read without them, 5,666.6 km². The difference is 4.1%
202
+ * of area and, far more importantly, a ray cast that answers "inside" for every location a plan carved out.
203
+ */
204
+ public async readShapeAreaSum(): Promise<number> {
205
+ const { data } = await this.fetch<{ features?: Array<{ attributes?: Record<string, number> }> }>({
206
+ method: "GET",
207
+ url: `${GZT_SERVICE_URL}/query`,
208
+ params: {
209
+ where: "1=1",
210
+ outStatistics: JSON.stringify([
211
+ { statisticType: "sum", onStatisticField: "Shape__Area", outStatisticFieldName: "area_sum" },
212
+ ]),
213
+ f: "json",
214
+ },
215
+ })
216
+
217
+ const sum = data.features?.[0]?.attributes?.area_sum
218
+
219
+ if (typeof sum !== "number" || !Number.isFinite(sum)) {
220
+ throw new TypeError(
221
+ "zoning client: the service returned no Shape__Area sum — without the publisher's own figure the hole-orientation check has nothing to compare against, and reading every ring as an exterior is silent"
222
+ )
223
+ }
224
+
225
+ return sum
226
+ }
227
+
228
+ /**
229
+ * Ask the Hub for a bulk GeoJSON export and return the URL it answers with.
230
+ *
231
+ * `redirect=false` asks for the job record rather than a redirect, so this call reads a small JSON body. The URL it
232
+ * returns is the one that 302s — see {@link downloadZoningExport}.
233
+ *
234
+ * @throws {Error} When the job is not `Completed`, or names no result URL. A partial job that answered with a status
235
+ * and no URL would otherwise present as an empty download.
236
+ */
237
+ public async readExportURL(): Promise<string> {
238
+ const { data } = await this.fetch<{ status?: string; resultUrl?: string; message?: string }>({
239
+ method: "GET",
240
+ url: `${HUB_DOWNLOAD_API_BASE_URL}/${GZT_ITEM_ID}/geojson`,
241
+ params: { redirect: "false", layers: "0" },
242
+ })
243
+
244
+ if (data.status !== "Completed" || !data.resultUrl) {
245
+ throw new Error(
246
+ `zoning client: the Hub download job answered status ${JSON.stringify(data.status)} with ${
247
+ data.resultUrl ? "a" : "no"
248
+ } result URL${data.message ? ` (${data.message})` : ""}`
249
+ )
250
+ }
251
+
252
+ return data.resultUrl
253
+ }
254
+
255
+ /**
256
+ * The features the service publishes near a point — the verification's second path.
257
+ *
258
+ * `outSR=4326` on the query path, because the service answers in Irish Transverse Mercator otherwise and the
259
+ * comparison is against coordinates this package reprojected itself. The service answers a bounding box rather than a
260
+ * point, so the containment decision is made against the returned rings by the caller.
261
+ */
262
+ public async readFeaturesNear(
263
+ latitude: number,
264
+ longitude: number,
265
+ halfWidthDegrees: number
266
+ ): Promise<Array<{ properties?: Record<string, unknown>; geometry?: { type: string; coordinates: unknown } }>> {
267
+ const { data } = await this.fetch<{
268
+ features?: Array<{ properties?: Record<string, unknown>; geometry?: { type: string; coordinates: unknown } }>
269
+ }>({
270
+ method: "GET",
271
+ url: `${GZT_SERVICE_URL}/query`,
272
+ params: {
273
+ geometry: JSON.stringify({
274
+ xmin: longitude - halfWidthDegrees,
275
+ ymin: latitude - halfWidthDegrees,
276
+ xmax: longitude + halfWidthDegrees,
277
+ ymax: latitude + halfWidthDegrees,
278
+ spatialReference: { wkid: 4326 },
279
+ }),
280
+ geometryType: "esriGeometryEnvelope",
281
+ inSR: "4326",
282
+ outSR: "4326",
283
+ spatialRel: "esriSpatialRelIntersects",
284
+ outFields: "OBJECTID,ZONE_ORIG,ZONE_GZT,LA_CODE",
285
+ returnGeometry: "true",
286
+ f: "geojson",
287
+ },
288
+ })
289
+
290
+ return data.features ?? []
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Refuse an attribution the published item no longer matches.
296
+ *
297
+ * READ AT BUILD TIME RATHER THAN TRUSTED FROM THE CONSTANT. The constant is what the artifact is stamped with offline;
298
+ * this is the live value it is reconciled with when the network is available. The check is on the DEPARTMENT'S CREDIT
299
+ * LINE and on the Tailte Éireann clause separately, because they are two different statements and the second is the one
300
+ * that holds this layer at `build-local`: an item that dropped it would be a licence change worth hearing about, and an
301
+ * item that dropped only the credit line would be a different one.
302
+ *
303
+ * @throws {Error} When either half of {@link GZT_ATTRIBUTION} is no longer in the item's own fields.
304
+ */
305
+ export function assertAttributionUnchanged(record: Pick<ZoningItemRecord, "accessInformation" | "licenseInfo">): void {
306
+ if (!GZT_ATTRIBUTION.includes(record.accessInformation.trim()) || !record.accessInformation.trim()) {
307
+ throw new Error(
308
+ `zoning client: the item's accessInformation reads ${JSON.stringify(record.accessInformation)}, and this build ships ` +
309
+ `${JSON.stringify(GZT_ATTRIBUTION)} — the credit line is what a re-user has to publish, so a change in it is a change in the terms`
310
+ )
311
+ }
312
+
313
+ if (!record.licenseInfo.includes("Tailte Éireann")) {
314
+ throw new Error(
315
+ "zoning client: the item's licenseInfo no longer names Tailte Éireann as a licensor. That clause is the reason " +
316
+ "this layer is built locally rather than shipped, so its disappearance is a licence change to read rather than absorb"
317
+ )
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Build a {@link GZTClient} with the disk cache and pacing this package's acquisition path expects.
323
+ */
324
+ export function createGZTClient(options: CreateZoningClientOptions = {}): GZTClient {
325
+ return createPacedCachedClient(
326
+ GZTClient,
327
+ {
328
+ displayName: "GZT",
329
+ minRequestIntervalMs: GZT_MIN_REQUEST_INTERVAL_MS,
330
+ cacheTTLMs: GZT_CACHE_TTL_MS,
331
+ cacheDirectory: ["zoning", "cache", "http"],
332
+ },
333
+ options
334
+ )
335
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Acquire the Department's bulk GeoJSON export — a 247,452,342-byte file streamed to disk.
7
+ *
8
+ * THIS IS A FILE TRANSFER, NOT AN API REQUEST, AND IT KEEPS RAW `fetch` ON PURPOSE. The repo's rule sends
9
+ * HTTP clients through `@mailwoman/core/api`'s `APIClient`, and the rule draws its line at what that class
10
+ * is for: pacing, bounded retry, response caching and error mapping over small bodies and repeated calls.
11
+ * None of it applies here. Caching a 247 MB body through a JSON-validating disk cache would write a second,
12
+ * unreadable copy of a file already on disk; there is nothing to pace, because this runs once per product
13
+ * vintage; and axios buffers any non-stream response type in memory. `packages/osm/lib/sdk/fetch.ts`,
14
+ * `packages/tiger/lib/sdk/download.ts`, `packages/flood/lib/sdk/download.ts` and `packages/coastal/lib/sdk/download.ts`
15
+ * are the existing transfers that say the same thing in the same place. The JOB that produces this URL, and
16
+ * every other metadata read around it, DO go through `APIClient` — see `client.ts`.
17
+ *
18
+ * THE RESULT URL REDIRECTS AND THE FETCH MUST FOLLOW IT. The Hub download job answers
19
+ * `{"status":"Completed","resultUrl":…}`; the result URL itself 302s to the generated file. Node's `fetch`
20
+ * follows redirects by default, and the option is passed explicitly anyway — a transfer that stopped at the
21
+ * redirect would write a short body to disk and report a successful download.
22
+ *
23
+ * FRESHNESS IS THE ITEM'S OWN MODIFIED DATE, NEVER A LENGTH PROBE. The cache is keyed on the vintage the
24
+ * item declares, so a re-run against the same vintage never re-transfers and a new vintage never overwrites
25
+ * the old one in place.
26
+ */
27
+
28
+ import { tryStat } from "@mailwoman/core/fs/readers"
29
+ import { makeDirectories } from "@mailwoman/core/fs/writers"
30
+ import { streamToDisk } from "@mailwoman/core/utils"
31
+ import { join } from "path-ts"
32
+
33
+ /**
34
+ * The file name one vintage's export is kept under.
35
+ */
36
+ export const GZT_EXPORT_FILE = "gzt-current-plan.geojson"
37
+
38
+ export interface DownloadZoningExportOptions {
39
+ /**
40
+ * The Hub job's `resultUrl`, read rather than assembled — it carries a generated file id with no relationship to the
41
+ * item id, so a hard-coded URL survives a republish by pointing at a file that is no longer the product.
42
+ */
43
+ url: string
44
+ /**
45
+ * The product vintage the cache is keyed on.
46
+ */
47
+ vintage: string
48
+ cacheRoot: string
49
+ onProgress?: (message: string) => void
50
+ }
51
+
52
+ /**
53
+ * Download the bulk export for one product vintage, returning the path of the GeoJSON file.
54
+ *
55
+ * Downloads to a `.part` file and renames only on a clean finish, so an interrupted transfer never presents as a
56
+ * complete export — the same discipline the database build uses, for the same reason.
57
+ */
58
+ export async function downloadZoningExport(options: DownloadZoningExportOptions): Promise<string> {
59
+ const vintageDir = join(options.cacheRoot, options.vintage)
60
+ const exportPath = join(vintageDir, GZT_EXPORT_FILE)
61
+
62
+ if (await tryStat(exportPath)) {
63
+ options.onProgress?.(`export for ${options.vintage} already downloaded`)
64
+
65
+ return exportPath
66
+ }
67
+
68
+ await makeDirectories(vintageDir)
69
+
70
+ await streamToDisk({
71
+ url: options.url,
72
+ destination: exportPath,
73
+ context: "zoning download",
74
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
75
+ })
76
+
77
+ return exportPath
78
+ }