forked from feross/simple-peer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tinysimplepeer.min.js
1 lines (1 loc) · 34 KB
/
tinysimplepeer.min.js
1
(function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,n.TinySimplePeer=e()}})(function(){var e=Math.abs;return function(){function s(d,e,n){function t(o,i){if(!e[o]){if(!d[o]){var l="function"==typeof require&&require;if(!i&&l)return l(o,!0);if(r)return r(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var a=e[o]={exports:{}};d[o][0].call(a.exports,function(e){var r=d[o][1][e];return t(r||e)},a,a.exports,s,d,e,n)}return e[o].exports}for(var r="function"==typeof require&&require,o=0;o<n.length;o++)t(n[o]);return t}return s}()({1:[function(e,n,t){(function(o){(function(){function r(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+n.exports.humanize(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,o=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"===e||(r++,"%c"===e&&(o=r))}),e.splice(o,0,t)}function i(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof o&&"env"in o&&(e=o.env.DEBUG),e}t.formatArgs=r,t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=i,t.useColors=function(){return!!("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),n.exports=e("./common")(t);const{formatters:s}=n.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":2,_process:7}],2:[function(n,t){t.exports=function(t){function r(e){function n(...e){if(!n.enabled)return;const o=n,i=+new Date,s=i-(t||i);o.diff=s,o.prev=t,o.curr=i,t=i,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,t)=>{if("%%"===n)return"%";a++;const i=r.formatters[t];if("function"==typeof i){const t=e[a];n=i.call(o,t),e.splice(a,1),a--}return n}),r.formatArgs.call(o,e);const d=o.log||r.log;d.apply(o,e)}let t,i,s,a=null;return n.namespace=e,n.useColors=r.useColors(),n.color=r.selectColor(e),n.extend=o,n.destroy=r.destroy,Object.defineProperty(n,"enabled",{enumerable:!0,configurable:!1,get:()=>null===a?(i!==r.namespaces&&(i=r.namespaces,s=r.enabled(e)),s):a,set:e=>{a=e}}),"function"==typeof r.init&&r.init(n),n}function o(e,n){const t=r(this.namespace+("undefined"==typeof n?":":n)+e);return t.log=this.log,t}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return r.debug=r,r.default=r,r.coerce=function(e){return e instanceof Error?e.stack||e.message:e},r.disable=function(){const e=[...r.names.map(i),...r.skips.map(i).map(e=>"-"+e)].join(",");return r.enable(""),e},r.enable=function(e){r.save(e),r.namespaces=e,r.names=[],r.skips=[];let n;const t=("string"==typeof e?e:"").split(/[\s,]+/),o=t.length;for(n=0;n<o;n++)t[n]&&(e=t[n].replace(/\*/g,".*?"),"-"===e[0]?r.skips.push(new RegExp("^"+e.slice(1)+"$")):r.names.push(new RegExp("^"+e+"$")))},r.enabled=function(e){if("*"===e[e.length-1])return!0;let n,t;for(n=0,t=r.skips.length;n<t;n++)if(r.skips[n].test(e))return!1;for(n=0,t=r.names.length;n<t;n++)if(r.names[n].test(e))return!0;return!1},r.humanize=n("ms"),r.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(t).forEach(e=>{r[e]=t[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(n){let t=0;for(let e=0;e<n.length;e++)t=(t<<5)-t+n.charCodeAt(e),t|=0;return r.colors[e(t)%r.colors.length]},r.enable(r.load()),r}},{ms:6}],3:[function(e,n){"use strict";function t(e,n){for(const t in n)Object.defineProperty(e,t,{value:n[t],enumerable:!0,configurable:!0});return e}n.exports=function(e,n,r){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof n&&(r=n,n=""),n&&(r.code=n);try{return t(e,r)}catch(n){r.message=e.message,r.stack=e.stack;const o=function(){};o.prototype=Object.create(Object.getPrototypeOf(e));const i=t(new o,r);return i}}},{}],4:[function(e,n){"use strict";function t(e){console&&console.warn&&console.warn(e)}function r(){r.init.call(this)}function o(e){if("function"!=typeof e)throw new TypeError("The \"listener\" argument must be of type Function. Received type "+typeof e)}function i(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function s(e,n,r,s){var a,d,c;if(o(r),d=e._events,void 0===d?(d=e._events=Object.create(null),e._eventsCount=0):(void 0!==d.newListener&&(e.emit("newListener",n,r.listener?r.listener:r),d=e._events),c=d[n]),void 0===c)c=d[n]=r,++e._eventsCount;else if("function"==typeof c?c=d[n]=s?[r,c]:[c,r]:s?c.unshift(r):c.push(r),a=i(e),0<a&&c.length>a&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+(n+" listeners added. Use emitter.setMaxListeners() to increase limit"));l.name="MaxListenersExceededWarning",l.emitter=e,l.type=n,l.count=c.length,t(l)}return e}function a(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,n,t){var r={fired:!1,wrapFn:void 0,target:e,type:n,listener:t},o=a.bind(r);return o.listener=t,r.wrapFn=o,o}function c(e,n,t){var r=e._events;if(r===void 0)return[];var o=r[n];return void 0===o?[]:"function"==typeof o?t?[o.listener||o]:[o]:t?_(o):p(o,o.length)}function l(e){var n=this._events;if(n!==void 0){var t=n[e];if("function"==typeof t)return 1;if(void 0!==t)return t.length}return 0}function p(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function u(e,n){for(;n+1<e.length;n++)e[n]=e[n+1];e.pop()}function _(e){for(var n=Array(e.length),t=0;t<n.length;++t)n[t]=e[t].listener||e[t];return n}function g(e,n,t){"function"==typeof e.on&&m(e,"error",n,t)}function m(e,n,t,r){if("function"==typeof e.on)r.once?e.once(n,t):e.on(n,t);else if("function"==typeof e.addEventListener)e.addEventListener(n,function i(o){r.once&&e.removeEventListener(n,i),t(o)});else throw new TypeError("The \"emitter\" argument must be of type EventEmitter. Received type "+typeof e)}var C,f="object"==typeof Reflect?Reflect:null,y=f&&"function"==typeof f.apply?f.apply:function(e,n,t){return Function.prototype.apply.call(e,n,t)};C=f&&"function"==typeof f.ownKeys?f.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var h=Number.isNaN||function(e){return e!==e};n.exports=r,n.exports.once=function(e,n){return new Promise(function(t,r){function o(t){e.removeListener(n,i),r(t)}function i(){"function"==typeof e.removeListener&&e.removeListener("error",o),t([].slice.call(arguments))}m(e,n,i,{once:!0}),"error"!==n&&g(e,o,{once:!0})})},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var b=10;Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return b},set:function(e){if("number"!=typeof e||0>e||h(e))throw new RangeError("The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received "+e+".");b=e}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||h(e))throw new RangeError("The value of \"n\" is out of range. It must be a non-negative number. Received "+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return i(this)},r.prototype.emit=function(e){for(var n=[],t=1;t<arguments.length;t++)n.push(arguments[t]);var r="error"===e,o=this._events;if(o!==void 0)r=r&&o.error===void 0;else if(!r)return!1;if(r){var s;if(0<n.length&&(s=n[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var d=o[e];if(d===void 0)return!1;if("function"==typeof d)y(d,this,n);else for(var c=d.length,l=p(d,c),t=0;t<c;++t)y(l[t],this,n);return!0},r.prototype.addListener=function(e,n){return s(this,e,n,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,n){return s(this,e,n,!0)},r.prototype.once=function(e,n){return o(n),this.on(e,d(this,e,n)),this},r.prototype.prependOnceListener=function(e,n){return o(n),this.prependListener(e,d(this,e,n)),this},r.prototype.removeListener=function(e,n){var t,r,s,a,d;if(o(n),r=this._events,void 0===r)return this;if(t=r[e],void 0===t)return this;if(t===n||t.listener===n)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,t.listener||n));else if("function"!=typeof t){for(s=-1,a=t.length-1;0<=a;a--)if(t[a]===n||t[a].listener===n){d=t[a].listener,s=a;break}if(0>s)return this;0===s?t.shift():u(t,s),1===t.length&&(r[e]=t[0]),void 0!==r.removeListener&&this.emit("removeListener",e,d||n)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var n,t,r;if(t=this._events,void 0===t)return this;if(void 0===t.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==t[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete t[e]),this;if(0===arguments.length){var o,s=Object.keys(t);for(r=0;r<s.length;++r)o=s[r],"removeListener"!==o&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=t[e],"function"==typeof n)this.removeListener(e,n);else if(void 0!==n)for(r=n.length-1;0<=r;r--)this.removeListener(e,n[r]);return this},r.prototype.listeners=function(e){return c(this,e,!0)},r.prototype.rawListeners=function(e){return c(this,e,!1)},r.listenerCount=function(e,n){return"function"==typeof e.listenerCount?e.listenerCount(n):l.call(e,n)},r.prototype.listenerCount=l,r.prototype.eventNames=function(){return 0<this._eventsCount?C(this._events):[]}},{}],5:[function(e,n){n.exports=function(){if("undefined"==typeof globalThis)return null;var e={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}},{}],6:[function(n,t){var r=Math.round;function o(e){if(e+="",!(100<e.length)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();return"years"===n||"year"===n||"yrs"===n||"yr"===n||"y"===n?31557600000*r:"weeks"===n||"week"===n||"w"===n?604800000*r:"days"===n||"day"===n||"d"===n?86400000*r:"hours"===n||"hour"===n||"hrs"===n||"hr"===n||"h"===n?3600000*r:"minutes"===n||"minute"===n||"mins"===n||"min"===n||"m"===n?60000*r:"seconds"===n||"second"===n||"secs"===n||"sec"===n||"s"===n?1000*r:"milliseconds"===n||"millisecond"===n||"msecs"===n||"msec"===n||"ms"===n?r:void 0}}}function i(n){var t=e(n);return 86400000<=t?r(n/86400000)+"d":3600000<=t?r(n/3600000)+"h":60000<=t?r(n/60000)+"m":1000<=t?r(n/1000)+"s":n+"ms"}function s(n){var t=e(n);return 86400000<=t?a(n,t,86400000,"day"):3600000<=t?a(n,t,3600000,"hour"):60000<=t?a(n,t,60000,"minute"):1000<=t?a(n,t,1000,"second"):n+" ms"}function a(e,t,o,n){return r(e/o)+" "+n+(t>=1.5*o?"s":"")}var c=24*(60*60000);t.exports=function(e,n){n=n||{};var t=typeof e;if("string"==t&&0<e.length)return o(e);if("number"===t&&isFinite(e))return n.long?s(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],7:[function(e,n){function t(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(n){if(l===setTimeout)return setTimeout(n,0);if((l===t||!l)&&setTimeout)return l=setTimeout,setTimeout(n,0);try{return l(n,0)}catch(t){try{return l.call(null,n,0)}catch(t){return l.call(this,n,0)}}}function i(n){if(p===clearTimeout)return clearTimeout(n);if((p===r||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(n);try{return p(n)}catch(t){try{return p.call(null,n)}catch(t){return p.call(this,n)}}}function s(){m&&_&&(m=!1,_.length?g=_.concat(g):C=-1,g.length&&a())}function a(){if(!m){var e=o(s);m=!0;for(var n=g.length;n;){for(_=g,g=[];++C<n;)_&&_[C].run();C=-1,n=g.length}_=null,m=!1,i(e)}}function d(e,n){this.fun=e,this.array=n}function c(){}var l,p,u=n.exports={};(function(){try{l="function"==typeof setTimeout?setTimeout:t}catch(n){l=t}try{p="function"==typeof clearTimeout?clearTimeout:r}catch(n){p=r}})();var _,g=[],m=!1,C=-1;u.nextTick=function(e){var n=Array(arguments.length-1);if(1<arguments.length)for(var t=1;t<arguments.length;t++)n[t-1]=arguments[t];g.push(new d(e,n)),1!==g.length||m||o(a)},d.prototype.run=function(){this.fun.apply(null,this.array)},u.title="browser",u.browser=!0,u.env={},u.argv=[],u.version="",u.versions={},u.on=c,u.addListener=c,u.once=c,u.off=c,u.removeListener=c,u.removeAllListeners=c,u.emit=c,u.prependListener=c,u.prependOnceListener=c,u.listeners=function(e){return[]},u.binding=function(e){throw new Error("process.binding is not supported")},u.cwd=function(){return"/"},u.chdir=function(e){throw new Error("process.chdir is not supported")},u.umask=function(){return 0}},{}],8:[function(e,n,t){(function(e){(function(){/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let t;n.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"==typeof window?e:window):e=>(t||(t=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0))}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],9:[function(e,n,t){"use strict";function r(e){return e||(e={}),{length:e.length||8,numeric:"boolean"!=typeof e.numeric||e.numeric,letters:"boolean"!=typeof e.letters||e.letters,special:"boolean"==typeof e.special&&e.special,exclude:Array.isArray(e.exclude)?e.exclude:[]}}function o(e){var n="";e.numeric&&(n+="0123456789"),e.letters&&(n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"),e.special&&(n+="!$%^&*()_+|~-=`{}[]:;<>?,./");for(var t=0;t<=e.exclude.length;t++)n=n.replace(e.exclude[t],"");return n}var i="0123456789",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",a="!$%^&*()_+|~-=`{}[]:;<>?,./";n.exports=function n(e){e=r(e);var t,s,a="",d=e.length,c=e.exclude,l=o(e);for(t=1;t<=d;t++)a+=l.substring(s=Math.floor(Math.random()*l.length),s+1);return a}},{}],"/":[function(e,n,t){function r(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}function o(e){console.warn(e)}/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const i=e("debug")("simple-peer"),s=e("get-browser-rtc"),a=e("random-string"),d=e("queue-microtask"),{EventEmitter:c}=e("events"),l=e("err-code"),p=65536,u=5000,_=5000;class g extends c{constructor(e){if(e=Object.assign({allowHalfOpen:!1},e),super(e),this.id=e.id||a({length:20}),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||a({length:20}):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||g.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},g.config,e.config),this.proprietaryConstraints=Object.assign({},g.proprietaryConstraints,e.proprietaryConstraints),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||u,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:s(),!this._wrtc)if("undefined"==typeof window)throw l(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT");else throw l(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config,this.proprietaryConstraints)}catch(e){return void this.destroy(l(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(e=>{this.destroy(l(e,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach(e=>{this.addStream(e)}),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw l(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(n){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(e=>{this.destroy(l(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(l(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const n=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(n).catch(e=>{!n.address||n.address.endsWith(".local")?o("Ignoring unsupported ICE candidate."):this.destroy(l(e,"ERR_ADD_ICE_CANDIDATE"))})}send(e){if(!this.destroying){if(this.destroyed)throw l(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}addTransceiver(e,n){if(!this.destroying){if(this.destroyed)throw l(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,n),this._needsNegotiation()}catch(e){this.destroy(l(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:n}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw l(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach(n=>{this.addTrack(n,e)})}}addTrack(e,n){if(this.destroying)return;if(this.destroyed)throw l(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const t=this._senderMap.get(e)||new Map;let r=t.get(n);if(!r)r=this._pc.addTrack(e,n),t.set(n,r),this._senderMap.set(e,t),this._needsNegotiation();else if(r.removed)throw l(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED");else throw l(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(e,n,t){if(this.destroying)return;if(this.destroyed)throw l(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const r=this._senderMap.get(e),o=r?r.get(t):null;if(!o)throw l(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");n&&this._senderMap.set(n,r),null==o.replaceTrack?this.destroy(l(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):o.replaceTrack(n)}removeTrack(e,n){if(this.destroying)return;if(this.destroyed)throw l(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const t=this._senderMap.get(e),r=t?t.get(n):null;if(!r)throw l(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(r):this.destroy(l(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw l(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach(n=>{this.removeTrack(n,e)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,d(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw l(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this._destroy(e,()=>{})}_destroy(e,n){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",e&&(e.message||e)),d(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",e&&(e.message||e)),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),n()}))}_setupData(e){if(!e.channel)return this.destroy(l(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=p),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const n=e.error instanceof Error?e.error:new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.destroy(l(n,"ERR_DATA_CHANNEL"))};let n=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(n&&this._onChannelClose(),n=!0):n=!1},_)}_read(){}_write(e,n,t){if(this.destroyed)return t(l(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(l(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>p?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=t):t(null)}else this._debug("write before connect"),this._chunk=e,this._cb=t}_onFinish(){if(!this.destroyed){const e=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?e():this.once("connect",e)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=r(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const n=()=>{if(!this.destroyed){const n=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:n.type,sdp:n.sdp})}},t=()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?n():this.once("_iceComplete",n))},o=e=>{this.destroy(l(e,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(e).then(t).catch(o)}).catch(e=>{this.destroy(l(e,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=r(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const n=()=>{if(!this.destroyed){const n=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:n.type,sdp:n.sdp}),this.initiator||this._requestMissingTransceivers()}},t=()=>{this.destroyed||(this.trickle||this._iceComplete?n():this.once("_iceComplete",n))},o=e=>{this.destroy(l(e,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(e).then(t).catch(o)}).catch(e=>{this.destroy(l(e,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(l(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,n=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,n),this.emit("iceStateChange",e,n),("connected"===e||"completed"===e)&&(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(l(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(l(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const n=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(n=>{Object.assign(e,n)}),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(t=>{const r=[];t.forEach(e=>{r.push(n(e))}),e(null,r)},n=>e(n)):0<this._pc.getStats.length?this._pc.getStats(t=>{if(this.destroyed)return;const r=[];t.result().forEach(e=>{const t={};e.names().forEach(n=>{t[n]=e.stat(n)}),t.id=e.id,t.type=e.type,t.timestamp=e.timestamp,r.push(n(t))}),e(null,r)},n=>e(n)):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats((n,t)=>{if(this.destroyed)return;n&&(t=[]);const r={},o={},i={};let s=!1;t.forEach(e=>{("remotecandidate"===e.type||"remote-candidate"===e.type)&&(r[e.id]=e),("localcandidate"===e.type||"local-candidate"===e.type)&&(o[e.id]=e),("candidatepair"===e.type||"candidate-pair"===e.type)&&(i[e.id]=e)});const a=e=>{s=!0;let n=o[e.localCandidateId];n&&(n.ip||n.address)?(this.localAddress=n.ip||n.address,this.localPort=+n.port):n&&n.ipAddress?(this.localAddress=n.ipAddress,this.localPort=+n.portNumber):"string"==typeof e.googLocalAddress&&(n=e.googLocalAddress.split(":"),this.localAddress=n[0],this.localPort=+n[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let t=r[e.remoteCandidateId];t&&(t.ip||t.address)?(this.remoteAddress=t.ip||t.address,this.remotePort=+t.port):t&&t.ipAddress?(this.remoteAddress=t.ipAddress,this.remotePort=+t.portNumber):"string"==typeof e.googRemoteAddress&&(t=e.googRemoteAddress.split(":"),this.remoteAddress=t[0],this.remotePort=+t[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(t.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(i[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)}),!s&&(!Object.keys(i).length||Object.keys(o).length))return void setTimeout(e,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(l(e,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};e()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>p)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){this.destroyed||this.emit("data",e.data)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){if(this.destroyed)return;const{track:n,receiver:t,streams:r}=e;r.forEach(e=>{this._debug("on track"),this.emit("track",n,e,t),this._remoteTracks.push({track:n,stream:e}),this._remoteStreams.some(n=>n.id===e.id)||(this._remoteStreams.push(e),d(()=>{this._debug("on stream"),this.emit("stream",e,t)}))})}_debug(){const e=[].slice.call(arguments);e[0]="["+this.id+"] "+e[0],i.apply(null,e)}}g.WEBRTC_SUPPORT=!!s(),g.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},g.channelConfig={},g.proprietaryConstraints={},n.exports=g},{debug:1,"err-code":3,events:4,"get-browser-rtc":5,"queue-microtask":8,"random-string":9}]},{},[])("/")});