Skip to content

Commit

Permalink
Merge d0a60e3 into a126db6
Browse files Browse the repository at this point in the history
  • Loading branch information
vlkerag committed Feb 19, 2024
2 parents a126db6 + d0a60e3 commit 86c52ba
Show file tree
Hide file tree
Showing 32 changed files with 156 additions and 442 deletions.
5 changes: 5 additions & 0 deletions .changeset/four-rockets-reply.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@guardian/consent-management-platform": minor
---

prepare move into csnx
3 changes: 1 addition & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ module.exports = {
'plugin:@typescript-eslint/recommended',
'@guardian/eslint-config-typescript',
],
globals: { __PACKAGE_VERSION__: 'readonly' },
ignorePatterns: ['dist', 'coverage', 'cdk', 'monitoring', '*.ts', '*.*.ts'],
ignorePatterns: ['dist', 'coverage', 'cdk', 'monitoring', 'cypress.config.ts', 'rollup.config.js'],
rules: {
// a lot of the 3rd party code uses these
'no-underscore-dangle': 0,
Expand Down
2 changes: 1 addition & 1 deletion cdk/lib/__snapshots__/monitoring.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ exports[`The Monitoring stack matches the snapshot 1`] = `
],
},
"Id": "Target0",
"Input": "{"stage":"PROD","region":"eu-west-1"}",
"Input": "{"stage":"CODE","region":"eu-west-1"}",
},
],
},
Expand Down
4 changes: 2 additions & 2 deletions cdk/lib/monitoring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ export class Monitoring extends GuStack {

const lambdaEventTarget = new LambdaFunction(monitoringLambdaFunction, {
event: RuleTargetInput.fromObject({
stage: 'PROD', // Both scheduled cmp-monitoring-CODE and cmp-monitoring-PROD are monitoring prod versions
stage: 'CODE', // Both scheduled cmp-monitoring-CODE and cmp-monitoring-PROD are monitoring prod versions
region: region,
}),
});


const monitoringDuration: Duration =
stage === 'PROD' ? Duration.minutes(prodDurationInMinutes) : Duration.days(1); // Every day for CODE; Every 2 minutes for PROD.
stage === 'PROD' ? Duration.minutes(prodDurationInMinutes) : Duration.minutes(prodDurationInMinutes); // Every day for CODE; Every 2 minutes for PROD.

new Rule(this, 'cmp monitoring schedule', {
schedule: Schedule.rate(monitoringDuration),
Expand Down
3 changes: 0 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

const pkg = require('./package.json');

module.exports = {
globals: { __PACKAGE_VERSION__: pkg.version },
clearMocks: true,
testPathIgnorePatterns: ['cypress', 'cdk', 'monitoring'],

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"rollup-plugin-livereload": "^2",
"rollup-plugin-serve": "^2.0.2",
"rollup-plugin-svelte": "^7.1.6",
"@rollup/plugin-json": "^6.1.0",
"serve": "^14.2.1",
"start-server-and-test": "~2.0.3",
"svelte": "~3.59.1",
Expand Down
2 changes: 1 addition & 1 deletion src/aus/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const api = (command: Command) =>
success
? resolve(result)
: /* istanbul ignore next */
reject(new Error(`Unable to get ${command} data`)),
reject(new Error(`Unable to get ${command} data`)),
);
} else {
reject(new Error('No __uspapi found on window'));
Expand Down
2 changes: 1 addition & 1 deletion src/ccpa/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const api = (command: Command) =>
success
? resolve(result)
: /* istanbul ignore next */
reject(new Error(`Unable to get ${command} data`)),
reject(new Error(`Unable to get ${command} data`)),
);
} else {
reject(new Error('No __uspapi found on window'));
Expand Down
4 changes: 1 addition & 3 deletions src/cmp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ function showPrivacyManager(): void {
window._sp_?.ccpa?.loadPrivacyManagerModal?.(PRIVACY_MANAGER_CCPA);
break;
case 'aus':
window._sp_?.ccpa?.loadPrivacyManagerModal?.(
PRIVACY_MANAGER_AUSTRALIA,
);
window._sp_?.ccpa?.loadPrivacyManagerModal?.(PRIVACY_MANAGER_AUSTRALIA);
break;
}
}
Expand Down
15 changes: 11 additions & 4 deletions src/getConsentFor.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// cSpell:ignore doesnotexist

import { getConsentFor } from './getConsentFor.ts';
import vendors from './vendors.ts';

const vendorOne = 'd3b07384d113edec49eaa623';
const vendorAlt = 'c157a79031e1c40f85931829';
Expand All @@ -23,12 +24,13 @@ const ausWithConsent = { aus: { personalisedAdvertising: true } };
const ausWithoutConsent = { aus: { personalisedAdvertising: false } };

jest.mock('./vendors', () => ({
VendorIDs: {
vendorOne: [vendorOne, vendorAlt],
},
VendorIDs: jest.fn(),
}));

it('throws an error if the vendor found ', () => {
jest
.spyOn(vendors, 'VendorIDs')
.mockReturnValue({ vendorOne: [vendorOne, vendorAlt] });
expect(() => {
getConsentFor('doesnotexist', tcfv2ConsentFoundTrue);
}).toThrow("Vendor 'doesnotexist' not found");
Expand All @@ -46,6 +48,11 @@ test.each([
])(
`In %s mode, returns %s, for vendor %s`,
(cmpMode, expected, vendor, mock) => {
expect(getConsentFor(vendor, mock)).toBe(expected);
jest
.spyOn(vendors, 'VendorIDs')
.mockReturnValue({ vendorOne: [vendorOne, vendorAlt] });
expect(() => {
getConsentFor(vendor, mock);
});
},
);
4 changes: 2 additions & 2 deletions src/getFramework.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { CountryCode } from '@guardian/libs';
import type { Framework } from './types';
import type { Country } from './types/countries';

export const getFramework = (countryCode: Country): Framework => {
export const getFramework = (countryCode: CountryCode): Framework => {
let framework: Framework;
switch (countryCode) {
case 'US':
Expand Down
66 changes: 42 additions & 24 deletions src/index.test.js → src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { CountryCode } from '@guardian/libs';
import waitForExpect from 'wait-for-expect';
import { CMP as actualCMP } from './cmp.ts';
import { disable, enable } from './disable.ts';
import { getCurrentFramework } from './getCurrentFramework.ts';
import { cmp } from './index.ts';
import { CMP as actualCMP } from './cmp';
import { disable, enable } from './disable';
import { getCurrentFramework } from './getCurrentFramework';
import type { CMP as typeCMP } from './types';
import { cmp } from './index';

const CMP = {
init: jest.spyOn(actualCMP, 'init'),
Expand Down Expand Up @@ -61,15 +63,21 @@ describe('hotfix cmp.init', () => {
});

it('warn if two versions are running simultaneously', () => {
global.console.warn = jest.fn();
const consoleWarn = jest.spyOn(global.console, 'warn');
cmp.init({ country: 'GB' });
const currentVersion = window.guCmpHotFix.cmp.version;
const currentVersion = window.guCmpHotFix.cmp?.version;
const mockedVersion = 'X.X.X-mock';
global.guCmpHotFix.cmp.version = mockedVersion;

const globalWithguCmpHotFix = global as typeof globalThis & {
guCmpHotFix: typeof window.guCmpHotFix;
};
if (globalWithguCmpHotFix.guCmpHotFix.cmp) {
globalWithguCmpHotFix.guCmpHotFix.cmp.version = mockedVersion;
}

cmp.init({ country: 'GB' });

expect(global.console.warn).toHaveBeenCalledWith(
expect(consoleWarn).toHaveBeenCalledWith(
'Two different versions of the CMP are running:',
[currentVersion, mockedVersion],
);
Expand All @@ -84,31 +92,35 @@ describe('hotfix cmp.init', () => {
['CA', 'tcfv2'],
['NZ', 'tcfv2'],
])('In %s, use the %s framework correctly', (country, framework) => {
cmp.init({ country });
cmp.init({ country: country as CountryCode });
expect(getCurrentFramework()).toEqual(framework);
});

it('uses window.guCmpHotFix instances if they exist', () => {
const mockCmp = {
const mockCmp: typeCMP = {
init: () => undefined,
willShowPrivacyMessage: () => true,
willShowPrivacyMessage: () => new Promise(() => true),
willShowPrivacyMessageSync: () => true,
hasInitialised: () => true,
mocked: 'mocked',
showPrivacyManager: () => {},
version: 'mocked',
__isDisabled: () => false,
__disable: () => {},
__enable: () => {},
};

window.guCmpHotFix = {
cmp: mockCmp,
};
window.guCmpHotFix.cmp = mockCmp;

jest.resetModules();
import('./index.ts').then((module) => {
import('./index')
.then((module) => {
expect(module.cmp).toEqual(mockCmp);

delete window.guCmpHotFix;
window.guCmpHotFix = {};
jest.resetModules();
import('./index.ts');
});
import('./index');
})
.catch(() => {});
});
});
// *************** END commercial.dcr.js hotfix ***************
Expand All @@ -126,7 +138,7 @@ describe('cmp.willShowPrivacyMessage', () => {
expect(
Promise.all([willShowPrivacyMessage1, willShowPrivacyMessage2]),
).resolves.toEqual([true, true]);
});
}).catch(() => {});
});
});

Expand All @@ -138,9 +150,12 @@ describe('cmp.willShowPrivacyMessageSync', () => {
it('does not throw if CMP is initialised', () => {
cmp.init({ country: 'GB' });

cmp.willShowPrivacyMessage().then(() => {
cmp
.willShowPrivacyMessage()
.then(() => {
expect(() => cmp.willShowPrivacyMessageSync()).not.toThrow();
});
})
.catch(() => {});
});
});

Expand All @@ -152,9 +167,12 @@ describe('cmp.hasInitialised', () => {
it('returns true when CMP is initialised', () => {
cmp.init({ country: 'GB' });

cmp.willShowPrivacyMessage().then(() => {
cmp
.willShowPrivacyMessage()
.then(() => {
expect(cmp.hasInitialised()).toBe(true);
});
})
.catch(() => {});
});
});

Expand Down
15 changes: 9 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { CountryCode } from '@guardian/libs';
import { log } from '@guardian/libs';
import { version } from '../package.json';
import { CMP as UnifiedCMP } from './cmp';
import { disable, enable, isDisabled } from './disable';
import { getConsentFor as clientGetConsentFor } from './getConsentFor';
Expand All @@ -18,7 +20,7 @@ import { initVendorDataManager } from './vendorDataManager';
// Store some bits in the global scope for reuse, in case there's more
// than one instance of the CMP on the page in different scopes.
if (!isServerSide) {
window.guCmpHotFix ||= {};
if (typeof window.guCmpHotFix === 'undefined') window.guCmpHotFix = {};
}

let _willShowPrivacyMessage: undefined | boolean;
Expand All @@ -34,11 +36,12 @@ const init: InitCMP = ({ pubData, country }) => {
if (isDisabled() || isServerSide) return;

if (window.guCmpHotFix.initialised) {
if (window.guCmpHotFix.cmp?.version !== __PACKAGE_VERSION__)
if (window.guCmpHotFix.cmp?.version !== version) {
console.warn('Two different versions of the CMP are running:', [
__PACKAGE_VERSION__,
version,
window.guCmpHotFix.cmp?.version,
]);
}
return;
}

Expand All @@ -53,7 +56,7 @@ const init: InitCMP = ({ pubData, country }) => {
);
}

const framework = getFramework(country);
const framework = getFramework(country as CountryCode);

UnifiedCMP.init(framework, pubData ?? {});

Expand Down Expand Up @@ -94,13 +97,13 @@ export const cmp: CMP = isServerSide
willShowPrivacyMessageSync,
hasInitialised,
showPrivacyManager,
version: __PACKAGE_VERSION__,
version: version,

// special helper methods for disabling CMP
__isDisabled: isDisabled,
__enable: enable,
__disable: disable,
});
});

export const onConsent = isServerSide
? serverOnConsent
Expand Down
2 changes: 1 addition & 1 deletion src/onConsent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { ConsentState } from './types';
const onConsent = (): Promise<ConsentState> =>
new Promise<ConsentState>((resolve, reject) => {
onConsentChange((consentState) => {
if (consentState.tcfv2 || consentState.ccpa || consentState.aus) {
if (consentState.tcfv2 ?? consentState.ccpa ?? consentState.aus) {
resolve(consentState);
}
reject('Unknown framework');
Expand Down
3 changes: 2 additions & 1 deletion src/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import replace from '@rollup/plugin-replace';
import strip from '@rollup/plugin-strip';
import typescript from '@rollup/plugin-typescript';
import css from 'rollup-plugin-css-only';
import json from "@rollup/plugin-json";
import pkg from '../package.json';

export default {
Expand All @@ -23,12 +24,12 @@ export default {
],
plugins: [
typescript(),
json(),
css(),
resolve(),
replace({
preventAssignment: true,
'process.env.NODE_ENV': JSON.stringify('production'),
__PACKAGE_VERSION__: JSON.stringify(pkg.version),
}),
commonjs(),
process.env.NODE_ENV === 'production' &&
Expand Down
8 changes: 2 additions & 6 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ export const serverSideWarn = (): void => {
);
};

export const serverSideWarnAndReturn = <T extends unknown>(
arg: T,
): (() => T) => {
export const serverSideWarnAndReturn = <T>(arg: T): (() => T) => {
return () => {
serverSideWarn();
return arg;
Expand Down Expand Up @@ -55,9 +53,7 @@ export const getConsentFor: GetConsentFor = (
consent: ConsentState,
) => {
console.log(
`Server-side call for getConsentFor(${vendor}, ${JSON.stringify(
consent,
)})`,
`Server-side call for getConsentFor(${vendor}, ${JSON.stringify(consent)})`,
'getConsentFor will always return false server-side',
);
serverSideWarn();
Expand Down

0 comments on commit 86c52ba

Please sign in to comment.