@messagebird/webrtc
Advanced tools
Comparing version 0.0.1 to 0.0.2
'use strict'; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
var jssip = require('jssip'); | ||
var EventEmitter = _interopDefault(require('events')); | ||
@@ -78,82 +83,364 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
function _toConsumableArray(arr) { | ||
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); | ||
function _inherits(subClass, superClass) { | ||
if (typeof superClass !== "function" && superClass !== null) { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
subClass.prototype = Object.create(superClass && superClass.prototype, { | ||
constructor: { | ||
value: subClass, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
if (superClass) _setPrototypeOf(subClass, superClass); | ||
} | ||
function _arrayWithoutHoles(arr) { | ||
if (Array.isArray(arr)) { | ||
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
return arr2; | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _assertThisInitialized(self) { | ||
if (self === void 0) { | ||
throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); | ||
} | ||
return self; | ||
} | ||
function _iterableToArray(iter) { | ||
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); | ||
function _possibleConstructorReturn(self, call) { | ||
if (call && (typeof call === "object" || typeof call === "function")) { | ||
return call; | ||
} | ||
return _assertThisInitialized(self); | ||
} | ||
function _nonIterableSpread() { | ||
throw new TypeError("Invalid attempt to spread non-iterable instance"); | ||
function _superPropBase(object, property) { | ||
while (!Object.prototype.hasOwnProperty.call(object, property)) { | ||
object = _getPrototypeOf(object); | ||
if (object === null) break; | ||
} | ||
return object; | ||
} | ||
var RtcSocketUrl = "wss://".concat(undefined); | ||
var API_HOST = undefined; | ||
function _get(target, property, receiver) { | ||
if (typeof Reflect !== "undefined" && Reflect.get) { | ||
_get = Reflect.get; | ||
} else { | ||
_get = function _get(target, property, receiver) { | ||
var base = _superPropBase(target, property); | ||
function makeSipUserAgent(options) { | ||
var ws = new jssip.WebSocketInterface(RtcSocketUrl); | ||
var ua = new jssip.UA({ | ||
sockets: [ws], | ||
register: options.register || false, | ||
uri: "sip:".concat(options.displayName, "@").concat(API_HOST) | ||
}); | ||
return ua; | ||
if (!base) return; | ||
var desc = Object.getOwnPropertyDescriptor(base, property); | ||
if (desc.get) { | ||
return desc.get.call(receiver); | ||
} | ||
return desc.value; | ||
}; | ||
} | ||
return _get(target, property, receiver || target); | ||
} | ||
var WebRtcClient = | ||
var RTC_SOCKET_URL = "wss://".concat("webrtc-staging.messagebird.io"); | ||
var API_HOST = "webrtc-staging.messagebird.io"; | ||
var USERNAME_REGEX = /^\S*$/; | ||
var validateOptions = function validateOptions(options) { | ||
if (!options.username) { | ||
throw new Error('You must pass a username.'); | ||
} | ||
if (!USERNAME_REGEX.test(options.username)) { | ||
throw new Error("Username cannot contain any spaces"); | ||
} | ||
}; | ||
var UserAgent = | ||
/*#__PURE__*/ | ||
function (_SipUserAgent) { | ||
_inherits(UserAgent, _SipUserAgent); | ||
function UserAgent(options) { | ||
var _this; | ||
_classCallCheck(this, UserAgent); | ||
validateOptions(options); | ||
var ws = new jssip.WebSocketInterface(RTC_SOCKET_URL); | ||
_this = _possibleConstructorReturn(this, _getPrototypeOf(UserAgent).call(this, { | ||
sockets: [ws], | ||
register: true, | ||
uri: "sip:".concat(options.username, "@").concat(API_HOST), | ||
display_name: options.displayName | ||
})); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "connectTimeout", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "resolveDisconnect", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "resolveConnection", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "rejectConnection", void 0); | ||
_this.registrator().setExtraHeaders(["X-Token: ".concat(options.jwt)]); | ||
_this.on('connected', _this.handleConnected); | ||
_this.on('disconnected', _this.handleDisconnected); | ||
return _this; | ||
} | ||
_createClass(UserAgent, [{ | ||
key: "start", | ||
value: function start() { | ||
var _this2 = this; | ||
var timeoutMs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10000; | ||
return new Promise(function (resolve, reject) { | ||
_this2.connectTimeout = setTimeout(function () { | ||
_this2.resolveConnection = null; | ||
_this2.rejectConnection = null; | ||
reject(new Error("Connectioned timed out after ".concat(timeoutMs, "ms"))); | ||
}, timeoutMs); | ||
_this2.resolveConnection = resolve; | ||
_this2.rejectConnection = reject; | ||
_get(_getPrototypeOf(UserAgent.prototype), "start", _this2).call(_this2); | ||
}); | ||
} | ||
}, { | ||
key: "stop", | ||
value: function stop() { | ||
var _this3 = this; | ||
return new Promise(function (resolve) { | ||
_this3.resolveDisconnect = resolve; | ||
_get(_getPrototypeOf(UserAgent.prototype), "stop", _this3).call(_this3); | ||
}); | ||
} | ||
}, { | ||
key: "handleConnected", | ||
value: function handleConnected(data) { | ||
if (this.resolveConnection) { | ||
clearTimeout(this.connectTimeout); | ||
this.resolveConnection(data); | ||
this.resolveConnection = null; | ||
this.rejectConnection = null; | ||
} | ||
} | ||
}, { | ||
key: "handleDisconnected", | ||
value: function handleDisconnected(data) { | ||
if (this.rejectConnection) { | ||
clearTimeout(this.connectTimeout); | ||
this.rejectConnection(new Error("Could not connect to WebRTC Socket: ".concat(data.reason))); | ||
this.resolveConnection = null; | ||
this.rejectConnection = null; | ||
} | ||
if (this.resolveDisconnect) { | ||
this.resolveDisconnect(data); | ||
this.resolveDisconnect = null; | ||
} | ||
} | ||
}]); | ||
return UserAgent; | ||
}(jssip.UA); | ||
function createStreamTarget(stream) { | ||
var video = document.createElement('video'); | ||
video.setAttribute('autoplay', 'true'); | ||
video.setAttribute('style', 'display: none;'); | ||
video.srcObject = stream; | ||
document.body.appendChild(video); | ||
return video; | ||
} | ||
function removeStreamTarget(target) { | ||
if (target.remove) { | ||
target.remove(); | ||
return; | ||
} | ||
try { | ||
document.body.removeChild(target); | ||
} catch (err) {// TODO: FIXME | ||
// sometimes this fails? does it matter if a hidden video tag stays? | ||
} | ||
} | ||
var Status; | ||
(function (Status) { | ||
Status["Initial"] = "initial"; | ||
Status["Connecting"] = "connecting"; | ||
Status["Failed"] = "failed"; | ||
Status["Accepted"] = "accepted"; | ||
Status["Confirmed"] = "confirmed"; | ||
Status["Disconnected"] = "disconnected"; | ||
})(Status || (Status = {})); | ||
var RTCSession = | ||
/*#__PURE__*/ | ||
function () { | ||
function WebRtcClient(_ref) { | ||
var displayName = _ref.displayName, | ||
_ref$register = _ref.register, | ||
register = _ref$register === void 0 ? false : _ref$register; | ||
function RTCSession(sipRtcSession) { | ||
var _this = this; | ||
_classCallCheck(this, WebRtcClient); | ||
_classCallCheck(this, RTCSession); | ||
_defineProperty(this, "listeners", {}); | ||
_defineProperty(this, "status", void 0); | ||
_defineProperty(this, "connected", void 0); | ||
_defineProperty(this, "streamTargets", void 0); | ||
_defineProperty(this, "sipUA", void 0); | ||
_defineProperty(this, "eventEmitter", new EventEmitter()); | ||
this.connected = false; | ||
this.sipUA = makeSipUserAgent({ | ||
register: register, | ||
displayName: displayName | ||
_defineProperty(this, "sipRTCSession", void 0); | ||
_defineProperty(this, "sendDTMF", function (key) { | ||
_this.sipRTCSession.sendDTMF(key); | ||
}); | ||
this.sipUA.on('connected', this.handleConnected); | ||
this.sipUA.on('disconnected', this.handleDisconnected); | ||
_defineProperty(this, "handleAccepted", function () { | ||
_this.status = Status.Accepted; | ||
}); | ||
_defineProperty(this, "handleConfirmed", function (data) { | ||
_this.status = Status.Confirmed; | ||
_this.eventEmitter.emit('confirmed', data); | ||
}); | ||
_defineProperty(this, "handleEnded", function (data) { | ||
_this.status = Status.Disconnected; | ||
_this.eventEmitter.emit('ended', data); | ||
}); | ||
_defineProperty(this, "handleFailed", function (data) { | ||
_this.status = Status.Failed; | ||
_this.eventEmitter.emit('failed', data); | ||
}); | ||
_defineProperty(this, "handleAddTrack", function (data) { | ||
_this.streamTargets = data.streams.map(function (stream) { | ||
return createStreamTarget(stream); | ||
}); | ||
}); | ||
this.sipRTCSession = sipRtcSession; | ||
this.sipRTCSession.connection.addEventListener('track', this.handleAddTrack); | ||
this.sipRTCSession.on('accepted', this.handleAccepted); | ||
this.sipRTCSession.on('confirmed', this.handleConfirmed); | ||
this.sipRTCSession.on('ended', this.handleEnded); | ||
this.sipRTCSession.on('failed', this.handleFailed); | ||
} | ||
_createClass(WebRtcClient, [{ | ||
_createClass(RTCSession, [{ | ||
key: "on", | ||
value: function on(name, callback) { | ||
if (!this.listeners[name]) { | ||
this.listeners[name] = [callback]; | ||
return; | ||
} | ||
this.listeners[name] = [].concat(_toConsumableArray(this.listeners[name]), [callback]); | ||
value: function on(name, cb) { | ||
this.eventEmitter.on(name, cb); | ||
} | ||
}, { | ||
key: "removeEventListener", | ||
value: function removeEventListener(name, callback) { | ||
if (this.listeners[name]) { | ||
this.listeners[name] = this.listeners[name].filter(function (listener) { | ||
return listener === callback; | ||
}); | ||
key: "removeEventlistener", | ||
value: function removeEventlistener(name, cb) { | ||
this.eventEmitter.removeListener(name, cb); | ||
} | ||
}, { | ||
key: "disconnect", | ||
// TODO: whassa good name? | ||
value: function disconnect() { | ||
this.streamTargets.forEach(function (target) { | ||
return removeStreamTarget(target); | ||
}); | ||
this.sipRTCSession.terminate(); | ||
} | ||
}]); | ||
return RTCSession; | ||
}(); | ||
var OutgoingRTCSession = | ||
/*#__PURE__*/ | ||
function (_RTCSession) { | ||
_inherits(OutgoingRTCSession, _RTCSession); | ||
function OutgoingRTCSession(ua, _ref) { | ||
var _this; | ||
var to = _ref.to, | ||
jwt = _ref.jwt, | ||
onEnded = _ref.onEnded; | ||
_classCallCheck(this, OutgoingRTCSession); | ||
_this = _possibleConstructorReturn(this, _getPrototypeOf(OutgoingRTCSession).call(this, ua.call("sip:".concat(to, "@").concat(API_HOST), { | ||
mediaConstraints: { | ||
audio: true, | ||
video: false // TODO: what if we support video? | ||
}, | ||
extraHeaders: ["X-Token: ".concat(jwt)] | ||
}))); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "connectTimeout", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "acceptResolver", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "failedRejector", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleOutboundSessionAccepted", function () { | ||
if (_this.acceptResolver) { | ||
_this.acceptResolver(_assertThisInitialized(_assertThisInitialized(_this))); | ||
_this.acceptResolver = undefined; | ||
_this.failedRejector = undefined; | ||
clearTimeout(_this.connectTimeout); | ||
} | ||
} // FIXME: This not nice. How to promisify this best? | ||
// Do we need promises for this? | ||
}); | ||
}, { | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleOutboundSessionFailed", function (data) { | ||
if (_this.failedRejector) { | ||
_this.failedRejector(data); | ||
_this.acceptResolver = undefined; | ||
_this.failedRejector = undefined; | ||
clearTimeout(_this.connectTimeout); | ||
} | ||
}); | ||
_this.status = Status.Connecting; | ||
_this.on('confirmed', _this.handleOutboundSessionAccepted); | ||
_this.on('failed', _this.handleOutboundSessionFailed); | ||
_this.on('ended', function (data) { | ||
return onEnded(_assertThisInitialized(_assertThisInitialized(_this)), data); | ||
}); | ||
return _this; | ||
} | ||
_createClass(OutgoingRTCSession, [{ | ||
key: "connect", | ||
@@ -163,7 +450,7 @@ value: function () { | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee(_ref2) { | ||
var _this = this; | ||
regeneratorRuntime.mark(function _callee() { | ||
var _this2 = this; | ||
var _ref2$timeoutMs, timeoutMs; | ||
var timeoutMs, | ||
_args = arguments; | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
@@ -173,33 +460,115 @@ while (1) { | ||
case 0: | ||
_ref2$timeoutMs = _ref2.timeoutMs, timeoutMs = _ref2$timeoutMs === void 0 ? 10000 : _ref2$timeoutMs; | ||
timeoutMs = _args.length > 0 && _args[0] !== undefined ? _args[0] : 10000; | ||
this.on('confirmed', this.handleOutboundSessionAccepted); | ||
this.on('failed', this.handleOutboundSessionFailed); // TODO: Confirmed or "accepted" event? | ||
return _context.abrupt("return", new Promise(function (resolve, reject) { | ||
var timeout = setTimeout(function () { | ||
reject(); | ||
_this2.connectTimeout = setTimeout(function () { | ||
reject(new Error("Outgoing RTC Session timed out after ".concat(timeoutMs, "ms"))); | ||
}, timeoutMs); | ||
_this2.acceptResolver = resolve; | ||
_this2.failedRejector = reject; | ||
})); | ||
var onConnected = function onConnected(data) { | ||
_this.sipUA.removeListener('connected', onConnected); | ||
case 4: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this); | ||
})); | ||
_this.sipUA.removeListener('disconnected', onDisconnected); | ||
function connect() { | ||
return _connect.apply(this, arguments); | ||
} | ||
clearTimeout(timeout); | ||
resolve(data); | ||
}; | ||
return connect; | ||
}() | ||
}]); | ||
var onDisconnected = function onDisconnected(data) { | ||
_this.sipUA.removeListener('connected', onConnected); | ||
return OutgoingRTCSession; | ||
}(RTCSession); | ||
_this.sipUA.removeListener('disconnected', onDisconnected); | ||
var WebRTCClient = | ||
/*#__PURE__*/ | ||
function () { | ||
function WebRTCClient(_ref) { | ||
var _this = this; | ||
clearTimeout(timeout); | ||
reject(data); | ||
}; | ||
var displayName = _ref.displayName, | ||
username = _ref.username, | ||
_ref$debug = _ref.debug, | ||
debug = _ref$debug === void 0 ? false : _ref$debug, | ||
jwt = _ref.jwt; | ||
_this.sipUA.on('connected', onConnected); | ||
_classCallCheck(this, WebRTCClient); | ||
_this.sipUA.on('disconnected', onDisconnected); | ||
_defineProperty(this, "eventEmitter", new EventEmitter()); | ||
_this.sipUA.start(); | ||
})); | ||
_defineProperty(this, "activeSessions", []); | ||
_defineProperty(this, "connected", void 0); | ||
_defineProperty(this, "jwt", void 0); | ||
_defineProperty(this, "sipUA", void 0); | ||
_defineProperty(this, "handleConnected", function (data) { | ||
_this.connected = true; | ||
_this.eventEmitter.emit('connected', data); | ||
}); | ||
_defineProperty(this, "handleDisconnected", function (data) { | ||
_this.connected = false; | ||
_this.eventEmitter.emit('disconnected', data); | ||
_this.activeSessions.forEach(function (session) { | ||
return session.disconnect(); | ||
}); | ||
}); | ||
this.connected = false; | ||
this.jwt = jwt; | ||
this.sipUA = new UserAgent({ | ||
register: false, | ||
// TODO: configurable? | ||
debug: debug, | ||
jwt: jwt, | ||
username: username, | ||
displayName: displayName | ||
}); | ||
this.sipUA.on('connected', this.handleConnected); | ||
this.sipUA.on('disconnected', this.handleDisconnected); | ||
} | ||
_createClass(WebRTCClient, [{ | ||
key: "on", | ||
value: function on(name, callback) { | ||
this.eventEmitter.on(name, callback); | ||
} | ||
}, { | ||
key: "removeEventListener", | ||
value: function removeEventListener(name, callback) { | ||
this.eventEmitter.removeListener(name, callback); | ||
} | ||
}, { | ||
key: "connect", | ||
value: function () { | ||
var _connect = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee() { | ||
var _ref2, | ||
_ref2$timeoutMs, | ||
timeoutMs, | ||
_args = arguments; | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
_ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, _ref2$timeoutMs = _ref2.timeoutMs, timeoutMs = _ref2$timeoutMs === void 0 ? 10000 : _ref2$timeoutMs; | ||
return _context.abrupt("return", this.sipUA.start(timeoutMs)); | ||
case 2: | ||
@@ -213,3 +582,3 @@ case "end": | ||
function connect(_x) { | ||
function connect() { | ||
return _connect.apply(this, arguments); | ||
@@ -221,33 +590,42 @@ } | ||
}, { | ||
key: "handleConnected", | ||
value: function handleConnected(data) { | ||
this.connected = true; | ||
if (this.listeners.connected) { | ||
this.listeners.connected.forEach(function (callback) { | ||
callback(data); | ||
}); | ||
} | ||
key: "disconnect", | ||
value: function disconnect() { | ||
this.sipUA.stop(); | ||
} | ||
}, { | ||
key: "handleDisconnected", | ||
value: function handleDisconnected(data) { | ||
this.connected = false; | ||
key: "startRTCSession", | ||
value: function startRTCSession(options) { | ||
var _this2 = this; | ||
if (this.listeners.disconnected) { | ||
this.listeners.disconnected.forEach(function (callback) { | ||
callback(data); | ||
}); | ||
if (!this.connected) { | ||
throw new Error('No active connection. Call `.connect()` first.'); | ||
} | ||
var session = new OutgoingRTCSession(this.sipUA, { | ||
to: options.to, | ||
jwt: this.jwt, | ||
onEnded: function onEnded(endedSession, data) { | ||
_this2.handleSessionEnded(endedSession); | ||
if (options.onEnded) { | ||
options.onEnded(endedSession, data); | ||
} | ||
} | ||
}); | ||
return session.connect(); | ||
} | ||
}, { | ||
key: "isConnected", | ||
get: function get() { | ||
return this.connected; | ||
key: "handleSessionEnded", | ||
value: function handleSessionEnded(rtcSession) { | ||
this.activeSessions = this.activeSessions.filter(function (session) { | ||
return session !== rtcSession; | ||
}); | ||
} | ||
}]); | ||
return WebRtcClient; | ||
return WebRTCClient; | ||
}(); | ||
module.exports = WebRtcClient; | ||
exports.WebRTCClient = WebRTCClient; | ||
exports.OutgoingRTCSession = OutgoingRTCSession; | ||
exports.RTCSession = RTCSession; |
@@ -1,1 +0,1 @@ | ||
"use strict";var jssip=require("jssip");function asyncGeneratorStep(e,n,t,r,i,o,s){try{var c=e[o](s),a=c.value}catch(e){return void t(e)}c.done?n(a):Promise.resolve(a).then(r,i)}function _asyncToGenerator(e){return function(){var n=this,t=arguments;return new Promise(function(r,i){var o=e.apply(n,t);function s(e){asyncGeneratorStep(o,r,i,s,c,"next",e)}function c(e){asyncGeneratorStep(o,r,i,s,c,"throw",e)}s(void 0)})}}function _classCallCheck(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,n){for(var t=0;t<n.length;t++){var r=n[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,n,t){return n&&_defineProperties(e.prototype,n),t&&_defineProperties(e,t),e}function _defineProperty(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_nonIterableSpread()}function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var n=0,t=new Array(e.length);n<e.length;n++)t[n]=e[n];return t}}function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}var RtcSocketUrl="wss://".concat(void 0),API_HOST=void 0;function makeSipUserAgent(e){var n=new jssip.WebSocketInterface(RtcSocketUrl);return new jssip.UA({sockets:[n],register:e.register||!1,uri:"sip:".concat(e.displayName,"@").concat(API_HOST)})}var WebRtcClient=function(){function e(n){var t=n.displayName,r=n.register,i=void 0!==r&&r;_classCallCheck(this,e),_defineProperty(this,"listeners",{}),_defineProperty(this,"connected",void 0),_defineProperty(this,"sipUA",void 0),this.connected=!1,this.sipUA=makeSipUserAgent({register:i,displayName:t}),this.sipUA.on("connected",this.handleConnected),this.sipUA.on("disconnected",this.handleDisconnected)}return _createClass(e,[{key:"on",value:function(e,n){this.listeners[e]?this.listeners[e]=[].concat(_toConsumableArray(this.listeners[e]),[n]):this.listeners[e]=[n]}},{key:"removeEventListener",value:function(e,n){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(function(e){return e===n}))}},{key:"connect",value:function(){var e=_asyncToGenerator(regeneratorRuntime.mark(function e(n){var t,r,i=this;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=n.timeoutMs,r=void 0===t?1e4:t,e.abrupt("return",new Promise(function(e,n){var t=setTimeout(function(){n()},r),o=function n(r){i.sipUA.removeListener("connected",n),i.sipUA.removeListener("disconnected",s),clearTimeout(t),e(r)},s=function e(r){i.sipUA.removeListener("connected",o),i.sipUA.removeListener("disconnected",e),clearTimeout(t),n(r)};i.sipUA.on("connected",o),i.sipUA.on("disconnected",s),i.sipUA.start()}));case 2:case"end":return e.stop()}},e,this)}));return function(n){return e.apply(this,arguments)}}()},{key:"handleConnected",value:function(e){this.connected=!0,this.listeners.connected&&this.listeners.connected.forEach(function(n){n(e)})}},{key:"handleDisconnected",value:function(e){this.connected=!1,this.listeners.disconnected&&this.listeners.disconnected.forEach(function(n){n(e)})}},{key:"isConnected",get:function(){return this.connected}}]),e}();module.exports=WebRtcClient; | ||
"use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var jssip=require("jssip"),EventEmitter=_interopDefault(require("events"));function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}var runtime=createCommonjsModule(function(e){!function(t){var n,r=Object.prototype,o=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},s=i.iterator||"@@iterator",a=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag",u=t.regeneratorRuntime;if(u)e.exports=u;else{(u=t.regeneratorRuntime=e.exports).wrap=_;var l="suspendedStart",f="suspendedYield",h="executing",d="completed",p={},y={};y[s]=function(){return this};var v=Object.getPrototypeOf,m=v&&v(v(k([])));m&&m!==r&&o.call(m,s)&&(y=m);var g=b.prototype=T.prototype=Object.create(y);C.prototype=g.constructor=b,b.constructor=C,b[c]=C.displayName="GeneratorFunction",u.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===C||"GeneratorFunction"===(t.displayName||t.name))},u.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,b):(e.__proto__=b,c in e||(e[c]="GeneratorFunction")),e.prototype=Object.create(g),e},u.awrap=function(e){return{__await:e}},S(E.prototype),E.prototype[a]=function(){return this},u.AsyncIterator=E,u.async=function(e,t,n,r){var o=new E(_(e,t,n,r));return u.isGeneratorFunction(t)?o:o.next().then(function(e){return e.done?e.value:o.next()})},S(g),g[c]="Generator",g[s]=function(){return this},g.toString=function(){return"[object Generator]"},u.keys=function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},u.values=k,j.prototype={constructor:j,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(O),!e)for(var t in this)"t"===t.charAt(0)&&o.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=n)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(r,o){return a.type="throw",a.arg=e,t.next=r,o&&(t.method="next",t.arg=n),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var s=this.tryEntries[i],a=s.completion;if("root"===s.tryLoc)return r("end");if(s.tryLoc<=this.prev){var c=o.call(s,"catchLoc"),u=o.call(s,"finallyLoc");if(c&&u){if(this.prev<s.catchLoc)return r(s.catchLoc,!0);if(this.prev<s.finallyLoc)return r(s.finallyLoc)}else if(c){if(this.prev<s.catchLoc)return r(s.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return r(s.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var s=i?i.completion:{};return s.type=e,s.arg=t,i?(this.method="next",this.next=i.finallyLoc,p):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),p},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),O(n),p}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var o=r.arg;O(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:k(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=n),p}}}function _(e,t,n,r){var o=t&&t.prototype instanceof T?t:T,i=Object.create(o.prototype),s=new j(r||[]);return i._invoke=function(e,t,n){var r=l;return function(o,i){if(r===h)throw new Error("Generator is already running");if(r===d){if("throw"===o)throw i;return x()}for(n.method=o,n.arg=i;;){var s=n.delegate;if(s){var a=R(s,n);if(a){if(a===p)continue;return a}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===l)throw r=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=h;var c=w(e,t,n);if("normal"===c.type){if(r=n.done?d:f,c.arg===p)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r=d,n.method="throw",n.arg=c.arg)}}}(e,n,s),i}function w(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}function T(){}function C(){}function b(){}function S(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function E(e){var t;this._invoke=function(n,r){function i(){return new Promise(function(t,i){!function t(n,r,i,s){var a=w(e[n],e,r);if("throw"!==a.type){var c=a.arg,u=c.value;return u&&"object"==typeof u&&o.call(u,"__await")?Promise.resolve(u.__await).then(function(e){t("next",e,i,s)},function(e){t("throw",e,i,s)}):Promise.resolve(u).then(function(e){c.value=e,i(c)},function(e){return t("throw",e,i,s)})}s(a.arg)}(n,r,t,i)})}return t=t?t.then(i,i):i()}}function R(e,t){var r=e.iterator[t.method];if(r===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=n,R(e,t),"throw"===t.method))return p;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return p}var o=w(r,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,p;var i=o.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=n),t.delegate=null,p):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,p)}function P(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function O(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function j(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(P,this),this.reset(!0)}function k(e){if(e){var t=e[s];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r<e.length;)if(o.call(e,r))return t.value=e[r],t.done=!1,t;return t.value=n,t.done=!0,t};return i.next=i}}return{next:x}}function x(){return{value:n,done:!0}}}(function(){return this||"object"==typeof self&&self}()||Function("return this")())}),g=function(){return this||"object"==typeof self&&self}()||Function("return this")(),hadRuntime=g.regeneratorRuntime&&Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime")>=0,oldRuntime=hadRuntime&&g.regeneratorRuntime;g.regeneratorRuntime=void 0;var runtimeModule=runtime;if(hadRuntime)g.regeneratorRuntime=oldRuntime;else try{delete g.regeneratorRuntime}catch(e){g.regeneratorRuntime=void 0}var regenerator=runtimeModule;function asyncGeneratorStep(e,t,n,r,o,i,s){try{var a=e[i](s),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(r,o){var i=e.apply(t,n);function s(e){asyncGeneratorStep(i,r,o,s,a,"next",e)}function a(e){asyncGeneratorStep(i,r,o,s,a,"throw",e)}s(void 0)})}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _typeof2(e){return(_typeof2="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(e){return _typeof2(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":_typeof2(e)})(e)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _possibleConstructorReturn(e,t){return!t||"object"!==_typeof(t)&&"function"!=typeof t?_assertThisInitialized(e):t}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function _superPropBase(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=_getPrototypeOf(e)););return e}function _get(e,t,n){return(_get="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var r=_superPropBase(e,t);if(r){var o=Object.getOwnPropertyDescriptor(r,t);return o.get?o.get.call(n):o.value}})(e,t,n||e)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&_setPrototypeOf(e,t)}var Status,RTC_SOCKET_URL="wss://".concat("webrtc-staging.messagebird.io"),API_HOST="webrtc-staging.messagebird.io",USERNAME_REGEX=/^\S*$/,validateOptions=function(e){if(!e.username)throw new Error("You must pass a username.");if(!USERNAME_REGEX.test(e.username))throw new Error("Username cannot contain any spaces")},UserAgent=function(e){function t(e){var n;_classCallCheck(this,t),validateOptions(e);var r=new jssip.WebSocketInterface(RTC_SOCKET_URL);return _defineProperty(_assertThisInitialized(_assertThisInitialized(n=_possibleConstructorReturn(this,_getPrototypeOf(t).call(this,{sockets:[r],register:!0,uri:"sip:".concat(e.username,"@").concat(API_HOST),display_name:e.displayName})))),"connectTimeout",void 0),_defineProperty(_assertThisInitialized(_assertThisInitialized(n)),"resolveDisconnect",void 0),_defineProperty(_assertThisInitialized(_assertThisInitialized(n)),"resolveConnection",void 0),_defineProperty(_assertThisInitialized(_assertThisInitialized(n)),"rejectConnection",void 0),n.registrator().setExtraHeaders(["X-Token: ".concat(e.jwt)]),n.on("connected",n.handleConnected),n.on("disconnected",n.handleDisconnected),n}return _inherits(t,jssip.UA),_createClass(t,[{key:"start",value:function(){var e=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return new Promise(function(r,o){e.connectTimeout=setTimeout(function(){e.resolveConnection=null,e.rejectConnection=null,o(new Error("Connectioned timed out after ".concat(n,"ms")))},n),e.resolveConnection=r,e.rejectConnection=o,_get(_getPrototypeOf(t.prototype),"start",e).call(e)})}},{key:"stop",value:function(){var e=this;return new Promise(function(n){e.resolveDisconnect=n,_get(_getPrototypeOf(t.prototype),"stop",e).call(e)})}},{key:"handleConnected",value:function(e){this.resolveConnection&&(clearTimeout(this.connectTimeout),this.resolveConnection(e),this.resolveConnection=null,this.rejectConnection=null)}},{key:"handleDisconnected",value:function(e){this.rejectConnection&&(clearTimeout(this.connectTimeout),this.rejectConnection(new Error("Could not connect to WebRTC Socket: ".concat(e.reason))),this.resolveConnection=null,this.rejectConnection=null),this.resolveDisconnect&&(this.resolveDisconnect(e),this.resolveDisconnect=null)}}]),t}();function createStreamTarget(e){var t=document.createElement("video");return t.setAttribute("autoplay","true"),t.setAttribute("style","display: none;"),t.srcObject=e,document.body.appendChild(t),t}function removeStreamTarget(e){if(e.remove)e.remove();else try{document.body.removeChild(e)}catch(e){}}!function(e){e.Initial="initial",e.Connecting="connecting",e.Failed="failed",e.Accepted="accepted",e.Confirmed="confirmed",e.Disconnected="disconnected"}(Status||(Status={}));var RTCSession=function(){function e(t){var n=this;_classCallCheck(this,e),_defineProperty(this,"status",void 0),_defineProperty(this,"eventEmitter",new EventEmitter),_defineProperty(this,"sipRTCSession",void 0),_defineProperty(this,"streamTargets",void 0),_defineProperty(this,"sendDTMF",function(e){n.sipRTCSession.sendDTMF(e)}),_defineProperty(this,"handleAccepted",function(){n.status=Status.Accepted}),_defineProperty(this,"handleConfirmed",function(e){n.status=Status.Confirmed,n.eventEmitter.emit("confirmed",e)}),_defineProperty(this,"handleEnded",function(e){n.status=Status.Disconnected,n.eventEmitter.emit("ended",e)}),_defineProperty(this,"handleFailed",function(e){n.status=Status.Failed,n.eventEmitter.emit("failed",e)}),_defineProperty(this,"handleAddTrack",function(e){n.streamTargets=e.streams.map(function(e){return createStreamTarget(e)})}),this.sipRTCSession=t,this.sipRTCSession.connection.addEventListener("track",this.handleAddTrack),this.sipRTCSession.on("accepted",this.handleAccepted),this.sipRTCSession.on("confirmed",this.handleConfirmed),this.sipRTCSession.on("ended",this.handleEnded),this.sipRTCSession.on("failed",this.handleFailed)}return _createClass(e,[{key:"on",value:function(e,t){this.eventEmitter.on(e,t)}},{key:"removeEventlistener",value:function(e,t){this.eventEmitter.removeListener(e,t)}},{key:"disconnect",value:function(){this.streamTargets.forEach(function(e){return removeStreamTarget(e)}),this.sipRTCSession.terminate()}}]),e}(),OutgoingRTCSession=function(e){function t(e,n){var r,o=n.to,i=n.jwt,s=n.onEnded;return _classCallCheck(this,t),_defineProperty(_assertThisInitialized(_assertThisInitialized(r=_possibleConstructorReturn(this,_getPrototypeOf(t).call(this,e.call("sip:".concat(o,"@").concat(API_HOST),{mediaConstraints:{audio:!0,video:!1},extraHeaders:["X-Token: ".concat(i)]}))))),"connectTimeout",void 0),_defineProperty(_assertThisInitialized(_assertThisInitialized(r)),"acceptResolver",void 0),_defineProperty(_assertThisInitialized(_assertThisInitialized(r)),"failedRejector",void 0),_defineProperty(_assertThisInitialized(_assertThisInitialized(r)),"handleOutboundSessionAccepted",function(){r.acceptResolver&&(r.acceptResolver(_assertThisInitialized(_assertThisInitialized(r))),r.acceptResolver=void 0,r.failedRejector=void 0,clearTimeout(r.connectTimeout))}),_defineProperty(_assertThisInitialized(_assertThisInitialized(r)),"handleOutboundSessionFailed",function(e){r.failedRejector&&(r.failedRejector(e),r.acceptResolver=void 0,r.failedRejector=void 0,clearTimeout(r.connectTimeout))}),r.status=Status.Connecting,r.on("confirmed",r.handleOutboundSessionAccepted),r.on("failed",r.handleOutboundSessionFailed),r.on("ended",function(e){return s(_assertThisInitialized(_assertThisInitialized(r)),e)}),r}return _inherits(t,RTCSession),_createClass(t,[{key:"connect",value:function(){var e=_asyncToGenerator(regenerator.mark(function e(){var t,n=this,r=arguments;return regenerator.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=r.length>0&&void 0!==r[0]?r[0]:1e4,this.on("confirmed",this.handleOutboundSessionAccepted),this.on("failed",this.handleOutboundSessionFailed),e.abrupt("return",new Promise(function(e,r){n.connectTimeout=setTimeout(function(){r(new Error("Outgoing RTC Session timed out after ".concat(t,"ms")))},t),n.acceptResolver=e,n.failedRejector=r}));case 4:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()}]),t}(),IncomingRTCSession=function(e){function t(e){return _classCallCheck(this,t),_possibleConstructorReturn(this,_getPrototypeOf(t).call(this,e))}return _inherits(t,RTCSession),_createClass(t,[{key:"answer",value:function(){this.sipRTCSession.answer(),this.eventEmitter.emit("answer",this)}}]),t}(),WebRTCClient=function(){function e(t){var n=this,r=t.displayName,o=t.username,i=t.debug,s=void 0!==i&&i,a=t.jwt;_classCallCheck(this,e),_defineProperty(this,"eventEmitter",new EventEmitter),_defineProperty(this,"activeSessions",[]),_defineProperty(this,"connected",void 0),_defineProperty(this,"jwt",void 0),_defineProperty(this,"sipUA",void 0),_defineProperty(this,"handleConnected",function(e){n.connected=!0,n.eventEmitter.emit("connected",e)}),_defineProperty(this,"handleDisconnected",function(e){n.connected=!1,n.eventEmitter.emit("disconnected",e),n.activeSessions.forEach(function(e){return e.disconnect()})}),this.connected=!1,this.jwt=a,this.sipUA=new UserAgent({register:!1,debug:s,jwt:a,username:o,displayName:r}),this.sipUA.on("connected",this.handleConnected),this.sipUA.on("disconnected",this.handleDisconnected),this.sipUA.on("newRTCSession",this.handleNewSession)}return _createClass(e,[{key:"on",value:function(e,t){this.eventEmitter.on(e,t)}},{key:"removeEventListener",value:function(e,t){this.eventEmitter.removeListener(e,t)}},{key:"connect",value:function(){var e=_asyncToGenerator(regenerator.mark(function e(){var t,n,r,o=arguments;return regenerator.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=o.length>0&&void 0!==o[0]?o[0]:{},n=t.timeoutMs,r=void 0===n?1e4:n,e.abrupt("return",this.sipUA.start(r));case 2:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()},{key:"disconnect",value:function(){this.sipUA.stop()}},{key:"startRTCSession",value:function(e){var t=this;if(!this.connected)throw new Error("No active connection. Call `.connect()` first.");return new OutgoingRTCSession(this.sipUA,{to:e.to,jwt:this.jwt,onEnded:function(n,r){t.handleSessionEnded(n),e.onEnded&&e.onEnded(n,r)}}).connect()}},{key:"handleSessionEnded",value:function(e){this.activeSessions=this.activeSessions.filter(function(t){return t!==e})}},{key:"handleNewSession",value:function(e){if("remote"===e.originator)new IncomingRTCSession(e.session)}}]),e}();exports.WebRTCClient=WebRTCClient,exports.OutgoingRTCSession=OutgoingRTCSession,exports.RTCSession=RTCSession; |
import { WebSocketInterface, UA } from 'jssip'; | ||
import EventEmitter from 'events'; | ||
@@ -76,82 +77,364 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { | ||
function _toConsumableArray(arr) { | ||
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); | ||
function _inherits(subClass, superClass) { | ||
if (typeof superClass !== "function" && superClass !== null) { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
subClass.prototype = Object.create(superClass && superClass.prototype, { | ||
constructor: { | ||
value: subClass, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
if (superClass) _setPrototypeOf(subClass, superClass); | ||
} | ||
function _arrayWithoutHoles(arr) { | ||
if (Array.isArray(arr)) { | ||
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
return arr2; | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _assertThisInitialized(self) { | ||
if (self === void 0) { | ||
throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); | ||
} | ||
return self; | ||
} | ||
function _iterableToArray(iter) { | ||
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); | ||
function _possibleConstructorReturn(self, call) { | ||
if (call && (typeof call === "object" || typeof call === "function")) { | ||
return call; | ||
} | ||
return _assertThisInitialized(self); | ||
} | ||
function _nonIterableSpread() { | ||
throw new TypeError("Invalid attempt to spread non-iterable instance"); | ||
function _superPropBase(object, property) { | ||
while (!Object.prototype.hasOwnProperty.call(object, property)) { | ||
object = _getPrototypeOf(object); | ||
if (object === null) break; | ||
} | ||
return object; | ||
} | ||
var RtcSocketUrl = "wss://".concat(undefined); | ||
var API_HOST = undefined; | ||
function _get(target, property, receiver) { | ||
if (typeof Reflect !== "undefined" && Reflect.get) { | ||
_get = Reflect.get; | ||
} else { | ||
_get = function _get(target, property, receiver) { | ||
var base = _superPropBase(target, property); | ||
function makeSipUserAgent(options) { | ||
var ws = new WebSocketInterface(RtcSocketUrl); | ||
var ua = new UA({ | ||
sockets: [ws], | ||
register: options.register || false, | ||
uri: "sip:".concat(options.displayName, "@").concat(API_HOST) | ||
}); | ||
return ua; | ||
if (!base) return; | ||
var desc = Object.getOwnPropertyDescriptor(base, property); | ||
if (desc.get) { | ||
return desc.get.call(receiver); | ||
} | ||
return desc.value; | ||
}; | ||
} | ||
return _get(target, property, receiver || target); | ||
} | ||
var WebRtcClient = | ||
var RTC_SOCKET_URL = "wss://".concat("webrtc-staging.messagebird.io"); | ||
var API_HOST = "webrtc-staging.messagebird.io"; | ||
var USERNAME_REGEX = /^\S*$/; | ||
var validateOptions = function validateOptions(options) { | ||
if (!options.username) { | ||
throw new Error('You must pass a username.'); | ||
} | ||
if (!USERNAME_REGEX.test(options.username)) { | ||
throw new Error("Username cannot contain any spaces"); | ||
} | ||
}; | ||
var UserAgent = | ||
/*#__PURE__*/ | ||
function (_SipUserAgent) { | ||
_inherits(UserAgent, _SipUserAgent); | ||
function UserAgent(options) { | ||
var _this; | ||
_classCallCheck(this, UserAgent); | ||
validateOptions(options); | ||
var ws = new WebSocketInterface(RTC_SOCKET_URL); | ||
_this = _possibleConstructorReturn(this, _getPrototypeOf(UserAgent).call(this, { | ||
sockets: [ws], | ||
register: true, | ||
uri: "sip:".concat(options.username, "@").concat(API_HOST), | ||
display_name: options.displayName | ||
})); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "connectTimeout", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "resolveDisconnect", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "resolveConnection", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "rejectConnection", void 0); | ||
_this.registrator().setExtraHeaders(["X-Token: ".concat(options.jwt)]); | ||
_this.on('connected', _this.handleConnected); | ||
_this.on('disconnected', _this.handleDisconnected); | ||
return _this; | ||
} | ||
_createClass(UserAgent, [{ | ||
key: "start", | ||
value: function start() { | ||
var _this2 = this; | ||
var timeoutMs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10000; | ||
return new Promise(function (resolve, reject) { | ||
_this2.connectTimeout = setTimeout(function () { | ||
_this2.resolveConnection = null; | ||
_this2.rejectConnection = null; | ||
reject(new Error("Connectioned timed out after ".concat(timeoutMs, "ms"))); | ||
}, timeoutMs); | ||
_this2.resolveConnection = resolve; | ||
_this2.rejectConnection = reject; | ||
_get(_getPrototypeOf(UserAgent.prototype), "start", _this2).call(_this2); | ||
}); | ||
} | ||
}, { | ||
key: "stop", | ||
value: function stop() { | ||
var _this3 = this; | ||
return new Promise(function (resolve) { | ||
_this3.resolveDisconnect = resolve; | ||
_get(_getPrototypeOf(UserAgent.prototype), "stop", _this3).call(_this3); | ||
}); | ||
} | ||
}, { | ||
key: "handleConnected", | ||
value: function handleConnected(data) { | ||
if (this.resolveConnection) { | ||
clearTimeout(this.connectTimeout); | ||
this.resolveConnection(data); | ||
this.resolveConnection = null; | ||
this.rejectConnection = null; | ||
} | ||
} | ||
}, { | ||
key: "handleDisconnected", | ||
value: function handleDisconnected(data) { | ||
if (this.rejectConnection) { | ||
clearTimeout(this.connectTimeout); | ||
this.rejectConnection(new Error("Could not connect to WebRTC Socket: ".concat(data.reason))); | ||
this.resolveConnection = null; | ||
this.rejectConnection = null; | ||
} | ||
if (this.resolveDisconnect) { | ||
this.resolveDisconnect(data); | ||
this.resolveDisconnect = null; | ||
} | ||
} | ||
}]); | ||
return UserAgent; | ||
}(UA); | ||
function createStreamTarget(stream) { | ||
var video = document.createElement('video'); | ||
video.setAttribute('autoplay', 'true'); | ||
video.setAttribute('style', 'display: none;'); | ||
video.srcObject = stream; | ||
document.body.appendChild(video); | ||
return video; | ||
} | ||
function removeStreamTarget(target) { | ||
if (target.remove) { | ||
target.remove(); | ||
return; | ||
} | ||
try { | ||
document.body.removeChild(target); | ||
} catch (err) {// TODO: FIXME | ||
// sometimes this fails? does it matter if a hidden video tag stays? | ||
} | ||
} | ||
var Status; | ||
(function (Status) { | ||
Status["Initial"] = "initial"; | ||
Status["Connecting"] = "connecting"; | ||
Status["Failed"] = "failed"; | ||
Status["Accepted"] = "accepted"; | ||
Status["Confirmed"] = "confirmed"; | ||
Status["Disconnected"] = "disconnected"; | ||
})(Status || (Status = {})); | ||
var RTCSession = | ||
/*#__PURE__*/ | ||
function () { | ||
function WebRtcClient(_ref) { | ||
var displayName = _ref.displayName, | ||
_ref$register = _ref.register, | ||
register = _ref$register === void 0 ? false : _ref$register; | ||
function RTCSession(sipRtcSession) { | ||
var _this = this; | ||
_classCallCheck(this, WebRtcClient); | ||
_classCallCheck(this, RTCSession); | ||
_defineProperty(this, "listeners", {}); | ||
_defineProperty(this, "status", void 0); | ||
_defineProperty(this, "connected", void 0); | ||
_defineProperty(this, "streamTargets", void 0); | ||
_defineProperty(this, "sipUA", void 0); | ||
_defineProperty(this, "eventEmitter", new EventEmitter()); | ||
this.connected = false; | ||
this.sipUA = makeSipUserAgent({ | ||
register: register, | ||
displayName: displayName | ||
_defineProperty(this, "sipRTCSession", void 0); | ||
_defineProperty(this, "sendDTMF", function (key) { | ||
_this.sipRTCSession.sendDTMF(key); | ||
}); | ||
this.sipUA.on('connected', this.handleConnected); | ||
this.sipUA.on('disconnected', this.handleDisconnected); | ||
_defineProperty(this, "handleAccepted", function () { | ||
_this.status = Status.Accepted; | ||
}); | ||
_defineProperty(this, "handleConfirmed", function (data) { | ||
_this.status = Status.Confirmed; | ||
_this.eventEmitter.emit('confirmed', data); | ||
}); | ||
_defineProperty(this, "handleEnded", function (data) { | ||
_this.status = Status.Disconnected; | ||
_this.eventEmitter.emit('ended', data); | ||
}); | ||
_defineProperty(this, "handleFailed", function (data) { | ||
_this.status = Status.Failed; | ||
_this.eventEmitter.emit('failed', data); | ||
}); | ||
_defineProperty(this, "handleAddTrack", function (data) { | ||
_this.streamTargets = data.streams.map(function (stream) { | ||
return createStreamTarget(stream); | ||
}); | ||
}); | ||
this.sipRTCSession = sipRtcSession; | ||
this.sipRTCSession.connection.addEventListener('track', this.handleAddTrack); | ||
this.sipRTCSession.on('accepted', this.handleAccepted); | ||
this.sipRTCSession.on('confirmed', this.handleConfirmed); | ||
this.sipRTCSession.on('ended', this.handleEnded); | ||
this.sipRTCSession.on('failed', this.handleFailed); | ||
} | ||
_createClass(WebRtcClient, [{ | ||
_createClass(RTCSession, [{ | ||
key: "on", | ||
value: function on(name, callback) { | ||
if (!this.listeners[name]) { | ||
this.listeners[name] = [callback]; | ||
return; | ||
} | ||
this.listeners[name] = [].concat(_toConsumableArray(this.listeners[name]), [callback]); | ||
value: function on(name, cb) { | ||
this.eventEmitter.on(name, cb); | ||
} | ||
}, { | ||
key: "removeEventListener", | ||
value: function removeEventListener(name, callback) { | ||
if (this.listeners[name]) { | ||
this.listeners[name] = this.listeners[name].filter(function (listener) { | ||
return listener === callback; | ||
}); | ||
key: "removeEventlistener", | ||
value: function removeEventlistener(name, cb) { | ||
this.eventEmitter.removeListener(name, cb); | ||
} | ||
}, { | ||
key: "disconnect", | ||
// TODO: whassa good name? | ||
value: function disconnect() { | ||
this.streamTargets.forEach(function (target) { | ||
return removeStreamTarget(target); | ||
}); | ||
this.sipRTCSession.terminate(); | ||
} | ||
}]); | ||
return RTCSession; | ||
}(); | ||
var OutgoingRTCSession = | ||
/*#__PURE__*/ | ||
function (_RTCSession) { | ||
_inherits(OutgoingRTCSession, _RTCSession); | ||
function OutgoingRTCSession(ua, _ref) { | ||
var _this; | ||
var to = _ref.to, | ||
jwt = _ref.jwt, | ||
onEnded = _ref.onEnded; | ||
_classCallCheck(this, OutgoingRTCSession); | ||
_this = _possibleConstructorReturn(this, _getPrototypeOf(OutgoingRTCSession).call(this, ua.call("sip:".concat(to, "@").concat(API_HOST), { | ||
mediaConstraints: { | ||
audio: true, | ||
video: false // TODO: what if we support video? | ||
}, | ||
extraHeaders: ["X-Token: ".concat(jwt)] | ||
}))); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "connectTimeout", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "acceptResolver", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "failedRejector", void 0); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleOutboundSessionAccepted", function () { | ||
if (_this.acceptResolver) { | ||
_this.acceptResolver(_assertThisInitialized(_assertThisInitialized(_this))); | ||
_this.acceptResolver = undefined; | ||
_this.failedRejector = undefined; | ||
clearTimeout(_this.connectTimeout); | ||
} | ||
} // FIXME: This not nice. How to promisify this best? | ||
// Do we need promises for this? | ||
}); | ||
}, { | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleOutboundSessionFailed", function (data) { | ||
if (_this.failedRejector) { | ||
_this.failedRejector(data); | ||
_this.acceptResolver = undefined; | ||
_this.failedRejector = undefined; | ||
clearTimeout(_this.connectTimeout); | ||
} | ||
}); | ||
_this.status = Status.Connecting; | ||
_this.on('confirmed', _this.handleOutboundSessionAccepted); | ||
_this.on('failed', _this.handleOutboundSessionFailed); | ||
_this.on('ended', function (data) { | ||
return onEnded(_assertThisInitialized(_assertThisInitialized(_this)), data); | ||
}); | ||
return _this; | ||
} | ||
_createClass(OutgoingRTCSession, [{ | ||
key: "connect", | ||
@@ -161,7 +444,7 @@ value: function () { | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee(_ref2) { | ||
var _this = this; | ||
regeneratorRuntime.mark(function _callee() { | ||
var _this2 = this; | ||
var _ref2$timeoutMs, timeoutMs; | ||
var timeoutMs, | ||
_args = arguments; | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
@@ -171,33 +454,115 @@ while (1) { | ||
case 0: | ||
_ref2$timeoutMs = _ref2.timeoutMs, timeoutMs = _ref2$timeoutMs === void 0 ? 10000 : _ref2$timeoutMs; | ||
timeoutMs = _args.length > 0 && _args[0] !== undefined ? _args[0] : 10000; | ||
this.on('confirmed', this.handleOutboundSessionAccepted); | ||
this.on('failed', this.handleOutboundSessionFailed); // TODO: Confirmed or "accepted" event? | ||
return _context.abrupt("return", new Promise(function (resolve, reject) { | ||
var timeout = setTimeout(function () { | ||
reject(); | ||
_this2.connectTimeout = setTimeout(function () { | ||
reject(new Error("Outgoing RTC Session timed out after ".concat(timeoutMs, "ms"))); | ||
}, timeoutMs); | ||
_this2.acceptResolver = resolve; | ||
_this2.failedRejector = reject; | ||
})); | ||
var onConnected = function onConnected(data) { | ||
_this.sipUA.removeListener('connected', onConnected); | ||
case 4: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this); | ||
})); | ||
_this.sipUA.removeListener('disconnected', onDisconnected); | ||
function connect() { | ||
return _connect.apply(this, arguments); | ||
} | ||
clearTimeout(timeout); | ||
resolve(data); | ||
}; | ||
return connect; | ||
}() | ||
}]); | ||
var onDisconnected = function onDisconnected(data) { | ||
_this.sipUA.removeListener('connected', onConnected); | ||
return OutgoingRTCSession; | ||
}(RTCSession); | ||
_this.sipUA.removeListener('disconnected', onDisconnected); | ||
var WebRTCClient = | ||
/*#__PURE__*/ | ||
function () { | ||
function WebRTCClient(_ref) { | ||
var _this = this; | ||
clearTimeout(timeout); | ||
reject(data); | ||
}; | ||
var displayName = _ref.displayName, | ||
username = _ref.username, | ||
_ref$debug = _ref.debug, | ||
debug = _ref$debug === void 0 ? false : _ref$debug, | ||
jwt = _ref.jwt; | ||
_this.sipUA.on('connected', onConnected); | ||
_classCallCheck(this, WebRTCClient); | ||
_this.sipUA.on('disconnected', onDisconnected); | ||
_defineProperty(this, "eventEmitter", new EventEmitter()); | ||
_this.sipUA.start(); | ||
})); | ||
_defineProperty(this, "activeSessions", []); | ||
_defineProperty(this, "connected", void 0); | ||
_defineProperty(this, "jwt", void 0); | ||
_defineProperty(this, "sipUA", void 0); | ||
_defineProperty(this, "handleConnected", function (data) { | ||
_this.connected = true; | ||
_this.eventEmitter.emit('connected', data); | ||
}); | ||
_defineProperty(this, "handleDisconnected", function (data) { | ||
_this.connected = false; | ||
_this.eventEmitter.emit('disconnected', data); | ||
_this.activeSessions.forEach(function (session) { | ||
return session.disconnect(); | ||
}); | ||
}); | ||
this.connected = false; | ||
this.jwt = jwt; | ||
this.sipUA = new UserAgent({ | ||
register: false, | ||
// TODO: configurable? | ||
debug: debug, | ||
jwt: jwt, | ||
username: username, | ||
displayName: displayName | ||
}); | ||
this.sipUA.on('connected', this.handleConnected); | ||
this.sipUA.on('disconnected', this.handleDisconnected); | ||
} | ||
_createClass(WebRTCClient, [{ | ||
key: "on", | ||
value: function on(name, callback) { | ||
this.eventEmitter.on(name, callback); | ||
} | ||
}, { | ||
key: "removeEventListener", | ||
value: function removeEventListener(name, callback) { | ||
this.eventEmitter.removeListener(name, callback); | ||
} | ||
}, { | ||
key: "connect", | ||
value: function () { | ||
var _connect = _asyncToGenerator( | ||
/*#__PURE__*/ | ||
regeneratorRuntime.mark(function _callee() { | ||
var _ref2, | ||
_ref2$timeoutMs, | ||
timeoutMs, | ||
_args = arguments; | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
_ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, _ref2$timeoutMs = _ref2.timeoutMs, timeoutMs = _ref2$timeoutMs === void 0 ? 10000 : _ref2$timeoutMs; | ||
return _context.abrupt("return", this.sipUA.start(timeoutMs)); | ||
case 2: | ||
@@ -211,3 +576,3 @@ case "end": | ||
function connect(_x) { | ||
function connect() { | ||
return _connect.apply(this, arguments); | ||
@@ -219,33 +584,40 @@ } | ||
}, { | ||
key: "handleConnected", | ||
value: function handleConnected(data) { | ||
this.connected = true; | ||
if (this.listeners.connected) { | ||
this.listeners.connected.forEach(function (callback) { | ||
callback(data); | ||
}); | ||
} | ||
key: "disconnect", | ||
value: function disconnect() { | ||
this.sipUA.stop(); | ||
} | ||
}, { | ||
key: "handleDisconnected", | ||
value: function handleDisconnected(data) { | ||
this.connected = false; | ||
key: "startRTCSession", | ||
value: function startRTCSession(options) { | ||
var _this2 = this; | ||
if (this.listeners.disconnected) { | ||
this.listeners.disconnected.forEach(function (callback) { | ||
callback(data); | ||
}); | ||
if (!this.connected) { | ||
throw new Error('No active connection. Call `.connect()` first.'); | ||
} | ||
var session = new OutgoingRTCSession(this.sipUA, { | ||
to: options.to, | ||
jwt: this.jwt, | ||
onEnded: function onEnded(endedSession, data) { | ||
_this2.handleSessionEnded(endedSession); | ||
if (options.onEnded) { | ||
options.onEnded(endedSession, data); | ||
} | ||
} | ||
}); | ||
return session.connect(); | ||
} | ||
}, { | ||
key: "isConnected", | ||
get: function get() { | ||
return this.connected; | ||
key: "handleSessionEnded", | ||
value: function handleSessionEnded(rtcSession) { | ||
this.activeSessions = this.activeSessions.filter(function (session) { | ||
return session !== rtcSession; | ||
}); | ||
} | ||
}]); | ||
return WebRtcClient; | ||
return WebRTCClient; | ||
}(); | ||
export default WebRtcClient; | ||
export { WebRTCClient, OutgoingRTCSession, RTCSession }; |
@@ -1,1 +0,1 @@ | ||
import{WebSocketInterface as e,UA as n}from"jssip";function t(e,n,t,i,r,o,s){try{var c=e[o](s),a=c.value}catch(e){return void t(e)}c.done?n(a):Promise.resolve(a).then(i,r)}function i(e,n){for(var t=0;t<n.length;t++){var i=n[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function r(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function o(e){return function(e){if(Array.isArray(e)){for(var n=0,t=new Array(e.length);n<e.length;n++)t[n]=e[n];return t}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var s="wss://".concat(void 0),c=void 0;export default(function(){function a(t){var i,o,u=t.displayName,l=t.register,d=void 0!==l&&l;!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,a),r(this,"listeners",{}),r(this,"connected",void 0),r(this,"sipUA",void 0),this.connected=!1,this.sipUA=(i={register:d,displayName:u},o=new e(s),new n({sockets:[o],register:i.register||!1,uri:"sip:".concat(i.displayName,"@").concat(c)})),this.sipUA.on("connected",this.handleConnected),this.sipUA.on("disconnected",this.handleDisconnected)}var u,l,d;return u=a,(l=[{key:"on",value:function(e,n){this.listeners[e]?this.listeners[e]=[].concat(o(this.listeners[e]),[n]):this.listeners[e]=[n]}},{key:"removeEventListener",value:function(e,n){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(function(e){return e===n}))}},{key:"connect",value:function(){var e,n=(e=regeneratorRuntime.mark(function e(n){var t,i,r=this;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=n.timeoutMs,i=void 0===t?1e4:t,e.abrupt("return",new Promise(function(e,n){var t=setTimeout(function(){n()},i),o=function n(i){r.sipUA.removeListener("connected",n),r.sipUA.removeListener("disconnected",s),clearTimeout(t),e(i)},s=function e(i){r.sipUA.removeListener("connected",o),r.sipUA.removeListener("disconnected",e),clearTimeout(t),n(i)};r.sipUA.on("connected",o),r.sipUA.on("disconnected",s),r.sipUA.start()}));case 2:case"end":return e.stop()}},e,this)}),function(){var n=this,i=arguments;return new Promise(function(r,o){var s=e.apply(n,i);function c(e){t(s,r,o,c,a,"next",e)}function a(e){t(s,r,o,c,a,"throw",e)}c(void 0)})});return function(e){return n.apply(this,arguments)}}()},{key:"handleConnected",value:function(e){this.connected=!0,this.listeners.connected&&this.listeners.connected.forEach(function(n){n(e)})}},{key:"handleDisconnected",value:function(e){this.connected=!1,this.listeners.disconnected&&this.listeners.disconnected.forEach(function(n){n(e)})}},{key:"isConnected",get:function(){return this.connected}}])&&i(u.prototype,l),d&&i(u,d),a}()); | ||
import{WebSocketInterface as t,UA as e}from"jssip";import n from"events";var r,o=(function(t){!function(e){var n,r=Object.prototype,o=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},c=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",a=i.toStringTag||"@@toStringTag",u=e.regeneratorRuntime;if(u)t.exports=u;else{(u=e.regeneratorRuntime=t.exports).wrap=w;var l="suspendedStart",f="suspendedYield",h="executing",d="completed",p={},v={};v[c]=function(){return this};var m=Object.getPrototypeOf,y=m&&m(m(L([])));y&&y!==r&&o.call(y,c)&&(v=y);var g=S.prototype=E.prototype=Object.create(v);j.prototype=g.constructor=S,S.constructor=j,S[a]=j.displayName="GeneratorFunction",u.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===j||"GeneratorFunction"===(e.displayName||e.name))},u.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,S):(t.__proto__=S,a in t||(t[a]="GeneratorFunction")),t.prototype=Object.create(g),t},u.awrap=function(t){return{__await:t}},C(T.prototype),T.prototype[s]=function(){return this},u.AsyncIterator=T,u.async=function(t,e,n,r){var o=new T(w(t,e,n,r));return u.isGeneratorFunction(e)?o:o.next().then(function(t){return t.done?t.value:o.next()})},C(g),g[a]="Generator",g[c]=function(){return this},g.toString=function(){return"[object Generator]"},u.keys=function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},u.values=L,k.prototype={constructor:k,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(O),!t)for(var e in this)"t"===e.charAt(0)&&o.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=n)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function r(r,o){return s.type="throw",s.arg=t,e.next=r,o&&(e.method="next",e.arg=n),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var c=this.tryEntries[i],s=c.completion;if("root"===c.tryLoc)return r("end");if(c.tryLoc<=this.prev){var a=o.call(c,"catchLoc"),u=o.call(c,"finallyLoc");if(a&&u){if(this.prev<c.catchLoc)return r(c.catchLoc,!0);if(this.prev<c.finallyLoc)return r(c.finallyLoc)}else if(a){if(this.prev<c.catchLoc)return r(c.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<c.finallyLoc)return r(c.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var c=i?i.completion:{};return c.type=t,c.arg=e,i?(this.method="next",this.next=i.finallyLoc,p):this.complete(c)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),p},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),O(n),p}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;O(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:L(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=n),p}}}function w(t,e,n,r){var o=e&&e.prototype instanceof E?e:E,i=Object.create(o.prototype),c=new k(r||[]);return i._invoke=function(t,e,n){var r=l;return function(o,i){if(r===h)throw new Error("Generator is already running");if(r===d){if("throw"===o)throw i;return _()}for(n.method=o,n.arg=i;;){var c=n.delegate;if(c){var s=R(c,n);if(s){if(s===p)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===l)throw r=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=h;var a=b(t,e,n);if("normal"===a.type){if(r=n.done?d:f,a.arg===p)continue;return{value:a.arg,done:n.done}}"throw"===a.type&&(r=d,n.method="throw",n.arg=a.arg)}}}(t,n,c),i}function b(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}function E(){}function j(){}function S(){}function C(t){["next","throw","return"].forEach(function(e){t[e]=function(t){return this._invoke(e,t)}})}function T(t){var e;this._invoke=function(n,r){function i(){return new Promise(function(e,i){!function e(n,r,i,c){var s=b(t[n],t,r);if("throw"!==s.type){var a=s.arg,u=a.value;return u&&"object"==typeof u&&o.call(u,"__await")?Promise.resolve(u.__await).then(function(t){e("next",t,i,c)},function(t){e("throw",t,i,c)}):Promise.resolve(u).then(function(t){a.value=t,i(a)},function(t){return e("throw",t,i,c)})}c(s.arg)}(n,r,e,i)})}return e=e?e.then(i,i):i()}}function R(t,e){var r=t.iterator[e.method];if(r===n){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=n,R(t,e),"throw"===e.method))return p;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return p}var o=b(r,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,p;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=n),e.delegate=null,p):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,p)}function x(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function O(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function k(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(x,this),this.reset(!0)}function L(t){if(t){var e=t[c];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,i=function e(){for(;++r<t.length;)if(o.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=n,e.done=!0,e};return i.next=i}}return{next:_}}function _(){return{value:n,done:!0}}}(function(){return this||"object"==typeof self&&self}()||Function("return this")())}(r={exports:{}},r.exports),r.exports),i=function(){return this||"object"==typeof self&&self}()||Function("return this")(),c=i.regeneratorRuntime&&Object.getOwnPropertyNames(i).indexOf("regeneratorRuntime")>=0,s=c&&i.regeneratorRuntime;i.regeneratorRuntime=void 0;var a=o;if(c)i.regeneratorRuntime=s;else try{delete i.regeneratorRuntime}catch(t){i.regeneratorRuntime=void 0}var u=a;function l(t,e,n,r,o,i,c){try{var s=t[i](c),a=s.value}catch(t){return void n(t)}s.done?e(a):Promise.resolve(a).then(r,o)}function f(t){return function(){var e=this,n=arguments;return new Promise(function(r,o){var i=t.apply(e,n);function c(t){l(i,r,o,c,s,"next",t)}function s(t){l(i,r,o,c,s,"throw",t)}c(void 0)})}}function h(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function d(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function p(t,e,n){return e&&d(t.prototype,e),n&&d(t,n),t}function v(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function m(t){return(m="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function y(t){return(y="function"==typeof Symbol&&"symbol"===m(Symbol.iterator)?function(t){return m(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":m(t)})(t)}function g(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function w(t,e){return!e||"object"!==y(e)&&"function"!=typeof e?g(t):e}function b(t){return(b=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function E(t,e,n){return(E="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=b(t)););return t}(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(n):o.value}})(t,e,n||t)}function j(t,e){return(j=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function S(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&j(t,e)}var C,T="wss://".concat("webrtc-staging.messagebird.io"),R="webrtc-staging.messagebird.io",x=/^\S*$/,O=function(t){if(!t.username)throw new Error("You must pass a username.");if(!x.test(t.username))throw new Error("Username cannot contain any spaces")},k=function(n){function r(e){var n;h(this,r),O(e);var o=new t(T);return v(g(g(n=w(this,b(r).call(this,{sockets:[o],register:!0,uri:"sip:".concat(e.username,"@").concat(R),display_name:e.displayName})))),"connectTimeout",void 0),v(g(g(n)),"resolveDisconnect",void 0),v(g(g(n)),"resolveConnection",void 0),v(g(g(n)),"rejectConnection",void 0),n.registrator().setExtraHeaders(["X-Token: ".concat(e.jwt)]),n.on("connected",n.handleConnected),n.on("disconnected",n.handleDisconnected),n}return S(r,e),p(r,[{key:"start",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return new Promise(function(n,o){t.connectTimeout=setTimeout(function(){t.resolveConnection=null,t.rejectConnection=null,o(new Error("Connectioned timed out after ".concat(e,"ms")))},e),t.resolveConnection=n,t.rejectConnection=o,E(b(r.prototype),"start",t).call(t)})}},{key:"stop",value:function(){var t=this;return new Promise(function(e){t.resolveDisconnect=e,E(b(r.prototype),"stop",t).call(t)})}},{key:"handleConnected",value:function(t){this.resolveConnection&&(clearTimeout(this.connectTimeout),this.resolveConnection(t),this.resolveConnection=null,this.rejectConnection=null)}},{key:"handleDisconnected",value:function(t){this.rejectConnection&&(clearTimeout(this.connectTimeout),this.rejectConnection(new Error("Could not connect to WebRTC Socket: ".concat(t.reason))),this.resolveConnection=null,this.rejectConnection=null),this.resolveDisconnect&&(this.resolveDisconnect(t),this.resolveDisconnect=null)}}]),r}();!function(t){t.Initial="initial",t.Connecting="connecting",t.Failed="failed",t.Accepted="accepted",t.Confirmed="confirmed",t.Disconnected="disconnected"}(C||(C={}));var L=function(){function t(e){var r=this;h(this,t),v(this,"status",void 0),v(this,"eventEmitter",new n),v(this,"sipRTCSession",void 0),v(this,"streamTargets",void 0),v(this,"sendDTMF",function(t){r.sipRTCSession.sendDTMF(t)}),v(this,"handleAccepted",function(){r.status=C.Accepted}),v(this,"handleConfirmed",function(t){r.status=C.Confirmed,r.eventEmitter.emit("confirmed",t)}),v(this,"handleEnded",function(t){r.status=C.Disconnected,r.eventEmitter.emit("ended",t)}),v(this,"handleFailed",function(t){r.status=C.Failed,r.eventEmitter.emit("failed",t)}),v(this,"handleAddTrack",function(t){r.streamTargets=t.streams.map(function(t){return function(t){var e=document.createElement("video");return e.setAttribute("autoplay","true"),e.setAttribute("style","display: none;"),e.srcObject=t,document.body.appendChild(e),e}(t)})}),this.sipRTCSession=e,this.sipRTCSession.connection.addEventListener("track",this.handleAddTrack),this.sipRTCSession.on("accepted",this.handleAccepted),this.sipRTCSession.on("confirmed",this.handleConfirmed),this.sipRTCSession.on("ended",this.handleEnded),this.sipRTCSession.on("failed",this.handleFailed)}return p(t,[{key:"on",value:function(t,e){this.eventEmitter.on(t,e)}},{key:"removeEventlistener",value:function(t,e){this.eventEmitter.removeListener(t,e)}},{key:"disconnect",value:function(){this.streamTargets.forEach(function(t){return function(t){if(t.remove)t.remove();else try{document.body.removeChild(t)}catch(t){}}(t)}),this.sipRTCSession.terminate()}}]),t}(),_=function(t){function e(t,n){var r,o=n.to,i=n.jwt,c=n.onEnded;return h(this,e),v(g(g(r=w(this,b(e).call(this,t.call("sip:".concat(o,"@").concat(R),{mediaConstraints:{audio:!0,video:!1},extraHeaders:["X-Token: ".concat(i)]}))))),"connectTimeout",void 0),v(g(g(r)),"acceptResolver",void 0),v(g(g(r)),"failedRejector",void 0),v(g(g(r)),"handleOutboundSessionAccepted",function(){r.acceptResolver&&(r.acceptResolver(g(g(r))),r.acceptResolver=void 0,r.failedRejector=void 0,clearTimeout(r.connectTimeout))}),v(g(g(r)),"handleOutboundSessionFailed",function(t){r.failedRejector&&(r.failedRejector(t),r.acceptResolver=void 0,r.failedRejector=void 0,clearTimeout(r.connectTimeout))}),r.status=C.Connecting,r.on("confirmed",r.handleOutboundSessionAccepted),r.on("failed",r.handleOutboundSessionFailed),r.on("ended",function(t){return c(g(g(r)),t)}),r}return S(e,L),p(e,[{key:"connect",value:function(){var t=f(u.mark(function t(){var e,n=this,r=arguments;return u.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return e=r.length>0&&void 0!==r[0]?r[0]:1e4,this.on("confirmed",this.handleOutboundSessionAccepted),this.on("failed",this.handleOutboundSessionFailed),t.abrupt("return",new Promise(function(t,r){n.connectTimeout=setTimeout(function(){r(new Error("Outgoing RTC Session timed out after ".concat(e,"ms")))},e),n.acceptResolver=t,n.failedRejector=r}));case 4:case"end":return t.stop()}},t,this)}));return function(){return t.apply(this,arguments)}}()}]),e}(),A=function(t){function e(t){return h(this,e),w(this,b(e).call(this,t))}return S(e,L),p(e,[{key:"answer",value:function(){this.sipRTCSession.answer(),this.eventEmitter.emit("answer",this)}}]),e}(),P=function(){function t(e){var r=this,o=e.displayName,i=e.username,c=e.debug,s=void 0!==c&&c,a=e.jwt;h(this,t),v(this,"eventEmitter",new n),v(this,"activeSessions",[]),v(this,"connected",void 0),v(this,"jwt",void 0),v(this,"sipUA",void 0),v(this,"handleConnected",function(t){r.connected=!0,r.eventEmitter.emit("connected",t)}),v(this,"handleDisconnected",function(t){r.connected=!1,r.eventEmitter.emit("disconnected",t),r.activeSessions.forEach(function(t){return t.disconnect()})}),this.connected=!1,this.jwt=a,this.sipUA=new k({register:!1,debug:s,jwt:a,username:i,displayName:o}),this.sipUA.on("connected",this.handleConnected),this.sipUA.on("disconnected",this.handleDisconnected),this.sipUA.on("newRTCSession",this.handleNewSession)}return p(t,[{key:"on",value:function(t,e){this.eventEmitter.on(t,e)}},{key:"removeEventListener",value:function(t,e){this.eventEmitter.removeListener(t,e)}},{key:"connect",value:function(){var t=f(u.mark(function t(){var e,n,r,o=arguments;return u.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return e=o.length>0&&void 0!==o[0]?o[0]:{},n=e.timeoutMs,r=void 0===n?1e4:n,t.abrupt("return",this.sipUA.start(r));case 2:case"end":return t.stop()}},t,this)}));return function(){return t.apply(this,arguments)}}()},{key:"disconnect",value:function(){this.sipUA.stop()}},{key:"startRTCSession",value:function(t){var e=this;if(!this.connected)throw new Error("No active connection. Call `.connect()` first.");return new _(this.sipUA,{to:t.to,jwt:this.jwt,onEnded:function(n,r){e.handleSessionEnded(n),t.onEnded&&t.onEnded(n,r)}}).connect()}},{key:"handleSessionEnded",value:function(t){this.activeSessions=this.activeSessions.filter(function(e){return e!==t})}},{key:"handleNewSession",value:function(t){if("remote"===t.originator)new A(t.session)}}]),t}();export{P as WebRTCClient,_ as OutgoingRTCSession,L as RTCSession}; |
107
jssip.d.ts
declare module 'jssip' { | ||
export interface UASip {} | ||
interface WebSocketInterfaceOptions {} | ||
@@ -23,2 +21,22 @@ | ||
export interface SessionFailedEventData { | ||
originator?: string; | ||
cause: string; // TODO: https://jssip.net/documentation/3.3.x/api/causes/ | ||
} | ||
export interface SessionEndedEventData { | ||
originator: string; | ||
message: string | null; | ||
cause: string; | ||
} | ||
export interface SessionConfirmedEventData { | ||
originator?: string; | ||
} | ||
interface MediaConstraints { | ||
audio: boolean; | ||
video: boolean; | ||
} | ||
interface UAOptions { | ||
@@ -28,3 +46,33 @@ sockets: WebSocketInterface[]; | ||
uri: string; | ||
display_name: string; | ||
} | ||
interface CallOptions { | ||
mediaConstraints: MediaConstraints; | ||
mediaStream?: any; // TODO | ||
pconfig?: any; // TODO: | ||
rtcConstraints?: any; // TODO | ||
eventHandlers?: { | ||
[eventName: string]: (data: any) => void; | ||
}; | ||
extraHeaders?: string[]; | ||
anonymous?: boolean; | ||
} | ||
interface AnswerOptions { | ||
extraHeaders: string[]; | ||
mediaConstraints?: MediaConstraints; | ||
mediaStream?: MediaStream; | ||
pConfig?: RTCConfiguration; | ||
rtcConstraints?: any; // TODO: docs unclear about this. | ||
rtcAnswerConstraints?: RTCAnswerOptions; | ||
rtcOfferConstraints?: RTCOfferOptions; | ||
sessionTimersExpires?: Number; | ||
} | ||
export interface NewSessionEvent { | ||
originator: 'local' | 'remote'; | ||
session: RTCSession; | ||
} | ||
export class UA { | ||
@@ -38,7 +86,62 @@ constructor(options: UAOptions); | ||
public on(name: 'disconnected', callback: (data: any) => void); | ||
public on( | ||
name: 'newRTCSession', | ||
callback: (data: NewSessionEvent) => void | ||
): void; | ||
public registrator(): Registrator; | ||
public removeListener(name: string, callback: Function); | ||
public call(target: string, options: CallOptions): RTCSession; | ||
public register(); | ||
} | ||
export class Registrator { | ||
public setExtraHeaders(headers: string[]): void; | ||
public setExtraContactParams(map: { [k: string]: string }): void; | ||
} | ||
export class RTCSession { | ||
public isInProgress(): boolean; | ||
public isEstablished(): boolean; | ||
public isEnded(): boolean; | ||
public isReadyToReOffer(): boolean; | ||
public isMuted(): boolean; | ||
public connection: RTCPeerConnection; | ||
public terminate(options?: { | ||
extraHeaders?: string[]; | ||
status_code?: number; | ||
reason_phrase: string; | ||
body?: string; | ||
}): void; | ||
public on(name: string, cb: (...args: any) => void): void; | ||
public answer(options?: AnswerOptions): void; | ||
public sendDTMF( | ||
key: string | number, | ||
options?: { | ||
duration?: number; | ||
innerToneGap?: number; | ||
extraHeaders?: string[]; | ||
} | ||
): void; | ||
public hold( | ||
options?: { | ||
useUpdatae?: boolean; | ||
extraHeaders: string[]; | ||
}, | ||
cb: () => void | ||
): void; | ||
} | ||
interface Debug { | ||
enable: (filter: string) => void; | ||
disable: (filter: string) => void; | ||
} | ||
const debug: Debug; | ||
} |
{ | ||
"name": "@messagebird/webrtc", | ||
"version": "0.0.1", | ||
"main": "lib/index.js", | ||
"version": "0.0.2", | ||
"main": "dist/web-rtc-sdk.cjs.js", | ||
"author": "Niek Kruse <niekkruse70@gmail.com>", | ||
"module": "dist/es/index.js", | ||
"module": "dist/web-rtc-sdk.es.js", | ||
"license": "MIT", | ||
@@ -51,5 +51,8 @@ "types": "types/index.d.ts", | ||
"@babel/core": "^7.2.2", | ||
"@babel/plugin-external-helpers": "^7.2.0", | ||
"@babel/plugin-proposal-class-properties": "^7.2.3", | ||
"@babel/plugin-transform-runtime": "^7.2.0", | ||
"@babel/preset-env": "^7.2.3", | ||
"@babel/preset-typescript": "^7.1.0", | ||
"@types/events": "^1.2.0", | ||
"@types/jest": "^23.3.12", | ||
@@ -63,2 +66,4 @@ "babel-core": "^7.0.0-bridge.0", | ||
"rollup-plugin-commonjs": "^9.2.0", | ||
"rollup-plugin-json": "^3.1.0", | ||
"rollup-plugin-node-builtins": "^2.1.2", | ||
"rollup-plugin-node-resolve": "^4.0.0", | ||
@@ -74,4 +79,6 @@ "rollup-plugin-replace": "^2.1.0", | ||
"dependencies": { | ||
"@babel/runtime": "^7.2.0", | ||
"events": "^3.0.0", | ||
"jssip": "^3.3.3" | ||
} | ||
} |
@@ -1,3 +0,89 @@ | ||
## JS WebRTC SDK | ||
# JavaScript WebRTC SDK | ||
TODO! | ||
## Initializing an RTC Client | ||
To enable your application to make and receive calls over WebRTC, you have to instantiate a new WebRTCClient (TODO: good name? Device). To instantiate a client and authenticate with your MessageBird account you need to generate a JWT and pass it to the client (docs) | ||
```js | ||
const client = new WebRTCClient({ | ||
displayName: 'test', | ||
username: 'test', | ||
jwt: 'test', | ||
}); | ||
// Open a connection to the MessageBird WebRTC API | ||
client | ||
.connect() | ||
.then(() => { | ||
// Ready to start and receive WebRTC connections. | ||
}) | ||
.catch(error => { | ||
// Error making a connection. The error object contains details of the failure. | ||
}); | ||
``` | ||
## Starting a new RTC session | ||
Make sure you've instantiated the `WebRTCClient` and opened the connection by calling the `.connect()` method. After succesfully instantiating a new client you can start new RTC sessions by calling the `starRTCSession` method. | ||
```js | ||
client | ||
.startRTCSession({ | ||
to: '+31612345678', // TODO: This will become `flowId` probably? | ||
onEnded() { | ||
console.log('session was ended'); | ||
}, | ||
}) | ||
.then(connection => { | ||
// resolves with a connection object (docs) | ||
}) | ||
.catch(error => { | ||
// Failed to start a session, error object contains details. | ||
}); | ||
``` | ||
## API Reference | ||
### WebRTCClient | ||
#### `constructor()` | ||
#### `startRTCConnection()` | ||
#### `connect()` | ||
Connect to the | ||
#### events | ||
##### `on('connected')` | ||
When the client connects. Can be called multiple times in case the client disconnects and automatically reconnects. | ||
##### `on('disconnected')` | ||
When the client disconnects for a certain reason. (docs on data object with reason) | ||
### RTCSession | ||
The `RTCSession` object describes an ongoing RTC session. You will never instantiate an `RTCSession` yourself, the SDK will take care of that for you. | ||
#### `disconnect()` | ||
Terminates the session | ||
#### `on(name, handler)` | ||
Bind a new event listener. See Events (link) below | ||
#### `removeEventListener(name, handler)` | ||
Removes an event listener | ||
#### Events | ||
##### `on('confirmed')` | ||
##### `on('failed')` | ||
##### `on('ended')` |
@@ -6,2 +6,4 @@ import nodeResolve from 'rollup-plugin-node-resolve'; | ||
import { terser } from 'rollup-plugin-terser'; | ||
import builtins from 'rollup-plugin-node-builtins'; | ||
import json from 'rollup-plugin-json'; | ||
import replace from 'rollup-plugin-replace'; | ||
@@ -13,18 +15,32 @@ import dotenv from 'dotenv'; | ||
const basePlugins = [ | ||
replace({ | ||
'process.env.API_HOST': JSON.stringify(process.env.API_URL), | ||
}), | ||
nodeResolve({ | ||
extensions: ['.ts', '.tsx'], | ||
}), | ||
sourceMaps(), | ||
babel({ | ||
extensions: ['.ts', '.tsx'], | ||
}), | ||
commonJs({ | ||
ignoreGlobal: true, | ||
extensions: ['.js', '.ts', '.tsx'], | ||
}), | ||
]; | ||
const createPlugins = ({ output, minify = false }) => { | ||
return [ | ||
replace({ | ||
'process.env.API_HOST': JSON.stringify(process.env.API_HOST), | ||
'process.env;': '{}', | ||
}), | ||
nodeResolve({ | ||
preferBuiltins: false, | ||
extensions: ['.ts', '.tsx', '.js'], | ||
}), | ||
sourceMaps(), | ||
babel({ | ||
extensions: ['.ts', '.tsx'], | ||
runtimeHelpers: true, | ||
presets: [ | ||
'@babel/preset-typescript', | ||
['@babel/preset-env', { modules: false }], | ||
], | ||
plugins: [ | ||
'@babel/plugin-proposal-class-properties', | ||
['@babel/transform-runtime', { useESModules: output.format !== 'esm' }], | ||
], | ||
}), | ||
commonJs({ | ||
ignoreGlobal: true, | ||
extensions: ['.js', '.ts', '.tsx'], | ||
}), | ||
...(minify ? [terser({ sourcemap: true })] : []), | ||
]; | ||
}; | ||
@@ -42,16 +58,25 @@ const baseConfig = { | ||
...baseConfig, | ||
plugins: [...basePlugins, terser({ sourcemap: true })], | ||
output: [ | ||
{ file: `dist/web-rtc-sdk.es.min.js`, format: 'es' }, | ||
{ file: `dist/web-rtc-sdk.cjs.min.js`, format: 'cjs' }, | ||
], | ||
plugins: createPlugins({ output: 'es', minify: true }), | ||
output: [{ file: `dist/web-rtc-sdk.es.min.js`, format: 'es' }], | ||
}, | ||
{ | ||
...baseConfig, | ||
plugins: basePlugins, | ||
plugins: createPlugins({ output: 'cjs', minify: true }), | ||
output: [{ file: `dist/web-rtc-sdk.cjs.min.js`, format: 'cjs' }], | ||
}, | ||
{ | ||
input: 'src/index.ts', | ||
plugins: createPlugins({ output: 'umd', minify: true }), | ||
external: ['jssip'], | ||
output: [ | ||
{ file: `dist/web-rtc-sdk.es.js`, format: 'es' }, | ||
{ file: `dist/web-rtc-sdk.cjs.js`, format: 'cjs' }, | ||
{ | ||
file: `dist/web-rtc-sdk.umd.min.js`, | ||
format: 'umd', | ||
name: 'WebRTC', | ||
globals: { | ||
jssip: 'JsSIP', | ||
}, | ||
}, | ||
], | ||
}, | ||
]; |
@@ -13,2 +13,3 @@ { | ||
"noUnusedParameters": true, | ||
"allowUnusedLabels": false, | ||
"skipLibCheck": true, | ||
@@ -15,0 +16,0 @@ "pretty": true, |
@@ -1,2 +0,3 @@ | ||
export declare const RtcSocketUrl: string; | ||
export declare const RTC_SOCKET_URL: string; | ||
export declare const TOKEN: string; | ||
export declare const API_HOST: string; |
@@ -1,2 +0,3 @@ | ||
import WebRtcClient from './WebRtcClient'; | ||
export default WebRtcClient; | ||
export { WebRTCClient } from './WebRTCClient'; | ||
export { OutgoingRTCSession } from './OutgoingRTCSession'; | ||
export { RTCSession } from './RTCSession'; |
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
618675
30
3825
90
3
25
4
9
+ Added@babel/runtime@^7.2.0
+ Addedevents@^3.0.0
+ Added@babel/runtime@7.26.7(transitive)
+ Addedregenerator-runtime@0.14.1(transitive)