@webex/webex-core 3.12.0 → 3.13.0

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 (75) hide show
  1. package/.repo-context.json +653 -0
  2. package/.sdd/manifest.json +605 -0
  3. package/AGENTS.md +209 -0
  4. package/README.md +5 -2
  5. package/dist/config.js +45 -0
  6. package/dist/config.js.map +1 -1
  7. package/dist/credentials-config.js +12 -0
  8. package/dist/credentials-config.js.map +1 -1
  9. package/dist/index.js +14 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/interceptors/catalog-url.js +87 -0
  12. package/dist/interceptors/catalog-url.js.map +1 -0
  13. package/dist/interceptors/payload-transformer.js +25 -4
  14. package/dist/interceptors/payload-transformer.js.map +1 -1
  15. package/dist/lib/batcher.js +23 -7
  16. package/dist/lib/batcher.js.map +1 -1
  17. package/dist/lib/credentials/credentials.js +103 -4
  18. package/dist/lib/credentials/credentials.js.map +1 -1
  19. package/dist/lib/credentials/token.js +1 -1
  20. package/dist/lib/domains.js +90 -0
  21. package/dist/lib/domains.js.map +1 -0
  22. package/dist/lib/services/service-catalog.js +108 -18
  23. package/dist/lib/services/service-catalog.js.map +1 -1
  24. package/dist/lib/services/services.js +242 -38
  25. package/dist/lib/services/services.js.map +1 -1
  26. package/dist/lib/services-v2/service-catalog.js +14 -13
  27. package/dist/lib/services-v2/service-catalog.js.map +1 -1
  28. package/dist/lib/services-v2/services-v2.js +255 -42
  29. package/dist/lib/services-v2/services-v2.js.map +1 -1
  30. package/dist/lib/static-asset-loader.js +153 -0
  31. package/dist/lib/static-asset-loader.js.map +1 -0
  32. package/dist/plugins/logger.js +1 -1
  33. package/dist/webex-core.js +11 -3
  34. package/dist/webex-core.js.map +1 -1
  35. package/docs/adr/index.md +32 -0
  36. package/docs/architecture.md +298 -0
  37. package/docs/getting-started.md +96 -0
  38. package/docs/index.md +55 -0
  39. package/docs/specs/README.md +76 -0
  40. package/package.json +13 -13
  41. package/schemas/repo-context.schema.json +796 -0
  42. package/src/config.js +49 -0
  43. package/src/credentials-config.js +13 -0
  44. package/src/docs/README.md +732 -0
  45. package/src/index.js +2 -0
  46. package/src/interceptors/catalog-url.js +66 -0
  47. package/src/interceptors/docs/README.md +658 -0
  48. package/src/interceptors/payload-transformer.js +23 -1
  49. package/src/lib/batcher.js +25 -10
  50. package/src/lib/credentials/credentials.js +93 -3
  51. package/src/lib/credentials/docs/README.md +846 -0
  52. package/src/lib/domains.ts +94 -0
  53. package/src/lib/services/docs/README.md +737 -0
  54. package/src/lib/services/service-catalog.js +112 -16
  55. package/src/lib/services/services.js +220 -22
  56. package/src/lib/services-v2/docs/README.md +751 -0
  57. package/src/lib/services-v2/service-catalog.ts +16 -12
  58. package/src/lib/services-v2/services-v2.ts +234 -24
  59. package/src/lib/static-asset-loader.ts +128 -0
  60. package/src/lib/storage/docs/README.md +646 -0
  61. package/src/webex-core.js +8 -0
  62. package/test/fixtures/activation-email.ts +22 -0
  63. package/test/integration/spec/services/services.js +183 -112
  64. package/test/integration/spec/services-v2/services-v2.js +169 -98
  65. package/test/unit/spec/credentials/credentials.js +247 -3
  66. package/test/unit/spec/interceptors/auth.js +56 -0
  67. package/test/unit/spec/interceptors/catalog-url.js +224 -0
  68. package/test/unit/spec/interceptors/payload-transformer.js +119 -1
  69. package/test/unit/spec/lib/batcher.js +56 -0
  70. package/test/unit/spec/services/service-catalog.js +368 -11
  71. package/test/unit/spec/services/services.js +466 -2
  72. package/test/unit/spec/services-v2/service-catalog.ts +134 -11
  73. package/test/unit/spec/services-v2/services-v2.ts +588 -0
  74. package/test/unit/spec/static-asset-loader.ts +224 -0
  75. package/test/unit/spec/webex-core.js +77 -1
@@ -3,6 +3,8 @@ import AmpState from 'ampersand-state';
3
3
  import {union} from 'lodash';
4
4
  import ServiceDetail from './service-detail';
5
5
  import {IServiceDetail, ServiceGroup} from './types';
6
+ import {matchAllowedDomain, normalizeAllowedDomains} from '../domains';
7
+ import {matchesParsedCatalogUrl, parseCatalogUrl} from '../services/service-catalog';
6
8
 
7
9
  /**
8
10
  * @class
@@ -198,9 +200,17 @@ const ServiceCatalog = AmpState.extend({
198
200
  findServiceDetailFromUrl(url: string): IServiceDetail | undefined {
199
201
  const serviceDetails = this._getAllServiceDetails();
200
202
 
203
+ let candidateUrl: URL;
204
+
205
+ try {
206
+ candidateUrl = new URL(url);
207
+ } catch {
208
+ return undefined;
209
+ }
210
+
201
211
  return serviceDetails.find(({serviceUrls}) => {
202
212
  for (const serviceUrl of serviceUrls) {
203
- if (url.startsWith(serviceUrl.baseUrl)) {
213
+ if (matchesParsedCatalogUrl(candidateUrl, parseCatalogUrl(serviceUrl.baseUrl))) {
204
214
  return true;
205
215
  }
206
216
  }
@@ -210,20 +220,14 @@ const ServiceCatalog = AmpState.extend({
210
220
  },
211
221
 
212
222
  /**
213
- * Finds an allowed domain that matches a specific url.
223
+ * Finds an allowed domain that matches a specific url. The url's hostname
224
+ * must be the allowed domain itself or a subdomain of it.
214
225
  *
215
226
  * @param {string} url - The url to match the allowed domains against.
216
227
  * @returns {string} - The matching allowed domain.
217
228
  */
218
229
  findAllowedDomain(url: string): string {
219
- try {
220
- const urlObj = new URL(url);
221
-
222
- return this.allowedDomains.find((allowedDomain) => urlObj.host.includes(allowedDomain));
223
- } catch {
224
- // If the URL is invalid or can't be found, return undefined
225
- return undefined;
226
- }
230
+ return matchAllowedDomain(url, this.allowedDomains);
227
231
  },
228
232
 
229
233
  /**
@@ -282,7 +286,7 @@ const ServiceCatalog = AmpState.extend({
282
286
  * @returns {void}
283
287
  */
284
288
  setAllowedDomains(allowedDomains: Array<string>): void {
285
- this.allowedDomains = [...allowedDomains];
289
+ this.allowedDomains = normalizeAllowedDomains(allowedDomains);
286
290
  },
287
291
 
288
292
  /**
@@ -291,7 +295,7 @@ const ServiceCatalog = AmpState.extend({
291
295
  * @returns {void}
292
296
  */
293
297
  addAllowedDomains(newAllowedDomains: Array<string>): void {
294
- this.allowedDomains = union(this.allowedDomains, newAllowedDomains);
298
+ this.allowedDomains = union(this.allowedDomains, normalizeAllowedDomains(newAllowedDomains));
295
299
  },
296
300
 
297
301
  /**
@@ -7,6 +7,7 @@ import METRICS from '../metrics';
7
7
  import ServiceCatalog from './service-catalog';
8
8
  import fedRampServices from './service-fed-ramp';
9
9
  import {COMMERCIAL_ALLOWED_DOMAINS} from '../constants';
10
+ import {matchesCatalogUrl} from '../services/service-catalog';
10
11
  import {
11
12
  ActiveServices,
12
13
  IServiceCatalog,
@@ -15,6 +16,7 @@ import {
15
16
  ServiceHostmap,
16
17
  ServiceGroup,
17
18
  ServiceHost,
19
+ ServiceUrl,
18
20
  SelectionMeta,
19
21
  } from './types';
20
22
 
@@ -44,6 +46,22 @@ const Services = WebexPlugin.extend({
44
46
  initFailed: ['boolean', false, false],
45
47
  },
46
48
 
49
+ session: {
50
+ /**
51
+ * Becomes `true` once the initial catalog collection has completed
52
+ * (successfully or otherwise) and any in-flight credentials refresh has
53
+ * settled. Blocks `webex.ready` so consumers can rely on `webex.ready`
54
+ * implying "catalogs populated AND credential state stable".
55
+ * @instance
56
+ * @memberof Services
57
+ * @type {boolean}
58
+ */
59
+ ready: {
60
+ default: false,
61
+ type: 'boolean',
62
+ },
63
+ },
64
+
47
65
  _catalogs: new WeakMap(),
48
66
 
49
67
  _activeServices: {},
@@ -200,13 +218,23 @@ const Services = WebexPlugin.extend({
200
218
  },
201
219
 
202
220
  /**
203
- * Checks if the current environment is an integration (INT) environment
204
- * by examining the u2c discovery URL from webex config.
221
+ * Checks if the current environment is an integration (INT) environment.
222
+ * Uses the explicit environment config when set, otherwise examines the u2c discovery URL.
205
223
  * INT environments use discovery URLs containing 'intb' (e.g., u2c-intb.ciscospark.com).
206
224
  * @returns {boolean} True if INT environment, false otherwise
207
225
  */
208
226
  isIntegrationEnvironment(): boolean {
209
227
  try {
228
+ const configuredEnvironment = this.webex?.config?.environment;
229
+
230
+ if (configuredEnvironment !== undefined) {
231
+ const isIntFromConfig = configuredEnvironment === 'integration';
232
+
233
+ this.logger.info(`services: isIntegrationEnvironment: ${isIntFromConfig} (config)`);
234
+
235
+ return isIntFromConfig;
236
+ }
237
+
210
238
  const u2cUrl = this.webex?.config?.services?.discovery?.u2c || '';
211
239
  const isInt = u2cUrl.includes('intb');
212
240
 
@@ -972,7 +1000,9 @@ const Services = WebexPlugin.extend({
972
1000
 
973
1001
  const priorityUrl = service.get();
974
1002
  const defaultUrl = new URL(
975
- service.serviceUrls.find((serviceUrl) => url.startsWith(serviceUrl.baseUrl)).baseUrl
1003
+ service.serviceUrls.find((serviceUrl: ServiceUrl) =>
1004
+ matchesCatalogUrl(url, serviceUrl.baseUrl)
1005
+ ).baseUrl
976
1006
  ).href;
977
1007
 
978
1008
  return {
@@ -1219,7 +1249,11 @@ const Services = WebexPlugin.extend({
1219
1249
  ): Promise<object> {
1220
1250
  const service = 'u2c';
1221
1251
  const resource = from ? `/${from}/catalog` : '/catalog';
1222
- const qs = {...(query || {}), format: 'U2CV2'};
1252
+ const qs = {
1253
+ ...(query || {}),
1254
+ format: 'U2CV2',
1255
+ ...(this.webex.config?.services?.useCatalogOverride && {useCatalogOverride: true}),
1256
+ };
1223
1257
 
1224
1258
  if (forceRefresh) {
1225
1259
  qs.timestamp = new Date().getTime();
@@ -1237,9 +1271,16 @@ const Services = WebexPlugin.extend({
1237
1271
  requestObject.headers = {authorization: token};
1238
1272
  }
1239
1273
 
1240
- return this.webex.internal.newMetrics.callDiagnosticLatencies
1241
- .measureLatency(() => this.request(requestObject), 'internal.get.u2c.time')
1242
- .then(({body}) => this._formatReceivedHostmap(body || {}));
1274
+ const sendRequest = () => this.request(requestObject);
1275
+
1276
+ const responsePromise = this.webex.internal.newMetrics
1277
+ ? this.webex.internal.newMetrics.callDiagnosticLatencies.measureLatency(
1278
+ sendRequest,
1279
+ 'internal.get.u2c.time'
1280
+ )
1281
+ : sendRequest();
1282
+
1283
+ return responsePromise.then(({body}) => this._formatReceivedHostmap(body || {}));
1243
1284
  },
1244
1285
 
1245
1286
  /**
@@ -1255,7 +1296,10 @@ const Services = WebexPlugin.extend({
1255
1296
  // Validate that the services configuration exists.
1256
1297
  if (services) {
1257
1298
  if (fedramp) {
1258
- services.discovery = fedRampServices;
1299
+ services.discovery = {
1300
+ ...fedRampServices,
1301
+ u2c: services.discovery?.u2c || fedRampServices.u2c,
1302
+ };
1259
1303
  }
1260
1304
  // Check for discovery services.
1261
1305
  if (services.discovery) {
@@ -1312,6 +1356,7 @@ const Services = WebexPlugin.extend({
1312
1356
 
1313
1357
  // Destructure the credentials plugin.
1314
1358
  const {credentials} = this.webex;
1359
+ const catalog = this._getCatalog();
1315
1360
 
1316
1361
  // Init a promise chain. Must be done as a Promise.resolve() to allow
1317
1362
  // credentials#getOrgId() to properly throw.
@@ -1324,11 +1369,18 @@ const Services = WebexPlugin.extend({
1324
1369
  .then(() => {
1325
1370
  // Validate if the token is authorized.
1326
1371
  if (credentials.canAuthorize) {
1327
- // Attempt to collect the postauth catalog.
1328
- return this.updateServices({forceRefresh: refresh}).catch(() => {
1329
- this.initFailed = true;
1330
- this.logger.warn('services: cannot retrieve postauth catalog');
1331
- });
1372
+ // Attempt to collect the postauth catalog, then mark the catalog
1373
+ // ready. Setting `isReady` here - rather than only in the init
1374
+ // callers - means a slow postauth fetch that loses the gated-init
1375
+ // timeout race still marks the catalog ready once it completes.
1376
+ return this.updateServices({forceRefresh: refresh})
1377
+ .then(() => {
1378
+ catalog.isReady = true;
1379
+ })
1380
+ .catch(() => {
1381
+ this.initFailed = true;
1382
+ this.logger.warn('services: cannot retrieve postauth catalog');
1383
+ });
1332
1384
  }
1333
1385
 
1334
1386
  // Return a resolved promise for consistent return value.
@@ -1337,6 +1389,51 @@ const Services = WebexPlugin.extend({
1337
1389
  );
1338
1390
  },
1339
1391
 
1392
+ /**
1393
+ * Await any in-flight credentials refresh, then flip `services.ready` so
1394
+ * `webex.ready` can fire. Closes the parallel-refresh window: if a credential
1395
+ * refresh is in flight when initial catalog collection settles, we must not
1396
+ * signal ready until the refresh has resolved - otherwise downstream
1397
+ * consumers may observe `canAuthorize`/token state that is about to change
1398
+ * under them.
1399
+ *
1400
+ * @private
1401
+ * @returns {Promise<void>}
1402
+ */
1403
+ async _finalizeReady(): Promise<void> {
1404
+ const {credentials} = this.webex;
1405
+
1406
+ if (credentials && credentials.isRefreshing) {
1407
+ await new Promise<void>((resolve) => {
1408
+ credentials.once('change:isRefreshing', resolve);
1409
+ });
1410
+ }
1411
+
1412
+ this.ready = true;
1413
+ },
1414
+
1415
+ /**
1416
+ * Build a promise that rejects once the catalog init timeout elapses. Race
1417
+ * this against catalog collection so a hung request never leaves
1418
+ * `services.ready` false forever - that would stall `webex.ready` and leave
1419
+ * consumers waiting on it indefinitely. Timeout is configurable via
1420
+ * `config.services.catalogInitTimeout` (defaults to 15s in config). Created
1421
+ * lazily so paths that skip catalog collection never schedule a stray timer.
1422
+ *
1423
+ * @private
1424
+ * @returns {Promise<never>}
1425
+ */
1426
+ _makeInitTimeout(): Promise<never> {
1427
+ const initTimeoutMs = this.webex.config?.services?.catalogInitTimeout;
1428
+
1429
+ return new Promise<never>((_, reject) => {
1430
+ setTimeout(
1431
+ () => reject(new Error(`services: init timed out after ${initTimeoutMs}ms`)),
1432
+ initTimeoutMs
1433
+ );
1434
+ });
1435
+ },
1436
+
1340
1437
  /**
1341
1438
  * Initializer
1342
1439
  *
@@ -1348,11 +1445,39 @@ const Services = WebexPlugin.extend({
1348
1445
  const catalog = new ServiceCatalog();
1349
1446
  this._catalogs.set(this.webex, catalog);
1350
1447
 
1351
- // Listen for configuration changes once.
1448
+ // Listen for configuration changes once. The config is not populated on the
1449
+ // webex instance until the `change:config` event fires, so any decision that
1450
+ // depends on config values (such as the gated-vs-ungated init below) must be
1451
+ // made from within this handler rather than synchronously in `initialize()`.
1352
1452
  this.listenToOnce(this.webex, 'change:config', () => {
1353
1453
  this.initConfig();
1454
+
1455
+ // Feature flag: when enabled, `webex.ready` is blocked until the initial
1456
+ // catalog collection has settled AND any in-flight credentials refresh has
1457
+ // completed. When disabled (the default), preserves the pre-existing
1458
+ // behavior where `webex.ready` fires as soon as `webex.loaded` does and
1459
+ // the catalog is collected out-of-band.
1460
+ const waitForCatalogInit = this.webex.config?.services?.waitForCatalogInit === true;
1461
+
1462
+ if (waitForCatalogInit) {
1463
+ this._initializeCatalogsGated(catalog);
1464
+ } else {
1465
+ // Not gating - immediately mark ready so we do not block webex.ready.
1466
+ this.ready = true;
1467
+ this._initializeCatalogsUngated(catalog);
1468
+ }
1354
1469
  });
1470
+ },
1355
1471
 
1472
+ /**
1473
+ * Original (pre-verified-ready) initialization path. Runs on `webex.ready`
1474
+ * and collects catalogs opportunistically without blocking anything.
1475
+ *
1476
+ * @private
1477
+ * @param {ServiceCatalog} catalog
1478
+ * @returns {void}
1479
+ */
1480
+ _initializeCatalogsUngated(catalog: ServiceCatalog): void {
1356
1481
  // wait for webex instance to be ready before attempting
1357
1482
  // to update the service catalogs
1358
1483
  this.listenToOnce(this.webex, 'ready', async () => {
@@ -1365,19 +1490,25 @@ const Services = WebexPlugin.extend({
1365
1490
  const {supertoken} = this.webex.credentials;
1366
1491
  // Validate if the supertoken exists.
1367
1492
  if (supertoken && supertoken.access_token) {
1368
- this.initServiceCatalogs()
1369
- .then(() => {
1370
- catalog.isReady = true;
1371
- })
1372
- .catch((error) => {
1373
- this.initFailed = true;
1374
- this.logger.error(
1375
- `services: failed to init initial services when credentials available, ${error?.message}`
1376
- );
1377
- });
1493
+ // `initServiceCatalogs` marks the catalog ready internally once the
1494
+ // postauth catalog is collected.
1495
+ this.initServiceCatalogs().catch((error) => {
1496
+ this.initFailed = true;
1497
+ this.logger.error(
1498
+ `services: failed to init initial services when credentials available, ${error?.message}`
1499
+ );
1500
+ });
1378
1501
  } else {
1379
1502
  const {email} = this.webex.config;
1380
1503
 
1504
+ if (this.webex.config?.services?.skipPreauthCatalogOnUnauthenticated === true) {
1505
+ this.logger.info(
1506
+ 'services: skipping preauth catalog collection while unauthenticated as per the config'
1507
+ );
1508
+
1509
+ return;
1510
+ }
1511
+
1381
1512
  this.collectPreauthCatalog(email ? {email} : undefined).catch((error) => {
1382
1513
  this.initFailed = true;
1383
1514
  this.logger.error(
@@ -1387,6 +1518,85 @@ const Services = WebexPlugin.extend({
1387
1518
  }
1388
1519
  });
1389
1520
  },
1521
+
1522
+ /**
1523
+ * Verified-ready initialization path. Blocks `webex.ready` until the initial
1524
+ * catalog fetch has settled (or timed out) AND any in-flight credentials
1525
+ * refresh has completed. Also handles the fresh-login case where OAuth
1526
+ * completes after `loaded` fires.
1527
+ *
1528
+ * @private
1529
+ * @param {ServiceCatalog} catalog
1530
+ * @returns {void}
1531
+ */
1532
+ _initializeCatalogsGated(catalog: ServiceCatalog): void {
1533
+ // Wait for storage to be loaded before attempting to update the service
1534
+ // catalogs. We listen for 'loaded' instead of 'ready' because `services.ready`
1535
+ // now blocks `webex.ready` - listening to 'ready' would deadlock.
1536
+ this.listenToOnce(this.webex, 'loaded', async () => {
1537
+ const warmed = await this._loadCatalogFromCache();
1538
+ if (warmed) {
1539
+ catalog.isReady = true;
1540
+ await this._finalizeReady();
1541
+
1542
+ return;
1543
+ }
1544
+ const {supertoken} = this.webex.credentials;
1545
+
1546
+ // Validate if the supertoken exists.
1547
+ if (supertoken && supertoken.access_token) {
1548
+ // `initServiceCatalogs` marks the catalog ready internally once the
1549
+ // postauth catalog is collected - even if it loses the timeout race
1550
+ // below, so a slow fetch still eventually flips `catalog.isReady`.
1551
+ Promise.race([this.initServiceCatalogs(), this._makeInitTimeout()])
1552
+ .catch((error) => {
1553
+ this.initFailed = true;
1554
+ this.logger.error(
1555
+ `services: failed to init initial services when credentials available, ${error?.message}`
1556
+ );
1557
+ })
1558
+ .finally(() => this._finalizeReady());
1559
+ } else {
1560
+ const {email} = this.webex.config;
1561
+
1562
+ // Handle fresh login: 'loaded' fires before OAuth completes, so listen
1563
+ // for `canAuthorize` flipping true and then collect the postauth catalog.
1564
+ this.listenToOnce(this.webex, 'change:canAuthorize', () => {
1565
+ if (this.webex.canAuthorize && !catalog.status.postauth.ready) {
1566
+ // `initServiceCatalogs` marks the catalog ready internally.
1567
+ this.initServiceCatalogs().catch((error) => {
1568
+ this.logger.error(
1569
+ `services: failed to init service catalogs after auth, ${error?.message}`
1570
+ );
1571
+ });
1572
+ }
1573
+ });
1574
+
1575
+ if (this.webex.config?.services?.skipPreauthCatalogOnUnauthenticated === true) {
1576
+ // Skip the preauth catalog fetch (it will be collected manually
1577
+ // later), but still finalize `services.ready` so `webex.ready` is not
1578
+ // stalled while unauthenticated. No timeout is created here so there
1579
+ // is no stray timer or unhandled rejection.
1580
+ this.logger.info(
1581
+ 'services: skipping preauth catalog collection while unauthenticated as per the config'
1582
+ );
1583
+ this._finalizeReady();
1584
+ } else {
1585
+ Promise.race([
1586
+ this.collectPreauthCatalog(email ? {email} : undefined),
1587
+ this._makeInitTimeout(),
1588
+ ])
1589
+ .catch((error) => {
1590
+ this.initFailed = true;
1591
+ this.logger.error(
1592
+ `services: failed to init initial services when no credentials available, ${error?.message}`
1593
+ );
1594
+ })
1595
+ .finally(() => this._finalizeReady());
1596
+ }
1597
+ }
1598
+ });
1599
+ },
1390
1600
  });
1391
1601
  /* eslint-enable no-underscore-dangle */
1392
1602
 
@@ -0,0 +1,128 @@
1
+ /*!
2
+ * Copyright (c) 2015-2026 Cisco Systems, Inc. See LICENSE file.
3
+ */
4
+
5
+ // @ts-ignore
6
+ import StatelessWebexPlugin from './stateless-webex-plugin';
7
+
8
+ /**
9
+ * Detects an HTML document prefix in an otherwise successful binary asset response.
10
+ * @param {ArrayBuffer} buffer
11
+ * @returns {boolean}
12
+ */
13
+ function looksLikeHtmlDocument(buffer: ArrayBuffer): boolean {
14
+ const prefix = new TextDecoder().decode(buffer.slice(0, 256)).trimStart();
15
+
16
+ return prefix.startsWith('<');
17
+ }
18
+
19
+ /**
20
+ * Resolves and downloads static assets for SDK plugins. Requests are shared between callers and
21
+ * cached after a successful response.
22
+ *
23
+ * IMPORTANT: When adding assets, ensure that their names are unique and versioned to avoid caching issues.
24
+ * Example: 'e2ee-0.0.1.wasm' instead of 'e2ee.wasm'
25
+ * or use content-based hashing in the filename to ensure uniqueness.
26
+ */
27
+ export default class StaticAssetLoader extends StatelessWebexPlugin {
28
+ private readonly baseUrl: string;
29
+
30
+ private readonly assets = new Map<string, Promise<ArrayBuffer>>();
31
+
32
+ /**
33
+ * @param {Object} attrs
34
+ * @param {string} attrs.baseUrl - Base URL for the plugin's static assets.
35
+ * @param {Object} options
36
+ * @param {Object} [options.parent] - The parent Webex SDK instance.
37
+ */
38
+ constructor(attrs: {baseUrl: string}, options: {parent?: any} = {}) {
39
+ super(attrs, options);
40
+ this.baseUrl = attrs.baseUrl.replace(/\/+$/, ''); // remove trailing slashes
41
+ }
42
+
43
+ /**
44
+ * Returns the URL for an asset in the configured asset directory.
45
+ * @param {string} assetName
46
+ * @returns {string}
47
+ */
48
+ getUrl(assetName: string): string {
49
+ return `${this.baseUrl}/${assetName.replace(/^\/+/, '')}`; // regex removes leading slashes from the asset name
50
+ }
51
+
52
+ /**
53
+ * Downloads an asset as bytes. Failed requests are evicted so a later call can retry.
54
+ * @param {string} assetName
55
+ * @returns {Promise<Uint8Array>}
56
+ */
57
+ async getBytes(assetName: string): Promise<Uint8Array> {
58
+ const url = this.getUrl(assetName);
59
+ let asset = this.assets.get(url);
60
+
61
+ if (!asset) {
62
+ // @ts-ignore - StatelessWebexPlugin exposes request from the parent Webex instance.
63
+ asset = this.request({
64
+ method: 'GET',
65
+ uri: url,
66
+ responseType: 'buffer',
67
+ // Assets may be hosted on a third-party CDN: never send the user's token, and suppress
68
+ // the SDK's custom headers so the request doesn't trigger a CORS preflight.
69
+ addAuthHeader: false,
70
+ headers: {
71
+ trackingid: null,
72
+ 'spark-user-agent': null,
73
+ 'cisco-no-http-redirect': null,
74
+ },
75
+ })
76
+ .then((response: any) => {
77
+ if (response.statusCode < 200 || response.statusCode >= 300) {
78
+ throw new Error(`Failed to fetch static asset ${url}: HTTP ${response.statusCode}`);
79
+ }
80
+
81
+ const contentType = response.headers?.['content-type']
82
+ ?.split(';')[0]
83
+ .trim()
84
+ .toLowerCase();
85
+
86
+ if (contentType === 'text/html' || contentType === 'application/xhtml+xml') {
87
+ throw new Error(
88
+ `Failed to fetch static asset ${url}: unexpected HTML content type "${contentType}"`
89
+ );
90
+ }
91
+
92
+ const responseBody = response.body;
93
+ let buffer: ArrayBuffer;
94
+
95
+ if (responseBody instanceof ArrayBuffer) {
96
+ buffer = responseBody;
97
+ } else if (ArrayBuffer.isView(responseBody)) {
98
+ buffer = responseBody.buffer.slice(
99
+ responseBody.byteOffset,
100
+ responseBody.byteOffset + responseBody.byteLength
101
+ ) as ArrayBuffer;
102
+ } else {
103
+ throw new Error(
104
+ `Failed to fetch static asset ${url}: response body is not binary data`
105
+ );
106
+ }
107
+
108
+ // Some static servers return an HTML fallback page with a successful status and a
109
+ // generic binary content type. Reject it before callers pass those bytes to modules
110
+ // that expect binary data, such as WASM.
111
+ if (looksLikeHtmlDocument(buffer)) {
112
+ throw new Error(
113
+ `Failed to fetch static asset ${url}: response body looks like an HTML document`
114
+ );
115
+ }
116
+
117
+ return buffer;
118
+ })
119
+ .catch((error: Error) => {
120
+ this.assets.delete(url);
121
+ throw error;
122
+ });
123
+ this.assets.set(url, asset);
124
+ }
125
+
126
+ return new Uint8Array((await asset).slice(0));
127
+ }
128
+ }