mobs-ws 0.16.1 → 0.17.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 +26 -9
  2. package/package.json +1 -1
  3. package/src/index.js +150 -6
package/README.md CHANGED
@@ -2,13 +2,27 @@
2
2
 
3
3
  Official JavaScript client for the MOBS `/v1/ws/metar` WebSocket (protocol 4).
4
4
 
5
- There are no runtime dependencies. The client uses the global `WebSocket`
6
- in the browser and in Node 22+. Snapshot and resume are opt-in. The client
7
- applies `awc_confirmed` frames last-wins per (`icao`, `versions`),
8
- handles `station_late`, `station_recovered`, and `usage` (use
9
- `requestUsage()`), and ignores unknown frame types. Late alerts are kept as the latest frame per `outage_id` and cleared on `station_recovered`. More than one `station_late` can arrive in the same outage. A change-only
10
- `filter` and parsed `delta` are opt-in on a mid-session `subscribe`,
11
- not on the handshake.
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
7
+ uses the global `WebSocket` in the browser and in Node 22+. Snapshot
8
+ and resume are opt-in. The client applies `awc_confirmed` frames
9
+ last-wins per (`icao`, `versions`), handles `station_late`,
10
+ `station_recovered`, and `usage` (use `requestUsage()`), and ignores
11
+ unknown frame types. Late alerts are kept as the latest frame per
12
+ `outage_id` and cleared on `station_recovered`. More than one
13
+ `station_late` can arrive in the same outage. Snapshot frames are
14
+ marked `cached`; they are merged into `latest` and do not advance
15
+ `seq`.
16
+
17
+ A change-only `filter`, parsed `delta`, a US `state`, a `bbox`, and a
18
+ `platform` (`polymarket_com` or `polymarket_us`) are opt-in on a
19
+ mid-session `subscribe`, not on the handshake query. A region or
20
+ platform grant counts as one subscription; a socket may hold at most
21
+ 10 grants. `invalid_region`, `unknown_platform`, and `too_many_grants`
22
+ are stored on `lastError`. On reconnect, the client passes `since_seq`
23
+ and `boot_id` as before, and re-subscribes held grants. The first
24
+ state, first bounding box, and first platform can be replayed; any
25
+ extra grants of the same kind are restored by snapshot, not replay.
12
26
 
13
27
  The API key is never embedded. Pass it to the constructor, or set
14
28
  `MOBS_TOKEN` (Node). In the browser, pass the token in and the client
@@ -16,7 +30,7 @@ uses `?token=` because a page cannot set socket headers. A browser
16
30
  `WebSocket` cannot see a handshake 401 or 403, so the client retries.
17
31
 
18
32
  ```bash
19
- npm install mobs-ws
33
+ npm install mobs-ws@0.17.0
20
34
  export MOBS_TOKEN=$MOBS_TOKEN
21
35
  ```
22
36
 
@@ -28,10 +42,13 @@ const client = new MetarClient({
28
42
  token: process.env.MOBS_TOKEN, // or "YOUR_API_KEY"
29
43
  snapshot: true,
30
44
  resume: true,
45
+ platform: "polymarket_com",
31
46
  onRecord: (rec) => console.log(rec.icao, rec.raw_metar, rec.awc_confirmed),
32
47
  });
33
48
 
49
+ // Mid-session: client.subscribe([], {state: "NY"})
50
+ // or client.subscribe([], {bbox: {south:40.0,west:-75.0,north:41.5,east:-73.0}})
34
51
  await client.runForever();
35
52
  ```
36
53
 
37
- MIT licensed. See [LICENSE](https://github.com/mobs-ws/mobs-sdks/blob/main/LICENSE).
54
+ 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.16.1",
3
+ "version": "0.17.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
@@ -5,6 +5,17 @@
5
5
  // variable. It is never embedded.
6
6
 
7
7
  export const DEFAULT_URL = "wss://mobs.ws/v1/ws/metar";
8
+ export const MAX_GRANTS = 10;
9
+ export const KNOWN_PLATFORMS = Object.freeze(["polymarket_com", "polymarket_us"]);
10
+ export const ERROR_CODES = Object.freeze([
11
+ "invalid_airports",
12
+ "bad_request",
13
+ "unknown_action",
14
+ "too_many_airports",
15
+ "invalid_region",
16
+ "unknown_platform",
17
+ "too_many_grants",
18
+ ]);
8
19
  export const PING_EVERY_MS = 20000;
9
20
  export const PONG_TIMEOUT_MS = 15000;
10
21
  export const BACKOFF_START_MS = 1000;
@@ -125,6 +136,9 @@ export class MetarClient {
125
136
  url = DEFAULT_URL,
126
137
  snapshot = true,
127
138
  resume = true,
139
+ state = null,
140
+ bbox = null,
141
+ platform = null,
128
142
  onRecord = null,
129
143
  onFrame = null,
130
144
  } = {}) {
@@ -146,24 +160,47 @@ export class MetarClient {
146
160
  this.lastLate = null;
147
161
  this.lastRecovered = null;
148
162
  this.lates = {};
163
+ this.lastError = null;
164
+ this.heldIcaos = this.airports.slice();
165
+ this.states = [];
166
+ this.bboxes = [];
167
+ this.platforms = [];
168
+ this._sessionOpen = false;
169
+ this._grantResumePending = false;
170
+ if (state) this.states.push(String(state).toUpperCase());
171
+ if (bbox) this.bboxes.push(Object.assign({}, bbox));
172
+ if (platform) this.platforms.push(String(platform).toLowerCase());
149
173
  }
150
174
 
151
175
  handshakeUrl() {
176
+ const useResume = this.resume && !this.hasGrants();
152
177
  return handshakeUrl(this.url, this.airports, {
153
- snapshot: this.snapshot,
154
- sinceSeq: this.resume ? this.seq : null,
155
- bootId: this.resume ? this.bootId : null,
178
+ snapshot: this.hasGrants() ? false : this.snapshot,
179
+ sinceSeq: useResume ? this.seq : null,
180
+ bootId: useResume ? this.bootId : null,
156
181
  });
157
182
  }
158
183
 
184
+ hasGrants() {
185
+ return this.states.length > 0 || this.bboxes.length > 0 || this.platforms.length > 0;
186
+ }
187
+
159
188
  handleFrame(message) {
160
189
  const kind = message && message.type;
161
190
  if (kind === "subscription_updated") {
162
191
  if (message.boot_id) this.bootId = message.boot_id;
192
+ if (Array.isArray(message.icaos)) {
193
+ this.heldIcaos = message.icaos.map((item) => String(item).toUpperCase());
194
+ }
195
+ if (this._sessionOpen) this._rememberGrantsFrom(message);
196
+ else if (this.hasGrants()) this._grantResumePending = true;
197
+ this._sessionOpen = true;
163
198
  // Do not take seq from subscription_updated: it is the server's
164
199
  // current seq, and would skip replay frames not yet received.
200
+ } else if (kind === "error") {
201
+ this.lastError = message;
165
202
  } else if (kind === "resume") {
166
- return fetchLatest(this.url, this.token, this.airports).then((rows) => {
203
+ return fetchLatest(this.url, this.token, this.heldIcaos.length ? this.heldIcaos : this.airports).then((rows) => {
167
204
  for (const rec of rows) {
168
205
  const before = this.latest[rec.icao];
169
206
  mergeRecord(this.latest, rec, false);
@@ -222,10 +259,113 @@ export class MetarClient {
222
259
  }
223
260
  }
224
261
 
262
+ subscribeBody(icaos, fields = {}) {
263
+ const body = {action: "subscribe"};
264
+ if (icaos != null) body.icaos = icaos.map((item) => String(item).toUpperCase());
265
+ if (fields.state != null) body.state = String(fields.state).toUpperCase();
266
+ if (fields.bbox != null) body.bbox = Object.assign({}, fields.bbox);
267
+ if (fields.platform != null) body.platform = String(fields.platform).toLowerCase();
268
+ if (fields.since_seq != null && fields.boot_id) {
269
+ body.since_seq = fields.since_seq;
270
+ body.boot_id = fields.boot_id;
271
+ }
272
+ if (fields.snapshot != null) body.snapshot = Boolean(fields.snapshot);
273
+ for (const [key, value] of Object.entries(fields)) {
274
+ if (!["state", "bbox", "platform", "since_seq", "boot_id", "snapshot"].includes(key)) {
275
+ body[key] = value;
276
+ }
277
+ }
278
+ return body;
279
+ }
280
+
281
+ reconnectSubscribeBodies() {
282
+ const states = this.states.slice();
283
+ const bboxes = this.bboxes.slice();
284
+ const platforms = this.platforms.slice();
285
+ const first = this.subscribeBody(this.airports.length ? this.airports : null, {
286
+ state: states.length ? states.shift() : null,
287
+ bbox: bboxes.length ? bboxes.shift() : null,
288
+ platform: platforms.length ? platforms.shift() : null,
289
+ since_seq: this.resume ? this.seq : null,
290
+ boot_id: this.resume ? this.bootId : null,
291
+ snapshot: this.snapshot ? true : null,
292
+ });
293
+ const bodies = [first];
294
+ while (states.length || bboxes.length || platforms.length) {
295
+ bodies.push(this.subscribeBody(null, {
296
+ state: states.length ? states.shift() : null,
297
+ bbox: bboxes.length ? bboxes.shift() : null,
298
+ platform: platforms.length ? platforms.shift() : null,
299
+ snapshot: true,
300
+ }));
301
+ }
302
+ return bodies;
303
+ }
304
+
305
+ _rememberGrantsFrom(message) {
306
+ const regions = message.regions || [];
307
+ const platforms = message.platforms || [];
308
+ const states = [];
309
+ const bboxes = [];
310
+ for (const item of regions) {
311
+ const raw = String(item);
312
+ if (raw.toLowerCase().startsWith("state:")) states.push(raw.split(":").slice(1).join(":").toUpperCase());
313
+ else if (raw.toLowerCase().startsWith("bbox:")) {
314
+ const parts = raw.split(":").slice(1).join(":").split(",");
315
+ if (parts.length === 4) {
316
+ const nums = parts.map(Number);
317
+ if (nums.every((n) => Number.isFinite(n))) {
318
+ bboxes.push({south: nums[0], west: nums[1], north: nums[2], east: nums[3]});
319
+ }
320
+ }
321
+ }
322
+ }
323
+ this.states = states;
324
+ this.bboxes = bboxes;
325
+ this.platforms = platforms.map((name) => String(name).toLowerCase());
326
+ }
327
+
328
+ _rememberOutgoingGrants(body) {
329
+ if (body.state && !this.states.includes(body.state)) this.states.push(body.state);
330
+ if (body.bbox) this.bboxes.push(Object.assign({}, body.bbox));
331
+ if (body.platform && !this.platforms.includes(body.platform)) this.platforms.push(body.platform);
332
+ if (Array.isArray(body.icaos)) {
333
+ for (const item of body.icaos) {
334
+ const code = String(item).toUpperCase();
335
+ if (!this.airports.includes(code)) this.airports.push(code);
336
+ }
337
+ }
338
+ }
339
+
225
340
  subscribe(icaos = [], fields = {}) {
226
341
  const ws = this._ws;
227
342
  if (!ws || ws.readyState !== 1) return;
228
- ws.send(JSON.stringify(Object.assign({action: "subscribe", icaos}, fields)));
343
+ const body = this.subscribeBody(icaos, fields);
344
+ this._rememberOutgoingGrants(body);
345
+ ws.send(JSON.stringify(body));
346
+ }
347
+
348
+ unsubscribe(icaos = null, fields = {}) {
349
+ const ws = this._ws;
350
+ if (!ws || ws.readyState !== 1) return;
351
+ const body = {action: "unsubscribe"};
352
+ if (icaos != null) body.icaos = icaos.map((item) => String(item).toUpperCase());
353
+ if (fields.state != null) body.state = String(fields.state).toUpperCase();
354
+ if (fields.bbox != null) body.bbox = Object.assign({}, fields.bbox);
355
+ if (fields.platform != null) body.platform = String(fields.platform).toLowerCase();
356
+ for (const [key, value] of Object.entries(fields)) {
357
+ if (!["state", "bbox", "platform"].includes(key)) body[key] = value;
358
+ }
359
+ ws.send(JSON.stringify(body));
360
+ }
361
+
362
+ _flushGrantResume() {
363
+ const ws = this._ws;
364
+ if (!this._grantResumePending || !ws || ws.readyState !== 1) return;
365
+ this._grantResumePending = false;
366
+ for (const body of this.reconnectSubscribeBodies()) {
367
+ ws.send(JSON.stringify(body));
368
+ }
229
369
  }
230
370
 
231
371
  stop() {
@@ -268,6 +408,8 @@ export class MetarClient {
268
408
  return;
269
409
  }
270
410
  this._ws = ws;
411
+ this._sessionOpen = false;
412
+ this._grantResumePending = false;
271
413
 
272
414
  ws.addEventListener("open", () => {
273
415
  openedAt = Date.now();
@@ -296,7 +438,9 @@ export class MetarClient {
296
438
  clearTimeout(pongTimer);
297
439
  pongTimer = null;
298
440
  }
299
- this.handleFrame(message);
441
+ const result = this.handleFrame(message);
442
+ if (result && typeof result.then === "function") result.then(() => this._flushGrantResume());
443
+ else this._flushGrantResume();
300
444
  });
301
445
 
302
446
  ws.addEventListener("close", (event) => {