@realsee/live 0.4.0-beta.6 → 0.4.0-beta.7

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.
@@ -1,9 +1,99 @@
1
1
  import JSBridge from '@realsee/jsbridge-x';
2
- import { DefaultModality, ConsoleLogger, LogLevel, DefaultDeviceController, MeetingSessionConfiguration, DefaultMeetingSession, MeetingSessionStatusCode } from 'amazon-chime-sdk-js';
2
+ import { DefaultModality, ConsoleLogger, LogLevel, DefaultDeviceController, MeetingSessionStatusCode, MeetingSessionConfiguration, DefaultMeetingSession } from 'amazon-chime-sdk-js';
3
3
  import TRTC from 'trtc-js-sdk';
4
4
  import React from 'react';
5
5
 
6
- const EVENT_SYMBOL = Symbol('$$REALSEE_LIVE_EVENT$$');
6
+ /******************************************************************************
7
+ Copyright (c) Microsoft Corporation.
8
+
9
+ Permission to use, copy, modify, and/or distribute this software for any
10
+ purpose with or without fee is hereby granted.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
+ PERFORMANCE OF THIS SOFTWARE.
19
+ ***************************************************************************** */
20
+ /* global Reflect, Promise */
21
+
22
+ var extendStatics = function(d, b) {
23
+ extendStatics = Object.setPrototypeOf ||
24
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
26
+ return extendStatics(d, b);
27
+ };
28
+
29
+ function __extends(d, b) {
30
+ if (typeof b !== "function" && b !== null)
31
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
32
+ extendStatics(d, b);
33
+ function __() { this.constructor = d; }
34
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35
+ }
36
+
37
+ var __assign = function() {
38
+ __assign = Object.assign || function __assign(t) {
39
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
40
+ s = arguments[i];
41
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
42
+ }
43
+ return t;
44
+ };
45
+ return __assign.apply(this, arguments);
46
+ };
47
+
48
+ function __awaiter(thisArg, _arguments, P, generator) {
49
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
50
+ return new (P || (P = Promise))(function (resolve, reject) {
51
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
52
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
53
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
54
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
55
+ });
56
+ }
57
+
58
+ function __generator(thisArg, body) {
59
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
60
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
61
+ function verb(n) { return function (v) { return step([n, v]); }; }
62
+ function step(op) {
63
+ if (f) throw new TypeError("Generator is already executing.");
64
+ while (_) try {
65
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
66
+ if (y = 0, t) op = [op[0] & 2, t.value];
67
+ switch (op[0]) {
68
+ case 0: case 1: t = op; break;
69
+ case 4: _.label++; return { value: op[1], done: false };
70
+ case 5: _.label++; y = op[1]; op = [0]; continue;
71
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
72
+ default:
73
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
74
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
75
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
76
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
77
+ if (t[2]) _.ops.pop();
78
+ _.trys.pop(); continue;
79
+ }
80
+ op = body.call(thisArg, _);
81
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
82
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
83
+ }
84
+ }
85
+
86
+ function __spreadArray(to, from, pack) {
87
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
88
+ if (ar || !(i in from)) {
89
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
90
+ ar[i] = from[i];
91
+ }
92
+ }
93
+ return to.concat(ar || Array.prototype.slice.call(from));
94
+ }
95
+
96
+ var EVENT_SYMBOL = Symbol('$$REALSEE_LIVE_EVENT$$');
7
97
  function __generateEventIfNotExisted(instance) {
8
98
  if (!instance[EVENT_SYMBOL]) {
9
99
  instance[EVENT_SYMBOL] = {};
@@ -26,15 +116,17 @@ function __removeEventIfNotExisted(instance) {
26
116
  * }>()
27
117
  * ```
28
118
  */
29
- class Subscribe {
119
+ var Subscribe = /** @class */ (function () {
120
+ function Subscribe() {
121
+ }
30
122
  /**
31
123
  * 判断是否注册了事件
32
124
  * @param name 事件类型
33
125
  */
34
- hasListener(name) {
35
- const events = __generateEventIfNotExisted(this);
126
+ Subscribe.prototype.hasListener = function (name) {
127
+ var events = __generateEventIfNotExisted(this);
36
128
  return events && events[name] && events[name].length > 0;
37
- }
129
+ };
38
130
  /**
39
131
  * 注册事件
40
132
  * @param name 事件类型
@@ -44,13 +136,14 @@ class Subscribe {
44
136
  * @template K 预设的监听事件名称
45
137
  * @template C 回调函数函数上下文
46
138
  */
47
- on(name, callback, once) {
48
- const events = __generateEventIfNotExisted(this);
139
+ Subscribe.prototype.on = function (name, callback, once) {
140
+ var _this = this;
141
+ var events = __generateEventIfNotExisted(this);
49
142
  if (!events[name])
50
143
  events[name] = [];
51
144
  events[name].push([callback, once || false]);
52
- return () => this.off(name, callback);
53
- }
145
+ return function () { return _this.off(name, callback); };
146
+ };
54
147
  /**
55
148
  * 注册事件(是否只执行一次)
56
149
  * @param name 事件类型
@@ -59,9 +152,9 @@ class Subscribe {
59
152
  * @template K 预设的监听事件名称
60
153
  * @template C 回调函数函数上下文
61
154
  */
62
- once(name, callback) {
155
+ Subscribe.prototype.once = function (name, callback) {
63
156
  return this.on(name, callback, true);
64
- }
157
+ };
65
158
  /**
66
159
  * 解除事件
67
160
  *
@@ -71,19 +164,19 @@ class Subscribe {
71
164
  * @param callback 事件回调函数
72
165
  * @template K 预设的监听事件名称
73
166
  */
74
- off(name, callback) {
167
+ Subscribe.prototype.off = function (name, callback) {
75
168
  if (name === undefined) {
76
169
  __removeEventIfNotExisted(this);
77
170
  return;
78
171
  }
79
- const events = __generateEventIfNotExisted(this);
172
+ var events = __generateEventIfNotExisted(this);
80
173
  if (!events[name])
81
174
  events[name] = [];
82
175
  if (callback === undefined) {
83
176
  events[name].length = 0;
84
177
  return;
85
178
  }
86
- let index = 0;
179
+ var index = 0;
87
180
  for (; index < events[name].length; index++) {
88
181
  if (events[name][index][0] === callback)
89
182
  break;
@@ -91,7 +184,7 @@ class Subscribe {
91
184
  if (index < events[name].length) {
92
185
  events[name].splice(index, 1);
93
186
  }
94
- }
187
+ };
95
188
  /**
96
189
  * 触发事件
97
190
  * @param name 事件类型
@@ -99,27 +192,38 @@ class Subscribe {
99
192
  * @returns canceled 是否被触发取消
100
193
  * @template K 预设的监听事件名称
101
194
  */
102
- emit(name, ...data) {
103
- let canceled = false;
104
- const events = __generateEventIfNotExisted(this);
105
- const event = events[name] || [];
106
- for (let one of event.slice()) {
107
- const [callback, once = false] = one;
108
- const result = callback(...data);
195
+ Subscribe.prototype.emit = function (name) {
196
+ var data = [];
197
+ for (var _i = 1; _i < arguments.length; _i++) {
198
+ data[_i - 1] = arguments[_i];
199
+ }
200
+ var canceled = false;
201
+ var events = __generateEventIfNotExisted(this);
202
+ var event = events[name] || [];
203
+ for (var _a = 0, _b = event.slice(); _a < _b.length; _a++) {
204
+ var one = _b[_a];
205
+ var callback = one[0], _c = one[1], once = _c === void 0 ? false : _c;
206
+ var result = callback.apply(void 0, data);
109
207
  if (once)
110
208
  this.off(name, callback);
111
209
  if (result === false)
112
210
  canceled = true;
113
211
  }
114
212
  return canceled;
115
- }
116
- }
213
+ };
214
+ return Subscribe;
215
+ }());
117
216
 
118
217
  /**
119
218
  * rtc 基础抽象类
120
219
  */
121
- class CoreRTC extends Subscribe {
122
- }
220
+ var CoreRTC = /** @class */ (function (_super) {
221
+ __extends(CoreRTC, _super);
222
+ function CoreRTC() {
223
+ return _super !== null && _super.apply(this, arguments) || this;
224
+ }
225
+ return CoreRTC;
226
+ }(Subscribe));
123
227
 
124
228
  /**
125
229
  * rtc 类型
@@ -159,202 +263,231 @@ function uuid() {
159
263
  S4()).toLowerCase();
160
264
  }
161
265
 
162
- class BrowserRTC extends CoreRTC {
163
- constructor(options) {
164
- super();
165
- this.type = RTCType.RealseeBrowserRTC;
166
- this.joined = false;
167
- this.micro = false;
168
- this.voiceId = '';
169
- this._getVoiceSign = () => {
266
+ var BrowserRTC = /** @class */ (function (_super) {
267
+ __extends(BrowserRTC, _super);
268
+ function BrowserRTC(options) {
269
+ var _this = _super.call(this) || this;
270
+ _this.type = RTCType.RealseeBrowserRTC;
271
+ _this.joined = false;
272
+ _this.micro = false;
273
+ _this.voiceId = '';
274
+ _this._getVoiceSign = function () {
170
275
  throw new Error('方法 getVoiceSign 未实现');
171
276
  };
172
- this.$dom = document.createElement('div');
173
- this._trtc = {
277
+ _this.$dom = document.createElement('div');
278
+ _this._trtc = {
174
279
  client: null,
175
280
  stream: null,
176
281
  };
177
- this.join = async (options) => {
282
+ _this.join = function (options) { return __awaiter(_this, void 0, void 0, function () {
283
+ var createClientOptions, result;
284
+ var _this = this;
178
285
  var _a;
179
- this.emit('joinWillStart');
180
- const createClientOptions = await this._getVoiceSign({
181
- voiceId: options.voiceId,
182
- roomId: options.roomId,
183
- userId: options.userId,
184
- });
185
- // 1. 创建client
186
- this._trtc.client = TRTC.createClient({
187
- mode: 'rtc',
188
- ...createClientOptions,
189
- });
190
- (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.enableAudioVolumeEvaluation();
191
- // 2. 订阅事件
192
- this._registerRtcEvent();
193
- // 3. 加入语音房间
194
- let result = await new Promise((resolve) => {
195
- var _a;
196
- (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.join({ roomId: Number(options.voiceId) }).then(() => resolve(true)).catch(() => resolve(false));
197
- });
198
- this.joined = result;
199
- if (!result)
200
- return false; // 进房失败
201
- // 4. 创建本地流
202
- this._trtc.stream = TRTC.createStream({
203
- userId: createClientOptions.userId,
204
- audio: true,
205
- video: false,
206
- });
207
- // 5. 初始化本地流
208
- result = await new Promise((resolve) => {
209
- var _a;
210
- (_a = this._trtc.stream) === null || _a === void 0 ? void 0 : _a.initialize().then(() => resolve(true)).catch(() => resolve(false));
211
- });
212
- // 6. 发布本地流
213
- result = await new Promise((resolve) => {
214
- var _a;
215
- (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.publish(this._trtc.stream).then(() => resolve(true)).catch(() => resolve(false));
286
+ return __generator(this, function (_b) {
287
+ switch (_b.label) {
288
+ case 0:
289
+ this.emit('joinWillStart');
290
+ return [4 /*yield*/, this._getVoiceSign({
291
+ voiceId: options.voiceId,
292
+ roomId: options.roomId,
293
+ userId: options.userId,
294
+ })];
295
+ case 1:
296
+ createClientOptions = _b.sent();
297
+ // 1. 创建client
298
+ this._trtc.client = TRTC.createClient(__assign({ mode: 'rtc' }, createClientOptions));
299
+ (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.enableAudioVolumeEvaluation();
300
+ // 2. 订阅事件
301
+ this._registerRtcEvent();
302
+ return [4 /*yield*/, new Promise(function (resolve) {
303
+ var _a;
304
+ (_a = _this._trtc.client) === null || _a === void 0 ? void 0 : _a.join({ roomId: Number(options.voiceId) }).then(function () { return resolve(true); }).catch(function () { return resolve(false); });
305
+ })];
306
+ case 2:
307
+ result = _b.sent();
308
+ this.joined = result;
309
+ if (!result)
310
+ return [2 /*return*/, false]; // 进房失败
311
+ // 4. 创建本地流
312
+ this._trtc.stream = TRTC.createStream({
313
+ userId: createClientOptions.userId,
314
+ audio: true,
315
+ video: false,
316
+ });
317
+ return [4 /*yield*/, new Promise(function (resolve) {
318
+ var _a;
319
+ (_a = _this._trtc.stream) === null || _a === void 0 ? void 0 : _a.initialize().then(function () { return resolve(true); }).catch(function () { return resolve(false); });
320
+ })];
321
+ case 3:
322
+ // 5. 初始化本地流
323
+ result = _b.sent();
324
+ return [4 /*yield*/, new Promise(function (resolve) {
325
+ var _a;
326
+ (_a = _this._trtc.client) === null || _a === void 0 ? void 0 : _a.publish(_this._trtc.stream).then(function () { return resolve(true); }).catch(function () { return resolve(false); });
327
+ })];
328
+ case 4:
329
+ // 6. 发布本地流
330
+ result = _b.sent();
331
+ this.joined = result;
332
+ if (this.joined)
333
+ this.emit('joined');
334
+ return [2 /*return*/, result];
335
+ }
216
336
  });
217
- this.joined = result;
218
- if (this.joined)
219
- this.emit('joined');
220
- return result;
221
- };
222
- this._handleStreamAdded = (event) => {
337
+ }); };
338
+ _this._handleStreamAdded = function (event) {
223
339
  var _a;
224
- const remoteStream = event.stream;
340
+ var remoteStream = event.stream;
225
341
  console.log('远端流增加: ' + remoteStream.getId());
226
342
  //订阅远端流
227
- (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.subscribe(remoteStream);
343
+ (_a = _this._trtc.client) === null || _a === void 0 ? void 0 : _a.subscribe(remoteStream);
228
344
  };
229
- this._handleStreamSubscribed = (event) => {
230
- const remoteStream = event.stream;
345
+ _this._handleStreamSubscribed = function (event) {
346
+ var remoteStream = event.stream;
231
347
  console.log('远端流订阅成功:' + remoteStream.getId());
232
- const playId = remoteStream.getId();
233
- const domId = `rs-rtc-remote_stream-${playId}`;
234
- const dom = document.createElement('div');
348
+ var playId = remoteStream.getId();
349
+ var domId = "rs-rtc-remote_stream-".concat(playId);
350
+ var dom = document.createElement('div');
235
351
  dom.id = domId;
236
- this.$dom.appendChild(dom);
352
+ _this.$dom.appendChild(dom);
237
353
  // 播放远端流
238
354
  remoteStream.play(domId);
239
355
  };
240
- this._getVoiceSign = options.getVoiceSign;
241
- this._initParentDom();
356
+ _this._getVoiceSign = options.getVoiceSign;
357
+ _this._initParentDom();
358
+ return _this;
242
359
  }
243
- _initParentDom() {
244
- this.$dom.id = `rs-rtc-${uuid()}`;
360
+ BrowserRTC.prototype._initParentDom = function () {
361
+ this.$dom.id = "rs-rtc-".concat(uuid());
245
362
  this.$dom.style.display = 'none';
246
363
  document.body.appendChild(this.$dom);
247
- }
248
- quit() {
249
- return new Promise(async (resolve) => {
364
+ };
365
+ BrowserRTC.prototype.quit = function () {
366
+ var _this = this;
367
+ return new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () {
368
+ var _this = this;
250
369
  var _a, _b;
251
- this.joined = false;
252
- if (this._trtc.stream) {
253
- await ((_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.unpublish(this._trtc.stream));
254
- this._trtc.stream.stop();
255
- this._trtc.stream.close();
256
- this._trtc.stream = null;
257
- }
258
- (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.leave().then(() => (this._trtc.client = null)).then(() => resolve(true)).catch(() => resolve(false));
259
- });
260
- }
261
- detectMicro() {
262
- return new Promise((resolve) => {
263
- const rule = { audio: true, video: false };
370
+ return __generator(this, function (_c) {
371
+ switch (_c.label) {
372
+ case 0:
373
+ this.joined = false;
374
+ if (!this._trtc.stream) return [3 /*break*/, 2];
375
+ return [4 /*yield*/, ((_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.unpublish(this._trtc.stream))];
376
+ case 1:
377
+ _c.sent();
378
+ this._trtc.stream.stop();
379
+ this._trtc.stream.close();
380
+ this._trtc.stream = null;
381
+ _c.label = 2;
382
+ case 2:
383
+ (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.leave().then(function () { return (_this._trtc.client = null); }).then(function () { return resolve(true); }).catch(function () { return resolve(false); });
384
+ return [2 /*return*/];
385
+ }
386
+ });
387
+ }); });
388
+ };
389
+ BrowserRTC.prototype.detectMicro = function () {
390
+ return new Promise(function (resolve) {
391
+ var rule = { audio: true, video: false };
264
392
  try {
265
393
  navigator.mediaDevices
266
394
  .getUserMedia(rule)
267
- .then(() => resolve(true))
268
- .catch(() => resolve(false));
395
+ .then(function () { return resolve(true); })
396
+ .catch(function () { return resolve(false); });
269
397
  }
270
398
  catch (e) {
271
399
  console.error(e);
272
400
  resolve(false);
273
401
  }
274
402
  });
275
- }
276
- toggleMicro(flag) {
403
+ };
404
+ BrowserRTC.prototype.toggleMicro = function (flag) {
277
405
  var _a, _b, _c, _d;
278
406
  return Promise.resolve((flag
279
407
  ? (_b = (_a = this._trtc) === null || _a === void 0 ? void 0 : _a.stream) === null || _b === void 0 ? void 0 : _b.unmuteAudio()
280
408
  : (_d = (_c = this._trtc) === null || _c === void 0 ? void 0 : _c.stream) === null || _d === void 0 ? void 0 : _d.muteAudio()) || false);
281
- }
282
- shock() {
409
+ };
410
+ BrowserRTC.prototype.shock = function () {
283
411
  throw new Error('Method not implemented.');
284
- }
285
- _registerRtcEvent() {
412
+ };
413
+ BrowserRTC.prototype._registerRtcEvent = function () {
414
+ var _this = this;
286
415
  var _a, _b, _c, _d;
287
416
  (_a = this._trtc.client) === null || _a === void 0 ? void 0 : _a.on('stream-added', this._handleStreamAdded);
288
417
  (_b = this._trtc.client) === null || _b === void 0 ? void 0 : _b.on('stream-subscribed', this._handleStreamSubscribed);
289
- (_c = this._trtc.client) === null || _c === void 0 ? void 0 : _c.on('audio-volume', (event) => this.emit('userVolumes', [
290
- { userId: event.userId, audioVolume: event.audioVolume },
291
- ]));
292
- (_d = this._trtc.client) === null || _d === void 0 ? void 0 : _d.on('error', (event) => this.emit('error', event));
293
- }
294
- }
418
+ (_c = this._trtc.client) === null || _c === void 0 ? void 0 : _c.on('audio-volume', function (event) {
419
+ return _this.emit('userVolumes', [
420
+ { userId: event.userId, audioVolume: event.audioVolume },
421
+ ]);
422
+ });
423
+ (_d = this._trtc.client) === null || _d === void 0 ? void 0 : _d.on('error', function (event) { return _this.emit('error', event); });
424
+ };
425
+ return BrowserRTC;
426
+ }(CoreRTC));
295
427
 
296
428
  /**
297
429
  * amazon-chime-sdk-js 适配的rtc实现
298
430
  */
299
- class BrowserRTC4Chime extends CoreRTC {
300
- constructor(options) {
301
- super();
302
- this.type = RTCType.RealseeBrowserChimeRTC;
303
- this.joined = false;
304
- this.micro = false;
305
- this.voiceId = '';
306
- this.userId = '';
307
- this.deviceChangeObserver = {};
308
- this.audioVideoObserver = {};
309
- this._getVoiceSign = () => {
431
+ var BrowserRTC4Chime = /** @class */ (function (_super) {
432
+ __extends(BrowserRTC4Chime, _super);
433
+ function BrowserRTC4Chime(options) {
434
+ var _this = _super.call(this) || this;
435
+ _this.type = RTCType.RealseeBrowserChimeRTC;
436
+ _this.joined = false;
437
+ _this.micro = false;
438
+ _this.voiceId = '';
439
+ _this.userId = '';
440
+ _this.deviceChangeObserver = {};
441
+ _this.audioVideoObserver = {};
442
+ _this._getVoiceSign = function () {
310
443
  throw new Error('方法 getVoiceSign 未实现');
311
444
  };
312
- this.$dom = document.createElement('div');
313
- this.$audio = document.createElement('audio');
445
+ _this.$dom = document.createElement('div');
446
+ _this.$audio = document.createElement('audio');
314
447
  /**
315
448
  * 对audio标签初始化
316
449
  */
317
- this._initDom = () => {
318
- this.$audio.id = `rs-rtc-${uuid()}`;
319
- this.$dom.id = `rs-rtc-${uuid()}`;
320
- this.$dom.appendChild(this.$audio);
321
- document.body.appendChild(this.$dom);
450
+ _this._initDom = function () {
451
+ _this.$audio.id = "rs-rtc-".concat(uuid());
452
+ _this.$dom.id = "rs-rtc-".concat(uuid());
453
+ _this.$dom.appendChild(_this.$audio);
454
+ document.body.appendChild(_this.$dom);
322
455
  };
323
456
  /**
324
457
  * 初始化事件监听器
325
458
  */
326
- this.initObservers = () => {
459
+ _this.initObservers = function () {
327
460
  // 输入输出设备变化的监听器
328
- this.deviceChangeObserver = {
329
- audioInputsChanged: (freshAudioInputDeviceList) => {
461
+ _this.deviceChangeObserver = {
462
+ audioInputsChanged: function (freshAudioInputDeviceList) {
330
463
  // An array of MediaDeviceInfo objects
331
- freshAudioInputDeviceList === null || freshAudioInputDeviceList === void 0 ? void 0 : freshAudioInputDeviceList.forEach((mediaDeviceInfo) => {
332
- this.logger.info(`Device ID: ${mediaDeviceInfo.deviceId} Microphone: ${mediaDeviceInfo.label}`);
464
+ freshAudioInputDeviceList === null || freshAudioInputDeviceList === void 0 ? void 0 : freshAudioInputDeviceList.forEach(function (mediaDeviceInfo) {
465
+ _this.logger.info("Device ID: ".concat(mediaDeviceInfo.deviceId, " Microphone: ").concat(mediaDeviceInfo.label));
333
466
  });
334
467
  },
335
- audioOutputsChanged: (freshAudioOutputDeviceList) => {
336
- this.logger.info(`Audio outputs updated: ${freshAudioOutputDeviceList}`);
468
+ audioOutputsChanged: function (freshAudioOutputDeviceList) {
469
+ _this.logger.info("Audio outputs updated: ".concat(freshAudioOutputDeviceList));
337
470
  },
338
- videoInputsChanged: (freshVideoInputDeviceList) => {
339
- this.logger.info(`Video inputs updated: ${freshVideoInputDeviceList}`);
471
+ videoInputsChanged: function (freshVideoInputDeviceList) {
472
+ _this.logger.info("Video inputs updated: ".concat(freshVideoInputDeviceList));
340
473
  },
341
- audioInputMuteStateChanged: (device, muted) => {
342
- this.logger.info(`Device ${device.toString()} ${muted ? 'is muted in hardware' : 'is not muted'}`);
474
+ audioInputMuteStateChanged: function (device, muted) {
475
+ _this.logger.info("Device ".concat(device.toString(), " ").concat(muted ? 'is muted in hardware' : 'is not muted'));
343
476
  },
344
477
  };
345
478
  // 流变化监听器
346
- this.audioVideoObserver = {
347
- audioVideoDidStart: () => {
348
- this.logger.info('Started');
479
+ _this.audioVideoObserver = {
480
+ audioVideoDidStart: function () {
481
+ _this.logger.info('Started');
349
482
  },
350
- audioVideoDidStop: (sessionStatus) => {
483
+ audioVideoDidStop: function (sessionStatus) {
351
484
  // See the "Stopping a session" section for details.
352
- this.logger.info(`Stopped with a session status code: ${sessionStatus.statusCode()}`);
485
+ _this.logger.info("Stopped with a session status code: ".concat(sessionStatus.statusCode()));
353
486
  },
354
- audioVideoDidStartConnecting: (reconnecting) => {
487
+ audioVideoDidStartConnecting: function (reconnecting) {
355
488
  if (reconnecting) {
356
489
  // e.g. the WiFi connection is dropped.
357
- this.logger.info('Attempting to reconnect');
490
+ _this.logger.info('Attempting to reconnect');
358
491
  }
359
492
  },
360
493
  };
@@ -362,15 +495,15 @@ class BrowserRTC4Chime extends CoreRTC {
362
495
  /**
363
496
  * 注册rtc事件
364
497
  */
365
- this._registerRtcEvent = () => {
498
+ _this._registerRtcEvent = function () {
366
499
  var _a, _b, _c, _d, _e, _f;
367
- const presentAttendeeId = ((_c = (_b = (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.configuration) === null || _b === void 0 ? void 0 : _b.credentials) === null || _c === void 0 ? void 0 : _c.attendeeId) || '';
500
+ var presentAttendeeId = ((_c = (_b = (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.configuration) === null || _b === void 0 ? void 0 : _b.credentials) === null || _c === void 0 ? void 0 : _c.attendeeId) || '';
368
501
  if (presentAttendeeId) {
369
502
  // 处理音量变化
370
- const roster = new Map();
371
- const getUserVolumes = () => {
372
- const result = [];
373
- roster.forEach((v, k) => {
503
+ var roster_1 = new Map();
504
+ var getUserVolumes_1 = function () {
505
+ var result = [];
506
+ roster_1.forEach(function (v, k) {
374
507
  result.push({
375
508
  userId: v.userId,
376
509
  volume: v.muted || v.signalStrength === 0 || !Boolean(v.volume)
@@ -380,177 +513,208 @@ class BrowserRTC4Chime extends CoreRTC {
380
513
  });
381
514
  return result;
382
515
  };
383
- (_d = this.meetingSession) === null || _d === void 0 ? void 0 : _d.audioVideo.realtimeSubscribeToAttendeeIdPresence((presentAttendeeId, present, externalUserId) => {
516
+ (_d = _this.meetingSession) === null || _d === void 0 ? void 0 : _d.audioVideo.realtimeSubscribeToAttendeeIdPresence(function (presentAttendeeId, present, externalUserId) {
384
517
  var _a;
385
518
  if (!present) {
386
- roster.delete(presentAttendeeId);
387
- this.emit('userVolumes', getUserVolumes());
519
+ roster_1.delete(presentAttendeeId);
520
+ _this.emit('userVolumes', getUserVolumes_1());
388
521
  return;
389
522
  }
390
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, (attendeeId, volume, muted, signalStrength) => {
391
- const baseAttendeeId = new DefaultModality(attendeeId).base();
523
+ (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, function (attendeeId, volume, muted, signalStrength) {
524
+ var baseAttendeeId = new DefaultModality(attendeeId).base();
392
525
  if (baseAttendeeId !== attendeeId) {
393
526
  // Optional: Do not include the content attendee (attendee-id#content) in the roster.
394
527
  // See the "Screen and content share" section for details.
395
528
  return;
396
529
  }
397
- roster.set(attendeeId, {
530
+ roster_1.set(attendeeId, {
398
531
  userId: externalUserId || attendeeId,
399
- volume,
400
- muted,
401
- signalStrength,
532
+ volume: volume,
533
+ muted: muted,
534
+ signalStrength: signalStrength,
402
535
  });
403
- this.emit('userVolumes', getUserVolumes());
536
+ _this.emit('userVolumes', getUserVolumes_1());
404
537
  });
405
538
  });
406
539
  // 弱网
407
- (_e = this.meetingSession) === null || _e === void 0 ? void 0 : _e.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, (attendeeId, volume, muted, signalStrength) => {
408
- const baseAttendeeId = new DefaultModality(attendeeId).base();
540
+ (_e = _this.meetingSession) === null || _e === void 0 ? void 0 : _e.audioVideo.realtimeSubscribeToVolumeIndicator(presentAttendeeId, function (attendeeId, volume, muted, signalStrength) {
541
+ var baseAttendeeId = new DefaultModality(attendeeId).base();
409
542
  if (baseAttendeeId === attendeeId) {
410
543
  if (signalStrength !== null && signalStrength !== 1) {
411
- this.emit('weakNetwork');
544
+ _this.emit('weakNetwork');
412
545
  }
413
546
  }
414
547
  });
415
548
  // 报错
416
- (_f = this.meetingSession) === null || _f === void 0 ? void 0 : _f.audioVideo.realtimeSubscribeToFatalError((error) => this.emit('error', error));
549
+ (_f = _this.meetingSession) === null || _f === void 0 ? void 0 : _f.audioVideo.realtimeSubscribeToFatalError(function (error) { return _this.emit('error', error); });
417
550
  }
418
551
  };
419
552
  // 挂载签名钩子
420
- this._getVoiceSign = options.getVoiceSign;
421
- this._initDom();
422
- this.logger = new ConsoleLogger('WebRTCLogger', options.logLevel || LogLevel.OFF);
423
- this.deviceController = new DefaultDeviceController(this.logger);
424
- this.initObservers();
553
+ _this._getVoiceSign = options.getVoiceSign;
554
+ _this._initDom();
555
+ _this.logger = new ConsoleLogger('WebRTCLogger', options.logLevel || LogLevel.OFF);
556
+ _this.deviceController = new DefaultDeviceController(_this.logger);
557
+ _this.initObservers();
558
+ return _this;
425
559
  }
426
560
  /**
427
561
  * 加入语音会议
428
562
  * @param options
429
563
  * @returns
430
564
  */
431
- async join(options) {
432
- return new Promise(async (success, fail) => {
433
- var _a;
434
- this.emit('joinWillStart');
435
- try {
436
- // 取签名
437
- const { sdkAppId, userId, roomId, userSig } = await this._getVoiceSign({
438
- ...options,
439
- roomId: options.roomId || 0,
440
- });
441
- this.userId = userId;
442
- const { attendence, vendor_wrapper, } = JSON.parse(decodeURIComponent(userSig));
443
- // 初始化配置
444
- const configuration = new MeetingSessionConfiguration({
445
- Meeting: vendor_wrapper,
446
- }, {
447
- Attendee: {
448
- ExternalUserId: attendence.external_user_id,
449
- AttendeeId: attendence.attendee_id,
450
- JoinToken: attendence.join_token,
451
- },
452
- });
453
- // 初始化会议会话
454
- this.meetingSession = new DefaultMeetingSession(configuration, this.logger, this.deviceController);
455
- // 注册事件
456
- this._registerRtcEvent();
457
- // 绑定监听器
458
- this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver);
459
- this.meetingSession.audioVideo.addObserver(this.audioVideoObserver);
460
- // 绑定播放器
461
- this.meetingSession.audioVideo.bindAudioElement(this.$audio);
462
- const observer = {
463
- audioVideoDidStart: () => {
464
- var _a;
465
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeMuteLocalAudio();
466
- this.joined = true;
467
- this.emit('joined');
468
- success(true);
469
- },
470
- audioVideoDidStop: () => {
471
- this.joined = false;
472
- success(false);
473
- },
474
- };
475
- this.meetingSession.audioVideo.addObserver(observer);
476
- // 选择语音输入设备
477
- const audioInputDevices = await this.deviceController.listAudioInputDevices(true);
478
- const defaultAudioInput = audioInputDevices.find((device) => device.deviceId === 'default');
479
- const otherAudioInput = audioInputDevices.find((device) => device.deviceId !== '');
480
- this.audioInput = defaultAudioInput || otherAudioInput;
481
- await this.meetingSession.audioVideo.chooseVideoInputDevice(null);
482
- await this.meetingSession.audioVideo.chooseAudioInputDevice(((_a = this.audioInput) === null || _a === void 0 ? void 0 : _a.deviceId) || 'default');
483
- this.meetingSession.audioVideo.start();
484
- }
485
- catch (e) {
486
- this.emit('error', e);
487
- this.logger.error(e.message);
488
- success(false);
489
- }
565
+ BrowserRTC4Chime.prototype.join = function (options) {
566
+ return __awaiter(this, void 0, void 0, function () {
567
+ var _this = this;
568
+ return __generator(this, function (_a) {
569
+ return [2 /*return*/, new Promise(function (success, fail) { return __awaiter(_this, void 0, void 0, function () {
570
+ var _a, userId, userSig, _b, attendence, vendor_wrapper, configuration, observer, audioInputDevices, defaultAudioInput, otherAudioInput, e_1;
571
+ var _this = this;
572
+ var _c;
573
+ return __generator(this, function (_d) {
574
+ switch (_d.label) {
575
+ case 0:
576
+ this.emit('joinWillStart');
577
+ _d.label = 1;
578
+ case 1:
579
+ _d.trys.push([1, 6, , 7]);
580
+ return [4 /*yield*/, this._getVoiceSign(__assign(__assign({}, options), { roomId: options.roomId || 0 }))];
581
+ case 2:
582
+ _a = _d.sent(), userId = _a.userId, userSig = _a.userSig;
583
+ this.userId = userId;
584
+ _b = JSON.parse(decodeURIComponent(userSig)), attendence = _b.attendence, vendor_wrapper = _b.vendor_wrapper;
585
+ configuration = new MeetingSessionConfiguration({
586
+ Meeting: vendor_wrapper,
587
+ }, {
588
+ Attendee: {
589
+ ExternalUserId: attendence.external_user_id,
590
+ AttendeeId: attendence.attendee_id,
591
+ JoinToken: attendence.join_token,
592
+ },
593
+ });
594
+ // 初始化会议会话
595
+ this.meetingSession = new DefaultMeetingSession(configuration, this.logger, this.deviceController);
596
+ // 注册事件
597
+ this._registerRtcEvent();
598
+ // 绑定监听器
599
+ this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver);
600
+ this.meetingSession.audioVideo.addObserver(this.audioVideoObserver);
601
+ // 绑定播放器
602
+ this.meetingSession.audioVideo.bindAudioElement(this.$audio);
603
+ observer = {
604
+ audioVideoDidStart: function () {
605
+ var _a;
606
+ (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeMuteLocalAudio();
607
+ _this.joined = true;
608
+ _this.emit('joined');
609
+ success(true);
610
+ },
611
+ audioVideoDidStop: function () {
612
+ _this.joined = false;
613
+ success(false);
614
+ },
615
+ };
616
+ this.meetingSession.audioVideo.addObserver(observer);
617
+ return [4 /*yield*/, this.deviceController.listAudioInputDevices(true)];
618
+ case 3:
619
+ audioInputDevices = _d.sent();
620
+ defaultAudioInput = audioInputDevices.find(function (device) { return device.deviceId === 'default'; });
621
+ otherAudioInput = audioInputDevices.find(function (device) { return device.deviceId !== ''; });
622
+ this.audioInput = defaultAudioInput || otherAudioInput;
623
+ return [4 /*yield*/, this.meetingSession.audioVideo.chooseVideoInputDevice(null)];
624
+ case 4:
625
+ _d.sent();
626
+ return [4 /*yield*/, this.meetingSession.audioVideo.chooseAudioInputDevice(((_c = this.audioInput) === null || _c === void 0 ? void 0 : _c.deviceId) || 'default')];
627
+ case 5:
628
+ _d.sent();
629
+ this.meetingSession.audioVideo.start();
630
+ return [3 /*break*/, 7];
631
+ case 6:
632
+ e_1 = _d.sent();
633
+ this.emit('error', e_1);
634
+ this.logger.error(e_1.message);
635
+ success(false);
636
+ return [3 /*break*/, 7];
637
+ case 7: return [2 /*return*/];
638
+ }
639
+ });
640
+ }); })];
641
+ });
490
642
  });
491
- }
492
- quit() {
643
+ };
644
+ BrowserRTC4Chime.prototype.quit = function () {
645
+ var _this = this;
493
646
  if (!this.joined)
494
647
  return Promise.resolve(true);
495
- return new Promise((success, fail) => {
648
+ return new Promise(function (success, fail) {
496
649
  var _a, _b;
497
- this.joined = false;
498
- const observer = {
499
- audioVideoDidStop: (sessionStatus) => {
500
- const sessionStatusCode = sessionStatus.statusCode();
650
+ _this.joined = false;
651
+ var observer = {
652
+ audioVideoDidStop: function (sessionStatus) {
653
+ var sessionStatusCode = sessionStatus.statusCode();
501
654
  if (sessionStatusCode === MeetingSessionStatusCode.Left) {
502
655
  /*
503
656
  - You called meetingSession.audioVideo.stop().
504
657
  - When closing a browser window or page, Chime SDK attempts to leave the session.
505
658
  */
506
- this.logger.info('You left the session');
659
+ _this.logger.info('You left the session');
507
660
  success(true);
508
661
  }
509
662
  else {
510
- this.logger.info(`Stopped with a session status code: ${sessionStatusCode}`);
663
+ _this.logger.info("Stopped with a session status code: ".concat(sessionStatusCode));
511
664
  success(true);
512
665
  }
513
666
  },
514
667
  };
515
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.addObserver(observer);
516
- (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.stop();
668
+ (_a = _this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.addObserver(observer);
669
+ (_b = _this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.stop();
517
670
  });
518
- }
519
- async detectMicro() {
520
- return new Promise((resolve) => {
521
- const rule = { audio: true, video: false };
522
- try {
523
- navigator.mediaDevices
524
- .getUserMedia(rule)
525
- .then(() => resolve(true))
526
- .catch(() => resolve(false));
527
- }
528
- catch (e) {
529
- this.logger.error(e.message);
530
- resolve(false);
531
- }
671
+ };
672
+ BrowserRTC4Chime.prototype.detectMicro = function () {
673
+ return __awaiter(this, void 0, void 0, function () {
674
+ var _this = this;
675
+ return __generator(this, function (_a) {
676
+ return [2 /*return*/, new Promise(function (resolve) {
677
+ var rule = { audio: true, video: false };
678
+ try {
679
+ navigator.mediaDevices
680
+ .getUserMedia(rule)
681
+ .then(function () { return resolve(true); })
682
+ .catch(function () { return resolve(false); });
683
+ }
684
+ catch (e) {
685
+ _this.logger.error(e.message);
686
+ resolve(false);
687
+ }
688
+ })];
689
+ });
532
690
  });
533
- }
534
- async toggleMicro(flag) {
691
+ };
692
+ BrowserRTC4Chime.prototype.toggleMicro = function (flag) {
535
693
  var _a, _b, _c;
536
- if (flag) {
537
- (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeUnmuteLocalAudio();
538
- }
539
- else {
540
- (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.realtimeMuteLocalAudio();
541
- }
542
- const muted = (_c = this.meetingSession) === null || _c === void 0 ? void 0 : _c.audioVideo.realtimeIsLocalAudioMuted();
543
- if (muted !== undefined) {
544
- return flag !== muted;
545
- }
546
- else {
547
- return false;
548
- }
549
- }
550
- shock() {
694
+ return __awaiter(this, void 0, void 0, function () {
695
+ var muted;
696
+ return __generator(this, function (_d) {
697
+ if (flag) {
698
+ (_a = this.meetingSession) === null || _a === void 0 ? void 0 : _a.audioVideo.realtimeUnmuteLocalAudio();
699
+ }
700
+ else {
701
+ (_b = this.meetingSession) === null || _b === void 0 ? void 0 : _b.audioVideo.realtimeMuteLocalAudio();
702
+ }
703
+ muted = (_c = this.meetingSession) === null || _c === void 0 ? void 0 : _c.audioVideo.realtimeIsLocalAudioMuted();
704
+ if (muted !== undefined) {
705
+ return [2 /*return*/, flag !== muted];
706
+ }
707
+ else {
708
+ return [2 /*return*/, false];
709
+ }
710
+ });
711
+ });
712
+ };
713
+ BrowserRTC4Chime.prototype.shock = function () {
551
714
  throw new Error('Method not implemented.');
552
- }
553
- }
715
+ };
716
+ return BrowserRTC4Chime;
717
+ }(CoreRTC));
554
718
 
555
719
  /**
556
720
  * rtc加入返回值code枚举
@@ -575,75 +739,122 @@ var RTCJoinedInfoCodeEnum;
575
739
  RTCJoinedInfoCodeEnum[RTCJoinedInfoCodeEnum["NoMicroPermission"] = 3] = "NoMicroPermission";
576
740
  })(RTCJoinedInfoCodeEnum || (RTCJoinedInfoCodeEnum = {}));
577
741
 
578
- class VRWebViewRTC extends CoreRTC {
579
- constructor({ jsBridge, getVoiceSign }) {
580
- super();
581
- this.type = RTCType.RealseeVRWebViewRTC;
582
- this.joined = false;
583
- this.micro = false;
584
- this.voiceId = '';
585
- this.options = { jsBridge, getVoiceSign };
586
- this.jsBridge.callAndListen('live/userVolumes', (userVolumes) => {
587
- this.emit('userVolumes', userVolumes);
742
+ var VRWebViewRTC = /** @class */ (function (_super) {
743
+ __extends(VRWebViewRTC, _super);
744
+ function VRWebViewRTC(_a) {
745
+ var jsBridge = _a.jsBridge, getVoiceSign = _a.getVoiceSign;
746
+ var _this = _super.call(this) || this;
747
+ _this.type = RTCType.RealseeVRWebViewRTC;
748
+ _this.joined = false;
749
+ _this.micro = false;
750
+ _this.voiceId = '';
751
+ _this.options = { jsBridge: jsBridge, getVoiceSign: getVoiceSign };
752
+ _this.jsBridge.callAndListen('live/userVolumes', function (userVolumes) {
753
+ _this.emit('userVolumes', userVolumes);
588
754
  });
589
- this.jsBridge.callAndListen('live/weakNetwork', (weakNetwork) => {
755
+ _this.jsBridge.callAndListen('live/weakNetwork', function (weakNetwork) {
590
756
  if (weakNetwork)
591
- this.emit('weakNetwork');
757
+ _this.emit('weakNetwork');
592
758
  });
759
+ return _this;
593
760
  }
594
- get jsBridge() {
595
- return this.options.jsBridge;
596
- }
597
- async join(options) {
598
- this.emit('joinWillStart');
599
- const { sdkAppId, userId, userSig } = await this.options.getVoiceSign(options);
600
- this.type = options.type;
601
- const [res, error] = await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${sdkAppId}&userID=${userId}&roomID=${Number(options.voiceId)}&userSig=${userSig}`);
602
- if (!res) {
603
- this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
604
- this.joined = false;
605
- }
606
- else {
607
- if (res.code === RTCJoinedInfoCodeEnum.Success) {
608
- this.emit('joined');
609
- this.joined = true;
610
- }
611
- else {
612
- this.emit('error', res);
613
- this.joined = false;
614
- }
615
- }
616
- return this.joined;
617
- }
618
- async quit() {
619
- const [res, error] = await this.jsBridge.callAndBackfeed('live/quit');
620
- if (res === null) {
621
- this.emit('error', error ? error : new Error('退出房间失败:未知异常。'));
622
- }
623
- this.joined = false;
624
- return !!res;
625
- }
626
- async detectMicro() {
627
- const [res, error] = await this.jsBridge.detectMicro();
628
- if (res === null) {
629
- this.emit('error', error ? error : new Error('麦克风监测异常!'));
630
- return false;
631
- }
632
- return res;
633
- }
634
- async toggleMicro(flag) {
635
- const [res, error] = await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${!!flag ? 1 : 0}`);
636
- if (res === null) {
637
- this.emit('error', error ? error : new Error('麦克风监测异常!'));
638
- return false;
639
- }
640
- this.micro = res;
641
- return res;
642
- }
643
- shock() {
761
+ Object.defineProperty(VRWebViewRTC.prototype, "jsBridge", {
762
+ get: function () {
763
+ return this.options.jsBridge;
764
+ },
765
+ enumerable: false,
766
+ configurable: true
767
+ });
768
+ VRWebViewRTC.prototype.join = function (options) {
769
+ return __awaiter(this, void 0, void 0, function () {
770
+ var _a, sdkAppId, userId, userSig, _b, res, error;
771
+ return __generator(this, function (_c) {
772
+ switch (_c.label) {
773
+ case 0:
774
+ this.emit('joinWillStart');
775
+ return [4 /*yield*/, this.options.getVoiceSign(options)];
776
+ case 1:
777
+ _a = _c.sent(), sdkAppId = _a.sdkAppId, userId = _a.userId, userSig = _a.userSig;
778
+ this.type = options.type;
779
+ return [4 /*yield*/, this.jsBridge.callAndBackfeed("live/join?sdkAppID=".concat(sdkAppId, "&userID=").concat(userId, "&roomID=").concat(Number(options.voiceId), "&userSig=").concat(userSig))];
780
+ case 2:
781
+ _b = _c.sent(), res = _b[0], error = _b[1];
782
+ if (!res) {
783
+ this.emit('error', error ? error : new Error('加入房间失败:未知异常。'));
784
+ this.joined = false;
785
+ }
786
+ else {
787
+ if (res.code === RTCJoinedInfoCodeEnum.Success) {
788
+ this.emit('joined');
789
+ this.joined = true;
790
+ }
791
+ else {
792
+ this.emit('error', res);
793
+ this.joined = false;
794
+ }
795
+ }
796
+ return [2 /*return*/, this.joined];
797
+ }
798
+ });
799
+ });
800
+ };
801
+ VRWebViewRTC.prototype.quit = function () {
802
+ return __awaiter(this, void 0, void 0, function () {
803
+ var _a, res, error;
804
+ return __generator(this, function (_b) {
805
+ switch (_b.label) {
806
+ case 0: return [4 /*yield*/, this.jsBridge.callAndBackfeed('live/quit')];
807
+ case 1:
808
+ _a = _b.sent(), res = _a[0], error = _a[1];
809
+ if (res === null) {
810
+ this.emit('error', error ? error : new Error('退出房间失败:未知异常。'));
811
+ }
812
+ this.joined = false;
813
+ return [2 /*return*/, !!res];
814
+ }
815
+ });
816
+ });
817
+ };
818
+ VRWebViewRTC.prototype.detectMicro = function () {
819
+ return __awaiter(this, void 0, void 0, function () {
820
+ var _a, res, error;
821
+ return __generator(this, function (_b) {
822
+ switch (_b.label) {
823
+ case 0: return [4 /*yield*/, this.jsBridge.detectMicro()];
824
+ case 1:
825
+ _a = _b.sent(), res = _a[0], error = _a[1];
826
+ if (res === null) {
827
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
828
+ return [2 /*return*/, false];
829
+ }
830
+ return [2 /*return*/, res];
831
+ }
832
+ });
833
+ });
834
+ };
835
+ VRWebViewRTC.prototype.toggleMicro = function (flag) {
836
+ return __awaiter(this, void 0, void 0, function () {
837
+ var _a, res, error;
838
+ return __generator(this, function (_b) {
839
+ switch (_b.label) {
840
+ case 0: return [4 /*yield*/, this.jsBridge.callAndBackfeed("live/toggleMicro?flag=".concat(!!flag ? 1 : 0))];
841
+ case 1:
842
+ _a = _b.sent(), res = _a[0], error = _a[1];
843
+ if (res === null) {
844
+ this.emit('error', error ? error : new Error('麦克风监测异常!'));
845
+ return [2 /*return*/, false];
846
+ }
847
+ this.micro = res;
848
+ return [2 /*return*/, res];
849
+ }
850
+ });
851
+ });
852
+ };
853
+ VRWebViewRTC.prototype.shock = function () {
644
854
  this.jsBridge.shock(1);
645
- }
646
- }
855
+ };
856
+ return VRWebViewRTC;
857
+ }(CoreRTC));
647
858
 
648
859
  /**
649
860
  * WebSocket 通信指令
@@ -728,8 +939,8 @@ var MicroStatus;
728
939
  */
729
940
  function parseLiveMsg(jsonTxt) {
730
941
  try {
731
- const msg = JSON.parse(jsonTxt);
732
- const resMsg = {
942
+ var msg = JSON.parse(jsonTxt);
943
+ var resMsg_1 = {
733
944
  code: msg.code,
734
945
  message: msg.message,
735
946
  command: msg.command,
@@ -740,11 +951,11 @@ function parseLiveMsg(jsonTxt) {
740
951
  triggerUserID: msg.trigger_user_id,
741
952
  data: msg.data || {},
742
953
  };
743
- const undefinedKeys = Object.keys(resMsg).filter((key) => resMsg[key] === undefined);
954
+ var undefinedKeys = Object.keys(resMsg_1).filter(function (key) { return resMsg_1[key] === undefined; });
744
955
  if (undefinedKeys.length > 0) {
745
- console.warn(`推送数据格式异常:${undefinedKeys.join(" ")} 值不存在!`);
956
+ console.warn("\u63A8\u9001\u6570\u636E\u683C\u5F0F\u5F02\u5E38\uFF1A".concat(undefinedKeys.join(" "), " \u503C\u4E0D\u5B58\u5728\uFF01"));
746
957
  }
747
- return resMsg;
958
+ return resMsg_1;
748
959
  }
749
960
  catch (error) {
750
961
  // notcare? 过滤掉所有不符合规范的数据
@@ -882,16 +1093,19 @@ function parseWSClsErr(code) {
882
1093
  }
883
1094
 
884
1095
  function appendUri(uri, query) {
885
- const hasQuery = uri.indexOf('?') !== -1;
886
- const newQuery = Object.keys(query).reduce((accu, curr, idx) => `${accu}${(idx === 0 && !hasQuery) ? '?' : '&'}${curr}=${query[curr]}`, '');
1096
+ if (query === void 0) { query = {}; }
1097
+ var hasQuery = uri.indexOf('?') !== -1;
1098
+ var newQuery = Object.keys(query).reduce(function (accu, curr, idx) {
1099
+ return "".concat(accu).concat((idx === 0 && !hasQuery) ? '?' : '&').concat(curr, "=").concat(query[curr]);
1100
+ }, '');
887
1101
  return uri + newQuery;
888
1102
  }
889
1103
 
890
- const userAgent = globalThis.navigator.userAgent;
891
- const isAndroid = /android/gi.test(userAgent);
892
- const isIOS = /iPhone|iPad\s+OS/gi.test(userAgent);
893
- const isWxMiniProgram = /MicroMessenger/gi.test(userAgent) && /miniProgram/gi.test(userAgent);
894
- const isRealseeVRWebview = /realsee/gi.test(userAgent);
1104
+ var userAgent = globalThis.navigator.userAgent;
1105
+ var isAndroid = /android/gi.test(userAgent);
1106
+ var isIOS = /iPhone|iPad\s+OS/gi.test(userAgent);
1107
+ var isWxMiniProgram = /MicroMessenger/gi.test(userAgent) && /miniProgram/gi.test(userAgent);
1108
+ var isRealseeVRWebview = /realsee/gi.test(userAgent);
895
1109
 
896
1110
  /**
897
1111
  * 判断是否是真实的对象类型
@@ -923,12 +1137,12 @@ function baseIsEqual(value, other) {
923
1137
  * @returns
924
1138
  */
925
1139
  function objEqualShallow(value, other) {
926
- const valueProps = Object.getOwnPropertyNames(value);
927
- const otherProps = Object.getOwnPropertyNames(other);
1140
+ var valueProps = Object.getOwnPropertyNames(value);
1141
+ var otherProps = Object.getOwnPropertyNames(other);
928
1142
  if (valueProps.length !== otherProps.length)
929
1143
  return false;
930
- for (let i = 0, len = valueProps.length; i < len; i++) {
931
- const propName = valueProps[i];
1144
+ for (var i = 0, len = valueProps.length; i < len; i++) {
1145
+ var propName = valueProps[i];
932
1146
  if (!baseIsEqual(value[propName], other[propName]))
933
1147
  return false;
934
1148
  }
@@ -943,7 +1157,7 @@ function objEqualShallow(value, other) {
943
1157
  function arrayEqualShallow(value, other) {
944
1158
  if (value.length !== other.length)
945
1159
  return false;
946
- for (let i = 0, len = value.length; i < len; i++) {
1160
+ for (var i = 0, len = value.length; i < len; i++) {
947
1161
  if (!baseIsEqual(value[i], other[i]))
948
1162
  return false;
949
1163
  }
@@ -988,7 +1202,7 @@ function isDeepEqual(value, other) {
988
1202
  function arrayEqualDeep(value, other) {
989
1203
  if (value.length !== other.length)
990
1204
  return false;
991
- for (let i = 0, len = value.length; i < len; i++) {
1205
+ for (var i = 0, len = value.length; i < len; i++) {
992
1206
  if (!isDeepEqual(value[i], other[i]))
993
1207
  return false;
994
1208
  }
@@ -1001,12 +1215,12 @@ function arrayEqualDeep(value, other) {
1001
1215
  * @returns
1002
1216
  */
1003
1217
  function objEqualDeep(value, other) {
1004
- const valueProps = Object.getOwnPropertyNames(value);
1005
- const otherProps = Object.getOwnPropertyNames(other);
1218
+ var valueProps = Object.getOwnPropertyNames(value);
1219
+ var otherProps = Object.getOwnPropertyNames(other);
1006
1220
  if (valueProps.length !== otherProps.length)
1007
1221
  return false;
1008
- for (let i = 0, len = valueProps.length; i < len; i++) {
1009
- const propName = valueProps[i];
1222
+ for (var i = 0, len = valueProps.length; i < len; i++) {
1223
+ var propName = valueProps[i];
1010
1224
  if (!isDeepEqual(value[propName], other[propName]))
1011
1225
  return false;
1012
1226
  }
@@ -1020,13 +1234,15 @@ function objEqualDeep(value, other) {
1020
1234
  * @returns {boolean} 是否相等。
1021
1235
  */
1022
1236
  function equal(value, other, opt) {
1237
+ if (opt === void 0) { opt = { deep: false }; }
1023
1238
  if (!opt.deep)
1024
1239
  return isShallowEqual(value, other);
1025
1240
  return isDeepEqual(value, other);
1026
1241
  }
1027
1242
 
1028
- class LiveController {
1029
- constructor(options) {
1243
+ var LiveController = /** @class */ (function () {
1244
+ function LiveController(options) {
1245
+ var _this = this;
1030
1246
  this.readyState = WebSocketState.NOTINITIALIZED;
1031
1247
  this.canSync = true;
1032
1248
  this.connecting = false;
@@ -1034,56 +1250,56 @@ class LiveController {
1034
1250
  /**
1035
1251
  * 检测 WebSocket.readyState 状态
1036
1252
  */
1037
- this.checkReadyState = (live) => {
1253
+ this.checkReadyState = function (live) {
1038
1254
  do {
1039
- if (!this.webSocket) {
1040
- if (this.readyState !== WebSocketState.NOTINITIALIZED) {
1041
- this.readyState = WebSocketState.NOTINITIALIZED;
1042
- live.emit('ws.readyStateUpdate', this.readyState);
1255
+ if (!_this.webSocket) {
1256
+ if (_this.readyState !== WebSocketState.NOTINITIALIZED) {
1257
+ _this.readyState = WebSocketState.NOTINITIALIZED;
1258
+ live.emit('ws.readyStateUpdate', _this.readyState);
1043
1259
  }
1044
1260
  break;
1045
1261
  }
1046
- const readyState = this.webSocket.readyState;
1047
- if (readyState !== this.readyState) {
1048
- this.readyState = readyState;
1049
- live.emit('ws.readyStateUpdate', this.readyState);
1262
+ var readyState = _this.webSocket.readyState;
1263
+ if (readyState !== _this.readyState) {
1264
+ _this.readyState = readyState;
1265
+ live.emit('ws.readyStateUpdate', _this.readyState);
1050
1266
  }
1051
1267
  } while (false);
1052
- return this.readyState;
1268
+ return _this.readyState;
1053
1269
  };
1054
- this.dispose = () => {
1055
- this.disposeWebSocket();
1056
- this.connecting = false;
1057
- if (this.healthCheckId) {
1058
- clearInterval(this.healthCheckId);
1059
- this.healthCheckId = undefined;
1270
+ this.dispose = function () {
1271
+ _this.disposeWebSocket();
1272
+ _this.connecting = false;
1273
+ if (_this.healthCheckId) {
1274
+ clearInterval(_this.healthCheckId);
1275
+ _this.healthCheckId = undefined;
1060
1276
  }
1061
1277
  return true;
1062
1278
  };
1063
1279
  /**
1064
1280
  * 销毁WebSocket相关依赖。
1065
1281
  */
1066
- this.disposeWebSocket = () => {
1067
- if (!this.webSocket)
1282
+ this.disposeWebSocket = function () {
1283
+ if (!_this.webSocket)
1068
1284
  return;
1069
- if (this.onEvtOpnListener) {
1070
- this.webSocket.removeEventListener('open', this.onEvtOpnListener);
1071
- this.onEvtOpnListener = undefined;
1285
+ if (_this.onEvtOpnListener) {
1286
+ _this.webSocket.removeEventListener('open', _this.onEvtOpnListener);
1287
+ _this.onEvtOpnListener = undefined;
1072
1288
  }
1073
- if (this.onEvtMsgListener) {
1074
- this.webSocket.removeEventListener('message', this.onEvtMsgListener);
1075
- this.onEvtMsgListener = undefined;
1289
+ if (_this.onEvtMsgListener) {
1290
+ _this.webSocket.removeEventListener('message', _this.onEvtMsgListener);
1291
+ _this.onEvtMsgListener = undefined;
1076
1292
  }
1077
- if (this.onEvtErrListener) {
1078
- this.webSocket.removeEventListener('error', this.onEvtErrListener);
1079
- this.onEvtErrListener = undefined;
1293
+ if (_this.onEvtErrListener) {
1294
+ _this.webSocket.removeEventListener('error', _this.onEvtErrListener);
1295
+ _this.onEvtErrListener = undefined;
1080
1296
  }
1081
- if (this.onEvtCLEListener) {
1082
- this.webSocket.removeEventListener('close', this.onEvtCLEListener);
1083
- this.onEvtCLEListener = undefined;
1297
+ if (_this.onEvtCLEListener) {
1298
+ _this.webSocket.removeEventListener('close', _this.onEvtCLEListener);
1299
+ _this.onEvtCLEListener = undefined;
1084
1300
  }
1085
- this.webSocket.close();
1086
- this.webSocket = undefined;
1301
+ _this.webSocket.close();
1302
+ _this.webSocket = undefined;
1087
1303
  return true;
1088
1304
  };
1089
1305
  this.options = Object.assign({ autoConnect: true, healthCheck: 3000 }, options);
@@ -1093,16 +1309,17 @@ class LiveController {
1093
1309
  * @param liveMsg
1094
1310
  * @param live
1095
1311
  */
1096
- handleMessage(liveMsg, live) {
1312
+ LiveController.prototype.handleMessage = function (liveMsg, live) {
1313
+ var _this = this;
1097
1314
  var _a, _b, _c;
1098
- const { command, data, frontRequestId, code, message } = liveMsg;
1315
+ var command = liveMsg.command, data = liveMsg.data, frontRequestId = liveMsg.frontRequestId, code = liveMsg.code;
1099
1316
  if (code === 'SUCCESS') {
1100
1317
  switch (command) {
1101
1318
  /**
1102
1319
  * 自己的状态变化
1103
1320
  */
1104
1321
  case Command.SelfUserInfo: {
1105
- const selfInfo = data;
1322
+ var selfInfo = data;
1106
1323
  if (equal(this.selfUserInfo, selfInfo, { deep: true }))
1107
1324
  return;
1108
1325
  this.selfUserInfo = selfInfo;
@@ -1113,7 +1330,7 @@ class LiveController {
1113
1330
  * 房间信息变化
1114
1331
  */
1115
1332
  case Command.RoomInfo: {
1116
- const roomInfo = data;
1333
+ var roomInfo = data;
1117
1334
  this.roomInfo = Object.assign({}, roomInfo);
1118
1335
  live.emit('readyKeyframeSync', (roomInfo.last_frame || {}));
1119
1336
  break;
@@ -1122,16 +1339,16 @@ class LiveController {
1122
1339
  * 语音信息变化
1123
1340
  */
1124
1341
  case Command.RTCInfo: {
1125
- const { voice_id: voiceId, type } = data;
1342
+ var _d = data, voiceId = _d.voice_id, type = _d.type;
1126
1343
  /* 如果已经进入语音房间,则不重复进入 --> "RTCInfo" 指令可能会下发多次 */
1127
1344
  if (live.$RTC.joined) {
1128
1345
  break;
1129
1346
  }
1130
1347
  live.$RTC.join({
1131
- voiceId,
1348
+ voiceId: voiceId,
1132
1349
  userId: ((_a = this.selfUserInfo) === null || _a === void 0 ? void 0 : _a.id) || '',
1133
1350
  roomId: (_b = this.roomInfo) === null || _b === void 0 ? void 0 : _b.info.room_code,
1134
- type,
1351
+ type: type,
1135
1352
  });
1136
1353
  // 加入房间后 麦克风默认就开启了:需要发个指令。
1137
1354
  live.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
@@ -1143,7 +1360,7 @@ class LiveController {
1143
1360
  * 房间用户列表变化
1144
1361
  */
1145
1362
  case Command.UserList: {
1146
- const userList = data;
1363
+ var userList = data;
1147
1364
  this.userList = userList;
1148
1365
  live.emit('userListUpdate', this.userList, frontRequestId);
1149
1366
  break;
@@ -1152,7 +1369,7 @@ class LiveController {
1152
1369
  * 自定义事件广播
1153
1370
  */
1154
1371
  case Command.CustomEvent: {
1155
- const evtMsg = data;
1372
+ var evtMsg = data;
1156
1373
  live.emit('broadcast', evtMsg, frontRequestId);
1157
1374
  break;
1158
1375
  }
@@ -1160,21 +1377,22 @@ class LiveController {
1160
1377
  * 帧数据同步
1161
1378
  */
1162
1379
  case Command.KeyframeSync: {
1163
- const remoteKeyframes = data;
1380
+ var remoteKeyframes_1 = data;
1164
1381
  // 此处做一层 diff,仅跟本地数据不一致的情况下才广播数据。
1165
- const keyframes = Object.keys(remoteKeyframes).reduce((accu, curr) => {
1166
- if (equal(remoteKeyframes[curr], this.keyframes[curr], { deep: true })) {
1382
+ var keyframes = Object.keys(remoteKeyframes_1).reduce(function (accu, curr) {
1383
+ var _a;
1384
+ if (equal(remoteKeyframes_1[curr], _this.keyframes[curr], { deep: true })) {
1167
1385
  return accu;
1168
1386
  }
1169
- const params = [
1170
- remoteKeyframes[curr],
1171
- this.keyframes[curr],
1387
+ var params = [
1388
+ remoteKeyframes_1[curr],
1389
+ _this.keyframes[curr],
1172
1390
  frontRequestId,
1173
1391
  ];
1174
- const evtName = curr;
1175
- live.keyframes.emit(evtName, ...params);
1176
- this.keyframes[curr] = remoteKeyframes[curr];
1177
- accu[curr] = remoteKeyframes[curr];
1392
+ var evtName = curr;
1393
+ (_a = live.keyframes).emit.apply(_a, __spreadArray([evtName], params, false));
1394
+ _this.keyframes[curr] = remoteKeyframes_1[curr];
1395
+ accu[curr] = remoteKeyframes_1[curr];
1178
1396
  return accu;
1179
1397
  }, {});
1180
1398
  live.emit('keyframes', keyframes, frontRequestId);
@@ -1184,7 +1402,7 @@ class LiveController {
1184
1402
  * 内置消息
1185
1403
  */
1186
1404
  case Command.BuiltinMsg: {
1187
- const builtinMsg = data;
1405
+ var builtinMsg = data;
1188
1406
  live.emit('builtinEvent', builtinMsg);
1189
1407
  if (builtinMsg.event_type === BuiltinEventType.UserChange) {
1190
1408
  live.emit('userChange', builtinMsg);
@@ -1227,27 +1445,31 @@ class LiveController {
1227
1445
  else {
1228
1446
  live.emit('error', liveMsg);
1229
1447
  }
1230
- }
1448
+ };
1231
1449
  /**
1232
1450
  * 发送数据
1233
1451
  * @param data
1234
1452
  */
1235
- sendMessage(data) {
1453
+ LiveController.prototype.sendMessage = function (data) {
1236
1454
  if (!this.webSocket)
1237
1455
  return console.warn('WebSocket has not yet been initialized!');
1238
1456
  if (!data)
1239
1457
  return console.warn('WebSocket messages is empty!');
1240
1458
  this.webSocket.send(JSON.stringify(data));
1241
- }
1242
- }
1459
+ };
1460
+ return LiveController;
1461
+ }());
1243
1462
 
1244
- const unimplementedGetVoiceSign = (params) => Promise.reject('unimplemented method GetVoiceSign');
1463
+ var unimplementedGetVoiceSign = function (params) {
1464
+ return Promise.reject('unimplemented method GetVoiceSign');
1465
+ };
1245
1466
  /**
1246
1467
  * 创建 `live` 实例。
1247
1468
  */
1248
1469
  function createLive(options) {
1249
- const liveController = new LiveController(options);
1250
- const createLiveMsg = (command, data = {}, toUserIds) => {
1470
+ var liveController = new LiveController(options);
1471
+ var createLiveMsg = function (command, data, toUserIds) {
1472
+ if (data === void 0) { data = {}; }
1251
1473
  toUserIds = toUserIds
1252
1474
  ? Array.isArray(toUserIds)
1253
1475
  ? toUserIds
@@ -1255,14 +1477,16 @@ function createLive(options) {
1255
1477
  : [];
1256
1478
  if (toUserIds)
1257
1479
  data['to_user_ids'] = toUserIds;
1258
- return { command, front_request_id: uuid(), data };
1480
+ return { command: command, front_request_id: uuid(), data: data };
1259
1481
  };
1260
- class LiveTpl extends Subscribe {
1261
- constructor() {
1482
+ var LiveTpl = /** @class */ (function (_super) {
1483
+ __extends(LiveTpl, _super);
1484
+ function LiveTpl() {
1485
+ var _this = this;
1262
1486
  var _a, _b;
1263
- super();
1264
- this.keyframes = new Subscribe();
1265
- const jsBridge = (() => {
1487
+ _this = _super.call(this) || this;
1488
+ _this.keyframes = new Subscribe();
1489
+ var jsBridge = (function () {
1266
1490
  if (options.jsBridge)
1267
1491
  return options.jsBridge;
1268
1492
  if (options.useBuiltInJsBridge)
@@ -1277,7 +1501,7 @@ function createLive(options) {
1277
1501
  if (!options.getVoiceSign) {
1278
1502
  throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
1279
1503
  }
1280
- const getVoiceSign = (_a = options.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
1504
+ var getVoiceSign = (_a = options.getVoiceSign) !== null && _a !== void 0 ? _a : unimplementedGetVoiceSign;
1281
1505
  switch (options.rtcType) {
1282
1506
  case RTCType.RealseeVRWebViewRTC: {
1283
1507
  // 内置的 VRWebViewRTC
@@ -1285,15 +1509,15 @@ function createLive(options) {
1285
1509
  throw new Error('JsBridge instance must be passed when using built-in VRWebViewRTC instances');
1286
1510
  }
1287
1511
  liveController.options.rtc = new VRWebViewRTC({
1288
- jsBridge,
1289
- getVoiceSign,
1512
+ jsBridge: jsBridge,
1513
+ getVoiceSign: getVoiceSign,
1290
1514
  });
1291
1515
  break;
1292
1516
  }
1293
1517
  case RTCType.RealseeBrowserChimeRTC: {
1294
1518
  // 内置的 RealseeBrowserChimeRTC
1295
1519
  liveController.options.rtc = new BrowserRTC4Chime({
1296
- getVoiceSign,
1520
+ getVoiceSign: getVoiceSign,
1297
1521
  logLevel: options.__debug__ ? LogLevel.DEBUG : LogLevel.ERROR,
1298
1522
  });
1299
1523
  break;
@@ -1301,7 +1525,7 @@ function createLive(options) {
1301
1525
  case RTCType.RealseeBrowserRTC: {
1302
1526
  // 内置的 RealseeBrowserRTC
1303
1527
  liveController.options.rtc = new BrowserRTC({
1304
- getVoiceSign,
1528
+ getVoiceSign: getVoiceSign,
1305
1529
  });
1306
1530
  break;
1307
1531
  }
@@ -1315,23 +1539,23 @@ function createLive(options) {
1315
1539
  if (!options.getVoiceSign) {
1316
1540
  throw new Error('GetVoiceSign method must be passed when using built-in RTC instances');
1317
1541
  }
1318
- const getVoiceSign = (_b = options.getVoiceSign) !== null && _b !== void 0 ? _b : unimplementedGetVoiceSign;
1542
+ var getVoiceSign = (_b = options.getVoiceSign) !== null && _b !== void 0 ? _b : unimplementedGetVoiceSign;
1319
1543
  if (!jsBridge) {
1320
1544
  throw new Error('jsBridge instance must be passed when using built-in RTC instances');
1321
1545
  }
1322
1546
  // vrwebview 默认
1323
1547
  if ((isRealseeVRWebview && (isAndroid || isIOS)) || isWxMiniProgram) {
1324
1548
  liveController.options.rtc = new VRWebViewRTC({
1325
- jsBridge,
1326
- getVoiceSign,
1549
+ jsBridge: jsBridge,
1550
+ getVoiceSign: getVoiceSign,
1327
1551
  });
1328
1552
  }
1329
1553
  else {
1330
1554
  // 其它终端使用
1331
1555
  liveController.options.rtc =
1332
1556
  options.builtInRTCType === BuiltInRTCType.RealseeXChimeRTC
1333
- ? new BrowserRTC4Chime({ getVoiceSign })
1334
- : new BrowserRTC({ getVoiceSign });
1557
+ ? new BrowserRTC4Chime({ getVoiceSign: getVoiceSign })
1558
+ : new BrowserRTC({ getVoiceSign: getVoiceSign });
1335
1559
  }
1336
1560
  }
1337
1561
  }
@@ -1340,288 +1564,407 @@ function createLive(options) {
1340
1564
  }
1341
1565
  // 默认自动连接
1342
1566
  if (liveController.options.url && liveController.options.getTicket) {
1343
- this.connect();
1567
+ _this.connect();
1344
1568
  }
1345
1569
  // 健康检查:WHY --> 在某些WebView特殊场景下 WebSocket.readyState 发生变化时不会出发error\close等事件;
1346
1570
  // 因此,开启一个定时任务监测 WebSocket.readyState 状态的更新
1347
- const healthCheck = ((healthCheck) => {
1571
+ var healthCheck = (function (healthCheck) {
1348
1572
  if (!healthCheck)
1349
1573
  return 0;
1350
1574
  if (healthCheck === true)
1351
1575
  return 3000;
1352
- const duration = Number(healthCheck);
1576
+ var duration = Number(healthCheck);
1353
1577
  if (duration > 0)
1354
1578
  return duration;
1355
1579
  return 3000;
1356
1580
  })(liveController.options.healthCheck);
1357
1581
  if (healthCheck) {
1358
- liveController.healthCheckId = setInterval(() => liveController.checkReadyState(this), healthCheck);
1359
- }
1360
- }
1361
- get options() {
1362
- return Object.freeze(Object.assign({}, liveController.options));
1363
- }
1364
- get readyState() {
1365
- liveController.checkReadyState(this);
1366
- return liveController.readyState;
1367
- }
1368
- get url() {
1369
- var _a;
1370
- return ((_a = liveController.webSocket) === null || _a === void 0 ? void 0 : _a.url) || '';
1371
- }
1372
- get selfInfo() {
1373
- return liveController.selfUserInfo;
1374
- }
1375
- get userList() {
1376
- return liveController.userList || [];
1377
- }
1378
- get snapshot() {
1379
- return liveController.keyframes || {};
1380
- }
1381
- get $RTC() {
1382
- return liveController.options.rtc;
1383
- }
1384
- get jsBridge() {
1385
- return liveController.options.jsBridge;
1386
- }
1387
- async setSelfInfo(userInfo) {
1388
- if (this.readyState !== WebSocketState.OPEN) {
1389
- return new Error('The connection is not open and ready to communicate.');
1390
- }
1391
- try {
1392
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserInfo, userInfo);
1393
- }
1394
- catch (error) {
1395
- return error;
1582
+ liveController.healthCheckId = setInterval(function () { return liveController.checkReadyState(_this); }, healthCheck);
1396
1583
  }
1584
+ return _this;
1397
1585
  }
1398
- getFramesByKey(key) {
1586
+ Object.defineProperty(LiveTpl.prototype, "options", {
1587
+ get: function () {
1588
+ return Object.freeze(Object.assign({}, liveController.options));
1589
+ },
1590
+ enumerable: false,
1591
+ configurable: true
1592
+ });
1593
+ Object.defineProperty(LiveTpl.prototype, "readyState", {
1594
+ get: function () {
1595
+ liveController.checkReadyState(this);
1596
+ return liveController.readyState;
1597
+ },
1598
+ enumerable: false,
1599
+ configurable: true
1600
+ });
1601
+ Object.defineProperty(LiveTpl.prototype, "url", {
1602
+ get: function () {
1603
+ var _a;
1604
+ return ((_a = liveController.webSocket) === null || _a === void 0 ? void 0 : _a.url) || '';
1605
+ },
1606
+ enumerable: false,
1607
+ configurable: true
1608
+ });
1609
+ Object.defineProperty(LiveTpl.prototype, "selfInfo", {
1610
+ get: function () {
1611
+ return liveController.selfUserInfo;
1612
+ },
1613
+ enumerable: false,
1614
+ configurable: true
1615
+ });
1616
+ Object.defineProperty(LiveTpl.prototype, "userList", {
1617
+ get: function () {
1618
+ return liveController.userList || [];
1619
+ },
1620
+ enumerable: false,
1621
+ configurable: true
1622
+ });
1623
+ Object.defineProperty(LiveTpl.prototype, "snapshot", {
1624
+ get: function () {
1625
+ return liveController.keyframes || {};
1626
+ },
1627
+ enumerable: false,
1628
+ configurable: true
1629
+ });
1630
+ Object.defineProperty(LiveTpl.prototype, "$RTC", {
1631
+ get: function () {
1632
+ return liveController.options.rtc;
1633
+ },
1634
+ enumerable: false,
1635
+ configurable: true
1636
+ });
1637
+ Object.defineProperty(LiveTpl.prototype, "jsBridge", {
1638
+ get: function () {
1639
+ return liveController.options.jsBridge;
1640
+ },
1641
+ enumerable: false,
1642
+ configurable: true
1643
+ });
1644
+ LiveTpl.prototype.setSelfInfo = function (userInfo) {
1645
+ return __awaiter(this, void 0, void 0, function () {
1646
+ var error_1;
1647
+ return __generator(this, function (_a) {
1648
+ switch (_a.label) {
1649
+ case 0:
1650
+ if (this.readyState !== WebSocketState.OPEN) {
1651
+ return [2 /*return*/, new Error('The connection is not open and ready to communicate.')];
1652
+ }
1653
+ _a.label = 1;
1654
+ case 1:
1655
+ _a.trys.push([1, 3, , 4]);
1656
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserInfo, userInfo)];
1657
+ case 2: return [2 /*return*/, _a.sent()];
1658
+ case 3:
1659
+ error_1 = _a.sent();
1660
+ return [2 /*return*/, error_1];
1661
+ case 4: return [2 /*return*/];
1662
+ }
1663
+ });
1664
+ });
1665
+ };
1666
+ LiveTpl.prototype.getFramesByKey = function (key) {
1399
1667
  return liveController.keyframes[key];
1400
- }
1401
- sendKeyframe(key, frame) {
1668
+ };
1669
+ LiveTpl.prototype.sendKeyframe = function (key, frame) {
1402
1670
  if (this.readyState !== WebSocketState.OPEN) {
1403
1671
  return new Error('The connection is not open and ready to communicate.');
1404
1672
  }
1405
1673
  liveController.keyframes[key] = frame;
1406
- const liveMsg = createLiveMsg(Command.KeyframeSync, this.snapshot);
1674
+ var liveMsg = createLiveMsg(Command.KeyframeSync, this.snapshot);
1407
1675
  liveController.sendMessage(liveMsg);
1408
1676
  return true;
1409
- }
1410
- broadcast(data, toUserIds, timeout) {
1677
+ };
1678
+ LiveTpl.prototype.broadcast = function (data, toUserIds, timeout) {
1679
+ var _this = this;
1411
1680
  if (this.readyState !== WebSocketState.OPEN) {
1412
1681
  return new Error('The connection is not open and ready to communicate.');
1413
1682
  }
1414
- return new Promise((resolve, reject) => {
1415
- const customEvent = createLiveMsg(Command.CustomEvent, data, toUserIds);
1416
- const front_request_id = customEvent.front_request_id;
1683
+ return new Promise(function (resolve, reject) {
1684
+ var customEvent = createLiveMsg(Command.CustomEvent, data, toUserIds);
1685
+ var front_request_id = customEvent.front_request_id;
1417
1686
  liveController.sendMessage(customEvent);
1418
- const timeoutId = timeout
1419
- ? setTimeout(() => {
1687
+ var timeoutId = timeout
1688
+ ? setTimeout(function () {
1420
1689
  reject(new Error('RESPONSE TIMEOUT'));
1421
- this.off('broadcast', broadcast);
1690
+ _this.off('broadcast', broadcast);
1422
1691
  }, timeout)
1423
1692
  : undefined;
1424
- const broadcast = (data, frontRequestId) => {
1693
+ var broadcast = function (data, frontRequestId) {
1425
1694
  if (frontRequestId !== front_request_id)
1426
1695
  return;
1427
- this.off('broadcast', broadcast);
1696
+ _this.off('broadcast', broadcast);
1428
1697
  resolve(data);
1429
1698
  if (timeoutId)
1430
1699
  clearInterval(timeoutId);
1431
1700
  };
1432
- this.on('broadcast', broadcast);
1701
+ _this.on('broadcast', broadcast);
1433
1702
  });
1434
- }
1435
- async updateStatus(evtType, atnType, status, toUserIds) {
1436
- // TODO 统一规则,不能联合类型
1437
- if (this.readyState !== WebSocketState.OPEN) {
1438
- return false;
1439
- }
1440
- const data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
1441
- const liveMsg = createLiveMsg(Command.BuiltinMsg, data, toUserIds);
1442
- liveController.sendMessage(liveMsg);
1443
- return true;
1444
- }
1703
+ };
1704
+ LiveTpl.prototype.updateStatus = function (evtType, atnType, status, toUserIds) {
1705
+ return __awaiter(this, void 0, void 0, function () {
1706
+ var data, liveMsg;
1707
+ return __generator(this, function (_a) {
1708
+ // TODO 统一规则,不能联合类型
1709
+ if (this.readyState !== WebSocketState.OPEN) {
1710
+ return [2 /*return*/, false];
1711
+ }
1712
+ data = Object.assign({ event_type: evtType, action: atnType }, { data: status });
1713
+ liveMsg = createLiveMsg(Command.BuiltinMsg, data, toUserIds);
1714
+ liveController.sendMessage(liveMsg);
1715
+ return [2 /*return*/, true];
1716
+ });
1717
+ });
1718
+ };
1445
1719
  // 仅用于用户自己的麦克风控制
1446
- async toggleMicro(microStatus) {
1720
+ LiveTpl.prototype.toggleMicro = function (microStatus) {
1447
1721
  var _a, _b;
1448
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_own_micro))
1449
- return false;
1450
- await this.$RTC.toggleMicro(microStatus);
1451
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1452
- status: microStatus ? MicroStatus.OPEN : MicroStatus.CLOSE,
1453
- }, []);
1454
- }
1455
- async forbidMicro(microStatus, toUserIds) {
1722
+ return __awaiter(this, void 0, void 0, function () {
1723
+ return __generator(this, function (_c) {
1724
+ switch (_c.label) {
1725
+ case 0:
1726
+ if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_own_micro))
1727
+ return [2 /*return*/, false];
1728
+ return [4 /*yield*/, this.$RTC.toggleMicro(microStatus)];
1729
+ case 1:
1730
+ _c.sent();
1731
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1732
+ status: microStatus ? MicroStatus.OPEN : MicroStatus.CLOSE,
1733
+ }, [])];
1734
+ case 2: return [2 /*return*/, _c.sent()];
1735
+ }
1736
+ });
1737
+ });
1738
+ };
1739
+ LiveTpl.prototype.forbidMicro = function (microStatus, toUserIds) {
1456
1740
  var _a, _b;
1457
- if (liveController.options.canForbidUserMicro &&
1458
- !liveController.options.canForbidUserMicro(toUserIds)) {
1459
- return false;
1460
- }
1461
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_micro)) {
1462
- return false;
1463
- }
1464
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1465
- status: microStatus,
1466
- }, toUserIds);
1467
- }
1741
+ return __awaiter(this, void 0, void 0, function () {
1742
+ return __generator(this, function (_c) {
1743
+ switch (_c.label) {
1744
+ case 0:
1745
+ if (liveController.options.canForbidUserMicro &&
1746
+ !liveController.options.canForbidUserMicro(toUserIds)) {
1747
+ return [2 /*return*/, false];
1748
+ }
1749
+ if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_micro)) {
1750
+ return [2 /*return*/, false];
1751
+ }
1752
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserMicroStatus, {
1753
+ status: microStatus,
1754
+ }, toUserIds)];
1755
+ case 1: return [2 /*return*/, _c.sent()];
1756
+ }
1757
+ });
1758
+ });
1759
+ };
1468
1760
  /**
1469
1761
  * @deprecated 暂不可用
1470
1762
  */
1471
- async forbidSync(sync, toUserIds) {
1763
+ LiveTpl.prototype.forbidSync = function (sync, toUserIds) {
1472
1764
  var _a, _b;
1473
- if (liveController.options.canForbidUserSync &&
1474
- !liveController.options.canForbidUserSync(toUserIds)) {
1475
- return false;
1476
- }
1477
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_sync)) {
1478
- return false;
1479
- }
1480
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds);
1481
- }
1482
- async kick(toUserIds) {
1765
+ return __awaiter(this, void 0, void 0, function () {
1766
+ return __generator(this, function (_c) {
1767
+ switch (_c.label) {
1768
+ case 0:
1769
+ if (liveController.options.canForbidUserSync &&
1770
+ !liveController.options.canForbidUserSync(toUserIds)) {
1771
+ return [2 /*return*/, false];
1772
+ }
1773
+ if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.control_other_sync)) {
1774
+ return [2 /*return*/, false];
1775
+ }
1776
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserPermission, { sync_frame: sync }, toUserIds)];
1777
+ case 1: return [2 /*return*/, _c.sent()];
1778
+ }
1779
+ });
1780
+ });
1781
+ };
1782
+ LiveTpl.prototype.kick = function (toUserIds) {
1483
1783
  var _a, _b;
1484
- if (liveController.options.canForbidUserKick &&
1485
- !liveController.options.canForbidUserKick(toUserIds)) {
1486
- return false;
1487
- }
1488
- if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.change_other_status)) {
1489
- return false;
1490
- }
1491
- return await this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserStatus, {
1492
- status: 'KICK_OUT',
1493
- }, toUserIds);
1494
- }
1495
- async exit() {
1496
- /** 退出强制关闭语音(?) */
1497
- try {
1498
- this.$RTC.quit();
1499
- await this.updateStatus(BuiltinEventType.RoomChange, BuiltinActionType.RoomClose, {});
1500
- }
1501
- catch (e) {
1502
- console.log(e);
1503
- }
1504
- return liveController.dispose();
1505
- }
1506
- async connect(options = {}) {
1507
- // 连接 WebSocket 前验证麦克风权限
1508
- const microAuth = await this.$RTC.detectMicro();
1509
- if (!microAuth) {
1510
- const error = new Error('系统监测麦克风未授权~');
1511
- this.emit('ws.error', { type: WebSocketErrorType.MicroAuth, error });
1512
- return error;
1513
- }
1514
- // WebSocket 正在连接中,规避重复连接
1515
- if (liveController.connecting) {
1516
- const error = new Error('WebSocket 正在连接中,请勿重复连接 ...');
1517
- this.emit('ws.error', {
1518
- type: WebSocketErrorType.DuplicateConnect,
1519
- error,
1784
+ return __awaiter(this, void 0, void 0, function () {
1785
+ return __generator(this, function (_c) {
1786
+ switch (_c.label) {
1787
+ case 0:
1788
+ if (liveController.options.canForbidUserKick &&
1789
+ !liveController.options.canForbidUserKick(toUserIds)) {
1790
+ return [2 /*return*/, false];
1791
+ }
1792
+ if (!((_b = (_a = this.selfInfo) === null || _a === void 0 ? void 0 : _a.permission) === null || _b === void 0 ? void 0 : _b.change_other_status)) {
1793
+ return [2 /*return*/, false];
1794
+ }
1795
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.UserChange, BuiltinActionType.UserStatus, {
1796
+ status: 'KICK_OUT',
1797
+ }, toUserIds)];
1798
+ case 1: return [2 /*return*/, _c.sent()];
1799
+ }
1520
1800
  });
1521
- return error;
1522
- }
1523
- // 非强制连接场景下,如果已经完成 WebSocket 连接则不执行后续逻辑
1524
- const { force } = options;
1525
- if (!force) {
1526
- if (this.readyState === WebSocketState.CONNECTING ||
1527
- this.readyState === WebSocketState.OPEN) {
1528
- return true;
1529
- }
1530
- }
1531
- // WebSocket URL 逻辑
1532
- if (options.url) {
1533
- liveController.options.url = options.url;
1534
- }
1535
- if (options.getTicket) {
1536
- liveController.options.getTicket = options.getTicket;
1537
- }
1538
- if (!liveController.options.url ||
1539
- !liveController.options.url.startsWith('ws')) {
1540
- const error = new Error(`WebSocket URL 未配置或格式不合法:"${liveController.options.url}"`);
1541
- this.emit('ws.error', { type: WebSocketErrorType.IllegalURL, error });
1542
- return error;
1543
- }
1544
- if (!liveController.options.getTicket) {
1545
- const error = new Error(`getTicket() 未配置!`);
1546
- this.emit('ws.error', { type: WebSocketErrorType.IllegalArgs, error });
1547
- return error;
1548
- }
1549
- // 连接锁
1550
- liveController.connecting = true;
1551
- // 连接前销毁之前绑定的事件
1552
- liveController.disposeWebSocket();
1553
- this.emit('ws.beforeConnect');
1554
- const url = force || options.url || !this.url
1555
- ? appendUri(liveController.options.url, {
1556
- ticket: await liveController.options.getTicket(),
1557
- force: Number(!!force),
1558
- })
1559
- : this.url;
1560
- liveController.webSocket = new WebSocket(url);
1561
- liveController.onEvtOpnListener = () => {
1562
- liveController.checkReadyState(this);
1563
- this.emit('ws.afterConnect');
1564
- };
1565
- liveController.onEvtMsgListener = (evt) => {
1566
- liveController.checkReadyState(this);
1567
- try {
1568
- const liveMsg = parseLiveMsg(evt.data);
1569
- if (liveMsg === false)
1570
- return;
1571
- liveController.handleMessage(liveMsg, this);
1572
- }
1573
- catch (error) {
1574
- // 未知错误
1575
- this.emit('ws.error', {
1576
- type: WebSocketErrorType.Unknown,
1577
- error,
1578
- target: evt,
1579
- });
1580
- }
1581
- };
1582
- liveController.onEvtErrListener = (evt) => {
1583
- live.emit('ws.error', { type: WebSocketErrorType.Error, target: evt });
1584
- liveController.checkReadyState(this);
1585
- };
1586
- liveController.onEvtCLEListener = (evt) => {
1587
- liveController.checkReadyState(this);
1588
- const code = Number(evt.code);
1589
- if (code === 1000)
1590
- return;
1591
- // 异常退出不一定会触发'error'事件,根据 evt.code 一些类型的退出也算是 error 行为
1592
- const errMsg = parseWSClsErr(code);
1593
- live.emit('ws.error', {
1594
- target: evt,
1595
- type: WebSocketErrorType.Close,
1596
- closeError: errMsg,
1801
+ });
1802
+ };
1803
+ LiveTpl.prototype.exit = function () {
1804
+ return __awaiter(this, void 0, void 0, function () {
1805
+ var e_1;
1806
+ return __generator(this, function (_a) {
1807
+ switch (_a.label) {
1808
+ case 0:
1809
+ _a.trys.push([0, 2, , 3]);
1810
+ this.$RTC.quit();
1811
+ return [4 /*yield*/, this.updateStatus(BuiltinEventType.RoomChange, BuiltinActionType.RoomClose, {})];
1812
+ case 1:
1813
+ _a.sent();
1814
+ return [3 /*break*/, 3];
1815
+ case 2:
1816
+ e_1 = _a.sent();
1817
+ console.log(e_1);
1818
+ return [3 /*break*/, 3];
1819
+ case 3: return [2 /*return*/, liveController.dispose()];
1820
+ }
1597
1821
  });
1598
- };
1599
- liveController.webSocket.addEventListener('open', liveController.onEvtOpnListener);
1600
- liveController.webSocket.addEventListener('message', liveController.onEvtMsgListener);
1601
- liveController.webSocket.addEventListener('error', liveController.onEvtErrListener);
1602
- liveController.webSocket.addEventListener('close', liveController.onEvtCLEListener);
1603
- return await new Promise((resolve, reject) => {
1604
- const success = () => {
1605
- resolve(true);
1606
- liveController.connecting = false;
1607
- this.off('ws.error', fail);
1608
- };
1609
- const fail = (error) => {
1610
- reject(error.error
1611
- ? error.error
1612
- : new Error('WebSocket connection failed!'));
1613
- liveController.connecting = false;
1614
- this.off('ws.afterConnect', success);
1615
- };
1616
- this.once('ws.afterConnect', success);
1617
- this.once('ws.error', fail);
1618
1822
  });
1619
- }
1620
- async revoke() {
1621
- return true;
1622
- }
1623
- }
1624
- const live = new LiveTpl();
1823
+ };
1824
+ LiveTpl.prototype.connect = function (options) {
1825
+ if (options === void 0) { options = {}; }
1826
+ return __awaiter(this, void 0, void 0, function () {
1827
+ var microAuth, error, error, force, error, error, url, _a, _b, _c;
1828
+ var _d;
1829
+ var _this = this;
1830
+ return __generator(this, function (_e) {
1831
+ switch (_e.label) {
1832
+ case 0: return [4 /*yield*/, this.$RTC.detectMicro()];
1833
+ case 1:
1834
+ microAuth = _e.sent();
1835
+ if (!microAuth) {
1836
+ error = new Error('系统监测麦克风未授权~');
1837
+ this.emit('ws.error', { type: WebSocketErrorType.MicroAuth, error: error });
1838
+ return [2 /*return*/, error];
1839
+ }
1840
+ // WebSocket 正在连接中,规避重复连接
1841
+ if (liveController.connecting) {
1842
+ error = new Error('WebSocket 正在连接中,请勿重复连接 ...');
1843
+ this.emit('ws.error', {
1844
+ type: WebSocketErrorType.DuplicateConnect,
1845
+ error: error,
1846
+ });
1847
+ return [2 /*return*/, error];
1848
+ }
1849
+ force = options.force;
1850
+ if (!force) {
1851
+ if (this.readyState === WebSocketState.CONNECTING ||
1852
+ this.readyState === WebSocketState.OPEN) {
1853
+ return [2 /*return*/, true];
1854
+ }
1855
+ }
1856
+ // WebSocket URL 逻辑
1857
+ if (options.url) {
1858
+ liveController.options.url = options.url;
1859
+ }
1860
+ if (options.getTicket) {
1861
+ liveController.options.getTicket = options.getTicket;
1862
+ }
1863
+ if (!liveController.options.url ||
1864
+ !liveController.options.url.startsWith('ws')) {
1865
+ error = new Error("WebSocket URL \u672A\u914D\u7F6E\u6216\u683C\u5F0F\u4E0D\u5408\u6CD5\uFF1A\"".concat(liveController.options.url, "\""));
1866
+ this.emit('ws.error', { type: WebSocketErrorType.IllegalURL, error: error });
1867
+ return [2 /*return*/, error];
1868
+ }
1869
+ if (!liveController.options.getTicket) {
1870
+ error = new Error("getTicket() \u672A\u914D\u7F6E!");
1871
+ this.emit('ws.error', { type: WebSocketErrorType.IllegalArgs, error: error });
1872
+ return [2 /*return*/, error];
1873
+ }
1874
+ // 连接锁
1875
+ liveController.connecting = true;
1876
+ // 连接前销毁之前绑定的事件
1877
+ liveController.disposeWebSocket();
1878
+ this.emit('ws.beforeConnect');
1879
+ if (!(force || options.url || !this.url)) return [3 /*break*/, 3];
1880
+ _b = appendUri;
1881
+ _c = [liveController.options.url];
1882
+ _d = {};
1883
+ return [4 /*yield*/, liveController.options.getTicket()];
1884
+ case 2:
1885
+ _a = _b.apply(void 0, _c.concat([(_d.ticket = _e.sent(),
1886
+ _d.force = Number(!!force),
1887
+ _d)]));
1888
+ return [3 /*break*/, 4];
1889
+ case 3:
1890
+ _a = this.url;
1891
+ _e.label = 4;
1892
+ case 4:
1893
+ url = _a;
1894
+ liveController.webSocket = new WebSocket(url);
1895
+ liveController.onEvtOpnListener = function () {
1896
+ liveController.checkReadyState(_this);
1897
+ _this.emit('ws.afterConnect');
1898
+ };
1899
+ liveController.onEvtMsgListener = function (evt) {
1900
+ liveController.checkReadyState(_this);
1901
+ try {
1902
+ var liveMsg = parseLiveMsg(evt.data);
1903
+ if (liveMsg === false)
1904
+ return;
1905
+ liveController.handleMessage(liveMsg, _this);
1906
+ }
1907
+ catch (error) {
1908
+ // 未知错误
1909
+ _this.emit('ws.error', {
1910
+ type: WebSocketErrorType.Unknown,
1911
+ error: error,
1912
+ target: evt,
1913
+ });
1914
+ }
1915
+ };
1916
+ liveController.onEvtErrListener = function (evt) {
1917
+ live.emit('ws.error', { type: WebSocketErrorType.Error, target: evt });
1918
+ liveController.checkReadyState(_this);
1919
+ };
1920
+ liveController.onEvtCLEListener = function (evt) {
1921
+ liveController.checkReadyState(_this);
1922
+ var code = Number(evt.code);
1923
+ if (code === 1000)
1924
+ return;
1925
+ // 异常退出不一定会触发'error'事件,根据 evt.code 一些类型的退出也算是 error 行为
1926
+ var errMsg = parseWSClsErr(code);
1927
+ live.emit('ws.error', {
1928
+ target: evt,
1929
+ type: WebSocketErrorType.Close,
1930
+ closeError: errMsg,
1931
+ });
1932
+ };
1933
+ liveController.webSocket.addEventListener('open', liveController.onEvtOpnListener);
1934
+ liveController.webSocket.addEventListener('message', liveController.onEvtMsgListener);
1935
+ liveController.webSocket.addEventListener('error', liveController.onEvtErrListener);
1936
+ liveController.webSocket.addEventListener('close', liveController.onEvtCLEListener);
1937
+ return [4 /*yield*/, new Promise(function (resolve, reject) {
1938
+ var success = function () {
1939
+ resolve(true);
1940
+ liveController.connecting = false;
1941
+ _this.off('ws.error', fail);
1942
+ };
1943
+ var fail = function (error) {
1944
+ reject(error.error
1945
+ ? error.error
1946
+ : new Error('WebSocket connection failed!'));
1947
+ liveController.connecting = false;
1948
+ _this.off('ws.afterConnect', success);
1949
+ };
1950
+ _this.once('ws.afterConnect', success);
1951
+ _this.once('ws.error', fail);
1952
+ })];
1953
+ case 5: return [2 /*return*/, _e.sent()];
1954
+ }
1955
+ });
1956
+ });
1957
+ };
1958
+ LiveTpl.prototype.revoke = function () {
1959
+ return __awaiter(this, void 0, void 0, function () {
1960
+ return __generator(this, function (_a) {
1961
+ return [2 /*return*/, true];
1962
+ });
1963
+ });
1964
+ };
1965
+ return LiveTpl;
1966
+ }(Subscribe));
1967
+ var live = new LiveTpl();
1625
1968
  // 如果是调试环境则将内部状态暴露出来
1626
1969
  if (options.__debug__) {
1627
1970
  Object.assign(live, { __controller__: liveController });
@@ -1634,14 +1977,14 @@ function createLive(options) {
1634
1977
  * 创建 {@link LiveReact} 实例,并提供 `React` 技术栈相关工具链。
1635
1978
  */
1636
1979
  function createLiveReact(options) {
1637
- const LiveContext = React.createContext(null);
1638
- const live = createLive(options);
1639
- const jsBridge = live.jsBridge;
1980
+ var LiveContext = React.createContext(null);
1981
+ var live = createLive(options);
1982
+ var jsBridge = live.jsBridge;
1640
1983
  function LiveProvider(props) {
1641
1984
  return (React.createElement(LiveContext.Provider, { value: props.live || live }, props.children));
1642
1985
  }
1643
1986
  function useLiveInstance() {
1644
- const context = React.useContext(LiveContext);
1987
+ var context = React.useContext(LiveContext);
1645
1988
  if (!context)
1646
1989
  throw new Error('LiveProvider never found.');
1647
1990
  return context;
@@ -1654,7 +1997,7 @@ function createLiveReact(options) {
1654
1997
  return useLiveInstance();
1655
1998
  }
1656
1999
  function useRTCInstance() {
1657
- const live = useLiveInstance();
2000
+ var live = useLiveInstance();
1658
2001
  return live.$RTC;
1659
2002
  }
1660
2003
  /**
@@ -1665,76 +2008,93 @@ function createLiveReact(options) {
1665
2008
  return useRTCInstance();
1666
2009
  }
1667
2010
  function useConnect() {
1668
- const live = useLiveInstance();
1669
- return async (options) => await live.connect(options);
2011
+ var _this = this;
2012
+ var live = useLiveInstance();
2013
+ return function (options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
2014
+ switch (_a.label) {
2015
+ case 0: return [4 /*yield*/, live.connect(options)];
2016
+ case 1: return [2 /*return*/, _a.sent()];
2017
+ }
2018
+ }); }); };
1670
2019
  }
1671
2020
  function useCurrentWebSocketUrl() {
1672
- const live = useLiveInstance();
1673
- const [state, setState] = React.useState(undefined);
1674
- React.useEffect(() => {
1675
- const onWSBeforeConnect = () => setState(live.url);
2021
+ var live = useLiveInstance();
2022
+ var _a = React.useState(undefined), state = _a[0], setState = _a[1];
2023
+ React.useEffect(function () {
2024
+ var onWSBeforeConnect = function () { return setState(live.url); };
1676
2025
  live.on('ws.beforeConnect', onWSBeforeConnect);
1677
- return () => live.off('ws.beforeConnect', onWSBeforeConnect);
2026
+ return function () { return live.off('ws.beforeConnect', onWSBeforeConnect); };
1678
2027
  }, [live]);
1679
2028
  return state;
1680
2029
  }
1681
- function useKeyframeUpdateCallback(name, callback, deps = []) {
1682
- const live = useLiveInstance();
1683
- const dependencyList = [live, name, ...deps];
1684
- const dispose = () => live.keyframes.off(name, callback);
1685
- React.useEffect(() => {
2030
+ function useKeyframeUpdateCallback(name, callback, deps) {
2031
+ if (deps === void 0) { deps = []; }
2032
+ var live = useLiveInstance();
2033
+ var dependencyList = __spreadArray([live, name], deps, true);
2034
+ var dispose = function () { return live.keyframes.off(name, callback); };
2035
+ React.useEffect(function () {
1686
2036
  live.keyframes.on(name, callback);
1687
2037
  return dispose;
1688
2038
  }, dependencyList);
1689
2039
  return dispose;
1690
2040
  }
1691
2041
  function useLiveAction() {
1692
- const live = useLiveInstance();
1693
- const toggleMicro = React.useCallback((microStatus) => live.toggleMicro(microStatus), [live]);
1694
- const broadcast = React.useCallback((data, toUserIds, timeout = 0) => live.broadcast(data, toUserIds, timeout), [live]);
1695
- const exit = React.useCallback(() => live.exit(), [live]);
1696
- const kick = React.useCallback((toUserIds) => live.kick(toUserIds), [live]);
1697
- const forbidMicro = React.useCallback((micro, toUserIds) => live.forbidMicro(micro, toUserIds), [live]);
2042
+ var live = useLiveInstance();
2043
+ var toggleMicro = React.useCallback(function (microStatus) { return live.toggleMicro(microStatus); }, [live]);
2044
+ var broadcast = React.useCallback(function (data, toUserIds, timeout) {
2045
+ if (timeout === void 0) { timeout = 0; }
2046
+ return live.broadcast(data, toUserIds, timeout);
2047
+ }, [live]);
2048
+ var exit = React.useCallback(function () { return live.exit(); }, [live]);
2049
+ var kick = React.useCallback(function (toUserIds) { return live.kick(toUserIds); }, [live]);
2050
+ var forbidMicro = React.useCallback(function (micro, toUserIds) {
2051
+ return live.forbidMicro(micro, toUserIds);
2052
+ }, [live]);
1698
2053
  // const forbidSync = React.useCallback(
1699
2054
  // (sync: boolean, toUserIds?: string | string[] | undefined) =>
1700
2055
  // live.forbidSync(sync, toUserIds),
1701
2056
  // [live],
1702
2057
  // );
1703
- const getFramesByKey = React.useCallback((key) => live.getFramesByKey(key), [live]);
1704
- const sendKeyframe = React.useCallback((key, frame) => live.sendKeyframe(key, frame), [live]);
1705
- const setSelfInfo = React.useCallback((userInfo) => live.setSelfInfo(userInfo), [live]);
1706
- const updateStatus = React.useCallback((evtType, atnType, status, toUserIds) => live.updateStatus(evtType, atnType, status, toUserIds), [live]);
2058
+ var getFramesByKey = React.useCallback(function (key) { return live.getFramesByKey(key); }, [live]);
2059
+ var sendKeyframe = React.useCallback(function (key, frame) {
2060
+ return live.sendKeyframe(key, frame);
2061
+ }, [live]);
2062
+ var setSelfInfo = React.useCallback(function (userInfo) { return live.setSelfInfo(userInfo); }, [live]);
2063
+ var updateStatus = React.useCallback(function (evtType, atnType, status, toUserIds) { return live.updateStatus(evtType, atnType, status, toUserIds); }, [live]);
1707
2064
  return {
1708
- broadcast,
1709
- exit,
1710
- kick,
1711
- toggleMicro,
1712
- forbidMicro,
2065
+ broadcast: broadcast,
2066
+ exit: exit,
2067
+ kick: kick,
2068
+ toggleMicro: toggleMicro,
2069
+ forbidMicro: forbidMicro,
1713
2070
  // forbidSync,
1714
- sendKeyframe,
1715
- getFramesByKey,
1716
- setSelfInfo,
1717
- updateStatus,
2071
+ sendKeyframe: sendKeyframe,
2072
+ getFramesByKey: getFramesByKey,
2073
+ setSelfInfo: setSelfInfo,
2074
+ updateStatus: updateStatus,
1718
2075
  };
1719
2076
  }
1720
2077
  function useKeyframe(key) {
1721
- const live = useLiveInstance();
1722
- const [state, updateState] = React.useState(live.getFramesByKey(key));
1723
- React.useEffect(() => {
1724
- const onUpdate = (nextKeyframes) => updateState(nextKeyframes);
1725
- const evtName = key;
1726
- const callback = onUpdate;
2078
+ var live = useLiveInstance();
2079
+ var _a = React.useState(live.getFramesByKey(key)), state = _a[0], updateState = _a[1];
2080
+ React.useEffect(function () {
2081
+ var onUpdate = function (nextKeyframes) {
2082
+ return updateState(nextKeyframes);
2083
+ };
2084
+ var evtName = key;
2085
+ var callback = onUpdate;
1727
2086
  live.keyframes.on(evtName, callback);
1728
- return () => live.keyframes.off(evtName, callback);
2087
+ return function () { return live.keyframes.off(evtName, callback); };
1729
2088
  }, [live]);
1730
- const setState = React.useCallback((frame) => live.sendKeyframe(key, frame), [live]);
2089
+ var setState = React.useCallback(function (frame) { return live.sendKeyframe(key, frame); }, [live]);
1731
2090
  return [state, setState];
1732
2091
  }
1733
- function useLiveEventCallback(name, callback, deps = []) {
1734
- const live = useLiveInstance();
1735
- const dispose = () => live.off(name, callback);
1736
- const dependencyList = [live, name, ...deps];
1737
- React.useEffect(() => {
2092
+ function useLiveEventCallback(name, callback, deps) {
2093
+ if (deps === void 0) { deps = []; }
2094
+ var live = useLiveInstance();
2095
+ var dispose = function () { return live.off(name, callback); };
2096
+ var dependencyList = __spreadArray([live, name], deps, true);
2097
+ React.useEffect(function () {
1738
2098
  live.on(name, callback);
1739
2099
  return dispose;
1740
2100
  }, dependencyList);
@@ -1745,70 +2105,81 @@ function createLiveReact(options) {
1745
2105
  * @returns
1746
2106
  */
1747
2107
  function useReadyState() {
1748
- const live = useLiveInstance();
1749
- const [state, updateState] = React.useState(live.readyState);
1750
- React.useEffect(() => {
1751
- const readyStateUpdate = (readyState) => updateState(readyState);
2108
+ var live = useLiveInstance();
2109
+ var _a = React.useState(live.readyState), state = _a[0], updateState = _a[1];
2110
+ React.useEffect(function () {
2111
+ var readyStateUpdate = function (readyState) {
2112
+ return updateState(readyState);
2113
+ };
1752
2114
  live.on('ws.readyStateUpdate', readyStateUpdate);
1753
- return () => live.off('ws.readyStateUpdate', readyStateUpdate);
2115
+ return function () { return live.off('ws.readyStateUpdate', readyStateUpdate); };
1754
2116
  }, [live]);
1755
2117
  return state;
1756
2118
  }
1757
2119
  function useRTCAction() {
1758
- const live = useLiveInstance();
1759
- const join = React.useCallback((options) => live.$RTC.join(options), [live]);
1760
- const quit = React.useCallback(() => live.$RTC.quit(), [live]);
1761
- const shock = React.useCallback(() => { var _a, _b; return (_b = (_a = live.$RTC).shock) === null || _b === void 0 ? void 0 : _b.call(_a); }, [live]);
1762
- const toggleMicro = React.useCallback((flag) => live.$RTC.toggleMicro(flag), [live]);
1763
- const detectMicro = React.useCallback(() => live.$RTC.detectMicro(), [live]);
2120
+ var live = useLiveInstance();
2121
+ var join = React.useCallback(function (options) { return live.$RTC.join(options); }, [live]);
2122
+ var quit = React.useCallback(function () { return live.$RTC.quit(); }, [live]);
2123
+ var shock = React.useCallback(function () { var _a, _b; return (_b = (_a = live.$RTC).shock) === null || _b === void 0 ? void 0 : _b.call(_a); }, [live]);
2124
+ var toggleMicro = React.useCallback(function (flag) { return live.$RTC.toggleMicro(flag); }, [live]);
2125
+ var detectMicro = React.useCallback(function () { return live.$RTC.detectMicro(); }, [live]);
1764
2126
  return {
1765
- join,
1766
- quit,
1767
- shock,
1768
- toggleMicro,
1769
- detectMicro,
2127
+ join: join,
2128
+ quit: quit,
2129
+ shock: shock,
2130
+ toggleMicro: toggleMicro,
2131
+ detectMicro: detectMicro,
1770
2132
  };
1771
2133
  }
1772
- function useRTCEventCallback(name, callback, deps = []) {
1773
- const live = useLiveInstance();
1774
- const dispose = () => live.$RTC.off(name, callback);
1775
- const dependencyList = [live, name, ...deps];
1776
- React.useEffect(() => {
2134
+ function useRTCEventCallback(name, callback, deps) {
2135
+ if (deps === void 0) { deps = []; }
2136
+ var live = useLiveInstance();
2137
+ var dispose = function () { return live.$RTC.off(name, callback); };
2138
+ var dependencyList = __spreadArray([live, name], deps, true);
2139
+ React.useEffect(function () {
1777
2140
  live.$RTC.on(name, callback);
1778
2141
  return dispose;
1779
2142
  }, dependencyList);
1780
2143
  return dispose;
1781
2144
  }
1782
2145
  function useSelfInfo() {
1783
- const live = useLiveInstance();
1784
- const [state, updateState] = React.useState(live.selfInfo || {});
1785
- const selfInfoUpdate = (userInfo) => updateState(userInfo);
1786
- React.useEffect(() => {
2146
+ var _this = this;
2147
+ var live = useLiveInstance();
2148
+ var _a = React.useState(live.selfInfo || {}), state = _a[0], updateState = _a[1];
2149
+ var selfInfoUpdate = function (userInfo) {
2150
+ return updateState(userInfo);
2151
+ };
2152
+ React.useEffect(function () {
1787
2153
  live.on('selfInfoUpdate', selfInfoUpdate);
1788
- return () => live.off('selfInfoUpdate', selfInfoUpdate);
1789
- }, [live]);
1790
- const setState = React.useCallback(async (userInfo) => {
1791
- return await live.setSelfInfo(userInfo);
2154
+ return function () { return live.off('selfInfoUpdate', selfInfoUpdate); };
1792
2155
  }, [live]);
2156
+ var setState = React.useCallback(function (userInfo) { return __awaiter(_this, void 0, void 0, function () {
2157
+ return __generator(this, function (_a) {
2158
+ switch (_a.label) {
2159
+ case 0: return [4 /*yield*/, live.setSelfInfo(userInfo)];
2160
+ case 1: return [2 /*return*/, _a.sent()];
2161
+ }
2162
+ });
2163
+ }); }, [live]);
1793
2164
  return [state, setState];
1794
2165
  }
1795
2166
  function useSnapshot() {
1796
- const live = useLiveInstance();
1797
- const [state, setState] = React.useState(live.snapshot);
1798
- React.useEffect(() => {
1799
- const onKeyframes = (keyframes) => setState(keyframes);
2167
+ var live = useLiveInstance();
2168
+ var _a = React.useState(live.snapshot), state = _a[0], setState = _a[1];
2169
+ React.useEffect(function () {
2170
+ var onKeyframes = function (keyframes) { return setState(keyframes); };
1800
2171
  live.on('keyframes', onKeyframes);
1801
- return () => live.off('keyframes', onKeyframes);
2172
+ return function () { return live.off('keyframes', onKeyframes); };
1802
2173
  });
1803
2174
  return state;
1804
2175
  }
1805
2176
  function useUserList() {
1806
- const live = useLiveInstance();
1807
- const [state, updateState] = React.useState(live.userList);
1808
- const userListUpdate = (userList) => updateState(userList);
1809
- React.useEffect(() => {
2177
+ var live = useLiveInstance();
2178
+ var _a = React.useState(live.userList), state = _a[0], updateState = _a[1];
2179
+ var userListUpdate = function (userList) { return updateState(userList); };
2180
+ React.useEffect(function () {
1810
2181
  live.on('userListUpdate', userListUpdate);
1811
- return () => live.off('userListUpdate', userListUpdate);
2182
+ return function () { return live.off('userListUpdate', userListUpdate); };
1812
2183
  }, [live]);
1813
2184
  return state;
1814
2185
  }
@@ -1820,35 +2191,36 @@ function createLiveReact(options) {
1820
2191
  * @returns
1821
2192
  * @deprecated
1822
2193
  */
1823
- function useWebSocketEventCallback(name, callback, deps = []) {
1824
- const live = useLiveInstance();
1825
- const dispose = () => live.off(name, callback);
1826
- const dependencyList = [live, name, ...deps];
1827
- React.useEffect(() => {
2194
+ function useWebSocketEventCallback(name, callback, deps) {
2195
+ if (deps === void 0) { deps = []; }
2196
+ var live = useLiveInstance();
2197
+ var dispose = function () { return live.off(name, callback); };
2198
+ var dependencyList = __spreadArray([live, name], deps, true);
2199
+ React.useEffect(function () {
1828
2200
  live.on(name, callback);
1829
2201
  return dispose;
1830
2202
  }, dependencyList);
1831
2203
  return dispose;
1832
2204
  }
1833
2205
  return {
1834
- live,
1835
- jsBridge,
1836
- LiveProvider,
1837
- unsafe__useLiveInstance,
1838
- unsafe__useRTCInstance,
1839
- useCurrentWebSocketUrl,
1840
- useConnect,
1841
- useKeyframe,
1842
- useKeyframeUpdateCallback,
1843
- useLiveAction,
1844
- useLiveEventCallback,
1845
- useReadyState,
1846
- useRTCAction,
1847
- useRTCEventCallback,
1848
- useSelfInfo,
1849
- useSnapshot,
1850
- useUserList,
1851
- useWebSocketEventCallback,
2206
+ live: live,
2207
+ jsBridge: jsBridge,
2208
+ LiveProvider: LiveProvider,
2209
+ unsafe__useLiveInstance: unsafe__useLiveInstance,
2210
+ unsafe__useRTCInstance: unsafe__useRTCInstance,
2211
+ useCurrentWebSocketUrl: useCurrentWebSocketUrl,
2212
+ useConnect: useConnect,
2213
+ useKeyframe: useKeyframe,
2214
+ useKeyframeUpdateCallback: useKeyframeUpdateCallback,
2215
+ useLiveAction: useLiveAction,
2216
+ useLiveEventCallback: useLiveEventCallback,
2217
+ useReadyState: useReadyState,
2218
+ useRTCAction: useRTCAction,
2219
+ useRTCEventCallback: useRTCEventCallback,
2220
+ useSelfInfo: useSelfInfo,
2221
+ useSnapshot: useSnapshot,
2222
+ useUserList: useUserList,
2223
+ useWebSocketEventCallback: useWebSocketEventCallback,
1852
2224
  };
1853
2225
  }
1854
2226