@aeroswarm/client 0.1.12 → 0.1.14

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/README.md CHANGED
@@ -65,6 +65,23 @@ client.disconnect();
65
65
  | `tracks.stream(opts)` | Same live stream as an `AsyncIterable<LabeledTrack>` (`for await`) |
66
66
  | `tracks.updateFilter(opts)` | Change bbox / minConfidence / maxUpdateHz / maxTracks without reconnecting |
67
67
  | `tracks.reconnect()` | Force an immediate reconnect (skips backoff, re-subscribes with the last options, resumes after `disconnect()`); `false` if never subscribed. Also `AeroSwarm.reconnect()` and `useAeroTracks().reconnect` |
68
+ | `tracks.snapshot(input?)` | One-shot current state via tRPC (`airportId`, `bbox`, `source`, `minConfidence`, `limit`, `offset`) |
69
+ | `tracks.history(input)` | Persisted position history for one track (`trackId`, `airportId?`, `limit?`) — federated airports are served by their own backend |
70
+ | `airports.*` | Airport registry: `list/create/update/delete` + `surface`/`setSurface` (runway/taxiway/apron GeoJSON for the map) |
71
+ | `sources.*` | Register/list (optionally by `airportId`)/delete data sources (returns per-source auth tokens) |
72
+ | `alerts.*` | Alert history + live alert subscription |
73
+ | `rules.*` | Detection-rule CRUD — **global or per-airport** (see example below) |
74
+ | `routes.*` | Route conformance: pre-defined ground routes + live track clearances (deviation alerts) |
75
+ | `analytics.movements()` | Takeoffs/landings per hour + peak hour, per airport |
76
+ | `webhooks.*` | Webhook CRUD |
77
+ | `replay.days(input?)` | Data-availability calendar — which days have recorded tracks (see example below) |
78
+ | `replay.range/seek/window` | Historical replay metadata: range summary, point-in-time seek, time-bucketed window for scrubbing |
79
+ | `replay.stream(opts, cb)` | **Server-paced WS playback** — historical tracks streamed like live (see example below) |
80
+ | `system.*` | `stats`, `infraHealth`, `getConfig`/`setConfig`, `clearTable`, `ingestHistory` |
81
+ | `trpc` / `rest` / `graphql` | Direct typed API clients for anything not wrapped above — **untyped** (`createTRPCProxyClient<any>`), so prefer the wrappers above; fall back to `client.trpc.<router>.<procedure>.query/mutate(...)` only for endpoints not yet wrapped |
82
+ | `cache` | A `TrackCache` instance (see below) |
83
+ | `getStatus()` / `getLastUpdateAt()` / `getError()` / `getSourceStatus()` | Connection introspection |
84
+ | `disconnect()` | Tear down the WS connection |
68
85
 
69
86
  ### Label category / color
70
87
 
@@ -106,6 +123,7 @@ The server sends JSON envelopes `{ type, seq, serverTime, payload }`. The client
106
123
  "targetType": "aircraft", // optional: aircraft | vehicle | unknown
107
124
  "vehicleFleet": 3, // optional, only for vehicles
108
125
  "airportId": "WARR", // optional ICAO scope
126
+ "dataSource": { "sac": 32, "sic": 136 }, // optional: the sensor behind the position shown (ASTERIX feeds)
109
127
  "lat": -7.3797, "lon": 112.7868,// number | null
110
128
  "altitudeFt": 0,
111
129
  "groundSpeedKt": 12,
@@ -127,23 +145,8 @@ The server sends JSON envelopes `{ type, seq, serverTime, payload }`. The client
127
145
  ```
128
146
 
129
147
  `status` and `labelColor` change only when the track's category or status actually changes — position-only deltas leave them untouched, so a label painted from `labelColor` does not flicker.
130
- | `tracks.snapshot(input?)` | One-shot current state via tRPC (`airportId`, `bbox`, `source`, `minConfidence`, `limit`, `offset`) |
131
- | `tracks.history(input)` | Persisted position history for one track (`trackId`, `airportId?`, `limit?`) — federated airports are served by their own backend |
132
- | `airports.*` | Airport registry: `list/create/update/delete` + `surface`/`setSurface` (runway/taxiway/apron GeoJSON for the map) |
133
- | `sources.*` | Register/list (optionally by `airportId`)/delete data sources (returns per-source auth tokens) |
134
- | `alerts.*` | Alert history + live alert subscription |
135
- | `rules.*` | Detection-rule CRUD — **global or per-airport** (see example below) |
136
- | `routes.*` | Route conformance: pre-defined ground routes + live track clearances (deviation alerts) |
137
- | `analytics.movements()` | Takeoffs/landings per hour + peak hour, per airport |
138
- | `webhooks.*` | Webhook CRUD |
139
- | `replay.days(input?)` | Data-availability calendar — which days have recorded tracks (see example below) |
140
- | `replay.range/seek/window` | Historical replay metadata: range summary, point-in-time seek, time-bucketed window for scrubbing |
141
- | `replay.stream(opts, cb)` | **Server-paced WS playback** — historical tracks streamed like live (see example below) |
142
- | `system.*` | `stats`, `infraHealth`, `getConfig`/`setConfig`, `clearTable`, `ingestHistory` |
143
- | `trpc` / `rest` / `graphql` | Direct typed API clients for anything not wrapped above — **untyped** (`createTRPCProxyClient<any>`), so prefer the wrappers above; fall back to `client.trpc.<router>.<procedure>.query/mutate(...)` only for endpoints not yet wrapped |
144
- | `cache` | A `TrackCache` instance (see below) |
145
- | `getStatus()` / `getLastUpdateAt()` / `getError()` / `getSourceStatus()` | Connection introspection |
146
- | `disconnect()` | Tear down the WS connection |
148
+
149
+ `dataSource` is the ASTERIX System Area / System Identification Code (SAC/SIC) of the sensor that reported the position shown (for a merged track, the sensor that is currently preferred). `formatDataSource(track)` gives the display string `"ADSB 32/136"` (`sourceLabel(track.source)` gives just the kind: `ADSB`, `SURFACE` for CAT010/011, `MLAT`, `RADAR`, `SYSTEM`, `FUSED`); without a SAC/SIC it is the kind alone.
147
150
 
148
151
  ## Per-domain usage examples
149
152
 
@@ -449,7 +452,59 @@ Shared live-track state; feed it from your subscription callbacks and read it im
449
452
  | `setStatus` / `setSourceStatus` / `setError` / `setDegraded` / `clear` | Connection metadata |
450
453
  | Selectors | `selectAllTracks`, `selectRenderableTracks`, `selectTrack(id)`, `selectTrackCount`, `selectStatus`, `selectIsDegraded`, `selectLastUpdateAt`, `selectError` |
451
454
 
452
- ### `useTrackHistory` — smooth map animation
455
+ ### REST errors: `AeroApiError`
456
+
457
+ Every failed REST call (`client.rest.*`, federated `tracks.history` and the like) throws an `AeroApiError` that keeps what the server said, instead of just `GET /x → 500`:
458
+
459
+ ```ts
460
+ try { await client.tracks.history({ trackId, airportId: "WARR" }); }
461
+ catch (e) {
462
+ if (e instanceof AeroApiError) {
463
+ e.status; // 403
464
+ e.code; // "FORBIDDEN" — stable, for switch; a newer server may send a code you do not know
465
+ e.recoverable; // retrying later may help (rate limit, server busy)
466
+ e.message; // "Federated request /tracks/t1/history → 403: not your airport"
467
+ e.details; // whatever the server attached
468
+ }
469
+ }
470
+ ```
471
+ Servers answer either in the standard format (`{ ok, data, meta }` / `{ ok: false, error: { code, message, recoverable } }`, see `@aeroswarm/core/api`) or in the older shape (bare data, `{ ok: false, error: "text" }`); both are read. Federated calls send `x-aero-envelope: 1` to get the standard format. `parseApiResponse(res)` and `readApiBody(res)` are exported for your own `fetch` calls.
472
+
473
+ ### `useTrackMotion` / `createTrackMotion` — smooth live tracks
474
+
475
+ Feeds update a track once a second (MLAT, ADS-B) or once per antenna sweep (radar, ~7.5 s). Drawn as they arrive, icons jump. `createTrackMotion` (no React needed) shows where the aircraft *probably is right now* and eases corrections in, like a flight tracker:
476
+
477
+ ```ts
478
+ import { createTrackMotion } from "@aeroswarm/client";
479
+
480
+ const motion = createTrackMotion(); // all options optional
481
+
482
+ client.tracks.subscribe(opts, {
483
+ onSnapshot: (tracks, meta) => tracks.forEach((t) => motion.update(t, meta)),
484
+ onTrackUpdate: (t, meta) => motion.update(t, meta), // meta.serverTime keeps the clocks aligned
485
+ onTrackRemoved: ({ trackId }) => motion.remove(trackId),
486
+ });
487
+
488
+ const stop = motion.start(({ changed }) => { // ~30 frames/s, only tracks that moved
489
+ for (const [id, s] of changed) layer.put(id, s.lat, s.lon, s.headingDeg);
490
+ });
491
+ ```
492
+
493
+ React: `const motion = useTrackMotion({ onFrame })`, then call `motion.update(...)` from the subscription. Nothing here renders React.
494
+
495
+ What it does:
496
+
497
+ | | |
498
+ |---|---|
499
+ | **Dead reckoning** | From the last fix, speed and heading carry the position forward, up to `maxExtrapolateMs` (20 s in the air, 8 s on the surface). `lost` tracks freeze. |
500
+ | **Eased corrections** | A new fix does not snap the icon. The gap between where it was shown and where the fix says it should be becomes an offset that fades out (smoothstep over `blendMs`, 1.5 s). The icon keeps moving at its own speed meanwhile, so there is no stop-and-go at every update. A correction larger than `snapDistanceM` (5 km) is a glitch and jumps. |
501
+ | **Heading** | Eases along the shortest arc (`headingSmoothMs`, 0.8 s); keeps the last heading when the track stops. |
502
+ | **Server clock** | `lastSeenAt` is the server's clock. `meta.serverTime` of each message lets the engine learn the offset to the browser clock (the estimate with the least network delay wins), so a wrong browser clock does not stretch or shrink the prediction. |
503
+ | **Cheap frames** | Tracks that stand still, or whose picture changed by less than `epsilonM` (0.5 m) / 0.5°, are not reported; no timer runs while nothing moves; `frameHz` caps the rate (30). |
504
+
505
+ Options (`MotionOptions`): `blendMs`, `headingSmoothMs`, `maxExtrapolateMs`, `minMovingKt` (5), `snapDistanceM`, `frameHz`, `epsilonM`, `extrapolate` (`false` shows raw positions, for comparing sources), `isSurface`, `clock` (inject the replay clock to play back at another speed), `scheduler` (tests). `motion.sample(id)` gives the shown position at any time without touching frame state, e.g. to attach a trail's head to the icon.
506
+
507
+ ### `useTrackHistory` — smooth map animation (deprecated: use `useTrackMotion`)
453
508
 
454
509
  Maintains per-track position interpolation (tweening), dead-reckoning between updates, and bounded trail history, emitting animation frames outside React render:
455
510
 
@@ -0,0 +1,75 @@
1
+ import { CurrentTrack } from '@aeroswarm/core/types';
2
+
3
+ /** What the engine reads from a track. */
4
+ type MotionInput = Pick<CurrentTrack, "trackId" | "lat" | "lon" | "groundSpeedKt" | "headingDeg" | "altitudeFt" | "status" | "lastSeenAt"> & {
5
+ targetType?: CurrentTrack["targetType"];
6
+ };
7
+ interface MotionSample {
8
+ lat: number;
9
+ lon: number;
10
+ /** Degrees 0..360, eased; null until a valid heading has been seen. */
11
+ headingDeg: number | null;
12
+ altitudeFt: number | null;
13
+ /** Speed is above `minMovingKt`. */
14
+ moving: boolean;
15
+ /** Position currently comes from dead reckoning (not frozen, limit not reached). */
16
+ extrapolating: boolean;
17
+ }
18
+ interface MotionFrame {
19
+ /** Server-aligned time of this frame (ms). */
20
+ at: number;
21
+ /** Only tracks whose picture changed since the previous frame. */
22
+ changed: ReadonlyMap<string, MotionSample>;
23
+ }
24
+ interface MotionScheduler {
25
+ request(callback: (timestamp: number) => void): unknown;
26
+ cancel(handle: unknown): void;
27
+ }
28
+ interface MotionOptions {
29
+ /** How long a correction takes to fade out. Default 1500 ms. */
30
+ blendMs?: number;
31
+ /** How long the icon takes to turn to a new heading. Default 800 ms. */
32
+ headingSmoothMs?: number;
33
+ /** Dead reckoning stops after this long without a new fix. Default 20 s in the air, 8 s on the surface. */
34
+ maxExtrapolateMs?: {
35
+ air: number;
36
+ surface: number;
37
+ };
38
+ /** Below this speed a track is treated as standing still. Default 5 kt. */
39
+ minMovingKt?: number;
40
+ /** A correction larger than this is a glitch or a sensor change far away: jump instead of easing. Default 5000 m. */
41
+ snapDistanceM?: number;
42
+ /** Frame rate limit for `start()`. Default 30. */
43
+ frameHz?: number;
44
+ /** Changes smaller than this are not reported. Default 0.5 m (and 0.5 degrees of heading). */
45
+ epsilonM?: number;
46
+ /** false = show raw positions (for comparing against another source). Default true. */
47
+ extrapolate?: boolean;
48
+ /** Decides what counts as "on the surface". Default: vehicles, or below 150 ft. */
49
+ isSurface?: (track: MotionInput) => boolean;
50
+ /** Browser clock. Default Date.now. Inject the replay clock to play back at another speed. */
51
+ clock?: () => number;
52
+ /** Frame timer. Default requestAnimationFrame, else setTimeout. Inject in tests. */
53
+ scheduler?: MotionScheduler;
54
+ }
55
+ interface TrackMotion {
56
+ /** `meta.serverTime` (from the WS envelope) keeps the server/browser clock offset current. */
57
+ update(track: MotionInput, meta?: {
58
+ serverTime?: number;
59
+ }): void;
60
+ remove(trackId: string): void;
61
+ clear(): void;
62
+ /** Where the track is shown at `at` (browser time; default now). Pure: does not touch frame state. */
63
+ sample(trackId: string, at?: number): MotionSample | undefined;
64
+ /** One frame: the tracks whose picture changed since the previous frame. `start()` calls this for you. */
65
+ tick(at?: number): ReadonlyMap<string, MotionSample>;
66
+ /** Runs frames until the returned function is called. Idles (no timer) while nothing moves. */
67
+ start(onFrame: (frame: MotionFrame) => void): () => void;
68
+ /** Tracks currently held. */
69
+ readonly size: number;
70
+ /** Current server minus browser clock, ms. */
71
+ offsetMs(): number;
72
+ }
73
+ declare function createTrackMotion(options?: MotionOptions): TrackMotion;
74
+
75
+ export { type MotionFrame as M, type TrackMotion as T, type MotionInput as a, type MotionOptions as b, type MotionSample as c, type MotionScheduler as d, createTrackMotion as e };