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