Merge main through #1637 into the renderer seam

Ports the cockpit bridge view, the orbital view riding a satellite with
ground-site focus, satellite classes and draw-mark row actions onto the
renderer contract. The orbital view's imagery look-ahead pre-load is
dropped (no contract member); tiles load as they come on screen.
This commit is contained in:
Sameh Khamis committed 2026-11-10 01:35:00 -08:00
commit e48ed3eb9e
169 files changed
+22415 -681

No files matched your search

+16
View File
@@ -1116,6 +1116,22 @@ test('vessel interaction wire: trail pick does not deselect', () => {
}
});
test('vessel interaction wire: a click on open water keeps the ship the bridge rides', () => {
const harness = installWireHarness({ id: 'gev-trailing-contact' });
try {
aisLiveVesselsLayer.setCockpitSubject(harness.record.mmsi);
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi);
assert.equal(harness.trail.clearCalls, 0);
// Released, the same click deselects as it always has.
aisLiveVesselsLayer.setCockpitSubject(null);
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(aisLiveVesselsLayer.getSelectedInfo(), null);
} finally {
harness.cleanup();
}
});
test('vessel interaction wire: only the gev-trail: namespace receives the trail no-op', () => {
const harness = installWireHarness({ id: 'gev-trailing-contact' });
try {
+14 -1
View File
@@ -148,10 +148,23 @@ export const DATA_CREDITS = [
{
key: 'celestrak',
html:
'Satellites (TLEs): CelesTrak ' +
'Satellites (TLEs and SATCAT): CelesTrak ' +
'(<a href="https://celestrak.org" target="_blank" rel="noopener">celestrak.org</a>), ' +
'Dr. T.S. Kelso',
},
{
key: 'ucs-satellite-database',
html:
'Satellite operators and purposes: ' +
'<a href="https://www.ucsusa.org/satellite_database" target="_blank" rel="noopener">UCS Satellite Database</a> ' +
'(UCS-Satellite-Database 5-1-2023), Union of Concerned Scientists',
},
{
key: 'imaging-sensors',
html:
'Imaging sensor swaths: operator and agency specifications, ' +
'cited per platform',
},
{
key: 'launch-library-2',
html:
+23
View File
@@ -39,6 +39,29 @@ test('adsbdb is credited and carries its published route-data restriction', () =
assert.match(credit.html, /href="https:\/\/www\.adsbdb\.com"/);
});
test('the UCS Satellite Database is acknowledged with its version and webpage', () => {
// UCS database manual, section 3: references name the version (the Excel
// file's name) and link www.ucsusa.org/satellite_database.
const credit = DATA_CREDITS.find(
(entry) => entry.key === 'ucs-satellite-database',
);
assert.ok(credit, 'the satellite classes and operators come from UCS');
assert.match(credit.html, /UCS-Satellite-Database 5-1-2023/);
assert.match(
credit.html,
/href="https:\/\/www\.ucsusa\.org\/satellite_database"/,
);
});
test('the imaging sensor swaths credit operator and agency specifications', () => {
// Each sensor-pack entry cites its operator's or agency's own pages;
// no aggregator database is credited.
const credit = DATA_CREDITS.find((entry) => entry.key === 'imaging-sensors');
assert.ok(credit, 'the orbital zoom caps come from the sensor pack');
assert.match(credit.html, /operator and agency specifications/);
assert.doesNotMatch(credit.html, /OSCAR|wmo\.int/);
});
test('OpenStreetMap has one generic data credit with separate tile and names distributors', () => {
const osm = DATA_CREDITS.filter((entry) =>
entry.html.includes('openstreetmap.org/copyright'),
+25
View File
@@ -0,0 +1,25 @@
/**
* @file The bundled imaging-sensor pack: swath and resolution for the main
* Earth-observation platforms, matched to satellites by NORAD number or name.
*
* Data: `local_data/imaging_sensors/imaging_sensors.json`; sources, licences
* and curation in that folder's README. Loaded once, on demand, by the
* satellites layer; a failed load is retried after a cooldown rather than
* remembered for the session.
*
* @module data/imagingSensors
*/
import { indexImagingSensors } from '../layers/satellites/sensors.js';
import { loadBundledJson } from './bundledJson.js';
import { createRetryableLoader } from './retryableLoad.js';
const PACK_URL = new URL(
'./local_data/imaging_sensors/imaging_sensors.json',
import.meta.url,
);
/** The pack, loaded and indexed once. */
export const loadImagingSensors = createRetryableLoader(async () =>
indexImagingSensors(await loadBundledJson(PACK_URL)),
);
+11
View File
@@ -2,6 +2,7 @@
// Local, not i18n/marker.js: the token-ledger tests run this file in isolation.
const msg = (text) => text;
import { normalizeIdSwitches, patchRequestedIdSwitches } from './idSwitches.js';
import { normalizeSatelliteClassMask } from './satelliteClassMask.js';
import reservationRows from './layerStateTokenReservations.json' with { type: 'json' };
const VALID_DISPOSITIONS = new Set([
@@ -416,6 +417,16 @@ const OPTION_GROUPS = Object.freeze({
dense: 'd',
}),
integerOption('selectedSatTrackingId', 't', null),
// Every class but Starlink shows by default (satellites/classes.js).
Object.freeze({
key: 'classes',
token: 'k',
defaultValue: 'sitpd',
normalize: normalizeSatelliteClassMask,
encode: (value) => value,
decode: (value) =>
typeof value === 'string' ? normalizeSatelliteClassMask(value) : null,
}),
]),
cctv: Object.freeze([
enumOption('coverageMode', 'c', 'on', ['off', 'on', 'viewshed'], {
+35
View File
@@ -970,6 +970,41 @@ test('a direct Context selection promotes its owned tracker layer before persist
coordinator.destroy();
});
test('a satellite class choice is saved, shared and restored', async () => {
const storage = memoryStorage();
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
storage,
});
await coordinator.start();
await manager.setEnabled('satellites', true, { origin: 'user' });
assert.equal(
coordinator.getDurableState().options.satellites.classes,
'sitpd',
'every class but Starlink by default',
);
manager.setLayerParams(
'satellites',
{ classes: { debris: false } },
{ origin: 'user' },
);
const durable = coordinator.getDurableState();
assert.equal(durable.options.satellites.classes, 'sitp');
assert.equal(
new URLSearchParams(encode(durable)).get('lo')?.includes('s.k.sitp'),
true,
);
coordinator.destroy();
// A reload hands the layer its letters back (the layer decodes them:
// src/data/satelliteClass.test.mjs).
const reloaded = productionManager();
const next = new LayerStateCoordinator(reloaded, shareSink(), { storage });
await next.start();
assert.equal(reloaded.getLayerParams('satellites')?.classes, 'sitp');
next.destroy();
});
test('explicit Flight to Satellite replacement keeps the new Satellite ID durable', async () => {
const manager = productionManager();
const coordinator = new LayerStateCoordinator(manager, shareSink(), {
+7 -6
View File
@@ -102,12 +102,13 @@ const preWildlifeRows = reservationRows.filter(
);
function writeCodecFixture(cwd, rows, entries) {
const providerCodec = path.join(cwd, 'src/data/idSwitches.js');
mkdirSync(path.dirname(providerCodec), { recursive: true });
writeFileSync(
providerCodec,
readFileSync(new URL('./idSwitches.js', import.meta.url)),
);
mkdirSync(path.join(cwd, 'src/data'), { recursive: true });
// The codec's own imports, beside it.
for (const name of ['idSwitches.js', 'satelliteClassMask.js'])
writeFileSync(
path.join(cwd, 'src/data', name),
readFileSync(new URL(`./${name}`, import.meta.url)),
);
let source = readFileSync(CODEC_SOURCE_PATH, 'utf8');
if (!rows.some(([id]) => id === 'wildlife-sightings'))
source = source.replace(
@@ -0,0 +1,63 @@
# Imaging sensor pack
Swath widths and ground resolutions for 46 Earth-observation platforms and
constellations, matched to satellites by NORAD catalog number or by their
CelesTrak name. The orbital view draws a satellite's sensor swath to scale and
lets it zoom past 8x only as far as that swath (`src/layers/satellites/sensors.js`,
`src/data/imagingSensors.js`, `orbitalMaxZoom` in `src/cockpitOrbital.js`).
| File | Content | Entries |
|------|---------|---------|
| `imaging_sensors.json` | Platform, match rule, operator, instruments, altitude, imaging modes (swath km, best ground resolution m), narrowest standard swath, sources, unverified fields | 46 |
**Compiled:** 2026-11-04, by hand from the pages cited per entry (`sources`).
Each match pattern was checked against CelesTrak's active list that day.
Altitude is the nominal value from a cited source; where none was found it is
the median altitude of the matching satellites from CelesTrak GP data, noted in
`unverified`. The app zooms on the live altitude, not this one.
**Narrowest standard swath** is the narrowest continuous standard imaging swath
or scene width (cross-track); for a geostationary imager, the narrower side of
its smallest standard scan area. Some listed modes are left out of it:
- Sampling modes: SAR wave vignettes, and Himawari's Landmark Area scans
(1000 × 500 km), so Himawari's narrowest is the 1000 km Target Area.
- Generations the operator has retired: PlanetScope's Dove Classic and Dove-R
(about 25 km scenes, imagery until April 2022 per Planet) stay in `modes`,
while its narrowest is the SuperDove's 32.5 km. The `^FLOCK ` name rule
would also match those older Doves.
**Unverified values.** A value not confirmed on an opened page is named in the
entry's `unverified` list. `swathConfirmed` is false when the narrowest swath is
missing or unverified; such a platform keeps the base 1–8x zoom steps:
- Landsat 9 (swath inferred from Landsat 8), ResourceSat-2 (LISS-3 swath),
SuperView Neo-1 (12 km from search snippets only), BlackSky and Meteosat
MTG FCI (no swath found).
## Sources and licences
The values are individual specification facts, each cited from the
operator's or agency's official pages listed per entry in `sources`. No text or
images are copied. The main sources:
- **Operator and agency pages and spec sheets** (NASA, USGS, NOAA/NESDIS,
ESA SentiWiki and Earth Online, EUMETSAT, JAXA, ISRO/NRSC, INPE, CSA, DLR,
JMA, ASI, KARI, China's Ministry of Natural Resources (LASAC), Planet,
Vantor (formerly Maxar) datasheet pages, L3Harris, China Siwei, BlackSky,
Airbus and KOMPSAT-5 via the Disasters Charter, ICEYE, Capella, Umbra,
Satellogic, Chang Guang).
- **Academic papers and proceedings** (Sensors papers on Gaofen-3, KARI's
ACRS 2012 paper on KOMPSAT-3, CAST's IAC-16 abstract on Gaofen-2).
- **eoPortal** (ESA's mission directory, an institutional source): a swath
read there counts as confirmed. It is cited beside the operator's and
agency's pages, and alone for values they do not give (the wider modes of
Gaofen-3 and COSMO-SkyMed Second Generation, and a few other entries).
Gaofen-1 takes eoPortal's 69 km PMS and 830 km WFV swaths by maintainer
choice; a 2019 Chinese lecture and a Sensors paper give 60 and 800 km.
- **CEOS MIM Database** (https://database.eohandbook.com): CC BY 4.0 since
7 September 2026, with the credit "CEOS MIM Database,
https://database.eohandbook.com". No entry relies on it yet; credit it if
values are taken from it later.
Listed in DATA_SOURCES.md and in the app's Data attribution popover.
@@ -0,0 +1 @@
{"version":1,"generated":"2026-11-04","entries":[{"id":"landsat-8-9","label":"Landsat 8 / Landsat 9","match":{"norad":[39084,49260],"nameRegex":"^LANDSAT [89]$"},"operator":"NASA / USGS","sensor":"OLI / OLI-2 / TIRS / TIRS-2","type":"multispectral / thermal","altitudeKm":705,"modes":[{"name":"OLI / OLI-2 · Standard scene","swathKm":185,"gsdM":15},{"name":"TIRS / TIRS-2 · Standard scene","swathKm":185,"gsdM":100}],"narrowestSwathKm":185,"swathConfirmed":false,"sources":["https://www.usgs.gov/landsat-missions/landsat-8","https://www.usgs.gov/landsat-missions/landsat-9"],"unverified":["Landsat 9 swath (inferred from Landsat 8)"]},{"id":"sentinel-2","label":"Sentinel-2A/B/C","match":{"norad":[40697,42063,60989],"nameRegex":"^SENTINEL-2[A-D]$"},"operator":"ESA / EU Copernicus","sensor":"MSI","type":"multispectral","altitudeKm":786,"modes":[{"name":"MSI · Nominal","swathKm":290,"gsdM":10}],"narrowestSwathKm":290,"swathConfirmed":true,"sources":["https://sentiwiki.copernicus.eu/web/s2-mission"],"unverified":[]},{"id":"sentinel-1","label":"Sentinel-1A/C/D","match":{"norad":[39634,62261,66315],"nameRegex":"^SENTINEL-1[A-D]$"},"operator":"ESA / EU Copernicus","sensor":"C-SAR","type":"SAR","altitudeKm":693,"modes":[{"name":"C-SAR · Stripmap (SM)","swathKm":80,"gsdM":5},{"name":"C-SAR · Interferometric Wide (IW)","swathKm":250,"gsdM":5},{"name":"C-SAR · Extra Wide (EW)","swathKm":400,"gsdM":20},{"name":"C-SAR · Wave (WV)","swathKm":null,"gsdM":5}],"narrowestSwathKm":80,"swathConfirmed":true,"sources":["https://sentiwiki.copernicus.eu/web/s1-mission"],"unverified":[]},{"id":"sentinel-3","label":"Sentinel-3A/B/C","match":{"norad":[41335,43437,100690],"nameRegex":"^SENTINEL-3[A-D]$"},"operator":"ESA / EUMETSAT (Copernicus)","sensor":"OLCI / SLSTR","type":"multispectral / thermal","altitudeKm":814.5,"modes":[{"name":"OLCI · Full resolution","swathKm":1270,"gsdM":300},{"name":"SLSTR · Nadir view","swathKm":1400,"gsdM":500},{"name":"SLSTR · Oblique view","swathKm":740,"gsdM":500}],"narrowestSwathKm":740,"swathConfirmed":true,"sources":["https://sentiwiki.copernicus.eu/web/s3-mission"],"unverified":[]},{"id":"terra-aqua-modis","label":"Terra / Aqua","match":{"norad":[25994,27424],"nameRegex":"^(TERRA|AQUA)$"},"operator":"NASA","sensor":"MODIS","type":"multispectral","altitudeKm":705,"modes":[{"name":"MODIS · Cross-track scan","swathKm":2330,"gsdM":250}],"narrowestSwathKm":2330,"swathConfirmed":true,"sources":["https://ladsweb.modaps.eosdis.nasa.gov/missions-and-measurements/modis/"],"unverified":["Aqua altitude (assumed same as Terra)"]},{"id":"viirs","label":"Suomi NPP / NOAA-20 / NOAA-21","match":{"norad":[37849,43013,54234],"nameRegex":"^(SUOMI NPP|NOAA 2[01] \\(JPSS-[12]\\))$"},"operator":"NASA / NOAA (JPSS)","sensor":"VIIRS","type":"multispectral","altitudeKm":830,"modes":[{"name":"VIIRS · Cross-track scan","swathKm":3000,"gsdM":375}],"narrowestSwathKm":3000,"swathConfirmed":true,"sources":["https://ladsweb.modaps.eosdis.nasa.gov/missions-and-measurements/viirs/","https://www.earthdata.nasa.gov/data/catalog/laads-vj102img-2.1"],"unverified":[]},{"id":"goes-abi","label":"GOES-16/17/18/19 (GOES-R series)","match":{"norad":[41866,43226,51850,60133],"nameRegex":"^GOES 1[6-9]$"},"operator":"NOAA / NASA","sensor":"ABI","type":"multispectral","altitudeKm":35786,"modes":[{"name":"ABI · Full disk","swathKm":null,"gsdM":500},{"name":"ABI · CONUS","swathKm":3000,"gsdM":500},{"name":"ABI · Mesoscale sector","swathKm":1000,"gsdM":500}],"narrowestSwathKm":1000,"swathConfirmed":true,"sources":["https://www.nesdis.noaa.gov/advanced-baseline-imager-scan-mode-information"],"unverified":["altitudeKm (standard GEO value)"]},{"id":"himawari-ahi","label":"Himawari-8 / Himawari-9","match":{"norad":[40267,41836],"nameRegex":"^HIMAWARI-[89]$"},"operator":"JMA","sensor":"AHI","type":"multispectral","altitudeKm":35786,"modes":[{"name":"AHI · Full Disk","swathKm":11000,"gsdM":500},{"name":"AHI · Japan Area","swathKm":2400,"gsdM":500},{"name":"AHI · Target Area","swathKm":1000,"gsdM":500},{"name":"AHI · Landmark Area","swathKm":500,"gsdM":500}],"narrowestSwathKm":1000,"swathConfirmed":true,"sources":["https://www.data.jma.go.jp/mscweb/en/himawari89/space_segment/spsg_ahi.html"],"unverified":["altitudeKm (standard GEO value)"]},{"id":"mtg-fci","label":"Meteosat Third Generation imager (Meteosat-12 / MTG-I2)","match":{"norad":[54743,100530],"nameRegex":"^(METEOSAT-12|MTG-I\\d)"},"operator":"EUMETSAT","sensor":"FCI","type":"multispectral","altitudeKm":35786,"modes":[{"name":"FCI · Full disc","swathKm":null,"gsdM":1000},{"name":"FCI · Rapid scan (Europe, 1/4 disc)","swathKm":null,"gsdM":500}],"narrowestSwathKm":null,"swathConfirmed":false,"sources":["https://www.esa.int/Applications/Observing_the_Earth/Meteorological_missions/Meteosat/About_Meteosat_Third_Generation","https://www-cdn.eumetsat.int/files/2020-04/pdf_mtg_goesr_ws_1.pdf"],"unverified":["narrowestSwathKm","altitudeKm (standard GEO value)"]},{"id":"gaofen-1","label":"GaoLine truncated
@@ -10,6 +10,7 @@ range geometry with no network dependency.
| `marine.json` | `ne_10m_geography_marine_polys` (seas, gulfs, straits, bays, …) | 292 named |
| `countries.json` | `ne_10m_admin_0_countries` (countries) | 256 |
| `states_provinces.json` | `ne_10m_admin_1_states_provinces` (states, provinces and other first-level units) | 4,587 named |
| `populated_places.json` | `ne_10m_populated_places_simple` (cities and towns, as points) | 7,342 |
**Source:** Natural Earth 10m physical vectors, via the canonical
[nvkelso/natural-earth-vector](https://github.com/nvkelso/natural-earth-vector)
@@ -103,3 +104,23 @@ Includes England, Scotland, Wales and Northern Ireland from
`ne_10m_admin_0_map_units.geojson` at the same commit (SHA-256
`57da82be755f4afccd8f3b14251bb2752f5df1395f47d2d86f817470c4a48862`).
Result: 945,843 bytes; 260 features, 2,088 parts, 122,788 vertices.
## Populated places (`populated_places.json`)
The orbital view's "near <city>" (`src/data/placeBelow.js`): from 8x it
names the most prominent place within half the view's width.
**Source:** `geojson/ne_10m_populated_places_simple.geojson` at the pinned
commit `ca96624a56bd078437bca8184e78163e5039ad19` (SHA-256
`fd3fa867a320cbd5c5b6bb5bc550afeec2939fb2cef688e508007282a55ac42f`, the file
the admin-1 build already reads), fetched 2026-11-04. Public domain, as above.
**Regenerate:** `node scripts/build-admin-packs.mjs --only places`.
**Schema:** `meta` (source, URL, hash, license, curation) and `places[]`, each
`[name, latitude, longitude, scalerank, rank_max]`: `scalerank` 0 (most
prominent) to 10, `rank_max` the population class (0 to 14, higher is
larger). Sorted by `scalerank`, then `rank_max` descending, then name.
**Curation:** every place kept; all other attributes dropped; coordinates
rounded to 3 decimals (~110 m). Result: 229,461 bytes (98,444 with gzip -9).
@@ -0,0 +1 @@
{"meta":{"title":"Natural Earth populated places","source":"ne_10m_populated_places_simple","url":"https://raw.githubusercontent.com/nvkelso/natural-earth-vector/ca96624a56bd078437bca8184e78163e5039ad19/geojson/ne_10m_populated_places_simple.geojson","sha256":"fd3fa867a320cbd5c5b6bb5bc550afeec2939fb2cef688e508007282a55ac42f","commit":"ca96624a56bd078437bca8184e78163e5039ad19","license":"Public domain (https://www.naturalearthdata.com/about/terms-of-use/)","schema":"places[]: [name, latitude, longitude, scalerank (0 most prominent .. 10), rank_max (population class, 0..14; higher is larger)]","decimals":3,"curation":{"decimals":3},"script":"scripts/build-admin-packs.mjs"},"places":[["Beijing",39.931,116.386,0,14],["Cairo",30.052,31.248,0,14],["Istanbul",41.107,29.008,0,14],["Kolkata",22.497,88.323,0,14],["Los Angeles",33.992,-118.182,0,14],["Mexico City",19.444,-99.133,0,14],["Moscow",55.754,37.614,0,14],["Mumbai",19.019,72.855,0,14],["New York",40.752,-73.982,0,14],["Rio de Janeiro",-22.923,-43.227,0,14],["São Paulo",-23.557,-46.627,0,14],["Shanghai",31.218,121.435,0,14],["Tokyo",35.687,139.749,0,14],["Bogota",4.598,-74.085,0,13],["Hong Kong",22.307,114.183,0,13],["Jakarta",-6.172,106.827,0,13],["Lagos",6.445,3.39,0,13],["London",51.502,-0.119,0,13],["Paris",48.869,2.331,0,13],["Santiago",-33.448,-70.669,0,13],["Singapore",1.295,103.854,0,13],["Cape Town",-33.918,18.433,0,12],["Nairobi",-1.281,36.815,0,12],["Riyadh",24.643,46.771,0,12],["Rome",41.898,12.481,0,12],["Sydney",-33.918,151.183,0,12],["Washington, D.C.",38.901,-77.011,0,12],["Buenos Aires",-34.601,-58.399,1,14],["Manila",14.606,120.98,1,14],["Ōsaka",34.752,135.458,1,14],["Baghdad",33.341,44.392,1,13],["Bangkok",13.752,100.515,1,13],["Bengaluru",12.972,77.558,1,13],["Chicago",41.832,-87.752,1,13],["Kinshasa",-4.328,15.313,1,13],["Lima",-12.046,-77.052,1,13],["Madrid",40.402,-3.685,1,13],["Miami",25.79,-80.226,1,13],["Seoul",37.568,126.998,1,13],["Taipei",25.036,121.568,1,13],["Tehran",35.674,51.422,1,13],["Toronto",43.702,-79.422,1,13],["Addis Ababa",9.035,38.698,1,12],["Amsterdam",52.352,4.915,1,12],["Athens",37.985,23.731,1,12],["Atlanta",33.832,-84.402,1,12],["Auckland",-36.848,174.763,1,12],["Berlin",52.524,13.4,1,12],["Caracas",10.503,-66.919,1,12],["Casablanca",33.602,-7.618,1,12],["Chengdu",30.672,104.068,1,12],["Dakar",14.718,-17.475,1,12],["Denver",39.741,-104.986,1,12],["Dubai",25.232,55.278,1,12],["Geneva",46.21,6.14,1,12],["Houston",29.822,-95.342,1,12],["Johannesburg",-26.168,28.028,1,12],["Kabul",34.519,69.181,1,12],["Kyiv",50.435,30.515,1,12],["Melbourne",-37.818,144.973,1,12],["Monterrey",25.672,-100.332,1,12],["San Francisco",37.769,-122.417,1,12],["Stockholm",59.353,18.095,1,12],["Tashkent",41.314,69.293,1,12],["Ürümqi",43.807,87.573,1,12],["Vancouver",49.275,-123.124,1,12],["Vienna",48.202,16.365,1,12],["New Delhi",28.6,77.2,1,10],["Delhi",28.672,77.228,2,14],["Dhaka",23.725,90.407,2,14],["Karachi",24.872,66.988,2,14],["Ahmedabad",23.032,72.578,2,13],["Chennai",13.092,80.278,2,13],["Chongqing",29.567,106.593,2,13],["Guangzhou",23.147,113.323,2,13],["Ho Chi Minh City",10.782,106.693,2,13],["Hyderabad",17.402,78.478,2,13],["Lahore",31.562,74.348,2,13],["Luanda",-8.836,13.232,2,13],["Philadelphia",40.002,-75.172,2,13],["Shenzhen",22.554,114.12,2,13],["Tianjin",39.132,117.198,2,13],["Wuhan",30.582,114.268,2,13],["Abidjan",5.322,-4.042,2,12],["Accra",5.552,-0.219,2,12],["Aleppo",36.232,37.168,2,12],["Alexandria",31.202,29.948,2,12],["Algiers",36.765,3.049,2,12],["Ankara",39.929,32.862,2,12],["Bandung",-6.948,107.568,2,12],["Baotou",40.654,109.82,2,12],["Barcelona",41.385,2.181,2,12],["Belém",-1.448,-48.482,2,12],["Boston",42.332,-71.072,2,12],["Brasília",-15.781,-47.918,2,12],["Brussels",50.835,4.331,2,12],["Bucharest",44.435,26.098,2,12],["Budapest",47.502,19.081,2,12],["Cali",3.402,-76.502,2,12],["Changchun",43.867,125.338,2,12],["Changsha",28.202,112.968,2,12],["Chattogram",22.332,91.798,2,12],["Curitiba",-25.418,-49.322,2,12],["Dallas",32.822,-96.842,2,12],["Damascus",33.502,36.298,2,12],["Dar es Salaam",-6.798,39.266,2,12],["Detroit",42.332,-83.082,2,12],["Dongguan",23.051,113.743,2,12],["Dublin",53.335,-6.251,2,12],["Durban",-29.863,30.978,2,12],["Edmonton",53.552,-113.502,2,12],["Fortaleza",-3.748,-38.582,2,12],["Frankfurt",50.1,8.675,2,12],["Fuzhou",26.082,119.298,2,12],["Goiânia",-16.718,-49.302,2,12],["Guadalajara",20.672,-103.332,2,12],["Guayaquil",-2.218,-79.922,2,12],["Guiyang",26.582,106.718,2,12],["Hamburg",53.552,9.998,2,12],["Hangzhou",30.252,120.168,2,12],["Hanoi",21.035,105.848,2,12],["Harbin",45.752,126.648,2,12],["Havana",23.134,-82.366,2,12],["Helsinki",60.178,24.932,2,12],["Hiroshima",34.39,132.441,2,12],["Jaipur",26.923,75.808,2,12],["Jeddah",21.519,39.217,2,12],["Jinan",36.677,116.993,2,12],["Kano",12.002,8.518,2,12],["Kanpur",26.462,80.318,2,12],["Khartoum",15.59,32.532,2,12],["København",55.681,12.562,2,12],["Kuala Lumpur",3.169,101.698,2,12],["Kunming",25.072,102.678,2,12],["Kuwait City",29.372,4Line truncated
+18
View File
@@ -0,0 +1,18 @@
# Owner flags
`owner_flags.png` is one sheet of every owner country a satellite can be
marked with (`OWNER_COUNTRY_CODES` in `src/layers/satellites/classes.js`),
drawn at 40 × 30 px (twice the orbital readout's 20 × 15) in sorted code
order, 16 to a row, each followed by 2 transparent pixels so a scaled flag
never smooths into its neighbour. `src/ui/ownerFlag.js` loads it once at startup and draws
each flag from its cell; the layout is `src/ui/ownerFlagSheet.js`.
**Source:** the 4:3 SVGs of [flag-icons](https://github.com/lipis/flag-icons)
7.5.0 (a devDependency, used only to build the sheet).
**License:** flag-icons is MIT licensed (© Panayiotis Lipiridis). Country
flags themselves are not copyrightable designs in most jurisdictions.
**Regenerate:** `node scripts/build-owner-flags.mjs` (after adding an owner
country, or updating flag-icons). With the same flag-icons and sharp versions
a rerun reproduces both files byte for byte.
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

@@ -0,0 +1,50 @@
# UCS Satellite Database pack
Offline operator, owner-country and purpose records for active satellites,
keyed by NORAD catalog number. The satellites layer joins them to CelesTrak's
positions to file each satellite under a class (stations, imaging, telecom,
probes) and to name its operator and owner country
(`src/data/ucsSatellites.js`, `src/layers/satellites/classes.js`).
| File | Source dataset | Records |
|------|----------------|---------|
| `ucs_satellites.json` | UCS Satellite Database, release **UCS-Satellite-Database 5-1-2023** (data current through 2023-05-01) | 3,564 |
**Source:** Union of Concerned Scientists, https://www.ucsusa.org/satellite_database.
The same release is mirrored on Hugging Face as
`juliensimon/ucs-satellite-database` (identical rows). UCS has paused updates
since this release, so satellites launched after May 2023 are not in it; the
layer classifies those from CelesTrak SATCAT, CelesTrak groups and name
patterns instead.
**License:** free, unrestricted use. Section 3 of the UCS database manual:
"The Database is free and its use is unrestricted. We request that its use be
acknowledged and referenced in written materials. References should include
the version of the Database that was used, which is indicated by the name of
the Excel file, and a link to or URL for the webpage
www.ucsusa.org/satellite_database."
**Acknowledgement:** "Satellite operators and purposes: UCS Satellite Database
(UCS-Satellite-Database 5-1-2023), https://www.ucsusa.org/satellite_database".
It is also listed in the app's Data attribution popover and in
DATA_SOURCES.md.
**Build:** `python scripts/build-ucs-satellites.py "<path>/UCS-Satellite-Database 5-1-2023.xlsx"`
(openpyxl). The file's `meta` header records the curation.
**Curation:**
- Kept columns: Operator/Owner, Country of Operator/Owner and Purpose, the
ones the layer reads. Everything else (detailed purpose, users, orbits,
masses, contractors, launch data, sources) is left out.
- Repeated text is stored once in `strings`; each record is
`[noradId, operator, operatorCountry, purpose]` with string-table indexes,
`0` meaning empty.
- The 3,996 Starlink rows are dropped: every Starlink object is classed and
credited to SpaceX by name, so they would only add size.
- Rows without a readable, positive NORAD number are dropped and counted apart
from duplicate NORAD numbers (the first row of a duplicate is kept); both
counts are 0 in this release.
- Owner countries stay as UCS writes them ("USA", "USA/Japan", "ESA",
"Multinational"); `src/layers/satellites/classes.js` normalises them, together with
CelesTrak SATCAT owner codes, in one table.
@@ -0,0 +1 @@
{"meta":{"source":"Union of Concerned Scientists Satellite Database","version":"UCS-Satellite-Database 5-1-2023","url":"https://www.ucsusa.org/satellite_database","dataCurrentTo":"2023-05-01","license":"Free, unrestricted use; acknowledgement requested (UCS database manual, section 3)","curation":{"sourceRows":7560,"starlinkRowsDropped":3996,"invalidNoradDropped":0,"duplicateNoradDropped":0,"columns":{"operator":"Operator/Owner","operatorCountry":"Country of Operator/Owner","purpose":"Purpose"}},"recordCount":3564},"fields":["noradId","operator","operatorCountry","purpose"],"strings":{"operator":["","Hera Systems","AAC Clyde Space","Aalto University","University of Aalborg","Asia Broadcast Satellite Ltd.","Asher Space Research Institute at Technion/Israeli Aircraft Industries","Austrian Space Forum (OEWF)/Spire","National Reconnaissance Office (NRO)","US Air Force","Department of Homeland Security","European Space Agency (ESA)","Aerospace Corporation","EUTELSAT S.A.","Aurora Insight","Center for Atmospheric Sciences, Hampton University/NASA","Norwegian Coastal Admnistration","AISTech","Al Yah Satellite Communications Co. (YAHSAT)","Al-Farabi Kazakh National University","Algerian Space Agency (ASAL)","Astro Live Experiences","University of Brasilia","US Air Force Institute of Technology","Algerian Space Agency (ASAL)/UK Space Agency","Hispamar (subsidiary of Hispasat - Spain)","National Institute for Space Research (INPE)","SES S.A.","Moscow State University","Space-Communication Ltd.","AMSAT-NA","Agency for Defense Development","ANDESITE - Boston University","Centre National d'Etudes Spatiales (CNES)","AngoSat","Telesat Canada Ltd. (BCE, Inc.)","Aprize Satellite, Argentina","APT Satellite Holdings Ltd.","Arab Satellite Communications Org. (ASCO)","University of South Florida, Institute of Applied Engineering (IAE).","Norwegian Defence Research Establishment","Aoyama Gakuin University in Tokyo","Naval Physical and Oceanographic Laboratory","Planetary Resources","ArSat","Aerospacelab","Istanbul Technical University","Asia Satellite Telecommunications Co. Ltd.","1Worldspace","Japan Space Systems","Chiba Institute of Technology","Astranis","Astrocast","Telemetry Tracking and Command Network (ISTRAC) Centre","DirecTV, Inc.","PointView Tech","Centre National d'Etudes Spatiales (CNES)/Agenzia Spaziale Italiana (ASI)","Microspace Rapid Pvt Ltd.","Azercosmos","Bangladesh Telecommunication Regulatory Commission (BTRC)","Tianyi Research Institute","Ministry of Defense","Space Development Agency","Central European Institute of Technology","Technical University Berlin","Chinese Ministry of National Defense","21st Century Aerospace Technology (21AT)","Beijing Landview Mapping Information Technology Co. Ltd (BLMIT)","Changsha Tianyi space science and Technology Research Institute Co., Ltd. (Spacety)","Belintersat","Institute of Space Sensor Technology and Planetary Exploration","Norwegian Defence Research Establishment (FFI)/","German Aerospace Center (DLR)","Salish Kootenai College","National Academy of Sciences","BlackSky Global","NanoAvionics","AST SpaceMobile","Embratel Star One","SpaceQuest, Ltd.","Bank Rakyat Indonesia (BRI)","University of Toronto, Institute for Aerospace Studies","BRITE Consortium","UnseenLabs","AstroForge","Broadcasting Satellite System Corp.","Broadcasting Satellite System Corp./Sky Perfect JSAT Corporation","Defence Science and Technology Group/University of New South Wales","China Academy of Space Technology (CAST)","Satellogic S.A.","Bulsatcom","Capital Technology University","Centre National d'Etudes Spatiales (CNES)/NASA","University of Louisiana at Lafayette","Capella Space","Indian Space Research Organization (ISRO)","Korea Aerospace Research Institute (KARI)","Canadian Space Agency","China National Space Administration (CNSA)/National Institute for Space Research (Brazil)","Surrey Satellite Technology Ltd.","Earth-i/Surrey Satellite Technology Ltd.","Canon Electronics","Air Force Research Laboratory","Fleet Space Technologies","Beijing Future Navigation Technology Co. Ltd.","NASA Goddard Space Flight Center","Ministry of Armed Forces","Defense Innovation Unit/Cesium Astro","China National Space Administration (CNSA)/National Centre for Space Studies (CNES)","TELNET Holding","National Aeronautics and Space Administration (NASA) Goddard Space Flight Center","Spacety Aerospace Company","Shanghai Engineering Center for Microsatellites","Spacety Co. Ltd.","Nanjing University","Epic Aerospace","University of Florida","Chinese Academy of Sciences","GeoOptics Inc.","GeoOptics, Inc.","Ciel Satellite Group","University of California-Berkeley/Imperial College-London","Laboratory for Atmospheric and Space Physics, University of Colorado, Boulder","Utah State University","Unknown US agency","National Aeronautics and Space Administration (NASA)/Colorado State University","Department of Defense/Missile Defense Agency","FH Aachen","Armed Forces","Plan-S","US Air Force/ US Navy/NASA","Astro Digital","TaLine truncated
+472
View File
@@ -0,0 +1,472 @@
/**
* What a ground point is over, offline: on land the country (Natural Earth
* admin-0) and its first-level division (admin-1: "Sichuan, China"), plus,
* when asked for a radius, the most prominent populated place within it
* ("near Chengdu"); else the smallest named sea, gulf, strait, channel,
* sound or bay, else the ocean (`marine.json` carries the seven oceans).
* Bays narrower than a satellite frame cares about — fjords, lagoons,
* inlets, reefs and rivers — are skipped, so a pass reads "Bay of Bengal",
* not a harbour.
*
* PURE data module: no Cesium, node-testable. Each pack loads lazily on the
* first lookup that needs it (divisions on the first land hit, places on the
* first radius) and is indexed once, and the loading status names them while
* one is on its way (`placePacksStatus`); a country's division rings are decoded
* the first time a point falls inside it. A failed load is retried later
* (see `createRetryableLoader`). No network.
*/
import { loadBundledJson } from './bundledJson.js';
import { createRetryableLoader } from './retryableLoad.js';
import { containsAnchor, decodeRing } from './adminBoundaries.js';
import { greatCircleKm } from '../geoDistance.js';
/** Marine feature classes named as the place below; oceans come last. */
const MARINE_KINDS = new Set([
'sea',
'gulf',
'strait',
'channel',
'sound',
'bay',
]);
const PACKS = {
countries: new URL(
'./local_data/natural_earth/countries.json',
import.meta.url,
),
marine: new URL('./local_data/natural_earth/marine.json', import.meta.url),
divisions: new URL(
'./local_data/natural_earth/states_provinces.json',
import.meta.url,
),
places: new URL(
'./local_data/natural_earth/populated_places.json',
import.meta.url,
),
};
/**
* The packs on their way now, and those that failed in the current load (or
* the last one): a load starts with no failures, so a retry that lands is
* not blamed for a pack that failed before. (A load that does not need the
* failed pack clears it too; the next lookup that needs it tries it again.)
*/
const loadingPacks = new Set();
const failedPacks = new Set();
// One lookup loads its packs one after another (countries and seas, then
// divisions, then places): the status holds them as one load until the
// lookup ends, rather than ending and starting a batch between packs.
let lookupsInFlight = 0;
let lookupLoaded = false;
const loadingListeners = new Set();
function notifyLoading() {
for (const listener of [...loadingListeners]) {
try {
listener();
} catch {
/* A status listener never breaks a lookup. */
}
}
}
/** Whether the status shows a load on its way. */
function loadingNow() {
return loadingPacks.size > 0 || (lookupLoaded && lookupsInFlight > 0);
}
/**
* A pack load that the loading status follows: on its way while it runs,
* and failed, if it fails, until the next load starts.
* @template T
* @param {string} name
* @param {() => Promise<T>} load
* @returns {() => Promise<T>}
*/
export function reportedPlacePackLoad(name, load) {
return async () => {
// A fresh load forgets earlier failures: it ends on what it loads.
if (!loadingNow()) failedPacks.clear();
if (lookupsInFlight > 0) lookupLoaded = true;
loadingPacks.add(name);
notifyLoading();
try {
return await load();
} catch (error) {
failedPacks.add(name);
throw error;
} finally {
loadingPacks.delete(name);
notifyLoading();
}
};
}
/**
* The place packs' state for the loading status. The packs load lazily, on
* the first lookup that needs them, so the status says so meanwhile, and
* says when one would not load.
* @returns {{loading: boolean, failed: boolean}}
*/
export function placePacksStatus() {
return {
loading: loadingNow(),
failed: failedPacks.size > 0,
};
}
/**
* Hear each start and end of a place pack load.
* @param {() => void} listener
* @returns {() => void} Stops listening.
*/
export function onPlacePacksLoadingChange(listener) {
loadingListeners.add(listener);
return () => loadingListeners.delete(listener);
}
/** Test seam: count pack loads (lazy-loading contract). */
export const placePackLoads = { divisions: 0, places: 0 };
/** The zoom from which the view names the populated place it shows. */
export const NEAR_PLACE_MIN_ZOOM = 8;
/**
* How far from the sub-satellite point a populated place may lie and still
* be named: half the view's smaller ground dimension from
* NEAR_PLACE_MIN_ZOOM on, so the place is in the picture whichever way it
* lies; null below it or without a size.
* @param {number} zoom Optical zoom.
* @param {number} widthKm The view's ground width, km.
* @param {number} [heightKm] The view's ground height, km; the width when
* not given.
* @returns {number|null}
*/
export function nearPlaceRadiusKm(zoom, widthKm, heightKm = widthKm) {
if (!(zoom >= NEAR_PLACE_MIN_ZOOM)) return null;
const smallerKm = Math.min(widthKm, heightKm);
return Number.isFinite(smallerKm) && smallerKm > 0 ? smallerKm / 2 : null;
}
/** Shortest wait between two lookups, ms. */
export const PLACE_LOOKUP_MIN_MS = 2000;
/** Ground travel that makes a fresh lookup worth it, km. */
export const PLACE_LOOKUP_MIN_MOVE_KM = 20;
function boxOf(parts) {
let west = Infinity;
let south = Infinity;
let east = -Infinity;
let north = -Infinity;
for (const part of parts)
for (const ring of part)
for (const [lon, lat] of ring) {
if (lon < west) west = lon;
if (lon > east) east = lon;
if (lat < south) south = lat;
if (lat > north) north = lat;
}
return [west, south, east, north];
}
function inBox([west, south, east, north], lat, lon) {
return lat >= south && lat <= north && lon >= west && lon <= east;
}
/** Planar ring area in degrees², shrunk by cos(latitude): enough to rank. */
function ringRank(ring) {
let sum = 0;
let latSum = 0;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
sum += (ring[j][0] - ring[i][0]) * (ring[j][1] + ring[i][1]);
latSum += ring[i][1];
}
const meanLat = ring.length ? latSum / ring.length : 0;
return (Math.abs(sum) / 2) * Math.cos((meanLat * Math.PI) / 180);
}
async function readPlaces() {
const [countries, marine] = await Promise.all([
loadBundledJson(PACKS.countries),
loadBundledJson(PACKS.marine),
]);
const decimals = countries.meta?.decimals ?? 3;
const land = [];
for (const feature of countries.features || []) {
const parts = (feature.polygons || []).map((part) =>
part.map((ring) => decodeRing(ring, decimals)),
);
if (!parts.length) continue;
land.push({
name: feature.name,
// Natural Earth writes -99 for units without an ISO code.
countryCode: /^[A-Z]{2}$/.test(feature.iso2 || '') ? feature.iso2 : null,
parts,
box: boxOf(parts),
});
}
const water = [];
for (const feature of marine.features || []) {
const kind = feature.featurecla;
if (kind !== 'ocean' && !MARINE_KINDS.has(kind)) continue;
// Marine rings are stored outer-only and plain [lon, lat].
const parts = (feature.polygons || []).map((ring) => [ring]);
if (!parts.length) continue;
water.push({
name: feature.name,
kind: kind === 'ocean' ? 'ocean' : 'sea',
parts,
box: boxOf(parts),
rank: parts.reduce((sum, [ring]) => sum + ringRank(ring), 0),
});
}
return { land, water };
}
const loadPlaces = createRetryableLoader(
reportedPlacePackLoad('places', readPlaces),
);
/** Divisions grouped by country code; rings decoded per country on demand. */
async function readDivisions() {
placePackLoads.divisions += 1;
const pack = await loadBundledJson(PACKS.divisions);
const decimals = pack.meta?.decimals ?? 3;
const byCountry = new Map();
for (const feature of pack.features || []) {
if (!feature.name || !/^[A-Z]{2}$/.test(feature.iso2 || '')) continue;
const list = byCountry.get(feature.iso2) || [];
list.push({ feature, decimals: feature.d ?? decimals });
byCountry.set(feature.iso2, list);
}
return { byCountry, decoded: new Map() };
}
const loadDivisions = createRetryableLoader(
reportedPlacePackLoad('divisions', readDivisions),
);
/** The first-level division holding a point inside country `code`, or null. */
async function divisionAt(code, lat, lon) {
if (!code) return null;
const { byCountry, decoded } = await loadDivisions();
let units = decoded.get(code);
if (!units) {
units = (byCountry.get(code) || []).map(({ feature, decimals }) => {
const parts = (feature.polygons || []).map((part) =>
part.map((ring) => decodeRing(ring, decimals)),
);
return { name: feature.name, parts, box: boxOf(parts) };
});
decoded.set(code, units);
}
for (const unit of units)
if (inBox(unit.box, lat, lon) && containsAnchor(unit.parts, lat, lon))
return unit.name;
return null;
}
async function readPopulatedPlaces() {
placePackLoads.places += 1;
const pack = await loadBundledJson(PACKS.places);
return (pack.places || []).filter(
(row) =>
Array.isArray(row) &&
row[0] &&
Number.isFinite(row[1]) &&
Number.isFinite(row[2]),
);
}
const loadPopulatedPlaces = createRetryableLoader(
reportedPlacePackLoad('populated-places', readPopulatedPlaces),
);
/**
* The most prominent populated place within `radiusKm` of a point (lowest
* Natural Earth scalerank, then the larger population class, then the
* nearer), or null.
* @returns {Promise<string|null>}
*/
export async function nearPlace(lat, lon, radiusKm) {
if (!(radiusKm > 0) || !Number.isFinite(lat) || !Number.isFinite(lon))
return null;
const places = await loadPopulatedPlaces();
const latSpan = radiusKm / 111;
const cosLat = Math.cos((lat * Math.PI) / 180);
const lonSpan = cosLat > 0.01 ? latSpan / cosLat : 360;
let best = null;
for (const [name, pLat, pLon, scalerank, rankMax] of places) {
if (Math.abs(pLat - lat) > latSpan) continue;
const dLon = Math.abs(((((pLon - lon + 180) % 360) + 360) % 360) - 180);
if (dLon > lonSpan) continue;
const km = greatCircleKm({ lat, lon }, { lat: pLat, lon: pLon });
if (km > radiusKm) continue;
if (
!best ||
scalerank < best.scalerank ||
(scalerank === best.scalerank &&
(rankMax > best.rankMax || (rankMax === best.rankMax && km < best.km)))
)
best = { name, scalerank, rankMax, km };
}
return best ? best.name : null;
}
/** The division and near-place lookups `placeBelow` adds on land. */
const DETAIL_LOOKUPS = Object.freeze({ division: divisionAt, near: nearPlace });
/** A detail lookup's answer, or null when it (its pack) fails. */
async function orNull(lookup) {
try {
return (await lookup()) ?? null;
} catch {
return null;
}
}
/**
* The place under a ground point.
* @param {number} latitude Degrees.
* @param {number} longitude Degrees, any wrap.
* @param {{nearKm?: number|null, detail?: {division: Function,
* near: Function}}} [options] On land, also name the most prominent
* populated place within `nearKm` (`nearPlaceRadiusKm`). `detail` replaces
* the division and near-place lookups (a test seam).
* @returns {Promise<{kind: 'country'|'sea'|'ocean', name: string,
* countryCode: string|null, division?: string|null,
* near?: string|null}|null>} A country carries its first-level `division`
* and the `near` place (each null when none, or when its pack failed to
* load: the country still stands); a sea or ocean neither. Null when no
* feature holds the point (a coastline gap left by the packs'
* simplification) or it is invalid. Rejects only when the country and
* marine packs fail.
*/
export async function placeBelow(latitude, longitude, options) {
lookupsInFlight += 1;
try {
return await findPlaceBelow(latitude, longitude, options);
} finally {
lookupsInFlight -= 1;
if (lookupsInFlight === 0 && lookupLoaded) {
lookupLoaded = false;
notifyLoading();
}
}
}
async function findPlaceBelow(
latitude,
longitude,
{ nearKm = null, detail = DETAIL_LOOKUPS } = {},
) {
if (
!Number.isFinite(latitude) ||
!Number.isFinite(longitude) ||
Math.abs(latitude) > 90
)
return null;
const lon = ((((longitude + 180) % 360) + 360) % 360) - 180;
const { land, water } = await loadPlaces();
for (const entry of land) {
if (
inBox(entry.box, latitude, lon) &&
containsAnchor(entry.parts, latitude, lon)
)
return {
kind: 'country',
name: entry.name,
countryCode: entry.countryCode,
division: await orNull(() =>
detail.division(entry.countryCode, latitude, lon),
),
near: await orNull(() => detail.near(latitude, lon, nearKm)),
};
}
let best = null;
for (const entry of water) {
if (best && entry.rank >= best.rank) continue;
if (
inBox(entry.box, latitude, lon) &&
containsAnchor(entry.parts, latitude, lon)
)
best = entry;
}
return best ? { kind: best.kind, name: best.name, countryCode: null } : null;
}
/**
* Whether two radii ask for the same detail: both off, or within 20% (a
* zoom step at least halves the view; altitude drift moves it far less).
*/
function sameRadius(a, b) {
if (a === null || b === null) return a === b;
return Math.max(a, b) / Math.min(a, b) < 1.2;
}
/**
* Keep the place below a moving ground point current without a lookup per
* frame: a new lookup once at least `minIntervalMs` has passed AND the point
* has moved `minMoveKm` (a low orbit refreshes about every 2.6 s, a
* geostationary one never after the first). A new `nearKm` radius (a zoom
* step) looks up again at once. One lookup runs at a time; a result that
* arrives after `reset()` is dropped. A failed lookup reports no place (the
* old one would name ground the view has left) and lets the next update
* look up again at once.
* @param {{onPlace: (place: object|null) => void,
* lookup?: (lat: number, lon: number,
* options: {nearKm: number|null}) => Promise<object|null>,
* minIntervalMs?: number, minMoveKm?: number}} options
*/
export function createPlaceTracker({
onPlace,
lookup = placeBelow,
minIntervalMs = PLACE_LOOKUP_MIN_MS,
minMoveKm = PLACE_LOOKUP_MIN_MOVE_KM,
}) {
let generation = 0;
let inFlight = false;
let last = null;
return {
/**
* Offer the current ground point and the radius to name a place in.
* @returns {boolean} True when a lookup started.
*/
update(lat, lon, nowMs, nearKm = null) {
if (inFlight || !Number.isFinite(lat) || !Number.isFinite(lon))
return false;
const radius = Number.isFinite(nearKm) && nearKm > 0 ? nearKm : null;
if (
last &&
sameRadius(last.nearKm, radius) &&
(nowMs - last.ms < minIntervalMs ||
greatCircleKm(last, { lat, lon }) < minMoveKm)
)
return false;
last = { lat, lon, ms: nowMs, nearKm: radius };
inFlight = true;
const token = generation;
Promise.resolve()
.then(() => lookup(lat, lon, { nearKm: radius }))
.then(
(place) => {
if (token !== generation) return;
inFlight = false;
onPlace(place ?? null);
},
() => {
if (token !== generation) return;
inFlight = false;
last = null;
onPlace(null);
},
);
return true;
},
/** Forget the point and drop any lookup still in flight. */
reset() {
generation += 1;
inFlight = false;
last = null;
},
};
}
+280
View File
@@ -0,0 +1,280 @@
// src/data/placeBelow.test.mjs — what the ground track is over, offline:
// division and country on land (with the populated place in view from 8x),
// the smallest named sea, else the ocean; and the tracker that keeps it
// current without a lookup per frame.
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import {
NEAR_PLACE_MIN_ZOOM,
PLACE_LOOKUP_MIN_MOVE_KM,
PLACE_LOOKUP_MIN_MS,
createPlaceTracker,
nearPlaceRadiusKm,
placeBelow,
placePackLoads,
} from './placeBelow.js';
const PLACES_PACK = new URL(
'./local_data/natural_earth/populated_places.json',
import.meta.url,
);
// Runs first: the counters are module-wide.
test('the division and place packs load only when a lookup needs them', async () => {
assert.deepEqual(placePackLoads, { divisions: 0, places: 0 });
await placeBelow(42, 51, { nearKm: 50 });
assert.deepEqual(placePackLoads, { divisions: 0, places: 0 }, 'at sea');
await placeBelow(30.9, 104.2);
assert.deepEqual(placePackLoads, { divisions: 1, places: 0 }, 'at 1x');
await placeBelow(30.9, 104.2, { nearKm: 60 });
await placeBelow(31.2, 104.5, { nearKm: 30 });
assert.deepEqual(placePackLoads, { divisions: 1, places: 1 }, 'kept');
});
test('the populated-place pack is compact rows of name, position and rank', () => {
const bytes = readFileSync(PLACES_PACK);
assert.ok(bytes.length < 300_000, `${bytes.length} bytes`);
const pack = JSON.parse(bytes);
assert.match(pack.meta.url, /nvkelso\/natural-earth-vector/);
assert.match(pack.meta.license, /^Public domain/);
assert.ok(pack.places.length > 7000);
for (const [name, lat, lon, scalerank, rankMax] of pack.places) {
assert.equal(typeof name, 'string');
assert.ok(Math.abs(lat) <= 90 && Math.abs(lon) <= 180, name);
assert.ok(Number.isInteger(scalerank) && Number.isInteger(rankMax), name);
}
});
test('over land the place is the division and country, with its ISO code', async () => {
assert.deepEqual(await placeBelow(48.85, 2.35), {
kind: 'country',
name: 'France',
countryCode: 'FR',
division: 'Paris',
near: null,
});
// Across the antimeridian, and with a wrapped longitude.
assert.equal((await placeBelow(66, -175)).countryCode, 'RU');
assert.equal((await placeBelow(-17.8, 178)).countryCode, 'FJ');
assert.equal((await placeBelow(48.85, 362.35)).countryCode, 'FR');
});
test('at 1x a point in Sichuan reads Sichuan, China, with no city', async () => {
assert.deepEqual(await placeBelow(30.9, 104.2), {
kind: 'country',
name: 'China',
countryCode: 'CN',
division: 'Sichuan',
near: null,
});
assert.equal(nearPlaceRadiusKm(1, 1400), null);
assert.equal(nearPlaceRadiusKm(NEAR_PLACE_MIN_ZOOM / 2, 300), null);
});
test('from 8x the most prominent populated place in view is named', async () => {
assert.equal(NEAR_PLACE_MIN_ZOOM, 8);
// An 8x view ~120 km wide: Chengdu lies ~30 km off, inside half of it.
const nearKm = nearPlaceRadiusKm(8, 120);
assert.equal(nearKm, 60);
const place = await placeBelow(30.9, 104.2, { nearKm });
assert.equal(place.division, 'Sichuan');
assert.equal(place.near, 'Chengdu');
// Deyang lies nearer this point; Chengdu still outranks it.
assert.equal(
(await placeBelow(31.1, 104.35, { nearKm: 60 })).near,
'Chengdu',
);
});
test('no city is named when none lies within half the view', async () => {
// ~100 km west of Chengdu, in the mountains.
const place = await placeBelow(30.67, 103.0, { nearKm: 30 });
assert.equal(place.division, 'Sichuan');
assert.equal(place.near, null);
assert.equal(nearPlaceRadiusKm(8, Number.NaN), null);
});
test('at sea the smallest named sea wins over its ocean', async () => {
assert.deepEqual(await placeBelow(42, 51), {
kind: 'sea',
name: 'Caspian Sea',
countryCode: null,
});
// A radius changes nothing at sea.
assert.deepEqual(await placeBelow(42, 51, { nearKm: 60 }), {
kind: 'sea',
name: 'Caspian Sea',
countryCode: null,
});
assert.equal((await placeBelow(15, 88)).name, 'Bay of Bengal');
assert.equal((await placeBelow(35, 18)).name, 'Mediterranean Sea');
});
test('open water far from any sea is the ocean', async () => {
assert.deepEqual(await placeBelow(0, -150), {
kind: 'ocean',
name: 'South Pacific Ocean',
countryCode: null,
});
assert.equal((await placeBelow(40, 179.9)).name, 'North Pacific Ocean');
assert.equal((await placeBelow(40, -179.9)).name, 'North Pacific Ocean');
assert.equal((await placeBelow(40, -40)).name, 'North Atlantic Ocean');
});
test('an invalid point has no place', async () => {
assert.equal(await placeBelow(Number.NaN, 0), null);
assert.equal(await placeBelow(91, 0), null);
});
/** A lookup whose answers the test releases by hand. */
function manualLookup() {
const calls = [];
const lookup = (lat, lon, options) =>
new Promise((resolve) => calls.push({ lat, lon, options, resolve }));
return { calls, lookup };
}
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
test('the tracker looks up again only after both time and distance', async () => {
const { calls, lookup } = manualLookup();
const places = [];
const tracker = createPlaceTracker({
lookup,
onPlace: (place) => places.push(place),
});
assert.equal(tracker.update(0, 0, 1000), true, 'the first point');
await flush();
assert.equal(tracker.update(5, 5, 1100), false, 'one lookup at a time');
calls[0].resolve({ kind: 'ocean', name: 'A' });
await flush();
assert.deepEqual(places, [{ kind: 'ocean', name: 'A' }]);
// Far enough, but too soon.
assert.equal(tracker.update(5, 5, 1000 + PLACE_LOOKUP_MIN_MS - 1), false);
// Long enough, but barely moved (a geostationary satellite).
assert.equal(tracker.update(0.01, 0, 1000 + PLACE_LOOKUP_MIN_MS * 5), false);
// Both: a low orbit ~2.6 s on.
const movedDeg = (PLACE_LOOKUP_MIN_MOVE_KM + 1) / 111.2;
assert.equal(
tracker.update(movedDeg, 0, 1000 + PLACE_LOOKUP_MIN_MS * 5),
true,
);
await flush();
calls[1].resolve(null);
await flush();
assert.deepEqual(places.at(-1), null, 'nothing named there is reported');
});
test('a new radius (a zoom step) looks up again at once', async () => {
const { calls, lookup } = manualLookup();
const tracker = createPlaceTracker({ lookup, onPlace: () => {} });
assert.equal(tracker.update(0, 0, 1000), true);
await flush();
assert.deepEqual(calls[0].lat, 0);
calls[0].resolve(null);
await flush();
// Same point, a moment later: only the zoom changed.
assert.equal(tracker.update(0, 0, 1100, 60), true, 'into 8x');
await flush();
calls[1].resolve(null);
await flush();
// Altitude drift barely moves the radius: the gate holds.
assert.equal(tracker.update(0, 0, 1200, 62), false);
assert.equal(tracker.update(0, 0, 1300, 30), true, 'to 16x');
await flush();
calls[2].resolve(null);
await flush();
assert.equal(tracker.update(0, 0, 1400, null), true, 'back below 8x');
await flush();
assert.deepEqual(
calls.map((call) => call.options),
[{ nearKm: null }, { nearKm: 60 }, { nearKm: 30 }, { nearKm: null }],
);
});
test('a lookup that lands after reset is dropped', async () => {
const { calls, lookup } = manualLookup();
const places = [];
const tracker = createPlaceTracker({
lookup,
onPlace: (place) => places.push(place),
});
tracker.update(0, 0, 0);
await flush();
tracker.reset();
// A new session looks up at once.
assert.equal(tracker.update(10, 10, 1), true);
await flush();
calls[0].resolve({ name: 'stale' });
calls[1].resolve({ name: 'fresh' });
await flush();
assert.deepEqual(places, [{ name: 'fresh' }]);
});
test('a failed lookup frees the tracker for the next point', async () => {
let fail = true;
const places = [];
const tracker = createPlaceTracker({
lookup: async () => {
if (fail) throw new Error('pack failed');
return { name: 'ok' };
},
onPlace: (place) => places.push(place),
minIntervalMs: 0,
minMoveKm: 0,
});
tracker.update(0, 0, 0);
await flush();
assert.deepEqual(places, [null]);
fail = false;
assert.equal(tracker.update(0, 0, 1), true);
await flush();
assert.deepEqual(places, [null, { name: 'ok' }]);
});
test('the near-place radius is half the smaller side of the view', () => {
assert.equal(nearPlaceRadiusKm(8, 120, 60), 30, 'landscape');
assert.equal(nearPlaceRadiusKm(8, 60, 120), 30, 'portrait');
assert.equal(nearPlaceRadiusKm(8, 120), 60, 'square without a height');
assert.equal(nearPlaceRadiusKm(8, 120, Number.NaN), null);
});
test('a failed division or place pack still names the country', async () => {
const fail = async () => {
throw new Error('pack failed');
};
const place = await placeBelow(30.9, 104.2, {
nearKm: 60,
detail: { division: fail, near: fail },
});
assert.equal(place.kind, 'country');
assert.equal(place.countryCode, 'CN');
assert.equal(place.division, null);
assert.equal(place.near, null);
});
test('a failed lookup hides the old place and looks again on the next update', async () => {
let fail = false;
const places = [];
const tracker = createPlaceTracker({
lookup: async () => {
if (fail) throw new Error('pack failed');
return { kind: 'sea', name: 'Bay of Biscay' };
},
onPlace: (place) => places.push(place),
});
assert.equal(tracker.update(45, -5, 0), true);
await flush();
assert.deepEqual(places, [{ kind: 'sea', name: 'Bay of Biscay' }]);
// Over France the lookup fails: the bay must not stay on the band.
fail = true;
const movedDeg = (PLACE_LOOKUP_MIN_MOVE_KM + 1) / 111.2;
assert.equal(tracker.update(45 + movedDeg, 0, PLACE_LOOKUP_MIN_MS), true);
await flush();
assert.equal(places.at(-1), null, 'the band hides');
// The next tick tries again at once, even without moving (a GEO view).
fail = false;
assert.equal(tracker.update(45 + movedDeg, 0, PLACE_LOOKUP_MIN_MS + 1), true);
await flush();
assert.deepEqual(places.at(-1), { kind: 'sea', name: 'Bay of Biscay' });
});
+111
View File
@@ -0,0 +1,111 @@
// src/data/placePacksLoading.test.mjs — the loading status hears the place
// packs while they are on their way.
import test from 'node:test';
import assert from 'node:assert/strict';
test('a place pack load is reported from its start to its end', async () => {
// A module of its own, so no other test has loaded the packs yet.
const place = await import('./placeBelow.js?loading-status');
const heard = [];
const stop = place.onPlacePacksLoadingChange(() =>
heard.push(place.placePacksStatus().loading),
);
assert.equal(place.placePacksStatus().loading, false);
const lookup = place.nearPlace(48.86, 2.35, 50);
assert.equal(place.placePacksStatus().loading, true, 'on its way');
assert.equal(await lookup, 'Paris');
assert.equal(place.placePacksStatus().loading, false, 'loaded');
assert.deepEqual(heard, [true, false]);
// Loaded once: a later lookup is not reported again.
await place.nearPlace(48.86, 2.35, 50);
assert.deepEqual(heard, [true, false]);
stop();
});
test('a pack that would not load stays failed until it loads', async () => {
const place = await import('./placeBelow.js?failed-status');
let fail = true;
const load = place.reportedPlacePackLoad('test', async () => {
if (fail) throw new Error('offline');
return 1;
});
await assert.rejects(load(), /offline/);
assert.deepEqual(place.placePacksStatus(), { loading: false, failed: true });
fail = false;
const retry = load();
assert.deepEqual(
place.placePacksStatus(),
{ loading: true, failed: false },
'a retry is not a failure until it fails',
);
assert.equal(await retry, 1);
assert.deepEqual(place.placePacksStatus(), { loading: false, failed: false });
});
test('one lookup that loads several packs reads as one load', async () => {
const place = await import('./placeBelow.js?one-lookup');
const heard = [];
const stop = place.onPlacePacksLoadingChange(() => {
const { loading } = place.placePacksStatus();
if (heard.at(-1) !== loading) heard.push(loading);
});
// On land with a radius: countries and seas, then divisions, then places.
const found = await place.placeBelow(48.86, 2.35, { nearKm: 50 });
assert.equal(found.near, 'Paris');
assert.deepEqual(heard, [true, false], 'no gap between the packs');
stop();
});
/** Two stand-in packs (not real pack names) that fail while named in `fail`. */
function standInPacks(place, fail) {
const pack = (name) =>
place.reportedPlacePackLoad(name, async () => {
if (fail.has(name)) throw new Error('offline');
return name;
});
return { first: pack('stand-in-first'), second: pack('stand-in-second') };
}
/** The statuses one lookup that loads both stand-ins reports, start to end. */
async function lookupStatuses(place, { first, second }) {
const statuses = [];
const stop = place.onPlacePacksLoadingChange(() =>
statuses.push(place.placePacksStatus()),
);
await place.placeBelow(48.86, 2.35, {
detail: { division: async () => first(), near: async () => second() },
});
stop();
return statuses;
}
test('a load is not blamed for packs that failed in an earlier one', async () => {
const place = await import('./placeBelow.js?two-failed');
const fail = new Set(['stand-in-first', 'stand-in-second']);
const packs = standInPacks(place, fail);
await assert.rejects(packs.first());
await assert.rejects(packs.second());
assert.equal(place.placePacksStatus().failed, true);
fail.clear();
const statuses = await lookupStatuses(place, packs);
assert.deepEqual(statuses[0], { loading: true, failed: false });
assert.ok(
statuses.every((status) => status.failed === false),
'the earlier failures do not colour this load',
);
assert.deepEqual(place.placePacksStatus(), {
loading: false,
failed: false,
});
});
test('a pack that fails in a load keeps it failed when the next one lands', async () => {
const place = await import('./placeBelow.js?mixed');
const packs = standInPacks(place, new Set(['stand-in-first']));
const statuses = await lookupStatuses(place, packs);
assert.deepEqual(statuses.at(-1), { loading: false, failed: true });
assert.deepEqual(place.placePacksStatus(), {
loading: false,
failed: true,
});
});
+34 -59
View File
@@ -1,23 +1,23 @@
/**
* Satellite classification — CelesTrak source group → operator-legible class.
* Satellite labels and colours by CelesTrak source group, beneath the six
* classes.
*
* The catalog already tags every satellite with the CelesTrak group it was
* ingested from (`CATALOG_GROUPS` in satellites.js), so classification is a
* pure lookup: no extra fetch, no heuristics, no per-frame work. This module is
* the single source of truth for the class a satellite belongs to, the label
* shown on its card, and the point color it renders in — the render path, the
* tracked card, and the row legend all read the same table, so a palette edit
* can never leave one surface disagreeing with another.
* The class a satellite is filed under (STATIONS, IMAGING, TELECOM,
* STARLINK, PROBES or DEBRIS) is decided in src/layers/satellites/classes.js
* from SATCAT, the UCS database, names and the group, and that module owns
* each class's colour, legend label and toggle. This module keeps the
* group-based layer: the constellation subtype a card adds to the class
* (`TELECOM · GPS`, `STATIONS · ISS`; satelliteClassText), the group's own
* label for a satellite with no class (satelliteClassLabel), and the colour
* per group (satelliteClassColor), which the layer's base point styles use
* where a satellite has no class (src/layers/satellites/policy.js).
*
* Deliberately Cesium-free: colors are CSS hex strings that satellites.js
* converts once at module load. That keeps this file unit-testable and lets the
* legend swatches reuse the exact same strings the points are drawn with.
*
* Class order below is the legend order: crewed first (the objects people look
* for), then the constellations users can actually name, then the grab-bag.
* Deliberately Cesium-free: colors are CSS hex strings that the layer
* converts once at module load, so this file stays unit-testable.
*/
import { t, msg } from '../i18n/index.js';
import { SATELLITE_CLASS_DISPLAY } from '../layers/satellites/classes.js';
/**
* Class registry: the point color of each class. The card and legend text is
@@ -167,50 +167,25 @@ export function satelliteClassLabel(
}
/**
* Tally satellites into a class → count record.
* Split from the legend builder so the counting rule stays independent of how
* the legend is presented. Entries may be bare group tags, or `{ group, isIss }`
* descriptors when the caller can identify the ISS — the tally classifies
* through satelliteClassOf, so the legend and the card always agree.
* @param {Iterable<string|undefined|null|{group?: string, isIss?: boolean}>} entries
* One entry per satellite.
* @returns {Record<string, number>} Class key → count.
* The class a satellite shows on its card, label, overlay and orbital
* readout: its class (src/layers/satellites/classes.js) with the CelesTrak group's
* subtype where one says more ("TELECOM · GPS", "STATIONS · ISS"). A subtype
* that only repeats the class ("STARLINK · STARLINK") is dropped. Without a
* class the group's label stands (satelliteClassLabel).
* @param {string|null|undefined} satelliteClass Six-class id.
* @param {string|undefined|null} group CelesTrak group tag.
* @param {{ isIss?: boolean, localize?: boolean }} [options] As for
* satelliteClassLabel.
* @returns {string} Display label.
*/
export function tallySatelliteClasses(entries) {
const counts = Object.create(null);
for (const entry of entries || []) {
const descriptor =
entry && typeof entry === 'object' ? entry : { group: entry };
const { klass } = satelliteClassOf(descriptor.group, {
isIss: descriptor.isIss,
});
counts[klass] = (counts[klass] || 0) + 1;
}
return counts;
}
/**
* Build the layer-row legend from a class tally.
* Classes with no members are omitted so the legend never advertises a class
* that is not on screen (COMMS only appears once DENSE is on).
* @param {Record<string, number>} counts Class key → count (see tallySatelliteClasses).
* @returns {Array<{ klass: string, label: string, color: string, blurb: string, count: number }>}
* Present classes in legend order.
*/
export function satelliteClassLegend(counts) {
const result = [];
for (const klass of SATELLITE_CLASS_ORDER) {
const count = counts?.[klass];
if (!(count > 0)) continue;
const spec = SATELLITE_CLASSES[klass];
const display = CLASS_DISPLAY_KEYS[klass];
result.push({
klass,
label: t(display.label),
color: spec.color,
blurb: t(display.blurb),
count,
});
}
return result;
export function satelliteClassText(
satelliteClass,
group,
{ isIss = false, localize = true } = {},
) {
const display = SATELLITE_CLASS_DISPLAY[satelliteClass];
if (!display) return satelliteClassLabel(group, { isIss, localize });
const base = localize ? t(display.label) : display.label;
const { subtype } = satelliteClassOf(group, { isIss });
return subtype && subtype !== display.label ? `${base} · ${subtype}` : base;
}
+136 -91
View File
@@ -5,15 +5,15 @@ import {
SATELLITE_CLASS_ORDER,
satelliteClassColor,
satelliteClassLabel,
satelliteClassLegend,
satelliteClassOf,
tallySatelliteClasses,
satelliteClassText,
} from './satelliteClass.js';
import satellitesLayer, {
_catalogGroupForTest,
_clearDenseCatalogStateForTest,
_setDenseCatalogStateForTest,
} from './satellites.js';
import { CATALOG_GROUPS } from '../layers/satellites/policy.js';
/**
* A real, parseable TLE under an arbitrary 5-digit catalog number, so the dense
@@ -35,15 +35,19 @@ const ISS_TLE = tleFor('25544', 'ISS (ZARYA)');
/** Poll the chip until the async dense load settles (or give up). */
async function settleChip(maxTicks = 50) {
for (let i = 0; i < maxTicks; i++) {
const chip = satellitesLayer.getRowControls().chips[0];
const chip = starlinkChip();
if (chip && !chip.busy) return chip;
await new Promise((resolve) => setTimeout(resolve, 1));
}
return satellitesLayer.getRowControls().chips[0];
return starlinkChip();
}
/** The STARLINK class chip: the dense catalog toggle (id `catalog`). */
const starlinkChip = () =>
satellitesLayer.getRowControls().chips.find((entry) => entry.id === 'catalog');
/** Every CelesTrak group the catalog ingests, plus the dense-mode tag. */
const INGESTED_GROUPS = ['stations', 'visual', 'gps-ops', 'glonass', 'galileo', 'geo', 'dense'];
const INGESTED_GROUPS = [...CATALOG_GROUPS.map((group) => group.tag), 'dense'];
test('every ingested CelesTrak group resolves to a real class', () => {
// Guards against drift: adding a group to CATALOG_GROUPS without classifying
@@ -146,69 +150,7 @@ test('the dense shell stays dimmer than the class it sits among', () => {
);
});
test('tallying groups counts by class, folding the GNSS constellations together', () => {
const counts = tallySatelliteClasses([
'gps-ops', 'gps-ops', 'glonass', 'galileo',
'geo', 'geo', 'geo',
'stations',
'visual',
'dense', 'dense',
]);
assert.equal(counts.nav, 4, 'all three GNSS groups fold into NAV');
assert.equal(counts.geo, 3);
assert.equal(counts.station, 1);
assert.equal(counts.visual, 1);
assert.equal(counts.comms, 2);
});
test('tallying tolerates an empty or missing input', () => {
assert.deepEqual({ ...tallySatelliteClasses([]) }, {});
assert.deepEqual({ ...tallySatelliteClasses(undefined) }, {});
});
test('the tally files the ISS under STATION even when a partial outage moved it', () => {
// The legend and the card must never disagree. With the stations feed down,
// the ISS is ingested as `visual`; counting it there would let STATION vanish
// from the legend while the tracked card still reads "STATION · ISS".
const outage = tallySatelliteClasses([
{ group: 'visual', isIss: true },
{ group: 'visual' },
{ group: 'visual' },
]);
assert.equal(outage.station, 1, 'the ISS is counted as a STATION');
assert.equal(outage.visual, 2, 'and is not double-counted under VISUAL');
const legend = satelliteClassLegend(outage);
assert.equal(legend.some((row) => row.klass === 'station'), true,
'STATION stays in the legend, matching the card');
// Bare group tags still work — the descriptor form is additive.
assert.deepEqual({ ...tallySatelliteClasses(['visual', 'visual']) }, { visual: 2 });
assert.equal(satelliteClassOf('visual', { isIss: true }).klass, 'station',
'one helper owns the rule for every consumer');
});
test('the legend lists present classes in order and omits absent ones', () => {
const legend = satelliteClassLegend(tallySatelliteClasses(['geo', 'gps-ops', 'stations']));
assert.deepEqual(legend.map((row) => row.klass), ['station', 'nav', 'geo'],
'legend follows SATELLITE_CLASS_ORDER, not input order');
// COMMS only exists in DENSE mode — the legend must not advertise a class
// that has nothing on screen.
assert.equal(legend.some((row) => row.klass === 'comms'), false);
const row = legend.find((entry) => entry.klass === 'nav');
assert.equal(row.label, 'NAV');
assert.equal(row.color, SATELLITE_CLASSES.nav.color);
assert.equal(row.count, 1);
assert.ok(row.blurb.length > 0, 'every legend row carries a plain-language gloss');
});
test('the legend drops zero and negative counts', () => {
assert.deepEqual(satelliteClassLegend({ nav: 0, geo: -1, station: 2 }).map((r) => r.klass), ['station']);
assert.deepEqual(satelliteClassLegend(null), []);
});
test('the DENSE row chip is stateless and declares the params to apply', () => {
test('the STARLINK row chip is stateless and declares the params to apply', () => {
// The chip never carries its own state: it declares the params to apply, so
// whatever else drives the catalog param (Space Missions capture/restore)
// stays authoritative. Whether it reads ACTIVE is decided by the dense LOAD,
@@ -217,7 +159,7 @@ test('the DENSE row chip is stateless and declares the params to apply', () => {
_setDenseCatalogStateForTest({});
const chip = satellitesLayer.getRowControls().chips.find((entry) => entry.id === 'catalog');
assert.equal(chip.id, 'catalog');
assert.equal(chip.label, 'DENSE');
assert.equal(chip.label, 'STARLINK');
assert.equal(chip.active, false);
assert.equal(chip.busy, false);
assert.equal(chip.state, 'idle');
@@ -236,7 +178,7 @@ test('an invalid catalog mode is rejected without disturbing the chip', () => {
assert.equal(chip.active, false);
});
test('DENSE reports loading, then ACTIVE only once the points exist', async () => {
test('STARLINK reports loading, then ACTIVE only once the points exist', async () => {
const originalFetch = globalThis.fetch;
const refreshes = [];
try {
@@ -247,7 +189,7 @@ test('DENSE reports loading, then ACTIVE only once the points exist', async () =
satellitesLayer.setParams({ catalog: 'dense' });
// The param flips synchronously, but the shell has not arrived yet — the
// chip must say BUSY, never ACTIVE.
const pending = satellitesLayer.getRowControls().chips[0];
const pending = starlinkChip();
assert.equal(pending.busy, true);
assert.equal(pending.disabled, true);
assert.equal(pending.active, false, 'never active before the points exist');
@@ -256,21 +198,21 @@ test('DENSE reports loading, then ACTIVE only once the points exist', async () =
const settled = await settleChip();
assert.equal(settled.active, true, 'active once the dense points are on screen');
assert.equal(settled.state, 'active');
assert.equal(settled.label, 'DENSE');
assert.equal(settled.label, 'STARLINK');
assert.deepEqual(settled.params, { catalog: 'core' }, 'a settled chip toggles back off');
// The completion pushed a refresh, and the legend gained COMMS with it —
// The completion pushed a refresh, and the legend gained STARLINK with it —
// without that push the row would keep the pre-load counts for 5 minutes.
assert.ok(refreshes.length >= 2, 'load start and load completion each pushed a refresh');
const legend = satellitesLayer.getRowControls().legend;
assert.equal(legend.some((row) => row.klass === 'comms'), true);
assert.equal(legend.some((row) => row.klass === 'starlink'), true);
} finally {
globalThis.fetch = originalFetch;
_clearDenseCatalogStateForTest();
}
});
test('a failed DENSE load reverts the mode rather than leaving an active chip', async () => {
test('a failed STARLINK load reverts the mode rather than leaving an active chip', async () => {
const originalFetch = globalThis.fetch;
const warn = console.warn;
console.warn = () => {};
@@ -285,14 +227,14 @@ test('a failed DENSE load reverts the mode rather than leaving an active chip',
assert.equal(settled.active, false, 'a 502 must never present as a live dense catalog');
assert.equal(settled.state, 'error');
assert.equal(settled.label, 'DENSE ✕');
assert.equal(settled.label, 'STARLINK ✕');
assert.match(settled.title, /502/, 'the chip explains why');
assert.equal(satellitesLayer.getParams().catalog, 'core', 'the mode reverts to reality');
assert.deepEqual(settled.params, { catalog: 'dense' }, 'clicking retries');
assert.equal(
satellitesLayer.getRowControls().legend.some((row) => row.klass === 'comms'),
satellitesLayer.getRowControls().legend.some((row) => row.klass === 'starlink'),
false,
'no COMMS class is advertised when nothing loaded',
'no STARLINK class is advertised when nothing loaded',
);
assert.ok(pushes >= 2, 'the failure pushed its own refresh');
@@ -365,9 +307,9 @@ test('an explicit return to core clears a failure the user never caused', async
// A no-op restore of the pre-mission snapshot.
satellitesLayer.setParams({ catalog: 'core', showPoints: true, showOrbits: true });
const restored = satellitesLayer.getRowControls().chips[0];
const restored = starlinkChip();
assert.equal(restored.state, 'idle', 'the error does not survive the restore');
assert.equal(restored.label, 'DENSE');
assert.equal(restored.label, 'STARLINK');
assert.doesNotMatch(restored.title, /502/);
} finally {
console.warn = warn;
@@ -376,7 +318,7 @@ test('an explicit return to core clears a failure the user never caused', async
}
});
test('a real stations-feed outage keeps STATION in the legend, matching the card', async () => {
test('a real stations-feed outage keeps the ISS under STATIONS in the legend', async () => {
// End-to-end version of the tally rule: drive a real rebuild in which only
// the `visual` group answers, so the ISS is genuinely ingested as `visual`.
// The legend must still file it under STATION or it disagrees with the card.
@@ -398,11 +340,11 @@ test('a real stations-feed outage keeps STATION in the legend, matching the card
'the outage really did ingest the ISS from the visual group');
const legend = satellitesLayer.getRowControls().legend;
assert.equal(legend.find((row) => row.klass === 'station')?.count, 1,
'STATION survives the outage because the ISS is counted there');
assert.equal(legend.some((row) => row.klass === 'visual'), false,
'and it is not also counted under VISUAL');
assert.equal(satelliteClassLabel('visual', { isIss: true }), 'STATION · ISS',
assert.equal(legend.find((row) => row.klass === 'stations')?.count, 1,
'STATIONS survives the outage because the ISS is counted there');
assert.equal(legend.length, 1, 'and it is not also counted under another class');
const [iss] = satellitesLayer.getAnalystRecords();
assert.equal(iss?.satelliteClass, 'STATIONS · ISS',
'the card says the same thing the legend does');
} finally {
console.log = log;
@@ -431,15 +373,21 @@ test('a catalog rebuild refreshes the detection overlay class strings', async ()
text: async () => (String(url).endsWith(`/${homeGroup}`) ? ALT_TLE : ''),
});
// Every class on: the seeded satellite's class must not hide it.
satellitesLayer.setParams({
classes: { telecom: true, probes: true, debris: true },
});
await satellitesLayer.update(viewer);
const first = satellitesLayer.getDetectableObjects().find((o) => o.sourceId === 33333);
assert.ok(first, 'the seeded satellite is collectable');
assert.equal(first.klass, 'GEO');
// A payload with no SATCAT record and no recognisable name takes its
// group's class (src/layers/satellites/classes.js).
assert.equal(first.klass, 'TELECOM');
homeGroup = 'visual';
homeGroup = 'resource';
await satellitesLayer.update(viewer);
const second = satellitesLayer.getDetectableObjects().find((o) => o.sourceId === 33333);
assert.equal(second.klass, 'VISUAL', 'the cached record does not outlive its catalog');
assert.equal(second.klass, 'IMAGING', 'the cached record does not outlive its catalog');
} finally {
console.log = log;
console.warn = warn;
@@ -451,7 +399,7 @@ test('a catalog rebuild refreshes the detection overlay class strings', async ()
test('a dependency owner hiding the points surrenders the whole row', async () => {
try {
_setDenseCatalogStateForTest({});
assert.equal(satellitesLayer.getRowControls().chips.length, 1);
assert.equal(satellitesLayer.getRowControls().chips.length, 6);
// Space Missions borrows this layer for TLE lookup with showPoints:false.
satellitesLayer.setParams({ showPoints: false });
@@ -460,8 +408,105 @@ test('a dependency owner hiding the points surrenders the whole row', async () =
assert.deepEqual(owned.legend, [], 'no legend describing an empty sky');
satellitesLayer.setParams({ showPoints: true });
assert.equal(satellitesLayer.getRowControls().chips.length, 1, 'released on restore');
assert.equal(satellitesLayer.getRowControls().chips.length, 6, 'released on restore');
} finally {
_clearDenseCatalogStateForTest();
}
});
test('every class but Starlink shows by default; each class chip turns its class on and off', async () => {
const originalFetch = globalThis.fetch;
const log = console.log;
const warn = console.warn;
console.log = () => {};
console.warn = () => {};
const served = {
'/api/celestrak/stations': ISS_TLE,
'/api/celestrak/resource': tleFor('90002', 'SENTINEL-2A'),
'/api/celestrak/gps-ops': tleFor('90001', 'GPS BIII-1'),
'/api/celestrak/visual': tleFor('90003', 'SL-16 R/B'),
};
const shown = () => satellitesLayer.getAllPositions().map((row) => row.id).sort();
const chip = (id) =>
satellitesLayer.getRowControls().chips.find((entry) => entry.id === `class-${id}`);
try {
_setDenseCatalogStateForTest({});
globalThis.fetch = async (url) => ({
ok: true,
text: async () => served[String(url)] || '',
});
await satellitesLayer.update({ scene: { primitives: { add: (p) => p, remove() {} } } });
assert.deepEqual(shown(), [25544, 90001, 90002, 90003], 'all but Starlink');
assert.deepEqual(
satellitesLayer.getRowControls().chips.map((entry) => entry.label),
['STATIONS', 'IMAGING', 'TELECOM', 'STARLINK', 'PROBES', 'DEBRIS'],
);
assert.equal(chip('imaging').active, true);
assert.equal(chip('telecom').active, true);
assert.equal(
satellitesLayer.getRowControls().chips.find((entry) => entry.id === 'catalog').active,
false,
);
assert.deepEqual(chip('telecom').params, { classes: { telecom: false } });
assert.deepEqual(
satellitesLayer.getRowControls().legend.map((row) => row.klass),
['stations', 'imaging', 'telecom', 'debris'],
'the legend keys only what is on screen',
);
satellitesLayer.setParams(chip('telecom').params);
satellitesLayer.setParams(chip('debris').params);
assert.deepEqual(shown(), [25544, 90002], 'telecom and debris off');
assert.equal(chip('debris').active, false);
assert.deepEqual(satellitesLayer.getParams().classes, {
stations: true,
imaging: true,
telecom: false,
starlink: false,
probes: true,
debris: false,
});
satellitesLayer.setParams(chip('telecom').params);
satellitesLayer.setParams(chip('imaging').params);
assert.deepEqual(shown(), [25544, 90001], 'telecom back on, imaging off');
assert.equal(satellitesLayer.setParams({ classes: 'all' }), false, 'malformed request refused');
// A saved or shared choice comes back as class letters.
assert.equal(satellitesLayer.setParams({ classes: 'sip' }), true);
assert.deepEqual(satellitesLayer.getParams().classes, {
stations: true,
imaging: true,
telecom: false,
starlink: false,
probes: true,
debris: false,
});
assert.deepEqual(shown(), [25544, 90002], 'restored from letters');
} finally {
console.log = log;
console.warn = warn;
globalThis.fetch = originalFetch;
_clearDenseCatalogStateForTest();
}
});
test('the shown class is the six-class one, with a subtype that says more', () => {
assert.equal(satelliteClassText('telecom', 'gps-ops'), 'TELECOM · GPS');
assert.equal(
satelliteClassText('stations', 'visual', { isIss: true }),
'STATIONS · ISS',
);
assert.equal(satelliteClassText('imaging', 'resource'), 'IMAGING');
assert.equal(satelliteClassText('imaging', 'visual'), 'IMAGING');
// A subtype that only repeats the class is dropped.
assert.equal(satelliteClassText('starlink', 'dense'), 'STARLINK');
// A dead geostationary comsat is debris, not GEO.
assert.equal(satelliteClassText('debris', 'geo'), 'DEBRIS');
// Without a class the group's label stands.
assert.equal(satelliteClassText(null, 'gps-ops'), 'NAV · GPS');
assert.equal(
satelliteClassText('telecom', 'gps-ops', { localize: false }),
'TELECOM · GPS',
);
});
+54
View File
@@ -0,0 +1,54 @@
/**
* @file The satellites layer's class choice as share-link and saved-state
* letters. Shared by the layer-state codec and the layer, which takes a saved
* choice back in this form.
*/
/**
* Satellite classes shown, as one letter each in legend order: stations,
* imaging, telecom, probes, debris (`sitpd`, every one; `0`, none).
* Starlink is the `catalog` option's, so it has no letter here.
*/
const SATELLITE_CLASS_LETTERS = Object.freeze([
['stations', 's'],
['imaging', 'i'],
['telecom', 't'],
['probes', 'p'],
['debris', 'd'],
]);
const SATELLITE_CLASS_MASK = /^(0|s?i?t?p?d?)$/;
/**
* The canonical class letters for a class choice (an object of booleans, as
* the layer's `classes` param, or a partial one) or for letters already,
* else null.
* @param {unknown} value
* @returns {string|null}
*/
export function normalizeSatelliteClassMask(value) {
if (typeof value === 'string')
return value && SATELLITE_CLASS_MASK.test(value) ? value : null;
if (!value || typeof value !== 'object') return null;
// A class the choice leaves out keeps its default, which is shown: a
// partial request (`{debris: false}`) hides only what it names.
const letters = SATELLITE_CLASS_LETTERS.filter(([id]) => value[id] !== false)
.map(([, letter]) => letter)
.join('');
return letters || '0';
}
/**
* The class choice the letters stand for, without Starlink, or null.
* @param {string} mask
* @returns {Record<string, boolean>|null}
*/
export function decodeSatelliteClassMask(mask) {
const normalized = normalizeSatelliteClassMask(mask);
if (normalized === null || typeof mask !== 'string') return null;
return Object.fromEntries(
SATELLITE_CLASS_LETTERS.map(([id, letter]) => [
id,
normalized.includes(letter),
]),
);
}
+49
View File
@@ -152,3 +152,52 @@ test('satellite getAnalystRecords: core rows beat dense extras under the cap', (
_clearDenseCatalogStateForTest();
}
});
test('satellite getAnalystRecords: a hidden class stays out, the tracked one stays in', () => {
const satrec = twoline2satrec(ISS_L1, ISS_L2);
const at = (lon, alt) => ({
position: Cesium.Cartesian3.fromDegrees(lon, 10, alt),
});
_setTrackedSatelliteRefreshStateForTest({
noradId: ISS_NORAD,
name: 'ISS (ZARYA)',
satrec,
entity: {},
point: at(-97, 420_000),
viewer: {},
now: () => Date.now(),
satelliteClass: 'stations',
classes: {
stations: false,
imaging: true,
telecom: false,
starlink: false,
probes: true,
debris: true,
},
neighbours: [
{
noradId: 24876,
name: 'GPS BIIR-2',
group: 'gps-ops',
satelliteClass: 'telecom',
point: at(-100, 20_200_000),
},
{
noradId: 90001,
name: 'TEST IMAGER',
group: 'resource',
satelliteClass: 'imaging',
point: at(-80, 700_000),
},
],
});
try {
assert.deepEqual(
satellitesLayer.getAnalystRecords(10).map((r) => r.noradId),
['25544', '90001'],
);
} finally {
_clearDenseCatalogStateForTest();
}
});
+8
View File
@@ -6,6 +6,14 @@ export function celestrakTleUrl(group) {
return url;
}
/** CelesTrak SATCAT records (object type, status, owner) for a GP group, as CSV. */
export function celestrakSatcatUrl(group) {
const url = new URL('https://celestrak.org/satcat/records.php');
url.searchParams.set('GROUP', group);
url.searchParams.set('FORMAT', 'CSV');
return url;
}
export function launchLibraryRecentUrl(end) {
// Stable minute boundaries let different installations share LL2's cache.
const roundedEnd = new Date(Math.floor(end.getTime() / 60000) * 60000);
+62
View File
@@ -0,0 +1,62 @@
/**
* @file The bundled UCS Satellite Database pack: operator, owner country and
* purpose for active satellites, keyed by NORAD catalog number.
*
* Data: `local_data/ucs_satellites/ucs_satellites.json`, built by
* `scripts/build-ucs-satellites.py` from UCS-Satellite-Database 5-1-2023
* (https://www.ucsusa.org/satellite_database; free, unrestricted use, with an
* acknowledgement). Loaded once, on demand, by the satellites layer; a failed
* load is retried after a cooldown rather than remembered for the session.
*
* @module data/ucsSatellites
*/
import { loadBundledJson } from './bundledJson.js';
import { createRetryableLoader } from './retryableLoad.js';
const PACK_URL = new URL(
'./local_data/ucs_satellites/ucs_satellites.json',
import.meta.url,
);
/**
* One UCS row: what UCS says about a satellite's operator and purpose.
* @typedef {{noradId: number, operator: string|null,
* operatorCountry: string|null, purpose: string|null}} UcsSatellite
*/
/**
* Expand the pack's string-table rows into records keyed by NORAD number.
* A pack of the wrong shape throws: read as an empty pack it would be kept
* for the session, and every satellite would quietly lose its UCS evidence.
* A malformed row is skipped.
* @param {{fields: string[], strings: Record<string, string[]>,
* records: Array<number[]>}} pack Parsed `ucs_satellites.json`.
* @returns {Map<number, UcsSatellite>}
*/
export function indexUcsPack(pack) {
const byNorad = new Map();
const fields = pack?.fields;
if (
!Array.isArray(fields) ||
fields[0] !== 'noradId' ||
!Array.isArray(pack.records)
)
throw new TypeError('UCS pack has an unexpected shape');
for (const row of pack.records) {
const noradId = row?.[0];
if (!Number.isInteger(noradId) || noradId <= 0) continue;
const record = { noradId };
for (let i = 1; i < fields.length; i++) {
const text = pack.strings?.[fields[i]]?.[row[i]];
record[fields[i]] = text ? text : null;
}
byNorad.set(noradId, record);
}
return byNorad;
}
/** The pack, loaded and indexed once. */
export const loadUcsSatellites = createRetryableLoader(async () =>
indexUcsPack(await loadBundledJson(PACK_URL)),
);
+80
View File
@@ -0,0 +1,80 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { indexUcsPack, loadUcsSatellites } from './ucsSatellites.js';
const PACK_URL = new URL(
'./local_data/ucs_satellites/ucs_satellites.json',
import.meta.url,
);
test('the bundled UCS pack names its release, licence and curation', () => {
const pack = JSON.parse(readFileSync(PACK_URL, 'utf8'));
assert.equal(pack.meta.version, 'UCS-Satellite-Database 5-1-2023');
assert.equal(pack.meta.url, 'https://www.ucsusa.org/satellite_database');
assert.equal(pack.meta.dataCurrentTo, '2023-05-01');
assert.match(pack.meta.license, /unrestricted/);
assert.equal(pack.meta.recordCount, pack.records.length);
assert.equal(
pack.meta.curation.sourceRows,
pack.records.length +
pack.meta.curation.starlinkRowsDropped +
pack.meta.curation.invalidNoradDropped +
pack.meta.curation.duplicateNoradDropped,
);
assert.deepEqual(pack.fields, [
'noradId',
'operator',
'operatorCountry',
'purpose',
]);
// Small enough to load with the layer.
assert.ok(readFileSync(PACK_URL).length < 200_000);
});
test('the pack loads into records keyed by NORAD number', async () => {
const records = await loadUcsSatellites();
assert.equal(records, await loadUcsSatellites(), 'loaded once');
const iss = records.get(25544);
assert.ok(iss, 'the ISS is in UCS');
assert.equal(iss.noradId, 25544);
assert.ok(iss.operator);
assert.ok(iss.purpose);
for (const record of records.values()) {
assert.doesNotMatch(
`${record.operator ?? ''} ${record.purpose ?? ''}`,
/starlink/i,
'Starlink rows are dropped',
);
}
});
test('indexing reads the string tables and turns empty strings into null', () => {
const records = indexUcsPack({
fields: ['noradId', 'operator', 'purpose'],
strings: { operator: ['', 'ESA'], purpose: ['', 'Earth Observation'] },
records: [
[39634, 1, 1],
[40000, 0, 1],
['bad', 1, 1],
[-5, 1, 1],
],
});
assert.deepEqual([...records.keys()], [39634, 40000]);
assert.deepEqual(records.get(39634), {
noradId: 39634,
operator: 'ESA',
purpose: 'Earth Observation',
});
assert.equal(records.get(40000).operator, null);
});
test('a pack of the wrong shape throws, so the loader tries again', () => {
// Read as empty, it would be cached for the session as a success.
assert.throws(() => indexUcsPack(null), TypeError);
assert.throws(
() => indexUcsPack({ fields: ['name'], records: [[1]] }),
TypeError,
);
assert.throws(() => indexUcsPack({ fields: ['noradId'] }), TypeError);
});