@mailwoman/spatial 10.0.0 → 10.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 (148) hide show
  1. package/README.md +2 -2
  2. package/lib/bbox.ts +41 -34
  3. package/lib/coordinate/bounds.ts +2 -2
  4. package/lib/coordinate/formats.ts +21 -33
  5. package/lib/distance.ts +56 -28
  6. package/lib/feature.ts +2 -2
  7. package/lib/geometries/point.ts +42 -35
  8. package/lib/geometries/polygon.ts +27 -135
  9. package/lib/geometries/ring-blob.ts +35 -132
  10. package/lib/google/place-id.ts +4 -2
  11. package/lib/h3/cell.ts +23 -78
  12. package/lib/h3/coverage.ts +13 -9
  13. package/lib/h3/interior-cells.ts +13 -34
  14. package/lib/h3/polygon-cells.ts +61 -167
  15. package/lib/{h3/index.ts → h3.ts} +1 -1
  16. package/lib/index.ts +6 -5
  17. package/lib/objects.ts +6 -6
  18. package/lib/open-location-code.ts +11 -42
  19. package/lib/osgb36.ts +28 -187
  20. package/lib/polyline.ts +5 -3
  21. package/lib/position.ts +39 -20
  22. package/lib/projection/transform.ts +43 -44
  23. package/lib/{projection/index.ts → projection.ts} +1 -1
  24. package/lib/well-known-text.ts +9 -9
  25. package/out/bbox.d.ts +17 -14
  26. package/out/bbox.d.ts.map +1 -1
  27. package/out/bbox.js +32 -23
  28. package/out/bbox.js.map +1 -1
  29. package/out/coordinate/bounds.d.ts +2 -2
  30. package/out/coordinate/bounds.js +2 -2
  31. package/out/coordinate/formats.d.ts +17 -16
  32. package/out/coordinate/formats.d.ts.map +1 -1
  33. package/out/coordinate/formats.js +20 -32
  34. package/out/coordinate/formats.js.map +1 -1
  35. package/out/distance.d.ts +51 -26
  36. package/out/distance.d.ts.map +1 -1
  37. package/out/distance.js +53 -27
  38. package/out/distance.js.map +1 -1
  39. package/out/feature.d.ts +2 -2
  40. package/out/feature.d.ts.map +1 -1
  41. package/out/geometries/point.d.ts +30 -22
  42. package/out/geometries/point.d.ts.map +1 -1
  43. package/out/geometries/point.js +37 -30
  44. package/out/geometries/point.js.map +1 -1
  45. package/out/geometries/polygon.d.ts +27 -126
  46. package/out/geometries/polygon.d.ts.map +1 -1
  47. package/out/geometries/polygon.js +14 -42
  48. package/out/geometries/polygon.js.map +1 -1
  49. package/out/geometries/ring-blob.d.ts +24 -110
  50. package/out/geometries/ring-blob.d.ts.map +1 -1
  51. package/out/geometries/ring-blob.js +30 -116
  52. package/out/geometries/ring-blob.js.map +1 -1
  53. package/out/{geometries/index.js → geometries.d.ts} +1 -1
  54. package/out/geometries.d.ts.map +1 -0
  55. package/out/{geometries/index.d.ts → geometries.js} +1 -1
  56. package/out/geometries.js.map +1 -0
  57. package/out/google/place-id.d.ts +4 -2
  58. package/out/google/place-id.d.ts.map +1 -1
  59. package/out/google/place-id.js.map +1 -1
  60. package/out/{google/index.d.ts → google.d.ts} +1 -1
  61. package/out/google.d.ts.map +1 -0
  62. package/out/{google/index.js → google.js} +1 -1
  63. package/out/google.js.map +1 -0
  64. package/out/h3/cell.d.ts +19 -73
  65. package/out/h3/cell.d.ts.map +1 -1
  66. package/out/h3/cell.js +22 -65
  67. package/out/h3/cell.js.map +1 -1
  68. package/out/h3/coverage.d.ts +12 -8
  69. package/out/h3/coverage.d.ts.map +1 -1
  70. package/out/h3/coverage.js +12 -8
  71. package/out/h3/coverage.js.map +1 -1
  72. package/out/h3/interior-cells.d.ts +9 -28
  73. package/out/h3/interior-cells.d.ts.map +1 -1
  74. package/out/h3/interior-cells.js +13 -32
  75. package/out/h3/interior-cells.js.map +1 -1
  76. package/out/h3/polygon-cells.d.ts +28 -120
  77. package/out/h3/polygon-cells.d.ts.map +1 -1
  78. package/out/h3/polygon-cells.js +50 -148
  79. package/out/h3/polygon-cells.js.map +1 -1
  80. package/out/{h3/index.d.ts → h3.d.ts} +2 -2
  81. package/out/h3.d.ts.map +1 -0
  82. package/out/{h3/index.js → h3.js} +2 -2
  83. package/out/h3.js.map +1 -0
  84. package/out/index.d.ts +6 -5
  85. package/out/index.d.ts.map +1 -1
  86. package/out/index.js +6 -5
  87. package/out/index.js.map +1 -1
  88. package/out/objects.d.ts +6 -6
  89. package/out/open-location-code.d.ts +11 -22
  90. package/out/open-location-code.d.ts.map +1 -1
  91. package/out/open-location-code.js +9 -40
  92. package/out/open-location-code.js.map +1 -1
  93. package/out/osgb36.d.ts +21 -97
  94. package/out/osgb36.d.ts.map +1 -1
  95. package/out/osgb36.js +12 -165
  96. package/out/osgb36.js.map +1 -1
  97. package/out/polyline.d.ts +5 -3
  98. package/out/polyline.d.ts.map +1 -1
  99. package/out/polyline.js +5 -3
  100. package/out/polyline.js.map +1 -1
  101. package/out/position.d.ts +36 -20
  102. package/out/position.d.ts.map +1 -1
  103. package/out/position.js +0 -1
  104. package/out/position.js.map +1 -1
  105. package/out/projection/transform.d.ts +33 -30
  106. package/out/projection/transform.d.ts.map +1 -1
  107. package/out/projection/transform.js +15 -17
  108. package/out/projection/transform.js.map +1 -1
  109. package/out/{projection/index.d.ts → projection.d.ts} +2 -2
  110. package/out/projection.d.ts.map +1 -0
  111. package/out/{projection/index.js → projection.js} +2 -2
  112. package/out/projection.js.map +1 -0
  113. package/out/{regions/index.js → regions.d.ts} +1 -1
  114. package/out/regions.d.ts.map +1 -0
  115. package/out/{regions/index.d.ts → regions.js} +1 -1
  116. package/out/regions.js.map +1 -0
  117. package/out/tools/ogr/stream.d.ts +21 -11
  118. package/out/tools/ogr/stream.d.ts.map +1 -1
  119. package/out/tools/ogr/stream.js +17 -10
  120. package/out/tools/ogr/stream.js.map +1 -1
  121. package/out/tools/{ogr/index.d.ts → ogr.d.ts} +25 -15
  122. package/out/tools/ogr.d.ts.map +1 -0
  123. package/out/tools/{ogr/index.js → ogr.js} +25 -21
  124. package/out/tools/ogr.js.map +1 -0
  125. package/out/tools/tsconfig.tsbuildinfo +1 -0
  126. package/out/tsconfig.test.tsbuildinfo +1 -1
  127. package/out/well-known-text.d.ts +9 -9
  128. package/out/well-known-text.d.ts.map +1 -1
  129. package/out/well-known-text.js +7 -7
  130. package/out/well-known-text.js.map +1 -1
  131. package/package.json +37 -129
  132. package/{lib/tools → tools}/ogr/stream.ts +26 -15
  133. package/{lib/tools/ogr/index.ts → tools/ogr.ts} +44 -30
  134. package/out/geometries/index.d.ts.map +0 -1
  135. package/out/geometries/index.js.map +0 -1
  136. package/out/google/index.d.ts.map +0 -1
  137. package/out/google/index.js.map +0 -1
  138. package/out/h3/index.d.ts.map +0 -1
  139. package/out/h3/index.js.map +0 -1
  140. package/out/projection/index.d.ts.map +0 -1
  141. package/out/projection/index.js.map +0 -1
  142. package/out/regions/index.d.ts.map +0 -1
  143. package/out/regions/index.js.map +0 -1
  144. package/out/tools/ogr/index.d.ts.map +0 -1
  145. package/out/tools/ogr/index.js.map +0 -1
  146. /package/lib/{geometries/index.ts → geometries.ts} +0 -0
  147. /package/lib/{google/index.ts → google.ts} +0 -0
  148. /package/lib/{regions/index.ts → regions.ts} +0 -0
@@ -3,73 +3,40 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
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.
6
+ * A polygon layer's stored ring blob: an 8-byte header, then a `(u32 pointCount, u32 polygonIndex)`
7
+ * pair per ring, then `[lon, lat]` pairs on an 8-byte boundary so the reader takes a
8
+ * `Float64Array` view; `polygonIndex` is required because one feature's rings belong to several polygons.
32
9
  */
33
10
 
11
+ import type { LatLonBounds } from "#bbox"
34
12
  import type { MultiPolygonRings } from "#geometries/polygon"
35
13
 
36
14
  /**
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.
15
+ * Format version stamped into every blob, rejected by a reader that meets a different number.
39
16
  */
40
17
  export const RING_BLOB_VERSION = 1
41
18
 
42
- /**
43
- * Bytes of fixed header before the per-ring table.
44
- */
45
19
  const HEADER_BYTES = 8
46
20
 
47
- /**
48
- * Bytes per ring-table entry: `u32 pointCount`, `u32 polygonIndex`.
49
- */
50
21
  const RING_ENTRY_BYTES = 8
51
22
 
52
23
  /**
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.
24
+ * Positions a linear ring needs to bound an area: three distinct vertices plus
25
+ * the repeat that closes it (RFC 7946 §3.1.6).
55
26
  */
56
27
  const MINIMUM_RING_POSITIONS = 4
57
28
 
58
29
  /**
59
- * One decoded feature: `[exteriorRing, ...holes]` per polygon, each ring a flat `[lon, lat, lon, lat, …]` run.
30
+ * One decoded feature: `[exteriorRing, ...holes]` per polygon, each ring a
31
+ * flat `[lon, lat, lon, lat, …]` run.
60
32
  */
61
33
  export interface DecodedRings {
62
- /**
63
- * `polygons[p][r]` is a flat coordinate run for ring `r` of polygon `p`.
64
- */
65
34
  polygons: number[][][]
66
35
  }
67
36
 
68
37
  /**
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).
38
+ * Pack a GeoJSON `MultiPolygon`/`Polygon` coordinate tree into the stored blob, throwing
39
+ * when the geometry has no ring or a ring has fewer than four positions.
73
40
  */
74
41
  export function encodeRings(polygons: MultiPolygonRings): Uint8Array {
75
42
  const entries: Array<{ pointCount: number; polygonIndex: number }> = []
@@ -120,11 +87,8 @@ export function encodeRings(polygons: MultiPolygonRings): Uint8Array {
120
87
  }
121
88
 
122
89
  /**
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.
90
+ * The ring table plus a `Float64Array` over the coordinates, throwing when the blob's version is not
91
+ * {@linkcode RING_BLOB_VERSION} or its declared ring table does not account for the bytes present.
128
92
  */
129
93
  function openRings(blob: Uint8Array): {
130
94
  ringCount: number
@@ -160,8 +124,8 @@ function openRings(blob: Uint8Array): {
160
124
  throw new Error(`ring blob: blob declares ${expected} bytes of geometry, holds ${blob.byteLength}`)
161
125
  }
162
126
 
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.
127
+ // The header is a multiple of eight by construction, so the coordinate run is 8-byte aligned.
128
+ // A misaligned source buffer is copied rather than rejected.
165
129
  const absoluteOffset = blob.byteOffset + headerBytes
166
130
 
167
131
  const coordinates =
@@ -173,12 +137,8 @@ function openRings(blob: Uint8Array): {
173
137
  }
174
138
 
175
139
  /**
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.
140
+ * Is the point inside the stored geometry, even-odd within each polygon's own ring list
141
+ * and inside-any-polygon across them, without allocating the ring arrays.
182
142
  */
183
143
  export function pointInEncodedRings(blob: Uint8Array, lon: number, lat: number): boolean {
184
144
  const { ringCount, pointCounts, polygonIndices, coordinates } = openRings(blob)
@@ -210,8 +170,8 @@ export function pointInEncodedRings(blob: Uint8Array, lon: number, lat: number):
210
170
  }
211
171
 
212
172
  /**
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.
173
+ * The even-odd crossing count over one ring held in a flat coordinate run, mirroring
174
+ * {@linkcode pointInRing} exactly so a decoded ring and an encoded one never disagree.
215
175
  */
216
176
  function crossesOdd(coordinates: Float64Array, offset: number, pointCount: number, lon: number, lat: number): boolean {
217
177
  let inside = false
@@ -231,8 +191,7 @@ function crossesOdd(coordinates: Float64Array, offset: number, pointCount: numbe
231
191
  }
232
192
 
233
193
  /**
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.
194
+ * Unpack the blob back into per-polygon flat coordinate runs.
236
195
  */
237
196
  export function decodeRings(blob: Uint8Array): DecodedRings {
238
197
  const { ringCount, pointCounts, polygonIndices, coordinates } = openRings(blob)
@@ -252,23 +211,13 @@ export function decodeRings(blob: Uint8Array): DecodedRings {
252
211
  }
253
212
 
254
213
  /**
255
- * Mean Earth radius in metres — the sphere the ring areas below are measured on.
214
+ * Mean Earth radius in meters, the sphere the ring areas are measured on.
256
215
  */
257
216
  const EARTH_RADIUS_M = 6_371_008.8
258
217
 
259
218
  /**
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.
219
+ * Signed spherical area of one linear ring, in square meters, with clockwise positive
220
+ * and counter-clockwise negative.
272
221
  */
273
222
  export function ringSignedAreaM2(ring: ReadonlyArray<readonly number[]>): number {
274
223
  let total = 0
@@ -285,11 +234,8 @@ export function ringSignedAreaM2(ring: ReadonlyArray<readonly number[]>): number
285
234
  }
286
235
 
287
236
  /**
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.
237
+ * Both readings of one feature's area, in square meters: `nested` respects ring
238
+ * orientation (holes subtract) and `allExterior` does not (holes add).
293
239
  */
294
240
  export function ringAreaReadings(polygons: MultiPolygonRings): {
295
241
  nested: number
@@ -299,8 +245,7 @@ export function ringAreaReadings(polygons: MultiPolygonRings): {
299
245
  let allExterior = 0
300
246
 
301
247
  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.
248
+ // Per polygon rather than pooled, so two disjoint polygons wound opposite ways do not cancel out.
304
249
  let signedTotal = 0
305
250
 
306
251
  for (const ring of rings) {
@@ -317,34 +262,13 @@ export function ringAreaReadings(polygons: MultiPolygonRings): {
317
262
  }
318
263
 
319
264
  /**
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.
265
+ * Refuse a feature whose reprojected vertices fall outside the publisher's own
266
+ * declared extent, throwing on the first vertex outside it.
343
267
  */
344
268
  export function assertRingsInsideExtent(
345
269
  polygons: MultiPolygonRings,
346
270
  label: string,
347
- extent: DegreeExtent,
271
+ extent: LatLonBounds,
348
272
  marginDegrees: number,
349
273
  context = "polygon ingest"
350
274
  ): void {
@@ -382,25 +306,13 @@ export interface EncodedArea {
382
306
  }
383
307
 
384
308
  /**
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.
309
+ * A point inside one stored polygon for a verification sampler, returning `undefined` when neither
310
+ * the bounding-box center nor any of the `gridSteps − 1` interior grid lines lands inside.
399
311
  */
400
312
  export function interiorPointOfEncodedRings(
401
313
  area: EncodedArea,
402
314
  gridSteps = 7
403
- ): { latitude: number; longitude: number } | undefined {
315
+ ): { latitude: number; longitude: number } | null {
404
316
  const centreLat = (area.min_lat + area.max_lat) / 2
405
317
  const centreLon = (area.min_lon + area.max_lon) / 2
406
318
 
@@ -417,12 +329,11 @@ export function interiorPointOfEncodedRings(
417
329
  }
418
330
  }
419
331
 
420
- return undefined
332
+ return null
421
333
  }
422
334
 
423
335
  /**
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.
336
+ * Whether a stored polygon's precomputed bounding box contains the point.
426
337
  */
427
338
  export function bboxContains(
428
339
  bounds: Pick<EncodedArea, "min_lat" | "min_lon" | "max_lat" | "max_lon">,
@@ -438,15 +349,7 @@ export function bboxContains(
438
349
  }
439
350
 
440
351
  /**
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.
352
+ * A reproducible sample of interior points drawn by a deterministic stride over a key list.
450
353
  */
451
354
  export function strideSampleInteriorPoints<Area extends EncodedArea, Point>(
452
355
  keys: readonly string[],
@@ -11,12 +11,14 @@ import type { Tagged } from "type-fest"
11
11
  /**
12
12
  * A Place ID uniquely identifies a place in the Google Places database and on Google Maps.
13
13
  *
14
- * The length of the identifier may vary. Generally, the identifier is a 27-character string, however, more specific
14
+ * The length of the identifier may vary.
15
+ * Generally, the identifier is a 27-character string, however, more specific
15
16
  * places may have longer identifiers.
16
17
  *
17
18
  * Place IDs appear to be base64-encoded strings, delimited by underscores and dashes.
18
19
  *
19
- * Note that Place IDs do change. Consider a them stale after a few days.
20
+ * Note that Place IDs do change.
21
+ * Consider a them stale after a few days.
20
22
  *
21
23
  * @category Google
22
24
  * @category Geocoding
package/lib/h3/cell.ts CHANGED
@@ -3,40 +3,26 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  * @file H3 cell primitives — the index types and the widen/shorten conversions.
6
- *
7
- * Split out from `./index.ts` because these carry no dependency on `GeoPoint`, while the
8
- * point-valued helpers there do. `geometries/point.ts` needs the primitives and is itself imported
9
- * by `./index.ts`, so keeping them together closed an import cycle.
6
+
10
7
  */
11
8
 
12
9
  import { cellToParent, isValidCell } from "h3-js"
13
10
  import type { Tagged } from "type-fest"
14
11
 
15
12
  /**
16
- * The finest resolution H3 defines. Resolutions run `[0, H3_MAX_RESOLUTION]`.
13
+ * The finest resolution H3 defines.
14
+ * Resolutions run `[0, H3_MAX_RESOLUTION]`.
17
15
  */
18
16
  export const H3_MAX_RESOLUTION = 15
19
17
 
20
18
  /**
21
- * A H3 cell index, full 64 bits.
22
- *
23
- * Written as 15 hex characters because the top nibble of a cell index is always zero: bit 63 is reserved, and the 4-bit
24
- * mode field that follows is `1` for a cell, which lands entirely inside the second nibble. That is why every cell
25
- * index printed here begins with `8`.
26
- *
27
- * @type {string}
28
- * @title H3 Cell Index
29
- * @pattern ^[0-9a-f]{15}$
19
+ * A H3 cell index, full 64 bits, written as 15 lowercase hex characters matching `^[0-9a-f]{15}$`.
30
20
  */
31
21
  export type H3Cell = Tagged<string, "H3Cell">
32
22
 
33
23
  /**
34
- * Is `value` a real H3 cell index?
35
- *
36
- * Delegates to h3-js rather than testing the surface shape. The shape is necessary but nowhere near sufficient —
37
- * `000000000000000`, `fffffffffffffff` and `123456789abcdef` are all fifteen lowercase hex characters and none of them
38
- * is a cell. A guard that returns `value is H3Cell` on those hands the caller a branded type it has not earned, and the
39
- * error surfaces later inside h3-js with no reference to where the bad value entered.
24
+ * Is `value` a real H3 cell index, delegating to h3-js because the hex surface
25
+ * shape is necessary but not sufficient.
40
26
  */
41
27
  export function isH3Cell(value: string): value is H3Cell {
42
28
  return isValidCell(value)
@@ -44,15 +30,11 @@ export function isH3Cell(value: string): value is H3Cell {
44
30
 
45
31
  /**
46
32
  * A H3 cell index with its mode and resolution nibbles removed — the low 52 bits, fixed width.
47
- *
48
- * @type {string}
49
- * @title H3 Cell Index (Short)
50
- * @pattern ^[0-9a-f]{13}$
51
33
  */
52
34
  export type H3CellShort = Tagged<string, "H3CellShort">
53
35
 
54
36
  /**
55
- * Number of hex characters in the short form. 52 bits: a 7-bit base cell followed by fifteen 3-bit digits.
37
+ * Number of hex characters in the short form: 52 bits, a 7-bit base cell followed by fifteen 3-bit digits.
56
38
  */
57
39
  const SHORT_CELL_HEX_LENGTH = 13
58
40
 
@@ -62,15 +44,8 @@ const SHORT_CELL_HEX_LENGTH = 13
62
44
  const SHORT_CELL_MASK = 0xf_ff_ff_ff_ff_ff_ffn
63
45
 
64
46
  /**
65
- * Strip the mode and resolution nibbles off a full H3 cell index, keeping the base cell and the whole digit path.
66
- *
67
- * The digits past the cell's own resolution are all `7` in a valid index, so nothing is discarded and nothing is
68
- * inferred: the short form carries the cell losslessly for every resolution, and {@link expandH3Cell} reverses it
69
- * exactly once you tell it which resolution the cell was captured at.
70
- *
71
- * Zero-padded to a fixed 13 characters, so the hex form orders and compares the same way the integer
72
- * {@link shortCellToInt} packs does. Base cells 0-7 leave the leading nibble zero, and an unpadded string would both
73
- * mis-sort and mis-expand.
47
+ * Strip the mode and resolution nibbles off a full H3 cell index, keeping the base cell
48
+ * and the whole digit path, zero-padded to a fixed 13 characters so hex order matches integer order.
74
49
  */
75
50
  export function shortenH3Cell(cell: H3Cell): H3CellShort {
76
51
  const cellBigInt = BigInt(`0x${cell}`)
@@ -80,21 +55,8 @@ export function shortenH3Cell(cell: H3Cell): H3CellShort {
80
55
  }
81
56
 
82
57
  /**
83
- * Rebuild a full H3 cell index from a short cell captured at `resolution`.
84
- *
85
- * The short form drops only the mode and resolution nibbles, so reconstruction is a straight concatenation: `"8"` (cell
86
- * mode) + the resolution nibble + the 52 bits verbatim. The result is the identical index `latLngToCell` would have
87
- * produced at that resolution.
88
- *
89
- * `resolution` is a required piece of external knowledge — a short cell does not name its own resolution, so the caller
90
- * has to supply the one the cell was shortened at. Supplying the wrong one is caught rather than tolerated: a mismatch
91
- * leaves digits past the stated resolution set to something other than `7`, which H3 rejects, and this throws instead
92
- * of returning an index that downstream `cellToParent` calls would refuse with `Cell arguments had incompatible
93
- * resolutions`.
94
- *
95
- * @throws {RangeError} If `resolution` is not an integer in `[0, 15]`, or `h3CellShort` is wider than 13 hex
96
- * characters.
97
- * @throws {Error} If the short cell and resolution do not together name a valid H3 cell.
58
+ * Rebuild a full H3 cell index from a short cell captured at `resolution`, throwing
59
+ * when the resolution is out of range or the pair does not name a valid cell.
98
60
  */
99
61
  export function expandH3Cell(h3CellShort: H3CellShort, resolution = H3_MAX_RESOLUTION): H3Cell {
100
62
  if (!Number.isInteger(resolution) || resolution < 0 || resolution > H3_MAX_RESOLUTION) {
@@ -121,45 +83,31 @@ export function expandH3Cell(h3CellShort: H3CellShort, resolution = H3_MAX_RESOL
121
83
  }
122
84
 
123
85
  /**
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.
86
+ * The full H3 index for a short cell held as an integer, stored at `resolution`,
87
+ * through {@link expandH3Cell} so an invalid pair throws rather than reaching `compactCells`.
128
88
  */
129
89
  export function expandShortCellInt(shortCell: number, resolution: number): H3Cell {
130
90
  return expandH3Cell(shortCell.toString(16).padStart(SHORT_CELL_HEX_LENGTH, "0") as H3CellShort, resolution)
131
91
  }
132
92
 
133
93
  /**
134
- * Pack an H3 cell into the short-cell integer used as a clustered B-tree key across layer databases (poi.db, bdc.db,
135
- * address-id). 52 bits, so it stays inside `Number.MAX_SAFE_INTEGER` and SQLite's signed 64-bit integer column alike.
94
+ * Pack an H3 cell into the short-cell integer used as a clustered B-tree key across layer databases —
95
+ * 52 bits, inside `Number.MAX_SAFE_INTEGER` and SQLite's signed 64-bit integer column.
136
96
  */
137
97
  export function shortCellToInt(cell: H3Cell): number {
138
98
  return Number(BigInt(`0x${shortenH3Cell(cell)}`))
139
99
  }
140
100
 
141
101
  /**
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.
102
+ * The one resolution a set of stored short cells was captured at, recovered by keeping
103
+ * the resolution at which a short cell expands to a valid index.
156
104
  */
157
105
  export function recoverShortCellResolution(cells: readonly number[], context = "layer coverage"): number {
158
106
  if (!cells.length) {
159
107
  throw new Error(`${context}: the coverage layer holds no cells — there is no resolution to recover`)
160
108
  }
161
109
 
162
- let recovered: number | undefined
110
+ let recovered: number | null = null
163
111
 
164
112
  for (const cell of cells) {
165
113
  const short = BigInt(cell).toString(16).padStart(SHORT_CELL_HEX_LENGTH, "0") as H3CellShort
@@ -170,8 +118,7 @@ export function recoverShortCellResolution(cells: readonly number[], context = "
170
118
  expandH3Cell(short, resolution)
171
119
  valid.push(resolution)
172
120
  } 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.
121
+ // A resolution the short cell does not expand at — every cell expands at exactly one.
175
122
  }
176
123
  }
177
124
 
@@ -183,7 +130,7 @@ export function recoverShortCellResolution(cells: readonly number[], context = "
183
130
 
184
131
  const resolution = valid[0]!
185
132
 
186
- if (recovered === undefined) {
133
+ if (recovered === null) {
187
134
  recovered = resolution
188
135
 
189
136
  continue
@@ -200,11 +147,9 @@ export function recoverShortCellResolution(cells: readonly number[], context = "
200
147
  }
201
148
 
202
149
  /**
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.
150
+ * Reconstruct a short-cell int's ancestor at a coarser resolution from the
151
+ * stored cell itself rather than a centroid.
152
+ * A centroid can land in a different parent.
208
153
  */
209
154
  export function shortCellToParentInt(shortCell: number, from: number, to: number): number {
210
155
  return shortCellToInt(cellToParent(expandShortCellInt(shortCell, from), to) as H3Cell)
@@ -4,10 +4,10 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
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.
7
+ * resolution, read through the layer interface's shared row mapping.
8
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
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 include the layer interface's Kysely graph. Import it from the
11
11
  * `@mailwoman/spatial/h3/coverage` subpath.
12
12
  */
13
13
 
@@ -24,21 +24,25 @@ export interface CoverageRowProbe {
24
24
  }
25
25
 
26
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}`.
27
+ * The coverage row for `indexCell`'s parent at the coverage resolution.
28
+ * It is `null` when the cell was never surveyed.
29
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.
30
+ * A caller must treat it as an unknown value, separate from `{completeness: 0}`.
31
+ *
32
+ * The shared mapping owns the NULL-basis rule.
33
+ * A NULL column means the artifact predates `basis`.
34
+ *
35
+ * It recorded source presence and no stronger basis than the builder had.
32
36
  */
33
37
  export function readCoverageAt(
34
38
  select: CoverageRowProbe,
35
39
  indexCell: H3Cell,
36
40
  coverageResolution: number
37
- ): (CoverageCell & { h3CellIndex: string; resolution: number }) | undefined {
41
+ ): (CoverageCell & { h3CellIndex: string; resolution: number }) | null {
38
42
  const coverageCell = cellToParent(indexCell, coverageResolution) as H3Cell
39
43
 
40
44
  return toCoverageCell(
41
- select.get(shortCellToInt(coverageCell)) as CoverageRow | undefined,
45
+ (select.get(shortCellToInt(coverageCell)) as CoverageRow | undefined) ?? null,
42
46
  coverageCell,
43
47
  coverageResolution
44
48
  )
@@ -3,53 +3,33 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * Turn an outline into the H3 cell set a coverage claim may be keyed to.
7
- *
8
- * Polyfilling a rectangle is right for a rectangular extract and wrong for a region: a region is
9
- * clipped to a polygon, so a rectangle polyfilled over it claims survey across whatever the rectangle
10
- * overhangs. These helpers answer the narrower question — which cells lie wholly INSIDE the outline —
11
- * and they answer conservatively, because the cells they return are the ones a completeness claim will
12
- * be written to.
13
- *
14
- * Interior is two tests, both required. A cell must have its whole `gridDisk(cell, 1)` inside the
15
- * outline's own polyfill, and all six of its boundary vertices inside the polygon. The first removes the
16
- * polyfill's edge ring (H3's polyfill keeps a cell whose CENTRE is inside, so an edge cell can be half
17
- * outside); the second catches a boundary that re-enters between two neighbours. Neither test alone is
18
- * sufficient, and the cost of being wrong is asymmetric — a cell wrongly called interior claims a survey
19
- * over ground the source never covered.
20
- *
21
- * Measured on the Île-de-France région (OSM relation 8649, admin_level 4) at res 6: 371 polyfilled
22
- * cells, 290 interior, holding 3,248 of the extract's 3,308 `amenity=pharmacy` features.
6
+ * Turn an outline into the H3 cell set a coverage claim may be keyed to, conservatively: a cell
7
+ * must have its whole `gridDisk(cell, 1)` and all six boundary vertices inside the outline.
23
8
  */
24
9
 
10
+ import { stringifyJSON } from "@mailwoman/core/json"
25
11
  import { cellToBoundary, gridDisk, polygonToCells } from "h3-js"
26
12
 
27
13
  import { arealPolygons, geometryContains, type ParsedGeometry, type PolygonRings } from "#geometries/polygon"
28
14
  import { shortCellToInt, type H3Cell } from "#h3/cell"
29
15
 
30
16
  /**
31
- * The rings a polyfill walks: every polygon's OUTER ring. Holes are deliberately not subtracted here — a hole would
32
- * only ever remove cells, and the interior test below re-checks every returned cell's vertices against the full
33
- * geometry (holes included), so a hole cannot survive into the result.
17
+ * The rings a polyfill walks: every polygon's outer ring, with holes deliberately not
18
+ * subtracted because the interior test re-checks vertices against the full geometry.
34
19
  */
35
20
  function outerRings(geometry: ParsedGeometry): PolygonRings {
36
21
  const polygons = arealPolygons(geometry)
37
22
 
38
23
  if (!polygons) {
39
- throw new Error(
40
- `coverage region: expected a Polygon or MultiPolygon geometry, got ${JSON.stringify(geometry.type)}`
41
- )
24
+ throw new Error(`coverage region: expected a Polygon or MultiPolygon geometry, got ${stringifyJSON(geometry.type)}`)
42
25
  }
43
26
 
44
27
  return polygons.filter((rings) => rings.length).map((rings) => rings[0]!)
45
28
  }
46
29
 
47
30
  /**
48
- * The outline's bounding rectangle, for pre-clipping a reference inventory that can only be probed by range.
49
- *
50
- * A coarse filter and nothing more — it CONTAINS the outline and is never the outline. The exact clip is
51
- * {@link interiorCoverageCellSet}; using this rectangle as the region would claim survey over every corner the outline
52
- * does not reach.
31
+ * The outline's bounding rectangle, for pre-clipping a reference inventory that can only
32
+ * be probed by range — a coarse filter that contains the outline and is never the outline.
53
33
  */
54
34
  export function geometryBBox(geometry: ParsedGeometry): {
55
35
  minLon: number
@@ -90,8 +70,8 @@ export function geometryBBox(geometry: ParsedGeometry): {
90
70
  }
91
71
 
92
72
  /**
93
- * Every cell whose CENTRE falls inside `geometry`, at `resolution`. The raw polyfill — {@link interiorCoverageCells}
94
- * narrows it.
73
+ * Every cell whose center falls inside `geometry`, at `resolution` — the raw
74
+ * polyfill that {@link interiorCoverageCells} narrows.
95
75
  */
96
76
  export function regionCoverageCells(geometry: ParsedGeometry, resolution: number): H3Cell[] {
97
77
  const cells = new Set<string>()
@@ -109,8 +89,7 @@ export function regionCoverageCells(geometry: ParsedGeometry, resolution: number
109
89
  }
110
90
 
111
91
  /**
112
- * The cells of {@link regionCoverageCells} that lie wholly inside `geometry` — see the module docstring for why both
113
- * tests are applied.
92
+ * The cells of {@link regionCoverageCells} that lie wholly inside `geometry`.
114
93
  */
115
94
  export function interiorCoverageCells(geometry: ParsedGeometry, resolution: number): H3Cell[] {
116
95
  const polyfilled = new Set<string>(regionCoverageCells(geometry, resolution))
@@ -130,8 +109,8 @@ export function interiorCoverageCells(geometry: ParsedGeometry, resolution: numb
130
109
  }
131
110
 
132
111
  /**
133
- * The 48-bit short-cell form of {@link interiorCoverageCells}, as a membership set — the shape both a row clipper and a
134
- * coverage writer probe.
112
+ * The 48-bit short-cell form of {@link interiorCoverageCells}, as a membership set —
113
+ * the shape both a row clipper and a coverage writer probe.
135
114
  */
136
115
  export function interiorCoverageCellSet(geometry: ParsedGeometry, resolution: number): Set<number> {
137
116
  return new Set(interiorCoverageCells(geometry, resolution).map((cell) => shortCellToInt(cell)))