@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,4 @@
1
- import { UPSTREAM_FAILURE_REASONS as UPSTREAM_FAILURE_REASONS$1, UpstreamError, unavailableReasonForError } from "@azohra/meteo.core";
1
+ import { UPSTREAM_FAILURE_REASONS as UPSTREAM_FAILURE_REASONS$1, UpstreamError as UpstreamError$1, unavailableReasonForError } from "@azohra/meteo.core";
2
2
  //#region src/server/environment.ts
3
3
  const UPSTREAM_FETCH_TIMEOUT_MS = 4e3;
4
4
  const UPSTREAM_RESPONSE_LIMIT_BYTES = 524288;
@@ -47,26 +47,33 @@ function resolveEnvironment(environment = {}) {
47
47
  }
48
48
  const inFlightLoads = /* @__PURE__ */ new WeakMap();
49
49
  /**
50
- * The one road to an upstream: cache lookup, bounded fetch under a timeout,
51
- * cache fill. Concurrent misses on the same (cache instance, cacheKey)
52
- * coalesce onto a single in-flight load.
50
+ * Coalesces concurrent misses on the same (cache instance, key) onto a single
51
+ * in-flight load. The load owns its own cache fill; this only deduplicates.
53
52
  */
54
- async function fetchUpstreamText(environment, request) {
55
- const cached = await environment.cache.get(request.cacheKey);
56
- if (cached != null) return cached;
57
- let pending = inFlightLoads.get(environment.cache);
53
+ function coalesceUpstreamLoad(cache, key, load) {
54
+ let pending = inFlightLoads.get(cache);
58
55
  if (!pending) {
59
56
  pending = /* @__PURE__ */ new Map();
60
- inFlightLoads.set(environment.cache, pending);
57
+ inFlightLoads.set(cache, pending);
61
58
  }
62
- const inFlight = pending.get(request.cacheKey);
59
+ const inFlight = pending.get(key);
63
60
  if (inFlight) return inFlight;
64
61
  const settled = pending;
65
- const load = loadUpstreamText(environment, request).finally(() => {
66
- settled.delete(request.cacheKey);
62
+ const loading = load().finally(() => {
63
+ settled.delete(key);
67
64
  });
68
- pending.set(request.cacheKey, load);
69
- return load;
65
+ pending.set(key, loading);
66
+ return loading;
67
+ }
68
+ /**
69
+ * The one road to an upstream document: cache lookup, bounded fetch under a
70
+ * timeout, cache fill. Concurrent misses on the same (cache instance,
71
+ * cacheKey) coalesce onto a single in-flight load.
72
+ */
73
+ async function fetchUpstreamText(environment, request) {
74
+ const cached = await environment.cache.get(request.cacheKey);
75
+ if (cached != null) return cached;
76
+ return coalesceUpstreamLoad(environment.cache, request.cacheKey, () => loadUpstreamText(environment, request));
70
77
  }
71
78
  async function loadUpstreamText(environment, request) {
72
79
  let response;
@@ -82,23 +89,60 @@ async function loadUpstreamText(environment, request) {
82
89
  signal: AbortSignal.timeout(request.timeoutMs ?? 4e3)
83
90
  });
84
91
  } catch (error) {
85
- if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) throw new UpstreamError(`${request.subject} timed out`, "timeout");
86
- throw new UpstreamError(`${request.subject} could not be reached: ${error instanceof Error ? error.message : String(error)}`);
92
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) throw new UpstreamError$1(`${request.subject} timed out`, "timeout");
93
+ throw new UpstreamError$1(`${request.subject} could not be reached: ${error instanceof Error ? error.message : String(error)}`);
87
94
  }
88
95
  if (!response.ok) {
89
96
  try {
90
97
  await response.body?.cancel();
91
98
  } catch {}
92
- if (response.status === 429) throw new UpstreamError(`${request.subject} is rate limiting requests`, "rate_limited");
93
- throw new UpstreamError(`${request.subject} returned ${response.status}`);
99
+ if (response.status === 429) throw new UpstreamError$1(`${request.subject} is rate limiting requests`, "rate_limited");
100
+ throw new UpstreamError$1(`${request.subject} returned ${response.status}`);
94
101
  }
95
102
  const text = await boundedResponseText(response, request.limitBytes ?? 524288, request.subject);
96
103
  await environment.cache.put(request.cacheKey, text, request.cacheTtlSeconds);
97
104
  return text;
98
105
  }
106
+ const UPSTREAM_CONNECT_TIMEOUT_MS = 1e4;
107
+ /**
108
+ * The road to a long-lived upstream body. No cache and no byte cap — the
109
+ * consumer bounds its own buffering — and never coalesced: every caller owns
110
+ * its connection and tears it down through its signal.
111
+ */
112
+ async function fetchUpstreamStream(environment, request) {
113
+ const connect = new AbortController();
114
+ const connectTimer = setTimeout(() => connect.abort(), request.connectTimeoutMs ?? 1e4);
115
+ const signal = request.signal ? AbortSignal.any([request.signal, connect.signal]) : connect.signal;
116
+ let response;
117
+ try {
118
+ response = await environment.fetch(request.url, {
119
+ headers: {
120
+ Accept: request.accept ?? "text/event-stream",
121
+ "User-Agent": environment.userAgent,
122
+ ...request.headers
123
+ },
124
+ signal
125
+ });
126
+ } catch (error) {
127
+ if (request.signal?.aborted) throw error;
128
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) throw new UpstreamError$1(`${request.subject} timed out`, "timeout");
129
+ throw new UpstreamError$1(`${request.subject} could not be reached: ${error instanceof Error ? error.message : String(error)}`);
130
+ } finally {
131
+ clearTimeout(connectTimer);
132
+ }
133
+ if (!response.ok) {
134
+ try {
135
+ await response.body?.cancel();
136
+ } catch {}
137
+ if (response.status === 429) throw new UpstreamError$1(`${request.subject} is rate limiting requests`, "rate_limited");
138
+ throw new UpstreamError$1(`${request.subject} returned ${response.status}`);
139
+ }
140
+ if (!response.body) throw new UpstreamError$1(`${request.subject} returned no body`);
141
+ return response;
142
+ }
99
143
  async function boundedResponseText(response, limitBytes, subject) {
100
144
  const reader = response.body?.getReader();
101
- if (!reader) throw new UpstreamError(`${subject} returned no body`);
145
+ if (!reader) throw new UpstreamError$1(`${subject} returned no body`);
102
146
  const decoder = new TextDecoder();
103
147
  let result = "";
104
148
  let totalBytes = 0;
@@ -108,7 +152,7 @@ async function boundedResponseText(response, limitBytes, subject) {
108
152
  totalBytes += value.byteLength;
109
153
  if (totalBytes > limitBytes) {
110
154
  await reader.cancel();
111
- throw new UpstreamError(`${subject} exceeded the response limit`);
155
+ throw new UpstreamError$1(`${subject} exceeded the response limit`);
112
156
  }
113
157
  result += decoder.decode(value, { stream: true });
114
158
  }
@@ -125,4 +169,4 @@ function logUpstreamFailure(environment, message, error, detail = {}) {
125
169
  });
126
170
  }
127
171
  //#endregion
128
- export { DEFAULT_USER_AGENT, UPSTREAM_FAILURE_REASONS$1 as UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, boundedResponseText, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError };
172
+ export { DEFAULT_USER_AGENT, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS$1 as UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError$1 as UpstreamError, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError };
@@ -1,4 +1,4 @@
1
- import { Station, StationCurrent, StationFeed } from "../contract.js";
1
+ import { Station, StationCurrent, StationFeed, StationLiveFrame } from "../contract.js";
2
2
  import { ResolvedEnvironment, ServerEnvironment } from "./environment.js";
3
3
  import { StationConfig, StationConfigInput } from "./config.js";
4
4
  //#region src/server/feed.d.ts
@@ -19,6 +19,24 @@ type LoadStationCurrentOptions = LoadStationFeedOptions & {
19
19
  declare class UnknownStationError extends Error {
20
20
  constructor(stationId: string);
21
21
  }
22
+ declare class StationLiveUnsupportedError extends Error {
23
+ constructor(stationId: string);
24
+ }
25
+ type OpenStationLiveOptions = {
26
+ stations: StationsInput;
27
+ stationId: string;
28
+ environment?: ServerEnvironment;
29
+ signal?: AbortSignal;
30
+ request?: Request;
31
+ };
32
+ /**
33
+ * Opens the live stream for one configured station. Unknown ids throw
34
+ * UnknownStationError; stations whose vendor has no live arm — and stations
35
+ * whose config failed validation — throw StationLiveUnsupportedError; connect
36
+ * failures reject with the upstream error. One call is one upstream
37
+ * connection.
38
+ */
39
+ declare function openStationLive(options: OpenStationLiveOptions): Promise<ReadableStream<StationLiveFrame>>;
22
40
  declare function loadStationFeed(options: LoadStationFeedOptions): Promise<StationFeed>;
23
41
  declare function loadStationCurrent(options: LoadStationCurrentOptions): Promise<StationCurrent>;
24
42
  type AssembledStation = {
@@ -28,4 +46,4 @@ type AssembledStation = {
28
46
  };
29
47
  declare function assembleStations(candidates: StationConfigInput[], environment: ResolvedEnvironment): AssembledStation[];
30
48
  //#endregion
31
- export { DEFAULT_HISTORY_HOURS, LoadStationCurrentOptions, LoadStationFeedOptions, StationsInput, StationsResolver, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed };
49
+ export { DEFAULT_HISTORY_HOURS, LoadStationCurrentOptions, LoadStationFeedOptions, OpenStationLiveOptions, StationLiveUnsupportedError, StationsInput, StationsResolver, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed, openStationLive };
@@ -4,6 +4,7 @@ import { stationConfigSchema } from "./config.js";
4
4
  import { loadCampbellStation } from "./adapters/campbell.js";
5
5
  import { loadTempestStation } from "./adapters/tempest.js";
6
6
  import { loadWindnerdStation } from "./adapters/windnerd.js";
7
+ import { openWindnerdLive } from "./adapters/windnerd-live.js";
7
8
  //#region src/server/feed.ts
8
9
  const DEFAULT_HISTORY_HOURS = 6;
9
10
  var UnknownStationError = class extends Error {
@@ -12,6 +13,32 @@ var UnknownStationError = class extends Error {
12
13
  this.name = "UnknownStationError";
13
14
  }
14
15
  };
16
+ var StationLiveUnsupportedError = class extends Error {
17
+ constructor(stationId) {
18
+ super(`station "${stationId}" has no live stream`);
19
+ this.name = "StationLiveUnsupportedError";
20
+ }
21
+ };
22
+ /**
23
+ * Opens the live stream for one configured station. Unknown ids throw
24
+ * UnknownStationError; stations whose vendor has no live arm — and stations
25
+ * whose config failed validation — throw StationLiveUnsupportedError; connect
26
+ * failures reject with the upstream error. One call is one upstream
27
+ * connection.
28
+ */
29
+ async function openStationLive(options) {
30
+ const environment = resolveEnvironment(options.environment);
31
+ const entry = assembleStations(await resolveStations({
32
+ stations: options.stations,
33
+ request: options.request
34
+ }, environment), environment).find((candidate) => ("config" in candidate ? candidate.config.id : candidate.degraded.id) === options.stationId);
35
+ if (!entry) throw new UnknownStationError(options.stationId);
36
+ if ("degraded" in entry || entry.config.vendor !== "windnerd") throw new StationLiveUnsupportedError(options.stationId);
37
+ return openWindnerdLive(entry.config, {
38
+ environment,
39
+ signal: options.signal
40
+ });
41
+ }
15
42
  async function loadStationFeed(options) {
16
43
  const environment = resolveEnvironment(options.environment);
17
44
  const assembled = assembleStations(await resolveStations(options, environment), environment);
@@ -213,4 +240,4 @@ function neverThrewButDid(config, environment, error) {
213
240
  return unavailableStation(configFallbackMeta(config), "contract_break");
214
241
  }
215
242
  //#endregion
216
- export { DEFAULT_HISTORY_HOURS, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed };
243
+ export { DEFAULT_HISTORY_HOURS, StationLiveUnsupportedError, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed, openStationLive };
@@ -1,7 +1,7 @@
1
1
  import { ServerEnvironment } from "./environment.js";
2
2
  import { StationsInput } from "./feed.js";
3
3
  //#region src/server/handler.d.ts
4
- type StationFeedHandlerRoute = "feed" | "current";
4
+ type StationFeedHandlerRoute = "feed" | "current" | "live";
5
5
  type StationFeedHandlerOptions = {
6
6
  stations: StationsInput;
7
7
  primaryStationId?: string;
@@ -1,5 +1,6 @@
1
- import { resolveEnvironment } from "./environment.js";
2
- import { UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed } from "./feed.js";
1
+ import { resolveEnvironment, unavailableReasonForError } from "./environment.js";
2
+ import { StationLiveUnsupportedError, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed, openStationLive } from "./feed.js";
3
+ import { STATION_LIVE_SSE_HEADERS, encodeStationLiveSse } from "./live.js";
3
4
  //#region src/server/handler.ts
4
5
  const ALLOWED_METHODS = "GET, HEAD, OPTIONS";
5
6
  function createStationFeedHandler(options) {
@@ -53,8 +54,41 @@ function createStationFeedHandler(options) {
53
54
  });
54
55
  const url = new URL(request.url);
55
56
  const pathname = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
56
- const route = basePath != null ? pathname === `${basePath}/feed` ? "feed" : pathname === `${basePath}/current` ? "current" : null : pathname.endsWith("/feed") ? "feed" : pathname.endsWith("/current") ? "current" : null;
57
+ const route = basePath != null ? pathname === `${basePath}/feed` ? "feed" : pathname === `${basePath}/current` ? "current" : pathname === `${basePath}/live` ? "live" : null : pathname.endsWith("/feed") ? "feed" : pathname.endsWith("/current") ? "current" : pathname.endsWith("/live") ? "live" : null;
57
58
  if (!route) return respond({ error: "not found" }, 404);
59
+ if (route === "live") {
60
+ const stationId = url.searchParams.get("station");
61
+ if (!stationId) return respond({ error: "missing station parameter" }, 400);
62
+ const liveHeaders = {
63
+ ...baseHeaders(),
64
+ ...STATION_LIVE_SSE_HEADERS
65
+ };
66
+ if (isHead) return new Response(null, {
67
+ status: 200,
68
+ headers: liveHeaders
69
+ });
70
+ let frames;
71
+ try {
72
+ frames = await openStationLive({
73
+ stations: options.stations,
74
+ stationId,
75
+ environment: options.environment,
76
+ signal: request.signal,
77
+ request
78
+ });
79
+ } catch (error) {
80
+ if (error instanceof UnknownStationError) return respond({ error: "unknown station" }, 404);
81
+ if (error instanceof StationLiveUnsupportedError) return respond({ error: "station has no live stream" }, 404);
82
+ return respond({
83
+ error: "live stream unavailable",
84
+ reason: unavailableReasonForError(error)
85
+ }, 502);
86
+ }
87
+ return new Response(encodeStationLiveSse(frames), {
88
+ status: 200,
89
+ headers: liveHeaders
90
+ });
91
+ }
58
92
  const hours = parseHoursParam(url, maxHistoryHours);
59
93
  if (hours == null) return respond({ error: `invalid hours: expected a number in (0, ${maxHistoryHours}]` }, 400);
60
94
  const loadOptions = {
@@ -1,10 +1,12 @@
1
1
  import { normalizeWindnerdStationKey, windnerdStationUrl } from "../windnerd.js";
2
- import { DEFAULT_USER_AGENT, FeedCache, LogEvent, LogEventCode, ResolvedEnvironment, ServerEnvironment, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, UpstreamErrorReason, UpstreamFailureReason, UpstreamTextRequest, boundedResponseText, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError } from "./environment.js";
2
+ import { DEFAULT_USER_AGENT, FeedCache, LogEvent, LogEventCode, ResolvedEnvironment, ServerEnvironment, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, UpstreamErrorReason, UpstreamFailureReason, UpstreamStreamRequest, UpstreamTextRequest, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError } from "./environment.js";
3
3
  import { CampbellStationConfig, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, StationConfig, StationConfigInput, TempestStationConfig, WindnerdStationConfig, campbellStationConfigSchema, customStationConfigSchema, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema } from "./config.js";
4
4
  import { StationAdapter, StationAdapterContext, StationAdapterDefinition, StationAdapterMode, StationAdapterOptions, StationAdapterResult, defineStationAdapter } from "./adapter.js";
5
- import { DEFAULT_HISTORY_HOURS, LoadStationCurrentOptions, LoadStationFeedOptions, StationsInput, StationsResolver, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed } from "./feed.js";
5
+ import { DEFAULT_HISTORY_HOURS, LoadStationCurrentOptions, LoadStationFeedOptions, OpenStationLiveOptions, StationLiveUnsupportedError, StationsInput, StationsResolver, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed, openStationLive } from "./feed.js";
6
6
  import { StationFeedHandler, StationFeedHandlerOptions, StationFeedHandlerRoute, createStationFeedHandler } from "./handler.js";
7
- import { WindnerdAdapterOptions, WindnerdRecords, loadWindnerdStation, parseWindnerdRecords, windnerdHistoryPoints } from "./adapters/windnerd.js";
7
+ import { STATION_LIVE_SSE_HEADERS, encodeStationLiveSse } from "./live.js";
8
+ import { WindnerdLiveOptions, openWindnerdLive } from "./adapters/windnerd-live.js";
9
+ import { WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, WindnerdAdapterOptions, WindnerdLiveDigest, WindnerdLiveInit, WindnerdLiveSampleRecord, WindnerdRecords, loadWindnerdStation, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl } from "./adapters/windnerd.js";
8
10
  import { TempestAdapterOptions, TempestObservation, loadTempestStation, parseTempestWind } from "./adapters/tempest.js";
9
11
  import { CAMPBELL_FIELD_CONTRACTS, CampbellAdapterOptions, CampbellTable, CampbellTableExpectation, loadCampbellCurrent, loadCampbellStation, naiveLocalToIso, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable } from "./adapters/campbell.js";
10
- export { CAMPBELL_FIELD_CONTRACTS, type CampbellAdapterOptions, CampbellStationConfig, type CampbellTable, type CampbellTableExpectation, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, DEFAULT_HISTORY_HOURS, DEFAULT_USER_AGENT, FeedCache, LoadStationCurrentOptions, LoadStationFeedOptions, LogEvent, LogEventCode, ResolvedEnvironment, ServerEnvironment, StationAdapter, StationAdapterContext, StationAdapterDefinition, StationAdapterMode, StationAdapterOptions, StationAdapterResult, StationConfig, StationConfigInput, StationFeedHandler, StationFeedHandlerOptions, StationFeedHandlerRoute, StationsInput, StationsResolver, type TempestAdapterOptions, type TempestObservation, TempestStationConfig, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UnknownStationError, UpstreamError, type UpstreamErrorReason, type UpstreamFailureReason, UpstreamTextRequest, type WindnerdAdapterOptions, type WindnerdRecords, WindnerdStationConfig, assembleStations, boundedResponseText, campbellStationConfigSchema, createStationFeedHandler, customStationConfigSchema, defineStationAdapter, fetchUpstreamText, loadCampbellCurrent, loadCampbellStation, loadStationCurrent, loadStationFeed, loadTempestStation, loadWindnerdStation, logUpstreamFailure, memoryCache, naiveLocalToIso, normalizeWindnerdStationKey, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable, parseStationConfig, parseTempestWind, parseWindnerdRecords, resolveEnvironment, stationConfigSchema, tempestStationConfigSchema, unavailableReasonForError, windnerdHistoryPoints, windnerdStationConfigSchema, windnerdStationUrl };
12
+ export { CAMPBELL_FIELD_CONTRACTS, type CampbellAdapterOptions, CampbellStationConfig, type CampbellTable, type CampbellTableExpectation, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, DEFAULT_HISTORY_HOURS, DEFAULT_USER_AGENT, FeedCache, LoadStationCurrentOptions, LoadStationFeedOptions, LogEvent, LogEventCode, OpenStationLiveOptions, ResolvedEnvironment, STATION_LIVE_SSE_HEADERS, ServerEnvironment, StationAdapter, StationAdapterContext, StationAdapterDefinition, StationAdapterMode, StationAdapterOptions, StationAdapterResult, StationConfig, StationConfigInput, StationFeedHandler, StationFeedHandlerOptions, StationFeedHandlerRoute, StationLiveUnsupportedError, StationsInput, StationsResolver, type TempestAdapterOptions, type TempestObservation, TempestStationConfig, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UnknownStationError, UpstreamError, type UpstreamErrorReason, type UpstreamFailureReason, UpstreamStreamRequest, UpstreamTextRequest, WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, type WindnerdAdapterOptions, type WindnerdLiveDigest, type WindnerdLiveInit, type WindnerdLiveOptions, type WindnerdLiveSampleRecord, type WindnerdRecords, WindnerdStationConfig, assembleStations, boundedResponseText, campbellStationConfigSchema, coalesceUpstreamLoad, createStationFeedHandler, customStationConfigSchema, defineStationAdapter, encodeStationLiveSse, fetchUpstreamStream, fetchUpstreamText, loadCampbellCurrent, loadCampbellStation, loadStationCurrent, loadStationFeed, loadTempestStation, loadWindnerdStation, logUpstreamFailure, memoryCache, naiveLocalToIso, normalizeWindnerdStationKey, openStationLive, openWindnerdLive, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable, parseStationConfig, parseTempestWind, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, resolveEnvironment, stationConfigSchema, tempestStationConfigSchema, unavailableReasonForError, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl, windnerdStationConfigSchema, windnerdStationUrl };
@@ -1,10 +1,12 @@
1
1
  import { normalizeWindnerdStationKey, windnerdStationUrl } from "../windnerd.js";
2
- import { DEFAULT_USER_AGENT, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, boundedResponseText, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError } from "./environment.js";
2
+ import { DEFAULT_USER_AGENT, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UpstreamError, boundedResponseText, coalesceUpstreamLoad, fetchUpstreamStream, fetchUpstreamText, logUpstreamFailure, memoryCache, resolveEnvironment, unavailableReasonForError } from "./environment.js";
3
3
  import { campbellStationConfigSchema, customStationConfigSchema, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema } from "./config.js";
4
4
  import { CAMPBELL_FIELD_CONTRACTS, loadCampbellCurrent, loadCampbellStation, naiveLocalToIso, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable } from "./adapters/campbell.js";
5
5
  import { loadTempestStation, parseTempestWind } from "./adapters/tempest.js";
6
- import { loadWindnerdStation, parseWindnerdRecords, windnerdHistoryPoints } from "./adapters/windnerd.js";
7
- import { DEFAULT_HISTORY_HOURS, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed } from "./feed.js";
6
+ import { WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, loadWindnerdStation, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl } from "./adapters/windnerd.js";
7
+ import { openWindnerdLive } from "./adapters/windnerd-live.js";
8
+ import { DEFAULT_HISTORY_HOURS, StationLiveUnsupportedError, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed, openStationLive } from "./feed.js";
8
9
  import { defineStationAdapter } from "./adapter.js";
10
+ import { STATION_LIVE_SSE_HEADERS, encodeStationLiveSse } from "./live.js";
9
11
  import { createStationFeedHandler } from "./handler.js";
10
- export { CAMPBELL_FIELD_CONTRACTS, DEFAULT_HISTORY_HOURS, DEFAULT_USER_AGENT, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UnknownStationError, UpstreamError, assembleStations, boundedResponseText, campbellStationConfigSchema, createStationFeedHandler, customStationConfigSchema, defineStationAdapter, fetchUpstreamText, loadCampbellCurrent, loadCampbellStation, loadStationCurrent, loadStationFeed, loadTempestStation, loadWindnerdStation, logUpstreamFailure, memoryCache, naiveLocalToIso, normalizeWindnerdStationKey, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable, parseStationConfig, parseTempestWind, parseWindnerdRecords, resolveEnvironment, stationConfigSchema, tempestStationConfigSchema, unavailableReasonForError, windnerdHistoryPoints, windnerdStationConfigSchema, windnerdStationUrl };
12
+ export { CAMPBELL_FIELD_CONTRACTS, DEFAULT_HISTORY_HOURS, DEFAULT_USER_AGENT, STATION_LIVE_SSE_HEADERS, StationLiveUnsupportedError, UPSTREAM_CONNECT_TIMEOUT_MS, UPSTREAM_FAILURE_REASONS, UPSTREAM_FETCH_TIMEOUT_MS, UPSTREAM_RESPONSE_LIMIT_BYTES, UnknownStationError, UpstreamError, WINDNERD_LIVE_SAMPLE_INTERVAL_SECONDS, assembleStations, boundedResponseText, campbellStationConfigSchema, coalesceUpstreamLoad, createStationFeedHandler, customStationConfigSchema, defineStationAdapter, encodeStationLiveSse, fetchUpstreamStream, fetchUpstreamText, loadCampbellCurrent, loadCampbellStation, loadStationCurrent, loadStationFeed, loadTempestStation, loadWindnerdStation, logUpstreamFailure, memoryCache, naiveLocalToIso, normalizeWindnerdStationKey, openStationLive, openWindnerdLive, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable, parseStationConfig, parseTempestWind, parseWindnerdLiveDigest, parseWindnerdLiveInit, parseWindnerdLiveSampleRecords, parseWindnerdRecords, resolveEnvironment, stationConfigSchema, tempestStationConfigSchema, unavailableReasonForError, windnerdHistoryPoints, windnerdLiveReading, windnerdLiveSamples, windnerdLiveStreamUrl, windnerdStationConfigSchema, windnerdStationUrl };
@@ -0,0 +1,15 @@
1
+ import { StationLiveFrame } from "../contract.js";
2
+ //#region src/server/live.d.ts
3
+ declare const STATION_LIVE_SSE_HEADERS: {
4
+ readonly "Content-Type": "text/event-stream; charset=utf-8";
5
+ readonly "Cache-Control": "no-cache, no-store";
6
+ readonly "X-Accel-Buffering": "no";
7
+ };
8
+ /**
9
+ * Encodes live frames as SSE bytes, one data event per frame. This plus a
10
+ * vendor open call (openWindnerdLive) is the seam a host uses to serve live
11
+ * data through its own route or fan-out infrastructure.
12
+ */
13
+ declare function encodeStationLiveSse(frames: ReadableStream<StationLiveFrame>): ReadableStream<Uint8Array>;
14
+ //#endregion
15
+ export { STATION_LIVE_SSE_HEADERS, encodeStationLiveSse };
@@ -0,0 +1,19 @@
1
+ //#region src/server/live.ts
2
+ const STATION_LIVE_SSE_HEADERS = {
3
+ "Content-Type": "text/event-stream; charset=utf-8",
4
+ "Cache-Control": "no-cache, no-store",
5
+ "X-Accel-Buffering": "no"
6
+ };
7
+ /**
8
+ * Encodes live frames as SSE bytes, one data event per frame. This plus a
9
+ * vendor open call (openWindnerdLive) is the seam a host uses to serve live
10
+ * data through its own route or fan-out infrastructure.
11
+ */
12
+ function encodeStationLiveSse(frames) {
13
+ const encoder = new TextEncoder();
14
+ return frames.pipeThrough(new TransformStream({ transform(frame, controller) {
15
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(frame)}\n\n`));
16
+ } }));
17
+ }
18
+ //#endregion
19
+ export { STATION_LIVE_SSE_HEADERS, encodeStationLiveSse };
package/dist/sse.js ADDED
@@ -0,0 +1,56 @@
1
+ //#region src/sse.ts
2
+ const DEFAULT_MAX_EVENT_BYTES = 262144;
3
+ async function* sseEvents(body, options = {}) {
4
+ const maxEventBytes = options.maxEventBytes ?? 262144;
5
+ const reader = body.getReader();
6
+ const decoder = new TextDecoder();
7
+ let buffered = "";
8
+ let dataLines = [];
9
+ let eventName = "";
10
+ let eventBytes = 0;
11
+ const abortError = () => new DOMException("SSE read aborted", "AbortError");
12
+ const aborted = options.signal ? new Promise((_resolve, reject) => {
13
+ if (options.signal?.aborted) reject(abortError());
14
+ options.signal?.addEventListener("abort", () => reject(abortError()), { once: true });
15
+ }) : null;
16
+ aborted?.catch(() => void 0);
17
+ const fieldValue = (line, colon) => {
18
+ const value = line.slice(colon + 1);
19
+ return value.startsWith(" ") ? value.slice(1) : value;
20
+ };
21
+ try {
22
+ while (true) {
23
+ const { done, value } = aborted ? await Promise.race([reader.read(), aborted]) : await reader.read();
24
+ buffered += decoder.decode(value ?? /* @__PURE__ */ new Uint8Array(), { stream: !done });
25
+ let newline = buffered.indexOf("\n");
26
+ while (newline !== -1) {
27
+ let line = buffered.slice(0, newline);
28
+ buffered = buffered.slice(newline + 1);
29
+ if (line.endsWith("\r")) line = line.slice(0, -1);
30
+ if (line === "") {
31
+ if (dataLines.length > 0) yield {
32
+ event: eventName === "" ? "message" : eventName,
33
+ data: dataLines.join("\n")
34
+ };
35
+ dataLines = [];
36
+ eventName = "";
37
+ eventBytes = 0;
38
+ } else if (!line.startsWith(":")) {
39
+ eventBytes += line.length;
40
+ if (eventBytes > maxEventBytes) throw new Error(`SSE event exceeded ${maxEventBytes} bytes`);
41
+ const colon = line.indexOf(":");
42
+ const field = colon === -1 ? line : line.slice(0, colon);
43
+ if (field === "data") dataLines.push(colon === -1 ? "" : fieldValue(line, colon));
44
+ else if (field === "event") eventName = colon === -1 ? "" : fieldValue(line, colon);
45
+ }
46
+ newline = buffered.indexOf("\n");
47
+ }
48
+ if (buffered.length > maxEventBytes) throw new Error(`SSE event exceeded ${maxEventBytes} bytes`);
49
+ if (done) return;
50
+ }
51
+ } finally {
52
+ await reader.cancel().catch(() => void 0);
53
+ }
54
+ }
55
+ //#endregion
56
+ export { DEFAULT_MAX_EVENT_BYTES, sseEvents };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@azohra/meteo.station",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "The station capability of meteo by Azohra: live weather-station reading, derivation, and display - the wire contract, provider adapters, a polling client, a Node server, and React and custom-element display bindings.",
5
5
  "keywords": [
6
6
  "weather-station",
package/schema/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Wire contract artifacts
2
2
 
3
3
  The station capability's wire contract in language-neutral form: JSON
4
- Schemas emitted from the zod contract (`station/contract.ts`), plus two
4
+ Schemas emitted from the zod contract (`station/contract.ts`), plus three
5
5
  annotated example documents. Never edited by hand — regenerate with
6
6
  `pnpm schemas` at the workspace root, which must reproduce every file
7
7
  byte-identical (the drift guard is this package's own test suite).
@@ -60,7 +60,9 @@
60
60
  "gustLull": true,
61
61
  "temperature": true,
62
62
  "conditions": true,
63
- "history": true
63
+ "history": true,
64
+ "live": true,
65
+ "battery": true
64
66
  },
65
67
  "samplingWindowSeconds": 60,
66
68
  "recommendedPollSeconds": 60,
@@ -119,6 +121,29 @@
119
121
  "seaLevelPressureHpa": 1006.1
120
122
  }
121
123
  ]
124
+ },
125
+ "telemetry": {
126
+ "batteryVoltage": 4.15
127
+ },
128
+ "samples": {
129
+ "intervalSeconds": 3,
130
+ "points": [
131
+ {
132
+ "observedAt": "2026-08-05T22:12:39.000Z",
133
+ "windMps": 2.2,
134
+ "windDirectionDeg": 288
135
+ },
136
+ {
137
+ "observedAt": "2026-08-05T22:12:42.000Z",
138
+ "windMps": 2.7,
139
+ "windDirectionDeg": 291
140
+ },
141
+ {
142
+ "observedAt": "2026-08-05T22:12:45.000Z",
143
+ "windMps": 0.3,
144
+ "windDirectionDeg": null
145
+ }
146
+ ]
122
147
  }
123
148
  },
124
149
  {
@@ -0,0 +1,74 @@
1
+ {
2
+ "$comment": "Example @azohra/meteo.station live frame — the init frame that opens every /live stream. Each SSE data event validates against stationlive.schema.json; readers must ignore unknown keys (this one included).",
3
+ "type": "init",
4
+ "schemaVersion": 2,
5
+ "servedAt": "2026-08-05T22:13:00.000Z",
6
+ "station": {
7
+ "id": "bluff",
8
+ "name": "Bluff Launch",
9
+ "sourceLabel": "WindNerd",
10
+ "pageUrl": "https://example.com/stations/bluff-launch",
11
+ "latitude": 49.7,
12
+ "longitude": -118.2,
13
+ "timeZone": "America/Vancouver",
14
+ "elevationM": 1370,
15
+ "capabilities": {
16
+ "gustLull": true,
17
+ "temperature": true,
18
+ "conditions": true,
19
+ "history": true,
20
+ "live": true,
21
+ "battery": true
22
+ },
23
+ "samplingWindowSeconds": 60,
24
+ "recommendedPollSeconds": 60,
25
+ "status": "ok",
26
+ "reading": {
27
+ "observedAt": "2026-08-05T22:12:45.000Z",
28
+ "windAvgMps": 2.5,
29
+ "windDirectionDeg": 290,
30
+ "windGustMps": 3.9,
31
+ "windLullMps": 1.7,
32
+ "temperatureC": 22.6,
33
+ "windChillC": null,
34
+ "conditions": {
35
+ "dewPointC": null,
36
+ "lastLightningStrikeAt": null,
37
+ "lastLightningStrikeDistanceKm": null,
38
+ "lightningStrikeCountLastHour": null,
39
+ "precipitationMinutesToday": null,
40
+ "precipitationRateMmPerHour": null,
41
+ "precipitationTodayMm": null,
42
+ "pressureTrend": "steady",
43
+ "relativeHumidityPercent": null,
44
+ "seaLevelPressureHpa": 1006.1,
45
+ "solarRadiationWm2": null,
46
+ "uvIndex": null
47
+ }
48
+ },
49
+ "history": null,
50
+ "telemetry": {
51
+ "batteryVoltage": 4.15
52
+ },
53
+ "samples": {
54
+ "intervalSeconds": 3,
55
+ "points": [
56
+ {
57
+ "observedAt": "2026-08-05T22:12:39.000Z",
58
+ "windMps": 2.2,
59
+ "windDirectionDeg": 288
60
+ },
61
+ {
62
+ "observedAt": "2026-08-05T22:12:42.000Z",
63
+ "windMps": 2.7,
64
+ "windDirectionDeg": 291
65
+ },
66
+ {
67
+ "observedAt": "2026-08-05T22:12:45.000Z",
68
+ "windMps": 0.3,
69
+ "windDirectionDeg": null
70
+ }
71
+ ]
72
+ }
73
+ }
74
+ }