@elliemae/ssf-host 2.25.3 → 2.25.5

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/esm/host.js CHANGED
@@ -25,6 +25,14 @@ const SANDBOX_DEFAULT = [
25
25
  IFrameSandboxValues.AllowDownloads,
26
26
  IFrameSandboxValues.AllowSameOrigin
27
27
  ];
28
+ const MODULE_OBJECT_ID = "module";
29
+ const MODULE_UNLOADING_EVENT = "module.unloading";
30
+ const MODULE_UNMOUNT_EVENT = "module.unmount";
31
+ const MODULE_EVENT_TIMEOUT_MS = 1e3;
32
+ const MODULE_EVENT_STUB = new ScriptingObject(MODULE_OBJECT_ID);
33
+ const isModuleUnloadVetoed = (feedback) => Array.isArray(feedback) && feedback.some((v) => v === false);
34
+ const ignoreRejectedPromise = () => {
35
+ };
28
36
  class SSFHost {
29
37
  /* eslint-enable indent */
30
38
  /**
@@ -147,7 +155,7 @@ class SSFHost {
147
155
  };
148
156
  #closeAllPopupGuests = () => {
149
157
  const popupIds = Array.from(this.#guests.values()).filter((guest) => guest.openMode === OpenMode.Popup).map((guest) => guest.id);
150
- popupIds.forEach((id) => this.unloadGuest(id));
158
+ popupIds.forEach((id) => this.#unloadGuestInBackground(id));
151
159
  };
152
160
  /**
153
161
  * get the reference to the guest application by its window
@@ -320,7 +328,7 @@ class SSFHost {
320
328
  if (sourceWin?.window) {
321
329
  const guest = this.#findGuest(sourceWin);
322
330
  if (guest && !await guest.handShake()) {
323
- this.unloadGuest(sourceWin);
331
+ this.#unloadGuestInBackground(sourceWin);
324
332
  }
325
333
  }
326
334
  };
@@ -693,7 +701,7 @@ class SSFHost {
693
701
  });
694
702
  guestsToRemove.forEach((guest) => {
695
703
  const { id } = guest;
696
- this.unloadGuest(id);
704
+ this.#unloadGuestInBackground(id);
697
705
  const callbacks = this.#guestCloseCallbackList.get(id);
698
706
  callbacks?.forEach((callback) => {
699
707
  Promise.resolve(callback({ id })).catch(() => {
@@ -1012,6 +1020,10 @@ class SSFHost {
1012
1020
  this.#guests.forEach(tryDispatch);
1013
1021
  }
1014
1022
  };
1023
+ #resolveEventSourceObject = (objectId, targetGuest) => {
1024
+ const scriptingObject = targetGuest ? this.getScriptingObject(objectId, { guest: targetGuest }) : this.getScriptingObject(objectId);
1025
+ return scriptingObject ?? (objectId === MODULE_OBJECT_ID && targetGuest ? MODULE_EVENT_STUB : null);
1026
+ };
1015
1027
  /**
1016
1028
  * dispatch event to guest application(s)
1017
1029
  * @param {EventDetail} params details of the event to be dispatched
@@ -1033,8 +1045,11 @@ class SSFHost {
1033
1045
  const objectId = id.split(".")[0];
1034
1046
  const guestIdorWnd = guestId || targetWindow;
1035
1047
  const targetGuest = guestIdorWnd ? this.#findGuest(guestIdorWnd) : null;
1036
- const scriptingObject = targetGuest ? this.getScriptingObject(objectId, { guest: targetGuest }) : this.getScriptingObject(objectId);
1037
- if (!scriptingObject) {
1048
+ const eventSourceObject = this.#resolveEventSourceObject(
1049
+ objectId,
1050
+ targetGuest ?? null
1051
+ );
1052
+ if (!eventSourceObject) {
1038
1053
  this.#logger.warn(
1039
1054
  `Attempt to dispatch event ${name} on unknown object ${objectId}`
1040
1055
  );
@@ -1042,7 +1057,7 @@ class SSFHost {
1042
1057
  }
1043
1058
  const eventObj = {
1044
1059
  // eslint-disable-next-line no-underscore-dangle
1045
- object: scriptingObject._toJSON(),
1060
+ object: eventSourceObject._toJSON(),
1046
1061
  eventName: name,
1047
1062
  eventParams,
1048
1063
  eventHandler,
@@ -1064,7 +1079,7 @@ class SSFHost {
1064
1079
  guestPromises.push(guest.dispatchEvent(eventObj, timeout));
1065
1080
  if (!eventTimingToken && this.#perfTracker.enabled) {
1066
1081
  eventTimingToken = this.#perfTracker.start(
1067
- `ScriptingObject.Event.${scriptingObject.id}.${name}`,
1082
+ `ScriptingObject.Event.${eventSourceObject.id}.${name}`,
1068
1083
  { appId: this.hostId, appUrl: window.location.href }
1069
1084
  );
1070
1085
  }
@@ -1237,32 +1252,819 @@ class SSFHost {
1237
1252
  this.#guests.forEach(this.#dispatchConfigEvent);
1238
1253
  this.#logger.debug("Dispatched config events to all guests");
1239
1254
  };
1255
+ #dispatchGuestModuleEvent = async (guest, eventId, eventName) => (
1256
+ /* eslint-disable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any */
1257
+ this.dispatchEvent({
1258
+ event: { id: eventId, name: eventName },
1259
+ eventParams: { moduleId: guest.id },
1260
+ eventOptions: {
1261
+ timeout: MODULE_EVENT_TIMEOUT_MS,
1262
+ guestId: guest.id
1263
+ }
1264
+ })
1265
+ );
1266
+ /* eslint-enable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any */
1267
+ #canUnloadGuest = async (guest) => {
1268
+ try {
1269
+ const feedback = await this.#dispatchGuestModuleEvent(
1270
+ guest,
1271
+ MODULE_UNLOADING_EVENT,
1272
+ "unloading"
1273
+ );
1274
+ if (isModuleUnloadVetoed(feedback)) {
1275
+ this.#logger.info(
1276
+ `Unload denied by guest ${guest.id} via module.unloading event`
1277
+ );
1278
+ return false;
1279
+ }
1280
+ } catch (err) {
1281
+ this.#logger.warn({
1282
+ message: `Error dispatching module.unloading event for ${guest.id}; proceeding with unload`,
1283
+ exception: err
1284
+ });
1285
+ }
1286
+ return true;
1287
+ };
1288
+ /**
1289
+ * Signal SDK teardown after the module.unloading veto phase passes.
1290
+ * @param guest
1291
+ */
1292
+ #dispatchModuleUnmount = async (guest) => {
1293
+ try {
1294
+ await this.#dispatchGuestModuleEvent(
1295
+ guest,
1296
+ MODULE_UNMOUNT_EVENT,
1297
+ "unmount"
1298
+ );
1299
+ } catch (err) {
1300
+ this.#logger.warn({
1301
+ message: `Error dispatching module.unmount event for ${guest.id}`,
1302
+ exception: err
1303
+ });
1304
+ }
1305
+ };
1306
+ #unloadGuestInBackground = (guestIdOrWindowOrEle) => {
1307
+ this.unloadGuest(guestIdOrWindowOrEle).catch(ignoreRejectedPromise);
1308
+ };
1240
1309
  /**
1241
1310
  * unloads guest application from host
1242
1311
  * @param guestIdOrWindowOrEle unique id of the guest application or window object or dom element of the guest application
1243
1312
  * @throws Error if guestId or Window reference is invalid
1244
1313
  */
1245
- unloadGuest = (guestIdOrWindowOrEle) => {
1314
+ unloadGuest = async (guestIdOrWindowOrEle) => {
1246
1315
  const guest = this.#findGuest(guestIdOrWindowOrEle);
1247
- if (guest) {
1248
- guest.dispose();
1249
- this.#guestsByWindow.delete(guest.window);
1250
- this.#guestsByUrl.delete(guest.url);
1251
- this.#guestMetadata.delete(guest.id);
1252
- this.#guests.delete(guest.id);
1253
- this.#logger.audit({
1254
- message: `Guest is removed from host`,
1255
- ...guest.getInfo()
1256
- });
1257
- this.#stopMonitoringPopupGuests();
1316
+ if (!guest) return;
1317
+ const windowAlreadyClosed = Boolean(guest.window?.closed);
1318
+ if (!windowAlreadyClosed) {
1319
+ if (!await this.#canUnloadGuest(guest)) return;
1320
+ await this.#dispatchModuleUnmount(guest);
1258
1321
  }
1322
+ guest.dispose();
1323
+ this.#guestsByWindow.delete(guest.window);
1324
+ this.#guestsByUrl.delete(guest.url);
1325
+ this.#guestMetadata.delete(guest.id);
1326
+ this.#guests.delete(guest.id);
1327
+ this.#logger.audit({
1328
+ message: `Guest is removed from host`,
1329
+ ...guest.getInfo()
1330
+ });
1331
+ this.#stopMonitoringPopupGuests();
1259
1332
  };
1260
- /**
1261
- * monitors guest window close action and executes the callback from host.
1262
- * @param callback host callback method
1263
- * @param id unique id of the guest application
1264
- * @param param
1265
- */
1333
+ // 2.25.x full-cleanup unload path (disabled for PUI-18792 backport)
1334
+ // /**
1335
+ // * Call cleanup function on guest window.emui
1336
+ // * @param {object} options - Cleanup options
1337
+ // * @param {any} options.guestEmui - The window.emui object
1338
+ // * @param {string} options.cleanupFunctionName - Function name to call
1339
+ // * @param {string} options.context - Context for logging
1340
+ // */
1341
+ // #callGuestCleanupFunction = (options: {
1342
+ // guestEmui: any;
1343
+ // cleanupFunctionName: string;
1344
+ // context: string;
1345
+ // }): void => {
1346
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1347
+ // const { guestEmui, cleanupFunctionName, context } = options;
1348
+ // const emuiObj: Record<string, unknown> = guestEmui as Record<
1349
+ // string,
1350
+ // unknown
1351
+ // >;
1352
+ // const cleanupFn = emuiObj[cleanupFunctionName];
1353
+ //
1354
+ // if (typeof cleanupFn !== 'function') {
1355
+ // return;
1356
+ // }
1357
+ //
1358
+ // try {
1359
+ // (cleanupFn as () => void)();
1360
+ // this.#logger.debug(
1361
+ // `[SSF] Called window.emui.${String(cleanupFunctionName)}() for ${String(
1362
+ // context,
1363
+ // )}`,
1364
+ // );
1365
+ // } catch (e) {
1366
+ // this.#logger.warn(
1367
+ // `[SSF] emui.${String(cleanupFunctionName)}() threw error for ${String(
1368
+ // context,
1369
+ // )}: ${(e as Error).message}`,
1370
+ // );
1371
+ // } finally {
1372
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1373
+ // guestEmui[cleanupFunctionName] = null;
1374
+ // }
1375
+ // };
1376
+ //
1377
+ // /**
1378
+ // * Null window.emui.app properties
1379
+ // * @param {Record<string, unknown> | unknown} app - The window.emui.app object
1380
+ // */
1381
+ // #nullAppProperties = (app: Record<string, unknown> | unknown): void => {
1382
+ // if (typeof app !== 'object' || app === null) {
1383
+ // return;
1384
+ // }
1385
+ //
1386
+ // const appObj = app as Record<string, unknown>;
1387
+ // appObj.init = null;
1388
+ // appObj.mount = null;
1389
+ // appObj.unmount = null;
1390
+ // appObj.getRef = null;
1391
+ // appObj.navigate = null;
1392
+ // };
1393
+ //
1394
+ // /**
1395
+ // * Null all window.emui properties
1396
+ // * @param {Record<string, unknown> | unknown} guestEmui - The window.emui object
1397
+ // */
1398
+ // #nullEmuiProperties = (
1399
+ // guestEmui: Record<string, unknown> | unknown,
1400
+ // ): void => {
1401
+ // if (typeof guestEmui !== 'object' || guestEmui === null) {
1402
+ // return;
1403
+ // }
1404
+ //
1405
+ // const emuiObj = guestEmui as Record<string, unknown>;
1406
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1407
+ // if (emuiObj.app) {
1408
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument
1409
+ // this.#nullAppProperties(emuiObj.app);
1410
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1411
+ // emuiObj.app = null;
1412
+ // }
1413
+ //
1414
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1415
+ // emuiObj.registerApp = null;
1416
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1417
+ // emuiObj.logRocket = null;
1418
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1419
+ // emuiObj.getEnvironment = null;
1420
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1421
+ // emuiObj.loadScript = null;
1422
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1423
+ // emuiObj.loadStylesheet = null;
1424
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1425
+ // emuiObj.unmount = null;
1426
+ // };
1427
+ //
1428
+ // /**
1429
+ // * Disconnect FieldMutation observer for iframe
1430
+ // * @param {Window | null} contentWindow - The iframe contentWindow
1431
+ // * @param {string} guestId - Guest ID for logging
1432
+ // */
1433
+ // #disconnectFieldMutationObserver = (
1434
+ // contentWindow: Window | null,
1435
+ // guestId: string,
1436
+ // ): void => {
1437
+ // try {
1438
+ // const bodyElement = contentWindow?.document?.body;
1439
+ // if (!bodyElement) return;
1440
+ //
1441
+ // const { observerReferences } = window as unknown as {
1442
+ // observerReferences?: Map<unknown, unknown>;
1443
+ // };
1444
+ // if (!observerReferences || !(observerReferences instanceof Map)) {
1445
+ // return;
1446
+ // }
1447
+ //
1448
+ // if (!observerReferences.has(bodyElement)) return;
1449
+ //
1450
+ // const observer = observerReferences.get(bodyElement) as
1451
+ // | { disconnect?: () => void }
1452
+ // | undefined;
1453
+ // if (observer && typeof observer.disconnect === 'function') {
1454
+ // observer.disconnect();
1455
+ // observerReferences.delete(bodyElement);
1456
+ // this.#logger.debug(
1457
+ // `[SSF] Disconnected FieldMutation observer for guest ${guestId}`,
1458
+ // );
1459
+ // }
1460
+ // } catch (e) {
1461
+ // this.#logger.debug(
1462
+ // `[SSF] Failed to disconnect FieldMutation observer for guest ${guestId}: ${
1463
+ // (e as Error).message
1464
+ // }`,
1465
+ // );
1466
+ // }
1467
+ // };
1468
+ //
1469
+ // /**
1470
+ // * Close contentWindow explicitly
1471
+ // * @param {Window | null} contentWindow - The iframe contentWindow
1472
+ // * @param {string} guestId - Guest ID for logging
1473
+ // */
1474
+ // #closeContentWindow = (
1475
+ // contentWindow: Window | null,
1476
+ // guestId: string,
1477
+ // ): void => {
1478
+ // try {
1479
+ // if (!contentWindow || contentWindow.closed) return;
1480
+ //
1481
+ // contentWindow.close();
1482
+ // this.#logger.debug(
1483
+ // `[SSF] Called contentWindow.close() for guest ${guestId}`,
1484
+ // );
1485
+ // } catch (e) {
1486
+ // this.#logger.debug(
1487
+ // `[SSF] contentWindow.close() failed for guest ${guestId}: ${
1488
+ // (e as Error).message
1489
+ // }`,
1490
+ // );
1491
+ // }
1492
+ // };
1493
+ //
1494
+ // /**
1495
+ // * Navigate iframe to about:blank
1496
+ // * @param {HTMLIFrameElement} iframe - The iframe element
1497
+ // * @param {string} guestId - Guest ID for logging
1498
+ // */
1499
+ // #navigateToBlank = (iframe: HTMLIFrameElement, guestId: string): void => {
1500
+ // try {
1501
+ // if (!iframe.parentNode) return;
1502
+ //
1503
+ // iframe.src = 'about:blank';
1504
+ // this.#logger.debug(`[SSF] Navigated to about:blank for guest ${guestId}`);
1505
+ // } catch (e) {
1506
+ // this.#logger.debug(
1507
+ // `[SSF] Navigation to about:blank failed for guest ${guestId}: ${
1508
+ // (e as Error).message
1509
+ // }`,
1510
+ // );
1511
+ // }
1512
+ // };
1513
+ //
1514
+ // /**
1515
+ // * Cleanup window.elli.script properties
1516
+ // * @param {Window} guestWindow - Guest window
1517
+ // * @param {string} context - Context string for logging
1518
+ // */
1519
+ // #cleanupElliScript = (guestWindow: Window, context: string): void => {
1520
+ // try {
1521
+ // const windowWithElli = guestWindow as Window & {
1522
+ // elli?: Record<string, unknown> & {
1523
+ // script?: Record<string, unknown> | null;
1524
+ // };
1525
+ // };
1526
+ // const { elli } = windowWithElli;
1527
+ // if (elli?.script && typeof elli.script === 'object') {
1528
+ // const { script } = elli;
1529
+ // if (script && script.guest && typeof script.guest === 'object') {
1530
+ // const { guest } = script;
1531
+ // const guestObj = guest as Record<string, unknown>;
1532
+ // guestObj.create = null;
1533
+ // }
1534
+ // if (script) {
1535
+ // script.guest = null;
1536
+ // script.connect = null;
1537
+ // script.getObject = null;
1538
+ // script.setLogLevel = null;
1539
+ // script.subscribe = null;
1540
+ // script.unsubscribe = null;
1541
+ // elli.script = null;
1542
+ // }
1543
+ // this.#logger.debug(
1544
+ // `[SSF] Nulled all window.elli.script properties for ${context}`,
1545
+ // );
1546
+ // }
1547
+ // } catch (e) {
1548
+ // this.#logger.debug(
1549
+ // `[SSF] Failed to cleanup window.elli: ${(e as Error).message}`,
1550
+ // );
1551
+ // }
1552
+ // };
1553
+ //
1554
+ // /**
1555
+ // * Clear Google Tag Manager data layer
1556
+ // * @param {Window} guestWindow - Guest window
1557
+ // * @param {string} context - Context string for logging
1558
+ // */
1559
+ // #clearGtmDataLayer = (guestWindow: Window, context: string): void => {
1560
+ // try {
1561
+ // const windowWithGtm = guestWindow as Window & {
1562
+ // gtmDataLayer?: unknown;
1563
+ // };
1564
+ // if (windowWithGtm.gtmDataLayer) {
1565
+ // windowWithGtm.gtmDataLayer = null;
1566
+ // this.#logger.debug(`[SSF] Cleared gtmDataLayer for ${context}`);
1567
+ // }
1568
+ // } catch (e) {
1569
+ // this.#logger.debug(
1570
+ // `[SSF] Failed to cleanup GTM data layer: ${(e as Error).message}`,
1571
+ // );
1572
+ // }
1573
+ // };
1574
+ //
1575
+ // /**
1576
+ // * Cleanup window.emui properties
1577
+ // * @param {unknown} guestEmui - Guest window.emui object
1578
+ // * @param {string} context - Context string for logging
1579
+ // */
1580
+ // #cleanupEmuiProperties = (guestEmui: unknown, context: string): void => {
1581
+ // try {
1582
+ // if (typeof guestEmui === 'object' && guestEmui !== null) {
1583
+ // this.#nullEmuiProperties(guestEmui);
1584
+ // }
1585
+ // this.#logger.debug(
1586
+ // `[SSF] Nulled all window.emui properties for ${context}`,
1587
+ // );
1588
+ // } catch (e) {
1589
+ // this.#logger.debug(
1590
+ // `[SSF] Failed to cleanup window.emui: ${(e as Error).message}`,
1591
+ // );
1592
+ // }
1593
+ // };
1594
+ //
1595
+ // /**
1596
+ // * Cleanup guest window context - nulls all window.emui and window.elli.script properties
1597
+ // * This breaks closure retention chains and allows GC of webpack bundles, SDKs, and singletons
1598
+ // * @param {object} options - Cleanup options
1599
+ // * @param {Window | null} options.guestWindow - The guest window
1600
+ // * @param {string} options.guestId - Guest ID for logging
1601
+ // * @param {string} options.cleanupFunctionName - Cleanup function name
1602
+ // * @param {string} options.windowType - Window type for logging
1603
+ // */
1604
+ // #cleanupGuestWindow = (options: {
1605
+ // guestWindow: Window | null;
1606
+ // guestId: string;
1607
+ // cleanupFunctionName: string;
1608
+ // windowType?: 'iframe' | 'popup';
1609
+ // }) => {
1610
+ // const {
1611
+ // guestWindow,
1612
+ // guestId,
1613
+ // cleanupFunctionName,
1614
+ // windowType = 'iframe',
1615
+ // } = options;
1616
+ //
1617
+ // if (!guestWindow) {
1618
+ // this.#logger.debug(
1619
+ // `No ${windowType} window available for cleanup of guest ${guestId}`,
1620
+ // );
1621
+ // return;
1622
+ // }
1623
+ //
1624
+ // const context = `${windowType} ${guestId}`;
1625
+ //
1626
+ // try {
1627
+ // const windowWithEmui = guestWindow as Window & { emui?: unknown };
1628
+ // const guestEmui = windowWithEmui.emui;
1629
+ //
1630
+ // if (!guestEmui) {
1631
+ // this.#logger.debug(`No window.emui found for ${context}`);
1632
+ // return;
1633
+ // }
1634
+ //
1635
+ // this.#callGuestCleanupFunction({
1636
+ // guestEmui,
1637
+ // cleanupFunctionName,
1638
+ // context,
1639
+ // });
1640
+ //
1641
+ // this.#cleanupEmuiProperties(guestEmui, context);
1642
+ // this.#cleanupElliScript(guestWindow, context);
1643
+ // this.#clearGtmDataLayer(guestWindow, context);
1644
+ // } catch (e) {
1645
+ // this.#logger.debug(
1646
+ // `[SSF] Could not access ${windowType} window for cleanup (guest ${guestId}): ${
1647
+ // (e as Error).message
1648
+ // }`,
1649
+ // );
1650
+ // }
1651
+ // };
1652
+ //
1653
+ // /**
1654
+ // * Navigate to parent of target property
1655
+ // * @param {string[]} parts - Path parts
1656
+ // * @param {string} path - Full path for logging
1657
+ // * @param {string} guestId - Guest ID for logging
1658
+ // * @returns {object | null} Navigation result with current object and parent chain
1659
+ // */
1660
+ // #navigateToParent = (
1661
+ // parts: string[],
1662
+ // path: string,
1663
+ // guestId: string,
1664
+ // ): {
1665
+ // current: Record<string, unknown>;
1666
+ // parentChain: Array<{ obj: Record<string, unknown>; key: string }>;
1667
+ // } | null => {
1668
+ // const parentChain: Array<{ obj: Record<string, unknown>; key: string }> =
1669
+ // [];
1670
+ // let current: Record<string, unknown> = window as unknown as Record<
1671
+ // string,
1672
+ // unknown
1673
+ // >;
1674
+ //
1675
+ // for (let i = 0; i < parts.length - 1; i += 1) {
1676
+ // const part = parts[i];
1677
+ // if (current[part] === undefined || current[part] === null) {
1678
+ // this.#logger.debug(
1679
+ // `Path "${path}" does not exist (stopped at ${part}) for guest ${guestId}`,
1680
+ // );
1681
+ // return null;
1682
+ // }
1683
+ // parentChain.push({ obj: current, key: part });
1684
+ // current = current[part] as Record<string, unknown>;
1685
+ // }
1686
+ //
1687
+ // return { current, parentChain };
1688
+ // };
1689
+ //
1690
+ // /**
1691
+ // * Clean up empty parent objects in chain
1692
+ // * @param {Array<{obj: Record<string, unknown>, key: string}>} parentChain - Chain of parent objects
1693
+ // * @param {string[]} parts - Path parts for logging
1694
+ // * @param {string} guestId - Guest ID for logging
1695
+ // */
1696
+ // #cleanupParentChain = (
1697
+ // parentChain: Array<{ obj: Record<string, unknown>; key: string }>,
1698
+ // parts: string[],
1699
+ // guestId: string,
1700
+ // ): void => {
1701
+ // for (let i = parentChain.length - 1; i >= 0; i -= 1) {
1702
+ // const { obj, key } = parentChain[i];
1703
+ // const parent = obj[key];
1704
+ //
1705
+ // if (
1706
+ // !parent ||
1707
+ // typeof parent !== 'object' ||
1708
+ // !this.#isEmptyOrNullObject(parent)
1709
+ // ) {
1710
+ // break;
1711
+ // }
1712
+ //
1713
+ // obj[key] = null;
1714
+ // this.#logger.debug(
1715
+ // `Cleaned up empty parent object at ${parts
1716
+ // .slice(0, i + 1)
1717
+ // .join('.')} for guest ${guestId}`,
1718
+ // );
1719
+ // }
1720
+ // };
1721
+ //
1722
+ // /**
1723
+ // * Recursively clear window references by path string
1724
+ // * Handles nested paths like "window.IMT.focusFormTitle" or "window.emui.app"
1725
+ // * Sets each reference to null and cleans up empty parent objects
1726
+ // * @param {string[]} paths - Array of dot-separated paths to window properties
1727
+ // * @param {string} guestId - Guest ID for logging purposes
1728
+ // * @example
1729
+ // * // Clear window.IMT.focusFormTitle and cleanup window.IMT if empty
1730
+ // * clearWindowRefs(["window.IMT.focusFormTitle"], "my-guest-id");
1731
+ // * @example
1732
+ // * // Clear multiple refs
1733
+ // * clearWindowRefs(["window.IMT.focusFormTitle", "window.emui.app"], "my-guest-id");
1734
+ // */
1735
+ // #clearWindowRefs = (paths: string[], guestId: string) => {
1736
+ // if (!paths || paths.length === 0) return;
1737
+ //
1738
+ // paths.forEach((path) => {
1739
+ // try {
1740
+ // const parts = path
1741
+ // .split('.')
1742
+ // .filter((p) => p !== 'window' && p.trim() !== '');
1743
+ //
1744
+ // if (parts.length === 0) {
1745
+ // this.#logger.debug(
1746
+ // `Invalid path "${path}" - skipping for guest ${guestId}`,
1747
+ // );
1748
+ // return;
1749
+ // }
1750
+ //
1751
+ // const result = this.#navigateToParent(parts, path, guestId);
1752
+ // if (!result) return;
1753
+ //
1754
+ // const { current, parentChain } = result;
1755
+ // const targetProp = parts[parts.length - 1];
1756
+ //
1757
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1758
+ // if (current[targetProp] === undefined) {
1759
+ // return;
1760
+ // }
1761
+ //
1762
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1763
+ // current[targetProp] = null;
1764
+ // this.#logger.debug(
1765
+ // `Cleared window reference: ${path} for guest ${guestId}`,
1766
+ // );
1767
+ //
1768
+ // this.#cleanupParentChain(parentChain, parts, guestId);
1769
+ // } catch (e) {
1770
+ // this.#logger.debug(
1771
+ // `Failed to clear window reference "${path}" for guest ${guestId}: ${
1772
+ // (e as Error).message
1773
+ // }`,
1774
+ // );
1775
+ // }
1776
+ // });
1777
+ // };
1778
+ //
1779
+ // /**
1780
+ // * Check if an object is empty or only contains null/undefined values
1781
+ // * Used to determine if parent objects should be cleaned up after nulling child properties
1782
+ // * @param {unknown} obj - Object to check
1783
+ // * @returns {boolean} true if object has no properties or all properties are null/undefined
1784
+ // */
1785
+ // #isEmptyOrNullObject = (obj: unknown): boolean => {
1786
+ // if (obj === null || obj === undefined || typeof obj !== 'object')
1787
+ // return true;
1788
+ // const keys = Object.keys(obj);
1789
+ // if (keys.length === 0) return true;
1790
+ //
1791
+ // const record = obj as Record<string, unknown>;
1792
+ // // Check if all properties are null or undefined
1793
+ // return keys.every(
1794
+ // (key) => record[key] === null || record[key] === undefined,
1795
+ // );
1796
+ // };
1797
+ //
1798
+ // /**
1799
+ // * Unloads guest application from host with optional enhanced cleanup.
1800
+ // *
1801
+ // * **Basic Mode (no options):**
1802
+ // * - Standard guest disposal
1803
+ // * - Removes from tracking maps
1804
+ // *
1805
+ // * **Enhanced Mode (with options):**
1806
+ // * - `purgeOnDestroy: true` - Uses comprehensive cleanup via `unloadGuestWithFullCleanup`
1807
+ // * - Calls guest cleanup function (React unmount, Redux teardown)
1808
+ // * - Closes contentWindow context
1809
+ // * - Navigates iframe to about:blank
1810
+ // * - Removes iframe from DOM (deferred)
1811
+ // * - Clears all window.emui and window.elli.script references
1812
+ // * - Disconnects FieldMutation observers
1813
+ // * - Removes from SSF tracking
1814
+ // *
1815
+ // * - `windowRefsToClear` - Array of paths to window refs to clear recursively
1816
+ // * - Example: ["window.IMT.focusFormTitle", "window.emui.customApp"]
1817
+ // * - Each path is parsed and set to null
1818
+ // *
1819
+ // * - `appId` - Optional appId for targeted window.emui[appId] cleanup
1820
+ // *
1821
+ // * - `cleanupFunctionName` - Name of cleanup function on window.emui (default: 'unmount')
1822
+ // * @param {string | Window | HTMLIFrameElement} guestIdOrWindowOrEle - Unique id, window object, or iframe element
1823
+ // * @param {object} options - Optional cleanup configuration
1824
+ // * @param {boolean} options.purgeOnDestroy - When true, use comprehensive cleanup sequence
1825
+ // * @param {string[]} options.windowRefsToClear - Array of window ref paths to clear
1826
+ // * @param {string} options.appId - Optional appId for targeted cleanup
1827
+ // * @param {string} options.cleanupFunctionName - Guest cleanup function name (default: 'unmount')
1828
+ // * @example
1829
+ // * // Basic cleanup
1830
+ // * host.unloadGuest('my-guest-id');
1831
+ // * @example
1832
+ // * // Enhanced cleanup with purge
1833
+ // * host.unloadGuest('my-guest-id', {
1834
+ // * purgeOnDestroy: true,
1835
+ // * windowRefsToClear: ["window.IMT.focusFormTitle"],
1836
+ // * cleanupFunctionName: 'appCleanup'
1837
+ // * });
1838
+ // * @example
1839
+ // * // Enhanced cleanup with appId
1840
+ // * host.unloadGuest('my-guest-id', {
1841
+ // * purgeOnDestroy: true,
1842
+ // * appId: 'workflowtasks',
1843
+ // * cleanupFunctionName: 'cleanup'
1844
+ // * });
1845
+ // */
1846
+ // unloadGuest = (
1847
+ // guestIdOrWindowOrEle: string | Window | HTMLIFrameElement,
1848
+ // options?: UnloadOptions,
1849
+ // ) => {
1850
+ // const guest = this.#findGuest(guestIdOrWindowOrEle);
1851
+ // if (!guest) {
1852
+ // this.#logger.warn('Attempted to unload unknown guest');
1853
+ // return;
1854
+ // }
1855
+ //
1856
+ // const guestId = guest.id;
1857
+ //
1858
+ // // Enhanced cleanup mode when purgeOnDestroy is true
1859
+ // if (options?.purgeOnDestroy) {
1860
+ // const cleanupFunctionName = options.cleanupFunctionName || 'unmount';
1861
+ //
1862
+ // // Clear custom window references if specified
1863
+ // if (options.windowRefsToClear && options.windowRefsToClear.length > 0) {
1864
+ // this.#clearWindowRefs(options.windowRefsToClear, guestId);
1865
+ // }
1866
+ //
1867
+ // // Use comprehensive cleanup
1868
+ // this.unloadGuestWithFullCleanup(guestId, cleanupFunctionName);
1869
+ //
1870
+ // this.#logger.audit({
1871
+ // message: `Guest unloaded with purge mode (windowRefs: ${
1872
+ // options.windowRefsToClear?.length || 0
1873
+ // })`,
1874
+ // ...guest.getInfo(),
1875
+ // });
1876
+ // return;
1877
+ // }
1878
+ //
1879
+ // // Standard cleanup mode (legacy behavior)
1880
+ // guest.dispose();
1881
+ // this.#guestsByWindow.delete(guest.window);
1882
+ // this.#guestsByUrl.delete(guest.url);
1883
+ // this.#guestMetadata.delete(guest.id);
1884
+ // this.#guests.delete(guest.id);
1885
+ // this.#logger.audit({
1886
+ // message: `Guest is removed from host`,
1887
+ // ...guest.getInfo(),
1888
+ // });
1889
+ // this.#stopMonitoringPopupGuests();
1890
+ // };
1891
+ //
1892
+ // /**
1893
+ // * Process iframe cleanup sequence
1894
+ // * @param {Guest} guest - Guest object
1895
+ // * @param {string} cleanupFunctionName - Cleanup function name
1896
+ // */
1897
+ // #processIframeCleanup = (guest: Guest, cleanupFunctionName: string): void => {
1898
+ // if (!guest.domElement) return;
1899
+ //
1900
+ // const iframe = guest.domElement;
1901
+ // const contentWindow = guest.window;
1902
+ // const { id: guestId } = guest;
1903
+ //
1904
+ // this.#cleanupGuestWindow({
1905
+ // guestWindow: contentWindow,
1906
+ // guestId,
1907
+ // cleanupFunctionName,
1908
+ // windowType: 'iframe',
1909
+ // });
1910
+ //
1911
+ // this.#disconnectFieldMutationObserver(contentWindow, guestId);
1912
+ // this.#closeContentWindow(contentWindow, guestId);
1913
+ // this.#navigateToBlank(iframe, guestId);
1914
+ //
1915
+ // setTimeout(() => {
1916
+ // try {
1917
+ // if (iframe.parentNode) {
1918
+ // iframe.remove();
1919
+ // this.#logger.debug(
1920
+ // `[SSF] Removed iframe from DOM for guest ${guestId}`,
1921
+ // );
1922
+ // }
1923
+ // } catch (e) {
1924
+ // this.#logger.warn(
1925
+ // `[SSF] Failed to remove iframe for guest ${guestId}: ${
1926
+ // (e as Error).message
1927
+ // }`,
1928
+ // );
1929
+ // }
1930
+ // }, 10);
1931
+ // };
1932
+ //
1933
+ // /**
1934
+ // * Process popup cleanup sequence
1935
+ // * @param {Guest} guest - Guest object
1936
+ // * @param {string} cleanupFunctionName - Cleanup function name
1937
+ // */
1938
+ // #processPopupCleanup = (guest: Guest, cleanupFunctionName: string): void => {
1939
+ // const popupWindow = guest.window;
1940
+ // const { id: guestId } = guest;
1941
+ //
1942
+ // this.#cleanupGuestWindow({
1943
+ // guestWindow: popupWindow,
1944
+ // guestId,
1945
+ // cleanupFunctionName,
1946
+ // windowType: 'popup',
1947
+ // });
1948
+ //
1949
+ // try {
1950
+ // if (popupWindow && !popupWindow.closed) {
1951
+ // popupWindow.close();
1952
+ // this.#logger.debug(`[SSF] Closed popup window for guest ${guestId}`);
1953
+ // }
1954
+ // } catch (e) {
1955
+ // this.#logger.debug(
1956
+ // `[SSF] Failed to close popup window for guest ${guestId}: ${
1957
+ // (e as Error).message
1958
+ // }`,
1959
+ // );
1960
+ // }
1961
+ //
1962
+ // guest.dispose();
1963
+ // };
1964
+ //
1965
+ // /**
1966
+ // * Unloads guest application with comprehensive memory leak prevention.
1967
+ // *
1968
+ // * This method implements industry best practices for iframe and popup cleanup to prevent
1969
+ // * memory leaks, particularly detached window retention and webpack bundle accumulation.
1970
+ // *
1971
+ // * **Enhanced Cleanup Sequence for Embedded Iframes:**
1972
+ // * 1. Call guest cleanup function (React unmount, Redux teardown, etc.)
1973
+ // * 2. Close contentWindow context explicitly
1974
+ // * 3. Navigate iframe to about:blank (Chrome GC recommendation)
1975
+ // * 4. Small delay, then remove iframe from DOM
1976
+ // * 5. Remove from SSF tracking maps
1977
+ // * 6. Null all internal references
1978
+ // *
1979
+ // * **Enhanced Cleanup Sequence for Popup Windows:**
1980
+ // * 1. Call guest cleanup function (React unmount, Redux teardown, etc.)
1981
+ // * 2. Null all window.emui and window.elli.script references
1982
+ // * 3. Clear Google Tag Manager data layer
1983
+ // * 4. Close popup window explicitly
1984
+ // * 5. Dispose guest (cleanup event listeners)
1985
+ // * 6. Remove from SSF tracking maps
1986
+ // *
1987
+ // * **Memory Leak Prevention:**
1988
+ // * - Breaks all closures from contentWindow/popup to parent
1989
+ // * - Signals V8 to GC webpack bundle backing store strings
1990
+ // * - Removes iframe from browser back/forward cache
1991
+ // * - Clears all SSF remoting message handlers
1992
+ // * - Nulls all window.emui and window.elli.script properties
1993
+ // *
1994
+ // * **Important:** This method does NOT clean up window.emui[appId] registry.
1995
+ // * When using selfInitialize=true pattern, the guest application handles
1996
+ // * its own emui registry cleanup internally.
1997
+ // *
1998
+ // * **Synchronous Design:** This method is intentionally synchronous to work
1999
+ // * with React useEffect cleanup functions. Cleanup steps use setTimeout
2000
+ // * for deferred operations rather than async/await.
2001
+ // * @param {string | Window | HTMLIFrameElement} guestIdOrWindowOrEle - unique id of the guest application or window object or dom element
2002
+ // * @param {string} cleanupFunctionName - name of cleanup function on window.emui (default: 'unmount')
2003
+ // * @example
2004
+ // * // Standard usage with app cleanup
2005
+ // * host.unloadGuestWithFullCleanup('my-guest-id', 'appCleanup');
2006
+ // * @example
2007
+ // * // Usage with custom cleanup function
2008
+ // * host.unloadGuestWithFullCleanup('my-guest-id', 'customUnmount');
2009
+ // * @example
2010
+ // * // Usage when guest uses default unmount
2011
+ // * host.unloadGuestWithFullCleanup('my-guest-id');
2012
+ // */
2013
+ // unloadGuestWithFullCleanup = (
2014
+ // guestIdOrWindowOrEle: string | Window | HTMLIFrameElement,
2015
+ // cleanupFunctionName = 'unmount',
2016
+ // ): void => {
2017
+ // const guest = this.#findGuest(guestIdOrWindowOrEle);
2018
+ // if (!guest) {
2019
+ // this.#logger.warn('Attempted to unload unknown guest');
2020
+ // return;
2021
+ // }
2022
+ //
2023
+ // const { id: guestId } = guest;
2024
+ //
2025
+ // if (guest.openMode === OpenMode.Embed && guest.domElement) {
2026
+ // this.#processIframeCleanup(guest, cleanupFunctionName);
2027
+ // } else if (guest.openMode === OpenMode.Popup) {
2028
+ // this.#processPopupCleanup(guest, cleanupFunctionName);
2029
+ // } else {
2030
+ // guest.dispose();
2031
+ // }
2032
+ //
2033
+ // // Step 5: Remove from remoting allowed senders
2034
+ // // This prevents any further postMessage communication
2035
+ // try {
2036
+ // this.#remoting.removeSender({
2037
+ // origin: guest.origin,
2038
+ // window: guest.window,
2039
+ // });
2040
+ // this.#logger.debug(`[SSF] Removed remoting sender for guest ${guestId}`);
2041
+ // } catch (e) {
2042
+ // this.#logger.debug(
2043
+ // `[SSF] Failed to remove remoting sender for guest ${guestId}: ${
2044
+ // (e as Error).message
2045
+ // }`,
2046
+ // );
2047
+ // }
2048
+ //
2049
+ // // Step 6: Remove from all SSF tracking maps
2050
+ // this.#guestsByWindow.delete(guest.window);
2051
+ // this.#guestsByUrl.delete(guest.url);
2052
+ // this.#guestMetadata.delete(guestId);
2053
+ // this.#guests.delete(guestId);
2054
+ //
2055
+ // // Step 7: Stop monitoring popup guests if none remain
2056
+ // this.#stopMonitoringPopupGuests();
2057
+ //
2058
+ // this.#logger.audit({
2059
+ // message: `Guest unloaded with full cleanup`,
2060
+ // ...guest.getInfo(),
2061
+ // });
2062
+ // };
2063
+ //
2064
+ // /**
2065
+ // * monitors guest window close action and executes the callback from host.
2066
+ // * @param param - Guest close parameters including id and callback
2067
+ // */
1266
2068
  onGuestClose = (param) => {
1267
2069
  const { id, guestCloseCallback } = param;
1268
2070
  const callbacks = this.#guestCloseCallbackList.get(id) || [];