kmw-sdk 0.0.0-stage → 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/dist/index.cjs ADDED
@@ -0,0 +1,973 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/auth.ts
3
+ const base64Utf8 = (text) => btoa(Array.from(new TextEncoder().encode(text), (byte) => String.fromCharCode(byte)).join(""));
4
+ const nonEmptyString = (value, name) => {
5
+ if (typeof value !== "string" || value.trim() === "") throw new TypeError(`${name} must be a non-empty string`);
6
+ return value;
7
+ };
8
+ /**
9
+ * Turns the client options into the header to send. Error messages never
10
+ * contain the credentials.
11
+ * @internal
12
+ */
13
+ function resolveCredentials(apiKey, auth, envApiKey) {
14
+ const key = apiKey?.trim();
15
+ if (auth === void 0) {
16
+ const resolved = key || envApiKey();
17
+ return resolved ? {
18
+ header: "X-API-Key",
19
+ value: resolved
20
+ } : void 0;
21
+ }
22
+ if (key) throw new TypeError("Pass either `apiKey` or `auth`, not both");
23
+ if (typeof auth !== "object" || auth === null) throw new TypeError("auth must be an object");
24
+ switch (auth.type) {
25
+ case "basic": {
26
+ const username = nonEmptyString(auth.username, "auth.username");
27
+ if (username.includes(":")) throw new TypeError("auth.username must not contain a colon");
28
+ if (typeof auth.password !== "string") throw new TypeError("auth.password must be a string");
29
+ return {
30
+ header: "Authorization",
31
+ value: `Basic ${base64Utf8(`${username}:${auth.password}`)}`
32
+ };
33
+ }
34
+ case "bearer": {
35
+ const token = nonEmptyString(auth.token, "auth.token").trim();
36
+ if (!/^[\x21-\x7e]+$/.test(token)) throw new TypeError("auth.token must not contain whitespace or non-ASCII characters");
37
+ return {
38
+ header: "Authorization",
39
+ value: `Bearer ${token}`
40
+ };
41
+ }
42
+ default: throw new TypeError(`auth.type must be "basic" or "bearer", got ${String(auth.type)}`);
43
+ }
44
+ }
45
+ // src/errors.ts
46
+ /**
47
+ * Base class of every error thrown by this SDK.
48
+ *
49
+ * Aborts triggered by your own `AbortSignal` are not wrapped: the signal's
50
+ * reason is re-thrown unchanged, exactly like `fetch` does.
51
+ */
52
+ var KachelmannError = class extends Error {
53
+ name = "KachelmannError";
54
+ };
55
+ const isProblem = (body) => typeof body === "object" && body !== null && ("title" in body || "detail" in body);
56
+ /** The API answered with a non-2xx status code. */
57
+ var ApiError = class extends KachelmannError {
58
+ name = "ApiError";
59
+ /** HTTP status code. */
60
+ status;
61
+ method;
62
+ /** Request URL (without credentials). */
63
+ url;
64
+ /** Parsed problem details, if the response body contained any. */
65
+ problem;
66
+ /** Raw response body (parsed JSON, or text). */
67
+ body;
68
+ /** Rate-limit headers of the failed response, if present. */
69
+ rateLimit;
70
+ /**
71
+ * @param init - Status, request and response body.
72
+ * @param hint - Extra explanation appended to the message.
73
+ */
74
+ constructor(init, hint) {
75
+ const problem = isProblem(init.body) ? init.body : void 0;
76
+ const reason = [problem?.title, problem?.detail].filter(Boolean).join(": ");
77
+ super(`${init.method} ${init.url} failed with HTTP ${init.status}${reason ? ` (${reason})` : ""}${hint ? `. ${hint}` : ""}`);
78
+ this.status = init.status;
79
+ this.method = init.method;
80
+ this.url = init.url;
81
+ this.problem = problem;
82
+ this.body = init.body;
83
+ this.rateLimit = init.rateLimit;
84
+ }
85
+ };
86
+ /** HTTP 400: a parameter is invalid or out of bounds. */
87
+ var BadRequestError = class extends ApiError {
88
+ name = "BadRequestError";
89
+ };
90
+ /** HTTP 401: the API key is missing or wrong. */
91
+ var AuthenticationError = class extends ApiError {
92
+ name = "AuthenticationError";
93
+ };
94
+ /**
95
+ * Appended to the message of every {@link PermissionDeniedError}.
96
+ * @internal
97
+ */
98
+ const PERMISSION_DENIED_HINT = "Your API key does not cover this request. Keys of some plans (e.g. Hobby, Smart-Home) only work for the API locations set under \"Manage API locations\" at https://accounts.meteologix.com/subscriptions. Other causes: an endpoint or station outside your plan, or a station search radius above 25 km.";
99
+ /**
100
+ * HTTP 403: your subscription does not cover this resource. Typical causes:
101
+ * a location or station outside the API locations set in the account portal
102
+ * (Hobby plans allow two), an endpoint your plan lacks, or a station search
103
+ * radius above 25 km. `problem` contains the API's explanation; `message`
104
+ * contains it too, followed by a hint about these causes.
105
+ */
106
+ var PermissionDeniedError = class extends ApiError {
107
+ name = "PermissionDeniedError";
108
+ constructor(init) {
109
+ super(init, PERMISSION_DENIED_HINT);
110
+ }
111
+ };
112
+ /** HTTP 404: the resource does not exist (e.g. an unknown weather symbol). */
113
+ var NotFoundError = class extends ApiError {
114
+ name = "NotFoundError";
115
+ };
116
+ /** HTTP 429: the per-minute or per-day request limit was exceeded. */
117
+ var RateLimitError = class extends ApiError {
118
+ name = "RateLimitError";
119
+ /** When requests are allowed again (from `x-ratelimit-retry-after`), if known. */
120
+ get retryAfter() {
121
+ return this.rateLimit?.retryAfter;
122
+ }
123
+ };
124
+ /** HTTP 5xx: the API had an internal problem. */
125
+ var ServerError = class extends ApiError {
126
+ name = "ServerError";
127
+ };
128
+ /** The request did not complete within the configured timeout. */
129
+ var RequestTimeoutError = class extends KachelmannError {
130
+ name = "RequestTimeoutError";
131
+ timeout;
132
+ constructor(timeout, options) {
133
+ super(`Request timed out after ${timeout} ms`, options);
134
+ this.timeout = timeout;
135
+ }
136
+ };
137
+ /** The request failed before a response arrived (DNS, TCP, TLS, ...). See `cause`. */
138
+ var ConnectionError = class extends KachelmannError {
139
+ name = "ConnectionError";
140
+ };
141
+ /**
142
+ * A request needs an API key, but none was configured (neither `apiKey`,
143
+ * `KACHELMANN_API_KEY` nor enterprise `auth`). Thrown before any network
144
+ * traffic.
145
+ */
146
+ var MissingApiKeyError = class extends KachelmannError {
147
+ name = "MissingApiKeyError";
148
+ constructor(options) {
149
+ super("No API key configured. Pass `apiKey` to `new Kachelmann()` or set the KACHELMANN_API_KEY environment variable.", options);
150
+ }
151
+ };
152
+ /** The API answered with 2xx, but the body could not be parsed or has an unexpected shape. */
153
+ var InvalidResponseError = class extends KachelmannError {
154
+ name = "InvalidResponseError";
155
+ };
156
+ /** Maps an HTTP status code to the most specific error class. */
157
+ function createApiError(init) {
158
+ switch (init.status) {
159
+ case 400: return new BadRequestError(init);
160
+ case 401: return new AuthenticationError(init);
161
+ case 403: return new PermissionDeniedError(init);
162
+ case 404: return new NotFoundError(init);
163
+ case 429: return new RateLimitError(init);
164
+ default: return init.status >= 500 ? new ServerError(init) : new ApiError(init);
165
+ }
166
+ }
167
+ // src/rate-limit.ts
168
+ const toInt = (value) => {
169
+ if (value === null || value.trim() === "") return void 0;
170
+ const n = Number(value);
171
+ return Number.isFinite(n) ? n : void 0;
172
+ };
173
+ const toDate = (value) => {
174
+ if (value === null || value.trim() === "") return void 0;
175
+ const seconds = Number(value);
176
+ const date = Number.isFinite(seconds) ? new Date(Date.now() + seconds * 1e3) : new Date(value);
177
+ return Number.isNaN(date.getTime()) ? void 0 : date;
178
+ };
179
+ /** Reads the `x-ratelimit-*` headers. Returns `undefined` if none of them is present. */
180
+ function parseRateLimit(headers) {
181
+ const limit = toInt(headers.get("x-ratelimit-limit"));
182
+ const remaining = toInt(headers.get("x-ratelimit-remaining"));
183
+ const retryAfter = toDate(headers.get("x-ratelimit-retry-after"));
184
+ if (limit === void 0 && remaining === void 0 && retryAfter === void 0) return void 0;
185
+ return {
186
+ ...limit !== void 0 && { limit },
187
+ ...remaining !== void 0 && { remaining },
188
+ ...retryAfter !== void 0 && { retryAfter }
189
+ };
190
+ }
191
+ // src/http.ts
192
+ /** Default API base URL. */
193
+ const DEFAULT_BASE_URL = "https://api.kachelmannwetter.com/v02";
194
+ /** Default per-attempt timeout in milliseconds. */
195
+ const DEFAULT_TIMEOUT = 1e4;
196
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
197
+ if (signal?.aborted) return reject(signal.reason);
198
+ const timer = setTimeout(() => {
199
+ signal?.removeEventListener("abort", onAbort);
200
+ resolve();
201
+ }, ms);
202
+ const onAbort = () => {
203
+ clearTimeout(timer);
204
+ reject(signal?.reason);
205
+ };
206
+ signal?.addEventListener("abort", onAbort, { once: true });
207
+ });
208
+ function appendQuery(params, key, value) {
209
+ if (value === void 0) return;
210
+ if (Array.isArray(value)) value.forEach((item, index) => {
211
+ appendQuery(params, `${key}[${index}]`, item);
212
+ });
213
+ else if (typeof value === "object") for (const [k, v] of Object.entries(value)) appendQuery(params, `${key}[${k}]`, v);
214
+ else params.append(key, String(value));
215
+ }
216
+ /** Encodes a query object. `undefined` values are skipped. */
217
+ function buildQuery(query) {
218
+ if (!query) return "";
219
+ const params = new URLSearchParams();
220
+ for (const [key, value] of Object.entries(query)) appendQuery(params, key, value);
221
+ const qs = params.toString();
222
+ return qs ? `?${qs}` : "";
223
+ }
224
+ /**
225
+ * Thin `fetch` wrapper: auth header, timeout, abort, retries and error mapping.
226
+ * @internal
227
+ */
228
+ var HttpClient = class {
229
+ #config;
230
+ #rateLimit;
231
+ constructor(config) {
232
+ this.#config = config;
233
+ }
234
+ /** Rate-limit headers of the most recent response, if the API sent any. */
235
+ get rateLimit() {
236
+ return this.#rateLimit;
237
+ }
238
+ /** Absolute URL for a path, without credentials. */
239
+ url(path, query) {
240
+ return `${this.#config.baseUrl}${path}${buildQuery(query)}`;
241
+ }
242
+ async get(request) {
243
+ const { retries, minDelay, maxDelay } = this.#config.retry;
244
+ for (let attempt = 0;; attempt++) try {
245
+ return await this.#attempt(request);
246
+ } catch (error) {
247
+ const delay = attempt < retries ? retryDelay(error, attempt, minDelay, maxDelay) : void 0;
248
+ if (delay === void 0) throw error;
249
+ await sleep(delay, request.signal);
250
+ }
251
+ }
252
+ async #attempt(request) {
253
+ const url = this.url(request.path, request.query);
254
+ const timeout = request.timeout ?? this.#config.timeout;
255
+ const userSignal = request.signal;
256
+ userSignal?.throwIfAborted();
257
+ const headers = {};
258
+ for (const [name, value] of Object.entries(this.#config.headers)) if (!/^(x-api-key|authorization)$/i.test(name)) headers[name] = value;
259
+ headers.Accept = request.accept ?? "application/json";
260
+ const auth = request.auth ?? "required";
261
+ const credentials = this.#config.credentials;
262
+ if (auth === "required" && !credentials) throw new MissingApiKeyError();
263
+ if (auth !== "none" && credentials) headers[credentials.header] = credentials.value;
264
+ const controller = new AbortController();
265
+ let timedOut = false;
266
+ const timer = setTimeout(() => {
267
+ timedOut = true;
268
+ controller.abort();
269
+ }, timeout);
270
+ const onUserAbort = () => controller.abort(userSignal?.reason);
271
+ userSignal?.addEventListener("abort", onUserAbort, { once: true });
272
+ try {
273
+ let response;
274
+ try {
275
+ response = await this.#config.fetch(url, {
276
+ method: "GET",
277
+ headers,
278
+ signal: controller.signal
279
+ });
280
+ } catch (cause) {
281
+ if (userSignal?.aborted) throw userSignal.reason;
282
+ if (timedOut) throw new RequestTimeoutError(timeout, { cause });
283
+ throw new ConnectionError(`GET ${url} failed: ${describe(cause)}`, { cause });
284
+ }
285
+ const rateLimit = parseRateLimit(response.headers);
286
+ if (rateLimit) this.#rateLimit = rateLimit;
287
+ if (!response.ok) throw createApiError({
288
+ status: response.status,
289
+ method: "GET",
290
+ url,
291
+ body: await readBody(response),
292
+ rateLimit
293
+ });
294
+ if (request.responseType === "text") return await response.text();
295
+ const text = await response.text();
296
+ try {
297
+ return JSON.parse(text);
298
+ } catch (cause) {
299
+ throw new InvalidResponseError(`GET ${url} returned a body that is not valid JSON`, { cause });
300
+ }
301
+ } catch (error) {
302
+ if (userSignal?.aborted) throw userSignal.reason;
303
+ if (timedOut && !(error instanceof KachelmannError)) throw new RequestTimeoutError(timeout, { cause: error });
304
+ throw error;
305
+ } finally {
306
+ clearTimeout(timer);
307
+ userSignal?.removeEventListener("abort", onUserAbort);
308
+ }
309
+ }
310
+ };
311
+ const describe = (error) => {
312
+ if (!(error instanceof Error)) return String(error);
313
+ const cause = error.cause instanceof Error ? `: ${error.cause.message}` : "";
314
+ return `${error.message}${cause}`;
315
+ };
316
+ async function readBody(response) {
317
+ try {
318
+ const text = await response.text();
319
+ if (!text) return void 0;
320
+ try {
321
+ return JSON.parse(text);
322
+ } catch {
323
+ return text.length > 2e3 ? `${text.slice(0, 2e3)}…` : text;
324
+ }
325
+ } catch {
326
+ return;
327
+ }
328
+ }
329
+ const RETRYABLE_STATUS = /* @__PURE__ */ new Set([
330
+ 500,
331
+ 502,
332
+ 503,
333
+ 504
334
+ ]);
335
+ /** Delay before the next attempt, or `undefined` if the error must not be retried. */
336
+ function retryDelay(error, attempt, minDelay, maxDelay) {
337
+ const backoff = Math.min(maxDelay, minDelay * 2 ** attempt) * (.5 + Math.random() * .5);
338
+ if (error instanceof RateLimitError) {
339
+ const retryAfter = error.retryAfter;
340
+ if (!retryAfter) return backoff;
341
+ const wait = retryAfter.getTime() - Date.now();
342
+ return wait <= maxDelay ? Math.max(0, wait) : void 0;
343
+ }
344
+ if (error instanceof ServerError) return RETRYABLE_STATUS.has(error.status) ? backoff : void 0;
345
+ if (error instanceof ConnectionError || error instanceof RequestTimeoutError) return backoff;
346
+ }
347
+ // src/internal.ts
348
+ /**
349
+ * Throws a `RangeError` unless `location` holds valid WGS 84 coordinates, and a
350
+ * `TypeError` if it has both `lon` and `lng` with different values. @internal
351
+ */
352
+ function coordinatesPath(location) {
353
+ const { lat, lon, lng } = location ?? {};
354
+ if (lon !== void 0 && lng !== void 0 && lon !== lng) throw new TypeError(`location has both lon (${String(lon)}) and lng (${String(lng)})`);
355
+ const longitude = lon ?? lng;
356
+ if (typeof lat !== "number" || !Number.isFinite(lat) || lat < -90 || lat > 90) throw new RangeError(`lat must be a number between -90 and 90, got ${String(lat)}`);
357
+ if (typeof longitude !== "number" || !Number.isFinite(longitude) || longitude < -180 || longitude > 180) throw new RangeError(`lon must be a number between -180 and 180, got ${String(longitude)}`);
358
+ return `/${lat}/${longitude}`;
359
+ }
360
+ /** Encodes a path segment and rejects empty values. @internal */
361
+ function segment(value, name) {
362
+ const text = String(value).trim();
363
+ if (text === "") throw new TypeError(`${name} must not be empty`);
364
+ return encodeURIComponent(text);
365
+ }
366
+ /** Throws unless one of `allowed` was given. @internal */
367
+ function oneOf(value, allowed, name) {
368
+ if (!allowed.includes(value)) throw new TypeError(`${name} must be one of ${allowed.join(", ")}, got ${String(value)}`);
369
+ return value;
370
+ }
371
+ /** Ensures the API answered with a JSON object. @internal */
372
+ function expectObject(value, what) {
373
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidResponseError(`Unexpected ${what} response: expected a JSON object`);
374
+ return value;
375
+ }
376
+ /** Ensures the API answered with a JSON array or object map. @internal */
377
+ function expectCollection(value, what) {
378
+ if (typeof value !== "object" || value === null) throw new InvalidResponseError(`Unexpected ${what} response: expected a JSON array`);
379
+ return value;
380
+ }
381
+ /** Picks `signal` and `timeout` from call options. @internal */
382
+ function requestOptions(options) {
383
+ return {
384
+ signal: options?.signal,
385
+ timeout: options?.timeout
386
+ };
387
+ }
388
+ // src/normalize.ts
389
+ /**
390
+ * The API is served by a PHP backend: a list may be serialized as a JSON
391
+ * array or as an object with numeric keys, and an empty map as `[]`. The spec
392
+ * documents this as `oneOf: [array, object]` on almost every collection.
393
+ * These helpers give every collection one stable shape.
394
+ * @internal
395
+ */
396
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
397
+ /** Array or object-map → array. `null`/`undefined` → `[]`. */
398
+ function toArray(value) {
399
+ if (Array.isArray(value)) return value;
400
+ if (isObject(value)) return Object.values(value);
401
+ return [];
402
+ }
403
+ /**
404
+ * Object-map or array → map keyed by `name`. An empty array (PHP's empty map)
405
+ * becomes `{}`; array items are keyed by their `name` property.
406
+ */
407
+ function toRecordByName(value) {
408
+ if (isObject(value)) return value;
409
+ const record = {};
410
+ if (Array.isArray(value)) {
411
+ for (const item of value) if (isObject(item) && typeof item.name === "string") record[item.name] = item;
412
+ }
413
+ return record;
414
+ }
415
+ /** Numeric strings → numbers; other values are passed through. */
416
+ function toNumberish(value) {
417
+ if (typeof value !== "string" || value.trim() === "") return value;
418
+ const n = Number(value);
419
+ return Number.isFinite(n) ? n : value;
420
+ }
421
+ /** Numbers and numeric strings → number; anything else → `null`. */
422
+ function toNumberOrNull(value) {
423
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
424
+ const n = toNumberish(value);
425
+ return typeof n === "number" ? n : null;
426
+ }
427
+ // src/resources/climate.ts
428
+ const BASE$1 = "/_frontend";
429
+ const PARAMETERS = [
430
+ "tlmean",
431
+ "rrsum",
432
+ "shsum"
433
+ ];
434
+ /** The website allows at most this many compared years. */
435
+ const MAX_COMPARED_YEARS = 5;
436
+ /**
437
+ * **Experimental.** Climate time series (warming stripes, heatmaps, daily
438
+ * curves) of long-term stations. Access via `client.experimental.climate`.
439
+ *
440
+ * These endpoints are **not part of the documented v02 API**: they power the
441
+ * climate pages of kachelmannwetter.com and may change or disappear at any
442
+ * time. They are called with *your* API key. In a live test (November 2026)
443
+ * a regular customer key was rejected with `PermissionDeniedError` (403).
444
+ *
445
+ * @experimental
446
+ */
447
+ var ClimateResource = class {
448
+ #http;
449
+ /** @internal */
450
+ constructor(http) {
451
+ this.#http = http;
452
+ }
453
+ /** Climate stations of a country, plus large cities for orientation. */
454
+ async stations(country, options) {
455
+ if (typeof country !== "string" || !/^[A-Za-z]{2}$/.test(country)) throw new TypeError("country must be an ISO 3166-1 alpha-2 code, e.g. \"DE\"");
456
+ const raw = expectObject(await this.#http.get({
457
+ path: `${BASE$1}/v2/climate/map`,
458
+ query: { country: country.toUpperCase() },
459
+ ...requestOptions(options)
460
+ }), "climate stations");
461
+ return {
462
+ stations: toArray(raw.stations),
463
+ cities: toArray(raw.cities)
464
+ };
465
+ }
466
+ /** Finds climate stations by station or place name. */
467
+ async search(query, options) {
468
+ if (typeof query !== "string" || query.trim() === "") throw new TypeError("query must not be empty");
469
+ return toArray(expectCollection(await this.#http.get({
470
+ path: `${BASE$1}/climate/search`,
471
+ query: { query: query.trim() },
472
+ ...requestOptions(options)
473
+ }), "climate search"));
474
+ }
475
+ /** Station details, supported charts, data availability and records. */
476
+ async station(stationId, options) {
477
+ return expectObject(await this.#http.get({
478
+ path: `${BASE$1}/climate/${segment(stationId, "stationId")}`,
479
+ ...requestOptions(options)
480
+ }), "climate station");
481
+ }
482
+ /** Warming stripes: one value per year (or per season of each year). */
483
+ async stripes(stationId, options) {
484
+ const by = oneOf(options.by ?? "byYear", ["byYear", "bySeason"], "by");
485
+ const raw = await this.#chart(stationId, `stripes/${by}`, options, { seasons: options.season });
486
+ return {
487
+ ...raw,
488
+ categories: toArray(raw.categories),
489
+ matrix: toArray(raw.matrix)
490
+ };
491
+ }
492
+ /** Heatmap of monthly, seasonal and yearly values. */
493
+ async heatmap(stationId, options) {
494
+ const by = oneOf(options.by ?? "byYear", ["byYear", "byMonth"], "by");
495
+ return await this.#chart(stationId, `heatmap/${by}`, options, { year: options.year });
496
+ }
497
+ /** Daily values of each year ("spaghetti" chart) plus the reference period. */
498
+ async spaghetti(stationId, options) {
499
+ const years = options.comparedYears;
500
+ if (years && years.length > MAX_COMPARED_YEARS) throw new RangeError(`comparedYears accepts at most ${MAX_COMPARED_YEARS} years`);
501
+ const raw = await this.#chart(stationId, "spaghetti/daily", options, { comparedYear: years ? [...years] : void 0 });
502
+ return {
503
+ ...raw,
504
+ series: toArray(raw.series)
505
+ };
506
+ }
507
+ async #chart(stationId, chart, options, extra) {
508
+ return expectObject(await this.#http.get({
509
+ path: `${BASE$1}/climate/${segment(stationId, "stationId")}/${chart}`,
510
+ query: {
511
+ param: oneOf(options.param, PARAMETERS, "param"),
512
+ start: options.start,
513
+ end: options.end,
514
+ reference: options.reference,
515
+ type: options.type,
516
+ ...extra
517
+ },
518
+ ...requestOptions(options)
519
+ }), `climate ${chart}`);
520
+ }
521
+ };
522
+ // src/resources/forecast.ts
523
+ const TIME_STEPS$1 = [
524
+ "1h",
525
+ "3h",
526
+ "6h"
527
+ ];
528
+ const withRisks = (item) => ({
529
+ ...item,
530
+ risks: toArray(item.risks)
531
+ });
532
+ /** Forecast endpoints. Access via `client.forecast`. */
533
+ var ForecastResource = class {
534
+ #http;
535
+ #units;
536
+ /** @internal */
537
+ constructor(http, units) {
538
+ this.#http = http;
539
+ this.#units = units;
540
+ }
541
+ async standard(location, timeSteps, options) {
542
+ return this.#series(location, "standard", timeSteps, options);
543
+ }
544
+ async advanced(location, timeSteps, options) {
545
+ return this.#series(location, "advanced", timeSteps, options);
546
+ }
547
+ async threeDay(location, options) {
548
+ const units = options?.units ?? this.#units;
549
+ const body = await this.#http.get({
550
+ path: `/forecast${coordinatesPath(location)}/3day`,
551
+ query: {
552
+ units,
553
+ minDays: options?.minDays,
554
+ model: options?.model
555
+ },
556
+ accept: "application/vnd.kmw.v2+json",
557
+ ...requestOptions(options)
558
+ });
559
+ if (options?.raw) return body;
560
+ const raw = expectObject(body, "3-day forecast");
561
+ const data = toArray(raw.data).map((day) => ({
562
+ ...withRisks(day),
563
+ timeOfDay: toArray(day.timeOfDay).map(withRisks)
564
+ }));
565
+ return {
566
+ ...raw,
567
+ systemOfUnits: raw.systemOfUnits ?? units,
568
+ data
569
+ };
570
+ }
571
+ async trend14Days(location, options) {
572
+ const units = options?.units ?? this.#units;
573
+ const body = await this.#http.get({
574
+ path: `/forecast${coordinatesPath(location)}/trend14days`,
575
+ query: { units },
576
+ ...requestOptions(options)
577
+ });
578
+ if (options?.raw) return body;
579
+ const raw = expectObject(body, "14-day trend");
580
+ return {
581
+ ...raw,
582
+ systemOfUnits: raw.systemOfUnits ?? units,
583
+ data: toArray(raw.data).map(withRisks)
584
+ };
585
+ }
586
+ async #series(location, kind, timeSteps, options) {
587
+ const units = options?.units ?? this.#units;
588
+ const path = `/forecast${coordinatesPath(location)}/${kind}/${oneOf(timeSteps, TIME_STEPS$1, "timeSteps")}`;
589
+ const body = await this.#http.get({
590
+ path,
591
+ query: { units },
592
+ ...requestOptions(options)
593
+ });
594
+ if (options?.raw) return body;
595
+ const raw = expectObject(body, `${kind} forecast`);
596
+ return {
597
+ ...raw,
598
+ systemOfUnits: raw.systemOfUnits ?? units,
599
+ data: toArray(raw.data)
600
+ };
601
+ }
602
+ };
603
+ // src/resources/photos.ts
604
+ const BASE = "/community/weatherphotos";
605
+ const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
606
+ const toDateString = (value, name) => {
607
+ if (value instanceof Date) {
608
+ if (Number.isNaN(value.getTime())) throw new RangeError(`${name} is an invalid Date`);
609
+ return value.toISOString().slice(0, 10);
610
+ }
611
+ if (typeof value !== "string" || !DATE_PATTERN.test(value)) throw new RangeError(`${name} must be a YYYY-MM-DD string or a Date`);
612
+ return value;
613
+ };
614
+ const expectSuccess = (value, what) => {
615
+ const raw = expectObject(value, what);
616
+ if (raw.status !== "success") throw new InvalidResponseError(`Unexpected ${what} response: status ${String(raw.status)}`);
617
+ return raw;
618
+ };
619
+ /**
620
+ * **Experimental.** Read-only access to the community weather photos of
621
+ * kachelmannwetter.com. Access via `client.photos`.
622
+ *
623
+ * These endpoints are **not part of the documented v02 API** and may change
624
+ * at any time. They are public: no API key is sent. Liking, uploading and
625
+ * view counting need a user account and are not supported.
626
+ *
627
+ * Photos are licensed to Kachelmann GmbH and contain personal data (uploader
628
+ * names, locations): respect copyright and data protection law.
629
+ *
630
+ * @experimental
631
+ */
632
+ var PhotosResource = class {
633
+ #http;
634
+ /** @internal */
635
+ constructor(http) {
636
+ this.#http = http;
637
+ }
638
+ /** Number of photos per day, keyed by `YYYY-MM-DD`. */
639
+ async counts(options) {
640
+ return expectObject(expectSuccess(await this.#http.get({
641
+ path: `${BASE}/counts`,
642
+ auth: "none",
643
+ ...requestOptions(options)
644
+ }), "photo counts").counts, "photo counts");
645
+ }
646
+ /** Photos taken between two days. */
647
+ async list(options) {
648
+ const lengthUnit = options.units === void 0 ? void 0 : options.units === "imperial" ? "anglo" : "metrisch";
649
+ return toArray(expectObject(await this.#http.get({
650
+ path: `${BASE}/list`,
651
+ query: {
652
+ startDate: toDateString(options.from, "from"),
653
+ endDate: toDateString(options.to, "to"),
654
+ format: "geojson",
655
+ windUnit: options.windUnit,
656
+ lengthUnit
657
+ },
658
+ auth: "none",
659
+ ...requestOptions(options)
660
+ }), "photo list").features).map((feature) => feature?.properties).filter((props) => typeof props === "object" && props !== null).map((props) => props);
661
+ }
662
+ /** A single photo. Throws `NotFoundError` if it does not exist. */
663
+ async get(id, options) {
664
+ return expectObject(expectSuccess(await this.#http.get({
665
+ path: `${BASE}/${segment(id, "id")}`,
666
+ auth: "none",
667
+ ...requestOptions(options)
668
+ }), "photo").photo, "photo");
669
+ }
670
+ };
671
+ // src/resources/stations.ts
672
+ const TIME_STEPS = [
673
+ "10min",
674
+ "1h",
675
+ "1d"
676
+ ];
677
+ /**
678
+ * Largest `radius` (km) of `stations.search()` that the API accepted in tests.
679
+ * Larger radii are answered with HTTP 403 (`PermissionDeniedError`). The spec
680
+ * does not state this limit and it may depend on the plan, so the SDK does not
681
+ * enforce it; compare against this constant to avoid the 403.
682
+ */
683
+ const STATION_SEARCH_MAX_RADIUS_KM = 25;
684
+ /** Station coordinates may arrive as strings. @internal */
685
+ const normalizeStation = (raw) => ({
686
+ ...raw,
687
+ lat: toNumberOrNull(raw.lat) ?? raw.lat,
688
+ lon: toNumberOrNull(raw.lon) ?? raw.lon
689
+ });
690
+ const header = (raw) => ({
691
+ ...raw,
692
+ lat: toNumberOrNull(raw.lat),
693
+ lon: toNumberOrNull(raw.lon),
694
+ ele: toNumberOrNull(raw.ele)
695
+ });
696
+ const observation = (raw) => {
697
+ const entry = {
698
+ ...raw,
699
+ thresholds: toRecordByName(raw.thresholds)
700
+ };
701
+ if ("snowHeight" in raw) entry.snowHeight = toNumberOrNull(raw.snowHeight);
702
+ return entry;
703
+ };
704
+ /** Weather station endpoints. Access via `client.stations`. */
705
+ var StationsResource = class {
706
+ #http;
707
+ /** @internal */
708
+ constructor(http) {
709
+ this.#http = http;
710
+ }
711
+ async search(location, options) {
712
+ const body = await this.#http.get({
713
+ path: `/station/search${coordinatesPath(location)}`,
714
+ query: { radius: options?.radius },
715
+ ...requestOptions(options)
716
+ });
717
+ if (options?.raw) return body;
718
+ return toArray(expectCollection(body, "station search")).map(normalizeStation);
719
+ }
720
+ async latest(stationId, options) {
721
+ const body = await this.#http.get({
722
+ path: `/station/${segment(stationId, "stationId")}/observations/latest`,
723
+ ...requestOptions(options)
724
+ });
725
+ if (options?.raw) return body;
726
+ const raw = expectObject(body, "latest observations");
727
+ return {
728
+ ...header(raw),
729
+ data: toRecordByName(raw.data)
730
+ };
731
+ }
732
+ async observations(stationId, timeSteps, options) {
733
+ const body = await this.#http.get({
734
+ path: `/station/${segment(stationId, "stationId")}/observations/${oneOf(timeSteps, TIME_STEPS, "timeSteps")}`,
735
+ query: { threshold: options?.threshold },
736
+ ...requestOptions(options)
737
+ });
738
+ if (options?.raw) return body;
739
+ const raw = expectObject(body, "observations");
740
+ return {
741
+ ...header(raw),
742
+ data: toArray(raw.data).map(observation)
743
+ };
744
+ }
745
+ };
746
+ // src/resources/tools.ts
747
+ const SYMBOL_PATTERN = /^[A-Za-z0-9_-]+$/;
748
+ const symbolPath = (symbol) => {
749
+ if (typeof symbol !== "string" || !SYMBOL_PATTERN.test(symbol)) throw new TypeError(`Invalid weather symbol: ${String(symbol)}`);
750
+ return `/tools/weatherSymbol/${symbol}.svg`;
751
+ };
752
+ /** Tool endpoints (astronomy, weather symbols). Access via `client.tools`. */
753
+ var ToolsResource = class {
754
+ #http;
755
+ /** @internal */
756
+ constructor(http) {
757
+ this.#http = http;
758
+ }
759
+ async astronomy(location, options) {
760
+ const body = await this.#http.get({
761
+ path: `/tools/astronomy${coordinatesPath(location)}`,
762
+ ...requestOptions(options)
763
+ });
764
+ if (options?.raw) return body;
765
+ const raw = expectObject(body, "astronomy");
766
+ return {
767
+ ...raw,
768
+ dailyData: toArray(raw.dailyData)
769
+ };
770
+ }
771
+ /**
772
+ * Downloads the SVG markup of a weather symbol, e.g. `"partlycloudy_night"`.
773
+ * The API key is sent if one is configured. The endpoint also works
774
+ * without one (checked live, November 2026).
775
+ */
776
+ async weatherSymbol(symbol, options) {
777
+ return this.#http.get({
778
+ path: symbolPath(symbol),
779
+ accept: "image/svg+xml",
780
+ responseType: "text",
781
+ auth: "optional",
782
+ ...requestOptions(options)
783
+ });
784
+ }
785
+ /**
786
+ * URL of a weather symbol SVG, e.g. for an `<img src>`. The URL contains no
787
+ * credentials; the endpoint answered without an API key in a live test
788
+ * (November 2026).
789
+ */
790
+ weatherSymbolUrl(symbol) {
791
+ return this.#http.url(symbolPath(symbol));
792
+ }
793
+ };
794
+ // src/client.ts
795
+ const envApiKey = () => {
796
+ const key = globalThis.process?.env?.KACHELMANN_API_KEY;
797
+ return key?.trim() ? key.trim() : void 0;
798
+ };
799
+ const nonNegative = (value, fallback, name) => {
800
+ if (value === void 0) return fallback;
801
+ if (!Number.isFinite(value) || value < 0) throw new RangeError(`${name} must be a non-negative number`);
802
+ return value;
803
+ };
804
+ const resolveRetry = (retry) => {
805
+ const options = typeof retry === "number" ? { retries: retry } : retry ?? {};
806
+ return {
807
+ retries: Math.floor(nonNegative(options.retries, 0, "retry.retries")),
808
+ minDelay: nonNegative(options.minDelay, 500, "retry.minDelay"),
809
+ maxDelay: nonNegative(options.maxDelay, 1e4, "retry.maxDelay")
810
+ };
811
+ };
812
+ /**
813
+ * Client for the Kachelmannwetter API v02.
814
+ *
815
+ * @typeParam U - Default system of units, inferred from `options.units`.
816
+ * @example
817
+ * import { Kachelmann } from "kmw-sdk";
818
+ *
819
+ * const client = new Kachelmann({ apiKey: process.env.KACHELMANN_API_KEY });
820
+ * const forecast = await client.forecast.threeDay({ lat: 50.1, lon: 8.7 });
821
+ */
822
+ var Kachelmann = class {
823
+ /** Forecasts: standard/advanced time series, 3-day summary and 14-day trend. */
824
+ forecast;
825
+ /** Weather stations: search, latest values and observation history. */
826
+ stations;
827
+ /** Astronomy data and weather symbols. */
828
+ tools;
829
+ /**
830
+ * Endpoints that are known not to work with regular API keys yet. Not
831
+ * covered by semver. See {@link ExperimentalApi}.
832
+ * @experimental
833
+ */
834
+ experimental;
835
+ /**
836
+ * **Experimental**, undocumented: community weather photos (read-only, no key needed).
837
+ * @experimental
838
+ */
839
+ photos;
840
+ #http;
841
+ #units;
842
+ constructor(options = {}) {
843
+ const fetchImpl = options.fetch ?? globalThis.fetch;
844
+ if (typeof fetchImpl !== "function") throw new TypeError("No fetch implementation available. Use Node.js 20+ or pass `fetch`.");
845
+ const units = options.units ?? "metric";
846
+ if (units !== "metric" && units !== "imperial") throw new TypeError(`units must be "metric" or "imperial", got ${String(units)}`);
847
+ this.#units = units;
848
+ this.#http = new HttpClient({
849
+ credentials: resolveCredentials(options.apiKey, options.auth, envApiKey),
850
+ baseUrl: (options.baseUrl ?? "https://api.kachelmannwetter.com/v02").replace(/\/+$/, ""),
851
+ timeout: nonNegative(options.timeout, DEFAULT_TIMEOUT, "timeout"),
852
+ retry: resolveRetry(options.retry),
853
+ fetch: (input, init) => fetchImpl(input, init),
854
+ headers: { ...options.headers }
855
+ });
856
+ this.forecast = new ForecastResource(this.#http, units);
857
+ this.stations = new StationsResource(this.#http);
858
+ this.tools = new ToolsResource(this.#http);
859
+ this.experimental = Object.freeze({ climate: new ClimateResource(this.#http) });
860
+ this.photos = new PhotosResource(this.#http);
861
+ }
862
+ /**
863
+ * Rate-limit headers of the most recent response (`x-ratelimit-*`), if the
864
+ * API sent any.
865
+ */
866
+ get rateLimit() {
867
+ return this.#http.rateLimit;
868
+ }
869
+ async current(location, options) {
870
+ const units = options?.units ?? this.#units;
871
+ const body = await this.#http.get({
872
+ path: `/current${coordinatesPath(location)}`,
873
+ query: { units },
874
+ ...requestOptions(options)
875
+ });
876
+ if (options?.raw) return body;
877
+ const raw = expectObject(body, "current weather");
878
+ const data = {};
879
+ for (const [name, value] of Object.entries(toRecordByName(raw.data))) {
880
+ const normalized = {
881
+ ...value,
882
+ value: value.value ?? null
883
+ };
884
+ if (value.station && typeof value.station === "object") Object.assign(normalized, { station: normalizeStation(value.station) });
885
+ data[name] = normalized;
886
+ }
887
+ return {
888
+ ...raw,
889
+ systemOfUnits: raw.systemOfUnits ?? units,
890
+ data
891
+ };
892
+ }
893
+ };
894
+ // src/units.ts
895
+ /**
896
+ * Small unit conversion helpers. Forecasts use m/s for wind (metric), station
897
+ * observations use knots, and most people expect km/h.
898
+ * @module
899
+ */
900
+ const round = (value, digits) => {
901
+ if (digits === void 0) return value;
902
+ const factor = 10 ** digits;
903
+ return Math.round(value * factor) / factor;
904
+ };
905
+ /** Knots → km/h. */
906
+ const knotsToKmh = (kn, digits) => round(kn * 1.852, digits);
907
+ /** Knots → m/s. */
908
+ const knotsToMps = (kn, digits) => round(kn * 1852 / 3600, digits);
909
+ /** Knots → mph. */
910
+ const knotsToMph = (kn, digits) => round(kn * 1.852 / 1.609344, digits);
911
+ /** m/s → km/h. */
912
+ const mpsToKmh = (mps, digits) => round(mps * 3.6, digits);
913
+ /** m/s → knots. */
914
+ const mpsToKnots = (mps, digits) => round(mps * 3600 / 1852, digits);
915
+ /** mph → km/h. */
916
+ const mphToKmh = (mph, digits) => round(mph * 1.609344, digits);
917
+ /** km/h → m/s. */
918
+ const kmhToMps = (kmh, digits) => round(kmh / 3.6, digits);
919
+ /** °C → °F. */
920
+ const celsiusToFahrenheit = (c, digits) => round(c * 9 / 5 + 32, digits);
921
+ /** °F → °C. */
922
+ const fahrenheitToCelsius = (f, digits) => round((f - 32) * 5 / 9, digits);
923
+ /** Millimetres → inches. */
924
+ const mmToInch = (mm, digits) => round(mm / 25.4, digits);
925
+ /** Inches → millimetres. */
926
+ const inchToMm = (inch, digits) => round(inch * 25.4, digits);
927
+ /** Groups a WMO 4677 present weather code. Returns `undefined` for values outside 0–99. */
928
+ function classifyWmoCode(code) {
929
+ if (!Number.isInteger(code) || code < 0 || code > 99) return void 0;
930
+ if (code <= 3) return "none";
931
+ if (code <= 9) return "haze";
932
+ if (code <= 12) return "mist";
933
+ if (code <= 19) return "nearby";
934
+ if (code <= 29) return "recent";
935
+ if (code <= 35) return "duststorm";
936
+ if (code <= 39) return "blowingSnow";
937
+ if (code <= 49) return "fog";
938
+ if (code <= 59) return "drizzle";
939
+ if (code <= 69) return "rain";
940
+ if (code <= 79) return "snow";
941
+ if (code <= 90) return "showers";
942
+ return "thunderstorm";
943
+ }
944
+ exports.ApiError = ApiError;
945
+ exports.AuthenticationError = AuthenticationError;
946
+ exports.BadRequestError = BadRequestError;
947
+ exports.ConnectionError = ConnectionError;
948
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
949
+ exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
950
+ exports.InvalidResponseError = InvalidResponseError;
951
+ exports.Kachelmann = Kachelmann;
952
+ exports.KachelmannError = KachelmannError;
953
+ exports.MissingApiKeyError = MissingApiKeyError;
954
+ exports.NotFoundError = NotFoundError;
955
+ exports.PermissionDeniedError = PermissionDeniedError;
956
+ exports.RateLimitError = RateLimitError;
957
+ exports.RequestTimeoutError = RequestTimeoutError;
958
+ exports.STATION_SEARCH_MAX_RADIUS_KM = STATION_SEARCH_MAX_RADIUS_KM;
959
+ exports.ServerError = ServerError;
960
+ exports.celsiusToFahrenheit = celsiusToFahrenheit;
961
+ exports.classifyWmoCode = classifyWmoCode;
962
+ exports.fahrenheitToCelsius = fahrenheitToCelsius;
963
+ exports.inchToMm = inchToMm;
964
+ exports.kmhToMps = kmhToMps;
965
+ exports.knotsToKmh = knotsToKmh;
966
+ exports.knotsToMph = knotsToMph;
967
+ exports.knotsToMps = knotsToMps;
968
+ exports.mmToInch = mmToInch;
969
+ exports.mphToKmh = mphToKmh;
970
+ exports.mpsToKmh = mpsToKmh;
971
+ exports.mpsToKnots = mpsToKnots;
972
+
973
+ //# sourceMappingURL=index.cjs.map