@webex/webex-core 3.8.0-next.2 → 3.8.0-next.20

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.
Files changed (48) hide show
  1. package/dist/index.js +43 -0
  2. package/dist/index.js.map +1 -1
  3. package/dist/lib/batcher.js +1 -1
  4. package/dist/lib/credentials/credentials.js +1 -1
  5. package/dist/lib/credentials/token.js +1 -1
  6. package/dist/lib/services/service-catalog.js +23 -68
  7. package/dist/lib/services/service-catalog.js.map +1 -1
  8. package/dist/lib/services/services.js +1 -1
  9. package/dist/lib/services-v2/constants.js +17 -0
  10. package/dist/lib/services-v2/constants.js.map +1 -0
  11. package/dist/lib/services-v2/index.js +58 -0
  12. package/dist/lib/services-v2/index.js.map +1 -0
  13. package/dist/lib/services-v2/interceptors/hostmap.js +64 -0
  14. package/dist/lib/services-v2/interceptors/hostmap.js.map +1 -0
  15. package/dist/lib/services-v2/interceptors/server-error.js +77 -0
  16. package/dist/lib/services-v2/interceptors/server-error.js.map +1 -0
  17. package/dist/lib/services-v2/interceptors/service.js +137 -0
  18. package/dist/lib/services-v2/interceptors/service.js.map +1 -0
  19. package/dist/lib/services-v2/metrics.js +12 -0
  20. package/dist/lib/services-v2/metrics.js.map +1 -0
  21. package/dist/lib/services-v2/service-catalog.js +433 -0
  22. package/dist/lib/services-v2/service-catalog.js.map +1 -0
  23. package/dist/lib/services-v2/service-fed-ramp.js +13 -0
  24. package/dist/lib/services-v2/service-fed-ramp.js.map +1 -0
  25. package/dist/lib/services-v2/service-url.js +119 -0
  26. package/dist/lib/services-v2/service-url.js.map +1 -0
  27. package/dist/lib/services-v2/services-v2.js +963 -0
  28. package/dist/lib/services-v2/services-v2.js.map +1 -0
  29. package/dist/plugins/logger.js +1 -1
  30. package/dist/webex-core.js +2 -2
  31. package/dist/webex-core.js.map +1 -1
  32. package/package.json +13 -13
  33. package/src/index.js +10 -0
  34. package/src/lib/services/service-catalog.js +14 -54
  35. package/src/lib/services-v2/README.md +3 -0
  36. package/src/lib/services-v2/constants.js +21 -0
  37. package/src/lib/services-v2/index.js +23 -0
  38. package/src/lib/services-v2/interceptors/hostmap.js +36 -0
  39. package/src/lib/services-v2/interceptors/server-error.js +48 -0
  40. package/src/lib/services-v2/interceptors/service.js +101 -0
  41. package/src/lib/services-v2/metrics.js +4 -0
  42. package/src/lib/services-v2/service-catalog.js +455 -0
  43. package/src/lib/services-v2/service-fed-ramp.js +5 -0
  44. package/src/lib/services-v2/service-url.js +124 -0
  45. package/src/lib/services-v2/services-v2.js +971 -0
  46. package/test/fixtures/host-catalog-v2.js +247 -0
  47. package/test/unit/spec/services/service-catalog.js +30 -90
  48. package/test/unit/spec/services-v2/services-v2.js +564 -0
@@ -0,0 +1,963 @@
1
+ "use strict";
2
+
3
+ var _Object$keys2 = require("@babel/runtime-corejs2/core-js/object/keys");
4
+ var _Object$getOwnPropertySymbols = require("@babel/runtime-corejs2/core-js/object/get-own-property-symbols");
5
+ var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptor");
6
+ var _Object$getOwnPropertyDescriptors = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptors");
7
+ var _Object$defineProperties = require("@babel/runtime-corejs2/core-js/object/define-properties");
8
+ var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
9
+ var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
10
+ _Object$defineProperty(exports, "__esModule", {
11
+ value: true
12
+ });
13
+ exports.default = exports.DEFAULT_CLUSTER_SERVICE = exports.DEFAULT_CLUSTER = void 0;
14
+ var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/slicedToArray"));
15
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
16
+ var _weakMap = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/weak-map"));
17
+ var _keys = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/keys"));
18
+ var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));
19
+ var _sha = _interopRequireDefault(require("crypto-js/sha256"));
20
+ var _lodash = require("lodash");
21
+ var _webexPlugin = _interopRequireDefault(require("../webex-plugin"));
22
+ var _metrics = _interopRequireDefault(require("./metrics"));
23
+ var _serviceCatalog = _interopRequireDefault(require("./service-catalog"));
24
+ var _serviceFedRamp = _interopRequireDefault(require("./service-fed-ramp"));
25
+ var _constants = require("./constants");
26
+ function ownKeys(e, r) { var t = _Object$keys2(e); if (_Object$getOwnPropertySymbols) { var o = _Object$getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return _Object$getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
27
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(e, _Object$getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { _Object$defineProperty(e, r, _Object$getOwnPropertyDescriptor(t, r)); }); } return e; }
28
+ var trailingSlashes = /(?:^\/)|(?:\/$)/;
29
+
30
+ // The default cluster when one is not provided (usually as 'US' from hydra)
31
+ var DEFAULT_CLUSTER = exports.DEFAULT_CLUSTER = 'urn:TEAM:us-east-2_a';
32
+ // The default service name for convo (currently identityLookup due to some weird CSB issue)
33
+ var DEFAULT_CLUSTER_SERVICE = exports.DEFAULT_CLUSTER_SERVICE = 'identityLookup';
34
+ var CLUSTER_SERVICE = process.env.WEBEX_CONVERSATION_CLUSTER_SERVICE || DEFAULT_CLUSTER_SERVICE;
35
+ var DEFAULT_CLUSTER_IDENTIFIER = process.env.WEBEX_CONVERSATION_DEFAULT_CLUSTER || "".concat(DEFAULT_CLUSTER, ":").concat(CLUSTER_SERVICE);
36
+
37
+ /* eslint-disable no-underscore-dangle */
38
+ /**
39
+ * @class
40
+ */
41
+ var Services = _webexPlugin.default.extend({
42
+ namespace: 'Services',
43
+ props: {
44
+ validateDomains: ['boolean', false, true],
45
+ initFailed: ['boolean', false, false]
46
+ },
47
+ _catalogs: new _weakMap.default(),
48
+ _activeServices: {},
49
+ _services: [],
50
+ /**
51
+ * @private
52
+ * Get the current catalog based on the assocaited
53
+ * webex instance.
54
+ * @returns {ServiceCatalog}
55
+ */
56
+ _getCatalog: function _getCatalog() {
57
+ return this._catalogs.get(this.webex);
58
+ },
59
+ /**
60
+ * Get a service url from the current services list by name
61
+ * from the associated instance catalog.
62
+ * @param {string} name
63
+ * @param {boolean} [priorityHost]
64
+ * @param {string} [serviceGroup]
65
+ * @returns {string|undefined}
66
+ */
67
+ get: function get(name, priorityHost, serviceGroup) {
68
+ var catalog = this._getCatalog();
69
+ return catalog.get(name, priorityHost, serviceGroup);
70
+ },
71
+ /**
72
+ * Determine if a whilelist exists in the service catalog.
73
+ *
74
+ * @returns {boolean} - True if a allowed domains list exists.
75
+ */
76
+ hasAllowedDomains: function hasAllowedDomains() {
77
+ var catalog = this._getCatalog();
78
+ return catalog.getAllowedDomains().length > 0;
79
+ },
80
+ /**
81
+ * Generate a service catalog as an object from
82
+ * the associated instance catalog.
83
+ * @param {boolean} [priorityHost] - use highest priority host if set to `true`
84
+ * @param {string} [serviceGroup]
85
+ * @returns {Record<string, string>}
86
+ */
87
+ list: function list(priorityHost, serviceGroup) {
88
+ var catalog = this._getCatalog();
89
+ return catalog.list(priorityHost, serviceGroup);
90
+ },
91
+ /**
92
+ * Mark a priority host service url as failed.
93
+ * This will mark the host associated with the
94
+ * `ServiceUrl` to be removed from the its
95
+ * respective host array, and then return the next
96
+ * viable host from the `ServiceUrls` host array,
97
+ * or the `ServiceUrls` default url if no other priority
98
+ * hosts are available, or if `noPriorityHosts` is set to
99
+ * `true`.
100
+ * @param {string} url
101
+ * @param {boolean} noPriorityHosts
102
+ * @returns {string}
103
+ */
104
+ markFailedUrl: function markFailedUrl(url, noPriorityHosts) {
105
+ var catalog = this._getCatalog();
106
+ return catalog.markFailedUrl(url, noPriorityHosts);
107
+ },
108
+ /**
109
+ * saves all the services from the pre and post catalog service
110
+ * @param {Object} activeServices
111
+ * @returns {void}
112
+ */
113
+ _updateActiveServices: function _updateActiveServices(activeServices) {
114
+ this._activeServices = _objectSpread(_objectSpread({}, this._activeServices), activeServices);
115
+ },
116
+ /**
117
+ * saves the hostCatalog object
118
+ * @param {Object} services
119
+ * @returns {void}
120
+ */
121
+ _updateServices: function _updateServices(services) {
122
+ this._services = (0, _lodash.unionBy)(services, this._services, 'id');
123
+ },
124
+ /**
125
+ * Update a list of `serviceUrls` to the most current
126
+ * catalog via the defined `discoveryUrl` then returns the current
127
+ * list of services.
128
+ * @param {object} [param]
129
+ * @param {string} [param.from] - This accepts `limited` or `signin`
130
+ * @param {object} [param.query] - This accepts `email`, `orgId` or `userId` key values
131
+ * @param {string} [param.query.email] - must be a standard-format email
132
+ * @param {string} [param.query.orgId] - must be an organization id
133
+ * @param {string} [param.query.userId] - must be a user id
134
+ * @param {string} [param.token] - used for signin catalog
135
+ * @returns {Promise<object>}
136
+ */
137
+ updateServices: function updateServices() {
138
+ var _this = this;
139
+ var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
140
+ from = _ref.from,
141
+ query = _ref.query,
142
+ token = _ref.token,
143
+ forceRefresh = _ref.forceRefresh;
144
+ var catalog = this._getCatalog();
145
+ var formattedQuery;
146
+ var serviceGroup;
147
+
148
+ // map catalog name to service group name.
149
+ switch (from) {
150
+ case 'limited':
151
+ serviceGroup = 'preauth';
152
+ break;
153
+ case 'signin':
154
+ serviceGroup = 'signin';
155
+ break;
156
+ default:
157
+ serviceGroup = 'postauth';
158
+ break;
159
+ }
160
+
161
+ // confirm catalog update for group is not in progress.
162
+ if (catalog.status[serviceGroup].collecting) {
163
+ return this.waitForCatalog(serviceGroup);
164
+ }
165
+ catalog.status[serviceGroup].collecting = true;
166
+ if (serviceGroup === 'preauth') {
167
+ var queryKey = query && (0, _keys.default)(query)[0];
168
+ if (!['email', 'emailhash', 'userId', 'orgId', 'mode'].includes(queryKey)) {
169
+ return _promise.default.reject(new Error('a query param of email, emailhash, userId, orgId, or mode is required'));
170
+ }
171
+ }
172
+ // encode email when query key is email
173
+ if (serviceGroup === 'preauth' || serviceGroup === 'signin') {
174
+ var _queryKey = (0, _keys.default)(query)[0];
175
+ formattedQuery = {};
176
+ if (_queryKey === 'email' && query.email) {
177
+ formattedQuery.emailhash = (0, _sha.default)(query.email.toLowerCase()).toString();
178
+ } else {
179
+ formattedQuery[_queryKey] = query[_queryKey];
180
+ }
181
+ }
182
+ return this._fetchNewServiceHostmap({
183
+ from: from,
184
+ token: token,
185
+ query: formattedQuery,
186
+ forceRefresh: forceRefresh
187
+ }).then(function (serviceHostMap) {
188
+ catalog.updateServiceUrls(serviceGroup, serviceHostMap);
189
+ _this.updateCredentialsConfig();
190
+ catalog.status[serviceGroup].collecting = false;
191
+ }).catch(function (error) {
192
+ catalog.status[serviceGroup].collecting = false;
193
+ return _promise.default.reject(error);
194
+ });
195
+ },
196
+ /**
197
+ * User validation parameter transfer object for {@link validateUser}.
198
+ * @param {object} ValidateUserPTO
199
+ * @property {string} ValidateUserPTO.email - The email of the user.
200
+ * @property {string} [ValidateUserPTO.reqId] - The activation requester.
201
+ * @property {object} [ValidateUserPTO.activationOptions] - Extra options to pass when sending the activation
202
+ * @property {object} [ValidateUserPTO.preloginUserId] - The prelogin user id to set when sending the activation.
203
+ */
204
+ /**
205
+ * User validation return transfer object for {@link validateUser}.
206
+ * @param {object} ValidateUserRTO
207
+ * @property {boolean} ValidateUserRTO.activated - If the user is activated.
208
+ * @property {boolean} ValidateUserRTO.exists - If the user exists.
209
+ * @property {string} ValidateUserRTO.details - A descriptive status message.
210
+ * @property {object} ValidateUserRTO.user - **License** service user object.
211
+ */
212
+ /**
213
+ * Validate if a user is activated and update the service catalogs as needed
214
+ * based on the user's activation status.
215
+ *
216
+ * @param {ValidateUserPTO} - The parameter transfer object.
217
+ * @returns {ValidateUserRTO} - The return transfer object.
218
+ */
219
+ validateUser: function validateUser(_ref2) {
220
+ var _this2 = this;
221
+ var email = _ref2.email,
222
+ _ref2$reqId = _ref2.reqId,
223
+ reqId = _ref2$reqId === void 0 ? 'WEBCLIENT' : _ref2$reqId,
224
+ _ref2$forceRefresh = _ref2.forceRefresh,
225
+ forceRefresh = _ref2$forceRefresh === void 0 ? false : _ref2$forceRefresh,
226
+ _ref2$activationOptio = _ref2.activationOptions,
227
+ activationOptions = _ref2$activationOptio === void 0 ? {} : _ref2$activationOptio,
228
+ preloginUserId = _ref2.preloginUserId;
229
+ this.logger.info('services: validating a user');
230
+
231
+ // Validate that an email parameter key was provided.
232
+ if (!email) {
233
+ return _promise.default.reject(new Error('`email` is required'));
234
+ }
235
+
236
+ // Destructure the credentials object.
237
+ var canAuthorize = this.webex.credentials.canAuthorize;
238
+
239
+ // Validate that the user is already authorized.
240
+ if (canAuthorize) {
241
+ return this.updateServices({
242
+ forceRefresh: forceRefresh
243
+ }).then(function () {
244
+ return _this2.webex.credentials.getUserToken();
245
+ }).then(function (token) {
246
+ return _this2.sendUserActivation({
247
+ email: email,
248
+ reqId: reqId,
249
+ token: token.toString(),
250
+ activationOptions: activationOptions,
251
+ preloginUserId: preloginUserId
252
+ });
253
+ }).then(function (userObj) {
254
+ return {
255
+ activated: true,
256
+ exists: true,
257
+ details: 'user is authorized via a user token',
258
+ user: userObj
259
+ };
260
+ });
261
+ }
262
+
263
+ // Destructure the client authorization details.
264
+ /* eslint-disable camelcase */
265
+ var _this$webex$credentia = this.webex.credentials.config,
266
+ client_id = _this$webex$credentia.client_id,
267
+ client_secret = _this$webex$credentia.client_secret;
268
+
269
+ // Validate that client authentication details exist.
270
+ if (!client_id || !client_secret) {
271
+ return _promise.default.reject(new Error('client authentication details are not available'));
272
+ }
273
+ /* eslint-enable camelcase */
274
+
275
+ // Declare a class-memeber-scoped token for usage within the promise chain.
276
+ var token;
277
+
278
+ // Begin client authentication user validation.
279
+ return this.collectPreauthCatalog({
280
+ email: email
281
+ }).then(function () {
282
+ // Retrieve the service url from the updated catalog. This is required
283
+ // since `WebexCore` is usually not fully initialized at the time this
284
+ // request completes.
285
+ var idbrokerService = _this2.get('idbroker', true);
286
+
287
+ // Collect the client auth token.
288
+ return _this2.webex.credentials.getClientToken({
289
+ uri: "".concat(idbrokerService, "idb/oauth2/v1/access_token"),
290
+ scope: 'webexsquare:admin webexsquare:get_conversation Identity:SCIM'
291
+ });
292
+ }).then(function (tokenObj) {
293
+ // Generate the token string.
294
+ token = tokenObj.toString();
295
+
296
+ // Collect the signin catalog using the client auth information.
297
+ return _this2.collectSigninCatalog({
298
+ email: email,
299
+ token: token,
300
+ forceRefresh: forceRefresh
301
+ });
302
+ })
303
+ // Validate if collecting the signin catalog failed and populate the RTO
304
+ // with the appropriate content.
305
+ .catch(function (error) {
306
+ return {
307
+ exists: error.name !== 'NotFound',
308
+ activated: false,
309
+ details: error.name !== 'NotFound' ? 'user exists but is not activated' : 'user does not exist and is not activated'
310
+ };
311
+ })
312
+ // Validate if the previous promise resolved with an RTO and populate the
313
+ // new RTO accordingly.
314
+ .then(function (rto) {
315
+ return _promise.default.all([rto || {
316
+ activated: true,
317
+ exists: true,
318
+ details: 'user exists and is activated'
319
+ }, _this2.sendUserActivation({
320
+ email: email,
321
+ reqId: reqId,
322
+ token: token,
323
+ activationOptions: activationOptions,
324
+ preloginUserId: preloginUserId
325
+ })]);
326
+ }).then(function (_ref3) {
327
+ var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
328
+ rto = _ref4[0],
329
+ user = _ref4[1];
330
+ return _objectSpread(_objectSpread({}, rto), {}, {
331
+ user: user
332
+ });
333
+ }).catch(function (error) {
334
+ var response = {
335
+ statusCode: error.statusCode,
336
+ responseText: error.body && error.body.message,
337
+ body: error.body
338
+ };
339
+ return _promise.default.reject(response);
340
+ });
341
+ },
342
+ /**
343
+ * Get user meeting preferences (preferred webex site).
344
+ *
345
+ * @returns {object} - User Information including user preferrences .
346
+ */
347
+ getMeetingPreferences: function getMeetingPreferences() {
348
+ var _this3 = this;
349
+ return this.request({
350
+ method: 'GET',
351
+ service: 'hydra',
352
+ resource: 'meetingPreferences'
353
+ }).then(function (res) {
354
+ _this3.logger.info('services: received user region info');
355
+ return res.body;
356
+ }).catch(function (err) {
357
+ _this3.logger.info('services: was not able to fetch user login information', err);
358
+ // resolve successfully even if request failed
359
+ });
360
+ },
361
+ /**
362
+ * Fetches client region info such as countryCode and timezone.
363
+ *
364
+ * @returns {object} - The region info object.
365
+ */
366
+ fetchClientRegionInfo: function fetchClientRegionInfo() {
367
+ var _this4 = this;
368
+ var services = this.webex.config.services;
369
+ return this.request({
370
+ uri: services.discovery.sqdiscovery,
371
+ addAuthHeader: false,
372
+ headers: {
373
+ 'spark-user-agent': null
374
+ },
375
+ timeout: 5000
376
+ }).then(function (res) {
377
+ _this4.logger.info('services: received user region info');
378
+ return res.body;
379
+ }).catch(function (err) {
380
+ _this4.logger.info('services: was not able to get user region info', err);
381
+ // resolve successfully even if request failed
382
+ });
383
+ },
384
+ /**
385
+ * User activation parameter transfer object for {@link sendUserActivation}.
386
+ * @typedef {object} SendUserActivationPTO
387
+ * @property {string} SendUserActivationPTO.email - The email of the user.
388
+ * @property {string} SendUserActivationPTO.reqId - The activation requester.
389
+ * @property {string} SendUserActivationPTO.token - The client auth token.
390
+ * @property {object} SendUserActivationPTO.activationOptions - Extra options to pass when sending the activation.
391
+ * @property {object} SendUserActivationPTO.preloginUserId - The prelogin user id to set when sending the activation.
392
+ */
393
+ /**
394
+ * Send a request to activate a user using a client token.
395
+ *
396
+ * @param {SendUserActivationPTO} - The Parameter transfer object.
397
+ * @returns {LicenseDTO} - The DTO returned from the **License** service.
398
+ */
399
+ sendUserActivation: function sendUserActivation(_ref5) {
400
+ var _this5 = this;
401
+ var email = _ref5.email,
402
+ reqId = _ref5.reqId,
403
+ token = _ref5.token,
404
+ activationOptions = _ref5.activationOptions,
405
+ preloginUserId = _ref5.preloginUserId;
406
+ this.logger.info('services: sending user activation request');
407
+ var countryCode;
408
+ var timezone;
409
+
410
+ // try to fetch client region info first
411
+ return this.fetchClientRegionInfo().then(function (clientRegionInfo) {
412
+ if (clientRegionInfo) {
413
+ countryCode = clientRegionInfo.countryCode;
414
+ timezone = clientRegionInfo.timezone;
415
+ }
416
+
417
+ // Send the user activation request to the **License** service.
418
+ return _this5.request({
419
+ service: 'license',
420
+ resource: 'users/activations',
421
+ method: 'POST',
422
+ headers: {
423
+ accept: 'application/json',
424
+ authorization: token,
425
+ 'x-prelogin-userid': preloginUserId
426
+ },
427
+ body: _objectSpread({
428
+ email: email,
429
+ reqId: reqId,
430
+ countryCode: countryCode,
431
+ timeZone: timezone
432
+ }, activationOptions),
433
+ shouldRefreshAccessToken: false
434
+ });
435
+ })
436
+ // On success, return the **License** user object.
437
+ .then(function (_ref6) {
438
+ var body = _ref6.body;
439
+ return body;
440
+ })
441
+ // On failure, reject with error from **License**.
442
+ .catch(function (error) {
443
+ return _promise.default.reject(error);
444
+ });
445
+ },
446
+ /**
447
+ * Updates a given service group i.e. preauth, signin, postauth with a new hostmap.
448
+ * @param {string} serviceGroup - preauth, signin, postauth
449
+ * @param {object} hostMap - The new hostmap to update the service group with.
450
+ * @returns {Promise<void>}
451
+ */
452
+ updateCatalog: function updateCatalog(serviceGroup, hostMap) {
453
+ var catalog = this._getCatalog();
454
+ var serviceHostMap = this._formatReceivedHostmap(hostMap);
455
+ return catalog.updateServiceUrls(serviceGroup, serviceHostMap);
456
+ },
457
+ /**
458
+ * simplified method to update the preauth catalog via email
459
+ *
460
+ * @param {object} query
461
+ * @param {string} query.email - A standard format email.
462
+ * @param {string} query.orgId - The user's OrgId.
463
+ * @param {boolean} forceRefresh - Boolean to bypass u2c cache control header
464
+ * @returns {Promise<void>}
465
+ */
466
+ collectPreauthCatalog: function collectPreauthCatalog(query) {
467
+ var forceRefresh = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
468
+ if (!query) {
469
+ return this.updateServices({
470
+ from: 'limited',
471
+ query: {
472
+ mode: 'DEFAULT_BY_PROXIMITY'
473
+ },
474
+ forceRefresh: forceRefresh
475
+ });
476
+ }
477
+ return this.updateServices({
478
+ from: 'limited',
479
+ query: query,
480
+ forceRefresh: forceRefresh
481
+ });
482
+ },
483
+ /**
484
+ * simplified method to update the signin catalog via email and token
485
+ * @param {object} param
486
+ * @param {string} param.email - must be a standard-format email
487
+ * @param {string} param.token - must be a client token
488
+ * @returns {Promise<void>}
489
+ */
490
+ collectSigninCatalog: function collectSigninCatalog() {
491
+ var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
492
+ email = _ref7.email,
493
+ token = _ref7.token,
494
+ forceRefresh = _ref7.forceRefresh;
495
+ if (!email) {
496
+ return _promise.default.reject(new Error('`email` is required'));
497
+ }
498
+ if (!token) {
499
+ return _promise.default.reject(new Error('`token` is required'));
500
+ }
501
+ return this.updateServices({
502
+ from: 'signin',
503
+ query: {
504
+ email: email
505
+ },
506
+ token: token,
507
+ forceRefresh: forceRefresh
508
+ });
509
+ },
510
+ /**
511
+ * Updates credentials config to utilize u2c catalog
512
+ * urls.
513
+ * @returns {void}
514
+ */
515
+ updateCredentialsConfig: function updateCredentialsConfig() {
516
+ var _this$list = this.list(true),
517
+ idbroker = _this$list.idbroker,
518
+ identity = _this$list.identity;
519
+ if (idbroker && identity) {
520
+ var _this$webex$config$cr = this.webex.config.credentials,
521
+ authorizationString = _this$webex$config$cr.authorizationString,
522
+ authorizeUrl = _this$webex$config$cr.authorizeUrl;
523
+
524
+ // This must be set outside of the setConfig method used to assign the
525
+ // idbroker and identity url values.
526
+ this.webex.config.credentials.authorizeUrl = authorizationString ? authorizeUrl : "".concat(idbroker.replace(trailingSlashes, ''), "/idb/oauth2/v1/authorize");
527
+ this.webex.setConfig({
528
+ credentials: {
529
+ idbroker: {
530
+ url: idbroker.replace(trailingSlashes, '') // remove trailing slash
531
+ },
532
+
533
+ identity: {
534
+ url: identity.replace(trailingSlashes, '') // remove trailing slash
535
+ }
536
+ }
537
+ });
538
+ }
539
+ },
540
+ /**
541
+ * Wait until the service catalog is available,
542
+ * or reject afte ra timeout of 60 seconds.
543
+ * @param {string} serviceGroup
544
+ * @param {number} [timeout] - in seconds
545
+ * @returns {Promise<void>}
546
+ */
547
+ waitForCatalog: function waitForCatalog(serviceGroup, timeout) {
548
+ var catalog = this._getCatalog();
549
+ var supertoken = this.webex.credentials.supertoken;
550
+ if (serviceGroup === 'postauth' && supertoken && supertoken.access_token && !catalog.status.postauth.collecting && !catalog.status.postauth.ready) {
551
+ if (!catalog.status.preauth.ready) {
552
+ return this.initServiceCatalogs();
553
+ }
554
+ return this.updateServices();
555
+ }
556
+ return catalog.waitForCatalog(serviceGroup, timeout);
557
+ },
558
+ /**
559
+ * Service waiting parameter transfer object for {@link waitForService}.
560
+ *
561
+ * @typedef {object} WaitForServicePTO
562
+ * @property {string} [WaitForServicePTO.name] - The service name.
563
+ * @property {string} [WaitForServicePTO.url] - The service url.
564
+ * @property {string} [WaitForServicePTO.timeout] - wait duration in seconds.
565
+ */
566
+ /**
567
+ * Wait until the service has been ammended to any service catalog. This
568
+ * method prioritizes the service name over the service url when searching.
569
+ *
570
+ * @param {WaitForServicePTO} - The parameter transfer object.
571
+ * @returns {Promise<string>} - Resolves to the priority host of a service.
572
+ */
573
+ waitForService: function waitForService(_ref8) {
574
+ var _this6 = this;
575
+ var name = _ref8.name,
576
+ _ref8$timeout = _ref8.timeout,
577
+ timeout = _ref8$timeout === void 0 ? 5 : _ref8$timeout,
578
+ url = _ref8.url;
579
+ var services = this.webex.config.services;
580
+
581
+ // Save memory by grabbing the catalog after there isn't a priortyURL
582
+ var catalog = this._getCatalog();
583
+ var fetchFromServiceUrl = services.servicesNotNeedValidation.find(function (service) {
584
+ return service === name;
585
+ });
586
+ if (fetchFromServiceUrl) {
587
+ return _promise.default.resolve(this._activeServices[name]);
588
+ }
589
+ var priorityUrl = this.get(name, true);
590
+ var priorityUrlObj = this.getServiceFromUrl(url);
591
+ if (priorityUrl || priorityUrlObj) {
592
+ return _promise.default.resolve(priorityUrl || priorityUrlObj.priorityUrl);
593
+ }
594
+ if (catalog.isReady) {
595
+ if (url) {
596
+ return _promise.default.resolve(url);
597
+ }
598
+ this.webex.internal.metrics.submitClientMetrics(_metrics.default.JS_SDK_SERVICE_NOT_FOUND, {
599
+ fields: {
600
+ service_name: name
601
+ }
602
+ });
603
+ return _promise.default.reject(new Error("services: service '".concat(name, "' was not found in any of the catalogs")));
604
+ }
605
+ return new _promise.default(function (resolve, reject) {
606
+ var groupsToCheck = ['preauth', 'signin', 'postauth'];
607
+ var checkCatalog = function checkCatalog(catalogGroup) {
608
+ return catalog.waitForCatalog(catalogGroup, timeout).then(function () {
609
+ var scopedPriorityUrl = _this6.get(name, true);
610
+ var scopedPrioriryUrlObj = _this6.getServiceFromUrl(url);
611
+ if (scopedPriorityUrl || scopedPrioriryUrlObj) {
612
+ resolve(scopedPriorityUrl || scopedPrioriryUrlObj.priorityUrl);
613
+ }
614
+ }).catch(function () {
615
+ return undefined;
616
+ });
617
+ };
618
+ _promise.default.all(groupsToCheck.map(function (group) {
619
+ return checkCatalog(group);
620
+ })).then(function () {
621
+ _this6.webex.internal.metrics.submitClientMetrics(_metrics.default.JS_SDK_SERVICE_NOT_FOUND, {
622
+ fields: {
623
+ service_name: name
624
+ }
625
+ });
626
+ reject(new Error("services: service '".concat(name, "' was not found after waiting")));
627
+ });
628
+ });
629
+ },
630
+ /**
631
+ * Looks up the hostname in the host catalog
632
+ * and replaces it with the first host if it finds it
633
+ * @param {string} uri
634
+ * @returns {string} uri with the host replaced
635
+ */
636
+ replaceHostFromHostmap: function replaceHostFromHostmap(uri) {
637
+ var url = new URL(uri);
638
+ var hostCatalog = this._services;
639
+ if (!hostCatalog) {
640
+ return uri;
641
+ }
642
+ var host = hostCatalog[url.host];
643
+ if (host && host[0]) {
644
+ var newHost = host[0].host;
645
+ url.host = newHost;
646
+ return url.toString();
647
+ }
648
+ return uri;
649
+ },
650
+ /**
651
+ * @private
652
+ * Organize a received hostmap from a service
653
+ * @param {object} serviceHostmap
654
+ * catalog endpoint.
655
+ * @returns {object}
656
+ */
657
+ _formatReceivedHostmap: function _formatReceivedHostmap(_ref9) {
658
+ var services = _ref9.services,
659
+ activeServices = _ref9.activeServices;
660
+ var formattedHostmap = services.map(function (_ref10) {
661
+ var id = _ref10.id,
662
+ serviceName = _ref10.serviceName,
663
+ serviceUrls = _ref10.serviceUrls;
664
+ var formattedServiceUrls = serviceUrls.map(function (serviceUrl) {
665
+ return _objectSpread({
666
+ host: new URL(serviceUrl.baseUrl).host
667
+ }, serviceUrl);
668
+ });
669
+ return {
670
+ id: id,
671
+ serviceName: serviceName,
672
+ serviceUrls: formattedServiceUrls
673
+ };
674
+ });
675
+ this._updateActiveServices(activeServices);
676
+ this._updateServices(services);
677
+ return formattedHostmap;
678
+ },
679
+ /**
680
+ * Get the clusterId associated with a URL string.
681
+ * @param {string} url
682
+ * @returns {string} - Cluster ID of url provided
683
+ */
684
+ getClusterId: function getClusterId(url) {
685
+ var catalog = this._getCatalog();
686
+ return catalog.findClusterId(url);
687
+ },
688
+ /**
689
+ * Get a service value from a provided clusterId. This method will
690
+ * return an object containing both the name and url of a found service.
691
+ * @param {object} params
692
+ * @param {string} params.clusterId - clusterId of found service
693
+ * @param {boolean} [params.priorityHost] - returns priority host url if true
694
+ * @param {string} [params.serviceGroup] - specify service group
695
+ * @returns {object} service
696
+ * @returns {string} service.name
697
+ * @returns {string} service.url
698
+ */
699
+ getServiceFromClusterId: function getServiceFromClusterId(params) {
700
+ var catalog = this._getCatalog();
701
+ return catalog.findServiceFromClusterId(params);
702
+ },
703
+ /**
704
+ * @param {String} cluster the cluster containing the id
705
+ * @param {UUID} [id] the id of the conversation.
706
+ * If empty, just return the base URL.
707
+ * @returns {String} url of the service
708
+ */
709
+ getServiceUrlFromClusterId: function getServiceUrlFromClusterId() {
710
+ var _ref11 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
711
+ _ref11$cluster = _ref11.cluster,
712
+ cluster = _ref11$cluster === void 0 ? 'us' : _ref11$cluster;
713
+ var clusterId = cluster === 'us' ? DEFAULT_CLUSTER_IDENTIFIER : cluster;
714
+
715
+ // Determine if cluster has service name (non-US clusters from hydra do not)
716
+ if (clusterId.split(':').length < 4) {
717
+ // Add Service to cluster identifier
718
+ clusterId = "".concat(cluster, ":").concat(CLUSTER_SERVICE);
719
+ }
720
+ var _ref12 = this.getServiceFromClusterId({
721
+ clusterId: clusterId
722
+ }) || {},
723
+ url = _ref12.url;
724
+ if (!url) {
725
+ throw Error("Could not find service for cluster [".concat(cluster, "]"));
726
+ }
727
+ return url;
728
+ },
729
+ /**
730
+ * Get a service object from a service url if the service url exists in the
731
+ * catalog.
732
+ *
733
+ * @param {string} url - The url to be validated.
734
+ * @returns {object} - Service object.
735
+ * @returns {object.name} - The name of the service found.
736
+ * @returns {object.priorityUrl} - The priority url of the found service.
737
+ * @returns {object.defaultUrl} - The default url of the found service.
738
+ */
739
+ getServiceFromUrl: function getServiceFromUrl() {
740
+ var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
741
+ var service = this._getCatalog().findServiceUrlFromUrl(url);
742
+ if (!service) {
743
+ return undefined;
744
+ }
745
+ return {
746
+ name: service.name,
747
+ priorityUrl: service.get(true),
748
+ defaultUrl: service.get()
749
+ };
750
+ },
751
+ /**
752
+ * Determine if a provided url is in the catalog's allowed domains.
753
+ *
754
+ * @param {string} url - The url to match allowed domains against.
755
+ * @returns {boolean} - True if the url provided is allowed.
756
+ */
757
+ isAllowedDomainUrl: function isAllowedDomainUrl(url) {
758
+ var catalog = this._getCatalog();
759
+ return !!catalog.findAllowedDomain(url);
760
+ },
761
+ /**
762
+ * Converts the host portion of the url from default host
763
+ * to a priority host
764
+ *
765
+ * @param {string} url a service url that contains a default host
766
+ * @returns {string} a service url that contains the top priority host.
767
+ * @throws if url isn't a service url
768
+ */
769
+ convertUrlToPriorityHostUrl: function convertUrlToPriorityHostUrl() {
770
+ var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
771
+ var data = this.getServiceFromUrl(url);
772
+ if (!data) {
773
+ throw Error("No service associated with url: [".concat(url, "]"));
774
+ }
775
+ return url.replace(data.defaultUrl, data.priorityUrl);
776
+ },
777
+ /**
778
+ * @private
779
+ * Simplified method wrapper for sending a request to get
780
+ * an updated service hostmap.
781
+ * @param {object} [param]
782
+ * @param {string} [param.from] - This accepts `limited` or `signin`
783
+ * @param {object} [param.query] - This accepts `email`, `orgId` or `userId` key values
784
+ * @param {string} [param.query.email] - must be a standard-format email
785
+ * @param {string} [param.query.orgId] - must be an organization id
786
+ * @param {string} [param.query.userId] - must be a user id
787
+ * @param {string} [param.token] - used for signin catalog
788
+ * @returns {Promise<object>}
789
+ */
790
+ _fetchNewServiceHostmap: function _fetchNewServiceHostmap() {
791
+ var _this7 = this;
792
+ var _ref13 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
793
+ from = _ref13.from,
794
+ query = _ref13.query,
795
+ token = _ref13.token,
796
+ forceRefresh = _ref13.forceRefresh;
797
+ var service = 'u2c';
798
+ var resource = from ? "/".concat(from, "/catalog") : '/catalog';
799
+ var qs = _objectSpread(_objectSpread({}, query || {}), {}, {
800
+ format: 'hostmap'
801
+ });
802
+ if (forceRefresh) {
803
+ qs.timestamp = new Date().getTime();
804
+ }
805
+ var requestObject = {
806
+ method: 'GET',
807
+ service: service,
808
+ resource: resource,
809
+ qs: qs
810
+ };
811
+ if (token) {
812
+ requestObject.headers = {
813
+ authorization: token
814
+ };
815
+ }
816
+ return this.webex.internal.newMetrics.callDiagnosticLatencies.measureLatency(function () {
817
+ return _this7.request(requestObject);
818
+ }, 'internal.get.u2c.time').then(function (_ref14) {
819
+ var body = _ref14.body;
820
+ return _this7._formatReceivedHostmap(body);
821
+ });
822
+ },
823
+ /**
824
+ * Initialize the discovery services and the whitelisted services.
825
+ *
826
+ * @returns {void}
827
+ */
828
+ initConfig: function initConfig() {
829
+ // Get the catalog and destructure the services config.
830
+ var catalog = this._getCatalog();
831
+ var _this$webex$config = this.webex.config,
832
+ services = _this$webex$config.services,
833
+ fedramp = _this$webex$config.fedramp;
834
+
835
+ // Validate that the services configuration exists.
836
+ if (services) {
837
+ if (fedramp) {
838
+ services.discovery = _serviceFedRamp.default;
839
+ }
840
+ // Check for discovery services.
841
+ if (services.discovery) {
842
+ // Format the discovery configuration into an injectable array.
843
+ var formattedDiscoveryServices = (0, _keys.default)(services.discovery).map(function (key) {
844
+ return {
845
+ name: key,
846
+ defaultUrl: services.discovery[key]
847
+ };
848
+ });
849
+
850
+ // Inject formatted discovery services into services catalog.
851
+ catalog.updateServiceUrls('discovery', formattedDiscoveryServices);
852
+ }
853
+ if (services.override) {
854
+ // Format the override configuration into an injectable array.
855
+ var formattedOverrideServices = (0, _keys.default)(services.override).map(function (key) {
856
+ return {
857
+ name: key,
858
+ defaultUrl: services.override[key]
859
+ };
860
+ });
861
+
862
+ // Inject formatted override services into services catalog.
863
+ catalog.updateServiceUrls('override', formattedOverrideServices);
864
+ }
865
+
866
+ // if not fedramp, append on the commercialAllowedDomains
867
+ if (!fedramp) {
868
+ services.allowedDomains = (0, _lodash.union)(services.allowedDomains, _constants.COMMERCIAL_ALLOWED_DOMAINS);
869
+ }
870
+
871
+ // Check for allowed host domains.
872
+ if (services.allowedDomains) {
873
+ // Store the allowed domains as a property of the catalog.
874
+ catalog.setAllowedDomains(services.allowedDomains);
875
+ }
876
+
877
+ // Set `validateDomains` property to match configuration
878
+ this.validateDomains = services.validateDomains;
879
+ }
880
+ },
881
+ /**
882
+ * Make the initial requests to collect the root catalogs.
883
+ *
884
+ * @returns {Promise<void, Error>} - Errors if the token is unavailable.
885
+ */
886
+ initServiceCatalogs: function initServiceCatalogs() {
887
+ var _this8 = this;
888
+ this.logger.info('services: initializing initial service catalogs');
889
+
890
+ // Destructure the credentials plugin.
891
+ var credentials = this.webex.credentials;
892
+
893
+ // Init a promise chain. Must be done as a Promise.resolve() to allow
894
+ // credentials#getOrgId() to properly throw.
895
+ return _promise.default.resolve()
896
+ // Get the user's OrgId.
897
+ .then(function () {
898
+ return credentials.getOrgId();
899
+ })
900
+ // Begin collecting the preauth/limited catalog.
901
+ .then(function (orgId) {
902
+ return _this8.collectPreauthCatalog({
903
+ orgId: orgId
904
+ });
905
+ }).then(function () {
906
+ // Validate if the token is authorized.
907
+ if (credentials.canAuthorize) {
908
+ // Attempt to collect the postauth catalog.
909
+ return _this8.updateServices().catch(function () {
910
+ _this8.initFailed = true;
911
+ _this8.logger.warn('services: cannot retrieve postauth catalog');
912
+ });
913
+ }
914
+
915
+ // Return a resolved promise for consistent return value.
916
+ return _promise.default.resolve();
917
+ });
918
+ },
919
+ /**
920
+ * Initializer
921
+ *
922
+ * @instance
923
+ * @memberof Services
924
+ * @returns {Services}
925
+ */
926
+ initialize: function initialize() {
927
+ var _this9 = this;
928
+ var catalog = new _serviceCatalog.default();
929
+ this._catalogs.set(this.webex, catalog);
930
+
931
+ // Listen for configuration changes once.
932
+ this.listenToOnce(this.webex, 'change:config', function () {
933
+ _this9.initConfig();
934
+ });
935
+
936
+ // wait for webex instance to be ready before attempting
937
+ // to update the service catalogs
938
+ this.listenToOnce(this.webex, 'ready', function () {
939
+ var supertoken = _this9.webex.credentials.supertoken;
940
+ // Validate if the supertoken exists.
941
+ if (supertoken && supertoken.access_token) {
942
+ _this9.initServiceCatalogs().then(function () {
943
+ catalog.isReady = true;
944
+ }).catch(function (error) {
945
+ _this9.initFailed = true;
946
+ _this9.logger.error("services: failed to init initial services when credentials available, ".concat(error === null || error === void 0 ? void 0 : error.message));
947
+ });
948
+ } else {
949
+ var email = _this9.webex.config.email;
950
+ _this9.collectPreauthCatalog(email ? {
951
+ email: email
952
+ } : undefined).catch(function (error) {
953
+ _this9.initFailed = true;
954
+ _this9.logger.error("services: failed to init initial services when no credentials available, ".concat(error === null || error === void 0 ? void 0 : error.message));
955
+ });
956
+ }
957
+ });
958
+ },
959
+ version: "3.8.0-next.20"
960
+ });
961
+ /* eslint-enable no-underscore-dangle */
962
+ var _default = exports.default = Services;
963
+ //# sourceMappingURL=services-v2.js.map