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

MWPW-149504 [MILO][MEP] Move entitlements object to the same JSON file used by the library #3047

Merged
merged 13 commits into from
Oct 23, 2024
Merged
4 changes: 2 additions & 2 deletions libs/blocks/library-config/library-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ async function loadList(type, content, list) {
case 'assets':
loadAssets(content, list);
break;
case 'personalization_tags':
case 'MEP_personalization':
loadPersonalization(content, list);
break;
default:
Expand Down Expand Up @@ -153,7 +153,7 @@ async function combineLibraries(base, supplied) {
blocks: base.blocks.data,
templates: base.templates?.data,
icons: base.icons?.data,
personalization_tags: base.personalization?.data,
MEP_personalization: base.personalization?.data,
placeholders: base.placeholders?.data,
};

Expand Down
32 changes: 20 additions & 12 deletions libs/blocks/library-config/lists/personalization.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import { createTag } from '../../../utils/utils.js';
import createCopy from '../library-utils.js';

const fetchTags = async (path) => {
const resp = await fetch(path);
if (!resp.ok) return [];
const json = await resp.json();
return json.data || [];
};

const categorize = (tagData) => tagData
const categorize = (tagData, category) => tagData
.reduce((tags, tag) => {
tags[tag.category] ??= [];
tags[tag.category].push({
const tagCategory = tag.category || category;
tags[tagCategory] ??= [];
tags[tagCategory].push({
tagname: tag.tagname,
description: tag.description,
});
return tags;
}, {});

const fetchTags = async (path, category) => {
const resp = await fetch(path);
if (!resp.ok) return [];
const json = await resp.json();
return categorize(json.data, category);
};

const getCopyBtn = (tagName) => {
const copy = createTag('button', { class: 'copy' });
copy.id = `${tagName}-tag-copy`;
Expand All @@ -32,8 +33,15 @@ const getCopyBtn = (tagName) => {
};

export default async function loadPersonalization(content, list) {
const tagData = await fetchTags(content[0].path);
const tagsObj = categorize(tagData);
let tagsObj = {};
for (const item of content) {
const { category, path } = item;
tagsObj = {
...tagsObj,
...await fetchTags(path, category),
};
}

list.textContent = '';

Object.entries(tagsObj).forEach(([category, tags]) => {
Expand Down
62 changes: 0 additions & 62 deletions libs/features/personalization/entitlements.js

This file was deleted.

44 changes: 42 additions & 2 deletions libs/features/personalization/personalization.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/* eslint-disable no-console */

import { createTag, getConfig, loadLink, loadScript, localizeLink } from '../../utils/utils.js';
import { getEntitlementMap } from './entitlements.js';
import { getFederatedUrl } from '../../utils/federated.js';

/* c8 ignore start */
const PHONE_SIZE = window.screen.width < 550 || window.screen.height < 550;
Expand Down Expand Up @@ -67,6 +67,9 @@ export const normalizePath = (p, localize = true) => {
}

const config = getConfig();
if (path.startsWith('https://www.adobe.com/federal/')) {
return getFederatedUrl(path);
}

if (path.startsWith(config.codeRoot)
|| path.includes('.hlx.')
Expand Down Expand Up @@ -340,6 +343,8 @@ function registerInBlockActions(command) {
blockSelector = blockAndSelector.slice(1).join(' ');
command.selector = blockSelector;
if (getSelectorType(blockSelector) === 'fragment') {
if (blockSelector.includes('/federal/')) blockSelector = getFederatedUrl(blockSelector);
if (command.content.includes('/federal/')) command.content = getFederatedUrl(command.content);
config.mep.inBlock[blockName].fragments ??= {};
const { fragments } = config.mep.inBlock[blockName];
delete command.selector;
Expand Down Expand Up @@ -447,7 +452,7 @@ function getSelectedElements(sel, rootEl, forceRootEl) {
);
return { els: fragments, modifiers: [FLAGS.all, FLAGS.includeFragments] };
} catch (e) {
/* c8 ignore next */
/* c8 ignore next 2 */
return { els: [], modifiers: [] };
}
}
Expand Down Expand Up @@ -702,6 +707,40 @@ export function buildVariantInfo(variantNames) {
}, { allNames: [] });
}

const getXLGListURL = (config) => {
const sheet = config.env?.name === 'prod' ? 'prod' : 'stage';
return `https://www.adobe.com/federal/assets/data/mep-entitlement-tags.json?sheet=${sheet}`;
};

export const getEntitlementMap = async () => {
const config = getConfig();
if (config.mep?.entitlementMap) return config.mep.entitlementMap;
const entitlementUrl = getXLGListURL(config);
const fetchedData = await fetchData(entitlementUrl, DATA_TYPE.JSON);
if (!fetchedData) return config.consumerEntitlements || {};
const entitlements = {};
fetchedData?.data?.forEach((ent) => {
const { id, tagname } = ent;
entitlements[id] = tagname;
});
config.mep ??= {};
config.mep.entitlementMap = { ...config.consumerEntitlements, ...entitlements };
return config.mep.entitlementMap;
};

export const getEntitlements = async (data) => {
const entitlementMap = await getEntitlementMap();

return data.flatMap((destination) => {
const ents = destination.segments?.flatMap((segment) => {
const entMatch = entitlementMap[segment.id];
return entMatch ? [entMatch] : [];
});

return ents || [];
});
};

async function getPersonalizationVariant(manifestPath, variantNames = [], variantLabel = null) {
const config = getConfig();
if (config.mep?.variantOverride?.[manifestPath]) {
Expand Down Expand Up @@ -1102,6 +1141,7 @@ export async function init(enablements = {}) {
const normalizedURL = normalizePath(manifest.manifestPath);
loadLink(normalizedURL, { as: 'fetch', crossorigin: 'anonymous', rel: 'preload' });
});
if (pzn) loadLink(getXLGListURL(config), { as: 'fetch', crossorigin: 'anonymous', rel: 'preload' });
}

if (target === true) manifests = manifests.concat(await callMartech(config));
Expand Down
6 changes: 3 additions & 3 deletions libs/martech/martech.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,8 @@ export const getTargetPersonalization = async () => {

const setupEntitlementCallback = () => {
const setEntitlements = async (destinations) => {
const { default: parseEntitlements } = await import('../features/personalization/entitlements.js');
return parseEntitlements(destinations);
const { getEntitlements } = await import('../features/personalization/personalization.js');
return getEntitlements(destinations);
};

const getEntitlements = (resolve) => {
Expand All @@ -173,7 +173,7 @@ const setupEntitlementCallback = () => {
getEntitlements(resolveEnt);

loadLink(
`${miloLibs || codeRoot}/features/personalization/entitlements.js`,
`${miloLibs || codeRoot}/features/personalization/personalization.js`,
{ as: 'script', rel: 'modulepreload' },
);
};
Expand Down
58 changes: 44 additions & 14 deletions test/features/personalization/actions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { readFile } from '@web/test-runner-commands';
import { stub } from 'sinon';
import { getConfig, loadBlock } from '../../../libs/utils/utils.js';
import initFragments from '../../../libs/blocks/fragment/fragment.js';
import { init, handleFragmentCommand } from '../../../libs/features/personalization/personalization.js';
import { init, handleCommands } from '../../../libs/features/personalization/personalization.js';
import mepSettings from './mepSettings.js';

document.head.innerHTML = await readFile({ path: './mocks/metadata.html' });
Expand Down Expand Up @@ -151,7 +151,6 @@ describe('prependToSection action', async () => {

describe('appendToSection action', async () => {
it('appendToSection should add fragment to end of section', async () => {
config.mep = { handleFragmentCommand };
let manifestJson = await readFile({ path: './mocks/actions/manifestAppendToSection.json' });

manifestJson = JSON.parse(manifestJson);
Expand All @@ -167,6 +166,24 @@ describe('appendToSection action', async () => {
});
});

describe('addHash', async () => {
it('if forceInline is true, addHash is called', async () => {
config.mep.commands = [{
action: 'replace',
content: '/new-fragment',
selector: 'h1',
}];
const rootEl = document.createElement('div');
handleCommands(config.mep.commands, rootEl, true, true);
console.log(config.mep.commands[0].content);
expect(config.mep.commands[0].content).to.equal('/new-fragment#_inline');
config.mep.commands[0].content = 'https://main--cc--adobecom.hlx.page/cc/fragments/new-fragment';
handleCommands(config.mep.commands, rootEl, true, true);
console.log(config.mep.commands[0].content);
expect(config.mep.commands[0].content).to.equal('https://main--cc--adobecom.hlx.page/cc/fragments/new-fragment#_inline');
});
});

describe('replace action with html/text instead of fragment', () => {
it('should replace marquee content', async () => {
document.body.innerHTML = await readFile({ path: './mocks/personalization.html' });
Expand Down Expand Up @@ -219,20 +236,25 @@ describe('remove action', () => {
let manifestJson = await readFile({ path: './mocks/actions/manifestRemove.json' });
manifestJson = JSON.parse(manifestJson);
setFetchResponse(manifestJson);
delete config.mep;

expect(document.querySelector('.z-pattern')).to.not.be.null;
await init({
mepParam: '',
mepHighlight: false,
mepButton: false,
pzn: '/path/to/manifest.json',
promo: false,
target: false,
});

setTimeout(async () => {
expect(document.querySelector('.z-pattern')).to.not.be.null;
mepSettings.mepButton = false;
await init(mepSettings);

expect(document.querySelector('.z-pattern')).to.not.be.null;
expect(document.querySelector('.z-pattern').dataset.removedManifestId).to.not.be.null;
expect(document.querySelector('.z-pattern')).to.not.be.null;
expect(document.querySelector('.z-pattern').dataset.removedManifestId).to.equal('manifest.json');

const removeMeFrag = document.querySelector('a[href="/fragments/removeme"]');
await initFragments(removeMeFrag);
expect(document.querySelector('a[href="/fragments/removeme"]')).to.not.be.null;
expect(document.querySelector('a[href="/fragments/removeme"]').dataset.removedManifestId).to.not.be.null;
}, 50);
const removeMeFrag = document.querySelector('a[href="/fragments/removeme"]');
await initFragments(removeMeFrag);
expect(document.querySelector('a[href="/fragments/removeme"]')).to.not.be.null;
expect(document.querySelector('a[href="/fragments/removeme"]').dataset.removedManifestId).to.not.be.null;
});
});

Expand Down Expand Up @@ -322,6 +344,14 @@ describe('custom actions', async () => {
pageFilter: '',
selectorType: 'in-block:',
},
'https://main--federal--adobecom.hlx.page/federal/fragments/new-sub-menu': {
action: 'replace',
pageFilter: '',
content: 'https://main--federal--adobecom.hlx.page/federal/fragments/even-more-new-sub-menu',
selectorType: 'in-block:',
manifestId: false,
targetManifestId: false,
},
},
},
});
Expand Down
Loading