@mailwoman/timezone-lookup 7.2.0 → 7.2.1

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 (4) hide show
  1. package/build.ts +78 -0
  2. package/cli.ts +50 -0
  3. package/index.ts +114 -0
  4. package/package.json +27 -10
package/build.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Build the timezone polygon DB from a timezone-boundary-builder GeoJSON
7
+ * (`combined-with-oceans.json`, features of `{ properties: { tzid }, geometry:
8
+ * Polygon|MultiPolygon }`). One row per feature: the tzid, a bounding box (for the lookup's
9
+ * prefilter), and the geometry normalized to MultiPolygon coordinates as JSON.
10
+ */
11
+
12
+ import { readFileSync } from "node:fs"
13
+ import { DatabaseSync } from "node:sqlite"
14
+
15
+ import type { MultiPolygonCoords } from "./index.ts"
16
+
17
+ interface TimezoneFeature {
18
+ properties: { tzid: string }
19
+ geometry: { type: "Polygon" | "MultiPolygon"; coordinates: number[][][] | number[][][][] }
20
+ }
21
+
22
+ /** Read the GeoJSON at `geojsonPath` and write the polygon DB to `dbPath` (overwriting its table). */
23
+ export function buildTimezoneDB(geojsonPath: string, dbPath: string): { features: number } {
24
+ const data = JSON.parse(readFileSync(geojsonPath, "utf8")) as { features: TimezoneFeature[] }
25
+ const db = new DatabaseSync(dbPath)
26
+ db.exec("DROP TABLE IF EXISTS timezone_polygons")
27
+ db.exec(
28
+ `CREATE TABLE timezone_polygons (tzid TEXT NOT NULL, minLat REAL, maxLat REAL, minLon REAL, maxLon REAL, geom TEXT NOT NULL)`
29
+ )
30
+ const insert = db.prepare(
31
+ "INSERT INTO timezone_polygons (tzid, minLat, maxLat, minLon, maxLon, geom) VALUES (?,?,?,?,?,?)"
32
+ )
33
+
34
+ db.exec("BEGIN")
35
+
36
+ for (const feature of data.features) {
37
+ const polygons: MultiPolygonCoords =
38
+ feature.geometry.type === "Polygon"
39
+ ? [feature.geometry.coordinates as number[][][]]
40
+ : (feature.geometry.coordinates as number[][][][])
41
+
42
+ let minLat = 90
43
+ let maxLat = -90
44
+ let minLon = 180
45
+ let maxLon = -180
46
+
47
+ for (const polygon of polygons) {
48
+ for (const ring of polygon) {
49
+ for (const point of ring) {
50
+ const lon = point[0]!
51
+ const lat = point[1]!
52
+
53
+ if (lat < minLat) {
54
+ minLat = lat
55
+ }
56
+
57
+ if (lat > maxLat) {
58
+ maxLat = lat
59
+ }
60
+
61
+ if (lon < minLon) {
62
+ minLon = lon
63
+ }
64
+
65
+ if (lon > maxLon) {
66
+ maxLon = lon
67
+ }
68
+ }
69
+ }
70
+ }
71
+ insert.run(feature.properties.tzid, minLat, maxLat, minLon, maxLon, JSON.stringify(polygons))
72
+ }
73
+ db.exec("COMMIT")
74
+ db.exec("CREATE INDEX idx_tz_bbox ON timezone_polygons (minLat, maxLat, minLon, maxLon)")
75
+ db.close()
76
+
77
+ return { features: data.features.length }
78
+ }
package/cli.ts ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @copyright Sister Software
4
+ * @license AGPL-3.0
5
+ * @author Teffen Ellis, et al.
6
+ *
7
+ * `mailwoman-timezone` — build the polygon DB, or look up a coordinate's IANA timezone.
8
+ *
9
+ * ```sh
10
+ * mailwoman-timezone build --geojson combined-with-oceans.json --out timezone.db
11
+ * mailwoman-timezone --db timezone.db -- 40.7128 -74.0060
12
+ * ```
13
+ *
14
+ * The `--` separates flags from coordinates so negative longitudes parse as positionals.
15
+ */
16
+
17
+ import { parseArgs } from "node:util"
18
+
19
+ import { buildTimezoneDB } from "./build.ts"
20
+ import { offsetSecForTimezone, TimezoneLookup } from "./index.ts"
21
+
22
+ const { values, positionals } = parseArgs({
23
+ options: {
24
+ geojson: { type: "string" },
25
+ out: { type: "string" },
26
+ db: { type: "string" },
27
+ },
28
+ allowPositionals: true,
29
+ })
30
+
31
+ if (positionals[0] === "build") {
32
+ if (!values.geojson || !values.out) {
33
+ console.error("Usage: mailwoman-timezone build --geojson <path> --out <db>")
34
+ process.exit(1)
35
+ }
36
+ const { features } = buildTimezoneDB(values.geojson, values.out)
37
+ console.error(`built ${values.out} (${features} features)`)
38
+ } else {
39
+ const lat = Number(positionals[0])
40
+ const lon = Number(positionals[1])
41
+
42
+ if (!values.db || !Number.isFinite(lat) || !Number.isFinite(lon)) {
43
+ console.error("Usage: mailwoman-timezone --db <db> -- <lat> <lon>")
44
+ process.exit(1)
45
+ }
46
+ const lookup = new TimezoneLookup({ databasePath: values.db })
47
+ const tzid = lookup.find(lat, lon)
48
+ console.log(JSON.stringify({ timezone: tzid, offsetSec: tzid ? offsetSecForTimezone(tzid) : null }))
49
+ lookup.close()
50
+ }
package/index.ts ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * `@mailwoman/timezone-lookup` — coordinate → IANA timezone, server-side. Point-in-polygon over the
7
+ * timezone-boundary-builder polygons stored in a `node:sqlite` DB (bbox-prefilter + ray-cast),
8
+ * mirroring the resolver's PIP pattern. The UTC offset comes from `Intl.DateTimeFormat` — no tz
9
+ * database dependency. Build the DB with `mailwoman-timezone build` (see `./build.ts`).
10
+ */
11
+
12
+ import { DatabaseSync } from "node:sqlite"
13
+
14
+ import type { AnnotationSet, Annotator } from "@mailwoman/annotations"
15
+
16
+ /**
17
+ * Normalized geometry: an array of polygons, each `[outerRing, ...holes]`, each ring `[[lon,lat],…]`.
18
+ */
19
+ export type MultiPolygonCoords = number[][][][]
20
+
21
+ /** Ray-cast point-in-ring (even-odd rule). `ring` is `[[lon, lat], …]`. */
22
+ function pointInRing(lon: number, lat: number, ring: number[][]): boolean {
23
+ let inside = false
24
+
25
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
26
+ const xi = ring[i]![0]!
27
+ const yi = ring[i]![1]!
28
+ const xj = ring[j]![0]!
29
+ const yj = ring[j]![1]!
30
+
31
+ if (yi > lat !== yj > lat && lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi) {
32
+ inside = !inside
33
+ }
34
+ }
35
+
36
+ return inside
37
+ }
38
+
39
+ /** Inside the outer ring and outside every hole. */
40
+ function pointInPolygon(lon: number, lat: number, polygon: number[][][]): boolean {
41
+ if (!polygon[0] || !pointInRing(lon, lat, polygon[0])) return false
42
+
43
+ for (let i = 1; i < polygon.length; i++) if (pointInRing(lon, lat, polygon[i]!)) return false
44
+
45
+ return true
46
+ }
47
+
48
+ /** Inside any polygon of a (multi)polygon feature. */
49
+ export function pointInMultiPolygon(lon: number, lat: number, polygons: MultiPolygonCoords): boolean {
50
+ return polygons.some((polygon) => pointInPolygon(lon, lat, polygon))
51
+ }
52
+
53
+ /**
54
+ * The current UTC offset (seconds) for an IANA timezone, via `Intl` (no tz-db dependency). Returns `undefined` if the
55
+ * runtime can't resolve the zone.
56
+ */
57
+ export function offsetSecForTimezone(tzid: string, date: Date = new Date()): number | undefined {
58
+ try {
59
+ const parts = new Intl.DateTimeFormat("en-US", { timeZone: tzid, timeZoneName: "longOffset" }).formatToParts(date)
60
+ const name = parts.find((p) => p.type === "timeZoneName")?.value ?? ""
61
+ const match = name.match(/GMT([+-])(\d{2}):?(\d{2})?/)
62
+
63
+ if (!match) return name === "GMT" ? 0 : undefined
64
+ const sign = match[1] === "-" ? -1 : 1
65
+ const hours = Number(match[2])
66
+ const minutes = Number(match[3] ?? "0")
67
+
68
+ return sign * (hours * 3600 + minutes * 60)
69
+ } catch {
70
+ return undefined
71
+ }
72
+ }
73
+
74
+ /** A timezone lookup over a built `node:sqlite` polygon DB. */
75
+ export class TimezoneLookup {
76
+ #db: DatabaseSync
77
+ #stmt: ReturnType<DatabaseSync["prepare"]>
78
+
79
+ constructor(opts: { databasePath: string } | { database: DatabaseSync }) {
80
+ this.#db = "database" in opts ? opts.database : new DatabaseSync(opts.databasePath, { readOnly: true })
81
+ // Candidate features whose bbox contains the point; PIP picks the exact one.
82
+ this.#stmt = this.#db.prepare(
83
+ `SELECT tzid, geom FROM timezone_polygons
84
+ WHERE minLat <= ? AND maxLat >= ? AND minLon <= ? AND maxLon >= ?`
85
+ )
86
+ }
87
+
88
+ /** The IANA timezone id containing `(lat, lon)`, or `null` if none (shouldn't happen with oceans). */
89
+ find(lat: number, lon: number): string | null {
90
+ const rows = this.#stmt.all(lat, lat, lon, lon) as Array<{ tzid: string; geom: string }>
91
+
92
+ for (const row of rows) {
93
+ if (pointInMultiPolygon(lon, lat, JSON.parse(row.geom) as MultiPolygonCoords)) return row.tzid
94
+ }
95
+
96
+ return null
97
+ }
98
+
99
+ close(): void {
100
+ this.#db.close()
101
+ }
102
+ }
103
+
104
+ /** Build an `Annotator` that fills `AnnotationSet.timezone` (name + current offset) from a lookup. */
105
+ export function makeTimezoneAnnotator(lookup: TimezoneLookup): Annotator {
106
+ return ({ lat, lon, date }): Partial<AnnotationSet> => {
107
+ const name = lookup.find(lat, lon)
108
+
109
+ if (!name) return {}
110
+ const offsetSec = offsetSecForTimezone(name, date)
111
+
112
+ return { timezone: offsetSec != null ? { name, offsetSec } : { name } }
113
+ }
114
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mailwoman/timezone-lookup",
3
- "version": "7.2.0",
3
+ "version": "7.2.1",
4
4
  "description": "Coordinate → IANA timezone, server-side. Point-in-polygon over timezone-boundary-builder polygons in a node:sqlite DB; UTC offset via Intl (no tz-db dependency). An @mailwoman/annotations Annotator.",
5
5
  "license": "AGPL-3.0-only OR LicenseRef-Commercial",
6
6
  "repository": {
@@ -14,26 +14,43 @@
14
14
  "out/**/*.js.map",
15
15
  "out/**/*.d.ts",
16
16
  "out/**/*.d.ts.map",
17
- "README.md"
17
+ "README.md",
18
+ "*.ts",
19
+ "*.tsx",
20
+ "**/*.ts",
21
+ "**/*.tsx",
22
+ "!*.test.ts",
23
+ "!*.test.tsx",
24
+ "!**/*.test.ts",
25
+ "!**/*.test.tsx"
18
26
  ],
19
27
  "type": "module",
20
28
  "exports": {
21
29
  "./package.json": "./package.json",
22
30
  ".": {
23
- "node": "./index.ts",
24
- "default": "./out/index.js",
25
- "types": "./out/index.d.ts"
31
+ "types": "./out/index.d.ts",
32
+ "default": "./out/index.js"
26
33
  },
27
34
  "./build": {
28
- "node": "./build.ts",
29
- "default": "./out/build.js",
30
- "types": "./out/build.d.ts"
35
+ "types": "./out/build.d.ts",
36
+ "default": "./out/build.js"
31
37
  }
32
38
  },
33
39
  "publishConfig": {
34
- "access": "public"
40
+ "access": "public",
41
+ "exports": {
42
+ "./package.json": "./package.json",
43
+ ".": {
44
+ "types": "./out/index.d.ts",
45
+ "default": "./out/index.js"
46
+ },
47
+ "./build": {
48
+ "types": "./out/build.d.ts",
49
+ "default": "./out/build.js"
50
+ }
51
+ }
35
52
  },
36
53
  "dependencies": {
37
- "@mailwoman/annotations": "7.2.0"
54
+ "@mailwoman/annotations": "7.2.1"
38
55
  }
39
56
  }