@testrtc/watchrtc-sdk
Advanced tools
Comparing version 1.28.9 to 1.29.0
import "./types"; | ||
import { IWatchRTCConfiguration, Rate } from "./sdk"; | ||
import { IWatchRTCConfiguration } from "./interfaces"; | ||
/** | ||
* Initialize SDK. Can be called multiple times but it will be initialized only at the first time. | ||
* Use 'start' function after if you don't have rtcRoomId and rtcPeerId yet. | ||
* @param watchrtc | ||
* @param prefixesToWrap | ||
*/ | ||
export declare const init: (watchrtcConfig?: IWatchRTCConfiguration | undefined) => void; | ||
export declare const setUserRating: (rate: Rate, reason?: string | undefined) => void; | ||
export declare const setConfig: (watchrtcConfig: IWatchRTCConfiguration) => void; | ||
/** | ||
* Add tags for peer session | ||
* @param rtcTags[] | ||
*/ | ||
export declare const addTags: (rtcTags: string[]) => void; | ||
export declare const disableDataCollection: () => void; | ||
export declare const enableDataCollection: () => void; | ||
declare const _default: { | ||
init: (watchrtcConfig?: IWatchRTCConfiguration | undefined) => void; | ||
addTags: (rtcTags: string[]) => void; | ||
setConfig: (watchrtcConfig: IWatchRTCConfiguration) => void; | ||
setUserRating: (rate: Rate, reason?: string | undefined) => void; | ||
disableDataCollection: () => void; | ||
enableDataCollection: () => void; | ||
}; | ||
export default _default; |
@@ -1,2 +0,2 @@ | ||
!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.watchRTC=n():e.watchRTC=n()}(self,(function(){return(e={607:(e,n,t)=>{"use strict";n.v6=n.IO=n.S1=void 0,t(699);var o=t(231);n.S1=function(e){o.initSDK(e,["","webkit","moz"])},n.IO=function(e,n){o.setUserRating(e,n)},n.v6=function(e){o.setConfig(e)},n.default={init:n.S1,setConfig:n.v6,setUserRating:n.IO}},231:function(e,n,t){"use strict";var o=this&&this.__assign||function(){return(o=Object.assign||function(e){for(var n,t=1,o=arguments.length;t<o;t++)for(var i in n=arguments[t])Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i]);return e}).apply(this,arguments)},i=this&&this.__spreadArrays||function(){for(var e=0,n=0,t=arguments.length;n<t;n++)e+=arguments[n].length;var o=Array(e),i=0;for(n=0;n<t;n++)for(var r=arguments[n],a=0,c=r.length;a<c;a++,i++)o[i]=r[a];return o};Object.defineProperty(n,"__esModule",{value:!0}),n.setUserRating=n.initSDK=n.setConfig=void 0;var r=t(85),a=t(412),c=t(593),s=function(e,n){e=e||{},n=n||{},n=JSON.parse(JSON.stringify(n)),Object.keys(n).forEach((function(t){var o=n[t];delete o.id,e[t]&&Object.keys(o).forEach((function(i){o[i]===e[t][i]&&delete n[t][i],(0===Object.keys(o).length||1===Object.keys(o).length&&o.timestamp)&&delete n[t]}))}));var t=-1/0;return Object.keys(n).forEach((function(e){var o=n[e];o.timestamp>t&&(t=o.timestamp)})),Object.keys(n).forEach((function(e){var o=n[e];o.timestamp===t&&(o.timestamp=0)})),n.timestamp=t,n},l=function(e){return{id:e.id,tracks:e.getTracks().map((function(e){return{id:e.id,kind:e.kind,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}}))}},u=null;n.setConfig=function(e){u=e},n.initSDK=function(e,n){if(!window.watchRTCInitialized){window.watchRTCInitialized=!0;var t,f=0,d=0,p=!1,g=new r.default(e.debug),h=g.trace,v={},m=!!window.mozRTCPeerConnection,y=!!window.RTCIceGatherer,w=(!m&&window.RTCPeerConnection&&window.navigator.webkitGetUserMedia,function(){return Object.keys(v).filter((function(e){return v[e].validConnection})).length}),_=function(){var e,n,r,s,l,f=w();if(f>0&&!p){p=!0;var m=(l=u)?l.rtcApiKey?l.rtcRoomId?!!l.rtcPeerId||(console.info.apply(console,i(c.logPrefix("error"),["config.rtcPeerId is required."])),!1):(console.info.apply(console,i(c.logPrefix("error"),["config.rtcRoomId is required."])),!1):(console.info.apply(console,i(c.logPrefix("error"),["config.rtcApiKey is required."])),!1):(console.info.apply(console,i(c.logPrefix("error"),["config is required."])),!1),_=Object.keys(v)[f-1];if(m){u.rtcTags&&(Array.isArray(u.rtcTags)?u.rtcTags.some((function(e){return e.includes(",")}))&&console.info.apply(console,i(c.logPrefix("info"),["To apply multiple tags please use an array and not comma separated values."])):(console.info.apply(console,i(c.logPrefix("info"),["config.rtcTags must be an array."])),u.rtcTags=void 0));var C=(e=u.rtcApiKey,n=u.proxyUrl||u.wsUrl,r="wss://watchrtc.testrtc.com",s=e.split(":"),-1!==e.indexOf("local")?{url:n||"ws://localhost:9101",apiKey:s[1]}:-1!==e.indexOf("staging")?{url:n||"wss://watchrtc-staging2.testrtc.com",apiKey:s[1]}:-1!==e.indexOf("production")?{url:n||r,apiKey:s[1]}:{url:n||r,apiKey:s[0]});d=Date.now(),g.connect(C.url+"?apiKey="+C.apiKey+"×tamp="+Date.now(),(function(e){console.info.apply(console,i(c.logPrefix("info"),["Connection established. watchRTCConnectionId: "+e.connectionId+" sdkVersion:"+a.default])),h("watchrtc",_,o(o(o({},u),e),{sdkVersion:a.default})),y||(window.clearInterval(t),t=window.setInterval((function(){0===w()?d&&d+2e4<Date.now()&&(p=!1,window.clearInterval(t),g.close(),console.info.apply(console,i(c.logPrefix("info"),["Last connection closed. watchRTCConnectionId: "+e.connectionId+" sdkVersion: "+a.default]))):(d=Date.now(),Object.values(v).forEach((function(e){"closed"!==e.pc.signalingState&&b(e)})))}),e.interval))}),(function(){p=!1,d=0}))}}},b=function(e){if(e){var n=e.id,t=e.pc,o=e.prev;t.getStats(null).then((function(t){var i=function(e){if(!e.entries)return e;var n={};return e.forEach((function(e,t){n[t]=e})),n}(t),r=JSON.parse(JSON.stringify(i)),a=s(o,i);null!==(null==a?void 0:a.timestamp)&&(null==a?void 0:a.timestamp)!==-1/0&&h("getstats",n,s(e.prev,i)),e.prev=r}))}};if(n.forEach((function(n){if(window[n+"RTCPeerConnection"]&&("webkit"!==n||!y)){var t=window[n+"RTCPeerConnection"],o=function(n,o){(null==u?void 0:u.debug)&&console.info.apply(console,i(c.logPrefix("info"),["new RTCPeerConnection called.",{config:n,constraints:o}]));var r=new t(n,o),a="PC_"+f++;return r.__rtcStatsId=a,v[a]={id:a,pc:r,validConnection:!1},u=u||e||(null==n?void 0:n.watchrtc),n||(n={nullConfig:!0}),((n=JSON.parse(JSON.stringify(n)))&&n.iceServers||[]).forEach((function(e){delete e.credential})),(null==n?void 0:n.watchrtc)&&delete n.watchrtc,n.browserType=m?"moz":y?"edge":"webkit",h("create",a,n),o&&h("constraints",a,o),r.addEventListener("icecandidate",(function(e){h("onicecandidate",a,e.candidate)})),r.addEventListener("addstream",(function(e){h("onaddstream",a,e.stream.id+" "+e.stream.getTracks().map((function(e){return e.kind+":"+e.id})))})),r.addEventListener("track",(function(e){h("ontrack",a,e.track.kind+":"+e.track.id+" "+e.streams.map((function(e){return"stream:"+e.id})))})),r.addEventListener("removestream",(function(e){h("onremovestream",a,e.stream.id+" "+e.stream.getTracks().map((function(e){return e.kind+":"+e.id})))})),r.addEventListener("signalingstatechange",(function(){v[a]&&!v[a].validConnection&&(v[a].validConnection=!0,setTimeout(_,5e3)),h("onsignalingstatechange",a,r.signalingState)})),r.addEventListener("iceconnectionstatechange",(function(){h("oniceconnectionstatechange",a,r.iceConnectionState)})),r.addEventListener("icegatheringstatechange",(function(){h("onicegatheringstatechange",a,r.iceGatheringState)})),r.addEventListener("connectionstatechange",(function(){h("onconnectionstatechange",a,r.connectionState)})),r.addEventListener("negotiationneeded",(function(){h("onnegotiationneeded",a,void 0)})),r.addEventListener("datachannel",(function(e){h("ondatachannel",a,[e.channel.id,e.channel.label])})),y||r.addEventListener("iceconnectionstatechange",(function(){"connected"===r.iceConnectionState&&b(v[a])})),r};["createDataChannel"].forEach((function(e){var n=t.prototype[e];n&&(t.prototype[e]=function(){return h(e,this.__rtcStatsId,arguments),n.apply(this,arguments)})})),["close"].forEach((function(e){var n=t.prototype[e];n&&(t.prototype[e]=function(){return h(e,this.__rtcStatsId,arguments),delete v[this.__rtcStatsId],n.apply(this,arguments)})})),["addStream","removeStream"].forEach((function(e){var n=t.prototype[e];n&&(t.prototype[e]=function(){var t=arguments[0],o=t.getTracks().map((function(e){return e.kind+":"+e.id})).join(",");return h(e,this.__rtcStatsId,t.id+" "+o),n.apply(this,arguments)})})),["addTrack"].forEach((function(e){var n=t.prototype[e];n&&(t.prototype[e]=function(){var t=arguments[0],o=[].slice.call(arguments,1);return h(e,this.__rtcStatsId,t.kind+":"+t.id+" "+(o.map((function(e){return"stream:"+e.id})).join(";")||"-")),n.apply(this,arguments)})})),["removeTrack"].forEach((function(e){var n=t.prototype[e];n&&(t.prototype[e]=function(){var t=arguments[0].track;return h(e,this.__rtcStatsId,t?t.kind+":"+t.id:"null"),n.apply(this,arguments)})})),["createOffer","createAnswer"].forEach((function(e){var n=t.prototype[e];n&&(t.prototype[e]=function(){var t,o=this.__rtcStatsId,i=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?t=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(t=arguments[2]),h(e,this.__rtcStatsId,t),n.apply(this,t?[t]:void 0).then((function(n){if(h(e+"OnSuccess",o,n),!(i.length>0&&"function"==typeof i[0]))return n;i[0].apply(null,[n])}),(function(n){if(h(e+"OnFailure",o,n.toString()),!(i.length>1&&"function"==typeof i[1]))throw n;i[1].apply(null,[n])}))})})),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(e){var n=t.prototype[e];n&&(t.prototype[e]=function(){var t=this.__rtcStatsId,o=arguments;return h(e,this.__rtcStatsId,o[0]),n.apply(this,[o[0]]).then((function(){h(e+"OnSuccess",t,void 0),o.length>=2&&"function"==typeof o[1]&&o[1].apply(null,[])}),(function(n){if(h(e+"OnFailure",t,n.toString()),!(o.length>=3&&"function"==typeof o[2]))throw n;o[2].apply(null,[n])}))})})),t.generateCertificate&&Object.defineProperty(o,"generateCertificate",{get:function(){return arguments.length?t.generateCertificate.apply(null,arguments):t.generateCertificate}}),window[n+"RTCPeerConnection"]=o,window[n+"RTCPeerConnection"].prototype=t.prototype}})),n.forEach((function(e){var n=e+(e.length?"GetUserMedia":"getUserMedia");if(navigator[n]){var t=navigator[n].bind(navigator);navigator[n]=function(){h("getUserMedia",null,arguments[0]);var e=arguments[1],n=arguments[2];t(arguments[0],(function(n){h("getUserMediaOnSuccess",null,l(n)),e&&e(n)}),(function(e){h("getUserMediaOnFailure",null,e.name),n&&n(e)}))}.bind(navigator)}})),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var C=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(){return h("navigator.mediaDevices.getUserMedia",null,arguments[0]),C.apply(navigator.mediaDevices,arguments).then((function(e){return h("navigator.mediaDevices.getUserMediaOnSuccess",null,l(e)),e}),(function(e){return h("navigator.mediaDevices.getUserMediaOnFailure",null,e.name),Promise.reject(e)}))}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var O=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getDisplayMedia=function(){return h("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),O.apply(navigator.mediaDevices,arguments).then((function(e){return h("navigator.mediaDevices.getDisplayMediaOnSuccess",null,l(e)),e}),(function(e){return h("navigator.mediaDevices.getDisplayMediaOnFailure",null,e.name),Promise.reject(e)}))}.bind(navigator.mediaDevices)}}},n.setUserRating=function(e,n){var t;e&&(r.default._instance&&(null===(t=r.default._instance.connection)||void 0===t?void 0:t.readyState)===WebSocket.OPEN?r.default._instance.trace("userRating","",{rate:e,rateReason:n}):console.info.apply(console,i(c.logPrefix("error"),["Please set user rating before websocket connection is closed."])))}},699:(e,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0})},593:(e,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.logPrefix=void 0,n.logPrefix=function(e){return void 0===e&&(e="info"),"error"===e?["%cwatchRTC %cERROR","background: gold; color: black; padding: 2px 0.5em; border-radius: 0.5em;","background: red; color: white; padding: 2px 0.5em; border-radius: 0.5em;"]:["%cwatchRTC","background: gold; color: black; padding: 2px 0.5em; border-radius: 0.5em;"]}},412:(e,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default="1.28.9"},85:function(e,n,t){"use strict";var o=this&&this.__spreadArrays||function(){for(var e=0,n=0,t=arguments.length;n<t;n++)e+=arguments[n].length;var o=Array(e),i=0;for(n=0;n<t;n++)for(var r=arguments[n],a=0,c=r.length;a<c;a++,i++)o[i]=r[a];return o};Object.defineProperty(n,"__esModule",{value:!0});var i=t(593),r=t(354),a=function(){function e(n){this.connection=null,this.buffer=[],this.sendInterval=1,this.onClose=function(){},this.debug=!1,e._instance?console.info.apply(console,o(i.logPrefix("info"),["WatchRTCSocket instance already created"])):(e._instance=this,this.debug=!!n)}return e.prototype.connect=function(n,t,r){e._instance.connection&&e._instance.connection.close(),e._instance.connection=new WebSocket(n,"2.0"),e._instance.connection.onopen=function(e){},e._instance.connection.onclose=function(e){};var a=e._instance;e._instance.connection.onmessage=function(n){var c;try{var s=JSON.parse(n.data);s.error?(null===(c=null==a?void 0:a.connection)||void 0===c||c.close(),a.connection=null,console.info.apply(console,o(i.logPrefix("error"),["\n"+s.error])),r(s.error)):(s.sendInterval&&(e._instance.sendInterval=s.sendInterval),t(s))}catch(e){console.info.apply(console,o(i.logPrefix("error"),[{err:e.stack}])),r(e.message)}},e._instance.connection.onerror=function(e){console.info.apply(console,o(i.logPrefix("error"),["\n",e])),r(e)}},e.prototype.trace=function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var a=Array.prototype.slice.call(n);if(a.push(Date.now()),a[1]instanceof RTCPeerConnection&&(a[1]=a[1].__rtcStatsId),e._instance.connection){if(e._instance.connection.readyState===WebSocket.OPEN&&(e._instance.buffer.push(a),e._instance.buffer.length>=e._instance.sendInterval)){var c=JSON.stringify(e._instance.buffer),s=r.compressToEncodedURIComponent(c);e._instance.debug&&(console.log.apply(console,o(i.logPrefix("info"),["lines: "+c.length])),console.log.apply(console,o(i.logPrefix("info"),["compressedMessage: "+s.length]))),e._instance.buffer=[],e._instance.connection.send(s)}}else{if(e._instance.buffer.length>1e3)return;e._instance.buffer.push(a)}},e.prototype.close=function(){e._instance.buffer=[],e._instance.connection&&(e._instance.connection.close(),e._instance.onClose(),e._instance.connection=null)},e}();n.default=a},354:(e,n,t)=>{var o,i=function(){function e(e,n){if(!i[e]){i[e]={};for(var t=0;t<e.length;t++)i[e][e.charAt(t)]=t}return i[e][n]}var n=String.fromCharCode,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",i={},r={compressToBase64:function(e){if(null==e)return"";var n=r._compress(e,6,(function(e){return t.charAt(e)}));switch(n.length%4){default:case 0:return n;case 1:return n+"===";case 2:return n+"==";case 3:return n+"="}},decompressFromBase64:function(n){return null==n?"":""==n?null:r._decompress(n.length,32,(function(o){return e(t,n.charAt(o))}))},compressToUTF16:function(e){return null==e?"":r._compress(e,15,(function(e){return n(e+32)}))+" "},decompressFromUTF16:function(e){return null==e?"":""==e?null:r._decompress(e.length,16384,(function(n){return e.charCodeAt(n)-32}))},compressToUint8Array:function(e){for(var n=r.compress(e),t=new Uint8Array(2*n.length),o=0,i=n.length;i>o;o++){var a=n.charCodeAt(o);t[2*o]=a>>>8,t[2*o+1]=a%256}return t},decompressFromUint8Array:function(e){if(null==e)return r.decompress(e);for(var t=new Array(e.length/2),o=0,i=t.length;i>o;o++)t[o]=256*e[2*o]+e[2*o+1];var a=[];return t.forEach((function(e){a.push(n(e))})),r.decompress(a.join(""))},compressToEncodedURIComponent:function(e){return null==e?"":r._compress(e,6,(function(e){return o.charAt(e)}))},decompressFromEncodedURIComponent:function(n){return null==n?"":""==n?null:(n=n.replace(/ /g,"+"),r._decompress(n.length,32,(function(t){return e(o,n.charAt(t))})))},compress:function(e){return r._compress(e,16,(function(e){return n(e)}))},_compress:function(e,n,t){if(null==e)return"";var o,i,r,a={},c={},s="",l="",u="",f=2,d=3,p=2,g=[],h=0,v=0;for(r=0;r<e.length;r+=1)if(s=e.charAt(r),Object.prototype.hasOwnProperty.call(a,s)||(a[s]=d++,c[s]=!0),l=u+s,Object.prototype.hasOwnProperty.call(a,l))u=l;else{if(Object.prototype.hasOwnProperty.call(c,u)){if(u.charCodeAt(0)<256){for(o=0;p>o;o++)h<<=1,v==n-1?(v=0,g.push(t(h)),h=0):v++;for(i=u.charCodeAt(0),o=0;8>o;o++)h=h<<1|1&i,v==n-1?(v=0,g.push(t(h)),h=0):v++,i>>=1}else{for(i=1,o=0;p>o;o++)h=h<<1|i,v==n-1?(v=0,g.push(t(h)),h=0):v++,i=0;for(i=u.charCodeAt(0),o=0;16>o;o++)h=h<<1|1&i,v==n-1?(v=0,g.push(t(h)),h=0):v++,i>>=1}0==--f&&(f=Math.pow(2,p),p++),delete c[u]}else for(i=a[u],o=0;p>o;o++)h=h<<1|1&i,v==n-1?(v=0,g.push(t(h)),h=0):v++,i>>=1;0==--f&&(f=Math.pow(2,p),p++),a[l]=d++,u=String(s)}if(""!==u){if(Object.prototype.hasOwnProperty.call(c,u)){if(u.charCodeAt(0)<256){for(o=0;p>o;o++)h<<=1,v==n-1?(v=0,g.push(t(h)),h=0):v++;for(i=u.charCodeAt(0),o=0;8>o;o++)h=h<<1|1&i,v==n-1?(v=0,g.push(t(h)),h=0):v++,i>>=1}else{for(i=1,o=0;p>o;o++)h=h<<1|i,v==n-1?(v=0,g.push(t(h)),h=0):v++,i=0;for(i=u.charCodeAt(0),o=0;16>o;o++)h=h<<1|1&i,v==n-1?(v=0,g.push(t(h)),h=0):v++,i>>=1}0==--f&&(f=Math.pow(2,p),p++),delete c[u]}else for(i=a[u],o=0;p>o;o++)h=h<<1|1&i,v==n-1?(v=0,g.push(t(h)),h=0):v++,i>>=1;0==--f&&(f=Math.pow(2,p),p++)}for(i=2,o=0;p>o;o++)h=h<<1|1&i,v==n-1?(v=0,g.push(t(h)),h=0):v++,i>>=1;for(;;){if(h<<=1,v==n-1){g.push(t(h));break}v++}return g.join("")},decompress:function(e){return null==e?"":""==e?null:r._decompress(e.length,32768,(function(n){return e.charCodeAt(n)}))},_decompress:function(e,t,o){var i,r,a,c,s,l,u,f=[],d=4,p=4,g=3,h="",v=[],m={val:o(0),position:t,index:1};for(i=0;3>i;i+=1)f[i]=i;for(a=0,s=Math.pow(2,2),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;switch(a){case 0:for(a=0,s=Math.pow(2,8),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;u=n(a);break;case 1:for(a=0,s=Math.pow(2,16),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;u=n(a);break;case 2:return""}for(f[3]=u,r=u,v.push(u);;){if(m.index>e)return"";for(a=0,s=Math.pow(2,g),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;switch(u=a){case 0:for(a=0,s=Math.pow(2,8),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;f[p++]=n(a),u=p-1,d--;break;case 1:for(a=0,s=Math.pow(2,16),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;f[p++]=n(a),u=p-1,d--;break;case 2:return v.join("")}if(0==d&&(d=Math.pow(2,g),g++),f[u])h=f[u];else{if(u!==p)return null;h=r+r.charAt(0)}v.push(h),f[p++]=r+h.charAt(0),r=h,0==--d&&(d=Math.pow(2,g),g++)}}};return r}();void 0===(o=function(){return i}.call(n,t,n,e))||(e.exports=o)}},n={},function t(o){if(n[o])return n[o].exports;var i=n[o]={exports:{}};return e[o].call(i.exports,i,i.exports,t),i.exports}(607)).default;var e,n})); | ||
!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.watchRTC=n():e.watchRTC=n()}(self,(function(){return(e={607:(e,n,t)=>{"use strict";n.xt=n.Zt=n.zl=n.v6=n.S1=void 0,t(699);var o=t(231);n.S1=function(e){o.initSDK(e,["","webkit","moz"])},n.v6=function(e){o.setConfig(e)},n.zl=function(e){o.addTags(e)},n.Zt=function(){o.disableDataCollection()},n.xt=function(){o.enableDataCollection()},n.default={init:n.S1,addTags:n.zl,setConfig:n.v6,disableDataCollection:n.Zt,enableDataCollection:n.xt}},231:function(e,n,t){"use strict";var o=this&&this.__assign||function(){return(o=Object.assign||function(e){for(var n,t=1,o=arguments.length;t<o;t++)for(var i in n=arguments[t])Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i]);return e}).apply(this,arguments)},i=this&&this.__spreadArrays||function(){for(var e=0,n=0,t=arguments.length;n<t;n++)e+=arguments[n].length;var o=Array(e),i=0;for(n=0;n<t;n++)for(var r=arguments[n],a=0,c=r.length;a<c;a++,i++)o[i]=r[a];return o};Object.defineProperty(n,"__esModule",{value:!0}),n.enableDataCollection=n.disableDataCollection=n.addTags=n.setConfig=n.initSDK=void 0;var r,a,c=t(85),s=t(593),l=t(412),d=!!window.mozRTCPeerConnection,u=!!window.RTCIceGatherer,f=(!d&&window.RTCPeerConnection&&window.navigator.webkitGetUserMedia,{}),p=null,g=null,v=0,h=!1,m=function(){var e=s.countOfValidConnections(f);if(e>0&&!h){h=!0;var n=s.validateConfig(p),t=Object.keys(f)[e-1];if(n){p.rtcTags&&(Array.isArray(p.rtcTags)?p.rtcTags.some((function(e){return e.includes(",")}))&&console.info.apply(console,i(s.logPrefix("info"),["To apply multiple tags please use an array and not comma separated values."])):(console.info.apply(console,i(s.logPrefix("info"),["config.rtcTags must be an array."])),p.rtcTags=void 0));var c=!!p.rtcToken,d=s.getWSConnectionData(c?p.rtcToken:p.rtcApiKey,p.proxyUrl||p.wsUrl);v=Date.now(),null==g||g.connect(d.url+"?"+(c?"token":"apiKey")+"="+d.key+"×tamp="+Date.now(),(function(e){console.info.apply(console,i(s.logPrefix("info"),["Connection established. watchRTCConnectionId: "+e.connectionId+" sdkVersion:"+l.default])),r("watchrtc",t,o(o(o({},p),e),{sdkVersion:l.default})),u||(window.clearInterval(a),a=window.setInterval((function(){0===s.countOfValidConnections(f)?v&&v+2e4<Date.now()&&(h=!1,window.clearInterval(a),null==g||g.close(),console.info.apply(console,i(s.logPrefix("info"),["Last connection closed. watchRTCConnectionId: "+e.connectionId+" sdkVersion: "+l.default]))):(v=Date.now(),Object.values(f).forEach((function(e){"closed"!==e.pc.signalingState&&y(e)})))}),e.interval))}),(function(){h=!1,v=0}))}else h=!1}},y=function(e){if(e){var n=e.id,t=e.pc,o=e.prev;t.getStats(null).then((function(t){var i=s.map2obj(t),a=JSON.parse(JSON.stringify(i)),c=s.deltaCompression(o,i);null!==(null==c?void 0:c.timestamp)&&(null==c?void 0:c.timestamp)!==-1/0&&r("getstats",n,s.deltaCompression(e.prev,i)),e.prev=a}))}};n.initSDK=function(e,n){if(!window.watchRTCInitialized){window.watchRTCInitialized=!0;var t=0;if(g=new c.default({debug:null==e?void 0:e.debug}),r=g.trace,n.forEach((function(n){if(window[n+"RTCPeerConnection"]&&("webkit"!==n||!u)){var a=window[n+"RTCPeerConnection"],c=function(n,c){(null==(p=o(o({},e),null==n?void 0:n.watchrtc))?void 0:p.debug)&&console.info.apply(console,i(s.logPrefix("info"),["new RTCPeerConnection called.",{config:n,constraints:c}]));var l=new a(n,c),g="PC_"+t++;return l.__rtcStatsId=g,f[g]={id:g,pc:l,validConnection:!1},n||(n={nullConfig:!0}),((n=JSON.parse(JSON.stringify(n)))&&n.iceServers||[]).forEach((function(e){delete e.credential})),(null==n?void 0:n.watchrtc)&&delete n.watchrtc,n.browserType=d?"moz":u?"edge":"webkit",r("create",g,n),c&&r("constraints",g,c),l.addEventListener("icecandidate",(function(e){r("onicecandidate",g,e.candidate)})),l.addEventListener("addstream",(function(e){r("onaddstream",g,e.stream.id+" "+e.stream.getTracks().map((function(e){return e.kind+":"+e.id})))})),l.addEventListener("track",(function(e){r("ontrack",g,e.track.kind+":"+e.track.id+" "+e.streams.map((function(e){return"stream:"+e.id})))})),l.addEventListener("removestream",(function(e){r("onremovestream",g,e.stream.id+" "+e.stream.getTracks().map((function(e){return e.kind+":"+e.id})))})),l.addEventListener("signalingstatechange",(function(){f[g]&&!f[g].validConnection&&(f[g].validConnection=!0,setTimeout(m,5e3)),r("onsignalingstatechange",g,l.signalingState)})),l.addEventListener("iceconnectionstatechange",(function(){r("oniceconnectionstatechange",g,l.iceConnectionState)})),l.addEventListener("icegatheringstatechange",(function(){r("onicegatheringstatechange",g,l.iceGatheringState)})),l.addEventListener("connectionstatechange",(function(){r("onconnectionstatechange",g,l.connectionState)})),l.addEventListener("negotiationneeded",(function(){r("onnegotiationneeded",g,void 0)})),l.addEventListener("datachannel",(function(e){r("ondatachannel",g,[e.channel.id,e.channel.label])})),u||l.addEventListener("iceconnectionstatechange",(function(){"connected"===l.iceConnectionState&&y(f[g])})),l};["createDataChannel"].forEach((function(e){var n=a.prototype[e];n&&(a.prototype[e]=function(){return r(e,this.__rtcStatsId,arguments),n.apply(this,arguments)})})),["close"].forEach((function(e){var n=a.prototype[e];n&&(a.prototype[e]=function(){return r(e,this.__rtcStatsId,arguments),delete f[this.__rtcStatsId],n.apply(this,arguments)})})),["addStream","removeStream"].forEach((function(e){var n=a.prototype[e];n&&(a.prototype[e]=function(){var t=arguments[0],o=t.getTracks().map((function(e){return e.kind+":"+e.id})).join(",");return r(e,this.__rtcStatsId,t.id+" "+o),n.apply(this,arguments)})})),["addTrack"].forEach((function(e){var n=a.prototype[e];n&&(a.prototype[e]=function(){var t=arguments[0],o=[].slice.call(arguments,1);return r(e,this.__rtcStatsId,t.kind+":"+t.id+" "+(o.map((function(e){return"stream:"+e.id})).join(";")||"-")),n.apply(this,arguments)})})),["removeTrack"].forEach((function(e){var n=a.prototype[e];n&&(a.prototype[e]=function(){var t=arguments[0].track;return r(e,this.__rtcStatsId,t?t.kind+":"+t.id:"null"),n.apply(this,arguments)})})),["createOffer","createAnswer"].forEach((function(e){var n=a.prototype[e];n&&(a.prototype[e]=function(){var t,o=this.__rtcStatsId,i=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?t=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(t=arguments[2]),r(e,this.__rtcStatsId,t),n.apply(this,t?[t]:void 0).then((function(n){if(r(e+"OnSuccess",o,n),!(i.length>0&&"function"==typeof i[0]))return n;i[0].apply(null,[n])}),(function(n){if(r(e+"OnFailure",o,n.toString()),!(i.length>1&&"function"==typeof i[1]))throw n;i[1].apply(null,[n])}))})})),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(e){var n=a.prototype[e];n&&(a.prototype[e]=function(){var t=this.__rtcStatsId,o=arguments;return r(e,this.__rtcStatsId,o[0]),n.apply(this,[o[0]]).then((function(){r(e+"OnSuccess",t,void 0),o.length>=2&&"function"==typeof o[1]&&o[1].apply(null,[])}),(function(n){if(r(e+"OnFailure",t,n.toString()),!(o.length>=3&&"function"==typeof o[2]))throw n;o[2].apply(null,[n])}))})})),a.generateCertificate&&Object.defineProperty(c,"generateCertificate",{get:function(){return arguments.length?a.generateCertificate.apply(null,arguments):a.generateCertificate}}),window[n+"RTCPeerConnection"]=c,window[n+"RTCPeerConnection"].prototype=a.prototype}})),n.forEach((function(e){var n=e+(e.length?"GetUserMedia":"getUserMedia");if(navigator[n]){var t=navigator[n].bind(navigator);navigator[n]=function(){r("getUserMedia",null,arguments[0]);var e=arguments[1],n=arguments[2];t(arguments[0],(function(n){r("getUserMediaOnSuccess",null,s.dumpStream(n)),e&&e(n)}),(function(e){r("getUserMediaOnFailure",null,e.name),n&&n(e)}))}.bind(navigator)}})),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var a=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(){return r("navigator.mediaDevices.getUserMedia",null,arguments[0]),a.apply(navigator.mediaDevices,arguments).then((function(e){return r("navigator.mediaDevices.getUserMediaOnSuccess",null,s.dumpStream(e)),e}),(function(e){return r("navigator.mediaDevices.getUserMediaOnFailure",null,e.name),Promise.reject(e)}))}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var l=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getDisplayMedia=function(){return r("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),l.apply(navigator.mediaDevices,arguments).then((function(e){return r("navigator.mediaDevices.getDisplayMediaOnSuccess",null,s.dumpStream(e)),e}),(function(e){return r("navigator.mediaDevices.getDisplayMediaOnFailure",null,e.name),Promise.reject(e)}))}.bind(navigator.mediaDevices)}}},n.setConfig=function(e){window.watchRTCInitialized?(null==p?void 0:p.rtcRoomId)&&(null==p?void 0:p.rtcPeerId)?(null==p?void 0:p.debug)&&console.info.apply(console,i(s.logPrefix("info"),["Websocket started to send data. 'setConfig' function ignored"])):e.rtcRoomId&&e.rtcPeerId?(p=o(o({},p),e),m()):console.info.apply(console,i(s.logPrefix("error"),["rtcRoomId and rtcPeerId are required"])):console.info.apply(console,i(s.logPrefix("error"),["SDK is not initialized. Use 'init' function fisrt."]))},n.addTags=function(e){window.watchRTCInitialized?e&&Array.isArray(e)?r("addRtcTags",null,{rtcTags:e}):console.info.apply(console,i(s.logPrefix("error"),["addTags excepts only array of strings"])):console.info.apply(console,i(s.logPrefix("error"),["SDK is not initialized. Use 'init' function fisrt."]))},n.disableDataCollection=function(){window.watchRTCInitialized?null==g||g.disableDataCollection():console.info.apply(console,i(s.logPrefix("error"),["SDK is not initialized. Use 'init' function fisrt."]))},n.enableDataCollection=function(){window.watchRTCInitialized?null==g||g.enableDataCollection():console.info.apply(console,i(s.logPrefix("error"),["SDK is not initialized. Use 'init' function fisrt."]))}},699:(e,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0})},593:function(e,n){"use strict";var t=this&&this.__spreadArrays||function(){for(var e=0,n=0,t=arguments.length;n<t;n++)e+=arguments[n].length;var o=Array(e),i=0;for(n=0;n<t;n++)for(var r=arguments[n],a=0,c=r.length;a<c;a++,i++)o[i]=r[a];return o};Object.defineProperty(n,"__esModule",{value:!0}),n.countOfValidConnections=n.validateConfig=n.getWSConnectionData=n.dumpStream=n.map2obj=n.mangleChromeStats=n.deltaCompression=n.logPrefix=void 0,n.logPrefix=function(e){return void 0===e&&(e="info"),"error"===e?["%cwatchRTC %cERROR","background: gold; color: black; padding: 2px 0.5em; border-radius: 0.5em;","background: red; color: white; padding: 2px 0.5em; border-radius: 0.5em;"]:["%cwatchRTC","background: gold; color: black; padding: 2px 0.5em; border-radius: 0.5em;"]},n.deltaCompression=function(e,n){e=e||{},n=n||{},n=JSON.parse(JSON.stringify(n)),Object.keys(n).forEach((function(t){var o=n[t];delete o.id,e[t]&&Object.keys(o).forEach((function(i){o[i]===e[t][i]&&delete n[t][i],(0===Object.keys(o).length||1===Object.keys(o).length&&o.timestamp)&&delete n[t]}))}));var t=-1/0;return Object.keys(n).forEach((function(e){var o=n[e];o.timestamp>t&&(t=o.timestamp)})),Object.keys(n).forEach((function(e){var o=n[e];o.timestamp===t&&(o.timestamp=0)})),n.timestamp=t,n},n.mangleChromeStats=function(e,n){var t={};return n.result().forEach((function(e){var n={id:e.id,timestamp:e.timestamp.getTime(),type:e.type};e.names().forEach((function(t){n[t]=e.stat(t)})),t[n.id]=n})),t},n.map2obj=function(e){if(!e.entries)return e;var n={};return e.forEach((function(e,t){n[t]=e})),n},n.dumpStream=function(e){return{id:e.id,tracks:e.getTracks().map((function(e){return{id:e.id,kind:e.kind,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}}))}},n.getWSConnectionData=function(e,n){var t="wss://watchrtc.testrtc.com",o=e.split(":");return-1!==e.indexOf("local")?{url:n||"ws://localhost:9101",key:o[1]}:-1!==e.indexOf("staging")?{url:n||"wss://watchrtc-staging2.testrtc.com",key:o[1]}:-1!==e.indexOf("production")?{url:n||t,key:o[1]}:{url:n||t,key:o[0]}},n.validateConfig=function(e){return!(null==e?void 0:e.rtcApiKey)&&(null==e?void 0:e.debug)?(console.info.apply(console,t(n.logPrefix("error"),["config.rtcApiKey or config.rtcToken need to be provided."])),!1):!(!(null==e?void 0:e.rtcRoomId)||!(null==e?void 0:e.rtcPeerId))||((null==e?void 0:e.debug)&&console.info.apply(console,t(n.logPrefix("error"),["rtcRoomId and rtcPeerId need to be provided."])),!1)},n.countOfValidConnections=function(e){return Object.keys(e).filter((function(n){return e[n].validConnection})).length}},412:(e,n)=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default="1.29.0"},85:function(e,n,t){"use strict";var o=this&&this.__spreadArrays||function(){for(var e=0,n=0,t=arguments.length;n<t;n++)e+=arguments[n].length;var o=Array(e),i=0;for(n=0;n<t;n++)for(var r=arguments[n],a=0,c=r.length;a<c;a++,i++)o[i]=r[a];return o};Object.defineProperty(n,"__esModule",{value:!0});var i=t(593),r=t(354),a=function(){function e(n){this.connection=null,this.buffer=[],this.sendInterval=1,this.onClose=function(){},this.debug=!1,this.dataCollection=!0,e._instance?console.info.apply(console,o(i.logPrefix("info"),["WatchRTCSocket instance already created"])):(e._instance=this,this.debug=!!n.debug)}return e.prototype.connect=function(n,t,r){e._instance.connection&&e._instance.connection.close();var a=e._instance;e._instance.connection=new WebSocket(n,"2.0"),e._instance.connection.onopen=function(e){},e._instance.connection.onclose=function(e){},e._instance.connection.onmessage=function(n){var c;try{var s=JSON.parse(n.data);s.error?(null===(c=null==a?void 0:a.connection)||void 0===c||c.close(),a.connection=null,console.info.apply(console,o(i.logPrefix("error"),["\n"+s.error])),r(s.error)):(s.sendInterval&&(e._instance.sendInterval=s.sendInterval),t(s))}catch(e){console.info.apply(console,o(i.logPrefix("error"),[{err:e.stack}])),r(e.message)}},e._instance.connection.onerror=function(e){console.info.apply(console,o(i.logPrefix("error"),["\n",e])),r(e)}},e.prototype.trace=function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var a=Array.prototype.slice.call(n);if(a.push(Date.now()),a[1]instanceof RTCPeerConnection&&(a[1]=a[1].__rtcStatsId),e._instance.dataCollection)if(e._instance.connection){if(e._instance.connection.readyState===WebSocket.OPEN&&(e._instance.buffer.push(a),e._instance.buffer.length>=e._instance.sendInterval)){var c=JSON.stringify(e._instance.buffer),s=r.compressToEncodedURIComponent(c);e._instance.debug&&(console.log.apply(console,o(i.logPrefix("info"),["lines: "+c.length])),console.log.apply(console,o(i.logPrefix("info"),["compressedMessage: "+s.length]))),e._instance.buffer=[],e._instance.connection.send(s)}}else{if(e._instance.buffer.length>1e3)return;e._instance.buffer.push(a)}},e.prototype.close=function(){e._instance.buffer=[],e._instance.connection&&(e._instance.connection.close(),e._instance.onClose(),e._instance.connection=null)},e.prototype.disableDataCollection=function(){e._instance.debug&&console.log.apply(console,o(i.logPrefix("info"),["Data collection disabled."])),e._instance.dataCollection=!1},e.prototype.enableDataCollection=function(){e._instance.debug&&console.log.apply(console,o(i.logPrefix("info"),["Data collection enabled."])),e._instance.dataCollection=!0},e}();n.default=a},354:(e,n,t)=>{var o,i=function(){function e(e,n){if(!i[e]){i[e]={};for(var t=0;t<e.length;t++)i[e][e.charAt(t)]=t}return i[e][n]}var n=String.fromCharCode,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",i={},r={compressToBase64:function(e){if(null==e)return"";var n=r._compress(e,6,(function(e){return t.charAt(e)}));switch(n.length%4){default:case 0:return n;case 1:return n+"===";case 2:return n+"==";case 3:return n+"="}},decompressFromBase64:function(n){return null==n?"":""==n?null:r._decompress(n.length,32,(function(o){return e(t,n.charAt(o))}))},compressToUTF16:function(e){return null==e?"":r._compress(e,15,(function(e){return n(e+32)}))+" "},decompressFromUTF16:function(e){return null==e?"":""==e?null:r._decompress(e.length,16384,(function(n){return e.charCodeAt(n)-32}))},compressToUint8Array:function(e){for(var n=r.compress(e),t=new Uint8Array(2*n.length),o=0,i=n.length;i>o;o++){var a=n.charCodeAt(o);t[2*o]=a>>>8,t[2*o+1]=a%256}return t},decompressFromUint8Array:function(e){if(null==e)return r.decompress(e);for(var t=new Array(e.length/2),o=0,i=t.length;i>o;o++)t[o]=256*e[2*o]+e[2*o+1];var a=[];return t.forEach((function(e){a.push(n(e))})),r.decompress(a.join(""))},compressToEncodedURIComponent:function(e){return null==e?"":r._compress(e,6,(function(e){return o.charAt(e)}))},decompressFromEncodedURIComponent:function(n){return null==n?"":""==n?null:(n=n.replace(/ /g,"+"),r._decompress(n.length,32,(function(t){return e(o,n.charAt(t))})))},compress:function(e){return r._compress(e,16,(function(e){return n(e)}))},_compress:function(e,n,t){if(null==e)return"";var o,i,r,a={},c={},s="",l="",d="",u=2,f=3,p=2,g=[],v=0,h=0;for(r=0;r<e.length;r+=1)if(s=e.charAt(r),Object.prototype.hasOwnProperty.call(a,s)||(a[s]=f++,c[s]=!0),l=d+s,Object.prototype.hasOwnProperty.call(a,l))d=l;else{if(Object.prototype.hasOwnProperty.call(c,d)){if(d.charCodeAt(0)<256){for(o=0;p>o;o++)v<<=1,h==n-1?(h=0,g.push(t(v)),v=0):h++;for(i=d.charCodeAt(0),o=0;8>o;o++)v=v<<1|1&i,h==n-1?(h=0,g.push(t(v)),v=0):h++,i>>=1}else{for(i=1,o=0;p>o;o++)v=v<<1|i,h==n-1?(h=0,g.push(t(v)),v=0):h++,i=0;for(i=d.charCodeAt(0),o=0;16>o;o++)v=v<<1|1&i,h==n-1?(h=0,g.push(t(v)),v=0):h++,i>>=1}0==--u&&(u=Math.pow(2,p),p++),delete c[d]}else for(i=a[d],o=0;p>o;o++)v=v<<1|1&i,h==n-1?(h=0,g.push(t(v)),v=0):h++,i>>=1;0==--u&&(u=Math.pow(2,p),p++),a[l]=f++,d=String(s)}if(""!==d){if(Object.prototype.hasOwnProperty.call(c,d)){if(d.charCodeAt(0)<256){for(o=0;p>o;o++)v<<=1,h==n-1?(h=0,g.push(t(v)),v=0):h++;for(i=d.charCodeAt(0),o=0;8>o;o++)v=v<<1|1&i,h==n-1?(h=0,g.push(t(v)),v=0):h++,i>>=1}else{for(i=1,o=0;p>o;o++)v=v<<1|i,h==n-1?(h=0,g.push(t(v)),v=0):h++,i=0;for(i=d.charCodeAt(0),o=0;16>o;o++)v=v<<1|1&i,h==n-1?(h=0,g.push(t(v)),v=0):h++,i>>=1}0==--u&&(u=Math.pow(2,p),p++),delete c[d]}else for(i=a[d],o=0;p>o;o++)v=v<<1|1&i,h==n-1?(h=0,g.push(t(v)),v=0):h++,i>>=1;0==--u&&(u=Math.pow(2,p),p++)}for(i=2,o=0;p>o;o++)v=v<<1|1&i,h==n-1?(h=0,g.push(t(v)),v=0):h++,i>>=1;for(;;){if(v<<=1,h==n-1){g.push(t(v));break}h++}return g.join("")},decompress:function(e){return null==e?"":""==e?null:r._decompress(e.length,32768,(function(n){return e.charCodeAt(n)}))},_decompress:function(e,t,o){var i,r,a,c,s,l,d,u=[],f=4,p=4,g=3,v="",h=[],m={val:o(0),position:t,index:1};for(i=0;3>i;i+=1)u[i]=i;for(a=0,s=Math.pow(2,2),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;switch(a){case 0:for(a=0,s=Math.pow(2,8),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;d=n(a);break;case 1:for(a=0,s=Math.pow(2,16),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;d=n(a);break;case 2:return""}for(u[3]=d,r=d,h.push(d);;){if(m.index>e)return"";for(a=0,s=Math.pow(2,g),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;switch(d=a){case 0:for(a=0,s=Math.pow(2,8),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;u[p++]=n(a),d=p-1,f--;break;case 1:for(a=0,s=Math.pow(2,16),l=1;l!=s;)c=m.val&m.position,m.position>>=1,0==m.position&&(m.position=t,m.val=o(m.index++)),a|=(c>0?1:0)*l,l<<=1;u[p++]=n(a),d=p-1,f--;break;case 2:return h.join("")}if(0==f&&(f=Math.pow(2,g),g++),u[d])v=u[d];else{if(d!==p)return null;v=r+r.charAt(0)}h.push(v),u[p++]=r+v.charAt(0),r=v,0==--f&&(f=Math.pow(2,g),g++)}}};return r}();void 0===(o=function(){return i}.call(n,t,n,e))||(e.exports=o)}},n={},function t(o){if(n[o])return n[o].exports;var i=n[o]={exports:{}};return e[o].call(i.exports,i,i.exports,t),i.exports}(607)).default;var e,n})); | ||
//# sourceMappingURL=index.js.map |
@@ -1,19 +0,4 @@ | ||
export interface IWatchRTCConfiguration { | ||
/** Watchrtc api key */ | ||
rtcApiKey: string; | ||
/** Identifier for the session */ | ||
rtcRoomId: string; | ||
/** Identifier for the current peer */ | ||
rtcPeerId: string; | ||
/** ["tag1", "tag2", "tag3"] */ | ||
rtcTags?: string[]; | ||
wsUrl?: string; | ||
proxyUrl?: string; | ||
/** Enables additional logging */ | ||
debug?: boolean; | ||
} | ||
export declare type Rate = 1 | 2 | 3 | 4 | 5; | ||
export declare const setConfig: (config: IWatchRTCConfiguration) => void; | ||
import { IWatchRTCConfiguration } from "./interfaces"; | ||
/** | ||
* Initialize SDK. Can be called multiple times but it will be initialized only at the first time. | ||
* Initialize SDK. | ||
* @param watchrtc | ||
@@ -23,2 +8,9 @@ * @param prefixesToWrap | ||
export declare const initSDK: (watchrtc: IWatchRTCConfiguration, prefixesToWrap: string[]) => void; | ||
export declare const setUserRating: (rate: Rate, rateReason?: string | undefined) => void; | ||
export declare const setConfig: (watchrtc: IWatchRTCConfiguration) => void; | ||
/** | ||
* Add tags for peer session | ||
* @param rtcTags[] | ||
*/ | ||
export declare const addTags: (rtcTags?: string[] | undefined) => void; | ||
export declare const disableDataCollection: () => void; | ||
export declare const enableDataCollection: () => void; |
391
lib/sdk.js
@@ -21,145 +21,102 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.setUserRating = exports.initSDK = exports.setConfig = void 0; | ||
exports.enableDataCollection = exports.disableDataCollection = exports.addTags = exports.setConfig = exports.initSDK = void 0; | ||
var watchrtcsocket_1 = require("./watchrtcsocket"); | ||
var utils_1 = require("./utils"); | ||
var version_1 = require("./version"); | ||
var utils_1 = require("./utils"); | ||
var standardGetstats = true; | ||
// transforms a maplike to an object. Mostly for getStats + | ||
// JSON.parse(JSON.stringify()) | ||
var map2obj = function (m) { | ||
if (!m.entries) { | ||
return m; | ||
} | ||
var o = {}; | ||
m.forEach(function (v, k) { | ||
o[k] = v; | ||
}); | ||
return o; | ||
}; | ||
// apply a delta compression to the stats report. Reduces size by ~90%. | ||
// To reduce further, report keys could be compressed. | ||
var deltaCompression = function (oldStats, newStats) { | ||
oldStats = oldStats || {}; | ||
newStats = newStats || {}; | ||
newStats = JSON.parse(JSON.stringify(newStats)); | ||
Object.keys(newStats).forEach(function (id) { | ||
var report = newStats[id]; | ||
delete report.id; | ||
if (!oldStats[id]) { | ||
return; | ||
} | ||
Object.keys(report).forEach(function (name) { | ||
if (report[name] === oldStats[id][name]) { | ||
delete newStats[id][name]; | ||
var isFirefox = !!window.mozRTCPeerConnection; | ||
var isEdge = !!window.RTCIceGatherer; | ||
var isSafari = !isFirefox && window.RTCPeerConnection && !window.navigator.webkitGetUserMedia; | ||
// Data structure for RTCPeerConnection related stuff we need | ||
var openChannels = {}; | ||
var watchrtcConfig = null; | ||
var socket = null; | ||
var trace; | ||
var lastConnectionOpen = 0; // so we know when was the last active connection seen | ||
var getStatsInterval; | ||
var tryingToConnectSocket = false; | ||
var maybeOpenWebsocketConnection = function () { | ||
var connectionCount = utils_1.countOfValidConnections(openChannels); | ||
if (connectionCount > 0 && !tryingToConnectSocket) { | ||
tryingToConnectSocket = true; | ||
var canConnect = utils_1.validateConfig(watchrtcConfig); | ||
// not very critical, but for consistency with trace | ||
var id_1 = Object.keys(openChannels)[connectionCount - 1]; | ||
if (canConnect) { | ||
if (watchrtcConfig.rtcTags) { | ||
if (!Array.isArray(watchrtcConfig.rtcTags)) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["config.rtcTags must be an array."])); | ||
watchrtcConfig.rtcTags = undefined; | ||
} | ||
else if (watchrtcConfig.rtcTags.some(function (x) { return x.includes(","); })) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["To apply multiple tags please use an array and not comma separated values."])); | ||
} | ||
} | ||
if (Object.keys(report).length === 0) { | ||
delete newStats[id]; | ||
} | ||
else if (Object.keys(report).length === 1 && report.timestamp) { | ||
delete newStats[id]; | ||
} | ||
}); | ||
}); | ||
var timestamp = -Infinity; | ||
Object.keys(newStats).forEach(function (id) { | ||
var report = newStats[id]; | ||
if (report.timestamp > timestamp) { | ||
timestamp = report.timestamp; | ||
var useToken = !!watchrtcConfig.rtcToken; | ||
var wsConnectionData = utils_1.getWSConnectionData(useToken ? watchrtcConfig.rtcToken : watchrtcConfig.rtcApiKey, watchrtcConfig.proxyUrl || watchrtcConfig.wsUrl); | ||
lastConnectionOpen = Date.now(); | ||
socket === null || socket === void 0 ? void 0 : socket.connect(wsConnectionData.url + "?" + (useToken ? "token" : "apiKey") + "=" + wsConnectionData.key + "×tamp=" + Date.now(), function (data) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["Connection established. watchRTCConnectionId: " + data.connectionId + " sdkVersion:" + version_1.default])); | ||
trace("watchrtc", id_1, __assign(__assign(__assign({}, watchrtcConfig), data), { sdkVersion: version_1.default })); | ||
if (!isEdge) { | ||
window.clearInterval(getStatsInterval); | ||
getStatsInterval = window.setInterval(function () { | ||
if (utils_1.countOfValidConnections(openChannels) === 0) { | ||
// if we don't have any connection for 20 sec we can close the socket | ||
if (lastConnectionOpen && lastConnectionOpen + 20000 < Date.now()) { | ||
tryingToConnectSocket = false; | ||
window.clearInterval(getStatsInterval); | ||
socket === null || socket === void 0 ? void 0 : socket.close(); | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["Last connection closed. watchRTCConnectionId: " + data.connectionId + " sdkVersion: " + version_1.default])); | ||
} | ||
} | ||
else { | ||
lastConnectionOpen = Date.now(); | ||
Object.values(openChannels).forEach(function (pcInfo) { | ||
if (pcInfo.pc.signalingState !== "closed") { | ||
getStats(pcInfo); | ||
} | ||
}); | ||
} | ||
}, data.interval); | ||
} | ||
}, function () { | ||
tryingToConnectSocket = false; | ||
lastConnectionOpen = 0; | ||
}); | ||
} | ||
}); | ||
Object.keys(newStats).forEach(function (id) { | ||
var report = newStats[id]; | ||
if (report.timestamp === timestamp) { | ||
report.timestamp = 0; | ||
else { | ||
tryingToConnectSocket = false; | ||
} | ||
}); | ||
newStats.timestamp = timestamp; | ||
return newStats; | ||
}; | ||
var mangleChromeStats = function (pc, response) { | ||
var standardReport = {}; | ||
var reports = response.result(); | ||
reports.forEach(function (report) { | ||
var standardStats = { | ||
id: report.id, | ||
timestamp: report.timestamp.getTime(), | ||
type: report.type, | ||
}; | ||
report.names().forEach(function (name) { | ||
standardStats[name] = report.stat(name); | ||
}); | ||
standardReport[standardStats.id] = standardStats; | ||
}); | ||
return standardReport; | ||
}; | ||
var dumpStream = function (stream) { | ||
return { | ||
id: stream.id, | ||
tracks: stream.getTracks().map(function (track) { | ||
return { | ||
id: track.id, | ||
kind: track.kind, | ||
label: track.label, | ||
enabled: track.enabled, | ||
muted: track.muted, | ||
readyState: track.readyState, | ||
}; | ||
}), | ||
}; | ||
}; | ||
var getWSConnectionData = function (rtcApiKey, overriddenWsUrl) { | ||
var localUrl = "ws://localhost:9101"; | ||
var stagingUrl = "wss://watchrtc-staging2.testrtc.com"; | ||
var productionUrl = "wss://watchrtc.testrtc.com"; | ||
var splitted = rtcApiKey.split(":"); | ||
if (rtcApiKey.indexOf("local") !== -1) { | ||
return { | ||
url: overriddenWsUrl || localUrl, | ||
apiKey: splitted[1], | ||
}; | ||
} | ||
else if (rtcApiKey.indexOf("staging") !== -1) { | ||
return { | ||
url: overriddenWsUrl || stagingUrl, | ||
apiKey: splitted[1], | ||
}; | ||
} | ||
else if (rtcApiKey.indexOf("production") !== -1) { | ||
return { | ||
url: overriddenWsUrl || productionUrl, | ||
apiKey: splitted[1], | ||
}; | ||
} | ||
else { | ||
return { | ||
url: overriddenWsUrl || productionUrl, | ||
apiKey: splitted[0], | ||
}; | ||
} | ||
}; | ||
var validateConfig = function (config) { | ||
if (!config) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["config is required."])); | ||
return false; | ||
var getStats = function (pcInfo) { | ||
if (pcInfo) { | ||
var id_2 = pcInfo.id, pc_1 = pcInfo.pc, prev_1 = pcInfo.prev; | ||
if (standardGetstats || isFirefox || isSafari) { | ||
pc_1.getStats(null).then(function (res) { | ||
var now = utils_1.map2obj(res); | ||
var base = JSON.parse(JSON.stringify(now)); // our new prev | ||
var data = utils_1.deltaCompression(prev_1, now); | ||
if ((data === null || data === void 0 ? void 0 : data.timestamp) !== null && (data === null || data === void 0 ? void 0 : data.timestamp) !== -Infinity) { | ||
trace("getstats", id_2, utils_1.deltaCompression(pcInfo.prev, now)); | ||
} | ||
pcInfo.prev = base; | ||
}); | ||
} | ||
else { | ||
pc_1.getStats(function (res) { | ||
var now = utils_1.mangleChromeStats(pc_1, res); | ||
var base = JSON.parse(JSON.stringify(now)); // our new prev | ||
var data = utils_1.deltaCompression(prev_1, now); | ||
if ((data === null || data === void 0 ? void 0 : data.timestamp) !== null && (data === null || data === void 0 ? void 0 : data.timestamp) !== -Infinity) { | ||
trace("getstats", id_2, utils_1.deltaCompression(prev_1, now)); | ||
} | ||
pcInfo.prev = base; | ||
}); | ||
} | ||
} | ||
else if (!config.rtcApiKey) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["config.rtcApiKey is required."])); | ||
return false; | ||
} | ||
else if (!config.rtcRoomId) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["config.rtcRoomId is required."])); | ||
return false; | ||
} | ||
else if (!config.rtcPeerId) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["config.rtcPeerId is required."])); | ||
return false; | ||
} | ||
return true; | ||
}; | ||
var watchrtcConfig = null; | ||
exports.setConfig = function (config) { | ||
watchrtcConfig = config; | ||
}; | ||
/** | ||
* Initialize SDK. Can be called multiple times but it will be initialized only at the first time. | ||
* Initialize SDK. | ||
* @param watchrtc | ||
@@ -177,93 +134,4 @@ * @param prefixesToWrap | ||
var peerconnectioncounter = 0; | ||
var lastConnectionOpen = 0; // so we know when was the last active connection seen | ||
var getStatsInterval; | ||
var tryingToConnectSocket = false; | ||
var socket = new watchrtcsocket_1.default(); | ||
var trace = socket.trace; | ||
// Data structure for RTCPeerConnection related stuff we need | ||
var openChannels = {}; | ||
var isFirefox = !!window.mozRTCPeerConnection; | ||
var isEdge = !!window.RTCIceGatherer; | ||
var isSafari = !isFirefox && window.RTCPeerConnection && !window.navigator.webkitGetUserMedia; | ||
var countOfValidConnections = function () { | ||
return Object.keys(openChannels).filter(function (id) { return openChannels[id].validConnection; }).length; | ||
}; | ||
var maybeOpenWebsocketConnection = function () { | ||
var connectionCount = countOfValidConnections(); | ||
if (connectionCount > 0 && !tryingToConnectSocket) { | ||
tryingToConnectSocket = true; | ||
var canConnect = validateConfig(watchrtcConfig); | ||
// not very critical, but for consistency with trace | ||
var id_1 = Object.keys(openChannels)[connectionCount - 1]; | ||
if (canConnect) { | ||
if (watchrtcConfig.rtcTags) { | ||
if (!Array.isArray(watchrtcConfig.rtcTags)) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["config.rtcTags must be an array."])); | ||
watchrtcConfig.rtcTags = undefined; | ||
} | ||
else if (watchrtcConfig.rtcTags.some(function (x) { return x.includes(","); })) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["To apply multiple tags please use an array and not comma separated values."])); | ||
} | ||
} | ||
var wsConnectionData = getWSConnectionData(watchrtcConfig.rtcApiKey, watchrtcConfig.proxyUrl || watchrtcConfig.wsUrl); | ||
lastConnectionOpen = Date.now(); | ||
socket.connect(wsConnectionData.url + "?apiKey=" + wsConnectionData.apiKey + "×tamp=" + Date.now(), function (data) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["Connection established. watchRTCConnectionId: " + data.connectionId + " sdkVersion:" + version_1.default])); | ||
trace("watchrtc", id_1, __assign(__assign(__assign({}, watchrtcConfig), data), { sdkVersion: version_1.default })); | ||
if (!isEdge) { | ||
window.clearInterval(getStatsInterval); | ||
getStatsInterval = window.setInterval(function () { | ||
if (countOfValidConnections() === 0) { | ||
// if we don't have any connection for 20 sec we can close the socket | ||
if (lastConnectionOpen && lastConnectionOpen + 20000 < Date.now()) { | ||
tryingToConnectSocket = false; | ||
window.clearInterval(getStatsInterval); | ||
socket.close(); | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["Last connection closed. watchRTCConnectionId: " + data.connectionId + " sdkVersion: " + version_1.default])); | ||
} | ||
} | ||
else { | ||
lastConnectionOpen = Date.now(); | ||
Object.values(openChannels).forEach(function (pcInfo) { | ||
if (pcInfo.pc.signalingState !== "closed") { | ||
getStats(pcInfo); | ||
} | ||
}); | ||
} | ||
}, data.interval); | ||
} | ||
}, function () { | ||
tryingToConnectSocket = false; | ||
lastConnectionOpen = 0; | ||
}); | ||
} | ||
} | ||
}; | ||
var getStats = function (pcInfo) { | ||
if (pcInfo) { | ||
var id_2 = pcInfo.id, pc_1 = pcInfo.pc, prev_1 = pcInfo.prev; | ||
if (standardGetstats || isFirefox || isSafari) { | ||
pc_1.getStats(null).then(function (res) { | ||
var now = map2obj(res); | ||
var base = JSON.parse(JSON.stringify(now)); // our new prev | ||
var data = deltaCompression(prev_1, now); | ||
if ((data === null || data === void 0 ? void 0 : data.timestamp) !== null && (data === null || data === void 0 ? void 0 : data.timestamp) !== -Infinity) { | ||
trace("getstats", id_2, deltaCompression(pcInfo.prev, now)); | ||
} | ||
pcInfo.prev = base; | ||
}); | ||
} | ||
else { | ||
pc_1.getStats(function (res) { | ||
var now = mangleChromeStats(pc_1, res); | ||
var base = JSON.parse(JSON.stringify(now)); // our new prev | ||
var data = deltaCompression(prev_1, now); | ||
if ((data === null || data === void 0 ? void 0 : data.timestamp) !== null && (data === null || data === void 0 ? void 0 : data.timestamp) !== -Infinity) { | ||
trace("getstats", id_2, deltaCompression(prev_1, now)); | ||
} | ||
pcInfo.prev = base; | ||
}); | ||
} | ||
} | ||
}; | ||
socket = new watchrtcsocket_1.default({ debug: watchrtc === null || watchrtc === void 0 ? void 0 : watchrtc.debug }); | ||
trace = socket.trace; | ||
prefixesToWrap.forEach(function (prefix) { | ||
@@ -279,6 +147,9 @@ if (!window[prefix + "RTCPeerConnection"]) { | ||
var peerconnection = function (config, constraints) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["new RTCPeerConnection called.", { | ||
config: config, | ||
constraints: constraints, | ||
}])); | ||
watchrtcConfig = __assign(__assign({}, watchrtc), config === null || config === void 0 ? void 0 : config.watchrtc); | ||
if (watchrtcConfig === null || watchrtcConfig === void 0 ? void 0 : watchrtcConfig.debug) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["new RTCPeerConnection called.", { | ||
config: config, | ||
constraints: constraints, | ||
}])); | ||
} | ||
var pc = new origPeerConnection(config, constraints); | ||
@@ -292,3 +163,2 @@ var id = "PC_" + peerconnectioncounter++; | ||
}; | ||
watchrtcConfig = watchrtcConfig || watchrtc || (config === null || config === void 0 ? void 0 : config.watchrtc); | ||
if (!config) { | ||
@@ -525,3 +395,3 @@ config = { nullConfig: true }; | ||
// to acquire the cam (in chrome) | ||
trace("getUserMediaOnSuccess", null, dumpStream(stream)); | ||
trace("getUserMediaOnSuccess", null, utils_1.dumpStream(stream)); | ||
if (cb) { | ||
@@ -544,3 +414,3 @@ cb(stream); | ||
return origGetUserMedia_1.apply(navigator.mediaDevices, arguments).then(function (stream) { | ||
trace("navigator.mediaDevices.getUserMediaOnSuccess", null, dumpStream(stream)); | ||
trace("navigator.mediaDevices.getUserMediaOnSuccess", null, utils_1.dumpStream(stream)); | ||
return stream; | ||
@@ -560,3 +430,3 @@ }, function (err) { | ||
return origGetDisplayMedia_1.apply(navigator.mediaDevices, arguments).then(function (stream) { | ||
trace("navigator.mediaDevices.getDisplayMediaOnSuccess", null, dumpStream(stream)); | ||
trace("navigator.mediaDevices.getDisplayMediaOnSuccess", null, utils_1.dumpStream(stream)); | ||
return stream; | ||
@@ -571,13 +441,54 @@ }, function (err) { | ||
}; | ||
exports.setUserRating = function (rate, rateReason) { | ||
var _a; | ||
if (rate) { | ||
if (watchrtcsocket_1.default._instance && | ||
((_a = watchrtcsocket_1.default._instance.connection) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) { | ||
watchrtcsocket_1.default._instance.trace("userRating", "", { rate: rate, rateReason: rateReason }); | ||
exports.setConfig = function (watchrtc) { | ||
var initialized = window.watchRTCInitialized; | ||
if (!initialized) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["SDK is not initialized. Use 'init' function fisrt."])); | ||
return; | ||
} | ||
if ((watchrtcConfig === null || watchrtcConfig === void 0 ? void 0 : watchrtcConfig.rtcRoomId) && (watchrtcConfig === null || watchrtcConfig === void 0 ? void 0 : watchrtcConfig.rtcPeerId)) { | ||
if (watchrtcConfig === null || watchrtcConfig === void 0 ? void 0 : watchrtcConfig.debug) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["Websocket started to send data. 'setConfig' function ignored"])); | ||
} | ||
else { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["Please set user rating before websocket connection is closed."])); | ||
} | ||
return; | ||
} | ||
if (!watchrtc.rtcRoomId || !watchrtc.rtcPeerId) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["rtcRoomId and rtcPeerId are required"])); | ||
return; | ||
} | ||
watchrtcConfig = __assign(__assign({}, watchrtcConfig), watchrtc); | ||
maybeOpenWebsocketConnection(); | ||
}; | ||
/** | ||
* Add tags for peer session | ||
* @param rtcTags[] | ||
*/ | ||
exports.addTags = function ( | ||
/** ["tag1", "tag2", "tag3"] */ | ||
rtcTags) { | ||
var initialized = window.watchRTCInitialized; | ||
if (!initialized) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["SDK is not initialized. Use 'init' function fisrt."])); | ||
return; | ||
} | ||
if (!rtcTags || !Array.isArray(rtcTags)) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["addTags excepts only array of strings"])); | ||
return; | ||
} | ||
trace("addRtcTags", null, { rtcTags: rtcTags }); | ||
}; | ||
exports.disableDataCollection = function () { | ||
var initialized = window.watchRTCInitialized; | ||
if (!initialized) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["SDK is not initialized. Use 'init' function fisrt."])); | ||
return; | ||
} | ||
socket === null || socket === void 0 ? void 0 : socket.disableDataCollection(); | ||
}; | ||
exports.enableDataCollection = function () { | ||
var initialized = window.watchRTCInitialized; | ||
if (!initialized) { | ||
console.info.apply(console, __spreadArrays(utils_1.logPrefix("error"), ["SDK is not initialized. Use 'init' function fisrt."])); | ||
return; | ||
} | ||
socket === null || socket === void 0 ? void 0 : socket.enableDataCollection(); | ||
}; |
@@ -0,1 +1,17 @@ | ||
import { IWatchRTCConfiguration, RTCPeerConnectionInformation } from "./interfaces"; | ||
export declare const logPrefix: (type?: "error" | "info") => string[]; | ||
export declare const deltaCompression: (oldStats: any, newStats: any) => any; | ||
export declare const mangleChromeStats: (pc: any, response: any) => any; | ||
export declare const map2obj: (m: any) => any; | ||
export declare const dumpStream: (stream: any) => { | ||
id: any; | ||
tracks: any; | ||
}; | ||
export declare const getWSConnectionData: (key: string, overriddenWsUrl?: string | undefined) => { | ||
url: string; | ||
key: string; | ||
}; | ||
export declare const validateConfig: (config: IWatchRTCConfiguration) => boolean; | ||
export declare const countOfValidConnections: (openChannels: { | ||
[id: string]: RTCPeerConnectionInformation; | ||
}) => number; |
138
lib/utils.js
"use strict"; | ||
var __spreadArrays = (this && this.__spreadArrays) || function () { | ||
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; | ||
for (var r = Array(s), k = 0, i = 0; i < il; i++) | ||
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) | ||
r[k] = a[j]; | ||
return r; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.logPrefix = void 0; | ||
exports.countOfValidConnections = exports.validateConfig = exports.getWSConnectionData = exports.dumpStream = exports.map2obj = exports.mangleChromeStats = exports.deltaCompression = exports.logPrefix = void 0; | ||
exports.logPrefix = function (type) { | ||
@@ -17,1 +24,130 @@ if (type === void 0) { type = "info"; } | ||
}; | ||
// apply a delta compression to the stats report. Reduces size by ~90%. | ||
// To reduce further, report keys could be compressed. | ||
exports.deltaCompression = function (oldStats, newStats) { | ||
oldStats = oldStats || {}; | ||
newStats = newStats || {}; | ||
newStats = JSON.parse(JSON.stringify(newStats)); | ||
Object.keys(newStats).forEach(function (id) { | ||
var report = newStats[id]; | ||
delete report.id; | ||
if (!oldStats[id]) { | ||
return; | ||
} | ||
Object.keys(report).forEach(function (name) { | ||
if (report[name] === oldStats[id][name]) { | ||
delete newStats[id][name]; | ||
} | ||
if (Object.keys(report).length === 0) { | ||
delete newStats[id]; | ||
} | ||
else if (Object.keys(report).length === 1 && report.timestamp) { | ||
delete newStats[id]; | ||
} | ||
}); | ||
}); | ||
var timestamp = -Infinity; | ||
Object.keys(newStats).forEach(function (id) { | ||
var report = newStats[id]; | ||
if (report.timestamp > timestamp) { | ||
timestamp = report.timestamp; | ||
} | ||
}); | ||
Object.keys(newStats).forEach(function (id) { | ||
var report = newStats[id]; | ||
if (report.timestamp === timestamp) { | ||
report.timestamp = 0; | ||
} | ||
}); | ||
newStats.timestamp = timestamp; | ||
return newStats; | ||
}; | ||
exports.mangleChromeStats = function (pc, response) { | ||
var standardReport = {}; | ||
var reports = response.result(); | ||
reports.forEach(function (report) { | ||
var standardStats = { | ||
id: report.id, | ||
timestamp: report.timestamp.getTime(), | ||
type: report.type, | ||
}; | ||
report.names().forEach(function (name) { | ||
standardStats[name] = report.stat(name); | ||
}); | ||
standardReport[standardStats.id] = standardStats; | ||
}); | ||
return standardReport; | ||
}; | ||
// transforms a maplike to an object. Mostly for getStats + | ||
// JSON.parse(JSON.stringify()) | ||
exports.map2obj = function (m) { | ||
if (!m.entries) { | ||
return m; | ||
} | ||
var o = {}; | ||
m.forEach(function (v, k) { | ||
o[k] = v; | ||
}); | ||
return o; | ||
}; | ||
exports.dumpStream = function (stream) { | ||
return { | ||
id: stream.id, | ||
tracks: stream.getTracks().map(function (track) { | ||
return { | ||
id: track.id, | ||
kind: track.kind, | ||
label: track.label, | ||
enabled: track.enabled, | ||
muted: track.muted, | ||
readyState: track.readyState, | ||
}; | ||
}), | ||
}; | ||
}; | ||
exports.getWSConnectionData = function (key, overriddenWsUrl) { | ||
var localUrl = "ws://localhost:9101"; | ||
var stagingUrl = "wss://watchrtc-staging2.testrtc.com"; | ||
var productionUrl = "wss://watchrtc.testrtc.com"; | ||
var splitted = key.split(":"); | ||
if (key.indexOf("local") !== -1) { | ||
return { | ||
url: overriddenWsUrl || localUrl, | ||
key: splitted[1], | ||
}; | ||
} | ||
else if (key.indexOf("staging") !== -1) { | ||
return { | ||
url: overriddenWsUrl || stagingUrl, | ||
key: splitted[1], | ||
}; | ||
} | ||
else if (key.indexOf("production") !== -1) { | ||
return { | ||
url: overriddenWsUrl || productionUrl, | ||
key: splitted[1], | ||
}; | ||
} | ||
else { | ||
return { | ||
url: overriddenWsUrl || productionUrl, | ||
key: splitted[0], | ||
}; | ||
} | ||
}; | ||
exports.validateConfig = function (config) { | ||
if (!(config === null || config === void 0 ? void 0 : config.rtcApiKey)) { | ||
if (config === null || config === void 0 ? void 0 : config.debug) { | ||
console.info.apply(console, __spreadArrays(exports.logPrefix("error"), ["config.rtcApiKey or config.rtcToken need to be provided."])); | ||
return false; | ||
} | ||
} | ||
if (!(config === null || config === void 0 ? void 0 : config.rtcRoomId) || !(config === null || config === void 0 ? void 0 : config.rtcPeerId)) { | ||
if (config === null || config === void 0 ? void 0 : config.debug) { | ||
console.info.apply(console, __spreadArrays(exports.logPrefix("error"), ["rtcRoomId and rtcPeerId need to be provided."])); | ||
} | ||
return false; | ||
} | ||
return true; | ||
}; | ||
exports.countOfValidConnections = function (openChannels) { return Object.keys(openChannels).filter(function (id) { return openChannels[id].validConnection; }).length; }; |
@@ -1,2 +0,2 @@ | ||
declare const _default: "1.28.9"; | ||
declare const _default: "1.29.0"; | ||
export default _default; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.default = "1.28.7"; | ||
exports.default = "1.29.0"; |
@@ -0,1 +1,4 @@ | ||
interface IWatchRTCSocketOptions { | ||
debug?: boolean; | ||
} | ||
export default class WatchRTCSocket { | ||
@@ -8,6 +11,10 @@ static _instance: WatchRTCSocket; | ||
private debug; | ||
constructor(debug?: boolean); | ||
private dataCollection; | ||
constructor(options: IWatchRTCSocketOptions); | ||
connect(url: string, onData: (data: any) => void, onError: (error: any) => void): void; | ||
trace(...data: any[]): void; | ||
close(): void; | ||
disableDataCollection(): void; | ||
enableDataCollection(): void; | ||
} | ||
export {}; |
@@ -14,3 +14,3 @@ "use strict"; | ||
var WatchRTCSocket = /** @class */ (function () { | ||
function WatchRTCSocket() { | ||
function WatchRTCSocket(options) { | ||
this.connection = null; | ||
@@ -20,2 +20,4 @@ this.buffer = []; | ||
this.onClose = function () { }; | ||
this.debug = false; | ||
this.dataCollection = true; | ||
if (WatchRTCSocket._instance) { | ||
@@ -26,2 +28,3 @@ console.info.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["WatchRTCSocket instance already created"])); | ||
WatchRTCSocket._instance = this; | ||
this.debug = !!options.debug; | ||
} | ||
@@ -33,6 +36,6 @@ } | ||
} | ||
var _this = WatchRTCSocket._instance; | ||
WatchRTCSocket._instance.connection = new WebSocket(url, PROTOCOL_VERSION); | ||
WatchRTCSocket._instance.connection.onopen = function (_e) { }; | ||
WatchRTCSocket._instance.connection.onclose = function (_e) { }; | ||
var _this = WatchRTCSocket._instance; | ||
WatchRTCSocket._instance.connection.onmessage = function (e) { | ||
@@ -75,2 +78,5 @@ var _a; | ||
} | ||
if (!WatchRTCSocket._instance.dataCollection) { | ||
return; | ||
} | ||
if (!WatchRTCSocket._instance.connection) { | ||
@@ -88,4 +94,6 @@ if (WatchRTCSocket._instance.buffer.length > 1000) { | ||
var compressedMessage = LZString.compressToEncodedURIComponent(lines); | ||
console.log.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["lines: " + lines.length])); | ||
console.log.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["compressedMessage: " + compressedMessage.length])); | ||
if (WatchRTCSocket._instance.debug) { | ||
console.log.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["lines: " + lines.length])); | ||
console.log.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["compressedMessage: " + compressedMessage.length])); | ||
} | ||
WatchRTCSocket._instance.buffer = []; | ||
@@ -104,4 +112,16 @@ WatchRTCSocket._instance.connection.send(compressedMessage); | ||
}; | ||
WatchRTCSocket.prototype.disableDataCollection = function () { | ||
if (WatchRTCSocket._instance.debug) { | ||
console.log.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["Data collection disabled."])); | ||
} | ||
WatchRTCSocket._instance.dataCollection = false; | ||
}; | ||
WatchRTCSocket.prototype.enableDataCollection = function () { | ||
if (WatchRTCSocket._instance.debug) { | ||
console.log.apply(console, __spreadArrays(utils_1.logPrefix("info"), ["Data collection enabled."])); | ||
} | ||
WatchRTCSocket._instance.dataCollection = true; | ||
}; | ||
return WatchRTCSocket; | ||
}()); | ||
exports.default = WatchRTCSocket; |
{ | ||
"name": "@testrtc/watchrtc-sdk", | ||
"version": "1.28.9", | ||
"version": "1.29.0", | ||
"description": "gather WebRTC API traces and statistics", | ||
@@ -5,0 +5,0 @@ "main": "lib/index.js", |
@@ -1,4 +0,4 @@ | ||
watchRTC offers users the ability to collect, track and analyze the metrics of real users on any WebRTC application. | ||
watchRTC enables application developers to collect, track and analyze telemetry and metrics of real users on any WebRTC application. | ||
This is done by including our watchRTC SDK which connects to the testRTC backend. | ||
This is done by including our watchRTC SDK which connects to the testRTC backend and collects the relevant data. | ||
@@ -27,4 +27,8 @@ ## Installation | ||
Before any of your webrtc javascript code, add the following: | ||
Before any of your WebRTC javascript code, you need to include and initialize our SDK. | ||
The watchRTC.init() needs to take place prior to including or loading any 3rd party SDKs that interact with WebRTC - failing to do so may hinder our ability to collect data. | ||
Use the following initialization sequence: | ||
#### javascript (ES6+) | ||
@@ -63,10 +67,10 @@ | ||
This will transparently modify the RTCPeerConnection objects, allowing it to connect to the watchRTC backend service. | ||
The watchrtc parameter is needed to make this connection. | ||
This will transparently modify the RTCPeerConnection objects, allowing it to connect to the watchRTC backend service transparently to your application. | ||
The watchRTC parameter is needed to make this connection. | ||
- rtcApiKey - the watchRTC API key, as provided by testRTC | ||
- rtcApiKey - watchRTC API key, as provided by testRTC | ||
- rtcRoomId - an identifier to the session/room/conference. This will enable an analysis of all participants in the same room as a single logical unit | ||
- rtcPeerId - an identifer of this peer/user in the session. This will make it easier to identify and troubleshoot users. It is recommended to use non-PII data here as much as possible | ||
- rtcPeerId - an identifer of this peer/user in the session. This will make it easier to identify and troubleshoot users. It is recommended to use non-PII data here as much as possible (no emails or names for example) | ||
- rtcTags - tags to associate with this peer connection. These can later be searched for or filtered | ||
- proxyUrl - (optional) secured web socket proxy server address, the proxy server should forward the connection to testRTC watch RTC server | ||
- proxyUrl - (optional) secured web socket proxy server address, the proxy server should forward the connection to testRTC's watchRTC servers | ||
@@ -77,3 +81,3 @@ ```javascript | ||
watchrtc:{ | ||
rtcApiKey: "watchrtc api key", | ||
rtcApiKey: "watchRTC API key", | ||
rtcRoomId: "identifier for the session", | ||
@@ -92,7 +96,7 @@ rtcPeerId: "identifier for the current peer", | ||
you can use next approach | ||
you can use next approach - this is useful when you don't have a direct/easy access to the RTCPeerConnection object: | ||
```javascript | ||
watchRTC.init({ | ||
rtcApiKey: "watchrtc api key", | ||
rtcApiKey: "watchRTC API key", | ||
rtcRoomId: "identifier for the session", | ||
@@ -104,7 +108,7 @@ rtcPeerId: "identifier for the current peer", | ||
You also can use `watchRTC.setConfig` function to set watchrtc configuration | ||
You also can use `watchRTC.setConfig` function to set watchRTC configuration after calling init() and before the creation of RTCPeerConnection objects: | ||
```javascript | ||
watchRTC.setConfig({ | ||
rtcApiKey: "watchrtc api key", | ||
rtcApiKey: "watchRTC API key", | ||
rtcRoomId: "identifier for the session", | ||
@@ -118,2 +122,4 @@ rtcPeerId: "identifier for the current peer", | ||
You can use `watchRTC.disableDataCollection()` and `watchRTC.disableDataCollection()` to control what data you want to send. | ||
### Initialize SDK. Can be called multiple times but it will be initialized only at the first time. | ||
@@ -120,0 +126,0 @@ |
Sorry, the diff of this file is not supported yet
139187
17
956
124