@s21g/peerjs 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/peerjs.js ADDED
@@ -0,0 +1,4718 @@
1
+ (() => {
2
+
3
+ function $parcel$export(e, n, v, s) {
4
+ Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
5
+ }
6
+
7
+ function $parcel$interopDefault(a) {
8
+ return a && a.__esModule ? a.default : a;
9
+ }
10
+ class $616ebdf1c4998439$export$f1c5f4c9cb95390b {
11
+ constructor(){
12
+ this.chunkedMTU = 16300 // The original 60000 bytes setting does not work when sending data from Firefox to Chrome, which is "cut off" after 16384 bytes and delivered individually.
13
+ ;
14
+ // Binary stuff
15
+ this._dataCount = 1;
16
+ this.chunk = (blob)=>{
17
+ const chunks = [];
18
+ const size = blob.byteLength;
19
+ const total = Math.ceil(size / this.chunkedMTU);
20
+ let index = 0;
21
+ let start = 0;
22
+ while(start < size){
23
+ const end = Math.min(size, start + this.chunkedMTU);
24
+ const b = blob.slice(start, end);
25
+ const chunk = {
26
+ __peerData: this._dataCount,
27
+ n: index,
28
+ data: b,
29
+ total: total
30
+ };
31
+ chunks.push(chunk);
32
+ start = end;
33
+ index++;
34
+ }
35
+ this._dataCount++;
36
+ return chunks;
37
+ };
38
+ }
39
+ }
40
+ function $616ebdf1c4998439$export$52c89ebcdc4f53f2(bufs) {
41
+ let size = 0;
42
+ for (const buf of bufs)size += buf.byteLength;
43
+ const result = new Uint8Array(size);
44
+ let offset = 0;
45
+ for (const buf of bufs){
46
+ result.set(buf, offset);
47
+ offset += buf.byteLength;
48
+ }
49
+ return result;
50
+ }
51
+
52
+
53
+ class $ff4d9c92b817f2ed$export$93654d4f2d6cd524 {
54
+ append_buffer(data) {
55
+ this.flush();
56
+ this._parts.push(data);
57
+ }
58
+ append(data) {
59
+ this._pieces.push(data);
60
+ }
61
+ flush() {
62
+ if (this._pieces.length > 0) {
63
+ const buf = new Uint8Array(this._pieces);
64
+ this._parts.push(buf);
65
+ this._pieces = [];
66
+ }
67
+ }
68
+ toArrayBuffer() {
69
+ const buffer = [];
70
+ for (const part of this._parts)buffer.push(part);
71
+ return $ff4d9c92b817f2ed$var$concatArrayBuffers(buffer).buffer;
72
+ }
73
+ constructor(){
74
+ this.encoder = new TextEncoder();
75
+ this._pieces = [];
76
+ this._parts = [];
77
+ }
78
+ }
79
+ function $ff4d9c92b817f2ed$var$concatArrayBuffers(bufs) {
80
+ let size = 0;
81
+ for (const buf of bufs)size += buf.byteLength;
82
+ const result = new Uint8Array(size);
83
+ let offset = 0;
84
+ for (const buf of bufs){
85
+ const view = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
86
+ result.set(view, offset);
87
+ offset += buf.byteLength;
88
+ }
89
+ return result;
90
+ }
91
+
92
+
93
+ function $6018e3630d94a7b2$export$417857010dc9287f(data) {
94
+ const unpacker = new $6018e3630d94a7b2$var$Unpacker(data);
95
+ return unpacker.unpack();
96
+ }
97
+ function $6018e3630d94a7b2$export$2a703dbb0cb35339(data) {
98
+ const packer = new $6018e3630d94a7b2$export$b9ec4b114aa40074();
99
+ const res = packer.pack(data);
100
+ if (res instanceof Promise) return res.then(()=>packer.getBuffer());
101
+ return packer.getBuffer();
102
+ }
103
+ class $6018e3630d94a7b2$var$Unpacker {
104
+ unpack() {
105
+ const type = this.unpack_uint8();
106
+ if (type < 0x80) return type;
107
+ else if ((type ^ 0xe0) < 0x20) return (type ^ 0xe0) - 0x20;
108
+ let size;
109
+ if ((size = type ^ 0xa0) <= 0x0f) return this.unpack_raw(size);
110
+ else if ((size = type ^ 0xb0) <= 0x0f) return this.unpack_string(size);
111
+ else if ((size = type ^ 0x90) <= 0x0f) return this.unpack_array(size);
112
+ else if ((size = type ^ 0x80) <= 0x0f) return this.unpack_map(size);
113
+ switch(type){
114
+ case 0xc0:
115
+ return null;
116
+ case 0xc1:
117
+ return undefined;
118
+ case 0xc2:
119
+ return false;
120
+ case 0xc3:
121
+ return true;
122
+ case 0xca:
123
+ return this.unpack_float();
124
+ case 0xcb:
125
+ return this.unpack_double();
126
+ case 0xcc:
127
+ return this.unpack_uint8();
128
+ case 0xcd:
129
+ return this.unpack_uint16();
130
+ case 0xce:
131
+ return this.unpack_uint32();
132
+ case 0xcf:
133
+ return this.unpack_uint64();
134
+ case 0xd0:
135
+ return this.unpack_int8();
136
+ case 0xd1:
137
+ return this.unpack_int16();
138
+ case 0xd2:
139
+ return this.unpack_int32();
140
+ case 0xd3:
141
+ return this.unpack_int64();
142
+ case 0xd4:
143
+ return undefined;
144
+ case 0xd5:
145
+ return undefined;
146
+ case 0xd6:
147
+ return undefined;
148
+ case 0xd7:
149
+ return undefined;
150
+ case 0xd8:
151
+ size = this.unpack_uint16();
152
+ return this.unpack_string(size);
153
+ case 0xd9:
154
+ size = this.unpack_uint32();
155
+ return this.unpack_string(size);
156
+ case 0xda:
157
+ size = this.unpack_uint16();
158
+ return this.unpack_raw(size);
159
+ case 0xdb:
160
+ size = this.unpack_uint32();
161
+ return this.unpack_raw(size);
162
+ case 0xdc:
163
+ size = this.unpack_uint16();
164
+ return this.unpack_array(size);
165
+ case 0xdd:
166
+ size = this.unpack_uint32();
167
+ return this.unpack_array(size);
168
+ case 0xde:
169
+ size = this.unpack_uint16();
170
+ return this.unpack_map(size);
171
+ case 0xdf:
172
+ size = this.unpack_uint32();
173
+ return this.unpack_map(size);
174
+ }
175
+ }
176
+ unpack_uint8() {
177
+ const byte = this.dataView[this.index] & 0xff;
178
+ this.index++;
179
+ return byte;
180
+ }
181
+ unpack_uint16() {
182
+ const bytes = this.read(2);
183
+ const uint16 = (bytes[0] & 0xff) * 256 + (bytes[1] & 0xff);
184
+ this.index += 2;
185
+ return uint16;
186
+ }
187
+ unpack_uint32() {
188
+ const bytes = this.read(4);
189
+ const uint32 = ((bytes[0] * 256 + bytes[1]) * 256 + bytes[2]) * 256 + bytes[3];
190
+ this.index += 4;
191
+ return uint32;
192
+ }
193
+ unpack_uint64() {
194
+ const bytes = this.read(8);
195
+ const uint64 = ((((((bytes[0] * 256 + bytes[1]) * 256 + bytes[2]) * 256 + bytes[3]) * 256 + bytes[4]) * 256 + bytes[5]) * 256 + bytes[6]) * 256 + bytes[7];
196
+ this.index += 8;
197
+ return uint64;
198
+ }
199
+ unpack_int8() {
200
+ const uint8 = this.unpack_uint8();
201
+ return uint8 < 0x80 ? uint8 : uint8 - 256;
202
+ }
203
+ unpack_int16() {
204
+ const uint16 = this.unpack_uint16();
205
+ return uint16 < 0x8000 ? uint16 : uint16 - 65536;
206
+ }
207
+ unpack_int32() {
208
+ const uint32 = this.unpack_uint32();
209
+ return uint32 < 2 ** 31 ? uint32 : uint32 - 2 ** 32;
210
+ }
211
+ unpack_int64() {
212
+ const uint64 = this.unpack_uint64();
213
+ return uint64 < 2 ** 63 ? uint64 : uint64 - 2 ** 64;
214
+ }
215
+ unpack_raw(size) {
216
+ if (this.length < this.index + size) throw new Error(`BinaryPackFailure: index is out of range ${this.index} ${size} ${this.length}`);
217
+ const buf = this.dataBuffer.slice(this.index, this.index + size);
218
+ this.index += size;
219
+ return buf;
220
+ }
221
+ unpack_string(size) {
222
+ const bytes = this.read(size);
223
+ let i = 0;
224
+ let str = "";
225
+ let c;
226
+ let code;
227
+ while(i < size){
228
+ c = bytes[i];
229
+ // The length of a UTF-8 sequence is specified in the first byte:
230
+ // 0xxxxxxx means length 1,
231
+ // 110xxxxx means length 2,
232
+ // 1110xxxx means length 3,
233
+ // 11110xxx means length 4.
234
+ // 10xxxxxx is for non-initial bytes.
235
+ if (c < 0xa0) {
236
+ // One-byte sequence: bits 0xxxxxxx
237
+ code = c;
238
+ i++;
239
+ } else if ((c ^ 0xc0) < 0x20) {
240
+ // Two-byte sequence: bits 110xxxxx 10xxxxxx
241
+ code = (c & 0x1f) << 6 | bytes[i + 1] & 0x3f;
242
+ i += 2;
243
+ } else if ((c ^ 0xe0) < 0x10) {
244
+ // Three-byte sequence: bits 1110xxxx 10xxxxxx 10xxxxxx
245
+ code = (c & 0x0f) << 12 | (bytes[i + 1] & 0x3f) << 6 | bytes[i + 2] & 0x3f;
246
+ i += 3;
247
+ } else {
248
+ // Four-byte sequence: bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
249
+ code = (c & 0x07) << 18 | (bytes[i + 1] & 0x3f) << 12 | (bytes[i + 2] & 0x3f) << 6 | bytes[i + 3] & 0x3f;
250
+ i += 4;
251
+ }
252
+ str += String.fromCodePoint(code);
253
+ }
254
+ this.index += size;
255
+ return str;
256
+ }
257
+ unpack_array(size) {
258
+ const objects = new Array(size);
259
+ for(let i = 0; i < size; i++)objects[i] = this.unpack();
260
+ return objects;
261
+ }
262
+ unpack_map(size) {
263
+ const map = {};
264
+ for(let i = 0; i < size; i++){
265
+ const key = this.unpack();
266
+ map[key] = this.unpack();
267
+ }
268
+ return map;
269
+ }
270
+ unpack_float() {
271
+ const uint32 = this.unpack_uint32();
272
+ const sign = uint32 >> 31;
273
+ const exp = (uint32 >> 23 & 0xff) - 127;
274
+ const fraction = uint32 & 0x7fffff | 0x800000;
275
+ return (sign === 0 ? 1 : -1) * fraction * 2 ** (exp - 23);
276
+ }
277
+ unpack_double() {
278
+ const h32 = this.unpack_uint32();
279
+ const l32 = this.unpack_uint32();
280
+ const sign = h32 >> 31;
281
+ const exp = (h32 >> 20 & 0x7ff) - 1023;
282
+ const hfrac = h32 & 0xfffff | 0x100000;
283
+ const frac = hfrac * 2 ** (exp - 20) + l32 * 2 ** (exp - 52);
284
+ return (sign === 0 ? 1 : -1) * frac;
285
+ }
286
+ read(length) {
287
+ const j = this.index;
288
+ if (j + length <= this.length) return this.dataView.subarray(j, j + length);
289
+ else throw new Error("BinaryPackFailure: read index out of range");
290
+ }
291
+ constructor(data){
292
+ this.index = 0;
293
+ this.dataBuffer = data;
294
+ this.dataView = new Uint8Array(this.dataBuffer);
295
+ this.length = this.dataBuffer.byteLength;
296
+ }
297
+ }
298
+ class $6018e3630d94a7b2$export$b9ec4b114aa40074 {
299
+ getBuffer() {
300
+ return this._bufferBuilder.toArrayBuffer();
301
+ }
302
+ pack(value) {
303
+ if (typeof value === "string") this.pack_string(value);
304
+ else if (typeof value === "number") {
305
+ if (Math.floor(value) === value) this.pack_integer(value);
306
+ else this.pack_double(value);
307
+ } else if (typeof value === "boolean") {
308
+ if (value === true) this._bufferBuilder.append(0xc3);
309
+ else if (value === false) this._bufferBuilder.append(0xc2);
310
+ } else if (value === undefined) this._bufferBuilder.append(0xc1);
311
+ else if (typeof value === "object") {
312
+ if (value === null) this._bufferBuilder.append(0xc0);
313
+ else {
314
+ const constructor = value.constructor;
315
+ if (value instanceof Array) {
316
+ const res = this.pack_array(value);
317
+ if (res instanceof Promise) return res.then(()=>this._bufferBuilder.flush());
318
+ } else if (value instanceof ArrayBuffer) this.pack_bin(new Uint8Array(value));
319
+ else if ("BYTES_PER_ELEMENT" in value) {
320
+ const v = value;
321
+ this.pack_bin(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
322
+ } else if (value instanceof Date) this.pack_string(value.toString());
323
+ else if (value instanceof Blob) return value.arrayBuffer().then((buffer)=>{
324
+ this.pack_bin(new Uint8Array(buffer));
325
+ this._bufferBuilder.flush();
326
+ });
327
+ else if (constructor == Object || constructor.toString().startsWith("class")) {
328
+ const res = this.pack_object(value);
329
+ if (res instanceof Promise) return res.then(()=>this._bufferBuilder.flush());
330
+ } else throw new Error(`Type "${constructor.toString()}" not yet supported`);
331
+ }
332
+ } else throw new Error(`Type "${typeof value}" not yet supported`);
333
+ this._bufferBuilder.flush();
334
+ }
335
+ pack_bin(blob) {
336
+ const length = blob.length;
337
+ if (length <= 0x0f) this.pack_uint8(0xa0 + length);
338
+ else if (length <= 0xffff) {
339
+ this._bufferBuilder.append(0xda);
340
+ this.pack_uint16(length);
341
+ } else if (length <= 0xffffffff) {
342
+ this._bufferBuilder.append(0xdb);
343
+ this.pack_uint32(length);
344
+ } else throw new Error("Invalid length");
345
+ this._bufferBuilder.append_buffer(blob);
346
+ }
347
+ pack_string(str) {
348
+ const encoded = this._textEncoder.encode(str);
349
+ const length = encoded.length;
350
+ if (length <= 0x0f) this.pack_uint8(0xb0 + length);
351
+ else if (length <= 0xffff) {
352
+ this._bufferBuilder.append(0xd8);
353
+ this.pack_uint16(length);
354
+ } else if (length <= 0xffffffff) {
355
+ this._bufferBuilder.append(0xd9);
356
+ this.pack_uint32(length);
357
+ } else throw new Error("Invalid length");
358
+ this._bufferBuilder.append_buffer(encoded);
359
+ }
360
+ pack_array(ary) {
361
+ const length = ary.length;
362
+ if (length <= 0x0f) this.pack_uint8(0x90 + length);
363
+ else if (length <= 0xffff) {
364
+ this._bufferBuilder.append(0xdc);
365
+ this.pack_uint16(length);
366
+ } else if (length <= 0xffffffff) {
367
+ this._bufferBuilder.append(0xdd);
368
+ this.pack_uint32(length);
369
+ } else throw new Error("Invalid length");
370
+ const packNext = (index)=>{
371
+ if (index < length) {
372
+ const res = this.pack(ary[index]);
373
+ if (res instanceof Promise) return res.then(()=>packNext(index + 1));
374
+ return packNext(index + 1);
375
+ }
376
+ };
377
+ return packNext(0);
378
+ }
379
+ pack_integer(num) {
380
+ if (num >= -32 && num <= 0x7f) this._bufferBuilder.append(num & 0xff);
381
+ else if (num >= 0x00 && num <= 0xff) {
382
+ this._bufferBuilder.append(0xcc);
383
+ this.pack_uint8(num);
384
+ } else if (num >= -128 && num <= 0x7f) {
385
+ this._bufferBuilder.append(0xd0);
386
+ this.pack_int8(num);
387
+ } else if (num >= 0x0000 && num <= 0xffff) {
388
+ this._bufferBuilder.append(0xcd);
389
+ this.pack_uint16(num);
390
+ } else if (num >= -32768 && num <= 0x7fff) {
391
+ this._bufferBuilder.append(0xd1);
392
+ this.pack_int16(num);
393
+ } else if (num >= 0x00000000 && num <= 0xffffffff) {
394
+ this._bufferBuilder.append(0xce);
395
+ this.pack_uint32(num);
396
+ } else if (num >= -2147483648 && num <= 0x7fffffff) {
397
+ this._bufferBuilder.append(0xd2);
398
+ this.pack_int32(num);
399
+ } else if (num >= -9223372036854776000 && num <= 0x7fffffffffffffff) {
400
+ this._bufferBuilder.append(0xd3);
401
+ this.pack_int64(num);
402
+ } else if (num >= 0x0000000000000000 && num <= 0xffffffffffffffff) {
403
+ this._bufferBuilder.append(0xcf);
404
+ this.pack_uint64(num);
405
+ } else throw new Error("Invalid integer");
406
+ }
407
+ pack_double(num) {
408
+ let sign = 0;
409
+ if (num < 0) {
410
+ sign = 1;
411
+ num = -num;
412
+ }
413
+ const exp = Math.floor(Math.log(num) / Math.LN2);
414
+ const frac0 = num / 2 ** exp - 1;
415
+ const frac1 = Math.floor(frac0 * 2 ** 52);
416
+ const b32 = 2 ** 32;
417
+ const h32 = sign << 31 | exp + 1023 << 20 | frac1 / b32 & 0x0fffff;
418
+ const l32 = frac1 % b32;
419
+ this._bufferBuilder.append(0xcb);
420
+ this.pack_int32(h32);
421
+ this.pack_int32(l32);
422
+ }
423
+ pack_object(obj) {
424
+ const keys = Object.keys(obj);
425
+ const length = keys.length;
426
+ if (length <= 0x0f) this.pack_uint8(0x80 + length);
427
+ else if (length <= 0xffff) {
428
+ this._bufferBuilder.append(0xde);
429
+ this.pack_uint16(length);
430
+ } else if (length <= 0xffffffff) {
431
+ this._bufferBuilder.append(0xdf);
432
+ this.pack_uint32(length);
433
+ } else throw new Error("Invalid length");
434
+ const packNext = (index)=>{
435
+ if (index < keys.length) {
436
+ const prop = keys[index];
437
+ // eslint-disable-next-line no-prototype-builtins
438
+ if (obj.hasOwnProperty(prop)) {
439
+ this.pack(prop);
440
+ const res = this.pack(obj[prop]);
441
+ if (res instanceof Promise) return res.then(()=>packNext(index + 1));
442
+ }
443
+ return packNext(index + 1);
444
+ }
445
+ };
446
+ return packNext(0);
447
+ }
448
+ pack_uint8(num) {
449
+ this._bufferBuilder.append(num);
450
+ }
451
+ pack_uint16(num) {
452
+ this._bufferBuilder.append(num >> 8);
453
+ this._bufferBuilder.append(num & 0xff);
454
+ }
455
+ pack_uint32(num) {
456
+ const n = num & 0xffffffff;
457
+ this._bufferBuilder.append((n & 0xff000000) >>> 24);
458
+ this._bufferBuilder.append((n & 0x00ff0000) >>> 16);
459
+ this._bufferBuilder.append((n & 0x0000ff00) >>> 8);
460
+ this._bufferBuilder.append(n & 0x000000ff);
461
+ }
462
+ pack_uint64(num) {
463
+ const high = num / 2 ** 32;
464
+ const low = num % 2 ** 32;
465
+ this._bufferBuilder.append((high & 0xff000000) >>> 24);
466
+ this._bufferBuilder.append((high & 0x00ff0000) >>> 16);
467
+ this._bufferBuilder.append((high & 0x0000ff00) >>> 8);
468
+ this._bufferBuilder.append(high & 0x000000ff);
469
+ this._bufferBuilder.append((low & 0xff000000) >>> 24);
470
+ this._bufferBuilder.append((low & 0x00ff0000) >>> 16);
471
+ this._bufferBuilder.append((low & 0x0000ff00) >>> 8);
472
+ this._bufferBuilder.append(low & 0x000000ff);
473
+ }
474
+ pack_int8(num) {
475
+ this._bufferBuilder.append(num & 0xff);
476
+ }
477
+ pack_int16(num) {
478
+ this._bufferBuilder.append((num & 0xff00) >> 8);
479
+ this._bufferBuilder.append(num & 0xff);
480
+ }
481
+ pack_int32(num) {
482
+ this._bufferBuilder.append(num >>> 24 & 0xff);
483
+ this._bufferBuilder.append((num & 0x00ff0000) >>> 16);
484
+ this._bufferBuilder.append((num & 0x0000ff00) >>> 8);
485
+ this._bufferBuilder.append(num & 0x000000ff);
486
+ }
487
+ pack_int64(num) {
488
+ const high = Math.floor(num / 2 ** 32);
489
+ const low = num % 2 ** 32;
490
+ this._bufferBuilder.append((high & 0xff000000) >>> 24);
491
+ this._bufferBuilder.append((high & 0x00ff0000) >>> 16);
492
+ this._bufferBuilder.append((high & 0x0000ff00) >>> 8);
493
+ this._bufferBuilder.append(high & 0x000000ff);
494
+ this._bufferBuilder.append((low & 0xff000000) >>> 24);
495
+ this._bufferBuilder.append((low & 0x00ff0000) >>> 16);
496
+ this._bufferBuilder.append((low & 0x0000ff00) >>> 8);
497
+ this._bufferBuilder.append(low & 0x000000ff);
498
+ }
499
+ constructor(){
500
+ this._bufferBuilder = new (0, $ff4d9c92b817f2ed$export$93654d4f2d6cd524)();
501
+ this._textEncoder = new TextEncoder();
502
+ }
503
+ }
504
+
505
+
506
+ /*
507
+ * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
508
+ *
509
+ * Use of this source code is governed by a BSD-style license
510
+ * that can be found in the LICENSE file in the root of the source
511
+ * tree.
512
+ */ /* eslint-env node */ /*
513
+ * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
514
+ *
515
+ * Use of this source code is governed by a BSD-style license
516
+ * that can be found in the LICENSE file in the root of the source
517
+ * tree.
518
+ */ /*
519
+ * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
520
+ *
521
+ * Use of this source code is governed by a BSD-style license
522
+ * that can be found in the LICENSE file in the root of the source
523
+ * tree.
524
+ */ /* eslint-env node */ 'use strict';
525
+ let $9fea4db837311579$var$logDisabled_ = true;
526
+ let $9fea4db837311579$var$deprecationWarnings_ = true;
527
+ function $9fea4db837311579$export$e3c02be309be1f23(uastring, expr, pos) {
528
+ const match = uastring.match(expr);
529
+ return match && match.length >= pos && parseInt(match[pos], 10);
530
+ }
531
+ function $9fea4db837311579$export$1f48841962b828b1(window1, eventNameToWrap, wrapper) {
532
+ if (!window1.RTCPeerConnection) return;
533
+ const proto = window1.RTCPeerConnection.prototype;
534
+ const nativeAddEventListener = proto.addEventListener;
535
+ proto.addEventListener = function(nativeEventName, cb) {
536
+ if (nativeEventName !== eventNameToWrap) return nativeAddEventListener.apply(this, arguments);
537
+ const wrappedCallback = (e)=>{
538
+ const modifiedEvent = wrapper(e);
539
+ if (modifiedEvent) {
540
+ if (cb.handleEvent) cb.handleEvent(modifiedEvent);
541
+ else cb(modifiedEvent);
542
+ }
543
+ };
544
+ this._eventMap = this._eventMap || {};
545
+ if (!this._eventMap[eventNameToWrap]) this._eventMap[eventNameToWrap] = new Map();
546
+ this._eventMap[eventNameToWrap].set(cb, wrappedCallback);
547
+ return nativeAddEventListener.apply(this, [
548
+ nativeEventName,
549
+ wrappedCallback
550
+ ]);
551
+ };
552
+ const nativeRemoveEventListener = proto.removeEventListener;
553
+ proto.removeEventListener = function(nativeEventName, cb) {
554
+ if (nativeEventName !== eventNameToWrap || !this._eventMap || !this._eventMap[eventNameToWrap]) return nativeRemoveEventListener.apply(this, arguments);
555
+ if (!this._eventMap[eventNameToWrap].has(cb)) return nativeRemoveEventListener.apply(this, arguments);
556
+ const unwrappedCb = this._eventMap[eventNameToWrap].get(cb);
557
+ this._eventMap[eventNameToWrap].delete(cb);
558
+ if (this._eventMap[eventNameToWrap].size === 0) delete this._eventMap[eventNameToWrap];
559
+ if (Object.keys(this._eventMap).length === 0) delete this._eventMap;
560
+ return nativeRemoveEventListener.apply(this, [
561
+ nativeEventName,
562
+ unwrappedCb
563
+ ]);
564
+ };
565
+ Object.defineProperty(proto, 'on' + eventNameToWrap, {
566
+ get () {
567
+ return this['_on' + eventNameToWrap];
568
+ },
569
+ set (cb) {
570
+ if (this['_on' + eventNameToWrap]) {
571
+ this.removeEventListener(eventNameToWrap, this['_on' + eventNameToWrap]);
572
+ delete this['_on' + eventNameToWrap];
573
+ }
574
+ if (cb) this.addEventListener(eventNameToWrap, this['_on' + eventNameToWrap] = cb);
575
+ },
576
+ enumerable: true,
577
+ configurable: true
578
+ });
579
+ }
580
+ function $9fea4db837311579$export$afbfee8cc06fd3e4(bool) {
581
+ if (typeof bool !== 'boolean') return new Error('Argument type: ' + typeof bool + '. Please use a boolean.');
582
+ $9fea4db837311579$var$logDisabled_ = bool;
583
+ return bool ? 'adapter.js logging disabled' : 'adapter.js logging enabled';
584
+ }
585
+ function $9fea4db837311579$export$51516be4b019e41e(bool) {
586
+ if (typeof bool !== 'boolean') return new Error('Argument type: ' + typeof bool + '. Please use a boolean.');
587
+ $9fea4db837311579$var$deprecationWarnings_ = !bool;
588
+ return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
589
+ }
590
+ function $9fea4db837311579$export$bef1f36f5486a6a3() {
591
+ if (typeof window === 'object') {
592
+ if ($9fea4db837311579$var$logDisabled_) return;
593
+ if (typeof console !== 'undefined' && typeof console.log === 'function') console.log.apply(console, arguments);
594
+ }
595
+ }
596
+ function $9fea4db837311579$export$cdd73fc4100a6ef4(oldMethod, newMethod) {
597
+ if (!$9fea4db837311579$var$deprecationWarnings_) return;
598
+ console.warn(oldMethod + ' is deprecated, please use ' + newMethod + ' instead.');
599
+ }
600
+ function $9fea4db837311579$export$2d31490a0c05f094(window1) {
601
+ // Returned result object.
602
+ const result = {
603
+ browser: null,
604
+ version: null
605
+ };
606
+ // Fail early if it's not a browser
607
+ if (typeof window1 === 'undefined' || !window1.navigator || !window1.navigator.userAgent) {
608
+ result.browser = 'Not a browser.';
609
+ return result;
610
+ }
611
+ const { navigator: navigator } = window1;
612
+ // Prefer navigator.userAgentData.
613
+ if (navigator.userAgentData && navigator.userAgentData.brands) {
614
+ const chromium = navigator.userAgentData.brands.find((brand)=>{
615
+ return brand.brand === 'Chromium';
616
+ });
617
+ if (chromium) return {
618
+ browser: 'chrome',
619
+ version: parseInt(chromium.version, 10)
620
+ };
621
+ }
622
+ if (navigator.mozGetUserMedia) {
623
+ result.browser = 'firefox';
624
+ result.version = $9fea4db837311579$export$e3c02be309be1f23(navigator.userAgent, /Firefox\/(\d+)\./, 1);
625
+ } else if (navigator.webkitGetUserMedia || window1.isSecureContext === false && window1.webkitRTCPeerConnection) {
626
+ // Chrome, Chromium, Webview, Opera.
627
+ // Version matches Chrome/WebRTC version.
628
+ // Chrome 74 removed webkitGetUserMedia on http as well so we need the
629
+ // more complicated fallback to webkitRTCPeerConnection.
630
+ result.browser = 'chrome';
631
+ result.version = $9fea4db837311579$export$e3c02be309be1f23(navigator.userAgent, /Chrom(e|ium)\/(\d+)\./, 2);
632
+ } else if (window1.RTCPeerConnection && navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
633
+ result.browser = 'safari';
634
+ result.version = $9fea4db837311579$export$e3c02be309be1f23(navigator.userAgent, /AppleWebKit\/(\d+)\./, 1);
635
+ result.supportsUnifiedPlan = window1.RTCRtpTransceiver && 'currentDirection' in window1.RTCRtpTransceiver.prototype;
636
+ } else {
637
+ result.browser = 'Not a supported browser.';
638
+ return result;
639
+ }
640
+ return result;
641
+ }
642
+ /**
643
+ * Checks if something is an object.
644
+ *
645
+ * @param {*} val The something you want to check.
646
+ * @return true if val is an object, false otherwise.
647
+ */ function $9fea4db837311579$var$isObject(val) {
648
+ return Object.prototype.toString.call(val) === '[object Object]';
649
+ }
650
+ function $9fea4db837311579$export$15384eac40dc88c8(data) {
651
+ if (!$9fea4db837311579$var$isObject(data)) return data;
652
+ return Object.keys(data).reduce(function(accumulator, key) {
653
+ const isObj = $9fea4db837311579$var$isObject(data[key]);
654
+ const value = isObj ? $9fea4db837311579$export$15384eac40dc88c8(data[key]) : data[key];
655
+ const isEmptyObject = isObj && !Object.keys(value).length;
656
+ if (value === undefined || isEmptyObject) return accumulator;
657
+ return Object.assign(accumulator, {
658
+ [key]: value
659
+ });
660
+ }, {});
661
+ }
662
+ function $9fea4db837311579$export$571b373e75babb58(stats, base, resultSet) {
663
+ if (!base || resultSet.has(base.id)) return;
664
+ resultSet.set(base.id, base);
665
+ Object.keys(base).forEach((name)=>{
666
+ if (name.endsWith('Id')) $9fea4db837311579$export$571b373e75babb58(stats, stats.get(base[name]), resultSet);
667
+ else if (name.endsWith('Ids')) base[name].forEach((id)=>{
668
+ $9fea4db837311579$export$571b373e75babb58(stats, stats.get(id), resultSet);
669
+ });
670
+ });
671
+ }
672
+ function $9fea4db837311579$export$93439ffc3f787d51(result, track, outbound) {
673
+ const streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';
674
+ const filteredResult = new Map();
675
+ if (track === null) return filteredResult;
676
+ const trackStats = [];
677
+ result.forEach((value)=>{
678
+ if (value.type === 'track' && value.trackIdentifier === track.id) trackStats.push(value);
679
+ });
680
+ trackStats.forEach((trackStat)=>{
681
+ result.forEach((stats)=>{
682
+ if (stats.type === streamStatsType && stats.trackId === trackStat.id) $9fea4db837311579$export$571b373e75babb58(result, stats, filteredResult);
683
+ });
684
+ });
685
+ return filteredResult;
686
+ }
687
+
688
+
689
+ var $fb04e59b477f17ce$exports = {};
690
+
691
+ $parcel$export($fb04e59b477f17ce$exports, "shimMediaStream", () => $fb04e59b477f17ce$export$33ee24e7a300bcd1);
692
+ $parcel$export($fb04e59b477f17ce$exports, "shimOnTrack", () => $fb04e59b477f17ce$export$f358708f68ab068);
693
+ $parcel$export($fb04e59b477f17ce$exports, "shimGetSendersWithDtmf", () => $fb04e59b477f17ce$export$a41a030a2842f5d6);
694
+ $parcel$export($fb04e59b477f17ce$exports, "shimSenderReceiverGetStats", () => $fb04e59b477f17ce$export$f2f0f2338114eb4b);
695
+ $parcel$export($fb04e59b477f17ce$exports, "shimAddTrackRemoveTrackWithNative", () => $fb04e59b477f17ce$export$30e3cdd46f8d5100);
696
+ $parcel$export($fb04e59b477f17ce$exports, "shimAddTrackRemoveTrack", () => $fb04e59b477f17ce$export$9588259fcf4ebc91);
697
+ $parcel$export($fb04e59b477f17ce$exports, "shimPeerConnection", () => $fb04e59b477f17ce$export$852a08dda9a55ea7);
698
+ $parcel$export($fb04e59b477f17ce$exports, "fixNegotiationNeeded", () => $fb04e59b477f17ce$export$341293bbeaae37cb);
699
+ $parcel$export($fb04e59b477f17ce$exports, "shimGetUserMedia", () => $de41d89a4eaa283f$export$1ed4910f4d37dc5e);
700
+ /*
701
+ * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
702
+ *
703
+ * Use of this source code is governed by a BSD-style license
704
+ * that can be found in the LICENSE file in the root of the source
705
+ * tree.
706
+ */ /* eslint-env node */
707
+ /*
708
+ * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
709
+ *
710
+ * Use of this source code is governed by a BSD-style license
711
+ * that can be found in the LICENSE file in the root of the source
712
+ * tree.
713
+ */ /* eslint-env node */
714
+ 'use strict';
715
+ const $de41d89a4eaa283f$var$logging = $9fea4db837311579$export$bef1f36f5486a6a3;
716
+ function $de41d89a4eaa283f$export$1ed4910f4d37dc5e(window, browserDetails) {
717
+ const navigator = window && window.navigator;
718
+ if (!navigator.mediaDevices) return;
719
+ const constraintsToChrome_ = function(c) {
720
+ if (typeof c !== 'object' || c.mandatory || c.optional) return c;
721
+ const cc = {};
722
+ Object.keys(c).forEach((key)=>{
723
+ if (key === 'require' || key === 'advanced' || key === 'mediaSource') return;
724
+ const r = typeof c[key] === 'object' ? c[key] : {
725
+ ideal: c[key]
726
+ };
727
+ if (r.exact !== undefined && typeof r.exact === 'number') r.min = r.max = r.exact;
728
+ const oldname_ = function(prefix, name) {
729
+ if (prefix) return prefix + name.charAt(0).toUpperCase() + name.slice(1);
730
+ return name === 'deviceId' ? 'sourceId' : name;
731
+ };
732
+ if (r.ideal !== undefined) {
733
+ cc.optional = cc.optional || [];
734
+ let oc = {};
735
+ if (typeof r.ideal === 'number') {
736
+ oc[oldname_('min', key)] = r.ideal;
737
+ cc.optional.push(oc);
738
+ oc = {};
739
+ oc[oldname_('max', key)] = r.ideal;
740
+ cc.optional.push(oc);
741
+ } else {
742
+ oc[oldname_('', key)] = r.ideal;
743
+ cc.optional.push(oc);
744
+ }
745
+ }
746
+ if (r.exact !== undefined && typeof r.exact !== 'number') {
747
+ cc.mandatory = cc.mandatory || {};
748
+ cc.mandatory[oldname_('', key)] = r.exact;
749
+ } else [
750
+ 'min',
751
+ 'max'
752
+ ].forEach((mix)=>{
753
+ if (r[mix] !== undefined) {
754
+ cc.mandatory = cc.mandatory || {};
755
+ cc.mandatory[oldname_(mix, key)] = r[mix];
756
+ }
757
+ });
758
+ });
759
+ if (c.advanced) cc.optional = (cc.optional || []).concat(c.advanced);
760
+ return cc;
761
+ };
762
+ const shimConstraints_ = function(constraints, func) {
763
+ if (browserDetails.version >= 61) return func(constraints);
764
+ constraints = JSON.parse(JSON.stringify(constraints));
765
+ if (constraints && typeof constraints.audio === 'object') {
766
+ const remap = function(obj, a, b) {
767
+ if (a in obj && !(b in obj)) {
768
+ obj[b] = obj[a];
769
+ delete obj[a];
770
+ }
771
+ };
772
+ constraints = JSON.parse(JSON.stringify(constraints));
773
+ remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
774
+ remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
775
+ constraints.audio = constraintsToChrome_(constraints.audio);
776
+ }
777
+ if (constraints && typeof constraints.video === 'object') {
778
+ // Shim facingMode for mobile & surface pro.
779
+ let face = constraints.video.facingMode;
780
+ face = face && (typeof face === 'object' ? face : {
781
+ ideal: face
782
+ });
783
+ const getSupportedFacingModeLies = browserDetails.version < 66;
784
+ if (face && (face.exact === 'user' || face.exact === 'environment' || face.ideal === 'user' || face.ideal === 'environment') && !(navigator.mediaDevices.getSupportedConstraints && navigator.mediaDevices.getSupportedConstraints().facingMode && !getSupportedFacingModeLies)) {
785
+ delete constraints.video.facingMode;
786
+ let matches;
787
+ if (face.exact === 'environment' || face.ideal === 'environment') matches = [
788
+ 'back',
789
+ 'rear'
790
+ ];
791
+ else if (face.exact === 'user' || face.ideal === 'user') matches = [
792
+ 'front'
793
+ ];
794
+ if (matches) // Look for matches in label, or use last cam for back (typical).
795
+ return navigator.mediaDevices.enumerateDevices().then((devices)=>{
796
+ devices = devices.filter((d)=>d.kind === 'videoinput');
797
+ let dev = devices.find((d)=>matches.some((match)=>d.label.toLowerCase().includes(match)));
798
+ if (!dev && devices.length && matches.includes('back')) dev = devices[devices.length - 1]; // more likely the back cam
799
+ if (dev) constraints.video.deviceId = face.exact ? {
800
+ exact: dev.deviceId
801
+ } : {
802
+ ideal: dev.deviceId
803
+ };
804
+ constraints.video = constraintsToChrome_(constraints.video);
805
+ $de41d89a4eaa283f$var$logging('chrome: ' + JSON.stringify(constraints));
806
+ return func(constraints);
807
+ });
808
+ }
809
+ constraints.video = constraintsToChrome_(constraints.video);
810
+ }
811
+ $de41d89a4eaa283f$var$logging('chrome: ' + JSON.stringify(constraints));
812
+ return func(constraints);
813
+ };
814
+ const shimError_ = function(e) {
815
+ if (browserDetails.version >= 64) return e;
816
+ return {
817
+ name: ({
818
+ PermissionDeniedError: 'NotAllowedError',
819
+ PermissionDismissedError: 'NotAllowedError',
820
+ InvalidStateError: 'NotAllowedError',
821
+ DevicesNotFoundError: 'NotFoundError',
822
+ ConstraintNotSatisfiedError: 'OverconstrainedError',
823
+ TrackStartError: 'NotReadableError',
824
+ MediaDeviceFailedDueToShutdown: 'NotAllowedError',
825
+ MediaDeviceKillSwitchOn: 'NotAllowedError',
826
+ TabCaptureError: 'AbortError',
827
+ ScreenCaptureError: 'AbortError',
828
+ DeviceCaptureError: 'AbortError'
829
+ })[e.name] || e.name,
830
+ message: e.message,
831
+ constraint: e.constraint || e.constraintName,
832
+ toString () {
833
+ return this.name + (this.message && ': ') + this.message;
834
+ }
835
+ };
836
+ };
837
+ const getUserMedia_ = function(constraints, onSuccess, onError) {
838
+ shimConstraints_(constraints, (c)=>{
839
+ navigator.webkitGetUserMedia(c, onSuccess, (e)=>{
840
+ if (onError) onError(shimError_(e));
841
+ });
842
+ });
843
+ };
844
+ navigator.getUserMedia = getUserMedia_.bind(navigator);
845
+ // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
846
+ // function which returns a Promise, it does not accept spec-style
847
+ // constraints.
848
+ if (navigator.mediaDevices.getUserMedia) {
849
+ const origGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
850
+ navigator.mediaDevices.getUserMedia = function(cs) {
851
+ return shimConstraints_(cs, (c)=>origGetUserMedia(c).then((stream)=>{
852
+ if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) {
853
+ stream.getTracks().forEach((track)=>{
854
+ track.stop();
855
+ });
856
+ throw new DOMException('', 'NotFoundError');
857
+ }
858
+ return stream;
859
+ }, (e)=>Promise.reject(shimError_(e))));
860
+ };
861
+ }
862
+ }
863
+
864
+
865
+ 'use strict';
866
+ function $fb04e59b477f17ce$export$33ee24e7a300bcd1(window) {
867
+ window.MediaStream = window.MediaStream || window.webkitMediaStream;
868
+ }
869
+ function $fb04e59b477f17ce$export$f358708f68ab068(window) {
870
+ if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) {
871
+ Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
872
+ get () {
873
+ return this._ontrack;
874
+ },
875
+ set (f) {
876
+ if (this._ontrack) this.removeEventListener('track', this._ontrack);
877
+ this.addEventListener('track', this._ontrack = f);
878
+ },
879
+ enumerable: true,
880
+ configurable: true
881
+ });
882
+ const origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
883
+ window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
884
+ if (!this._ontrackpoly) {
885
+ this._ontrackpoly = (e)=>{
886
+ // onaddstream does not fire when a track is added to an existing
887
+ // stream. But stream.onaddtrack is implemented so we use that.
888
+ e.stream.addEventListener('addtrack', (te)=>{
889
+ let receiver;
890
+ if (window.RTCPeerConnection.prototype.getReceivers) receiver = this.getReceivers().find((r)=>r.track && r.track.id === te.track.id);
891
+ else receiver = {
892
+ track: te.track
893
+ };
894
+ const event = new Event('track');
895
+ event.track = te.track;
896
+ event.receiver = receiver;
897
+ event.transceiver = {
898
+ receiver: receiver
899
+ };
900
+ event.streams = [
901
+ e.stream
902
+ ];
903
+ this.dispatchEvent(event);
904
+ });
905
+ e.stream.getTracks().forEach((track)=>{
906
+ let receiver;
907
+ if (window.RTCPeerConnection.prototype.getReceivers) receiver = this.getReceivers().find((r)=>r.track && r.track.id === track.id);
908
+ else receiver = {
909
+ track: track
910
+ };
911
+ const event = new Event('track');
912
+ event.track = track;
913
+ event.receiver = receiver;
914
+ event.transceiver = {
915
+ receiver: receiver
916
+ };
917
+ event.streams = [
918
+ e.stream
919
+ ];
920
+ this.dispatchEvent(event);
921
+ });
922
+ };
923
+ this.addEventListener('addstream', this._ontrackpoly);
924
+ }
925
+ return origSetRemoteDescription.apply(this, arguments);
926
+ };
927
+ } else // even if RTCRtpTransceiver is in window, it is only used and
928
+ // emitted in unified-plan. Unfortunately this means we need
929
+ // to unconditionally wrap the event.
930
+ $9fea4db837311579$export$1f48841962b828b1(window, 'track', (e)=>{
931
+ if (!e.transceiver) Object.defineProperty(e, 'transceiver', {
932
+ value: {
933
+ receiver: e.receiver
934
+ }
935
+ });
936
+ return e;
937
+ });
938
+ }
939
+ function $fb04e59b477f17ce$export$a41a030a2842f5d6(window) {
940
+ // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
941
+ if (typeof window === 'object' && window.RTCPeerConnection && !('getSenders' in window.RTCPeerConnection.prototype) && 'createDTMFSender' in window.RTCPeerConnection.prototype) {
942
+ const shimSenderWithDtmf = function(pc, track) {
943
+ return {
944
+ track: track,
945
+ get dtmf () {
946
+ if (this._dtmf === undefined) {
947
+ if (track.kind === 'audio') this._dtmf = pc.createDTMFSender(track);
948
+ else this._dtmf = null;
949
+ }
950
+ return this._dtmf;
951
+ },
952
+ _pc: pc
953
+ };
954
+ };
955
+ // augment addTrack when getSenders is not available.
956
+ if (!window.RTCPeerConnection.prototype.getSenders) {
957
+ window.RTCPeerConnection.prototype.getSenders = function getSenders() {
958
+ this._senders = this._senders || [];
959
+ return this._senders.slice(); // return a copy of the internal state.
960
+ };
961
+ const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
962
+ window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
963
+ let sender = origAddTrack.apply(this, arguments);
964
+ if (!sender) {
965
+ sender = shimSenderWithDtmf(this, track);
966
+ this._senders.push(sender);
967
+ }
968
+ return sender;
969
+ };
970
+ const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
971
+ window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
972
+ origRemoveTrack.apply(this, arguments);
973
+ const idx = this._senders.indexOf(sender);
974
+ if (idx !== -1) this._senders.splice(idx, 1);
975
+ };
976
+ }
977
+ const origAddStream = window.RTCPeerConnection.prototype.addStream;
978
+ window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
979
+ this._senders = this._senders || [];
980
+ origAddStream.apply(this, [
981
+ stream
982
+ ]);
983
+ stream.getTracks().forEach((track)=>{
984
+ this._senders.push(shimSenderWithDtmf(this, track));
985
+ });
986
+ };
987
+ const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
988
+ window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
989
+ this._senders = this._senders || [];
990
+ origRemoveStream.apply(this, [
991
+ stream
992
+ ]);
993
+ stream.getTracks().forEach((track)=>{
994
+ const sender = this._senders.find((s)=>s.track === track);
995
+ if (sender) this._senders.splice(this._senders.indexOf(sender), 1);
996
+ });
997
+ };
998
+ } else if (typeof window === 'object' && window.RTCPeerConnection && 'getSenders' in window.RTCPeerConnection.prototype && 'createDTMFSender' in window.RTCPeerConnection.prototype && window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
999
+ const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
1000
+ window.RTCPeerConnection.prototype.getSenders = function getSenders() {
1001
+ const senders = origGetSenders.apply(this, []);
1002
+ senders.forEach((sender)=>sender._pc = this);
1003
+ return senders;
1004
+ };
1005
+ Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
1006
+ get () {
1007
+ if (this._dtmf === undefined) {
1008
+ if (this.track.kind === 'audio') this._dtmf = this._pc.createDTMFSender(this.track);
1009
+ else this._dtmf = null;
1010
+ }
1011
+ return this._dtmf;
1012
+ }
1013
+ });
1014
+ }
1015
+ }
1016
+ function $fb04e59b477f17ce$export$f2f0f2338114eb4b(window) {
1017
+ if (!(typeof window === 'object' && window.RTCPeerConnection && window.RTCRtpSender && window.RTCRtpReceiver)) return;
1018
+ // shim sender stats.
1019
+ if (!('getStats' in window.RTCRtpSender.prototype)) {
1020
+ const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
1021
+ if (origGetSenders) window.RTCPeerConnection.prototype.getSenders = function getSenders() {
1022
+ const senders = origGetSenders.apply(this, []);
1023
+ senders.forEach((sender)=>sender._pc = this);
1024
+ return senders;
1025
+ };
1026
+ const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
1027
+ if (origAddTrack) window.RTCPeerConnection.prototype.addTrack = function addTrack() {
1028
+ const sender = origAddTrack.apply(this, arguments);
1029
+ sender._pc = this;
1030
+ return sender;
1031
+ };
1032
+ window.RTCRtpSender.prototype.getStats = function getStats() {
1033
+ const sender = this;
1034
+ return this._pc.getStats().then((result)=>/* Note: this will include stats of all senders that
1035
+ * send a track with the same id as sender.track as
1036
+ * it is not possible to identify the RTCRtpSender.
1037
+ */ $9fea4db837311579$export$93439ffc3f787d51(result, sender.track, true));
1038
+ };
1039
+ }
1040
+ // shim receiver stats.
1041
+ if (!('getStats' in window.RTCRtpReceiver.prototype)) {
1042
+ const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
1043
+ if (origGetReceivers) window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
1044
+ const receivers = origGetReceivers.apply(this, []);
1045
+ receivers.forEach((receiver)=>receiver._pc = this);
1046
+ return receivers;
1047
+ };
1048
+ $9fea4db837311579$export$1f48841962b828b1(window, 'track', (e)=>{
1049
+ e.receiver._pc = e.srcElement;
1050
+ return e;
1051
+ });
1052
+ window.RTCRtpReceiver.prototype.getStats = function getStats() {
1053
+ const receiver = this;
1054
+ return this._pc.getStats().then((result)=>$9fea4db837311579$export$93439ffc3f787d51(result, receiver.track, false));
1055
+ };
1056
+ }
1057
+ if (!('getStats' in window.RTCRtpSender.prototype && 'getStats' in window.RTCRtpReceiver.prototype)) return;
1058
+ // shim RTCPeerConnection.getStats(track).
1059
+ const origGetStats = window.RTCPeerConnection.prototype.getStats;
1060
+ window.RTCPeerConnection.prototype.getStats = function getStats() {
1061
+ if (arguments.length > 0 && arguments[0] instanceof window.MediaStreamTrack) {
1062
+ const track = arguments[0];
1063
+ let sender;
1064
+ let receiver;
1065
+ let err;
1066
+ this.getSenders().forEach((s)=>{
1067
+ if (s.track === track) {
1068
+ if (sender) err = true;
1069
+ else sender = s;
1070
+ }
1071
+ });
1072
+ this.getReceivers().forEach((r)=>{
1073
+ if (r.track === track) {
1074
+ if (receiver) err = true;
1075
+ else receiver = r;
1076
+ }
1077
+ return r.track === track;
1078
+ });
1079
+ if (err || sender && receiver) return Promise.reject(new DOMException('There are more than one sender or receiver for the track.', 'InvalidAccessError'));
1080
+ else if (sender) return sender.getStats();
1081
+ else if (receiver) return receiver.getStats();
1082
+ return Promise.reject(new DOMException('There is no sender or receiver for the track.', 'InvalidAccessError'));
1083
+ }
1084
+ return origGetStats.apply(this, arguments);
1085
+ };
1086
+ }
1087
+ function $fb04e59b477f17ce$export$30e3cdd46f8d5100(window) {
1088
+ // shim addTrack/removeTrack with native variants in order to make
1089
+ // the interactions with legacy getLocalStreams behave as in other browsers.
1090
+ // Keeps a mapping stream.id => [stream, rtpsenders...]
1091
+ window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
1092
+ this._shimmedLocalStreams = this._shimmedLocalStreams || {};
1093
+ return Object.keys(this._shimmedLocalStreams).map((streamId)=>this._shimmedLocalStreams[streamId][0]);
1094
+ };
1095
+ const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
1096
+ window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
1097
+ if (!stream) return origAddTrack.apply(this, arguments);
1098
+ this._shimmedLocalStreams = this._shimmedLocalStreams || {};
1099
+ const sender = origAddTrack.apply(this, arguments);
1100
+ if (!this._shimmedLocalStreams[stream.id]) this._shimmedLocalStreams[stream.id] = [
1101
+ stream,
1102
+ sender
1103
+ ];
1104
+ else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) this._shimmedLocalStreams[stream.id].push(sender);
1105
+ return sender;
1106
+ };
1107
+ const origAddStream = window.RTCPeerConnection.prototype.addStream;
1108
+ window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
1109
+ this._shimmedLocalStreams = this._shimmedLocalStreams || {};
1110
+ stream.getTracks().forEach((track)=>{
1111
+ const alreadyExists = this.getSenders().find((s)=>s.track === track);
1112
+ if (alreadyExists) throw new DOMException('Track already exists.', 'InvalidAccessError');
1113
+ });
1114
+ const existingSenders = this.getSenders();
1115
+ origAddStream.apply(this, arguments);
1116
+ const newSenders = this.getSenders().filter((newSender)=>existingSenders.indexOf(newSender) === -1);
1117
+ this._shimmedLocalStreams[stream.id] = [
1118
+ stream
1119
+ ].concat(newSenders);
1120
+ };
1121
+ const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
1122
+ window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
1123
+ this._shimmedLocalStreams = this._shimmedLocalStreams || {};
1124
+ delete this._shimmedLocalStreams[stream.id];
1125
+ return origRemoveStream.apply(this, arguments);
1126
+ };
1127
+ const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
1128
+ window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
1129
+ this._shimmedLocalStreams = this._shimmedLocalStreams || {};
1130
+ if (sender) Object.keys(this._shimmedLocalStreams).forEach((streamId)=>{
1131
+ const idx = this._shimmedLocalStreams[streamId].indexOf(sender);
1132
+ if (idx !== -1) this._shimmedLocalStreams[streamId].splice(idx, 1);
1133
+ if (this._shimmedLocalStreams[streamId].length === 1) delete this._shimmedLocalStreams[streamId];
1134
+ });
1135
+ return origRemoveTrack.apply(this, arguments);
1136
+ };
1137
+ }
1138
+ function $fb04e59b477f17ce$export$9588259fcf4ebc91(window, browserDetails) {
1139
+ if (!window.RTCPeerConnection) return;
1140
+ // shim addTrack and removeTrack.
1141
+ if (window.RTCPeerConnection.prototype.addTrack && browserDetails.version >= 65) return $fb04e59b477f17ce$export$30e3cdd46f8d5100(window);
1142
+ // also shim pc.getLocalStreams when addTrack is shimmed
1143
+ // to return the original streams.
1144
+ const origGetLocalStreams = window.RTCPeerConnection.prototype.getLocalStreams;
1145
+ window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
1146
+ const nativeStreams = origGetLocalStreams.apply(this);
1147
+ this._reverseStreams = this._reverseStreams || {};
1148
+ return nativeStreams.map((stream)=>this._reverseStreams[stream.id]);
1149
+ };
1150
+ const origAddStream = window.RTCPeerConnection.prototype.addStream;
1151
+ window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
1152
+ this._streams = this._streams || {};
1153
+ this._reverseStreams = this._reverseStreams || {};
1154
+ stream.getTracks().forEach((track)=>{
1155
+ const alreadyExists = this.getSenders().find((s)=>s.track === track);
1156
+ if (alreadyExists) throw new DOMException('Track already exists.', 'InvalidAccessError');
1157
+ });
1158
+ // Add identity mapping for consistency with addTrack.
1159
+ // Unless this is being used with a stream from addTrack.
1160
+ if (!this._reverseStreams[stream.id]) {
1161
+ const newStream = new window.MediaStream(stream.getTracks());
1162
+ this._streams[stream.id] = newStream;
1163
+ this._reverseStreams[newStream.id] = stream;
1164
+ stream = newStream;
1165
+ }
1166
+ origAddStream.apply(this, [
1167
+ stream
1168
+ ]);
1169
+ };
1170
+ const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
1171
+ window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
1172
+ this._streams = this._streams || {};
1173
+ this._reverseStreams = this._reverseStreams || {};
1174
+ origRemoveStream.apply(this, [
1175
+ this._streams[stream.id] || stream
1176
+ ]);
1177
+ delete this._reverseStreams[this._streams[stream.id] ? this._streams[stream.id].id : stream.id];
1178
+ delete this._streams[stream.id];
1179
+ };
1180
+ window.RTCPeerConnection.prototype.addTrack = function addTrack(track, stream) {
1181
+ if (this.signalingState === 'closed') throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
1182
+ const streams = [].slice.call(arguments, 1);
1183
+ if (streams.length !== 1 || !streams[0].getTracks().find((t)=>t === track)) // this is not fully correct but all we can manage without
1184
+ // [[associated MediaStreams]] internal slot.
1185
+ throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.", 'NotSupportedError');
1186
+ const alreadyExists = this.getSenders().find((s)=>s.track === track);
1187
+ if (alreadyExists) throw new DOMException('Track already exists.', 'InvalidAccessError');
1188
+ this._streams = this._streams || {};
1189
+ this._reverseStreams = this._reverseStreams || {};
1190
+ const oldStream = this._streams[stream.id];
1191
+ if (oldStream) {
1192
+ // this is using odd Chrome behaviour, use with caution:
1193
+ // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
1194
+ // Note: we rely on the high-level addTrack/dtmf shim to
1195
+ // create the sender with a dtmf sender.
1196
+ oldStream.addTrack(track);
1197
+ // Trigger ONN async.
1198
+ Promise.resolve().then(()=>{
1199
+ this.dispatchEvent(new Event('negotiationneeded'));
1200
+ });
1201
+ } else {
1202
+ const newStream = new window.MediaStream([
1203
+ track
1204
+ ]);
1205
+ this._streams[stream.id] = newStream;
1206
+ this._reverseStreams[newStream.id] = stream;
1207
+ this.addStream(newStream);
1208
+ }
1209
+ return this.getSenders().find((s)=>s.track === track);
1210
+ };
1211
+ // replace the internal stream id with the external one and
1212
+ // vice versa.
1213
+ function replaceInternalStreamId(pc, description) {
1214
+ let sdp = description.sdp;
1215
+ Object.keys(pc._reverseStreams || []).forEach((internalId)=>{
1216
+ const externalStream = pc._reverseStreams[internalId];
1217
+ const internalStream = pc._streams[externalStream.id];
1218
+ sdp = sdp.replace(new RegExp(internalStream.id, 'g'), externalStream.id);
1219
+ });
1220
+ return new RTCSessionDescription({
1221
+ type: description.type,
1222
+ sdp: sdp
1223
+ });
1224
+ }
1225
+ function replaceExternalStreamId(pc, description) {
1226
+ let sdp = description.sdp;
1227
+ Object.keys(pc._reverseStreams || []).forEach((internalId)=>{
1228
+ const externalStream = pc._reverseStreams[internalId];
1229
+ const internalStream = pc._streams[externalStream.id];
1230
+ sdp = sdp.replace(new RegExp(externalStream.id, 'g'), internalStream.id);
1231
+ });
1232
+ return new RTCSessionDescription({
1233
+ type: description.type,
1234
+ sdp: sdp
1235
+ });
1236
+ }
1237
+ [
1238
+ 'createOffer',
1239
+ 'createAnswer'
1240
+ ].forEach(function(method) {
1241
+ const nativeMethod = window.RTCPeerConnection.prototype[method];
1242
+ const methodObj = {
1243
+ [method] () {
1244
+ const args = arguments;
1245
+ const isLegacyCall = arguments.length && typeof arguments[0] === 'function';
1246
+ if (isLegacyCall) return nativeMethod.apply(this, [
1247
+ (description)=>{
1248
+ const desc = replaceInternalStreamId(this, description);
1249
+ args[0].apply(null, [
1250
+ desc
1251
+ ]);
1252
+ },
1253
+ (err)=>{
1254
+ if (args[1]) args[1].apply(null, err);
1255
+ },
1256
+ arguments[2]
1257
+ ]);
1258
+ return nativeMethod.apply(this, arguments).then((description)=>replaceInternalStreamId(this, description));
1259
+ }
1260
+ };
1261
+ window.RTCPeerConnection.prototype[method] = methodObj[method];
1262
+ });
1263
+ const origSetLocalDescription = window.RTCPeerConnection.prototype.setLocalDescription;
1264
+ window.RTCPeerConnection.prototype.setLocalDescription = function setLocalDescription() {
1265
+ if (!arguments.length || !arguments[0].type) return origSetLocalDescription.apply(this, arguments);
1266
+ arguments[0] = replaceExternalStreamId(this, arguments[0]);
1267
+ return origSetLocalDescription.apply(this, arguments);
1268
+ };
1269
+ // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
1270
+ const origLocalDescription = Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype, 'localDescription');
1271
+ Object.defineProperty(window.RTCPeerConnection.prototype, 'localDescription', {
1272
+ get () {
1273
+ const description = origLocalDescription.get.apply(this);
1274
+ if (description.type === '') return description;
1275
+ return replaceInternalStreamId(this, description);
1276
+ }
1277
+ });
1278
+ window.RTCPeerConnection.prototype.removeTrack = function removeTrack(sender) {
1279
+ if (this.signalingState === 'closed') throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
1280
+ // We can not yet check for sender instanceof RTCRtpSender
1281
+ // since we shim RTPSender. So we check if sender._pc is set.
1282
+ if (!sender._pc) throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.", 'TypeError');
1283
+ const isLocal = sender._pc === this;
1284
+ if (!isLocal) throw new DOMException('Sender was not created by this connection.', 'InvalidAccessError');
1285
+ // Search for the native stream the senders track belongs to.
1286
+ this._streams = this._streams || {};
1287
+ let stream;
1288
+ Object.keys(this._streams).forEach((streamid)=>{
1289
+ const hasTrack = this._streams[streamid].getTracks().find((track)=>sender.track === track);
1290
+ if (hasTrack) stream = this._streams[streamid];
1291
+ });
1292
+ if (stream) {
1293
+ if (stream.getTracks().length === 1) // if this is the last track of the stream, remove the stream. This
1294
+ // takes care of any shimmed _senders.
1295
+ this.removeStream(this._reverseStreams[stream.id]);
1296
+ else // relying on the same odd chrome behaviour as above.
1297
+ stream.removeTrack(sender.track);
1298
+ this.dispatchEvent(new Event('negotiationneeded'));
1299
+ }
1300
+ };
1301
+ }
1302
+ function $fb04e59b477f17ce$export$852a08dda9a55ea7(window, browserDetails) {
1303
+ if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) // very basic support for old versions.
1304
+ window.RTCPeerConnection = window.webkitRTCPeerConnection;
1305
+ if (!window.RTCPeerConnection) return;
1306
+ // shim implicit creation of RTCSessionDescription/RTCIceCandidate
1307
+ if (browserDetails.version < 53) [
1308
+ 'setLocalDescription',
1309
+ 'setRemoteDescription',
1310
+ 'addIceCandidate'
1311
+ ].forEach(function(method) {
1312
+ const nativeMethod = window.RTCPeerConnection.prototype[method];
1313
+ const methodObj = {
1314
+ [method] () {
1315
+ arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
1316
+ return nativeMethod.apply(this, arguments);
1317
+ }
1318
+ };
1319
+ window.RTCPeerConnection.prototype[method] = methodObj[method];
1320
+ });
1321
+ }
1322
+ function $fb04e59b477f17ce$export$341293bbeaae37cb(window, browserDetails) {
1323
+ $9fea4db837311579$export$1f48841962b828b1(window, 'negotiationneeded', (e)=>{
1324
+ const pc = e.target;
1325
+ if (browserDetails.version < 72 || pc.getConfiguration && pc.getConfiguration().sdpSemantics === 'plan-b') {
1326
+ if (pc.signalingState !== 'stable') return;
1327
+ }
1328
+ return e;
1329
+ });
1330
+ }
1331
+
1332
+
1333
+ var $215e6581d7a09c61$exports = {};
1334
+
1335
+ $parcel$export($215e6581d7a09c61$exports, "shimOnTrack", () => $215e6581d7a09c61$export$f358708f68ab068);
1336
+ $parcel$export($215e6581d7a09c61$exports, "shimPeerConnection", () => $215e6581d7a09c61$export$852a08dda9a55ea7);
1337
+ $parcel$export($215e6581d7a09c61$exports, "shimSenderGetStats", () => $215e6581d7a09c61$export$f0525502095c04ef);
1338
+ $parcel$export($215e6581d7a09c61$exports, "shimReceiverGetStats", () => $215e6581d7a09c61$export$83d69126527b1171);
1339
+ $parcel$export($215e6581d7a09c61$exports, "shimRemoveStream", () => $215e6581d7a09c61$export$825e523ef749bd8c);
1340
+ $parcel$export($215e6581d7a09c61$exports, "shimRTCDataChannel", () => $215e6581d7a09c61$export$ff9cb3bc8990e8f7);
1341
+ $parcel$export($215e6581d7a09c61$exports, "shimAddTransceiver", () => $215e6581d7a09c61$export$70c77533b6e9908d);
1342
+ $parcel$export($215e6581d7a09c61$exports, "shimGetParameters", () => $215e6581d7a09c61$export$66238223c298fbaa);
1343
+ $parcel$export($215e6581d7a09c61$exports, "shimCreateOffer", () => $215e6581d7a09c61$export$51beccf0e777b843);
1344
+ $parcel$export($215e6581d7a09c61$exports, "shimCreateAnswer", () => $215e6581d7a09c61$export$df0b46e7cef08150);
1345
+ $parcel$export($215e6581d7a09c61$exports, "shimGetUserMedia", () => $6c9e5f7e9edd1e60$export$1ed4910f4d37dc5e);
1346
+ $parcel$export($215e6581d7a09c61$exports, "shimGetDisplayMedia", () => $c12684406b986df8$export$97270b87351d9c04);
1347
+ /*
1348
+ * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
1349
+ *
1350
+ * Use of this source code is governed by a BSD-style license
1351
+ * that can be found in the LICENSE file in the root of the source
1352
+ * tree.
1353
+ */ /* eslint-env node */
1354
+ /*
1355
+ * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
1356
+ *
1357
+ * Use of this source code is governed by a BSD-style license
1358
+ * that can be found in the LICENSE file in the root of the source
1359
+ * tree.
1360
+ */ /* eslint-env node */
1361
+ 'use strict';
1362
+ function $6c9e5f7e9edd1e60$export$1ed4910f4d37dc5e(window, browserDetails) {
1363
+ const navigator = window && window.navigator;
1364
+ const MediaStreamTrack = window && window.MediaStreamTrack;
1365
+ navigator.getUserMedia = function(constraints, onSuccess, onError) {
1366
+ // Replace Firefox 44+'s deprecation warning with unprefixed version.
1367
+ $9fea4db837311579$export$cdd73fc4100a6ef4('navigator.getUserMedia', 'navigator.mediaDevices.getUserMedia');
1368
+ navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
1369
+ };
1370
+ if (!(browserDetails.version > 55 && 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
1371
+ const remap = function(obj, a, b) {
1372
+ if (a in obj && !(b in obj)) {
1373
+ obj[b] = obj[a];
1374
+ delete obj[a];
1375
+ }
1376
+ };
1377
+ const nativeGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
1378
+ navigator.mediaDevices.getUserMedia = function(c) {
1379
+ if (typeof c === 'object' && typeof c.audio === 'object') {
1380
+ c = JSON.parse(JSON.stringify(c));
1381
+ remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
1382
+ remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
1383
+ }
1384
+ return nativeGetUserMedia(c);
1385
+ };
1386
+ if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
1387
+ const nativeGetSettings = MediaStreamTrack.prototype.getSettings;
1388
+ MediaStreamTrack.prototype.getSettings = function() {
1389
+ const obj = nativeGetSettings.apply(this, arguments);
1390
+ remap(obj, 'mozAutoGainControl', 'autoGainControl');
1391
+ remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
1392
+ return obj;
1393
+ };
1394
+ }
1395
+ if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
1396
+ const nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints;
1397
+ MediaStreamTrack.prototype.applyConstraints = function(c) {
1398
+ if (this.kind === 'audio' && typeof c === 'object') {
1399
+ c = JSON.parse(JSON.stringify(c));
1400
+ remap(c, 'autoGainControl', 'mozAutoGainControl');
1401
+ remap(c, 'noiseSuppression', 'mozNoiseSuppression');
1402
+ }
1403
+ return nativeApplyConstraints.apply(this, [
1404
+ c
1405
+ ]);
1406
+ };
1407
+ }
1408
+ }
1409
+ }
1410
+
1411
+
1412
+ /*
1413
+ * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
1414
+ *
1415
+ * Use of this source code is governed by a BSD-style license
1416
+ * that can be found in the LICENSE file in the root of the source
1417
+ * tree.
1418
+ */ /* eslint-env node */ 'use strict';
1419
+ function $c12684406b986df8$export$97270b87351d9c04(window, preferredMediaSource) {
1420
+ if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) return;
1421
+ if (!window.navigator.mediaDevices) return;
1422
+ window.navigator.mediaDevices.getDisplayMedia = function getDisplayMedia(constraints) {
1423
+ if (!(constraints && constraints.video)) {
1424
+ const err = new DOMException("getDisplayMedia without video constraints is undefined");
1425
+ err.name = 'NotFoundError';
1426
+ // from https://heycam.github.io/webidl/#idl-DOMException-error-names
1427
+ err.code = 8;
1428
+ return Promise.reject(err);
1429
+ }
1430
+ if (constraints.video === true) constraints.video = {
1431
+ mediaSource: preferredMediaSource
1432
+ };
1433
+ else constraints.video.mediaSource = preferredMediaSource;
1434
+ return window.navigator.mediaDevices.getUserMedia(constraints);
1435
+ };
1436
+ }
1437
+
1438
+
1439
+ 'use strict';
1440
+ function $215e6581d7a09c61$export$f358708f68ab068(window) {
1441
+ if (typeof window === 'object' && window.RTCTrackEvent && 'receiver' in window.RTCTrackEvent.prototype && !('transceiver' in window.RTCTrackEvent.prototype)) Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
1442
+ get () {
1443
+ return {
1444
+ receiver: this.receiver
1445
+ };
1446
+ }
1447
+ });
1448
+ }
1449
+ function $215e6581d7a09c61$export$852a08dda9a55ea7(window, browserDetails) {
1450
+ if (typeof window !== 'object' || !(window.RTCPeerConnection || window.mozRTCPeerConnection)) return; // probably media.peerconnection.enabled=false in about:config
1451
+ if (!window.RTCPeerConnection && window.mozRTCPeerConnection) // very basic support for old versions.
1452
+ window.RTCPeerConnection = window.mozRTCPeerConnection;
1453
+ if (browserDetails.version < 53) // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
1454
+ [
1455
+ 'setLocalDescription',
1456
+ 'setRemoteDescription',
1457
+ 'addIceCandidate'
1458
+ ].forEach(function(method) {
1459
+ const nativeMethod = window.RTCPeerConnection.prototype[method];
1460
+ const methodObj = {
1461
+ [method] () {
1462
+ arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
1463
+ return nativeMethod.apply(this, arguments);
1464
+ }
1465
+ };
1466
+ window.RTCPeerConnection.prototype[method] = methodObj[method];
1467
+ });
1468
+ const modernStatsTypes = {
1469
+ inboundrtp: 'inbound-rtp',
1470
+ outboundrtp: 'outbound-rtp',
1471
+ candidatepair: 'candidate-pair',
1472
+ localcandidate: 'local-candidate',
1473
+ remotecandidate: 'remote-candidate'
1474
+ };
1475
+ const nativeGetStats = window.RTCPeerConnection.prototype.getStats;
1476
+ window.RTCPeerConnection.prototype.getStats = function getStats() {
1477
+ const [selector, onSucc, onErr] = arguments;
1478
+ return nativeGetStats.apply(this, [
1479
+ selector || null
1480
+ ]).then((stats)=>{
1481
+ if (browserDetails.version < 53 && !onSucc) // Shim only promise getStats with spec-hyphens in type names
1482
+ // Leave callback version alone; misc old uses of forEach before Map
1483
+ try {
1484
+ stats.forEach((stat)=>{
1485
+ stat.type = modernStatsTypes[stat.type] || stat.type;
1486
+ });
1487
+ } catch (e) {
1488
+ if (e.name !== 'TypeError') throw e;
1489
+ // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
1490
+ stats.forEach((stat, i)=>{
1491
+ stats.set(i, Object.assign({}, stat, {
1492
+ type: modernStatsTypes[stat.type] || stat.type
1493
+ }));
1494
+ });
1495
+ }
1496
+ return stats;
1497
+ }).then(onSucc, onErr);
1498
+ };
1499
+ }
1500
+ function $215e6581d7a09c61$export$f0525502095c04ef(window) {
1501
+ if (!(typeof window === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) return;
1502
+ if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) return;
1503
+ const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
1504
+ if (origGetSenders) window.RTCPeerConnection.prototype.getSenders = function getSenders() {
1505
+ const senders = origGetSenders.apply(this, []);
1506
+ senders.forEach((sender)=>sender._pc = this);
1507
+ return senders;
1508
+ };
1509
+ const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
1510
+ if (origAddTrack) window.RTCPeerConnection.prototype.addTrack = function addTrack() {
1511
+ const sender = origAddTrack.apply(this, arguments);
1512
+ sender._pc = this;
1513
+ return sender;
1514
+ };
1515
+ window.RTCRtpSender.prototype.getStats = function getStats() {
1516
+ return this.track ? this._pc.getStats(this.track) : Promise.resolve(new Map());
1517
+ };
1518
+ }
1519
+ function $215e6581d7a09c61$export$83d69126527b1171(window) {
1520
+ if (!(typeof window === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) return;
1521
+ if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) return;
1522
+ const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
1523
+ if (origGetReceivers) window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
1524
+ const receivers = origGetReceivers.apply(this, []);
1525
+ receivers.forEach((receiver)=>receiver._pc = this);
1526
+ return receivers;
1527
+ };
1528
+ $9fea4db837311579$export$1f48841962b828b1(window, 'track', (e)=>{
1529
+ e.receiver._pc = e.srcElement;
1530
+ return e;
1531
+ });
1532
+ window.RTCRtpReceiver.prototype.getStats = function getStats() {
1533
+ return this._pc.getStats(this.track);
1534
+ };
1535
+ }
1536
+ function $215e6581d7a09c61$export$825e523ef749bd8c(window) {
1537
+ if (!window.RTCPeerConnection || 'removeStream' in window.RTCPeerConnection.prototype) return;
1538
+ window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
1539
+ $9fea4db837311579$export$cdd73fc4100a6ef4('removeStream', 'removeTrack');
1540
+ this.getSenders().forEach((sender)=>{
1541
+ if (sender.track && stream.getTracks().includes(sender.track)) this.removeTrack(sender);
1542
+ });
1543
+ };
1544
+ }
1545
+ function $215e6581d7a09c61$export$ff9cb3bc8990e8f7(window) {
1546
+ // rename DataChannel to RTCDataChannel (native fix in FF60):
1547
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851
1548
+ if (window.DataChannel && !window.RTCDataChannel) window.RTCDataChannel = window.DataChannel;
1549
+ }
1550
+ function $215e6581d7a09c61$export$70c77533b6e9908d(window) {
1551
+ // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
1552
+ // Firefox ignores the init sendEncodings options passed to addTransceiver
1553
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
1554
+ if (!(typeof window === 'object' && window.RTCPeerConnection)) return;
1555
+ const origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;
1556
+ if (origAddTransceiver) window.RTCPeerConnection.prototype.addTransceiver = function addTransceiver() {
1557
+ this.setParametersPromises = [];
1558
+ // WebIDL input coercion and validation
1559
+ let sendEncodings = arguments[1] && arguments[1].sendEncodings;
1560
+ if (sendEncodings === undefined) sendEncodings = [];
1561
+ sendEncodings = [
1562
+ ...sendEncodings
1563
+ ];
1564
+ const shouldPerformCheck = sendEncodings.length > 0;
1565
+ if (shouldPerformCheck) // If sendEncodings params are provided, validate grammar
1566
+ sendEncodings.forEach((encodingParam)=>{
1567
+ if ('rid' in encodingParam) {
1568
+ const ridRegex = /^[a-z0-9]{0,16}$/i;
1569
+ if (!ridRegex.test(encodingParam.rid)) throw new TypeError('Invalid RID value provided.');
1570
+ }
1571
+ if ('scaleResolutionDownBy' in encodingParam) {
1572
+ if (!(parseFloat(encodingParam.scaleResolutionDownBy) >= 1.0)) throw new RangeError('scale_resolution_down_by must be >= 1.0');
1573
+ }
1574
+ if ('maxFramerate' in encodingParam) {
1575
+ if (!(parseFloat(encodingParam.maxFramerate) >= 0)) throw new RangeError('max_framerate must be >= 0.0');
1576
+ }
1577
+ });
1578
+ const transceiver = origAddTransceiver.apply(this, arguments);
1579
+ if (shouldPerformCheck) {
1580
+ // Check if the init options were applied. If not we do this in an
1581
+ // asynchronous way and save the promise reference in a global object.
1582
+ // This is an ugly hack, but at the same time is way more robust than
1583
+ // checking the sender parameters before and after the createOffer
1584
+ // Also note that after the createoffer we are not 100% sure that
1585
+ // the params were asynchronously applied so we might miss the
1586
+ // opportunity to recreate offer.
1587
+ const { sender: sender } = transceiver;
1588
+ const params = sender.getParameters();
1589
+ if (!('encodings' in params) || // Avoid being fooled by patched getParameters() below.
1590
+ params.encodings.length === 1 && Object.keys(params.encodings[0]).length === 0) {
1591
+ params.encodings = sendEncodings;
1592
+ sender.sendEncodings = sendEncodings;
1593
+ this.setParametersPromises.push(sender.setParameters(params).then(()=>{
1594
+ delete sender.sendEncodings;
1595
+ }).catch(()=>{
1596
+ delete sender.sendEncodings;
1597
+ }));
1598
+ }
1599
+ }
1600
+ return transceiver;
1601
+ };
1602
+ }
1603
+ function $215e6581d7a09c61$export$66238223c298fbaa(window) {
1604
+ if (!(typeof window === 'object' && window.RTCRtpSender)) return;
1605
+ const origGetParameters = window.RTCRtpSender.prototype.getParameters;
1606
+ if (origGetParameters) window.RTCRtpSender.prototype.getParameters = function getParameters() {
1607
+ const params = origGetParameters.apply(this, arguments);
1608
+ if (!('encodings' in params)) params.encodings = [].concat(this.sendEncodings || [
1609
+ {}
1610
+ ]);
1611
+ return params;
1612
+ };
1613
+ }
1614
+ function $215e6581d7a09c61$export$51beccf0e777b843(window) {
1615
+ // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
1616
+ // Firefox ignores the init sendEncodings options passed to addTransceiver
1617
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
1618
+ if (!(typeof window === 'object' && window.RTCPeerConnection)) return;
1619
+ const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
1620
+ window.RTCPeerConnection.prototype.createOffer = function createOffer() {
1621
+ if (this.setParametersPromises && this.setParametersPromises.length) return Promise.all(this.setParametersPromises).then(()=>{
1622
+ return origCreateOffer.apply(this, arguments);
1623
+ }).finally(()=>{
1624
+ this.setParametersPromises = [];
1625
+ });
1626
+ return origCreateOffer.apply(this, arguments);
1627
+ };
1628
+ }
1629
+ function $215e6581d7a09c61$export$df0b46e7cef08150(window) {
1630
+ // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
1631
+ // Firefox ignores the init sendEncodings options passed to addTransceiver
1632
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
1633
+ if (!(typeof window === 'object' && window.RTCPeerConnection)) return;
1634
+ const origCreateAnswer = window.RTCPeerConnection.prototype.createAnswer;
1635
+ window.RTCPeerConnection.prototype.createAnswer = function createAnswer() {
1636
+ if (this.setParametersPromises && this.setParametersPromises.length) return Promise.all(this.setParametersPromises).then(()=>{
1637
+ return origCreateAnswer.apply(this, arguments);
1638
+ }).finally(()=>{
1639
+ this.setParametersPromises = [];
1640
+ });
1641
+ return origCreateAnswer.apply(this, arguments);
1642
+ };
1643
+ }
1644
+
1645
+
1646
+ var $c1f641ee5a6f6c8f$exports = {};
1647
+
1648
+ $parcel$export($c1f641ee5a6f6c8f$exports, "shimLocalStreamsAPI", () => $c1f641ee5a6f6c8f$export$8df41282f4fdcea2);
1649
+ $parcel$export($c1f641ee5a6f6c8f$exports, "shimRemoteStreamsAPI", () => $c1f641ee5a6f6c8f$export$762aa4cbb4f2f857);
1650
+ $parcel$export($c1f641ee5a6f6c8f$exports, "shimCallbacksAPI", () => $c1f641ee5a6f6c8f$export$da31df245debdd3);
1651
+ $parcel$export($c1f641ee5a6f6c8f$exports, "shimGetUserMedia", () => $c1f641ee5a6f6c8f$export$1ed4910f4d37dc5e);
1652
+ $parcel$export($c1f641ee5a6f6c8f$exports, "shimConstraints", () => $c1f641ee5a6f6c8f$export$494a01ac68ba81ac);
1653
+ $parcel$export($c1f641ee5a6f6c8f$exports, "shimRTCIceServerUrls", () => $c1f641ee5a6f6c8f$export$671a8b47b41b6f41);
1654
+ $parcel$export($c1f641ee5a6f6c8f$exports, "shimTrackEventTransceiver", () => $c1f641ee5a6f6c8f$export$85d53da088cb1b14);
1655
+ $parcel$export($c1f641ee5a6f6c8f$exports, "shimCreateOfferLegacy", () => $c1f641ee5a6f6c8f$export$d444266503fdd2d4);
1656
+ $parcel$export($c1f641ee5a6f6c8f$exports, "shimAudioContext", () => $c1f641ee5a6f6c8f$export$857cd739a7b795d2);
1657
+ /*
1658
+ * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
1659
+ *
1660
+ * Use of this source code is governed by a BSD-style license
1661
+ * that can be found in the LICENSE file in the root of the source
1662
+ * tree.
1663
+ */
1664
+ 'use strict';
1665
+ function $c1f641ee5a6f6c8f$export$8df41282f4fdcea2(window) {
1666
+ if (typeof window !== 'object' || !window.RTCPeerConnection) return;
1667
+ if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) window.RTCPeerConnection.prototype.getLocalStreams = function getLocalStreams() {
1668
+ if (!this._localStreams) this._localStreams = [];
1669
+ return this._localStreams;
1670
+ };
1671
+ if (!('addStream' in window.RTCPeerConnection.prototype)) {
1672
+ const _addTrack = window.RTCPeerConnection.prototype.addTrack;
1673
+ window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
1674
+ if (!this._localStreams) this._localStreams = [];
1675
+ if (!this._localStreams.includes(stream)) this._localStreams.push(stream);
1676
+ // Try to emulate Chrome's behaviour of adding in audio-video order.
1677
+ // Safari orders by track id.
1678
+ stream.getAudioTracks().forEach((track)=>_addTrack.call(this, track, stream));
1679
+ stream.getVideoTracks().forEach((track)=>_addTrack.call(this, track, stream));
1680
+ };
1681
+ window.RTCPeerConnection.prototype.addTrack = function addTrack(track, ...streams) {
1682
+ if (streams) streams.forEach((stream)=>{
1683
+ if (!this._localStreams) this._localStreams = [
1684
+ stream
1685
+ ];
1686
+ else if (!this._localStreams.includes(stream)) this._localStreams.push(stream);
1687
+ });
1688
+ return _addTrack.apply(this, arguments);
1689
+ };
1690
+ }
1691
+ if (!('removeStream' in window.RTCPeerConnection.prototype)) window.RTCPeerConnection.prototype.removeStream = function removeStream(stream) {
1692
+ if (!this._localStreams) this._localStreams = [];
1693
+ const index = this._localStreams.indexOf(stream);
1694
+ if (index === -1) return;
1695
+ this._localStreams.splice(index, 1);
1696
+ const tracks = stream.getTracks();
1697
+ this.getSenders().forEach((sender)=>{
1698
+ if (tracks.includes(sender.track)) this.removeTrack(sender);
1699
+ });
1700
+ };
1701
+ }
1702
+ function $c1f641ee5a6f6c8f$export$762aa4cbb4f2f857(window) {
1703
+ if (typeof window !== 'object' || !window.RTCPeerConnection) return;
1704
+ if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) window.RTCPeerConnection.prototype.getRemoteStreams = function getRemoteStreams() {
1705
+ return this._remoteStreams ? this._remoteStreams : [];
1706
+ };
1707
+ if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
1708
+ Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
1709
+ get () {
1710
+ return this._onaddstream;
1711
+ },
1712
+ set (f) {
1713
+ if (this._onaddstream) {
1714
+ this.removeEventListener('addstream', this._onaddstream);
1715
+ this.removeEventListener('track', this._onaddstreampoly);
1716
+ }
1717
+ this.addEventListener('addstream', this._onaddstream = f);
1718
+ this.addEventListener('track', this._onaddstreampoly = (e)=>{
1719
+ e.streams.forEach((stream)=>{
1720
+ if (!this._remoteStreams) this._remoteStreams = [];
1721
+ if (this._remoteStreams.includes(stream)) return;
1722
+ this._remoteStreams.push(stream);
1723
+ const event = new Event('addstream');
1724
+ event.stream = stream;
1725
+ this.dispatchEvent(event);
1726
+ });
1727
+ });
1728
+ }
1729
+ });
1730
+ const origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
1731
+ window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
1732
+ const pc = this;
1733
+ if (!this._onaddstreampoly) this.addEventListener('track', this._onaddstreampoly = function(e) {
1734
+ e.streams.forEach((stream)=>{
1735
+ if (!pc._remoteStreams) pc._remoteStreams = [];
1736
+ if (pc._remoteStreams.indexOf(stream) >= 0) return;
1737
+ pc._remoteStreams.push(stream);
1738
+ const event = new Event('addstream');
1739
+ event.stream = stream;
1740
+ pc.dispatchEvent(event);
1741
+ });
1742
+ });
1743
+ return origSetRemoteDescription.apply(pc, arguments);
1744
+ };
1745
+ }
1746
+ }
1747
+ function $c1f641ee5a6f6c8f$export$da31df245debdd3(window) {
1748
+ if (typeof window !== 'object' || !window.RTCPeerConnection) return;
1749
+ const prototype = window.RTCPeerConnection.prototype;
1750
+ const origCreateOffer = prototype.createOffer;
1751
+ const origCreateAnswer = prototype.createAnswer;
1752
+ const setLocalDescription = prototype.setLocalDescription;
1753
+ const setRemoteDescription = prototype.setRemoteDescription;
1754
+ const addIceCandidate = prototype.addIceCandidate;
1755
+ prototype.createOffer = function createOffer(successCallback, failureCallback) {
1756
+ const options = arguments.length >= 2 ? arguments[2] : arguments[0];
1757
+ const promise = origCreateOffer.apply(this, [
1758
+ options
1759
+ ]);
1760
+ if (!failureCallback) return promise;
1761
+ promise.then(successCallback, failureCallback);
1762
+ return Promise.resolve();
1763
+ };
1764
+ prototype.createAnswer = function createAnswer(successCallback, failureCallback) {
1765
+ const options = arguments.length >= 2 ? arguments[2] : arguments[0];
1766
+ const promise = origCreateAnswer.apply(this, [
1767
+ options
1768
+ ]);
1769
+ if (!failureCallback) return promise;
1770
+ promise.then(successCallback, failureCallback);
1771
+ return Promise.resolve();
1772
+ };
1773
+ let withCallback = function(description, successCallback, failureCallback) {
1774
+ const promise = setLocalDescription.apply(this, [
1775
+ description
1776
+ ]);
1777
+ if (!failureCallback) return promise;
1778
+ promise.then(successCallback, failureCallback);
1779
+ return Promise.resolve();
1780
+ };
1781
+ prototype.setLocalDescription = withCallback;
1782
+ withCallback = function(description, successCallback, failureCallback) {
1783
+ const promise = setRemoteDescription.apply(this, [
1784
+ description
1785
+ ]);
1786
+ if (!failureCallback) return promise;
1787
+ promise.then(successCallback, failureCallback);
1788
+ return Promise.resolve();
1789
+ };
1790
+ prototype.setRemoteDescription = withCallback;
1791
+ withCallback = function(candidate, successCallback, failureCallback) {
1792
+ const promise = addIceCandidate.apply(this, [
1793
+ candidate
1794
+ ]);
1795
+ if (!failureCallback) return promise;
1796
+ promise.then(successCallback, failureCallback);
1797
+ return Promise.resolve();
1798
+ };
1799
+ prototype.addIceCandidate = withCallback;
1800
+ }
1801
+ function $c1f641ee5a6f6c8f$export$1ed4910f4d37dc5e(window) {
1802
+ const navigator = window && window.navigator;
1803
+ if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
1804
+ // shim not needed in Safari 12.1
1805
+ const mediaDevices = navigator.mediaDevices;
1806
+ const _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);
1807
+ navigator.mediaDevices.getUserMedia = (constraints)=>{
1808
+ return _getUserMedia($c1f641ee5a6f6c8f$export$494a01ac68ba81ac(constraints));
1809
+ };
1810
+ }
1811
+ if (!navigator.getUserMedia && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) navigator.getUserMedia = (function getUserMedia(constraints, cb, errcb) {
1812
+ navigator.mediaDevices.getUserMedia(constraints).then(cb, errcb);
1813
+ }).bind(navigator);
1814
+ }
1815
+ function $c1f641ee5a6f6c8f$export$494a01ac68ba81ac(constraints) {
1816
+ if (constraints && constraints.video !== undefined) return Object.assign({}, constraints, {
1817
+ video: $9fea4db837311579$export$15384eac40dc88c8(constraints.video)
1818
+ });
1819
+ return constraints;
1820
+ }
1821
+ function $c1f641ee5a6f6c8f$export$671a8b47b41b6f41(window) {
1822
+ if (!window.RTCPeerConnection) return;
1823
+ // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
1824
+ const OrigPeerConnection = window.RTCPeerConnection;
1825
+ window.RTCPeerConnection = function RTCPeerConnection(pcConfig, pcConstraints) {
1826
+ if (pcConfig && pcConfig.iceServers) {
1827
+ const newIceServers = [];
1828
+ for(let i = 0; i < pcConfig.iceServers.length; i++){
1829
+ let server = pcConfig.iceServers[i];
1830
+ if (server.urls === undefined && server.url) {
1831
+ $9fea4db837311579$export$cdd73fc4100a6ef4('RTCIceServer.url', 'RTCIceServer.urls');
1832
+ server = JSON.parse(JSON.stringify(server));
1833
+ server.urls = server.url;
1834
+ delete server.url;
1835
+ newIceServers.push(server);
1836
+ } else newIceServers.push(pcConfig.iceServers[i]);
1837
+ }
1838
+ pcConfig.iceServers = newIceServers;
1839
+ }
1840
+ return new OrigPeerConnection(pcConfig, pcConstraints);
1841
+ };
1842
+ window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
1843
+ // wrap static methods. Currently just generateCertificate.
1844
+ if ('generateCertificate' in OrigPeerConnection) Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
1845
+ get () {
1846
+ return OrigPeerConnection.generateCertificate;
1847
+ }
1848
+ });
1849
+ }
1850
+ function $c1f641ee5a6f6c8f$export$85d53da088cb1b14(window) {
1851
+ // Add event.transceiver member over deprecated event.receiver
1852
+ if (typeof window === 'object' && window.RTCTrackEvent && 'receiver' in window.RTCTrackEvent.prototype && !('transceiver' in window.RTCTrackEvent.prototype)) Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
1853
+ get () {
1854
+ return {
1855
+ receiver: this.receiver
1856
+ };
1857
+ }
1858
+ });
1859
+ }
1860
+ function $c1f641ee5a6f6c8f$export$d444266503fdd2d4(window) {
1861
+ const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
1862
+ window.RTCPeerConnection.prototype.createOffer = function createOffer(offerOptions) {
1863
+ if (offerOptions) {
1864
+ if (typeof offerOptions.offerToReceiveAudio !== 'undefined') // support bit values
1865
+ offerOptions.offerToReceiveAudio = !!offerOptions.offerToReceiveAudio;
1866
+ const audioTransceiver = this.getTransceivers().find((transceiver)=>transceiver.receiver.track.kind === 'audio');
1867
+ if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
1868
+ if (audioTransceiver.direction === 'sendrecv') {
1869
+ if (audioTransceiver.setDirection) audioTransceiver.setDirection('sendonly');
1870
+ else audioTransceiver.direction = 'sendonly';
1871
+ } else if (audioTransceiver.direction === 'recvonly') {
1872
+ if (audioTransceiver.setDirection) audioTransceiver.setDirection('inactive');
1873
+ else audioTransceiver.direction = 'inactive';
1874
+ }
1875
+ } else if (offerOptions.offerToReceiveAudio === true && !audioTransceiver) this.addTransceiver('audio', {
1876
+ direction: 'recvonly'
1877
+ });
1878
+ if (typeof offerOptions.offerToReceiveVideo !== 'undefined') // support bit values
1879
+ offerOptions.offerToReceiveVideo = !!offerOptions.offerToReceiveVideo;
1880
+ const videoTransceiver = this.getTransceivers().find((transceiver)=>transceiver.receiver.track.kind === 'video');
1881
+ if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
1882
+ if (videoTransceiver.direction === 'sendrecv') {
1883
+ if (videoTransceiver.setDirection) videoTransceiver.setDirection('sendonly');
1884
+ else videoTransceiver.direction = 'sendonly';
1885
+ } else if (videoTransceiver.direction === 'recvonly') {
1886
+ if (videoTransceiver.setDirection) videoTransceiver.setDirection('inactive');
1887
+ else videoTransceiver.direction = 'inactive';
1888
+ }
1889
+ } else if (offerOptions.offerToReceiveVideo === true && !videoTransceiver) this.addTransceiver('video', {
1890
+ direction: 'recvonly'
1891
+ });
1892
+ }
1893
+ return origCreateOffer.apply(this, arguments);
1894
+ };
1895
+ }
1896
+ function $c1f641ee5a6f6c8f$export$857cd739a7b795d2(window) {
1897
+ if (typeof window !== 'object' || window.AudioContext) return;
1898
+ window.AudioContext = window.webkitAudioContext;
1899
+ }
1900
+
1901
+
1902
+ var $5151b78094cea2ba$exports = {};
1903
+
1904
+ $parcel$export($5151b78094cea2ba$exports, "shimRTCIceCandidate", () => $5151b78094cea2ba$export$cf133661e444ccfe);
1905
+ $parcel$export($5151b78094cea2ba$exports, "shimRTCIceCandidateRelayProtocol", () => $5151b78094cea2ba$export$fdafb8d8280e29b5);
1906
+ $parcel$export($5151b78094cea2ba$exports, "shimMaxMessageSize", () => $5151b78094cea2ba$export$a99147c78a56edc4);
1907
+ $parcel$export($5151b78094cea2ba$exports, "shimSendThrowTypeError", () => $5151b78094cea2ba$export$d461c8d5c5db5da7);
1908
+ $parcel$export($5151b78094cea2ba$exports, "shimConnectionState", () => $5151b78094cea2ba$export$63bb816cc75460);
1909
+ $parcel$export($5151b78094cea2ba$exports, "removeExtmapAllowMixed", () => $5151b78094cea2ba$export$a57d114344295149);
1910
+ $parcel$export($5151b78094cea2ba$exports, "shimAddIceCandidateNullOrEmpty", () => $5151b78094cea2ba$export$51d5e40b48c771c7);
1911
+ $parcel$export($5151b78094cea2ba$exports, "shimParameterlessSetLocalDescription", () => $5151b78094cea2ba$export$7170d04e59f9d553);
1912
+ /*
1913
+ * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
1914
+ *
1915
+ * Use of this source code is governed by a BSD-style license
1916
+ * that can be found in the LICENSE file in the root of the source
1917
+ * tree.
1918
+ */ /* eslint-env node */ var $5d0e6002f6ec24ec$exports = {};
1919
+ /* eslint-env node */ 'use strict';
1920
+ // SDP helpers.
1921
+ const $5d0e6002f6ec24ec$var$SDPUtils = {};
1922
+ // Generate an alphanumeric identifier for cname or mids.
1923
+ // TODO: use UUIDs instead? https://gist.github.com/jed/982883
1924
+ $5d0e6002f6ec24ec$var$SDPUtils.generateIdentifier = function() {
1925
+ return Math.random().toString(36).substring(2, 12);
1926
+ };
1927
+ // The RTCP CNAME used by all peerconnections from the same JS.
1928
+ $5d0e6002f6ec24ec$var$SDPUtils.localCName = $5d0e6002f6ec24ec$var$SDPUtils.generateIdentifier();
1929
+ // Splits SDP into lines, dealing with both CRLF and LF.
1930
+ $5d0e6002f6ec24ec$var$SDPUtils.splitLines = function(blob) {
1931
+ return blob.trim().split('\n').map((line)=>line.trim());
1932
+ };
1933
+ // Splits SDP into sessionpart and mediasections. Ensures CRLF.
1934
+ $5d0e6002f6ec24ec$var$SDPUtils.splitSections = function(blob) {
1935
+ const parts = blob.split('\nm=');
1936
+ return parts.map((part, index)=>(index > 0 ? 'm=' + part : part).trim() + '\r\n');
1937
+ };
1938
+ // Returns the session description.
1939
+ $5d0e6002f6ec24ec$var$SDPUtils.getDescription = function(blob) {
1940
+ const sections = $5d0e6002f6ec24ec$var$SDPUtils.splitSections(blob);
1941
+ return sections && sections[0];
1942
+ };
1943
+ // Returns the individual media sections.
1944
+ $5d0e6002f6ec24ec$var$SDPUtils.getMediaSections = function(blob) {
1945
+ const sections = $5d0e6002f6ec24ec$var$SDPUtils.splitSections(blob);
1946
+ sections.shift();
1947
+ return sections;
1948
+ };
1949
+ // Returns lines that start with a certain prefix.
1950
+ $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix = function(blob, prefix) {
1951
+ return $5d0e6002f6ec24ec$var$SDPUtils.splitLines(blob).filter((line)=>line.indexOf(prefix) === 0);
1952
+ };
1953
+ // Parses an ICE candidate line. Sample input:
1954
+ // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
1955
+ // rport 55996"
1956
+ // Input can be prefixed with a=.
1957
+ $5d0e6002f6ec24ec$var$SDPUtils.parseCandidate = function(line) {
1958
+ let parts;
1959
+ // Parse both variants.
1960
+ if (line.indexOf('a=candidate:') === 0) parts = line.substring(12).split(' ');
1961
+ else parts = line.substring(10).split(' ');
1962
+ const candidate = {
1963
+ foundation: parts[0],
1964
+ component: {
1965
+ 1: 'rtp',
1966
+ 2: 'rtcp'
1967
+ }[parts[1]] || parts[1],
1968
+ protocol: parts[2].toLowerCase(),
1969
+ priority: parseInt(parts[3], 10),
1970
+ ip: parts[4],
1971
+ address: parts[4],
1972
+ port: parseInt(parts[5], 10),
1973
+ // skip parts[6] == 'typ'
1974
+ type: parts[7]
1975
+ };
1976
+ for(let i = 8; i < parts.length; i += 2)switch(parts[i]){
1977
+ case 'raddr':
1978
+ candidate.relatedAddress = parts[i + 1];
1979
+ break;
1980
+ case 'rport':
1981
+ candidate.relatedPort = parseInt(parts[i + 1], 10);
1982
+ break;
1983
+ case 'tcptype':
1984
+ candidate.tcpType = parts[i + 1];
1985
+ break;
1986
+ case 'ufrag':
1987
+ candidate.ufrag = parts[i + 1]; // for backward compatibility.
1988
+ candidate.usernameFragment = parts[i + 1];
1989
+ break;
1990
+ default:
1991
+ if (candidate[parts[i]] === undefined) candidate[parts[i]] = parts[i + 1];
1992
+ break;
1993
+ }
1994
+ return candidate;
1995
+ };
1996
+ // Translates a candidate object into SDP candidate attribute.
1997
+ // This does not include the a= prefix!
1998
+ $5d0e6002f6ec24ec$var$SDPUtils.writeCandidate = function(candidate) {
1999
+ const sdp = [];
2000
+ sdp.push(candidate.foundation);
2001
+ const component = candidate.component;
2002
+ if (component === 'rtp') sdp.push(1);
2003
+ else if (component === 'rtcp') sdp.push(2);
2004
+ else sdp.push(component);
2005
+ sdp.push(candidate.protocol.toUpperCase());
2006
+ sdp.push(candidate.priority);
2007
+ sdp.push(candidate.address || candidate.ip);
2008
+ sdp.push(candidate.port);
2009
+ const type = candidate.type;
2010
+ sdp.push('typ');
2011
+ sdp.push(type);
2012
+ if (type !== 'host' && candidate.relatedAddress && candidate.relatedPort) {
2013
+ sdp.push('raddr');
2014
+ sdp.push(candidate.relatedAddress);
2015
+ sdp.push('rport');
2016
+ sdp.push(candidate.relatedPort);
2017
+ }
2018
+ if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
2019
+ sdp.push('tcptype');
2020
+ sdp.push(candidate.tcpType);
2021
+ }
2022
+ if (candidate.usernameFragment || candidate.ufrag) {
2023
+ sdp.push('ufrag');
2024
+ sdp.push(candidate.usernameFragment || candidate.ufrag);
2025
+ }
2026
+ return 'candidate:' + sdp.join(' ');
2027
+ };
2028
+ // Parses an ice-options line, returns an array of option tags.
2029
+ // Sample input:
2030
+ // a=ice-options:foo bar
2031
+ $5d0e6002f6ec24ec$var$SDPUtils.parseIceOptions = function(line) {
2032
+ return line.substring(14).split(' ');
2033
+ };
2034
+ // Parses a rtpmap line, returns RTCRtpCoddecParameters. Sample input:
2035
+ // a=rtpmap:111 opus/48000/2
2036
+ $5d0e6002f6ec24ec$var$SDPUtils.parseRtpMap = function(line) {
2037
+ let parts = line.substring(9).split(' ');
2038
+ const parsed = {
2039
+ payloadType: parseInt(parts.shift(), 10)
2040
+ };
2041
+ parts = parts[0].split('/');
2042
+ parsed.name = parts[0];
2043
+ parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
2044
+ parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
2045
+ // legacy alias, got renamed back to channels in ORTC.
2046
+ parsed.numChannels = parsed.channels;
2047
+ return parsed;
2048
+ };
2049
+ // Generates a rtpmap line from RTCRtpCodecCapability or
2050
+ // RTCRtpCodecParameters.
2051
+ $5d0e6002f6ec24ec$var$SDPUtils.writeRtpMap = function(codec) {
2052
+ let pt = codec.payloadType;
2053
+ if (codec.preferredPayloadType !== undefined) pt = codec.preferredPayloadType;
2054
+ const channels = codec.channels || codec.numChannels || 1;
2055
+ return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + (channels !== 1 ? '/' + channels : '') + '\r\n';
2056
+ };
2057
+ // Parses a extmap line (headerextension from RFC 5285). Sample input:
2058
+ // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
2059
+ // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
2060
+ $5d0e6002f6ec24ec$var$SDPUtils.parseExtmap = function(line) {
2061
+ const parts = line.substring(9).split(' ');
2062
+ return {
2063
+ id: parseInt(parts[0], 10),
2064
+ direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
2065
+ uri: parts[1],
2066
+ attributes: parts.slice(2).join(' ')
2067
+ };
2068
+ };
2069
+ // Generates an extmap line from RTCRtpHeaderExtensionParameters or
2070
+ // RTCRtpHeaderExtension.
2071
+ $5d0e6002f6ec24ec$var$SDPUtils.writeExtmap = function(headerExtension) {
2072
+ return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + (headerExtension.direction && headerExtension.direction !== 'sendrecv' ? '/' + headerExtension.direction : '') + ' ' + headerExtension.uri + (headerExtension.attributes ? ' ' + headerExtension.attributes : '') + '\r\n';
2073
+ };
2074
+ // Parses a fmtp line, returns dictionary. Sample input:
2075
+ // a=fmtp:96 vbr=on;cng=on
2076
+ // Also deals with vbr=on; cng=on
2077
+ $5d0e6002f6ec24ec$var$SDPUtils.parseFmtp = function(line) {
2078
+ const parsed = {};
2079
+ let kv;
2080
+ const parts = line.substring(line.indexOf(' ') + 1).split(';');
2081
+ for(let j = 0; j < parts.length; j++){
2082
+ kv = parts[j].trim().split('=');
2083
+ parsed[kv[0].trim()] = kv[1];
2084
+ }
2085
+ return parsed;
2086
+ };
2087
+ // Generates a fmtp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
2088
+ $5d0e6002f6ec24ec$var$SDPUtils.writeFmtp = function(codec) {
2089
+ let line = '';
2090
+ let pt = codec.payloadType;
2091
+ if (codec.preferredPayloadType !== undefined) pt = codec.preferredPayloadType;
2092
+ if (codec.parameters && Object.keys(codec.parameters).length) {
2093
+ const params = [];
2094
+ Object.keys(codec.parameters).forEach((param)=>{
2095
+ if (codec.parameters[param] !== undefined) params.push(param + '=' + codec.parameters[param]);
2096
+ else params.push(param);
2097
+ });
2098
+ line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
2099
+ }
2100
+ return line;
2101
+ };
2102
+ // Parses a rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
2103
+ // a=rtcp-fb:98 nack rpsi
2104
+ $5d0e6002f6ec24ec$var$SDPUtils.parseRtcpFb = function(line) {
2105
+ const parts = line.substring(line.indexOf(' ') + 1).split(' ');
2106
+ return {
2107
+ type: parts.shift(),
2108
+ parameter: parts.join(' ')
2109
+ };
2110
+ };
2111
+ // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
2112
+ $5d0e6002f6ec24ec$var$SDPUtils.writeRtcpFb = function(codec) {
2113
+ let lines = '';
2114
+ let pt = codec.payloadType;
2115
+ if (codec.preferredPayloadType !== undefined) pt = codec.preferredPayloadType;
2116
+ if (codec.rtcpFeedback && codec.rtcpFeedback.length) // FIXME: special handling for trr-int?
2117
+ codec.rtcpFeedback.forEach((fb)=>{
2118
+ lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + '\r\n';
2119
+ });
2120
+ return lines;
2121
+ };
2122
+ // Parses a RFC 5576 ssrc media attribute. Sample input:
2123
+ // a=ssrc:3735928559 cname:something
2124
+ $5d0e6002f6ec24ec$var$SDPUtils.parseSsrcMedia = function(line) {
2125
+ const sp = line.indexOf(' ');
2126
+ const parts = {
2127
+ ssrc: parseInt(line.substring(7, sp), 10)
2128
+ };
2129
+ const colon = line.indexOf(':', sp);
2130
+ if (colon > -1) {
2131
+ parts.attribute = line.substring(sp + 1, colon);
2132
+ parts.value = line.substring(colon + 1);
2133
+ } else parts.attribute = line.substring(sp + 1);
2134
+ return parts;
2135
+ };
2136
+ // Parse a ssrc-group line (see RFC 5576). Sample input:
2137
+ // a=ssrc-group:semantics 12 34
2138
+ $5d0e6002f6ec24ec$var$SDPUtils.parseSsrcGroup = function(line) {
2139
+ const parts = line.substring(13).split(' ');
2140
+ return {
2141
+ semantics: parts.shift(),
2142
+ ssrcs: parts.map((ssrc)=>parseInt(ssrc, 10))
2143
+ };
2144
+ };
2145
+ // Extracts the MID (RFC 5888) from a media section.
2146
+ // Returns the MID or undefined if no mid line was found.
2147
+ $5d0e6002f6ec24ec$var$SDPUtils.getMid = function(mediaSection) {
2148
+ const mid = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
2149
+ if (mid) return mid.substring(6);
2150
+ };
2151
+ // Parses a fingerprint line for DTLS-SRTP.
2152
+ $5d0e6002f6ec24ec$var$SDPUtils.parseFingerprint = function(line) {
2153
+ const parts = line.substring(14).split(' ');
2154
+ return {
2155
+ algorithm: parts[0].toLowerCase(),
2156
+ value: parts[1].toUpperCase()
2157
+ };
2158
+ };
2159
+ // Extracts DTLS parameters from SDP media section or sessionpart.
2160
+ // FIXME: for consistency with other functions this should only
2161
+ // get the fingerprint line as input. See also getIceParameters.
2162
+ $5d0e6002f6ec24ec$var$SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
2163
+ const lines = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=fingerprint:');
2164
+ // Note: a=setup line is ignored since we use the 'auto' role in Edge.
2165
+ return {
2166
+ role: 'auto',
2167
+ fingerprints: lines.map($5d0e6002f6ec24ec$var$SDPUtils.parseFingerprint)
2168
+ };
2169
+ };
2170
+ // Serializes DTLS parameters to SDP.
2171
+ $5d0e6002f6ec24ec$var$SDPUtils.writeDtlsParameters = function(params, setupType) {
2172
+ let sdp = 'a=setup:' + setupType + '\r\n';
2173
+ params.fingerprints.forEach((fp)=>{
2174
+ sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
2175
+ });
2176
+ return sdp;
2177
+ };
2178
+ // Parses a=crypto lines into
2179
+ // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members
2180
+ $5d0e6002f6ec24ec$var$SDPUtils.parseCryptoLine = function(line) {
2181
+ const parts = line.substring(9).split(' ');
2182
+ return {
2183
+ tag: parseInt(parts[0], 10),
2184
+ cryptoSuite: parts[1],
2185
+ keyParams: parts[2],
2186
+ sessionParams: parts.slice(3)
2187
+ };
2188
+ };
2189
+ $5d0e6002f6ec24ec$var$SDPUtils.writeCryptoLine = function(parameters) {
2190
+ return 'a=crypto:' + parameters.tag + ' ' + parameters.cryptoSuite + ' ' + (typeof parameters.keyParams === 'object' ? $5d0e6002f6ec24ec$var$SDPUtils.writeCryptoKeyParams(parameters.keyParams) : parameters.keyParams) + (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') + '\r\n';
2191
+ };
2192
+ // Parses the crypto key parameters into
2193
+ // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*
2194
+ $5d0e6002f6ec24ec$var$SDPUtils.parseCryptoKeyParams = function(keyParams) {
2195
+ if (keyParams.indexOf('inline:') !== 0) return null;
2196
+ const parts = keyParams.substring(7).split('|');
2197
+ return {
2198
+ keyMethod: 'inline',
2199
+ keySalt: parts[0],
2200
+ lifeTime: parts[1],
2201
+ mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,
2202
+ mkiLength: parts[2] ? parts[2].split(':')[1] : undefined
2203
+ };
2204
+ };
2205
+ $5d0e6002f6ec24ec$var$SDPUtils.writeCryptoKeyParams = function(keyParams) {
2206
+ return keyParams.keyMethod + ':' + keyParams.keySalt + (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') + (keyParams.mkiValue && keyParams.mkiLength ? '|' + keyParams.mkiValue + ':' + keyParams.mkiLength : '');
2207
+ };
2208
+ // Extracts all SDES parameters.
2209
+ $5d0e6002f6ec24ec$var$SDPUtils.getCryptoParameters = function(mediaSection, sessionpart) {
2210
+ const lines = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=crypto:');
2211
+ return lines.map($5d0e6002f6ec24ec$var$SDPUtils.parseCryptoLine);
2212
+ };
2213
+ // Parses ICE information from SDP media section or sessionpart.
2214
+ // FIXME: for consistency with other functions this should only
2215
+ // get the ice-ufrag and ice-pwd lines as input.
2216
+ $5d0e6002f6ec24ec$var$SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
2217
+ const ufrag = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-ufrag:')[0];
2218
+ const pwd = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection + sessionpart, 'a=ice-pwd:')[0];
2219
+ if (!(ufrag && pwd)) return null;
2220
+ return {
2221
+ usernameFragment: ufrag.substring(12),
2222
+ password: pwd.substring(10)
2223
+ };
2224
+ };
2225
+ // Serializes ICE parameters to SDP.
2226
+ $5d0e6002f6ec24ec$var$SDPUtils.writeIceParameters = function(params) {
2227
+ let sdp = 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 'a=ice-pwd:' + params.password + '\r\n';
2228
+ if (params.iceLite) sdp += 'a=ice-lite\r\n';
2229
+ return sdp;
2230
+ };
2231
+ // Parses the SDP media section and returns RTCRtpParameters.
2232
+ $5d0e6002f6ec24ec$var$SDPUtils.parseRtpParameters = function(mediaSection) {
2233
+ const description = {
2234
+ codecs: [],
2235
+ headerExtensions: [],
2236
+ fecMechanisms: [],
2237
+ rtcp: []
2238
+ };
2239
+ const lines = $5d0e6002f6ec24ec$var$SDPUtils.splitLines(mediaSection);
2240
+ const mline = lines[0].split(' ');
2241
+ description.profile = mline[2];
2242
+ for(let i = 3; i < mline.length; i++){
2243
+ const pt = mline[i];
2244
+ const rtpmapline = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=rtpmap:' + pt + ' ')[0];
2245
+ if (rtpmapline) {
2246
+ const codec = $5d0e6002f6ec24ec$var$SDPUtils.parseRtpMap(rtpmapline);
2247
+ const fmtps = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=fmtp:' + pt + ' ');
2248
+ // Only the first a=fmtp:<pt> is considered.
2249
+ codec.parameters = fmtps.length ? $5d0e6002f6ec24ec$var$SDPUtils.parseFmtp(fmtps[0]) : {};
2250
+ codec.rtcpFeedback = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:' + pt + ' ').map($5d0e6002f6ec24ec$var$SDPUtils.parseRtcpFb);
2251
+ description.codecs.push(codec);
2252
+ // parse FEC mechanisms from rtpmap lines.
2253
+ switch(codec.name.toUpperCase()){
2254
+ case 'RED':
2255
+ case 'ULPFEC':
2256
+ description.fecMechanisms.push(codec.name.toUpperCase());
2257
+ break;
2258
+ default:
2259
+ break;
2260
+ }
2261
+ }
2262
+ }
2263
+ $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach((line)=>{
2264
+ description.headerExtensions.push($5d0e6002f6ec24ec$var$SDPUtils.parseExtmap(line));
2265
+ });
2266
+ const wildcardRtcpFb = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=rtcp-fb:* ').map($5d0e6002f6ec24ec$var$SDPUtils.parseRtcpFb);
2267
+ description.codecs.forEach((codec)=>{
2268
+ wildcardRtcpFb.forEach((fb)=>{
2269
+ const duplicate = codec.rtcpFeedback.find((existingFeedback)=>{
2270
+ return existingFeedback.type === fb.type && existingFeedback.parameter === fb.parameter;
2271
+ });
2272
+ if (!duplicate) codec.rtcpFeedback.push(fb);
2273
+ });
2274
+ });
2275
+ // FIXME: parse rtcp.
2276
+ return description;
2277
+ };
2278
+ // Generates parts of the SDP media section describing the capabilities /
2279
+ // parameters.
2280
+ $5d0e6002f6ec24ec$var$SDPUtils.writeRtpDescription = function(kind, caps) {
2281
+ let sdp = '';
2282
+ // Build the mline.
2283
+ sdp += 'm=' + kind + ' ';
2284
+ sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
2285
+ sdp += ' ' + (caps.profile || 'UDP/TLS/RTP/SAVPF') + ' ';
2286
+ sdp += caps.codecs.map((codec)=>{
2287
+ if (codec.preferredPayloadType !== undefined) return codec.preferredPayloadType;
2288
+ return codec.payloadType;
2289
+ }).join(' ') + '\r\n';
2290
+ sdp += 'c=IN IP4 0.0.0.0\r\n';
2291
+ sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
2292
+ // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
2293
+ caps.codecs.forEach((codec)=>{
2294
+ sdp += $5d0e6002f6ec24ec$var$SDPUtils.writeRtpMap(codec);
2295
+ sdp += $5d0e6002f6ec24ec$var$SDPUtils.writeFmtp(codec);
2296
+ sdp += $5d0e6002f6ec24ec$var$SDPUtils.writeRtcpFb(codec);
2297
+ });
2298
+ let maxptime = 0;
2299
+ caps.codecs.forEach((codec)=>{
2300
+ if (codec.maxptime > maxptime) maxptime = codec.maxptime;
2301
+ });
2302
+ if (maxptime > 0) sdp += 'a=maxptime:' + maxptime + '\r\n';
2303
+ if (caps.headerExtensions) caps.headerExtensions.forEach((extension)=>{
2304
+ sdp += $5d0e6002f6ec24ec$var$SDPUtils.writeExtmap(extension);
2305
+ });
2306
+ // FIXME: write fecMechanisms.
2307
+ return sdp;
2308
+ };
2309
+ // Parses the SDP media section and returns an array of
2310
+ // RTCRtpEncodingParameters.
2311
+ $5d0e6002f6ec24ec$var$SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
2312
+ const encodingParameters = [];
2313
+ const description = $5d0e6002f6ec24ec$var$SDPUtils.parseRtpParameters(mediaSection);
2314
+ const hasRed = description.fecMechanisms.indexOf('RED') !== -1;
2315
+ const hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
2316
+ // filter a=ssrc:... cname:, ignore PlanB-msid
2317
+ const ssrcs = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map((line)=>$5d0e6002f6ec24ec$var$SDPUtils.parseSsrcMedia(line)).filter((parts)=>parts.attribute === 'cname');
2318
+ const primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
2319
+ let secondarySsrc;
2320
+ const flows = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID').map((line)=>{
2321
+ const parts = line.substring(17).split(' ');
2322
+ return parts.map((part)=>parseInt(part, 10));
2323
+ });
2324
+ if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) secondarySsrc = flows[0][1];
2325
+ description.codecs.forEach((codec)=>{
2326
+ if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
2327
+ let encParam = {
2328
+ ssrc: primarySsrc,
2329
+ codecPayloadType: parseInt(codec.parameters.apt, 10)
2330
+ };
2331
+ if (primarySsrc && secondarySsrc) encParam.rtx = {
2332
+ ssrc: secondarySsrc
2333
+ };
2334
+ encodingParameters.push(encParam);
2335
+ if (hasRed) {
2336
+ encParam = JSON.parse(JSON.stringify(encParam));
2337
+ encParam.fec = {
2338
+ ssrc: primarySsrc,
2339
+ mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
2340
+ };
2341
+ encodingParameters.push(encParam);
2342
+ }
2343
+ }
2344
+ });
2345
+ if (encodingParameters.length === 0 && primarySsrc) encodingParameters.push({
2346
+ ssrc: primarySsrc
2347
+ });
2348
+ // we support both b=AS and b=TIAS but interpret AS as TIAS.
2349
+ let bandwidth = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'b=');
2350
+ if (bandwidth.length) {
2351
+ if (bandwidth[0].indexOf('b=TIAS:') === 0) bandwidth = parseInt(bandwidth[0].substring(7), 10);
2352
+ else if (bandwidth[0].indexOf('b=AS:') === 0) // use formula from JSEP to convert b=AS to TIAS value.
2353
+ bandwidth = parseInt(bandwidth[0].substring(5), 10) * 950 - 16000;
2354
+ else bandwidth = undefined;
2355
+ encodingParameters.forEach((params)=>{
2356
+ params.maxBitrate = bandwidth;
2357
+ });
2358
+ }
2359
+ return encodingParameters;
2360
+ };
2361
+ // parses http://draft.ortc.org/#rtcrtcpparameters*
2362
+ $5d0e6002f6ec24ec$var$SDPUtils.parseRtcpParameters = function(mediaSection) {
2363
+ const rtcpParameters = {};
2364
+ // Gets the first SSRC. Note that with RTX there might be multiple
2365
+ // SSRCs.
2366
+ const remoteSsrc = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map((line)=>$5d0e6002f6ec24ec$var$SDPUtils.parseSsrcMedia(line)).filter((obj)=>obj.attribute === 'cname')[0];
2367
+ if (remoteSsrc) {
2368
+ rtcpParameters.cname = remoteSsrc.value;
2369
+ rtcpParameters.ssrc = remoteSsrc.ssrc;
2370
+ }
2371
+ // Edge uses the compound attribute instead of reducedSize
2372
+ // compound is !reducedSize
2373
+ const rsize = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
2374
+ rtcpParameters.reducedSize = rsize.length > 0;
2375
+ rtcpParameters.compound = rsize.length === 0;
2376
+ // parses the rtcp-mux attrіbute.
2377
+ // Note that Edge does not support unmuxed RTCP.
2378
+ const mux = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
2379
+ rtcpParameters.mux = mux.length > 0;
2380
+ return rtcpParameters;
2381
+ };
2382
+ $5d0e6002f6ec24ec$var$SDPUtils.writeRtcpParameters = function(rtcpParameters) {
2383
+ let sdp = '';
2384
+ if (rtcpParameters.reducedSize) sdp += 'a=rtcp-rsize\r\n';
2385
+ if (rtcpParameters.mux) sdp += 'a=rtcp-mux\r\n';
2386
+ if (rtcpParameters.ssrc !== undefined && rtcpParameters.cname) sdp += 'a=ssrc:' + rtcpParameters.ssrc + ' cname:' + rtcpParameters.cname + '\r\n';
2387
+ return sdp;
2388
+ };
2389
+ // parses either a=msid: or a=ssrc:... msid lines and returns
2390
+ // the id of the MediaStream and MediaStreamTrack.
2391
+ $5d0e6002f6ec24ec$var$SDPUtils.parseMsid = function(mediaSection) {
2392
+ let parts;
2393
+ const spec = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=msid:');
2394
+ if (spec.length === 1) {
2395
+ parts = spec[0].substring(7).split(' ');
2396
+ return {
2397
+ stream: parts[0],
2398
+ track: parts[1]
2399
+ };
2400
+ }
2401
+ const planB = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=ssrc:').map((line)=>$5d0e6002f6ec24ec$var$SDPUtils.parseSsrcMedia(line)).filter((msidParts)=>msidParts.attribute === 'msid');
2402
+ if (planB.length > 0) {
2403
+ parts = planB[0].value.split(' ');
2404
+ return {
2405
+ stream: parts[0],
2406
+ track: parts[1]
2407
+ };
2408
+ }
2409
+ };
2410
+ // SCTP
2411
+ // parses draft-ietf-mmusic-sctp-sdp-26 first and falls back
2412
+ // to draft-ietf-mmusic-sctp-sdp-05
2413
+ $5d0e6002f6ec24ec$var$SDPUtils.parseSctpDescription = function(mediaSection) {
2414
+ const mline = $5d0e6002f6ec24ec$var$SDPUtils.parseMLine(mediaSection);
2415
+ const maxSizeLine = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');
2416
+ let maxMessageSize;
2417
+ if (maxSizeLine.length > 0) maxMessageSize = parseInt(maxSizeLine[0].substring(19), 10);
2418
+ if (isNaN(maxMessageSize)) maxMessageSize = 65536;
2419
+ const sctpPort = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');
2420
+ if (sctpPort.length > 0) return {
2421
+ port: parseInt(sctpPort[0].substring(12), 10),
2422
+ protocol: mline.fmt,
2423
+ maxMessageSize: maxMessageSize
2424
+ };
2425
+ const sctpMapLines = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');
2426
+ if (sctpMapLines.length > 0) {
2427
+ const parts = sctpMapLines[0].substring(10).split(' ');
2428
+ return {
2429
+ port: parseInt(parts[0], 10),
2430
+ protocol: parts[1],
2431
+ maxMessageSize: maxMessageSize
2432
+ };
2433
+ }
2434
+ };
2435
+ // SCTP
2436
+ // outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers
2437
+ // support by now receiving in this format, unless we originally parsed
2438
+ // as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line
2439
+ // protocol of DTLS/SCTP -- without UDP/ or TCP/)
2440
+ $5d0e6002f6ec24ec$var$SDPUtils.writeSctpDescription = function(media, sctp) {
2441
+ let output = [];
2442
+ if (media.protocol !== 'DTLS/SCTP') output = [
2443
+ 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\r\n',
2444
+ 'c=IN IP4 0.0.0.0\r\n',
2445
+ 'a=sctp-port:' + sctp.port + '\r\n'
2446
+ ];
2447
+ else output = [
2448
+ 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\r\n',
2449
+ 'c=IN IP4 0.0.0.0\r\n',
2450
+ 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\r\n'
2451
+ ];
2452
+ if (sctp.maxMessageSize !== undefined) output.push('a=max-message-size:' + sctp.maxMessageSize + '\r\n');
2453
+ return output.join('');
2454
+ };
2455
+ // Generate a session ID for SDP.
2456
+ // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
2457
+ // recommends using a cryptographically random +ve 64-bit value
2458
+ // but right now this should be acceptable and within the right range
2459
+ $5d0e6002f6ec24ec$var$SDPUtils.generateSessionId = function() {
2460
+ return Math.random().toString().substr(2, 22);
2461
+ };
2462
+ // Write boiler plate for start of SDP
2463
+ // sessId argument is optional - if not supplied it will
2464
+ // be generated randomly
2465
+ // sessVersion is optional and defaults to 2
2466
+ // sessUser is optional and defaults to 'thisisadapterortc'
2467
+ $5d0e6002f6ec24ec$var$SDPUtils.writeSessionBoilerplate = function(sessId, sessVer, sessUser) {
2468
+ let sessionId;
2469
+ const version = sessVer !== undefined ? sessVer : 2;
2470
+ if (sessId) sessionId = sessId;
2471
+ else sessionId = $5d0e6002f6ec24ec$var$SDPUtils.generateSessionId();
2472
+ const user = sessUser || 'thisisadapterortc';
2473
+ // FIXME: sess-id should be an NTP timestamp.
2474
+ return "v=0\r\no=" + user + ' ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' + 's=-\r\n' + 't=0 0\r\n';
2475
+ };
2476
+ // Gets the direction from the mediaSection or the sessionpart.
2477
+ $5d0e6002f6ec24ec$var$SDPUtils.getDirection = function(mediaSection, sessionpart) {
2478
+ // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
2479
+ const lines = $5d0e6002f6ec24ec$var$SDPUtils.splitLines(mediaSection);
2480
+ for(let i = 0; i < lines.length; i++)switch(lines[i]){
2481
+ case 'a=sendrecv':
2482
+ case 'a=sendonly':
2483
+ case 'a=recvonly':
2484
+ case 'a=inactive':
2485
+ return lines[i].substring(2);
2486
+ default:
2487
+ }
2488
+ if (sessionpart) return $5d0e6002f6ec24ec$var$SDPUtils.getDirection(sessionpart);
2489
+ return 'sendrecv';
2490
+ };
2491
+ $5d0e6002f6ec24ec$var$SDPUtils.getKind = function(mediaSection) {
2492
+ const lines = $5d0e6002f6ec24ec$var$SDPUtils.splitLines(mediaSection);
2493
+ const mline = lines[0].split(' ');
2494
+ return mline[0].substring(2);
2495
+ };
2496
+ $5d0e6002f6ec24ec$var$SDPUtils.isRejected = function(mediaSection) {
2497
+ return mediaSection.split(' ', 2)[1] === '0';
2498
+ };
2499
+ $5d0e6002f6ec24ec$var$SDPUtils.parseMLine = function(mediaSection) {
2500
+ const lines = $5d0e6002f6ec24ec$var$SDPUtils.splitLines(mediaSection);
2501
+ const parts = lines[0].substring(2).split(' ');
2502
+ return {
2503
+ kind: parts[0],
2504
+ port: parseInt(parts[1], 10),
2505
+ protocol: parts[2],
2506
+ fmt: parts.slice(3).join(' ')
2507
+ };
2508
+ };
2509
+ $5d0e6002f6ec24ec$var$SDPUtils.parseOLine = function(mediaSection) {
2510
+ const line = $5d0e6002f6ec24ec$var$SDPUtils.matchPrefix(mediaSection, 'o=')[0];
2511
+ const parts = line.substring(2).split(' ');
2512
+ return {
2513
+ username: parts[0],
2514
+ sessionId: parts[1],
2515
+ sessionVersion: parseInt(parts[2], 10),
2516
+ netType: parts[3],
2517
+ addressType: parts[4],
2518
+ address: parts[5]
2519
+ };
2520
+ };
2521
+ // a very naive interpretation of a valid SDP.
2522
+ $5d0e6002f6ec24ec$var$SDPUtils.isValidSDP = function(blob) {
2523
+ if (typeof blob !== 'string' || blob.length === 0) return false;
2524
+ const lines = $5d0e6002f6ec24ec$var$SDPUtils.splitLines(blob);
2525
+ for(let i = 0; i < lines.length; i++){
2526
+ if (lines[i].length < 2 || lines[i].charAt(1) !== '=') return false;
2527
+ // TODO: check the modifier a bit more.
2528
+ }
2529
+ return true;
2530
+ };
2531
+ $5d0e6002f6ec24ec$exports = $5d0e6002f6ec24ec$var$SDPUtils;
2532
+
2533
+
2534
+
2535
+ 'use strict';
2536
+ function $5151b78094cea2ba$export$cf133661e444ccfe(window) {
2537
+ // foundation is arbitrarily chosen as an indicator for full support for
2538
+ // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
2539
+ if (!window.RTCIceCandidate || window.RTCIceCandidate && 'foundation' in window.RTCIceCandidate.prototype) return;
2540
+ const NativeRTCIceCandidate = window.RTCIceCandidate;
2541
+ window.RTCIceCandidate = function RTCIceCandidate(args) {
2542
+ // Remove the a= which shouldn't be part of the candidate string.
2543
+ if (typeof args === 'object' && args.candidate && args.candidate.indexOf('a=') === 0) {
2544
+ args = JSON.parse(JSON.stringify(args));
2545
+ args.candidate = args.candidate.substring(2);
2546
+ }
2547
+ if (args.candidate && args.candidate.length) {
2548
+ // Augment the native candidate with the parsed fields.
2549
+ const nativeCandidate = new NativeRTCIceCandidate(args);
2550
+ const parsedCandidate = (0, (/*@__PURE__*/$parcel$interopDefault($5d0e6002f6ec24ec$exports))).parseCandidate(args.candidate);
2551
+ for(const key in parsedCandidate)if (!(key in nativeCandidate)) Object.defineProperty(nativeCandidate, key, {
2552
+ value: parsedCandidate[key]
2553
+ });
2554
+ // Override serializer to not serialize the extra attributes.
2555
+ nativeCandidate.toJSON = function toJSON() {
2556
+ return {
2557
+ candidate: nativeCandidate.candidate,
2558
+ sdpMid: nativeCandidate.sdpMid,
2559
+ sdpMLineIndex: nativeCandidate.sdpMLineIndex,
2560
+ usernameFragment: nativeCandidate.usernameFragment
2561
+ };
2562
+ };
2563
+ return nativeCandidate;
2564
+ }
2565
+ return new NativeRTCIceCandidate(args);
2566
+ };
2567
+ window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;
2568
+ // Hook up the augmented candidate in onicecandidate and
2569
+ // addEventListener('icecandidate', ...)
2570
+ $9fea4db837311579$export$1f48841962b828b1(window, 'icecandidate', (e)=>{
2571
+ if (e.candidate) Object.defineProperty(e, 'candidate', {
2572
+ value: new window.RTCIceCandidate(e.candidate),
2573
+ writable: 'false'
2574
+ });
2575
+ return e;
2576
+ });
2577
+ }
2578
+ function $5151b78094cea2ba$export$fdafb8d8280e29b5(window) {
2579
+ if (!window.RTCIceCandidate || window.RTCIceCandidate && 'relayProtocol' in window.RTCIceCandidate.prototype) return;
2580
+ // Hook up the augmented candidate in onicecandidate and
2581
+ // addEventListener('icecandidate', ...)
2582
+ $9fea4db837311579$export$1f48841962b828b1(window, 'icecandidate', (e)=>{
2583
+ if (e.candidate) {
2584
+ const parsedCandidate = (0, (/*@__PURE__*/$parcel$interopDefault($5d0e6002f6ec24ec$exports))).parseCandidate(e.candidate.candidate);
2585
+ if (parsedCandidate.type === 'relay') // This is a libwebrtc-specific mapping of local type preference
2586
+ // to relayProtocol.
2587
+ e.candidate.relayProtocol = ({
2588
+ 0: 'tls',
2589
+ 1: 'tcp',
2590
+ 2: 'udp'
2591
+ })[parsedCandidate.priority >> 24];
2592
+ }
2593
+ return e;
2594
+ });
2595
+ }
2596
+ function $5151b78094cea2ba$export$a99147c78a56edc4(window, browserDetails) {
2597
+ if (!window.RTCPeerConnection) return;
2598
+ if (!('sctp' in window.RTCPeerConnection.prototype)) Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {
2599
+ get () {
2600
+ return typeof this._sctp === 'undefined' ? null : this._sctp;
2601
+ }
2602
+ });
2603
+ const sctpInDescription = function(description) {
2604
+ if (!description || !description.sdp) return false;
2605
+ const sections = (0, (/*@__PURE__*/$parcel$interopDefault($5d0e6002f6ec24ec$exports))).splitSections(description.sdp);
2606
+ sections.shift();
2607
+ return sections.some((mediaSection)=>{
2608
+ const mLine = (0, (/*@__PURE__*/$parcel$interopDefault($5d0e6002f6ec24ec$exports))).parseMLine(mediaSection);
2609
+ return mLine && mLine.kind === 'application' && mLine.protocol.indexOf('SCTP') !== -1;
2610
+ });
2611
+ };
2612
+ const getRemoteFirefoxVersion = function(description) {
2613
+ // TODO: Is there a better solution for detecting Firefox?
2614
+ const match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
2615
+ if (match === null || match.length < 2) return -1;
2616
+ const version = parseInt(match[1], 10);
2617
+ // Test for NaN (yes, this is ugly)
2618
+ return version !== version ? -1 : version;
2619
+ };
2620
+ const getCanSendMaxMessageSize = function(remoteIsFirefox) {
2621
+ // Every implementation we know can send at least 64 KiB.
2622
+ // Note: Although Chrome is technically able to send up to 256 KiB, the
2623
+ // data does not reach the other peer reliably.
2624
+ // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419
2625
+ let canSendMaxMessageSize = 65536;
2626
+ if (browserDetails.browser === 'firefox') {
2627
+ if (browserDetails.version < 57) {
2628
+ if (remoteIsFirefox === -1) // FF < 57 will send in 16 KiB chunks using the deprecated PPID
2629
+ // fragmentation.
2630
+ canSendMaxMessageSize = 16384;
2631
+ else // However, other FF (and RAWRTC) can reassemble PPID-fragmented
2632
+ // messages. Thus, supporting ~2 GiB when sending.
2633
+ canSendMaxMessageSize = 2147483637;
2634
+ } else if (browserDetails.version < 60) // Currently, all FF >= 57 will reset the remote maximum message size
2635
+ // to the default value when a data channel is created at a later
2636
+ // stage. :(
2637
+ // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
2638
+ canSendMaxMessageSize = browserDetails.version === 57 ? 65535 : 65536;
2639
+ else // FF >= 60 supports sending ~2 GiB
2640
+ canSendMaxMessageSize = 2147483637;
2641
+ }
2642
+ return canSendMaxMessageSize;
2643
+ };
2644
+ const getMaxMessageSize = function(description, remoteIsFirefox) {
2645
+ // Note: 65536 bytes is the default value from the SDP spec. Also,
2646
+ // every implementation we know supports receiving 65536 bytes.
2647
+ let maxMessageSize = 65536;
2648
+ // FF 57 has a slightly incorrect default remote max message size, so
2649
+ // we need to adjust it here to avoid a failure when sending.
2650
+ // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697
2651
+ if (browserDetails.browser === 'firefox' && browserDetails.version === 57) maxMessageSize = 65535;
2652
+ const match = (0, (/*@__PURE__*/$parcel$interopDefault($5d0e6002f6ec24ec$exports))).matchPrefix(description.sdp, 'a=max-message-size:');
2653
+ if (match.length > 0) maxMessageSize = parseInt(match[0].substring(19), 10);
2654
+ else if (browserDetails.browser === 'firefox' && remoteIsFirefox !== -1) // If the maximum message size is not present in the remote SDP and
2655
+ // both local and remote are Firefox, the remote peer can receive
2656
+ // ~2 GiB.
2657
+ maxMessageSize = 2147483637;
2658
+ return maxMessageSize;
2659
+ };
2660
+ const origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
2661
+ window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription() {
2662
+ this._sctp = null;
2663
+ // Chrome decided to not expose .sctp in plan-b mode.
2664
+ // As usual, adapter.js has to do an 'ugly worakaround'
2665
+ // to cover up the mess.
2666
+ if (browserDetails.browser === 'chrome' && browserDetails.version >= 76) {
2667
+ const { sdpSemantics: sdpSemantics } = this.getConfiguration();
2668
+ if (sdpSemantics === 'plan-b') Object.defineProperty(this, 'sctp', {
2669
+ get () {
2670
+ return typeof this._sctp === 'undefined' ? null : this._sctp;
2671
+ },
2672
+ enumerable: true,
2673
+ configurable: true
2674
+ });
2675
+ }
2676
+ if (sctpInDescription(arguments[0])) {
2677
+ // Check if the remote is FF.
2678
+ const isFirefox = getRemoteFirefoxVersion(arguments[0]);
2679
+ // Get the maximum message size the local peer is capable of sending
2680
+ const canSendMMS = getCanSendMaxMessageSize(isFirefox);
2681
+ // Get the maximum message size of the remote peer.
2682
+ const remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
2683
+ // Determine final maximum message size
2684
+ let maxMessageSize;
2685
+ if (canSendMMS === 0 && remoteMMS === 0) maxMessageSize = Number.POSITIVE_INFINITY;
2686
+ else if (canSendMMS === 0 || remoteMMS === 0) maxMessageSize = Math.max(canSendMMS, remoteMMS);
2687
+ else maxMessageSize = Math.min(canSendMMS, remoteMMS);
2688
+ // Create a dummy RTCSctpTransport object and the 'maxMessageSize'
2689
+ // attribute.
2690
+ const sctp = {};
2691
+ Object.defineProperty(sctp, 'maxMessageSize', {
2692
+ get () {
2693
+ return maxMessageSize;
2694
+ }
2695
+ });
2696
+ this._sctp = sctp;
2697
+ }
2698
+ return origSetRemoteDescription.apply(this, arguments);
2699
+ };
2700
+ }
2701
+ function $5151b78094cea2ba$export$d461c8d5c5db5da7(window) {
2702
+ if (!(window.RTCPeerConnection && 'createDataChannel' in window.RTCPeerConnection.prototype)) return;
2703
+ // Note: Although Firefox >= 57 has a native implementation, the maximum
2704
+ // message size can be reset for all data channels at a later stage.
2705
+ // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
2706
+ function wrapDcSend(dc, pc) {
2707
+ const origDataChannelSend = dc.send;
2708
+ dc.send = function send() {
2709
+ const data = arguments[0];
2710
+ const length = data.length || data.size || data.byteLength;
2711
+ if (dc.readyState === 'open' && pc.sctp && length > pc.sctp.maxMessageSize) throw new TypeError('Message too large (can send a maximum of ' + pc.sctp.maxMessageSize + ' bytes)');
2712
+ return origDataChannelSend.apply(dc, arguments);
2713
+ };
2714
+ }
2715
+ const origCreateDataChannel = window.RTCPeerConnection.prototype.createDataChannel;
2716
+ window.RTCPeerConnection.prototype.createDataChannel = function createDataChannel() {
2717
+ const dataChannel = origCreateDataChannel.apply(this, arguments);
2718
+ wrapDcSend(dataChannel, this);
2719
+ return dataChannel;
2720
+ };
2721
+ $9fea4db837311579$export$1f48841962b828b1(window, 'datachannel', (e)=>{
2722
+ wrapDcSend(e.channel, e.target);
2723
+ return e;
2724
+ });
2725
+ }
2726
+ function $5151b78094cea2ba$export$63bb816cc75460(window) {
2727
+ if (!window.RTCPeerConnection || 'connectionState' in window.RTCPeerConnection.prototype) return;
2728
+ const proto = window.RTCPeerConnection.prototype;
2729
+ Object.defineProperty(proto, 'connectionState', {
2730
+ get () {
2731
+ return ({
2732
+ completed: 'connected',
2733
+ checking: 'connecting'
2734
+ })[this.iceConnectionState] || this.iceConnectionState;
2735
+ },
2736
+ enumerable: true,
2737
+ configurable: true
2738
+ });
2739
+ Object.defineProperty(proto, 'onconnectionstatechange', {
2740
+ get () {
2741
+ return this._onconnectionstatechange || null;
2742
+ },
2743
+ set (cb) {
2744
+ if (this._onconnectionstatechange) {
2745
+ this.removeEventListener('connectionstatechange', this._onconnectionstatechange);
2746
+ delete this._onconnectionstatechange;
2747
+ }
2748
+ if (cb) this.addEventListener('connectionstatechange', this._onconnectionstatechange = cb);
2749
+ },
2750
+ enumerable: true,
2751
+ configurable: true
2752
+ });
2753
+ [
2754
+ 'setLocalDescription',
2755
+ 'setRemoteDescription'
2756
+ ].forEach((method)=>{
2757
+ const origMethod = proto[method];
2758
+ proto[method] = function() {
2759
+ if (!this._connectionstatechangepoly) {
2760
+ this._connectionstatechangepoly = (e)=>{
2761
+ const pc = e.target;
2762
+ if (pc._lastConnectionState !== pc.connectionState) {
2763
+ pc._lastConnectionState = pc.connectionState;
2764
+ const newEvent = new Event('connectionstatechange', e);
2765
+ pc.dispatchEvent(newEvent);
2766
+ }
2767
+ return e;
2768
+ };
2769
+ this.addEventListener('iceconnectionstatechange', this._connectionstatechangepoly);
2770
+ }
2771
+ return origMethod.apply(this, arguments);
2772
+ };
2773
+ });
2774
+ }
2775
+ function $5151b78094cea2ba$export$a57d114344295149(window, browserDetails) {
2776
+ /* remove a=extmap-allow-mixed for webrtc.org < M71 */ if (!window.RTCPeerConnection) return;
2777
+ if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) return;
2778
+ if (browserDetails.browser === 'safari' && browserDetails.version >= 605) return;
2779
+ const nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;
2780
+ window.RTCPeerConnection.prototype.setRemoteDescription = function setRemoteDescription(desc) {
2781
+ if (desc && desc.sdp && desc.sdp.indexOf('\na=extmap-allow-mixed') !== -1) {
2782
+ const sdp = desc.sdp.split('\n').filter((line)=>{
2783
+ return line.trim() !== 'a=extmap-allow-mixed';
2784
+ }).join('\n');
2785
+ // Safari enforces read-only-ness of RTCSessionDescription fields.
2786
+ if (window.RTCSessionDescription && desc instanceof window.RTCSessionDescription) arguments[0] = new window.RTCSessionDescription({
2787
+ type: desc.type,
2788
+ sdp: sdp
2789
+ });
2790
+ else desc.sdp = sdp;
2791
+ }
2792
+ return nativeSRD.apply(this, arguments);
2793
+ };
2794
+ }
2795
+ function $5151b78094cea2ba$export$51d5e40b48c771c7(window, browserDetails) {
2796
+ // Support for addIceCandidate(null or undefined)
2797
+ // as well as addIceCandidate({candidate: "", ...})
2798
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=978582
2799
+ // Note: must be called before other polyfills which change the signature.
2800
+ if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) return;
2801
+ const nativeAddIceCandidate = window.RTCPeerConnection.prototype.addIceCandidate;
2802
+ if (!nativeAddIceCandidate || nativeAddIceCandidate.length === 0) return;
2803
+ window.RTCPeerConnection.prototype.addIceCandidate = function addIceCandidate() {
2804
+ if (!arguments[0]) {
2805
+ if (arguments[1]) arguments[1].apply(null);
2806
+ return Promise.resolve();
2807
+ }
2808
+ // Firefox 68+ emits and processes {candidate: "", ...}, ignore
2809
+ // in older versions.
2810
+ // Native support for ignoring exists for Chrome M77+.
2811
+ // Safari ignores as well, exact version unknown but works in the same
2812
+ // version that also ignores addIceCandidate(null).
2813
+ if ((browserDetails.browser === 'chrome' && browserDetails.version < 78 || browserDetails.browser === 'firefox' && browserDetails.version < 68 || browserDetails.browser === 'safari') && arguments[0] && arguments[0].candidate === '') return Promise.resolve();
2814
+ return nativeAddIceCandidate.apply(this, arguments);
2815
+ };
2816
+ }
2817
+ function $5151b78094cea2ba$export$7170d04e59f9d553(window, browserDetails) {
2818
+ if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) return;
2819
+ const nativeSetLocalDescription = window.RTCPeerConnection.prototype.setLocalDescription;
2820
+ if (!nativeSetLocalDescription || nativeSetLocalDescription.length === 0) return;
2821
+ window.RTCPeerConnection.prototype.setLocalDescription = function setLocalDescription() {
2822
+ let desc = arguments[0] || {};
2823
+ if (typeof desc !== 'object' || desc.type && desc.sdp) return nativeSetLocalDescription.apply(this, arguments);
2824
+ // The remaining steps should technically happen when SLD comes off the
2825
+ // RTCPeerConnection's operations chain (not ahead of going on it), but
2826
+ // this is too difficult to shim. Instead, this shim only covers the
2827
+ // common case where the operations chain is empty. This is imperfect, but
2828
+ // should cover many cases. Rationale: Even if we can't reduce the glare
2829
+ // window to zero on imperfect implementations, there's value in tapping
2830
+ // into the perfect negotiation pattern that several browsers support.
2831
+ desc = {
2832
+ type: desc.type,
2833
+ sdp: desc.sdp
2834
+ };
2835
+ if (!desc.type) switch(this.signalingState){
2836
+ case 'stable':
2837
+ case 'have-local-offer':
2838
+ case 'have-remote-pranswer':
2839
+ desc.type = 'offer';
2840
+ break;
2841
+ default:
2842
+ desc.type = 'answer';
2843
+ break;
2844
+ }
2845
+ if (desc.sdp || desc.type !== 'offer' && desc.type !== 'answer') return nativeSetLocalDescription.apply(this, [
2846
+ desc
2847
+ ]);
2848
+ const func = desc.type === 'offer' ? this.createOffer : this.createAnswer;
2849
+ return func.apply(this).then((d)=>nativeSetLocalDescription.apply(this, [
2850
+ d
2851
+ ]));
2852
+ };
2853
+ }
2854
+
2855
+
2856
+
2857
+ function $b657217e95eb14d8$export$e77bf46c04ac7d12({ window: window } = {}, options = {
2858
+ shimChrome: true,
2859
+ shimFirefox: true,
2860
+ shimSafari: true
2861
+ }) {
2862
+ // Utils.
2863
+ const logging = $9fea4db837311579$export$bef1f36f5486a6a3;
2864
+ const browserDetails = $9fea4db837311579$export$2d31490a0c05f094(window);
2865
+ const adapter = {
2866
+ browserDetails: browserDetails,
2867
+ commonShim: $5151b78094cea2ba$exports,
2868
+ extractVersion: $9fea4db837311579$export$e3c02be309be1f23,
2869
+ disableLog: $9fea4db837311579$export$afbfee8cc06fd3e4,
2870
+ disableWarnings: $9fea4db837311579$export$51516be4b019e41e,
2871
+ sdp: // Expose sdp as a convenience. For production apps include directly.
2872
+ $5d0e6002f6ec24ec$exports
2873
+ };
2874
+ // Shim browser if found.
2875
+ switch(browserDetails.browser){
2876
+ case 'chrome':
2877
+ if (!$fb04e59b477f17ce$exports || !$fb04e59b477f17ce$exports.shimPeerConnection || !options.shimChrome) {
2878
+ logging('Chrome shim is not included in this adapter release.');
2879
+ return adapter;
2880
+ }
2881
+ if (browserDetails.version === null) {
2882
+ logging('Chrome shim can not determine version, not shimming.');
2883
+ return adapter;
2884
+ }
2885
+ logging('adapter.js shimming chrome.');
2886
+ // Export to the adapter global object visible in the browser.
2887
+ adapter.browserShim = $fb04e59b477f17ce$exports;
2888
+ // Must be called before shimPeerConnection.
2889
+ $5151b78094cea2ba$export$51d5e40b48c771c7(window, browserDetails);
2890
+ $5151b78094cea2ba$export$7170d04e59f9d553(window, browserDetails);
2891
+ $fb04e59b477f17ce$exports.shimGetUserMedia(window, browserDetails);
2892
+ $fb04e59b477f17ce$exports.shimMediaStream(window, browserDetails);
2893
+ $fb04e59b477f17ce$exports.shimPeerConnection(window, browserDetails);
2894
+ $fb04e59b477f17ce$exports.shimOnTrack(window, browserDetails);
2895
+ $fb04e59b477f17ce$exports.shimAddTrackRemoveTrack(window, browserDetails);
2896
+ $fb04e59b477f17ce$exports.shimGetSendersWithDtmf(window, browserDetails);
2897
+ $fb04e59b477f17ce$exports.shimSenderReceiverGetStats(window, browserDetails);
2898
+ $fb04e59b477f17ce$exports.fixNegotiationNeeded(window, browserDetails);
2899
+ $5151b78094cea2ba$export$cf133661e444ccfe(window, browserDetails);
2900
+ $5151b78094cea2ba$export$fdafb8d8280e29b5(window, browserDetails);
2901
+ $5151b78094cea2ba$export$63bb816cc75460(window, browserDetails);
2902
+ $5151b78094cea2ba$export$a99147c78a56edc4(window, browserDetails);
2903
+ $5151b78094cea2ba$export$d461c8d5c5db5da7(window, browserDetails);
2904
+ $5151b78094cea2ba$export$a57d114344295149(window, browserDetails);
2905
+ break;
2906
+ case 'firefox':
2907
+ if (!$215e6581d7a09c61$exports || !$215e6581d7a09c61$exports.shimPeerConnection || !options.shimFirefox) {
2908
+ logging('Firefox shim is not included in this adapter release.');
2909
+ return adapter;
2910
+ }
2911
+ logging('adapter.js shimming firefox.');
2912
+ // Export to the adapter global object visible in the browser.
2913
+ adapter.browserShim = $215e6581d7a09c61$exports;
2914
+ // Must be called before shimPeerConnection.
2915
+ $5151b78094cea2ba$export$51d5e40b48c771c7(window, browserDetails);
2916
+ $5151b78094cea2ba$export$7170d04e59f9d553(window, browserDetails);
2917
+ $215e6581d7a09c61$exports.shimGetUserMedia(window, browserDetails);
2918
+ $215e6581d7a09c61$exports.shimPeerConnection(window, browserDetails);
2919
+ $215e6581d7a09c61$exports.shimOnTrack(window, browserDetails);
2920
+ $215e6581d7a09c61$exports.shimRemoveStream(window, browserDetails);
2921
+ $215e6581d7a09c61$exports.shimSenderGetStats(window, browserDetails);
2922
+ $215e6581d7a09c61$exports.shimReceiverGetStats(window, browserDetails);
2923
+ $215e6581d7a09c61$exports.shimRTCDataChannel(window, browserDetails);
2924
+ $215e6581d7a09c61$exports.shimAddTransceiver(window, browserDetails);
2925
+ $215e6581d7a09c61$exports.shimGetParameters(window, browserDetails);
2926
+ $215e6581d7a09c61$exports.shimCreateOffer(window, browserDetails);
2927
+ $215e6581d7a09c61$exports.shimCreateAnswer(window, browserDetails);
2928
+ $5151b78094cea2ba$export$cf133661e444ccfe(window, browserDetails);
2929
+ $5151b78094cea2ba$export$63bb816cc75460(window, browserDetails);
2930
+ $5151b78094cea2ba$export$a99147c78a56edc4(window, browserDetails);
2931
+ $5151b78094cea2ba$export$d461c8d5c5db5da7(window, browserDetails);
2932
+ break;
2933
+ case 'safari':
2934
+ if (!$c1f641ee5a6f6c8f$exports || !options.shimSafari) {
2935
+ logging('Safari shim is not included in this adapter release.');
2936
+ return adapter;
2937
+ }
2938
+ logging('adapter.js shimming safari.');
2939
+ // Export to the adapter global object visible in the browser.
2940
+ adapter.browserShim = $c1f641ee5a6f6c8f$exports;
2941
+ // Must be called before shimCallbackAPI.
2942
+ $5151b78094cea2ba$export$51d5e40b48c771c7(window, browserDetails);
2943
+ $5151b78094cea2ba$export$7170d04e59f9d553(window, browserDetails);
2944
+ $c1f641ee5a6f6c8f$exports.shimRTCIceServerUrls(window, browserDetails);
2945
+ $c1f641ee5a6f6c8f$exports.shimCreateOfferLegacy(window, browserDetails);
2946
+ $c1f641ee5a6f6c8f$exports.shimCallbacksAPI(window, browserDetails);
2947
+ $c1f641ee5a6f6c8f$exports.shimLocalStreamsAPI(window, browserDetails);
2948
+ $c1f641ee5a6f6c8f$exports.shimRemoteStreamsAPI(window, browserDetails);
2949
+ $c1f641ee5a6f6c8f$exports.shimTrackEventTransceiver(window, browserDetails);
2950
+ $c1f641ee5a6f6c8f$exports.shimGetUserMedia(window, browserDetails);
2951
+ $c1f641ee5a6f6c8f$exports.shimAudioContext(window, browserDetails);
2952
+ $5151b78094cea2ba$export$cf133661e444ccfe(window, browserDetails);
2953
+ $5151b78094cea2ba$export$fdafb8d8280e29b5(window, browserDetails);
2954
+ $5151b78094cea2ba$export$a99147c78a56edc4(window, browserDetails);
2955
+ $5151b78094cea2ba$export$d461c8d5c5db5da7(window, browserDetails);
2956
+ $5151b78094cea2ba$export$a57d114344295149(window, browserDetails);
2957
+ break;
2958
+ default:
2959
+ logging('Unsupported browser!');
2960
+ break;
2961
+ }
2962
+ return adapter;
2963
+ }
2964
+
2965
+
2966
+ 'use strict';
2967
+ const $90c50c10bd6fa8b4$var$adapter = (0, $b657217e95eb14d8$export$e77bf46c04ac7d12)({
2968
+ window: typeof window === 'undefined' ? undefined : window
2969
+ });
2970
+ var $90c50c10bd6fa8b4$export$2e2bcd8739ae039 = $90c50c10bd6fa8b4$var$adapter;
2971
+
2972
+
2973
+ const $a9bc9397a7d36afa$var$webRTCAdapter = //@ts-ignore
2974
+ (0, $90c50c10bd6fa8b4$export$2e2bcd8739ae039).default || (0, $90c50c10bd6fa8b4$export$2e2bcd8739ae039);
2975
+ const $a9bc9397a7d36afa$export$25be9502477c137d = new class {
2976
+ isWebRTCSupported() {
2977
+ return typeof RTCPeerConnection !== "undefined";
2978
+ }
2979
+ isBrowserSupported() {
2980
+ const browser = this.getBrowser();
2981
+ const version = this.getVersion();
2982
+ const validBrowser = this.supportedBrowsers.includes(browser);
2983
+ if (!validBrowser) return false;
2984
+ if (browser === "chrome") return version >= this.minChromeVersion;
2985
+ if (browser === "firefox") return version >= this.minFirefoxVersion;
2986
+ if (browser === "safari") return !this.isIOS && version >= this.minSafariVersion;
2987
+ return false;
2988
+ }
2989
+ getBrowser() {
2990
+ return $a9bc9397a7d36afa$var$webRTCAdapter.browserDetails.browser;
2991
+ }
2992
+ getVersion() {
2993
+ return $a9bc9397a7d36afa$var$webRTCAdapter.browserDetails.version || 0;
2994
+ }
2995
+ isUnifiedPlanSupported() {
2996
+ const browser = this.getBrowser();
2997
+ const version = $a9bc9397a7d36afa$var$webRTCAdapter.browserDetails.version || 0;
2998
+ if (browser === "chrome" && version < this.minChromeVersion) return false;
2999
+ if (browser === "firefox" && version >= this.minFirefoxVersion) return true;
3000
+ if (!window.RTCRtpTransceiver || !("currentDirection" in RTCRtpTransceiver.prototype)) return false;
3001
+ let tempPc;
3002
+ let supported = false;
3003
+ try {
3004
+ tempPc = new RTCPeerConnection();
3005
+ tempPc.addTransceiver("audio");
3006
+ supported = true;
3007
+ } catch (e) {} finally{
3008
+ if (tempPc) tempPc.close();
3009
+ }
3010
+ return supported;
3011
+ }
3012
+ toString() {
3013
+ return `Supports:
3014
+ browser:${this.getBrowser()}
3015
+ version:${this.getVersion()}
3016
+ isIOS:${this.isIOS}
3017
+ isWebRTCSupported:${this.isWebRTCSupported()}
3018
+ isBrowserSupported:${this.isBrowserSupported()}
3019
+ isUnifiedPlanSupported:${this.isUnifiedPlanSupported()}`;
3020
+ }
3021
+ constructor(){
3022
+ this.isIOS = typeof navigator !== "undefined" ? [
3023
+ "iPad",
3024
+ "iPhone",
3025
+ "iPod"
3026
+ ].includes(navigator.platform) : false;
3027
+ this.supportedBrowsers = [
3028
+ "firefox",
3029
+ "chrome",
3030
+ "safari"
3031
+ ];
3032
+ this.minFirefoxVersion = 59;
3033
+ this.minChromeVersion = 72;
3034
+ this.minSafariVersion = 605;
3035
+ }
3036
+ }();
3037
+
3038
+
3039
+ const $fce54fbdd74b2319$export$f35f128fd59ea256 = (id)=>{
3040
+ // Allow empty ids
3041
+ return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(id);
3042
+ };
3043
+
3044
+
3045
+ const $008766fe99f03c2f$export$4e61f672936bec77 = ()=>Math.random().toString(36).slice(2);
3046
+
3047
+
3048
+ const $01f0d223090cb1f8$var$DEFAULT_CONFIG = {
3049
+ iceServers: [
3050
+ {
3051
+ urls: "stun:stun.l.google.com:19302"
3052
+ },
3053
+ {
3054
+ urls: [
3055
+ "turn:eu-0.turn.peerjs.com:3478",
3056
+ "turn:us-0.turn.peerjs.com:3478"
3057
+ ],
3058
+ username: "peerjs",
3059
+ credential: "peerjsp"
3060
+ }
3061
+ ],
3062
+ sdpSemantics: "unified-plan"
3063
+ };
3064
+ class $01f0d223090cb1f8$export$f8f26dd395d7e1bd extends (0, $616ebdf1c4998439$export$f1c5f4c9cb95390b) {
3065
+ noop() {}
3066
+ blobToArrayBuffer(blob, cb) {
3067
+ const fr = new FileReader();
3068
+ fr.onload = function(evt) {
3069
+ if (evt.target) cb(evt.target.result);
3070
+ };
3071
+ fr.readAsArrayBuffer(blob);
3072
+ return fr;
3073
+ }
3074
+ binaryStringToArrayBuffer(binary) {
3075
+ const byteArray = new Uint8Array(binary.length);
3076
+ for(let i = 0; i < binary.length; i++)byteArray[i] = binary.charCodeAt(i) & 0xff;
3077
+ return byteArray.buffer;
3078
+ }
3079
+ isSecure() {
3080
+ return location.protocol === "https:";
3081
+ }
3082
+ constructor(...args){
3083
+ super(...args), this.CLOUD_HOST = "0.peerjs.com", this.CLOUD_PORT = 443, // Browsers that need chunking:
3084
+ this.chunkedBrowsers = {
3085
+ Chrome: 1,
3086
+ chrome: 1
3087
+ }, // Returns browser-agnostic default config
3088
+ this.defaultConfig = $01f0d223090cb1f8$var$DEFAULT_CONFIG, this.browser = (0, $a9bc9397a7d36afa$export$25be9502477c137d).getBrowser(), this.browserVersion = (0, $a9bc9397a7d36afa$export$25be9502477c137d).getVersion(), this.pack = $6018e3630d94a7b2$export$2a703dbb0cb35339, this.unpack = $6018e3630d94a7b2$export$417857010dc9287f, /**
3089
+ * A hash of WebRTC features mapped to booleans that correspond to whether the feature is supported by the current browser.
3090
+ *
3091
+ * :::caution
3092
+ * Only the properties documented here are guaranteed to be present on `util.supports`
3093
+ * :::
3094
+ */ this.supports = function() {
3095
+ const supported = {
3096
+ browser: (0, $a9bc9397a7d36afa$export$25be9502477c137d).isBrowserSupported(),
3097
+ webRTC: (0, $a9bc9397a7d36afa$export$25be9502477c137d).isWebRTCSupported(),
3098
+ audioVideo: false,
3099
+ data: false,
3100
+ binaryBlob: false,
3101
+ reliable: false
3102
+ };
3103
+ if (!supported.webRTC) return supported;
3104
+ let pc;
3105
+ try {
3106
+ pc = new RTCPeerConnection($01f0d223090cb1f8$var$DEFAULT_CONFIG);
3107
+ supported.audioVideo = true;
3108
+ let dc;
3109
+ try {
3110
+ dc = pc.createDataChannel("_PEERJSTEST", {
3111
+ ordered: true
3112
+ });
3113
+ supported.data = true;
3114
+ supported.reliable = !!dc.ordered;
3115
+ // Binary test
3116
+ try {
3117
+ dc.binaryType = "blob";
3118
+ supported.binaryBlob = !(0, $a9bc9397a7d36afa$export$25be9502477c137d).isIOS;
3119
+ } catch (e) {}
3120
+ } catch (e) {} finally{
3121
+ if (dc) dc.close();
3122
+ }
3123
+ } catch (e) {} finally{
3124
+ if (pc) pc.close();
3125
+ }
3126
+ return supported;
3127
+ }(), // Ensure alphanumeric ids
3128
+ this.validateId = (0, $fce54fbdd74b2319$export$f35f128fd59ea256), this.randomToken = (0, $008766fe99f03c2f$export$4e61f672936bec77);
3129
+ }
3130
+ }
3131
+ const $01f0d223090cb1f8$export$7debb50ef11d5e0b = new $01f0d223090cb1f8$export$f8f26dd395d7e1bd();
3132
+
3133
+
3134
+
3135
+ const $d3fc3aacca52312c$var$LOG_PREFIX = "PeerJS: ";
3136
+ var $d3fc3aacca52312c$export$243e62d78d3b544d = /*#__PURE__*/ function(LogLevel) {
3137
+ /**
3138
+ * Prints no logs.
3139
+ */ LogLevel[LogLevel["Disabled"] = 0] = "Disabled";
3140
+ /**
3141
+ * Prints only errors.
3142
+ */ LogLevel[LogLevel["Errors"] = 1] = "Errors";
3143
+ /**
3144
+ * Prints errors and warnings.
3145
+ */ LogLevel[LogLevel["Warnings"] = 2] = "Warnings";
3146
+ /**
3147
+ * Prints all logs.
3148
+ */ LogLevel[LogLevel["All"] = 3] = "All";
3149
+ return LogLevel;
3150
+ }({});
3151
+ class $d3fc3aacca52312c$var$Logger {
3152
+ get logLevel() {
3153
+ return this._logLevel;
3154
+ }
3155
+ set logLevel(logLevel) {
3156
+ this._logLevel = logLevel;
3157
+ }
3158
+ log(...args) {
3159
+ if (this._logLevel >= 3) this._print(3, ...args);
3160
+ }
3161
+ warn(...args) {
3162
+ if (this._logLevel >= 2) this._print(2, ...args);
3163
+ }
3164
+ error(...args) {
3165
+ if (this._logLevel >= 1) this._print(1, ...args);
3166
+ }
3167
+ setLogFunction(fn) {
3168
+ this._print = fn;
3169
+ }
3170
+ _print(logLevel, ...rest) {
3171
+ const copy = [
3172
+ $d3fc3aacca52312c$var$LOG_PREFIX,
3173
+ ...rest
3174
+ ];
3175
+ for(const i in copy)if (copy[i] instanceof Error) copy[i] = "(" + copy[i].name + ") " + copy[i].message;
3176
+ if (logLevel >= 3) console.log(...copy);
3177
+ else if (logLevel >= 2) console.warn("WARNING", ...copy);
3178
+ else if (logLevel >= 1) console.error("ERROR", ...copy);
3179
+ }
3180
+ constructor(){
3181
+ this._logLevel = 0;
3182
+ }
3183
+ }
3184
+ var $d3fc3aacca52312c$export$2e2bcd8739ae039 = new $d3fc3aacca52312c$var$Logger();
3185
+
3186
+
3187
+ var $f5d7fbd88de797fd$exports = {};
3188
+ 'use strict';
3189
+ var $f5d7fbd88de797fd$var$has = Object.prototype.hasOwnProperty, $f5d7fbd88de797fd$var$prefix = '~';
3190
+ /**
3191
+ * Constructor to create a storage for our `EE` objects.
3192
+ * An `Events` instance is a plain object whose properties are event names.
3193
+ *
3194
+ * @constructor
3195
+ * @private
3196
+ */ function $f5d7fbd88de797fd$var$Events() {}
3197
+ //
3198
+ // We try to not inherit from `Object.prototype`. In some engines creating an
3199
+ // instance in this way is faster than calling `Object.create(null)` directly.
3200
+ // If `Object.create(null)` is not supported we prefix the event names with a
3201
+ // character to make sure that the built-in object properties are not
3202
+ // overridden or used as an attack vector.
3203
+ //
3204
+ if (Object.create) {
3205
+ $f5d7fbd88de797fd$var$Events.prototype = Object.create(null);
3206
+ //
3207
+ // This hack is needed because the `__proto__` property is still inherited in
3208
+ // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
3209
+ //
3210
+ if (!new $f5d7fbd88de797fd$var$Events().__proto__) $f5d7fbd88de797fd$var$prefix = false;
3211
+ }
3212
+ /**
3213
+ * Representation of a single event listener.
3214
+ *
3215
+ * @param {Function} fn The listener function.
3216
+ * @param {*} context The context to invoke the listener with.
3217
+ * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
3218
+ * @constructor
3219
+ * @private
3220
+ */ function $f5d7fbd88de797fd$var$EE(fn, context, once) {
3221
+ this.fn = fn;
3222
+ this.context = context;
3223
+ this.once = once || false;
3224
+ }
3225
+ /**
3226
+ * Add a listener for a given event.
3227
+ *
3228
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
3229
+ * @param {(String|Symbol)} event The event name.
3230
+ * @param {Function} fn The listener function.
3231
+ * @param {*} context The context to invoke the listener with.
3232
+ * @param {Boolean} once Specify if the listener is a one-time listener.
3233
+ * @returns {EventEmitter}
3234
+ * @private
3235
+ */ function $f5d7fbd88de797fd$var$addListener(emitter, event, fn, context, once) {
3236
+ if (typeof fn !== 'function') throw new TypeError('The listener must be a function');
3237
+ var listener = new $f5d7fbd88de797fd$var$EE(fn, context || emitter, once), evt = $f5d7fbd88de797fd$var$prefix ? $f5d7fbd88de797fd$var$prefix + event : event;
3238
+ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
3239
+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
3240
+ else emitter._events[evt] = [
3241
+ emitter._events[evt],
3242
+ listener
3243
+ ];
3244
+ return emitter;
3245
+ }
3246
+ /**
3247
+ * Clear event by name.
3248
+ *
3249
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
3250
+ * @param {(String|Symbol)} evt The Event name.
3251
+ * @private
3252
+ */ function $f5d7fbd88de797fd$var$clearEvent(emitter, evt) {
3253
+ if (--emitter._eventsCount === 0) emitter._events = new $f5d7fbd88de797fd$var$Events();
3254
+ else delete emitter._events[evt];
3255
+ }
3256
+ /**
3257
+ * Minimal `EventEmitter` interface that is molded against the Node.js
3258
+ * `EventEmitter` interface.
3259
+ *
3260
+ * @constructor
3261
+ * @public
3262
+ */ function $f5d7fbd88de797fd$var$EventEmitter() {
3263
+ this._events = new $f5d7fbd88de797fd$var$Events();
3264
+ this._eventsCount = 0;
3265
+ }
3266
+ /**
3267
+ * Return an array listing the events for which the emitter has registered
3268
+ * listeners.
3269
+ *
3270
+ * @returns {Array}
3271
+ * @public
3272
+ */ $f5d7fbd88de797fd$var$EventEmitter.prototype.eventNames = function eventNames() {
3273
+ var names = [], events, name;
3274
+ if (this._eventsCount === 0) return names;
3275
+ for(name in events = this._events)if ($f5d7fbd88de797fd$var$has.call(events, name)) names.push($f5d7fbd88de797fd$var$prefix ? name.slice(1) : name);
3276
+ if (Object.getOwnPropertySymbols) return names.concat(Object.getOwnPropertySymbols(events));
3277
+ return names;
3278
+ };
3279
+ /**
3280
+ * Return the listeners registered for a given event.
3281
+ *
3282
+ * @param {(String|Symbol)} event The event name.
3283
+ * @returns {Array} The registered listeners.
3284
+ * @public
3285
+ */ $f5d7fbd88de797fd$var$EventEmitter.prototype.listeners = function listeners(event) {
3286
+ var evt = $f5d7fbd88de797fd$var$prefix ? $f5d7fbd88de797fd$var$prefix + event : event, handlers = this._events[evt];
3287
+ if (!handlers) return [];
3288
+ if (handlers.fn) return [
3289
+ handlers.fn
3290
+ ];
3291
+ for(var i = 0, l = handlers.length, ee = new Array(l); i < l; i++)ee[i] = handlers[i].fn;
3292
+ return ee;
3293
+ };
3294
+ /**
3295
+ * Return the number of listeners listening to a given event.
3296
+ *
3297
+ * @param {(String|Symbol)} event The event name.
3298
+ * @returns {Number} The number of listeners.
3299
+ * @public
3300
+ */ $f5d7fbd88de797fd$var$EventEmitter.prototype.listenerCount = function listenerCount(event) {
3301
+ var evt = $f5d7fbd88de797fd$var$prefix ? $f5d7fbd88de797fd$var$prefix + event : event, listeners = this._events[evt];
3302
+ if (!listeners) return 0;
3303
+ if (listeners.fn) return 1;
3304
+ return listeners.length;
3305
+ };
3306
+ /**
3307
+ * Calls each of the listeners registered for a given event.
3308
+ *
3309
+ * @param {(String|Symbol)} event The event name.
3310
+ * @returns {Boolean} `true` if the event had listeners, else `false`.
3311
+ * @public
3312
+ */ $f5d7fbd88de797fd$var$EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
3313
+ var evt = $f5d7fbd88de797fd$var$prefix ? $f5d7fbd88de797fd$var$prefix + event : event;
3314
+ if (!this._events[evt]) return false;
3315
+ var listeners = this._events[evt], len = arguments.length, args, i;
3316
+ if (listeners.fn) {
3317
+ if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
3318
+ switch(len){
3319
+ case 1:
3320
+ return listeners.fn.call(listeners.context), true;
3321
+ case 2:
3322
+ return listeners.fn.call(listeners.context, a1), true;
3323
+ case 3:
3324
+ return listeners.fn.call(listeners.context, a1, a2), true;
3325
+ case 4:
3326
+ return listeners.fn.call(listeners.context, a1, a2, a3), true;
3327
+ case 5:
3328
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
3329
+ case 6:
3330
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
3331
+ }
3332
+ for(i = 1, args = new Array(len - 1); i < len; i++)args[i - 1] = arguments[i];
3333
+ listeners.fn.apply(listeners.context, args);
3334
+ } else {
3335
+ var length = listeners.length, j;
3336
+ for(i = 0; i < length; i++){
3337
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
3338
+ switch(len){
3339
+ case 1:
3340
+ listeners[i].fn.call(listeners[i].context);
3341
+ break;
3342
+ case 2:
3343
+ listeners[i].fn.call(listeners[i].context, a1);
3344
+ break;
3345
+ case 3:
3346
+ listeners[i].fn.call(listeners[i].context, a1, a2);
3347
+ break;
3348
+ case 4:
3349
+ listeners[i].fn.call(listeners[i].context, a1, a2, a3);
3350
+ break;
3351
+ default:
3352
+ if (!args) for(j = 1, args = new Array(len - 1); j < len; j++)args[j - 1] = arguments[j];
3353
+ listeners[i].fn.apply(listeners[i].context, args);
3354
+ }
3355
+ }
3356
+ }
3357
+ return true;
3358
+ };
3359
+ /**
3360
+ * Add a listener for a given event.
3361
+ *
3362
+ * @param {(String|Symbol)} event The event name.
3363
+ * @param {Function} fn The listener function.
3364
+ * @param {*} [context=this] The context to invoke the listener with.
3365
+ * @returns {EventEmitter} `this`.
3366
+ * @public
3367
+ */ $f5d7fbd88de797fd$var$EventEmitter.prototype.on = function on(event, fn, context) {
3368
+ return $f5d7fbd88de797fd$var$addListener(this, event, fn, context, false);
3369
+ };
3370
+ /**
3371
+ * Add a one-time listener for a given event.
3372
+ *
3373
+ * @param {(String|Symbol)} event The event name.
3374
+ * @param {Function} fn The listener function.
3375
+ * @param {*} [context=this] The context to invoke the listener with.
3376
+ * @returns {EventEmitter} `this`.
3377
+ * @public
3378
+ */ $f5d7fbd88de797fd$var$EventEmitter.prototype.once = function once(event, fn, context) {
3379
+ return $f5d7fbd88de797fd$var$addListener(this, event, fn, context, true);
3380
+ };
3381
+ /**
3382
+ * Remove the listeners of a given event.
3383
+ *
3384
+ * @param {(String|Symbol)} event The event name.
3385
+ * @param {Function} fn Only remove the listeners that match this function.
3386
+ * @param {*} context Only remove the listeners that have this context.
3387
+ * @param {Boolean} once Only remove one-time listeners.
3388
+ * @returns {EventEmitter} `this`.
3389
+ * @public
3390
+ */ $f5d7fbd88de797fd$var$EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
3391
+ var evt = $f5d7fbd88de797fd$var$prefix ? $f5d7fbd88de797fd$var$prefix + event : event;
3392
+ if (!this._events[evt]) return this;
3393
+ if (!fn) {
3394
+ $f5d7fbd88de797fd$var$clearEvent(this, evt);
3395
+ return this;
3396
+ }
3397
+ var listeners = this._events[evt];
3398
+ if (listeners.fn) {
3399
+ if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) $f5d7fbd88de797fd$var$clearEvent(this, evt);
3400
+ } else {
3401
+ for(var i = 0, events = [], length = listeners.length; i < length; i++)if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) events.push(listeners[i]);
3402
+ //
3403
+ // Reset the array, or remove it completely if we have no more listeners.
3404
+ //
3405
+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
3406
+ else $f5d7fbd88de797fd$var$clearEvent(this, evt);
3407
+ }
3408
+ return this;
3409
+ };
3410
+ /**
3411
+ * Remove all listeners, or those of the specified event.
3412
+ *
3413
+ * @param {(String|Symbol)} [event] The event name.
3414
+ * @returns {EventEmitter} `this`.
3415
+ * @public
3416
+ */ $f5d7fbd88de797fd$var$EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
3417
+ var evt;
3418
+ if (event) {
3419
+ evt = $f5d7fbd88de797fd$var$prefix ? $f5d7fbd88de797fd$var$prefix + event : event;
3420
+ if (this._events[evt]) $f5d7fbd88de797fd$var$clearEvent(this, evt);
3421
+ } else {
3422
+ this._events = new $f5d7fbd88de797fd$var$Events();
3423
+ this._eventsCount = 0;
3424
+ }
3425
+ return this;
3426
+ };
3427
+ //
3428
+ // Alias methods names because people roll like that.
3429
+ //
3430
+ $f5d7fbd88de797fd$var$EventEmitter.prototype.off = $f5d7fbd88de797fd$var$EventEmitter.prototype.removeListener;
3431
+ $f5d7fbd88de797fd$var$EventEmitter.prototype.addListener = $f5d7fbd88de797fd$var$EventEmitter.prototype.on;
3432
+ //
3433
+ // Expose the prefix.
3434
+ //
3435
+ $f5d7fbd88de797fd$var$EventEmitter.prefixed = $f5d7fbd88de797fd$var$prefix;
3436
+ //
3437
+ // Allow `EventEmitter` to be imported as module namespace.
3438
+ //
3439
+ $f5d7fbd88de797fd$var$EventEmitter.EventEmitter = $f5d7fbd88de797fd$var$EventEmitter;
3440
+ $f5d7fbd88de797fd$exports = $f5d7fbd88de797fd$var$EventEmitter;
3441
+
3442
+
3443
+
3444
+ var $edbcf3072a01d580$export$3157d57b4135e3bc = /*#__PURE__*/ function(ConnectionType) {
3445
+ ConnectionType["Data"] = "data";
3446
+ ConnectionType["Media"] = "media";
3447
+ return ConnectionType;
3448
+ }({});
3449
+ var $edbcf3072a01d580$export$9547aaa2e39030ff = /*#__PURE__*/ function(PeerErrorType) {
3450
+ /**
3451
+ * The client's browser does not support some or all WebRTC features that you are trying to use.
3452
+ */ PeerErrorType["BrowserIncompatible"] = "browser-incompatible";
3453
+ /**
3454
+ * You've already disconnected this peer from the server and can no longer make any new connections on it.
3455
+ */ PeerErrorType["Disconnected"] = "disconnected";
3456
+ /**
3457
+ * The ID passed into the Peer constructor contains illegal characters.
3458
+ */ PeerErrorType["InvalidID"] = "invalid-id";
3459
+ /**
3460
+ * The API key passed into the Peer constructor contains illegal characters or is not in the system (cloud server only).
3461
+ */ PeerErrorType["InvalidKey"] = "invalid-key";
3462
+ /**
3463
+ * Lost or cannot establish a connection to the signalling server.
3464
+ */ PeerErrorType["Network"] = "network";
3465
+ /**
3466
+ * The peer you're trying to connect to does not exist.
3467
+ */ PeerErrorType["PeerUnavailable"] = "peer-unavailable";
3468
+ /**
3469
+ * PeerJS is being used securely, but the cloud server does not support SSL. Use a custom PeerServer.
3470
+ */ PeerErrorType["SslUnavailable"] = "ssl-unavailable";
3471
+ /**
3472
+ * Unable to reach the server.
3473
+ */ PeerErrorType["ServerError"] = "server-error";
3474
+ /**
3475
+ * An error from the underlying socket.
3476
+ */ PeerErrorType["SocketError"] = "socket-error";
3477
+ /**
3478
+ * The underlying socket closed unexpectedly.
3479
+ */ PeerErrorType["SocketClosed"] = "socket-closed";
3480
+ /**
3481
+ * The ID passed into the Peer constructor is already taken.
3482
+ *
3483
+ * :::caution
3484
+ * This error is not fatal if your peer has open peer-to-peer connections.
3485
+ * This can happen if you attempt to {@apilink Peer.reconnect} a peer that has been disconnected from the server,
3486
+ * but its old ID has now been taken.
3487
+ * :::
3488
+ */ PeerErrorType["UnavailableID"] = "unavailable-id";
3489
+ /**
3490
+ * Native WebRTC errors.
3491
+ */ PeerErrorType["WebRTC"] = "webrtc";
3492
+ return PeerErrorType;
3493
+ }({});
3494
+ var $edbcf3072a01d580$export$7974935686149686 = /*#__PURE__*/ function(BaseConnectionErrorType) {
3495
+ BaseConnectionErrorType["NegotiationFailed"] = "negotiation-failed";
3496
+ BaseConnectionErrorType["ConnectionClosed"] = "connection-closed";
3497
+ return BaseConnectionErrorType;
3498
+ }({});
3499
+ var $edbcf3072a01d580$export$49ae800c114df41d = /*#__PURE__*/ function(DataConnectionErrorType) {
3500
+ DataConnectionErrorType["NotOpenYet"] = "not-open-yet";
3501
+ DataConnectionErrorType["MessageToBig"] = "message-too-big";
3502
+ return DataConnectionErrorType;
3503
+ }({});
3504
+ var $edbcf3072a01d580$export$89f507cf986a947 = /*#__PURE__*/ function(SerializationType) {
3505
+ SerializationType["Binary"] = "binary";
3506
+ SerializationType["BinaryUTF8"] = "binary-utf8";
3507
+ SerializationType["JSON"] = "json";
3508
+ SerializationType["None"] = "raw";
3509
+ return SerializationType;
3510
+ }({});
3511
+ var $edbcf3072a01d580$export$3b5c4a4b6354f023 = /*#__PURE__*/ function(SocketEventType) {
3512
+ SocketEventType["Message"] = "message";
3513
+ SocketEventType["Disconnected"] = "disconnected";
3514
+ SocketEventType["Error"] = "error";
3515
+ SocketEventType["Close"] = "close";
3516
+ return SocketEventType;
3517
+ }({});
3518
+ var $edbcf3072a01d580$export$adb4a1754da6f10d = /*#__PURE__*/ function(ServerMessageType) {
3519
+ ServerMessageType["Heartbeat"] = "HEARTBEAT";
3520
+ ServerMessageType["Candidate"] = "CANDIDATE";
3521
+ ServerMessageType["Offer"] = "OFFER";
3522
+ ServerMessageType["Answer"] = "ANSWER";
3523
+ ServerMessageType["Open"] = "OPEN";
3524
+ ServerMessageType["Error"] = "ERROR";
3525
+ ServerMessageType["IdTaken"] = "ID-TAKEN";
3526
+ ServerMessageType["InvalidKey"] = "INVALID-KEY";
3527
+ ServerMessageType["Leave"] = "LEAVE";
3528
+ ServerMessageType["Expire"] = "EXPIRE";
3529
+ return ServerMessageType;
3530
+ }({});
3531
+
3532
+
3533
+ var $580fed67ed3c559d$exports = {};
3534
+ $580fed67ed3c559d$exports = JSON.parse('{"name":"@s21g/peerjs","version":"1.5.4","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz St\xfcckler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","So\u0308ren Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","browser-minified-msgpack":"dist/serializer.msgpack.mjs","types":"dist/types.d.ts","engines":{"node":">= 14"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 80, safari >= 15"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 80, safari >= 15"},"source":"lib/global.ts"},"browser-minified-msgpack":{"context":"browser","outputFormat":"esmodule","isLibrary":true,"optimize":true,"engines":{"browsers":"chrome >= 83, edge >= 83, firefox >= 102, safari >= 15"},"source":"lib/dataconnection/StreamConnection/MsgPack.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit && tsc -p e2e/tsconfig.json --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","clean":"rm -rf .parcel-cache dist","prepublishOnly":"npm run build","test":"jest","test:watch":"jest --watch","coverage":"jest --coverage --collectCoverageFrom=\\"./lib/**\\"","format":"prettier --write .","format:check":"prettier --check .","semantic-release":"semantic-release","e2e":"wdio run e2e/wdio.local.conf.ts","e2e:bstack":"wdio run e2e/wdio.bstack.conf.ts"},"devDependencies":{"@jest/globals":"^29.7.0","@parcel/config-default":"^2.9.3","@parcel/packager-ts":"^2.9.3","@parcel/transformer-typescript-tsc":"^2.9.3","@parcel/transformer-typescript-types":"^2.9.3","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@swc/core":"^1.3.27","@swc/jest":"^0.2.24","@types/jasmine":"^4.3.4","@wdio/browserstack-service":"^8.11.2","@wdio/cli":"^8.11.2","@wdio/globals":"^8.11.2","@wdio/jasmine-framework":"^8.11.2","@wdio/local-runner":"^8.11.2","@wdio/spec-reporter":"^8.11.2","@wdio/types":"^8.10.4","http-server":"^14.1.1","jest":"^29.3.1","jest-environment-jsdom":"^29.3.1","mock-socket":"^9.0.0","parcel":"^2.9.3","prettier":"^3.0.0","semantic-release":"^23.0.0","ts-node":"^10.9.1","typescript":"^5.0.0","wdio-geckodriver-service":"^5.0.1"},"dependencies":{"@msgpack/msgpack":"^2.8.0","eventemitter3":"^4.0.7","peerjs-js-binarypack":"file:../js-binarypack","webrtc-adapter":"^9.0.0"},"alias":{"process":false,"buffer":false}}');
3535
+
3536
+
3537
+ class $5dd3b97502a89fbb$export$4798917dbf149b79 extends (0, $f5d7fbd88de797fd$exports.EventEmitter) {
3538
+ start(id, token) {
3539
+ this._id = id;
3540
+ const wsUrl = `${this._baseUrl}&id=${id}&token=${token}`;
3541
+ if (!!this._socket || !this._disconnected) return;
3542
+ this._socket = new WebSocket(wsUrl + "&version=" + (0, $580fed67ed3c559d$exports.version));
3543
+ this._disconnected = false;
3544
+ this._socket.onmessage = (event)=>{
3545
+ let data;
3546
+ try {
3547
+ data = JSON.parse(event.data);
3548
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Server message received:", data);
3549
+ } catch (e) {
3550
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Invalid server message", event.data);
3551
+ return;
3552
+ }
3553
+ this.emit((0, $edbcf3072a01d580$export$3b5c4a4b6354f023).Message, data);
3554
+ };
3555
+ this._socket.onclose = (event)=>{
3556
+ if (this._disconnected) return;
3557
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Socket closed.", event);
3558
+ this._cleanup();
3559
+ this._disconnected = true;
3560
+ this.emit((0, $edbcf3072a01d580$export$3b5c4a4b6354f023).Disconnected);
3561
+ };
3562
+ // Take care of the queue of connections if necessary and make sure Peer knows
3563
+ // socket is open.
3564
+ this._socket.onopen = ()=>{
3565
+ if (this._disconnected) return;
3566
+ this._sendQueuedMessages();
3567
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Socket open");
3568
+ this._scheduleHeartbeat();
3569
+ };
3570
+ }
3571
+ _scheduleHeartbeat() {
3572
+ this._wsPingTimer = setTimeout(()=>{
3573
+ this._sendHeartbeat();
3574
+ }, this.pingInterval);
3575
+ }
3576
+ _sendHeartbeat() {
3577
+ if (!this._wsOpen()) {
3578
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`Cannot send heartbeat, because socket closed`);
3579
+ return;
3580
+ }
3581
+ const message = JSON.stringify({
3582
+ type: (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Heartbeat
3583
+ });
3584
+ this._socket.send(message);
3585
+ this._scheduleHeartbeat();
3586
+ }
3587
+ /** Is the websocket currently open? */ _wsOpen() {
3588
+ return !!this._socket && this._socket.readyState === 1;
3589
+ }
3590
+ /** Send queued messages. */ _sendQueuedMessages() {
3591
+ //Create copy of queue and clear it,
3592
+ //because send method push the message back to queue if smth will go wrong
3593
+ const copiedQueue = [
3594
+ ...this._messagesQueue
3595
+ ];
3596
+ this._messagesQueue = [];
3597
+ for (const message of copiedQueue)this.send(message);
3598
+ }
3599
+ /** Exposed send for DC & Peer. */ send(data) {
3600
+ if (this._disconnected) return;
3601
+ // If we didn't get an ID yet, we can't yet send anything so we should queue
3602
+ // up these messages.
3603
+ if (!this._id) {
3604
+ this._messagesQueue.push(data);
3605
+ return;
3606
+ }
3607
+ if (!data.type) {
3608
+ this.emit((0, $edbcf3072a01d580$export$3b5c4a4b6354f023).Error, "Invalid message");
3609
+ return;
3610
+ }
3611
+ if (!this._wsOpen()) return;
3612
+ const message = JSON.stringify(data);
3613
+ this._socket.send(message);
3614
+ }
3615
+ close() {
3616
+ if (this._disconnected) return;
3617
+ this._cleanup();
3618
+ this._disconnected = true;
3619
+ }
3620
+ _cleanup() {
3621
+ if (this._socket) {
3622
+ this._socket.onopen = this._socket.onmessage = this._socket.onclose = null;
3623
+ this._socket.close();
3624
+ this._socket = undefined;
3625
+ }
3626
+ clearTimeout(this._wsPingTimer);
3627
+ }
3628
+ constructor(secure, host, port, path, key, pingInterval = 5000){
3629
+ super(), this.pingInterval = pingInterval, this._disconnected = true, this._messagesQueue = [];
3630
+ const wsProtocol = secure ? "wss://" : "ws://";
3631
+ this._baseUrl = wsProtocol + host + ":" + port + path + "peerjs?key=" + key;
3632
+ }
3633
+ }
3634
+
3635
+
3636
+
3637
+
3638
+
3639
+
3640
+ class $3cabb799c2437cbe$export$89e6bb5ad64bf4a {
3641
+ /** Returns a PeerConnection object set up correctly (for data, media). */ startConnection(options) {
3642
+ const peerConnection = this._startPeerConnection();
3643
+ // Set the connection's PC.
3644
+ this.connection.peerConnection = peerConnection;
3645
+ if (this.connection.type === (0, $edbcf3072a01d580$export$3157d57b4135e3bc).Media && options._stream) this._addTracksToConnection(options._stream, peerConnection);
3646
+ // What do we need to do now?
3647
+ if (options.originator) {
3648
+ const dataConnection = this.connection;
3649
+ const config = {
3650
+ ordered: !!options.reliable
3651
+ };
3652
+ const dataChannel = peerConnection.createDataChannel(dataConnection.label, config);
3653
+ dataConnection._initializeDataChannel(dataChannel);
3654
+ this._makeOffer();
3655
+ } else this.handleSDP("OFFER", options.sdp);
3656
+ }
3657
+ /** Start a PC. */ _startPeerConnection() {
3658
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Creating RTCPeerConnection.");
3659
+ const peerConnection = new RTCPeerConnection(this.connection.provider.options.config);
3660
+ this._setupListeners(peerConnection);
3661
+ return peerConnection;
3662
+ }
3663
+ /** Set up various WebRTC listeners. */ _setupListeners(peerConnection) {
3664
+ const peerId = this.connection.peer;
3665
+ const connectionId = this.connection.connectionId;
3666
+ const connectionType = this.connection.type;
3667
+ const provider = this.connection.provider;
3668
+ // ICE CANDIDATES.
3669
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Listening for ICE candidates.");
3670
+ peerConnection.onicecandidate = (evt)=>{
3671
+ if (!evt.candidate || !evt.candidate.candidate) return;
3672
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`Received ICE candidates for ${peerId}:`, evt.candidate);
3673
+ provider.socket.send({
3674
+ type: (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Candidate,
3675
+ payload: {
3676
+ candidate: evt.candidate,
3677
+ type: connectionType,
3678
+ connectionId: connectionId
3679
+ },
3680
+ dst: peerId
3681
+ });
3682
+ };
3683
+ peerConnection.oniceconnectionstatechange = ()=>{
3684
+ switch(peerConnection.iceConnectionState){
3685
+ case "failed":
3686
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("iceConnectionState is failed, closing connections to " + peerId);
3687
+ this.connection.emitError((0, $edbcf3072a01d580$export$7974935686149686).NegotiationFailed, "Negotiation of connection to " + peerId + " failed.");
3688
+ this.connection.close();
3689
+ break;
3690
+ case "closed":
3691
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("iceConnectionState is closed, closing connections to " + peerId);
3692
+ this.connection.emitError((0, $edbcf3072a01d580$export$7974935686149686).ConnectionClosed, "Connection to " + peerId + " closed.");
3693
+ this.connection.close();
3694
+ break;
3695
+ case "disconnected":
3696
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("iceConnectionState changed to disconnected on the connection with " + peerId);
3697
+ break;
3698
+ case "completed":
3699
+ peerConnection.onicecandidate = ()=>{};
3700
+ break;
3701
+ }
3702
+ this.connection.emit("iceStateChanged", peerConnection.iceConnectionState);
3703
+ };
3704
+ // DATACONNECTION.
3705
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Listening for data channel");
3706
+ // Fired between offer and answer, so options should already be saved
3707
+ // in the options hash.
3708
+ peerConnection.ondatachannel = (evt)=>{
3709
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Received data channel");
3710
+ const dataChannel = evt.channel;
3711
+ const connection = provider.getConnection(peerId, connectionId);
3712
+ connection._initializeDataChannel(dataChannel);
3713
+ };
3714
+ // MEDIACONNECTION.
3715
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Listening for remote stream");
3716
+ peerConnection.ontrack = (evt)=>{
3717
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Received remote stream");
3718
+ const stream = evt.streams[0];
3719
+ const connection = provider.getConnection(peerId, connectionId);
3720
+ if (connection.type === (0, $edbcf3072a01d580$export$3157d57b4135e3bc).Media) {
3721
+ const mediaConnection = connection;
3722
+ this._addStreamToMediaConnection(stream, mediaConnection);
3723
+ }
3724
+ };
3725
+ }
3726
+ cleanup() {
3727
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Cleaning up PeerConnection to " + this.connection.peer);
3728
+ const peerConnection = this.connection.peerConnection;
3729
+ if (!peerConnection) return;
3730
+ this.connection.peerConnection = null;
3731
+ //unsubscribe from all PeerConnection's events
3732
+ peerConnection.onicecandidate = peerConnection.oniceconnectionstatechange = peerConnection.ondatachannel = peerConnection.ontrack = ()=>{};
3733
+ const peerConnectionNotClosed = peerConnection.signalingState !== "closed";
3734
+ let dataChannelNotClosed = false;
3735
+ const dataChannel = this.connection.dataChannel;
3736
+ if (dataChannel) dataChannelNotClosed = !!dataChannel.readyState && dataChannel.readyState !== "closed";
3737
+ if (peerConnectionNotClosed || dataChannelNotClosed) peerConnection.close();
3738
+ }
3739
+ async _makeOffer() {
3740
+ const peerConnection = this.connection.peerConnection;
3741
+ const provider = this.connection.provider;
3742
+ try {
3743
+ const offer = await peerConnection.createOffer(this.connection.options.constraints);
3744
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Created offer.");
3745
+ if (this.connection.options.sdpTransform && typeof this.connection.options.sdpTransform === "function") offer.sdp = this.connection.options.sdpTransform(offer.sdp) || offer.sdp;
3746
+ try {
3747
+ await peerConnection.setLocalDescription(offer);
3748
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Set localDescription:", offer, `for:${this.connection.peer}`);
3749
+ let payload = {
3750
+ sdp: offer,
3751
+ type: this.connection.type,
3752
+ connectionId: this.connection.connectionId,
3753
+ metadata: this.connection.metadata
3754
+ };
3755
+ if (this.connection.type === (0, $edbcf3072a01d580$export$3157d57b4135e3bc).Data) {
3756
+ const dataConnection = this.connection;
3757
+ payload = {
3758
+ ...payload,
3759
+ label: dataConnection.label,
3760
+ reliable: dataConnection.reliable,
3761
+ serialization: dataConnection.serialization
3762
+ };
3763
+ }
3764
+ provider.socket.send({
3765
+ type: (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Offer,
3766
+ payload: payload,
3767
+ dst: this.connection.peer
3768
+ });
3769
+ } catch (err) {
3770
+ // TODO: investigate why _makeOffer is being called from the answer
3771
+ if (err != "OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer") {
3772
+ provider.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).WebRTC, err);
3773
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Failed to setLocalDescription, ", err);
3774
+ }
3775
+ }
3776
+ } catch (err_1) {
3777
+ provider.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).WebRTC, err_1);
3778
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Failed to createOffer, ", err_1);
3779
+ }
3780
+ }
3781
+ async _makeAnswer() {
3782
+ const peerConnection = this.connection.peerConnection;
3783
+ const provider = this.connection.provider;
3784
+ try {
3785
+ const answer = await peerConnection.createAnswer();
3786
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Created answer.");
3787
+ if (this.connection.options.sdpTransform && typeof this.connection.options.sdpTransform === "function") answer.sdp = this.connection.options.sdpTransform(answer.sdp) || answer.sdp;
3788
+ try {
3789
+ await peerConnection.setLocalDescription(answer);
3790
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`Set localDescription:`, answer, `for:${this.connection.peer}`);
3791
+ provider.socket.send({
3792
+ type: (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Answer,
3793
+ payload: {
3794
+ sdp: answer,
3795
+ type: this.connection.type,
3796
+ connectionId: this.connection.connectionId
3797
+ },
3798
+ dst: this.connection.peer
3799
+ });
3800
+ } catch (err) {
3801
+ provider.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).WebRTC, err);
3802
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Failed to setLocalDescription, ", err);
3803
+ }
3804
+ } catch (err_1) {
3805
+ provider.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).WebRTC, err_1);
3806
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Failed to create answer, ", err_1);
3807
+ }
3808
+ }
3809
+ /** Handle an SDP. */ async handleSDP(type, sdp) {
3810
+ sdp = new RTCSessionDescription(sdp);
3811
+ const peerConnection = this.connection.peerConnection;
3812
+ const provider = this.connection.provider;
3813
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Setting remote description", sdp);
3814
+ const self = this;
3815
+ try {
3816
+ await peerConnection.setRemoteDescription(sdp);
3817
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`Set remoteDescription:${type} for:${this.connection.peer}`);
3818
+ if (type === "OFFER") await self._makeAnswer();
3819
+ } catch (err) {
3820
+ provider.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).WebRTC, err);
3821
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Failed to setRemoteDescription, ", err);
3822
+ }
3823
+ }
3824
+ /** Handle a candidate. */ async handleCandidate(ice) {
3825
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`handleCandidate:`, ice);
3826
+ try {
3827
+ await this.connection.peerConnection.addIceCandidate(ice);
3828
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`Added ICE candidate for:${this.connection.peer}`);
3829
+ } catch (err) {
3830
+ this.connection.provider.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).WebRTC, err);
3831
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Failed to handleCandidate, ", err);
3832
+ }
3833
+ }
3834
+ _addTracksToConnection(stream, peerConnection) {
3835
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`add tracks from stream ${stream.id} to peer connection`);
3836
+ if (!peerConnection.addTrack) return (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).error(`Your browser does't support RTCPeerConnection#addTrack. Ignored.`);
3837
+ stream.getTracks().forEach((track)=>{
3838
+ peerConnection.addTrack(track, stream);
3839
+ });
3840
+ }
3841
+ _addStreamToMediaConnection(stream, mediaConnection) {
3842
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`add stream ${stream.id} to media connection ${mediaConnection.connectionId}`);
3843
+ mediaConnection.addStream(stream);
3844
+ }
3845
+ constructor(connection){
3846
+ this.connection = connection;
3847
+ }
3848
+ }
3849
+
3850
+
3851
+
3852
+
3853
+
3854
+ class $41eb28b5735ed6cf$export$6a678e589c8a4542 extends (0, $f5d7fbd88de797fd$exports.EventEmitter) {
3855
+ /**
3856
+ * Emits a typed error message.
3857
+ *
3858
+ * @internal
3859
+ */ emitError(type, err) {
3860
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).error("Error:", err);
3861
+ // @ts-ignore
3862
+ this.emit("error", new $41eb28b5735ed6cf$export$98871882f492de82(`${type}`, err));
3863
+ }
3864
+ }
3865
+ class $41eb28b5735ed6cf$export$98871882f492de82 extends Error {
3866
+ /**
3867
+ * @internal
3868
+ */ constructor(type, err){
3869
+ if (typeof err === "string") super(err);
3870
+ else {
3871
+ super();
3872
+ Object.assign(this, err);
3873
+ }
3874
+ this.type = type;
3875
+ }
3876
+ }
3877
+
3878
+
3879
+ class $f06f075a81a8b63e$export$23a2a68283c24d80 extends (0, $41eb28b5735ed6cf$export$6a678e589c8a4542) {
3880
+ /**
3881
+ * Whether the media connection is active (e.g. your call has been answered).
3882
+ * You can check this if you want to set a maximum wait time for a one-sided call.
3883
+ */ get open() {
3884
+ return this._open;
3885
+ }
3886
+ constructor(/**
3887
+ * The ID of the peer on the other end of this connection.
3888
+ */ peer, provider, options){
3889
+ super(), this.peer = peer, this.provider = provider, this.options = options, this._open = false;
3890
+ this.metadata = options.metadata;
3891
+ }
3892
+ }
3893
+
3894
+
3895
+ class $0bc12d7ac26e1491$export$4a84e95a2324ac29 extends (0, $f06f075a81a8b63e$export$23a2a68283c24d80) {
3896
+ /**
3897
+ * For media connections, this is always 'media'.
3898
+ */ get type() {
3899
+ return (0, $edbcf3072a01d580$export$3157d57b4135e3bc).Media;
3900
+ }
3901
+ get localStream() {
3902
+ return this._localStream;
3903
+ }
3904
+ get remoteStream() {
3905
+ return this._remoteStream;
3906
+ }
3907
+ /** Called by the Negotiator when the DataChannel is ready. */ _initializeDataChannel(dc) {
3908
+ this.dataChannel = dc;
3909
+ this.dataChannel.onopen = ()=>{
3910
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`DC#${this.connectionId} dc connection success`);
3911
+ this.emit("willCloseOnRemote");
3912
+ };
3913
+ this.dataChannel.onclose = ()=>{
3914
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`DC#${this.connectionId} dc closed for:`, this.peer);
3915
+ this.close();
3916
+ };
3917
+ }
3918
+ addStream(remoteStream) {
3919
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log("Receiving stream", remoteStream);
3920
+ this._remoteStream = remoteStream;
3921
+ super.emit("stream", remoteStream); // Should we call this `open`?
3922
+ }
3923
+ /**
3924
+ * @internal
3925
+ */ handleMessage(message) {
3926
+ const type = message.type;
3927
+ const payload = message.payload;
3928
+ switch(message.type){
3929
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Answer:
3930
+ // Forward to negotiator
3931
+ this._negotiator.handleSDP(type, payload.sdp);
3932
+ this._open = true;
3933
+ break;
3934
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Candidate:
3935
+ this._negotiator.handleCandidate(payload.candidate);
3936
+ break;
3937
+ default:
3938
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).warn(`Unrecognized message type:${type} from peer:${this.peer}`);
3939
+ break;
3940
+ }
3941
+ }
3942
+ /**
3943
+ * When receiving a {@apilink PeerEvents | `call`} event on a peer, you can call
3944
+ * `answer` on the media connection provided by the callback to accept the call
3945
+ * and optionally send your own media stream.
3946
+
3947
+ *
3948
+ * @param stream A WebRTC media stream.
3949
+ * @param options
3950
+ * @returns
3951
+ */ answer(stream, options = {}) {
3952
+ if (this._localStream) {
3953
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");
3954
+ return;
3955
+ }
3956
+ this._localStream = stream;
3957
+ if (options && options.sdpTransform) this.options.sdpTransform = options.sdpTransform;
3958
+ this._negotiator.startConnection({
3959
+ ...this.options._payload,
3960
+ _stream: stream
3961
+ });
3962
+ // Retrieve lost messages stored because PeerConnection not set up.
3963
+ const messages = this.provider._getMessages(this.connectionId);
3964
+ for (const message of messages)this.handleMessage(message);
3965
+ this._open = true;
3966
+ }
3967
+ /**
3968
+ * Exposed functionality for users.
3969
+ */ /**
3970
+ * Closes the media connection.
3971
+ */ close() {
3972
+ if (this._negotiator) {
3973
+ this._negotiator.cleanup();
3974
+ this._negotiator = null;
3975
+ }
3976
+ this._localStream = null;
3977
+ this._remoteStream = null;
3978
+ if (this.provider) {
3979
+ this.provider._removeConnection(this);
3980
+ this.provider = null;
3981
+ }
3982
+ if (this.options && this.options._stream) this.options._stream = null;
3983
+ if (!this.open) return;
3984
+ this._open = false;
3985
+ super.emit("close");
3986
+ }
3987
+ constructor(peerId, provider, options){
3988
+ super(peerId, provider, options);
3989
+ this._localStream = this.options._stream;
3990
+ this.connectionId = this.options.connectionId || $0bc12d7ac26e1491$export$4a84e95a2324ac29.ID_PREFIX + (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).randomToken();
3991
+ this._negotiator = new (0, $3cabb799c2437cbe$export$89e6bb5ad64bf4a)(this);
3992
+ if (this._localStream) this._negotiator.startConnection({
3993
+ _stream: this._localStream,
3994
+ originator: true
3995
+ });
3996
+ }
3997
+ }
3998
+ $0bc12d7ac26e1491$export$4a84e95a2324ac29.ID_PREFIX = "mc_";
3999
+
4000
+
4001
+
4002
+
4003
+
4004
+
4005
+ class $4c932c6613316196$export$2c4e825dc9120f87 {
4006
+ _buildRequest(method) {
4007
+ const protocol = this._options.secure ? "https" : "http";
4008
+ const { host: host, port: port, path: path, key: key } = this._options;
4009
+ const url = new URL(`${protocol}://${host}:${port}${path}${key}/${method}`);
4010
+ // TODO: Why timestamp, why random?
4011
+ url.searchParams.set("ts", `${Date.now()}${Math.random()}`);
4012
+ url.searchParams.set("version", (0, $580fed67ed3c559d$exports.version));
4013
+ return fetch(url.href, {
4014
+ referrerPolicy: this._options.referrerPolicy
4015
+ });
4016
+ }
4017
+ /** Get a unique ID from the server via XHR and initialize with it. */ async retrieveId() {
4018
+ try {
4019
+ const response = await this._buildRequest("id");
4020
+ if (response.status !== 200) throw new Error(`Error. Status:${response.status}`);
4021
+ return response.text();
4022
+ } catch (error) {
4023
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).error("Error retrieving ID", error);
4024
+ let pathError = "";
4025
+ if (this._options.path === "/" && this._options.host !== (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).CLOUD_HOST) pathError = " If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer.";
4026
+ throw new Error("Could not get an ID from the server." + pathError);
4027
+ }
4028
+ }
4029
+ /** @deprecated */ async listAllPeers() {
4030
+ try {
4031
+ const response = await this._buildRequest("peers");
4032
+ if (response.status !== 200) {
4033
+ if (response.status === 401) {
4034
+ let helpfulError = "";
4035
+ if (this._options.host === (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).CLOUD_HOST) helpfulError = "It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.";
4036
+ else helpfulError = "You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.";
4037
+ throw new Error("It doesn't look like you have permission to list peers IDs. " + helpfulError);
4038
+ }
4039
+ throw new Error(`Error. Status:${response.status}`);
4040
+ }
4041
+ return response.json();
4042
+ } catch (error) {
4043
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).error("Error retrieving list peers", error);
4044
+ throw new Error("Could not get list peers from the server." + error);
4045
+ }
4046
+ }
4047
+ constructor(_options){
4048
+ this._options = _options;
4049
+ }
4050
+ }
4051
+
4052
+
4053
+
4054
+
4055
+
4056
+
4057
+
4058
+
4059
+
4060
+
4061
+ class $392ccce28b647101$export$d365f7ad9d7df9c9 extends (0, $f06f075a81a8b63e$export$23a2a68283c24d80) {
4062
+ get type() {
4063
+ return (0, $edbcf3072a01d580$export$3157d57b4135e3bc).Data;
4064
+ }
4065
+ /** Called by the Negotiator when the DataChannel is ready. */ _initializeDataChannel(dc) {
4066
+ this.dataChannel = dc;
4067
+ this.dataChannel.onopen = ()=>{
4068
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`DC#${this.connectionId} dc connection success`);
4069
+ this._open = true;
4070
+ this.emit("open");
4071
+ };
4072
+ this.dataChannel.onmessage = (e)=>{
4073
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`DC#${this.connectionId} dc onmessage:`, e.data);
4074
+ // this._handleDataMessage(e);
4075
+ };
4076
+ this.dataChannel.onclose = ()=>{
4077
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`DC#${this.connectionId} dc closed for:`, this.peer);
4078
+ this.close();
4079
+ };
4080
+ }
4081
+ /**
4082
+ * Exposed functionality for users.
4083
+ */ /** Allows user to close connection. */ close(options) {
4084
+ if (options?.flush) {
4085
+ this.send({
4086
+ __peerData: {
4087
+ type: "close"
4088
+ }
4089
+ });
4090
+ return;
4091
+ }
4092
+ if (this._negotiator) {
4093
+ this._negotiator.cleanup();
4094
+ this._negotiator = null;
4095
+ }
4096
+ if (this.provider) {
4097
+ this.provider._removeConnection(this);
4098
+ this.provider = null;
4099
+ }
4100
+ if (this.dataChannel) {
4101
+ this.dataChannel.onopen = null;
4102
+ this.dataChannel.onmessage = null;
4103
+ this.dataChannel.onclose = null;
4104
+ this.dataChannel = null;
4105
+ }
4106
+ if (!this.open) return;
4107
+ this._open = false;
4108
+ super.emit("close");
4109
+ }
4110
+ /** Allows user to send data. */ send(data, chunked = false) {
4111
+ if (!this.open) {
4112
+ this.emitError((0, $edbcf3072a01d580$export$49ae800c114df41d).NotOpenYet, "Connection is not open. You should listen for the `open` event before sending messages.");
4113
+ return;
4114
+ }
4115
+ return this._send(data, chunked);
4116
+ }
4117
+ async handleMessage(message) {
4118
+ const payload = message.payload;
4119
+ switch(message.type){
4120
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Answer:
4121
+ await this._negotiator.handleSDP(message.type, payload.sdp);
4122
+ break;
4123
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Candidate:
4124
+ await this._negotiator.handleCandidate(payload.candidate);
4125
+ break;
4126
+ default:
4127
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).warn("Unrecognized message type:", message.type, "from peer:", this.peer);
4128
+ break;
4129
+ }
4130
+ }
4131
+ constructor(peerId, provider, options){
4132
+ super(peerId, provider, options);
4133
+ this.connectionId = this.options.connectionId || $392ccce28b647101$export$d365f7ad9d7df9c9.ID_PREFIX + (0, $008766fe99f03c2f$export$4e61f672936bec77)();
4134
+ this.label = this.options.label || this.connectionId;
4135
+ this.reliable = !!this.options.reliable;
4136
+ this._negotiator = new (0, $3cabb799c2437cbe$export$89e6bb5ad64bf4a)(this);
4137
+ this._negotiator.startConnection(this.options._payload || {
4138
+ originator: true,
4139
+ reliable: this.reliable
4140
+ });
4141
+ }
4142
+ }
4143
+ $392ccce28b647101$export$d365f7ad9d7df9c9.ID_PREFIX = "dc_";
4144
+ $392ccce28b647101$export$d365f7ad9d7df9c9.MAX_BUFFERED_AMOUNT = 8388608;
4145
+
4146
+
4147
+ class $8d1d5e45d8d6520c$export$ff7c9d4c11d94e8b extends (0, $392ccce28b647101$export$d365f7ad9d7df9c9) {
4148
+ get bufferSize() {
4149
+ return this._bufferSize;
4150
+ }
4151
+ _initializeDataChannel(dc) {
4152
+ super._initializeDataChannel(dc);
4153
+ this.dataChannel.binaryType = "arraybuffer";
4154
+ this.dataChannel.addEventListener("message", (e)=>this._handleDataMessage(e));
4155
+ }
4156
+ _bufferedSend(msg) {
4157
+ if (this._buffering || !this._trySend(msg)) {
4158
+ this._buffer.push(msg);
4159
+ this._bufferSize = this._buffer.length;
4160
+ }
4161
+ }
4162
+ // Returns true if the send succeeds.
4163
+ _trySend(msg) {
4164
+ if (!this.open) return false;
4165
+ if (this.dataChannel.bufferedAmount > (0, $392ccce28b647101$export$d365f7ad9d7df9c9).MAX_BUFFERED_AMOUNT) {
4166
+ this._buffering = true;
4167
+ setTimeout(()=>{
4168
+ this._buffering = false;
4169
+ this._tryBuffer();
4170
+ }, 50);
4171
+ return false;
4172
+ }
4173
+ try {
4174
+ this.dataChannel.send(msg);
4175
+ } catch (e) {
4176
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).error(`DC#:${this.connectionId} Error when sending:`, e);
4177
+ this._buffering = true;
4178
+ this.close();
4179
+ return false;
4180
+ }
4181
+ return true;
4182
+ }
4183
+ // Try to send the first message in the buffer.
4184
+ _tryBuffer() {
4185
+ if (!this.open) return;
4186
+ if (this._buffer.length === 0) return;
4187
+ const msg = this._buffer[0];
4188
+ if (this._trySend(msg)) {
4189
+ this._buffer.shift();
4190
+ this._bufferSize = this._buffer.length;
4191
+ this._tryBuffer();
4192
+ }
4193
+ }
4194
+ close(options) {
4195
+ if (options?.flush) {
4196
+ this.send({
4197
+ __peerData: {
4198
+ type: "close"
4199
+ }
4200
+ });
4201
+ return;
4202
+ }
4203
+ this._buffer = [];
4204
+ this._bufferSize = 0;
4205
+ super.close();
4206
+ }
4207
+ constructor(...args){
4208
+ super(...args), this._buffer = [], this._bufferSize = 0, this._buffering = false;
4209
+ }
4210
+ }
4211
+
4212
+
4213
+
4214
+
4215
+ class $6b2c8b37149b9a13$export$f0a5a64d5bb37108 extends (0, $8d1d5e45d8d6520c$export$ff7c9d4c11d94e8b) {
4216
+ close(options) {
4217
+ super.close(options);
4218
+ this._chunkedData = {};
4219
+ }
4220
+ // Handles a DataChannel message.
4221
+ _handleDataMessage({ data: data }) {
4222
+ const deserializedData = (0, $6018e3630d94a7b2$export$417857010dc9287f)(data);
4223
+ // PeerJS specific message
4224
+ const peerData = deserializedData["__peerData"];
4225
+ if (peerData) {
4226
+ if (peerData.type === "close") {
4227
+ this.close();
4228
+ return;
4229
+ }
4230
+ // Chunked data -- piece things back together.
4231
+ // @ts-ignore
4232
+ this._handleChunk(deserializedData);
4233
+ return;
4234
+ }
4235
+ this.emit("data", deserializedData);
4236
+ }
4237
+ _handleChunk(data) {
4238
+ const id = data.__peerData;
4239
+ const chunkInfo = this._chunkedData[id] || {
4240
+ data: [],
4241
+ count: 0,
4242
+ total: data.total
4243
+ };
4244
+ chunkInfo.data[data.n] = new Uint8Array(data.data);
4245
+ chunkInfo.count++;
4246
+ this._chunkedData[id] = chunkInfo;
4247
+ if (chunkInfo.total === chunkInfo.count) {
4248
+ // Clean up before making the recursive call to `_handleDataMessage`.
4249
+ delete this._chunkedData[id];
4250
+ // We've received all the chunks--time to construct the complete data.
4251
+ // const data = new Blob(chunkInfo.data);
4252
+ const data = (0, $616ebdf1c4998439$export$52c89ebcdc4f53f2)(chunkInfo.data);
4253
+ this._handleDataMessage({
4254
+ data: data
4255
+ });
4256
+ }
4257
+ }
4258
+ _send(data, chunked) {
4259
+ const blob = (0, $6018e3630d94a7b2$export$2a703dbb0cb35339)(data);
4260
+ if (blob instanceof Promise) return this._send_blob(blob);
4261
+ if (!chunked && blob.byteLength > this.chunker.chunkedMTU) {
4262
+ this._sendChunks(blob);
4263
+ return;
4264
+ }
4265
+ this._bufferedSend(blob);
4266
+ }
4267
+ async _send_blob(blobPromise) {
4268
+ const blob = await blobPromise;
4269
+ if (blob.byteLength > this.chunker.chunkedMTU) {
4270
+ this._sendChunks(blob);
4271
+ return;
4272
+ }
4273
+ this._bufferedSend(blob);
4274
+ }
4275
+ _sendChunks(blob) {
4276
+ const blobs = this.chunker.chunk(blob);
4277
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`DC#${this.connectionId} Try to send ${blobs.length} chunks...`);
4278
+ for (const blob of blobs)this.send(blob, true);
4279
+ }
4280
+ constructor(peerId, provider, options){
4281
+ super(peerId, provider, options), this.chunker = new (0, $616ebdf1c4998439$export$f1c5f4c9cb95390b)(), this.serialization = (0, $edbcf3072a01d580$export$89f507cf986a947).Binary, this._chunkedData = {};
4282
+ }
4283
+ }
4284
+
4285
+
4286
+
4287
+
4288
+ class $6faa8477ae391a66$export$6f88fe47d32c9c94 extends (0, $8d1d5e45d8d6520c$export$ff7c9d4c11d94e8b) {
4289
+ _handleDataMessage({ data: data }) {
4290
+ super.emit("data", data);
4291
+ }
4292
+ _send(data, _chunked) {
4293
+ this._bufferedSend(data);
4294
+ }
4295
+ constructor(...args){
4296
+ super(...args), this.serialization = (0, $edbcf3072a01d580$export$89f507cf986a947).None;
4297
+ }
4298
+ }
4299
+
4300
+
4301
+
4302
+
4303
+
4304
+ class $b524315f5ff1ee78$export$48880ac635f47186 extends (0, $8d1d5e45d8d6520c$export$ff7c9d4c11d94e8b) {
4305
+ // Handles a DataChannel message.
4306
+ _handleDataMessage({ data: data }) {
4307
+ const deserializedData = this.parse(this.decoder.decode(data));
4308
+ // PeerJS specific message
4309
+ const peerData = deserializedData["__peerData"];
4310
+ if (peerData && peerData.type === "close") {
4311
+ this.close();
4312
+ return;
4313
+ }
4314
+ this.emit("data", deserializedData);
4315
+ }
4316
+ _send(data, _chunked) {
4317
+ const encodedData = this.encoder.encode(this.stringify(data));
4318
+ if (encodedData.byteLength >= (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).chunkedMTU) {
4319
+ this.emitError((0, $edbcf3072a01d580$export$49ae800c114df41d).MessageToBig, "Message too big for JSON channel");
4320
+ return;
4321
+ }
4322
+ this._bufferedSend(encodedData);
4323
+ }
4324
+ constructor(...args){
4325
+ super(...args), this.serialization = (0, $edbcf3072a01d580$export$89f507cf986a947).JSON, this.encoder = new TextEncoder(), this.decoder = new TextDecoder(), this.stringify = JSON.stringify, this.parse = JSON.parse;
4326
+ }
4327
+ }
4328
+
4329
+
4330
+
4331
+ class $11967427976ce06d$var$PeerOptions {
4332
+ }
4333
+ class $11967427976ce06d$export$ecd1fc136c422448 extends (0, $41eb28b5735ed6cf$export$6a678e589c8a4542) {
4334
+ /**
4335
+ * The brokering ID of this peer
4336
+ *
4337
+ * If no ID was specified in {@apilink Peer | the constructor},
4338
+ * this will be `undefined` until the {@apilink PeerEvents | `open`} event is emitted.
4339
+ */ get id() {
4340
+ return this._id;
4341
+ }
4342
+ get options() {
4343
+ return this._options;
4344
+ }
4345
+ get open() {
4346
+ return this._open;
4347
+ }
4348
+ /**
4349
+ * @internal
4350
+ */ get socket() {
4351
+ return this._socket;
4352
+ }
4353
+ /**
4354
+ * A hash of all connections associated with this peer, keyed by the remote peer's ID.
4355
+ * @deprecated
4356
+ * Return type will change from Object to Map<string,[]>
4357
+ */ get connections() {
4358
+ const plainConnections = Object.create(null);
4359
+ for (const [k, v] of this._connections)plainConnections[k] = v;
4360
+ return plainConnections;
4361
+ }
4362
+ /**
4363
+ * true if this peer and all of its connections can no longer be used.
4364
+ */ get destroyed() {
4365
+ return this._destroyed;
4366
+ }
4367
+ /**
4368
+ * false if there is an active connection to the PeerServer.
4369
+ */ get disconnected() {
4370
+ return this._disconnected;
4371
+ }
4372
+ _createServerConnection() {
4373
+ const socket = new (0, $5dd3b97502a89fbb$export$4798917dbf149b79)(this._options.secure, this._options.host, this._options.port, this._options.path, this._options.key, this._options.pingInterval);
4374
+ socket.on((0, $edbcf3072a01d580$export$3b5c4a4b6354f023).Message, (data)=>{
4375
+ this._handleMessage(data);
4376
+ });
4377
+ socket.on((0, $edbcf3072a01d580$export$3b5c4a4b6354f023).Error, (error)=>{
4378
+ this._abort((0, $edbcf3072a01d580$export$9547aaa2e39030ff).SocketError, error);
4379
+ });
4380
+ socket.on((0, $edbcf3072a01d580$export$3b5c4a4b6354f023).Disconnected, ()=>{
4381
+ if (this.disconnected) return;
4382
+ this.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).Network, "Lost connection to server.");
4383
+ this.disconnect();
4384
+ });
4385
+ socket.on((0, $edbcf3072a01d580$export$3b5c4a4b6354f023).Close, ()=>{
4386
+ if (this.disconnected) return;
4387
+ this._abort((0, $edbcf3072a01d580$export$9547aaa2e39030ff).SocketClosed, "Underlying socket is already closed.");
4388
+ });
4389
+ return socket;
4390
+ }
4391
+ /** Initialize a connection with the server. */ _initialize(id) {
4392
+ this._id = id;
4393
+ this.socket.start(id, this._options.token);
4394
+ }
4395
+ /** Handles messages from the server. */ _handleMessage(message) {
4396
+ const type = message.type;
4397
+ const payload = message.payload;
4398
+ const peerId = message.src;
4399
+ switch(type){
4400
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Open:
4401
+ this._lastServerId = this.id;
4402
+ this._open = true;
4403
+ this.emit("open", this.id);
4404
+ break;
4405
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Error:
4406
+ this._abort((0, $edbcf3072a01d580$export$9547aaa2e39030ff).ServerError, payload.msg);
4407
+ break;
4408
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).IdTaken:
4409
+ this._abort((0, $edbcf3072a01d580$export$9547aaa2e39030ff).UnavailableID, `ID "${this.id}" is taken`);
4410
+ break;
4411
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).InvalidKey:
4412
+ this._abort((0, $edbcf3072a01d580$export$9547aaa2e39030ff).InvalidKey, `API KEY "${this._options.key}" is invalid`);
4413
+ break;
4414
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Leave:
4415
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`Received leave message from ${peerId}`);
4416
+ this._cleanupPeer(peerId);
4417
+ this._connections.delete(peerId);
4418
+ break;
4419
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Expire:
4420
+ this.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).PeerUnavailable, `Could not connect to peer ${peerId}`);
4421
+ break;
4422
+ case (0, $edbcf3072a01d580$export$adb4a1754da6f10d).Offer:
4423
+ {
4424
+ // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
4425
+ const connectionId = payload.connectionId;
4426
+ let connection = this.getConnection(peerId, connectionId);
4427
+ if (connection) {
4428
+ connection.close();
4429
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).warn(`Offer received for existing Connection ID:${connectionId}`);
4430
+ }
4431
+ // Create a new connection.
4432
+ if (payload.type === (0, $edbcf3072a01d580$export$3157d57b4135e3bc).Media) {
4433
+ const mediaConnection = new (0, $0bc12d7ac26e1491$export$4a84e95a2324ac29)(peerId, this, {
4434
+ connectionId: connectionId,
4435
+ _payload: payload,
4436
+ metadata: payload.metadata
4437
+ });
4438
+ connection = mediaConnection;
4439
+ this._addConnection(peerId, connection);
4440
+ this.emit("call", mediaConnection);
4441
+ } else if (payload.type === (0, $edbcf3072a01d580$export$3157d57b4135e3bc).Data) {
4442
+ const dataConnection = new this._serializers[payload.serialization](peerId, this, {
4443
+ connectionId: connectionId,
4444
+ _payload: payload,
4445
+ metadata: payload.metadata,
4446
+ label: payload.label,
4447
+ serialization: payload.serialization,
4448
+ reliable: payload.reliable
4449
+ });
4450
+ connection = dataConnection;
4451
+ this._addConnection(peerId, connection);
4452
+ this.emit("connection", dataConnection);
4453
+ } else {
4454
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).warn(`Received malformed connection type:${payload.type}`);
4455
+ return;
4456
+ }
4457
+ // Find messages.
4458
+ const messages = this._getMessages(connectionId);
4459
+ for (const message of messages)connection.handleMessage(message);
4460
+ break;
4461
+ }
4462
+ default:
4463
+ {
4464
+ if (!payload) {
4465
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).warn(`You received a malformed message from ${peerId} of type ${type}`);
4466
+ return;
4467
+ }
4468
+ const connectionId = payload.connectionId;
4469
+ const connection = this.getConnection(peerId, connectionId);
4470
+ if (connection && connection.peerConnection) // Pass it on.
4471
+ connection.handleMessage(message);
4472
+ else if (connectionId) // Store for possible later use
4473
+ this._storeMessage(connectionId, message);
4474
+ else (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).warn("You received an unrecognized message:", message);
4475
+ break;
4476
+ }
4477
+ }
4478
+ }
4479
+ /** Stores messages without a set up connection, to be claimed later. */ _storeMessage(connectionId, message) {
4480
+ if (!this._lostMessages.has(connectionId)) this._lostMessages.set(connectionId, []);
4481
+ this._lostMessages.get(connectionId).push(message);
4482
+ }
4483
+ /**
4484
+ * Retrieve messages from lost message store
4485
+ * @internal
4486
+ */ //TODO Change it to private
4487
+ _getMessages(connectionId) {
4488
+ const messages = this._lostMessages.get(connectionId);
4489
+ if (messages) {
4490
+ this._lostMessages.delete(connectionId);
4491
+ return messages;
4492
+ }
4493
+ return [];
4494
+ }
4495
+ /**
4496
+ * Connects to the remote peer specified by id and returns a data connection.
4497
+ * @param peer The brokering ID of the remote peer (their {@apilink Peer.id}).
4498
+ * @param options for specifying details about Peer Connection
4499
+ */ connect(peer, options = {}) {
4500
+ options = {
4501
+ serialization: "default",
4502
+ ...options
4503
+ };
4504
+ if (this.disconnected) {
4505
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available.");
4506
+ this.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).Disconnected, "Cannot connect to new Peer after disconnecting from server.");
4507
+ return;
4508
+ }
4509
+ const dataConnection = new this._serializers[options.serialization](peer, this, options);
4510
+ this._addConnection(peer, dataConnection);
4511
+ return dataConnection;
4512
+ }
4513
+ /**
4514
+ * Calls the remote peer specified by id and returns a media connection.
4515
+ * @param peer The brokering ID of the remote peer (their peer.id).
4516
+ * @param stream The caller's media stream
4517
+ * @param options Metadata associated with the connection, passed in by whoever initiated the connection.
4518
+ */ call(peer, stream, options = {}) {
4519
+ if (this.disconnected) {
4520
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect.");
4521
+ this.emitError((0, $edbcf3072a01d580$export$9547aaa2e39030ff).Disconnected, "Cannot connect to new Peer after disconnecting from server.");
4522
+ return;
4523
+ }
4524
+ if (!stream) {
4525
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");
4526
+ return;
4527
+ }
4528
+ const mediaConnection = new (0, $0bc12d7ac26e1491$export$4a84e95a2324ac29)(peer, this, {
4529
+ ...options,
4530
+ _stream: stream
4531
+ });
4532
+ this._addConnection(peer, mediaConnection);
4533
+ return mediaConnection;
4534
+ }
4535
+ /** Add a data/media connection to this peer. */ _addConnection(peerId, connection) {
4536
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`add connection ${connection.type}:${connection.connectionId} to peerId:${peerId}`);
4537
+ if (!this._connections.has(peerId)) this._connections.set(peerId, []);
4538
+ this._connections.get(peerId).push(connection);
4539
+ }
4540
+ //TODO should be private
4541
+ _removeConnection(connection) {
4542
+ const connections = this._connections.get(connection.peer);
4543
+ if (connections) {
4544
+ const index = connections.indexOf(connection);
4545
+ if (index !== -1) connections.splice(index, 1);
4546
+ }
4547
+ //remove from lost messages
4548
+ this._lostMessages.delete(connection.connectionId);
4549
+ }
4550
+ /** Retrieve a data/media connection for this peer. */ getConnection(peerId, connectionId) {
4551
+ const connections = this._connections.get(peerId);
4552
+ if (!connections) return null;
4553
+ for (const connection of connections){
4554
+ if (connection.connectionId === connectionId) return connection;
4555
+ }
4556
+ return null;
4557
+ }
4558
+ _delayedAbort(type, message) {
4559
+ setTimeout(()=>{
4560
+ this._abort(type, message);
4561
+ }, 0);
4562
+ }
4563
+ /**
4564
+ * Emits an error message and destroys the Peer.
4565
+ * The Peer is not destroyed if it's in a disconnected state, in which case
4566
+ * it retains its disconnected state and its existing connections.
4567
+ */ _abort(type, message) {
4568
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).error("Aborting!");
4569
+ this.emitError(type, message);
4570
+ if (!this._lastServerId) this.destroy();
4571
+ else this.disconnect();
4572
+ }
4573
+ /**
4574
+ * Destroys the Peer: closes all active connections as well as the connection
4575
+ * to the server.
4576
+ *
4577
+ * :::caution
4578
+ * This cannot be undone; the respective peer object will no longer be able
4579
+ * to create or receive any connections, its ID will be forfeited on the server,
4580
+ * and all of its data and media connections will be closed.
4581
+ * :::
4582
+ */ destroy() {
4583
+ if (this.destroyed) return;
4584
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`Destroy peer with ID:${this.id}`);
4585
+ this.disconnect();
4586
+ this._cleanup();
4587
+ this._destroyed = true;
4588
+ this.emit("close");
4589
+ }
4590
+ /** Disconnects every connection on this peer. */ _cleanup() {
4591
+ for (const peerId of this._connections.keys()){
4592
+ this._cleanupPeer(peerId);
4593
+ this._connections.delete(peerId);
4594
+ }
4595
+ this.socket.removeAllListeners();
4596
+ }
4597
+ /** Closes all connections to this peer. */ _cleanupPeer(peerId) {
4598
+ const connections = this._connections.get(peerId);
4599
+ if (!connections) return;
4600
+ for (const connection of connections)connection.close();
4601
+ }
4602
+ /**
4603
+ * Disconnects the Peer's connection to the PeerServer. Does not close any
4604
+ * active connections.
4605
+ * Warning: The peer can no longer create or accept connections after being
4606
+ * disconnected. It also cannot reconnect to the server.
4607
+ */ disconnect() {
4608
+ if (this.disconnected) return;
4609
+ const currentId = this.id;
4610
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`Disconnect peer with ID:${currentId}`);
4611
+ this._disconnected = true;
4612
+ this._open = false;
4613
+ this.socket.close();
4614
+ this._lastServerId = currentId;
4615
+ this._id = null;
4616
+ this.emit("disconnected", currentId);
4617
+ }
4618
+ /** Attempts to reconnect with the same ID.
4619
+ *
4620
+ * Only {@apilink Peer.disconnect | disconnected peers} can be reconnected.
4621
+ * Destroyed peers cannot be reconnected.
4622
+ * If the connection fails (as an example, if the peer's old ID is now taken),
4623
+ * the peer's existing connections will not close, but any associated errors events will fire.
4624
+ */ reconnect() {
4625
+ if (this.disconnected && !this.destroyed) {
4626
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).log(`Attempting reconnection to server with ID ${this._lastServerId}`);
4627
+ this._disconnected = false;
4628
+ this._initialize(this._lastServerId);
4629
+ } else if (this.destroyed) throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");
4630
+ else if (!this.disconnected && !this.open) // Do nothing. We're still connecting the first time.
4631
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).error("In a hurry? We're still trying to make the initial connection!");
4632
+ else throw new Error(`Peer ${this.id} cannot reconnect because it is not disconnected from the server!`);
4633
+ }
4634
+ /**
4635
+ * Get a list of available peer IDs. If you're running your own server, you'll
4636
+ * want to set allow_discovery: true in the PeerServer options. If you're using
4637
+ * the cloud server, email team@peerjs.com to get the functionality enabled for
4638
+ * your key.
4639
+ */ listAllPeers(cb = (_)=>{}) {
4640
+ this._api.listAllPeers().then((peers)=>cb(peers)).catch((error)=>this._abort((0, $edbcf3072a01d580$export$9547aaa2e39030ff).ServerError, error));
4641
+ }
4642
+ constructor(id, options){
4643
+ super(), this._serializers = {
4644
+ raw: (0, $6faa8477ae391a66$export$6f88fe47d32c9c94),
4645
+ json: (0, $b524315f5ff1ee78$export$48880ac635f47186),
4646
+ binary: (0, $6b2c8b37149b9a13$export$f0a5a64d5bb37108),
4647
+ "binary-utf8": (0, $6b2c8b37149b9a13$export$f0a5a64d5bb37108),
4648
+ default: (0, $6b2c8b37149b9a13$export$f0a5a64d5bb37108)
4649
+ }, this._id = null, this._lastServerId = null, // States.
4650
+ this._destroyed = false // Connections have been killed
4651
+ , this._disconnected = false // Connection to PeerServer killed but P2P connections still active
4652
+ , this._open = false // Sockets and such are not yet open.
4653
+ , this._connections = new Map() // All connections for this peer.
4654
+ , this._lostMessages = new Map() // src => [list of messages]
4655
+ ;
4656
+ let userId;
4657
+ // Deal with overloading
4658
+ if (id && id.constructor == Object) options = id;
4659
+ else if (id) userId = id.toString();
4660
+ // Configurize options
4661
+ options = {
4662
+ debug: 0,
4663
+ host: (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).CLOUD_HOST,
4664
+ port: (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).CLOUD_PORT,
4665
+ path: "/",
4666
+ key: $11967427976ce06d$export$ecd1fc136c422448.DEFAULT_KEY,
4667
+ token: (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).randomToken(),
4668
+ config: (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).defaultConfig,
4669
+ referrerPolicy: "strict-origin-when-cross-origin",
4670
+ serializers: {},
4671
+ ...options
4672
+ };
4673
+ this._options = options;
4674
+ this._serializers = {
4675
+ ...this._serializers,
4676
+ ...this.options.serializers
4677
+ };
4678
+ // Detect relative URL host.
4679
+ if (this._options.host === "/") this._options.host = window.location.hostname;
4680
+ // Set path correctly.
4681
+ if (this._options.path) {
4682
+ if (this._options.path[0] !== "/") this._options.path = "/" + this._options.path;
4683
+ if (this._options.path[this._options.path.length - 1] !== "/") this._options.path += "/";
4684
+ }
4685
+ // Set whether we use SSL to same as current host
4686
+ if (this._options.secure === undefined && this._options.host !== (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).CLOUD_HOST) this._options.secure = (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).isSecure();
4687
+ else if (this._options.host == (0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).CLOUD_HOST) this._options.secure = true;
4688
+ // Set a custom log function if present
4689
+ if (this._options.logFunction) (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).setLogFunction(this._options.logFunction);
4690
+ (0, $d3fc3aacca52312c$export$2e2bcd8739ae039).logLevel = this._options.debug || 0;
4691
+ this._api = new (0, $4c932c6613316196$export$2c4e825dc9120f87)(options);
4692
+ this._socket = this._createServerConnection();
4693
+ // Sanity checks
4694
+ // Ensure WebRTC supported
4695
+ if (!(0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).supports.audioVideo && !(0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).supports.data) {
4696
+ this._delayedAbort((0, $edbcf3072a01d580$export$9547aaa2e39030ff).BrowserIncompatible, "The current browser does not support WebRTC");
4697
+ return;
4698
+ }
4699
+ // Ensure alphanumeric id
4700
+ if (!!userId && !(0, $01f0d223090cb1f8$export$7debb50ef11d5e0b).validateId(userId)) {
4701
+ this._delayedAbort((0, $edbcf3072a01d580$export$9547aaa2e39030ff).InvalidID, `ID "${userId}" is invalid`);
4702
+ return;
4703
+ }
4704
+ if (userId) this._initialize(userId);
4705
+ else this._api.retrieveId().then((id)=>this._initialize(id)).catch((error)=>this._abort((0, $edbcf3072a01d580$export$9547aaa2e39030ff).ServerError, error));
4706
+ }
4707
+ }
4708
+ $11967427976ce06d$export$ecd1fc136c422448.DEFAULT_KEY = "peerjs";
4709
+
4710
+
4711
+ window.peerjs = {
4712
+ Peer: $11967427976ce06d$export$ecd1fc136c422448,
4713
+ util: $01f0d223090cb1f8$export$7debb50ef11d5e0b
4714
+ };
4715
+ /** @deprecated Should use peerjs namespace */ window.Peer = (0, $11967427976ce06d$export$ecd1fc136c422448);
4716
+
4717
+ })();
4718
+ //# sourceMappingURL=peerjs.js.map