@azohra/meteo.station 0.1.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 +21 -0
- package/README.md +53 -0
- package/dist/air.d.ts +13 -0
- package/dist/air.js +76 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +4 -0
- package/dist/client/poll.d.ts +42 -0
- package/dist/client/poll.js +121 -0
- package/dist/client/stores.d.ts +46 -0
- package/dist/client/stores.js +128 -0
- package/dist/client/ticker.d.ts +4 -0
- package/dist/client/ticker.js +19 -0
- package/dist/contract.d.ts +381 -0
- package/dist/contract.js +143 -0
- package/dist/derive.d.ts +54 -0
- package/dist/derive.js +134 -0
- package/dist/display.d.ts +28 -0
- package/dist/display.js +27 -0
- package/dist/elements/elements/AirMatrixElement.d.ts +14 -0
- package/dist/elements/elements/AirMatrixElement.js +83 -0
- package/dist/elements/elements/CurrentConditionsElement.d.ts +9 -0
- package/dist/elements/elements/CurrentConditionsElement.js +52 -0
- package/dist/elements/elements/DailyPatternElement.d.ts +15 -0
- package/dist/elements/elements/DailyPatternElement.js +200 -0
- package/dist/elements/elements/DialElement.d.ts +9 -0
- package/dist/elements/elements/DialElement.js +128 -0
- package/dist/elements/elements/FreshnessBadgeElement.d.ts +8 -0
- package/dist/elements/elements/FreshnessBadgeElement.js +22 -0
- package/dist/elements/elements/SparklineElement.d.ts +9 -0
- package/dist/elements/elements/SparklineElement.js +74 -0
- package/dist/elements/elements/StationCardElement.d.ts +53 -0
- package/dist/elements/elements/StationCardElement.js +211 -0
- package/dist/elements/elements/StationFeedElement.d.ts +32 -0
- package/dist/elements/elements/StationFeedElement.js +215 -0
- package/dist/elements/elements/StationStripElement.d.ts +9 -0
- package/dist/elements/elements/StationStripElement.js +43 -0
- package/dist/elements/elements/StationTableElement.d.ts +18 -0
- package/dist/elements/elements/StationTableElement.js +102 -0
- package/dist/elements/elements/TrendChartElement.d.ts +10 -0
- package/dist/elements/elements/TrendChartElement.js +174 -0
- package/dist/elements/elements/WindArrowElement.d.ts +8 -0
- package/dist/elements/elements/WindArrowElement.js +14 -0
- package/dist/elements/elements/WindHistoryChartElement.d.ts +10 -0
- package/dist/elements/elements/WindHistoryChartElement.js +277 -0
- package/dist/elements/elements/WindRoseElement.d.ts +17 -0
- package/dist/elements/elements/WindRoseElement.js +106 -0
- package/dist/elements/elements/atoms.d.ts +48 -0
- package/dist/elements/elements/atoms.js +131 -0
- package/dist/elements/index.d.ts +48 -0
- package/dist/elements/index.js +57 -0
- package/dist/elements/lib/ambient.d.ts +15 -0
- package/dist/elements/lib/ambient.js +5 -0
- package/dist/elements/lib/attributes.js +21 -0
- package/dist/elements/lib/base.d.ts +45 -0
- package/dist/elements/lib/base.js +152 -0
- package/dist/elements/lib/context.js +28 -0
- package/dist/elements/lib/fragments.js +45 -0
- package/dist/elements/lib/h.js +35 -0
- package/dist/elements/register.d.ts +1 -0
- package/dist/elements/register.js +5 -0
- package/dist/endpoints.d.ts +5 -0
- package/dist/endpoints.js +10 -0
- package/dist/fixtures.d.ts +23 -0
- package/dist/fixtures.js +67 -0
- package/dist/format.d.ts +31 -0
- package/dist/format.js +82 -0
- package/dist/geometry.d.ts +84 -0
- package/dist/geometry.js +333 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/dist/instruments.d.ts +75 -0
- package/dist/instruments.js +173 -0
- package/dist/merge-current.d.ts +13 -0
- package/dist/merge-current.js +54 -0
- package/dist/react/components/AirMatrix.d.ts +11 -0
- package/dist/react/components/AirMatrix.js +82 -0
- package/dist/react/components/CurrentConditions.d.ts +17 -0
- package/dist/react/components/CurrentConditions.js +98 -0
- package/dist/react/components/DailyPattern.d.ts +19 -0
- package/dist/react/components/DailyPattern.js +212 -0
- package/dist/react/components/Dial.d.ts +17 -0
- package/dist/react/components/Dial.js +133 -0
- package/dist/react/components/FreshnessBadge.d.ts +10 -0
- package/dist/react/components/FreshnessBadge.js +20 -0
- package/dist/react/components/Sparkline.d.ts +17 -0
- package/dist/react/components/Sparkline.js +60 -0
- package/dist/react/components/StationCard.d.ts +46 -0
- package/dist/react/components/StationCard.js +140 -0
- package/dist/react/components/StationFeedProvider.d.ts +27 -0
- package/dist/react/components/StationFeedProvider.js +40 -0
- package/dist/react/components/StationStrip.d.ts +16 -0
- package/dist/react/components/StationStrip.js +84 -0
- package/dist/react/components/StationTable.d.ts +18 -0
- package/dist/react/components/StationTable.js +115 -0
- package/dist/react/components/TrendChart.d.ts +14 -0
- package/dist/react/components/TrendChart.js +150 -0
- package/dist/react/components/WindArrow.d.ts +7 -0
- package/dist/react/components/WindArrow.js +21 -0
- package/dist/react/components/WindHistoryChart.d.ts +18 -0
- package/dist/react/components/WindHistoryChart.js +278 -0
- package/dist/react/components/WindRose.d.ts +17 -0
- package/dist/react/components/WindRose.js +99 -0
- package/dist/react/components/atoms.d.ts +33 -0
- package/dist/react/components/atoms.js +136 -0
- package/dist/react/hooks/useFreshness.d.ts +6 -0
- package/dist/react/hooks/useFreshness.js +21 -0
- package/dist/react/hooks/usePolledJson.js +17 -0
- package/dist/react/hooks/useStation.d.ts +23 -0
- package/dist/react/hooks/useStation.js +42 -0
- package/dist/react/hooks/useStationCurrent.d.ts +23 -0
- package/dist/react/hooks/useStationCurrent.js +32 -0
- package/dist/react/hooks/useStationFeed.d.ts +22 -0
- package/dist/react/hooks/useStationFeed.js +28 -0
- package/dist/react/index.d.ts +20 -0
- package/dist/react/index.js +21 -0
- package/dist/react/lib/cells.js +29 -0
- package/dist/scene/air-matrix.js +71 -0
- package/dist/scene/atoms.js +102 -0
- package/dist/scene/card.js +54 -0
- package/dist/scene/chart.js +28 -0
- package/dist/scene/current.js +66 -0
- package/dist/scene/daily-pattern.js +81 -0
- package/dist/scene/dial.js +141 -0
- package/dist/scene/glyphs.js +24 -0
- package/dist/scene/rose.js +120 -0
- package/dist/scene/sparkline.js +73 -0
- package/dist/scene/strip.js +63 -0
- package/dist/scene/table.js +76 -0
- package/dist/scene/trend.js +160 -0
- package/dist/scene/wind-history.js +148 -0
- package/dist/scene/wind-plot.js +214 -0
- package/dist/server/adapter.d.ts +28 -0
- package/dist/server/adapter.js +32 -0
- package/dist/server/adapters/campbell.d.ts +112 -0
- package/dist/server/adapters/campbell.js +414 -0
- package/dist/server/adapters/tempest.d.ts +27 -0
- package/dist/server/adapters/tempest.js +137 -0
- package/dist/server/adapters/windnerd.d.ts +39 -0
- package/dist/server/adapters/windnerd.js +159 -0
- package/dist/server/config.d.ts +135 -0
- package/dist/server/config.js +57 -0
- package/dist/server/environment.d.ts +48 -0
- package/dist/server/environment.js +128 -0
- package/dist/server/feed.d.ts +31 -0
- package/dist/server/feed.js +216 -0
- package/dist/server/handler.d.ts +17 -0
- package/dist/server/handler.js +133 -0
- package/dist/server/index.d.ts +10 -0
- package/dist/server/index.js +10 -0
- package/dist/strings.d.ts +118 -0
- package/dist/strings.js +237 -0
- package/dist/windnerd.d.ts +5 -0
- package/dist/windnerd.js +25 -0
- package/package.json +97 -0
- package/schema/README.md +14 -0
- package/schema/example-current.json +48 -0
- package/schema/example-feed.json +147 -0
- package/schema/stationcurrent.schema.json +641 -0
- package/schema/stationfeed.schema.json +656 -0
- package/styles.css +1141 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { stationSchema, unavailableStation } from "../contract.js";
|
|
2
|
+
import { logUpstreamFailure, resolveEnvironment, unavailableReasonForError } from "./environment.js";
|
|
3
|
+
import { stationConfigSchema } from "./config.js";
|
|
4
|
+
import { loadCampbellStation } from "./adapters/campbell.js";
|
|
5
|
+
import { loadTempestStation } from "./adapters/tempest.js";
|
|
6
|
+
import { loadWindnerdStation } from "./adapters/windnerd.js";
|
|
7
|
+
//#region src/server/feed.ts
|
|
8
|
+
const DEFAULT_HISTORY_HOURS = 6;
|
|
9
|
+
var UnknownStationError = class extends Error {
|
|
10
|
+
constructor(stationId) {
|
|
11
|
+
super(`no station is configured with id "${stationId}"`);
|
|
12
|
+
this.name = "UnknownStationError";
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
async function loadStationFeed(options) {
|
|
16
|
+
const environment = resolveEnvironment(options.environment);
|
|
17
|
+
const assembled = assembleStations(await resolveStations(options, environment), environment);
|
|
18
|
+
const historyHours = effectiveHistoryHours(options);
|
|
19
|
+
const stations = await Promise.all(assembled.map((entry) => loadAssembledStation(entry, environment, historyHours, "full")));
|
|
20
|
+
return {
|
|
21
|
+
schemaVersion: 2,
|
|
22
|
+
servedAt: environment.now().toISOString(),
|
|
23
|
+
primaryStationId: options.primaryStationId ?? null,
|
|
24
|
+
stations
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
async function loadStationCurrent(options) {
|
|
28
|
+
const environment = resolveEnvironment(options.environment);
|
|
29
|
+
const entry = assembleStations(await resolveStations(options, environment), environment).find((candidate) => ("config" in candidate ? candidate.config.id : candidate.degraded.id) === options.stationId);
|
|
30
|
+
if (!entry) throw new UnknownStationError(options.stationId);
|
|
31
|
+
const station = await loadAssembledStation(entry, environment, effectiveHistoryHours(options), "current");
|
|
32
|
+
return {
|
|
33
|
+
schemaVersion: 2,
|
|
34
|
+
servedAt: environment.now().toISOString(),
|
|
35
|
+
station
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
async function resolveStations(options, environment) {
|
|
39
|
+
if (Array.isArray(options.stations)) return options.stations;
|
|
40
|
+
const resolved = await options.stations(options.request);
|
|
41
|
+
if (!Array.isArray(resolved)) {
|
|
42
|
+
environment.logger({
|
|
43
|
+
level: "error",
|
|
44
|
+
code: "resolver_invalid",
|
|
45
|
+
message: "stations resolver returned a non-array; serving an empty feed",
|
|
46
|
+
detail: { returned: typeof resolved }
|
|
47
|
+
});
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
return resolved;
|
|
51
|
+
}
|
|
52
|
+
function effectiveHistoryHours(options) {
|
|
53
|
+
const ceiling = options.maxHistoryHours ?? 6;
|
|
54
|
+
const requested = options.historyHours;
|
|
55
|
+
const wanted = requested != null && Number.isFinite(requested) && requested > 0 ? requested : ceiling;
|
|
56
|
+
return options.maxHistoryHours != null ? Math.min(wanted, options.maxHistoryHours) : wanted;
|
|
57
|
+
}
|
|
58
|
+
function assembleStations(candidates, environment) {
|
|
59
|
+
const seen = /* @__PURE__ */ new Set();
|
|
60
|
+
return candidates.map((candidate, index) => {
|
|
61
|
+
const result = stationConfigSchema.safeParse(candidate);
|
|
62
|
+
if (!result.success) {
|
|
63
|
+
environment.logger({
|
|
64
|
+
level: "warn",
|
|
65
|
+
code: "config_invalid",
|
|
66
|
+
message: `station config at index ${index} is invalid — serving it unavailable (not_configured)`,
|
|
67
|
+
detail: {
|
|
68
|
+
index,
|
|
69
|
+
issues: describeIssues(result.error)
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
const meta = scavengedMeta(candidate, index);
|
|
73
|
+
seen.add(meta.id);
|
|
74
|
+
return { degraded: unavailableStation(meta, "not_configured") };
|
|
75
|
+
}
|
|
76
|
+
if (seen.has(result.data.id)) {
|
|
77
|
+
environment.logger({
|
|
78
|
+
level: "warn",
|
|
79
|
+
code: "duplicate_station",
|
|
80
|
+
message: `duplicate station id "${result.data.id}" at index ${index} — serving the duplicate unavailable (not_configured); ids must be unique per feed`,
|
|
81
|
+
detail: {
|
|
82
|
+
index,
|
|
83
|
+
station: result.data.id
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
return { degraded: unavailableStation(configFallbackMeta(result.data), "not_configured") };
|
|
87
|
+
}
|
|
88
|
+
seen.add(result.data.id);
|
|
89
|
+
return { config: result.data };
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function describeIssues(error) {
|
|
93
|
+
return error.issues.map((issue) => `${issue.path.join(".") || "(config)"}: ${issue.message}`).join("; ");
|
|
94
|
+
}
|
|
95
|
+
function scavengedMeta(candidate, index) {
|
|
96
|
+
const record = typeof candidate === "object" && candidate !== null ? candidate : {};
|
|
97
|
+
const id = typeof record.id === "string" && record.id.length > 0 ? record.id : `station-${index}`;
|
|
98
|
+
return {
|
|
99
|
+
id,
|
|
100
|
+
name: typeof record.name === "string" && record.name.length > 0 ? record.name : id,
|
|
101
|
+
sourceLabel: typeof record.vendor === "string" ? record.vendor : "unknown",
|
|
102
|
+
pageUrl: null,
|
|
103
|
+
latitude: null,
|
|
104
|
+
longitude: null,
|
|
105
|
+
timeZone: null,
|
|
106
|
+
elevationM: null,
|
|
107
|
+
capabilities: {
|
|
108
|
+
gustLull: false,
|
|
109
|
+
temperature: false,
|
|
110
|
+
conditions: false,
|
|
111
|
+
history: false
|
|
112
|
+
},
|
|
113
|
+
samplingWindowSeconds: null,
|
|
114
|
+
recommendedPollSeconds: 60
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function configFallbackMeta(config) {
|
|
118
|
+
return {
|
|
119
|
+
id: config.id,
|
|
120
|
+
name: config.name,
|
|
121
|
+
sourceLabel: config.vendor,
|
|
122
|
+
pageUrl: null,
|
|
123
|
+
latitude: config.latitude ?? null,
|
|
124
|
+
longitude: config.longitude ?? null,
|
|
125
|
+
timeZone: config.timeZone ?? null,
|
|
126
|
+
elevationM: config.elevationM ?? null,
|
|
127
|
+
capabilities: {
|
|
128
|
+
gustLull: false,
|
|
129
|
+
temperature: false,
|
|
130
|
+
conditions: false,
|
|
131
|
+
history: false
|
|
132
|
+
},
|
|
133
|
+
samplingWindowSeconds: null,
|
|
134
|
+
recommendedPollSeconds: 60
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
async function loadAssembledStation(entry, environment, historyHours, mode) {
|
|
138
|
+
if ("degraded" in entry) return entry.degraded;
|
|
139
|
+
return loadStation(entry.config, environment, historyHours, mode).catch((error) => neverThrewButDid(entry.config, environment, error));
|
|
140
|
+
}
|
|
141
|
+
async function loadStation(config, environment, historyHours, mode) {
|
|
142
|
+
switch (config.vendor) {
|
|
143
|
+
case "windnerd": return loadWindnerdStation(config, {
|
|
144
|
+
historyHours,
|
|
145
|
+
mode,
|
|
146
|
+
environment
|
|
147
|
+
});
|
|
148
|
+
case "tempest": return loadTempestStation(config, {
|
|
149
|
+
historyHours,
|
|
150
|
+
mode,
|
|
151
|
+
environment
|
|
152
|
+
});
|
|
153
|
+
case "campbell": return loadCampbellStation(config, {
|
|
154
|
+
historyHours,
|
|
155
|
+
mode,
|
|
156
|
+
environment
|
|
157
|
+
});
|
|
158
|
+
case "custom": return loadCustomStation(config, environment, historyHours, mode);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async function loadCustomStation(config, environment, historyHours, mode) {
|
|
162
|
+
let returned;
|
|
163
|
+
try {
|
|
164
|
+
returned = await config.load({
|
|
165
|
+
environment,
|
|
166
|
+
historyHours,
|
|
167
|
+
mode,
|
|
168
|
+
station: customStationIdentity(config)
|
|
169
|
+
});
|
|
170
|
+
} catch (error) {
|
|
171
|
+
logUpstreamFailure(environment, `${config.name} live wind unavailable`, error, { station: config.id });
|
|
172
|
+
return unavailableStation(configFallbackMeta(config), unavailableReasonForError(error));
|
|
173
|
+
}
|
|
174
|
+
const parsed = stationSchema.safeParse(returned);
|
|
175
|
+
if (!parsed.success) {
|
|
176
|
+
environment.logger({
|
|
177
|
+
level: "error",
|
|
178
|
+
code: "custom_contract_break",
|
|
179
|
+
message: `${config.name} custom loader returned an invalid Station`,
|
|
180
|
+
detail: {
|
|
181
|
+
station: config.id,
|
|
182
|
+
issues: describeIssues(parsed.error)
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
return unavailableStation(configFallbackMeta(config), "contract_break");
|
|
186
|
+
}
|
|
187
|
+
return mode === "current" && parsed.data.status === "ok" ? {
|
|
188
|
+
...parsed.data,
|
|
189
|
+
history: null
|
|
190
|
+
} : parsed.data;
|
|
191
|
+
}
|
|
192
|
+
function customStationIdentity(config) {
|
|
193
|
+
return {
|
|
194
|
+
id: config.id,
|
|
195
|
+
name: config.name,
|
|
196
|
+
elevationM: config.elevationM ?? null,
|
|
197
|
+
latitude: config.latitude ?? null,
|
|
198
|
+
longitude: config.longitude ?? null,
|
|
199
|
+
timeZone: config.timeZone ?? null,
|
|
200
|
+
pageUrl: config.pageUrl ?? null
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
function neverThrewButDid(config, environment, error) {
|
|
204
|
+
environment.logger({
|
|
205
|
+
level: "error",
|
|
206
|
+
code: "adapter_threw",
|
|
207
|
+
message: `${config.name} adapter threw instead of degrading`,
|
|
208
|
+
detail: {
|
|
209
|
+
error: error instanceof Error ? error.message : String(error),
|
|
210
|
+
station: config.id
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
return unavailableStation(configFallbackMeta(config), "contract_break");
|
|
214
|
+
}
|
|
215
|
+
//#endregion
|
|
216
|
+
export { DEFAULT_HISTORY_HOURS, UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ServerEnvironment } from "./environment.js";
|
|
2
|
+
import { StationsInput } from "./feed.js";
|
|
3
|
+
//#region src/server/handler.d.ts
|
|
4
|
+
type StationFeedHandlerRoute = "feed" | "current";
|
|
5
|
+
type StationFeedHandlerOptions = {
|
|
6
|
+
stations: StationsInput;
|
|
7
|
+
primaryStationId?: string;
|
|
8
|
+
maxHistoryHours?: number;
|
|
9
|
+
basePath?: string;
|
|
10
|
+
cors?: boolean | string;
|
|
11
|
+
cacheControl?: string | ((route: StationFeedHandlerRoute, maxAgeSeconds: number) => string);
|
|
12
|
+
environment?: ServerEnvironment;
|
|
13
|
+
};
|
|
14
|
+
type StationFeedHandler = (request: Request) => Promise<Response>;
|
|
15
|
+
declare function createStationFeedHandler(options: StationFeedHandlerOptions): StationFeedHandler;
|
|
16
|
+
//#endregion
|
|
17
|
+
export { StationFeedHandler, StationFeedHandlerOptions, StationFeedHandlerRoute, createStationFeedHandler };
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { resolveEnvironment } from "./environment.js";
|
|
2
|
+
import { UnknownStationError, assembleStations, loadStationCurrent, loadStationFeed } from "./feed.js";
|
|
3
|
+
//#region src/server/handler.ts
|
|
4
|
+
const ALLOWED_METHODS = "GET, HEAD, OPTIONS";
|
|
5
|
+
function createStationFeedHandler(options) {
|
|
6
|
+
const environment = resolveEnvironment(options.environment);
|
|
7
|
+
if (Array.isArray(options.stations)) assembleStations(options.stations, environment);
|
|
8
|
+
const maxHistoryHours = options.maxHistoryHours ?? 6;
|
|
9
|
+
const basePath = options.basePath?.endsWith("/") ? options.basePath.slice(0, -1) : options.basePath;
|
|
10
|
+
const corsOrigin = options.cors === true ? "*" : typeof options.cors === "string" ? options.cors : null;
|
|
11
|
+
const baseHeaders = () => {
|
|
12
|
+
const headers = {};
|
|
13
|
+
if (corsOrigin) {
|
|
14
|
+
headers["Access-Control-Allow-Origin"] = corsOrigin;
|
|
15
|
+
if (corsOrigin !== "*") headers["Vary"] = "Origin";
|
|
16
|
+
}
|
|
17
|
+
return headers;
|
|
18
|
+
};
|
|
19
|
+
const cacheControlFor = (route, maxAgeSeconds) => typeof options.cacheControl === "function" ? options.cacheControl(route, maxAgeSeconds) : options.cacheControl ?? `public, max-age=${Math.round(maxAgeSeconds)}`;
|
|
20
|
+
const json = (body, status, extraHeaders = {}) => new Response(JSON.stringify(body), {
|
|
21
|
+
status,
|
|
22
|
+
headers: {
|
|
23
|
+
...baseHeaders(),
|
|
24
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
25
|
+
...extraHeaders
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
return async (request) => {
|
|
29
|
+
if (request.method === "OPTIONS" && corsOrigin) return new Response(null, {
|
|
30
|
+
status: 204,
|
|
31
|
+
headers: {
|
|
32
|
+
...baseHeaders(),
|
|
33
|
+
"Access-Control-Allow-Methods": ALLOWED_METHODS,
|
|
34
|
+
"Access-Control-Allow-Headers": "Accept, Content-Type",
|
|
35
|
+
"Access-Control-Max-Age": "86400"
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
const isHead = request.method === "HEAD";
|
|
39
|
+
if (request.method !== "GET" && !isHead) return json({ error: "method not allowed" }, 405, { Allow: ALLOWED_METHODS });
|
|
40
|
+
const respond = (body, status, extraHeaders = {}) => {
|
|
41
|
+
const response = json(body, status, extraHeaders);
|
|
42
|
+
return isHead ? new Response(null, {
|
|
43
|
+
status: response.status,
|
|
44
|
+
headers: response.headers
|
|
45
|
+
}) : response;
|
|
46
|
+
};
|
|
47
|
+
const notModified = (extraHeaders) => new Response(null, {
|
|
48
|
+
status: 304,
|
|
49
|
+
headers: {
|
|
50
|
+
...baseHeaders(),
|
|
51
|
+
...extraHeaders
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
const url = new URL(request.url);
|
|
55
|
+
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
|
+
if (!route) return respond({ error: "not found" }, 404);
|
|
58
|
+
const hours = parseHoursParam(url, maxHistoryHours);
|
|
59
|
+
if (hours == null) return respond({ error: `invalid hours: expected a number in (0, ${maxHistoryHours}]` }, 400);
|
|
60
|
+
const loadOptions = {
|
|
61
|
+
stations: options.stations,
|
|
62
|
+
primaryStationId: options.primaryStationId,
|
|
63
|
+
historyHours: hours,
|
|
64
|
+
maxHistoryHours,
|
|
65
|
+
environment: options.environment,
|
|
66
|
+
request
|
|
67
|
+
};
|
|
68
|
+
if (route === "feed") {
|
|
69
|
+
const feed = await loadStationFeed(loadOptions);
|
|
70
|
+
const maxAge = feed.stations.length === 0 ? 60 : feed.stations.reduce((least, station) => Math.min(least, station.recommendedPollSeconds), Infinity);
|
|
71
|
+
const headers = {
|
|
72
|
+
"Cache-Control": cacheControlFor("feed", maxAge),
|
|
73
|
+
ETag: weakEtag({
|
|
74
|
+
schemaVersion: feed.schemaVersion,
|
|
75
|
+
primaryStationId: feed.primaryStationId,
|
|
76
|
+
stations: feed.stations
|
|
77
|
+
})
|
|
78
|
+
};
|
|
79
|
+
if (etagMatches(request.headers.get("If-None-Match"), headers.ETag)) return notModified(headers);
|
|
80
|
+
return respond(feed, 200, headers);
|
|
81
|
+
}
|
|
82
|
+
const stationId = url.searchParams.get("station");
|
|
83
|
+
if (!stationId) return respond({ error: "missing station parameter" }, 400);
|
|
84
|
+
let current;
|
|
85
|
+
try {
|
|
86
|
+
current = await loadStationCurrent({
|
|
87
|
+
...loadOptions,
|
|
88
|
+
stationId
|
|
89
|
+
});
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error instanceof UnknownStationError) return respond({ error: "unknown station" }, 404);
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
const headers = {
|
|
95
|
+
"Cache-Control": cacheControlFor("current", current.station.recommendedPollSeconds),
|
|
96
|
+
ETag: weakEtag({
|
|
97
|
+
schemaVersion: current.schemaVersion,
|
|
98
|
+
station: current.station
|
|
99
|
+
})
|
|
100
|
+
};
|
|
101
|
+
if (etagMatches(request.headers.get("If-None-Match"), headers.ETag)) return notModified(headers);
|
|
102
|
+
return respond(current, 200, headers);
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const HOURS_STEP = .25;
|
|
106
|
+
function parseHoursParam(url, ceiling) {
|
|
107
|
+
const raw = url.searchParams.get("hours");
|
|
108
|
+
if (raw == null) return ceiling;
|
|
109
|
+
const value = Number(raw.trim() === "" ? NaN : raw);
|
|
110
|
+
if (!Number.isFinite(value) || value <= 0 || value > ceiling) return null;
|
|
111
|
+
const quantized = Math.round(value / HOURS_STEP) * HOURS_STEP;
|
|
112
|
+
return Math.min(ceiling, Math.max(HOURS_STEP, quantized));
|
|
113
|
+
}
|
|
114
|
+
function weakEtag(value) {
|
|
115
|
+
const text = JSON.stringify(value);
|
|
116
|
+
let h1 = 2166136261;
|
|
117
|
+
let h2 = 19088743;
|
|
118
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
119
|
+
const code = text.charCodeAt(index);
|
|
120
|
+
h1 = Math.imul(h1 ^ code, 16777619) >>> 0;
|
|
121
|
+
h2 = Math.imul(h2 ^ code, 16777619) >>> 0;
|
|
122
|
+
}
|
|
123
|
+
const hex = (value32) => value32.toString(16).padStart(8, "0");
|
|
124
|
+
return `W/"${hex(h1)}${hex(h2)}"`;
|
|
125
|
+
}
|
|
126
|
+
function etagMatches(ifNoneMatch, etag) {
|
|
127
|
+
if (!ifNoneMatch) return false;
|
|
128
|
+
if (ifNoneMatch.trim() === "*") return true;
|
|
129
|
+
const bare = (tag) => tag.startsWith("W/") ? tag.slice(2) : tag;
|
|
130
|
+
return ifNoneMatch.split(",").some((candidate) => bare(candidate.trim()) === bare(etag));
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
export { createStationFeedHandler };
|
|
@@ -0,0 +1,10 @@
|
|
|
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";
|
|
3
|
+
import { CampbellStationConfig, CustomStationConfig, CustomStationContext, CustomStationIdentity, CustomStationLoader, StationConfig, StationConfigInput, TempestStationConfig, WindnerdStationConfig, campbellStationConfigSchema, customStationConfigSchema, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema } from "./config.js";
|
|
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";
|
|
6
|
+
import { StationFeedHandler, StationFeedHandlerOptions, StationFeedHandlerRoute, createStationFeedHandler } from "./handler.js";
|
|
7
|
+
import { WindnerdAdapterOptions, WindnerdRecords, loadWindnerdStation, parseWindnerdRecords, windnerdHistoryPoints } from "./adapters/windnerd.js";
|
|
8
|
+
import { TempestAdapterOptions, TempestObservation, loadTempestStation, parseTempestWind } from "./adapters/tempest.js";
|
|
9
|
+
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 };
|
|
@@ -0,0 +1,10 @@
|
|
|
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";
|
|
3
|
+
import { campbellStationConfigSchema, customStationConfigSchema, parseStationConfig, stationConfigSchema, tempestStationConfigSchema, windnerdStationConfigSchema } from "./config.js";
|
|
4
|
+
import { CAMPBELL_FIELD_CONTRACTS, loadCampbellCurrent, loadCampbellStation, naiveLocalToIso, parseCampbellCurrent, parseCampbellHistory, parseCampbellTable } from "./adapters/campbell.js";
|
|
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";
|
|
8
|
+
import { defineStationAdapter } from "./adapter.js";
|
|
9
|
+
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 };
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { UnavailableReason } from "./contract.js";
|
|
2
|
+
import { CompassPoint, FreshnessStatus, SpeedUnit } from "./derive.js";
|
|
3
|
+
//#region src/strings.d.ts
|
|
4
|
+
type StationStrings = {
|
|
5
|
+
averageLabel: string;
|
|
6
|
+
avgLabel: string;
|
|
7
|
+
calm: string;
|
|
8
|
+
calmHistory: string;
|
|
9
|
+
degC: string;
|
|
10
|
+
feelsLikeLabel: string;
|
|
11
|
+
fromLabel: string;
|
|
12
|
+
gustLabel: string;
|
|
13
|
+
inspectHint: string;
|
|
14
|
+
km: string;
|
|
15
|
+
lullLabel: string;
|
|
16
|
+
minLabel: string;
|
|
17
|
+
noHistory: string;
|
|
18
|
+
notMeasured: string;
|
|
19
|
+
notReporting: string;
|
|
20
|
+
peakLabel: string;
|
|
21
|
+
tempRangeLabel: string;
|
|
22
|
+
trendPressure: string;
|
|
23
|
+
trendTemperature: string;
|
|
24
|
+
toLabel: string;
|
|
25
|
+
windRunLabel: string;
|
|
26
|
+
elevation: (metres: number) => string;
|
|
27
|
+
percentCalm: (percent: number) => string;
|
|
28
|
+
percentShare: (percent: number) => string;
|
|
29
|
+
dailyPatternSamples: (sampleCount: number) => string;
|
|
30
|
+
dailyPatternCoverage: (sampleCount: number, expectedCount: number) => string;
|
|
31
|
+
compassSpoken: Record<CompassPoint, string>;
|
|
32
|
+
updated: {
|
|
33
|
+
justNow: string;
|
|
34
|
+
minutesAgo: (minutes: number) => string;
|
|
35
|
+
hoursAgo: (hours: number) => string;
|
|
36
|
+
};
|
|
37
|
+
freshness: Record<FreshnessStatus, string>;
|
|
38
|
+
reasons: Record<UnavailableReason, string>;
|
|
39
|
+
speedUnits: Record<SpeedUnit, string>;
|
|
40
|
+
table: {
|
|
41
|
+
station: string;
|
|
42
|
+
wind: string;
|
|
43
|
+
lull: string;
|
|
44
|
+
gust: string;
|
|
45
|
+
from: string;
|
|
46
|
+
temp: string;
|
|
47
|
+
updated: string;
|
|
48
|
+
};
|
|
49
|
+
air: {
|
|
50
|
+
title: string;
|
|
51
|
+
summaryFallback: string;
|
|
52
|
+
summaryHumidity: (percent: number) => string;
|
|
53
|
+
summaryRaining: (mmPerHour: number) => string;
|
|
54
|
+
summaryRainToday: (mm: number) => string;
|
|
55
|
+
summaryDry: string;
|
|
56
|
+
summaryStrikes: (count: number) => string;
|
|
57
|
+
noStrike: string;
|
|
58
|
+
lastStrike: (distanceKm: number, time: string) => string;
|
|
59
|
+
lastStrikeNoDistance: (time: string) => string;
|
|
60
|
+
trendFalling: string;
|
|
61
|
+
trendRising: string;
|
|
62
|
+
trendSteady: string;
|
|
63
|
+
feelsLike: string;
|
|
64
|
+
humidity: string;
|
|
65
|
+
dewPoint: string;
|
|
66
|
+
pressure: string;
|
|
67
|
+
pressureTrend: string;
|
|
68
|
+
solar: string;
|
|
69
|
+
uv: string;
|
|
70
|
+
rainRate: string;
|
|
71
|
+
rainToday: string;
|
|
72
|
+
rainMinutes: string;
|
|
73
|
+
lightning: string;
|
|
74
|
+
unitPercent: string;
|
|
75
|
+
unitHpa: string;
|
|
76
|
+
unitWm2: string;
|
|
77
|
+
unitIndex: string;
|
|
78
|
+
unitMmPerHour: string;
|
|
79
|
+
unitMm: string;
|
|
80
|
+
unitMinutes: string;
|
|
81
|
+
unitStrikesPastHour: string;
|
|
82
|
+
};
|
|
83
|
+
aria: {
|
|
84
|
+
air: (stationCount: number) => string;
|
|
85
|
+
chart: (stationName: string) => string;
|
|
86
|
+
table: (stationCount: number) => string;
|
|
87
|
+
current: (stationName: string) => string;
|
|
88
|
+
dailyPattern: (stationName: string) => string;
|
|
89
|
+
dailyPatternGeneric: string;
|
|
90
|
+
direction: (spoken: string, deg: number) => string;
|
|
91
|
+
readout: (stationName: string) => string;
|
|
92
|
+
rose: (stationName: string) => string;
|
|
93
|
+
roseFavorable: (sectors: string) => string;
|
|
94
|
+
roseGeneric: string;
|
|
95
|
+
sparkline: (stationName: string) => string;
|
|
96
|
+
strip: (stationName: string) => string;
|
|
97
|
+
summary: (endedAtFormatted: string) => string;
|
|
98
|
+
trend: (stationName: string, seriesName: string) => string;
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
declare const defaultStrings: StationStrings;
|
|
102
|
+
type StationStringOverrides = Partial<Omit<StationStrings, "compassSpoken" | "updated" | "freshness" | "reasons" | "speedUnits" | "table" | "air" | "aria"> & {
|
|
103
|
+
compassSpoken: Partial<StationStrings["compassSpoken"]>;
|
|
104
|
+
updated: Partial<StationStrings["updated"]>;
|
|
105
|
+
freshness: Partial<StationStrings["freshness"]>;
|
|
106
|
+
reasons: Partial<StationStrings["reasons"]>;
|
|
107
|
+
speedUnits: Partial<StationStrings["speedUnits"]>;
|
|
108
|
+
table: Partial<StationStrings["table"]>;
|
|
109
|
+
air: Partial<StationStrings["air"]>;
|
|
110
|
+
aria: Partial<StationStrings["aria"]>;
|
|
111
|
+
}>;
|
|
112
|
+
declare function resolveStrings(overrides?: StationStringOverrides): StationStrings;
|
|
113
|
+
declare function mergeStringOverrides(outer: StationStringOverrides | undefined, inner: StationStringOverrides | undefined): StationStringOverrides | undefined;
|
|
114
|
+
type FormatTime = (date: Date) => string;
|
|
115
|
+
declare function defaultFormatTime(date: Date): string;
|
|
116
|
+
declare function localeFormatTime(locale: string): FormatTime;
|
|
117
|
+
//#endregion
|
|
118
|
+
export { FormatTime, StationStringOverrides, StationStrings, defaultFormatTime, defaultStrings, localeFormatTime, mergeStringOverrides, resolveStrings };
|