@loksly/weather-astro 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Loksly
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @loksly/weather-astro
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Weather, moon phase and sunrise/sunset for small always-on displays. No
4
+ dependencies, no API keys, no drawing.
5
+
6
+ - **Weather** from [Open-Meteo](https://open-meteo.com/) (free, no key): current
7
+ conditions, the next 48 hours and a seven-day forecast, in metric or imperial
8
+ units, with WMO codes mapped to a
9
+ small set of icons. A tiny file cache keeps the last good reading so a network
10
+ outage does not blank your screen.
11
+ - **Moon phase**, computed locally (no network), with the eight usual phase names.
12
+ - **Sunrise and sunset**, computed locally with NOAA's equation.
13
+
14
+ Text descriptions are deliberately left out: the library returns codes and
15
+ icon kinds, and your app words them in its own language.
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npm install @loksly/weather-astro
21
+ ```
22
+
23
+ Node.js 20 or newer. ESM only.
24
+
25
+ ## Usage
26
+
27
+ ```ts
28
+ import { fetchWeather, iconFor, saveWeather, loadWeather, moonPhase, sunTimes } from '@loksly/weather-astro';
29
+
30
+ const place = { name: 'Madrid', latitude: 40.4168, longitude: -3.7038 };
31
+
32
+ const w = (await fetchWeather(place, 10_000)) ?? loadWeather('/tmp/weather.json');
33
+ if (w) {
34
+ saveWeather('/tmp/weather.json', w);
35
+ console.log(w.temp, iconFor(w.code, w.night)); // 21 'sun-cloud'
36
+ }
37
+
38
+ const moon = moonPhase(); // { phase, illumination, waxing, name: 'waxing-gibbous', daysToFull, daysToNew }
39
+ const sun = sunTimes(new Date(), place.latitude, place.longitude); // { rise: 7.9, set: 19.4 } in local decimal hours
40
+ ```
41
+
42
+ ### API
43
+
44
+ | Export | What it does |
45
+ |---|---|
46
+ | `fetchWeather(place, timeoutMs \| { timeoutMs, signal?, units? }, log?)` | Reads Open-Meteo: now, 48 hours (`HOURS_AHEAD`) and 7 days (`FORECAST_DAYS`). `units: 'imperial'` gives °F and mph. Never throws: `null` on failure. |
47
+ | `openMeteoUrl(place, units?)` | The address it reads. |
48
+ | `parseOpenMeteo(raw, place, now?)` | The parser behind it, for your own fetch. |
49
+ | `iconFor(code, night?)` | WMO code → `IconKind` (`sun`, `moon`, `sun-cloud`, `moon-cloud`, `cloud`, `fog`, `drizzle`, `rain`, `snow`, `storm`). |
50
+ | `saveWeather(path, w)` / `loadWeather(path, now?)` | Atomic file cache. `loadWeather` drops readings older than `MAX_AGE_MS` (6 h). |
51
+ | `moonPhase(at?)` | Phase 0..1, lit fraction, waxing, name and days to the next full and new moon. |
52
+ | `sunTimes(date, lat, lon)` | Sunrise and sunset in local decimal hours, or `null` near the poles. |
53
+
54
+ ## Accuracy
55
+
56
+ The moon model ignores orbital perturbations and can be a few hours off real
57
+ ephemerides. Sunrise and sunset are within a couple of minutes at mid latitudes.
58
+
59
+ ## Contributing
60
+
61
+ This package lives in the [aimonitor](https://github.com/Loksly/aimonitor)
62
+ repository under `packages/weather-astro`. Issues and pull requests are
63
+ welcome there. Run `npm test` from the package directory.
64
+
65
+ ## License
66
+
67
+ MIT
@@ -0,0 +1,3 @@
1
+ export * from './weather.ts';
2
+ export * from './moon.ts';
3
+ export * from './sun.ts';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./weather.js";
2
+ export * from "./moon.js";
3
+ export * from "./sun.js";
package/dist/moon.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Moon phase, computed locally.
3
+ *
4
+ * Deterministic arithmetic: elapsed time since a known new moon, modulo the
5
+ * mean synodic month. It ignores orbital perturbations, so it can be a few
6
+ * hours off real ephemerides; plenty for "waning quarter, full in eleven days".
7
+ * Checked against Open-Meteo on 2026-09-04: 0.751 here, 0.753 there.
8
+ */
9
+ /** Mean synodic month: new moon to new moon, in days. */
10
+ export declare const SYNODIC = 29.530588853;
11
+ /** The eight usual phase names, in order from new moon. */
12
+ export declare const PHASE_NAMES: readonly ["new", "waxing-crescent", "first-quarter", "waxing-gibbous", "full", "waning-gibbous", "last-quarter", "waning-crescent"];
13
+ export type PhaseName = (typeof PHASE_NAMES)[number];
14
+ export interface Moon {
15
+ /** 0 = new moon, 0.5 = full, almost 1 = new again. */
16
+ phase: number;
17
+ /** Lit fraction of the disc, 0 to 1. */
18
+ illumination: number;
19
+ /** Growing? Before full it waxes, after full it wanes. */
20
+ waxing: boolean;
21
+ /** Nearest of the eight named phases (so "full" covers the day before and after). */
22
+ name: PhaseName;
23
+ /** Days to the next full moon (0 if today). */
24
+ daysToFull: number;
25
+ /** Days to the next new moon. */
26
+ daysToNew: number;
27
+ }
28
+ /** The moon at an instant. */
29
+ export declare function moonPhase(at?: number | Date): Moon;
package/dist/moon.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Moon phase, computed locally.
3
+ *
4
+ * Deterministic arithmetic: elapsed time since a known new moon, modulo the
5
+ * mean synodic month. It ignores orbital perturbations, so it can be a few
6
+ * hours off real ephemerides; plenty for "waning quarter, full in eleven days".
7
+ * Checked against Open-Meteo on 2026-09-04: 0.751 here, 0.753 there.
8
+ */
9
+ /** Mean synodic month: new moon to new moon, in days. */
10
+ export const SYNODIC = 29.530588853;
11
+ /** Reference new moon: 2000-01-06 18:14 UTC, the usual epoch for this calculation. */
12
+ const REFERENCE_NEW_MOON = Date.UTC(2000, 0, 6, 18, 14, 0);
13
+ /** The eight usual phase names, in order from new moon. */
14
+ export const PHASE_NAMES = [
15
+ 'new',
16
+ 'waxing-crescent',
17
+ 'first-quarter',
18
+ 'waxing-gibbous',
19
+ 'full',
20
+ 'waning-gibbous',
21
+ 'last-quarter',
22
+ 'waning-crescent',
23
+ ];
24
+ /** Days elapsed since the reference new moon. */
25
+ function daysSinceReference(at) {
26
+ return (at - REFERENCE_NEW_MOON) / 86_400_000;
27
+ }
28
+ /** The moon at an instant. */
29
+ export function moonPhase(at = Date.now()) {
30
+ const ms = at instanceof Date ? at.getTime() : at;
31
+ // JS's % keeps the sign, so dates before 2000 are normalised by adding a cycle.
32
+ const phase = (((daysSinceReference(ms) % SYNODIC) + SYNODIC) % SYNODIC) / SYNODIC;
33
+ const illumination = (1 - Math.cos(2 * Math.PI * phase)) / 2;
34
+ const waxing = phase < 0.5;
35
+ // Nearest eighth, wrapping round: 0.97 is "new", not "waning crescent".
36
+ const name = PHASE_NAMES[Math.round(phase * 8) % 8] ?? 'new';
37
+ const toFull = phase <= 0.5 ? 0.5 - phase : 1.5 - phase;
38
+ const toNew = phase === 0 ? 0 : 1 - phase;
39
+ return {
40
+ phase,
41
+ illumination,
42
+ waxing,
43
+ name,
44
+ daysToFull: Math.round(toFull * SYNODIC),
45
+ daysToNew: Math.round(toNew * SYNODIC),
46
+ };
47
+ }
package/dist/sun.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export interface SunTimes {
2
+ /** Local time as decimal hours (7.5 = 7:30), in the machine's time zone. */
3
+ rise: number;
4
+ set: number;
5
+ }
6
+ /** Sunrise and sunset on the day of `date` at a place, or null if the sun does not rise or set. */
7
+ export declare function sunTimes(date: Date, lat: number, lon: number): SunTimes | null;
package/dist/sun.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Sunrise and sunset, computed locally with NOAA's equation (the one behind
3
+ * its solar calculator). No network needed.
4
+ *
5
+ * Accuracy: a couple of minutes at mid latitudes. Near the poles there may be
6
+ * no sunrise or sunset; then `sunTimes` returns null.
7
+ */
8
+ const RAD = Math.PI / 180;
9
+ /** UTC minutes of sunrise and sunset for the UTC day of `date`. */
10
+ function utcMinutes(date, lat, lon) {
11
+ const start = Date.UTC(date.getUTCFullYear(), 0, 1);
12
+ const day = Math.floor((Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()) - start) / 86_400_000) + 1;
13
+ const g = ((2 * Math.PI) / 365) * (day - 1);
14
+ const eq = 229.18 * (0.000075 + 0.001868 * Math.cos(g) - 0.032077 * Math.sin(g) - 0.014615 * Math.cos(2 * g) - 0.040849 * Math.sin(2 * g));
15
+ const decl = 0.006918 - 0.399912 * Math.cos(g) + 0.070257 * Math.sin(g) - 0.006758 * Math.cos(2 * g) + 0.000907 * Math.sin(2 * g) - 0.002697 * Math.cos(3 * g) + 0.00148 * Math.sin(3 * g);
16
+ // 90.833°: the whole disc below the horizon, allowing for atmospheric refraction.
17
+ const cosH = Math.cos(90.833 * RAD) / (Math.cos(lat * RAD) * Math.cos(decl)) - Math.tan(lat * RAD) * Math.tan(decl);
18
+ if (cosH < -1 || cosH > 1)
19
+ return null;
20
+ const h = Math.acos(cosH) / RAD;
21
+ return { rise: 720 - 4 * (lon + h) - eq, set: 720 - 4 * (lon - h) - eq };
22
+ }
23
+ /** Sunrise and sunset on the day of `date` at a place, or null if the sun does not rise or set. */
24
+ export function sunTimes(date, lat, lon) {
25
+ const m = utcMinutes(date, lat, lon);
26
+ if (!m)
27
+ return null;
28
+ // To local time on that day, with its summer or winter offset.
29
+ const toLocal = (min) => {
30
+ const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()) + min * 60_000);
31
+ return d.getHours() + d.getMinutes() / 60 + d.getSeconds() / 3600;
32
+ };
33
+ return { rise: toLocal(m.rise), set: toLocal(m.set) };
34
+ }
@@ -0,0 +1,121 @@
1
+ /** A reading older than this no longer describes the street outside. */
2
+ export declare const MAX_AGE_MS: number;
3
+ /** Icon for a weather code; `sun`/`moon` variants depend on the time of day. */
4
+ export type IconKind = 'sun' | 'moon' | 'sun-cloud' | 'moon-cloud' | 'cloud' | 'fog' | 'drizzle' | 'rain' | 'snow' | 'storm';
5
+ export interface DayForecast {
6
+ /** ISO date (YYYY-MM-DD). */
7
+ date: string;
8
+ /** WMO weather code. */
9
+ code: number;
10
+ min: number;
11
+ max: number;
12
+ /** Probability of precipitation, in %. */
13
+ rain: number;
14
+ }
15
+ export interface HourForecast {
16
+ /** Local time at the place, "HH:MM". */
17
+ label: string;
18
+ temp: number;
19
+ /** Probability of precipitation, in %. */
20
+ rain: number;
21
+ }
22
+ /** `metric` (°C, km/h, Open-Meteo's default) or `imperial` (°F, mph). */
23
+ export type Units = 'metric' | 'imperial';
24
+ export interface Weather {
25
+ place: string;
26
+ /** Coordinates of the reading, when the provider returned them. */
27
+ latitude?: number;
28
+ longitude?: number;
29
+ temp: number;
30
+ /** Apparent ("feels like") temperature. */
31
+ feels: number;
32
+ /** WMO weather code. */
33
+ code: number;
34
+ humidity: number;
35
+ wind: number;
36
+ /** Units of `temp`, `feels`, `days`, `hours` and `wind`; absent means `metric`. */
37
+ units?: Units;
38
+ /** Is it night at the place? Turns sun icons into moon icons. */
39
+ night: boolean;
40
+ days: DayForecast[];
41
+ /** The next hours, starting with the current one. */
42
+ hours: HourForecast[];
43
+ /** When it was read, ms epoch. */
44
+ fetched: number;
45
+ }
46
+ /**
47
+ * WMO codes → icon. Codes not listed are not emitted by this endpoint.
48
+ * Text descriptions are left to the caller, in its own language.
49
+ */
50
+ export declare const WMO_ICON: Readonly<Record<number, IconKind>>;
51
+ /** Icon for a code, swapping the sun for the moon at night. */
52
+ export declare function iconFor(code: number, night?: boolean): IconKind;
53
+ /** The subset of Open-Meteo's response that is read. */
54
+ export interface OpenMeteo {
55
+ latitude?: number;
56
+ longitude?: number;
57
+ current?: {
58
+ time?: string;
59
+ temperature_2m?: number;
60
+ apparent_temperature?: number;
61
+ weather_code?: number;
62
+ relative_humidity_2m?: number;
63
+ wind_speed_10m?: number;
64
+ };
65
+ daily?: {
66
+ time?: string[];
67
+ weather_code?: number[];
68
+ temperature_2m_max?: number[];
69
+ temperature_2m_min?: number[];
70
+ precipitation_probability_max?: number[];
71
+ };
72
+ hourly?: {
73
+ time?: string[];
74
+ temperature_2m?: number[];
75
+ precipitation_probability?: number[];
76
+ };
77
+ }
78
+ /** How many hourly entries `parseOpenMeteo` keeps: two days, enough to see tomorrow from tonight. */
79
+ export declare const HOURS_AHEAD = 48;
80
+ /** Days of daily forecast asked for, today included: a week. */
81
+ export declare const FORECAST_DAYS = 7;
82
+ /**
83
+ * Trims the hourly series so that it starts at the current hour.
84
+ *
85
+ * The API returns the whole day from 00:00. ISO strings are compared as text
86
+ * ("2026-09-04T14" sorts the same as a date), which avoids building `Date`s and
87
+ * time-zone mistakes: the place may be in a different zone than the computer.
88
+ */
89
+ export declare function sliceHours(times: string[], temps: number[], rains: number[], currentIso: string, count?: number): HourForecast[];
90
+ /**
91
+ * Is it night? Decided with the local time the API itself returns, in the
92
+ * place's zone, not the computer's.
93
+ */
94
+ export declare function isNight(localTime: string | undefined): boolean;
95
+ /** Turns an Open-Meteo response into a `Weather`, or null if it has no current data. */
96
+ export declare function parseOpenMeteo(raw: OpenMeteo, place: string, now?: number): Weather | null;
97
+ export interface WeatherPlace {
98
+ name: string;
99
+ latitude: number;
100
+ longitude: number;
101
+ }
102
+ export interface FetchWeatherOptions {
103
+ /** Longest the request may take. */
104
+ timeoutMs: number;
105
+ /** Aborts the request early (the caller stopped). */
106
+ signal?: AbortSignal;
107
+ /** Default `metric`. */
108
+ units?: Units;
109
+ }
110
+ /** The Open-Meteo address for a place: now, the next `HOURS_AHEAD` hours and `FORECAST_DAYS` days. */
111
+ export declare function openMeteoUrl(place: Pick<WeatherPlace, 'latitude' | 'longitude'>, units?: Units): string;
112
+ /**
113
+ * Reads the current weather, the next two days hour by hour and a week of
114
+ * daily forecast. Never throws: null on failure. The second argument is the
115
+ * timeout in ms, or `{ timeoutMs, signal, units }`.
116
+ */
117
+ export declare function fetchWeather(place: WeatherPlace, options: number | FetchWeatherOptions, log?: (msg: string) => void): Promise<Weather | null>;
118
+ /** Atomic write, so that no reader ever sees half a JSON file. */
119
+ export declare function saveWeather(path: string, w: Weather): void;
120
+ /** The last reading saved at `path`, or null if missing, invalid or older than `MAX_AGE_MS`. */
121
+ export declare function loadWeather(path: string, now?: number): Weather | null;
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Weather from Open-Meteo.
3
+ *
4
+ * Why Open-Meteo: it needs **no API key**, which rules out almost every other
5
+ * provider, and it returns plain JSON with standard WMO weather codes, so
6
+ * turning a reading into an icon is a lookup table.
7
+ *
8
+ * The on-disk cache (`saveWeather`/`loadWeather`) is not an optimisation: it
9
+ * keeps the last good reading so that a network outage does not blank the
10
+ * screen. Readings older than six hours are dropped instead of being shown as
11
+ * if they were current.
12
+ */
13
+ import { readFileSync, renameSync, writeFileSync } from 'node:fs';
14
+ /** A reading older than this no longer describes the street outside. */
15
+ export const MAX_AGE_MS = 6 * 3600_000;
16
+ /**
17
+ * WMO codes → icon. Codes not listed are not emitted by this endpoint.
18
+ * Text descriptions are left to the caller, in its own language.
19
+ */
20
+ export const WMO_ICON = {
21
+ 0: 'sun', 1: 'sun-cloud', 2: 'sun-cloud', 3: 'cloud',
22
+ 45: 'fog', 48: 'fog',
23
+ 51: 'drizzle', 53: 'drizzle', 55: 'drizzle', 56: 'drizzle', 57: 'drizzle',
24
+ 61: 'rain', 63: 'rain', 65: 'rain', 66: 'rain', 67: 'rain',
25
+ 71: 'snow', 73: 'snow', 75: 'snow', 77: 'snow',
26
+ 80: 'rain', 81: 'rain', 82: 'rain',
27
+ 85: 'snow', 86: 'snow',
28
+ 95: 'storm', 96: 'storm', 99: 'storm',
29
+ };
30
+ /** Icon for a code, swapping the sun for the moon at night. */
31
+ export function iconFor(code, night = false) {
32
+ const icon = WMO_ICON[code] ?? 'cloud';
33
+ if (!night)
34
+ return icon;
35
+ if (icon === 'sun')
36
+ return 'moon';
37
+ if (icon === 'sun-cloud')
38
+ return 'moon-cloud';
39
+ return icon;
40
+ }
41
+ /** How many hourly entries `parseOpenMeteo` keeps: two days, enough to see tomorrow from tonight. */
42
+ export const HOURS_AHEAD = 48;
43
+ /** Days of daily forecast asked for, today included: a week. */
44
+ export const FORECAST_DAYS = 7;
45
+ /**
46
+ * Trims the hourly series so that it starts at the current hour.
47
+ *
48
+ * The API returns the whole day from 00:00. ISO strings are compared as text
49
+ * ("2026-09-04T14" sorts the same as a date), which avoids building `Date`s and
50
+ * time-zone mistakes: the place may be in a different zone than the computer.
51
+ */
52
+ export function sliceHours(times, temps, rains, currentIso, count = HOURS_AHEAD) {
53
+ const key = currentIso.slice(0, 13);
54
+ let start = times.findIndex((t) => t.slice(0, 13) >= key);
55
+ if (start < 0)
56
+ start = 0;
57
+ const out = [];
58
+ for (let i = start; i < times.length && out.length < count; i += 1) {
59
+ const t = times[i];
60
+ if (t === undefined)
61
+ continue;
62
+ out.push({
63
+ label: t.slice(11, 16),
64
+ temp: Math.round(temps[i] ?? 0),
65
+ rain: Math.round(rains[i] ?? 0),
66
+ });
67
+ }
68
+ return out;
69
+ }
70
+ /**
71
+ * Is it night? Decided with the local time the API itself returns, in the
72
+ * place's zone, not the computer's.
73
+ */
74
+ export function isNight(localTime) {
75
+ const hour = Number.parseInt(localTime?.slice(11, 13) ?? '', 10);
76
+ if (!Number.isFinite(hour))
77
+ return false;
78
+ return hour < 7 || hour >= 21;
79
+ }
80
+ /** Turns an Open-Meteo response into a `Weather`, or null if it has no current data. */
81
+ export function parseOpenMeteo(raw, place, now = Date.now()) {
82
+ const c = raw.current;
83
+ if (!c || typeof c.temperature_2m !== 'number')
84
+ return null;
85
+ const d = raw.daily;
86
+ const days = [];
87
+ for (let i = 0; i < (d?.time?.length ?? 0); i += 1) {
88
+ days.push({
89
+ date: d?.time?.[i] ?? '',
90
+ code: d?.weather_code?.[i] ?? 0,
91
+ min: Math.round(d?.temperature_2m_min?.[i] ?? 0),
92
+ max: Math.round(d?.temperature_2m_max?.[i] ?? 0),
93
+ rain: Math.round(d?.precipitation_probability_max?.[i] ?? 0),
94
+ });
95
+ }
96
+ const h = raw.hourly;
97
+ const hours = h?.time
98
+ ? sliceHours(h.time, h.temperature_2m ?? [], h.precipitation_probability ?? [], c.time ?? '')
99
+ : [];
100
+ return {
101
+ place,
102
+ ...(typeof raw.latitude === 'number' && typeof raw.longitude === 'number' ? { latitude: raw.latitude, longitude: raw.longitude } : {}),
103
+ temp: Math.round(c.temperature_2m),
104
+ feels: Math.round(c.apparent_temperature ?? c.temperature_2m),
105
+ code: c.weather_code ?? 0,
106
+ humidity: Math.round(c.relative_humidity_2m ?? 0),
107
+ wind: Math.round(c.wind_speed_10m ?? 0),
108
+ night: isNight(c.time),
109
+ days,
110
+ hours,
111
+ fetched: now,
112
+ };
113
+ }
114
+ /** The Open-Meteo address for a place: now, the next `HOURS_AHEAD` hours and `FORECAST_DAYS` days. */
115
+ export function openMeteoUrl(place, units = 'metric') {
116
+ return ('https://api.open-meteo.com/v1/forecast' +
117
+ `?latitude=${place.latitude}&longitude=${place.longitude}` +
118
+ '&current=temperature_2m,apparent_temperature,weather_code,relative_humidity_2m,wind_speed_10m' +
119
+ '&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max' +
120
+ '&hourly=temperature_2m,precipitation_probability' +
121
+ (units === 'imperial' ? '&temperature_unit=fahrenheit&wind_speed_unit=mph' : '') +
122
+ `&timezone=auto&forecast_days=${FORECAST_DAYS}`);
123
+ }
124
+ /**
125
+ * Reads the current weather, the next two days hour by hour and a week of
126
+ * daily forecast. Never throws: null on failure. The second argument is the
127
+ * timeout in ms, or `{ timeoutMs, signal, units }`.
128
+ */
129
+ export async function fetchWeather(place, options, log = () => { }) {
130
+ const o = typeof options === 'number' ? { timeoutMs: options } : options;
131
+ const timeout = AbortSignal.timeout(o.timeoutMs);
132
+ try {
133
+ const res = await fetch(openMeteoUrl(place, o.units), { signal: o.signal ? AbortSignal.any([o.signal, timeout]) : timeout });
134
+ if (!res.ok)
135
+ throw new Error(`HTTP ${res.status}`);
136
+ const parsed = parseOpenMeteo((await res.json()), place.name);
137
+ if (!parsed)
138
+ throw new Error('response without current data');
139
+ return o.units === 'imperial' ? { ...parsed, units: 'imperial' } : parsed;
140
+ }
141
+ catch (err) {
142
+ log(`weather: failed (${err instanceof Error ? err.message : String(err)})`);
143
+ return null;
144
+ }
145
+ }
146
+ /** Atomic write, so that no reader ever sees half a JSON file. */
147
+ export function saveWeather(path, w) {
148
+ const tmp = `${path}.tmp`;
149
+ writeFileSync(tmp, JSON.stringify(w));
150
+ renameSync(tmp, path);
151
+ }
152
+ /** The last reading saved at `path`, or null if missing, invalid or older than `MAX_AGE_MS`. */
153
+ export function loadWeather(path, now = Date.now()) {
154
+ try {
155
+ const w = JSON.parse(readFileSync(path, 'utf8'));
156
+ if (typeof w?.temp !== 'number' || typeof w.fetched !== 'number')
157
+ return null;
158
+ return now - w.fetched > MAX_AGE_MS ? null : w;
159
+ }
160
+ catch {
161
+ return null;
162
+ }
163
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@loksly/weather-astro",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Weather from Open-Meteo (no API key), moon phase and sunrise/sunset, with no dependencies and no drawing.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Loksly",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Loksly/aimonitor.git",
11
+ "directory": "packages/weather-astro"
12
+ },
13
+ "keywords": [
14
+ "weather",
15
+ "open-meteo",
16
+ "moon",
17
+ "moon-phase",
18
+ "sunrise",
19
+ "sunset"
20
+ ],
21
+ "exports": {
22
+ ".": {
23
+ "source": "./src/index.ts",
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "src",
31
+ "!src/**/*.test.ts",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "engines": {
36
+ "node": ">=20"
37
+ },
38
+ "scripts": {
39
+ "build": "tsc -p tsconfig.json",
40
+ "test": "node --conditions=source --import tsx --test 'src/**/*.test.ts'",
41
+ "check": "tsc -p tsconfig.json --noEmit"
42
+ }
43
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './weather.ts';
2
+ export * from './moon.ts';
3
+ export * from './sun.ts';
package/src/moon.ts ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Moon phase, computed locally.
3
+ *
4
+ * Deterministic arithmetic: elapsed time since a known new moon, modulo the
5
+ * mean synodic month. It ignores orbital perturbations, so it can be a few
6
+ * hours off real ephemerides; plenty for "waning quarter, full in eleven days".
7
+ * Checked against Open-Meteo on 2026-09-04: 0.751 here, 0.753 there.
8
+ */
9
+
10
+ /** Mean synodic month: new moon to new moon, in days. */
11
+ export const SYNODIC = 29.530588853;
12
+
13
+ /** Reference new moon: 2000-01-06 18:14 UTC, the usual epoch for this calculation. */
14
+ const REFERENCE_NEW_MOON = Date.UTC(2000, 0, 6, 18, 14, 0);
15
+
16
+ /** The eight usual phase names, in order from new moon. */
17
+ export const PHASE_NAMES = [
18
+ 'new',
19
+ 'waxing-crescent',
20
+ 'first-quarter',
21
+ 'waxing-gibbous',
22
+ 'full',
23
+ 'waning-gibbous',
24
+ 'last-quarter',
25
+ 'waning-crescent',
26
+ ] as const;
27
+ export type PhaseName = (typeof PHASE_NAMES)[number];
28
+
29
+ export interface Moon {
30
+ /** 0 = new moon, 0.5 = full, almost 1 = new again. */
31
+ phase: number;
32
+ /** Lit fraction of the disc, 0 to 1. */
33
+ illumination: number;
34
+ /** Growing? Before full it waxes, after full it wanes. */
35
+ waxing: boolean;
36
+ /** Nearest of the eight named phases (so "full" covers the day before and after). */
37
+ name: PhaseName;
38
+ /** Days to the next full moon (0 if today). */
39
+ daysToFull: number;
40
+ /** Days to the next new moon. */
41
+ daysToNew: number;
42
+ }
43
+
44
+ /** Days elapsed since the reference new moon. */
45
+ function daysSinceReference(at: number): number {
46
+ return (at - REFERENCE_NEW_MOON) / 86_400_000;
47
+ }
48
+
49
+ /** The moon at an instant. */
50
+ export function moonPhase(at: number | Date = Date.now()): Moon {
51
+ const ms = at instanceof Date ? at.getTime() : at;
52
+ // JS's % keeps the sign, so dates before 2000 are normalised by adding a cycle.
53
+ const phase = (((daysSinceReference(ms) % SYNODIC) + SYNODIC) % SYNODIC) / SYNODIC;
54
+
55
+ const illumination = (1 - Math.cos(2 * Math.PI * phase)) / 2;
56
+ const waxing = phase < 0.5;
57
+
58
+ // Nearest eighth, wrapping round: 0.97 is "new", not "waning crescent".
59
+ const name: PhaseName = PHASE_NAMES[Math.round(phase * 8) % 8] ?? 'new';
60
+
61
+ const toFull = phase <= 0.5 ? 0.5 - phase : 1.5 - phase;
62
+ const toNew = phase === 0 ? 0 : 1 - phase;
63
+
64
+ return {
65
+ phase,
66
+ illumination,
67
+ waxing,
68
+ name,
69
+ daysToFull: Math.round(toFull * SYNODIC),
70
+ daysToNew: Math.round(toNew * SYNODIC),
71
+ };
72
+ }
73
+
package/src/sun.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Sunrise and sunset, computed locally with NOAA's equation (the one behind
3
+ * its solar calculator). No network needed.
4
+ *
5
+ * Accuracy: a couple of minutes at mid latitudes. Near the poles there may be
6
+ * no sunrise or sunset; then `sunTimes` returns null.
7
+ */
8
+ const RAD = Math.PI / 180;
9
+
10
+ export interface SunTimes {
11
+ /** Local time as decimal hours (7.5 = 7:30), in the machine's time zone. */
12
+ rise: number;
13
+ set: number;
14
+ }
15
+
16
+ /** UTC minutes of sunrise and sunset for the UTC day of `date`. */
17
+ function utcMinutes(date: Date, lat: number, lon: number): { rise: number; set: number } | null {
18
+ const start = Date.UTC(date.getUTCFullYear(), 0, 1);
19
+ const day = Math.floor((Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()) - start) / 86_400_000) + 1;
20
+ const g = ((2 * Math.PI) / 365) * (day - 1);
21
+ const eq = 229.18 * (0.000075 + 0.001868 * Math.cos(g) - 0.032077 * Math.sin(g) - 0.014615 * Math.cos(2 * g) - 0.040849 * Math.sin(2 * g));
22
+ const decl = 0.006918 - 0.399912 * Math.cos(g) + 0.070257 * Math.sin(g) - 0.006758 * Math.cos(2 * g) + 0.000907 * Math.sin(2 * g) - 0.002697 * Math.cos(3 * g) + 0.00148 * Math.sin(3 * g);
23
+ // 90.833°: the whole disc below the horizon, allowing for atmospheric refraction.
24
+ const cosH = Math.cos(90.833 * RAD) / (Math.cos(lat * RAD) * Math.cos(decl)) - Math.tan(lat * RAD) * Math.tan(decl);
25
+ if (cosH < -1 || cosH > 1) return null;
26
+ const h = Math.acos(cosH) / RAD;
27
+ return { rise: 720 - 4 * (lon + h) - eq, set: 720 - 4 * (lon - h) - eq };
28
+ }
29
+
30
+ /** Sunrise and sunset on the day of `date` at a place, or null if the sun does not rise or set. */
31
+ export function sunTimes(date: Date, lat: number, lon: number): SunTimes | null {
32
+ const m = utcMinutes(date, lat, lon);
33
+ if (!m) return null;
34
+ // To local time on that day, with its summer or winter offset.
35
+ const toLocal = (min: number) => {
36
+ const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()) + min * 60_000);
37
+ return d.getHours() + d.getMinutes() / 60 + d.getSeconds() / 3600;
38
+ };
39
+ return { rise: toLocal(m.rise), set: toLocal(m.set) };
40
+ }
package/src/weather.ts ADDED
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Weather from Open-Meteo.
3
+ *
4
+ * Why Open-Meteo: it needs **no API key**, which rules out almost every other
5
+ * provider, and it returns plain JSON with standard WMO weather codes, so
6
+ * turning a reading into an icon is a lookup table.
7
+ *
8
+ * The on-disk cache (`saveWeather`/`loadWeather`) is not an optimisation: it
9
+ * keeps the last good reading so that a network outage does not blank the
10
+ * screen. Readings older than six hours are dropped instead of being shown as
11
+ * if they were current.
12
+ */
13
+ import { readFileSync, renameSync, writeFileSync } from 'node:fs';
14
+
15
+ /** A reading older than this no longer describes the street outside. */
16
+ export const MAX_AGE_MS = 6 * 3600_000;
17
+
18
+ /** Icon for a weather code; `sun`/`moon` variants depend on the time of day. */
19
+ export type IconKind =
20
+ | 'sun'
21
+ | 'moon'
22
+ | 'sun-cloud'
23
+ | 'moon-cloud'
24
+ | 'cloud'
25
+ | 'fog'
26
+ | 'drizzle'
27
+ | 'rain'
28
+ | 'snow'
29
+ | 'storm';
30
+
31
+ export interface DayForecast {
32
+ /** ISO date (YYYY-MM-DD). */
33
+ date: string;
34
+ /** WMO weather code. */
35
+ code: number;
36
+ min: number;
37
+ max: number;
38
+ /** Probability of precipitation, in %. */
39
+ rain: number;
40
+ }
41
+
42
+ export interface HourForecast {
43
+ /** Local time at the place, "HH:MM". */
44
+ label: string;
45
+ temp: number;
46
+ /** Probability of precipitation, in %. */
47
+ rain: number;
48
+ }
49
+
50
+ /** `metric` (°C, km/h, Open-Meteo's default) or `imperial` (°F, mph). */
51
+ export type Units = 'metric' | 'imperial';
52
+
53
+ export interface Weather {
54
+ place: string;
55
+ /** Coordinates of the reading, when the provider returned them. */
56
+ latitude?: number;
57
+ longitude?: number;
58
+ temp: number;
59
+ /** Apparent ("feels like") temperature. */
60
+ feels: number;
61
+ /** WMO weather code. */
62
+ code: number;
63
+ humidity: number;
64
+ wind: number;
65
+ /** Units of `temp`, `feels`, `days`, `hours` and `wind`; absent means `metric`. */
66
+ units?: Units;
67
+ /** Is it night at the place? Turns sun icons into moon icons. */
68
+ night: boolean;
69
+ days: DayForecast[];
70
+ /** The next hours, starting with the current one. */
71
+ hours: HourForecast[];
72
+ /** When it was read, ms epoch. */
73
+ fetched: number;
74
+ }
75
+
76
+ /**
77
+ * WMO codes → icon. Codes not listed are not emitted by this endpoint.
78
+ * Text descriptions are left to the caller, in its own language.
79
+ */
80
+ export const WMO_ICON: Readonly<Record<number, IconKind>> = {
81
+ 0: 'sun', 1: 'sun-cloud', 2: 'sun-cloud', 3: 'cloud',
82
+ 45: 'fog', 48: 'fog',
83
+ 51: 'drizzle', 53: 'drizzle', 55: 'drizzle', 56: 'drizzle', 57: 'drizzle',
84
+ 61: 'rain', 63: 'rain', 65: 'rain', 66: 'rain', 67: 'rain',
85
+ 71: 'snow', 73: 'snow', 75: 'snow', 77: 'snow',
86
+ 80: 'rain', 81: 'rain', 82: 'rain',
87
+ 85: 'snow', 86: 'snow',
88
+ 95: 'storm', 96: 'storm', 99: 'storm',
89
+ };
90
+
91
+ /** Icon for a code, swapping the sun for the moon at night. */
92
+ export function iconFor(code: number, night = false): IconKind {
93
+ const icon = WMO_ICON[code] ?? 'cloud';
94
+ if (!night) return icon;
95
+ if (icon === 'sun') return 'moon';
96
+ if (icon === 'sun-cloud') return 'moon-cloud';
97
+ return icon;
98
+ }
99
+
100
+ /** The subset of Open-Meteo's response that is read. */
101
+ export interface OpenMeteo {
102
+ latitude?: number;
103
+ longitude?: number;
104
+ current?: {
105
+ time?: string;
106
+ temperature_2m?: number;
107
+ apparent_temperature?: number;
108
+ weather_code?: number;
109
+ relative_humidity_2m?: number;
110
+ wind_speed_10m?: number;
111
+ };
112
+ daily?: {
113
+ time?: string[];
114
+ weather_code?: number[];
115
+ temperature_2m_max?: number[];
116
+ temperature_2m_min?: number[];
117
+ precipitation_probability_max?: number[];
118
+ };
119
+ hourly?: {
120
+ time?: string[];
121
+ temperature_2m?: number[];
122
+ precipitation_probability?: number[];
123
+ };
124
+ }
125
+
126
+ /** How many hourly entries `parseOpenMeteo` keeps: two days, enough to see tomorrow from tonight. */
127
+ export const HOURS_AHEAD = 48;
128
+
129
+ /** Days of daily forecast asked for, today included: a week. */
130
+ export const FORECAST_DAYS = 7;
131
+
132
+ /**
133
+ * Trims the hourly series so that it starts at the current hour.
134
+ *
135
+ * The API returns the whole day from 00:00. ISO strings are compared as text
136
+ * ("2026-09-04T14" sorts the same as a date), which avoids building `Date`s and
137
+ * time-zone mistakes: the place may be in a different zone than the computer.
138
+ */
139
+ export function sliceHours(
140
+ times: string[],
141
+ temps: number[],
142
+ rains: number[],
143
+ currentIso: string,
144
+ count = HOURS_AHEAD,
145
+ ): HourForecast[] {
146
+ const key = currentIso.slice(0, 13);
147
+ let start = times.findIndex((t) => t.slice(0, 13) >= key);
148
+ if (start < 0) start = 0;
149
+
150
+ const out: HourForecast[] = [];
151
+ for (let i = start; i < times.length && out.length < count; i += 1) {
152
+ const t = times[i];
153
+ if (t === undefined) continue;
154
+ out.push({
155
+ label: t.slice(11, 16),
156
+ temp: Math.round(temps[i] ?? 0),
157
+ rain: Math.round(rains[i] ?? 0),
158
+ });
159
+ }
160
+ return out;
161
+ }
162
+
163
+ /**
164
+ * Is it night? Decided with the local time the API itself returns, in the
165
+ * place's zone, not the computer's.
166
+ */
167
+ export function isNight(localTime: string | undefined): boolean {
168
+ const hour = Number.parseInt(localTime?.slice(11, 13) ?? '', 10);
169
+ if (!Number.isFinite(hour)) return false;
170
+ return hour < 7 || hour >= 21;
171
+ }
172
+
173
+ /** Turns an Open-Meteo response into a `Weather`, or null if it has no current data. */
174
+ export function parseOpenMeteo(raw: OpenMeteo, place: string, now = Date.now()): Weather | null {
175
+ const c = raw.current;
176
+ if (!c || typeof c.temperature_2m !== 'number') return null;
177
+
178
+ const d = raw.daily;
179
+ const days: DayForecast[] = [];
180
+ for (let i = 0; i < (d?.time?.length ?? 0); i += 1) {
181
+ days.push({
182
+ date: d?.time?.[i] ?? '',
183
+ code: d?.weather_code?.[i] ?? 0,
184
+ min: Math.round(d?.temperature_2m_min?.[i] ?? 0),
185
+ max: Math.round(d?.temperature_2m_max?.[i] ?? 0),
186
+ rain: Math.round(d?.precipitation_probability_max?.[i] ?? 0),
187
+ });
188
+ }
189
+
190
+ const h = raw.hourly;
191
+ const hours = h?.time
192
+ ? sliceHours(h.time, h.temperature_2m ?? [], h.precipitation_probability ?? [], c.time ?? '')
193
+ : [];
194
+
195
+ return {
196
+ place,
197
+ ...(typeof raw.latitude === 'number' && typeof raw.longitude === 'number' ? { latitude: raw.latitude, longitude: raw.longitude } : {}),
198
+ temp: Math.round(c.temperature_2m),
199
+ feels: Math.round(c.apparent_temperature ?? c.temperature_2m),
200
+ code: c.weather_code ?? 0,
201
+ humidity: Math.round(c.relative_humidity_2m ?? 0),
202
+ wind: Math.round(c.wind_speed_10m ?? 0),
203
+ night: isNight(c.time),
204
+ days,
205
+ hours,
206
+ fetched: now,
207
+ };
208
+ }
209
+
210
+ export interface WeatherPlace {
211
+ name: string;
212
+ latitude: number;
213
+ longitude: number;
214
+ }
215
+
216
+ export interface FetchWeatherOptions {
217
+ /** Longest the request may take. */
218
+ timeoutMs: number;
219
+ /** Aborts the request early (the caller stopped). */
220
+ signal?: AbortSignal;
221
+ /** Default `metric`. */
222
+ units?: Units;
223
+ }
224
+
225
+ /** The Open-Meteo address for a place: now, the next `HOURS_AHEAD` hours and `FORECAST_DAYS` days. */
226
+ export function openMeteoUrl(place: Pick<WeatherPlace, 'latitude' | 'longitude'>, units: Units = 'metric'): string {
227
+ return (
228
+ 'https://api.open-meteo.com/v1/forecast' +
229
+ `?latitude=${place.latitude}&longitude=${place.longitude}` +
230
+ '&current=temperature_2m,apparent_temperature,weather_code,relative_humidity_2m,wind_speed_10m' +
231
+ '&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max' +
232
+ '&hourly=temperature_2m,precipitation_probability' +
233
+ (units === 'imperial' ? '&temperature_unit=fahrenheit&wind_speed_unit=mph' : '') +
234
+ `&timezone=auto&forecast_days=${FORECAST_DAYS}`
235
+ );
236
+ }
237
+
238
+ /**
239
+ * Reads the current weather, the next two days hour by hour and a week of
240
+ * daily forecast. Never throws: null on failure. The second argument is the
241
+ * timeout in ms, or `{ timeoutMs, signal, units }`.
242
+ */
243
+ export async function fetchWeather(
244
+ place: WeatherPlace,
245
+ options: number | FetchWeatherOptions,
246
+ log: (msg: string) => void = () => {},
247
+ ): Promise<Weather | null> {
248
+ const o: FetchWeatherOptions = typeof options === 'number' ? { timeoutMs: options } : options;
249
+ const timeout = AbortSignal.timeout(o.timeoutMs);
250
+ try {
251
+ const res = await fetch(openMeteoUrl(place, o.units), { signal: o.signal ? AbortSignal.any([o.signal, timeout]) : timeout });
252
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
253
+ const parsed = parseOpenMeteo((await res.json()) as OpenMeteo, place.name);
254
+ if (!parsed) throw new Error('response without current data');
255
+ return o.units === 'imperial' ? { ...parsed, units: 'imperial' } : parsed;
256
+ } catch (err) {
257
+ log(`weather: failed (${err instanceof Error ? err.message : String(err)})`);
258
+ return null;
259
+ }
260
+ }
261
+
262
+ /** Atomic write, so that no reader ever sees half a JSON file. */
263
+ export function saveWeather(path: string, w: Weather): void {
264
+ const tmp = `${path}.tmp`;
265
+ writeFileSync(tmp, JSON.stringify(w));
266
+ renameSync(tmp, path);
267
+ }
268
+
269
+ /** The last reading saved at `path`, or null if missing, invalid or older than `MAX_AGE_MS`. */
270
+ export function loadWeather(path: string, now = Date.now()): Weather | null {
271
+ try {
272
+ const w = JSON.parse(readFileSync(path, 'utf8')) as Weather;
273
+ if (typeof w?.temp !== 'number' || typeof w.fetched !== 'number') return null;
274
+ return now - w.fetched > MAX_AGE_MS ? null : w;
275
+ } catch {
276
+ return null;
277
+ }
278
+ }