@chofter/geo 0.0.0-stage → 0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shane O'Sullivan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,304 @@
1
- # Temporary Holding Version
1
+ # @chofter/geo
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Town and city search for any country, as a tiny dependency-free client. There is
4
+ no API and no key. The data is served as static JSON files from
5
+ [geo.chofter.com](https://geo.chofter.com), built monthly from
6
+ [GeoNames](https://www.geonames.org/). The client works out which file holds the
7
+ answer, fetches it from the CDN and ranks the results locally.
8
+
9
+ - About 226,000 towns and cities in 246 countries, with coordinates.
10
+ - One small request per keystroke at most, often none (files are cached).
11
+ - About 1.4 KB minified and gzipped. Works in browsers, Node 18+, Deno, Bun, Workers and React Native.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @chofter/geo
17
+ ```
18
+
19
+ ```js
20
+ import { createGeo } from "@chofter/geo";
21
+
22
+ const geo = createGeo();
23
+ const places = await geo.search("IE", "dub", { limit: 5 });
24
+ // [{ id: 2964574, name: "Dublin", region: "Leinster", country: "Ireland",
25
+ // countryCode: "IE", lat: 53.3331, lng: -6.2489, population: 1024027,
26
+ // label: "Dublin, Leinster, Ireland" }, ...]
27
+ ```
28
+
29
+ Without a bundler, import it straight from the CDN:
30
+
31
+ ```html
32
+ <script type="module">
33
+ import { createGeo } from "https://geo.chofter.com/geo.js";
34
+ </script>
35
+ ```
36
+
37
+ Or load the classic script, which adds one global, `choftergeo`:
38
+
39
+ ```html
40
+ <script src="https://geo.chofter.com/geo.global.min.js"></script>
41
+ <script>
42
+ const geo = choftergeo.createGeo();
43
+ </script>
44
+ ```
45
+
46
+ ### Files
47
+
48
+ Every build is in the npm package and on the CDN (`https://geo.chofter.com/<file>`),
49
+ and npm CDNs such as jsDelivr and unpkg serve the package too.
50
+
51
+ | File | Format | Import from npm | Size (gzip) |
52
+ | ------------------------ | ----------------------------- | ------------------------- | ----------- |
53
+ | `dist/geo.js` | ES module, readable | `@chofter/geo` | 2.8 KB |
54
+ | `dist/geo.min.js` | ES module, minified | `@chofter/geo/min` | 1.4 KB |
55
+ | `dist/geo.global.js` | classic script, readable | `@chofter/geo/global` | 2.8 KB |
56
+ | `dist/geo.global.min.js` | classic script, minified | `@chofter/geo/global.min` | 1.4 KB |
57
+ | `dist/geo.d.ts` | TypeScript types (all builds) | | |
58
+
59
+ Bundlers should use the default `@chofter/geo` entry and minify it themselves.
60
+ The minified files are for loading directly in a page.
61
+
62
+ ## API
63
+
64
+ ### `createGeo(options?)`
65
+
66
+ - `baseUrl`: where the data lives. Defaults to `https://geo.chofter.com/v1`;
67
+ set it if you host the files yourself.
68
+ - `fetch`: a custom `fetch` implementation.
69
+
70
+ Returns an object with:
71
+
72
+ - `search(countryCode, query, { limit = 10 })`: places in that country whose
73
+ name or an alternate name (including local spellings, such as "München" for
74
+ Munich) starts with the query, or has a later word that does. Case, accents
75
+ and punctuation are ignored. Exact matches come first, then larger places.
76
+ An empty query returns the largest places.
77
+ - `countries()`: `[{ code, name, count }]` for a country picker.
78
+ - `preload(countryCode)`: fetches the country's index early, for example when
79
+ the user picks a country.
80
+
81
+ `countryCode` is an ISO 3166-1 alpha-2 code such as `"US"` or `"ie"`.
82
+ Results include `matched` when the query matched an alternate name,
83
+ `district` when another place in the country has the same name and region, and
84
+ `localName` when the country's own language has a different name for the place.
85
+
86
+ ## Examples
87
+
88
+ These are real results from the live data. Long ones are cut down to the
89
+ fields that matter, with `// …` marking what was left out.
90
+
91
+ ### A full result
92
+
93
+ ```js
94
+ await geo.search("IE", "dub", { limit: 3 });
95
+ ```
96
+
97
+ ```json
98
+ [
99
+ {
100
+ "id": 2964574,
101
+ "name": "Dublin",
102
+ "region": "Leinster",
103
+ "country": "Ireland",
104
+ "countryCode": "IE",
105
+ "lat": 53.3331,
106
+ "lng": -6.2489,
107
+ "population": 1024027,
108
+ "label": "Dublin, Leinster, Ireland"
109
+ },
110
+ {
111
+ "id": 2964690,
112
+ "name": "Douglas",
113
+ "region": "Munster",
114
+ "country": "Ireland",
115
+ "countryCode": "IE",
116
+ "lat": 51.8744,
117
+ "lng": -8.435,
118
+ "population": 26883,
119
+ "label": "Douglas, Munster, Ireland",
120
+ "matched": "Dúbhglas"
121
+ },
122
+ {
123
+ "id": 2966131,
124
+ "name": "Blackrock",
125
+ "region": "Leinster",
126
+ "country": "Ireland",
127
+ "countryCode": "IE",
128
+ "lat": 53.3015,
129
+ "lng": -6.1778,
130
+ "population": 8821,
131
+ "label": "Blackrock, Dún Laoghaire-Rathdown, Leinster, Ireland",
132
+ "district": "Dún Laoghaire-Rathdown",
133
+ "matched": "Carraig Dubh"
134
+ }
135
+ ]
136
+ ```
137
+
138
+ `id` is the GeoNames id. `label` is ready to display. Douglas and Blackrock are
139
+ found by their Irish names, so `matched` says which name was hit. You might show
140
+ it as "Douglas (Dúbhglas)". Blackrock has a `district` because there is another
141
+ Blackrock in Leinster (see below).
142
+
143
+ ### Local spellings and other scripts
144
+
145
+ ```js
146
+ await geo.search("DE", "München", { limit: 2 });
147
+ await geo.search("RU", "Москва", { limit: 1 });
148
+ ```
149
+
150
+ ```jsonc
151
+ [
152
+ { "name": "Munich", "label": "Munich, Bavaria, Germany", "localName": "München", "matched": "München" /* … */ },
153
+ { "name": "Münchenbernsdorf", "label": "Münchenbernsdorf, Thuringia, Germany" /* … */ }
154
+ ]
155
+ [
156
+ { "name": "Moscow", "label": "Moscow, Moscow, Russia", "localName": "Москва", "matched": "Москва" /* … */ }
157
+ ]
158
+ ```
159
+
160
+ Accents are optional: `"munchen"` and `"sao pau"` work just as well.
161
+
162
+ ### Local names
163
+
164
+ `name` is in English where English has its own name for the place, and
165
+ otherwise in the local spelling in Latin letters. `localName` gives the name in
166
+ the country's own language, whatever you searched for:
167
+
168
+ ```js
169
+ (await geo.search("KR", "", { limit: 3 })).map((p) => [p.name, p.localName]);
170
+ ```
171
+
172
+ ```json
173
+ [
174
+ ["Seoul", "서울"],
175
+ ["Busan", "부산"],
176
+ ["Incheon", "인천"]
177
+ ]
178
+ ```
179
+
180
+ It is left out when there is nothing to add: when the country's first language
181
+ is English (the US, Ireland, India), when GeoNames has no name in it, or when it
182
+ is the same as `name` (Paris, Berlin). Countries with several languages use the
183
+ first one GeoNames lists, so Geneva's `localName` is German, "Genf".
184
+
185
+ ### Same name, different places
186
+
187
+ ```js
188
+ (await geo.search("US", "springfield", { limit: 4 })).map((p) => p.label);
189
+ ```
190
+
191
+ ```json
192
+ [
193
+ "Springfield, Missouri, United States",
194
+ "Springfield, Massachusetts, United States",
195
+ "Springfield, Illinois, United States",
196
+ "Springfield, Oregon, United States"
197
+ ]
198
+ ```
199
+
200
+ Exact matches come first, largest first. When two places share a name and a
201
+ region, they also get a `district` (a county or district), and the label
202
+ includes it:
203
+
204
+ ```js
205
+ (await geo.search("US", "plantation", { limit: 3 })).map((p) => p.label);
206
+ (await geo.search("IE", "blackrock", { limit: 2 })).map((p) => p.label);
207
+ ```
208
+
209
+ ```json
210
+ [
211
+ "Plantation, Broward County, Florida, United States",
212
+ "Plantation, Sarasota County, Florida, United States",
213
+ "Plantation, Monroe County, Florida, United States"
214
+ ]
215
+ [
216
+ "Blackrock, Dún Laoghaire-Rathdown, Leinster, Ireland",
217
+ "Blackrock, Louth, Leinster, Ireland"
218
+ ]
219
+ ```
220
+
221
+ So `label` tells namesakes apart in nearly every case. A few small places share
222
+ their name, region and district too; use `lat` and `lng` (or `id`) for those.
223
+
224
+ ### Ranking: exact names, then prefixes and later words
225
+
226
+ ```js
227
+ (await geo.search("US", "york")).map((p) => p.name);
228
+ ```
229
+
230
+ ```json
231
+ [
232
+ "York",
233
+ "York",
234
+ "York",
235
+ "York",
236
+ "York",
237
+ "New York City",
238
+ "West New York",
239
+ "Yorkville",
240
+ "York Beach",
241
+ "Yorktown"
242
+ ]
243
+ ```
244
+
245
+ The five towns called exactly "York" rank first. After them come names that
246
+ start with "york", or that have a later word starting with it, ordered by
247
+ population. That's how New York City appears.
248
+
249
+ ### An empty query
250
+
251
+ ```js
252
+ (await geo.search("FR", "", { limit: 5 })).map((p) => p.name);
253
+ ```
254
+
255
+ ```json
256
+ ["Paris", "Marseille", "Lyon", "Toulouse", "Nice"]
257
+ ```
258
+
259
+ The country's largest places, which are handy to show before the user types.
260
+
261
+ ### Countries
262
+
263
+ ```js
264
+ await geo.countries();
265
+ ```
266
+
267
+ ```jsonc
268
+ [
269
+ { "code": "AF", "name": "Afghanistan", "count": 319 },
270
+ { "code": "AX", "name": "Aland Islands", "count": 21 },
271
+ { "code": "AL", "name": "Albania", "count": 418 },
272
+ // … 246 countries in all, sorted by name
273
+ ]
274
+ ```
275
+
276
+ `count` is the number of places in that country.
277
+
278
+ ### No match and errors
279
+
280
+ ```js
281
+ await geo.search("IE", "zzz"); // []
282
+ await geo.search("XX", "a"); // rejects: Error("geo: xx/_.json returned 404")
283
+ ```
284
+
285
+ No match is an empty array, not an error. An unknown country code or a network
286
+ failure rejects, and the failed file is fetched again on the next call.
287
+
288
+ ## How it works
289
+
290
+ Each country has an index file, `/v1/{cc}/_.json`, that lists its prefix files.
291
+ A small country fits in its index. For a larger one, the client reads the file
292
+ for the longest listed prefix of the query, such as `/v1/us/sa.json` for "San Fr".
293
+ Busy prefixes are split further, and the shorter file keeps the most populous
294
+ places, so every keystroke stays one small request.
295
+
296
+ ## Licence
297
+
298
+ The code is MIT. The data comes from GeoNames under
299
+ [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/): if you show results,
300
+ credit GeoNames, for example "Place data © GeoNames".
301
+
302
+ Clients for other languages live alongside this one in
303
+ [shaneosullivan/geo](https://github.com/shaneosullivan/geo) and share its
304
+ conformance tests.
package/dist/geo.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ export interface Place {
2
+ /** GeoNames id. */
3
+ id: number;
4
+ name: string;
5
+ /** First-level admin division (state, province, county), may be empty. */
6
+ region: string;
7
+ /**
8
+ * Second-level admin division (county, district), set only when another place
9
+ * in the country has the same name and region.
10
+ */
11
+ district?: string;
12
+ /**
13
+ * The name in the country's own language, such as "서울" for Seoul or "München"
14
+ * for Munich. Absent when that language is English, GeoNames has no name in
15
+ * it, or it is the same as `name`.
16
+ */
17
+ localName?: string;
18
+ country: string;
19
+ countryCode: string;
20
+ lat: number;
21
+ lng: number;
22
+ population: number;
23
+ /** "Name, Region, Country", or "Name, District, Region, Country" when `district` is set. */
24
+ label: string;
25
+ /** Set when the query matched an alternate name rather than `name`. */
26
+ matched?: string;
27
+ }
28
+
29
+ export interface Country {
30
+ code: string;
31
+ name: string;
32
+ count: number;
33
+ }
34
+
35
+ export interface GeoOptions {
36
+ /** URL of the versioned data folder. Defaults to "https://geo.chofter.com/v1". */
37
+ baseUrl?: string;
38
+ fetch?: typeof fetch;
39
+ }
40
+
41
+ export interface Geo {
42
+ search(countryCode: string, query: string, options?: { limit?: number }): Promise<Place[]>;
43
+ countries(): Promise<Country[]>;
44
+ preload(countryCode: string): Promise<void>;
45
+ }
46
+
47
+ export function createGeo(options?: GeoOptions): Geo;
@@ -0,0 +1,236 @@
1
+ // @chofter/geo 0.2.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
+ (function () {
3
+ "use strict";
4
+ // Client for the static place-search files. No dependencies; works in browsers,
5
+ // Node 18+, Workers and React Native.
6
+ //
7
+ // Naming scheme (everything is relative to baseUrl, e.g. https://geo.example.com/v1):
8
+ // {countryCode}/_.json country index: name, list of prefix files, top places.
9
+ // Small countries have no prefix files; `top` is every place.
10
+ // {countryCode}/{prefix}.json places whose search key starts with `prefix`
11
+ // For a query, the file to read is the longest listed prefix of the normalised
12
+ // query. Busy prefixes are split further: "s" may hold only the most populous
13
+ // places starting with s, while "sa" or "san" hold everything for that prefix.
14
+
15
+ const LETTER_FOLDS = {
16
+ ß: "ss",
17
+ æ: "ae",
18
+ œ: "oe",
19
+ ø: "o",
20
+ đ: "d",
21
+ ð: "d",
22
+ þ: "th",
23
+ ł: "l",
24
+ ı: "i",
25
+ ħ: "h",
26
+ };
27
+
28
+ // normalize, prefixOf and fileKey are exported only so the data build can share
29
+ // them; the package's public entry point exposes nothing but createGeo.
30
+
31
+ /** Lowercase, strip accents and punctuation. Build script and client must agree on this. */
32
+ function normalize(text) {
33
+ return String(text)
34
+ .toLowerCase()
35
+ .normalize("NFD")
36
+ .replace(/\p{M}+/gu, "")
37
+ .replace(/[ßæœøđðþłıħ]/g, (letter) => LETTER_FOLDS[letter])
38
+ .replace(/['’‘ʼ`]/g, "")
39
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
40
+ .trim();
41
+ }
42
+
43
+ /** First `length` characters (code points) of a normalised key. */
44
+ function prefixOf(key, length) {
45
+ return Array.from(key).slice(0, length).join("");
46
+ }
47
+
48
+ /** URL-safe file name for a prefix: a-z0-9 as is, space as "-", anything else as ~hex. */
49
+ function fileKey(prefix) {
50
+ let fileName = "";
51
+ for (const character of prefix) {
52
+ if (/[a-z0-9]/.test(character)) {
53
+ fileName += character;
54
+ } else if (character === " ") {
55
+ fileName += "-";
56
+ } else {
57
+ fileName += "~" + character.codePointAt(0).toString(16);
58
+ }
59
+ }
60
+ return fileName;
61
+ }
62
+
63
+ // A place in the JSON files is an array:
64
+ // [name, region, lat, lng, population, id, altNames?, district?, localName?]
65
+ // `district` is set only when another place in the country has the same name and
66
+ // region. `localName` is the name in the country's own language, when that is not
67
+ // English and differs from `name`. Trailing items are left out; one that is
68
+ // missing before a present one is [] (altNames) or "".
69
+ const NAME = 0;
70
+ const POPULATION = 4;
71
+ const ALT_NAMES = 6;
72
+ const LOCAL_NAME = 8;
73
+
74
+ const EXACT_MATCH = 0;
75
+ const PREFIX_MATCH = 1;
76
+ const NO_MATCH = -1;
77
+
78
+ /** Pair each place with its names and their normalised search keys. */
79
+ function prepare(records) {
80
+ return records.map((record) => {
81
+ const names = [record[NAME], ...(record[ALT_NAMES] || [])];
82
+ if (record[LOCAL_NAME]) {
83
+ names.push(record[LOCAL_NAME]);
84
+ }
85
+ return { record, names, searchKeys: names.map(normalize) };
86
+ });
87
+ }
88
+
89
+ function matchTier(searchKey, query) {
90
+ if (searchKey === query) {
91
+ return EXACT_MATCH;
92
+ }
93
+ // A match at the start of the name or of a later word ranks the same, so
94
+ // "york" lists New York City above small towns that merely start with York.
95
+ if (searchKey.startsWith(query) || searchKey.includes(" " + query)) {
96
+ return PREFIX_MATCH;
97
+ }
98
+ return NO_MATCH;
99
+ }
100
+
101
+ /** The best tier over all of a place's names, and which name gave it. */
102
+ function bestMatch(place, query) {
103
+ let tier = NO_MATCH;
104
+ let nameIndex = 0;
105
+ place.searchKeys.forEach((searchKey, index) => {
106
+ const candidate = matchTier(searchKey, query);
107
+ if (candidate !== NO_MATCH && (tier === NO_MATCH || candidate < tier)) {
108
+ tier = candidate;
109
+ nameIndex = index;
110
+ }
111
+ });
112
+ return { tier, nameIndex };
113
+ }
114
+
115
+ const DEFAULT_BASE_URL = "https://geo.chofter.com/v1";
116
+ const DEFAULT_LIMIT = 10;
117
+
118
+ function createGeo(options = {}) {
119
+ const baseUrl = String(options.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
120
+ const fetchFile = options.fetch || globalThis.fetch.bind(globalThis);
121
+ const cache = new Map(); // path -> Promise of the transformed file contents
122
+
123
+ /** Fetch and transform a file once; failed fetches are dropped so they are retried. */
124
+ function load(path, transform) {
125
+ let pending = cache.get(path);
126
+ if (!pending) {
127
+ pending = fetchFile(`${baseUrl}/${path}`)
128
+ .then((response) => {
129
+ if (!response.ok) {
130
+ throw new Error(`geo: ${path} returned ${response.status}`);
131
+ }
132
+ return response.json();
133
+ })
134
+ .then(transform);
135
+ pending.catch(() => cache.delete(path));
136
+ cache.set(path, pending);
137
+ }
138
+ return pending;
139
+ }
140
+
141
+ function loadCountry(countryCode) {
142
+ return load(`${countryCode}/_.json`, (index) => ({
143
+ code: countryCode.toUpperCase(),
144
+ name: index.name,
145
+ depth: index.depth,
146
+ count: index.count,
147
+ prefixFiles: new Set(index.shards),
148
+ topPlaces: prepare(index.top),
149
+ }));
150
+ }
151
+
152
+ function toResult(country, place, nameIndex) {
153
+ const [name, region, lat, lng, population, id, , district, localName] = place.record;
154
+ const result = {
155
+ id,
156
+ name,
157
+ region,
158
+ country: country.name,
159
+ countryCode: country.code,
160
+ lat,
161
+ lng,
162
+ population,
163
+ label: [name, district, region, country.name].filter(Boolean).join(", "),
164
+ };
165
+ if (district) {
166
+ result.district = district;
167
+ }
168
+ if (localName) {
169
+ result.localName = localName;
170
+ }
171
+ if (nameIndex > 0) {
172
+ result.matched = place.names[nameIndex];
173
+ }
174
+ return result;
175
+ }
176
+
177
+ /** The prefix file holding every place that could match `query`, or null if none is listed. */
178
+ function prefixFileFor(country, query) {
179
+ const longest = Math.min(country.depth, Array.from(query).length);
180
+ for (let length = longest; length > 0; length--) {
181
+ const candidate = fileKey(prefixOf(query, length));
182
+ if (country.prefixFiles.has(candidate)) {
183
+ return candidate;
184
+ }
185
+ }
186
+ return null;
187
+ }
188
+
189
+ /** Search one country. `countryCode` is an ISO 3166-1 alpha-2 code. */
190
+ async function search(countryCode, query, searchOptions = {}) {
191
+ const limit = searchOptions.limit || DEFAULT_LIMIT;
192
+ const country = await loadCountry(String(countryCode).toLowerCase());
193
+ const normalizedQuery = normalize(query || "");
194
+ if (!normalizedQuery) {
195
+ return country.topPlaces.slice(0, limit).map((place) => toResult(country, place, 0));
196
+ }
197
+
198
+ let candidates = country.topPlaces;
199
+ if (country.depth > 0) {
200
+ const prefixFile = prefixFileFor(country, normalizedQuery);
201
+ if (prefixFile === null) {
202
+ return [];
203
+ }
204
+ candidates = await load(`${country.code.toLowerCase()}/${prefixFile}.json`, prepare);
205
+ }
206
+
207
+ const matches = [];
208
+ for (const place of candidates) {
209
+ const { tier, nameIndex } = bestMatch(place, normalizedQuery);
210
+ if (tier !== NO_MATCH) {
211
+ matches.push({ place, tier, nameIndex });
212
+ }
213
+ }
214
+ matches.sort(
215
+ (a, b) => a.tier - b.tier || b.place.record[POPULATION] - a.place.record[POPULATION],
216
+ );
217
+ return matches.slice(0, limit).map((match) => toResult(country, match.place, match.nameIndex));
218
+ }
219
+
220
+ /** Countries that have data: [{ code, name, count }]. */
221
+ function countries() {
222
+ return load("countries.json", (rows) =>
223
+ rows.map(([code, name, count]) => ({ code, name, count })),
224
+ );
225
+ }
226
+
227
+ /** Warm the cache for a country, e.g. when the user picks it. */
228
+ function preload(countryCode) {
229
+ return loadCountry(String(countryCode).toLowerCase()).then(() => undefined);
230
+ }
231
+
232
+ return { search, countries, preload };
233
+ }
234
+
235
+ globalThis.choftergeo = { createGeo };
236
+ })();
@@ -0,0 +1,2 @@
1
+ // @chofter/geo 0.2.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
+ (()=>{var x={ß:"ss",æ:"ae",œ:"oe",ø:"o",đ:"d",ð:"d",þ:"th",ł:"l",ı:"i",ħ:"h"};function M(o){return String(o).toLowerCase().normalize("NFD").replace(/\p{M}+/gu,"").replace(/[ßæœøđðþłıħ]/g,(e)=>x[e]).replace(/['’‘ʼ`]/g,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function P(o,e){return Array.from(o).slice(0,e).join("")}function U(o){let e="";for(let r of o)if(/[a-z0-9]/.test(r))e+=r;else if(r===" ")e+="-";else e+="~"+r.codePointAt(0).toString(16);return e}var j=0,E=4,I=6,C=8,O=0,z=1,d=-1;function F(o){return o.map((e)=>{let r=[e[j],...e[I]||[]];if(e[C])r.push(e[C]);return{record:e,names:r,searchKeys:r.map(M)}})}function D(o,e){if(o===e)return O;if(o.startsWith(e)||o.includes(" "+e))return z;return d}function R(o,e){let r=d,f=0;return o.searchKeys.forEach((p,g)=>{let u=D(p,e);if(u!==d&&(r===d||u<r))r=u,f=g}),{tier:r,nameIndex:f}}var H="https://geo.chofter.com/v1",y=10;function w(o={}){let e=String(o.baseUrl||H).replace(/\/+$/,""),r=o.fetch||globalThis.fetch.bind(globalThis),f=new Map;function p(t,n){let a=f.get(t);if(!a)a=r(`${e}/${t}`).then((c)=>{if(!c.ok)throw Error(`geo: ${t} returned ${c.status}`);return c.json()}).then(n),a.catch(()=>f.delete(t)),f.set(t,a);return a}function g(t){return p(`${t}/_.json`,(n)=>({code:t.toUpperCase(),name:n.name,depth:n.depth,count:n.count,prefixFiles:new Set(n.shards),topPlaces:F(n.top)}))}function u(t,n,a){let[c,s,h,A,m,i,,l,L]=n.record,T={id:i,name:c,region:s,country:t.name,countryCode:t.code,lat:h,lng:A,population:m,label:[c,l,s,t.name].filter(Boolean).join(", ")};if(l)T.district=l;if(L)T.localName=L;if(a>0)T.matched=n.names[a];return T}function N(t,n){let a=Math.min(t.depth,Array.from(n).length);for(let c=a;c>0;c--){let s=U(P(n,c));if(t.prefixFiles.has(s))return s}return null}async function _(t,n,a={}){let c=a.limit||y,s=await g(String(t).toLowerCase()),h=M(n||"");if(!h)return s.topPlaces.slice(0,c).map((i)=>u(s,i,0));let A=s.topPlaces;if(s.depth>0){let i=N(s,h);if(i===null)return[];A=await p(`${s.code.toLowerCase()}/${i}.json`,F)}let m=[];for(let i of A){let{tier:l,nameIndex:L}=R(i,h);if(l!==d)m.push({place:i,tier:l,nameIndex:L})}return m.sort((i,l)=>i.tier-l.tier||l.place.record[E]-i.place.record[E]),m.slice(0,c).map((i)=>u(s,i.place,i.nameIndex))}function S(){return p("countries.json",(t)=>t.map(([n,a,c])=>({code:n,name:a,count:c})))}function b(t){return g(String(t).toLowerCase()).then(()=>{return})}return{search:_,countries:S,preload:b}}globalThis.choftergeo={createGeo:w};})();
package/dist/geo.js ADDED
@@ -0,0 +1,231 @@
1
+ // @chofter/geo 0.2.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
+ // Client for the static place-search files. No dependencies; works in browsers,
3
+ // Node 18+, Workers and React Native.
4
+ //
5
+ // Naming scheme (everything is relative to baseUrl, e.g. https://geo.example.com/v1):
6
+ // {countryCode}/_.json country index: name, list of prefix files, top places.
7
+ // Small countries have no prefix files; `top` is every place.
8
+ // {countryCode}/{prefix}.json places whose search key starts with `prefix`
9
+ // For a query, the file to read is the longest listed prefix of the normalised
10
+ // query. Busy prefixes are split further: "s" may hold only the most populous
11
+ // places starting with s, while "sa" or "san" hold everything for that prefix.
12
+
13
+ const LETTER_FOLDS = {
14
+ ß: "ss",
15
+ æ: "ae",
16
+ œ: "oe",
17
+ ø: "o",
18
+ đ: "d",
19
+ ð: "d",
20
+ þ: "th",
21
+ ł: "l",
22
+ ı: "i",
23
+ ħ: "h",
24
+ };
25
+
26
+ // normalize, prefixOf and fileKey are exported only so the data build can share
27
+ // them; the package's public entry point exposes nothing but createGeo.
28
+
29
+ /** Lowercase, strip accents and punctuation. Build script and client must agree on this. */
30
+ function normalize(text) {
31
+ return String(text)
32
+ .toLowerCase()
33
+ .normalize("NFD")
34
+ .replace(/\p{M}+/gu, "")
35
+ .replace(/[ßæœøđðþłıħ]/g, (letter) => LETTER_FOLDS[letter])
36
+ .replace(/['’‘ʼ`]/g, "")
37
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
38
+ .trim();
39
+ }
40
+
41
+ /** First `length` characters (code points) of a normalised key. */
42
+ function prefixOf(key, length) {
43
+ return Array.from(key).slice(0, length).join("");
44
+ }
45
+
46
+ /** URL-safe file name for a prefix: a-z0-9 as is, space as "-", anything else as ~hex. */
47
+ function fileKey(prefix) {
48
+ let fileName = "";
49
+ for (const character of prefix) {
50
+ if (/[a-z0-9]/.test(character)) {
51
+ fileName += character;
52
+ } else if (character === " ") {
53
+ fileName += "-";
54
+ } else {
55
+ fileName += "~" + character.codePointAt(0).toString(16);
56
+ }
57
+ }
58
+ return fileName;
59
+ }
60
+
61
+ // A place in the JSON files is an array:
62
+ // [name, region, lat, lng, population, id, altNames?, district?, localName?]
63
+ // `district` is set only when another place in the country has the same name and
64
+ // region. `localName` is the name in the country's own language, when that is not
65
+ // English and differs from `name`. Trailing items are left out; one that is
66
+ // missing before a present one is [] (altNames) or "".
67
+ const NAME = 0;
68
+ const POPULATION = 4;
69
+ const ALT_NAMES = 6;
70
+ const LOCAL_NAME = 8;
71
+
72
+ const EXACT_MATCH = 0;
73
+ const PREFIX_MATCH = 1;
74
+ const NO_MATCH = -1;
75
+
76
+ /** Pair each place with its names and their normalised search keys. */
77
+ function prepare(records) {
78
+ return records.map((record) => {
79
+ const names = [record[NAME], ...(record[ALT_NAMES] || [])];
80
+ if (record[LOCAL_NAME]) {
81
+ names.push(record[LOCAL_NAME]);
82
+ }
83
+ return { record, names, searchKeys: names.map(normalize) };
84
+ });
85
+ }
86
+
87
+ function matchTier(searchKey, query) {
88
+ if (searchKey === query) {
89
+ return EXACT_MATCH;
90
+ }
91
+ // A match at the start of the name or of a later word ranks the same, so
92
+ // "york" lists New York City above small towns that merely start with York.
93
+ if (searchKey.startsWith(query) || searchKey.includes(" " + query)) {
94
+ return PREFIX_MATCH;
95
+ }
96
+ return NO_MATCH;
97
+ }
98
+
99
+ /** The best tier over all of a place's names, and which name gave it. */
100
+ function bestMatch(place, query) {
101
+ let tier = NO_MATCH;
102
+ let nameIndex = 0;
103
+ place.searchKeys.forEach((searchKey, index) => {
104
+ const candidate = matchTier(searchKey, query);
105
+ if (candidate !== NO_MATCH && (tier === NO_MATCH || candidate < tier)) {
106
+ tier = candidate;
107
+ nameIndex = index;
108
+ }
109
+ });
110
+ return { tier, nameIndex };
111
+ }
112
+
113
+ const DEFAULT_BASE_URL = "https://geo.chofter.com/v1";
114
+ const DEFAULT_LIMIT = 10;
115
+
116
+ export function createGeo(options = {}) {
117
+ const baseUrl = String(options.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
118
+ const fetchFile = options.fetch || globalThis.fetch.bind(globalThis);
119
+ const cache = new Map(); // path -> Promise of the transformed file contents
120
+
121
+ /** Fetch and transform a file once; failed fetches are dropped so they are retried. */
122
+ function load(path, transform) {
123
+ let pending = cache.get(path);
124
+ if (!pending) {
125
+ pending = fetchFile(`${baseUrl}/${path}`)
126
+ .then((response) => {
127
+ if (!response.ok) {
128
+ throw new Error(`geo: ${path} returned ${response.status}`);
129
+ }
130
+ return response.json();
131
+ })
132
+ .then(transform);
133
+ pending.catch(() => cache.delete(path));
134
+ cache.set(path, pending);
135
+ }
136
+ return pending;
137
+ }
138
+
139
+ function loadCountry(countryCode) {
140
+ return load(`${countryCode}/_.json`, (index) => ({
141
+ code: countryCode.toUpperCase(),
142
+ name: index.name,
143
+ depth: index.depth,
144
+ count: index.count,
145
+ prefixFiles: new Set(index.shards),
146
+ topPlaces: prepare(index.top),
147
+ }));
148
+ }
149
+
150
+ function toResult(country, place, nameIndex) {
151
+ const [name, region, lat, lng, population, id, , district, localName] = place.record;
152
+ const result = {
153
+ id,
154
+ name,
155
+ region,
156
+ country: country.name,
157
+ countryCode: country.code,
158
+ lat,
159
+ lng,
160
+ population,
161
+ label: [name, district, region, country.name].filter(Boolean).join(", "),
162
+ };
163
+ if (district) {
164
+ result.district = district;
165
+ }
166
+ if (localName) {
167
+ result.localName = localName;
168
+ }
169
+ if (nameIndex > 0) {
170
+ result.matched = place.names[nameIndex];
171
+ }
172
+ return result;
173
+ }
174
+
175
+ /** The prefix file holding every place that could match `query`, or null if none is listed. */
176
+ function prefixFileFor(country, query) {
177
+ const longest = Math.min(country.depth, Array.from(query).length);
178
+ for (let length = longest; length > 0; length--) {
179
+ const candidate = fileKey(prefixOf(query, length));
180
+ if (country.prefixFiles.has(candidate)) {
181
+ return candidate;
182
+ }
183
+ }
184
+ return null;
185
+ }
186
+
187
+ /** Search one country. `countryCode` is an ISO 3166-1 alpha-2 code. */
188
+ async function search(countryCode, query, searchOptions = {}) {
189
+ const limit = searchOptions.limit || DEFAULT_LIMIT;
190
+ const country = await loadCountry(String(countryCode).toLowerCase());
191
+ const normalizedQuery = normalize(query || "");
192
+ if (!normalizedQuery) {
193
+ return country.topPlaces.slice(0, limit).map((place) => toResult(country, place, 0));
194
+ }
195
+
196
+ let candidates = country.topPlaces;
197
+ if (country.depth > 0) {
198
+ const prefixFile = prefixFileFor(country, normalizedQuery);
199
+ if (prefixFile === null) {
200
+ return [];
201
+ }
202
+ candidates = await load(`${country.code.toLowerCase()}/${prefixFile}.json`, prepare);
203
+ }
204
+
205
+ const matches = [];
206
+ for (const place of candidates) {
207
+ const { tier, nameIndex } = bestMatch(place, normalizedQuery);
208
+ if (tier !== NO_MATCH) {
209
+ matches.push({ place, tier, nameIndex });
210
+ }
211
+ }
212
+ matches.sort(
213
+ (a, b) => a.tier - b.tier || b.place.record[POPULATION] - a.place.record[POPULATION],
214
+ );
215
+ return matches.slice(0, limit).map((match) => toResult(country, match.place, match.nameIndex));
216
+ }
217
+
218
+ /** Countries that have data: [{ code, name, count }]. */
219
+ function countries() {
220
+ return load("countries.json", (rows) =>
221
+ rows.map(([code, name, count]) => ({ code, name, count })),
222
+ );
223
+ }
224
+
225
+ /** Warm the cache for a country, e.g. when the user picks it. */
226
+ function preload(countryCode) {
227
+ return loadCountry(String(countryCode).toLowerCase()).then(() => undefined);
228
+ }
229
+
230
+ return { search, countries, preload };
231
+ }
@@ -0,0 +1,2 @@
1
+ // @chofter/geo 0.2.0 · MIT · https://geo.chofter.com · data © GeoNames (CC BY 4.0)
2
+ var x={ß:"ss",æ:"ae",œ:"oe",ø:"o",đ:"d",ð:"d",þ:"th",ł:"l",ı:"i",ħ:"h"};function M(o){return String(o).toLowerCase().normalize("NFD").replace(/\p{M}+/gu,"").replace(/[ßæœøđðþłıħ]/g,(e)=>x[e]).replace(/['’‘ʼ`]/g,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function P(o,e){return Array.from(o).slice(0,e).join("")}function U(o){let e="";for(let r of o)if(/[a-z0-9]/.test(r))e+=r;else if(r===" ")e+="-";else e+="~"+r.codePointAt(0).toString(16);return e}var b=0,E=4,j=6,C=8,I=0,O=1,h=-1;function F(o){return o.map((e)=>{let r=[e[b],...e[j]||[]];if(e[C])r.push(e[C]);return{record:e,names:r,searchKeys:r.map(M)}})}function z(o,e){if(o===e)return I;if(o.startsWith(e)||o.includes(" "+e))return O;return h}function D(o,e){let r=h,f=0;return o.searchKeys.forEach((p,g)=>{let u=z(p,e);if(u!==h&&(r===h||u<r))r=u,f=g}),{tier:r,nameIndex:f}}var R="https://geo.chofter.com/v1",H=10;function y(o={}){let e=String(o.baseUrl||R).replace(/\/+$/,""),r=o.fetch||globalThis.fetch.bind(globalThis),f=new Map;function p(t,n){let a=f.get(t);if(!a)a=r(`${e}/${t}`).then((c)=>{if(!c.ok)throw Error(`geo: ${t} returned ${c.status}`);return c.json()}).then(n),a.catch(()=>f.delete(t)),f.set(t,a);return a}function g(t){return p(`${t}/_.json`,(n)=>({code:t.toUpperCase(),name:n.name,depth:n.depth,count:n.count,prefixFiles:new Set(n.shards),topPlaces:F(n.top)}))}function u(t,n,a){let[c,s,m,A,d,i,,l,L]=n.record,T={id:i,name:c,region:s,country:t.name,countryCode:t.code,lat:m,lng:A,population:d,label:[c,l,s,t.name].filter(Boolean).join(", ")};if(l)T.district=l;if(L)T.localName=L;if(a>0)T.matched=n.names[a];return T}function w(t,n){let a=Math.min(t.depth,Array.from(n).length);for(let c=a;c>0;c--){let s=U(P(n,c));if(t.prefixFiles.has(s))return s}return null}async function N(t,n,a={}){let c=a.limit||H,s=await g(String(t).toLowerCase()),m=M(n||"");if(!m)return s.topPlaces.slice(0,c).map((i)=>u(s,i,0));let A=s.topPlaces;if(s.depth>0){let i=w(s,m);if(i===null)return[];A=await p(`${s.code.toLowerCase()}/${i}.json`,F)}let d=[];for(let i of A){let{tier:l,nameIndex:L}=D(i,m);if(l!==h)d.push({place:i,tier:l,nameIndex:L})}return d.sort((i,l)=>i.tier-l.tier||l.place.record[E]-i.place.record[E]),d.slice(0,c).map((i)=>u(s,i.place,i.nameIndex))}function _(){return p("countries.json",(t)=>t.map(([n,a,c])=>({code:n,name:a,count:c})))}function S(t){return g(String(t).toLowerCase()).then(()=>{return})}return{search:N,countries:_,preload:S}}export{y as createGeo};
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@chofter/geo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Tiny, dependency-free town and city search over static GeoNames files. No API, no key.",
5
+ "keywords": [
6
+ "geonames",
7
+ "geocoding",
8
+ "places",
9
+ "cities",
10
+ "towns",
11
+ "autocomplete",
12
+ "search"
13
+ ],
14
+ "homepage": "https://github.com/shaneosullivan/geo/tree/main/js#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/shaneosullivan/geo.git",
18
+ "directory": "js"
19
+ },
20
+ "bugs": "https://github.com/shaneosullivan/geo/issues",
21
+ "license": "MIT",
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/geo.d.ts",
27
+ "default": "./dist/geo.js"
28
+ },
29
+ "./min": {
30
+ "types": "./dist/geo.d.ts",
31
+ "default": "./dist/geo.min.js"
32
+ },
33
+ "./global": "./dist/geo.global.js",
34
+ "./global.min": "./dist/geo.global.min.js",
35
+ "./package.json": "./package.json"
36
+ },
37
+ "types": "./dist/geo.d.ts",
38
+ "unpkg": "./dist/geo.global.min.js",
39
+ "jsdelivr": "./dist/geo.global.min.js",
40
+ "files": [
41
+ "dist"
42
+ ],
43
+ "scripts": {
44
+ "build": "bun build.mjs",
45
+ "test": "bun build.mjs && node --test",
46
+ "lint": "oxlint -c ../.oxlintrc.json .",
47
+ "format": "oxfmt -c ../.oxfmtrc.json .",
48
+ "format:check": "oxfmt --check -c ../.oxfmtrc.json .",
49
+ "prepublishOnly": "npm test"
50
+ },
51
+ "engines": {
52
+ "node": ">=18"
53
+ },
54
+ "devDependencies": {
55
+ "oxlint": "^1.94.0",
56
+ "oxfmt": "^0.79.0"
57
+ }
58
+ }