New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

peerjs

Package Overview
Dependencies
Maintainers
2
Versions
59
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

peerjs - npm Package Compare versions

Comparing version 2.0.0-beta.2 to 2.0.0-beta.3

2

dist/peerjs.min.js

@@ -1,2 +0,2 @@

(()=>{var de=Object.create;var F=Object.defineProperty,fe=Object.defineProperties,le=Object.getOwnPropertyDescriptor,pe=Object.getOwnPropertyDescriptors,he=Object.getOwnPropertyNames,Y=Object.getOwnPropertySymbols,ue=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty,_e=Object.prototype.propertyIsEnumerable;var q=(n,e,t)=>e in n?F(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,m=(n,e)=>{for(var t in e||(e={}))V.call(e,t)&&q(n,t,e[t]);if(Y)for(var t of Y(e))_e.call(e,t)&&q(n,t,e[t]);return n},P=(n,e)=>fe(n,pe(e)),ge=n=>F(n,"__esModule",{value:!0});var $=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ye=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of he(e))!V.call(n,r)&&(t||r!=="default")&&F(n,r,{get:()=>e[r],enumerable:!(i=le(e,r))||i.enumerable});return n},x=(n,e)=>ye(ge(F(n!=null?de(ue(n)):{},"default",!e&&n&&n.__esModule?{get:()=>n.default,enumerable:!0}:{value:n,enumerable:!0})),n);var y=(n,e,t)=>new Promise((i,r)=>{var o=c=>{try{d(t.next(c))}catch(p){r(p)}},a=c=>{try{d(t.throw(c))}catch(p){r(p)}},d=c=>c.done?i(c.value):Promise.resolve(c.value).then(o,a);d((t=t.apply(n,e)).next())});var z=$((Me,B)=>{var k={};k.useBlobBuilder=function(){try{return new Blob([]),!1}catch(n){return!0}}();k.useArrayBufferView=!k.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch(n){return!0}}();B.exports.binaryFeatures=k;var K=B.exports.BlobBuilder;typeof window!="undefined"&&(K=B.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder);function A(){this._pieces=[],this._parts=[]}A.prototype.append=function(n){typeof n=="number"?this._pieces.push(n):(this.flush(),this._parts.push(n))};A.prototype.flush=function(){if(this._pieces.length>0){var n=new Uint8Array(this._pieces);k.useArrayBufferView||(n=n.buffer),this._parts.push(n),this._pieces=[]}};A.prototype.getBuffer=function(){if(this.flush(),k.useBlobBuilder){for(var n=new K,e=0,t=this._parts.length;e<t;e++)n.append(this._parts[e]);return n.getBlob()}else return new Blob(this._parts)};B.exports.BufferBuilder=A});var Z=$((Te,G)=>{var ve=z().BufferBuilder,X=z().binaryFeatures,be={unpack:function(n){var e=new h(n);return e.unpack()},pack:function(n){var e=new u;e.pack(n);var t=e.getBuffer();return t}};G.exports=be;function h(n){this.index=0,this.dataBuffer=n,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}h.prototype.unpack=function(){var n=this.unpack_uint8();if(n<128)return n;if((n^224)<32)return(n^224)-32;var e;if((e=n^160)<=15)return this.unpack_raw(e);if((e=n^176)<=15)return this.unpack_string(e);if((e=n^144)<=15)return this.unpack_array(e);if((e=n^128)<=15)return this.unpack_map(e);switch(n){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:return;case 213:return;case 214:return;case 215:return;case 216:return e=this.unpack_uint16(),this.unpack_string(e);case 217:return e=this.unpack_uint32(),this.unpack_string(e);case 218:return e=this.unpack_uint16(),this.unpack_raw(e);case 219:return e=this.unpack_uint32(),this.unpack_raw(e);case 220:return e=this.unpack_uint16(),this.unpack_array(e);case 221:return e=this.unpack_uint32(),this.unpack_array(e);case 222:return e=this.unpack_uint16(),this.unpack_map(e);case 223:return e=this.unpack_uint32(),this.unpack_map(e)}};h.prototype.unpack_uint8=function(){var n=this.dataView[this.index]&255;return this.index++,n};h.prototype.unpack_uint16=function(){var n=this.read(2),e=(n[0]&255)*256+(n[1]&255);return this.index+=2,e};h.prototype.unpack_uint32=function(){var n=this.read(4),e=((n[0]*256+n[1])*256+n[2])*256+n[3];return this.index+=4,e};h.prototype.unpack_uint64=function(){var n=this.read(8),e=((((((n[0]*256+n[1])*256+n[2])*256+n[3])*256+n[4])*256+n[5])*256+n[6])*256+n[7];return this.index+=8,e};h.prototype.unpack_int8=function(){var n=this.unpack_uint8();return n<128?n:n-(1<<8)};h.prototype.unpack_int16=function(){var n=this.unpack_uint16();return n<32768?n:n-(1<<16)};h.prototype.unpack_int32=function(){var n=this.unpack_uint32();return n<Math.pow(2,31)?n:n-Math.pow(2,32)};h.prototype.unpack_int64=function(){var n=this.unpack_uint64();return n<Math.pow(2,63)?n:n-Math.pow(2,64)};h.prototype.unpack_raw=function(n){if(this.length<this.index+n)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+n+" "+this.length);var e=this.dataBuffer.slice(this.index,this.index+n);return this.index+=n,e};h.prototype.unpack_string=function(n){for(var e=this.read(n),t=0,i="",r,o;t<n;)r=e[t],r<128?(i+=String.fromCharCode(r),t++):(r^192)<32?(o=(r^192)<<6|e[t+1]&63,i+=String.fromCharCode(o),t+=2):(o=(r&15)<<12|(e[t+1]&63)<<6|e[t+2]&63,i+=String.fromCharCode(o),t+=3);return this.index+=n,i};h.prototype.unpack_array=function(n){for(var e=new Array(n),t=0;t<n;t++)e[t]=this.unpack();return e};h.prototype.unpack_map=function(n){for(var e={},t=0;t<n;t++){var i=this.unpack(),r=this.unpack();e[i]=r}return e};h.prototype.unpack_float=function(){var n=this.unpack_uint32(),e=n>>31,t=(n>>23&255)-127,i=n&8388607|8388608;return(e===0?1:-1)*i*Math.pow(2,t-23)};h.prototype.unpack_double=function(){var n=this.unpack_uint32(),e=this.unpack_uint32(),t=n>>31,i=(n>>20&2047)-1023,r=n&1048575|1048576,o=r*Math.pow(2,i-20)+e*Math.pow(2,i-52);return(t===0?1:-1)*o};h.prototype.read=function(n){var e=this.index;if(e+n<=this.length)return this.dataView.subarray(e,e+n);throw new Error("BinaryPackFailure: read index out of range")};function u(){this.bufferBuilder=new ve}u.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()};u.prototype.pack=function(n){var e=typeof n;if(e==="string")this.pack_string(n);else if(e==="number")Math.floor(n)===n?this.pack_integer(n):this.pack_double(n);else if(e==="boolean")n===!0?this.bufferBuilder.append(195):n===!1&&this.bufferBuilder.append(194);else if(e==="undefined")this.bufferBuilder.append(192);else if(e==="object")if(n===null)this.bufferBuilder.append(192);else{var t=n.constructor;if(t==Array)this.pack_array(n);else if(t==Blob||t==File||n instanceof Blob||n instanceof File)this.pack_bin(n);else if(t==ArrayBuffer)X.useArrayBufferView?this.pack_bin(new Uint8Array(n)):this.pack_bin(n);else if("BYTES_PER_ELEMENT"in n)X.useArrayBufferView?this.pack_bin(new Uint8Array(n.buffer)):this.pack_bin(n.buffer);else if(t==Object||t.toString().startsWith("class"))this.pack_object(n);else if(t==Date)this.pack_string(n.toString());else if(typeof n.toBinaryPack=="function")this.bufferBuilder.append(n.toBinaryPack());else throw new Error('Type "'+t.toString()+'" not yet supported')}else throw new Error('Type "'+e+'" not yet supported');this.bufferBuilder.flush()};u.prototype.pack_bin=function(n){var e=n.length||n.byteLength||n.size;if(e<=15)this.pack_uint8(160+e);else if(e<=65535)this.bufferBuilder.append(218),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(219),this.pack_uint32(e);else throw new Error("Invalid length");this.bufferBuilder.append(n)};u.prototype.pack_string=function(n){var e=ke(n);if(e<=15)this.pack_uint8(176+e);else if(e<=65535)this.bufferBuilder.append(216),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(217),this.pack_uint32(e);else throw new Error("Invalid length");this.bufferBuilder.append(n)};u.prototype.pack_array=function(n){var e=n.length;if(e<=15)this.pack_uint8(144+e);else if(e<=65535)this.bufferBuilder.append(220),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(221),this.pack_uint32(e);else throw new Error("Invalid length");for(var t=0;t<e;t++)this.pack(n[t])};u.prototype.pack_integer=function(n){if(n>=-32&&n<=127)this.bufferBuilder.append(n&255);else if(n>=0&&n<=255)this.bufferBuilder.append(204),this.pack_uint8(n);else if(n>=-128&&n<=127)this.bufferBuilder.append(208),this.pack_int8(n);else if(n>=0&&n<=65535)this.bufferBuilder.append(205),this.pack_uint16(n);else if(n>=-32768&&n<=32767)this.bufferBuilder.append(209),this.pack_int16(n);else if(n>=0&&n<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(n);else if(n>=-2147483648&&n<=2147483647)this.bufferBuilder.append(210),this.pack_int32(n);else if(n>=-9223372036854776e3&&n<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(n);else if(n>=0&&n<=18446744073709552e3)this.bufferBuilder.append(207),this.pack_uint64(n);else throw new Error("Invalid integer")};u.prototype.pack_double=function(n){var e=0;n<0&&(e=1,n=-n);var t=Math.floor(Math.log(n)/Math.LN2),i=n/Math.pow(2,t)-1,r=Math.floor(i*Math.pow(2,52)),o=Math.pow(2,32),a=e<<31|t+1023<<20|r/o&1048575,d=r%o;this.bufferBuilder.append(203),this.pack_int32(a),this.pack_int32(d)};u.prototype.pack_object=function(n){var e=Object.keys(n),t=e.length;if(t<=15)this.pack_uint8(128+t);else if(t<=65535)this.bufferBuilder.append(222),this.pack_uint16(t);else if(t<=4294967295)this.bufferBuilder.append(223),this.pack_uint32(t);else throw new Error("Invalid length");for(var i in n)n.hasOwnProperty(i)&&(this.pack(i),this.pack(n[i]))};u.prototype.pack_uint8=function(n){this.bufferBuilder.append(n)};u.prototype.pack_uint16=function(n){this.bufferBuilder.append(n>>8),this.bufferBuilder.append(n&255)};u.prototype.pack_uint32=function(n){var e=n&4294967295;this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255)};u.prototype.pack_uint64=function(n){var e=n/Math.pow(2,32),t=n%Math.pow(2,32);this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255),this.bufferBuilder.append((t&4278190080)>>>24),this.bufferBuilder.append((t&16711680)>>>16),this.bufferBuilder.append((t&65280)>>>8),this.bufferBuilder.append(t&255)};u.prototype.pack_int8=function(n){this.bufferBuilder.append(n&255)};u.prototype.pack_int16=function(n){this.bufferBuilder.append((n&65280)>>8),this.bufferBuilder.append(n&255)};u.prototype.pack_int32=function(n){this.bufferBuilder.append(n>>>24&255),this.bufferBuilder.append((n&16711680)>>>16),this.bufferBuilder.append((n&65280)>>>8),this.bufferBuilder.append(n&255)};u.prototype.pack_int64=function(n){var e=Math.floor(n/Math.pow(2,32)),t=n%Math.pow(2,32);this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255),this.bufferBuilder.append((t&4278190080)>>>24),this.bufferBuilder.append((t&16711680)>>>16),this.bufferBuilder.append((t&65280)>>>8),this.bufferBuilder.append(t&255)};function me(n){var e=n.charCodeAt(0);return e<=2047?"00":e<=65535?"000":e<=2097151?"0000":e<=67108863?"00000":"000000"}function ke(n){return n.length>600?new Blob([n]).size:n.replace(/[^\u0000-\u007F]/g,me).length}});var E=$((Pe,N)=>{"use strict";var we=Object.prototype.hasOwnProperty,g="~";function S(){}Object.create&&(S.prototype=Object.create(null),new S().__proto__||(g=!1));function xe(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function ee(n,e,t,i,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new xe(t,i||n,r),a=g?g+e:e;return n._events[a]?n._events[a].fn?n._events[a]=[n._events[a],o]:n._events[a].push(o):(n._events[a]=o,n._eventsCount++),n}function R(n,e){--n._eventsCount===0?n._events=new S:delete n._events[e]}function _(){this._events=new S,this._eventsCount=0}_.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)we.call(t,i)&&e.push(g?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};_.prototype.listeners=function(e){var t=g?g+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,a=new Array(o);r<o;r++)a[r]=i[r].fn;return a};_.prototype.listenerCount=function(e){var t=g?g+e:e,i=this._events[t];return i?i.fn?1:i.length:0};_.prototype.emit=function(e,t,i,r,o,a){var d=g?g+e:e;if(!this._events[d])return!1;var c=this._events[d],p=arguments.length,b,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),p){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,i),!0;case 4:return c.fn.call(c.context,t,i,r),!0;case 5:return c.fn.call(c.context,t,i,r,o),!0;case 6:return c.fn.call(c.context,t,i,r,o,a),!0}for(l=1,b=new Array(p-1);l<p;l++)b[l-1]=arguments[l];c.fn.apply(c.context,b)}else{var ce=c.length,w;for(l=0;l<ce;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),p){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,i);break;case 4:c[l].fn.call(c[l].context,t,i,r);break;default:if(!b)for(w=1,b=new Array(p-1);w<p;w++)b[w-1]=arguments[w];c[l].fn.apply(c[l].context,b)}}return!0};_.prototype.on=function(e,t,i){return ee(this,e,t,i,!1)};_.prototype.once=function(e,t,i){return ee(this,e,t,i,!0)};_.prototype.removeListener=function(e,t,i,r){var o=g?g+e:e;if(!this._events[o])return this;if(!t)return R(this,o),this;var a=this._events[o];if(a.fn)a.fn===t&&(!r||a.once)&&(!i||a.context===i)&&R(this,o);else{for(var d=0,c=[],p=a.length;d<p;d++)(a[d].fn!==t||r&&!a[d].once||i&&a[d].context!==i)&&c.push(a[d]);c.length?this._events[o]=c.length===1?c[0]:c:R(this,o)}return this};_.prototype.removeAllListeners=function(e){var t;return e?(t=g?g+e:e,this._events[t]&&R(this,t)):(this._events=new S,this._eventsCount=0),this};_.prototype.off=_.prototype.removeListener;_.prototype.addListener=_.prototype.on;_.prefixed=g;_.EventEmitter=_;typeof N!="undefined"&&(N.exports=_)});var O=x(Z()),Ce={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"turn:0.peerjs.com:3478",username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},f=new class{constructor(){this.CLOUD_HOST="0.peerjs.com";this.CLOUD_PORT=443;this.chunkedMTU=16300;this.defaultConfig=Ce;this.pack=O.pack;this.unpack=O.unpack;this._dataCount=1}validateId(n){return!n||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(n)}chunk(n){let e=[],t=n.size,i=Math.ceil(t/f.chunkedMTU),r=0,o=0;for(;o<t;){let a=Math.min(t,o+f.chunkedMTU),d=n.slice(o,a),c={__peerData:this._dataCount,n:r,data:d,total:i};e.push(c),o=a,r++}return this._dataCount++,e}blobToArrayBuffer(n,e,t){let i=new n;return i.onload=function(r){r.target&&t(r.target.result)},i.readAsArrayBuffer(e),i}binaryStringToArrayBuffer(n){let e=new Uint8Array(n.length);for(let t=0;t<n.length;t++)e[t]=n.charCodeAt(t)&255;return e.buffer}randomToken(){return Math.random().toString(36).substr(2)}isSecure(){return location.protocol==="https:"}};var ae=x(E());var Be="PeerJS: ";var te=class{constructor(){this._logLevel=0}get logLevel(){return this._logLevel}set logLevel(e){this._logLevel=e}log(...e){this._logLevel>=3&&this._print(3,...e)}warn(...e){this._logLevel>=2&&this._print(2,...e)}error(...e){this._logLevel>=1&&this._print(1,...e)}setLogFunction(e){this._print=e}_print(e,...t){let i=[Be,...t];for(let r in i)i[r]instanceof Error&&(i[r]="("+i[r].name+") "+i[r].message);e>=3?console.log(...i):e>=2?console.warn("WARNING",...i):e>=1&&console.error("ERROR",...i)}},s=new te;var ne=x(E());var W=class extends ne.EventEmitter{constructor({secure:e,host:t,port:i,path:r,key:o,pingInterval:a=5e3,polyfills:d}){super();this._disconnected=!0;this._id=null;this._messagesQueue=[];this.alive=!1;this._destroyed=!1;var p;this.pingInterval=a;let c=e?"wss://":"ws://";this._baseUrl=c+t+":"+i+r+"peerjs?key="+o,this.WebSocketConstructor=(p=d==null?void 0:d.WebSocket)!=null?p:window.WebSocket}get messagesQueue(){return this._messagesQueue}get destroyed(){return this._destroyed}start(e,t){if(this._destroyed)throw new Error("Socket was destroyed!");if(this._id=e,!!this._socket||!this._disconnected)return;let i=`${this._baseUrl}&id=${e}&token=${t}`;this._socket=new this.WebSocketConstructor(i),this._disconnected=!1,this._socket.onmessage=r=>{if(this._destroyed)return;let o;try{o=JSON.parse(r.data),s.log("Server message received:",o)}catch(a){s.log("Invalid server message",r.data);return}this.emit("message",o)},this._socket.onclose=r=>{this._disconnected||this._destroyed||(s.log("Socket closed.",r),this._cleanup(),this._disconnected=!0,this.emit("disconnected"))},this._socket.onopen=()=>{this._disconnected||this._destroyed||(s.log("Socket open"),this.emit("open"),this._sendQueuedMessages(),this._scheduleHeartbeat())}}_scheduleHeartbeat(){this._wsPingTimer=setTimeout(()=>{this._sendHeartbeat()},this.pingInterval)}_sendHeartbeat(){if(this._destroyed)return;if(!this._wsOpen()){s.log("Cannot send heartbeat, because socket closed");return}let e=JSON.stringify({type:"HEARTBEAT"});this._socket.send(e),this._scheduleHeartbeat()}_wsOpen(){return!!this._socket&&this._socket.readyState===1}_sendQueuedMessages(){let e=[...this._messagesQueue];this._messagesQueue=[];for(let t of e)this.send(t);e.length>0&&s.log(`${e.length} queued messages was sent`)}send(e){if(this._destroyed)throw new Error("Socket was destroyed!");if(!e.type){this.emit("error","Invalid message");return}if(!this.alive)return;if(this._id==null||!this._wsOpen()){this._messagesQueue.push(e);return}let t=JSON.stringify(e);this._socket.send(t)}close(){this._disconnected||(this._cleanup(),this._id=null,this._disconnected=!0)}_cleanup(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)}destroy(){this._destroyed||(this.close(),this._messagesQueue.length=0,this._destroyed=!0)}};function De(){}var D=class{constructor(e){this.connection=e}get webRtc(){var e,t;return(t=(e=this.connection.provider.options.polyfills)==null?void 0:e.WebRTC)!=null?t:window}startConnection(e){let t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type==="media"&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type==="data"){let i=this.connection,r={ordered:!!e.reliable},o=t.createDataChannel(i.label,r);i.initialize(o)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){s.log("Creating RTCPeerConnection.");let e=this.webRtc.RTCPeerConnection,t=new e(this.connection.provider.options.config);return this._setupListeners(t),t}_setupListeners(e){let t=this.connection.peer,i=this.connection.connectionId,r=this.connection.type,o=this.connection.provider;s.log("Listening for ICE candidates, remote streams and data channels."),e.onicecandidate=a=>{!a.candidate||!a.candidate.candidate||(s.log(`Received ICE candidates for ${t}:`,a.candidate),o.socket.send({type:"CANDIDATE",payload:{candidate:a.candidate,type:r,connectionId:i},dst:t}))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":s.log("iceConnectionState is failed, closing connections to "+t),this.connection.emit("error",new Error("Negotiation of connection to "+t+" failed.")),this.connection.close();break;case"closed":s.log("iceConnectionState is closed, closing connections to "+t),this.connection.emit("error",new Error("Connection to "+t+" closed.")),this.connection.close();break;case"connected":s.log("iceConnectionState changed to connected on the connection with "+t);break;case"disconnected":s.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":s.log("iceConnectionState changed to completed on the connection with "+t),e.onicecandidate=De;break}this.connection.emit("iceStateChanged",e.iceConnectionState)},e.ondatachannel=a=>{s.log("Received data channel");let d=a.channel;o.getConnection(t,i).initialize(d)},e.ontrack=a=>{s.log("Received remote stream");let d=a.streams[0],c=o.getConnection(t,i);if(c.type==="media"){let p=c;this._addStreamToMediaConnection(d,p)}}}cleanup(){s.log("Cleaning up PeerConnection to "+this.connection.peer);let e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=null;let t=e.signalingState!=="closed",i=!1;if(this.connection.type==="data"){let o=this.connection.dataChannel;o&&(i=!!o.readyState&&o.readyState!=="closed")}(t||i)&&e.close()}_makeOffer(){return y(this,null,function*(){let e=this.connection.peerConnection,t=this.connection.provider;try{let i=yield e.createOffer(this.connection.options.constraints);if(e.signalingState==="closed")return;s.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(i.sdp=this.connection.options.sdpTransform(i.sdp)||i.sdp);try{yield e.setLocalDescription(i),s.log("Set localDescription:",i,`for:${this.connection.peer}`);let r={sdp:i,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type==="data"){let o=this.connection;r=P(m({},r),{label:o.label,reliable:o.reliable,serialization:o.serialization})}t.socket.send({type:"OFFER",payload:r,dst:this.connection.peer})}catch(r){r!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError("webrtc",r),s.log("Failed to setLocalDescription, ",r))}}catch(i){t.emitError("webrtc",i),s.log("Failed to createOffer, ",i)}})}_makeAnswer(){return y(this,null,function*(){let e=this.connection.peerConnection,t=this.connection.provider;try{let i=yield e.createAnswer();if(e.signalingState==="closed")return;s.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(i.sdp=this.connection.options.sdpTransform(i.sdp)||i.sdp);try{yield e.setLocalDescription(i),s.log("Set localDescription:",i,`for:${this.connection.peer}`),t.socket.send({type:"ANSWER",payload:{sdp:i,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(r){t.emitError("webrtc",r),s.log("Failed to setLocalDescription, ",r)}}catch(i){t.emitError("webrtc",i),s.log("Failed to create answer, ",i)}})}handleSDP(e,t){return y(this,null,function*(){let i=this.webRtc.RTCSessionDescription;t=new i(t);let r=this.connection.peerConnection,o=this.connection.provider;s.log("Setting remote description",t);let a=this;try{yield r.setRemoteDescription(t),s.log(`Set remoteDescription:${e} for:${this.connection.peer}`),e==="OFFER"&&(yield a._makeAnswer())}catch(d){o.emitError("webrtc",d),s.log("Failed to setRemoteDescription, ",d)}})}handleCandidate(e){return y(this,null,function*(){s.log("handleCandidate:",e);let t=e.candidate,i=e.sdpMLineIndex,r=e.sdpMid,o=this.connection.peerConnection,a=this.connection.provider;try{let d=this.webRtc.RTCIceCandidate;yield o.addIceCandidate(new d({sdpMid:r,sdpMLineIndex:i,candidate:t})),s.log(`Added ICE candidate for:${this.connection.peer}`)}catch(d){a.emitError("webrtc",d),s.log("Failed to handleCandidate, ",d)}})}_addTracksToConnection(e,t){if(s.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack)return s.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(i=>{t.addTrack(i,e)})}_addStreamToMediaConnection(e,t){s.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}};var re=x(E()),I=class extends re.EventEmitter{constructor(e,t,i){super();this.peer=e;this.provider=t;this.options=i;this._open=!1;this.metadata=i.metadata}get open(){return this._open}};var j=class extends I{get type(){return"media"}get localStream(){return this._localStream}get remoteStream(){return this._remoteStream}constructor(e,t,i){super(e,t,i);this._localStream=this.options._stream,this.connectionId=this.options.connectionId||j.ID_PREFIX+f.randomToken(),this._negotiator=new D(this),this._localStream&&this._negotiator.startConnection({_stream:this._localStream,originator:!0})}addStream(e){s.log("Receiving stream",e),this._remoteStream=e,super.emit("stream",e)}handleMessage(e){let t=e.type,i=e.payload;switch(e.type){case"ANSWER":this._negotiator.handleSDP(t,i.sdp),this._open=!0;break;case"CANDIDATE":this._negotiator.handleCandidate(i.candidate);break;default:s.warn(`Unrecognized message type:${t} from peer:${this.peer}`);break}}answer(e,t={}){if(this._localStream){s.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,t&&t.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection(P(m({},this.options._payload),{_stream:e}));let i=this.provider._getMessages(this.connectionId);for(let r of i)this.handleMessage(r);this._open=!0}close(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),!!this.open&&(this._open=!1,super.emit("close"))}},M=j;M.ID_PREFIX="mc_";var oe=x(E());var J=class extends oe.EventEmitter{constructor(e){super();this.fileReader=e;this._queue=[];this._processing=!1;this.fileReader.onload=t=>{this._processing=!1,t.target&&this.emit("done",t.target.result),this.doNextTask()},this.fileReader.onerror=t=>{s.error("EncodingQueue error:",t),this._processing=!1,this.destroy(),this.emit("error",t)}}get queue(){return this._queue}get size(){return this.queue.length}get processing(){return this._processing}enque(e){this.queue.push(e),!this.processing&&this.doNextTask()}destroy(){this.fileReader.abort(),this._queue=[]}doNextTask(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))}};var U=class extends I{constructor(e,t,i){super(e,t,i);this.stringify=JSON.stringify;this.parse=JSON.parse;this._buffer=[];this._bufferSize=0;this._buffering=!1;this._chunkedData={};var r,o;this.connectionId=this.options.connectionId||U.ID_PREFIX+f.randomToken(),this.label=this.options.label||this.connectionId,this.serialization=this.options.serialization||"binary",this.reliable=!!this.options.reliable,this.FileReaderCtr=(o=(r=t.options.polyfills)==null?void 0:r.FileReader)!=null?o:window.FileReader,this._encodingQueue=new J(new this.FileReaderCtr),this._encodingQueue.on("done",a=>{this._bufferedSend(a)}),this._encodingQueue.on("error",()=>{s.error(`DC#${this.connectionId}: Error occured in encoding from blob to arraybuffer, close DC`),this.close()}),this._negotiator=new D(this),this._negotiator.startConnection(this.options._payload||{originator:!0})}get type(){return"data"}get dataChannel(){return this._dc}get bufferSize(){return this._bufferSize}initialize(e){this._dc=e,this._configureDataChannel()}_configureDataChannel(){(!this.provider.features.binaryBlob||this.provider.features.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=()=>{s.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this.emit("open")},this.dataChannel.onmessage=e=>{s.log(`DC#${this.connectionId} dc onmessage:`,e.data),this._handleDataMessage(e)},this.dataChannel.onclose=()=>{s.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}_handleDataMessage({data:e}){let t=e.constructor,i=this.serialization==="binary"||this.serialization==="binary-utf8",r=e;if(i){if(t===Blob){f.blobToArrayBuffer(this.FileReaderCtr,e,o=>{let a=f.unpack(o);this.emit("data",a)});return}else if(t===ArrayBuffer)r=f.unpack(e);else if(t===String){let o=f.binaryStringToArrayBuffer(e);r=f.unpack(o)}}else this.serialization==="json"&&(r=this.parse(e));if(r.__peerData){this._handleChunk(r);return}super.emit("data",r)}_handleChunk(e){let t=e.__peerData,i=this._chunkedData[t]||{data:[],count:0,total:e.total};if(i.data[e.n]=e.data,i.count++,this._chunkedData[t]=i,i.total===i.count){delete this._chunkedData[t];let r=new Blob(i.data);this._handleDataMessage({data:r})}}close(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),!!this.open&&(this._open=!1,super.emit("close"))}send(e,t){if(!this.open){super.emit("error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization==="json")this._bufferedSend(this.stringify(e));else if(this.serialization==="binary"||this.serialization==="binary-utf8"){let i=f.pack(e);if(!t&&i.size>f.chunkedMTU){this._sendChunks(i);return}this.provider.features.binaryBlob?this._bufferedSend(i):this._encodingQueue.enque(i)}else this._bufferedSend(e)}_bufferedSend(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)}_trySend(e){if(!this.open)return!1;if(this.dataChannel.bufferedAmount>U.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(()=>{this._buffering=!1,this._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(t){return s.error(`DC#:${this.connectionId} Error when sending:`,t),this._buffering=!0,this.close(),!1}return!0}_tryBuffer(){if(!this.open||this._buffer.length===0)return;let e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}_sendChunks(e){let t=f.chunk(e);s.log(`DC#${this.connectionId} Try to send ${t.length} chunks...`);for(let i of t)this.send(i,!0)}handleMessage(e){let t=e.payload;switch(e.type){case"ANSWER":this._negotiator.handleSDP(e.type,t.sdp);break;case"CANDIDATE":this._negotiator.handleCandidate(t.candidate);break;default:s.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}}},C=U;C.ID_PREFIX="dc_",C.MAX_BUFFERED_AMOUNT=8*1024*1024;var H=class{constructor(e){this._options=e;var t,i;this.fetch=(i=(t=e.polyfills)==null?void 0:t.fetch)!=null?i:window.fetch}_buildUrl(e){let i=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+e;return i+="?ts="+new Date().getTime()+Math.random(),i}retrieveId(){return y(this,null,function*(){let e=this._buildUrl("id");try{let t=yield this.fetch(e);if(t.status!==200)throw new Error(`Error. Status:${t.status}`);return t.text()}catch(t){s.error("Error retrieving ID",t);let i="";throw this._options.path==="/"&&this._options.host!==f.CLOUD_HOST&&(i=" 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."),new Error("Could not get an ID from the server."+i)}})}listAllPeers(){return y(this,null,function*(){let e=this._buildUrl("peers");try{let t=yield this.fetch(e);if(t.status!==200){if(t.status===401){let i="";throw this._options.host===f.CLOUD_HOST?i="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":i="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+i)}throw new Error(`Error. Status:${t.status}`)}return t.json()}catch(t){throw s.error("Error retrieving list peers",t),new Error("Could not get list peers from the server."+t)}})}};var se={isUnifiedPlanSupported(n){if(!n&&typeof window!="undefined"&&(n=window),typeof n.RTCRtpTransceiver=="undefined"||!("currentDirection"in n.RTCRtpTransceiver.prototype))return!1;let e,t=!1;try{e=new n.RTCPeerConnection,e.addTransceiver("audio"),t=!0}catch(i){}finally{e&&e.close()}return t}};var v=class extends ae.EventEmitter{constructor(e,t){super();this._id=null;this._lastServerId=null;this._destroyed=!1;this._disconnected=!1;this._open=!1;this._connections=new Map;this._lostMessages=new Map;var r;let i;if(e&&e.constructor==Object?t=e:e&&(i=e.toString()),t=m({debug:0,host:f.CLOUD_HOST,port:f.CLOUD_PORT,path:"/",key:v.DEFAULT_KEY,token:f.randomToken(),config:f.defaultConfig},t),this._options=t,typeof window!="undefined"&&this._options.host==="/"&&(this._options.host=window.location.hostname),this._options.path&&(this._options.path[0]!=="/"&&(this._options.path="/"+this._options.path),this._options.path[this._options.path.length-1]!=="/"&&(this._options.path+="/")),this._options.secure===void 0&&this._options.host!==f.CLOUD_HOST?this._options.secure=f.isSecure():this._options.host==f.CLOUD_HOST&&(this._options.secure=!0),this._options.logFunction&&s.setLogFunction(this._options.logFunction),s.logLevel=this._options.debug||0,this._api=new H(t),this._socket=this._createServerConnection(),this.features=v.getFeatures((r=this._options.polyfills)==null?void 0:r.WebRTC),!this.features.audioVideo&&!this.features.data){this._delayedAbort("browser-incompatible","The current browser does not support WebRTC");return}if(!!i&&!f.validateId(i)){this._delayedAbort("invalid-id",`ID "${i}" is invalid`);return}this.socket.alive=!0,i?this._initialize(i):this._api.retrieveId().then(o=>this._initialize(o)).catch(o=>this._abort("server-error",o))}get id(){return this._id}get options(){return this._options}get open(){return this._open}get socket(){return this._socket}get connections(){let e=Object.create(null);for(let[t,i]of this._connections)e[t]=i;return e}get destroyed(){return this._destroyed}get disconnected(){return this._disconnected}_createServerConnection(){let e=new W(this._options);return e.on("message",t=>{this._handleMessage(t)}),e.on("error",t=>{this._abort("socket-error",t)}),e.on("disconnected",()=>{this.disconnected||(this.emitError("network","Lost connection to server."),this.disconnect())}),e.on("close",()=>{this.disconnected||this._abort("socket-closed","Underlying socket is already closed.")}),e}_initialize(e){this.destroyed||(this._id=e,this.socket.start(e,this._options.token))}_handleMessage(e){let t=e.type,i=e.payload,r=e.src;switch(t){case"OPEN":this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case"ERROR":this._abort("server-error",i.msg);break;case"ID-TAKEN":this._abort("unavailable-id",`ID "${this.id}" is taken`);break;case"INVALID-KEY":this._abort("invalid-key",`API KEY "${this._options.key}" is invalid`);break;case"LEAVE":s.log(`Received leave message from ${r}`),this._cleanupPeer(r),this._connections.delete(r);break;case"EXPIRE":this.emitError("peer-unavailable",`Could not connect to peer ${r}`);break;case"OFFER":{let o=i.connectionId,a=this.getConnection(r,o);if(a&&(a.close(),s.warn(`Offer received for existing Connection ID:${o}`)),i.type==="media")a=new M(r,this,{connectionId:o,_payload:i,metadata:i.metadata}),this._addConnection(r,a),this.emit("call",a);else if(i.type==="data")a=new C(r,this,{connectionId:o,_payload:i,metadata:i.metadata,label:i.label,serialization:i.serialization,reliable:i.reliable}),this._addConnection(r,a),this.emit("connection",a);else{s.warn(`Received malformed connection type:${i.type}`);return}let d=this._getMessages(o);for(let c of d)a.handleMessage(c);break}default:{if(!i){s.warn(`You received a malformed message from ${r} of type ${t}`);return}let o=i.connectionId,a=this.getConnection(r,o);a&&a.peerConnection?a.handleMessage(e):o?this._storeMessage(o,e):s.warn("You received an unrecognized message:",e);break}}}_storeMessage(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(t)}_getMessages(e){let t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),t):[]}connect(e,t={}){if(this.disconnected){s.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."),this.emitError("disconnected","Cannot connect to new Peer after disconnecting from server.");return}let i=new C(e,this,t);return this._addConnection(e,i),i}call(e,t,i={}){if(this.disconnected){s.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."),this.emitError("disconnected","Cannot connect to new Peer after disconnecting from server.");return}if(!t){s.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}i._stream=t;let r=new M(e,this,i);return this._addConnection(e,r),r}_addConnection(e,t){s.log(`add connection ${t.type}:${t.connectionId} to peerId:${e}`),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(t)}_removeConnection(e){let t=this._connections.get(e.peer);if(t){let i=t.indexOf(e);i!==-1&&(t.splice(i,1),t.length===0&&this._connections.delete(e.peer))}this._lostMessages.delete(e.connectionId)}getConnection(e,t){let i=this._connections.get(e);if(!i)return null;for(let r of i)if(r.connectionId===t)return r;return null}_delayedAbort(e,t){setTimeout(()=>{this._abort(e,t)},0)}_abort(e,t){s.error("Aborting!"),this.emitError(e,t),this._lastServerId?this.disconnect():this.destroy()}emitError(e,t){s.error("Error:",t);let i;typeof t=="string"?i=new Error(t):i=t,i.type=e,this.emit("error",i)}destroy(){this.destroyed||(s.log(`Destroy peer with ID:${this.id}`),this.disconnect(),this._cleanup(),this.socket.destroy(),this._destroyed=!0,this.emit("close"))}_cleanup(){for(let e of this._connections.keys())this._cleanupPeer(e),this._connections.delete(e);this.socket.removeAllListeners()}_cleanupPeer(e){let t=this._connections.get(e);if(!!t)for(let i of t)i.close()}disconnect(){if(this.disconnected)return;let e=this.id;s.log(`Disconnect peer with ID:${e}`),this._disconnected=!0,this._open=!1,this.socket.alive=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}reconnect(){if(this.disconnected&&!this.destroyed)s.log(`Attempting reconnection to server with ID ${this._lastServerId}`),this._disconnected=!1,this.socket.alive=!0,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)s.error("In a hurry? We're still trying to make the initial connection!");else throw new Error(`Peer ${this.id} cannot reconnect because it is not disconnected from the server!`)}}listAllPeers(e=t=>{}){this._api.listAllPeers().then(t=>e(t)).catch(t=>this._abort("server-error",t))}static getFeatures(e){return!e&&typeof window!="undefined"&&(e=window),v._features||(v._features=v.checkFeatures(e)),v._features}static checkFeatures(e){!e&&typeof window!="undefined"&&(e=window);let t={webRTC:typeof e.RTCPeerConnection!="undefined",audioVideo:!0,data:!1,binaryBlob:!1,reliable:!1,unifiedPlan:!1};if(!t.webRTC)return t;let i;try{i=new e.RTCPeerConnection(f.defaultConfig);let r;try{r=i.createDataChannel("_PEERJSTEST",{ordered:!0}),t.data=!0,t.reliable=!!r.ordered;try{r.binaryType="blob",t.binaryBlob=!0}catch(o){}}catch(o){}finally{r&&r.close()}}catch(r){}finally{i&&i.close()}return t.unifiedPlan=se.isUnifiedPlanSupported(e),t}},T=v;T.DEFAULT_KEY="peerjs";var Ct=T;typeof window!="undefined"&&(window.Peer=T);})();
(()=>{var de=Object.create;var F=Object.defineProperty,fe=Object.defineProperties,le=Object.getOwnPropertyDescriptor,pe=Object.getOwnPropertyDescriptors,he=Object.getOwnPropertyNames,H=Object.getOwnPropertySymbols,ue=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty,_e=Object.prototype.propertyIsEnumerable;var Y=(n,e,t)=>e in n?F(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,m=(n,e)=>{for(var t in e||(e={}))V.call(e,t)&&Y(n,t,e[t]);if(H)for(var t of H(e))_e.call(e,t)&&Y(n,t,e[t]);return n},P=(n,e)=>fe(n,pe(e)),ge=n=>F(n,"__esModule",{value:!0});var $=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ye=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of he(e))!V.call(n,r)&&(t||r!=="default")&&F(n,r,{get:()=>e[r],enumerable:!(i=le(e,r))||i.enumerable});return n},x=(n,e)=>ye(ge(F(n!=null?de(ue(n)):{},"default",!e&&n&&n.__esModule?{get:()=>n.default,enumerable:!0}:{value:n,enumerable:!0})),n);var y=(n,e,t)=>new Promise((i,r)=>{var o=c=>{try{d(t.next(c))}catch(p){r(p)}},a=c=>{try{d(t.throw(c))}catch(p){r(p)}},d=c=>c.done?i(c.value):Promise.resolve(c.value).then(o,a);d((t=t.apply(n,e)).next())});var z=$((Me,B)=>{var k={};k.useBlobBuilder=function(){try{return new Blob([]),!1}catch(n){return!0}}();k.useArrayBufferView=!k.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch(n){return!0}}();B.exports.binaryFeatures=k;var K=B.exports.BlobBuilder;typeof window!="undefined"&&(K=B.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder);function A(){this._pieces=[],this._parts=[]}A.prototype.append=function(n){typeof n=="number"?this._pieces.push(n):(this.flush(),this._parts.push(n))};A.prototype.flush=function(){if(this._pieces.length>0){var n=new Uint8Array(this._pieces);k.useArrayBufferView||(n=n.buffer),this._parts.push(n),this._pieces=[]}};A.prototype.getBuffer=function(){if(this.flush(),k.useBlobBuilder){for(var n=new K,e=0,t=this._parts.length;e<t;e++)n.append(this._parts[e]);return n.getBlob()}else return new Blob(this._parts)};B.exports.BufferBuilder=A});var Z=$((Te,G)=>{var ve=z().BufferBuilder,X=z().binaryFeatures,be={unpack:function(n){var e=new h(n);return e.unpack()},pack:function(n){var e=new u;e.pack(n);var t=e.getBuffer();return t}};G.exports=be;function h(n){this.index=0,this.dataBuffer=n,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}h.prototype.unpack=function(){var n=this.unpack_uint8();if(n<128)return n;if((n^224)<32)return(n^224)-32;var e;if((e=n^160)<=15)return this.unpack_raw(e);if((e=n^176)<=15)return this.unpack_string(e);if((e=n^144)<=15)return this.unpack_array(e);if((e=n^128)<=15)return this.unpack_map(e);switch(n){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:return;case 213:return;case 214:return;case 215:return;case 216:return e=this.unpack_uint16(),this.unpack_string(e);case 217:return e=this.unpack_uint32(),this.unpack_string(e);case 218:return e=this.unpack_uint16(),this.unpack_raw(e);case 219:return e=this.unpack_uint32(),this.unpack_raw(e);case 220:return e=this.unpack_uint16(),this.unpack_array(e);case 221:return e=this.unpack_uint32(),this.unpack_array(e);case 222:return e=this.unpack_uint16(),this.unpack_map(e);case 223:return e=this.unpack_uint32(),this.unpack_map(e)}};h.prototype.unpack_uint8=function(){var n=this.dataView[this.index]&255;return this.index++,n};h.prototype.unpack_uint16=function(){var n=this.read(2),e=(n[0]&255)*256+(n[1]&255);return this.index+=2,e};h.prototype.unpack_uint32=function(){var n=this.read(4),e=((n[0]*256+n[1])*256+n[2])*256+n[3];return this.index+=4,e};h.prototype.unpack_uint64=function(){var n=this.read(8),e=((((((n[0]*256+n[1])*256+n[2])*256+n[3])*256+n[4])*256+n[5])*256+n[6])*256+n[7];return this.index+=8,e};h.prototype.unpack_int8=function(){var n=this.unpack_uint8();return n<128?n:n-(1<<8)};h.prototype.unpack_int16=function(){var n=this.unpack_uint16();return n<32768?n:n-(1<<16)};h.prototype.unpack_int32=function(){var n=this.unpack_uint32();return n<Math.pow(2,31)?n:n-Math.pow(2,32)};h.prototype.unpack_int64=function(){var n=this.unpack_uint64();return n<Math.pow(2,63)?n:n-Math.pow(2,64)};h.prototype.unpack_raw=function(n){if(this.length<this.index+n)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+n+" "+this.length);var e=this.dataBuffer.slice(this.index,this.index+n);return this.index+=n,e};h.prototype.unpack_string=function(n){for(var e=this.read(n),t=0,i="",r,o;t<n;)r=e[t],r<128?(i+=String.fromCharCode(r),t++):(r^192)<32?(o=(r^192)<<6|e[t+1]&63,i+=String.fromCharCode(o),t+=2):(o=(r&15)<<12|(e[t+1]&63)<<6|e[t+2]&63,i+=String.fromCharCode(o),t+=3);return this.index+=n,i};h.prototype.unpack_array=function(n){for(var e=new Array(n),t=0;t<n;t++)e[t]=this.unpack();return e};h.prototype.unpack_map=function(n){for(var e={},t=0;t<n;t++){var i=this.unpack(),r=this.unpack();e[i]=r}return e};h.prototype.unpack_float=function(){var n=this.unpack_uint32(),e=n>>31,t=(n>>23&255)-127,i=n&8388607|8388608;return(e===0?1:-1)*i*Math.pow(2,t-23)};h.prototype.unpack_double=function(){var n=this.unpack_uint32(),e=this.unpack_uint32(),t=n>>31,i=(n>>20&2047)-1023,r=n&1048575|1048576,o=r*Math.pow(2,i-20)+e*Math.pow(2,i-52);return(t===0?1:-1)*o};h.prototype.read=function(n){var e=this.index;if(e+n<=this.length)return this.dataView.subarray(e,e+n);throw new Error("BinaryPackFailure: read index out of range")};function u(){this.bufferBuilder=new ve}u.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()};u.prototype.pack=function(n){var e=typeof n;if(e==="string")this.pack_string(n);else if(e==="number")Math.floor(n)===n?this.pack_integer(n):this.pack_double(n);else if(e==="boolean")n===!0?this.bufferBuilder.append(195):n===!1&&this.bufferBuilder.append(194);else if(e==="undefined")this.bufferBuilder.append(192);else if(e==="object")if(n===null)this.bufferBuilder.append(192);else{var t=n.constructor;if(t==Array)this.pack_array(n);else if(t==Blob||t==File||n instanceof Blob||n instanceof File)this.pack_bin(n);else if(t==ArrayBuffer)X.useArrayBufferView?this.pack_bin(new Uint8Array(n)):this.pack_bin(n);else if("BYTES_PER_ELEMENT"in n)X.useArrayBufferView?this.pack_bin(new Uint8Array(n.buffer)):this.pack_bin(n.buffer);else if(t==Object||t.toString().startsWith("class"))this.pack_object(n);else if(t==Date)this.pack_string(n.toString());else if(typeof n.toBinaryPack=="function")this.bufferBuilder.append(n.toBinaryPack());else throw new Error('Type "'+t.toString()+'" not yet supported')}else throw new Error('Type "'+e+'" not yet supported');this.bufferBuilder.flush()};u.prototype.pack_bin=function(n){var e=n.length||n.byteLength||n.size;if(e<=15)this.pack_uint8(160+e);else if(e<=65535)this.bufferBuilder.append(218),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(219),this.pack_uint32(e);else throw new Error("Invalid length");this.bufferBuilder.append(n)};u.prototype.pack_string=function(n){var e=ke(n);if(e<=15)this.pack_uint8(176+e);else if(e<=65535)this.bufferBuilder.append(216),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(217),this.pack_uint32(e);else throw new Error("Invalid length");this.bufferBuilder.append(n)};u.prototype.pack_array=function(n){var e=n.length;if(e<=15)this.pack_uint8(144+e);else if(e<=65535)this.bufferBuilder.append(220),this.pack_uint16(e);else if(e<=4294967295)this.bufferBuilder.append(221),this.pack_uint32(e);else throw new Error("Invalid length");for(var t=0;t<e;t++)this.pack(n[t])};u.prototype.pack_integer=function(n){if(n>=-32&&n<=127)this.bufferBuilder.append(n&255);else if(n>=0&&n<=255)this.bufferBuilder.append(204),this.pack_uint8(n);else if(n>=-128&&n<=127)this.bufferBuilder.append(208),this.pack_int8(n);else if(n>=0&&n<=65535)this.bufferBuilder.append(205),this.pack_uint16(n);else if(n>=-32768&&n<=32767)this.bufferBuilder.append(209),this.pack_int16(n);else if(n>=0&&n<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(n);else if(n>=-2147483648&&n<=2147483647)this.bufferBuilder.append(210),this.pack_int32(n);else if(n>=-9223372036854776e3&&n<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(n);else if(n>=0&&n<=18446744073709552e3)this.bufferBuilder.append(207),this.pack_uint64(n);else throw new Error("Invalid integer")};u.prototype.pack_double=function(n){var e=0;n<0&&(e=1,n=-n);var t=Math.floor(Math.log(n)/Math.LN2),i=n/Math.pow(2,t)-1,r=Math.floor(i*Math.pow(2,52)),o=Math.pow(2,32),a=e<<31|t+1023<<20|r/o&1048575,d=r%o;this.bufferBuilder.append(203),this.pack_int32(a),this.pack_int32(d)};u.prototype.pack_object=function(n){var e=Object.keys(n),t=e.length;if(t<=15)this.pack_uint8(128+t);else if(t<=65535)this.bufferBuilder.append(222),this.pack_uint16(t);else if(t<=4294967295)this.bufferBuilder.append(223),this.pack_uint32(t);else throw new Error("Invalid length");for(var i in n)n.hasOwnProperty(i)&&(this.pack(i),this.pack(n[i]))};u.prototype.pack_uint8=function(n){this.bufferBuilder.append(n)};u.prototype.pack_uint16=function(n){this.bufferBuilder.append(n>>8),this.bufferBuilder.append(n&255)};u.prototype.pack_uint32=function(n){var e=n&4294967295;this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255)};u.prototype.pack_uint64=function(n){var e=n/Math.pow(2,32),t=n%Math.pow(2,32);this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255),this.bufferBuilder.append((t&4278190080)>>>24),this.bufferBuilder.append((t&16711680)>>>16),this.bufferBuilder.append((t&65280)>>>8),this.bufferBuilder.append(t&255)};u.prototype.pack_int8=function(n){this.bufferBuilder.append(n&255)};u.prototype.pack_int16=function(n){this.bufferBuilder.append((n&65280)>>8),this.bufferBuilder.append(n&255)};u.prototype.pack_int32=function(n){this.bufferBuilder.append(n>>>24&255),this.bufferBuilder.append((n&16711680)>>>16),this.bufferBuilder.append((n&65280)>>>8),this.bufferBuilder.append(n&255)};u.prototype.pack_int64=function(n){var e=Math.floor(n/Math.pow(2,32)),t=n%Math.pow(2,32);this.bufferBuilder.append((e&4278190080)>>>24),this.bufferBuilder.append((e&16711680)>>>16),this.bufferBuilder.append((e&65280)>>>8),this.bufferBuilder.append(e&255),this.bufferBuilder.append((t&4278190080)>>>24),this.bufferBuilder.append((t&16711680)>>>16),this.bufferBuilder.append((t&65280)>>>8),this.bufferBuilder.append(t&255)};function me(n){var e=n.charCodeAt(0);return e<=2047?"00":e<=65535?"000":e<=2097151?"0000":e<=67108863?"00000":"000000"}function ke(n){return n.length>600?new Blob([n]).size:n.replace(/[^\u0000-\u007F]/g,me).length}});var E=$((Pe,N)=>{"use strict";var we=Object.prototype.hasOwnProperty,g="~";function S(){}Object.create&&(S.prototype=Object.create(null),new S().__proto__||(g=!1));function xe(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function ee(n,e,t,i,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new xe(t,i||n,r),a=g?g+e:e;return n._events[a]?n._events[a].fn?n._events[a]=[n._events[a],o]:n._events[a].push(o):(n._events[a]=o,n._eventsCount++),n}function R(n,e){--n._eventsCount===0?n._events=new S:delete n._events[e]}function _(){this._events=new S,this._eventsCount=0}_.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)we.call(t,i)&&e.push(g?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};_.prototype.listeners=function(e){var t=g?g+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,a=new Array(o);r<o;r++)a[r]=i[r].fn;return a};_.prototype.listenerCount=function(e){var t=g?g+e:e,i=this._events[t];return i?i.fn?1:i.length:0};_.prototype.emit=function(e,t,i,r,o,a){var d=g?g+e:e;if(!this._events[d])return!1;var c=this._events[d],p=arguments.length,b,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),p){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,i),!0;case 4:return c.fn.call(c.context,t,i,r),!0;case 5:return c.fn.call(c.context,t,i,r,o),!0;case 6:return c.fn.call(c.context,t,i,r,o,a),!0}for(l=1,b=new Array(p-1);l<p;l++)b[l-1]=arguments[l];c.fn.apply(c.context,b)}else{var ce=c.length,w;for(l=0;l<ce;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),p){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,i);break;case 4:c[l].fn.call(c[l].context,t,i,r);break;default:if(!b)for(w=1,b=new Array(p-1);w<p;w++)b[w-1]=arguments[w];c[l].fn.apply(c[l].context,b)}}return!0};_.prototype.on=function(e,t,i){return ee(this,e,t,i,!1)};_.prototype.once=function(e,t,i){return ee(this,e,t,i,!0)};_.prototype.removeListener=function(e,t,i,r){var o=g?g+e:e;if(!this._events[o])return this;if(!t)return R(this,o),this;var a=this._events[o];if(a.fn)a.fn===t&&(!r||a.once)&&(!i||a.context===i)&&R(this,o);else{for(var d=0,c=[],p=a.length;d<p;d++)(a[d].fn!==t||r&&!a[d].once||i&&a[d].context!==i)&&c.push(a[d]);c.length?this._events[o]=c.length===1?c[0]:c:R(this,o)}return this};_.prototype.removeAllListeners=function(e){var t;return e?(t=g?g+e:e,this._events[t]&&R(this,t)):(this._events=new S,this._eventsCount=0),this};_.prototype.off=_.prototype.removeListener;_.prototype.addListener=_.prototype.on;_.prefixed=g;_.EventEmitter=_;typeof N!="undefined"&&(N.exports=_)});var O=x(Z()),Ce={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"turn:0.peerjs.com:3478",username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},f=new class{constructor(){this.CLOUD_HOST="0.peerjs.com";this.CLOUD_PORT=443;this.chunkedMTU=16300;this.defaultConfig=Ce;this.pack=O.pack;this.unpack=O.unpack;this._dataCount=1}validateId(n){return!n||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(n)}chunk(n){let e=[],t=n.size,i=Math.ceil(t/f.chunkedMTU),r=0,o=0;for(;o<t;){let a=Math.min(t,o+f.chunkedMTU),d=n.slice(o,a),c={__peerData:this._dataCount,n:r,data:d,total:i};e.push(c),o=a,r++}return this._dataCount++,e}blobToArrayBuffer(n,e,t){let i=new n;return i.onload=function(r){r.target&&t(r.target.result)},i.readAsArrayBuffer(e),i}binaryStringToArrayBuffer(n){let e=new Uint8Array(n.length);for(let t=0;t<n.length;t++)e[t]=n.charCodeAt(t)&255;return e.buffer}randomToken(){return Math.random().toString(36).substr(2)}isSecure(){return location.protocol==="https:"}};var ae=x(E());var Be="PeerJS: ";var te=class{constructor(){this._logLevel=0}get logLevel(){return this._logLevel}set logLevel(e){this._logLevel=e}log(...e){this._logLevel>=3&&this._print(3,...e)}warn(...e){this._logLevel>=2&&this._print(2,...e)}error(...e){this._logLevel>=1&&this._print(1,...e)}setLogFunction(e){this._print=e}_print(e,...t){let i=[Be,...t];for(let r in i)i[r]instanceof Error&&(i[r]="("+i[r].name+") "+i[r].message);e>=3?console.log(...i):e>=2?console.warn("WARNING",...i):e>=1&&console.error("ERROR",...i)}},s=new te;var ne=x(E());var W=class extends ne.EventEmitter{constructor({secure:e,host:t,port:i,path:r,key:o,pingInterval:a=5e3,polyfills:d}){super();this._disconnected=!0;this._id=null;this._messagesQueue=[];this.alive=!1;this._destroyed=!1;var p;this.pingInterval=a;let c=e?"wss://":"ws://";this._baseUrl=c+t+":"+i+r+"peerjs?key="+o,this.WebSocketConstructor=(p=d==null?void 0:d.WebSocket)!=null?p:window.WebSocket}get messagesQueue(){return this._messagesQueue}get destroyed(){return this._destroyed}start(e,t){if(this._destroyed)throw new Error("Socket was destroyed!");if(this._id=e,!!this._socket||!this._disconnected)return;let i=`${this._baseUrl}&id=${e}&token=${t}`;this._socket=new this.WebSocketConstructor(i),this._disconnected=!1,this._socket.onmessage=r=>{if(this._destroyed)return;let o;try{o=JSON.parse(r.data),s.log("Server message received:",o)}catch(a){s.log("Invalid server message",r.data);return}this.emit("message",o)},this._socket.onclose=r=>{this._disconnected||this._destroyed||(s.log("Socket closed.",r),this._cleanup(),this._disconnected=!0,this.emit("disconnected"))},this._socket.onopen=()=>{this._disconnected||this._destroyed||(s.log("Socket open"),this.emit("open"),this._sendQueuedMessages(),this._scheduleHeartbeat())}}_scheduleHeartbeat(){this._wsPingTimer=setTimeout(()=>{this._sendHeartbeat()},this.pingInterval)}_sendHeartbeat(){if(this._destroyed)return;if(!this._wsOpen()){s.log("Cannot send heartbeat, because socket closed");return}let e=JSON.stringify({type:"HEARTBEAT"});this._socket.send(e),this._scheduleHeartbeat()}_wsOpen(){return!!this._socket&&this._socket.readyState===1}_sendQueuedMessages(){let e=[...this._messagesQueue];this._messagesQueue=[];for(let t of e)this.send(t);e.length>0&&s.log(`${e.length} queued messages was sent`)}send(e){if(this._destroyed)throw new Error("Socket was destroyed!");if(!e.type){this.emit("error","Invalid message");return}if(!this.alive)return;if(this._id==null||!this._wsOpen()){this._messagesQueue.push(e);return}let t=JSON.stringify(e);this._socket.send(t)}close(){this._disconnected||(this._cleanup(),this._id=null,this._disconnected=!0)}_cleanup(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)}destroy(){this._destroyed||(this.close(),this._messagesQueue.length=0,this._destroyed=!0)}};function De(){}var D=class{constructor(e){this.connection=e}get webRtc(){var e,t;return(t=(e=this.connection.provider.options.polyfills)==null?void 0:e.WebRTC)!=null?t:window}startConnection(e){let t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type==="media"&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type==="data"){let i=this.connection,r={ordered:!!e.reliable},o=t.createDataChannel(i.label,r);i.initialize(o)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){s.log("Creating RTCPeerConnection.");let e=this.webRtc.RTCPeerConnection,t=new e(this.connection.provider.options.config);return this._setupListeners(t),t}_setupListeners(e){let t=this.connection.peer,i=this.connection.connectionId,r=this.connection.type,o=this.connection.provider;s.log("Listening for ICE candidates, remote streams and data channels."),e.onicecandidate=a=>{!a.candidate||!a.candidate.candidate||(s.log(`Received ICE candidates for ${t}:`,a.candidate),o.socket.send({type:"CANDIDATE",payload:{candidate:a.candidate,type:r,connectionId:i},dst:t}))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":s.log("iceConnectionState is failed, closing connections to "+t),this.connection.emit("error",new Error("Negotiation of connection to "+t+" failed.")),this.connection.close();break;case"closed":s.log("iceConnectionState is closed, closing connections to "+t),this.connection.emit("error",new Error("Connection to "+t+" closed.")),this.connection.close();break;case"connected":s.log("iceConnectionState changed to connected on the connection with "+t);break;case"disconnected":s.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":s.log("iceConnectionState changed to completed on the connection with "+t),e.onicecandidate=De;break}this.connection.emit("iceStateChanged",e.iceConnectionState)},e.ondatachannel=a=>{s.log("Received data channel");let d=a.channel;o.getConnection(t,i).initialize(d)},e.ontrack=a=>{s.log("Received remote stream");let d=a.streams[0],c=o.getConnection(t,i);if(c.type==="media"){let p=c;this._addStreamToMediaConnection(d,p)}}}cleanup(){s.log("Cleaning up PeerConnection to "+this.connection.peer);let e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=null;let t=e.signalingState!=="closed",i=!1;if(this.connection.type==="data"){let o=this.connection.dataChannel;o&&(i=!!o.readyState&&o.readyState!=="closed")}(t||i)&&e.close()}_makeOffer(){return y(this,null,function*(){let e=this.connection.peerConnection,t=this.connection.provider;try{let i=yield e.createOffer(this.connection.options.constraints);if(e.signalingState==="closed")return;s.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(i.sdp=this.connection.options.sdpTransform(i.sdp)||i.sdp);try{yield e.setLocalDescription(i),s.log("Set localDescription:",i,`for:${this.connection.peer}`);let r={sdp:i,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type==="data"){let o=this.connection;r=P(m({},r),{label:o.label,reliable:o.reliable,serialization:o.serialization})}t.socket.send({type:"OFFER",payload:r,dst:this.connection.peer})}catch(r){r!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError("webrtc",r),s.log("Failed to setLocalDescription, ",r))}}catch(i){t.emitError("webrtc",i),s.log("Failed to createOffer, ",i)}})}_makeAnswer(){return y(this,null,function*(){let e=this.connection.peerConnection,t=this.connection.provider;try{let i=yield e.createAnswer();if(e.signalingState==="closed")return;s.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(i.sdp=this.connection.options.sdpTransform(i.sdp)||i.sdp);try{yield e.setLocalDescription(i),s.log("Set localDescription:",i,`for:${this.connection.peer}`),t.socket.send({type:"ANSWER",payload:{sdp:i,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(r){t.emitError("webrtc",r),s.log("Failed to setLocalDescription, ",r)}}catch(i){t.emitError("webrtc",i),s.log("Failed to create answer, ",i)}})}handleSDP(e,t){return y(this,null,function*(){let i=this.webRtc.RTCSessionDescription;t=new i(t);let r=this.connection.peerConnection,o=this.connection.provider;s.log("Setting remote description",t);let a=this;try{yield r.setRemoteDescription(t),s.log(`Set remoteDescription:${e} for:${this.connection.peer}`),e==="OFFER"&&(yield a._makeAnswer())}catch(d){o.emitError("webrtc",d),s.log("Failed to setRemoteDescription, ",d)}})}handleCandidate(e){return y(this,null,function*(){s.log("handleCandidate:",e);let t=e.candidate,i=e.sdpMLineIndex,r=e.sdpMid,o=this.connection.peerConnection,a=this.connection.provider;try{let d=this.webRtc.RTCIceCandidate;yield o.addIceCandidate(new d({sdpMid:r,sdpMLineIndex:i,candidate:t})),s.log(`Added ICE candidate for:${this.connection.peer}`)}catch(d){a.emitError("webrtc",d),s.log("Failed to handleCandidate, ",d)}})}_addTracksToConnection(e,t){if(s.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack)return s.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(i=>{t.addTrack(i,e)})}_addStreamToMediaConnection(e,t){s.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}};var re=x(E()),I=class extends re.EventEmitter{constructor(e,t,i){super();this.peer=e;this.provider=t;this.options=i;this._open=!1;this.metadata=i.metadata}get open(){return this._open}};var j=class extends I{get type(){return"media"}get localStream(){return this._localStream}get remoteStream(){return this._remoteStream}constructor(e,t,i){super(e,t,i);this._localStream=this.options._stream,this.connectionId=this.options.connectionId||j.ID_PREFIX+f.randomToken(),this._negotiator=new D(this),this._localStream&&this._negotiator.startConnection({_stream:this._localStream,originator:!0})}addStream(e){s.log("Receiving stream",e),this._remoteStream=e,super.emit("stream",e)}handleMessage(e){let t=e.type,i=e.payload;switch(e.type){case"ANSWER":this._negotiator.handleSDP(t,i.sdp),this._open=!0;break;case"CANDIDATE":this._negotiator.handleCandidate(i.candidate);break;default:s.warn(`Unrecognized message type:${t} from peer:${this.peer}`);break}}answer(e,t={}){if(this._localStream){s.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,t&&t.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection(P(m({},this.options._payload),{_stream:e}));let i=this.provider._getMessages(this.connectionId);for(let r of i)this.handleMessage(r);this._open=!0}close(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),!!this.open&&(this._open=!1,super.emit("close"))}},M=j;M.ID_PREFIX="mc_";var oe=x(E());var q=class extends oe.EventEmitter{constructor(e){super();this.fileReader=e;this._queue=[];this._processing=!1;this.fileReader.onload=t=>{this._processing=!1,t.target&&this.emit("done",t.target.result),this.doNextTask()},this.fileReader.onerror=t=>{s.error("EncodingQueue error:",t),this._processing=!1,this.destroy(),this.emit("error",t)}}get queue(){return this._queue}get size(){return this.queue.length}get processing(){return this._processing}enque(e){this.queue.push(e),!this.processing&&this.doNextTask()}destroy(){this.fileReader.abort(),this._queue=[]}doNextTask(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))}};var U=class extends I{constructor(e,t,i){super(e,t,i);this.stringify=JSON.stringify;this.parse=JSON.parse;this._buffer=[];this._bufferSize=0;this._buffering=!1;this._chunkedData={};var r,o;this.connectionId=this.options.connectionId||U.ID_PREFIX+f.randomToken(),this.label=this.options.label||this.connectionId,this.serialization=this.options.serialization||"binary",this.reliable=!!this.options.reliable,this.FileReaderCtr=(o=(r=t.options.polyfills)==null?void 0:r.FileReader)!=null?o:window.FileReader,this._encodingQueue=new q(new this.FileReaderCtr),this._encodingQueue.on("done",a=>{this._bufferedSend(a)}),this._encodingQueue.on("error",()=>{s.error(`DC#${this.connectionId}: Error occured in encoding from blob to arraybuffer, close DC`),this.close()}),this._negotiator=new D(this),this._negotiator.startConnection(this.options._payload||{originator:!0})}get type(){return"data"}get dataChannel(){return this._dc}get bufferSize(){return this._bufferSize}initialize(e){this._dc=e,this._configureDataChannel()}_configureDataChannel(){(!this.provider.features.binaryBlob||this.provider.features.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=()=>{s.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this.emit("open")},this.dataChannel.onmessage=e=>{s.log(`DC#${this.connectionId} dc onmessage:`,e.data),this._handleDataMessage(e)},this.dataChannel.onclose=()=>{s.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}_handleDataMessage({data:e}){let t=e.constructor,i=this.serialization==="binary"||this.serialization==="binary-utf8",r=e;if(i){if(t===Blob){f.blobToArrayBuffer(this.FileReaderCtr,e,o=>{let a=f.unpack(o);this.emit("data",a)});return}else if(t===ArrayBuffer)r=f.unpack(e);else if(t===String){let o=f.binaryStringToArrayBuffer(e);r=f.unpack(o)}}else this.serialization==="json"&&(r=this.parse(e));if(r.__peerData){this._handleChunk(r);return}super.emit("data",r)}_handleChunk(e){let t=e.__peerData,i=this._chunkedData[t]||{data:[],count:0,total:e.total};if(i.data[e.n]=e.data,i.count++,this._chunkedData[t]=i,i.total===i.count){delete this._chunkedData[t];let r=new Blob(i.data);this._handleDataMessage({data:r})}}close(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),!!this.open&&(this._open=!1,super.emit("close"))}send(e,t){if(!this.open){super.emit("error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization==="json")this._bufferedSend(this.stringify(e));else if(this.serialization==="binary"||this.serialization==="binary-utf8"){let i=f.pack(e);if(!t&&i.size>f.chunkedMTU){this._sendChunks(i);return}this.provider.features.binaryBlob?this._bufferedSend(i):this._encodingQueue.enque(i)}else this._bufferedSend(e)}_bufferedSend(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)}_trySend(e){if(!this.open)return!1;if(this.dataChannel.bufferedAmount>U.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(()=>{this._buffering=!1,this._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(t){return s.error(`DC#:${this.connectionId} Error when sending:`,t),this._buffering=!0,this.close(),!1}return!0}_tryBuffer(){if(!this.open||this._buffer.length===0)return;let e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}_sendChunks(e){let t=f.chunk(e);s.log(`DC#${this.connectionId} Try to send ${t.length} chunks...`);for(let i of t)this.send(i,!0)}handleMessage(e){let t=e.payload;switch(e.type){case"ANSWER":this._negotiator.handleSDP(e.type,t.sdp);break;case"CANDIDATE":this._negotiator.handleCandidate(t.candidate);break;default:s.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}}},C=U;C.ID_PREFIX="dc_",C.MAX_BUFFERED_AMOUNT=8*1024*1024;var J=class{constructor(e){this._options=e}_request(e){var t,i;return((i=(t=this._options.polyfills)==null?void 0:t.fetch)!=null?i:window.fetch)(e)}_buildUrl(e){let i=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+e;return i+="?ts="+new Date().getTime()+Math.random(),i}retrieveId(){return y(this,null,function*(){let e=this._buildUrl("id");try{let t=yield this._request(e);if(t.status!==200)throw new Error(`Error. Status:${t.status}`);return t.text()}catch(t){s.error("Error retrieving ID",t);let i="";throw this._options.path==="/"&&this._options.host!==f.CLOUD_HOST&&(i=" 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."),new Error("Could not get an ID from the server."+i)}})}listAllPeers(){return y(this,null,function*(){let e=this._buildUrl("peers");try{let t=yield this._request(e);if(t.status!==200){if(t.status===401){let i="";throw this._options.host===f.CLOUD_HOST?i="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":i="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+i)}throw new Error(`Error. Status:${t.status}`)}return t.json()}catch(t){throw s.error("Error retrieving list peers",t),new Error("Could not get list peers from the server."+t)}})}};var se={isUnifiedPlanSupported(n){if(!n&&typeof window!="undefined"&&(n=window),typeof n.RTCRtpTransceiver=="undefined"||!("currentDirection"in n.RTCRtpTransceiver.prototype))return!1;let e,t=!1;try{e=new n.RTCPeerConnection,e.addTransceiver("audio"),t=!0}catch(i){}finally{e&&e.close()}return t}};var v=class extends ae.EventEmitter{constructor(e,t){super();this._id=null;this._lastServerId=null;this._destroyed=!1;this._disconnected=!1;this._open=!1;this._connections=new Map;this._lostMessages=new Map;var r;let i;if(e&&e.constructor==Object?t=e:e&&(i=e.toString()),t=m({debug:0,host:f.CLOUD_HOST,port:f.CLOUD_PORT,path:"/",key:v.DEFAULT_KEY,token:f.randomToken(),config:f.defaultConfig},t),this._options=t,typeof window!="undefined"&&this._options.host==="/"&&(this._options.host=window.location.hostname),this._options.path&&(this._options.path[0]!=="/"&&(this._options.path="/"+this._options.path),this._options.path[this._options.path.length-1]!=="/"&&(this._options.path+="/")),this._options.secure===void 0&&this._options.host!==f.CLOUD_HOST?this._options.secure=f.isSecure():this._options.host==f.CLOUD_HOST&&(this._options.secure=!0),this._options.logFunction&&s.setLogFunction(this._options.logFunction),s.logLevel=this._options.debug||0,this._api=new J(t),this._socket=this._createServerConnection(),this.features=v.getFeatures((r=this._options.polyfills)==null?void 0:r.WebRTC),!this.features.audioVideo&&!this.features.data){this._delayedAbort("browser-incompatible","The current browser does not support WebRTC");return}if(!!i&&!f.validateId(i)){this._delayedAbort("invalid-id",`ID "${i}" is invalid`);return}this.socket.alive=!0,i?this._initialize(i):this._api.retrieveId().then(o=>this._initialize(o)).catch(o=>this._abort("server-error",o))}get id(){return this._id}get options(){return this._options}get open(){return this._open}get socket(){return this._socket}get connections(){let e=Object.create(null);for(let[t,i]of this._connections)e[t]=i;return e}get destroyed(){return this._destroyed}get disconnected(){return this._disconnected}_createServerConnection(){let e=new W(this._options);return e.on("message",t=>{this._handleMessage(t)}),e.on("error",t=>{this._abort("socket-error",t)}),e.on("disconnected",()=>{this.disconnected||(this.emitError("network","Lost connection to server."),this.disconnect())}),e.on("close",()=>{this.disconnected||this._abort("socket-closed","Underlying socket is already closed.")}),e}_initialize(e){this.destroyed||(this._id=e,this.socket.start(e,this._options.token))}_handleMessage(e){let t=e.type,i=e.payload,r=e.src;switch(t){case"OPEN":this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case"ERROR":this._abort("server-error",i.msg);break;case"ID-TAKEN":this._abort("unavailable-id",`ID "${this.id}" is taken`);break;case"INVALID-KEY":this._abort("invalid-key",`API KEY "${this._options.key}" is invalid`);break;case"LEAVE":s.log(`Received leave message from ${r}`),this._cleanupPeer(r),this._connections.delete(r);break;case"EXPIRE":this.emitError("peer-unavailable",`Could not connect to peer ${r}`);break;case"OFFER":{let o=i.connectionId,a=this.getConnection(r,o);if(a&&(a.close(),s.warn(`Offer received for existing Connection ID:${o}`)),i.type==="media")a=new M(r,this,{connectionId:o,_payload:i,metadata:i.metadata}),this._addConnection(r,a),this.emit("call",a);else if(i.type==="data")a=new C(r,this,{connectionId:o,_payload:i,metadata:i.metadata,label:i.label,serialization:i.serialization,reliable:i.reliable}),this._addConnection(r,a),this.emit("connection",a);else{s.warn(`Received malformed connection type:${i.type}`);return}let d=this._getMessages(o);for(let c of d)a.handleMessage(c);break}default:{if(!i){s.warn(`You received a malformed message from ${r} of type ${t}`);return}let o=i.connectionId,a=this.getConnection(r,o);a&&a.peerConnection?a.handleMessage(e):o?this._storeMessage(o,e):s.warn("You received an unrecognized message:",e);break}}}_storeMessage(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(t)}_getMessages(e){let t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),t):[]}connect(e,t={}){if(this.disconnected){s.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."),this.emitError("disconnected","Cannot connect to new Peer after disconnecting from server.");return}let i=new C(e,this,t);return this._addConnection(e,i),i}call(e,t,i={}){if(this.disconnected){s.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."),this.emitError("disconnected","Cannot connect to new Peer after disconnecting from server.");return}if(!t){s.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}i._stream=t;let r=new M(e,this,i);return this._addConnection(e,r),r}_addConnection(e,t){s.log(`add connection ${t.type}:${t.connectionId} to peerId:${e}`),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(t)}_removeConnection(e){let t=this._connections.get(e.peer);if(t){let i=t.indexOf(e);i!==-1&&(t.splice(i,1),t.length===0&&this._connections.delete(e.peer))}this._lostMessages.delete(e.connectionId)}getConnection(e,t){let i=this._connections.get(e);if(!i)return null;for(let r of i)if(r.connectionId===t)return r;return null}_delayedAbort(e,t){setTimeout(()=>{this._abort(e,t)},0)}_abort(e,t){s.error("Aborting!"),this.emitError(e,t),this._lastServerId?this.disconnect():this.destroy()}emitError(e,t){s.error("Error:",t);let i;typeof t=="string"?i=new Error(t):i=t,i.type=e,this.emit("error",i)}destroy(){this.destroyed||(s.log(`Destroy peer with ID:${this.id}`),this.disconnect(),this._cleanup(),this.socket.destroy(),this._destroyed=!0,this.emit("close"))}_cleanup(){for(let e of this._connections.keys())this._cleanupPeer(e),this._connections.delete(e);this.socket.removeAllListeners()}_cleanupPeer(e){let t=this._connections.get(e);if(!!t)for(let i of t)i.close()}disconnect(){if(this.disconnected)return;let e=this.id;s.log(`Disconnect peer with ID:${e}`),this._disconnected=!0,this._open=!1,this.socket.alive=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}reconnect(){if(this.disconnected&&!this.destroyed)s.log(`Attempting reconnection to server with ID ${this._lastServerId}`),this._disconnected=!1,this.socket.alive=!0,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)s.error("In a hurry? We're still trying to make the initial connection!");else throw new Error(`Peer ${this.id} cannot reconnect because it is not disconnected from the server!`)}}listAllPeers(e=t=>{}){this._api.listAllPeers().then(t=>e(t)).catch(t=>this._abort("server-error",t))}static getFeatures(e){return!e&&typeof window!="undefined"&&(e=window),v._features||(v._features=v.checkFeatures(e)),v._features}static checkFeatures(e){!e&&typeof window!="undefined"&&(e=window);let t={webRTC:typeof e.RTCPeerConnection!="undefined",audioVideo:!0,data:!1,binaryBlob:!1,reliable:!1,unifiedPlan:!1};if(!t.webRTC)return t;let i;try{i=new e.RTCPeerConnection(f.defaultConfig);let r;try{r=i.createDataChannel("_PEERJSTEST",{ordered:!0}),t.data=!0,t.reliable=!!r.ordered;try{r.binaryType="blob",t.binaryBlob=!0}catch(o){}}catch(o){}finally{r&&r.close()}}catch(r){}finally{i&&i.close()}return t.unifiedPlan=se.isUnifiedPlanSupported(e),t}},T=v;T.DEFAULT_KEY="peerjs";var Ct=T;typeof window!="undefined"&&(window.Peer=T);})();
//# sourceMappingURL=peerjs.min.js.map

@@ -6,6 +6,6 @@ import { Utils } from './utils';

export class API {
private readonly fetch: typeof fetch;
constructor(private readonly _options: PeerJSOption) {}
constructor(private readonly _options: PeerJSOption) {
this.fetch = _options.polyfills?.fetch ?? window.fetch;
private _request(url: string) {
return (this._options.polyfills?.fetch ?? window.fetch)(url);
}

@@ -28,3 +28,3 @@

try {
const response = await this.fetch(url);
const response = await this._request(url);

@@ -57,3 +57,3 @@ if (response.status !== 200) {

try {
const response = await this.fetch(url);
const response = await this._request(url);

@@ -60,0 +60,0 @@ if (response.status !== 200) {

{
"name": "peerjs",
"version": "2.0.0-beta.2",
"version": "2.0.0-beta.3",
"description": "PeerJS client",

@@ -5,0 +5,0 @@ "main": "./dist/peerjs.cjs.js",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc