Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MEP][AJO] POC to integrate AJO with MEP #3654

Open
wants to merge 7 commits into
base: stage
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 37 additions & 30 deletions libs/features/personalization/personalization.js
Original file line number Diff line number Diff line change
Expand Up @@ -1199,28 +1199,28 @@ export const combineMepSources = async (persEnabled, promoEnabled, mepParam) =>
};

async function updateManifestsAndPropositions(
{ config, targetManifests, targetPropositions },
{ config, targetAjoManifests, targetAjoPropositions },
) {
targetManifests.forEach((manifest) => {
manifest.source = ['target'];
targetAjoManifests.forEach((manifest) => {
manifest.source = [config.mep.ajoEnabled ? 'ajo' : 'target'];
});
config.mep.targetManifests = targetManifests;
config.mep.targetAjoManifests = targetAjoManifests;
if (config.mep.enablePersV2) {
if (!config.mep.hybridPersEnabled) {
window.addEventListener('alloy_sendEvent', () => {
if (targetPropositions?.length && window._satellite) {
window._satellite.track('propositionDisplay', targetPropositions);
if (targetAjoPropositions?.length && window._satellite) {
window._satellite.track('propositionDisplay', targetAjoPropositions);
}
}, { once: true });
}
} else if (targetPropositions?.length && window._satellite) {
window._satellite.track('propositionDisplay', targetPropositions);
} else if (targetAjoPropositions?.length && window._satellite) {
window._satellite.track('propositionDisplay', targetAjoPropositions);
}
if (config.mep.targetEnabled === 'postlcp') {
const event = new CustomEvent(MARTECH_RETURNED_EVENT, { detail: 'Martech returned' });
window.dispatchEvent(event);
}
return targetManifests;
return targetAjoManifests;
}

function roundToQuarter(num) {
Expand Down Expand Up @@ -1259,20 +1259,23 @@ function sendTargetResponseAnalytics(failure, responseStart, timeoutLocal, messa
}

const handleAlloyResponse = (response) => ((response.propositions || response.decisions))
?.map((i) => i.items)
?.map((i) => {
const { id } = i;
return i.items.map((item) => ({ ...item, id }));
})
?.flat()
?.map((item) => {
const content = item?.data?.content;
if (!content || !(content.manifestLocation || content.manifestContent)) return null;

return {
manifestPath: content.manifestLocation || content.manifestPath,
manifestUrl: content.manifestLocation,
manifestData: content.manifestContent?.experiences?.data || content.manifestContent?.data,
manifestPlaceholders: content.manifestContent?.placeholders?.data,
manifestInfo: content.manifestContent?.info.data,
name: item.meta['activity.name'],
variantLabel: item.meta['experience.name'] && `target-${item.meta['experience.name']}`,
name: item.meta?.['activity.name'] || item.id,
variantLabel: (item.meta?.['experience.name'] && `target-${item.meta['experience.name']}`)
|| content.experienceName,
meta: item.meta,
};
})
Expand All @@ -1281,8 +1284,9 @@ const handleAlloyResponse = (response) => ((response.propositions || response.de
async function handleMartechTargetInteraction(
{ config, targetInteractionPromise, calculatedTimeout },
) {
let targetManifests = [];
let targetPropositions = [];
const targetAjo = config.mep.ajoEnabled ? 'ajo' : 'target';
let targetAjoManifests = [];
let targetAjoPropositions = [];
if (config?.mep?.enablePersV2 && targetInteractionPromise) {
const { targetInteractionData, respTime, respStartTime } = await targetInteractionPromise;
sendTargetResponseAnalytics(false, respStartTime, calculatedTimeout);
Expand All @@ -1291,33 +1295,35 @@ async function handleMartechTargetInteraction(
performance.clearMarks();
performance.clearMeasures();
try {
window.lana.log(`target response time: ${roundedResponseTime}`, {
window.lana.log(`${targetAjo} response time: ${roundedResponseTime}`, {
tags: 'martech',
errorType: 'e',
sampleRate: 0.5,
});
} catch (e) {
// eslint-disable-next-line no-console
console.error('Error logging target response time:', e);
console.error(`Error logging ${targetAjo} response time:`, e);
}
targetManifests = handleAlloyResponse(targetInteractionData.result);
targetPropositions = targetInteractionData.result?.propositions || [];
targetAjoManifests = handleAlloyResponse(targetInteractionData.result);
targetAjoPropositions = targetInteractionData.result?.propositions || [];
}
}

return updateManifestsAndPropositions(
{ config, targetManifests, targetPropositions },
{ config, targetAjoManifests, targetAjoPropositions },
);
}

async function callMartech(config) {
const { getTargetPersonalization } = await import('../../martech/martech.js');
const { getTargetAjoPersonalization } = await import('../../martech/martech.js');
const {
targetManifests,
targetPropositions,
} = await getTargetPersonalization({ handleAlloyResponse, sendTargetResponseAnalytics });
targetAjoManifests,
targetAjoPropositions,
} = await getTargetAjoPersonalization(
{ handleAlloyResponse, config, sendTargetResponseAnalytics },
);
return updateManifestsAndPropositions(
{ config, targetManifests, targetPropositions },
{ config, targetAjoManifests, targetAjoPropositions },
);
}

Expand All @@ -1330,7 +1336,7 @@ export async function init(enablements = {}) {
let manifests = [];
const {
mepParam, mepHighlight, mepButton, pzn, promo, enablePersV2, hybridPersEnabled,
target, targetInteractionPromise, calculatedTimeout, postLCP,
target, ajo, targetInteractionPromise, calculatedTimeout, postLCP,
} = enablements;
const config = getConfig();
if (postLCP) {
Expand All @@ -1343,6 +1349,7 @@ export async function init(enablements = {}) {
variantOverride: parseMepParam(mepParam),
highlight: (mepHighlight !== undefined && mepHighlight !== 'false'),
targetEnabled: target,
ajoEnabled: ajo,
experiments: [],
prefix: config.locale?.prefix.split('/')[1]?.toLowerCase() || US_GEO,
enablePersV2,
Expand All @@ -1363,12 +1370,12 @@ export async function init(enablements = {}) {
{ config, targetInteractionPromise, calculatedTimeout },
));
} else {
if (target === true) manifests = manifests.concat(await callMartech(config));
if (target === 'postlcp') callMartech(config);
if (target === true || ajo === true) manifests = manifests.concat(await callMartech(config));
if (target === 'postlcp' || ajo === 'postlcp') callMartech(config);
}
if (postLCP) {
if (!config.mep.targetManifests) await awaitMartech();
manifests = config.mep.targetManifests;
if (!config.mep.targetAjoManifests) await awaitMartech();
manifests = config.mep.targetAjoManifests;
}
try {
if (manifests?.length) await applyPers({ manifests });
Expand Down
35 changes: 21 additions & 14 deletions libs/martech/martech.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
getConfig, loadIms, loadLink, loadScript, getMepEnablement, getMetadata,
} from '../utils/utils.js';

const ALLOY_PROPOSITION_FETCH = 'alloy_propositionFetch';
const ALLOY_SEND_EVENT = 'alloy_sendEvent';
const ALLOY_SEND_EVENT_ERROR = 'alloy_sendEvent_error';
const ENTITLEMENT_TIMEOUT = 3000;
Expand Down Expand Up @@ -49,8 +50,10 @@ const waitForEventOrTimeout = (eventName, timeoutLocal, returnValIfTimeout) => n
}
}, timeoutLocal);

const eventError = eventName
=== ALLOY_SEND_EVENT ? ALLOY_SEND_EVENT_ERROR : ALLOY_PROPOSITION_FETCH;
window.addEventListener(eventName, listener, { once: true });
window.addEventListener(ALLOY_SEND_EVENT_ERROR, errorListener, { once: true });
window.addEventListener(eventError, errorListener, { once: true });
});

function roundToQuarter(num) {
Expand All @@ -62,11 +65,14 @@ function calculateResponseTime(responseStart) {
return roundToQuarter(responseTime);
}

export const getTargetPersonalization = async (
{ handleAlloyResponse, sendTargetResponseAnalytics },
export const getTargetAjoPersonalization = async (
{ handleAlloyResponse, config, sendTargetResponseAnalytics },
) => {
const responseStart = Date.now();
window.addEventListener(ALLOY_SEND_EVENT, () => {
const ajo = config.mep.ajoEnabled;
const eventName = ajo ? ALLOY_PROPOSITION_FETCH : ALLOY_SEND_EVENT;
const targetAjo = ajo ? 'ajo' : 'target';
window.addEventListener(eventName, () => {
const responseTime = calculateResponseTime(responseStart);
try {
window.lana.log(`target response time: ${responseTime}`, {
Expand All @@ -80,33 +86,34 @@ export const getTargetPersonalization = async (
}
}, { once: true });

let targetManifests = [];
let targetPropositions = [];
let targetAjoManifests = [];
let targetAjoPropositions = [];

const response = await waitForEventOrTimeout(eventName, timeout);

const response = await waitForEventOrTimeout(ALLOY_SEND_EVENT, timeout);
if (response.error) {
try {
window.lana.log('target response time: ad blocker', {
window.lana.log(`${targetAjo} response time: ad blocker`, {
tags: 'martech',
errorType: 'e',
sampleRate: 0.5,
});
} catch (e) {
// eslint-disable-next-line no-console
console.error('Error logging target response time for ad blocker:', e);
console.error(`Error logging ${targetAjo} response time for ad blocker:`, e);
}
return { targetManifests, targetPropositions };
return { targetAjoManifests, targetAjoPropositions };
}
if (response.timeout) {
waitForEventOrTimeout(ALLOY_SEND_EVENT, 5100 - timeout)
waitForEventOrTimeout(eventName, 5100 - timeout)
.then(() => sendTargetResponseAnalytics(true, responseStart, timeout));
} else {
sendTargetResponseAnalytics(false, responseStart, timeout);
targetManifests = handleAlloyResponse(response.result);
targetPropositions = response.result?.propositions || [];
targetAjoManifests = handleAlloyResponse(response.result);
targetAjoPropositions = response.result?.propositions || [];
}

return { targetManifests, targetPropositions };
return { targetAjoManifests, targetAjoPropositions };
};

const setupEntitlementCallback = () => {
Expand Down
6 changes: 4 additions & 2 deletions libs/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -1184,9 +1184,10 @@ async function checkForPageMods() {
const promo = getMepEnablement('manifestnames', PROMO_PARAM);
const target = martech === 'off' ? false : getMepEnablement('target');
const xlg = martech === 'off' ? false : getMepEnablement('xlg');
const ajo = martech === 'off' ? false : getMepEnablement('ajo');

if (!(pzn || target || promo || mepParam
|| mepHighlight || mepButton || mepParam === '' || xlg)) return;
|| mepHighlight || mepButton || mepParam === '' || xlg || ajo)) return;

const enablePersV2 = enablePersonalizationV2();
const hybridPersEnabled = getMepEnablement('hybrid-pers');
Expand All @@ -1210,7 +1211,7 @@ async function checkForPageMods() {

return { targetInteractionData: data, respTime, respStartTime: now };
})();
} else if ((target || xlg) && !isMartechLoaded) loadMartech();
} else if ((target || xlg || ajo) && !isMartechLoaded) loadMartech();
else if (pzn && martech !== 'off') {
loadIms()
.then(() => {
Expand All @@ -1228,6 +1229,7 @@ async function checkForPageMods() {
pzn,
promo,
target,
ajo,
targetInteractionPromise,
calculatedTimeout,
enablePersV2,
Expand Down
4 changes: 4 additions & 0 deletions test/utils/mocks/mep/head-ajo-off.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<meta name="ajo" content="off">
<title>Document Title</title>
<link rel="icon" href="data:,">

4 changes: 4 additions & 0 deletions test/utils/mocks/mep/head-ajo-on.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<meta name="ajo" content="on">
<title>Document Title</title>
<link rel="icon" href="data:,">

3 changes: 3 additions & 0 deletions test/utils/mocks/mep/head-ajo-postlcp.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<meta name="ajo" content="postlcp">
<title>Document Title</title>
<link rel="icon" href="data:,">
2 changes: 2 additions & 0 deletions test/utils/utils-mep-with-params.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ describe('MEP Utils', () => {
setTimeout(() => {
const persEnabled = getMepEnablement('personalization');
const promoEnabled = getMepEnablement('manifestnames', 'promo');
const ajoEnabled = getMepEnablement('ajo');
const targetEnabled = getMepEnablement('target');
expect(promoEnabled).to.equal(false);
expect(persEnabled).to.equal(false);
expect(ajoEnabled).to.equal(false);
expect(targetEnabled).to.equal('postlcp');
}, 1000);
});
Expand Down
19 changes: 17 additions & 2 deletions test/utils/utils-mep.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ describe('MEP Utils', () => {
});
});
describe('getMepEnablement', async () => {
it('checks target metadata set to off', async () => {
it('checks target metadata set to on', async () => {
document.head.innerHTML = await readFile({ path: './mocks/mep/head-target-on.html' });
const targetEnabled = getMepEnablement('target');
expect(targetEnabled).to.equal(true);
});
it('checks target metadata set to on', async () => {
it('checks target metadata set to off', async () => {
document.head.innerHTML = await readFile({ path: './mocks/mep/head-target-off.html' });
const targetEnabled = getMepEnablement('target');
expect(targetEnabled).to.equal(false);
Expand All @@ -48,6 +48,21 @@ describe('MEP Utils', () => {
const targetEnabled = getMepEnablement('target');
expect(targetEnabled).to.equal('postlcp');
});
it('checks ajo metadata set to on', async () => {
document.head.innerHTML = await readFile({ path: './mocks/mep/head-ajo-on.html' });
const ajoEnabled = getMepEnablement('ajo');
expect(ajoEnabled).to.equal(true);
});
it('checks ajo metadata set to off', async () => {
document.head.innerHTML = await readFile({ path: './mocks/mep/head-ajo-off.html' });
const ajoEnabled = getMepEnablement('ajo');
expect(ajoEnabled).to.equal(false);
});
it('checks ajo metadata set to postlcp', async () => {
document.head.innerHTML = await readFile({ path: './mocks/mep/head-ajo-postlcp.html' });
const ajoEnabled = getMepEnablement('ajo');
expect(ajoEnabled).to.equal('postlcp');
});
it('checks from just metadata with no target metadata', async () => {
document.head.innerHTML = await readFile({ path: './mocks/mep/head-promo.html' });
const persEnabled = getMepEnablement('personalization');
Expand Down
Loading