@johnmorrisdotca/chikyu-earth 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.0 - 2026-11-03
4
+
5
+ The demo's elements refresh by themselves, every satellite shows its age, and you can bring your own source (MODULES-261, steps 3 and 4).
6
+
7
+ - **A scheduled build refreshes the demo's element files every six hours** (`.github/workflows/pages.yml`, `scripts/elements.ts fetch`): one download of each of CelesTrak's 13 lists and 5 single satellites, a six-second pause between asks, a user agent that names the repository and a contact, a list not asked for again within 110 minutes, and a stop at the first answer that is not 200 (CelesTrak's rules for software, read 2026-11-03), keeping every other group's last file. A push carries over the files already on the live site and asks CelesTrak for nothing. A check refuses to publish a set with an empty or missing group or one older than 30 days. No server runs per view: the browser reads files on Pages. The embed page reads the same files, and takes any group (`&satellites=gps,weather`).
8
+ - **Age and dimming.** The page says how long ago the files were downloaded and each satellite's age. A satellite whose elements are more than 14 days from the time shown is placed but drawn dimmer (`createSatellites` option `dimAfterDays`, `Satellites.dimmed` and `dimVersion`, `DEFAULT_DIM_AFTER_DAYS`), and the page says why (its place is less exact); one more than 30 days away is left out. **`DEFAULT_MAX_AGE_DAYS` is now 30** (it was 14, where the satellite was left out): the 14 days is the dimming now. Still one instanced draw for a group, and the dimming costs one number a satellite, copied to the graphics card only when one changes.
9
+ - **Tests on recorded and made-up elements, never a live request.** The browser tests are served the recorded stations and Starlink of 2026-11-02 (`test/recorded/`, `e2e/recorded.ts`) so no position moves as the demo's files are refreshed; the file maker, the polite downloader (a made-up CelesTrak that answers 200, then 403), the age check and the dimming are unit-tested (`test/elements.test.ts`, `test/satellites.test.ts`), and the demo's dimming and notes in `e2e/groups.gl.ts`.
10
+ - **`fetchElements(url, options)`** (`@johnmorrisdotca/chikyu-earth/satellites`) asks an address you choose, in the visitor's browser, for OMM JSON, OMM CSV or TLE text and returns element sets for `createSatellites`, with `skipped` (what it left out, and why), `retrievedAt` and `fromCache`. It has no address of its own, and it is polite by design: https only (http on localhost), no cookies or referrer, no redirects; the same address is not asked again within two hours (the answer already read is returned from the page or from `localStorage`); any answer that is not 200, or none, leaves the address alone for an hour and throws an **`ElementSourceError`** (`status`, `retryAt`), using the answer already read meanwhile; at most 20 million bytes and 50,000 sets. `forgetElements()` is for tests.
11
+ - **`parseElements(text)`** reads the three formats with no request (so it runs on a server): OMM JSON (an array or one object, numbers as numbers or text), OMM CSV (quoted names) and TLE (two lines or three, checksums checked, the epoch, the implied decimals and the designator turned into OMM's fields); a TLE read this way flies to within half a kilometre of the OMM it was written from.
12
+ - **The demo has "Your own source"**: paste an address, press Load; the satellites become a "Yours" group you can show, find by name and ride. Nothing is asked until the visitor presses the button (an address in the page's own address only fills the box). It says how many were read and from where, what was left out and why, whether the answer was just asked for or kept (and for how long it will not be asked again), or why it could not be used. English and Japanese.
13
+ - Tests: made-up fetch and made-up TLE with real checksums (`test/source.test.ts`); in the browser a made-up address that the test serves, a refusal, something that is not elements and an http address, with a check that the page asked nothing else (`e2e/groups.gl.ts`).
14
+
15
+ ## 0.12.0 - 2026-11-03
16
+
17
+ More satellites to follow and ride (MODULES-261, steps 1 and 2): where the data may come from, a curated catalogue, and fourteen groups in the demo.
18
+
19
+ - **`docs/satellite-sources.md`: every source's terms read and quoted** (CelesTrak, Space-Track, SatNOGS DB, N2YO, AMSAT, NASA and ESA, Wikidata), each with a tier (green, grey, red) and whether it may be fetched by the visitor's own browser, snapshotted on the demo site, or redistributed in the package. CelesTrak stays grey; Space-Track's blanket approval for passing on basic data (TLEs, OMMs) with a citation is noted; the decisions that are John's are one ticket (MODULES-333). The package still ships no orbital elements.
20
+ - **A curated catalogue** in `@johnmorrisdotca/chikyu-earth/satellites`: `SATELLITE_GROUPS` (fourteen groups: stations, famous, science, Earth observation, weather, geostationary, GPS, GLONASS, Galileo, BeiDou, amateur radio, OneWeb, Iridium, Starlink, each with its CelesTrak list or catalogue numbers, an orbit kind, whether it sits still, and a line in English and Japanese), `CATALOGUE` (about forty satellites by NORAD number, from the ISS and Tiangong to Hubble and Vanguard 1, the oldest satellite still in orbit, each with a line in English and Japanese), `findInCatalogue` and `catalogueEntry`. JWST is left out on purpose: it is not in Earth orbit. No elements in it.
21
+ - **The demo's groups are buttons** (a coloured dot each; a group switched on says what it is, and the demo zooms out to a group that goes far from the Earth), with **Find** (a search box over the catalogue and the names of every satellite in the demo's files, plus ISS and Tiangong) and two new rides, **The chosen satellite** and **One from the last group**. The address keeps the groups (`sats=gps,weather`), the chosen satellite (`sat=<NORAD number>`) and the ride (`ride=chosen`). A chosen satellite shows its catalogue line beside its height, speed and age.
22
+ - **`demo/elements/`** (demo site only): one file for each group, made from one download of each CelesTrak list on 2026-11-03, `manifest.json` and `index.json`; `scripts/elements.ts` makes them from downloaded lists and fetches nothing. Starlink stays at every fifth satellite (about 2,200 dots in one draw call); the others are whole (the geostationary list has 569).
23
+ - **Moons that have left the view are let go even when nothing else is drawn.** The space view let go of a moon four seconds after it left the view, but only when the next draw happened; a view at rest draws nothing, so the moons of Jupiter and Saturn were kept (their shaders and pictures) until someone touched the view. It now asks for one more draw when the first of them is due. Test: `e2e/space.gl.ts`. This is why the space soak failed in CI on "programs" since 0.11.0 (the count was never growing: the moons kept after leaving the view made it differ from one moment to the next); the soak now also looks at the Earth, on the day the view opened on (which moons of Saturn and Jupiter are in the view depends on the day), in sight and drawing, before it counts; the count came back to what it was in three of three local runs and the one-minute soak in CI.
24
+ - Tests: the catalogue and the file maker (`test/catalogue.test.ts`, `test/elements.test.ts`) and the demo's groups, Find and Ride on **made-up** element files served in place of the demo's own, with a check that nothing is asked of any other site (`e2e/groups.gl.ts`).
25
+
3
26
  ## 0.11.0 - 2026-11-03
4
27
 
5
28
  The real Sun, planets, Pluto and moons in the space view.
package/NOTICE.md CHANGED
@@ -49,11 +49,12 @@ bundle or ship it. The planets are drawn as plain colours, from no picture.
49
49
  `<chikyu-space>` draws satellites from orbital elements that **your page** passes in; this package fetches and ships none. SGP4 is run by **satellite.js** (https://github.com/shashwatak/satellite-js, MIT, by
50
50
  Shashwat Kandadai and contributors), the page's own optional peer dependency: this package does not bundle or ship it.
51
51
 
52
- The demo's file `demo/celestrak-snapshot.json` (the demo site only, not the npm package) holds element sets from **CelesTrak** (https://celestrak.org, T.S. Kelso), which serves the U.S. Space Force's
52
+ The demo's files `demo/elements/*.json` (the demo site only, not the npm package) hold element sets, one file for each of fourteen groups, from one download of each of CelesTrak's lists on 2026-11-03 (about 16:00 UTC), with every fifth
53
+ Starlink satellite kept (2,231 of 11,155), within the same usage policy, credited the same way and with the same grey tier. The files are refreshed by a scheduled build every six hours (`.github/workflows/pages.yml`, `scripts/elements.ts`), one download of each list each time, within the same policy; `test/recorded/celestrak-snapshot-2026-11-02.json` below is the older snapshot of 2026-11-02, kept only for the tests. It holds element sets from **CelesTrak** (https://celestrak.org, T.S. Kelso), which serves the U.S. Space Force's
53
54
  18th Space Defense Squadron's general-perturbation (GP) data and, for Starlink, SpaceX's own supplemental elements. It is one download of the `stations` list and one of the `starlink` list on 2026-11-02
54
55
  (about 17:07 UTC), within CelesTrak's usage policy (https://celestrak.org/usage-policy.php, read 2026-11-02: one download per update per list, nothing fetched at a visitor's request), with every fifth Starlink satellite
55
56
  kept (2,232 of 11,156), as numbers only. CelesTrak states no licence or credit rule for the data; it is credited on the demo page, and the demo shows the age of the elements. The tier is "grey" in John's
56
- terms: a snapshot with credit, never a live fetch. Space-Track's data are not used: its user agreement does not let an account holder pass the data on.
57
+ terms: a snapshot with credit, never a live fetch. The catalogue (`src/satellites/catalogue.ts`) holds names, NORAD numbers and orbit kinds, which are facts, and lines written for this package in its own words (English and Japanese); nothing is copied from NASA, ESA, Wikipedia or any other page. Space-Track's data are not used (it needs an account; its user agreement allows passing on basic data such as TLEs and OMMs only with a citation). docs/satellite-sources.md has every source's terms, read 2026-11-03.
57
58
 
58
59
  ## Sun position
59
60
 
package/README.md CHANGED
@@ -157,7 +157,7 @@ computed in the browser by astronomy-engine (MIT), nothing is fetched. [docs/spa
157
157
 
158
158
  ## Satellites
159
159
 
160
- The ISS, a space station or thousands of Starlink satellites at the places SGP4 puts them for the date and time shown, on `<chikyu-space>`: a group is one draw call however many it holds, press one to get its name, height and speed, and its orbit is drawn. Chikyu fetches nothing: your page passes in orbital elements (CelesTrak's JSON, within its usage policy), and satellite.js (MIT, an optional peer) does the maths about once a second, with every frame between interpolated. A group is hidden while the clock runs faster than 60 times real time. The guide has the rules for getting elements and the budget, each line tested: [satellites guide](docs/guides/satellites.md), [docs/satellites.md](docs/satellites.md).
160
+ The ISS, a space station or thousands of Starlink satellites at the places SGP4 puts them for the date and time shown, on `<chikyu-space>`: a group is one draw call however many it holds, press one to get its name, height and speed, and its orbit is drawn. Chikyu fetches nothing: your page passes in orbital elements (CelesTrak's JSON, within its usage policy), and satellite.js (MIT, an optional peer) does the maths about once a second, with every frame between interpolated. `fetchElements(url)` reads OMM JSON, CSV or TLE from an address you choose, politely (https, not again within two hours, stop on any answer that is not 200). A satellite whose elements are more than 14 days from the time shown is drawn dimmer, and one more than 30 days away is left out. A group is hidden while the clock runs faster than 60 times real time. A small catalogue (`SATELLITE_GROUPS`, `CATALOGUE`, `findInCatalogue`) names fourteen groups (stations, weather, GPS, Galileo, OneWeb and more) and about forty satellites worth following, with no elements in it. The guide has the rules for getting elements and the budget, each line tested: [satellites guide](docs/guides/satellites.md), [docs/satellites.md](docs/satellites.md).
161
161
 
162
162
  <p align="center"><img alt="The ISS, ringed, over South Africa on 3 November 2026, with its orbit and the stations' orbits" src="docs/images/space-sat-iss.png" width="420"></p>
163
163
 
@@ -0,0 +1,109 @@
1
+ /**
2
+ * What kind of orbit a satellite or a group is in: `leo` (low, below 2,000 km), `meo` (medium, up to about 35,000 km: the navigation satellites), `geo` (about 35,786 km up, where a satellite goes round once
3
+ * a day; over the equator it sits still over one place), `heo` (a long oval that swings far out) or `mixed` (a group with more than one kind).
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import type { OrbitKind } from "@johnmorrisdotca/chikyu-earth/satellites";
8
+ *
9
+ * const sitsStill = (orbit: OrbitKind): boolean => orbit === "geo";
10
+ * console.log(sitsStill("geo"));
11
+ * ```
12
+ */
13
+ export type OrbitKind = "leo" | "meo" | "geo" | "heo" | "mixed";
14
+ /**
15
+ * A group of satellites the demo offers as one button: what it is, in English and Japanese, and where its elements come from (a CelesTrak list name, or single catalogue numbers).
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { SATELLITE_GROUPS } from "@johnmorrisdotca/chikyu-earth/satellites";
20
+ *
21
+ * const gps = SATELLITE_GROUPS.find((group) => group.id === "gps");
22
+ * console.log(gps?.celestrak, gps?.orbit);
23
+ * ```
24
+ */
25
+ export interface SatelliteGroupInfo {
26
+ /** A short name for an address or a button, lower case with hyphens. */
27
+ id: string;
28
+ label: string;
29
+ labelJa: string;
30
+ /** A line on what the group is. */
31
+ about: string;
32
+ aboutJa: string;
33
+ orbit: OrbitKind;
34
+ /** True when the satellites of this group sit still over one place (geostationary), so a reader is not surprised that they do not move. */
35
+ still: boolean;
36
+ /** The name of the CelesTrak list (`GROUP=` in its address) that holds the group, when there is one. */
37
+ celestrak?: string;
38
+ /** Single NORAD catalogue numbers to ask for one by one, when the group has no list of its own. */
39
+ catnr?: readonly number[];
40
+ }
41
+ /**
42
+ * One satellite worth naming: its NORAD catalogue number (the number every source uses), its usual name, the group it is shown in, its orbit and a line on what it is.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * import { CATALOGUE } from "@johnmorrisdotca/chikyu-earth/satellites";
47
+ *
48
+ * const oldest = CATALOGUE.find((entry) => entry.noradId === 5);
49
+ * console.log(oldest?.name, oldest?.about);
50
+ * ```
51
+ */
52
+ export interface CatalogueEntry {
53
+ noradId: number;
54
+ name: string;
55
+ group: string;
56
+ orbit: OrbitKind;
57
+ about: string;
58
+ aboutJa: string;
59
+ }
60
+ /**
61
+ * The groups, in the order the demo shows them. Each one is a CelesTrak list or a few single numbers; the elements are fetched by the page (or the demo's scheduled build), never by the package.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * import { SATELLITE_GROUPS } from "@johnmorrisdotca/chikyu-earth/satellites";
66
+ *
67
+ * console.log(SATELLITE_GROUPS.map((group) => group.label).join(", "));
68
+ * ```
69
+ */
70
+ export declare const SATELLITE_GROUPS: readonly SatelliteGroupInfo[];
71
+ /**
72
+ * The satellites worth naming, with the NORAD number every source uses for them: the stations, the famous ones, and a few of each group.
73
+ * JWST is not here on purpose: it is not in Earth orbit (it circles the Sun about 1.5 million km out, at the second Lagrange point).
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * import { CATALOGUE } from "@johnmorrisdotca/chikyu-earth/satellites";
78
+ *
79
+ * console.log(CATALOGUE.filter((entry) => entry.group === "stations").map((entry) => entry.name));
80
+ * ```
81
+ */
82
+ export declare const CATALOGUE: readonly CatalogueEntry[];
83
+ /**
84
+ * Find catalogue entries by name, group name or NORAD number: "hubble", "hst", "25544" or "weather". Matching ignores case, spaces and punctuation, and a name that starts with the text comes before one that only has it inside.
85
+ *
86
+ * @param text - What the reader typed.
87
+ * @param limit - The most entries to give back (8 by default).
88
+ * @returns The matching entries, best first; none for empty text.
89
+ * @example
90
+ * ```ts
91
+ * import { findInCatalogue } from "@johnmorrisdotca/chikyu-earth/satellites";
92
+ *
93
+ * console.log(findInCatalogue("sentinel 2").map((entry) => entry.name));
94
+ * ```
95
+ */
96
+ export declare function findInCatalogue(text: string, limit?: number): CatalogueEntry[];
97
+ /**
98
+ * The catalogue entry for a NORAD number, if there is one.
99
+ *
100
+ * @param noradId - The NORAD catalogue number.
101
+ * @returns The entry, or undefined when the catalogue does not name that satellite.
102
+ * @example
103
+ * ```ts
104
+ * import { catalogueEntry } from "@johnmorrisdotca/chikyu-earth/satellites";
105
+ *
106
+ * console.log(catalogueEntry(25544)?.about);
107
+ * ```
108
+ */
109
+ export declare function catalogueEntry(noradId: number): CatalogueEntry | undefined;
@@ -0,0 +1,249 @@
1
+ // A small curated catalogue of satellites worth following: the groups the demo offers as buttons and the famous ones by name. Facts (names, NORAD numbers, orbit types) and our own words;
2
+ // no orbital elements are here, and nothing is fetched. The elements come from the page (see docs/satellite-sources.md for the sources and their terms).
3
+ /**
4
+ * The groups, in the order the demo shows them. Each one is a CelesTrak list or a few single numbers; the elements are fetched by the page (or the demo's scheduled build), never by the package.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { SATELLITE_GROUPS } from "@johnmorrisdotca/chikyu-earth/satellites";
9
+ *
10
+ * console.log(SATELLITE_GROUPS.map((group) => group.label).join(", "));
11
+ * ```
12
+ */
13
+ export const SATELLITE_GROUPS = [
14
+ {
15
+ id: "stations",
16
+ label: "Stations",
17
+ labelJa: "宇宙ステーション",
18
+ about: "The ISS and China's Tiangong, with the craft docked to them. Both circle about 400 km up, once round in about 92 minutes.",
19
+ aboutJa: "ISS と中国の天宮、つながっている宇宙船です。どちらも高さ約400 km を、約92分で1周します。",
20
+ orbit: "leo",
21
+ still: false,
22
+ celestrak: "stations",
23
+ },
24
+ {
25
+ id: "famous",
26
+ label: "Famous",
27
+ labelJa: "有名な衛星",
28
+ about: "Vanguard 1 (the oldest satellite still in orbit), Hubble, the Chandra X-ray telescope, LAGEOS 1 and Envisat.",
29
+ aboutJa: "いちばん古い現役の軌道上の衛星バンガード1、ハッブル、チャンドラ X線望遠鏡、LAGEOS 1、エンビサットです。",
30
+ orbit: "mixed",
31
+ still: false,
32
+ catnr: [5, 8820, 20580, 25867, 27386],
33
+ },
34
+ {
35
+ id: "science",
36
+ label: "Science",
37
+ labelJa: "科学衛星",
38
+ about: "Space telescopes and research satellites: Hubble, Swift, Fermi, XMM-Newton, the four MMS craft. A few swing out far beyond the rest.",
39
+ aboutJa: "宇宙望遠鏡や研究用の衛星です。ハッブル、Swift、Fermi、XMM-Newton、MMS の4機など。ほかよりずっと遠くまで行くものもあります。",
40
+ orbit: "mixed",
41
+ still: false,
42
+ celestrak: "science",
43
+ },
44
+ {
45
+ id: "earth-observation",
46
+ label: "Earth observation",
47
+ labelJa: "地球観測",
48
+ about: "Satellites that photograph or measure the land, ice and seas: Landsat 8 and 9, the Sentinels, Terra, Aqua and many more. Most circle from pole to pole at about 700 km.",
49
+ aboutJa: "陸、氷、海を撮影したり測ったりする衛星です。Landsat 8 と 9、Sentinel、Terra、Aqua など。多くは高さ約700 km で、極から極へ回ります。",
50
+ orbit: "leo",
51
+ still: false,
52
+ celestrak: "resource",
53
+ },
54
+ {
55
+ id: "weather",
56
+ label: "Weather",
57
+ labelJa: "気象衛星",
58
+ about: "Weather satellites. The polar ones (NOAA-20 and -21, Metop, Fengyun 3) pass over each place twice a day; the others (GOES, Himawari, Meteosat, Fengyun 2 and 4) hang over the equator and sit still.",
59
+ aboutJa: "気象衛星です。極を回るもの (NOAA-20、-21、Metop、風雲3号) は、同じ場所の上を1日に2回通ります。ほかのもの (GOES、ひまわり、Meteosat、風雲2号と4号) は赤道の上で止まって見えます。",
60
+ orbit: "mixed",
61
+ still: false,
62
+ celestrak: "weather",
63
+ },
64
+ {
65
+ id: "geostationary",
66
+ label: "Geostationary",
67
+ labelJa: "静止衛星",
68
+ about: "Satellites 35,786 km above the equator. They go round once a day, as fast as the Earth turns, so each one sits still over one place.",
69
+ aboutJa: "赤道の上、高さ35,786 km の衛星です。1日に1周して、地球の回る速さと同じなので、1つの場所の上で止まって見えます。",
70
+ orbit: "geo",
71
+ still: true,
72
+ celestrak: "geo",
73
+ },
74
+ {
75
+ id: "gps",
76
+ label: "GPS",
77
+ labelJa: "GPS",
78
+ about: "The American GPS satellites, about 20,200 km up, twice round the Earth a day.",
79
+ aboutJa: "アメリカの GPS 衛星です。高さ約20,200 km で、1日に2周します。",
80
+ orbit: "meo",
81
+ still: false,
82
+ celestrak: "gps-ops",
83
+ },
84
+ {
85
+ id: "glonass",
86
+ label: "GLONASS",
87
+ labelJa: "GLONASS",
88
+ about: "Russia's GLONASS satellites, about 19,100 km up, once round in about 11 hours 15 minutes.",
89
+ aboutJa: "ロシアの GLONASS 衛星です。高さ約19,100 km で、約11時間15分で1周します。",
90
+ orbit: "meo",
91
+ still: false,
92
+ celestrak: "glo-ops",
93
+ },
94
+ {
95
+ id: "galileo",
96
+ label: "Galileo",
97
+ labelJa: "ガリレオ",
98
+ about: "Europe's Galileo satellites, about 23,200 km up, once round in about 14 hours.",
99
+ aboutJa: "ヨーロッパのガリレオ衛星です。高さ約23,200 km で、約14時間で1周します。",
100
+ orbit: "meo",
101
+ still: false,
102
+ celestrak: "galileo",
103
+ },
104
+ {
105
+ id: "beidou",
106
+ label: "BeiDou",
107
+ labelJa: "北斗",
108
+ about: "China's BeiDou satellites. Most are about 21,500 km up; some are geostationary or on tilted orbits that stay near one place.",
109
+ aboutJa: "中国の北斗衛星です。多くは高さ約21,500 km にあります。静止しているものや、傾いた軌道で1つの場所の近くにとどまるものもあります。",
110
+ orbit: "mixed",
111
+ still: false,
112
+ celestrak: "beidou",
113
+ },
114
+ {
115
+ id: "amateur",
116
+ label: "Amateur radio",
117
+ labelJa: "アマチュア無線",
118
+ about: "Satellites built or used by radio amateurs: FUNcube-1, SO-50, RS-44, the Fox satellites, and old ones like OSCAR 7 from 1974.",
119
+ aboutJa: "アマチュア無線の人たちが作ったり使ったりする衛星です。FUNcube-1、SO-50、RS-44、Fox 衛星、1974年の OSCAR 7 などの古いものもあります。",
120
+ orbit: "mixed",
121
+ still: false,
122
+ celestrak: "amateur",
123
+ },
124
+ {
125
+ id: "oneweb",
126
+ label: "OneWeb",
127
+ labelJa: "OneWeb",
128
+ about: "About 650 OneWeb internet satellites, 1,200 km up on orbits that pass near the poles.",
129
+ aboutJa: "インターネット用の OneWeb 衛星、約650機です。高さ1,200 km で、極の近くを通る軌道を回ります。",
130
+ orbit: "leo",
131
+ still: false,
132
+ celestrak: "oneweb",
133
+ },
134
+ {
135
+ id: "iridium",
136
+ label: "Iridium",
137
+ labelJa: "イリジウム",
138
+ about: "The Iridium NEXT satellites for phones and data anywhere on Earth, 780 km up on orbits that pass near the poles.",
139
+ aboutJa: "地球のどこでも電話やデータが使える、イリジウム NEXT の衛星です。高さ780 km で、極の近くを通ります。",
140
+ orbit: "leo",
141
+ still: false,
142
+ celestrak: "iridium-NEXT",
143
+ },
144
+ {
145
+ id: "starlink",
146
+ label: "Starlink",
147
+ labelJa: "Starlink",
148
+ about: "SpaceX's Starlink: thousands of small internet satellites, mostly about 550 km up.",
149
+ aboutJa: "SpaceX の Starlink です。小さなインターネット衛星が何千機もあり、多くは高さ約550 km にあります。",
150
+ orbit: "leo",
151
+ still: false,
152
+ celestrak: "starlink",
153
+ },
154
+ ];
155
+ /**
156
+ * The satellites worth naming, with the NORAD number every source uses for them: the stations, the famous ones, and a few of each group.
157
+ * JWST is not here on purpose: it is not in Earth orbit (it circles the Sun about 1.5 million km out, at the second Lagrange point).
158
+ *
159
+ * @example
160
+ * ```ts
161
+ * import { CATALOGUE } from "@johnmorrisdotca/chikyu-earth/satellites";
162
+ *
163
+ * console.log(CATALOGUE.filter((entry) => entry.group === "stations").map((entry) => entry.name));
164
+ * ```
165
+ */
166
+ export const CATALOGUE = [
167
+ { noradId: 25544, name: "ISS (ZARYA)", group: "stations", orbit: "leo", about: "The International Space Station, lived in without a break since November 2000, about 420 km up and tilted 51.6 degrees.", aboutJa: "国際宇宙ステーション。2000年11月から、ずっと人が滞在しています。高さ約420 km で、傾きは51.6度です。" },
168
+ { noradId: 48274, name: "CSS (TIANHE)", group: "stations", orbit: "leo", about: "Tianhe, the core of China's Tiangong station, tilted 41.5 degrees.", aboutJa: "中国の宇宙ステーション、天宮の中心になる天和です。傾きは41.5度です。" },
169
+ { noradId: 5, name: "VANGUARD 1", group: "famous", orbit: "heo", about: "A grapefruit-sized sphere launched on 17 March 1958: the oldest satellite still in orbit, on a long oval that takes it about 3,800 km out.", aboutJa: "1958年3月17日に打ち上げた、グレープフルーツくらいの球です。今も軌道にある、いちばん古い衛星で、いちばん遠いところは高さ約3,800 km です。" },
170
+ { noradId: 20580, name: "HST", group: "famous", orbit: "leo", about: "The Hubble Space Telescope, in orbit since 1990, about 94 minutes round and tilted 28.5 degrees.", aboutJa: "ハッブル宇宙望遠鏡です。1990年から軌道にあり、約94分で1周します。傾きは28.5度です。" },
171
+ { noradId: 25867, name: "CXO", group: "famous", orbit: "heo", about: "The Chandra X-ray Observatory, launched 1999, on a long oval that swings out to about a third of the way to the Moon.", aboutJa: "チャンドラ X線天文台です。1999年に打ち上げ、月までの約3分の1の遠さまで行く、細長い軌道を回ります。" },
172
+ { noradId: 8820, name: "LAGEOS 1", group: "famous", orbit: "meo", about: "A 60 cm ball covered in mirrors that lasers on the ground bounce light off, to measure the Earth's shape and the slow drift of its continents. Launched 1976.", aboutJa: "地上のレーザーの光を返す鏡で全体をおおった、直径60 cm の球です。地球の形や、大陸のゆっくりした動きを測ります。1976年に打ち上げました。" },
173
+ { noradId: 27386, name: "ENVISAT", group: "famous", orbit: "leo", about: "Europe's Earth-watching satellite, working from 2002 until contact was lost in 2012. Still up there, one of the biggest pieces of space junk.", aboutJa: "ヨーロッパの地球観測衛星です。2002年から働き、2012年に連絡が取れなくなりました。今も軌道にあり、大きな宇宙ごみの1つです。" },
174
+ { noradId: 28485, name: "SWIFT", group: "science", orbit: "leo", about: "NASA's Swift, which turns within a minute to look at gamma-ray bursts, the flashes of exploding stars.", aboutJa: "NASA の Swift です。星の爆発で起こるガンマ線バーストを、1分もかからず向きを変えて見ます。" },
175
+ { noradId: 33053, name: "FGRST (GLAST)", group: "science", orbit: "leo", about: "NASA's Fermi gamma-ray telescope, which maps the whole sky every few hours.", aboutJa: "NASA の Fermi ガンマ線望遠鏡です。数時間ごとに、空全体を調べます。" },
176
+ { noradId: 25989, name: "XMM-NEWTON", group: "science", orbit: "heo", about: "Europe's X-ray telescope, on a long oval orbit that takes it more than 100,000 km out.", aboutJa: "ヨーロッパの X線望遠鏡です。高さ10万 km 以上まで行く、細長い軌道を回ります。" },
177
+ { noradId: 49954, name: "IXPE", group: "science", orbit: "leo", about: "NASA's Imaging X-ray Polarimetry Explorer, which orbits right over the equator.", aboutJa: "NASA の IXPE です。赤道のすぐ上を回ります。" },
178
+ { noradId: 57800, name: "XRISM", group: "science", orbit: "leo", about: "The X-ray satellite JAXA launched in 2023, built with NASA and ESA.", aboutJa: "NASA と ESA といっしょに作り、2023年に JAXA が打ち上げた X線天文衛星です。" },
179
+ { noradId: 36395, name: "SDO", group: "science", orbit: "geo", about: "NASA's Solar Dynamics Observatory, which watches the Sun all day from a tilted orbit that takes a day to go round, so it draws a figure eight over one place.", aboutJa: "NASA の太陽観測衛星です。傾いた軌道を1日で1周して、1つの場所の上で8の字をえがきながら、いつも太陽を見ています。" },
180
+ { noradId: 40482, name: "MMS 1", group: "science", orbit: "heo", about: "One of NASA's four MMS craft that fly in a tight group through the Earth's magnetic field.", aboutJa: "NASA の MMS の4機のうちの1機です。4機は近くに並んで、地球の磁場の中を飛びます。" },
181
+ { noradId: 25994, name: "TERRA", group: "earth-observation", orbit: "leo", about: "NASA's Terra, launched 1999, which crosses the equator on the day side every morning at the same hour.", aboutJa: "1999年に打ち上げた NASA の Terra です。毎日同じ時刻の午前中に、昼間の赤道を通ります。" },
182
+ { noradId: 27424, name: "AQUA", group: "earth-observation", orbit: "leo", about: "NASA's Aqua, Terra's partner, which crosses in the afternoon and watches water in the air, sea and ice.", aboutJa: "Terra の仲間の NASA の Aqua です。午後に通り、空気、海、氷の水を見ています。" },
183
+ { noradId: 39084, name: "LANDSAT 8", group: "earth-observation", orbit: "leo", about: "Landsat 8, part of the longest unbroken record of the Earth's land seen from space, since 1972.", aboutJa: "Landsat 8 です。1972年から続く、宇宙から見た地球の陸の、いちばん長い記録の一部です。" },
184
+ { noradId: 49260, name: "LANDSAT 9", group: "earth-observation", orbit: "leo", about: "Landsat 9, launched 2021, flying half an orbit apart from Landsat 8 so the pair sees any place every eight days.", aboutJa: "2021年に打ち上げた Landsat 9 です。Landsat 8 と半周ずれて飛び、2機で同じ場所を8日ごとに見ます。" },
185
+ { noradId: 40697, name: "SENTINEL-2A", group: "earth-observation", orbit: "leo", about: "One of Europe's Copernicus Sentinel-2 pair that photograph land and coasts in colour.", aboutJa: "ヨーロッパの Copernicus の Sentinel-2 の2機のうちの1機です。陸と海岸をカラーで撮影します。" },
186
+ { noradId: 42063, name: "SENTINEL-2B", group: "earth-observation", orbit: "leo", about: "The other of the Sentinel-2 pair.", aboutJa: "Sentinel-2 の、もう1機です。" },
187
+ { noradId: 39634, name: "SENTINEL-1A", group: "earth-observation", orbit: "leo", about: "A Copernicus radar satellite that sees through cloud and at night.", aboutJa: "雲があっても夜でも見える、Copernicus のレーダー衛星です。" },
188
+ { noradId: 46984, name: "SENTINEL-6A", group: "earth-observation", orbit: "leo", about: "The reference satellite for the height of the sea, higher up than most (about 1,300 km).", aboutJa: "海面の高さを測る基準の衛星です。ほかの多くより高く、約1,300 km にあります。" },
189
+ { noradId: 43613, name: "ICESAT-2", group: "earth-observation", orbit: "leo", about: "NASA's laser satellite that measures the height of ice sheets.", aboutJa: "氷床の高さを測る、NASA のレーザー衛星です。" },
190
+ { noradId: 54754, name: "SWOT", group: "earth-observation", orbit: "leo", about: "A NASA and CNES satellite that measures the height of the water in oceans, lakes and rivers.", aboutJa: "海、湖、川の水面の高さを測る、NASA と CNES の衛星です。" },
191
+ { noradId: 43013, name: "NOAA 20 (JPSS-1)", group: "weather", orbit: "leo", about: "An American polar weather satellite that sees every place on Earth twice a day.", aboutJa: "アメリカの極軌道の気象衛星です。地球のどこでも、1日に2回見ます。" },
192
+ { noradId: 54234, name: "NOAA 21 (JPSS-2)", group: "weather", orbit: "leo", about: "NOAA 20's partner, half an orbit apart.", aboutJa: "NOAA 20 の仲間で、半周ずれて飛びます。" },
193
+ { noradId: 37849, name: "SUOMI NPP", group: "weather", orbit: "leo", about: "The satellite that took the Black Marble night pictures of the Earth's lights.", aboutJa: "地球の夜の明かりの写真、ブラックマーブルを撮った衛星です。" },
194
+ { noradId: 38771, name: "METOP-B", group: "weather", orbit: "leo", about: "One of Europe's Metop polar weather satellites.", aboutJa: "ヨーロッパの極軌道の気象衛星 Metop の1機です。" },
195
+ { noradId: 60133, name: "GOES 19", group: "weather", orbit: "geo", about: "An American weather satellite that sits still over the equator, watching the Americas all day.", aboutJa: "アメリカの気象衛星です。赤道の上で止まって見え、南北アメリカを1日中見ています。" },
196
+ { noradId: 41836, name: "HIMAWARI-9", group: "weather", orbit: "geo", about: "Japan's Himawari (sunflower) weather satellite, sitting still over the western Pacific.", aboutJa: "日本の気象衛星ひまわりです。西太平洋の上で止まって見えます。" },
197
+ { noradId: 54743, name: "METEOSAT-12 (MTG-I1)", group: "weather", orbit: "geo", about: "Europe's newest weather imager, sitting still over the Gulf of Guinea.", aboutJa: "ヨーロッパの新しい気象衛星です。ギニア湾の上で止まって見えます。" },
198
+ { noradId: 41882, name: "FENGYUN 4A", group: "weather", orbit: "geo", about: "A Chinese weather satellite that sits still over the equator.", aboutJa: "赤道の上で止まって見える、中国の気象衛星です。" },
199
+ { noradId: 7530, name: "OSCAR 7 (AO-7)", group: "amateur", orbit: "leo", about: "A radio-amateur satellite launched in 1974 that went silent in 1981 and came back to life in 2002.", aboutJa: "1974年に打ち上げたアマチュア無線の衛星です。1981年に止まり、2002年に動き出しました。" },
200
+ { noradId: 39444, name: "FUNCUBE-1 (AO-73)", group: "amateur", orbit: "leo", about: "A cubesat made for schools, with a radio beacon anyone can listen to.", aboutJa: "学校のために作られた小さな衛星です。だれでも聞ける電波を出しています。" },
201
+ { noradId: 27607, name: "SAUDISAT 1C (SO-50)", group: "amateur", orbit: "leo", about: "A long-lived FM voice repeater that hams use with a handheld radio.", aboutJa: "手持ちの無線機で使える、長く働いている FM の中継衛星です。" },
202
+ { noradId: 44909, name: "RS-44 & BREEZE-KM R/B", group: "amateur", orbit: "leo", about: "A Russian amateur satellite on a higher orbit than most (about 1,500 km), used for long-distance calls.", aboutJa: "ほかより高い、約1,500 km の軌道を回る、ロシアのアマチュア無線の衛星です。遠くの人との交信に使います。" },
203
+ { noradId: 40967, name: "FOX-1A (AO-85)", group: "amateur", orbit: "leo", about: "The first of AMSAT's Fox satellites, built with university students.", aboutJa: "AMSAT の Fox 衛星の1機目です。大学の学生といっしょに作りました。" },
204
+ ];
205
+ /** A name made easy to compare: upper case, letters and digits only. */
206
+ const squash = (text) => text.toUpperCase().replace(/[^A-Z0-9]+/g, "");
207
+ /**
208
+ * Find catalogue entries by name, group name or NORAD number: "hubble", "hst", "25544" or "weather". Matching ignores case, spaces and punctuation, and a name that starts with the text comes before one that only has it inside.
209
+ *
210
+ * @param text - What the reader typed.
211
+ * @param limit - The most entries to give back (8 by default).
212
+ * @returns The matching entries, best first; none for empty text.
213
+ * @example
214
+ * ```ts
215
+ * import { findInCatalogue } from "@johnmorrisdotca/chikyu-earth/satellites";
216
+ *
217
+ * console.log(findInCatalogue("sentinel 2").map((entry) => entry.name));
218
+ * ```
219
+ */
220
+ export function findInCatalogue(text, limit = 8) {
221
+ const wanted = squash(text);
222
+ if (!wanted)
223
+ return [];
224
+ const starts = [];
225
+ const inside = [];
226
+ for (const entry of CATALOGUE) {
227
+ const name = squash(entry.name);
228
+ if (String(entry.noradId) === wanted || name.startsWith(wanted))
229
+ starts.push(entry);
230
+ else if (name.includes(wanted) || squash(entry.group).includes(wanted) || squash(entry.about).includes(wanted))
231
+ inside.push(entry);
232
+ }
233
+ return [...starts, ...inside].slice(0, limit);
234
+ }
235
+ /**
236
+ * The catalogue entry for a NORAD number, if there is one.
237
+ *
238
+ * @param noradId - The NORAD catalogue number.
239
+ * @returns The entry, or undefined when the catalogue does not name that satellite.
240
+ * @example
241
+ * ```ts
242
+ * import { catalogueEntry } from "@johnmorrisdotca/chikyu-earth/satellites";
243
+ *
244
+ * console.log(catalogueEntry(25544)?.about);
245
+ * ```
246
+ */
247
+ export function catalogueEntry(noradId) {
248
+ return CATALOGUE.find((entry) => entry.noradId === noradId);
249
+ }
@@ -1,3 +1,5 @@
1
1
  export { createSatellites, type SatellitesOptions } from "./track.ts";
2
- export { DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.ts";
2
+ export { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.ts";
3
3
  export type { ElementSet, RefusedElementSet, SatelliteInfo, SatelliteRef, Satellites } from "./types.ts";
4
+ export { CATALOGUE, SATELLITE_GROUPS, catalogueEntry, findInCatalogue, type CatalogueEntry, type OrbitKind, type SatelliteGroupInfo } from "./catalogue.ts";
5
+ export { ElementSourceError, fetchElements, forgetElements, parseElements, type ElementFormat, type ElementSource, type FetchElementsOptions, type ParsedElements } from "./source.ts";
@@ -1,3 +1,5 @@
1
1
  // The satellites' pure parts: orbital elements in, positions out (SGP4 by satellite.js, an optional peer). They import on a server. The space view takes a group with `setSatellites`.
2
2
  export { createSatellites } from "./track.js";
3
- export { DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.js";
3
+ export { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.js";
4
+ export { CATALOGUE, SATELLITE_GROUPS, catalogueEntry, findInCatalogue } from "./catalogue.js";
5
+ export { ElementSourceError, fetchElements, forgetElements, parseElements } from "./source.js";
@@ -1,5 +1,5 @@
1
1
  /**
2
- * How old, in days, an element set may be at the moment shown before the satellite is left out: SGP4's error grows by a few kilometres a day, so a fortnight is as far as a picture should trust.
2
+ * How old, in days, an element set may be at the moment shown before the satellite is left out altogether (30 by default). Between `DEFAULT_DIM_AFTER_DAYS` and this the satellite is still placed, but drawn dimmer, because SGP4's error grows by a few kilometres a day.
3
3
  *
4
4
  * @example
5
5
  * ```ts
@@ -8,7 +8,18 @@
8
8
  * console.log(DEFAULT_MAX_AGE_DAYS);
9
9
  * ```
10
10
  */
11
- export declare const DEFAULT_MAX_AGE_DAYS = 14;
11
+ export declare const DEFAULT_MAX_AGE_DAYS = 30;
12
+ /**
13
+ * How old, in days, an element set may be at the moment shown before the satellite is drawn dimmer to say its place is less exact: SGP4's error grows by a few kilometres a day, so a fortnight is as far as a picture should trust it fully.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { DEFAULT_DIM_AFTER_DAYS } from "@johnmorrisdotca/chikyu-earth/satellites";
18
+ *
19
+ * console.log(DEFAULT_DIM_AFTER_DAYS);
20
+ * ```
21
+ */
22
+ export declare const DEFAULT_DIM_AFTER_DAYS = 14;
12
23
  /**
13
24
  * The fastest clock, in game seconds a second, at which the space view still places a group of satellites: above it the two moments SGP4 is run at would be too far apart to interpolate, so the group is hidden rather than drawn wrongly. A satellite that was chosen with `selectSatellite` or ridden along is still placed exactly, one SGP4 call a frame.
14
25
  *
@@ -1,6 +1,6 @@
1
1
  // The satellites' two limits, apart from the SGP4 code so the space view can read them without needing satellite.js.
2
2
  /**
3
- * How old, in days, an element set may be at the moment shown before the satellite is left out: SGP4's error grows by a few kilometres a day, so a fortnight is as far as a picture should trust.
3
+ * How old, in days, an element set may be at the moment shown before the satellite is left out altogether (30 by default). Between `DEFAULT_DIM_AFTER_DAYS` and this the satellite is still placed, but drawn dimmer, because SGP4's error grows by a few kilometres a day.
4
4
  *
5
5
  * @example
6
6
  * ```ts
@@ -9,7 +9,18 @@
9
9
  * console.log(DEFAULT_MAX_AGE_DAYS);
10
10
  * ```
11
11
  */
12
- export const DEFAULT_MAX_AGE_DAYS = 14;
12
+ export const DEFAULT_MAX_AGE_DAYS = 30;
13
+ /**
14
+ * How old, in days, an element set may be at the moment shown before the satellite is drawn dimmer to say its place is less exact: SGP4's error grows by a few kilometres a day, so a fortnight is as far as a picture should trust it fully.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { DEFAULT_DIM_AFTER_DAYS } from "@johnmorrisdotca/chikyu-earth/satellites";
19
+ *
20
+ * console.log(DEFAULT_DIM_AFTER_DAYS);
21
+ * ```
22
+ */
23
+ export const DEFAULT_DIM_AFTER_DAYS = 14;
13
24
  /**
14
25
  * The fastest clock, in game seconds a second, at which the space view still places a group of satellites: above it the two moments SGP4 is run at would be too far apart to interpolate, so the group is hidden rather than drawn wrongly. A satellite that was chosen with `selectSatellite` or ridden along is still placed exactly, one SGP4 call a frame.
15
26
  *
@@ -0,0 +1,155 @@
1
+ import type { ElementSet } from "./types.ts";
2
+ /**
3
+ * The text formats `parseElements` reads: CCSDS OMM as JSON (what CelesTrak's `FORMAT=json` and Space-Track's JSON serve), the same as CSV (CelesTrak's default), and two- or three-line TLE text.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import type { ElementFormat } from "@johnmorrisdotca/chikyu-earth/satellites";
8
+ *
9
+ * const format: ElementFormat = "tle";
10
+ * console.log(format);
11
+ * ```
12
+ */
13
+ export type ElementFormat = "omm-json" | "omm-csv" | "tle";
14
+ /**
15
+ * What `parseElements` found: the element sets that can be used, and the ones it left out with the reason.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import type { ParsedElements } from "@johnmorrisdotca/chikyu-earth/satellites";
20
+ *
21
+ * const count = (parsed: ParsedElements): number => parsed.sets.length;
22
+ * console.log(typeof count);
23
+ * ```
24
+ */
25
+ export interface ParsedElements {
26
+ format: ElementFormat;
27
+ sets: ElementSet[];
28
+ skipped: {
29
+ name: string;
30
+ reason: string;
31
+ }[];
32
+ }
33
+ /**
34
+ * Read element sets from text: OMM as JSON (an array or a single object), OMM as CSV (a header row, then one satellite a row) or TLE (two lines, or three with the name first). The format is found from the text.
35
+ * An element set that is missing a number, has a wrong TLE checksum or is not a possible orbit is left out, with the reason, in `skipped`. It throws if the text is none of the three.
36
+ *
37
+ * @param text - What the source answered.
38
+ * @returns The element sets that can be used and the ones that cannot.
39
+ * @example
40
+ * ```js
41
+ * import { parseElements } from "@johnmorrisdotca/chikyu-earth/satellites";
42
+ *
43
+ * const csv = [
44
+ * "OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,NORAD_CAT_ID,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT",
45
+ * "MADE-UP 1,2026-001A,2026-11-03T12:00:00,15.2,0.0002,53,10,90,20,900001,0.0001,0.00001,0",
46
+ * ].join("\n");
47
+ * const { sets, format } = parseElements(csv);
48
+ * console.log(format, sets.length, sets[0].OBJECT_NAME);
49
+ * ```
50
+ */
51
+ export declare function parseElements(text: string): ParsedElements;
52
+ /**
53
+ * Why a source could not be used: the address was refused before any request, the source answered something other than 200 (and will not be asked again for a while), the answer was too big, or it could not be read.
54
+ *
55
+ * @param message - What went wrong, in a sentence.
56
+ * @param details - The HTTP status the source answered and when it may be asked again, when they are known.
57
+ * @example
58
+ * ```ts
59
+ * import { ElementSourceError } from "@johnmorrisdotca/chikyu-earth/satellites";
60
+ *
61
+ * const error = new ElementSourceError("refused", { status: 403 });
62
+ * console.log(error.status);
63
+ * ```
64
+ */
65
+ export declare class ElementSourceError extends Error {
66
+ /** The HTTP status the source answered, when it answered. */
67
+ readonly status: number | undefined;
68
+ /** When, in milliseconds since the Unix epoch, the source may be asked again (it is not asked before). */
69
+ readonly retryAt: number | undefined;
70
+ constructor(message: string, details?: {
71
+ status?: number;
72
+ retryAt?: number;
73
+ });
74
+ }
75
+ /**
76
+ * What `fetchElements` can be told. Every one has a safe default.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * import type { FetchElementsOptions } from "@johnmorrisdotca/chikyu-earth/satellites";
81
+ *
82
+ * const options: FetchElementsOptions = { minIntervalMs: 3 * 3_600_000 };
83
+ * console.log(options.minIntervalMs);
84
+ * ```
85
+ */
86
+ export interface FetchElementsOptions {
87
+ /** The shortest time between two requests to the same address; within it the answer already read is returned (2 hours by default: CelesTrak's elements change every 2 hours and it asks for one download an update). */
88
+ minIntervalMs?: number;
89
+ /** How long a source that answered anything but 200 (or did not answer) is left alone (1 hour by default). */
90
+ blockedMs?: number;
91
+ /** The most bytes of answer read (20 million by default). */
92
+ maxBytes?: number;
93
+ /** The most element sets kept (50,000 by default). */
94
+ maxSets?: number;
95
+ /** Where answers and refusals are kept between page loads: `localStorage` by default where there is one; `null` keeps them for this page only. */
96
+ store?: Pick<Storage, "getItem" | "setItem" | "removeItem"> | null;
97
+ /** The fetch function (the browser's by default). */
98
+ fetch?: typeof fetch;
99
+ /** The time, in milliseconds since the Unix epoch (`Date.now` by default). */
100
+ now?: () => number;
101
+ signal?: AbortSignal;
102
+ }
103
+ /**
104
+ * Element sets read from a source: where from, when, and whether this answer was kept from earlier rather than asked for now.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * import type { ElementSource } from "@johnmorrisdotca/chikyu-earth/satellites";
109
+ *
110
+ * const describe = (source: ElementSource): string => `${source.sets.length} from ${source.url}, ${source.fromCache ? "kept" : "new"}`;
111
+ * console.log(typeof describe);
112
+ * ```
113
+ */
114
+ export interface ElementSource extends ParsedElements {
115
+ url: string;
116
+ /** When the source was asked, in milliseconds since the Unix epoch. */
117
+ retrievedAt: number;
118
+ fromCache: boolean;
119
+ }
120
+ /**
121
+ * Forget what `fetchElements` kept in this page and which sources it is leaving alone: for a test. It does not clear `localStorage`, and a page that asks again at once is asking against the source's rules.
122
+ *
123
+ * @returns Nothing.
124
+ * @example
125
+ * ```ts
126
+ * import { forgetElements } from "@johnmorrisdotca/chikyu-earth/satellites";
127
+ *
128
+ * forgetElements();
129
+ * console.log("forgotten");
130
+ * ```
131
+ */
132
+ export declare function forgetElements(): void;
133
+ /**
134
+ * Ask a source of your own choosing for element sets, in the visitor's browser, and read them. The package has no address of its own: you pass one, and you are the one to read that source's terms
135
+ * (docs/satellite-sources.md has what CelesTrak, Space-Track and others say). It is polite by design:
136
+ * - only `https` (or `http` on `localhost`), with no cookies and no referrer sent;
137
+ * - the same address is not asked again within `minIntervalMs` (2 hours): the answer already read is returned, from this page or from `localStorage`;
138
+ * - any answer that is not 200, or no answer, stops the asking: the address is left alone for `blockedMs` (1 hour) and a `ElementSourceError` with the status says so (the answer already read, if there is one, is returned instead);
139
+ * - an answer over `maxBytes` or `maxSets` is refused.
140
+ * The source must send the headers a browser needs to let a page read it (CORS); one that does not cannot be read from a page, and no workaround is made here.
141
+ *
142
+ * @param url - The address of OMM JSON, OMM CSV or TLE text.
143
+ * @param options - See `FetchElementsOptions`.
144
+ * @returns The element sets, ready for `createSatellites`, with where and when they came from.
145
+ * @example
146
+ * ```ts no-run
147
+ * import { createSatellites, fetchElements } from "@johnmorrisdotca/chikyu-earth/satellites";
148
+ *
149
+ * // An address you chose, whose terms you have read. This one answers made-up elements.
150
+ * const source = await fetchElements("https://example.org/my-elements.json");
151
+ * const group = createSatellites(source.sets);
152
+ * console.log(group.count, source.skipped.length, source.fromCache);
153
+ * ```
154
+ */
155
+ export declare function fetchElements(url: string, options?: FetchElementsOptions): Promise<ElementSource>;
@@ -0,0 +1,383 @@
1
+ const NUMBERS = ["MEAN_MOTION", "ECCENTRICITY", "INCLINATION", "RA_OF_ASC_NODE", "ARG_OF_PERICENTER", "MEAN_ANOMALY", "NORAD_CAT_ID", "BSTAR", "MEAN_MOTION_DOT", "MEAN_MOTION_DDOT"];
2
+ const OPTIONAL_NUMBERS = ["EPHEMERIS_TYPE", "ELEMENT_SET_NO", "REV_AT_EPOCH"];
3
+ /** A record with the fields of an OMM, from text or numbers, or the reason it is not one. */
4
+ function toElementSet(record) {
5
+ const out = {};
6
+ const name = typeof record["OBJECT_NAME"] === "string" ? record["OBJECT_NAME"].trim() : "";
7
+ out["OBJECT_NAME"] = name || `NORAD ${String(record["NORAD_CAT_ID"] ?? "?")}`;
8
+ if (typeof record["OBJECT_ID"] === "string" && record["OBJECT_ID"])
9
+ out["OBJECT_ID"] = record["OBJECT_ID"];
10
+ if (typeof record["CLASSIFICATION_TYPE"] === "string" && record["CLASSIFICATION_TYPE"])
11
+ out["CLASSIFICATION_TYPE"] = record["CLASSIFICATION_TYPE"];
12
+ const epoch = record["EPOCH"];
13
+ if (typeof epoch !== "string" || !Number.isFinite(Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(epoch) ? epoch : `${epoch}Z`)))
14
+ return "the epoch is missing or is not a date";
15
+ out["EPOCH"] = epoch;
16
+ for (const key of NUMBERS) {
17
+ const value = typeof record[key] === "string" && record[key].trim() !== "" ? Number(record[key]) : record[key];
18
+ if (typeof value !== "number" || !Number.isFinite(value))
19
+ return `${key} is missing or is not a number`;
20
+ out[key] = value;
21
+ }
22
+ for (const key of OPTIONAL_NUMBERS) {
23
+ const value = typeof record[key] === "string" && record[key].trim() !== "" ? Number(record[key]) : record[key];
24
+ if (typeof value === "number" && Number.isFinite(value))
25
+ out[key] = value;
26
+ }
27
+ if (out["MEAN_MOTION"] <= 0)
28
+ return "MEAN_MOTION must be above zero";
29
+ if (out["ECCENTRICITY"] < 0 || out["ECCENTRICITY"] >= 1)
30
+ return "ECCENTRICITY must be from 0 up to (not including) 1";
31
+ return out;
32
+ }
33
+ function fromRecords(records, format) {
34
+ const sets = [];
35
+ const skipped = [];
36
+ for (const record of records) {
37
+ if (record === null || typeof record !== "object" || Array.isArray(record)) {
38
+ skipped.push({ name: "?", reason: "not an object" });
39
+ continue;
40
+ }
41
+ const made = toElementSet(record);
42
+ if (typeof made === "string")
43
+ skipped.push({ name: String(record["OBJECT_NAME"] ?? "?"), reason: made });
44
+ else
45
+ sets.push(made);
46
+ }
47
+ return { format, sets, skipped };
48
+ }
49
+ /** The cells of one CSV line (a cell may be in double quotes, with `""` for a quote). */
50
+ function cellsOf(line) {
51
+ const cells = [];
52
+ let at = 0;
53
+ while (at <= line.length) {
54
+ if (line[at] === '"') {
55
+ let text = "";
56
+ at += 1;
57
+ while (at < line.length) {
58
+ if (line[at] === '"' && line[at + 1] === '"') {
59
+ text += '"';
60
+ at += 2;
61
+ }
62
+ else if (line[at] === '"') {
63
+ at += 1;
64
+ break;
65
+ }
66
+ else
67
+ text += line[at++];
68
+ }
69
+ cells.push(text);
70
+ at += 1;
71
+ }
72
+ else {
73
+ const next = line.indexOf(",", at);
74
+ const end = next < 0 ? line.length : next;
75
+ cells.push(line.slice(at, end));
76
+ at = end + 1;
77
+ }
78
+ }
79
+ return cells;
80
+ }
81
+ /** The checksum of a TLE line: the digits added, each minus sign counting one, modulo 10. */
82
+ const tleChecksum = (line) => {
83
+ let sum = 0;
84
+ for (const ch of line.slice(0, 68))
85
+ sum += ch >= "0" && ch <= "9" ? Number(ch) : ch === "-" ? 1 : 0;
86
+ return sum % 10;
87
+ };
88
+ /** `00000-0` style: a sign, five digits with the point before them, and an exponent. */
89
+ const implied = (text) => {
90
+ const t = text.trim();
91
+ const m = /^([+-]?)(\d+)([+-]\d)$/.exec(t.replace(/^ +/, ""));
92
+ if (!m)
93
+ return Number.NaN;
94
+ return (m[1] === "-" ? -1 : 1) * Number(`0.${m[2]}`) * 10 ** Number(m[3]);
95
+ };
96
+ function fromTle(text) {
97
+ const lines = text.split(/\r?\n/).map((line) => line.replace(/\s+$/, "")).filter((line) => line.trim() !== "");
98
+ const sets = [];
99
+ const skipped = [];
100
+ for (let i = 0; i < lines.length; i += 1) {
101
+ const one = lines[i];
102
+ if (!one.startsWith("1 "))
103
+ continue;
104
+ const two = lines[i + 1];
105
+ const named = i > 0 && !lines[i - 1].startsWith("1 ") && !lines[i - 1].startsWith("2 ") ? lines[i - 1].replace(/^0 /, "").trim() : "";
106
+ const id = Number(one.slice(2, 7));
107
+ const label = named || `NORAD ${id}`;
108
+ if (!two || !two.startsWith("2 ")) {
109
+ skipped.push({ name: label, reason: "the second line is missing" });
110
+ continue;
111
+ }
112
+ i += 1;
113
+ if (one.length < 69 || two.length < 69) {
114
+ skipped.push({ name: label, reason: "a line is shorter than 69 characters" });
115
+ continue;
116
+ }
117
+ if (tleChecksum(one) !== Number(one[68]) || tleChecksum(two) !== Number(two[68])) {
118
+ skipped.push({ name: label, reason: "a line's checksum is wrong" });
119
+ continue;
120
+ }
121
+ if (Number(two.slice(2, 7)) !== id) {
122
+ skipped.push({ name: label, reason: "the two lines are for different satellites" });
123
+ continue;
124
+ }
125
+ const yy = Number(one.slice(18, 20));
126
+ const year = yy < 57 ? 2000 + yy : 1900 + yy;
127
+ const day = Number(one.slice(20, 32));
128
+ const epoch = new Date(Date.UTC(year, 0, 1) + (day - 1) * 86_400_000).toISOString().replace("Z", "");
129
+ const designator = one.slice(9, 17).trim();
130
+ const dy = Number(designator.slice(0, 2));
131
+ const record = {
132
+ OBJECT_NAME: label,
133
+ OBJECT_ID: designator.length >= 5 && Number.isFinite(dy) ? `${dy < 57 ? 2000 + dy : 1900 + dy}-${designator.slice(2)}` : undefined,
134
+ EPOCH: epoch,
135
+ MEAN_MOTION: Number(two.slice(52, 63)),
136
+ ECCENTRICITY: Number(`0.${two.slice(26, 33).trim()}`),
137
+ INCLINATION: Number(two.slice(8, 16)),
138
+ RA_OF_ASC_NODE: Number(two.slice(17, 25)),
139
+ ARG_OF_PERICENTER: Number(two.slice(34, 42)),
140
+ MEAN_ANOMALY: Number(two.slice(43, 51)),
141
+ NORAD_CAT_ID: id,
142
+ BSTAR: implied(one.slice(53, 61)),
143
+ MEAN_MOTION_DOT: Number(one.slice(33, 43)),
144
+ MEAN_MOTION_DDOT: implied(one.slice(44, 52)),
145
+ CLASSIFICATION_TYPE: one[7],
146
+ EPHEMERIS_TYPE: Number(one[62]),
147
+ ELEMENT_SET_NO: Number(one.slice(64, 68)),
148
+ REV_AT_EPOCH: Number(two.slice(63, 68)),
149
+ };
150
+ const made = toElementSet(record);
151
+ if (typeof made === "string")
152
+ skipped.push({ name: label, reason: made });
153
+ else
154
+ sets.push(made);
155
+ }
156
+ return { format: "tle", sets, skipped };
157
+ }
158
+ /**
159
+ * Read element sets from text: OMM as JSON (an array or a single object), OMM as CSV (a header row, then one satellite a row) or TLE (two lines, or three with the name first). The format is found from the text.
160
+ * An element set that is missing a number, has a wrong TLE checksum or is not a possible orbit is left out, with the reason, in `skipped`. It throws if the text is none of the three.
161
+ *
162
+ * @param text - What the source answered.
163
+ * @returns The element sets that can be used and the ones that cannot.
164
+ * @example
165
+ * ```js
166
+ * import { parseElements } from "@johnmorrisdotca/chikyu-earth/satellites";
167
+ *
168
+ * const csv = [
169
+ * "OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,NORAD_CAT_ID,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT",
170
+ * "MADE-UP 1,2026-001A,2026-11-03T12:00:00,15.2,0.0002,53,10,90,20,900001,0.0001,0.00001,0",
171
+ * ].join("\n");
172
+ * const { sets, format } = parseElements(csv);
173
+ * console.log(format, sets.length, sets[0].OBJECT_NAME);
174
+ * ```
175
+ */
176
+ export function parseElements(text) {
177
+ const body = text.replace(/^\uFEFF/, "").trim();
178
+ if (body.startsWith("[") || body.startsWith("{")) {
179
+ let json;
180
+ try {
181
+ json = JSON.parse(body);
182
+ }
183
+ catch {
184
+ throw new Error("the text looks like JSON but is not");
185
+ }
186
+ return fromRecords(Array.isArray(json) ? json : [json], "omm-json");
187
+ }
188
+ const first = body.split(/\r?\n/, 1)[0] ?? "";
189
+ if (/OBJECT_NAME|NORAD_CAT_ID/.test(first) && first.includes(",")) {
190
+ const lines = body.split(/\r?\n/).filter((line) => line.trim() !== "");
191
+ const header = cellsOf(lines[0]).map((cell) => cell.trim());
192
+ return fromRecords(lines.slice(1).map((line) => Object.fromEntries(cellsOf(line).map((cell, index) => [header[index] ?? `#${index}`, cell]))), "omm-csv");
193
+ }
194
+ if (/^\s*(0 .*\n)?1 \d{5}/m.test(body) || /^1 \d{5}/m.test(body))
195
+ return fromTle(body);
196
+ throw new Error("the text is not OMM JSON, OMM CSV or TLE");
197
+ }
198
+ /**
199
+ * Why a source could not be used: the address was refused before any request, the source answered something other than 200 (and will not be asked again for a while), the answer was too big, or it could not be read.
200
+ *
201
+ * @param message - What went wrong, in a sentence.
202
+ * @param details - The HTTP status the source answered and when it may be asked again, when they are known.
203
+ * @example
204
+ * ```ts
205
+ * import { ElementSourceError } from "@johnmorrisdotca/chikyu-earth/satellites";
206
+ *
207
+ * const error = new ElementSourceError("refused", { status: 403 });
208
+ * console.log(error.status);
209
+ * ```
210
+ */
211
+ export class ElementSourceError extends Error {
212
+ /** The HTTP status the source answered, when it answered. */
213
+ status;
214
+ /** When, in milliseconds since the Unix epoch, the source may be asked again (it is not asked before). */
215
+ retryAt;
216
+ constructor(message, details = {}) {
217
+ super(message);
218
+ this.name = "ElementSourceError";
219
+ this.status = details.status;
220
+ this.retryAt = details.retryAt;
221
+ }
222
+ }
223
+ const memory = new Map();
224
+ const blocked = new Map();
225
+ const KEY = "chikyu-earth.elements.";
226
+ const MAX_STORED = 2_000_000;
227
+ const defaultStore = () => {
228
+ try {
229
+ return globalThis.localStorage ?? null;
230
+ }
231
+ catch {
232
+ return null;
233
+ }
234
+ };
235
+ /**
236
+ * Forget what `fetchElements` kept in this page and which sources it is leaving alone: for a test. It does not clear `localStorage`, and a page that asks again at once is asking against the source's rules.
237
+ *
238
+ * @returns Nothing.
239
+ * @example
240
+ * ```ts
241
+ * import { forgetElements } from "@johnmorrisdotca/chikyu-earth/satellites";
242
+ *
243
+ * forgetElements();
244
+ * console.log("forgotten");
245
+ * ```
246
+ */
247
+ export function forgetElements() {
248
+ memory.clear();
249
+ blocked.clear();
250
+ }
251
+ /**
252
+ * Ask a source of your own choosing for element sets, in the visitor's browser, and read them. The package has no address of its own: you pass one, and you are the one to read that source's terms
253
+ * (docs/satellite-sources.md has what CelesTrak, Space-Track and others say). It is polite by design:
254
+ * - only `https` (or `http` on `localhost`), with no cookies and no referrer sent;
255
+ * - the same address is not asked again within `minIntervalMs` (2 hours): the answer already read is returned, from this page or from `localStorage`;
256
+ * - any answer that is not 200, or no answer, stops the asking: the address is left alone for `blockedMs` (1 hour) and a `ElementSourceError` with the status says so (the answer already read, if there is one, is returned instead);
257
+ * - an answer over `maxBytes` or `maxSets` is refused.
258
+ * The source must send the headers a browser needs to let a page read it (CORS); one that does not cannot be read from a page, and no workaround is made here.
259
+ *
260
+ * @param url - The address of OMM JSON, OMM CSV or TLE text.
261
+ * @param options - See `FetchElementsOptions`.
262
+ * @returns The element sets, ready for `createSatellites`, with where and when they came from.
263
+ * @example
264
+ * ```ts no-run
265
+ * import { createSatellites, fetchElements } from "@johnmorrisdotca/chikyu-earth/satellites";
266
+ *
267
+ * // An address you chose, whose terms you have read. This one answers made-up elements.
268
+ * const source = await fetchElements("https://example.org/my-elements.json");
269
+ * const group = createSatellites(source.sets);
270
+ * console.log(group.count, source.skipped.length, source.fromCache);
271
+ * ```
272
+ */
273
+ export async function fetchElements(url, options = {}) {
274
+ const now = options.now ?? Date.now;
275
+ const minInterval = options.minIntervalMs ?? 2 * 3_600_000;
276
+ const blockedMs = options.blockedMs ?? 3_600_000;
277
+ const maxBytes = options.maxBytes ?? 20_000_000;
278
+ const maxSets = options.maxSets ?? 50_000;
279
+ const store = options.store === undefined ? defaultStore() : options.store;
280
+ let address;
281
+ try {
282
+ address = new URL(url);
283
+ }
284
+ catch {
285
+ throw new ElementSourceError("that is not an address");
286
+ }
287
+ const local = address.hostname === "localhost" || address.hostname === "127.0.0.1" || address.hostname === "[::1]";
288
+ if (address.protocol !== "https:" && !(address.protocol === "http:" && local))
289
+ throw new ElementSourceError("only https addresses are used (http only on localhost)");
290
+ const key = address.href;
291
+ const kept = () => {
292
+ const found = memory.get(key);
293
+ if (found)
294
+ return found;
295
+ try {
296
+ const text = store?.getItem(`${KEY}${key}`);
297
+ const at = Number(store?.getItem(`${KEY}${key}.at`));
298
+ if (text && Number.isFinite(at))
299
+ return { at, text };
300
+ }
301
+ catch {
302
+ // storage is not available: this page only
303
+ }
304
+ return undefined;
305
+ };
306
+ const useKept = (found) => {
307
+ const parsed = parseElements(found.text);
308
+ return { ...parsed, url: key, retrievedAt: found.at, fromCache: true };
309
+ };
310
+ const have = kept();
311
+ if (have && now() - have.at < minInterval)
312
+ return useKept(have);
313
+ let until = blocked.get(key) ?? 0;
314
+ try {
315
+ until = Math.max(until, Number(store?.getItem(`${KEY}${key}.until`)) || 0);
316
+ }
317
+ catch {
318
+ // storage is not available
319
+ }
320
+ if (until > now()) {
321
+ if (have)
322
+ return useKept(have);
323
+ throw new ElementSourceError("that source did not answer 200 a short while ago and is being left alone", { retryAt: until });
324
+ }
325
+ const stop = (message, status) => {
326
+ const retryAt = now() + blockedMs;
327
+ blocked.set(key, retryAt);
328
+ try {
329
+ store?.setItem(`${KEY}${key}.until`, String(retryAt));
330
+ }
331
+ catch {
332
+ // storage is full or not available
333
+ }
334
+ return new ElementSourceError(message, { status, retryAt });
335
+ };
336
+ const ask = options.fetch ?? globalThis.fetch;
337
+ let response;
338
+ try {
339
+ response = await ask(key, { method: "GET", credentials: "omit", referrerPolicy: "no-referrer", redirect: "error", signal: options.signal ?? null, headers: { accept: "application/json, text/csv, text/plain" } });
340
+ }
341
+ catch (error) {
342
+ if (options.signal?.aborted)
343
+ throw error;
344
+ if (have)
345
+ return useKept(have);
346
+ throw stop(`the source could not be reached: ${error instanceof Error ? error.message : "no answer"}`);
347
+ }
348
+ if (response.status !== 200) {
349
+ const blockedError = stop(`the source answered ${response.status}, so it is left alone for a while`, response.status);
350
+ if (have)
351
+ return useKept(have);
352
+ throw blockedError;
353
+ }
354
+ const declared = Number(response.headers.get("content-length"));
355
+ if (Number.isFinite(declared) && declared > maxBytes)
356
+ throw new ElementSourceError(`the answer is ${declared} bytes, over the ${maxBytes} allowed`, { status: 200 });
357
+ const text = await response.text();
358
+ if (text.length > maxBytes)
359
+ throw new ElementSourceError(`the answer is over the ${maxBytes} bytes allowed`, { status: 200 });
360
+ let parsed;
361
+ try {
362
+ parsed = parseElements(text);
363
+ }
364
+ catch (error) {
365
+ throw new ElementSourceError(error instanceof Error ? error.message : "the answer could not be read", { status: 200 });
366
+ }
367
+ if (parsed.sets.length > maxSets)
368
+ throw new ElementSourceError(`the answer has ${parsed.sets.length} element sets, over the ${maxSets} allowed`, { status: 200 });
369
+ const at = now();
370
+ memory.set(key, { at, text });
371
+ blocked.delete(key);
372
+ try {
373
+ if (text.length <= MAX_STORED) {
374
+ store?.setItem(`${KEY}${key}`, text);
375
+ store?.setItem(`${KEY}${key}.at`, String(at));
376
+ }
377
+ store?.removeItem(`${KEY}${key}.until`);
378
+ }
379
+ catch {
380
+ // storage is full or not available: this page only
381
+ }
382
+ return { ...parsed, url: key, retrievedAt: at, fromCache: false };
383
+ }
@@ -6,20 +6,22 @@ import type { ElementSet, Satellites } from "./types.ts";
6
6
  * ```ts
7
7
  * import type { SatellitesOptions } from "@johnmorrisdotca/chikyu-earth/satellites";
8
8
  *
9
- * const options: SatellitesOptions = { maxAgeDays: 7 };
9
+ * const options: SatellitesOptions = { dimAfterDays: 7, maxAgeDays: 21 };
10
10
  * console.log(options.maxAgeDays);
11
11
  * ```
12
12
  */
13
13
  export interface SatellitesOptions {
14
- /** The oldest an element set may be at the moment shown, in days (14 by default). */
14
+ /** The oldest an element set may be at the moment shown, in days, before the satellite is left out (30 by default). */
15
15
  maxAgeDays?: number;
16
+ /** The age, in days, past which a satellite is drawn dimmer because its place is less exact (14 by default). */
17
+ dimAfterDays?: number;
16
18
  }
17
19
  /**
18
20
  * Make a group of satellites from their element sets. Each starts SGP4 once here; one that does not (bad numbers, decayed at its own epoch) is listed in `refused` and left out.
19
21
  * It needs satellite.js (MIT, an optional peer dependency) and imports in a browser or on a server.
20
22
  *
21
23
  * @param sets - Element sets in CelesTrak's JSON format (`ElementSet`), fetched by your page.
22
- * @param options - `maxAgeDays`: the oldest an element set may be at the moment shown.
24
+ * @param options - `maxAgeDays`: the oldest an element set may be at the moment shown; `dimAfterDays`: the age past which it is drawn dimmer.
23
25
  * @returns The group: `at(ms, out)` for positions, `exact`, `orbit`, `info`, and counters.
24
26
  *
25
27
  * @example
@@ -1,7 +1,7 @@
1
1
  // SGP4 for a group of satellites, kept cheap: the whole group is run at two moments a step apart and every position in between is an interpolation, so the cost is one batch a step
2
2
  // (about once a second), never one a frame. satellite.js (MIT) does the SGP4 itself; this file never touches the screen and imports on a server.
3
3
  import { json2satrec, sgp4 } from "satellite.js";
4
- import { DEFAULT_MAX_AGE_DAYS } from "./limits.js";
4
+ import { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS } from "./limits.js";
5
5
  /** The Earth's mean radius in kilometres: the unit of every position here (the same as the space view's). */
6
6
  const EARTH_RADIUS_KM = 6371;
7
7
  const DAY_MS = 86_400_000;
@@ -13,7 +13,7 @@ const epochOf = (text) => Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(text) ? text :
13
13
  * It needs satellite.js (MIT, an optional peer dependency) and imports in a browser or on a server.
14
14
  *
15
15
  * @param sets - Element sets in CelesTrak's JSON format (`ElementSet`), fetched by your page.
16
- * @param options - `maxAgeDays`: the oldest an element set may be at the moment shown.
16
+ * @param options - `maxAgeDays`: the oldest an element set may be at the moment shown; `dimAfterDays`: the age past which it is drawn dimmer.
17
17
  * @returns The group: `at(ms, out)` for positions, `exact`, `orbit`, `info`, and counters.
18
18
  *
19
19
  * @example
@@ -44,6 +44,8 @@ const epochOf = (text) => Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(text) ? text :
44
44
  export function createSatellites(sets, options = {}) {
45
45
  const maxAgeDays = options.maxAgeDays ?? DEFAULT_MAX_AGE_DAYS;
46
46
  const maxAgeMs = maxAgeDays * DAY_MS;
47
+ const dimAfterDays = options.dimAfterDays ?? DEFAULT_DIM_AFTER_DAYS;
48
+ const dimAfterMs = dimAfterDays * DAY_MS;
47
49
  const recs = [];
48
50
  const usable = [];
49
51
  const epochs = [];
@@ -76,6 +78,8 @@ export function createSatellites(sets, options = {}) {
76
78
  let okA = new Uint8Array(n);
77
79
  let okB = new Uint8Array(n);
78
80
  const shown = new Uint8Array(n);
81
+ const dimmed = new Float32Array(n);
82
+ let dimVersion = 0;
79
83
  let aMs = 0;
80
84
  let bMs = 0;
81
85
  let ready = false;
@@ -129,6 +133,11 @@ export function createSatellites(sets, options = {}) {
129
133
  sets: usable,
130
134
  refused,
131
135
  maxAgeDays,
136
+ dimAfterDays,
137
+ dimmed,
138
+ get dimVersion() {
139
+ return dimVersion;
140
+ },
132
141
  get propagations() {
133
142
  return propagations;
134
143
  },
@@ -173,6 +182,11 @@ export function createSatellites(sets, options = {}) {
173
182
  let count = 0;
174
183
  for (let i = 0; i < n; i += 1) {
175
184
  const k = i * 3;
185
+ const dim = Math.abs(ms - epochs[i]) > dimAfterMs ? 1 : 0;
186
+ if (dim !== dimmed[i]) {
187
+ dimmed[i] = dim;
188
+ dimVersion += 1;
189
+ }
176
190
  if (okA[i] === 1 && okB[i] === 1) {
177
191
  out[k] = a[k] + (b[k] - a[k]) * t;
178
192
  out[k + 1] = a[k + 1] + (b[k + 1] - a[k + 1]) * t;
@@ -115,7 +115,7 @@ export interface RefusedElementSet {
115
115
  /**
116
116
  * A group of satellites, ready to give positions for any moment: what `createSatellites` returns, and what `<chikyu-space>` takes in `setSatellites`.
117
117
  * Positions are in Earth radii (6371 km) from the Earth's centre, in the space view's axes (x to the vernal equinox, y north); a satellite whose elements
118
- * are older than `maxAgeDays` at the moment asked about is not placed (its place stays at the centre and `visible(index)` is false).
118
+ * are older than `maxAgeDays` at the moment asked about is not placed (its place stays at the centre and `visible(index)` is false); one older than `dimAfterDays` is placed and flagged in `dimmed`.
119
119
  *
120
120
  * @example
121
121
  * ```ts
@@ -134,6 +134,12 @@ export interface Satellites {
134
134
  readonly refused: readonly RefusedElementSet[];
135
135
  /** The oldest an element set may be at the moment shown, in days. */
136
136
  readonly maxAgeDays: number;
137
+ /** The age, in days, past which a satellite is drawn dimmer. */
138
+ readonly dimAfterDays: number;
139
+ /** One number for each satellite, set by `at`: 1 when its elements are more than `dimAfterDays` from the moment shown (draw it dimmer), 0 when not. */
140
+ readonly dimmed: Float32Array;
141
+ /** Goes up each time `at` changes any of `dimmed`, so a drawing can copy the numbers only when they changed. */
142
+ readonly dimVersion: number;
137
143
  /** SGP4 calls made so far, for a page or a test to count. */
138
144
  readonly propagations: number;
139
145
  /** Milliseconds the last batch of SGP4 took, and the longest so far. */
@@ -7,18 +7,22 @@ const ORBIT_REFRESH_GAME_MS = 30 * 60_000;
7
7
  const ORBIT_REFRESH_WALL_MS = 1000;
8
8
  const POINT_VERT = /* glsl */ `
9
9
  uniform float size;
10
+ attribute float dim;
11
+ varying float vDim;
10
12
  void main() {
13
+ vDim = dim;
11
14
  gl_PointSize = size;
12
15
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
13
16
  }`;
14
17
  const POINT_FRAG = /* glsl */ `
15
18
  uniform vec3 tint;
16
19
  uniform float ring;
20
+ varying float vDim;
17
21
  void main() {
18
22
  float d = length(gl_PointCoord - vec2(0.5));
19
23
  if (d > 0.5) discard;
20
24
  float a = ring > 0.5 ? smoothstep(0.30, 0.38, d) * (1.0 - smoothstep(0.44, 0.5, d)) : smoothstep(0.5, 0.2, d);
21
- gl_FragColor = vec4(tint, a);
25
+ gl_FragColor = vec4(tint, a * (1.0 - 0.7 * vDim));
22
26
  }`;
23
27
  export function createSatelliteLayer(three, scene, state, ratio) {
24
28
  if (!three.Points)
@@ -31,6 +35,7 @@ export function createSatelliteLayer(three, scene, state, ratio) {
31
35
  const selectedPosition = new Float32Array(3);
32
36
  const selectedGeometry = new three.BufferGeometry();
33
37
  selectedGeometry.setAttribute("position", new three.BufferAttribute(selectedPosition, 3));
38
+ selectedGeometry.setAttribute("dim", new three.BufferAttribute(new Float32Array(1), 1));
34
39
  const selectedPoints = new Points(selectedGeometry, selectedMaterial);
35
40
  selectedPoints.frustumCulled = false;
36
41
  selectedPoints.renderOrder = 6;
@@ -109,12 +114,14 @@ export function createSatelliteLayer(three, scene, state, ratio) {
109
114
  const geometry = new three.BufferGeometry();
110
115
  const attribute = new three.BufferAttribute(positions, 3);
111
116
  geometry.setAttribute("position", attribute);
117
+ const dim = new three.BufferAttribute(group.satellites.dimmed, 1);
118
+ geometry.setAttribute("dim", dim);
112
119
  const material = new three.ShaderMaterial({ vertexShader: POINT_VERT, fragmentShader: POINT_FRAG, uniforms: { size: { value: group.size * ratio() }, tint: { value: new three.Color(group.color) }, ring: { value: 0 } }, transparent: true, depthWrite: false });
113
120
  const points = new Points(geometry, material);
114
121
  points.frustumCulled = false;
115
122
  points.renderOrder = 5;
116
123
  scene.add(points);
117
- entry = { source: group.satellites, points, geometry, material, positions, attribute, lines: [], linesAt: Number.NaN, linesWall: 0, style: "" };
124
+ entry = { source: group.satellites, points, geometry, material, positions, attribute, dim, dimVersion: -1, lines: [], linesAt: Number.NaN, linesWall: 0, style: "" };
118
125
  drawn.set(name, entry);
119
126
  }
120
127
  const style = `${group.color}|${group.size}|${ratio()}`;
@@ -133,6 +140,10 @@ export function createSatelliteLayer(three, scene, state, ratio) {
133
140
  group.satellites.setStep(step);
134
141
  group.satellites.at(time, entry.positions);
135
142
  entry.attribute.needsUpdate = true;
143
+ if (entry.dimVersion !== group.satellites.dimVersion) {
144
+ entry.dimVersion = group.satellites.dimVersion;
145
+ entry.dim.needsUpdate = true;
146
+ }
136
147
  placed += group.satellites.placed;
137
148
  orbitsOf(entry, group, time, started);
138
149
  }
@@ -230,6 +230,7 @@ export function createSpaceItem(model, deps) {
230
230
  planets.set(name, { slot: newSlot(name), orbit, positions, samples: [], epoch: Number.NaN, toSun: [1, 0, 0] });
231
231
  }
232
232
  const moonSlots = new Map();
233
+ let releaseTimer;
233
234
  let layer;
234
235
  const rideState = new Float64Array(6);
235
236
  let selectedShown = false;
@@ -499,6 +500,7 @@ export function createSpaceItem(model, deps) {
499
500
  drawing.update?.({ toSun: p.toSun, ms: model.time, radiusPx: moonPx });
500
501
  }
501
502
  }
503
+ let soonest = Number.POSITIVE_INFINITY;
502
504
  for (const [key, held] of moonSlots) {
503
505
  if (seen.has(key))
504
506
  continue;
@@ -508,7 +510,13 @@ export function createSpaceItem(model, deps) {
508
510
  empty(held.slot);
509
511
  moonSlots.delete(key);
510
512
  }
513
+ else
514
+ soonest = Math.min(soonest, held.seen + MOON_KEEP_MS - now);
511
515
  }
516
+ // a view that is at rest draws nothing, so a moon that has gone from the view would be kept for ever: ask for one more draw when the first of them is due to be let go
517
+ if (releaseTimer !== undefined)
518
+ clearTimeout(releaseTimer);
519
+ releaseTimer = soonest < Number.POSITIVE_INFINITY ? setTimeout(() => deps.invalidate(), soonest + 50) : undefined;
512
520
  }
513
521
  const ratio = model.ratio();
514
522
  const earthPx = Math.min(px.Earth, 1e5) * ratio;
@@ -537,6 +545,8 @@ export function createSpaceItem(model, deps) {
537
545
  size = { width: w, height: h };
538
546
  },
539
547
  dispose() {
548
+ if (releaseTimer !== undefined)
549
+ clearTimeout(releaseTimer);
540
550
  layer?.dispose();
541
551
  model.pick = null;
542
552
  textures.dispose();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnmorrisdotca/chikyu-earth",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Chikyu Earth 地球 — A line-drawn globe for the web: country outlines that turn at the Earth's own rate, centred on where you are, with an optional realistic Earth from space (three.js), the Sun, Moon and planets, satellites on their orbits, and markers for any place. A web component and an SVG string.",
5
5
  "keywords": [
6
6
  "earth",