From fbe69943ec062032d5b5e142328026056c25cb37 Mon Sep 17 00:00:00 2001 From: Swati Mukherjee Date: Thu, 16 Jan 2025 16:34:06 +0530 Subject: [PATCH] Fix logs, flags, code, methods --- .../personalization/personalization.js | 61 ++++++++++++------- libs/utils/utils.js | 44 ++++++------- .../personalization/personalization.test.js | 4 +- test/utils/utils.test.js | 23 ++++++- 4 files changed, 79 insertions(+), 53 deletions(-) diff --git a/libs/features/personalization/personalization.js b/libs/features/personalization/personalization.js index 225b09d0c7..3af18cd66e 100644 --- a/libs/features/personalization/personalization.js +++ b/libs/features/personalization/personalization.js @@ -1,9 +1,8 @@ +/* eslint-disable default-param-last */ /* eslint-disable no-underscore-dangle */ /* eslint-disable no-console */ -import { - createTag, getConfig, loadLink, loadScript, localizeLink, enablePersonalizationV2, -} from '../../utils/utils.js'; +import { createTag, getConfig, loadLink, loadScript, localizeLink } from '../../utils/utils.js'; import { getFederatedUrl } from '../../utils/federated.js'; /* c8 ignore start */ @@ -763,7 +762,12 @@ export const getEntitlements = async (data) => { }); }; -async function getPersonalizationVariant(manifestPath, variantNames = [], variantLabel = null) { +async function getPersonalizationVariant( + manifestPath, + variantNames = [], + variantLabel = null, + enablePersV2, +) { const config = getConfig(); if (config.mep?.variantOverride?.[manifestPath]) { return config.mep.variantOverride[manifestPath]; @@ -776,7 +780,7 @@ async function getPersonalizationVariant(manifestPath, variantNames = [], varian let userEntitlements = []; if (hasEntitlementTag) { - if (enablePersonalizationV2()) { + if (enablePersV2) { userEntitlements = []; } else { userEntitlements = await config.entitlements(); @@ -834,7 +838,7 @@ export const addMepAnalytics = (config, header) => { } }); }; -export async function getManifestConfig(info = {}, variantOverride = false) { +export async function getManifestConfig(info = {}, variantOverride = false, enablePersV2 = false) { const { name, manifestData, @@ -904,6 +908,7 @@ export async function getManifestConfig(info = {}, variantOverride = false) { manifestConfig.manifestPath, manifestConfig.variantNames, variantLabel, + enablePersV2, ); manifestConfig.placeholderData = manifestPlaceholders || data?.placeholders?.data; @@ -1040,12 +1045,16 @@ export function parseNestedPlaceholders({ placeholders }) { }); } -export async function applyPers(manifests) { +export async function applyPers({ manifests, enablePersV2 }) { if (!manifests?.length) return; let experiments = manifests; const config = getConfig(); for (let i = 0; i < experiments.length; i += 1) { - experiments[i] = await getManifestConfig(experiments[i], config.mep?.variantOverride); + experiments[i] = await getManifestConfig( + experiments[i], + config.mep?.variantOverride, + enablePersV2, + ); } experiments = cleanAndSortManifestList(experiments); @@ -1121,12 +1130,14 @@ export const combineMepSources = async (persEnabled, promoEnabled, mepParam) => return persManifests; }; -async function updateManifestsAndPropositions({ config, targetManifests, targetPropositions }) { +async function updateManifestsAndPropositions( + { config, targetManifests, targetPropositions, enablePersV2 }, +) { targetManifests.forEach((manifest) => { manifest.source = ['target']; }); config.mep.targetManifests = targetManifests; - if (enablePersonalizationV2()) { + if (enablePersV2) { window.addEventListener('alloy_sendEvent', () => { if (targetPropositions?.length && window._satellite) { window._satellite.track('propositionDisplay', targetPropositions); @@ -1195,11 +1206,11 @@ const handleAlloyResponse = (response) => ((response.propositions || response.de ?.filter(Boolean) ?? []; async function handleMartechTargetInteraction( - { config, targetInteractionPromise, calculatedTimeout }, + { config, targetInteractionPromise, calculatedTimeout, enablePersV2 }, ) { let targetManifests = []; let targetPropositions = []; - if (enablePersonalizationV2() && targetInteractionPromise) { + if (enablePersV2 && targetInteractionPromise) { try { const { targetInteractionData, respTime, respStartTime } = await targetInteractionPromise; sendTargetResponseAnalytics(false, respStartTime, calculatedTimeout); @@ -1220,7 +1231,9 @@ async function handleMartechTargetInteraction( } } - return updateManifestsAndPropositions({ config, targetManifests, targetPropositions }); + return updateManifestsAndPropositions( + { config, targetManifests, targetPropositions, enablePersV2 }, + ); } async function callMartech(config) { @@ -1229,7 +1242,9 @@ async function callMartech(config) { targetManifests, targetPropositions, } = await getTargetPersonalization({ handleAlloyResponse, sendTargetResponseAnalytics }); - return updateManifestsAndPropositions({ config, targetManifests, targetPropositions }); + return updateManifestsAndPropositions( + { config, targetManifests, targetPropositions, enablePersV2: false }, + ); } const awaitMartech = () => new Promise((resolve) => { @@ -1240,7 +1255,7 @@ const awaitMartech = () => new Promise((resolve) => { export async function init(enablements = {}) { let manifests = []; const { - mepParam, mepHighlight, mepButton, pzn, promo, + mepParam, mepHighlight, mepButton, pzn, promo, enablePersV2, target, targetInteractionPromise, calculatedTimeout, postLCP, } = enablements; const config = getConfig(); @@ -1266,20 +1281,22 @@ export async function init(enablements = {}) { if (pzn) loadLink(getXLGListURL(config), { as: 'fetch', crossorigin: 'anonymous', rel: 'preload' }); } - if (enablePersonalizationV2()) { + if (enablePersV2 && target === true) { manifests = manifests.concat(await handleMartechTargetInteraction( - { config, targetInteractionPromise, calculatedTimeout }, + { config, targetInteractionPromise, calculatedTimeout, enablePersV2 }, )); } else { if (target === true) manifests = manifests.concat(await callMartech(config)); + + console.log('here ------------------------------>'); if (target === 'postlcp') callMartech(config); - if (postLCP) { - if (!config.mep.targetManifests) await awaitMartech(); - manifests = config.mep.targetManifests; - } + } + if (postLCP) { + if (!config.mep.targetManifests) await awaitMartech(); + manifests = config.mep.targetManifests; } try { - if (manifests?.length) await applyPers(manifests); + if (manifests?.length) await applyPers({ manifests, enablePersV2 }); if (config.mep?.preview) await import('./preview.js').then(({ saveToMmm }) => saveToMmm()); } catch (e) { log(`MEP Error: ${e.toString()}`); diff --git a/libs/utils/utils.js b/libs/utils/utils.js index 2f6d849a8e..61912e9e23 100644 --- a/libs/utils/utils.js +++ b/libs/utils/utils.js @@ -150,6 +150,7 @@ const PAGE_URL = new URL(window.location.href); export const SLD = PAGE_URL.hostname.includes('.aem.') ? 'aem' : 'hlx'; const PROMO_PARAM = 'promo'; +let isMartechLoaded = false; export function getEnv(conf) { const { host } = window.location; @@ -1070,6 +1071,7 @@ export async function loadMartech({ const { default: initMartech } = await import('../martech/martech.js'); await initMartech({ persEnabled, persManifests, postLCP }); + isMartechLoaded = true; return true; } @@ -1106,6 +1108,7 @@ async function checkForPageMods() { martech, } = Object.fromEntries(PAGE_URL.searchParams); let targetInteractionPromise = null; + let calculatedTimeout = null; if (mepParam === 'off') return; const pzn = getMepEnablement('personalization'); const promo = getMepEnablement('manifestnames', PROMO_PARAM); @@ -1118,7 +1121,7 @@ async function checkForPageMods() { const enablePersV2 = enablePersonalizationV2(); if ((target || xlg) && enablePersV2) { const params = new URL(window.location.href).searchParams; - const calculatedTimeout = parseInt(params.get('target-timeout'), 10) + calculatedTimeout = parseInt(params.get('target-timeout'), 10) || parseInt(getMetadata('target-timeout'), 10) || TARGET_TIMEOUT_MS; @@ -1136,34 +1139,27 @@ async function checkForPageMods() { return { targetInteractionData: data, respTime, respStartTime: now }; })(); - - const { init } = await import('../features/personalization/personalization.js'); - await init({ - mepParam, - mepHighlight, - mepButton, - pzn, - promo, - target, - targetInteractionPromise, - calculatedTimeout, - }); - return; - } - if (target || xlg) { - loadMartech(); - } else if (pzn && martech !== 'off') { + } else if ((target || xlg) && !isMartechLoaded) loadMartech(); + else if (pzn && martech !== 'off') { loadIms() .then(() => { /* c8 ignore next */ - if (window.adobeIMS?.isSignedInUser()) loadMartech(); + if (window.adobeIMS?.isSignedInUser() && !isMartechLoaded) loadMartech(); }) .catch((e) => { console.log('Unable to load IMS:', e); }); } const { init } = await import('../features/personalization/personalization.js'); await init({ - mepParam, mepHighlight, mepButton, pzn, promo, target, targetInteractionPromise, + mepParam, + mepHighlight, + mepButton, + pzn, + promo, + target, + targetInteractionPromise, + calculatedTimeout, + enablePersV2, }); } @@ -1175,12 +1171,8 @@ async function loadPostLCP(config) { /* c8 ignore next 2 */ const { init } = await import('../features/personalization/personalization.js'); await init({ postLCP: true }); - if (enablePersonalizationV2()) { - loadMartech(); - } - } else { - loadMartech(); - } + if (enablePersonalizationV2() && !isMartechLoaded) loadMartech(); + } else if (!isMartechLoaded) loadMartech(); const georouting = getMetadata('georouting') || config.geoRouting; if (georouting === 'on') { diff --git a/test/features/personalization/personalization.test.js b/test/features/personalization/personalization.test.js index 0f4322e7be..0ce20dd3a7 100644 --- a/test/features/personalization/personalization.test.js +++ b/test/features/personalization/personalization.test.js @@ -110,7 +110,7 @@ describe('Functional Test', () => { manifestJson = JSON.parse(manifestJson); setFetchResponse(manifestJson); expect(document.querySelector('a[href="/test/features/personalization/mocks/fragments/insertafter3"]')).to.be.null; - await applyPers(promoMepSettings); + await applyPers({ manifests: promoMepSettings }); const fragment = document.querySelector('a[href="/test/features/personalization/mocks/fragments/insertafter3"]'); expect(fragment).to.not.be.null; @@ -137,7 +137,7 @@ describe('Functional Test', () => { ]; await loadManifestAndSetResponse('./mocks/manifestScheduledInactive.json'); expect(document.querySelector('a[href="/fragments/insertafter4"]')).to.be.null; - await applyPers(promoMepSettings); + await applyPers({ manifests: promoMepSettings }); const fragment = document.querySelector('a[href="/fragments/insertafter4"]'); expect(fragment).to.be.null; diff --git a/test/utils/utils.test.js b/test/utils/utils.test.js index 6e85cb4f13..e04f9cdcae 100644 --- a/test/utils/utils.test.js +++ b/test/utils/utils.test.js @@ -96,7 +96,26 @@ describe('Utils', () => { }); it('render meta performanceV2 renders the normal flow', async () => { - // const spyOnLoadMartech = sinon.spy(loadMartech); + // const localHead = await readFile({ path: './mocks/mep/head-target-postlcp.html' }); + // document.head.innerHTML = localHead; + const metaTag = document.createElement('meta'); + metaTag.setAttribute('name', 'personalization-v2'); + document.head.appendChild(metaTag); + + const bodyWithheader = await readFile({ path: './mocks/body-gnav.html' }); + document.body.innerHTML = bodyWithheader; + + await utils.loadArea(); + expect(document.querySelector('.global-navigation')).to.exist; + }); + + it('render meta performanceV2 renders the normal flow with params', async () => { + const params = new URLSearchParams({ 'target-timeout': '1000' }); + const baseUrl = `${window.location.origin}${window.location.pathname}`; + + const newUrl = `${baseUrl}?${params.toString()}`; + + window.history.pushState({ path: newUrl }, '', newUrl); const localHead = await readFile({ path: './mocks/mep/head-target-postlcp.html' }); document.head.innerHTML = localHead; const metaTag = document.createElement('meta'); @@ -107,8 +126,6 @@ describe('Utils', () => { document.body.innerHTML = bodyWithheader; await utils.loadArea(); - // expect(spyOnLoadMartech.called).to.be.true; - // spyOnLoadMartech.resetHistory(); expect(document.querySelector('.global-navigation')).to.exist; });