@azohra/meteo.station 0.1.1 → 0.1.2

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.
Files changed (44) hide show
  1. package/dist/client/index.d.ts +2 -1
  2. package/dist/client/index.js +2 -1
  3. package/dist/client/live.d.ts +37 -0
  4. package/dist/client/live.js +241 -0
  5. package/dist/client/stores.d.ts +1 -0
  6. package/dist/client/stores.js +41 -6
  7. package/dist/contract.d.ts +237 -1
  8. package/dist/contract.js +57 -3
  9. package/dist/endpoints.d.ts +2 -1
  10. package/dist/endpoints.js +4 -1
  11. package/dist/index.d.ts +3 -3
  12. package/dist/index.js +3 -3
  13. package/dist/react/hooks/useStation.d.ts +1 -0
  14. package/dist/react/hooks/useStation.js +25 -5
  15. package/dist/react/hooks/useStationLive.d.ts +20 -0
  16. package/dist/react/hooks/useStationLive.js +33 -0
  17. package/dist/react/index.d.ts +2 -1
  18. package/dist/react/index.js +2 -1
  19. package/dist/server/adapter.d.ts +3 -1
  20. package/dist/server/adapter.js +3 -1
  21. package/dist/server/adapters/windnerd-live.d.ts +21 -0
  22. package/dist/server/adapters/windnerd-live.js +179 -0
  23. package/dist/server/adapters/windnerd.d.ts +36 -5
  24. package/dist/server/adapters/windnerd.js +177 -15
  25. package/dist/server/config.d.ts +2 -0
  26. package/dist/server/config.js +2 -1
  27. package/dist/server/environment.d.ts +25 -5
  28. package/dist/server/environment.js +65 -21
  29. package/dist/server/feed.d.ts +20 -2
  30. package/dist/server/feed.js +28 -1
  31. package/dist/server/handler.d.ts +1 -1
  32. package/dist/server/handler.js +37 -3
  33. package/dist/server/index.d.ts +6 -4
  34. package/dist/server/index.js +6 -4
  35. package/dist/server/live.d.ts +15 -0
  36. package/dist/server/live.js +19 -0
  37. package/dist/sse.js +56 -0
  38. package/package.json +1 -1
  39. package/schema/README.md +1 -1
  40. package/schema/example-feed.json +26 -1
  41. package/schema/example-live.json +74 -0
  42. package/schema/stationcurrent.schema.json +115 -0
  43. package/schema/stationfeed.schema.json +115 -0
  44. package/schema/stationlive.schema.json +868 -0
@@ -1,4 +1,5 @@
1
1
  import { FRESHNESS_REEVALUATE_MS, JsonPoller, JsonPollerOptions, ParseOutcome, PollError, PollSeed, PollSnapshot, REQUEST_TIMEOUT_MS, createJsonPoller } from "./poll.js";
2
2
  import { StationSnapshot, StationStore, createStationCurrentStore, createStationFeedStore, createStationStore, parseCurrentText, parseFeedText } from "./stores.js";
3
+ import { LIVE_BACKOFF_MAX_MS, LIVE_BACKOFF_MIN_MS, LIVE_IDLE_RECONNECT_MS, LiveStatus, StationLiveSnapshot, StationLiveStore, createStationLiveStore, liveSnapshotToCurrent } from "./live.js";
3
4
  import { subscribeTicker } from "./ticker.js";
4
- export { FRESHNESS_REEVALUATE_MS, type JsonPoller, type JsonPollerOptions, type ParseOutcome, type PollError, type PollSeed, type PollSnapshot, REQUEST_TIMEOUT_MS, type StationSnapshot, type StationStore, createJsonPoller, createStationCurrentStore, createStationFeedStore, createStationStore, parseCurrentText, parseFeedText, subscribeTicker };
5
+ export { FRESHNESS_REEVALUATE_MS, type JsonPoller, type JsonPollerOptions, LIVE_BACKOFF_MAX_MS, LIVE_BACKOFF_MIN_MS, LIVE_IDLE_RECONNECT_MS, type LiveStatus, type ParseOutcome, type PollError, type PollSeed, type PollSnapshot, REQUEST_TIMEOUT_MS, type StationLiveSnapshot, type StationLiveStore, type StationSnapshot, type StationStore, createJsonPoller, createStationCurrentStore, createStationFeedStore, createStationLiveStore, createStationStore, liveSnapshotToCurrent, parseCurrentText, parseFeedText, subscribeTicker };
@@ -1,4 +1,5 @@
1
1
  import { FRESHNESS_REEVALUATE_MS, REQUEST_TIMEOUT_MS, createJsonPoller } from "./poll.js";
2
+ import { LIVE_BACKOFF_MAX_MS, LIVE_BACKOFF_MIN_MS, LIVE_IDLE_RECONNECT_MS, createStationLiveStore, liveSnapshotToCurrent } from "./live.js";
2
3
  import { createStationCurrentStore, createStationFeedStore, createStationStore, parseCurrentText, parseFeedText } from "./stores.js";
3
4
  import { subscribeTicker } from "./ticker.js";
4
- export { FRESHNESS_REEVALUATE_MS, REQUEST_TIMEOUT_MS, createJsonPoller, createStationCurrentStore, createStationFeedStore, createStationStore, parseCurrentText, parseFeedText, subscribeTicker };
5
+ export { FRESHNESS_REEVALUATE_MS, LIVE_BACKOFF_MAX_MS, LIVE_BACKOFF_MIN_MS, LIVE_IDLE_RECONNECT_MS, REQUEST_TIMEOUT_MS, createJsonPoller, createStationCurrentStore, createStationFeedStore, createStationLiveStore, createStationStore, liveSnapshotToCurrent, parseCurrentText, parseFeedText, subscribeTicker };
@@ -0,0 +1,37 @@
1
+ import { PollError } from "./poll.js";
2
+ import { LiveSample, Station, StationCurrent } from "../contract.js";
3
+ //#region src/client/live.d.ts
4
+ declare const LIVE_BACKOFF_MIN_MS = 1000;
5
+ declare const LIVE_BACKOFF_MAX_MS = 30000;
6
+ declare const LIVE_IDLE_RECONNECT_MS = 60000;
7
+ type LiveStatus = "connecting" | "open" | "backoff" | "stopped";
8
+ type StationLiveSnapshot = {
9
+ status: LiveStatus;
10
+ station: Station | null;
11
+ samples: LiveSample[];
12
+ servedAt: string | null;
13
+ receivedAtMs: number | null;
14
+ error: PollError | null;
15
+ };
16
+ type StationLiveStore = {
17
+ getSnapshot(): StationLiveSnapshot;
18
+ subscribe(listener: () => void): () => void;
19
+ start(): void;
20
+ stop(): void;
21
+ };
22
+ type FetchInitOption = RequestInit | (() => RequestInit | undefined);
23
+ /**
24
+ * Subscribes to the /live route and folds its frames into one snapshot. The
25
+ * store owns the reconnect loop — exponential backoff from 1 s capped at
26
+ * 30 s with full jitter, reset by a successful init frame — and an idle
27
+ * watchdog that forces a reconnect on a silent pipe. Hidden documents
28
+ * disconnect and reconnect on return; a reconnect's fresh init frame heals
29
+ * any gap the ring can cover.
30
+ */
31
+ declare function createStationLiveStore(base: string, stationId: string, options?: {
32
+ fetchInit?: FetchInitOption;
33
+ windowSeconds?: number;
34
+ }): StationLiveStore;
35
+ declare function liveSnapshotToCurrent(live: Pick<StationLiveSnapshot, "station" | "servedAt" | "samples">): StationCurrent | null;
36
+ //#endregion
37
+ export { LIVE_BACKOFF_MAX_MS, LIVE_BACKOFF_MIN_MS, LIVE_IDLE_RECONNECT_MS, LiveStatus, StationLiveSnapshot, StationLiveStore, createStationLiveStore, liveSnapshotToCurrent };
@@ -0,0 +1,241 @@
1
+ import { parseStationLiveFrameJson } from "../contract.js";
2
+ import { liveEndpoint } from "../endpoints.js";
3
+ import { sseEvents } from "../sse.js";
4
+ //#region src/client/live.ts
5
+ const LIVE_BACKOFF_MIN_MS = 1e3;
6
+ const LIVE_BACKOFF_MAX_MS = 3e4;
7
+ const LIVE_IDLE_RECONNECT_MS = 6e4;
8
+ const DEFAULT_WINDOW_SECONDS = 600;
9
+ /**
10
+ * Subscribes to the /live route and folds its frames into one snapshot. The
11
+ * store owns the reconnect loop — exponential backoff from 1 s capped at
12
+ * 30 s with full jitter, reset by a successful init frame — and an idle
13
+ * watchdog that forces a reconnect on a silent pipe. Hidden documents
14
+ * disconnect and reconnect on return; a reconnect's fresh init frame heals
15
+ * any gap the ring can cover.
16
+ */
17
+ function createStationLiveStore(base, stationId, options = {}) {
18
+ const windowSeconds = options.windowSeconds ?? DEFAULT_WINDOW_SECONDS;
19
+ const fetchInitFor = () => typeof options.fetchInit === "function" ? options.fetchInit() : options.fetchInit;
20
+ let snapshot = {
21
+ status: "stopped",
22
+ station: null,
23
+ samples: [],
24
+ servedAt: null,
25
+ receivedAtMs: null,
26
+ error: null
27
+ };
28
+ const listeners = /* @__PURE__ */ new Set();
29
+ let session = null;
30
+ const setSnapshot = (next) => {
31
+ snapshot = next;
32
+ for (const listener of [...listeners]) listener();
33
+ };
34
+ const hidden = () => typeof document !== "undefined" && document.hidden;
35
+ const applyFrame = (frame, current) => {
36
+ switch (frame.type) {
37
+ case "init": {
38
+ current.attempt = 0;
39
+ const points = frame.station.status === "ok" ? frame.station.samples?.points ?? [] : [];
40
+ setSnapshot({
41
+ status: "open",
42
+ station: frame.station,
43
+ samples: mergeSamples(snapshot.samples, points, windowSeconds),
44
+ servedAt: frame.servedAt,
45
+ receivedAtMs: Date.now(),
46
+ error: null
47
+ });
48
+ return;
49
+ }
50
+ case "samples":
51
+ setSnapshot({
52
+ ...snapshot,
53
+ status: "open",
54
+ samples: mergeSamples(snapshot.samples, frame.samples.points, windowSeconds),
55
+ receivedAtMs: Date.now(),
56
+ error: null
57
+ });
58
+ return;
59
+ case "reading": {
60
+ const station = snapshot.station;
61
+ setSnapshot({
62
+ ...snapshot,
63
+ status: "open",
64
+ station: station?.status === "ok" ? {
65
+ ...station,
66
+ reading: frame.reading,
67
+ telemetry: frame.telemetry
68
+ } : station,
69
+ servedAt: frame.servedAt,
70
+ receivedAtMs: Date.now(),
71
+ error: null
72
+ });
73
+ return;
74
+ }
75
+ case "ping": return;
76
+ case "unavailable":
77
+ setSnapshot({
78
+ ...snapshot,
79
+ error: { kind: "network" }
80
+ });
81
+ return;
82
+ }
83
+ };
84
+ const connect = async (current) => {
85
+ const controller = new AbortController();
86
+ current.controller = controller;
87
+ setSnapshot({
88
+ ...snapshot,
89
+ status: "connecting"
90
+ });
91
+ const resetIdle = () => {
92
+ if (current.idleTimer != null) clearTimeout(current.idleTimer);
93
+ current.idleTimer = setTimeout(() => controller.abort(), LIVE_IDLE_RECONNECT_MS);
94
+ };
95
+ try {
96
+ resetIdle();
97
+ const response = await fetch(liveEndpoint(base, stationId), {
98
+ ...fetchInitFor(),
99
+ signal: controller.signal
100
+ });
101
+ if (!response.ok || response.body == null) {
102
+ await response.body?.cancel();
103
+ if (!current.disposed) setSnapshot({
104
+ ...snapshot,
105
+ error: {
106
+ kind: "network",
107
+ status: response.status
108
+ }
109
+ });
110
+ return;
111
+ }
112
+ resetIdle();
113
+ for await (const event of sseEvents(response.body, { signal: controller.signal })) {
114
+ if (current.disposed) return;
115
+ resetIdle();
116
+ const frame = parseStationLiveFrameJson(event.data);
117
+ if (frame == null) {
118
+ setSnapshot({
119
+ ...snapshot,
120
+ error: { kind: "contract" }
121
+ });
122
+ return;
123
+ }
124
+ applyFrame(frame, current);
125
+ }
126
+ } catch {
127
+ if (!current.disposed) setSnapshot({
128
+ ...snapshot,
129
+ error: { kind: "network" }
130
+ });
131
+ } finally {
132
+ if (current.idleTimer != null) clearTimeout(current.idleTimer);
133
+ current.idleTimer = void 0;
134
+ controller.abort();
135
+ if (current.controller === controller) current.controller = null;
136
+ }
137
+ };
138
+ const sleep = (current, delayMs) => new Promise((resolve) => {
139
+ current.wake = () => {
140
+ current.wake = null;
141
+ if (current.timer != null) clearTimeout(current.timer);
142
+ current.timer = void 0;
143
+ resolve();
144
+ };
145
+ current.timer = setTimeout(() => current.wake?.(), delayMs);
146
+ });
147
+ const runLoop = async (current) => {
148
+ while (!current.disposed) {
149
+ if (hidden()) {
150
+ setSnapshot({
151
+ ...snapshot,
152
+ status: "backoff"
153
+ });
154
+ await sleep(current, LIVE_BACKOFF_MAX_MS);
155
+ continue;
156
+ }
157
+ await connect(current);
158
+ if (current.disposed) return;
159
+ setSnapshot({
160
+ ...snapshot,
161
+ status: "backoff"
162
+ });
163
+ const delay = backoffDelayMs(current.attempt);
164
+ current.attempt += 1;
165
+ await sleep(current, delay);
166
+ }
167
+ };
168
+ const start = () => {
169
+ if (session != null) return;
170
+ const current = {
171
+ disposed: false,
172
+ controller: null,
173
+ attempt: 0,
174
+ wake: null,
175
+ timer: void 0,
176
+ idleTimer: void 0,
177
+ onVisibilityChange: () => {
178
+ if (hidden()) current.controller?.abort();
179
+ else current.wake?.();
180
+ }
181
+ };
182
+ session = current;
183
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", current.onVisibilityChange);
184
+ runLoop(current);
185
+ };
186
+ const stop = () => {
187
+ const current = session;
188
+ if (current == null) return;
189
+ session = null;
190
+ current.disposed = true;
191
+ current.controller?.abort();
192
+ current.wake?.();
193
+ if (current.timer != null) clearTimeout(current.timer);
194
+ if (current.idleTimer != null) clearTimeout(current.idleTimer);
195
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", current.onVisibilityChange);
196
+ setSnapshot({
197
+ ...snapshot,
198
+ status: "stopped"
199
+ });
200
+ };
201
+ return {
202
+ getSnapshot: () => snapshot,
203
+ subscribe: (listener) => {
204
+ listeners.add(listener);
205
+ return () => listeners.delete(listener);
206
+ },
207
+ start,
208
+ stop
209
+ };
210
+ }
211
+ function liveSnapshotToCurrent(live) {
212
+ if (live.station == null || live.servedAt == null) return null;
213
+ const station = live.station.status === "ok" && live.samples.length > 0 ? {
214
+ ...live.station,
215
+ samples: {
216
+ intervalSeconds: live.station.samples?.intervalSeconds ?? 3,
217
+ points: live.samples
218
+ }
219
+ } : live.station;
220
+ return {
221
+ schemaVersion: 2,
222
+ servedAt: live.servedAt,
223
+ station
224
+ };
225
+ }
226
+ function backoffDelayMs(attempt) {
227
+ const ceiling = Math.min(LIVE_BACKOFF_MAX_MS, LIVE_BACKOFF_MIN_MS * 2 ** attempt);
228
+ return Math.random() * ceiling;
229
+ }
230
+ function mergeSamples(existing, incoming, windowSeconds) {
231
+ const byObservedAt = /* @__PURE__ */ new Map();
232
+ for (const sample of existing) byObservedAt.set(sample.observedAt, sample);
233
+ for (const sample of incoming) byObservedAt.set(sample.observedAt, sample);
234
+ const merged = [...byObservedAt.values()].sort((a, b) => Date.parse(a.observedAt) - Date.parse(b.observedAt));
235
+ const latest = merged[merged.length - 1];
236
+ if (latest == null) return merged;
237
+ const cutoffMs = Date.parse(latest.observedAt) - windowSeconds * 1e3;
238
+ return merged.filter((sample) => Date.parse(sample.observedAt) >= cutoffMs);
239
+ }
240
+ //#endregion
241
+ export { LIVE_BACKOFF_MAX_MS, LIVE_BACKOFF_MIN_MS, LIVE_IDLE_RECONNECT_MS, createStationLiveStore, liveSnapshotToCurrent };
@@ -41,6 +41,7 @@ declare function createStationStore(base: string, stationId: string, options?: {
41
41
  feed: StationFeed;
42
42
  receivedAtMs: number;
43
43
  };
44
+ live?: boolean;
44
45
  }): StationStore;
45
46
  //#endregion
46
47
  export { StationSnapshot, StationStore, createStationCurrentStore, createStationFeedStore, createStationStore, parseCurrentText, parseFeedText };
@@ -2,6 +2,7 @@ import { stationCurrentSchema, stationFeedSchema } from "../contract.js";
2
2
  import { currentEndpoint, feedEndpoint } from "../endpoints.js";
3
3
  import { foldCurrent } from "../merge-current.js";
4
4
  import { createJsonPoller } from "./poll.js";
5
+ import { createStationLiveStore, liveSnapshotToCurrent } from "./live.js";
5
6
  //#region src/client/stores.ts
6
7
  const FEED_DEFAULT_POLL_SECONDS = 60;
7
8
  const CURRENT_DEFAULT_POLL_SECONDS = 15;
@@ -71,6 +72,40 @@ function createStationCurrentStore(base, stationId, options = {}) {
71
72
  } } : {}
72
73
  });
73
74
  }
75
+ function liveCurrentLeg(base, stationId, fetchInit) {
76
+ const liveStore = createStationLiveStore(base, stationId, { ...fetchInit != null ? { fetchInit } : {} });
77
+ let lastLive = null;
78
+ let mapped = {
79
+ data: null,
80
+ error: null,
81
+ receivedAtMs: null
82
+ };
83
+ const toCurrent = (live) => {
84
+ const data = liveSnapshotToCurrent(live);
85
+ return {
86
+ data,
87
+ error: live.error,
88
+ receivedAtMs: data == null ? null : live.receivedAtMs
89
+ };
90
+ };
91
+ return {
92
+ getSnapshot: () => {
93
+ const live = liveStore.getSnapshot();
94
+ if (live !== lastLive) {
95
+ lastLive = live;
96
+ mapped = toCurrent(live);
97
+ }
98
+ return mapped;
99
+ },
100
+ subscribe: (listener) => liveStore.subscribe(listener),
101
+ start: () => liveStore.start(),
102
+ stop: () => liveStore.stop(),
103
+ refresh: () => {
104
+ liveStore.stop();
105
+ liveStore.start();
106
+ }
107
+ };
108
+ }
74
109
  function createStationStore(base, stationId, options = {}) {
75
110
  const { pollSeconds, currentPollSeconds, fetchInit, initialData } = options;
76
111
  const feedStore = createStationFeedStore(base, {
@@ -78,7 +113,7 @@ function createStationStore(base, stationId, options = {}) {
78
113
  ...fetchInit != null ? { fetchInit } : {},
79
114
  ...initialData != null ? { initial: initialData } : {}
80
115
  });
81
- const currentStore = createStationCurrentStore(base, stationId, {
116
+ const currentLeg = options.live ? liveCurrentLeg(base, stationId, fetchInit) : createStationCurrentStore(base, stationId, {
82
117
  ...currentPollSeconds != null ? { pollSeconds: currentPollSeconds } : {},
83
118
  ...fetchInit != null ? { fetchInit } : {}
84
119
  });
@@ -88,7 +123,7 @@ function createStationStore(base, stationId, options = {}) {
88
123
  return {
89
124
  getSnapshot: () => {
90
125
  const feedSnapshot = feedStore.getSnapshot();
91
- const currentSnapshot = currentStore.getSnapshot();
126
+ const currentSnapshot = currentLeg.getSnapshot();
92
127
  if (cached == null || feedSnapshot !== lastFeed || currentSnapshot !== lastCurrent) {
93
128
  lastFeed = feedSnapshot;
94
129
  lastCurrent = currentSnapshot;
@@ -104,7 +139,7 @@ function createStationStore(base, stationId, options = {}) {
104
139
  },
105
140
  subscribe: (listener) => {
106
141
  const unsubscribeFeed = feedStore.subscribe(listener);
107
- const unsubscribeCurrent = currentStore.subscribe(listener);
142
+ const unsubscribeCurrent = currentLeg.subscribe(listener);
108
143
  return () => {
109
144
  unsubscribeFeed();
110
145
  unsubscribeCurrent();
@@ -112,15 +147,15 @@ function createStationStore(base, stationId, options = {}) {
112
147
  },
113
148
  start: () => {
114
149
  feedStore.start();
115
- currentStore.start();
150
+ currentLeg.start();
116
151
  },
117
152
  stop: () => {
118
153
  feedStore.stop();
119
- currentStore.stop();
154
+ currentLeg.stop();
120
155
  },
121
156
  refresh: () => {
122
157
  feedStore.refresh();
123
- currentStore.refresh();
158
+ currentLeg.refresh();
124
159
  }
125
160
  };
126
161
  }