@mailwoman/un-locode-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 +59 -0
  2. package/cli.ts +56 -0
  3. package/index.ts +112 -0
  4. package/package.json +27 -10
package/build.ts ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Build the UN/LOCODE lookup DB from the UNECE code list CSV (datasets/un-locode `code-list.csv`:
7
+ * columns Change, Country, Location, Name, NameWoDiacritics, Subdivision, Status, Function, Date,
8
+ * IATA, Coordinates, Remarks). One row per assigned location; coordinates parsed where present.
9
+ */
10
+
11
+ import { readFileSync } from "node:fs"
12
+ import { DatabaseSync } from "node:sqlite"
13
+
14
+ import { parse } from "csv-parse/sync"
15
+
16
+ import { foldName, parseUnLocodeCoords } from "./index.ts"
17
+
18
+ interface CSVRow {
19
+ Country: string
20
+ Location: string
21
+ Name: string
22
+ NameWoDiacritics: string
23
+ Coordinates: string
24
+ }
25
+
26
+ /** Read the code-list CSV at `csvPath` and write the lookup DB to `dbPath`. */
27
+ export function buildUnLocodeDB(csvPath: string, dbPath: string): { rows: number; withCoords: number } {
28
+ const records = parse(readFileSync(csvPath), {
29
+ columns: true,
30
+ skip_empty_lines: true,
31
+ relax_quotes: true,
32
+ }) as CSVRow[]
33
+ const db = new DatabaseSync(dbPath)
34
+ db.exec("DROP TABLE IF EXISTS un_locode")
35
+ db.exec(
36
+ "CREATE TABLE un_locode (country TEXT NOT NULL, location TEXT NOT NULL, name TEXT, nameNorm TEXT, lat REAL, lon REAL)"
37
+ )
38
+ const insert = db.prepare("INSERT INTO un_locode (country, location, name, nameNorm, lat, lon) VALUES (?,?,?,?,?,?)")
39
+
40
+ let withCoords = 0
41
+ db.exec("BEGIN")
42
+
43
+ for (const r of records) {
44
+ if (!r.Country || !r.Location) continue // header/country rows carry no Location
45
+ const coords = r.Coordinates ? parseUnLocodeCoords(r.Coordinates) : null
46
+
47
+ if (coords) {
48
+ withCoords++
49
+ }
50
+ const name = r.NameWoDiacritics || r.Name || ""
51
+ insert.run(r.Country, r.Location, r.Name || name, foldName(name), coords?.lat ?? null, coords?.lon ?? null)
52
+ }
53
+ db.exec("COMMIT")
54
+ db.exec("CREATE INDEX idx_locode_name ON un_locode (country, nameNorm)")
55
+ db.exec("CREATE INDEX idx_locode_bbox ON un_locode (lat, lon)")
56
+ db.close()
57
+
58
+ return { rows: records.length, withCoords }
59
+ }
package/cli.ts ADDED
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @copyright Sister Software
4
+ * @license AGPL-3.0
5
+ * @author Teffen Ellis, et al.
6
+ *
7
+ * `mailwoman-un-locode` — build the lookup DB, or look up a UN/LOCODE by name or coordinate.
8
+ *
9
+ * ```sh
10
+ * mailwoman-un-locode build --csv code-list.csv --out un-locode.db
11
+ * mailwoman-un-locode --db un-locode.db --country US --name "New York"
12
+ * mailwoman-un-locode --db un-locode.db -- 40.7128 -74.0060
13
+ * ```
14
+ *
15
+ * The `--` separates flags from coordinates so negative coordinates parse as positionals (the
16
+ * coordinate form is the nearest-code lookup, formerly `--near`).
17
+ */
18
+
19
+ import { parseArgs } from "node:util"
20
+
21
+ import { buildUnLocodeDB } from "./build.ts"
22
+ import { UnLocodeLookup } from "./index.ts"
23
+
24
+ const { values, positionals } = parseArgs({
25
+ options: {
26
+ csv: { type: "string" },
27
+ out: { type: "string" },
28
+ db: { type: "string" },
29
+ country: { type: "string" },
30
+ name: { type: "string" },
31
+ },
32
+ allowPositionals: true,
33
+ })
34
+
35
+ if (positionals[0] === "build") {
36
+ if (!values.csv || !values.out) {
37
+ console.error("Usage: mailwoman-un-locode build --csv <code-list.csv> --out <db>")
38
+ process.exit(1)
39
+ }
40
+ const { rows, withCoords } = buildUnLocodeDB(values.csv, values.out)
41
+ console.error(`built ${values.out} (${rows} rows, ${withCoords} with coordinates)`)
42
+ } else {
43
+ const lat = Number(positionals[0])
44
+ const lon = Number(positionals[1])
45
+ const byName = Boolean(values.country && values.name)
46
+ const byCoord = Number.isFinite(lat) && Number.isFinite(lon)
47
+
48
+ if (!values.db || (!byName && !byCoord)) {
49
+ console.error("Usage: mailwoman-un-locode --db <db> (--country CC --name NAME | -- <lat> <lon>)")
50
+ process.exit(1)
51
+ }
52
+ const lookup = new UnLocodeLookup({ databasePath: values.db })
53
+ const code = byName ? lookup.byName(values.country!, values.name!) : lookup.nearest(lat, lon)
54
+ console.log(JSON.stringify({ unLocode: code }))
55
+ lookup.close()
56
+ }
package/index.ts ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * `@mailwoman/un-locode-lookup` — place → UN/LOCODE (UNECE Code for Trade and Transport Locations).
7
+ * Two ways in: by country + place name (exact, diacritic-folded), or by nearest coordinate (for
8
+ * the ~⅓ of entries that carry one). Backed by a `node:sqlite` table built from the UNECE code
9
+ * list. An `@mailwoman/annotations` `Annotator`.
10
+ */
11
+
12
+ import { DatabaseSync } from "node:sqlite"
13
+
14
+ import type { AnnotationSet, Annotator } from "@mailwoman/annotations"
15
+
16
+ /** Fold a place name to its match key: strip diacritics, lowercase, collapse whitespace. */
17
+ export function foldName(name: string): string {
18
+ return name
19
+ .normalize("NFD")
20
+ .replace(/[̀-ͯ]/g, "")
21
+ .toLowerCase()
22
+ .trim()
23
+ .replace(/\s+/g, " ")
24
+ }
25
+
26
+ /** Parse a UN/LOCODE coordinate (`"4923N 01522E"`) to decimal degrees, or null if absent/malformed. */
27
+ export function parseUnLocodeCoords(raw: string): { lat: number; lon: number } | null {
28
+ const m = raw.trim().match(/^(\d{2})(\d{2})([NS])\s+(\d{3})(\d{2})([EW])$/)
29
+
30
+ if (!m) return null
31
+ const lat = (Number(m[1]) + Number(m[2]) / 60) * (m[3] === "S" ? -1 : 1)
32
+ const lon = (Number(m[4]) + Number(m[5]) / 60) * (m[6] === "W" ? -1 : 1)
33
+
34
+ return { lat, lon }
35
+ }
36
+
37
+ const EARTH_R_KM = 6371
38
+ function haversineKm(aLat: number, aLon: number, bLat: number, bLon: number): number {
39
+ const dLat = ((bLat - aLat) * Math.PI) / 180
40
+ const dLon = ((bLon - aLon) * Math.PI) / 180
41
+ const s =
42
+ Math.sin(dLat / 2) ** 2 +
43
+ Math.cos((aLat * Math.PI) / 180) * Math.cos((bLat * Math.PI) / 180) * Math.sin(dLon / 2) ** 2
44
+
45
+ return 2 * EARTH_R_KM * Math.asin(Math.sqrt(s))
46
+ }
47
+
48
+ /** A UN/LOCODE lookup over a built `node:sqlite` table. */
49
+ export class UnLocodeLookup {
50
+ #db: DatabaseSync
51
+ #byName: ReturnType<DatabaseSync["prepare"]>
52
+ #byBox: ReturnType<DatabaseSync["prepare"]>
53
+
54
+ constructor(opts: { databasePath: string } | { database: DatabaseSync }) {
55
+ this.#db = "database" in opts ? opts.database : new DatabaseSync(opts.databasePath, { readOnly: true })
56
+ this.#byName = this.#db.prepare(
57
+ "SELECT country, location FROM un_locode WHERE country = ? AND nameNorm = ? LIMIT 1"
58
+ )
59
+ this.#byBox = this.#db.prepare(
60
+ "SELECT location, country, lat, lon FROM un_locode WHERE lat BETWEEN ? AND ? AND lon BETWEEN ? AND ?"
61
+ )
62
+ }
63
+
64
+ /** The UN/LOCODE (`"US NYC"`) for a country + place name, or null. */
65
+ byName(country: string, name: string): string | null {
66
+ const row = this.#byName.get(country.toUpperCase(), foldName(name)) as
67
+ | { country: string; location: string }
68
+ | undefined
69
+
70
+ return row ? `${row.country} ${row.location}` : null
71
+ }
72
+
73
+ /** The nearest coordinate-bearing UN/LOCODE within `maxKm`, or null. */
74
+ nearest(lat: number, lon: number, maxKm = 25): string | null {
75
+ const dLat = maxKm / 111
76
+ const dLon = maxKm / (111 * Math.max(0.01, Math.cos((lat * Math.PI) / 180)))
77
+ const rows = this.#byBox.all(lat - dLat, lat + dLat, lon - dLon, lon + dLon) as Array<{
78
+ location: string
79
+ country: string
80
+ lat: number
81
+ lon: number
82
+ }>
83
+ let best: { code: string; km: number } | null = null
84
+
85
+ for (const r of rows) {
86
+ const km = haversineKm(lat, lon, r.lat, r.lon)
87
+
88
+ if (km <= maxKm && (!best || km < best.km)) {
89
+ best = { code: `${r.country} ${r.location}`, km }
90
+ }
91
+ }
92
+
93
+ return best?.code ?? null
94
+ }
95
+
96
+ close(): void {
97
+ this.#db.close()
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Build an `Annotator` filling `AnnotationSet.unLocode`. Prefers a country + place-name match (when the resolver
103
+ * supplies them via `countryCode` / `placeName`), and falls back to the nearest coordinate.
104
+ */
105
+ export function makeUnLocodeAnnotator(lookup: UnLocodeLookup, opts: { maxKm?: number } = {}): Annotator {
106
+ return ({ lat, lon, countryCode, placeName }): Partial<AnnotationSet> => {
107
+ const byName = countryCode && placeName ? lookup.byName(countryCode, placeName) : null
108
+ const code = byName ?? lookup.nearest(lat, lon, opts.maxKm)
109
+
110
+ return code ? { unLocode: code } : {}
111
+ }
112
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mailwoman/un-locode-lookup",
3
- "version": "7.2.0",
3
+ "version": "7.2.1",
4
4
  "description": "Place → UN/LOCODE (UNECE Code for Trade and Transport Locations), by country + name or nearest coordinate. node:sqlite over the UNECE code list. An @mailwoman/annotations Annotator.",
5
5
  "license": "AGPL-3.0-only OR LicenseRef-Commercial",
6
6
  "repository": {
@@ -14,27 +14,44 @@
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
  "csv-parse": "^7.0.1"
39
56
  }
40
57
  }