@mailwoman/spatial 9.1.0 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/{bbox.ts → lib/bbox.ts} +54 -3
  2. package/lib/coordinate-bounds.ts +52 -0
  3. package/{coordinate-formats.ts → lib/coordinate-formats.ts} +16 -3
  4. package/lib/distance.ts +165 -0
  5. package/{feature.ts → lib/feature.ts} +1 -1
  6. package/{geometries → lib/geometries}/collection.ts +4 -4
  7. package/lib/geometries/index.ts +13 -0
  8. package/{geometries → lib/geometries}/line-string.ts +2 -2
  9. package/{geometries → lib/geometries}/point.ts +9 -9
  10. package/{geometries → lib/geometries}/polygon.ts +93 -89
  11. package/lib/geometries/ring-blob.ts +521 -0
  12. package/{google → lib/google}/index.ts +1 -1
  13. package/{h3 → lib/h3}/cell.ts +83 -1
  14. package/lib/h3/coverage.ts +45 -0
  15. package/{h3 → lib/h3}/index.ts +5 -3
  16. package/lib/h3/interior-cells.ts +138 -0
  17. package/lib/h3/polygon-cells.ts +462 -0
  18. package/lib/index.ts +21 -0
  19. package/{objects.ts → lib/objects.ts} +1 -1
  20. package/lib/open-location-code.ts +168 -0
  21. package/{osgb36.ts → lib/osgb36.ts} +2 -2
  22. package/{polyline.ts → lib/polyline.ts} +1 -1
  23. package/lib/position.ts +216 -0
  24. package/lib/projection-transform.ts +115 -0
  25. package/{regions → lib/regions}/codes.ts +1 -1
  26. package/{regions → lib/regions}/index.ts +2 -2
  27. package/lib/tools/ogr-stream.ts +99 -0
  28. package/lib/tools/ogr.ts +201 -0
  29. package/{sdk → lib}/well-known-text.ts +2 -1
  30. package/out/bbox.d.ts +23 -2
  31. package/out/bbox.d.ts.map +1 -1
  32. package/out/bbox.js +33 -2
  33. package/out/bbox.js.map +1 -1
  34. package/out/coordinate-bounds.d.ts +41 -0
  35. package/out/coordinate-bounds.d.ts.map +1 -0
  36. package/out/coordinate-bounds.js +45 -0
  37. package/out/coordinate-bounds.js.map +1 -0
  38. package/out/coordinate-formats.d.ts +8 -0
  39. package/out/coordinate-formats.d.ts.map +1 -1
  40. package/out/coordinate-formats.js +14 -3
  41. package/out/coordinate-formats.js.map +1 -1
  42. package/out/distance.d.ts +84 -0
  43. package/out/distance.d.ts.map +1 -0
  44. package/out/distance.js +132 -0
  45. package/out/distance.js.map +1 -0
  46. package/out/feature.d.ts +1 -1
  47. package/out/feature.d.ts.map +1 -1
  48. package/out/feature.js.map +1 -1
  49. package/out/geometries/collection.d.ts +4 -4
  50. package/out/geometries/collection.d.ts.map +1 -1
  51. package/out/geometries/collection.js.map +1 -1
  52. package/out/geometries/index.d.ts +5 -4
  53. package/out/geometries/index.d.ts.map +1 -1
  54. package/out/geometries/index.js +5 -4
  55. package/out/geometries/index.js.map +1 -1
  56. package/out/geometries/line-string.d.ts +2 -2
  57. package/out/geometries/line-string.d.ts.map +1 -1
  58. package/out/geometries/line-string.js.map +1 -1
  59. package/out/geometries/point.d.ts +9 -9
  60. package/out/geometries/point.d.ts.map +1 -1
  61. package/out/geometries/point.js +9 -9
  62. package/out/geometries/point.js.map +1 -1
  63. package/out/geometries/polygon.d.ts +60 -56
  64. package/out/geometries/polygon.d.ts.map +1 -1
  65. package/out/geometries/polygon.js +66 -63
  66. package/out/geometries/polygon.js.map +1 -1
  67. package/out/geometries/ring-blob.d.ts +183 -0
  68. package/out/geometries/ring-blob.d.ts.map +1 -0
  69. package/out/geometries/ring-blob.js +376 -0
  70. package/out/geometries/ring-blob.js.map +1 -0
  71. package/out/google/index.d.ts +1 -1
  72. package/out/google/index.d.ts.map +1 -1
  73. package/out/google/index.js +1 -1
  74. package/out/google/index.js.map +1 -1
  75. package/out/google/place-id.d.ts.map +1 -1
  76. package/out/google/place-id.js.map +1 -1
  77. package/out/h3/cell.d.ts +32 -0
  78. package/out/h3/cell.d.ts.map +1 -1
  79. package/out/h3/cell.js +68 -1
  80. package/out/h3/cell.js.map +1 -1
  81. package/out/h3/coverage.d.ts +32 -0
  82. package/out/h3/coverage.d.ts.map +1 -0
  83. package/out/h3/coverage.js +27 -0
  84. package/out/h3/coverage.js.map +1 -0
  85. package/out/h3/index.d.ts +5 -3
  86. package/out/h3/index.d.ts.map +1 -1
  87. package/out/h3/index.js +5 -3
  88. package/out/h3/index.js.map +1 -1
  89. package/out/h3/interior-cells.d.ts +54 -0
  90. package/out/h3/interior-cells.d.ts.map +1 -0
  91. package/out/h3/interior-cells.js +111 -0
  92. package/out/h3/interior-cells.js.map +1 -0
  93. package/out/h3/polygon-cells.d.ts +182 -0
  94. package/out/h3/polygon-cells.d.ts.map +1 -0
  95. package/out/h3/polygon-cells.js +339 -0
  96. package/out/h3/polygon-cells.js.map +1 -0
  97. package/out/index.d.ts +15 -12
  98. package/out/index.d.ts.map +1 -1
  99. package/out/index.js +15 -12
  100. package/out/index.js.map +1 -1
  101. package/out/objects.d.ts +1 -1
  102. package/out/objects.d.ts.map +1 -1
  103. package/out/objects.js +1 -1
  104. package/out/objects.js.map +1 -1
  105. package/out/open-location-code.d.ts +48 -0
  106. package/out/open-location-code.d.ts.map +1 -0
  107. package/out/open-location-code.js +137 -0
  108. package/out/open-location-code.js.map +1 -0
  109. package/out/osgb36.d.ts +2 -2
  110. package/out/osgb36.d.ts.map +1 -1
  111. package/out/osgb36.js +1 -1
  112. package/out/osgb36.js.map +1 -1
  113. package/out/polyline.d.ts.map +1 -1
  114. package/out/polyline.js +1 -1
  115. package/out/polyline.js.map +1 -1
  116. package/out/position.d.ts +4 -61
  117. package/out/position.d.ts.map +1 -1
  118. package/out/position.js +14 -126
  119. package/out/position.js.map +1 -1
  120. package/out/projection-transform.d.ts +67 -0
  121. package/out/projection-transform.d.ts.map +1 -0
  122. package/out/projection-transform.js +48 -0
  123. package/out/projection-transform.js.map +1 -0
  124. package/out/projection.d.ts.map +1 -1
  125. package/out/projection.js.map +1 -1
  126. package/out/regions/codes.d.ts.map +1 -1
  127. package/out/regions/codes.js.map +1 -1
  128. package/out/regions/index.d.ts +2 -2
  129. package/out/regions/index.d.ts.map +1 -1
  130. package/out/regions/index.js +2 -2
  131. package/out/regions/index.js.map +1 -1
  132. package/out/regions/names.d.ts.map +1 -1
  133. package/out/regions/names.js.map +1 -1
  134. package/out/tools/ogr-stream.d.ts +34 -0
  135. package/out/tools/ogr-stream.d.ts.map +1 -0
  136. package/out/tools/ogr-stream.js +74 -0
  137. package/out/tools/ogr-stream.js.map +1 -0
  138. package/out/tools/ogr.d.ts +87 -0
  139. package/out/tools/ogr.d.ts.map +1 -0
  140. package/out/tools/ogr.js +84 -0
  141. package/out/tools/ogr.js.map +1 -0
  142. package/out/tsconfig.test.tsbuildinfo +1 -1
  143. package/out/{sdk/well-known-text.d.ts → well-known-text.d.ts} +1 -1
  144. package/out/well-known-text.d.ts.map +1 -0
  145. package/out/well-known-text.js.map +1 -0
  146. package/package.json +143 -14
  147. package/geometries/index.ts +0 -12
  148. package/index.ts +0 -18
  149. package/out/sdk/index.d.ts +0 -7
  150. package/out/sdk/index.d.ts.map +0 -1
  151. package/out/sdk/index.js +0 -7
  152. package/out/sdk/index.js.map +0 -1
  153. package/out/sdk/well-known-text.d.ts.map +0 -1
  154. package/out/sdk/well-known-text.js.map +0 -1
  155. package/out/tsconfig.tsbuildinfo +0 -1
  156. package/position.ts +0 -345
  157. package/sdk/index.ts +0 -7
  158. /package/{google → lib/google}/place-id.ts +0 -0
  159. /package/{projection.ts → lib/projection.ts} +0 -0
  160. /package/{regions → lib/regions}/names.ts +0 -0
  161. /package/out/{sdk/well-known-text.js → well-known-text.js} +0 -0
@@ -0,0 +1,521 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The ring blob — how a polygon layer stores one authority feature's UNSIMPLIFIED coordinates, and the
7
+ * point test that reads it without materializing them.
8
+ *
9
+ * THE GEOMETRY IS THE TRUTH TABLE. An H3 index above it answers a cell that lies wholly inside one
10
+ * feature; a cell a boundary crosses falls through to a ray cast against the few features the index
11
+ * already named. A rooftop answer at a boundary — which is where the answer usually matters most — has
12
+ * no other source, so the rings are stored at the resolution the authority published them and never
13
+ * simplified.
14
+ *
15
+ * THE LAYOUT PUTS THE COORDINATES ON AN 8-BYTE BOUNDARY, so the reader takes a `Float64Array` view over
16
+ * them instead of a `DataView.getFloat64` per ordinate. Header is `u32 version`, `u32 ringCount`, then
17
+ * one `(u32 pointCount, u32 polygonIndex)` pair per ring — `8 + 8 × ringCount` bytes, a multiple of
18
+ * eight by construction. Coordinates follow as `[lon, lat]` pairs, ring by ring.
19
+ *
20
+ * `polygonIndex` IS required AND CANNOT BE INFERRED. A source feature is a MultiPolygon, so its
21
+ * rings belong to several polygons and "the first ring is the exterior" is true only per polygon. The
22
+ * point test is orientation-free and nesting-free (even-odd across a polygon's own rings, the rule
23
+ * {@link pointInPolygon} uses), but it still has to know which rings share a polygon: an island sitting
24
+ * inside another polygon's hole is inside the layer and would cancel to "outside" if every ring were
25
+ * pooled into one list.
26
+ *
27
+ * SHARED BY EVERY POLYGON LAYER RATHER THAN COPIED INTO EACH. `@mailwoman/flood` and `@mailwoman/soil`
28
+ * both store an authority's rings this way, and a second copy of the alignment arithmetic or of the
29
+ * signed-area reading would be a second thing to get right — both failure modes are silent, since a
30
+ * mis-read blob answers a containment question wrongly and a hole-blind area reading answers "inside"
31
+ * for every point in a hole.
32
+ */
33
+
34
+ import type { MultiPolygonRings } from "#geometries/polygon"
35
+
36
+ /**
37
+ * Format version stamped into every blob. A reader that meets a different number throws rather than reinterpreting
38
+ * bytes it does not know the shape of.
39
+ */
40
+ export const RING_BLOB_VERSION = 1
41
+
42
+ /**
43
+ * Bytes of fixed header before the per-ring table.
44
+ */
45
+ const HEADER_BYTES = 8
46
+
47
+ /**
48
+ * Bytes per ring-table entry: `u32 pointCount`, `u32 polygonIndex`.
49
+ */
50
+ const RING_ENTRY_BYTES = 8
51
+
52
+ /**
53
+ * Positions a linear ring needs to bound an area: three distinct vertices plus the repeat that closes it (RFC 7946
54
+ * §3.1.6). Fewer is a degenerate ring, and encoding one would store a polygon no point can be inside.
55
+ */
56
+ const MINIMUM_RING_POSITIONS = 4
57
+
58
+ /**
59
+ * One decoded feature: `[exteriorRing, ...holes]` per polygon, each ring a flat `[lon, lat, lon, lat, …]` run.
60
+ */
61
+ export interface DecodedRings {
62
+ /**
63
+ * `polygons[p][r]` is a flat coordinate run for ring `r` of polygon `p`.
64
+ */
65
+ polygons: number[][][]
66
+ }
67
+
68
+ /**
69
+ * Pack a GeoJSON `MultiPolygon`/`Polygon` coordinate tree into the stored blob.
70
+ *
71
+ * @throws {RangeError} When the geometry carries no ring, or a ring carries fewer than four positions (a linear ring is
72
+ * closed, so three is the minimum distinct-vertex count plus the repeat).
73
+ */
74
+ export function encodeRings(polygons: MultiPolygonRings): Uint8Array {
75
+ const entries: Array<{ pointCount: number; polygonIndex: number }> = []
76
+ let totalPoints = 0
77
+
78
+ for (const [polygonIndex, rings] of polygons.entries()) {
79
+ for (const ring of rings) {
80
+ if (ring.length < MINIMUM_RING_POSITIONS) {
81
+ throw new RangeError(
82
+ `ring blob: a linear ring needs at least ${MINIMUM_RING_POSITIONS} positions, got ${ring.length}`
83
+ )
84
+ }
85
+
86
+ entries.push({ pointCount: ring.length, polygonIndex })
87
+ totalPoints += ring.length
88
+ }
89
+ }
90
+
91
+ if (!entries.length) {
92
+ throw new RangeError("ring blob: geometry carries no ring")
93
+ }
94
+
95
+ const headerBytes = HEADER_BYTES + RING_ENTRY_BYTES * entries.length
96
+ const buffer = new ArrayBuffer(headerBytes + totalPoints * 2 * Float64Array.BYTES_PER_ELEMENT)
97
+ const view = new DataView(buffer)
98
+
99
+ view.setUint32(0, RING_BLOB_VERSION, true)
100
+ view.setUint32(4, entries.length, true)
101
+
102
+ for (const [index, entry] of entries.entries()) {
103
+ view.setUint32(HEADER_BYTES + index * RING_ENTRY_BYTES, entry.pointCount, true)
104
+ view.setUint32(HEADER_BYTES + index * RING_ENTRY_BYTES + 4, entry.polygonIndex, true)
105
+ }
106
+
107
+ const coordinates = new Float64Array(buffer, headerBytes, totalPoints * 2)
108
+ let cursor = 0
109
+
110
+ for (const rings of polygons) {
111
+ for (const ring of rings) {
112
+ for (const position of ring) {
113
+ coordinates[cursor++] = position[0]!
114
+ coordinates[cursor++] = position[1]!
115
+ }
116
+ }
117
+ }
118
+
119
+ return new Uint8Array(buffer)
120
+ }
121
+
122
+ /**
123
+ * The ring table plus a `Float64Array` over the coordinates — what both the point test and the decoder walk.
124
+ *
125
+ * @throws {Error} When the blob's version is not {@linkcode RING_BLOB_VERSION}, or its declared ring table does not
126
+ * account for the bytes present. A blob that is silently mis-read answers a containment question wrongly, and a wrong
127
+ * containment answer is indistinguishable from a real one.
128
+ */
129
+ function openRings(blob: Uint8Array): {
130
+ ringCount: number
131
+ pointCounts: Uint32Array
132
+ polygonIndices: Uint32Array
133
+ coordinates: Float64Array
134
+ } {
135
+ // `blob.byteOffset` is not always zero: node:sqlite hands back a view into a shared buffer.
136
+ const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength)
137
+ const version = view.getUint32(0, true)
138
+
139
+ if (version !== RING_BLOB_VERSION) {
140
+ throw new Error(`ring blob: blob version ${version}, expected ${RING_BLOB_VERSION}`)
141
+ }
142
+
143
+ const ringCount = view.getUint32(4, true)
144
+ const headerBytes = HEADER_BYTES + RING_ENTRY_BYTES * ringCount
145
+ const pointCounts = new Uint32Array(ringCount)
146
+ const polygonIndices = new Uint32Array(ringCount)
147
+ let totalPoints = 0
148
+
149
+ for (let index = 0; index < ringCount; index++) {
150
+ const pointCount = view.getUint32(HEADER_BYTES + index * RING_ENTRY_BYTES, true)
151
+
152
+ pointCounts[index] = pointCount
153
+ polygonIndices[index] = view.getUint32(HEADER_BYTES + index * RING_ENTRY_BYTES + 4, true)
154
+ totalPoints += pointCount
155
+ }
156
+
157
+ const expected = headerBytes + totalPoints * 2 * Float64Array.BYTES_PER_ELEMENT
158
+
159
+ if (expected !== blob.byteLength) {
160
+ throw new Error(`ring blob: blob declares ${expected} bytes of geometry, holds ${blob.byteLength}`)
161
+ }
162
+
163
+ // The header is a multiple of eight by construction, so the coordinate run is 8-byte aligned and this view is legal
164
+ // on a shared buffer whose own offset is aligned. A misaligned source buffer is copied rather than rejected.
165
+ const absoluteOffset = blob.byteOffset + headerBytes
166
+
167
+ const coordinates =
168
+ absoluteOffset % Float64Array.BYTES_PER_ELEMENT === 0
169
+ ? new Float64Array(blob.buffer, absoluteOffset, totalPoints * 2)
170
+ : new Float64Array(blob.slice(headerBytes).buffer, 0, totalPoints * 2)
171
+
172
+ return { ringCount, pointCounts, polygonIndices, coordinates }
173
+ }
174
+
175
+ /**
176
+ * Is the point inside the stored geometry?
177
+ *
178
+ * Even-odd within each polygon's own ring list, inside-any-polygon across them — the orientation-free rule
179
+ * {@linkcode pointInPolygon} states, applied without allocating the ring arrays. Reading a hole as an exterior ring is
180
+ * what this rule survives: a point inside a hole crosses two rings and comes out even, whichever way either ring
181
+ * winds.
182
+ */
183
+ export function pointInEncodedRings(blob: Uint8Array, lon: number, lat: number): boolean {
184
+ const { ringCount, pointCounts, polygonIndices, coordinates } = openRings(blob)
185
+
186
+ if (!ringCount) return false
187
+
188
+ let cursor = 0
189
+ let polygon = polygonIndices[0]
190
+ let inside = false
191
+
192
+ for (let index = 0; index < ringCount; index++) {
193
+ const pointCount = pointCounts[index]!
194
+
195
+ if (polygonIndices[index] !== polygon) {
196
+ if (inside) return true
197
+
198
+ polygon = polygonIndices[index]
199
+ inside = false
200
+ }
201
+
202
+ if (crossesOdd(coordinates, cursor, pointCount, lon, lat)) {
203
+ inside = !inside
204
+ }
205
+
206
+ cursor += pointCount * 2
207
+ }
208
+
209
+ return inside
210
+ }
211
+
212
+ /**
213
+ * The even-odd crossing count over one ring held in a flat coordinate run. Mirrors {@linkcode pointInRing} exactly —
214
+ * same predicate, same tie behavior — so a decoded ring and an encoded one never disagree.
215
+ */
216
+ function crossesOdd(coordinates: Float64Array, offset: number, pointCount: number, lon: number, lat: number): boolean {
217
+ let inside = false
218
+
219
+ for (let i = 0, j = pointCount - 1; i < pointCount; j = i++) {
220
+ const xi = coordinates[offset + i * 2]!
221
+ const yi = coordinates[offset + i * 2 + 1]!
222
+ const xj = coordinates[offset + j * 2]!
223
+ const yj = coordinates[offset + j * 2 + 1]!
224
+
225
+ if (yi > lat !== yj > lat && lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi) {
226
+ inside = !inside
227
+ }
228
+ }
229
+
230
+ return inside
231
+ }
232
+
233
+ /**
234
+ * Unpack the blob back into per-polygon flat coordinate runs — for tests, for a debug render, and for the round-trip
235
+ * check a build's fixtures assert.
236
+ */
237
+ export function decodeRings(blob: Uint8Array): DecodedRings {
238
+ const { ringCount, pointCounts, polygonIndices, coordinates } = openRings(blob)
239
+ const polygons: number[][][] = []
240
+ let cursor = 0
241
+
242
+ for (let index = 0; index < ringCount; index++) {
243
+ const pointCount = pointCounts[index]!
244
+ const polygonIndex = polygonIndices[index]!
245
+
246
+ polygons[polygonIndex] ??= []
247
+ polygons[polygonIndex]!.push([...coordinates.subarray(cursor, cursor + pointCount * 2)])
248
+ cursor += pointCount * 2
249
+ }
250
+
251
+ return { polygons }
252
+ }
253
+
254
+ /**
255
+ * Mean Earth radius in metres — the sphere the ring areas below are measured on.
256
+ */
257
+ const EARTH_RADIUS_M = 6_371_008.8
258
+
259
+ /**
260
+ * Signed spherical area of one linear ring, in square metres. **CLOCKWISE is positive**, counter-clockwise negative.
261
+ *
262
+ * The sign is the whole point: an orientation-respecting sum over a polygon's rings subtracts its holes, while a sum of
263
+ * absolute values adds them. Comparing the two against the source's own area figure is what tells a builder whether it
264
+ * has read the holes at all — the failure mode is silent, because a hole read as an exterior ring produces a perfectly
265
+ * well-formed polygon that simply covers more ground than the authority mapped.
266
+ *
267
+ * WHICH WINDING IS POSITIVE IS A CONTRACT, NOT A DETAIL, because a builder whose source encodes hole roles by
268
+ * ORIENTATION reads roles off this sign. It is the opposite of the standard planar shoelace: this sum runs `(lonᵢ −
269
+ * lonⱼ)` against the shoelace's `(xⱼ − xᵢ)`, so a ring `@mailwoman/spatial`'s own {@link rectangleRing} builds
270
+ * counter-clockwise answers NEGATIVE here. `@mailwoman/zoning` is the caller that depends on it, and
271
+ * `packages/zoning/test/unit/ring-roles.test.ts` pins the sign directly.
272
+ */
273
+ export function ringSignedAreaM2(ring: ReadonlyArray<readonly number[]>): number {
274
+ let total = 0
275
+
276
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
277
+ const [lonI, latI] = ring[i] as [number, number]
278
+ const [lonJ, latJ] = ring[j] as [number, number]
279
+
280
+ total +=
281
+ (((lonI - lonJ) * Math.PI) / 180) * (2 + Math.sin((latJ * Math.PI) / 180) + Math.sin((latI * Math.PI) / 180))
282
+ }
283
+
284
+ return (total * EARTH_RADIUS_M * EARTH_RADIUS_M) / 2
285
+ }
286
+
287
+ /**
288
+ * Both readings of one feature's area, in square metres: `nested` respects ring orientation (holes subtract) and
289
+ * `allExterior` does not (holes add).
290
+ *
291
+ * A source whose holes are correctly nested makes `nested` match the authority's own figure and `allExterior` exceed
292
+ * it. The gap between them is the area a hole-blind reader would answer "inside" for.
293
+ */
294
+ export function ringAreaReadings(polygons: MultiPolygonRings): {
295
+ nested: number
296
+ allExterior: number
297
+ } {
298
+ let nested = 0
299
+ let allExterior = 0
300
+
301
+ for (const rings of polygons) {
302
+ // Per POLYGON, not pooled: two disjoint polygons of one feature can wind opposite ways without either being a
303
+ // hole, and a pooled sum would silently cancel them against each other.
304
+ let signedTotal = 0
305
+
306
+ for (const ring of rings) {
307
+ const signed = ringSignedAreaM2(ring)
308
+
309
+ signedTotal += signed
310
+ allExterior += Math.abs(signed)
311
+ }
312
+
313
+ nested += Math.abs(signedTotal)
314
+ }
315
+
316
+ return { nested, allExterior }
317
+ }
318
+
319
+ /**
320
+ * A rectangle in CRS84 degrees.
321
+ */
322
+ export interface DegreeExtent {
323
+ minLon: number
324
+ minLat: number
325
+ maxLon: number
326
+ maxLat: number
327
+ }
328
+
329
+ /**
330
+ * Refuse a feature whose reprojected vertices fall outside the publisher's own declared extent.
331
+ *
332
+ * THE CHECK A PROJECTION CHECK CANNOT MAKE. A swapped coordinate order survives an authority-code comparison — both
333
+ * axes are still numbers in a plausible range — and a source read in its own metres as if they were degrees produces
334
+ * perfectly well-formed coordinates in the wrong ocean. Both show up here on the first feature, before a whole layer is
335
+ * written to the wrong side of the planet.
336
+ *
337
+ * SHARED BY EVERY POLYGON INGEST, because it is rectangle arithmetic over the ring types and knows nothing about any
338
+ * product. `marginDegrees` is the caller's, because a declared extent is itself a rounded published value and how
339
+ * tightly a source hugs its own is a fact about that source.
340
+ *
341
+ * @param context Names the calling ingest in the refusal, so a build log says which layer stopped.
342
+ * @throws {RangeError} On the first vertex outside the extent.
343
+ */
344
+ export function assertRingsInsideExtent(
345
+ polygons: MultiPolygonRings,
346
+ label: string,
347
+ extent: DegreeExtent,
348
+ marginDegrees: number,
349
+ context = "polygon ingest"
350
+ ): void {
351
+ for (const rings of polygons) {
352
+ for (const ring of rings) {
353
+ for (const position of ring) {
354
+ const lon = position[0]!
355
+ const lat = position[1]!
356
+
357
+ if (
358
+ lon < extent.minLon - marginDegrees ||
359
+ lon > extent.maxLon + marginDegrees ||
360
+ lat < extent.minLat - marginDegrees ||
361
+ lat > extent.maxLat + marginDegrees
362
+ ) {
363
+ throw new RangeError(
364
+ `${context}: ${label} has a vertex at ${lon}, ${lat}, outside the declared extent ` +
365
+ `[${extent.minLon}, ${extent.minLat}, ${extent.maxLon}, ${extent.maxLat}] — the reprojection or the coordinate order is wrong`
366
+ )
367
+ }
368
+ }
369
+ }
370
+ }
371
+ }
372
+
373
+ /**
374
+ * One stored polygon's bounding box and geometry, as every polygon layer's truth table stores them.
375
+ */
376
+ export interface EncodedArea {
377
+ min_lat: number
378
+ min_lon: number
379
+ max_lat: number
380
+ max_lon: number
381
+ rings: Uint8Array
382
+ }
383
+
384
+ /**
385
+ * A point INSIDE one stored polygon, for a verification sampler.
386
+ *
387
+ * The bounding-box centre is tried first; where it is not inside — a crescent, a band hugging a river, a polygon with a
388
+ * hole through its middle — a small deterministic grid over the box is scanned. A polygon no grid point lands inside is
389
+ * refused (`undefined`) rather than approximated, because a sample point that is not actually inside the polygon turns
390
+ * an agreement check into a check on the sampler.
391
+ *
392
+ * SHARED BY EVERY POLYGON LAYER'S VERIFY, because it is bounding-box arithmetic over the ring blob and knows nothing
393
+ * about any product. `gridSteps` is the one thing that differs between them: a layer whose polygons are narrow strips
394
+ * needs a finer grid than one whose polygons are compact, and the value is part of a layer's sampling receipt — two
395
+ * runs of the same layer must draw the same points, so it is a caller's choice rather than a shared default nobody
396
+ * owns.
397
+ *
398
+ * @param gridSteps Grid divisions per axis. Only `steps − 1` interior lines are tested, so 7 gives a 6 × 6 grid.
399
+ */
400
+ export function interiorPointOfEncodedRings(
401
+ area: EncodedArea,
402
+ gridSteps = 7
403
+ ): { latitude: number; longitude: number } | undefined {
404
+ const centreLat = (area.min_lat + area.max_lat) / 2
405
+ const centreLon = (area.min_lon + area.max_lon) / 2
406
+
407
+ if (pointInEncodedRings(area.rings, centreLon, centreLat)) {
408
+ return { latitude: centreLat, longitude: centreLon }
409
+ }
410
+
411
+ for (let row = 1; row < gridSteps; row++) {
412
+ for (let column = 1; column < gridSteps; column++) {
413
+ const latitude = area.min_lat + ((area.max_lat - area.min_lat) * row) / gridSteps
414
+ const longitude = area.min_lon + ((area.max_lon - area.min_lon) * column) / gridSteps
415
+
416
+ if (pointInEncodedRings(area.rings, longitude, latitude)) return { latitude, longitude }
417
+ }
418
+ }
419
+
420
+ return undefined
421
+ }
422
+
423
+ /**
424
+ * Whether a stored polygon's precomputed bounding box contains the point — the ray cast's prefilter, so the blob is
425
+ * only pulled off disk for a polygon that could contain the point.
426
+ */
427
+ export function bboxContains(
428
+ bounds: Pick<EncodedArea, "min_lat" | "min_lon" | "max_lat" | "max_lon">,
429
+ longitude: number,
430
+ latitude: number
431
+ ): boolean {
432
+ return (
433
+ longitude >= bounds.min_lon &&
434
+ longitude <= bounds.max_lon &&
435
+ latitude >= bounds.min_lat &&
436
+ latitude <= bounds.max_lat
437
+ )
438
+ }
439
+
440
+ /**
441
+ * A reproducible sample of interior points drawn by a deterministic STRIDE over a key list — the shape every polygon
442
+ * layer's verification sampler shares.
443
+ *
444
+ * The keys are chosen before any geometry is read: selecting them alone is an index-only walk over the primary key, and
445
+ * the rows they name are then fetched by key. The draw is deterministic rather than random, so a re-run compares the
446
+ * same points and a disagreement can be looked at rather than re-rolled.
447
+ *
448
+ * @param options.gridSteps The interior-point search depth, per {@link interiorPointOfEncodedRings} — part of a layer's
449
+ * sampling receipt, so it is a caller's choice rather than a shared default nobody owns.
450
+ */
451
+ export function strideSampleInteriorPoints<Area extends EncodedArea, Point>(
452
+ keys: readonly string[],
453
+ count: number,
454
+ options: {
455
+ fetch: (key: string) => Area | undefined
456
+ gridSteps: number
457
+ toPoint: (area: Area, interior: { latitude: number; longitude: number }) => Point
458
+ }
459
+ ): Point[] {
460
+ const points: Point[] = []
461
+
462
+ if (!keys.length) return points
463
+
464
+ const stride = Math.max(1, Math.floor(keys.length / Math.max(1, count)))
465
+
466
+ for (let index = 0; index < keys.length && points.length < count; index += stride) {
467
+ const area = options.fetch(keys[index]!)
468
+
469
+ if (!area) continue
470
+
471
+ const interior = interiorPointOfEncodedRings(area, options.gridSteps)
472
+
473
+ if (!interior) continue
474
+
475
+ points.push(options.toPoint(area, interior))
476
+ }
477
+
478
+ return points
479
+ }
480
+
481
+ /**
482
+ * The bounding rectangle of one feature's rings, in degrees — a ray cast's prefilter, precomputed.
483
+ */
484
+ export function ringsBoundingBox(polygons: MultiPolygonRings): {
485
+ minLat: number
486
+ minLon: number
487
+ maxLat: number
488
+ maxLon: number
489
+ } {
490
+ let minLat = Infinity
491
+ let minLon = Infinity
492
+ let maxLat = -Infinity
493
+ let maxLon = -Infinity
494
+
495
+ for (const rings of polygons) {
496
+ for (const ring of rings) {
497
+ for (const position of ring) {
498
+ const lon = position[0]!
499
+ const lat = position[1]!
500
+
501
+ if (lon < minLon) {
502
+ minLon = lon
503
+ }
504
+
505
+ if (lon > maxLon) {
506
+ maxLon = lon
507
+ }
508
+
509
+ if (lat < minLat) {
510
+ minLat = lat
511
+ }
512
+
513
+ if (lat > maxLat) {
514
+ maxLat = lat
515
+ }
516
+ }
517
+ }
518
+ }
519
+
520
+ return { minLat, minLon, maxLat, maxLon }
521
+ }
@@ -4,4 +4,4 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
6
 
7
- export * from "./place-id.ts"
7
+ export * from "#google/place-id"
@@ -9,7 +9,7 @@
9
9
  * by `./index.ts`, so keeping them together closed an import cycle.
10
10
  */
11
11
 
12
- import { isValidCell } from "h3-js"
12
+ import { cellToParent, isValidCell } from "h3-js"
13
13
  import type { Tagged } from "type-fest"
14
14
 
15
15
  /**
@@ -120,6 +120,16 @@ export function expandH3Cell(h3CellShort: H3CellShort, resolution = H3_MAX_RESOL
120
120
  return cell
121
121
  }
122
122
 
123
+ /**
124
+ * The full H3 index for a short cell held as an integer, stored at `resolution`.
125
+ *
126
+ * Through {@link expandH3Cell} rather than a string concatenation, because it VALIDATES: a short cell that does not name
127
+ * a valid cell at the stated resolution throws here instead of reaching `compactCells` as a plausible-looking index.
128
+ */
129
+ export function expandShortCellInt(shortCell: number, resolution: number): H3Cell {
130
+ return expandH3Cell(shortCell.toString(16).padStart(SHORT_CELL_HEX_LENGTH, "0") as H3CellShort, resolution)
131
+ }
132
+
123
133
  /**
124
134
  * Pack an H3 cell into the short-cell integer used as a clustered B-tree key across layer databases (poi.db, bdc.db,
125
135
  * address-id). 52 bits, so it stays inside `Number.MAX_SAFE_INTEGER` and SQLite's signed 64-bit integer column alike.
@@ -127,3 +137,75 @@ export function expandH3Cell(h3CellShort: H3CellShort, resolution = H3_MAX_RESOL
127
137
  export function shortCellToInt(cell: H3Cell): number {
128
138
  return Number(BigInt(`0x${shortenH3Cell(cell)}`))
129
139
  }
140
+
141
+ /**
142
+ * The one resolution a set of stored short cells was captured at.
143
+ *
144
+ * A short cell drops the resolution nibble, so a table of them does not say what resolution it is keyed at — and every
145
+ * `layer_coverage` reader needs that number to derive a probe's coverage cell. It is recoverable because
146
+ * {@link expandH3Cell} validates: a short cell expands to a valid index at EXACTLY ONE resolution, so trying all
147
+ * sixteen and keeping the one that survives is an exact answer rather than an inference.
148
+ *
149
+ * SHARED RATHER THAN COPIED, because both failure modes it names are silent in a second copy. A table that mixes
150
+ * resolutions read at one of them reports every cell at the other as unsurveyed, and an empty table read as "resolution
151
+ * 0" puts every probe in the same cell. `packages/mailwoman/lib/observations/absence-route.ts` re-exports this under
152
+ * its own name; `@mailwoman/coastal` calls it directly.
153
+ *
154
+ * @param context Names the caller in both messages, so a failure says which reader refused.
155
+ * @throws {Error} When `cells` is empty, when a value is not a short cell, or when the set mixes resolutions.
156
+ */
157
+ export function recoverShortCellResolution(cells: readonly number[], context = "layer coverage"): number {
158
+ if (!cells.length) {
159
+ throw new Error(`${context}: the coverage layer holds no cells — there is no resolution to recover`)
160
+ }
161
+
162
+ let recovered: number | undefined
163
+
164
+ for (const cell of cells) {
165
+ const short = BigInt(cell).toString(16).padStart(SHORT_CELL_HEX_LENGTH, "0") as H3CellShort
166
+ const valid: number[] = []
167
+
168
+ for (let resolution = 0; resolution <= H3_MAX_RESOLUTION; resolution++) {
169
+ try {
170
+ expandH3Cell(short, resolution)
171
+ valid.push(resolution)
172
+ } catch {
173
+ // A resolution the short cell does not expand at. Every cell expands at exactly one, so this is the
174
+ // ordinary case for fifteen of the sixteen probes.
175
+ }
176
+ }
177
+
178
+ if (valid.length !== 1) {
179
+ throw new Error(
180
+ `${context}: coverage cell ${cell} expands at ${valid.length} resolutions (${valid.join(", ") || "none"}) — it is not a short H3 cell this layer can be probed by`
181
+ )
182
+ }
183
+
184
+ const resolution = valid[0]!
185
+
186
+ if (recovered === undefined) {
187
+ recovered = resolution
188
+
189
+ continue
190
+ }
191
+
192
+ if (recovered !== resolution) {
193
+ throw new Error(
194
+ `${context}: the coverage table mixes resolutions (${recovered} and ${resolution}) — a single-resolution probe would read every cell at the other resolution as unsurveyed`
195
+ )
196
+ }
197
+ }
198
+
199
+ return recovered!
200
+ }
201
+
202
+ /**
203
+ * Reconstruct a short-cell int's ancestor at a coarser resolution WITHOUT going through a centroid.
204
+ *
205
+ * The centroid is the wrong input: re-deriving a parent from a stored cell's center can land in a different parent than
206
+ * the original cell belonged to (measured at ~6% of CONUS blocks between res 9 and res 6), so a coverage read and the
207
+ * build that wrote it disagree on a fraction of cells. Reconstructing from the stored cell itself is exact.
208
+ */
209
+ export function shortCellToParentInt(shortCell: number, from: number, to: number): number {
210
+ return shortCellToInt(cellToParent(expandShortCellInt(shortCell, from), to) as H3Cell)
211
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @copyright Sister Software.
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The coverage probe every polygon layer's reader repeats: an index cell's parent at the coverage
7
+ * resolution, read through the layer contract's shared row mapping.
8
+ *
9
+ * NOT exported from this package's main barrel on purpose — it reaches `@mailwoman/core/layers`, and the
10
+ * barrel serves browser bundles that must not carry the layer contract's Kysely graph. Import it from the
11
+ * `@mailwoman/spatial/h3/coverage` subpath.
12
+ */
13
+
14
+ import { toCoverageCell, type CoverageCell, type CoverageRow } from "@mailwoman/core/layers"
15
+ import { cellToParent } from "h3-js"
16
+
17
+ import { shortCellToInt, type H3Cell } from "#h3/cell"
18
+
19
+ /**
20
+ * The one capability the probe needs of a prepared statement.
21
+ */
22
+ export interface CoverageRowProbe {
23
+ get(shortCell: number): unknown
24
+ }
25
+
26
+ /**
27
+ * The coverage row for `indexCell`'s parent at the coverage resolution, or `undefined` when the cell was never surveyed
28
+ * — which a caller must read as UNKNOWN, never as `{completeness: 0}`.
29
+ *
30
+ * The NULL-basis rule lives in the shared mapping: a NULL column is an artifact built before `basis` existed, and it
31
+ * was recording source presence — never a stronger basis than the builder actually had.
32
+ */
33
+ export function readCoverageAt(
34
+ select: CoverageRowProbe,
35
+ indexCell: H3Cell,
36
+ coverageResolution: number
37
+ ): (CoverageCell & { h3CellIndex: string; resolution: number }) | undefined {
38
+ const coverageCell = cellToParent(indexCell, coverageResolution) as H3Cell
39
+
40
+ return toCoverageCell(
41
+ select.get(shortCellToInt(coverageCell)) as CoverageRow | undefined,
42
+ coverageCell,
43
+ coverageResolution
44
+ )
45
+ }
@@ -6,10 +6,12 @@
6
6
 
7
7
  import { cellToLatLng } from "h3-js"
8
8
 
9
- import { GeoPoint, type PointLiteral } from "../geometries/point.ts"
10
- import { type H3Cell, type H3CellShort, expandH3Cell } from "./cell.ts"
9
+ import { GeoPoint, type PointLiteral } from "#geometries/point"
10
+ import { type H3Cell, type H3CellShort, expandH3Cell } from "#h3/cell"
11
11
 
12
- export * from "./cell.ts"
12
+ export * from "#h3/cell"
13
+ export * from "#h3/interior-cells"
14
+ export * from "#h3/polygon-cells"
13
15
 
14
16
  /**
15
17
  * Given a short cell address and the resolution it was captured at, return the centre of that cell.