@defra/flood-webchat 0.0.1-alpha.11 → 0.0.1-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -7,21 +7,12 @@
7
7
  \*****************************/
8
8
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
9
9
 
10
- function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
11
- function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return { value: void 0, done: !0 }; } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable || "" === iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } throw new TypeError(_typeof(iterable) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
12
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
13
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
14
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
15
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
16
- function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
17
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
18
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
19
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
20
- var _require = __webpack_require__(/*! ./lib/client.js */ "./src/server/lib/client.js"),
21
- authenticate = _require.authenticate,
22
- getHost = _require.getHost,
23
- getIsOpen = _require.getIsOpen,
24
- getActivity = _require.getActivity;
10
+ const {
11
+ authenticate,
12
+ getApiBaseUrl,
13
+ getIsOpen,
14
+ getActivity
15
+ } = __webpack_require__(/*! ./lib/client.js */ "./src/server/lib/client.js");
25
16
 
26
17
  /**
27
18
  * Returns webchat availability
@@ -32,72 +23,67 @@ var _require = __webpack_require__(/*! ./lib/client.js */ "./src/server/lib/clie
32
23
  * @param options.accessSecret {string}
33
24
  * @param options.skillEndpoint {string}
34
25
  * @param options.hoursEndpoint {string}
26
+ * @param options.authenticationUri {string}
27
+ * @param options.wellKnownUri {string}
35
28
  * @param options.maxQueueCount {string}
36
29
  * @returns {Promise<{date: Date, availability: (string)}>}
37
30
  */
38
- module.exports = /*#__PURE__*/function () {
39
- var _getAvailability = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
40
- var clientId, clientSecret, accessKey, accessSecret, skillEndpoint, hoursEndpoint, maxQueueCount, authorisation, _yield$authenticate, tenantId, token, tokenType, host, _yield$Promise$all, _yield$Promise$all2, _yield$Promise$all2$, hasCapacity, hasAgentsAvailable, isOpen, isAvailable, isExistingOnly, availability;
41
- return _regeneratorRuntime().wrap(function _callee$(_context) {
42
- while (1) switch (_context.prev = _context.next) {
43
- case 0:
44
- clientId = _ref.clientId, clientSecret = _ref.clientSecret, accessKey = _ref.accessKey, accessSecret = _ref.accessSecret, skillEndpoint = _ref.skillEndpoint, hoursEndpoint = _ref.hoursEndpoint, maxQueueCount = _ref.maxQueueCount;
45
- authorisation = 'Basic ' + Buffer.from("".concat(encodeURIComponent(clientId), ":").concat(encodeURIComponent(clientSecret))).toString('base64'); // Cache authentication and re-authenticate when needed (lasts 1 hour?)
46
- _context.next = 4;
47
- return authenticate({
48
- authorisation: authorisation,
49
- accessKey: accessKey,
50
- accessSecret: accessSecret
51
- });
52
- case 4:
53
- _yield$authenticate = _context.sent;
54
- tenantId = _yield$authenticate.tenantId;
55
- token = _yield$authenticate.token;
56
- tokenType = _yield$authenticate.tokenType;
57
- _context.next = 10;
58
- return getHost({
59
- tenantId: tenantId
60
- });
61
- case 10:
62
- host = _context.sent;
63
- _context.next = 13;
64
- return Promise.all([getActivity({
65
- tokenType: tokenType,
66
- token: token,
67
- host: host,
68
- skillEndpoint: skillEndpoint,
69
- maxQueueCount: maxQueueCount
70
- }), getIsOpen({
71
- token: token,
72
- tokenType: tokenType,
73
- host: host,
74
- hoursEndpoint: hoursEndpoint
75
- })]);
76
- case 13:
77
- _yield$Promise$all = _context.sent;
78
- _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
79
- _yield$Promise$all2$ = _yield$Promise$all2[0];
80
- hasCapacity = _yield$Promise$all2$.hasCapacity;
81
- hasAgentsAvailable = _yield$Promise$all2$.hasAgentsAvailable;
82
- isOpen = _yield$Promise$all2[1];
83
- isAvailable = isOpen && hasAgentsAvailable && hasCapacity;
84
- isExistingOnly = isOpen && hasAgentsAvailable && !hasCapacity;
85
- availability = isAvailable ? 'AVAILABLE' : isExistingOnly ? 'EXISTING' : 'UNAVAILABLE';
86
- return _context.abrupt("return", {
87
- date: new Date(),
88
- availability: availability
89
- });
90
- case 23:
91
- case "end":
92
- return _context.stop();
93
- }
94
- }, _callee);
95
- }));
96
- function getAvailability(_x) {
97
- return _getAvailability.apply(this, arguments);
31
+ module.exports = async function getAvailability({
32
+ clientId,
33
+ clientSecret,
34
+ accessKey,
35
+ accessSecret,
36
+ maxQueueCount,
37
+ skillEndpoint,
38
+ hoursEndpoint,
39
+ wellKnownUri = 'https://cxone.niceincontact.com/.well-known/cxone-configuration',
40
+ authenticationUri = 'https://cxone.niceincontact.com/auth/token'
41
+ }) {
42
+ const authorisation = 'Basic ' + Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString('base64');
43
+
44
+ // Cache authentication and re-authenticate when needed (lasts 1 hour?)
45
+ const {
46
+ tenantId,
47
+ token,
48
+ tokenType
49
+ } = await authenticate({
50
+ authenticationUri,
51
+ authorisation,
52
+ accessKey,
53
+ accessSecret
54
+ });
55
+ const apiBaseUrl = await getApiBaseUrl({
56
+ wellKnownUri,
57
+ tenantId
58
+ });
59
+ const [{
60
+ hasCapacity,
61
+ hasAgentsAvailable
62
+ }, isOpen] = await Promise.all([getActivity({
63
+ tokenType,
64
+ token,
65
+ baseUrl: apiBaseUrl,
66
+ skillEndpoint,
67
+ maxQueueCount
68
+ }), getIsOpen({
69
+ token,
70
+ tokenType,
71
+ baseUrl: apiBaseUrl,
72
+ hoursEndpoint
73
+ })]);
74
+ const isAvailable = isOpen && hasAgentsAvailable && hasCapacity;
75
+ const isExistingOnly = isOpen && hasAgentsAvailable && !hasCapacity;
76
+ let availability = 'UNAVAILABLE';
77
+ if (isAvailable) {
78
+ availability = 'AVAILABLE';
79
+ } else if (isExistingOnly) {
80
+ availability = 'EXISTING';
98
81
  }
99
- return getAvailability;
100
- }();
82
+ return {
83
+ date: new Date(),
84
+ availability
85
+ };
86
+ };
101
87
 
102
88
  /***/ }),
103
89
 
@@ -107,154 +93,100 @@ module.exports = /*#__PURE__*/function () {
107
93
  \**********************************/
108
94
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
109
95
 
110
- function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
111
- function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return { value: void 0, done: !0 }; } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable || "" === iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } throw new TypeError(_typeof(iterable) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
112
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
113
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
114
- var querystring = __webpack_require__(/*! querystring */ "querystring");
115
- var axios = __webpack_require__(/*! axios */ "axios");
116
- var jwtdecode = __webpack_require__(/*! jwt-decode */ "jwt-decode");
117
- var _require = __webpack_require__(/*! ./utils.js */ "./src/server/lib/utils.js"),
118
- isWithinHours = _require.isWithinHours;
119
- var authenticate = /*#__PURE__*/function () {
120
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
121
- var _jwtdecode;
122
- var authorisation, accessKey, accessSecret, uri, config, body, auth;
123
- return _regeneratorRuntime().wrap(function _callee$(_context) {
124
- while (1) switch (_context.prev = _context.next) {
125
- case 0:
126
- authorisation = _ref.authorisation, accessKey = _ref.accessKey, accessSecret = _ref.accessSecret;
127
- uri = 'https://cxone.niceincontact.com/auth/token';
128
- config = {
129
- signal: AbortSignal.timeout(3000),
130
- headers: {
131
- Host: 'eu1.niceincontact.com',
132
- 'Content-Type': 'application/x-www-form-urlencoded',
133
- Authorization: authorisation
134
- }
135
- };
136
- body = querystring.stringify({
137
- grant_type: 'password',
138
- username: accessKey,
139
- password: accessSecret
140
- });
141
- _context.next = 6;
142
- return axios.post(uri, body, config);
143
- case 6:
144
- auth = _context.sent;
145
- return _context.abrupt("return", {
146
- token: auth.data.access_token,
147
- tokenType: auth.data.token_type,
148
- tenantId: (_jwtdecode = jwtdecode(auth.data.id_token)) === null || _jwtdecode === void 0 ? void 0 : _jwtdecode.tenantId
149
- });
150
- case 8:
151
- case "end":
152
- return _context.stop();
153
- }
154
- }, _callee);
155
- }));
156
- return function authenticate(_x) {
157
- return _ref2.apply(this, arguments);
158
- };
159
- }();
160
- var getHost = /*#__PURE__*/function () {
161
- var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref3) {
162
- var tenantId, uri, config, api;
163
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
164
- while (1) switch (_context2.prev = _context2.next) {
165
- case 0:
166
- tenantId = _ref3.tenantId;
167
- uri = "https://cxone.niceincontact.com/.well-known/cxone-configuration?tenantId=".concat(tenantId);
168
- config = {
169
- signal: AbortSignal.timeout(3000)
170
- };
171
- _context2.next = 5;
172
- return axios.get(uri, config);
173
- case 5:
174
- api = _context2.sent;
175
- return _context2.abrupt("return", "api-".concat(api.data.area, ".niceincontact.com"));
176
- case 7:
177
- case "end":
178
- return _context2.stop();
179
- }
180
- }, _callee2);
181
- }));
182
- return function getHost(_x2) {
183
- return _ref4.apply(this, arguments);
184
- };
185
- }();
186
- var getActivity = /*#__PURE__*/function () {
187
- var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref5) {
188
- var tokenType, token, host, skillEndpoint, maxQueueCount, config, uri, skill, activity;
189
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
190
- while (1) switch (_context3.prev = _context3.next) {
191
- case 0:
192
- tokenType = _ref5.tokenType, token = _ref5.token, host = _ref5.host, skillEndpoint = _ref5.skillEndpoint, maxQueueCount = _ref5.maxQueueCount;
193
- config = {
194
- signal: AbortSignal.timeout(3000),
195
- headers: {
196
- Host: host,
197
- Authorization: "".concat(tokenType, " ").concat(token),
198
- 'Content-Type': 'application/x-www-form-urlencoded'
199
- }
200
- };
201
- uri = "https://".concat(host).concat(skillEndpoint);
202
- _context3.next = 5;
203
- return axios.get(uri, config);
204
- case 5:
205
- skill = _context3.sent;
206
- activity = skill.data.skillActivity[0];
207
- return _context3.abrupt("return", {
208
- hasCapacity: activity.queueCount < maxQueueCount,
209
- hasAgentsAvailable: activity.agentsAvailable >= 1
210
- });
211
- case 8:
212
- case "end":
213
- return _context3.stop();
214
- }
215
- }, _callee3);
216
- }));
217
- return function getActivity(_x3) {
218
- return _ref6.apply(this, arguments);
96
+ const querystring = __webpack_require__(/*! querystring */ "querystring");
97
+ const axios = __webpack_require__(/*! axios */ "axios");
98
+ const jwtdecode = __webpack_require__(/*! jwt-decode */ "jwt-decode");
99
+ const {
100
+ isWithinHours
101
+ } = __webpack_require__(/*! ./utils.js */ "./src/server/lib/utils.js");
102
+ const contentType = 'application/x-www-form-urlencoded';
103
+ const authenticate = async ({
104
+ authenticationUri,
105
+ authorisation,
106
+ accessKey,
107
+ accessSecret
108
+ }) => {
109
+ const url = new URL(authenticationUri);
110
+ const body = querystring.stringify({
111
+ grant_type: 'password',
112
+ username: accessKey,
113
+ password: accessSecret
114
+ });
115
+ const auth = await axios.post(url.href, body, {
116
+ signal: AbortSignal.timeout(3000),
117
+ headers: {
118
+ Host: url.host,
119
+ 'Content-Type': contentType,
120
+ Authorization: authorisation
121
+ }
122
+ });
123
+ return {
124
+ token: auth.data.access_token,
125
+ tokenType: auth.data.token_type,
126
+ tenantId: jwtdecode(auth.data.id_token)?.tenantId
219
127
  };
220
- }();
221
- var getIsOpen = /*#__PURE__*/function () {
222
- var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref7) {
223
- var host, token, tokenType, hoursEndpoint, config, uri, hours, days;
224
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
225
- while (1) switch (_context4.prev = _context4.next) {
226
- case 0:
227
- host = _ref7.host, token = _ref7.token, tokenType = _ref7.tokenType, hoursEndpoint = _ref7.hoursEndpoint;
228
- config = {
229
- signal: AbortSignal.timeout(3000),
230
- headers: {
231
- Host: 'api-l36.niceincontact.com',
232
- Authorization: "".concat(tokenType, " ").concat(token),
233
- 'Content-Type': 'application/x-www-form-urlencoded'
234
- }
235
- };
236
- uri = "https://".concat(host).concat(hoursEndpoint);
237
- _context4.next = 5;
238
- return axios.get(uri, config);
239
- case 5:
240
- hours = _context4.sent;
241
- days = hours.data.resultSet.hoursOfOperationProfiles[0].days;
242
- return _context4.abrupt("return", isWithinHours(days));
243
- case 8:
244
- case "end":
245
- return _context4.stop();
246
- }
247
- }, _callee4);
248
- }));
249
- return function getIsOpen(_x4) {
250
- return _ref8.apply(this, arguments);
128
+ };
129
+ const getApiBaseUrl = async ({
130
+ wellKnownUri,
131
+ tenantId
132
+ }) => {
133
+ const url = new URL(wellKnownUri);
134
+ url.searchParams.set('tenantId', tenantId);
135
+ const {
136
+ data
137
+ } = await axios.get(url.href, {
138
+ headers: {
139
+ Host: url.host
140
+ },
141
+ signal: AbortSignal.timeout(3000)
142
+ });
143
+ return data.api_endpoint;
144
+ };
145
+ const getActivity = async ({
146
+ tokenType,
147
+ token,
148
+ baseUrl,
149
+ skillEndpoint,
150
+ maxQueueCount
151
+ }) => {
152
+ const url = new URL(skillEndpoint, baseUrl);
153
+ const skill = await axios.get(url.href, {
154
+ signal: AbortSignal.timeout(3000),
155
+ headers: {
156
+ Host: url.host,
157
+ Authorization: `${tokenType} ${token}`,
158
+ 'Content-Type': contentType
159
+ }
160
+ });
161
+ const activity = skill.data.skillActivity[0];
162
+ return {
163
+ hasCapacity: activity.queueCount < maxQueueCount,
164
+ hasAgentsAvailable: activity.agentsAvailable >= 1
251
165
  };
252
- }();
166
+ };
167
+ const getIsOpen = async ({
168
+ baseUrl,
169
+ token,
170
+ tokenType,
171
+ hoursEndpoint
172
+ }) => {
173
+ const url = new URL(hoursEndpoint, baseUrl);
174
+ const hours = await axios.get(url.href, {
175
+ signal: AbortSignal.timeout(3000),
176
+ headers: {
177
+ Host: url.host,
178
+ Authorization: `${tokenType} ${token}`,
179
+ 'Content-Type': contentType
180
+ }
181
+ });
182
+ const days = hours.data.resultSet.hoursOfOperationProfiles[0].days;
183
+ return isWithinHours(days);
184
+ };
253
185
  module.exports = {
254
- authenticate: authenticate,
255
- getHost: getHost,
256
- getIsOpen: getIsOpen,
257
- getActivity: getActivity
186
+ authenticate,
187
+ getApiBaseUrl,
188
+ getIsOpen,
189
+ getActivity
258
190
  };
259
191
 
260
192
  /***/ }),
@@ -265,21 +197,19 @@ module.exports = {
265
197
  \*********************************/
266
198
  /***/ ((module) => {
267
199
 
268
- var isWithinHours = function isWithinHours(days) {
269
- var now = new Date();
270
- var name = now.toLocaleDateString('en-GB', {
200
+ const isWithinHours = (days, date = null) => {
201
+ const now = date ? new Date(date) : new Date();
202
+ const name = now.toLocaleDateString('en-GB', {
271
203
  weekday: 'long'
272
204
  });
273
- var day = days.find(function (d) {
274
- return d.day.toLowerCase() === name.toLowerCase();
275
- });
276
- var date = now.toLocaleDateString('en-GB').split('/');
277
- var open = "".concat(date[2], "-").concat(date[1], "-").concat(date[0], "T").concat(day.openTime, ".000Z");
278
- var close = "".concat(date[2], "-").concat(date[1], "-").concat(date[0], "T").concat(day.closeTime, ".000Z");
205
+ const day = days.find(d => d.day.toLowerCase() === name.toLowerCase());
206
+ const dateItems = now.toLocaleDateString('en-GB').split('/');
207
+ const open = `${dateItems[2]}-${dateItems[1]}-${dateItems[0]}T${day.openTime}`;
208
+ const close = `${dateItems[2]}-${dateItems[1]}-${dateItems[0]}T${day.closeTime}`;
279
209
  return now.getTime() >= Date.parse(open) && now.getTime() <= Date.parse(close);
280
210
  };
281
211
  module.exports = {
282
- isWithinHours: isWithinHours
212
+ isWithinHours
283
213
  };
284
214
 
285
215
  /***/ }),