@raydiculousx/ts-sdk 0.0.0-stage → 1.0.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 (126) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +55 -0
  3. package/NOTICE +14 -0
  4. package/README.md +91 -3
  5. package/dist/THIRD_PARTY_NOTICES.txt +466 -0
  6. package/dist/host/src/bootstrap/client.d.ts +37 -0
  7. package/dist/host/src/bootstrap/client.js +215 -0
  8. package/dist/host/src/bootstrap/host.d.ts +79 -0
  9. package/dist/host/src/bootstrap/host.js +214 -0
  10. package/dist/host/src/bootstrap/protocol.d.ts +20 -0
  11. package/dist/host/src/bootstrap/protocol.js +72 -0
  12. package/dist/host/src/dev.d.ts +30 -0
  13. package/dist/host/src/dev.js +20 -0
  14. package/dist/host/src/entry/app.d.ts +10 -0
  15. package/dist/host/src/entry/app.js +9 -0
  16. package/dist/host/src/entry/auto.d.ts +16 -0
  17. package/dist/host/src/entry/auto.js +18747 -0
  18. package/dist/host/src/standalone/account-api.d.ts +32 -0
  19. package/dist/host/src/standalone/account-api.js +176 -0
  20. package/dist/host/src/standalone/connection-slot.d.ts +12 -0
  21. package/dist/host/src/standalone/connection-slot.js +28 -0
  22. package/dist/host/src/standalone/device-picker.d.ts +6 -0
  23. package/dist/host/src/standalone/device-picker.js +19 -0
  24. package/dist/host/src/standalone/locale.d.ts +4 -0
  25. package/dist/host/src/standalone/locale.js +35 -0
  26. package/dist/host/src/standalone/mount-host.d.ts +155 -0
  27. package/dist/host/src/standalone/mount-host.js +396 -0
  28. package/dist/host/src/standalone/mount-surface.d.ts +12 -0
  29. package/dist/host/src/standalone/mount-surface.js +69 -0
  30. package/dist/host/src/standalone/robot-setup.d.ts +61 -0
  31. package/dist/host/src/standalone/robot-setup.js +160 -0
  32. package/dist/lib/client/action-ownership.d.ts +31 -0
  33. package/dist/lib/client/action-ownership.js +182 -0
  34. package/dist/lib/client/direct.d.ts +149 -0
  35. package/dist/lib/client/direct.js +560 -0
  36. package/dist/lib/client/raydiculousx.d.ts +541 -0
  37. package/dist/lib/client/raydiculousx.js +694 -0
  38. package/dist/lib/client/runtime.d.ts +165 -0
  39. package/dist/lib/client/runtime.js +1 -0
  40. package/dist/lib/core/index.d.ts +16 -0
  41. package/dist/lib/core/index.js +9 -0
  42. package/dist/lib/core/rpc/command-channel.d.ts +345 -0
  43. package/dist/lib/core/rpc/command-channel.js +697 -0
  44. package/dist/lib/core/rpc/commands.d.ts +354 -0
  45. package/dist/lib/core/rpc/commands.js +134 -0
  46. package/dist/lib/core/rpc/request-policy.d.ts +29 -0
  47. package/dist/lib/core/rpc/request-policy.js +35 -0
  48. package/dist/lib/core/rpc/robot-api.d.ts +184 -0
  49. package/dist/lib/core/rpc/robot-api.js +34 -0
  50. package/dist/lib/core/signaling/ice-servers.d.ts +10 -0
  51. package/dist/lib/core/signaling/ice-servers.js +58 -0
  52. package/dist/lib/core/signaling/peer-negotiator.d.ts +164 -0
  53. package/dist/lib/core/signaling/peer-negotiator.js +366 -0
  54. package/dist/lib/core/signaling/signaling-client.d.ts +204 -0
  55. package/dist/lib/core/signaling/signaling-client.js +473 -0
  56. package/dist/lib/core/signaling/signaling-contract.d.ts +164 -0
  57. package/dist/lib/core/signaling/signaling-contract.js +35 -0
  58. package/dist/lib/core/signaling/signaling.d.ts +172 -0
  59. package/dist/lib/core/signaling/signaling.js +381 -0
  60. package/dist/lib/media/attach-video.d.ts +3 -0
  61. package/dist/lib/media/attach-video.js +243 -0
  62. package/dist/lib/media/direct-audio.d.ts +36 -0
  63. package/dist/lib/media/direct-audio.js +94 -0
  64. package/dist/lib/media/index.d.ts +5 -0
  65. package/dist/lib/media/index.js +3 -0
  66. package/dist/lib/media/pcm-types.d.ts +33 -0
  67. package/dist/lib/media/pcm-types.js +1 -0
  68. package/dist/lib/media/robot-audio.d.ts +64 -0
  69. package/dist/lib/media/robot-audio.js +82 -0
  70. package/dist/lib/media/robot-pcm-output.d.ts +16 -0
  71. package/dist/lib/media/robot-pcm-output.js +101 -0
  72. package/dist/lib/robot/action-upload.d.ts +32 -0
  73. package/dist/lib/robot/action-upload.js +143 -0
  74. package/dist/lib/robot/robot-commands.d.ts +148 -0
  75. package/dist/lib/robot/robot-commands.js +164 -0
  76. package/dist/lib/robot/robot-responses.d.ts +42 -0
  77. package/dist/lib/robot/robot-responses.js +226 -0
  78. package/dist/lib/robot/robot-tof.d.ts +61 -0
  79. package/dist/lib/robot/robot-tof.js +25 -0
  80. package/dist/lib/robot/robot-types.d.ts +293 -0
  81. package/dist/lib/robot/robot-types.js +17 -0
  82. package/dist/lib/shared/errors.d.ts +57 -0
  83. package/dist/lib/shared/errors.js +45 -0
  84. package/dist/lib/shared/events.d.ts +11 -0
  85. package/dist/lib/shared/events.js +40 -0
  86. package/dist/lib/shared/types.d.ts +26 -0
  87. package/dist/lib/shared/types.js +1 -0
  88. package/dist/lib/shared/validation.d.ts +29 -0
  89. package/dist/lib/shared/validation.js +87 -0
  90. package/dist/lib/version.d.ts +2 -0
  91. package/dist/lib/version.js +3 -0
  92. package/dist/raydiculousx-sdk.d.ts +26 -0
  93. package/dist/raydiculousx-sdk.js +17 -0
  94. package/docs/API.md +1106 -0
  95. package/docs/DIRECT_APPS.md +83 -0
  96. package/docs/HOST_HANDOFF.md +59 -0
  97. package/docs/HOST_PROTOCOL.md +43 -0
  98. package/docs/RELEASING.md +33 -0
  99. package/docs/assets/raydiculousx-mark.png +0 -0
  100. package/examples/README.md +10 -0
  101. package/examples/application-template/README.md +60 -0
  102. package/examples/application-template/index.html +12 -0
  103. package/examples/application-template/package.json +21 -0
  104. package/examples/application-template/src/app.config.ts +8 -0
  105. package/examples/application-template/src/app.ts +81 -0
  106. package/examples/application-template/src/dispatch.ts +29 -0
  107. package/examples/application-template/src/embed.ts +39 -0
  108. package/examples/application-template/src/env.d.ts +10 -0
  109. package/examples/application-template/src/host-origin.ts +9 -0
  110. package/examples/application-template/src/locale.ts +90 -0
  111. package/examples/application-template/src/styles.css +31 -0
  112. package/examples/application-template/tsconfig.json +24 -0
  113. package/examples/application-template/vite.config.mjs +16 -0
  114. package/examples/sdk-diagnostics/README.md +199 -0
  115. package/examples/sdk-diagnostics/assets/THIRD_PARTY_NOTICES.txt +567 -0
  116. package/examples/sdk-diagnostics/assets/auto-CnsixhmH.js +9 -0
  117. package/examples/sdk-diagnostics/assets/console-BjvPHSNK.css +1 -0
  118. package/examples/sdk-diagnostics/assets/console-BrwFsb65.js +9 -0
  119. package/examples/sdk-diagnostics/assets/favicon-BZQEit-G.ico +0 -0
  120. package/examples/sdk-diagnostics/assets/index-DXSJUMrS.js +2 -0
  121. package/examples/sdk-diagnostics/assets/messages-C1UCo5nT.js +1 -0
  122. package/examples/sdk-diagnostics/assets/robot-x3-D4wBvBN8.webp +0 -0
  123. package/examples/sdk-diagnostics/assets/styles-D3TrErcf.css +1 -0
  124. package/examples/sdk-diagnostics/index.html +15 -0
  125. package/host/README.md +34 -0
  126. package/package.json +80 -4
@@ -0,0 +1,172 @@
1
+ /**
2
+ * 共享信令与 WebRTC 协商入口,由 @raydiculousx/ts-sdk/core 导出。
3
+ * 管理信令连接、设备发现和单个协商器;业务命令和音频由连接持有者使用交出的句柄发送。
4
+ */
5
+ import { type ConnectionStatus } from './signaling-client.ts';
6
+ import { type AuthOkPayload, type DeviceInfo, type DownFrame, type EstablishedConnection, type SendFrameParams } from './signaling-contract.ts';
7
+ /** WebRTC 协商阶段,独立于信令连接状态和设备执行器状态。 */
8
+ export type NegotiationPhase = 'idle' | 'offering' | 'answering' | 'connected' | 'failed';
9
+ /** 信令模块的当前状态;设备在线不代表执行器已就绪。 */
10
+ export interface SignalingState {
11
+ /** WSS 通道状态 */
12
+ ws: ConnectionStatus;
13
+ /** 是否已收到 auth.ok */
14
+ authed: boolean;
15
+ /** 当前身份 */
16
+ role: 'user' | 'device' | null;
17
+ /** 协商阶段 */
18
+ phase: NegotiationPhase;
19
+ /** 当前协商的目标设备 */
20
+ sn: string | null;
21
+ /** 设备列表(用户侧) */
22
+ devices: DeviceInfo[];
23
+ /** ICE 连接状态,供调试 */
24
+ iceState: RTCIceConnectionState | null;
25
+ /** 最近一次错误,消费后可 clearError() */
26
+ error: string | null;
27
+ }
28
+ /** 信令模块发布的错误分类,不包含认证凭据。 */
29
+ export interface SignalingError {
30
+ /** 错误来源:信令连接、WebRTC 协商或服务端协议。 */
31
+ kind: 'ws' | 'negotiation' | 'server';
32
+ /** 服务端可用时提供的错误码;本地错误可省略。 */
33
+ code?: string;
34
+ /** 面向调用方的说明。 */
35
+ message: string;
36
+ }
37
+ /** 创建共享信令模块的配置;构造模块本身不建立网络连接。 */
38
+ export interface SignalingOptions {
39
+ /**
40
+ * 信令地址。
41
+ *
42
+ * 走网关:ws(s)://<网关>/campus-websocket/ws
43
+ * 直连 :ws://<内网IP>:8082/ws
44
+ */
45
+ url: string;
46
+ /**
47
+ * 平台提供的信令登录凭据,客户端将其放入 WebSocket query 的 jti 参数。
48
+ * 本模块不解析凭据,不应将其写入日志、页面 URL 或公开业务状态。
49
+ */
50
+ jti: string;
51
+ /** 是否自动恢复信令连接;默认 true,不会自动重放设备动作或重新协商。 */
52
+ autoReconnect?: boolean;
53
+ /** 设备侧才需要;用户侧不传 */
54
+ sn?: string;
55
+ /**
56
+ * ICE 服务器列表;省略时使用 DEFAULT_ICE_SERVERS,当前默认仅配置 STUN。
57
+ * 显式空数组表示不配置外部 ICE 服务器;列表不会由信令回执自动补充。
58
+ */
59
+ iceServers?: RTCIceServer[];
60
+ /**
61
+ * 是否由浏览器连接所有者创建 control、telemetry 和可选上传通道 blob,默认 true。
62
+ *
63
+ * 依据 webrtc-control.md §2.2:WebRTC 要求 offer 侧先有 m=application,
64
+ * answer 方不能为当前 offer 新增媒体行,创建通道应在生成 offer 前完成。
65
+ */
66
+ createChannels?: boolean;
67
+ /** 首次 offer 的媒体选项;此入口默认预留音频发送端,实际媒体方向由 answer 确定。 */
68
+ media?: {
69
+ /** 是否请求接收远端视频,默认 false;不会请求本机摄像头。 */
70
+ receiveVideo?: boolean;
71
+ /** 是否请求接收远端音频,默认 false;不会请求本机麦克风。 */
72
+ receiveAudio?: boolean;
73
+ /** 是否添加静音占位音轨,默认 true,以便之后复用发送端替换真实音轨。 */
74
+ addSilentAudio?: boolean;
75
+ };
76
+ }
77
+ /** 状态、设备发现与 WebRTC 协商接口;不负责发送机器人业务命令。 */
78
+ export interface SignalingModule {
79
+ /**
80
+ * 建立信令连接并等待鉴权。
81
+ * @returns 收到 auth.ok 后解析为 {@link AuthOkPayload}。
82
+ * @throws 已有连接、握手失败或主动关闭时拒绝 Promise。
83
+ * @remarks 本层没有鉴权等待超时或 AbortSignal,可用 disconnectSignaling 结束等待。自动重连只恢复信令,机器人连接需重新协商。
84
+ */
85
+ connectSignaling(): Promise<AuthOkPayload>;
86
+ /**
87
+ * 关闭 WebRTC 并主动关闭信令。
88
+ * @returns 浏览器确认关闭 WebSocket 后完成,最长等待 3000 ms。
89
+ * @throws 等待关闭超时或浏览器关闭失败时拒绝 Promise。
90
+ * @remarks 停止自动重连,调用方可在关闭前单独协调停车。
91
+ */
92
+ disconnectSignaling(): Promise<void>;
93
+ /**
94
+ * 单向提交自定义信令帧。
95
+ * @param type - 上行信令消息类型。
96
+ * @param frame - 关联标识、目标序列号及载荷,见 {@link SendFrameParams}。
97
+ * @returns 交给 WebSocket 时返回 true,未连接时返回 false。
98
+ * @throws 序列化失败、超出帧大小限制或浏览器发送失败时同步抛出,见 {@link SignalingClient.sendFrame}。
99
+ */
100
+ sendFrame(type: string, frame: SendFrameParams): boolean;
101
+ /**
102
+ * 按帧类型订阅完整下行信令帧。
103
+ * @param type - 要订阅的下行帧类型。
104
+ * @param handler - 接收 {@link DownFrame} 的回调。
105
+ * @returns 可重复调用的退订函数。
106
+ * @remarks 历史帧不回放,见 {@link SignalingClient.onFrame}。
107
+ */
108
+ onFrame(type: string, handler: (frame: DownFrame) => void): () => void;
109
+ /**
110
+ * 查询并更新当前用户可见的设备列表。
111
+ * @returns 服务端返回的本次列表,最长等待 10000 ms。
112
+ * @throws 未连接、服务端错误或超时时拒绝 Promise。
113
+ */
114
+ listDevices(): Promise<DeviceInfo[]>;
115
+ /**
116
+ * 为目标设备启动 WebRTC 协商。
117
+ * @param sn - 目标设备序列号。
118
+ * @param iceServers - 本次协商使用的 STUN/TURN 列表,省略时使用模块配置。
119
+ * @returns 生成 offer 并尝试发送后完成;已连接同一设备或本轮被替换时可直接完成。
120
+ * @throws 浏览器创建协商器、生成 offer 或 WebSocket 发送失败时拒绝 Promise。
121
+ * @remarks 切换目标会先关闭旧协商器。通过 onEstablished 确认建立连接,此 Promise 不等待 answer 或 ICE 完成。
122
+ */
123
+ negotiate(sn: string, iceServers?: RTCIceServer[]): Promise<void>;
124
+ /** 结束当前协商并释放 WebRTC,保留信令连接;不发送停车请求,不等待远端确认。 */
125
+ stopNegotiation(): void;
126
+ /**
127
+ * 读取当前信令和协商状态。
128
+ * @returns 状态对象和 devices 数组的浅副本;其中的设备项仍为共享引用,调用方应按只读使用。
129
+ */
130
+ getState(): SignalingState;
131
+ /**
132
+ * 订阅信令模块状态。
133
+ * @param fn - 接收状态快照的回调,注册时立即同步调用一次。
134
+ * @returns 可重复调用的退订函数。
135
+ * @throws 首次回调同步抛错时透传异常。
136
+ * @remarks 后续发布时,同步异常会被记录和隔离,异步拒绝由回调自行处理。
137
+ */
138
+ subscribe(fn: (state: SignalingState) => void): () => void;
139
+ /**
140
+ * 订阅已建立的机器人连接。
141
+ * @param fn - WebRTC connected 且 control 和 telemetry 均为 open 时接收连接句柄的回调。
142
+ * @returns 可重复调用的退订函数。
143
+ * @remarks 不回放已有连接,模块仍管理句柄的关闭和信令生命周期。
144
+ */
145
+ onEstablished(fn: (conn: EstablishedConnection) => void): () => void;
146
+ /**
147
+ * 订阅协商结束或连接断开的通知。
148
+ * @param fn - 接收协商失败、连接断开或主动停止原因的回调。
149
+ * @returns 可重复调用的退订函数。
150
+ * @remarks 历史通知不回放。
151
+ */
152
+ onEnded(fn: (reason: string) => void): () => void;
153
+ /**
154
+ * 订阅信令或协商错误。
155
+ * @param fn - 接收 {@link SignalingError} 的回调。
156
+ * @returns 可重复调用的退订函数。
157
+ * @remarks 历史错误不回放,业务请求的重试由调用方管理。
158
+ */
159
+ onError(fn: (err: SignalingError) => void): () => void;
160
+ /** 清除最近错误说明并发布状态;不修复连接或清除设备故障。 */
161
+ clearError(): void;
162
+ }
163
+ /**
164
+ * 创建信令与 WebRTC 协商模块。
165
+ * @param opts - 信令、鉴权及 WebRTC 配置,见 {@link SignalingOptions}。
166
+ * @returns 未连接的 {@link SignalingModule} 句柄。
167
+ * @remarks 调用 connectSignaling 才会建立 WebSocket,调用 negotiate 才会创建 WebRTC。
168
+ */
169
+ export declare function createSignaling(opts: SignalingOptions): SignalingModule;
170
+ export type { AuthOkPayload, DeviceInfo, DeviceStatusPayload, ErrorCode, EstablishedConnection, IcePayload, PeerIdentity, SdpPayload, } from './signaling-contract.ts';
171
+ export { DEFAULT_ICE_SERVERS, ERROR_HINTS } from './signaling-contract.ts';
172
+ export type { ConnectionStatus } from './signaling-client.ts';
@@ -0,0 +1,381 @@
1
+ /**
2
+ * 共享信令与 WebRTC 协商入口,由 @raydiculousx/ts-sdk/core 导出。
3
+ * 管理信令连接、设备发现和单个协商器;业务命令和音频由连接持有者使用交出的句柄发送。
4
+ */
5
+ import { SignalingClient } from "./signaling-client.js";
6
+ import { PeerNegotiator } from "./peer-negotiator.js";
7
+ import { DEFAULT_ICE_SERVERS, } from "./signaling-contract.js";
8
+ /* ───────────────────────────── 实现 ───────────────────────────── */
9
+ /**
10
+ * 创建信令与 WebRTC 协商模块。
11
+ * @param opts - 信令、鉴权及 WebRTC 配置,见 {@link SignalingOptions}。
12
+ * @returns 未连接的 {@link SignalingModule} 句柄。
13
+ * @remarks 调用 connectSignaling 才会建立 WebSocket,调用 negotiate 才会创建 WebRTC。
14
+ */
15
+ export function createSignaling(opts) {
16
+ const client = new SignalingClient({
17
+ url: opts.url,
18
+ jti: opts.jti,
19
+ ...(opts.sn === undefined ? {} : { sn: opts.sn }),
20
+ ...(opts.autoReconnect === undefined ? {} : { autoReconnect: opts.autoReconnect }),
21
+ });
22
+ const state = {
23
+ ws: 'idle',
24
+ authed: false,
25
+ role: null,
26
+ phase: 'idle',
27
+ sn: null,
28
+ devices: [],
29
+ iceState: null,
30
+ error: null,
31
+ };
32
+ const stateListeners = new Set();
33
+ const establishedListeners = new Set();
34
+ const endedListeners = new Set();
35
+ const errorListeners = new Set();
36
+ let negotiator = null;
37
+ const iceServers = opts.iceServers ?? DEFAULT_ICE_SERVERS;
38
+ const notify = () => {
39
+ const snap = { ...state, devices: [...state.devices] };
40
+ for (const fn of stateListeners) {
41
+ try {
42
+ fn(snap);
43
+ }
44
+ catch (err) {
45
+ console.error('[signaling] state listener threw', err);
46
+ }
47
+ }
48
+ };
49
+ const emitError = (e) => {
50
+ state.error = e.message;
51
+ notify();
52
+ for (const fn of errorListeners) {
53
+ try {
54
+ fn(e);
55
+ }
56
+ catch (err) {
57
+ console.error('[signaling] error listener threw', err);
58
+ }
59
+ }
60
+ };
61
+ /**
62
+ * 释放当前协商者。
63
+ *
64
+ * 抽成函数是因为「关闭旧连接」出现在 4 个地方
65
+ * (切换设备、协商失败、WS 断开、用户主动停止),
66
+ * 每处都写一遍 close + 置 null 容易漏。
67
+ */
68
+ const disposeNegotiator = () => {
69
+ negotiator?.close();
70
+ negotiator = null;
71
+ };
72
+ const emitEnded = (reason) => {
73
+ state.phase = 'idle';
74
+ state.sn = null;
75
+ state.iceState = null;
76
+ notify();
77
+ for (const fn of endedListeners) {
78
+ try {
79
+ fn(reason);
80
+ }
81
+ catch (err) {
82
+ console.error('[signaling] ended listener threw', err);
83
+ }
84
+ }
85
+ };
86
+ /* ── WSS 事件 ── */
87
+ client.on('close', (e) => {
88
+ state.ws = client.getStatus();
89
+ state.authed = false;
90
+ // 断线后协商一律作废(后端无会话恢复)
91
+ if (state.phase === 'offering' || state.phase === 'answering' || state.phase === 'connected') {
92
+ disposeNegotiator();
93
+ emitEnded(e.willRetry ? 'signaling_reconnecting' : 'signaling_closed');
94
+ }
95
+ else {
96
+ notify();
97
+ }
98
+ if (!e.willRetry && !e.reason.includes('client closed')) {
99
+ emitError({ kind: 'ws', code: String(e.code), message: '信令连接已关闭' });
100
+ }
101
+ });
102
+ client.on('authOk', (p) => {
103
+ state.authed = true;
104
+ state.role = p.role;
105
+ state.ws = 'open';
106
+ notify();
107
+ });
108
+ client.on('deviceStatus', (p) => {
109
+ const idx = state.devices.findIndex((d) => d.sn === p.sn);
110
+ if (idx >= 0) {
111
+ const next = [...state.devices];
112
+ next[idx] = { ...next[idx], online: p.online, name: p.name };
113
+ state.devices = next;
114
+ }
115
+ else if (p.online) {
116
+ // 新上线的设备,列表里没有则补一条
117
+ state.devices = [
118
+ ...state.devices,
119
+ { sn: p.sn, name: p.name, online: true, connectedAt: new Date().toISOString() },
120
+ ];
121
+ }
122
+ notify();
123
+ });
124
+ /**
125
+ * 判断一条信令消息是否来自当前协商目标。
126
+ *
127
+ * ★ 这是多设备下最关键的一处校验。
128
+ *
129
+ * 切换设备时,旧设备的 answer / ICE 可能在网络上在途,
130
+ * 比新起一轮协商晚到。之前只判 `negotiator` 非空就应用,
131
+ * 结果旧设备的 SDP 被塞给新连接的 PeerConnection:
132
+ * 轻则协商失败,重则连上一台「看似成功但无画面」的会话。
133
+ *
134
+ * 判据用 ev.from.sn 与当前 state.sn 比对(都用不了时放行,
135
+ * 保持与单设备旧行为兼容)。
136
+ */
137
+ /** 从对端身份里取设备序列号;user 身份没有这个字段 */
138
+ const senderSn = (from) => from?.type === 'device' ? from.sn : undefined;
139
+ const isFromCurrentTarget = (ev) => {
140
+ const fromSn = senderSn(ev.from);
141
+ // 服务端没带来源信息:无法判断,按旧行为放行
142
+ if (!fromSn)
143
+ return true;
144
+ return fromSn === state.sn;
145
+ };
146
+ client.on('answer', (ev) => {
147
+ if (!negotiator)
148
+ return;
149
+ if (!isFromCurrentTarget(ev)) {
150
+ // 旧设备的迟到 answer,丢弃即可 —— 不是错误,不该报给用户
151
+ console.debug('[signaling] 忽略非当前设备的 answer', senderSn(ev.from), '!=', state.sn);
152
+ return;
153
+ }
154
+ const sp = ev.payload;
155
+ const fromName = ev.from && ev.from.type === 'device' ? ev.from.name : undefined;
156
+ void negotiator
157
+ .applyAnswer({ type: 'answer', sdp: sp.sdp }, fromName)
158
+ .catch((err) => {
159
+ console.error('[signaling] 应用 answer 失败', err);
160
+ emitError({ kind: 'negotiation', message: '应用 SDP answer 失败' });
161
+ });
162
+ });
163
+ client.on('ice', (ev) => {
164
+ if (!negotiator)
165
+ return;
166
+ if (!isFromCurrentTarget(ev)) {
167
+ console.debug('[signaling] 忽略非当前设备的 ICE', senderSn(ev.from), '!=', state.sn);
168
+ return;
169
+ }
170
+ const ip = ev.payload;
171
+ void negotiator.addIceCandidate({
172
+ candidate: ip.candidate,
173
+ sdpMid: ip.sdpMid,
174
+ sdpMLineIndex: ip.sdpMLineIndex,
175
+ });
176
+ });
177
+ client.on('error', (p) => {
178
+ // duplicate_login 等需要上层感知
179
+ emitError({ kind: 'server', code: p.code, message: p.message });
180
+ });
181
+ /* ── 公开方法 ── */
182
+ return {
183
+ async connectSignaling() {
184
+ state.ws = 'connecting';
185
+ notify();
186
+ try {
187
+ const auth = await client.connectSignaling();
188
+ notify();
189
+ return auth;
190
+ }
191
+ catch (err) {
192
+ state.ws = client.getStatus();
193
+ const msg = err instanceof Error ? err.message : String(err);
194
+ emitError({ kind: 'ws', message: msg });
195
+ throw err;
196
+ }
197
+ },
198
+ disconnectSignaling() {
199
+ negotiator?.close();
200
+ negotiator = null;
201
+ const closed = client.close();
202
+ state.ws = 'closed';
203
+ state.authed = false;
204
+ state.phase = 'idle';
205
+ state.sn = null;
206
+ notify();
207
+ return closed;
208
+ },
209
+ sendFrame(type, frame) {
210
+ return client.sendFrame(type, frame);
211
+ },
212
+ onFrame(type, handler) {
213
+ return client.onFrame(type, handler);
214
+ },
215
+ async listDevices() {
216
+ try {
217
+ const res = await client.listDevices();
218
+ state.devices = res.devices;
219
+ notify();
220
+ return res.devices;
221
+ }
222
+ catch (err) {
223
+ const msg = err instanceof Error ? err.message : String(err);
224
+ emitError({ kind: 'server', message: msg });
225
+ throw err;
226
+ }
227
+ },
228
+ async negotiate(sn, sessionIceServers) {
229
+ /*
230
+ * 多设备场景:单连接 + 支持切换。
231
+ *
232
+ * 本模块的结构决定了同时只能有一路协商:
233
+ * · `negotiator` 是单个变量
234
+ * · `state.sn` 只能记一个目标
235
+ * · `conn` 只有一个(control/telemetry 通道各一份)
236
+ *
237
+ * 与其在「已有连接时抛错」把切换成本转嫁给用户(要手动断开再连),
238
+ * 不如在这里把「切换」做成一等操作:先彻底释放旧的,再连新的。
239
+ *
240
+ * 关键:必须同步完成清理再往下走。
241
+ * 若只是发起 stopNegotiation() 而不等状态归位,
242
+ * 旧 negotiator 的 answer/ICE 回调仍可能落到新连接上,
243
+ * 表现为「切换后协商一直失败」。
244
+ */
245
+ const switching = state.phase !== 'idle' || negotiator !== null;
246
+ if (switching) {
247
+ // 同一台重复点击视为无操作,避免无谓的断开重连
248
+ if (state.phase === 'connected' && state.sn === sn) {
249
+ return;
250
+ }
251
+ disposeNegotiator();
252
+ /*
253
+ * 通知订阅者「旧连接已结束」,但不走 emitEnded ——
254
+ * 那会把 phase 置回 idle 并触发一次状态广播,
255
+ * 紧接着的 offering 又广播一次,UI 会闪一下「未连接」。
256
+ * 这里只清掉与旧连接绑定的字段。
257
+ */
258
+ state.phase = 'idle';
259
+ state.sn = null;
260
+ state.iceState = null;
261
+ notify();
262
+ }
263
+ state.sn = sn;
264
+ state.phase = 'offering';
265
+ notify();
266
+ /**
267
+ * addSilentAudio 默认开启。
268
+ *
269
+ * 机器人要收到 App 播放的音频,SDP 里必须先存在一条 audio transceiver;
270
+ * 它由本端 offer 建立,之后再通过 sender.replaceTrack() 换成真实音轨。
271
+ * 若这里不开,getTransceivers() 找不到音频条目,
272
+ * RobotAudio.setOutgoingAudioTrack() 会直接返回 false,声音永远发不出去。
273
+ *
274
+ * 「静音」只是初始内容(振荡器增益为 0、track.enabled=false),
275
+ * 不承载业务音频;浏览器仍可能发送静音 RTP,因此不能据此判断网络没有音频流量。
276
+ */
277
+ const neg = new PeerNegotiator({
278
+ sn,
279
+ iceServers: sessionIceServers ?? iceServers,
280
+ createChannels: opts.createChannels ?? true,
281
+ media: { ...opts.media, addSilentAudio: opts.media?.addSilentAudio ?? true },
282
+ });
283
+ negotiator = neg;
284
+ neg.on('iceCandidate', (c) => {
285
+ client.sendIce(sn, c);
286
+ });
287
+ neg.on('iceState', (s) => {
288
+ state.iceState = s;
289
+ notify();
290
+ });
291
+ neg.on('established', (conn) => {
292
+ /*
293
+ * 被替换掉的旧实例不该再宣告建立。
294
+ * 否则 UI 会先显示「已连接旧设备」再被新结果覆盖,出现闪跳。
295
+ */
296
+ if (negotiator !== neg) {
297
+ conn.pc.close();
298
+ return;
299
+ }
300
+ state.phase = 'connected';
301
+ notify();
302
+ for (const fn of establishedListeners) {
303
+ try {
304
+ fn(conn);
305
+ }
306
+ catch (err) {
307
+ console.error('[signaling] established listener threw', err);
308
+ }
309
+ }
310
+ });
311
+ neg.on('failed', ({ reason }) => {
312
+ /*
313
+ * 必须是「当前」这个 negotiator 才允许清理状态。
314
+ *
315
+ * 切换设备时旧实例被 close 后会异步抛出 failed,
316
+ * 那时 negotiator 已经指向新实例。若不做这个判断,
317
+ * 旧实例的迟到失败会把新连接一起打回 idle ——
318
+ * 表现是「切到第二台,刚点就连不上」。
319
+ */
320
+ if (negotiator !== neg)
321
+ return;
322
+ emitError({ kind: 'negotiation', message: `WebRTC 协商失败:${reason}` });
323
+ disposeNegotiator();
324
+ emitEnded(reason);
325
+ });
326
+ try {
327
+ const offer = await neg.createOffer();
328
+ /*
329
+ * createOffer 是异步的,期间用户可能已经切到别的设备。
330
+ * 此时继续发送 offer 会把旧目标带回服务端,与新连接交叉。
331
+ * 直接静默放弃这一轮即可 —— 新的一轮已经自己接管了。
332
+ */
333
+ if (negotiator !== neg)
334
+ return;
335
+ client.sendOffer(sn, offer.sdp ?? '', 'offer');
336
+ state.phase = 'answering';
337
+ notify();
338
+ }
339
+ catch (err) {
340
+ // 同理:已被替换掉的实例失败,不该影响当前连接
341
+ if (negotiator !== neg)
342
+ return;
343
+ disposeNegotiator();
344
+ const msg = err instanceof Error ? err.message : String(err);
345
+ emitError({ kind: 'negotiation', message: msg });
346
+ emitEnded('offer_failed');
347
+ throw err;
348
+ }
349
+ },
350
+ stopNegotiation() {
351
+ disposeNegotiator();
352
+ if (state.phase !== 'idle')
353
+ emitEnded('user');
354
+ },
355
+ getState() {
356
+ return { ...state, devices: [...state.devices] };
357
+ },
358
+ subscribe(fn) {
359
+ stateListeners.add(fn);
360
+ fn({ ...state, devices: [...state.devices] });
361
+ return () => stateListeners.delete(fn);
362
+ },
363
+ onEstablished(fn) {
364
+ establishedListeners.add(fn);
365
+ return () => establishedListeners.delete(fn);
366
+ },
367
+ onEnded(fn) {
368
+ endedListeners.add(fn);
369
+ return () => endedListeners.delete(fn);
370
+ },
371
+ onError(fn) {
372
+ errorListeners.add(fn);
373
+ return () => errorListeners.delete(fn);
374
+ },
375
+ clearError() {
376
+ state.error = null;
377
+ notify();
378
+ },
379
+ };
380
+ }
381
+ export { DEFAULT_ICE_SERVERS, ERROR_HINTS } from "./signaling-contract.js";
@@ -0,0 +1,3 @@
1
+ import type { SignalingModule } from '../core/signaling/signaling.ts';
2
+ /** 为当前页面挂载中枢视频;页面可见时自动恢复断流,卸载时取消协商和重试。 */
3
+ export declare function attachHubVideo(element: HTMLVideoElement, signaling: SignalingModule, sn: string, iceServers: RTCIceServer[], onClosed: () => void): () => void;