// @vitest-environment happy-dom /** * The cookie banner is part of the first render (1.17.0): in the server HTML, decided before the first paint, with * no hydration mismatch — and nothing about consent itself changes: no tag earlier, Consent Mode default first, the * consent log and the stored cookie as before. */ import { act, createElement, type ReactElement } from 'react' import { hydrateRoot, type Root } from 'react-dom/client' import { renderToString } from 'react-dom/server' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import type { ConsentState } from '../src/modules/consent/categories.js' import { Analytics } from '../src/modules/analytics/Analytics.js' import { ConsentProvider } from '../src/modules/consent/ConsentContext.js' import { resetConsentStore } from '../src/modules/consent/consentStore.js' import { CookieBanner } from '../src/modules/consent/CookieBanner.js' import { CookieButton } from '../src/modules/consent/CookieButton.js' import { consentBannerScript } from '../src/modules/consent/firstPaint.js' import { CONSENT_FALLBACK, CONSENT_FALLBACK_PL } from '../src/modules/consent/getConsentTexts.js' import { CONSENT_COOKIE, readConsentRecord, serializeConsent } from '../src/modules/consent/storage.js' import { SiteProviders } from '../src/modules/frontend/SiteProviders.js' const h = createElement as unknown as (type: unknown, props?: null | object, ...children: unknown[]) => ReactElement ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true const ACCEPT: ConsentState = { analytics: true, functional: true, marketing: true, necessary: true } const REJECT: ConsentState = { analytics: false, functional: false, marketing: false, necessary: true } const texts = { ...CONSENT_FALLBACK, version: 3 } const stored = (state: ConsentState, version = 3) => serializeConsent(state, version, 'id-1') type TreeOptions = { analytics?: object; banner?: object; cookieValue?: null | string; gpc?: 'ask' | 'honour' | false; logEndpoint?: string; nonce?: string; texts?: object } const tree = (o: TreeOptions = {}) => h( ConsentProvider, { cookieValue: o.cookieValue, gpc: o.gpc, logEndpoint: o.logEndpoint, nonce: o.nonce, texts: o.texts ?? texts }, h('main', null, 'page'), h(CookieBanner, o.banner ?? {}), h(CookieButton), o.analytics ? h(Analytics, o.analytics) : null, ) const clearCookies = () => { for (const c of document.cookie.split('; ')) { const name = c.split('=')[0] if (name) {document.cookie = `${name}=;path=/;max-age=0`} } } /** Cookies that hold a value (happy-dom keeps a just-expired cookie, emptied, until the second is over). */ const liveCookies = () => document.cookie.split('; ').filter((c) => c.split('=')[1]) const storedRaw = () => liveCookies().find((c) => c.startsWith(`${CONSENT_COOKIE}=`))?.split('=')[1] const setConsentCookie = (value: string) => { document.cookie = `${CONSENT_COOKIE}=${value};path=/` } let container: HTMLDivElement let root: Root | undefined let errors: ReturnType /** Scripts the code under test adds to (never really loaded). */ let injected: string[] beforeEach(() => { clearCookies() resetConsentStore() delete (window as { dataLayer?: unknown[] }).dataLayer delete (window as { fbq?: unknown }).fbq delete (window as { _fbq?: unknown })._fbq container = document.createElement('div') document.body.appendChild(container) errors = vi.spyOn(console, 'error').mockImplementation(() => {}) injected = [] vi.spyOn(document.head, 'appendChild').mockImplementation((node) => { injected.push((node as HTMLScriptElement).src || 'inline') return node }) }) afterEach(() => { if (root) {act(() => root!.unmount())} root = undefined container.remove() vi.restoreAllMocks() vi.unstubAllGlobals() }) const banner = () => container.querySelector('[data-ipal="banner"]') const button = () => container.querySelector('[data-ipal="cookie-button"]') const scriptEl = () => container.querySelector('[data-ipal="banner-script"]') const click = (name: string) => act(() => container.querySelector(`[data-ipal="${name}"]`)!.click()) /** What the browser does while parsing: run the inline script with itself as document.currentScript. */ function runInlineScript(html: string) { const el = scriptEl() // happy-dom gives no text for a script that came in through innerHTML: take it from the HTML itself const code = /]*data-ipal="banner-script"[^>]*>(?.*?)<\/script>/s.exec(html)?.groups?.code if (!el || !code) {return} // eslint-disable-next-line @typescript-eslint/no-implied-eval new Function('document', code)({ get cookie() { return document.cookie }, currentScript: el, }) } /** Server HTML into the page, the inline script as the parser would run it, then hydration. */ function load(o: { blocked?: boolean; serverCookie?: null | string } & TreeOptions = {}) { const node = tree({ ...o, cookieValue: o.serverCookie }) // renderToString never reads document.cookie (the store's server snapshot): see 'the same HTML for every visitor' container.innerHTML = renderToString(node) const html = renderToString(node) if (!o.blocked) {runInlineScript(html)} const beforeHydration = { display: banner()?.style.display, hidden: banner()?.hasAttribute('hidden') } act(() => { root = hydrateRoot(container, node) }) return { beforeHydration, html } } const visibleBeforeHydration = (r: ReturnType) => r.beforeHydration.hidden === false && r.beforeHydration.display !== 'none' describe('server render', () => { test('static page: the banner is in the HTML, hidden, with its script right after it; no button', () => { const html = renderToString(tree()) expect(html).toMatch(/]*data-ipal="banner"[^>]*hidden=""/) expect(html).toContain(CONSENT_FALLBACK.message.slice(0, 40)) expect(html).toMatch(/<\/div>]*data-ipal="banner-script"[^>]*>\(function/) expect(html).toContain('.version===3') expect(html).not.toContain('data-ipal="cookie-button"') // the same HTML for every visitor: nothing in it depends on a cookie setConsentCookie(stored(ACCEPT)) resetConsentStore() expect(renderToString(tree())).toBe(html) }) test('the page language decides the text', () => { const html = renderToString(tree({ texts: { ...CONSENT_FALLBACK_PL, version: 3 } })) expect(html).toContain('Używamy plików cookies') expect(html).toContain('Akceptuj wszystkie') }) test('server-read cookie with a current decision: no banner, no script, the button is in the HTML', () => { const html = renderToString(tree({ cookieValue: stored(REJECT) })) expect(html).not.toContain('data-ipal="banner"') expect(html).not.toContain(' { // the server cannot know Global Privacy Control (a browser signal): with 'honour' the script decides that part const html = renderToString(tree({ cookieValue })) expect(html).toMatch(/]*data-ipal="banner"[^>]*hidden=""/) expect(html).toContain('data-ipal="banner-script"') expect(html).toContain('navigator.globalPrivacyControl===true') expect(html).not.toContain('data-ipal="cookie-button"') // the signal ignored: as before GPC, shown with no script const off = renderToString(tree({ cookieValue, gpc: false })) expect(off).toContain('data-ipal="banner"') expect(off).not.toMatch(/data-ipal="banner"[^>]*hidden/) expect(off).not.toContain(' { const html = renderToString(tree({ banner: { firstPaint: false } })) expect(html).not.toContain('data-ipal="banner"') expect(html).not.toContain(' { expect(renderToString(tree({ nonce: 'n-1' }))).toMatch(/]*nonce="n-1"/) expect(renderToString(tree({ banner: { nonce: 'n-2' }, nonce: 'n-1' }))).toMatch(/]*nonce="n-2"/) }) test('SiteProviders passes its nonce and the optional server-read cookie', () => { const shell = { analytics: {}, consent: texts, jsonLd: [], lightboxTexts: {}, theme: {}, turnstileSiteKey: undefined } const site = (props: object) => renderToString(h(SiteProviders, { analytics: false, preconnect: false, shell, ...props }, h('main', null, 'page'))) expect(site({ nonce: 'n-3' })).toMatch(/]*data-ipal="banner-script"[^>]*nonce="n-3"|]*nonce="n-3"[^>]*data-ipal="banner-script"/) const decided = site({ consentCookie: stored(REJECT) }) expect(decided).not.toContain('data-ipal="banner"') expect(decided).toContain('data-ipal="cookie-button"') expect(site({ consentCookie: null })).toContain('data-ipal="banner-script"') expect(site({ consentCookie: null, gpc: false })).not.toMatch(/data-ipal="banner"[^>]*hidden/) }) }) describe('the first-paint script decides as readConsentRecord does', () => { const run = (cookie: string, version = 3) => { const b = { removeAttribute: (n: string) => void b.removed.push(n), removed: [] as string[], style: {} as Record } // eslint-disable-next-line @typescript-eslint/no-implied-eval new Function('document', consentBannerScript({ version }))({ cookie, currentScript: { previousElementSibling: b } }) return b.style.display === 'none' ? 'hidden' : b.removed.includes('hidden') ? 'shown' : 'untouched' } const raw = (cookie: string) => cookie .split('; ') .find((c) => c.startsWith(`${CONSENT_COOKIE}=`)) ?.split('=')[1] test.each([ ['no cookie at all', ''], ['other cookies only', 'a=1; theme=dark'], ['a current decision', `a=1; ${CONSENT_COOKIE}=${stored(REJECT)}; b=2`], ['a current decision, accept', `${CONSENT_COOKIE}=${stored(ACCEPT)}`], ['an older policy version', `${CONSENT_COOKIE}=${stored(ACCEPT, 2)}`], ['a newer policy version', `${CONSENT_COOKIE}=${stored(ACCEPT, 4)}`], ['version as a string', `${CONSENT_COOKIE}=${encodeURIComponent(JSON.stringify({ state: ACCEPT, version: '3' }))}`], ['malformed JSON', `${CONSENT_COOKIE}=%7Bnope`], ['malformed encoding', `${CONSENT_COOKIE}=%E0%A4%A`], ['empty value', `${CONSENT_COOKIE}=`], ['JSON null', `${CONSENT_COOKIE}=null`], ['a foreign value', `${CONSENT_COOKIE}=accepted`], ['a cookie whose name only ends the same', `x-${CONSENT_COOKIE}=${stored(ACCEPT)}`], ['a cookie whose name only starts the same', `${CONSENT_COOKIE}-old=${stored(ACCEPT)}`], ['no state in the record (read as all refused)', `${CONSENT_COOKIE}=${encodeURIComponent(JSON.stringify({ version: 3 }))}`], ['two cookies of the name: the first counts', `${CONSENT_COOKIE}=bad; ${CONSENT_COOKIE}=${stored(ACCEPT)}`], ])('%s', (_label, cookie) => { const decided = readConsentRecord(raw(cookie), 3) !== null expect(run(cookie)).toBe(decided ? 'hidden' : 'shown') }) test('default version 1; no banner element next to the script: nothing happens, nothing throws', () => { expect(consentBannerScript()).toContain('.version===1') expect(run(`${CONSENT_COOKIE}=${serializeConsent(REJECT)}`, 1)).toBe('hidden') // eslint-disable-next-line @typescript-eslint/no-implied-eval expect(() => new Function('document', consentBannerScript())({ cookie: '', currentScript: null })).not.toThrow() }) test('cannot close its own