[content] Places: 7,342 public-domain towns searched on the device, and a sunset guess for every time zone a browser reports
This commit is contained in:
@@ -8,7 +8,9 @@
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./validate": "./src/validator.ts"
|
||||
"./validate": "./src/validator.ts",
|
||||
"./places": "./src/places/places.ts",
|
||||
"./guess": "./src/places/guess.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* The guess when a player skips choosing a town: the largest town in the device's
|
||||
* time zone, or the zone's own location from the time zone database (ROADMAP Phase 1:
|
||||
* "if skipped, it is guessed from the device time zone"). Never GPS, never a lookup.
|
||||
* Small, so the garden can load it without the town list.
|
||||
*/
|
||||
import data from './zone-guesses.json' with { type: 'json' };
|
||||
import type { Town } from './places.js';
|
||||
|
||||
type Guess = readonly [name: string, country: string, lat: number, lon: number];
|
||||
const guesses = data.guesses as unknown as Readonly<Record<string, Guess>>;
|
||||
|
||||
/**
|
||||
* A town for `timeZone`, the name the device reports (Intl's, so Asia/Calcutta and
|
||||
* Asia/Kolkata both work). Null for a zone that names no place, such as UTC: then
|
||||
* the player has to choose.
|
||||
*/
|
||||
export function guessTown(timeZone: string): Town | null {
|
||||
const g = Object.hasOwn(guesses, timeZone) ? guesses[timeZone] : undefined;
|
||||
if (!g) return null;
|
||||
return { name: g[0], region: '', country: g[1], lat: g[2], lon: g[3], timeZone };
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* The towns a player can choose for the sunset (.agents/features/sunset-place.md).
|
||||
* Data: places.json, built by scripts/build-places.ts from Natural Earth and the
|
||||
* IANA time zone database, both public domain. Everything here runs on the device;
|
||||
* a search never leaves it.
|
||||
*
|
||||
* Large (about 400 KB): the app imports this module only when the search opens.
|
||||
* The garden's guess lives in ./guess.ts, which does not load it.
|
||||
*/
|
||||
import data from './places.json' with { type: 'json' };
|
||||
|
||||
/** A town a player may choose. The only location Rosea ever knows (CLAUDE.md §5.6 rule 6). */
|
||||
export interface Town {
|
||||
readonly name: string;
|
||||
/** The province, state or region, or '' when it adds nothing. */
|
||||
readonly region: string;
|
||||
readonly country: string;
|
||||
readonly lat: number;
|
||||
readonly lon: number;
|
||||
readonly timeZone: string;
|
||||
}
|
||||
|
||||
type Row = readonly [string, string, string, number, number, number, number, number];
|
||||
const rows = data.places as unknown as readonly Row[];
|
||||
|
||||
const town = (r: Row): Town => ({
|
||||
name: r[0],
|
||||
region: r[2],
|
||||
country: data.countries[r[3]] ?? '',
|
||||
lat: r[4],
|
||||
lon: r[5],
|
||||
timeZone: data.zones[r[6]] ?? 'UTC'
|
||||
});
|
||||
|
||||
/** Lower case, no accents, words separated by single spaces: "Plzeň" and "plzen" meet. */
|
||||
export function normalize(s: string): string {
|
||||
return s.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
|
||||
}
|
||||
|
||||
let index: { names: string[]; others: string[]; where: string[] } | undefined;
|
||||
function searchIndex(): NonNullable<typeof index> {
|
||||
index ??= {
|
||||
names: rows.map((r) => normalize(r[0])),
|
||||
others: rows.map((r) => normalize(r[1].replace(/\|/g, ' | '))),
|
||||
where: rows.map((r) => normalize(`${r[2]} ${data.countries[r[3]] ?? ''}`))
|
||||
};
|
||||
return index;
|
||||
}
|
||||
|
||||
/** How well a town's names match: lower is better, Infinity is no match. */
|
||||
function score(q: string, name: string, others: string): number {
|
||||
if (name === q) return 0;
|
||||
if (name.startsWith(q)) return 1;
|
||||
if (name.includes(` ${q}`)) return 2;
|
||||
if (others.split(' | ').some((o) => o === q)) return 3;
|
||||
if (others.split(' | ').some((o) => o.startsWith(q) || o.includes(` ${q}`))) return 4;
|
||||
return Infinity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Towns matching what the player typed, best first; among equals, the larger town
|
||||
* first. "Sydney, Canada" narrows by region or country after a comma.
|
||||
*/
|
||||
export function searchTowns(query: string, limit = 8): Town[] {
|
||||
const [namePart = '', wherePart = ''] = query.split(',');
|
||||
const q = normalize(namePart);
|
||||
const w = normalize(wherePart);
|
||||
if (q === '') return [];
|
||||
const { names, others, where } = searchIndex();
|
||||
const hits: { i: number; s: number }[] = [];
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const s = score(q, names[i]!, others[i]!);
|
||||
if (s === Infinity) continue;
|
||||
if (w && !where[i]!.split(' ').some((word) => word.startsWith(w.split(' ')[0]!)) && !where[i]!.includes(w)) continue;
|
||||
hits.push({ i, s });
|
||||
}
|
||||
// Rows are stored largest first, so sorting by score alone keeps size order within a score.
|
||||
hits.sort((a, b) => a.s - b.s || a.i - b.i);
|
||||
return hits.slice(0, limit).map((h) => town(rows[h.i]!));
|
||||
}
|
||||
|
||||
/** Every town, for checks over the whole list. */
|
||||
export function allTowns(): Town[] {
|
||||
return rows.map(town);
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,117 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { guessTown } from '../src/places/guess.js';
|
||||
import { allTowns, normalize, searchTowns, type Town } from '../src/places/places.js';
|
||||
|
||||
const towns = allTowns();
|
||||
const first = (q: string): Town | undefined => searchTowns(q)[0];
|
||||
|
||||
function standardOffset(zone: string): number {
|
||||
const f = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'longOffset' });
|
||||
const at = (ms: number): number => {
|
||||
const m = /GMT([+-])(\d\d):(\d\d)/.exec(f.formatToParts(ms).find((p) => p.type === 'timeZoneName')?.value ?? '');
|
||||
return m ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) + Number(m[3]) / 60) : 0;
|
||||
};
|
||||
return Math.min(at(Date.UTC(2026, 0, 15)), at(Date.UTC(2026, 6, 15)));
|
||||
}
|
||||
|
||||
describe('the town list', () => {
|
||||
it('holds every Natural Earth town, each with a position and a zone Intl knows', () => {
|
||||
expect(towns).toHaveLength(7342);
|
||||
const zones = new Set(towns.map((t) => t.timeZone));
|
||||
for (const z of zones) expect(() => new Intl.DateTimeFormat('en', { timeZone: z })).not.toThrow();
|
||||
for (const t of towns) {
|
||||
expect(Math.abs(t.lat)).toBeLessThanOrEqual(90);
|
||||
expect(Math.abs(t.lon)).toBeLessThanOrEqual(180);
|
||||
expect(t.name).not.toBe('');
|
||||
expect(t.name).not.toContain('�');
|
||||
}
|
||||
});
|
||||
|
||||
it("every town's clock fits its longitude within 3.5 hours, across the date line too", () => {
|
||||
const off = new Map<string, number>();
|
||||
const bad = towns.filter((t) => {
|
||||
if (!off.has(t.timeZone)) off.set(t.timeZone, standardOffset(t.timeZone));
|
||||
const drift = ((((off.get(t.timeZone)! - t.lon / 15) % 24) + 36) % 24) - 12;
|
||||
return Math.abs(drift) > 3.5;
|
||||
});
|
||||
expect(bad.map((t) => `${t.name} ${t.timeZone}`)).toEqual([]);
|
||||
});
|
||||
|
||||
// Natural Earth's own zones were wrong for these; the build corrects them.
|
||||
it.each([
|
||||
['Prague', 'Czechia', 'Europe/Prague'], // Natural Earth: America/Chicago
|
||||
['Cardiff', 'United Kingdom', 'Europe/London'], // Natural Earth: Australia/Sydney
|
||||
['Sydney', 'Australia', 'Australia/Sydney'], // Natural Earth: none
|
||||
['Anchorage', 'United States of America', 'America/Anchorage'], // Natural Earth: America/Juneau
|
||||
['Kryvyi Rih', 'Ukraine', 'Europe/Kyiv'], // never Simferopol's Moscow time
|
||||
['Apia', 'Samoa', 'Pacific/Apia'], // UTC+13 at 172° W
|
||||
['Pristina', 'Kosovo', 'Europe/Belgrade'] // no ISO code in Natural Earth
|
||||
])('%s, %s, keeps %s', (name, country, zone) => {
|
||||
const t = towns.find((x) => x.name === name && x.country === country);
|
||||
expect(t?.timeZone).toBe(zone);
|
||||
});
|
||||
});
|
||||
|
||||
describe('searchTowns', () => {
|
||||
it('finds a town by its English name, its local name, or without accents', () => {
|
||||
expect(first('brno')?.name).toBe('Brno');
|
||||
expect(first('praha')?.name).toBe('Prague');
|
||||
expect(first('plzen')?.name).toBe('Plzeň');
|
||||
expect(first('Plzeň')?.name).toBe('Plzeň');
|
||||
expect(first('ceske bud')?.name).toBe('České Budějovice');
|
||||
});
|
||||
|
||||
it('puts the larger of two towns with one name first, and a comma narrows by country or region', () => {
|
||||
const sydneys = searchTowns('sydney');
|
||||
expect(sydneys[0]?.country).toBe('Australia');
|
||||
expect(sydneys.some((t) => t.country === 'Canada')).toBe(true);
|
||||
expect(first('sydney, canada')?.country).toBe('Canada');
|
||||
expect(first('sydney, nova')?.region).toBe('Nova Scotia');
|
||||
});
|
||||
|
||||
it('an exact name beats a longer one that starts the same', () => {
|
||||
expect(first('york')?.name).toBe('York');
|
||||
});
|
||||
|
||||
it('nothing typed, or nothing found, is an empty list, never an error', () => {
|
||||
expect(searchTowns('')).toEqual([]);
|
||||
expect(searchTowns(' ')).toEqual([]);
|
||||
expect(searchTowns('zzzzqx')).toEqual([]);
|
||||
});
|
||||
|
||||
it('never returns more than asked', () => {
|
||||
expect(searchTowns('san', 5)).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('normalize folds case, accents and punctuation', () => {
|
||||
expect(normalize(' Hradec Králové! ')).toBe('hradec kralove');
|
||||
expect(normalize("Nuku'alofa")).toBe('nuku alofa');
|
||||
});
|
||||
});
|
||||
|
||||
describe('guessTown', () => {
|
||||
it.each([
|
||||
['Europe/Prague', 'Prague'],
|
||||
['America/New_York', 'New York City'],
|
||||
['America/Anchorage', 'Anchorage'],
|
||||
['Australia/Sydney', 'Sydney'],
|
||||
['Asia/Kolkata', 'Mumbai'],
|
||||
['Asia/Calcutta', 'Mumbai'], // the name browsers report
|
||||
['Europe/Kiev', 'Kyiv'] // likewise
|
||||
])('%s guesses %s', (zone, name) => {
|
||||
const t = guessTown(zone);
|
||||
expect(t?.name).toBe(name);
|
||||
expect(t?.timeZone).toBe(zone);
|
||||
});
|
||||
|
||||
it('a zone with no place, such as UTC, guesses nothing: the player chooses', () => {
|
||||
expect(guessTown('UTC')).toBeNull();
|
||||
expect(guessTown('Etc/GMT+3')).toBeNull();
|
||||
expect(guessTown('constructor')).toBeNull(); // not a key of a plain object's prototype
|
||||
});
|
||||
|
||||
it('every zone Intl knows has a guess or is a zone of no place', () => {
|
||||
const missing = Intl.supportedValuesOf('timeZone').filter((z) => guessTown(z) === null && !/^(Etc\/|UTC$|GMT)/.test(z));
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* Builds packages/content/src/places/places.json: the towns a player can choose for
|
||||
* the sunset, and the best guess for each time zone (.agents/features/sunset-place.md).
|
||||
* Run by hand after downloading the two public-domain sources into one folder:
|
||||
*
|
||||
* tsx scripts/build-places.ts <folder>
|
||||
*
|
||||
* <folder>/ne/ne_10m_populated_places.dbf Natural Earth 10m populated places
|
||||
* (https://www.naturalearthdata.com, public domain), from its .zip
|
||||
* <folder>/zone.tab, zone1970.tab, version the IANA time zone database
|
||||
* (https://data.iana.org/time-zones/tzdb/, public domain)
|
||||
*
|
||||
* Only the derived file is committed. The downloads stay outside the repository.
|
||||
*/
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const folder = process.argv[2];
|
||||
if (!folder) {
|
||||
console.error('Usage: tsx scripts/build-places.ts <folder with ne/ and the tzdb tables>');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
/** Reads a dBase III table: the attribute part of a shapefile. */
|
||||
function readDbf(path: string): Record<string, string>[] {
|
||||
const buf = readFileSync(path);
|
||||
const count = buf.readUInt32LE(4);
|
||||
const headerLength = buf.readUInt16LE(8);
|
||||
const recordLength = buf.readUInt16LE(10);
|
||||
const fields: { name: string; length: number }[] = [];
|
||||
for (let at = 32; buf[at] !== 0x0d; at += 32) {
|
||||
fields.push({ name: buf.toString('latin1', at, at + 11).replace(/\0.*$/, ''), length: buf[at + 16] ?? 0 });
|
||||
}
|
||||
const rows: Record<string, string>[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
let at = headerLength + i * recordLength;
|
||||
if (buf[at] === 0x2a) continue; // deleted
|
||||
at += 1;
|
||||
const row: Record<string, string> = {};
|
||||
for (const f of fields) {
|
||||
row[f.name] = buf.toString('utf8', at, at + f.length).trim();
|
||||
at += f.length;
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** ±DDMM[SS]±DDDMM[SS] from zone.tab, in degrees. */
|
||||
function isoCoordinates(s: string): [number, number] {
|
||||
const m = /^([+-])(\d{2})(\d{2})(\d{2})?([+-])(\d{3})(\d{2})(\d{2})?$/.exec(s);
|
||||
if (!m) throw new Error(`zone.tab: bad coordinates ${s}`);
|
||||
const deg = (sign: string, d: string, mm: string, ss = '0'): number => (sign === '-' ? -1 : 1) * (Number(d) + Number(mm) / 60 + Number(ss) / 3600);
|
||||
return [deg(m[1]!, m[2]!, m[3]!, m[4]), deg(m[5]!, m[6]!, m[7]!, m[8])];
|
||||
}
|
||||
|
||||
const validZone = (zone: string): boolean => {
|
||||
try {
|
||||
new Intl.DateTimeFormat('en', { timeZone: zone });
|
||||
return true;
|
||||
} catch {
|
||||
return false; // reported below as dropped, never silently
|
||||
}
|
||||
};
|
||||
|
||||
const round2 = (x: number): number => Math.round(x * 100) / 100;
|
||||
|
||||
// --- The time zone database: which zones each country has, and where -------
|
||||
interface TzZone { readonly zone: string; readonly lat: number; readonly lon: number; readonly countries: readonly string[] }
|
||||
const tz = new Map<string, TzZone>();
|
||||
for (const file of ['zone1970.tab', 'zone.tab']) {
|
||||
for (const line of readFileSync(join(folder, file), 'utf8').split('\n')) {
|
||||
if (line.startsWith('#') || line.trim() === '') continue;
|
||||
const [codes, coords, zone] = line.split('\t');
|
||||
if (!codes || !coords || !zone || !validZone(zone)) continue;
|
||||
const [lat, lon] = isoCoordinates(coords);
|
||||
const old = tz.get(zone);
|
||||
tz.set(zone, { zone, lat, lon, countries: [...new Set([...(old?.countries ?? []), ...codes.split(',')])] });
|
||||
}
|
||||
}
|
||||
|
||||
/** The zone's clock through 2026: its offset in minutes on the 1st and 15th of every month. */
|
||||
const clocks = new Map<string, string>();
|
||||
function clockOf(zone: string): string {
|
||||
let c = clocks.get(zone);
|
||||
if (c === undefined) {
|
||||
const f = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'longOffset' });
|
||||
c = Array.from({ length: 24 }, (_, i) => f.formatToParts(Date.UTC(2026, i >> 1, i % 2 ? 15 : 1, 12)).find((p) => p.type === 'timeZoneName')?.value ?? '').join(',');
|
||||
clocks.set(zone, c);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
const standardOffset = (zone: string): number => {
|
||||
const hours = clockOf(zone).split(',').map((s) => {
|
||||
const m = /GMT([+-])(\d\d):(\d\d)/.exec(s);
|
||||
return m ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) + Number(m[3]) / 60) : 0;
|
||||
});
|
||||
return Math.min(...hours);
|
||||
};
|
||||
|
||||
const MAX_SOLAR_DRIFT_HOURS = 3.5; // the furthest a real zone strays from its longitude (western China: ~3)
|
||||
/** Whether a zone's clock fits a longitude, the long way round the date line too (Tonga: UTC+13 at 175° W). */
|
||||
const fitsLongitude = (zone: string, lon: number): boolean => {
|
||||
const drift = (((standardOffset(zone) - lon / 15) % 24) + 36) % 24 - 12;
|
||||
return Math.abs(drift) <= MAX_SOLAR_DRIFT_HOURS;
|
||||
};
|
||||
const countryZones = (country: string): TzZone[] => [...tz.values()].filter((z) => z.countries.includes(country));
|
||||
|
||||
const d2 = (a: { lat: number; lon: number }, b: { lat: number; lon: number }): number =>
|
||||
(a.lat - b.lat) ** 2 + ((a.lon - b.lon) * Math.cos((a.lat * Math.PI) / 180)) ** 2;
|
||||
|
||||
/**
|
||||
* Natural Earth's own TIMEZONE, if it can be trusted: a clock identical all through
|
||||
* 2026 to one of the country's zones in the time zone database (which also accepts old
|
||||
* names such as Europe/Kiev), with an offset that fits the longitude. Returned as the
|
||||
* nearest of the country's zones with that clock, so Anchorage, filed under
|
||||
* America/Juneau, is America/Anchorage.
|
||||
*/
|
||||
function trustedZone(neZone: string, country: string, lat: number, lon: number): string | null {
|
||||
if (!neZone || !validZone(neZone) || !fitsLongitude(neZone, lon)) return null;
|
||||
const same = countryZones(country).filter((z) => clockOf(z.zone) === clockOf(neZone));
|
||||
return same.sort((a, b) => d2({ lat, lon }, a) - d2({ lat, lon }, b))[0]?.zone ?? null;
|
||||
}
|
||||
|
||||
/** A name field that a fixed-width DBF did not cut in the middle of a letter. */
|
||||
const clean = (s: string | undefined): string => (s && !s.includes('�') ? s : '');
|
||||
|
||||
// --- Natural Earth towns --------------------------------------------------
|
||||
const raw = readDbf(join(folder, 'ne', 'ne_10m_populated_places.dbf'));
|
||||
const zones: string[] = [];
|
||||
const countries: string[] = [];
|
||||
const index = (list: string[], v: string): number => {
|
||||
let i = list.indexOf(v);
|
||||
if (i < 0) i = list.push(v) - 1;
|
||||
return i;
|
||||
};
|
||||
|
||||
/** [name, other names for search ('|'-joined), region, country index, lat, lon, zone index, population in thousands] */
|
||||
type Row = [string, string, string, number, number, number, number, number];
|
||||
interface Town { r: Record<string, string>; name: string; country: string; lat: number; lon: number; zone: string | null }
|
||||
/**
|
||||
* Natural Earth gives these no ISO code (-99). The code here only picks the zone whose
|
||||
* clock they keep; the country shown to the player is Natural Earth's own name.
|
||||
*/
|
||||
const CLOCK_COUNTRY: Readonly<Record<string, string>> = { Kosovo: 'RS', 'Northern Cyprus': 'CY', Somaliland: 'SO' };
|
||||
/** Natural Earth's Latin-script name columns, searched as other names. */
|
||||
const SEARCH_LANGUAGES = ['DE', 'ES', 'FR', 'PT', 'IT', 'NL', 'PL', 'SV', 'HU', 'TR', 'ID', 'VI'] as const;
|
||||
const towns: Town[] = [];
|
||||
const dropped: string[] = [];
|
||||
for (const r of raw) {
|
||||
const lat = Number(r['LATITUDE']);
|
||||
const lon = Number(r['LONGITUDE']);
|
||||
const name = clean(r['NAME_EN']) || clean(r['NAME']);
|
||||
if (!name || !Number.isFinite(lat) || !Number.isFinite(lon)) {
|
||||
dropped.push(`${r['NAME']} (${r['ADM0NAME']}): no usable name or position`);
|
||||
continue;
|
||||
}
|
||||
const country = r['ISO_A2'] === '-99' ? (CLOCK_COUNTRY[r['ADM0NAME'] ?? ''] ?? '') : (r['ISO_A2'] ?? '');
|
||||
towns.push({ r, name, country, lat, lon, zone: trustedZone(r['TIMEZONE'] ?? '', country, lat, lon) });
|
||||
}
|
||||
|
||||
// A town without a trusted zone takes the zone most of its five nearest trusted
|
||||
// towns in the same country share; with none, the country's nearest zone location.
|
||||
const trusted = towns.filter((t) => t.zone !== null);
|
||||
const corrected: string[] = [];
|
||||
for (const t of towns) {
|
||||
if (t.zone !== null) continue;
|
||||
const near = trusted.filter((o) => o.country === t.country).sort((a, b) => d2(t, a) - d2(t, b)).slice(0, 5);
|
||||
const votes = new Map<string, number>();
|
||||
for (const o of near) votes.set(o.zone!, (votes.get(o.zone!) ?? 0) + 1);
|
||||
const voted = [...votes.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
|
||||
const location = countryZones(t.country).filter((z) => fitsLongitude(z.zone, t.lon)).sort((a, b) => d2(t, a) - d2(t, b))[0]?.zone;
|
||||
t.zone = voted ?? location ?? null;
|
||||
if (t.zone === null) dropped.push(`${t.name} (${t.r['ADM0NAME']}, ${t.country}): no zone for the country`);
|
||||
else corrected.push(`${t.name} (${t.country}): '${t.r['TIMEZONE']}' -> ${t.zone}${voted ? ' (neighbours)' : ' (zone location)'}`);
|
||||
}
|
||||
|
||||
const rows: Row[] = [];
|
||||
for (const t of towns) {
|
||||
if (t.zone === null) continue;
|
||||
const { r, name } = t;
|
||||
// Other names a player may type: the local name (NAMEPAR: Praha, Wien) and the
|
||||
// Latin-script language columns. Natural Earth has no Czech column.
|
||||
const names = [r['NAME'], r['NAMEASCII'], r['NAMEPAR'], r['MEGANAME'], ...(r['NAMEALT'] ?? '').split('|'), ...SEARCH_LANGUAGES.map((l) => r[`NAME_${l}`])];
|
||||
const others = [...new Set(names.map((s) => clean(s?.trim())).filter((s) => s && s !== name))];
|
||||
const region = r['ADM1NAME'] === name ? '' : clean(r['ADM1NAME']);
|
||||
rows.push([name, others.join('|'), region, index(countries, r['ADM0NAME'] ?? ''), round2(t.lat), round2(t.lon), index(zones, t.zone), Math.round(Number(r['POP_MAX'] ?? 0) / 1000)]);
|
||||
}
|
||||
// Largest first, so a search shows the town most people mean.
|
||||
rows.sort((a, b) => b[7] - a[7] || a[0].localeCompare(b[0]));
|
||||
|
||||
// --- One guess per time zone ----------------------------------------------
|
||||
// The largest town in the zone; where Natural Earth has none, the zone's own
|
||||
// location from the time zone database, named after the zone. Kept in its own
|
||||
// small file, so the garden can guess without loading every town.
|
||||
/** zone -> [name, country, lat, lon] */
|
||||
const guesses: Record<string, [string, string, number, number]> = {};
|
||||
for (const r of rows) {
|
||||
const zone = zones[r[6]]!;
|
||||
if (!(zone in guesses)) guesses[zone] = [r[0], countries[r[3]]!, r[4], r[5]];
|
||||
}
|
||||
let fromTzdb = 0;
|
||||
for (const z of tz.values()) {
|
||||
if (z.zone in guesses) continue;
|
||||
guesses[z.zone] = [z.zone.split('/').pop()!.replace(/_/g, ' '), '', round2(z.lat), round2(z.lon)];
|
||||
fromTzdb++;
|
||||
}
|
||||
// Browsers report a zone by the name Intl resolves it to, which is CLDR's and not
|
||||
// always the time zone database's (Asia/Calcutta, Europe/Kiev). Key each guess by
|
||||
// that name too, resolved by the same Intl.
|
||||
let aliases = 0;
|
||||
for (const zone of Object.keys(guesses)) {
|
||||
const resolved = new Intl.DateTimeFormat('en', { timeZone: zone }).resolvedOptions().timeZone;
|
||||
if (resolved !== zone && !(resolved in guesses)) {
|
||||
guesses[resolved] = guesses[zone]!;
|
||||
aliases++;
|
||||
}
|
||||
}
|
||||
const unguessable = Intl.supportedValuesOf('timeZone').filter((z) => !(z in guesses));
|
||||
|
||||
const tzdb = readFileSync(join(folder, 'version'), 'utf8').trim();
|
||||
const source = `Natural Earth 10m populated places (public domain) and the IANA time zone database ${tzdb} (public domain). Built by scripts/build-places.ts.`;
|
||||
const dir = fileURLToPath(new URL('../packages/content/src/places/', import.meta.url));
|
||||
writeFileSync(join(dir, 'places.json'), JSON.stringify({
|
||||
source,
|
||||
fields: ['name', 'other names', 'region', 'country', 'lat', 'lon', 'zone', 'population in thousands'],
|
||||
countries,
|
||||
zones,
|
||||
places: rows
|
||||
}) + '\n');
|
||||
writeFileSync(join(dir, 'zone-guesses.json'), JSON.stringify({ source, fields: ['name', 'country', 'lat', 'lon'], guesses }, null, 0) + '\n');
|
||||
console.log(`build-places: ${rows.length} towns (${rows.length - corrected.length} kept Natural Earth's zone, ${corrected.length} corrected), ${countries.length} countries, ${zones.length} zones, ${Object.keys(guesses).length} zone guesses (${fromTzdb} from tzdb, ${aliases} under Intl's name); dropped ${dropped.length}`);
|
||||
console.log(` zones Intl knows with no guess: ${unguessable.join(', ') || 'none'}`);
|
||||
for (const d of dropped) console.log(` dropped: ${d}`);
|
||||
for (const c of corrected) console.log(` corrected: ${c}`);
|
||||
Reference in New Issue
Block a user