@mailwoman/spatial 8.5.0 → 9.0.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 (52) hide show
  1. package/README.md +4 -0
  2. package/geometries/point.ts +37 -15
  3. package/geometries/polygon.ts +70 -2
  4. package/h3/cell.ts +78 -39
  5. package/h3/index.ts +1 -1
  6. package/index.ts +1 -1
  7. package/osgb36.ts +371 -0
  8. package/out/geometries/point.d.ts +26 -1
  9. package/out/geometries/point.d.ts.map +1 -1
  10. package/out/geometries/point.js +33 -16
  11. package/out/geometries/point.js.map +1 -1
  12. package/out/geometries/polygon.d.ts +34 -2
  13. package/out/geometries/polygon.d.ts.map +1 -1
  14. package/out/geometries/polygon.js +43 -0
  15. package/out/geometries/polygon.js.map +1 -1
  16. package/out/h3/cell.d.ts +43 -15
  17. package/out/h3/cell.d.ts.map +1 -1
  18. package/out/h3/cell.js +63 -34
  19. package/out/h3/cell.js.map +1 -1
  20. package/out/h3/index.d.ts +1 -1
  21. package/out/h3/index.js +1 -1
  22. package/out/index.d.ts +1 -1
  23. package/out/index.d.ts.map +1 -1
  24. package/out/index.js +1 -1
  25. package/out/index.js.map +1 -1
  26. package/out/osgb36.d.ts +125 -0
  27. package/out/osgb36.d.ts.map +1 -0
  28. package/out/osgb36.js +301 -0
  29. package/out/osgb36.js.map +1 -0
  30. package/out/position.d.ts +28 -1
  31. package/out/position.d.ts.map +1 -1
  32. package/out/position.js +40 -1
  33. package/out/position.js.map +1 -1
  34. package/out/tsconfig.test.tsbuildinfo +1 -1
  35. package/out/tsconfig.tsbuildinfo +1 -1
  36. package/package.json +3 -3
  37. package/position.ts +44 -1
  38. package/countries/codes.ts +0 -534
  39. package/countries/index.ts +0 -8
  40. package/countries/names.ts +0 -274
  41. package/out/countries/codes.d.ts +0 -529
  42. package/out/countries/codes.d.ts.map +0 -1
  43. package/out/countries/codes.js +0 -519
  44. package/out/countries/codes.js.map +0 -1
  45. package/out/countries/index.d.ts +0 -8
  46. package/out/countries/index.d.ts.map +0 -1
  47. package/out/countries/index.js +0 -8
  48. package/out/countries/index.js.map +0 -1
  49. package/out/countries/names.d.ts +0 -23
  50. package/out/countries/names.d.ts.map +0 -1
  51. package/out/countries/names.js +0 -264
  52. package/out/countries/names.js.map +0 -1
package/README.md CHANGED
@@ -40,6 +40,10 @@ Optional: `@googlemaps/google-maps-services-js` for Google Maps API integration.
40
40
  - [`@mailwoman/match`](../match) — uses H3 cells for geo-first record blocking
41
41
  - [`@mailwoman/address-id`](../address-id) — uses H3 for stable address primary keys
42
42
  - [`@mailwoman/core`](../core) — consumes spatial types
43
+ - [`@mailwoman/codex/country`](../codex/country) — ISO 3166-1 country codes and names. This
44
+ package once carried a byte-identical second copy of that table under `countries/` (salvaged
45
+ from isp-nexus alongside the geometry code, never imported by anything). It was deleted
46
+ 2026-08-04; country reference data belongs to `codex`, not to the math home.
43
47
 
44
48
  ## License
45
49
 
@@ -18,10 +18,11 @@ import {
18
18
  type Coordinates2D as Point2DCoordinates,
19
19
  type Coordinates3D as Point3DCoordinates,
20
20
  clampLatitude,
21
- inferGeoJSONCoordOrder,
22
21
  isCoordPairLiteral,
23
22
  isGoogleMapsLatLngLiteral,
24
23
  isInterpolatedCoordinates,
24
+ isValidLatitude,
25
+ isValidLongitude,
25
26
  wrapLongitude,
26
27
  } from "../position.ts"
27
28
 
@@ -145,9 +146,22 @@ export class GeoPoint implements PointLiteral {
145
146
  return [this.#longitude, this.#latitude]
146
147
  }
147
148
 
149
+ /**
150
+ * Assigns the pair as GeoJSON [longitude, latitude(, altitude)] — the axis order is the contract, never inferred from
151
+ * the magnitudes — and REJECTS a coordinate that is not on the globe. See {@link GeoPoint.from} for why both halves of
152
+ * that sentence are load-bearing.
153
+ *
154
+ * @throws {RangeError} When longitude is outside [-180, 180] or latitude is outside [-90, 90].
155
+ */
148
156
  public set coordinates(coords: Point2DCoordinates | Point3DCoordinates) {
149
157
  const [longitude, latitude, altitude] = coords
150
158
 
159
+ if (!isValidLongitude(longitude) || !isValidLatitude(latitude)) {
160
+ throw new RangeError(
161
+ `GeoPoint expects GeoJSON [longitude, latitude] with longitude in [-180, 180] and latitude in [-90, 90]; got [${longitude}, ${latitude}]`
162
+ )
163
+ }
164
+
151
165
  this.#longitude = longitude
152
166
  this.#latitude = latitude
153
167
  this.#altitude = typeof altitude === "number" ? altitude : 0
@@ -249,13 +263,7 @@ export class GeoPoint implements PointLiteral {
249
263
  constructor(input: GeoPointInput, bbox?: BBox2DLiteral | BBox3DLiteral | GeoBoundingBox)
250
264
  constructor(input?: GeoPointInput, bbox?: BBox2DLiteral | BBox3DLiteral | GeoBoundingBox) {
251
265
  if (isCoordPairLiteral(input)) {
252
- // A ternary does not carry the narrowing through, and inferGeoJSONCoordOrder needs the 2-tuple.
253
- // oxlint-disable-next-line unicorn/prefer-ternary -- the if/else is what narrows `input`
254
- if (input.length === 2) {
255
- this.coordinates = inferGeoJSONCoordOrder(input)
256
- } else {
257
- this.coordinates = input
258
- }
266
+ this.coordinates = input
259
267
  } else if (isPointLiteral(input)) {
260
268
  this.coordinates = [...input.coordinates]
261
269
 
@@ -265,13 +273,9 @@ export class GeoPoint implements PointLiteral {
265
273
  } else if (isGoogleMapsLatLngLiteral(input)) {
266
274
  this.coordinates = [input.lng, input.lat]
267
275
  } else if (isGeolocationCoordinatesLike(input)) {
268
- this.#longitude = input.longitude
269
- this.#latitude = input.latitude
270
- this.#altitude = input.altitude || 0
276
+ this.coordinates = [input.longitude, input.latitude, input.altitude || 0]
271
277
  } else if (isInterpolatedCoordinates(input)) {
272
- this.#longitude = input.x
273
- this.#latitude = input.y
274
- this.#altitude = 0
278
+ this.coordinates = [input.x, input.y]
275
279
  } else {
276
280
  this.coordinates = [0, 0]
277
281
  }
@@ -282,7 +286,25 @@ export class GeoPoint implements PointLiteral {
282
286
  }
283
287
 
284
288
  /**
285
- * Attempts to create a new GeoPoint instance from the given input.
289
+ * Attempts to create a new GeoPoint instance from the given input, returning `null` rather than throwing when the
290
+ * input is not a coordinate this class will stand behind.
291
+ *
292
+ * Two rules, both of which this constructor got wrong until 2026-08-05 (the defect was recorded in `e9bfd139` and
293
+ * routed around rather than fixed):
294
+ *
295
+ * 1. **A 2-tuple is GeoJSON [longitude, latitude]. The axis order is never inferred.** The old path ran the pair through
296
+ * `inferGeoJSONCoordOrder`, whose only signal is the [-90, 90] latitude range, so it transposed a pair exactly
297
+ * when |the second magnitude| > 90. A caller handing it `[latitude, longitude]` therefore got the pair repaired in
298
+ * Dallas and left corrupted in Berlin — behaviour selected by the data, from one code path. This change is a no-op
299
+ * for every WELL-FORMED input: a valid `[longitude, latitude]` pair can never have an out-of-range second element,
300
+ * so the heuristic never fired on one.
301
+ * 2. **An out-of-range magnitude is rejected, not repaired.** `[999, 999]` used to produce a GeoPoint reporting latitude
302
+ * 999. It now returns `null` here and throws a `RangeError` from the constructor. Note the deliberate asymmetry
303
+ * with the scalar `longitude` / `latitude` setters, which still wrap and clamp: mutating a point is a pan gesture,
304
+ * where 190° meaning -170° is right; PARSING one is a claim about the world, where an impossible magnitude means
305
+ * the input was malformed and any repair invents a location.
306
+ *
307
+ * A 0/0 result is treated as the "missing coordinate" sentinel (Null Island) and also returns `null`.
286
308
  */
287
309
  static from(input: unknown): GeoPoint | null {
288
310
  if (!input) return null
@@ -121,6 +121,71 @@ export function isSolidPolygonPath(input: PolygonLiteral): boolean {
121
121
  return input.coordinates.length === 1
122
122
  }
123
123
 
124
+ /**
125
+ * A linear ring as the containment predicates read it: positions of `[lon, lat, …]`.
126
+ *
127
+ * Deliberately looser than {@link LineStringPath} — the ray cast only ever indexes `[0]` and `[1]`, and the callers
128
+ * arrive with different position types (`[number, number, ...number[]]` from the resolver's GeoJSON reader, plain
129
+ * `number[][]` from a `JSON.parse` of a stored geometry column). A tight tuple type here would force a cast at every
130
+ * call site and buy nothing the predicate uses.
131
+ */
132
+ export type ContainmentRing = readonly (readonly number[])[]
133
+
134
+ /**
135
+ * Ray-cast a point against ONE linear ring — the even-odd crossing count. Shoot a ray along +lon and toggle on every
136
+ * edge crossing.
137
+ *
138
+ * Points exactly on an edge are implementation-defined; either side is acceptable for geocoding, where admin boundaries
139
+ * are Douglas-Peucker–simplified before they ever reach us.
140
+ */
141
+ export function pointInRing(lon: number, lat: number, ring: ContainmentRing): boolean {
142
+ let inside = false
143
+ const n = ring.length
144
+
145
+ for (let i = 0, j = n - 1; i < n; j = i++) {
146
+ const xi = ring[i]![0]!
147
+ const yi = ring[i]![1]!
148
+ const xj = ring[j]![0]!
149
+ const yj = ring[j]![1]!
150
+
151
+ if (yi > lat !== yj > lat && lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi) {
152
+ inside = !inside
153
+ }
154
+ }
155
+
156
+ return inside
157
+ }
158
+
159
+ /**
160
+ * Even-odd containment over a polygon's ring list (`[outer, hole₁, …]`).
161
+ *
162
+ * Being inside an odd number of rings means inside the polygon, which handles holes — and islands inside holes —
163
+ * without depending on ring winding order. GeoJSON nominally specifies orientation, but the gazetteer sources do not
164
+ * reliably honour it, so the orientation-free rule is the one that survives real data.
165
+ */
166
+ export function pointInPolygon(lon: number, lat: number, rings: readonly ContainmentRing[]): boolean {
167
+ let inside = false
168
+
169
+ for (const ring of rings) {
170
+ if (pointInRing(lon, lat, ring)) {
171
+ inside = !inside
172
+ }
173
+ }
174
+
175
+ return inside
176
+ }
177
+
178
+ /**
179
+ * Inside ANY polygon of a multi-polygon.
180
+ */
181
+ export function pointInMultiPolygon(
182
+ lon: number,
183
+ lat: number,
184
+ polygons: readonly (readonly ContainmentRing[])[]
185
+ ): boolean {
186
+ return polygons.some((rings) => pointInPolygon(lon, lat, rings))
187
+ }
188
+
124
189
  /**
125
190
  * A collection of polygons, such as a country with islands or a lake with islands.
126
191
  */
@@ -128,9 +193,12 @@ export interface MultiPolygonLiteral<P extends PolygonPath = SolidPolygonPath> e
128
193
  type: "MultiPolygon"
129
194
 
130
195
  /**
131
- * An array of polygons.
196
+ * One ring array per polygon — `coordinates[polygon][ring][position]`, matching a `Polygon`'s `coordinates` lifted by
197
+ * exactly one level.
198
+ *
199
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.7 | RFC 7946 Section 3.1.7}
132
200
  */
133
- coordinates: P[][]
201
+ coordinates: P[]
134
202
  }
135
203
 
136
204
  /**
package/h3/cell.ts CHANGED
@@ -9,81 +9,120 @@
9
9
  * by `./index.ts`, so keeping them together closed an import cycle.
10
10
  */
11
11
 
12
+ import { isValidCell } from "h3-js"
12
13
  import type { Tagged } from "type-fest"
13
14
 
15
+ /**
16
+ * The finest resolution H3 defines. Resolutions run `[0, H3_MAX_RESOLUTION]`.
17
+ */
18
+ export const H3_MAX_RESOLUTION = 15
19
+
14
20
  /**
15
21
  * A H3 cell index, full 64 bits.
16
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
+ *
17
27
  * @type {string}
18
28
  * @title H3 Cell Index
19
29
  * @pattern ^[0-9a-f]{15}$
20
30
  */
21
31
  export type H3Cell = Tagged<string, "H3Cell">
22
32
 
33
+ /**
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.
40
+ */
23
41
  export function isH3Cell(value: string): value is H3Cell {
24
- return /^[0-9a-f]{15}$/.test(value)
42
+ return isValidCell(value)
25
43
  }
26
44
 
27
45
  /**
28
- * A H3 cell index, shortened to 48 bits.
46
+ * A H3 cell index with its mode and resolution nibbles removed — the low 52 bits, fixed width.
29
47
  *
30
48
  * @type {string}
31
49
  * @title H3 Cell Index (Short)
32
- * @pattern ^[0-9a-f]{12}$
50
+ * @pattern ^[0-9a-f]{13}$
33
51
  */
34
52
  export type H3CellShort = Tagged<string, "H3CellShort">
35
53
 
36
54
  /**
37
- * Given a full H3 cell index, shorten it to 48 bits.
55
+ * Number of hex characters in the short form. 52 bits: a 7-bit base cell followed by fifteen 3-bit digits.
38
56
  */
39
- export function shortenH3Cell(cell: H3Cell): H3CellShort {
40
- // ...and convert it to a 48-bit cell address.
41
- const cellBigInt = BigInt(`0x${cell}`)
42
- // 8 f 2 aa 84 5a 18 ac 6b
43
- // aa 84 5a 18 ac 6b
57
+ const SHORT_CELL_HEX_LENGTH = 13
44
58
 
45
- // Extract the cell address without the resolution
46
- const h3CellShortBigInt = cellBigInt & 0xf_ff_ff_ff_ff_ff_ffn
59
+ /**
60
+ * Mask selecting the low 52 bits of a cell index — everything but the mode and resolution nibbles.
61
+ */
62
+ const SHORT_CELL_MASK = 0xf_ff_ff_ff_ff_ff_ffn
47
63
 
48
- const h3CellShortHex = h3CellShortBigInt.toString(16)
64
+ /**
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.
74
+ */
75
+ export function shortenH3Cell(cell: H3Cell): H3CellShort {
76
+ const cellBigInt = BigInt(`0x${cell}`)
77
+ const h3CellShortBigInt = cellBigInt & SHORT_CELL_MASK
49
78
 
50
- return h3CellShortHex as H3CellShort
79
+ return h3CellShortBigInt.toString(16).padStart(SHORT_CELL_HEX_LENGTH, "0") as H3CellShort
51
80
  }
52
81
 
53
- //2 aa 84 5a 18 ac 6b
54
-
55
- // 8 f2 aa 84 5a 18 ac 6b
56
82
  /**
57
- * Given a short cell address, expand it to a full H3 cell index.
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`.
58
94
  *
59
- * @warning BROKEN for any `resolution` other than the default `15` — tracked as issue #1373. The left-shift
60
- * reconstruction here only round-trips a short cell that was SHORTENED at resolution 15 (the address-id spine); fed a
61
- * short cell captured at some other resolution R, it silently produces a full index `cellToParent`/H3 rejects
62
- * (`Cell arguments had incompatible resolutions`) rather than throwing here. A caller needing to reconstruct a full
63
- * cell from a short cell captured at a KNOWN resolution R other than 15 must NOT pass `resolution: R` to this
64
- * function — see `bdc/sdk/filing-landscape.ts`'s `res9ShortCellToRes6Parent` for the correct straight-concatenation
65
- * formula (`"8" + R.toString(16) + shortHex.padStart(13, "0")`) and its docstring for the full explanation. Do not
66
- * "fix" this function to take an arbitrary resolution without reading that docstring first — it's out of scope for
67
- * casual changes.
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.
68
98
  */
69
- export function expandH3Cell(h3CellShort: H3CellShort, resolution = 15): H3Cell {
70
- // Convert the short cell address back to BigInt
71
- const h3CellShortBigInt = BigInt(`0x${h3CellShort}`)
99
+ export function expandH3Cell(h3CellShort: H3CellShort, resolution = H3_MAX_RESOLUTION): H3Cell {
100
+ if (!Number.isInteger(resolution) || resolution < 0 || resolution > H3_MAX_RESOLUTION) {
101
+ throw new RangeError(`H3 resolution must be an integer in [0, ${H3_MAX_RESOLUTION}], received ${resolution}.`)
102
+ }
103
+
104
+ if (h3CellShort.length > SHORT_CELL_HEX_LENGTH) {
105
+ throw new RangeError(
106
+ `Short H3 cell "${h3CellShort}" is ${h3CellShort.length} hex characters, wider than the ${SHORT_CELL_HEX_LENGTH} a short cell holds.`
107
+ )
108
+ }
109
+
110
+ // Accept an unpadded short cell too — an integer round-tripped through `toString(16)` loses its leading zeros.
111
+ const shortHex = h3CellShort.padStart(SHORT_CELL_HEX_LENGTH, "0")
112
+ const cell = `8${resolution.toString(16)}${shortHex}` as H3Cell
72
113
 
73
- const resolutionHex = resolution.toString(16)
74
- // Reassemble the H3 cell index portion...
75
- const cellBigInt = h3CellShortBigInt << BigInt(8 * (15 - resolution))
76
- // Back to a string...
77
- const partialCell = cellBigInt.toString(16)
78
- // Finally, we add the resolution back to the cell index.
79
- const cell = `8${resolutionHex}${partialCell}`
114
+ if (!isValidCell(cell)) {
115
+ throw new Error(
116
+ `Short H3 cell "${h3CellShort}" does not name a valid cell at resolution ${resolution} — it was captured at a different resolution.`
117
+ )
118
+ }
80
119
 
81
- return cell as H3Cell
120
+ return cell
82
121
  }
83
122
 
84
123
  /**
85
- * Pack an H3 cell into the 48-bit short-cell integer used as a clustered B-tree key across layer databases (poi.db,
86
- * bdc.db, address-id).
124
+ * Pack an H3 cell into the short-cell integer used as a clustered B-tree key across layer databases (poi.db, bdc.db,
125
+ * address-id). 52 bits, so it stays inside `Number.MAX_SAFE_INTEGER` and SQLite's signed 64-bit integer column alike.
87
126
  */
88
127
  export function shortCellToInt(cell: H3Cell): number {
89
128
  return Number(BigInt(`0x${shortenH3Cell(cell)}`))
package/h3/index.ts CHANGED
@@ -12,7 +12,7 @@ import { type H3Cell, type H3CellShort, expandH3Cell } from "./cell.ts"
12
12
  export * from "./cell.ts"
13
13
 
14
14
  /**
15
- * Given a geographic point, return a short cell address.
15
+ * Given a short cell address and the resolution it was captured at, return the centre of that cell.
16
16
  */
17
17
  export function shortCellToPoint(shortCell: H3CellShort, resolution = 15): GeoPoint {
18
18
  const cell = expandH3Cell(shortCell, resolution)
package/index.ts CHANGED
@@ -6,12 +6,12 @@
6
6
 
7
7
  export * from "./bbox.ts"
8
8
  export * from "./coordinate-formats.ts"
9
- export * from "./countries/index.ts"
10
9
  export * from "./feature.ts"
11
10
  export * from "./geometries/index.ts"
12
11
  export * from "./google/index.ts"
13
12
  export * from "./h3/index.ts"
14
13
  export * from "./objects.ts"
14
+ export * from "./osgb36.ts"
15
15
  export * from "./polyline.ts"
16
16
  export * from "./position.ts"
17
17
  export * from "./projection.ts"