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.0 to 2.0.0-beta.1

2

dist/peerjs.min.js

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

var Peer=(()=>{var pe=Object.create;var B=Object.defineProperty,he=Object.defineProperties,ue=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertyNames,Y=Object.getOwnPropertySymbols,ye=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty,ve=Object.prototype.propertyIsEnumerable;var q=(n,e,t)=>e in n?B(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))ve.call(e,t)&&q(n,t,e[t]);return n},P=(n,e)=>he(n,_e(e)),K=n=>B(n,"__esModule",{value:!0});var $=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),be=(n,e)=>{for(var t in e)B(n,t,{get:e[t],enumerable:!0})},X=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ge(e))!V.call(n,r)&&(t||r!=="default")&&B(n,r,{get:()=>e[r],enumerable:!(i=ue(e,r))||i.enumerable});return n},S=(n,e)=>X(K(B(n!=null?pe(ye(n)):{},"default",!e&&n&&n.__esModule?{get:()=>n.default,enumerable:!0}:{value:n,enumerable:!0})),n),me=(n=>(e,t)=>n&&n.get(e)||(t=X(K({}),e,1),n&&n.set(e,t),t))(typeof WeakMap!="undefined"?new WeakMap:0);var y=(n,e,t)=>new Promise((i,r)=>{var o=c=>{try{f(t.next(c))}catch(p){r(p)}},a=c=>{try{f(t.throw(c))}catch(p){r(p)}},f=c=>c.done?i(c.value):Promise.resolve(c.value).then(o,a);f((t=t.apply(n,e)).next())});var z=$((Ae,E)=>{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}}();E.exports.binaryFeatures=k;var G=E.exports.BlobBuilder;typeof window!="undefined"&&(G=E.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 G,e=0,t=this._parts.length;e<t;e++)n.append(this._parts[e]);return n.getBlob()}else return new Blob(this._parts)};E.exports.BufferBuilder=A});var te=$((Oe,ee)=>{var ke=z().BufferBuilder,Z=z().binaryFeatures,Ce={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}};ee.exports=Ce;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 ke}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)Z.useArrayBufferView?this.pack_bin(new Uint8Array(n)):this.pack_bin(n);else if("BYTES_PER_ELEMENT"in n)Z.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=xe(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,f=r%o;this.bufferBuilder.append(203),this.pack_int32(a),this.pack_int32(f)};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 we(n){var e=n.charCodeAt(0);return e<=2047?"00":e<=65535?"000":e<=2097151?"0000":e<=67108863?"00000":"000000"}function xe(n){return n.length>600?new Blob([n]).size:n.replace(/[^\u0000-\u007F]/g,we).length}});var D=$((Le,N)=>{"use strict";var Se=Object.prototype.hasOwnProperty,g="~";function I(){}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(g=!1));function Ee(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function ne(n,e,t,i,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Ee(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 I:delete n._events[e]}function _(){this._events=new I,this._eventsCount=0}_.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)Se.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 f=g?g+e:e;if(!this._events[f])return!1;var c=this._events[f],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 le=c.length,x;for(l=0;l<le;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(x=1,b=new Array(p-1);x<p;x++)b[x-1]=arguments[x];c[l].fn.apply(c[l].context,b)}}return!0};_.prototype.on=function(e,t,i){return ne(this,e,t,i,!1)};_.prototype.once=function(e,t,i){return ne(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 f=0,c=[],p=a.length;f<p;f++)(a[f].fn!==t||r&&!a[f].once||i&&a[f].context!==i)&&c.push(a[f]);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 I,this._eventsCount=0),this};_.prototype.off=_.prototype.removeListener;_.prototype.addListener=_.prototype.on;_.prefixed=g;_.EventEmitter=_;typeof N!="undefined"&&(N.exports=_)});var Fe={};be(Fe,{Peer:()=>w,Utils:()=>d,default:()=>Te});var O=S(te()),Be={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"turn:0.peerjs.com:3478",username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},d=new class{constructor(){this.CLOUD_HOST="0.peerjs.com";this.CLOUD_PORT=443;this.chunkedMTU=16300;this.defaultConfig=Be;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/d.chunkedMTU),r=0,o=0;for(;o<t;){let a=Math.min(t,o+d.chunkedMTU),f=n.slice(o,a),c={__peerData:this._dataCount,n:r,data:f,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 de=S(D());var Ie="PeerJS: ";var ie=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=[Ie,...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 ie;var re=S(D());var W=class extends re.EventEmitter{constructor({secure:e,host:t,port:i,path:r,key:o,pingInterval:a=5e3,polyfills:f}){super();this._disconnected=!0;this._messagesQueue=[];var p;this.pingInterval=a;let c=e?"wss://":"ws://";this._baseUrl=c+t+":"+i+r+"peerjs?key="+o,this.WebSocketConstructor=(p=f==null?void 0:f.WebSocket)!=null?p:window.WebSocket}start(e,t){this._id=e;let i=`${this._baseUrl}&id=${e}&token=${t}`;!!this._socket||!this._disconnected||(this._socket=new this.WebSocketConstructor(i),this._disconnected=!1,this._socket.onmessage=r=>{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||(s.log("Socket closed.",r),this._cleanup(),this._disconnected=!0,this.emit("disconnected"))},this._socket.onopen=()=>{this._disconnected||(this._sendQueuedMessages(),s.log("Socket open"),this._scheduleHeartbeat())})}_scheduleHeartbeat(){this._wsPingTimer=setTimeout(()=>{this._sendHeartbeat()},this.pingInterval)}_sendHeartbeat(){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)}send(e){if(this._disconnected)return;if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit("error","Invalid message");return}if(!this._wsOpen())return;let t=JSON.stringify(e);this._socket.send(t)}close(){this._disconnected||(this._cleanup(),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)}};function oe(){}var M=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."),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"disconnected":s.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":e.onicecandidate=oe;break}this.connection.emit("iceStateChanged",e.iceConnectionState)},s.log("Listening for data channel"),e.ondatachannel=a=>{s.log("Received data channel");let f=a.channel;o.getConnection(t,i).initialize(f)},s.log("Listening for remote stream"),e.ontrack=a=>{s.log("Received remote stream");let f=a.streams[0],c=o.getConnection(t,i);if(c.type==="media"){let p=c;this._addStreamToMediaConnection(f,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=oe;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);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();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(f){o.emitError("webrtc",f),s.log("Failed to setRemoteDescription, ",f)}})}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 f=this.webRtc.RTCIceCandidate;yield o.addIceCandidate(new f({sdpMid:r,sdpMLineIndex:i,candidate:t})),s.log(`Added ICE candidate for:${this.connection.peer}`)}catch(f){a.emitError("webrtc",f),s.log("Failed to handleCandidate, ",f)}})}_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 ae=S(D()),T=class extends ae.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 T{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+d.randomToken(),this._negotiator=new M(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"))}},F=j;F.ID_PREFIX="mc_";var ce=S(D());var J=class extends ce.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 T{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+d.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 M(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){d.blobToArrayBuffer(this.FileReaderCtr,e,o=>{let a=d.unpack(o);this.emit("data",a)});return}else if(t===ArrayBuffer)r=d.unpack(e);else if(t===String){let o=d.binaryStringToArrayBuffer(e);r=d.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=d.pack(e);if(!t&&i.size>d.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=d.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!==d.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===d.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 fe={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 de.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:d.CLOUD_HOST,port:d.CLOUD_PORT,path:"/",key:v.DEFAULT_KEY,token:d.randomToken(),config:d.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!==d.CLOUD_HOST?this._options.secure=d.isSecure():this._options.host==d.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&&!d.validateId(i)){this._delayedAbort("invalid-id",`ID "${i}" is invalid`);return}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._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 F(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 f=this._getMessages(o);for(let c of f)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 F(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)}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._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.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._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(d.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=fe.isUnifiedPlanSupported(e),t}},w=v;w.DEFAULT_KEY="peerjs";var Te=w;typeof window!="undefined"&&(window.Peer=w);return me(Fe);})();
var Peer=(()=>{var le=Object.create;var B=Object.defineProperty,pe=Object.defineProperties,he=Object.getOwnPropertyDescriptor,ue=Object.getOwnPropertyDescriptors,_e=Object.getOwnPropertyNames,Y=Object.getOwnPropertySymbols,ge=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty,ye=Object.prototype.propertyIsEnumerable;var q=(n,e,t)=>e in n?B(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))ye.call(e,t)&&q(n,t,e[t]);return n},P=(n,e)=>pe(n,ue(e)),K=n=>B(n,"__esModule",{value:!0});var $=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),ve=(n,e)=>{for(var t in e)B(n,t,{get:e[t],enumerable:!0})},X=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _e(e))!V.call(n,r)&&(t||r!=="default")&&B(n,r,{get:()=>e[r],enumerable:!(i=he(e,r))||i.enumerable});return n},S=(n,e)=>X(K(B(n!=null?le(ge(n)):{},"default",!e&&n&&n.__esModule?{get:()=>n.default,enumerable:!0}:{value:n,enumerable:!0})),n),be=(n=>(e,t)=>n&&n.get(e)||(t=X(K({}),e,1),n&&n.set(e,t),t))(typeof WeakMap!="undefined"?new WeakMap:0);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=$((Ae,E)=>{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}}();E.exports.binaryFeatures=k;var G=E.exports.BlobBuilder;typeof window!="undefined"&&(G=E.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 G,e=0,t=this._parts.length;e<t;e++)n.append(this._parts[e]);return n.getBlob()}else return new Blob(this._parts)};E.exports.BufferBuilder=A});var te=$((Oe,ee)=>{var me=z().BufferBuilder,Z=z().binaryFeatures,ke={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}};ee.exports=ke;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 me}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)Z.useArrayBufferView?this.pack_bin(new Uint8Array(n)):this.pack_bin(n);else if("BYTES_PER_ELEMENT"in n)Z.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=we(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 Ce(n){var e=n.charCodeAt(0);return e<=2047?"00":e<=65535?"000":e<=2097151?"0000":e<=67108863?"00000":"000000"}function we(n){return n.length>600?new Blob([n]).size:n.replace(/[^\u0000-\u007F]/g,Ce).length}});var I=$((Le,N)=>{"use strict";var Be=Object.prototype.hasOwnProperty,g="~";function D(){}Object.create&&(D.prototype=Object.create(null),new D().__proto__||(g=!1));function Se(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function ne(n,e,t,i,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Se(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 D:delete n._events[e]}function _(){this._events=new D,this._eventsCount=0}_.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)Be.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 fe=c.length,x;for(l=0;l<fe;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(x=1,b=new Array(p-1);x<p;x++)b[x-1]=arguments[x];c[l].fn.apply(c[l].context,b)}}return!0};_.prototype.on=function(e,t,i){return ne(this,e,t,i,!1)};_.prototype.once=function(e,t,i){return ne(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 D,this._eventsCount=0),this};_.prototype.off=_.prototype.removeListener;_.prototype.addListener=_.prototype.on;_.prefixed=g;_.EventEmitter=_;typeof N!="undefined"&&(N.exports=_)});var Fe={};ve(Fe,{Peer:()=>w,Utils:()=>f,default:()=>Te});var O=S(te()),xe={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=xe;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 de=S(I());var Ee="PeerJS: ";var ie=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=[Ee,...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 ie;var re=S(I());var W=class extends re.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 Me(){}var M=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=Me;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 se=S(I()),T=class extends se.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 T{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 M(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"))}},F=j;F.ID_PREFIX="mc_";var ae=S(I());var J=class extends ae.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 T{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 M(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 ce={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 de.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 F(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 F(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=ce.isUnifiedPlanSupported(e),t}},w=v;w.DEFAULT_KEY="peerjs";var Te=w;typeof window!="undefined"&&(window.Peer=w);return be(Fe);})();
//# sourceMappingURL=peerjs.min.js.map

@@ -50,2 +50,3 @@ export enum ConnectionEventType {

Close = 'close',
Open = 'open',
}

@@ -52,0 +53,0 @@

@@ -67,3 +67,3 @@ import logger from './logger';

// ICE CANDIDATES.
logger.log('Listening for ICE candidates.');
logger.log('Listening for ICE candidates, remote streams and data channels.');

@@ -101,2 +101,5 @@ peerConnection.onicecandidate = evt => {

break;
case 'connected':
logger.log('iceConnectionState changed to connected on the connection with ' + peerId);
break;
case 'disconnected':

@@ -106,2 +109,3 @@ logger.log('iceConnectionState changed to disconnected on the connection with ' + peerId);

case 'completed':
logger.log('iceConnectionState changed to completed on the connection with ' + peerId);
peerConnection.onicecandidate = noop;

@@ -114,4 +118,2 @@ break;

// DATACONNECTION.
logger.log('Listening for data channel');
// Fired between offer and answer, so options should already be saved

@@ -128,5 +130,2 @@ // in the options hash.

// MEDIACONNECTION.
logger.log('Listening for remote stream');
peerConnection.ontrack = evt => {

@@ -162,3 +161,3 @@ logger.log('Received remote stream');

peerConnection.ontrack =
noop;
null;

@@ -189,2 +188,4 @@ const peerConnectionNotClosed = peerConnection.signalingState !== 'closed';

if (peerConnection.signalingState === 'closed') return;
logger.log('Created offer.');

@@ -243,2 +244,5 @@

const answer = await peerConnection.createAnswer();
if (peerConnection.signalingState === 'closed') return;
logger.log('Created answer.');

@@ -245,0 +249,0 @@

@@ -149,2 +149,4 @@ import { EventEmitter } from 'eventemitter3';

this.socket.alive = true;
if (userId) {

@@ -193,2 +195,4 @@ this._initialize(userId);

private _initialize(id: string): void {
if (this.destroyed) return;
this._id = id;

@@ -382,2 +386,6 @@ this.socket.start(id, this._options.token!);

connections.splice(index, 1);
if (connections.length === 0) {
this._connections.delete(connection.peer);
}
}

@@ -462,2 +470,4 @@ }

this.socket.destroy();
this._destroyed = true;

@@ -507,2 +517,3 @@

this.socket.alive = false;
this.socket.close();

@@ -521,2 +532,3 @@

this._disconnected = false;
this.socket.alive = true;
this._initialize(this._lastServerId!);

@@ -523,0 +535,0 @@ } else if (this.destroyed) {

import { EventEmitter } from 'eventemitter3';
import logger from './logger';
import { SocketEventType, ServerMessageType } from './enums';
import { SocketEventType, ServerMessageType, type ConnectionType } from './enums';
import type { PeerJSOption } from '../index';
type MessageData = {
type: ServerMessageType;
dst: string;
payload: {
type: ConnectionType;
connectionId: string;
} & Record<string, any>;
};
/**

@@ -12,4 +20,4 @@ * An abstraction on top of WebSockets to provide the fastest

private _disconnected: boolean = true;
private _id?: string;
private _messagesQueue: Array<object> = [];
private _id: string | null = null;
private _messagesQueue: Array<MessageData> = [];
private _socket?: WebSocket;

@@ -22,2 +30,14 @@ private _wsPingTimer?: any;

alive: boolean = false;
private _destroyed = false;
get messagesQueue(): ReadonlyArray<MessageData> {
return this._messagesQueue;
}
get destroyed() {
return this._destroyed;
}
constructor({ secure, host, port, path, key, pingInterval = 5000, polyfills }: PeerJSOption) {

@@ -35,6 +55,6 @@ super();

start(id: string, token: string): void {
if (this._destroyed) throw new Error('Socket was destroyed!');
this._id = id;
const wsUrl = `${this._baseUrl}&id=${id}&token=${token}`;
if (!!this._socket || !this._disconnected) {

@@ -44,2 +64,4 @@ return;

const wsUrl = `${this._baseUrl}&id=${id}&token=${token}`;
this._socket = new this.WebSocketConstructor(wsUrl);

@@ -49,2 +71,4 @@ this._disconnected = false;

this._socket.onmessage = event => {
if (this._destroyed) return;
let data;

@@ -64,3 +88,3 @@

this._socket.onclose = event => {
if (this._disconnected) {
if (this._disconnected || this._destroyed) {
return;

@@ -80,10 +104,12 @@ }

this._socket.onopen = () => {
if (this._disconnected) {
if (this._disconnected || this._destroyed) {
return;
}
logger.log('Socket open');
this.emit(SocketEventType.Open);
this._sendQueuedMessages();
logger.log('Socket open');
this._scheduleHeartbeat();

@@ -100,2 +126,4 @@ };

private _sendHeartbeat(): void {
if (this._destroyed) return;
if (!this._wsOpen()) {

@@ -121,3 +149,3 @@ logger.log(`Cannot send heartbeat, because socket closed`);

//Create copy of queue and clear it,
//because send method push the message back to queue if smth will go wrong
//because send method push the message back to queue if something will go wrong
const copiedQueue = [...this._messagesQueue];

@@ -129,23 +157,25 @@ this._messagesQueue = [];

}
if (copiedQueue.length > 0) {
logger.log(`${copiedQueue.length} queued messages was sent`);
}
}
/** Exposed send for DC & Peer. */
send(data: any): void {
if (this._disconnected) {
return;
}
send(data: MessageData): void {
if (this._destroyed) throw new Error('Socket was destroyed!');
// If we didn't get an ID yet, we can't yet send anything so we should queue
// up these messages.
if (!this._id) {
this._messagesQueue.push(data);
if (!data.type) {
this.emit(SocketEventType.Error, 'Invalid message');
return;
}
if (!data.type) {
this.emit(SocketEventType.Error, 'Invalid message');
if (!this.alive) {
return;
}
if (!this._wsOpen()) {
// If we didn't get an ID yet, we can't yet send anything so we should queue
// up these messages.
if (this._id == null || !this._wsOpen()) {
this._messagesQueue.push(data);
return;

@@ -166,2 +196,4 @@ }

this._id = null;
this._disconnected = true;

@@ -179,2 +211,11 @@ }

}
destroy() {
if (this._destroyed) return;
this.close();
this._messagesQueue.length = 0;
this._destroyed = true;
}
}
{
"name": "peerjs",
"version": "2.0.0-beta.0",
"version": "2.0.0-beta.1",
"description": "PeerJS client",

@@ -37,3 +37,3 @@ "main": "./dist/peerjs.cjs.js",

"prepublishOnly": "npm run tsc-check && npm run test && npm run build",
"test": "mocha -r ts-node/register -r jsdom-global/register test/**/*.ts",
"test": "mocha -r ts-node/register -r jsdom-global/register test/*.spec.ts",
"tsc-check": "tsc --noEmit"

@@ -55,5 +55,7 @@ },

"mock-socket": "8.0.5",
"node-fetch": "^2.6.7",
"prettier": "^2.5.1",
"ts-node": "^10.5.0",
"typescript": "^4.5.5"
"typescript": "^4.5.5",
"wrtc": "^0.4.7"
},

@@ -60,0 +62,0 @@ "dependencies": {

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

# PeerJS: Simple peer-to-peer with WebRTC #
# PeerJS: Simple peer-to-peer with WebRTC

@@ -6,6 +6,14 @@ ### https://t.me/joinchat/VWI0UBxnG7f7_DV7

[![Backers on Open Collective](https://opencollective.com/peer/backers/badge.svg)](#backers)
[![Sponsors on Open Collective](https://opencollective.com/peer/sponsors/badge.svg)](#sponsors)
[![Sponsors on Open Collective](https://opencollective.com/peer/sponsors/badge.svg)](#sponsors)
PeerJS provides a complete, configurable, and easy-to-use peer-to-peer API built on top of WebRTC, supporting both data channels and media streams.
## Features
- TypeScript 100%
- respects CommonJS, ES Module
- NodeJS support
- Simple API
- DataChannel + MediaStream
## Live Example

@@ -17,19 +25,22 @@

**Install a dependency**
with npm:
`npm install peerjs`
with yarn:
`yarn add peerjs`
**Include the library**
with npm:
`npm install peerjs`
with yarn:
`yarn add peerjs`
```js
// The usage -
import Peer from 'peerjs';
```
```js
import { Peer } from 'peerjs';
```
**Create a Peer**
**Create a Peer**
```javascript
const peer = new Peer('pick-an-id');
const peer = new Peer('pick-an-id');
// You can pick your own id or omit the id if you want to get a random one from the server.

@@ -39,3 +50,5 @@ ```

## Data connections
**Connect**
```javascript

@@ -47,6 +60,8 @@ const conn = peer.connect('another-peers-id');

```
**Receive**
```javascript
peer.on('connection', (conn) => {
conn.on('data', (data) => {
peer.on('connection', conn => {
conn.on('data', data => {
// Will print 'hi!'

@@ -62,25 +77,36 @@ console.log(data);

## Media calls
**Call**
```javascript
navigator.mediaDevices.getUserMedia({video: true, audio: true}, (stream) => {
const call = peer.call('another-peers-id', stream);
call.on('stream', (remoteStream) => {
// Show stream in some <video> element.
});
}, (err) => {
console.error('Failed to get local stream', err);
});
```
**Answer**
```javascript
peer.on('call', (call) => {
navigator.mediaDevices.getUserMedia({video: true, audio: true}, (stream) => {
call.answer(stream); // Answer the call with an A/V stream.
call.on('stream', (remoteStream) => {
navigator.mediaDevices.getUserMedia(
{ video: true, audio: true },
stream => {
const call = peer.call('another-peers-id', stream);
call.on('stream', remoteStream => {
// Show stream in some <video> element.
});
}, (err) => {
},
err => {
console.error('Failed to get local stream', err);
});
}
);
```
**Answer**
```javascript
peer.on('call', call => {
navigator.mediaDevices.getUserMedia(
{ video: true, audio: true },
stream => {
call.answer(stream); // Answer the call with an A/V stream.
call.on('stream', remoteStream => {
// Show stream in some <video> element.
});
},
err => {
console.error('Failed to get local stream', err);
}
);
});

@@ -97,6 +123,12 @@ ```

| [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Firefox | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Chrome | [<img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png" alt="Safari" width="24px" height="24px" />](http://godban.github.io/browsers-support-badges/)</br>Safari |
| --------- | --------- | --------- |
| last 4 versions| last 4 versions| 12.1+
Firefox: 70
Chrome: 76
Edge: 79
Opera: 63
Safari: 12.1+
## Safari

@@ -108,7 +140,14 @@

Q. I have a message ```Critical dependency: the request of a dependency is an expression``` in browser's console
- How to create an empty stream?
A. The message occurs when you use PeerJS with Webpack. It is not critical! It relates to Parcel https://github.com/parcel-bundler/parcel/issues/2883 We'll resolve it when updated to Parcel V2.
https://github.com/peers/peerjs/issues/594#issuecomment-1046147052
- It doesn't work for iOS, any idea?
https://github.com/peers/peerjs/issues/599#issuecomment-559981544
- How to change the codecs/quality of streams?
You should modify the sdp message: https://github.com/peers/peerjs/issues/901#issuecomment-1046230997
## Links

@@ -235,3 +274,2 @@

## Sponsors

@@ -252,7 +290,4 @@

## License
PeerJS is licensed under the [MIT License](https://tldrlegal.com/l/mit).

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