Builds the markers, data block and stand-in host for the CMS host injection

The pages carry the CMS markers (data block, list regions, JSON-LD price,
inline price); PackagesProvider reads the host's data block after hydration
and asks the API only when there is none; the site address comes from the
block. A stand-in for the host (config/hostInjector.ts, --cms-data in the
preview server) and browser tests check the behaviour with different data.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 16:21:08 +01:00
co-authored by Claude Sonnet 5.5
parent 16027f5688
commit bf21b6f690
26 changed files with 1207 additions and 70 deletions
+149
View File
@@ -0,0 +1,149 @@
import { describe, expect, it } from 'vitest';
import { injectCms, type LiveData } from './hostInjector.ts';
const AUTHORED = 'https://andreaslop.nl';
const page = (inner: string) => `<html><body>${inner}</body></html>`;
const pakket = (slug: string, price: string, extra = {}) => ({
slug,
title: slug.toUpperCase(),
price,
features: ['a'],
displayOrder: 0,
...extra,
});
const live = (
offerings: unknown,
banners: LiveData['banners'] = { top: null, bottom: null },
): LiveData => ({ offerings, banners });
const run = (html: string, data: LiveData, publicBaseUrl?: string) =>
injectCms(html, { data, authoredBaseUrl: AUTHORED, publicBaseUrl });
describe('injectCms regions', () => {
const region = (name: string) =>
`<!--CMS:${name}-->baked<!--/CMS:${name}-->`;
it('writes the lists between the markers and keeps the markers', () => {
const out = run(
page(
region('OFFERINGS-HTML') +
region('BANNER-TOP-HTML') +
region('BANNER-BOTTOM-HTML'),
),
live([pakket('newborn', '€ 185')], {
top: { text: 'Boven' },
bottom: { title: 'Onder' },
}),
);
expect(out).toContain(
'<!--CMS:OFFERINGS-HTML--><ul class="cms-offerings">',
);
expect(out).toContain('€&nbsp;185');
expect(out).toContain('<!--CMS:BANNER-TOP-HTML--><aside');
expect(out).toContain('<span>Boven</span>');
expect(out).toContain('<strong>Onder</strong>');
expect(out).toContain('<!--/CMS:BANNER-BOTTOM-HTML-->');
expect(out).not.toContain('baked');
});
it('empties a region without data', () => {
const out = run(page(region('OFFERINGS-HTML')), live([]));
expect(out).toContain(
'<!--CMS:OFFERINGS-HTML--><!--/CMS:OFFERINGS-HTML-->',
);
});
});
describe('injectCms data block', () => {
const baked =
'<!--CMS:DATA--><script type="application/json" id="cms-data">{"source":"build"}</script>';
it('replaces the marker and the baked block by the live one, with the address', () => {
const out = run(
page(baked),
live([pakket('x', '€ 5')]),
'https://t.nl',
);
expect(out).not.toContain('"source"');
const json = /id="cms-data">(.*?)<\/script>/.exec(out)?.[1] ?? '';
expect(JSON.parse(json)).toMatchObject({
siteUrl: 'https://t.nl',
offerings: [{ slug: 'x' }],
banners: { top: null, bottom: null },
});
});
it('writes the block in place of a lone marker, and escapes it', () => {
const out = run(
page('<!--CMS:DATA-->'),
live([pakket('x', '€ 5', { title: '</script><b>' })]),
);
expect(out).toContain('<script type="application/json" id="cms-data">');
expect(out.match(/<\/script>/g)).toHaveLength(1);
expect(out).toContain('\\u003c/script\\u003e');
});
});
describe('injectCms JSON-LD and prices', () => {
const ld = (offers: unknown) =>
`<!--CMS:OFFER-JSON-LD slug="newborn"--><script type="application/ld+json">${JSON.stringify(
{ '@graph': [{ '@type': 'Service', offers }] },
)}</script>`;
it('sets the price of the package', () => {
const out = run(
page(ld({ '@type': 'Offer', price: 1, priceCurrency: 'EUR' })),
live([pakket('newborn', '€ 1.250')]),
);
expect(out).toContain('"price":1250');
expect(out).toContain('"priceCurrency":"EUR"');
expect(out).not.toContain('CMS:OFFER-JSON-LD');
});
it('removes offers when the package is gone or has no readable price', () => {
for (const offerings of [
[pakket('gezin', '€ 1')],
[pakket('newborn', 'op aanvraag')],
]) {
const out = run(page(ld({ price: 1 })), live(offerings));
expect(out).not.toContain('offers');
}
});
it('leaves a block that is not JSON as it is', () => {
const broken =
'<!--CMS:OFFER-JSON-LD slug="newborn"--><script type="application/ld+json">{kapot</script>';
expect(run(page(broken), live([]))).toContain(broken);
});
it('sets the text of an inline price and leaves unknown slugs alone', () => {
const out = run(
page(
'<span data-cms-price="newborn" x>€ 1</span><span data-cms-price="onbekend">€ 9</span>',
),
live([pakket('newborn', '€ 185')]),
);
expect(out).toContain(
'<span data-cms-price="newborn" x>€ 185</span>'.replace(
'€ ',
'€' + String.fromCharCode(160),
),
);
expect(out).toContain('<span data-cms-price="onbekend">€ 9</span>');
});
});
describe('injectCms address', () => {
it('replaces the written address everywhere when another one is set', () => {
const html = page(`<link href="${AUTHORED}/a"><i>${AUTHORED}/b</i>`);
const out = run(html, live([]), 'https://t.nl');
expect(out).not.toContain(AUTHORED);
expect(out.match(/https:\/\/t\.nl/g)).toHaveLength(2);
});
it('leaves it when none is set or it is the same', () => {
const html = page(`<i>${AUTHORED}/b</i>`);
expect(run(html, live([]))).toBe(html);
expect(run(html, live([]), AUTHORED)).toBe(html);
});
});
+116
View File
@@ -0,0 +1,116 @@
// A stand-in for what the CMS host does to a prerendered page: it fills the CMS
// markers from live data (the contract is in aidlc-docs/features/
// asf-cms-host-injection/plan.md and contract/host-injection). The real
// injector is C# in the CMS repo; this one lets the preview server and the
// browser tests show how the site behaves when a host rewrites the HTML, so
// hydration, fail-safe behaviour and layout can be checked without a host.
// It uses the site's own mapping and HTML code, so it proves the page copes
// with what the host writes; the golden files prove the host's template
// matches that code.
import { bannerHtml, offeringsHtml } from '../src/lib/cmsHtml.ts';
import { scriptJson } from '../src/lib/cmsData.ts';
import { formatPrice } from '../src/lib/formatPrice.ts';
import { mapBanner, mapOfferings, mapTopBanner } from '../src/lib/offerings.ts';
export interface LiveData {
// The answers as the public API gives them
offerings: unknown;
banners: { top: unknown; bottom: unknown };
}
export interface InjectOptions {
data: LiveData;
// The address the build was written with and the one to show instead
authoredBaseUrl?: string;
publicBaseUrl?: string;
}
// ld+json that cannot close its script element (same rule as the site's)
const jsonLd = (value: unknown) =>
JSON.stringify(value)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026');
const REGION =
/<!--CMS:(OFFERINGS-HTML|BANNER-TOP-HTML|BANNER-BOTTOM-HTML)-->[\s\S]*?<!--\/CMS:\1-->/g;
const DATA_BLOCK =
/<!--CMS:DATA-->(?:<script type="application\/json" id="cms-data">[\s\S]*?<\/script>)?/g;
const OFFER_JSON_LD =
/<!--CMS:OFFER-JSON-LD slug="([a-z0-9-]+)"--><script type="application\/ld\+json">([\s\S]*?)<\/script>/g;
const PRICE_SPAN =
/(<span data-cms-price="([a-z0-9-]+)"[^>]*>)[^<]*(<\/span>)/g;
type Price = Map<string, number>;
// Sets or removes offers on every node of a JSON-LD value that has them
function editOffers(value: unknown, price: number | undefined): void {
if (Array.isArray(value)) {
for (const item of value) editOffers(item, price);
return;
}
if (typeof value !== 'object' || value === null) return;
const node = value as Record<string, unknown>;
if ('offers' in node) {
if (price === undefined) delete node.offers;
else {
node.offers = { ...(node.offers as object), price };
}
}
for (const child of Object.values(node)) editOffers(child, price);
}
export function injectCms(html: string, options: InjectOptions): string {
const { data } = options;
const mapped = mapOfferings(data.offerings);
const packages = mapped ? mapped.packages : [];
const prices: Price = new Map(packages.map((pkg) => [pkg.id, pkg.price]));
const regions: Record<string, string> = {
'OFFERINGS-HTML': offeringsHtml(packages),
'BANNER-TOP-HTML': bannerHtml(mapTopBanner(data.banners.top)),
'BANNER-BOTTOM-HTML': bannerHtml(mapBanner(data.banners.bottom)),
};
const siteUrl = options.publicBaseUrl ?? options.authoredBaseUrl;
let out = html
.replace(
REGION,
(_match, name: string) =>
`<!--CMS:${name}-->${regions[name]}<!--/CMS:${name}-->`,
)
.replace(
DATA_BLOCK,
() =>
'<!--CMS:DATA-->' +
`<script type="application/json" id="cms-data">${scriptJson({
...(siteUrl ? { siteUrl } : {}),
offerings: data.offerings,
banners: data.banners,
})}</script>`,
)
.replace(OFFER_JSON_LD, (match, slug: string, json: string) => {
let parsed: unknown;
try {
parsed = JSON.parse(json);
} catch {
return match;
}
editOffers(parsed, prices.get(slug));
return `<script type="application/ld+json">${jsonLd(parsed)}</script>`;
})
.replace(
PRICE_SPAN,
(match, open: string, slug: string, close: string) => {
const price = prices.get(slug);
return price === undefined
? match
: `${open}${formatPrice(price)}${close}`;
},
);
const { authoredBaseUrl, publicBaseUrl } = options;
if (authoredBaseUrl && publicBaseUrl && authoredBaseUrl !== publicBaseUrl) {
out = out.split(authoredBaseUrl).join(publicBaseUrl);
}
return out;
}
+42 -2
View File
@@ -8,7 +8,7 @@
// slash aan het eind krijgen één 301 (BR-HST-03, 04). /404.html is een echte
// 404; Lighthouse auditeert de 404-pagina via de opt-in route /__audit/404
// (--audit-route, BR-HST-22).
import { createReadStream, statSync } from 'node:fs';
import { createReadStream, readFileSync, statSync } from 'node:fs';
import {
createServer,
type IncomingMessage,
@@ -18,6 +18,7 @@ import {
import { extname, join, resolve, sep, win32 } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createGzip } from 'node:zlib';
import { injectCms, type InjectOptions } from './hostInjector.ts';
import { canonicalRedirect, stripTrailingSlashes } from './canonicalUrls.ts';
import {
compressibleExtensions,
@@ -197,6 +198,10 @@ export interface PreviewOptions {
// 202. Productie gebruikt dit nooit; tests kunnen het per pagina met
// page.route vervangen (bijvoorbeeld 404 of een captcha).
contactStub?: boolean;
// Opt-in stand-in for the CMS host's injection (--cms-data=<json file>):
// called for every HTML page; the answer is what the host would write into
// the markers (see hostInjector.ts), null serves the page as built.
inject?: () => InjectOptions | null;
}
const CONTACT_API = '/api/v1/contact-messages';
@@ -307,6 +312,21 @@ export function startPreviewServer(
);
return;
}
const injection = file.endsWith('.html') ? options.inject?.() : null;
if (injection) {
const body = injectCms(readFileSync(target, 'utf8'), injection);
send(
response,
status,
{
'Content-Type': contentTypeOf(file),
'Cache-Control': 'no-cache',
'Content-Length': Buffer.byteLength(body),
},
request.method === 'HEAD' ? null : body,
);
return;
}
const headers: Record<string, string | number> = {
'Content-Type': contentTypeOf(file),
};
@@ -346,6 +366,7 @@ function parseArguments(args: string[]) {
dir: 'dist/client',
auditRoute: false,
contactStub: false,
cmsData: '',
};
for (let i = 0; i < args.length; i++) {
const [name, inline] = args[i].split('=', 2);
@@ -355,6 +376,7 @@ function parseArguments(args: string[]) {
else if (name === '--strictPort') options.strictPort = true;
else if (name === '--audit-route') options.auditRoute = true;
else if (name === '--contact-stub') options.contactStub = true;
else if (name === '--cms-data') options.cmsData = value();
}
return options;
}
@@ -362,7 +384,7 @@ function parseArguments(args: string[]) {
const MAX_PORT_TRIES = 10;
async function main(args: string[]) {
const { port, strictPort, dir, auditRoute, contactStub } =
const { port, strictPort, dir, auditRoute, contactStub, cmsData } =
parseArguments(args);
if (!Number.isInteger(port) || port < 0 || port > 65535) {
console.error(`Ongeldige poort: ${port}`);
@@ -377,6 +399,24 @@ async function main(args: string[]) {
const server = await startPreviewServer(dir, port + attempt, {
auditRoute,
contactStub,
// Read again for every page, so the file can change while the
// server runs: { offerings, banners, publicBaseUrl? }
...(cmsData
? {
inject: () => {
const file = JSON.parse(
readFileSync(cmsData, 'utf8'),
) as InjectOptions['data'] & {
publicBaseUrl?: string;
};
return {
data: file,
authoredBaseUrl: 'https://andreaslop.nl',
publicBaseUrl: file.publicBaseUrl,
};
},
}
: {}),
});
const address = server.address();
const actual =
+339
View File
@@ -0,0 +1,339 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import type { LiveData } from '../config/hostInjector.ts';
import {
eventually,
openPage,
waitForHydration,
type OpenedPage,
} from './support/browser.ts';
import { startServer } from './support/server.ts';
// De CMS-host vult markers in de geprerenderde HTML (plan: aidlc-docs/features/
// asf-cms-host-injection). Hier doet de previewserver alsof hij die host is
// (config/hostInjector.ts), met data die van de gebakken data afwijkt. Wat
// getest wordt: de HTML die de host schrijft is leesbaar zonder JavaScript,
// de pagina hydrateert zonder fout, toont daarna de actuele data zonder zelf
// de API te vragen, en valt terug op wat gebakken is als de data niet bruikbaar
// is.
const AUTHORED = 'https://andreaslop.nl';
let live: { data: LiveData; publicBaseUrl?: string } | null = null;
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer({
inject: () =>
live && {
data: live.data,
authoredBaseUrl: AUTHORED,
publicBaseUrl: live.publicBaseUrl,
},
});
});
afterAll(() => server.close());
const pakket = (
slug: string,
title: string,
price: string,
order: number,
extra: Record<string, unknown> = {},
) => ({
slug,
title,
price,
features: [`Kenmerk van ${title}`],
displayOrder: order,
...extra,
});
const FIVE = [
pakket('zwangerschap', 'Zwangerschap', '€ 200', 0),
pakket('newborn', 'Newborn', '€ 210', 1, { featured: true }),
pakket('gezin', 'Gezin', '€ 220', 2),
pakket('loveshoot', 'Loveshoot', '€ 230', 3),
pakket('portret', 'Portret', '€ 240', 4),
];
const NO_BANNERS = { top: null, bottom: null };
const html = async (path: string) => (await fetch(server.origin + path)).text();
const cards = (page: OpenedPage['page']) =>
page.locator('[data-testid^="price-card-"]:not([data-testid$="-book"])');
// Elke test begint zonder injectie en zet live zelf
const inject = (data: LiveData, publicBaseUrl?: string) => {
live = { data, publicBaseUrl };
};
describe('markers in de gebouwde pagina', () => {
it('heeft ze op de plekken van het contract, en niet op andere', async () => {
live = null;
const home = await html('/');
for (const marker of [
'OFFERINGS-HTML',
'BANNER-TOP-HTML',
'BANNER-BOTTOM-HTML',
]) {
expect(home.split(`<!--CMS:${marker}-->`)).toHaveLength(2);
expect(home.split(`<!--/CMS:${marker}-->`)).toHaveLength(2);
}
for (const path of [
'/',
'/over-mij',
'/contact',
'/soorten-fotoshoots',
]) {
const page = await html(path);
expect(page.split('<!--CMS:DATA-->')).toHaveLength(2);
expect(page).toMatch(
/<!--CMS:DATA--><script type="application\/json" id="cms-data">\{/,
);
}
// Prijs-JSON-LD en inline prijs alleen op de pakketpagina's
for (const slug of ['newborn', 'zwangerschap', 'gezin']) {
const page = await html(`/soorten-fotoshoots/${slug}`);
expect(page).toContain(
`<!--CMS:OFFER-JSON-LD slug="${slug}"--><script type="application/ld+json">`,
);
expect(page).toContain(`data-cms-price="${slug}"`);
}
for (const slug of ['loveshoot', 'portret']) {
const page = await html(`/soorten-fotoshoots/${slug}`);
expect(page).not.toContain('CMS:OFFER-JSON-LD');
expect(page).not.toContain('data-cms-price');
}
});
});
describe('met data van de host die afwijkt van de build', () => {
it('schrijft leesbare HTML zonder JavaScript', async () => {
inject({
offerings: FIVE,
banners: {
top: {
title: 'Nieuw',
text: 'Nog twee plekken',
position: 'top',
},
bottom: { title: 'Onder', position: 'bottom' },
},
});
const home = await html('/');
// Eén pakket per kaart met de nieuwe prijs, de uitgelichte gemarkeerd
for (const price of ['200', '210', '220', '230', '240']) {
expect(home).toContain(`€&nbsp;${price}`);
}
expect(home).toContain('data-slug="newborn" data-featured="true"');
expect(home).toContain('<strong>Nieuw</strong>');
expect(home).toContain('<strong>Onder</strong>');
// De gebakken prijs (175) staat er niet meer in de lijst
const list = home.slice(
home.indexOf('<!--CMS:OFFERINGS-HTML-->'),
home.indexOf('<!--/CMS:OFFERINGS-HTML-->'),
);
expect(list).not.toContain('175');
});
it('hydrateert zonder fout en toont daarna de actuele data zonder API-verzoek', async () => {
inject({
offerings: FIVE,
banners: {
top: { title: '', text: 'Nog twee plekken', position: 'top' },
bottom: { title: 'Onder', text: 't', position: 'bottom' },
},
});
const requested: string[] = [];
const { page, messages } = await openPage(server.origin + '/', {
prepare: async (p) => {
p.on('request', (request) => {
if (request.url().includes('/api/v1/offerings')) {
requested.push(request.url());
}
});
},
});
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(5);
expect(await cards(page).first().textContent()).toContain('€\u00a0200');
expect(await page.locator('.cms-offerings').count()).toBe(0);
expect(await page.getByTestId('price-top-bar').textContent()).toContain(
'Nog twee plekken',
);
expect(await page.getByTestId('price-banner').textContent()).toContain(
'Onder',
);
// De uitgelichte kaart is gemarkeerd
expect(await page.locator('[data-featured="true"]').count()).toBe(1);
// Het datablok is er: de site vraagt de API niet zelf
expect(requested).toEqual([]);
expect(messages).toEqual([]);
});
it('verbergt de banners als de host geen actieve heeft (204)', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS });
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(5);
expect(await page.getByTestId('price-top-bar').count()).toBe(0);
expect(await page.getByTestId('price-banner').count()).toBe(0);
expect(messages).toEqual([]);
});
it('verbergt de sectie als de host alle pakketten heeft uitgezet', async () => {
inject({ offerings: [], banners: NO_BANNERS });
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => page.getByTestId('pricing').count()).toBe(0);
expect(messages).toEqual([]);
});
it('past de formulierkeuze aan op de data van de host', async () => {
inject({ offerings: FIVE, banners: NO_BANNERS });
const { page, messages } = await openPage(
server.origin + '/contact?pakket=portret',
);
await waitForHydration(page);
await eventually(() =>
page.getByTestId('contact-form-shoot').locator('option').count(),
).toBe(7); // Kies een optie, vijf pakketten, Overig
expect(messages).toEqual([]);
});
it('zet de prijs op de pakketpagina in de HTML, in de JSON-LD en na hydratatie', async () => {
inject({
offerings: [pakket('newborn', 'Newborn', '€ 1.250', 0)],
banners: NO_BANNERS,
});
const raw = await html('/soorten-fotoshoots/newborn');
expect(raw).toMatch(/data-cms-price="newborn"[^>]*>€\u00a01\.250</);
expect(raw).toContain('"price":1250');
const { page, messages } = await openPage(
server.origin + '/soorten-fotoshoots/newborn',
);
await waitForHydration(page);
await eventually(() =>
page.locator('[data-cms-price="newborn"]').textContent(),
).toBe('€\u00a01.250');
const prices = await page.evaluate(() =>
[...document.querySelectorAll('script[type="application/ld+json"]')]
.map((script) => JSON.parse(script.textContent ?? ''))
.flatMap(
(data) => JSON.stringify(data).match(/"price":\d+/g) ?? [],
),
);
expect(prices).toEqual(['"price":1250']);
expect(messages).toEqual([]);
});
it('haalt de prijs uit de JSON-LD als het pakket niet meer bestaat', async () => {
inject({
offerings: [pakket('gezin', 'Gezin', '€ 220', 0)],
banners: NO_BANNERS,
});
const raw = await html('/soorten-fotoshoots/newborn');
expect(raw).not.toContain('"offers"');
// Het pakket dat er nog wel is houdt zijn prijs
expect(await html('/soorten-fotoshoots/gezin')).toContain(
'"price":220',
);
});
});
describe('adres van de site', () => {
it('zet canonical, og: en JSON-LD op het adres van de host, ook na navigatie', async () => {
inject(
{ offerings: FIVE, banners: NO_BANNERS },
'https://test.voorbeeld.nl',
);
const raw = await html('/');
expect(raw).not.toContain(AUTHORED);
expect(raw).toContain(
'rel="canonical" href="https://test.voorbeeld.nl/"',
);
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
// Navigeren binnen de site: de head wordt opnieuw opgebouwd en moet het
// adres uit het datablok gebruiken, niet het gebakken productie-adres
await page.getByRole('link', { name: 'Over mij' }).first().click();
await eventually(() => page.title()).toContain('Over mij');
expect(
await page.locator('link[rel="canonical"]').getAttribute('href'),
).toBe('https://test.voorbeeld.nl/over-mij');
expect(
await page
.locator('meta[property="og:image"]')
.getAttribute('content'),
).toMatch(/^https:\/\/test\.voorbeeld\.nl\//);
expect(messages).toEqual([]);
});
});
describe('als de data niet bruikbaar is', () => {
it('toont wat gebakken is bij een datablok zonder bruikbare lijst', async () => {
// De host schreef een blok waar geen lijst in staat. De site gelooft
// dat niet en houdt de gebakken pakketten (zonder fout).
inject({ offerings: 'kapot', banners: NO_BANNERS });
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(3);
expect(messages).toEqual([]);
});
it('vangt vijandige tekst op: geen script, wel de tekst', async () => {
inject({
offerings: [
pakket(
'newborn',
'<img src=x onerror="window.pwned=1">',
'€ 200',
0,
{
features: ['<script>window.pwned=1</script>'],
},
),
],
banners: {
top: null,
bottom: { title: '<b onmouseover=1>x</b>', position: 'bottom' },
},
});
const raw = await html('/');
expect(raw).not.toContain('<img src=x');
expect(raw).not.toContain('<script>window.pwned');
const { page, messages } = await openPage(server.origin + '/');
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(1);
expect(await page.evaluate(() => 'pwned' in window)).toBe(false);
expect(await cards(page).first().textContent()).toContain(
'<img src=x onerror="window.pwned=1">',
);
expect(messages).toEqual([]);
});
});
describe('zonder host die injecteert', () => {
it('toont de gebakken pakketten en vraagt de API zelf, zoals voor de injectie', async () => {
live = null;
const requested: string[] = [];
const { page, messages } = await openPage(server.origin + '/', {
prepare: async (p) => {
p.on('request', (request) => {
if (request.url().includes('/api/v1/offerings')) {
requested.push(new URL(request.url()).pathname);
}
});
},
});
await waitForHydration(page);
await eventually(() => cards(page).count()).toBe(3);
await eventually(async () => requested.length).toBe(3);
// Het blok dat de build schreef telt niet als data van de host
expect(requested.sort()).toEqual([
'/api/v1/offerings',
'/api/v1/offerings/banner',
'/api/v1/offerings/banner',
]);
expect(messages).toEqual([]);
});
});
+5 -1
View File
@@ -1,5 +1,6 @@
import type { AddressInfo } from 'node:net';
import { resolve } from 'node:path';
import type { InjectOptions } from '../../config/hostInjector.ts';
import { startPreviewServer } from '../../config/previewServer.ts';
// De gebouwde site: `pnpm build` schrijft hem, de tests bouwen niets. Relatief
@@ -12,7 +13,10 @@ export const clientDir = resolve('dist/client');
// auditRoute zet de opt-in route /__audit/404 aan, zoals Lighthouse hem start.
// De contact-API wordt standaard nagebootst (CI heeft geen CMS-host); een
// test die iets anders nodig heeft vervangt het met page.route.
export async function startServer(options: { auditRoute?: boolean } = {}) {
// inject laat de server doen alsof de CMS-host de markers vult (hostInjector)
export async function startServer(
options: { auditRoute?: boolean; inject?: () => InjectOptions | null } = {},
) {
const server = await startPreviewServer(clientDir, 0, {
contactStub: true,
...options,
+7
View File
@@ -1,13 +1,20 @@
import { StrictMode, startTransition } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { StartClient } from '@tanstack/react-start/client';
import { readCmsData } from './lib/cmsData';
import { startSentry } from './monitoring/sentry';
import { setSiteUrl } from './seo';
// Foutmeldingen naar Sentry, alleen op test en productie (M1). Dit bestand
// draait alleen in de browser, dus niet tijdens het prerenderen, en loopt voor
// op het hydrateren zodat ook vroege fouten gemeld worden.
startSentry();
// The CMS host writes the address of the site it serves into the data block;
// the script files cannot carry it. Without a block the built-in one stays.
const page = readCmsData(document);
if (page?.siteUrl) setSiteUrl(page.siteUrl);
startTransition(() => {
hydrateRoot(
document,
@@ -0,0 +1,24 @@
import packages, { banner, topBanner } from '@/content/packages';
import { bakedCmsData, CMS_DATA_ID, scriptJson } from '@/lib/cmsData';
import { siteUrl } from '@/seo';
// The data block of the page, in the root document: <!--CMS:DATA--> followed
// by the JSON of the packages and banners the build baked. The CMS host
// replaces the pair with the current data; the browser reads it after
// hydration (PackagesProvider) and the address from it before (client.tsx).
// Hidden and never hydrated: the host's block differs from the baked one.
export default function CmsDataIsland() {
const json = scriptJson(bakedCmsData(siteUrl, packages, banner, topBanner));
return (
<div
hidden
data-cms-island
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html:
'<!--CMS:DATA-->' +
`<script type="application/json" id="${CMS_DATA_ID}">${json}</script>`,
}}
/>
);
}
@@ -0,0 +1,51 @@
import { renderToString } from 'react-dom/server';
import { screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { renderWithProviders } from '@/test/renderWithProviders';
import CmsDataIsland from './CmsDataIsland';
import CmsRegion from './CmsRegion';
describe('CmsRegion', () => {
it('is plain HTML between two markers on the server', () => {
const html = renderToString(
<CmsRegion name="OFFERINGS-HTML" html="<ul><li>x</li></ul>">
<p>gestijld</p>
</CmsRegion>,
);
expect(html).toContain(
'<!--CMS:OFFERINGS-HTML--><ul><li>x</li></ul><!--/CMS:OFFERINGS-HTML-->',
);
expect(html).not.toContain('gestijld');
});
it('shows the styled content once it runs in the browser', async () => {
await renderWithProviders(
<CmsRegion name="OFFERINGS-HTML" html="<ul></ul>">
<p>gestijld</p>
</CmsRegion>,
);
expect(screen.getByText('gestijld')).toBeInTheDocument();
});
});
describe('CmsDataIsland', () => {
it('writes the marker and the baked block, hidden, with the build as source', () => {
const html = renderToString(<CmsDataIsland />);
expect(html).toMatch(
/<div hidden="" data-cms-island="true"><!--CMS:DATA--><script type="application\/json" id="cms-data">\{/,
);
const json = /id="cms-data">(.*?)<\/script>/.exec(html)?.[1] ?? '';
const data = JSON.parse(json) as {
source: string;
siteUrl: string;
offerings: unknown[];
banners: object;
};
expect(data.source).toBe('build');
expect(data.siteUrl).toBe('https://andreaslop.nl');
expect(data.offerings.length).toBeGreaterThan(0);
expect(Object.keys(data.banners)).toEqual(['top', 'bottom']);
// Nothing in it can end the script element
expect(json).not.toMatch(/[<>&]/);
});
});
@@ -0,0 +1,32 @@
import type { ReactNode } from 'react';
import useHydrated from '@/hooks/useHydrated';
import { regionMarkers } from '@/lib/cmsHtml';
type CmsRegionProps = {
// Marker name, for example "OFFERINGS-HTML": <!--CMS:OFFERINGS-HTML-->
name: string;
// The plain HTML of the data the page was built with (lib/cmsHtml); the
// CMS host replaces it with the same markup from the current data
html: string;
// What the visitor gets once the page has hydrated: the styled
// components, built from the current data
children: ReactNode;
};
// A part of the page that the CMS host may rewrite before it sends the HTML
// (packages, banners). Until hydration it is plain HTML between two marker
// comments, which React leaves alone (a host that wrote different data would
// otherwise cause a hydration mismatch). After hydration the styled
// components replace it. React cannot write comments, so the markers go in
// through dangerouslySetInnerHTML; the html is escaped by lib/cmsHtml and
// never contains anything but what that escapes.
export default function CmsRegion({ name, html, children }: CmsRegionProps) {
if (useHydrated()) return <>{children}</>;
return (
<div
data-cms-region={name}
suppressHydrationWarning
dangerouslySetInnerHTML={{ __html: regionMarkers(name, html) }}
/>
);
}
@@ -56,7 +56,16 @@ export default function PackageBlock({
color="accent.deep"
mt={4}
>
{pkg ? formatPrice(pkg.price) : onRequest.price}
{pkg ? (
// CMS data: the host rewrites the text of this span in the
// HTML it sends, so a different text is not a hydration
// error
<span data-cms-price={pkg.id} suppressHydrationWarning>
{formatPrice(pkg.price)}
</span>
) : (
onRequest.price
)}
</Text>
{pkg ? (
<Box as="ul" role="list" listStyle="none" m={0} p={0} mt={5}>
@@ -191,3 +191,67 @@ describe('PackagesProvider', () => {
expect(signals.every((signal) => signal.aborted)).toBe(true);
});
});
describe('the data block of the CMS host', () => {
const putBlock = (json: string) => {
const script = document.createElement('script');
script.type = 'application/json';
script.id = 'cms-data';
script.textContent = json;
document.body.append(script);
return () => script.remove();
};
it('is shown without asking the API', async () => {
const remove = putBlock(
JSON.stringify({
offerings: card('€ 333'),
banners: { top: { text: 'Van de host' }, bottom: null },
}),
);
try {
const load = fake({ offerings: card('€ 999') });
await show(load);
await waitFor(() =>
expect(screen.getByText('Newborn 333')).toBeInTheDocument(),
);
expect(screen.getByTestId('top')).toHaveTextContent('Van de host');
expect(screen.getByTestId('banner')).toHaveTextContent(
'geen banner',
);
expect(load).not.toHaveBeenCalled();
} finally {
remove();
}
});
it('is not trusted when it is the one the build baked: the API is asked', async () => {
const remove = putBlock(
JSON.stringify({ source: 'build', offerings: card('€ 111') }),
);
try {
const load = fake({ offerings: card('€ 222') });
await show(load);
await waitFor(() =>
expect(screen.getByText('Newborn 222')).toBeInTheDocument(),
);
expect(load).toHaveBeenCalled();
} finally {
remove();
}
});
it('keeps the baked data for a block that cannot be read', async () => {
const remove = putBlock('niet json');
try {
await show(fake({ offerings: undefined }));
expect(
screen.getByText(
`${bakedPackages[0].name} ${bakedPackages[0].price}`,
),
).toBeInTheDocument();
} finally {
remove();
}
});
});
@@ -9,6 +9,8 @@ import type {
PricingPackage,
PricingTopBanner,
} from '@/content/types';
import useHydrated from '@/hooks/useHydrated';
import { hostCmsData, liveFromData } from '@/lib/cmsData';
import { mapBanner, mapOfferings, mapTopBanner } from '@/lib/offerings';
// The shoot packages and the announcement banner the pages show. The build
@@ -81,8 +83,19 @@ export default function PackagesProvider({
load = loadFromApi,
}: PackagesProviderProps) {
const [live, setLive] = useState<Live>(baked);
// The data block the CMS host wrote into the page, read in the first render
// after hydration (not before: the HTML the server rendered used the baked
// data, and hydration must see the same). Without a block (preview, tests,
// a host that does not inject) the page asks the CMS instead, below.
const hydrated = useHydrated();
const fromBlock = useMemo(
() => (hydrated ? liveFromData(hostCmsData(document)) : null),
[hydrated],
);
useEffect(() => {
// The host sent the data: nothing to ask
if (hostCmsData(document)) return;
const controller = new AbortController();
const { signal } = controller;
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
@@ -130,7 +143,10 @@ export default function PackagesProvider({
};
}, [load]);
const value = useMemo(() => live, [live]);
const value = useMemo(
() => (fromBlock ? { ...live, ...fromBlock } : live),
[live, fromBlock],
);
return (
<LiveContext.Provider value={value}>{children}</LiveContext.Provider>
);
@@ -2,13 +2,36 @@ import { jsonLdScript } from '@/seo';
type StructuredDataProps = {
data: unknown;
// The package whose price is in this data: marks the block for the CMS
// host, which keeps offers.price current (<!--CMS:OFFER-JSON-LD-->)
offerSlug?: string;
};
// One object of structured data as an ld+json script in the page. This is
// the only place the shoot pages use dangerouslySetInnerHTML, and only with
// jsonLdScript's output: it escapes <, > and &, so content can never close
// the script element (SECURITY-04, SECURITY-11).
export default function StructuredData({ data }: StructuredDataProps) {
export default function StructuredData({
data,
offerSlug,
}: StructuredDataProps) {
if (offerSlug !== undefined) {
// The marker has to sit directly before the script, and React cannot
// write comments, so both go in through one hidden wrapper. The slug is
// checked: it comes from our own routes, never from the CMS.
const slug = /^[a-z0-9-]+$/.test(offerSlug) ? offerSlug : '';
return (
<div
hidden
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html:
`<!--CMS:OFFER-JSON-LD slug="${slug}"-->` +
`<script type="application/ld+json">${jsonLdScript(data)}</script>`,
}}
/>
);
}
return (
<script
type="application/ld+json"
+49 -32
View File
@@ -1,4 +1,5 @@
import { Box, Flex } from '@chakra-ui/react';
import CmsRegion from '@/components/CmsRegion/CmsRegion';
import DeferredImage from '@/components/DeferredImage/DeferredImage';
import PageSection from '@/components/PageSection/PageSection';
import Reveal from '@/components/Reveal/Reveal';
@@ -9,6 +10,7 @@ import type {
PricingPackage,
PricingTopBanner,
} from '@/content/types';
import { bannerHtml, offeringsHtml } from '@/lib/cmsHtml';
import { visiblePackages } from '@/lib/visiblePackages';
import PriceBanner from './PriceBanner';
import PriceCard from './PriceCard';
@@ -77,44 +79,59 @@ export default function Pricing({
lead={content.lead}
/>
</Reveal>
{topBanner && (
<Reveal>
<PriceTopBar banner={topBanner} />
</Reveal>
)}
{/* Packages and banners are CMS data: the CMS host may rewrite
them in the HTML it sends (CmsRegion), so they are plain
HTML until the page has hydrated */}
<CmsRegion
name="BANNER-TOP-HTML"
html={bannerHtml(topBanner ?? null)}
>
{topBanner && (
<Reveal>
<PriceTopBar banner={topBanner} />
</Reveal>
)}
</CmsRegion>
{/* Wrapping flex, not a grid: a grid leaves the last row at
the left. Every card is exactly a third of the row minus
the gaps, so the cards of a full row line up and an
incomplete last row is centred. */}
<Flex
direction={{ base: 'column', lg: 'row' }}
wrap={{ base: 'nowrap', lg: 'wrap' }}
justify="center"
gap="gridGap"
maxW={{ base: '460px', lg: 'none' }}
mx="auto"
<CmsRegion name="OFFERINGS-HTML" html={offeringsHtml(shown)}>
<Flex
direction={{ base: 'column', lg: 'row' }}
wrap={{ base: 'nowrap', lg: 'wrap' }}
justify="center"
gap="gridGap"
maxW={{ base: '460px', lg: 'none' }}
mx="auto"
>
{shown.map((pkg, index) => (
<Reveal
key={pkg.id}
delay={index * STAGGER}
w={{
base: '100%',
lg: 'calc((100% - 2 * {spacing.gridGap}) / 3)',
}}
>
<PriceCard pkg={pkg} />
</Reveal>
))}
</Flex>
</CmsRegion>
<CmsRegion
name="BANNER-BOTTOM-HTML"
html={bannerHtml(banner ?? null)}
>
{shown.map((pkg, index) => (
<Reveal
key={pkg.id}
delay={index * STAGGER}
w={{
base: '100%',
lg: 'calc((100% - 2 * {spacing.gridGap}) / 3)',
}}
>
<PriceCard pkg={pkg} />
{banner && (
<Reveal>
<PriceBanner
banner={banner}
decoration={content.decorations[0]}
/>
</Reveal>
))}
</Flex>
{banner && (
<Reveal>
<PriceBanner
banner={banner}
decoration={content.decorations[0]}
/>
</Reveal>
)}
)}
</CmsRegion>
</Box>
</PageSection>
);
+64
View File
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest';
import {
bakedCmsData,
BUILD_SOURCE,
hostCmsData,
liveFromData,
parseCmsData,
rawBanner,
rawOfferings,
@@ -132,3 +135,64 @@ describe('the baked block', () => {
).toEqual(['newborn', 'gezin']);
});
});
const docWith = (json: string) =>
({
getElementById: () => ({ textContent: json }),
}) as unknown as Document;
describe('hostCmsData', () => {
it('is the block the host wrote', () => {
expect(hostCmsData(docWith('{"offerings":[]}'))?.offerings).toEqual([]);
});
it('is null for the block the build baked, and for no block', () => {
const baked = JSON.stringify(
bakedCmsData('https://andreaslop.nl', packages, null, null),
);
expect(parseCmsData(baked)?.source).toBe(BUILD_SOURCE);
expect(hostCmsData(docWith(baked))).toBeNull();
expect(
hostCmsData({ getElementById: () => null } as unknown as Document),
).toBeNull();
});
});
describe('liveFromData', () => {
it('gives nothing for no data', () => {
expect(liveFromData(null)).toBeNull();
});
it('takes only what the block has', () => {
expect(liveFromData({ siteUrl: 'https://andreaslop.nl' })).toEqual({});
});
it('trusts the host: an empty or unusable list is no packages', () => {
expect(liveFromData({ offerings: [] })).toEqual({ packages: [] });
expect(liveFromData({ offerings: [{ slug: 'Bad Slug' }] })).toEqual({
packages: [],
});
expect(
liveFromData({
offerings: [
{ slug: 'x', title: 'X', price: '€ 5', features: ['a'] },
],
})?.packages?.map((pkg) => pkg.id),
).toEqual(['x']);
});
it('maps both banners, null meaning none and an unusable answer too', () => {
expect(liveFromData({ banners: { top: null, bottom: null } })).toEqual({
topBanner: null,
banner: null,
});
expect(
liveFromData({
banners: { top: { text: 'Boven' }, bottom: { title: '' } },
}),
).toEqual({
topBanner: { title: undefined, text: 'Boven', link: undefined },
banner: null,
});
});
});
+45 -3
View File
@@ -1,7 +1,12 @@
import type { PricingBanner, PricingPackage } from '@/content/types';
import { formatPrice } from './formatPrice';
import type { OfferingTopBanner } from './offerings';
import { resolveSiteUrl } from './siteUrl';
import { formatPrice } from './formatPrice.ts';
import {
mapBanner,
mapOfferings,
mapTopBanner,
type OfferingTopBanner,
} from './offerings.ts';
import { resolveSiteUrl } from './siteUrl.ts';
// The data island of a page: what the CMS host writes into
// <script type="application/json" id="cms-data"> after the <!--CMS:DATA-->
@@ -12,6 +17,9 @@ import { resolveSiteUrl } from './siteUrl';
// and the page keeps what it was built with.
export interface CmsData {
// "build" in the block the build baked; absent in what the host writes. A
// baked block is the data the page was built with, not live data.
source?: string;
// Already checked by resolveSiteUrl
siteUrl?: string;
offerings?: unknown;
@@ -35,6 +43,7 @@ export function parseCmsData(text: string | null | undefined): CmsData | null {
? { top: raw.banners.top, bottom: raw.banners.bottom }
: undefined;
return {
source: typeof raw.source === 'string' ? raw.source : undefined,
siteUrl:
typeof raw.siteUrl === 'string' && raw.siteUrl !== ''
? resolveSiteUrl(raw.siteUrl)
@@ -45,6 +54,7 @@ export function parseCmsData(text: string | null | undefined): CmsData | null {
}
export const CMS_DATA_ID = 'cms-data';
export const BUILD_SOURCE = 'build';
// The block of the page, or null without a usable one (a preview, a test, a
// host that does not inject)
@@ -54,6 +64,15 @@ export function readCmsData(
return parseCmsData(doc.getElementById(CMS_DATA_ID)?.textContent);
}
// The block the CMS host wrote, or null when the page has none or only the one
// the build baked (a host that does not inject): then the page asks the API
export function hostCmsData(
doc: Pick<Document, 'getElementById'>,
): CmsData | null {
const data = readCmsData(doc);
return data?.source === BUILD_SOURCE ? null : data;
}
// JSON that cannot end the script element or break a line terminator rule:
// < > & and U+2028/2029 as \u escapes (the host does the same)
export function scriptJson(value: unknown): string {
@@ -103,6 +122,7 @@ export function bakedCmsData(
topBanner: OfferingTopBanner | null,
): CmsData {
return {
source: BUILD_SOURCE,
siteUrl,
offerings: rawOfferings(packages),
banners: {
@@ -111,3 +131,25 @@ export function bakedCmsData(
},
};
}
// What the page shows from a data block: only the parts the block has. The
// host's list is authoritative, so an empty list means no packages (the host
// switched them all off); null for a banner means none; a part that is not in
// the block, or a banner answer that cannot be used, leaves the baked one.
export interface LiveFromData {
packages?: PricingPackage[];
banner?: PricingBanner | null;
topBanner?: OfferingTopBanner | null;
}
export function liveFromData(data: CmsData | null): LiveFromData | null {
if (!data) return null;
const live: LiveFromData = {};
if (data.offerings !== undefined) {
live.packages = mapOfferings(data.offerings)?.packages ?? [];
}
const { top, bottom } = data.banners ?? {};
if (bottom !== undefined) live.banner = mapBanner(bottom);
if (top !== undefined) live.topBanner = mapTopBanner(top);
return live;
}
+2 -2
View File
@@ -1,6 +1,6 @@
import type { PricingBanner, PricingPackage } from '@/content/types';
import type { OfferingTopBanner } from './offerings';
import { formatPrice } from './formatPrice';
import type { OfferingTopBanner } from './offerings.ts';
import { formatPrice } from './formatPrice.ts';
// The plain, crawlable HTML that sits between the CMS markers in the
// prerendered pages. The host (SLP Modular CMS) writes the same markup from
+2
View File
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';
import { createRootRoute, HeadContent, Scripts } from '@tanstack/react-router';
import { ChakraProvider } from '@chakra-ui/react';
import AppShell from '../components/AppShell';
import CmsDataIsland from '../components/CmsRegion/CmsDataIsland';
import PackagesProvider from '../components/PackagesProvider/PackagesProvider';
import NoScriptStyles from '../components/NoScript/NoScriptStyles';
import ErrorPage from '../components/StatusPage/ErrorPage';
@@ -34,6 +35,7 @@ const RootDocument = ({ children }: { children: ReactNode }) => (
<NoScriptStyles />
</head>
<body>
<CmsDataIsland />
{/* De site is alleen licht; de _dark-waarden in het thema blijven
staan voor een eventuele donkere modus later */}
<ChakraProvider value={system}>{children}</ChakraProvider>
+7 -1
View File
@@ -23,7 +23,13 @@ function GezinPage() {
return (
<>
{shootPageGraph(view, siteContent).map((data) => (
<StructuredData key={data['@type']} data={data} />
<StructuredData
key={data['@type']}
data={data}
offerSlug={
data['@type'] === 'WebPage' ? 'gezin' : undefined
}
/>
))}
<ShootPage view={view} />
</>
@@ -23,7 +23,13 @@ function NewbornPage() {
return (
<>
{shootPageGraph(view, siteContent).map((data) => (
<StructuredData key={data['@type']} data={data} />
<StructuredData
key={data['@type']}
data={data}
offerSlug={
data['@type'] === 'WebPage' ? 'newborn' : undefined
}
/>
))}
<ShootPage view={view} />
</>
@@ -23,7 +23,13 @@ function ZwangerschapPage() {
return (
<>
{shootPageGraph(view, siteContent).map((data) => (
<StructuredData key={data['@type']} data={data} />
<StructuredData
key={data['@type']}
data={data}
offerSlug={
data['@type'] === 'WebPage' ? 'zwangerschap' : undefined
}
/>
))}
<ShootPage view={view} />
</>
+38 -11
View File
@@ -36,6 +36,7 @@ import {
shootServiceId,
shootServices,
siteHead,
setSiteUrl,
siteUrl,
structuredDataScript,
webPage,
@@ -237,7 +238,7 @@ describe('structured data about Andrea', () => {
it('describes Andrea from the page content and the site socials', () => {
expect(person(aboutContent.person, siteContent, image)).toEqual({
'@type': 'Person',
'@id': personId,
'@id': personId(),
name: 'Andrea Slop',
jobTitle: 'Lifestyle fotograaf',
image,
@@ -247,7 +248,7 @@ describe('structured data about Andrea', () => {
addressCountry: 'NL',
},
url: `${siteUrl}/over-mij`,
worksFor: { '@id': businessId },
worksFor: { '@id': businessId() },
knowsAbout: [
'Newbornfotografie',
'Zwangerschapsfotografie',
@@ -272,7 +273,7 @@ describe('structured data about Andrea', () => {
fc.property(anySiteContent, (site) => {
const business = professionalService(site);
const andrea = person(aboutContent.person, site, image);
expect(business['@id']).toBe(businessId);
expect(business['@id']).toBe(businessId());
expect(business.founder['@id']).toBe(andrea['@id']);
expect(andrea.worksFor['@id']).toBe(business['@id']);
}),
@@ -381,7 +382,7 @@ describe('webPage', () => {
it('describes a page from the registry', () => {
expect(
webPage('ContactPage', '/contact', {
about: { '@id': businessId },
about: { '@id': businessId() },
}),
).toEqual({
'@context': 'https://schema.org',
@@ -391,7 +392,7 @@ describe('webPage', () => {
name: sitePages['/contact'].title,
description: sitePages['/contact'].description,
inLanguage: 'nl-NL',
about: { '@id': businessId },
about: { '@id': businessId() },
});
});
@@ -526,7 +527,7 @@ describe('shootServices', () => {
'@type': 'Service',
name: 'Newbornshoot',
serviceType: 'Newbornshoot',
provider: { '@id': businessId },
provider: { '@id': businessId() },
areaServed: [
{ '@type': 'City', name: 'Huizen' },
{ '@type': 'AdministrativeArea', name: 'Gooi en Vechtstreek' },
@@ -585,7 +586,7 @@ describe('shootServices', () => {
fc.property(uniqueShootTypes, anySiteContent, (shoots, site) => {
shootServices(shoots, site).itemListElement.forEach(
({ item }, index) => {
expect(item.provider).toEqual({ '@id': businessId });
expect(item.provider).toEqual({ '@id': businessId() });
expect(item.areaServed).toEqual(
areaServed(site.serviceArea),
);
@@ -912,7 +913,7 @@ describe('the contact page', () => {
name: sitePages['/contact'].title,
description: sitePages['/contact'].description,
inLanguage: 'nl-NL',
about: { '@id': businessId },
about: { '@id': businessId() },
});
});
@@ -926,7 +927,7 @@ describe('the contact page', () => {
expect(script).not.toMatch(/@[a-z0-9-]+\.[a-z]/i);
expect(JSON.parse(script)).toEqual(data);
expect(data['@id']).toBe(canonicalUrl(path));
expect(data.about).toEqual({ '@id': businessId });
expect(data.about).toEqual({ '@id': businessId() });
},
),
);
@@ -945,8 +946,8 @@ describe('galleryImages', () => {
description: first.thumb.alt,
width: 1067,
height: 1600,
creator: { '@id': personId },
copyrightHolder: { '@id': businessId },
creator: { '@id': personId() },
copyrightHolder: { '@id': businessId() },
});
});
@@ -1030,3 +1031,29 @@ describe('preloadImage', () => {
);
});
});
describe('setSiteUrl', () => {
it('moves canonical, og: and the ids to the address of the page', () => {
const before = siteUrl;
try {
setSiteUrl('https://test.andreaslop.nl/');
expect(siteUrl).toBe('https://test.andreaslop.nl');
expect(canonicalUrl('/over-mij')).toBe(
'https://test.andreaslop.nl/over-mij',
);
expect(businessId()).toBe('https://test.andreaslop.nl/#business');
expect(personId()).toBe(
'https://test.andreaslop.nl/over-mij#andrea',
);
expect(
pageHead('/').meta.find((m) => m.property === 'og:image')
?.content,
).toBe('https://test.andreaslop.nl/og-image.jpg');
// Anything that is not a clean origin falls back to production
setSiteUrl('javascript:alert(1)');
expect(siteUrl).toBe('https://andreaslop.nl');
} finally {
setSiteUrl(before);
}
});
});
+20 -11
View File
@@ -22,7 +22,16 @@ import sitePages from './sitePages.ts';
import { configuredSiteUrl } from './siteUrlEnv.ts';
// Production unless the build sets VITE_SITE_URL (the test build does)
export const siteUrl = resolveSiteUrl(configuredSiteUrl());
export let siteUrl = resolveSiteUrl(configuredSiteUrl());
// In the browser the page can carry its own address in the cms-data block (the
// CMS host writes it there, because the script files cannot be rewritten per
// host). Called once before hydrating, so canonical, og: and the structured
// data match the HTML the host sent. Every use of siteUrl reads it when it
// runs, never at load.
export function setSiteUrl(url: string): void {
siteUrl = resolveSiteUrl(url);
}
export const siteName = 'Andrea Slop Fotografie';
// Preview-afbeelding voor WhatsApp, Facebook en LinkedIn (public/og-image.jpg)
@@ -105,8 +114,8 @@ export function jsonLdScript(data: unknown): string {
// Stable ids, so the business on every page and Andrea on the about page
// refer to each other (BR-SD-03)
export const businessId = `${siteUrl}/#business`;
export const personId = `${siteUrl}/over-mij#andrea`;
export const businessId = (): string => `${siteUrl}/#business`;
export const personId = (): string => `${siteUrl}/over-mij#andrea`;
const huizen = {
'@type': 'PostalAddress',
@@ -129,7 +138,7 @@ export function professionalService(content: SiteContent) {
return {
'@context': 'https://schema.org',
'@type': 'ProfessionalService',
'@id': businessId,
'@id': businessId(),
name: siteName,
url: `${siteUrl}/`,
logo: `${siteUrl}/logo.png`,
@@ -138,7 +147,7 @@ export function professionalService(content: SiteContent) {
address: huizen,
areaServed: areaServed(content.serviceArea),
sameAs: visibleSocials(content.socials).map((social) => social.href),
founder: { '@id': personId },
founder: { '@id': personId() },
};
}
@@ -153,13 +162,13 @@ export function person(
const knowsAbout = knowsAboutList(content.knowsAbout);
return {
'@type': 'Person',
'@id': personId,
'@id': personId(),
name: content.name,
jobTitle: content.jobTitle,
image,
address: huizen,
url: canonicalUrl('/over-mij'),
worksFor: { '@id': businessId },
worksFor: { '@id': businessId() },
...(knowsAbout.length > 0 ? { knowsAbout } : {}),
...(sameAs.length > 0 ? { sameAs } : {}),
};
@@ -206,7 +215,7 @@ export function aboutPage(
// The contact page, about the business (SEO-CP-03); no e-mail address, for
// the same reason as above
export function contactPage(path: RoutePath) {
return webPage('ContactPage', path, { about: { '@id': businessId } });
return webPage('ContactPage', path, { about: { '@id': businessId() } });
}
// An image URL for structured data: bundled images have a path, which
@@ -239,7 +248,7 @@ export function shootService(
serviceType: shoot.shootLabel,
description: shoot.paragraphs[0],
image: absoluteUrl(shoot.image.src),
provider: { '@id': businessId },
provider: { '@id': businessId() },
areaServed: areaServed(site.serviceArea),
...(pkg !== undefined
? {
@@ -349,7 +358,7 @@ export function galleryImages(photos: readonly PortfolioPhoto[]) {
description: photo.thumb.alt,
width: photo.full.width,
height: photo.full.height,
creator: { '@id': personId },
copyrightHolder: { '@id': businessId },
creator: { '@id': personId() },
copyrightHolder: { '@id': businessId() },
}));
}
+81
View File
@@ -28,6 +28,87 @@ const config = defineConfig({
'[tabindex="-1"]:focus': {
outline: 'none',
},
// The plain HTML between the CMS markers (components/CmsRegion): what
// the CMS host writes, shown until the styled cards take over after
// hydration. Looks like the cards (white, hairline border, centred),
// rows of three from lg (62em), one column below.
'.cms-offerings': {
listStyle: 'none',
margin: '0 auto',
padding: 0,
display: 'flex',
flexDirection: 'column',
gap: '{spacing.gridGap}',
maxWidth: '460px',
'@media (min-width: 62em)': {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
maxWidth: 'none',
},
},
'.cms-offering': {
background: 'white',
border: '1px solid {colors.line}',
padding: '2.5rem 1.5rem',
textAlign: 'center',
'@media (min-width: 62em)': {
width: 'calc((100% - 2 * {spacing.gridGap}) / 3)',
},
'&[data-featured]': {
borderColor: '{colors.accent}',
boxShadow: 'inset 0 3px 0 {colors.accent}',
},
},
'.cms-offering h3': {
fontFamily: '{fonts.heading}',
fontWeight: 'normal',
fontSize: '1.5rem',
margin: '0 0 0.75rem',
},
'.cms-price': {
fontFamily: '{fonts.heading}',
fontSize: '2.25rem',
lineHeight: 1,
color: '{colors.accent.deep}',
margin: '0 0 1.5rem',
},
'.cms-features': {
listStyle: 'none',
margin: '0 0 2rem',
padding: '1.5rem 0',
borderBlock: '1px solid {colors.line}',
color: '{colors.ink.soft}',
fontSize: '0.875rem',
},
'.cms-features li + li': { marginTop: '0.75rem' },
'.cms-offering a': {
color: '{colors.accent.deep}',
textDecoration: 'underline',
textUnderlineOffset: '3px',
},
'.cms-banner': {
display: 'block',
background: 'white',
border: '1px solid {colors.line}',
borderTop: '3px solid {colors.accent}',
padding: '1rem 1.5rem',
marginBlock: '{spacing.gridGap}',
textAlign: 'center',
color: '{colors.ink.soft}',
},
'.cms-banner strong': {
fontFamily: '{fonts.heading}',
fontWeight: 'normal',
letterSpacing: '0.14em',
textTransform: 'uppercase',
color: '{colors.ink}',
},
'.cms-banner a': {
color: '{colors.accent.deep}',
textDecoration: 'underline',
textUnderlineOffset: '3px',
},
},
theme: {
// Use default breakpoints from Chakra UI when breakpoints are commented out. Uncomment the breakpoints below for custom breakpoints.