@ksp-gonogo/kerbcast 1.11.0-rc.10 → 1.11.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.
package/README.md CHANGED
@@ -63,6 +63,11 @@ Commands can be sent as soon as `connect` resolves. Any sent before the
63
63
  control channel has opened wait for it, and reject if it has not opened
64
64
  within 10 s or the client disconnects first.
65
65
 
66
+ Kerbcast streams H.264 only. A browser that offers none (some Firefox builds
67
+ ship without OpenH264) is refused, and `connect` rejects with an
68
+ `OfferRefusedError` whose `code` is `ErrorCode.CodecUnsupported` and whose
69
+ message says what to change.
70
+
66
71
  ### Pre-handshake discovery
67
72
 
68
73
  ```ts
@@ -350,6 +355,14 @@ await client.setCommandAim(hill.flightId, null);
350
355
  A station watching a craft is the same with
351
356
  `{ kind: CommandVantageKind.Station, station: "KSC" }` and a `vessel` aim.
352
357
 
358
+ A `vessel` aim, or an `orbit` or `positionAt` aim's `subjectPersistentId`,
359
+ must name a craft in the camera's `commandCentre.targets`. One that is not
360
+ there (a craft merged into another by docking, or destroyed) makes
361
+ `setCommandAim` reject with a `CommandTargetUnknownError`; a call that races
362
+ the list changing comes back as an `error` event with code
363
+ `ErrorCode.CommandTargetUnknown`. Before the game has reported the camera's
364
+ list, the aim is sent and the game decides.
365
+
353
366
  ### The command lock
354
367
 
355
368
  A mod in game can take a lock on every command camera's aim
@@ -632,7 +632,18 @@ export declare enum ErrorCode {
632
632
  /** The named camera exists but its part is gone. */
633
633
  CameraDestroyed = "camera-destroyed",
634
634
  /** A command authority in game holds the command cameras' aim lock. */
635
- CommandLocked = "command-locked"
635
+ CommandLocked = "command-locked",
636
+ /**
637
+ * A command aim names a craft that is not in the camera's latest
638
+ * `commandCentre.targets`, for example one merged away in a dock.
639
+ */
640
+ CommandTargetUnknown = "command-target-unknown",
641
+ /**
642
+ * `POST /offer` refused: the offer's video carries no H.264 with
643
+ * packetization-mode=1, the only video Kerbcast sends. A browser
644
+ * without H.264 support (some Firefox builds lack OpenH264) offers none.
645
+ */
646
+ CodecUnsupported = "codec-unsupported"
636
647
  }
637
648
  export interface ErrorPayload {
638
649
  message: string;
@@ -172,4 +172,15 @@ export var ErrorCode;
172
172
  ErrorCode["CameraDestroyed"] = "camera-destroyed";
173
173
  /** A command authority in game holds the command cameras' aim lock. */
174
174
  ErrorCode["CommandLocked"] = "command-locked";
175
+ /**
176
+ * A command aim names a craft that is not in the camera's latest
177
+ * `commandCentre.targets`, for example one merged away in a dock.
178
+ */
179
+ ErrorCode["CommandTargetUnknown"] = "command-target-unknown";
180
+ /**
181
+ * `POST /offer` refused: the offer's video carries no H.264 with
182
+ * packetization-mode=1, the only video Kerbcast sends. A browser
183
+ * without H.264 support (some Firefox builds lack OpenH264) offers none.
184
+ */
185
+ ErrorCode["CodecUnsupported"] = "codec-unsupported";
175
186
  })(ErrorCode || (ErrorCode = {}));
package/dist/client.d.ts CHANGED
@@ -302,6 +302,27 @@ export declare class CommandLockedError extends Error {
302
302
  readonly code = ErrorCode.CommandLocked;
303
303
  constructor(owner: string);
304
304
  }
305
+ /**
306
+ * {@link KerbcastClient.setCommandAim} refused because the aim's craft (a
307
+ * `vessel` aim's craft, or an `orbit` or `positionAt` aim's subject) is not in
308
+ * the camera's `commandCentre.targets`, for example one merged away in a dock.
309
+ */
310
+ export declare class CommandTargetUnknownError extends Error {
311
+ readonly flightId: number;
312
+ readonly persistentId: number;
313
+ readonly code = ErrorCode.CommandTargetUnknown;
314
+ constructor(flightId: number, persistentId: number);
315
+ }
316
+ /**
317
+ * The sidecar refused `POST /offer` with a reason, for example
318
+ * `ErrorCode.CodecUnsupported` when the browser offers no H.264 video.
319
+ */
320
+ export declare class OfferRefusedError extends Error {
321
+ readonly status: number;
322
+ readonly reason: string;
323
+ readonly code?: ErrorCode | undefined;
324
+ constructor(status: number, reason: string, code?: ErrorCode | undefined);
325
+ }
305
326
  /** How long {@link KerbcastClient.createCommandCamera} waits for the camera by default. */
306
327
  export declare const COMMAND_CAMERA_CREATE_TIMEOUT_MS = 35000;
307
328
  /**
@@ -703,6 +724,11 @@ export declare class KerbcastClient extends TypedEmitter<KerbcastClientEvents> {
703
724
  * (`commandTrack.authority`): it holds the lock and only it can aim. A
704
725
  * refusal that races the lock being taken arrives as an `error` event with
705
726
  * code `ErrorCode.CommandLocked` instead.
727
+ *
728
+ * Rejects with a {@link CommandTargetUnknownError} when the aim's craft is
729
+ * not in the camera's `commandCentre.targets` (a craft merged away in a
730
+ * dock, say). A refusal that races the list changing arrives as an `error`
731
+ * event with code `ErrorCode.CommandTargetUnknown`.
706
732
  */
707
733
  setCommandAim(flightId: number, aim: CommandAim | null): Promise<void>;
708
734
  /**
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- import { CameraKind, CameraLifecycle, ErrorCode, ErrorSource } from "./__generated__/types";
1
+ import { CameraKind, CameraLifecycle, CommandAimKind, ErrorCode, ErrorSource } from "./__generated__/types";
2
2
  import { FrameStampStore, STAMP_TO_DISPLAY_MAX_MS, extrapolateCaptureUt, monotonicNowMs, } from "./frameUt";
3
3
  import { tryCreateNoisePipeline, } from "./noise";
4
4
  import { RecordingController } from "./recording";
@@ -34,6 +34,42 @@ export class CommandLockedError extends Error {
34
34
  this.name = "CommandLockedError";
35
35
  }
36
36
  }
37
+ /**
38
+ * {@link KerbcastClient.setCommandAim} refused because the aim's craft (a
39
+ * `vessel` aim's craft, or an `orbit` or `positionAt` aim's subject) is not in
40
+ * the camera's `commandCentre.targets`, for example one merged away in a dock.
41
+ */
42
+ export class CommandTargetUnknownError extends Error {
43
+ constructor(flightId, persistentId) {
44
+ super(`[kerbcast] craft ${persistentId} is not among camera ${flightId}'s targets; aim refused`);
45
+ this.flightId = flightId;
46
+ this.persistentId = persistentId;
47
+ this.code = ErrorCode.CommandTargetUnknown;
48
+ this.name = "CommandTargetUnknownError";
49
+ }
50
+ }
51
+ /**
52
+ * The sidecar refused `POST /offer` with a reason, for example
53
+ * `ErrorCode.CodecUnsupported` when the browser offers no H.264 video.
54
+ */
55
+ export class OfferRefusedError extends Error {
56
+ constructor(status, reason, code) {
57
+ super(`[kerbcast] connection refused: ${reason}`);
58
+ this.status = status;
59
+ this.reason = reason;
60
+ this.code = code;
61
+ this.name = "OfferRefusedError";
62
+ }
63
+ }
64
+ /** The craft an aim names: a `vessel` aim's craft, or an `orbit` or `positionAt` aim's subject. */
65
+ function aimCraft(aim) {
66
+ const pid = aim.kind === CommandAimKind.Vessel
67
+ ? aim.persistentId
68
+ : aim.kind === CommandAimKind.Orbit || aim.kind === CommandAimKind.PositionAt
69
+ ? aim.subjectPersistentId
70
+ : undefined;
71
+ return pid ? pid : undefined;
72
+ }
37
73
  /** How long {@link KerbcastClient.createCommandCamera} waits for the camera by default. */
38
74
  export const COMMAND_CAMERA_CREATE_TIMEOUT_MS = 35000;
39
75
  /**
@@ -1023,8 +1059,14 @@ export class KerbcastClient extends TypedEmitter {
1023
1059
  headers: { "Content-Type": "application/json" },
1024
1060
  body: JSON.stringify(offer),
1025
1061
  });
1026
- if (!res.ok)
1062
+ if (!res.ok) {
1063
+ /* A refusal carries an ErrorPayload; anything else keeps the bare status. */
1064
+ const refusal = (await res.json().catch(() => null));
1065
+ if (typeof refusal?.message === "string") {
1066
+ throw new OfferRefusedError(res.status, refusal.message, refusal.code);
1067
+ }
1027
1068
  throw new Error(`POST /offer returned ${res.status}`);
1069
+ }
1028
1070
  return (await res.json());
1029
1071
  }
1030
1072
  disconnect() {
@@ -1119,12 +1161,24 @@ export class KerbcastClient extends TypedEmitter {
1119
1161
  * (`commandTrack.authority`): it holds the lock and only it can aim. A
1120
1162
  * refusal that races the lock being taken arrives as an `error` event with
1121
1163
  * code `ErrorCode.CommandLocked` instead.
1164
+ *
1165
+ * Rejects with a {@link CommandTargetUnknownError} when the aim's craft is
1166
+ * not in the camera's `commandCentre.targets` (a craft merged away in a
1167
+ * dock, say). A refusal that races the list changing arrives as an `error`
1168
+ * event with code `ErrorCode.CommandTargetUnknown`.
1122
1169
  */
1123
1170
  async setCommandAim(flightId, aim) {
1124
- const owner = this._cameras.find((c) => c.flightId === flightId)?.commandTrack?.authority?.owner;
1171
+ const cam = this._cameras.find((c) => c.flightId === flightId);
1172
+ const owner = cam?.commandTrack?.authority?.owner;
1125
1173
  if (owner) {
1126
1174
  throw new CommandLockedError(owner);
1127
1175
  }
1176
+ /* An empty list is what the game writes when listing fails, so it decides then. */
1177
+ const craft = aim ? aimCraft(aim) : undefined;
1178
+ const targets = cam?.commandCentre?.targets;
1179
+ if (craft !== undefined && targets?.length && !targets.some((t) => t.persistentId === craft)) {
1180
+ throw new CommandTargetUnknownError(flightId, craft);
1181
+ }
1128
1182
  await this._send({
1129
1183
  type: "set-command-aim",
1130
1184
  content: aim ? { flightId, aim } : { flightId },
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from "./__generated__/types";
2
- export { KerbcastClient, BrowserKerbcastTransport, COMMAND_CAMERA_CREATE_TIMEOUT_MS, CommandLockedError, COMMAND_CAMERA_STATE_WAIT_MS, CONTROL_OPEN_TIMEOUT_MS, type CreateCommandCameraOptions, type BrowserKerbcastTransportOptions, type InboundVideoStats, type KerbcastCameraHandle, type KerbcastClientConfig, type KerbcastConnectionState, type KerbcastClientEvents, type KerbcastCameraEvents, type KerbcastTransport, type KerbcastPeer, type KerbcastPeerOptions, type KerbcastDataChannel, type EncodedTransform, type EncodedTransformContext, type EncodedTransformFactory, type EncodedTransformPath, type DiscoveredCamera, type NoiseConfig, } from "./client";
2
+ export { KerbcastClient, BrowserKerbcastTransport, COMMAND_CAMERA_CREATE_TIMEOUT_MS, CommandLockedError, CommandTargetUnknownError, OfferRefusedError, COMMAND_CAMERA_STATE_WAIT_MS, CONTROL_OPEN_TIMEOUT_MS, type CreateCommandCameraOptions, type BrowserKerbcastTransportOptions, type InboundVideoStats, type KerbcastCameraHandle, type KerbcastClientConfig, type KerbcastConnectionState, type KerbcastClientEvents, type KerbcastCameraEvents, type KerbcastTransport, type KerbcastPeer, type KerbcastPeerOptions, type KerbcastDataChannel, type EncodedTransform, type EncodedTransformContext, type EncodedTransformFactory, type EncodedTransformPath, type DiscoveredCamera, type NoiseConfig, } from "./client";
3
3
  export { FRAME_STAMP_HISTORY, MAX_UT_EXTRAPOLATION_MS, STAMP_TO_DISPLAY_MAX_MS, extrapolateCaptureUt, type DisplayedFrameUt, type FrameUt, type FrameUtSource, } from "./frameUt";
4
4
  export { PanZoomController, type PanZoomCommandSink, type PanZoomBounds, type PanZoomControllerOptions, } from "./panZoom";
5
5
  export { RecordingController, createMediabunnyTrimmerLoader, negotiateMimeType, commonUtWindow, utToRecordingTimeMs, DEFAULT_COVERAGE_TIMEOUT_MS, ARM_TIMEOUT_MS, videoElementDecodedSizeProbe, type ActiveRecordingInfo, type DecodedSizeProbe, type RecordingClient, type RecordingControllerOptions, type RecordingHandle, type RecordingsSnapshot, type GroupedRecordingHandle, type GroupedRecordingStart, type GroupTrimmer, type TrimmerLoader, type UtSample, type StartRecordingOptions, type StopGroupedRecordingOptions, } from "./recording";
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // `KerbcastClient` re-exported below, but the underlying wire types
4
4
  // stay available for consumers that want to roll their own transport.
5
5
  export * from "./__generated__/types";
6
- export { KerbcastClient, BrowserKerbcastTransport, COMMAND_CAMERA_CREATE_TIMEOUT_MS, CommandLockedError, COMMAND_CAMERA_STATE_WAIT_MS, CONTROL_OPEN_TIMEOUT_MS, } from "./client";
6
+ export { KerbcastClient, BrowserKerbcastTransport, COMMAND_CAMERA_CREATE_TIMEOUT_MS, CommandLockedError, CommandTargetUnknownError, OfferRefusedError, COMMAND_CAMERA_STATE_WAIT_MS, CONTROL_OPEN_TIMEOUT_MS, } from "./client";
7
7
  export { FRAME_STAMP_HISTORY, MAX_UT_EXTRAPOLATION_MS, STAMP_TO_DISPLAY_MAX_MS, extrapolateCaptureUt, } from "./frameUt";
8
8
  export { PanZoomController, } from "./panZoom";
9
9
  export { RecordingController, createMediabunnyTrimmerLoader, negotiateMimeType, commonUtWindow, utToRecordingTimeMs, DEFAULT_COVERAGE_TIMEOUT_MS, ARM_TIMEOUT_MS, videoElementDecodedSizeProbe, } from "./recording";
@@ -553,6 +553,25 @@ export class MockSidecar {
553
553
  });
554
554
  break;
555
555
  }
556
+ const aim = msg.content.aim;
557
+ const craft = aim?.kind === CommandAimKind.Vessel
558
+ ? aim.persistentId
559
+ : aim?.kind === CommandAimKind.Orbit || aim?.kind === CommandAimKind.PositionAt
560
+ ? aim.subjectPersistentId
561
+ : undefined;
562
+ const targets = cam.commandCentre.targets;
563
+ if (craft && targets.length > 0 && !targets.some((t) => t.persistentId === craft)) {
564
+ this._sendToClient({
565
+ type: "error",
566
+ content: {
567
+ message: `craft ${craft} is not among camera ${msg.content.flightId}'s targets; aim refused`,
568
+ source: ErrorSource.Sidecar,
569
+ flightId: msg.content.flightId,
570
+ code: ErrorCode.CommandTargetUnknown,
571
+ },
572
+ });
573
+ break;
574
+ }
556
575
  const updated = {
557
576
  ...cam,
558
577
  commandCentre: { ...cam.commandCentre, ...aimFields(msg.content.aim ?? null, this._defaultSubject) },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ksp-gonogo/kerbcast",
3
- "version": "1.11.0-rc.10",
3
+ "version": "1.11.0",
4
4
  "description": "TypeScript client for the kerbcast KSP camera-streaming sidecar. KerbcastClient wraps the WebRTC peer + control channel; wire-format types are typeshare-generated from the sidecar's Rust protocol module.",
5
5
  "license": "MIT",
6
6
  "author": "Jon Pepler",
@@ -662,6 +662,17 @@ export enum ErrorCode {
662
662
  CameraDestroyed = "camera-destroyed",
663
663
  /** A command authority in game holds the command cameras' aim lock. */
664
664
  CommandLocked = "command-locked",
665
+ /**
666
+ * A command aim names a craft that is not in the camera's latest
667
+ * `commandCentre.targets`, for example one merged away in a dock.
668
+ */
669
+ CommandTargetUnknown = "command-target-unknown",
670
+ /**
671
+ * `POST /offer` refused: the offer's video carries no H.264 with
672
+ * packetization-mode=1, the only video Kerbcast sends. A browser
673
+ * without H.264 support (some Firefox builds lack OpenH264) offers none.
674
+ */
675
+ CodecUnsupported = "codec-unsupported",
665
676
  }
666
677
 
667
678
  export interface ErrorPayload {
@@ -14,7 +14,9 @@ import {
14
14
  BrowserKerbcastTransport,
15
15
  COMMAND_CAMERA_STATE_WAIT_MS,
16
16
  CommandLockedError,
17
+ CommandTargetUnknownError,
17
18
  CONTROL_OPEN_TIMEOUT_MS,
19
+ OfferRefusedError,
18
20
  type KerbcastConnectionState,
19
21
  type KerbcastDataChannel,
20
22
  type KerbcastPeer,
@@ -835,6 +837,39 @@ describe("KerbcastClient", () => {
835
837
  JSON.stringify({ type: "set-command-aim", content: { flightId: 300 } }),
836
838
  ]);
837
839
  });
840
+
841
+ it("setCommandAim rejects an aim at a craft missing from the target list", async () => {
842
+ const { client, captured, snapshot } = await connected();
843
+ snapshot([commandCamera(300)]);
844
+
845
+ const err = await client
846
+ .setCommandAim(300, { kind: CommandAimKind.Vessel, persistentId: 99 })
847
+ .catch((e: unknown) => e);
848
+ expect(err).toBeInstanceOf(CommandTargetUnknownError);
849
+ expect((err as CommandTargetUnknownError).code).toBe(ErrorCode.CommandTargetUnknown);
850
+ expect((err as CommandTargetUnknownError).persistentId).toBe(99);
851
+ expect((err as CommandTargetUnknownError).flightId).toBe(300);
852
+ await expect(
853
+ client.setCommandAim(300, {
854
+ kind: CommandAimKind.PositionAt,
855
+ body: "Kerbin",
856
+ ut: 0,
857
+ position: [0, 0, 7e5],
858
+ velocity: [0, 0, 0],
859
+ subjectPersistentId: 99,
860
+ }),
861
+ ).rejects.toBeInstanceOf(CommandTargetUnknownError);
862
+ expect(captured.dc?.sent).toEqual([]);
863
+
864
+ await client.setCommandAim(300, { kind: CommandAimKind.Vessel, persistentId: 42 });
865
+ await client.setCommandAim(300, { kind: CommandAimKind.Direction, azimuth: 0, elevation: 10 });
866
+ expect(captured.dc?.sent).toHaveLength(2);
867
+
868
+ /* No list yet: the game decides. */
869
+ snapshot([commandCamera(301, undefined, false)]);
870
+ await client.setCommandAim(301, { kind: CommandAimKind.Vessel, persistentId: 99 });
871
+ expect(captured.dc?.sent).toHaveLength(3);
872
+ });
838
873
  });
839
874
 
840
875
  it("disconnect tears down peer + emits null MediaStream events", async () => {
@@ -895,6 +930,28 @@ describe("KerbcastClient", () => {
895
930
  expect(client.state).toBe("failed");
896
931
  });
897
932
 
933
+ it("a refused /offer surfaces the sidecar's reason and code", async () => {
934
+ const { transport } = makeFakeTransport();
935
+ const client = new KerbcastClient({ host: "h", port: 1 }, transport);
936
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
937
+ new Response(
938
+ JSON.stringify({
939
+ message: "the browser offered no H.264 video",
940
+ source: ErrorSource.Sidecar,
941
+ code: ErrorCode.CodecUnsupported,
942
+ }),
943
+ { status: 422, headers: { "content-type": "application/json" } },
944
+ ),
945
+ );
946
+
947
+ const err = await client.connect().catch((e: unknown) => e);
948
+ expect(err).toBeInstanceOf(OfferRefusedError);
949
+ expect((err as OfferRefusedError).status).toBe(422);
950
+ expect((err as OfferRefusedError).code).toBe(ErrorCode.CodecUnsupported);
951
+ expect((err as Error).message).toMatch(/no H\.264 video/);
952
+ expect(client.state).toBe("failed");
953
+ });
954
+
898
955
  it("discover() returns the camera list from /cameras", async () => {
899
956
  const { transport } = makeFakeTransport();
900
957
  const client = new KerbcastClient({ host: "h", port: 1 }, transport);
package/src/client.ts CHANGED
@@ -12,7 +12,7 @@ import type {
12
12
  SettingsStatePayload,
13
13
  TrackMode,
14
14
  } from "./__generated__/types";
15
- import { CameraKind, CameraLifecycle, ErrorCode, ErrorSource } from "./__generated__/types";
15
+ import { CameraKind, CameraLifecycle, CommandAimKind, ErrorCode, ErrorSource } from "./__generated__/types";
16
16
  import {
17
17
  type DisplayedFrameUt,
18
18
  type FrameUt,
@@ -380,6 +380,49 @@ export class CommandLockedError extends Error {
380
380
  }
381
381
  }
382
382
 
383
+ /**
384
+ * {@link KerbcastClient.setCommandAim} refused because the aim's craft (a
385
+ * `vessel` aim's craft, or an `orbit` or `positionAt` aim's subject) is not in
386
+ * the camera's `commandCentre.targets`, for example one merged away in a dock.
387
+ */
388
+ export class CommandTargetUnknownError extends Error {
389
+ readonly code = ErrorCode.CommandTargetUnknown;
390
+
391
+ constructor(
392
+ readonly flightId: number,
393
+ readonly persistentId: number,
394
+ ) {
395
+ super(`[kerbcast] craft ${persistentId} is not among camera ${flightId}'s targets; aim refused`);
396
+ this.name = "CommandTargetUnknownError";
397
+ }
398
+ }
399
+
400
+ /**
401
+ * The sidecar refused `POST /offer` with a reason, for example
402
+ * `ErrorCode.CodecUnsupported` when the browser offers no H.264 video.
403
+ */
404
+ export class OfferRefusedError extends Error {
405
+ constructor(
406
+ readonly status: number,
407
+ readonly reason: string,
408
+ readonly code?: ErrorCode,
409
+ ) {
410
+ super(`[kerbcast] connection refused: ${reason}`);
411
+ this.name = "OfferRefusedError";
412
+ }
413
+ }
414
+
415
+ /** The craft an aim names: a `vessel` aim's craft, or an `orbit` or `positionAt` aim's subject. */
416
+ function aimCraft(aim: CommandAim): number | undefined {
417
+ const pid =
418
+ aim.kind === CommandAimKind.Vessel
419
+ ? aim.persistentId
420
+ : aim.kind === CommandAimKind.Orbit || aim.kind === CommandAimKind.PositionAt
421
+ ? aim.subjectPersistentId
422
+ : undefined;
423
+ return pid ? pid : undefined;
424
+ }
425
+
383
426
  /** How long {@link KerbcastClient.createCommandCamera} waits for the camera by default. */
384
427
  export const COMMAND_CAMERA_CREATE_TIMEOUT_MS = 35_000;
385
428
 
@@ -1614,7 +1657,14 @@ export class KerbcastClient extends TypedEmitter<KerbcastClientEvents> {
1614
1657
  headers: { "Content-Type": "application/json" },
1615
1658
  body: JSON.stringify(offer),
1616
1659
  });
1617
- if (!res.ok) throw new Error(`POST /offer returned ${res.status}`);
1660
+ if (!res.ok) {
1661
+ /* A refusal carries an ErrorPayload; anything else keeps the bare status. */
1662
+ const refusal = (await res.json().catch(() => null)) as Partial<ErrorPayload> | null;
1663
+ if (typeof refusal?.message === "string") {
1664
+ throw new OfferRefusedError(res.status, refusal.message, refusal.code);
1665
+ }
1666
+ throw new Error(`POST /offer returned ${res.status}`);
1667
+ }
1618
1668
  return (await res.json()) as { sdp: string; cameras: number[] };
1619
1669
  }
1620
1670
 
@@ -1717,12 +1767,24 @@ export class KerbcastClient extends TypedEmitter<KerbcastClientEvents> {
1717
1767
  * (`commandTrack.authority`): it holds the lock and only it can aim. A
1718
1768
  * refusal that races the lock being taken arrives as an `error` event with
1719
1769
  * code `ErrorCode.CommandLocked` instead.
1770
+ *
1771
+ * Rejects with a {@link CommandTargetUnknownError} when the aim's craft is
1772
+ * not in the camera's `commandCentre.targets` (a craft merged away in a
1773
+ * dock, say). A refusal that races the list changing arrives as an `error`
1774
+ * event with code `ErrorCode.CommandTargetUnknown`.
1720
1775
  */
1721
1776
  async setCommandAim(flightId: number, aim: CommandAim | null): Promise<void> {
1722
- const owner = this._cameras.find((c) => c.flightId === flightId)?.commandTrack?.authority?.owner;
1777
+ const cam = this._cameras.find((c) => c.flightId === flightId);
1778
+ const owner = cam?.commandTrack?.authority?.owner;
1723
1779
  if (owner) {
1724
1780
  throw new CommandLockedError(owner);
1725
1781
  }
1782
+ /* An empty list is what the game writes when listing fails, so it decides then. */
1783
+ const craft = aim ? aimCraft(aim) : undefined;
1784
+ const targets = cam?.commandCentre?.targets;
1785
+ if (craft !== undefined && targets?.length && !targets.some((t) => t.persistentId === craft)) {
1786
+ throw new CommandTargetUnknownError(flightId, craft);
1787
+ }
1726
1788
  await this._send({
1727
1789
  type: "set-command-aim",
1728
1790
  content: aim ? { flightId, aim } : { flightId },
package/src/index.ts CHANGED
@@ -9,6 +9,8 @@ export {
9
9
  BrowserKerbcastTransport,
10
10
  COMMAND_CAMERA_CREATE_TIMEOUT_MS,
11
11
  CommandLockedError,
12
+ CommandTargetUnknownError,
13
+ OfferRefusedError,
12
14
  COMMAND_CAMERA_STATE_WAIT_MS,
13
15
  CONTROL_OPEN_TIMEOUT_MS,
14
16
  type CreateCommandCameraOptions,
@@ -683,6 +683,26 @@ export class MockSidecar {
683
683
  });
684
684
  break;
685
685
  }
686
+ const aim = msg.content.aim;
687
+ const craft =
688
+ aim?.kind === CommandAimKind.Vessel
689
+ ? aim.persistentId
690
+ : aim?.kind === CommandAimKind.Orbit || aim?.kind === CommandAimKind.PositionAt
691
+ ? aim.subjectPersistentId
692
+ : undefined;
693
+ const targets = cam.commandCentre.targets;
694
+ if (craft && targets.length > 0 && !targets.some((t) => t.persistentId === craft)) {
695
+ this._sendToClient({
696
+ type: "error",
697
+ content: {
698
+ message: `craft ${craft} is not among camera ${msg.content.flightId}'s targets; aim refused`,
699
+ source: ErrorSource.Sidecar,
700
+ flightId: msg.content.flightId,
701
+ code: ErrorCode.CommandTargetUnknown,
702
+ },
703
+ });
704
+ break;
705
+ }
686
706
  const updated: CameraState = {
687
707
  ...cam,
688
708
  commandCentre: { ...cam.commandCentre, ...aimFields(msg.content.aim ?? null, this._defaultSubject) },
@@ -1,12 +1,16 @@
1
1
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
2
  import {
3
+ CameraKind,
3
4
  CameraLifecycle,
4
5
  CommandAimKind,
6
+ CommandTargetEligibility,
5
7
  CommandVantageKind,
8
+ ErrorCode,
9
+ type ErrorPayload,
6
10
  Layer,
7
11
  TrackMode,
8
12
  } from "./__generated__/types";
9
- import { CommandLockedError, KerbcastClient } from "./index";
13
+ import { CommandLockedError, CommandTargetUnknownError, KerbcastClient } from "./index";
10
14
  import { MockSidecar } from "./testing/index";
11
15
 
12
16
  beforeEach(() => {
@@ -90,6 +94,50 @@ describe("MockSidecar", () => {
90
94
  await client.setCommandAim(pad.flightId, null);
91
95
  });
92
96
 
97
+ it("refuses a command aim at a craft outside the target list", async () => {
98
+ const sidecar = new MockSidecar();
99
+ sidecar.addCamera({
100
+ flightId: 300,
101
+ kind: CameraKind.Command,
102
+ commandCentre: {
103
+ stationId: "ground:LaunchPad",
104
+ nodeName: "LaunchPad",
105
+ displayName: "Launch Pad",
106
+ body: "Kerbin",
107
+ latitude: 0,
108
+ longitude: 0,
109
+ altitude: 0,
110
+ subjectPersistentId: 5,
111
+ trackingLevel: 1,
112
+ targets: [
113
+ {
114
+ persistentId: 5,
115
+ vesselName: "Kerbal X",
116
+ vesselType: "Ship",
117
+ eligibility: CommandTargetEligibility.Ok,
118
+ eligibilityText: "Trackable",
119
+ },
120
+ ],
121
+ },
122
+ });
123
+ const client = new KerbcastClient({ host: "localhost", port: 8088 }, sidecar.createTransport());
124
+ await client.connect([]);
125
+ sidecar.open();
126
+ const errors: ErrorPayload[] = [];
127
+ client.on("error", (e) => errors.push(e));
128
+
129
+ await expect(
130
+ client.setCommandAim(300, { kind: CommandAimKind.Vessel, persistentId: 9 }),
131
+ ).rejects.toBeInstanceOf(CommandTargetUnknownError);
132
+
133
+ /* A client that skips the up-front check still gets the sidecar's refusal. */
134
+ await client._send({
135
+ type: "set-command-aim",
136
+ content: { flightId: 300, aim: { kind: CommandAimKind.Vessel, persistentId: 9 } },
137
+ });
138
+ expect(errors.map((e) => e.code)).toEqual([ErrorCode.CommandTargetUnknown]);
139
+ });
140
+
93
141
  it("client sends hello on open()", async () => {
94
142
  const sidecar = new MockSidecar();
95
143
  sidecar.addCamera({ flightId: 42 });