@mailwoman/spatial 9.4.0 → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/README.md +2 -2
  2. package/lib/bbox.ts +41 -34
  3. package/lib/{coordinate-bounds.ts → coordinate/bounds.ts} +2 -2
  4. package/lib/{coordinate-formats.ts → coordinate/formats.ts} +11 -28
  5. package/lib/distance.ts +53 -27
  6. package/lib/feature.ts +2 -2
  7. package/lib/geometries/point.ts +41 -33
  8. package/lib/geometries/polygon.ts +24 -128
  9. package/lib/geometries/ring-blob.ts +33 -130
  10. package/lib/google/place-id.ts +4 -2
  11. package/lib/h3/cell.ts +21 -76
  12. package/lib/h3/coverage.ts +11 -7
  13. package/lib/h3/interior-cells.ts +13 -34
  14. package/lib/h3/polygon-cells.ts +59 -165
  15. package/lib/{h3/index.ts → h3.ts} +1 -1
  16. package/lib/index.ts +6 -6
  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 +20 -4
  22. package/lib/projection/transform.ts +114 -0
  23. package/lib/projection.ts +1 -1
  24. package/lib/well-known-text.ts +8 -8
  25. package/out/bbox.d.ts +16 -13
  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 → coordinate/bounds.d.ts} +3 -3
  30. package/out/coordinate/bounds.d.ts.map +1 -0
  31. package/out/{coordinate-bounds.js → coordinate/bounds.js} +3 -3
  32. package/out/coordinate/bounds.js.map +1 -0
  33. package/out/{coordinate-formats.d.ts → coordinate/formats.d.ts} +9 -12
  34. package/out/coordinate/formats.d.ts.map +1 -0
  35. package/out/{coordinate-formats.js → coordinate/formats.js} +12 -29
  36. package/out/coordinate/formats.js.map +1 -0
  37. package/out/distance.d.ts +48 -25
  38. package/out/distance.d.ts.map +1 -1
  39. package/out/distance.js +53 -27
  40. package/out/distance.js.map +1 -1
  41. package/out/feature.d.ts +2 -2
  42. package/out/feature.d.ts.map +1 -1
  43. package/out/geometries/point.d.ts +30 -22
  44. package/out/geometries/point.d.ts.map +1 -1
  45. package/out/geometries/point.js +35 -29
  46. package/out/geometries/point.js.map +1 -1
  47. package/out/geometries/polygon.d.ts +23 -122
  48. package/out/geometries/polygon.d.ts.map +1 -1
  49. package/out/geometries/polygon.js +13 -41
  50. package/out/geometries/polygon.js.map +1 -1
  51. package/out/geometries/ring-blob.d.ts +23 -109
  52. package/out/geometries/ring-blob.d.ts.map +1 -1
  53. package/out/geometries/ring-blob.js +29 -115
  54. package/out/geometries/ring-blob.js.map +1 -1
  55. package/out/{geometries/index.js → geometries.d.ts} +1 -1
  56. package/out/geometries.d.ts.map +1 -0
  57. package/out/{geometries/index.d.ts → geometries.js} +1 -1
  58. package/out/geometries.js.map +1 -0
  59. package/out/google/place-id.d.ts +4 -2
  60. package/out/google/place-id.d.ts.map +1 -1
  61. package/out/google/place-id.js.map +1 -1
  62. package/out/{google/index.d.ts → google.d.ts} +1 -1
  63. package/out/google.d.ts.map +1 -0
  64. package/out/{google/index.js → google.js} +1 -1
  65. package/out/google.js.map +1 -0
  66. package/out/h3/cell.d.ts +19 -73
  67. package/out/h3/cell.d.ts.map +1 -1
  68. package/out/h3/cell.js +20 -63
  69. package/out/h3/cell.js.map +1 -1
  70. package/out/h3/coverage.d.ts +11 -7
  71. package/out/h3/coverage.d.ts.map +1 -1
  72. package/out/h3/coverage.js +11 -7
  73. package/out/h3/coverage.js.map +1 -1
  74. package/out/h3/interior-cells.d.ts +9 -28
  75. package/out/h3/interior-cells.d.ts.map +1 -1
  76. package/out/h3/interior-cells.js +13 -32
  77. package/out/h3/interior-cells.js.map +1 -1
  78. package/out/h3/polygon-cells.d.ts +28 -120
  79. package/out/h3/polygon-cells.d.ts.map +1 -1
  80. package/out/h3/polygon-cells.js +48 -146
  81. package/out/h3/polygon-cells.js.map +1 -1
  82. package/out/{h3/index.d.ts → h3.d.ts} +2 -2
  83. package/out/h3.d.ts.map +1 -0
  84. package/out/{h3/index.js → h3.js} +2 -2
  85. package/out/h3.js.map +1 -0
  86. package/out/index.d.ts +6 -6
  87. package/out/index.d.ts.map +1 -1
  88. package/out/index.js +6 -6
  89. package/out/index.js.map +1 -1
  90. package/out/objects.d.ts +6 -6
  91. package/out/objects.d.ts.map +1 -1
  92. package/out/open-location-code.d.ts +11 -22
  93. package/out/open-location-code.d.ts.map +1 -1
  94. package/out/open-location-code.js +9 -40
  95. package/out/open-location-code.js.map +1 -1
  96. package/out/osgb36.d.ts +21 -97
  97. package/out/osgb36.d.ts.map +1 -1
  98. package/out/osgb36.js +12 -165
  99. package/out/osgb36.js.map +1 -1
  100. package/out/polyline.d.ts +5 -3
  101. package/out/polyline.d.ts.map +1 -1
  102. package/out/polyline.js +5 -3
  103. package/out/polyline.js.map +1 -1
  104. package/out/position.d.ts +17 -3
  105. package/out/position.d.ts.map +1 -1
  106. package/out/position.js +2 -2
  107. package/out/position.js.map +1 -1
  108. package/out/projection/transform.d.ts +70 -0
  109. package/out/projection/transform.d.ts.map +1 -0
  110. package/out/{projection-transform.js → projection/transform.js} +15 -17
  111. package/out/projection/transform.js.map +1 -0
  112. package/out/projection.d.ts +1 -1
  113. package/out/projection.d.ts.map +1 -1
  114. package/out/projection.js +1 -1
  115. package/out/regions/codes.d.ts.map +1 -1
  116. package/out/{regions/index.js → regions.d.ts} +1 -1
  117. package/out/regions.d.ts.map +1 -0
  118. package/out/{regions/index.d.ts → regions.js} +1 -1
  119. package/out/regions.js.map +1 -0
  120. package/out/tools/ogr/stream.d.ts +44 -0
  121. package/out/tools/ogr/stream.d.ts.map +1 -0
  122. package/out/tools/{ogr-stream.js → ogr/stream.js} +17 -10
  123. package/out/tools/ogr/stream.js.map +1 -0
  124. package/out/tools/ogr.d.ts +13 -10
  125. package/out/tools/ogr.d.ts.map +1 -1
  126. package/out/tools/ogr.js +18 -14
  127. package/out/tools/ogr.js.map +1 -1
  128. package/out/tools/tsconfig.tsbuildinfo +1 -0
  129. package/out/tsconfig.test.tsbuildinfo +1 -1
  130. package/out/well-known-text.d.ts +8 -8
  131. package/out/well-known-text.js +7 -7
  132. package/package.json +35 -127
  133. package/{lib/tools/ogr-stream.ts → tools/ogr/stream.ts} +25 -14
  134. package/{lib/tools → tools}/ogr.ts +26 -20
  135. package/lib/projection-transform.ts +0 -115
  136. package/out/coordinate-bounds.d.ts.map +0 -1
  137. package/out/coordinate-bounds.js.map +0 -1
  138. package/out/coordinate-formats.d.ts.map +0 -1
  139. package/out/coordinate-formats.js.map +0 -1
  140. package/out/geometries/index.d.ts.map +0 -1
  141. package/out/geometries/index.js.map +0 -1
  142. package/out/google/index.d.ts.map +0 -1
  143. package/out/google/index.js.map +0 -1
  144. package/out/h3/index.d.ts.map +0 -1
  145. package/out/h3/index.js.map +0 -1
  146. package/out/projection-transform.d.ts +0 -67
  147. package/out/projection-transform.d.ts.map +0 -1
  148. package/out/projection-transform.js.map +0 -1
  149. package/out/regions/index.d.ts.map +0 -1
  150. package/out/regions/index.js.map +0 -1
  151. package/out/tools/ogr-stream.d.ts +0 -34
  152. package/out/tools/ogr-stream.d.ts.map +0 -1
  153. package/out/tools/ogr-stream.js.map +0 -1
  154. /package/lib/{geometries/index.ts → geometries.ts} +0 -0
  155. /package/lib/{google/index.ts → google.ts} +0 -0
  156. /package/lib/{regions/index.ts → regions.ts} +0 -0
@@ -3,60 +3,8 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * Turn one authority polygon into the H3 cells that summarize it — the conversion SCOPE invariant 6 asks
7
- * for, done once at build time so the runtime probes structure instead of geometry.
8
- *
9
- * SHARED BY EVERY POLYGON LAYER RATHER THAN COPIED INTO EACH, because the traps below are properties of
10
- * the TOOL rather than of any one product. `packages/flood` measured them; `packages/soil` inherits them
11
- * unchanged; the layer contract's polygon-builder section states them as requirements. A second copy of
12
- * an allocator guard is a second place for it to stop guarding.
13
- *
14
- * THE INDEX IS CELL-TOUCHES-POLYGON, NOT CENTRE-IN-POLYGON, AND A ZERO-CELL FEATURE FAILS THE BUILD.
15
- * A polyfill keyed on cell centres drops every polygon smaller than a cell, and each dropped feature
16
- * reads downstream as an absence. Measured: on Ireland's zoning layer `polygonToCells` returns zero cells
17
- * for 86.8% of polygons at resolution 9, and the EA flood product's first row is a 128 m² square that
18
- * `polygonToCells` misses at resolutions 7 through 10 while `containmentOverlapping` returns one cell for
19
- * it. So the index takes overlapping containment, and {@link classifyFeatureCells} throws on a feature
20
- * that reaches no cell rather than skipping it.
21
- *
22
- * THE `[lat, lng]` TRAP IS AVOIDED BY NOT ENTERING IT. h3-js reads a vertex as `[lat, lng]` in its
23
- * default mode; every call here passes `isGeoJSON = true` and hands it GeoJSON-order `[lon, lat]` rings,
24
- * which is the order an ingest already produces. Converting instead would put a transposition between the
25
- * geometry and the index that nothing downstream could see.
26
- *
27
- * WHOLE AND PARTIAL ARE TWO POLYFILLS OF THE SAME RING, NOT A TEST WE INVENT. `containmentFull` is the
28
- * cell set entirely inside the polygon; `containmentOverlapping` is the set that touches it at all. The
29
- * difference is exactly the boundary fringe, which is where the geometry tier has to be consulted.
30
- *
31
- * MOST PARTS NEVER REACH h3 AT ALL, AND THAT IS THE POINT. The WASM heap is exhausted by CALL VOLUME, not
32
- * by any one polygon: h3-js frees every buffer it allocates, so what accumulates over millions of
33
- * interleaved tiny and large allocations is fragmentation. Three runs over the EA product died on the
34
- * same feature after roughly 510,000 others — a 164 m² feature of 23 parts and 130 vertices that
35
- * classifies in 35 ms at every resolution 9 through 4 in a fresh process. So the calls are removed rather
36
- * than shrunk, in the two places where the answer is a fact about geometry: {@link enclosingCell} (a part
37
- * whose bounding-box corners all fall in one cell lies inside it, because a cell is convex) and
38
- * {@link canContainCell} (a part narrower than `edge × √3` cannot enclose a hexagon, so its
39
- * `containmentFull` set is empty). Both were checked against the unconditional polyfill over 60,000 real
40
- * features at resolution 9 with zero disagreements, and `packages/flood/test/unit/cells.test.ts` pins the
41
- * comparison.
42
- *
43
- * A BIG POLYGON IS ALSO INDEXED COARSER, BECAUSE h3's ALLOCATOR IS SIZED FROM THE BOUNDING BOX.
44
- * `polygonToCells` reserves room for the whole bounding box before it walks anything, so a long thin river
45
- * polygon reserves the rectangle the river's meanders span rather than the river. Each feature is
46
- * therefore indexed at the finest resolution whose bounding-box estimate fits {@link CELL_ESTIMATE_BUDGET},
47
- * and the resolution it got is returned on the result. That is not a compromise bolted on: a coarse cell
48
- * wholly inside a large polygon is exactly what `compactCells` would have produced anyway, so the whole
49
- * tier is unchanged in meaning and only the fringe is coarser.
50
- *
51
- * AND THE ESTIMATE IS A PREDICTION, SO AN ALLOCATION FAILURE IS RECOVERED RATHER THAN FATAL.
52
- * {@linkcode classifyFeatureCells} steps the resolution down and retries; only a feature that fails at
53
- * {@linkcode MIN_INDEX_RESOLUTION} is refused. Nothing is ever skipped, because a skipped feature is an
54
- * invented absence.
55
- *
56
- * BOUNDING THE CALL VOLUME IS THE CALLER'S JOB AND IT IS NOT OPTIONAL. The shortcuts here make a build
57
- * faster; they are not what makes it reproducible. A builder runs the classification in child processes
58
- * over ranges of the source's own stable ids, so each gets a heap that starts empty — see
59
- * `packages/flood/lib/sdk/ingest-chunk.ts` and `packages/soil/lib/sdk/ingest-chunk.ts`.
6
+ * Turn one authority polygon into the H3 cells that summarize it, done once at build time so the
7
+ * runtime probes structure instead of geometry.
60
8
  */
61
9
 
62
10
  import {
@@ -71,41 +19,29 @@ import {
71
19
  POLYGON_TO_CELLS_FLAGS,
72
20
  } from "h3-js"
73
21
 
22
+ import type { LatLonBounds } from "#bbox"
74
23
  import { METRES_PER_DEGREE } from "#distance"
75
24
  import type { MultiPolygonRings } from "#geometries/polygon"
76
25
  import { ringsBoundingBox } from "#geometries/ring-blob"
77
26
  import { shortCellToInt, type H3Cell } from "#h3/cell"
78
27
 
79
28
  /**
80
- * The largest bounding-box cell estimate a single polyfill may reserve.
81
- *
82
- * H3-js allocates its output buffer from the polygon's bounding box before walking, so this is a memory ceiling rather
83
- * than a limit on real output: two million cells is sixteen megabytes of `uint64`, comfortably inside the WASM heap,
84
- * and the largest EA flood features exceed it by orders of magnitude at resolution 9 (the run that established this
85
- * failed with `Memory allocation failed (code: 13)`).
29
+ * The largest bounding-box cell estimate a single polyfill may reserve, a memory ceiling
30
+ * because h3-js allocates its output buffer from the polygon's bounding box before walking.
86
31
  */
87
32
  export const CELL_ESTIMATE_BUDGET = 2_000_000
88
33
 
89
34
  /**
90
- * The coarsest resolution a feature may be pushed down to. Below this a "cell" is tens of thousands of square
91
- * kilometres and the index stops summarizing anything.
35
+ * The coarsest resolution a feature may be pushed down to, below which a cell is tens
36
+ * of thousands of square kilometers and the index stops summarizing anything.
92
37
  */
93
38
  export const MIN_INDEX_RESOLUTION = 4
94
39
 
95
40
  /**
96
- * A rectangle in degrees, the shape every helper here prefilters on.
97
- */
98
- export interface DegreeBox {
99
- minLat: number
100
- minLon: number
101
- maxLat: number
102
- maxLon: number
103
- }
104
-
105
- /**
106
- * A degree box's height and width in metres, longitude scaled at the box's mid-latitude so the two are comparable.
41
+ * A degree box's height and width in meters, longitude scaled at the box's
42
+ * mid-latitude so the two are comparable.
107
43
  */
108
- function boxExtentMetres(box: DegreeBox): { heightM: number; widthM: number } {
44
+ function boxExtentMetres(box: LatLonBounds): { heightM: number; widthM: number } {
109
45
  const midLat = ((box.minLat + box.maxLat) / 2) * (Math.PI / 180)
110
46
 
111
47
  return {
@@ -115,14 +51,10 @@ function boxExtentMetres(box: DegreeBox): { heightM: number; widthM: number } {
115
51
  }
116
52
 
117
53
  /**
118
- * The single cell containing this whole bounding box, or `undefined` when it spans more than one.
119
- *
120
- * An H3 cell is convex, so a rectangle whose four corners all fall in the same cell lies entirely inside it. That makes
121
- * this an exact answer rather than an approximation, and it takes the WASM polyfill off the majority of a small-polygon
122
- * product's parts: 38.8% of the EA flood features are under 11 m across, and most parts of the multi-part ones are
123
- * smaller still.
54
+ * The single cell containing this whole bounding box, or `undefined` when it spans
55
+ * more than one — exact because an H3 cell is convex.
124
56
  */
125
- function enclosingCell(box: DegreeBox, resolution: number): string | undefined {
57
+ function enclosingCell(box: LatLonBounds, resolution: number): string | undefined {
126
58
  if (!Number.isFinite(box.minLat)) return undefined
127
59
 
128
60
  const first = latLngToCell(box.minLat, box.minLon, resolution)
@@ -139,14 +71,10 @@ function enclosingCell(box: DegreeBox, resolution: number): string | undefined {
139
71
  }
140
72
 
141
73
  /**
142
- * Could a shape this size contain a whole cell?
143
- *
144
- * A hexagon's minimum width is twice its inradius, and its inradius is `edge × √3/2` — so a bounding box narrower than
145
- * `edge × √3` in either direction cannot enclose one, and the `containmentFull` polyfill is guaranteed to return
146
- * nothing. The comparison is deliberately permissive: a wrong `true` costs one polyfill call, while a wrong `false`
147
- * would demote a whole cell to a partial one, which the ray cast still answers correctly but more slowly.
74
+ * Could a shape this size contain a whole cell — false when either bounding-box dimension is
75
+ * under `edge × √3`, compared permissively because a wrong `true` only costs one polyfill call.
148
76
  */
149
- function canContainCell(box: DegreeBox, resolution: number): boolean {
77
+ function canContainCell(box: LatLonBounds, resolution: number): boolean {
150
78
  if (!Number.isFinite(box.minLat)) return false
151
79
 
152
80
  const minimumWidthM = getHexagonEdgeLengthAvg(resolution, "m") * Math.sqrt(3)
@@ -156,28 +84,28 @@ function canContainCell(box: DegreeBox, resolution: number): boolean {
156
84
  }
157
85
 
158
86
  /**
159
- * The two cell sets one feature produces, and the resolution they came out at.
87
+ * The two cell sets produced by one feature.
88
+ * The record also stores their resolution.
160
89
  */
161
90
  export interface FeatureCells {
162
91
  /**
163
- * The resolution this feature was indexed at — the target, or coarser where the target's estimate did not fit.
92
+ * The resolution this feature was indexed at — the target, or coarser
93
+ * where the target's estimate did not fit.
164
94
  */
165
95
  resolution: number
166
96
  /**
167
- * Cells lying entirely inside the feature. A point in one of these is inside without a geometry read.
97
+ * Cells lying entirely inside the feature, so a point in one is inside without a geometry read.
168
98
  */
169
99
  whole: H3Cell[]
170
100
  /**
171
- * Cells the feature reaches but does not fill. A point in one of these needs the ray cast.
101
+ * Cells the feature reaches but does not fill, so a point in one needs the ray cast.
172
102
  */
173
103
  partial: H3Cell[]
174
104
  }
175
105
 
176
106
  /**
177
- * How many cells at `resolution` the feature's bounding box spans.
178
- *
179
- * The same quantity h3 reserves its buffer from, computed here so an oversized polyfill is never issued. Approximate on
180
- * purpose: it decides which resolution to ask for, not what the answer is.
107
+ * How many cells at `resolution` the feature's bounding box spans — the same quantity
108
+ * h3 reserves its buffer from, approximate on purpose.
181
109
  */
182
110
  export function estimateCellCount(polygons: MultiPolygonRings, resolution: number): number {
183
111
  const box = ringsBoundingBox(polygons)
@@ -203,12 +131,8 @@ export function resolutionForFeature(polygons: MultiPolygonRings, target: number
203
131
  }
204
132
 
205
133
  /**
206
- * Classify one feature's cells, at `targetResolution` or the coarsest resolution its bounding box allows.
207
- *
208
- * @param layerLabel Names the layer in every message, so a build log says which artifact refused rather than only which
209
- * feature.
210
- * @throws {Error} When the feature reaches no cell at all. That cannot happen with overlapping containment on a valid
211
- * ring, so it means the geometry is degenerate — and a silently skipped feature is an invented absence.
134
+ * Classify one feature's cells at `targetResolution` or the coarsest resolution its
135
+ * bounding box allows, throwing when the feature reaches no cell at all.
212
136
  */
213
137
  export function classifyFeatureCells(
214
138
  polygons: MultiPolygonRings,
@@ -220,28 +144,23 @@ export function classifyFeatureCells(
220
144
  let touched = new Set<string>()
221
145
  let full = new Set<string>()
222
146
 
223
- // THE BUDGET IS A PREDICTION AND THE RETRY IS WHAT MAKES IT NON-FATAL. `estimateCellCount` is a bounding-box
224
- // approximation of what h3 will reserve, and h3's own reservation depends on the polygon's shape and on what the WASM
225
- // heap already holds — measured over the EA product, a run that had classified 350,000 features threw `Memory
226
- // allocation failed (code: 13)` on a feature that classified cleanly on its own. So an allocation failure steps the
227
- // resolution down and tries again rather than ending the build, and only a feature that fails at
228
- // {@link MIN_INDEX_RESOLUTION} is refused: a coarser cell is a real answer, and a skipped feature is an invented
229
- // absence.
147
+ // `estimateCellCount` approximates what h3 will reserve, so an allocation failure
148
+ // steps the resolution down and retries rather than ending the build. a feature
149
+ // that fails at {@link MIN_INDEX_RESOLUTION} is refused.
230
150
  for (;;) {
231
151
  try {
232
152
  touched = new Set<string>()
233
153
  full = new Set<string>()
234
154
 
235
155
  for (const rings of polygons) {
236
- // `isGeoJSON = true`: the rings are already `[lon, lat]`, which is the order an ingest emits. Converting
237
- // instead would put a transposition between the geometry and the index that nothing downstream could see.
156
+ // `isGeoJSON = true`: the rings are already `[lon, lat]`, so converting would
157
+ // put a transposition between the geometry and the index.
238
158
  const geoJSONRings = rings as number[][][]
239
159
  const box = ringsBoundingBox([rings])
240
160
  const enclosing = enclosingCell(box, resolution)
241
161
 
242
- // A PART THAT FITS INSIDE ONE CELL IS ANSWERED WITHOUT THE ALLOCATOR, and that is a fact rather than an
243
- // approximation: an H3 cell is convex, so a rectangle whose four corners all fall in one cell lies entirely
244
- // within it. Such a part touches exactly that cell and fills none of it.
162
+ // A part that fits inside one cell is answered without the allocator: an H3 cell
163
+ // is convex, so a rectangle whose corners share a cell lies entirely within it.
245
164
  if (enclosing) {
246
165
  touched.add(enclosing)
247
166
 
@@ -255,12 +174,9 @@ export function classifyFeatureCells(
255
174
  true
256
175
  )
257
176
 
258
- // AN EMPTY ANSWER FOR A REAL PART IS AN ALLOCATOR FAILURE WEARING A RESULT'S CLOTHES, and it has to be caught
259
- // HERE rather than after the whole feature. h3-js sizes its output buffer with `_calloc`, and a `_calloc`
260
- // that fails returns the null pointer — which in WASM is ordinary writable memory, so the call reports
261
- // success and the reader hands back an array of zeros, i.e. nothing. Every part with a non-degenerate
262
- // bounding box touches at least one cell, so zero is impossible as an answer. Checking per FEATURE instead
263
- // would pass any multi-part feature whose other parts happened to answer, and silently index it short.
177
+ // An empty answer for a real part is an allocator failure rather than a result: every part
178
+ // with a non-degenerate bounding box touches at least one cell, so zero is impossible as
179
+ // an answer and checking per feature would silently index a multi-part feature short.
264
180
  if (!overlapping.length) {
265
181
  throw new Error(
266
182
  `${layerLabel}: part of feature ${featureID} spanning ${box.minLat},${box.minLon} to ${box.maxLat},${box.maxLon} returned no cell at resolution ${resolution} — a part always touches at least one, so this is an allocator failure reported as an answer`
@@ -271,9 +187,10 @@ export function classifyFeatureCells(
271
187
  touched.add(cell)
272
188
  }
273
189
 
274
- // A part narrower than a cell's minimum width cannot contain one, so its `full` set is empty and asking for it
275
- // is pure cost. Erring towards asking is safe — a missed whole cell becomes a partial one and the ray cast
276
- // still answers correctly — so the comparison is the permissive one.
190
+ // A part narrower than a cell's minimum width cannot contain one,
191
+ // so its `full` set is empty and asking for it is pure cost.
192
+ // The comparison is permissive because a missed whole cell becomes a
193
+ // partial one the ray cast still answers.
277
194
  if (!canContainCell(box, resolution)) continue
278
195
 
279
196
  for (const cell of polygonToCellsExperimental(
@@ -290,9 +207,8 @@ export function classifyFeatureCells(
290
207
  } catch (error) {
291
208
  if (resolution <= MIN_INDEX_RESOLUTION) {
292
209
  throw new Error(
293
- `${layerLabel}: feature ${featureID} could not be indexed at any resolution down to ${MIN_INDEX_RESOLUTION} — ${String(
294
- (error as Error).message
295
- )}`
210
+ `${layerLabel}: feature ${featureID} could not be indexed at any resolution down to ${MIN_INDEX_RESOLUTION}`,
211
+ { cause: error }
296
212
  )
297
213
  }
298
214
 
@@ -306,8 +222,8 @@ export function classifyFeatureCells(
306
222
  )
307
223
  }
308
224
 
309
- // A cell can be full for one polygon of a MultiPolygon and merely touched by another; full wins, because the point
310
- // is inside either way.
225
+ // A cell can be full for one polygon of a MultiPolygon and merely touched by
226
+ // another. full wins because the point is inside either way.
311
227
  const partial: H3Cell[] = []
312
228
 
313
229
  for (const cell of touched) {
@@ -320,11 +236,8 @@ export function classifyFeatureCells(
320
236
  }
321
237
 
322
238
  /**
323
- * Split a cell set into same-resolution groups — what `compactCells` requires, and what an adaptively-indexed layer
324
- * cannot assume it already has.
325
- *
326
- * Pooling mixed resolutions throws inside h3; compacting only the target-resolution group would silently drop every
327
- * coarsened feature's interior, which is the shape of failure that still produces an artifact.
239
+ * Split a cell set into same-resolution groups — what `compactCells` requires
240
+ * and an adaptively-indexed layer cannot assume it already has.
328
241
  */
329
242
  export function groupCellsByResolution(cells: Iterable<string>): string[][] {
330
243
  const groups = new Map<number, string[]>()
@@ -344,12 +257,9 @@ export function groupCellsByResolution(cells: Iterable<string>): string[][] {
344
257
  }
345
258
 
346
259
  /**
347
- * Compact a cell set that may span several resolutions.
260
+ * Compact a cell set that spans several resolutions by grouping its cells first.
348
261
  *
349
- * `compactCells` takes one resolution at a time, and an adaptively-indexed layer's coarsened features sit at another —
350
- * so the set is grouped before compaction rather than pooled. Pooling would throw; compacting only the
351
- * target-resolution group would silently drop every coarsened feature's interior, which is the shape of failure that
352
- * still produces an artifact.
262
+ * Cells from different resolutions cause h3 to throw when pooled.
353
263
  */
354
264
  export function compactAcrossResolutions(cells: Iterable<string>): string[] {
355
265
  const compacted: string[] = []
@@ -362,12 +272,9 @@ export function compactAcrossResolutions(cells: Iterable<string>): string[] {
362
272
  }
363
273
 
364
274
  /**
365
- * The cells a probe walks for one index cell: the cell itself at the index resolution, and its parent at every other
366
- * resolution the layer stores.
275
+ * The probe visits the index cell at its own resolution.
367
276
  *
368
- * The stored rows sit at SEVERAL resolutions — each feature's whole tier is compacted parent-ward, and a polygon too
369
- * large for h3's allocator at the index resolution was indexed coarser — so a point is answered by walking its own
370
- * ancestor chain over every resolution the layer stores.
277
+ * At every other resolution stored by the layer, it visits the parent cell.
371
278
  */
372
279
  export function ancestorChainCells(
373
280
  indexCell: H3Cell,
@@ -380,16 +287,8 @@ export function ancestorChainCells(
380
287
  }
381
288
 
382
289
  /**
383
- * One classified feature's cell rows, ready for insertion — the whole set compacted, the partial set left at its own
384
- * resolution.
385
- *
386
- * SHARED BY EVERY POLYGON LAYER WHOSE CELL ROW NAMES A POLYGON rather than a class accumulated across features. There
387
- * is no product knowledge in it: compaction, the short-cell encoding and the belt-and-braces subtraction below are h3
388
- * and blob arithmetic, and a second copy is a second place for the subtraction to stop happening.
389
- *
390
- * COMPACTION IS PER FEATURE, which is what keeps a build's memory flat in row count with no temporary table: a row that
391
- * names one polygon is final the moment that polygon is classified. Only the WHOLE set is compacted — compacting the
392
- * fringe would claim it covers ground it does not.
290
+ * One classified feature's cell rows, ready for insertion — the whole set compacted,
291
+ * the partial set left at its own resolution.
393
292
  */
394
293
  export function featureCellRows(cells: FeatureCells): Array<{
395
294
  h3Cell: number
@@ -410,8 +309,9 @@ export function featureCellRows(cells: FeatureCells): Array<{
410
309
  for (const cell of cells.partial) {
411
310
  const short = shortCellToInt(cell)
412
311
 
413
- // A cell cannot be both for one polygon; the classifier already subtracts the whole set, and this is belt and braces
414
- // against a compaction that produced a parent the partial set also names.
312
+ // A cell cannot be both for one polygon.
313
+ // This subtraction is belt and braces against a compaction that produced a
314
+ // parent the partial set also names.
415
315
  if (wholeShort.has(short)) continue
416
316
 
417
317
  rows.push({ h3Cell: short, resolution: cells.resolution, containment: "partial" })
@@ -421,22 +321,16 @@ export function featureCellRows(cells: FeatureCells): Array<{
421
321
  }
422
322
 
423
323
  /**
424
- * The coverage cell a row at `cell` belongs to.
425
- *
426
- * `cellToParent` of the finer cell, never a fresh `latLngToCell` at the coarse resolution: every existing reader in
427
- * this repo derives a coverage cell that way, and the two agree for a point but not for a cell — a re-derivation from a
428
- * representative point would put a fringe row in a neighbouring coverage cell.
324
+ * The coverage cell a row at `cell` belongs to, derived with `cellToParent` rather than a
325
+ * fresh `latLngToCell` so a fringe row does not land in a neighboring coverage cell.
429
326
  */
430
327
  export function coverageCellFor(cell: H3Cell, coverageResolution: number): H3Cell {
431
328
  return cellToParent(cell, coverageResolution) as H3Cell
432
329
  }
433
330
 
434
331
  /**
435
- * Record the coverage cells one index cell falls in.
436
- *
437
- * An adaptively-coarsened cell can be COARSER than the coverage resolution, in which case it spans several coverage
438
- * cells and every one of them is recorded: a coarse cell counted against one arbitrary child would leave the others
439
- * reading as empty.
332
+ * Record the coverage cells one index cell falls in, so an adaptively-coarsened cell coarser
333
+ * than the coverage resolution counts against every child rather than one arbitrary child.
440
334
  */
441
335
  export function addCoverageCells(
442
336
  into: Set<number>,
@@ -14,7 +14,7 @@ export * from "#h3/interior-cells"
14
14
  export * from "#h3/polygon-cells"
15
15
 
16
16
  /**
17
- * Given a short cell address and the resolution it was captured at, return the centre of that cell.
17
+ * Given a short cell address and the resolution it was captured at, return the center of that cell.
18
18
  */
19
19
  export function shortCellToPoint(shortCell: H3CellShort, resolution = 15): GeoPoint {
20
20
  const cell = expandH3Cell(shortCell, resolution)
package/lib/index.ts CHANGED
@@ -5,17 +5,17 @@
5
5
  */
6
6
 
7
7
  export * from "#bbox"
8
- export * from "#coordinate-formats"
9
- export * from "#coordinate-bounds"
8
+ export * from "#coordinate/formats"
9
+ export * from "#coordinate/bounds"
10
10
  export * from "#distance"
11
11
  export * from "#feature"
12
12
  export * from "#open-location-code"
13
- export * from "#geometries/index"
14
- export * from "#google/index"
15
- export * from "#h3/index"
13
+ export * from "#geometries"
14
+ export * from "#google"
15
+ export * from "#h3"
16
16
  export * from "#objects"
17
17
  export * from "#osgb36"
18
18
  export * from "#polyline"
19
19
  export * from "#position"
20
20
  export * from "#projection"
21
- export * from "#regions/index"
21
+ export * from "#regions"
package/lib/objects.ts CHANGED
@@ -36,8 +36,8 @@ export const GeometryType = {
36
36
  /**
37
37
  * The base GeoJSON object.
38
38
  *
39
- * The GeoJSON specification also allows foreign members (https://tools.ietf.org/html/rfc7946#section-6.1) to be
40
- * included in the object.
39
+ * The GeoJSON specification also allows foreign members
40
+ * (https://tools.ietf.org/html/rfc7946#section-6.1) to be included in the object.
41
41
  *
42
42
  * @title Geo Object
43
43
  * @public
@@ -50,15 +50,15 @@ export interface GeoObjectLiteral {
50
50
  type: GeometryType
51
51
 
52
52
  /**
53
- * A unique identifier for the feature, such as a UUID, a serial number, or a name.
53
+ * A unique identifier for the feature, such as a uuid, a serial number, or a name.
54
54
  */
55
55
  id?: string | number | undefined | null
56
56
 
57
57
  /**
58
58
  * A bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections.
59
59
  *
60
- * This is useful when defining the extent of a GeoJSON object, i.e. the minimum and maximum coordinates of the
61
- * object's Geometries, Features, or Feature Collections.
60
+ * This is useful when defining the extent of a GeoJSON object, i.e. the minimum
61
+ * and maximum coordinates of the object's Geometries, Features, or Feature Collections.
62
62
  *
63
63
  * @see {@link https://tools.ietf.org/html/rfc7946#section-5 GeoJSON Bounding Boxes}
64
64
  */
@@ -77,7 +77,7 @@ export interface GeoObjectLiteral {
77
77
  /**
78
78
  * The name of the coordinate reference system.
79
79
  *
80
- * @default "EPSG:4326"
80
+ * @default "epsg:4326"
81
81
  */
82
82
  name: string
83
83
  }
@@ -2,43 +2,20 @@
2
2
  * @copyright Sister Software
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
- *
6
- * Open Location Code (plus code) decode + nearest-recovery — the coordinate system Google Maps
7
- * prints on every place card, which makes it a first-class user register in countries with sparse
8
- * street addressing (the Nicaraguan board rows arrived exactly this way). Pure arithmetic over the
9
- * published spec (https://github.com/google/open-location-code/blob/main/docs/specification.md);
10
- * no dependency, no I/O.
11
- *
12
- * A FULL code (8 digits, a `+`, then 2–3 more) decodes directly. A SHORT code (2–6 leading digits
13
- * removed, e.g. `VFQ6+92P`) is only meaningful near a reference point — the removed prefix is
14
- * recovered from the reference, then the candidate cell is shifted by whole prefix-resolutions if
15
- * a neighboring cell sits closer (the spec's `recoverNearest`). The reference in an address is the
16
- * RESOLVED LOCALITY, which is why the geocode wiring recovers after the admin walk.
17
5
  */
18
6
 
19
- /**
20
- * The 20-character OLC digit set. Deliberately excludes letters that read as words or digits (no A/E/I/L/N/O/S/T…), so
21
- * a matched token is very unlikely to be ordinary text.
22
- */
23
7
  const OLC_ALPHABET = "23456789CFGHJMPQRVWX"
24
8
 
25
9
  const OLC_DIGIT_VALUE = new Map<string, number>([...OLC_ALPHABET].map((c, i) => [c, i]))
26
10
 
27
- /**
28
- * Degree width of each pair-position, most significant first: the pair at index i spans `20^(2-i)` degrees. Ten pair
29
- * digits (five lat/lon pairs) take a cell to 1/400° ≈ 275 m; grid digits refine further.
30
- */
31
11
  const PAIR_RESOLUTIONS = [20, 1, 1 / 20, 1 / 400, 1 / 8000] as const
32
12
 
33
- /**
34
- * Grid refinement past ten digits: each digit subdivides the cell into 4 columns × 5 rows.
35
- */
36
13
  const GRID_COLUMNS = 4
37
14
  const GRID_ROWS = 5
38
15
 
39
16
  /**
40
- * A decoded plus-code cell: the center (the coordinate consumers want) plus the cell's span, from which callers price
41
- * the claim (`uncertaintyM` ≈ the half-diagonal).
17
+ * Describes a decoded plus-code cell by its center and its span in degrees, from
18
+ * which callers derive an uncertainty radius.
42
19
  */
43
20
  export interface DecodedPlusCode {
44
21
  lat: number
@@ -48,23 +25,24 @@ export interface DecodedPlusCode {
48
25
  }
49
26
 
50
27
  /**
51
- * A syntactically-valid FULL plus code: exactly 8 digits, `+`, then 2 or 3 digits. (The spec allows padded and longer
52
- * forms; addresses carry the 10–11 digit register, which is all this reader accepts.)
28
+ * Returns true for a full plus code of exactly 8 digits, `+`, and 2 or 3 digits.
29
+ *
30
+ * It rejects the padded and longer forms the spec allows, since addresses use only the 10–11 digit form.
53
31
  */
54
32
  export function isFullPlusCode(token: string): boolean {
55
33
  return /^[23456789CFGHJMPQRVWX]{8}\+[23456789CFGHJMPQRVWX]{2,3}$/i.test(token)
56
34
  }
57
35
 
58
36
  /**
59
- * A syntactically-valid SHORT plus code: 2, 4, or 6 leading digits removed — so 6, 4, or 2 digits before the `+`. The
60
- * 4-before-`+` form (`VFQ6+92P`) is the one Google prints on place cards.
37
+ * Returns true for a short plus code with 2, 4 or 6 digits before the `+`,
38
+ * such as the `VFQ6+92P` form Google prints on place cards.
61
39
  */
62
40
  export function isShortPlusCode(token: string): boolean {
63
41
  return /^[23456789CFGHJMPQRVWX]{2,6}\+[23456789CFGHJMPQRVWX]{2,3}$/i.test(token) && token.indexOf("+") % 2 === 0
64
42
  }
65
43
 
66
44
  /**
67
- * Decode a FULL plus code to its cell. Returns null on anything `isFullPlusCode` rejects.
45
+ * Decodes a full plus code to its cell, returning null for anything {@link isFullPlusCode} rejects.
68
46
  */
69
47
  export function decodePlusCode(code: string): DecodedPlusCode | null {
70
48
  if (!isFullPlusCode(code)) return null
@@ -75,7 +53,6 @@ export function decodePlusCode(code: string): DecodedPlusCode | null {
75
53
  let latSpan = 400
76
54
  let lonSpan = 400
77
55
 
78
- // The first ten digits arrive in (lat, lon) pairs.
79
56
  const pairCount = Math.min(digits.length, 10)
80
57
 
81
58
  for (let i = 0; i < pairCount; i += 2) {
@@ -87,7 +64,6 @@ export function decodePlusCode(code: string): DecodedPlusCode | null {
87
64
  lonSpan = resolution
88
65
  }
89
66
 
90
- // Grid refinement: each further digit indexes a 4×5 (columns × rows) subdivision.
91
67
  for (let i = 10; i < digits.length; i++) {
92
68
  const value = OLC_DIGIT_VALUE.get(digits[i]!)!
93
69
 
@@ -105,10 +81,6 @@ export function decodePlusCode(code: string): DecodedPlusCode | null {
105
81
  }
106
82
  }
107
83
 
108
- /**
109
- * Encode the pair digits of a coordinate to `length` digits (length ≤ 10, even) — the prefix implementation
110
- * {@link recoverNearestPlusCode} needs; not a general encoder.
111
- */
112
84
  function encodePairDigits(lat: number, lon: number, length: number): string {
113
85
  let latVal = Math.min(Math.max(lat + 90, 0), 180 - 1e-12)
114
86
  let lonVal = lon + 180
@@ -131,9 +103,9 @@ function encodePairDigits(lat: number, lon: number, length: number): string {
131
103
  }
132
104
 
133
105
  /**
134
- * Recover a SHORT plus code against a reference coordinate, per the spec's `recoverNearest`: prepend the reference's
135
- * prefix at the missing precision, then shift the candidate cell by whole prefix-resolutions when a neighboring cell
136
- * center sits closer to the reference. Returns the decoded nearest cell, or null for an invalid short code.
106
+ * Recovers a short plus code to the matching cell nearest a reference coordinate,
107
+ * following the spec's `recoverNearest`.
108
+ * It returns null for an invalid short code.
137
109
  */
138
110
  export function recoverNearestPlusCode(shortCode: string, refLat: number, refLon: number): DecodedPlusCode | null {
139
111
  if (!isShortPlusCode(shortCode)) return null
@@ -144,9 +116,6 @@ export function recoverNearestPlusCode(shortCode: string, refLat: number, refLon
144
116
 
145
117
  if (!candidate) return null
146
118
 
147
- // The prefix pins the cell modulo its own resolution; the nearest bearer of the short code may sit
148
- // one prefix-cell away (the reference near a cell edge). Shift by whole prefix-resolutions, never
149
- // past the poles.
150
119
  const LAT_MIN = -90
151
120
  const LAT_MAX = 90
152
121
  const prefixResolution = PAIR_RESOLUTIONS[missing / 2 - 1]!