@ringcentral/sdk
Version:
- [Installation](#installation) - [Getting Started](#getting-started) - [API Calls](#api-calls) - [Advanced SDK Configuration & Polyfills](#advanced-sdk-configuration--polyfills) - [Making telephony calls](#making-telephony-calls) - [Call management using
1,239 lines (1,137 loc) • 155 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["SDK"] = factory();
else
root["RingCentral"] = root["RingCentral"] || {}, root["RingCentral"]["SDK"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 5);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function $getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return $getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = $getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
var args = [];
for (var i = 0; i < arguments.length; i++) args.push(arguments[i]);
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
ReflectApply(this.listener, this.target, args);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
/***/ }),
/* 1 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1, eval)("this");
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var version = __webpack_require__(8).version; //eslint-disable-line
exports.version = version;
exports.authResponseProperty = 'RCAuthorizationResponse';
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var events_1 = __importDefault(__webpack_require__(0));
var qs = __importStar(__webpack_require__(4));
var is_plain_object_1 = __importDefault(__webpack_require__(11));
function findHeaderName(name, headers) {
name = name.toLowerCase();
return Object.keys(headers).reduce(function (res, key) {
if (res)
return res;
if (name === key.toLowerCase())
return key;
return res;
}, null);
}
var events;
(function (events) {
events["beforeRequest"] = "beforeRequest";
events["requestSuccess"] = "requestSuccess";
events["requestError"] = "requestError";
})(events = exports.events || (exports.events = {}));
var Client = /** @class */ (function (_super) {
__extends(Client, _super);
function Client(_a) {
var externals = _a.externals, _b = _a.defaultRequestInit, defaultRequestInit = _b === void 0 ? {} : _b;
var _this = _super.call(this) || this;
_this.events = events;
_this._defaultRequestInit = {};
_this._defaultRequestInit = defaultRequestInit;
_this._externals = externals;
return _this;
}
Client.prototype.sendRequest = function (request) {
return __awaiter(this, void 0, void 0, function () {
var response, e_1, error, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 2, , 6]);
//TODO Stop request if listeners return false
this.emit(this.events.beforeRequest, request);
return [4 /*yield*/, this._loadResponse(request)];
case 1:
response = _b.sent();
if (!response.ok)
throw new Error('Response has unsuccessful status');
this.emit(this.events.requestSuccess, response, request);
return [2 /*return*/, response];
case 2:
e_1 = _b.sent();
if (!!e_1.response) return [3 /*break*/, 4];
return [4 /*yield*/, this.makeError(e_1, response, request)];
case 3:
_a = _b.sent();
return [3 /*break*/, 5];
case 4:
_a = e_1;
_b.label = 5;
case 5:
error = _a;
this.emit(this.events.requestError, error);
throw error;
case 6: return [2 /*return*/];
}
});
});
};
Client.prototype._loadResponse = function (request) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this._externals.fetch.call(null, request)]; // fixed illegal invocation in Chrome
});
});
};
/**
* Wraps the JS Error object with transaction information
*/
Client.prototype.makeError = function (e, response, request) {
if (response === void 0) { response = null; }
if (request === void 0) { request = null; }
return __awaiter(this, void 0, void 0, function () {
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!(!e.response && !e.originalMessage)) return [3 /*break*/, 3];
e.response = response;
e.request = request;
e.originalMessage = e.message;
_a = e;
_b = response;
if (!_b) return [3 /*break*/, 2];
return [4 /*yield*/, this.error(response, true)];
case 1:
_b = (_c.sent());
_c.label = 2;
case 2:
_a.message = (_b) || e.originalMessage;
_c.label = 3;
case 3: return [2 /*return*/, e];
}
});
});
};
Client.prototype.createRequest = function (init) {
if (init === void 0) { init = Client._defaultRequestInit; }
init = __assign({}, this._defaultRequestInit, init);
init.headers = init.headers || {};
// Sanity checks
if (!init.url)
throw new Error('Url is not defined');
if (!init.method)
init.method = 'GET';
init.method = init.method.toUpperCase();
if (init.method && Client._allowedMethods.indexOf(init.method) < 0) {
throw new Error("Method has wrong value: " + init.method);
}
// Defaults
init.credentials = init.credentials || 'include';
init.mode = init.mode || 'cors';
// Append Query String
if (init.query) {
init.url = init.url + (init.url.includes('?') ? '&' : '?') + qs.stringify(init.query);
}
if (!findHeaderName('Accept', init.headers)) {
init.headers.Accept = Client._jsonContentType;
}
// Serialize body
if (is_plain_object_1.default(init.body) || !init.body) {
var contentTypeHeaderName = findHeaderName(Client._contentType, init.headers);
if (!contentTypeHeaderName) {
contentTypeHeaderName = Client._contentType;
init.headers[contentTypeHeaderName] = Client._jsonContentType;
}
var contentType = init.headers[contentTypeHeaderName];
// Assign a new encoded body
if (contentType.includes(Client._jsonContentType)) {
if ((init.method === 'GET' || init.method === 'HEAD') && !!init.body) {
// oddly setting body to null still result in TypeError in phantomjs
init.body = undefined;
}
else {
init.body = JSON.stringify(init.body);
}
}
else if (contentType.includes(Client._urlencodedContentType)) {
init.body = qs.stringify(init.body);
}
}
// Create a request with encoded body
var req = new this._externals.Request(init.url, init);
// Keep the original body accessible directly (for mocks)
req.originalBody = init.body;
return req;
};
Client.prototype._isContentType = function (contentType, response) {
return this.getContentType(response).includes(contentType);
};
Client.prototype.getContentType = function (response) {
return response.headers.get(Client._contentType) || '';
};
Client.prototype.isMultipart = function (response) {
return this._isContentType(Client._multipartContentType, response);
};
Client.prototype.isJson = function (response) {
return this._isContentType(Client._jsonContentType, response);
};
Client.prototype.toMultipart = function (response) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.isMultipart(response) ? this.multipart(response) : [response]];
});
});
};
Client.prototype.multipart = function (response) {
return __awaiter(this, void 0, void 0, function () {
var text, boundary, parts, statusInfo;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.isMultipart(response))
throw new Error('Response is not multipart');
return [4 /*yield*/, response.text()];
case 1:
text = _a.sent();
if (!text)
throw new Error('No response body');
try {
boundary = this.getContentType(response).match(/boundary=([^;]+)/i)[1]; //eslint-disable-line
}
catch (e) {
throw new Error('Cannot find boundary');
}
if (!boundary)
throw new Error('Cannot find boundary');
parts = text.toString().split(Client._boundarySeparator + boundary);
if (parts[0].trim() === '')
parts.shift();
if (parts[parts.length - 1].trim() === Client._boundarySeparator)
parts.pop();
if (parts.length < 1)
throw new Error('No parts in body');
return [4 /*yield*/, this._create(parts.shift(), response.status, response.statusText).json()];
case 2:
statusInfo = _a.sent();
// Step 3. Parse all other parts
return [2 /*return*/, parts.map(function (part, i) { return _this._create(part, statusInfo.response[i].status); })];
}
});
});
};
/**
* Method is used to create Response object from string parts of multipart/mixed response
*/
Client.prototype._create = function (text, status, statusText) {
if (text === void 0) { text = ''; }
if (status === void 0) { status = 200; }
if (statusText === void 0) { statusText = 'OK'; }
text = text.replace(/\r/g, '');
var headers = new this._externals.Headers();
var headersAndBody = text.split(Client._bodySeparator);
var headersText = headersAndBody.length > 1 ? headersAndBody.shift() : '';
text = headersAndBody.length > 0 ? headersAndBody.join(Client._bodySeparator) : null;
(headersText || '').split('\n').forEach(function (header) {
var split = header.trim().split(Client._headerSeparator);
var key = split.shift().trim();
var value = split.join(Client._headerSeparator).trim();
if (key)
headers.append(key, value);
});
return new this._externals.Response(text, {
headers: headers,
status: status,
statusText: statusText,
});
};
Client.prototype.error = function (response, skipOKCheck) {
if (skipOKCheck === void 0) { skipOKCheck = false; }
return __awaiter(this, void 0, void 0, function () {
var msg, _a, message, error_description, description, e_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (response.ok && !skipOKCheck)
return [2 /*return*/, null];
msg = (response.status ? response.status + " " : '') + (response.statusText ? response.statusText : '');
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, response.clone().json()];
case 2:
_a = _b.sent(), message = _a.message, error_description = _a.error_description, description = _a.description;
if (message)
msg = message;
if (error_description)
msg = error_description;
if (description)
msg = description;
return [3 /*break*/, 4];
case 3:
e_2 = _b.sent();
return [3 /*break*/, 4];
case 4: //eslint-disable-line
return [2 /*return*/, msg];
}
});
});
};
Client.prototype.on = function (event, listener) {
return _super.prototype.on.call(this, event, listener);
};
Client._contentType = 'Content-Type';
Client._jsonContentType = 'application/json';
Client._multipartContentType = 'multipart/mixed';
Client._urlencodedContentType = 'application/x-www-form-urlencoded';
Client._headerSeparator = ':';
Client._bodySeparator = '\n\n';
Client._boundarySeparator = '--';
Client._unauthorizedStatus = 401;
Client._rateLimitStatus = 429;
Client._allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD'];
Client._defaultRequestInit = {
credentials: 'include',
mode: 'cors',
};
return Client;
}(events_1.default));
exports.default = Client;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.decode = exports.parse = __webpack_require__(9);
exports.encode = exports.stringify = __webpack_require__(10);
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var events_1 = __importDefault(__webpack_require__(0));
exports.EventEmitter = events_1.default;
var Cache_1 = __importDefault(__webpack_require__(6));
exports.Cache = Cache_1.default;
var Externals_1 = __importDefault(__webpack_require__(7));
exports.Externals = Externals_1.default;
var Constants = __importStar(__webpack_require__(2));
var Client_1 = __importDefault(__webpack_require__(3));
var Platform_1 = __importDefault(__webpack_require__(13));
var defaultExternals = {};
exports.setDefaultExternals = function (externals) { return (defaultExternals = externals); };
var SDK = /** @class */ (function () {
function SDK(options) {
if (options === void 0) { options = {}; }
var _this = this;
/* istanbul ignore next */
this.send = function (options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().send(options)];
}); }); };
/* istanbul ignore next */
this.get = function (url, query, options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().send(__assign({ method: 'GET', url: url, query: query }, options))];
}); }); };
/* istanbul ignore next */
this.post = function (url, body, query, options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().send(__assign({ method: 'POST', url: url, query: query, body: body }, options))];
}); }); };
/* istanbul ignore next */
this.put = function (url, body, query, options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().send(__assign({ method: 'PUT', url: url, query: query, body: body }, options))];
}); }); };
/* istanbul ignore next */
this.delete = function (url, query, options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().send(__assign({ method: 'DELETE', url: url, query: query }, options))];
}); }); };
/* istanbul ignore next */
this.login = function (options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().login(options)];
}); }); };
/* istanbul ignore next */
this.ensureLoggedIn = function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().ensureLoggedIn()];
}); }); };
/* istanbul ignore next */
this.loginUrl = function (options) { return _this.platform().loginUrl(options); };
/* istanbul ignore next */
this.createUrl = function (path, options) { return _this.platform().createUrl(path, options); };
/* istanbul ignore next */
this.signUrl = function (path) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().signUrl(path)];
}); }); };
/* istanbul ignore next */
this.parseLoginRedirect = function (url) { return _this.platform().parseLoginRedirect(url); };
/* istanbul ignore next */
this.logout = function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().logout()];
}); }); };
/* istanbul ignore next */
this.loginWindow = function (options) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().loginWindow(options)];
}); }); };
/* istanbul ignore next */
this.refresh = function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.platform().refresh()];
}); }); };
/* istanbul ignore next */
this.multipart = function (response) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, this.client().multipart(response)];
}); }); };
/* istanbul ignore next */
this.getContentType = function (response) { return _this.client().getContentType(response); };
/* istanbul ignore next */
this.isMultipart = function (response) { return _this.client().isMultipart(response); };
/* istanbul ignore next */
this.isJson = function (response) { return _this.client().isJson(response); };
/* istanbul ignore next */
this.error = function (response) { return _this.client().error(response); };
var cachePrefix = options.cachePrefix, defaultRequestInit = options.defaultRequestInit;
this._externals = new Externals_1.default(__assign({}, defaultExternals, options));
this._cache = new Cache_1.default({
externals: this._externals,
prefix: cachePrefix,
});
this._client = new Client_1.default({
externals: this._externals,
defaultRequestInit: defaultRequestInit,
});
this._platform = new Platform_1.default(__assign({}, options, { externals: this._externals, client: this._client, cache: this._cache }));
}
SDK.handleLoginRedirect = function (origin, win) {
win = win || window;
var response = win.location.search ? win.location.search : win.location.hash;
var msg = {};
msg[Constants.authResponseProperty] = response;
win.opener.postMessage(msg, origin || win.location.origin);
};
SDK.prototype.platform = function () {
return this._platform;
};
SDK.prototype.client = function () {
return this._client;
};
SDK.prototype.cache = function () {
return this._cache;
};
SDK.version = Constants.version;
SDK.server = {
sandbox: 'https://platform.devtest.ringcentral.com',
production: 'https://platform.ringcentral.com',
};
return SDK;
}());
exports.SDK = SDK;
exports.default = SDK;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var Cache = /** @class */ (function () {
function Cache(_a) {
var _b = _a.prefix, prefix = _b === void 0 ? Cache.defaultPrefix : _b, externals = _a.externals;
this._prefix = null;
this._externals = null;
this._prefix = prefix;
this._externals = externals;
}
Cache.prototype.setItemSync = function (key, data) {
this._externals.localStorage.setItem(this._prefixKey(key), JSON.stringify(data));
return this;
};
Cache.prototype.setItem = function (key, data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
this.setItemSync(key, data);
return [2 /*return*/];
});
});
};
Cache.prototype.removeItemSync = function (key) {
this._externals.localStorage.removeItem(this._prefixKey(key));
return this;
};
Cache.prototype.removeItem = function (key) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.removeItemSync(key)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
Cache.prototype.getItemSync = function (key) {
var item = this._externals.localStorage.getItem(this._prefixKey(key));
if (!item)
return null;
return JSON.parse(item);
};
Cache.prototype.getItem = function (key) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.getItemSync(key)];
});
});
};
Cache.prototype._keys = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, 'keys' in this._externals.localStorag