@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,473 @@
1
+ /**
2
+ * 信令客户端,与平台信令服务交换发现、SDP 和 ICE 消息。
3
+ *
4
+ * 边界:
5
+ * - 只管 WSS 收发、requestId 配对、心跳、重连
6
+ * - 不碰 WebRTC,不碰 DOM
7
+ */
8
+ import { HEARTBEAT_INTERVAL_MS, MAX_FRAME_BYTES, } from "./signaling-contract.js";
9
+ /* ─────────────────────────── 工具 ─────────────────────────── */
10
+ let reqCounter = 0;
11
+ function newRequestId(prefix = 'r') {
12
+ if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
13
+ return crypto.randomUUID();
14
+ }
15
+ return `${prefix}-${Date.now()}-${++reqCounter}`;
16
+ }
17
+ function withJitter(ms, ratio = 0.25) {
18
+ const delta = ms * ratio;
19
+ return Math.round(ms - delta + Math.random() * delta * 2);
20
+ }
21
+ /* ───────────────────────────── 主体 ───────────────────────────── */
22
+ /**
23
+ * 管理一个 WebSocket 的信令收发、请求关联、30 秒心跳及可选重连。
24
+ * @remarks 自动重连按 1/2/4/8/16/30 秒基准延迟并加入 ±25% 抖动;不负责机器人业务命令。
25
+ */
26
+ export class SignalingClient {
27
+ ws = null;
28
+ opts;
29
+ handlers = new Map();
30
+ frameHandlers = new Map();
31
+ status = 'idle';
32
+ attempt = 0;
33
+ heartbeatTimer = null;
34
+ reconnectTimer = null;
35
+ manualClose = false;
36
+ closing = null;
37
+ cancelConnect = null;
38
+ /** requestId → 等待回执 */
39
+ pending = new Map();
40
+ /** requestId → 期望的回执 type,用于区分同名回执 */
41
+ expectType = new Map();
42
+ /**
43
+ * 保存信令连接配置。
44
+ * @param options - 地址、认证信息及自动重连选项,见 {@link SignalingOptions}。
45
+ * @remarks 默认启用自动重连。调用 connectSignaling 时才会创建 WebSocket。
46
+ */
47
+ constructor(options) {
48
+ this.opts = {
49
+ autoReconnect: true,
50
+ ...options,
51
+ };
52
+ }
53
+ /* ───────────── 事件订阅 ───────────── */
54
+ /**
55
+ * 订阅信令客户端事件。
56
+ * @param key - 要订阅的事件,见 {@link SignalingEvents}。
57
+ * @param handler - 接收该事件载荷的回调。
58
+ * @returns 可重复调用的退订函数。
59
+ * @remarks 同步回调异常会被隔离,异步拒绝由回调自行处理。
60
+ */
61
+ on(key, handler) {
62
+ let set = this.handlers.get(key);
63
+ if (!set) {
64
+ set = new Set();
65
+ this.handlers.set(key, set);
66
+ }
67
+ const h = handler;
68
+ set.add(h);
69
+ return () => {
70
+ set.delete(h);
71
+ };
72
+ }
73
+ /**
74
+ * 按消息类型订阅完整下行帧。
75
+ * @param type - 要匹配的下行帧类型。
76
+ * @param handler - 同步接收 {@link DownFrame} 的回调。
77
+ * @returns 可重复调用的退订函数。
78
+ * @remarks 历史帧不回放,单个回调的同步异常会被隔离。
79
+ */
80
+ onFrame(type, handler) {
81
+ const listeners = this.frameHandlers.get(type) ?? new Set();
82
+ this.frameHandlers.set(type, listeners);
83
+ const listener = (frame) => handler(frame);
84
+ listeners.add(listener);
85
+ return () => {
86
+ if (listeners.delete(listener) && listeners.size === 0)
87
+ this.frameHandlers.delete(type);
88
+ };
89
+ }
90
+ emit(key, payload) {
91
+ const set = this.handlers.get(key);
92
+ if (!set)
93
+ return;
94
+ for (const h of set) {
95
+ try {
96
+ h(payload);
97
+ }
98
+ catch (err) {
99
+ console.error(`[signaling] handler for "${key}" threw`, err);
100
+ }
101
+ }
102
+ }
103
+ /**
104
+ * 读取当前 WebSocket 状态。
105
+ * @returns 当前状态,见 {@link ConnectionStatus};open 只表示 socket 已打开,鉴权状态需另行确认。
106
+ */
107
+ getStatus() {
108
+ return this.status;
109
+ }
110
+ /* ───────────── 连接 ───────────── */
111
+ /**
112
+ * 建立并认证信令连接。
113
+ * @returns 收到 auth.ok 后解析为 {@link AuthOkPayload}。
114
+ * @throws URL 构造失败时同步抛出;已有连接、正在关闭、浏览器无法创建 WebSocket 或握手未完成便关闭时拒绝 Promise。
115
+ * @remarks 本方法没有鉴权等待超时或 AbortSignal。可调用 {@link SignalingClient.close} 结束等待。
116
+ * 关闭码 1008、4001、4003 被视为鉴权失败且不自动重连,其他非主动关闭按配置处理。
117
+ */
118
+ connectSignaling() {
119
+ if (this.closing || (this.ws && this.ws.readyState !== WebSocket.CLOSED)) {
120
+ return Promise.reject(new Error('[signaling] 连接已存在或正在建立'));
121
+ }
122
+ this.manualClose = false;
123
+ this.status = this.attempt === 0 ? 'connecting' : 'reconnecting';
124
+ /*
125
+ * 凭据放 query 的 jti 参数。
126
+ *
127
+ * 浏览器无法为 WebSocket 设置请求头,只能走 query。
128
+ * 服务端按 jti → token → access_token 的顺序取,
129
+ * 用 jti 是推荐写法(与网关、oauth 保持一致)。
130
+ */
131
+ const url = new URL(this.opts.url);
132
+ url.searchParams.set('jti', this.opts.jti);
133
+ if (this.opts.sn)
134
+ url.searchParams.set('sn', this.opts.sn);
135
+ return new Promise((resolve, reject) => {
136
+ const ws = new WebSocket(url.toString());
137
+ this.ws = ws;
138
+ let settled = false;
139
+ const settle = (fn) => {
140
+ if (settled)
141
+ return;
142
+ settled = true;
143
+ offAuth();
144
+ this.cancelConnect = null;
145
+ fn();
146
+ };
147
+ this.cancelConnect = (error) => settle(() => reject(error));
148
+ ws.onopen = () => {
149
+ if (this.ws !== ws || this.manualClose)
150
+ return;
151
+ this.attempt = 0;
152
+ this.status = 'open';
153
+ this.startHeartbeat();
154
+ this.emit('open', undefined);
155
+ // 注意:此处不 resolve,等 auth.ok
156
+ };
157
+ ws.onmessage = (ev) => {
158
+ if (this.ws !== ws || this.manualClose)
159
+ return;
160
+ this.handleMessage(ev.data);
161
+ };
162
+ ws.onclose = (ev) => {
163
+ if (this.ws !== ws)
164
+ return;
165
+ this.stopHeartbeat();
166
+ this.rejectAllPending(new Error(`[signaling] 连接关闭 ${ev.code} ${ev.reason}`));
167
+ // 1008 = policy violation(令牌无效),不重连
168
+ const authFailed = ev.code === 1008 || ev.code === 4001 || ev.code === 4003;
169
+ const willRetry = !this.manualClose && this.opts.autoReconnect && !authFailed;
170
+ this.status = willRetry ? 'reconnecting' : 'closed';
171
+ this.emit('close', { code: ev.code, reason: ev.reason, willRetry });
172
+ settle(() => reject(new Error(`[signaling] 握手失败 (${ev.code})`)));
173
+ if (willRetry)
174
+ this.scheduleReconnect();
175
+ };
176
+ // auth.ok 到达时 resolve
177
+ const offAuth = this.on('authOk', (p) => {
178
+ offAuth();
179
+ settle(() => resolve(p));
180
+ });
181
+ });
182
+ }
183
+ /**
184
+ * 停止重连、心跳与在途请求,并等待当前 WebSocket 的 close 事件。
185
+ * @param timeoutMs - 等待浏览器连接关闭的毫秒上限,默认 3000,范围为 1~30000 的整数。
186
+ * @returns 没有活动 socket 或浏览器已确认关闭时完成。
187
+ * @throws 超时、超时参数非法或浏览器关闭失败时拒绝 Promise。
188
+ * @remarks 正在关闭时复用同一次等待。超时后保留未关闭的 socket,旧连接关闭前不能重新 connectSignaling。
189
+ */
190
+ close(timeoutMs = 3000) {
191
+ if (this.closing)
192
+ return this.closing;
193
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000) {
194
+ return Promise.reject(new Error('[signaling] 关闭超时应为 1–30000 ms'));
195
+ }
196
+ this.manualClose = true;
197
+ this.clearReconnectTimer();
198
+ this.stopHeartbeat();
199
+ this.cancelConnect?.(new Error('[signaling] 连接初始化已取消'));
200
+ this.rejectAllPending(new Error('[signaling] 连接已主动关闭'));
201
+ const ws = this.ws;
202
+ this.status = 'closed';
203
+ if (!ws || ws.readyState === WebSocket.CLOSED) {
204
+ this.ws = null;
205
+ return Promise.resolve();
206
+ }
207
+ // 先摘掉回调,再关闭连接。
208
+ // 否则 close 过程中仍可能触发 onclose / onerror,
209
+ // 在 StrictMode 双执行或 HMR 场景下会重复安排重连、抛出无意义异常。
210
+ ws.onopen = null;
211
+ ws.onmessage = null;
212
+ ws.onerror = null;
213
+ ws.onclose = null;
214
+ const work = new Promise((resolve, reject) => {
215
+ let finished = false;
216
+ const finish = (error) => {
217
+ if (finished)
218
+ return;
219
+ finished = true;
220
+ clearTimeout(timer);
221
+ ws.removeEventListener('close', onClose);
222
+ if (ws.readyState === WebSocket.CLOSED && this.ws === ws)
223
+ this.ws = null;
224
+ if (error)
225
+ reject(error);
226
+ else
227
+ resolve();
228
+ };
229
+ const onClose = () => finish();
230
+ const timer = setTimeout(() => finish(new Error('[signaling] 等待 WebSocket 关闭超时')), timeoutMs);
231
+ ws.addEventListener('close', onClose, { once: true });
232
+ try {
233
+ if (ws.readyState === WebSocket.OPEN)
234
+ ws.close(1000, 'client closed');
235
+ else if (ws.readyState === WebSocket.CONNECTING)
236
+ ws.close();
237
+ }
238
+ catch (error) {
239
+ finish(error instanceof Error ? error : new Error('关闭 WebSocket 失败'));
240
+ }
241
+ });
242
+ this.closing = work;
243
+ // 两个分支均处理,避免清理链制造未捕获的拒绝。
244
+ void work.then(() => { this.closing = null; }, () => { this.closing = null; });
245
+ return work;
246
+ }
247
+ scheduleReconnect() {
248
+ this.clearReconnectTimer();
249
+ // 后端建议:1s / 2s / 4s / 8s,上限 30s
250
+ const seq = [1_000, 2_000, 4_000, 8_000, 16_000, 30_000];
251
+ const base = seq[Math.min(this.attempt, seq.length - 1)] ?? 30_000;
252
+ this.attempt += 1;
253
+ this.reconnectTimer = setTimeout(() => {
254
+ this.connectSignaling().catch(() => {
255
+ /* connectSignaling 内部已安排下一次 */
256
+ });
257
+ }, withJitter(base));
258
+ }
259
+ clearReconnectTimer() {
260
+ if (this.reconnectTimer) {
261
+ clearTimeout(this.reconnectTimer);
262
+ this.reconnectTimer = null;
263
+ }
264
+ }
265
+ /* ───────────── 心跳 §7 ───────────── */
266
+ startHeartbeat() {
267
+ this.stopHeartbeat();
268
+ this.heartbeatTimer = setInterval(() => {
269
+ this.send({ type: 'ping', requestId: `hb-${Date.now()}` });
270
+ }, HEARTBEAT_INTERVAL_MS);
271
+ }
272
+ stopHeartbeat() {
273
+ if (this.heartbeatTimer) {
274
+ clearInterval(this.heartbeatTimer);
275
+ this.heartbeatTimer = null;
276
+ }
277
+ }
278
+ /* ───────────── 发送 ───────────── */
279
+ send(frame, checkSize = false) {
280
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
281
+ console.warn('[signaling] 发送跳过,连接未就绪:', frame.type);
282
+ return false;
283
+ }
284
+ const text = JSON.stringify(frame);
285
+ if (checkSize && new TextEncoder().encode(text).byteLength > MAX_FRAME_BYTES) {
286
+ throw new RangeError(`[signaling] 信令帧超过 ${MAX_FRAME_BYTES} 字节`);
287
+ }
288
+ this.ws.send(text);
289
+ return true;
290
+ }
291
+ /**
292
+ * 单向发送自定义信令帧。
293
+ * @param type - 上行帧类型。
294
+ * @param frame - 关联标识、目标序列号及载荷,见 {@link SendFrameParams}。
295
+ * @returns 提交给 WebSocket 时返回 true,WebSocket 未打开时返回 false。
296
+ * @throws 序列化失败、整帧超过 65536 个 UTF-8 字节或浏览器发送失败时同步抛出。
297
+ * @remarks 不登记请求或排队,重连后不重发。
298
+ */
299
+ sendFrame(type, { requestId, targetSN, payload }) {
300
+ const frame = { type, payload };
301
+ if (requestId !== undefined)
302
+ frame.requestId = requestId;
303
+ if (targetSN !== undefined)
304
+ frame.targetSN = targetSN;
305
+ return this.send(frame, true);
306
+ }
307
+ /**
308
+ * 发送一条信令请求并等待对应类型的关联回执。
309
+ * @param type - 上行信令消息类型。
310
+ * @param payload - 消息载荷,undefined 时序列化会省略该字段。
311
+ * @param expectType - 期望的回执类型,例如 device.list.result。
312
+ * @param timeoutMs - 本地等待上限,单位 ms,默认 10000;调用方应提供正的有限值,本层未额外校验范围。
313
+ * @returns 关联回执的 payload;T 由调用方指定,返回值不包含信令信封。
314
+ * @throws 未连接、服务端错误或等待超时会拒绝;序列化和浏览器发送异常也可能导致拒绝。
315
+ * @remarks 不提供独立取消信号,不自动重发;close 或连接关闭会拒绝在途请求。
316
+ */
317
+ request(type, payload, expectType, timeoutMs = 10_000) {
318
+ const requestId = newRequestId();
319
+ return new Promise((resolve, reject) => {
320
+ const timer = setTimeout(() => {
321
+ this.pending.delete(requestId);
322
+ this.expectType.delete(requestId);
323
+ reject(new Error(`[signaling] "${type}" 超时 (${timeoutMs}ms)`));
324
+ }, timeoutMs);
325
+ this.pending.set(requestId, {
326
+ resolve: (v) => {
327
+ clearTimeout(timer);
328
+ resolve(v);
329
+ },
330
+ reject: (e) => {
331
+ clearTimeout(timer);
332
+ reject(e);
333
+ },
334
+ });
335
+ this.expectType.set(requestId, expectType);
336
+ const ok = this.send({ type, requestId, payload });
337
+ if (!ok) {
338
+ clearTimeout(timer);
339
+ this.pending.delete(requestId);
340
+ this.expectType.delete(requestId);
341
+ reject(new Error('[signaling] 连接未就绪'));
342
+ }
343
+ });
344
+ }
345
+ /* ───────────── 业务方法 §5 ───────────── */
346
+ /**
347
+ * 查询用户侧设备列表。
348
+ * @param timeoutMs - 本地等待上限,单位 ms,默认 10000;调用方应提供正的有限值。
349
+ * @returns 对应 device.list.result 的 {@link DeviceListPayload}。
350
+ * @throws 未连接、服务端错误、关闭连接或等待超时时拒绝 Promise,见 {@link SignalingClient.request}。
351
+ */
352
+ listDevices(timeoutMs = 10_000) {
353
+ return this.request('device.list', undefined, 'device.list.result', timeoutMs);
354
+ }
355
+ /**
356
+ * 向目标设备发送 SDP offer。
357
+ * @param targetSN - 目标设备序列号。
358
+ * @param sdp - 本地 offer 的 SDP 文本。
359
+ * @param sdpType - 固定为 offer,省略时补 offer。
360
+ * @returns 已提交给浏览器 WebSocket 时返回 true,连接未打开时返回 false。
361
+ * @throws 序列化或 WebSocket 发送失败时同步抛出。
362
+ * @remarks 不等待服务端或设备确认。
363
+ */
364
+ sendOffer(targetSN, sdp, sdpType = 'offer') {
365
+ return this.send({
366
+ type: 'offer',
367
+ requestId: newRequestId('neg'),
368
+ targetSN,
369
+ payload: { sdp, sdpType },
370
+ });
371
+ }
372
+ /**
373
+ * 向目标设备发送 ICE 候选。
374
+ * @param targetSN - 目标设备序列号。
375
+ * @param ice - 待发送的候选,candidate 缺省时补空字符串,媒体索引和标识缺省时补 null。
376
+ * @returns 已提交给浏览器 WebSocket 时返回 true,连接未打开时返回 false。
377
+ * @throws 序列化或 WebSocket 发送失败时同步抛出。
378
+ * @remarks 不等待设备收到候选的确认。
379
+ */
380
+ sendIce(targetSN, ice) {
381
+ return this.send({
382
+ type: 'ice',
383
+ targetSN,
384
+ payload: {
385
+ candidate: ice.candidate ?? '',
386
+ sdpMid: ice.sdpMid ?? null,
387
+ sdpMLineIndex: ice.sdpMLineIndex ?? null,
388
+ },
389
+ });
390
+ }
391
+ /* ───────────── 收包分派 ───────────── */
392
+ handleMessage(raw) {
393
+ let msg;
394
+ try {
395
+ msg = JSON.parse(String(raw));
396
+ }
397
+ catch {
398
+ console.warn('[signaling] 非法 JSON,已丢弃');
399
+ return;
400
+ }
401
+ if (!msg || typeof msg.type !== 'string')
402
+ return;
403
+ this.dispatchMessage(msg);
404
+ const listeners = this.frameHandlers.get(msg.type);
405
+ if (!listeners)
406
+ return;
407
+ for (const handler of [...listeners]) {
408
+ try {
409
+ handler(msg);
410
+ }
411
+ catch (err) {
412
+ console.error(`[signaling] frame handler for "${msg.type}" threw`, err);
413
+ }
414
+ }
415
+ }
416
+ dispatchMessage(msg) {
417
+ // requestId 配对
418
+ const rid = msg.requestId;
419
+ if (rid && this.pending.has(rid)) {
420
+ const expected = this.expectType.get(rid);
421
+ const p = this.pending.get(rid);
422
+ if (msg.type === 'error') {
423
+ this.pending.delete(rid);
424
+ this.expectType.delete(rid);
425
+ const e = msg.payload;
426
+ p.reject(new Error(`[signaling] ${e?.code ?? 'error'}: ${e?.message ?? ''}`));
427
+ return;
428
+ }
429
+ if (expected && msg.type === expected) {
430
+ this.pending.delete(rid);
431
+ this.expectType.delete(rid);
432
+ p.resolve(msg.payload);
433
+ return;
434
+ }
435
+ }
436
+ this.dispatch(msg);
437
+ }
438
+ dispatch(msg) {
439
+ const payload = msg.payload;
440
+ switch (msg.type) {
441
+ case 'auth.ok':
442
+ this.emit('authOk', payload);
443
+ break;
444
+ case 'device.status':
445
+ this.emit('deviceStatus', payload);
446
+ break;
447
+ case 'offer':
448
+ this.emit('offer', { payload: payload, from: msg.from });
449
+ break;
450
+ case 'answer':
451
+ this.emit('answer', { payload: payload, from: msg.from });
452
+ break;
453
+ case 'ice':
454
+ this.emit('ice', { payload: payload, from: msg.from });
455
+ break;
456
+ case 'command':
457
+ case 'command.result':
458
+ this.emit('command', { payload, from: msg.from });
459
+ break;
460
+ case 'error':
461
+ this.emit('error', payload);
462
+ break;
463
+ case 'pong':
464
+ break;
465
+ }
466
+ }
467
+ rejectAllPending(err) {
468
+ for (const p of this.pending.values())
469
+ p.reject(err);
470
+ this.pending.clear();
471
+ this.expectType.clear();
472
+ }
473
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * 共享信令客户端使用的帧、身份、连接句柄和协议常量。
3
+ * 信令负责发现与 SDP/ICE 交换;机器人业务命令通过应用自己持有的 WebRTC 发送。
4
+ */
5
+ /** 协议中的 token 握手参数形态;SignalingClient 实际使用 jti 配置构造 query,不直接消费本类型。 */
6
+ export interface ConnectParams {
7
+ /** 信令握手凭据,不应记录到日志或业务状态。 */
8
+ token: string;
9
+ /** 设备侧必填;用户侧不传 */
10
+ sn?: string;
11
+ }
12
+ /** 握手阶段 HTTP 错误的说明映射;浏览器 WebSocket 关闭事件不保证暴露这些 HTTP 状态。 */
13
+ export declare const HANDSHAKE_REJECT: Record<number, string>;
14
+ /** 对端身份,由服务端注入,客户端无法伪造 */
15
+ export type PeerIdentity = {
16
+ /** 用户身份标记。 */
17
+ type: 'user';
18
+ /** 服务端用户编号。 */
19
+ userId: number;
20
+ /** 服务端用户显示名。 */
21
+ username: string;
22
+ } | {
23
+ /** 设备身份标记。 */
24
+ type: 'device';
25
+ /** 设备序列号。 */
26
+ sn: string;
27
+ /** 设备显示名。 */
28
+ name: string;
29
+ /** 设备所属用户编号。 */
30
+ userId: number;
31
+ };
32
+ /** 上行帧(客户端 → 服务端) */
33
+ export interface UpFrame<T = unknown> {
34
+ /** 信令消息类型,例如 offer、ice 或 device.list。 */
35
+ type: string;
36
+ /** 服务端原样回传,用于请求-响应配对 */
37
+ requestId?: string;
38
+ /** 用户侧转发帧必填;设备侧忽略 */
39
+ targetSN?: string;
40
+ /** 对应消息类型的载荷;无载荷时可省略。 */
41
+ payload?: T;
42
+ }
43
+ /** 自定义上行帧的信封字段与载荷;同一业务会话可复用调用方指定的 requestId。 */
44
+ export type SendFrameParams = Pick<UpFrame, 'requestId' | 'targetSN' | 'payload'>;
45
+ /** 下行帧(服务端 → 客户端) */
46
+ export interface DownFrame<T = unknown> {
47
+ /** 信令消息类型,例如 auth.ok 或 answer。 */
48
+ type: string;
49
+ /** 对应上行请求的关联编号;广播或无关联消息可省略。 */
50
+ requestId?: string;
51
+ /** 服务端注入 */
52
+ from?: PeerIdentity;
53
+ /** 对应消息类型的载荷。 */
54
+ payload?: T;
55
+ /** 服务端记录的 UTC 时间,格式为 ISO 8601。 */
56
+ timestamp?: string;
57
+ }
58
+ /** 上下行信令处理共用的帧形态;来源与服务端时间在上行帧中通常不存在。 */
59
+ export type AnyFrame = UpFrame & Partial<Pick<DownFrame, 'from' | 'timestamp'>>;
60
+ /**
61
+ * auth.ok 的鉴权结果,不包含登录凭据。
62
+ */
63
+ export interface AuthOkPayload {
64
+ /** 服务端确认的连接角色。 */
65
+ role: 'user' | 'device';
66
+ /** 用户侧有 */
67
+ userId?: number;
68
+ /** 设备侧有 */
69
+ sn?: string;
70
+ /** 显示名,两侧都有 */
71
+ name?: string;
72
+ /** 服务端时间,ISO-8601 字符串;不是本地单调时钟。 */
73
+ serverTime: string;
74
+ /** 信令服务可在鉴权成功时下发本次会话的 STUN/TURN 配置。 */
75
+ iceServers?: RTCIceServer[];
76
+ /** 临时凭证的有效时间,单位秒,从收到鉴权回执起算。 */
77
+ iceTtlSeconds?: number;
78
+ /** 临时凭证的到期时间,ISO-8601。 */
79
+ iceExpiresAt?: string;
80
+ }
81
+ /** device.list.result 里的设备项 */
82
+ export interface DeviceInfo {
83
+ /** 设备序列号。 */
84
+ sn: string;
85
+ /** 设备显示名。 */
86
+ name: string;
87
+ /** 信令服务记录的在线状态,不代表执行器就绪或可被独占控制。 */
88
+ online: boolean;
89
+ /** ISO-8601,设备本次上线时间 */
90
+ connectedAt: string;
91
+ }
92
+ /** device.list.result 的设备列表载荷。 */
93
+ export interface DeviceListPayload {
94
+ /** 服务端返回的设备总数。 */
95
+ total: number;
96
+ /** 本次列表中的设备项。 */
97
+ devices: DeviceInfo[];
98
+ }
99
+ /** device.status 推送 */
100
+ export interface DeviceStatusPayload {
101
+ /** 状态发生变化的设备序列号。 */
102
+ sn: string;
103
+ /** 设备显示名。 */
104
+ name: string;
105
+ /** 信令在线状态,不等同于机器人执行器状态。 */
106
+ online: boolean;
107
+ }
108
+ /** offer / answer 的 payload */
109
+ export interface SdpPayload {
110
+ /** SDP 文本。 */
111
+ sdp: string;
112
+ /** SDP 类型。 */
113
+ sdpType: 'offer' | 'answer';
114
+ }
115
+ /** ice 的 payload,与服务端无关,两端自行约定 */
116
+ export interface IcePayload {
117
+ /** ICE 候选字符串;空字符串可表示候选收集结束,PeerNegotiator 会忽略该标记。 */
118
+ candidate: string;
119
+ /** 候选对应的媒体标识,未知时为 null。 */
120
+ sdpMid: string | null;
121
+ /** 候选对应媒体行的零基索引,未知时为 null。 */
122
+ sdpMLineIndex: number | null;
123
+ }
124
+ /** 信令服务端错误码,不是机器人 JSON-RPC 错误码。 */
125
+ export type ErrorCode = 'invalid_message' | 'unauthenticated' | 'unsupported_type' | 'target_required' | 'device_offline' | 'forbidden' | 'no_subscriber' | 'duplicate_login';
126
+ /** 信令服务端错误载荷。 */
127
+ export interface ErrorPayload {
128
+ /** 可用于分类处理的信令错误码。 */
129
+ code: ErrorCode;
130
+ /** 服务端说明。 */
131
+ message: string;
132
+ }
133
+ /** 错误码对应的用户可读提示 */
134
+ export declare const ERROR_HINTS: Record<ErrorCode, string>;
135
+ /** WebRTC 建连完成后的产物,交由上层(控制 SDK)使用 */
136
+ export interface EstablishedConnection {
137
+ /** 当前页面持有的 WebRTC 连接;调用方读取统计或发送媒体时应复用此连接。 */
138
+ pc: RTCPeerConnection;
139
+ /** control 通道,可能为 null(取决于设备端是否创建) */
140
+ control: RTCDataChannel | null;
141
+ /** telemetry 通道,可能为 null */
142
+ telemetry: RTCDataChannel | null;
143
+ /** 文件上传专用可靠有序通道。旧连接可省略,通道关闭不影响控制。 */
144
+ blob?: RTCDataChannel | null;
145
+ /** 头部 ToF 的不可靠无序通道。可省略,通道状态不参与控制连接的就绪判定。 */
146
+ tof?: RTCDataChannel | null;
147
+ /** 已接收音视频轨道的聚合流;尚未收到时为 null,不会自动播放。 */
148
+ remoteStream: MediaStream | null;
149
+ /** 对端设备 SN */
150
+ sn: string;
151
+ /** 对端设备名,来自 answer 帧的 from.name */
152
+ deviceName: string | null;
153
+ }
154
+ /** 信令客户端应用层 ping 的发送间隔,单位 ms,值为 30000。 */
155
+ export declare const HEARTBEAT_INTERVAL_MS = 30000;
156
+ /** 协议中的服务端读空闲参考超时,单位 ms,值为 90000;客户端不使用此常量主动断线。 */
157
+ export declare const READER_IDLE_TIMEOUT_MS = 90000;
158
+ /** 信令协议单帧上限,单位字节;sendFrame 按整帧 JSON 的 UTF-8 长度检查。 */
159
+ export declare const MAX_FRAME_BYTES = 65536;
160
+ /**
161
+ * 未显式配置 iceServers 时使用的 STUN 列表,不包含 TURN 中继。
162
+ * 列表不证明服务器当前可达;调用方可按自己的网络环境覆盖配置。
163
+ */
164
+ export declare const DEFAULT_ICE_SERVERS: RTCIceServer[];
@@ -0,0 +1,35 @@
1
+ /**
2
+ * 共享信令客户端使用的帧、身份、连接句柄和协议常量。
3
+ * 信令负责发现与 SDP/ICE 交换;机器人业务命令通过应用自己持有的 WebRTC 发送。
4
+ */
5
+ /** 握手阶段 HTTP 错误的说明映射;浏览器 WebSocket 关闭事件不保证暴露这些 HTTP 状态。 */
6
+ export const HANDSHAKE_REJECT = {
7
+ 401: '令牌无效或已过期',
8
+ 404: '信令端点错误,应为 /ws',
9
+ 426: '该路径仅接受 WebSocket 连接',
10
+ };
11
+ /** 错误码对应的用户可读提示 */
12
+ export const ERROR_HINTS = {
13
+ invalid_message: '报文格式错误',
14
+ unauthenticated: '连接未鉴权,请重新登录',
15
+ unsupported_type: '消息类型不支持',
16
+ target_required: '缺少目标设备',
17
+ device_offline: '设备已离线',
18
+ forbidden: '无权访问该设备',
19
+ no_subscriber: '设备侧等待 App 重新发起',
20
+ duplicate_login: '该设备已在其他位置上线',
21
+ };
22
+ /* ─────────────────────────── 常量 ─────────────────────────── */
23
+ /** 信令客户端应用层 ping 的发送间隔,单位 ms,值为 30000。 */
24
+ export const HEARTBEAT_INTERVAL_MS = 30_000;
25
+ /** 协议中的服务端读空闲参考超时,单位 ms,值为 90000;客户端不使用此常量主动断线。 */
26
+ export const READER_IDLE_TIMEOUT_MS = 90_000;
27
+ /** 信令协议单帧上限,单位字节;sendFrame 按整帧 JSON 的 UTF-8 长度检查。 */
28
+ export const MAX_FRAME_BYTES = 65_536;
29
+ /**
30
+ * 未显式配置 iceServers 时使用的 STUN 列表,不包含 TURN 中继。
31
+ * 列表不证明服务器当前可达;调用方可按自己的网络环境覆盖配置。
32
+ */
33
+ export const DEFAULT_ICE_SERVERS = [
34
+ { urls: 'stun:8.156.38.92:3478' },
35
+ ];