mobs-ws 0.17.0 → 0.18.0

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 (3) hide show
  1. package/README.md +33 -3
  2. package/package.json +1 -1
  3. package/src/index.js +192 -4
package/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  Official JavaScript client for the MOBS `/v1/ws/metar` WebSocket (protocol 4).
4
4
 
5
- Requires Node 22+ (or a browser) and `mobs-ws` 0.17.0 for region and
6
- platform subscriptions. There are no runtime dependencies. The client
5
+ Requires Node 22+ (or a browser). `mobs-ws` 0.17.0+ for region and
6
+ platform subscriptions, 0.18.0 for D-ATIS and feed notices (server v0.44.0+). There are no runtime dependencies. The client
7
7
  uses the global `WebSocket` in the browser and in Node 22+. Snapshot
8
8
  and resume are opt-in. The client applies `awc_confirmed` frames
9
9
  last-wins per (`icao`, `versions`), handles `station_late`,
@@ -30,7 +30,7 @@ uses `?token=` because a page cannot set socket headers. A browser
30
30
  `WebSocket` cannot see a handshake 401 or 403, so the client retries.
31
31
 
32
32
  ```bash
33
- npm install mobs-ws@0.17.0
33
+ npm install mobs-ws@0.18.0
34
34
  export MOBS_TOKEN=$MOBS_TOKEN
35
35
  ```
36
36
 
@@ -51,4 +51,34 @@ const client = new MetarClient({
51
51
  await client.runForever();
52
52
  ```
53
53
 
54
+ ## D-ATIS and feed notices (0.18.0, server v0.44.0+)
55
+
56
+ Pass `datis: ["KLGA"]` (handshake) or call `client.subscribeDatis(["KJFK"], {types: ["combined"]})`
57
+ mid-session; `client.unsubscribeDatis([...])` drops them without touching METAR. The key needs
58
+ the `datis` scope. Each `new_datis_arrived` record (`DatisRecord` JSDoc type) is kept in
59
+ `datisLatest["ICAO/type"]`: a later `issued_at` wins, then a higher `revision`. `onDatis(record)`
60
+ fires when it changes. Snapshot frames (`cached: true`) do not advance `seq`. `backlog: true` marks a
61
+ newer copy that arrived late. `datisTypes` (`combined`, `arr`, `dep`) are sent with a subscribe
62
+ once the socket opens. On a resume fallback with `datis_fallback`, the client refetches
63
+ `GET /v1/datis/latest`.
64
+
65
+ A server without D-ATIS answers with no `datis_icaos`. The client then sets `datisSupported = false`
66
+ and `lastError` to `{code: "unsupported", message: "server does not support D-ATIS"}`, and
67
+ `subscribeDatis()` throws `Error("server does not support D-ATIS")`. METAR keeps working.
68
+ A key without the scope gets `forbidden`, and a server with the product off gets `unavailable`;
69
+ both land on `lastError`.
70
+
71
+ `feed_notice` frames replace `client.notices` (whole state, `FeedNotice` JSDoc type) and call
72
+ `onFeedNotice(notices)`. Opt out with `notices: false`, or later with `client.setNotices(false)`.
73
+
74
+ D-ATIS from mobs-ws is not for operational or flight-safety use; it is best effort with no guarantee.
75
+
76
+ ```javascript
77
+ const client = new MetarClient({
78
+ airports: ["KLGA"], datis: ["KLGA"], datisTypes: ["combined"],
79
+ onDatis: (rec) => console.log(rec.icao, rec.type, rec.letter, rec.text.slice(0, 60)),
80
+ onFeedNotice: (notices) => console.log(notices.map((n) => n.message)),
81
+ });
82
+ ```
83
+
54
84
  MIT licensed. See [LICENSE](https://github.com/Mobs-ws/mobs-sdks/blob/main/LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mobs-ws",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "Official client for the MOBS /v1/ws/metar WebSocket (protocol 4).",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/index.js CHANGED
@@ -3,6 +3,11 @@
3
3
  // No runtime dependencies: uses the global WebSocket (browser and Node 22+).
4
4
  // The token comes only from the caller or the MOBS_TOKEN environment
5
5
  // variable. It is never embedded.
6
+ // 0.18.0 (server v0.44.0+): per-station D-ATIS (`datis` option or
7
+ // subscribeDatis(); the key needs the `datis` scope), new_datis_arrived kept
8
+ // per (icao, type) newest issued_at then revision, onDatis, datis_fallback
9
+ // resync from GET /v1/datis/latest, and feed_notice (`notices`,
10
+ // onFeedNotice; opt out with `notices: false`).
6
11
 
7
12
  export const DEFAULT_URL = "wss://mobs.ws/v1/ws/metar";
8
13
  export const MAX_GRANTS = 10;
@@ -15,7 +20,11 @@ export const ERROR_CODES = Object.freeze([
15
20
  "invalid_region",
16
21
  "unknown_platform",
17
22
  "too_many_grants",
23
+ "forbidden",
24
+ "unavailable",
18
25
  ]);
26
+ export const DATIS_TYPES = Object.freeze(["combined", "arr", "dep"]);
27
+ export const DATIS_UNSUPPORTED = "server does not support D-ATIS";
19
28
  export const PING_EVERY_MS = 20000;
20
29
  export const PONG_TIMEOUT_MS = 15000;
21
30
  export const BACKOFF_START_MS = 1000;
@@ -75,9 +84,62 @@ export function applyAwcConfirmed(latest, message) {
75
84
  return latest;
76
85
  }
77
86
 
78
- export function handshakeUrl(base, airports, {snapshot = true, sinceSeq = null, bootId = null} = {}) {
87
+ /**
88
+ * One D-ATIS bulletin (`data[]` of new_datis_arrived, and GET /v1/datis rows).
89
+ * @typedef {Object} DatisRecord
90
+ * @property {string} icao
91
+ * @property {"combined"|"arr"|"dep"} type
92
+ * @property {string} letter
93
+ * @property {string} issued_at ISO 8601, milliseconds, Z
94
+ * @property {string|null} datis_time HHMM as broadcast
95
+ * @property {string} text
96
+ * @property {string} arrived_at
97
+ * @property {"swim"|"atis.info"} source
98
+ * @property {string|null} source_time
99
+ * @property {number} revision
100
+ * @property {string} versions e.g. "KLGA/combined/U/2026-11-19T11:51Z/0"
101
+ */
102
+
103
+ /**
104
+ * One feed notice (`feed_notice.notices[]` and /v1/status `notices[]`).
105
+ * @typedef {Object} FeedNotice
106
+ * @property {string} id
107
+ * @property {"metar"|"datis"} feed
108
+ * @property {string|null} source
109
+ * @property {string[]|null} icaos
110
+ * @property {string} kind
111
+ * @property {string} message
112
+ * @property {string} starts_at
113
+ * @property {string|null} ends_at
114
+ * @property {string} posted_at
115
+ * @property {string} posted_by
116
+ */
117
+
118
+ export function datisKey(record) {
119
+ return String((record && record.icao) || "").toUpperCase() + "/" + String((record && record.type) || "");
120
+ }
121
+
122
+ /** Keep the newest bulletin per icao/type: later issued_at, then higher revision. True when it changed. */
123
+ export function mergeDatis(latest, record) {
124
+ if (!record || !record.icao || !record.type) return false;
125
+ const key = datisKey(record);
126
+ const held = latest[key];
127
+ if (held) {
128
+ if (record.versions === held.versions) return false;
129
+ const mine = String(record.issued_at || "");
130
+ const theirs = String(held.issued_at || "");
131
+ if (mine < theirs) return false;
132
+ if (mine === theirs && Number(record.revision || 0) < Number(held.revision || 0)) return false;
133
+ }
134
+ latest[key] = Object.assign({}, record);
135
+ return true;
136
+ }
137
+
138
+ export function handshakeUrl(base, airports, {snapshot = true, sinceSeq = null, bootId = null, datis = null, notices = true} = {}) {
79
139
  const url = new URL(base);
80
140
  url.searchParams.set("airports", airports.join(","));
141
+ if (datis && datis.length) url.searchParams.set("datis", datis.join(","));
142
+ if (!notices) url.searchParams.set("notices", "false");
81
143
  if (snapshot) url.searchParams.set("snapshot", "true");
82
144
  if (sinceSeq != null && bootId) {
83
145
  url.searchParams.set("since_seq", String(sinceSeq));
@@ -86,10 +148,10 @@ export function handshakeUrl(base, airports, {snapshot = true, sinceSeq = null,
86
148
  return url.toString();
87
149
  }
88
150
 
89
- export function latestUrl(wsUrl, airports) {
151
+ export function latestUrl(wsUrl, airports, path = "/v1/metar/latest") {
90
152
  const url = new URL(wsUrl);
91
153
  url.protocol = url.protocol === "wss:" || url.protocol === "https:" ? "https:" : "http:";
92
- url.pathname = "/v1/metar/latest";
154
+ url.pathname = path;
93
155
  url.search = new URLSearchParams({airports: airports.join(",")}).toString();
94
156
  return url.toString();
95
157
  }
@@ -106,6 +168,23 @@ export async function fetchLatest(wsUrl, token, airports) {
106
168
  }
107
169
  }
108
170
 
171
+ export function datisLatestUrl(wsUrl, icaos) {
172
+ return latestUrl(wsUrl, icaos, "/v1/datis/latest");
173
+ }
174
+
175
+ export async function fetchDatisLatest(wsUrl, token, icaos) {
176
+ if (!icaos || !icaos.length) return [];
177
+ try {
178
+ const headers = token ? {Authorization: "Bearer " + token} : {};
179
+ const response = await fetch(datisLatestUrl(wsUrl, icaos), {headers});
180
+ if (!response.ok) return [];
181
+ const body = await response.json();
182
+ return body.data || [];
183
+ } catch {
184
+ return [];
185
+ }
186
+ }
187
+
109
188
  function isBrowser() {
110
189
  return typeof window !== "undefined" && typeof window.document !== "undefined";
111
190
  }
@@ -141,6 +220,11 @@ export class MetarClient {
141
220
  platform = null,
142
221
  onRecord = null,
143
222
  onFrame = null,
223
+ datis = null,
224
+ datisTypes = null,
225
+ onDatis = null,
226
+ notices = true,
227
+ onFeedNotice = null,
144
228
  } = {}) {
145
229
  this.url = url;
146
230
  this.token = resolveToken(token);
@@ -167,6 +251,20 @@ export class MetarClient {
167
251
  this.platforms = [];
168
252
  this._sessionOpen = false;
169
253
  this._grantResumePending = false;
254
+ // 0.18.0: D-ATIS and feed notices.
255
+ this.datis = (datis || []).map((name) => String(name).toUpperCase());
256
+ this.datisTypes = datisTypes && datisTypes.length ? datisTypes.slice() : null;
257
+ this.onDatis = onDatis;
258
+ this.datisLatest = {};
259
+ this.heldDatis = this.datis.slice();
260
+ this.heldDatisTypes = [];
261
+ this.datisSupported = null; // null until the first subscription_updated
262
+ this.noticesEnabled = Boolean(notices);
263
+ this.notices = [];
264
+ this.onFeedNotice = onFeedNotice;
265
+ this._datisTypesPending = false;
266
+ this.fetchLatest = fetchLatest;
267
+ this.fetchDatisLatest = fetchDatisLatest;
170
268
  if (state) this.states.push(String(state).toUpperCase());
171
269
  if (bbox) this.bboxes.push(Object.assign({}, bbox));
172
270
  if (platform) this.platforms.push(String(platform).toLowerCase());
@@ -178,6 +276,8 @@ export class MetarClient {
178
276
  snapshot: this.hasGrants() ? false : this.snapshot,
179
277
  sinceSeq: useResume ? this.seq : null,
180
278
  bootId: useResume ? this.bootId : null,
279
+ datis: this.datis,
280
+ notices: this.noticesEnabled,
181
281
  });
182
282
  }
183
283
 
@@ -192,6 +292,7 @@ export class MetarClient {
192
292
  if (Array.isArray(message.icaos)) {
193
293
  this.heldIcaos = message.icaos.map((item) => String(item).toUpperCase());
194
294
  }
295
+ this._noteDatis(message);
195
296
  if (this._sessionOpen) this._rememberGrantsFrom(message);
196
297
  else if (this.hasGrants()) this._grantResumePending = true;
197
298
  this._sessionOpen = true;
@@ -199,15 +300,28 @@ export class MetarClient {
199
300
  // current seq, and would skip replay frames not yet received.
200
301
  } else if (kind === "error") {
201
302
  this.lastError = message;
303
+ // A server that knows D-ATIS but refused it (no datis scope, or the product is off).
304
+ if (message.code === "forbidden" || message.code === "unavailable") this.datisSupported = null;
202
305
  } else if (kind === "resume") {
203
- return fetchLatest(this.url, this.token, this.heldIcaos.length ? this.heldIcaos : this.airports).then((rows) => {
306
+ const metar = this.fetchLatest(this.url, this.token, this.heldIcaos.length ? this.heldIcaos : this.airports);
307
+ const datis = message.datis_fallback && this.heldDatis.length
308
+ ? this.fetchDatisLatest(this.url, this.token, this.heldDatis)
309
+ : Promise.resolve([]);
310
+ return Promise.all([metar, datis]).then(([rows, datisRows]) => {
204
311
  for (const rec of rows) {
205
312
  const before = this.latest[rec.icao];
206
313
  mergeRecord(this.latest, rec, false);
207
314
  this._emit(rec.icao, before);
208
315
  }
316
+ this._applyDatis(datisRows);
209
317
  if (this.onFrame) this.onFrame(message);
210
318
  });
319
+ } else if (kind === "new_datis_arrived") {
320
+ this._applyDatis(message.data || []);
321
+ if (message.cached !== true && message.seq != null) this._advanceSeq(message.seq);
322
+ } else if (kind === "feed_notice") {
323
+ this.notices = Array.isArray(message.notices) ? message.notices.slice() : [];
324
+ if (this.onFeedNotice) this.onFeedNotice(this.notices);
211
325
  } else if (kind === "new_metar_arrived") {
212
326
  const live = message.cached === false && message.replay === false;
213
327
  const replayed = message.replay === true;
@@ -240,6 +354,75 @@ export class MetarClient {
240
354
  if (this.onFrame) this.onFrame(message);
241
355
  }
242
356
 
357
+ _noteDatis(message) {
358
+ const first = !this._sessionOpen;
359
+ if (Array.isArray(message.datis_icaos)) {
360
+ this.datisSupported = true;
361
+ this.heldDatis = message.datis_icaos.map((item) => String(item).toUpperCase());
362
+ if (Array.isArray(message.datis_types)) this.heldDatisTypes = message.datis_types.map(String);
363
+ // datis_types are subscribe-only: send the wanted types once per socket.
364
+ if (first && this.datisTypes) {
365
+ const want = [...this.datisTypes].sort().join(",");
366
+ const have = [...this.heldDatisTypes].sort().join(",");
367
+ if (want !== have) this._datisTypesPending = true;
368
+ }
369
+ } else if (this.datisSupported === true) {
370
+ this.heldDatis = [];
371
+ this.heldDatisTypes = [];
372
+ } else if (this.datis.length && first) {
373
+ // Asked for D-ATIS and the first answer has no datis_icaos: the server predates v0.44.0.
374
+ // A v0.44.0 server that refuses it follows with forbidden or unavailable, which resets this.
375
+ this.datisSupported = false;
376
+ this.lastError = {type: "error", code: "unsupported", message: DATIS_UNSUPPORTED};
377
+ }
378
+ }
379
+
380
+ _applyDatis(rows) {
381
+ for (const rec of rows || []) {
382
+ if (mergeDatis(this.datisLatest, rec) && this.onDatis) this.onDatis(this.datisLatest[datisKey(rec)]);
383
+ }
384
+ }
385
+
386
+ _requireDatis() {
387
+ if (this.datisSupported === false) throw new Error(DATIS_UNSUPPORTED);
388
+ }
389
+
390
+ /** Add D-ATIS stations mid-session. Throws "server does not support D-ATIS" on an old server. */
391
+ subscribeDatis(icaos, {types = null, snapshot = null} = {}) {
392
+ this._requireDatis();
393
+ const codes = icaos.map((item) => String(item).toUpperCase());
394
+ for (const code of codes) if (!this.datis.includes(code)) this.datis.push(code);
395
+ const fields = {datis: codes};
396
+ if (types != null) {
397
+ fields.datis_types = types.slice();
398
+ this.datisTypes = types.slice();
399
+ }
400
+ if (snapshot != null) fields.snapshot = snapshot;
401
+ const ws = this._ws;
402
+ if (!ws || ws.readyState !== 1) return;
403
+ ws.send(JSON.stringify(this.subscribeBody(null, fields)));
404
+ }
405
+
406
+ /** Drop D-ATIS stations mid-session; METAR stations are untouched. */
407
+ unsubscribeDatis(icaos) {
408
+ this._requireDatis();
409
+ const codes = [...new Set(icaos.map((item) => String(item).toUpperCase()))].sort();
410
+ this.datis = this.datis.filter((code) => !codes.includes(code));
411
+ for (const key of Object.keys(this.datisLatest)) {
412
+ if (codes.includes(key.split("/")[0])) delete this.datisLatest[key];
413
+ }
414
+ const ws = this._ws;
415
+ if (!ws || ws.readyState !== 1) return;
416
+ ws.send(JSON.stringify({action: "unsubscribe", datis: codes}));
417
+ }
418
+
419
+ /** Turn feed_notice frames on or off for this socket (and later reconnects). */
420
+ setNotices(enabled) {
421
+ this.noticesEnabled = Boolean(enabled);
422
+ const ws = this._ws;
423
+ if (ws && ws.readyState === 1) ws.send(JSON.stringify({action: "subscribe", notices: this.noticesEnabled}));
424
+ }
425
+
243
426
  _advanceSeq(seq) {
244
427
  if (this.seq == null || seq > this.seq) this.seq = seq;
245
428
  }
@@ -361,6 +544,10 @@ export class MetarClient {
361
544
 
362
545
  _flushGrantResume() {
363
546
  const ws = this._ws;
547
+ if (this._datisTypesPending && ws && ws.readyState === 1) {
548
+ this._datisTypesPending = false;
549
+ ws.send(JSON.stringify({action: "subscribe", datis: this.datis.slice(), datis_types: (this.datisTypes || []).slice()}));
550
+ }
364
551
  if (!this._grantResumePending || !ws || ws.readyState !== 1) return;
365
552
  this._grantResumePending = false;
366
553
  for (const body of this.reconnectSubscribeBodies()) {
@@ -410,6 +597,7 @@ export class MetarClient {
410
597
  this._ws = ws;
411
598
  this._sessionOpen = false;
412
599
  this._grantResumePending = false;
600
+ this._datisTypesPending = false;
413
601
 
414
602
  ws.addEventListener("open", () => {
415
603
  openedAt = Date.now();