diff --git a/aidlc-docs/features/asf-cms-host-injection/plan.md b/aidlc-docs/features/asf-cms-host-injection/plan.md index d3861bd..85491c2 100644 --- a/aidlc-docs/features/asf-cms-host-injection/plan.md +++ b/aidlc-docs/features/asf-cms-host-injection/plan.md @@ -64,7 +64,7 @@ Why not exact copies of the styled cards: Chakra/Emotion class names and styles The host (CMS repo) finds all markers in one pass. A page with no marker and without the written production address is served unchanged as a static file. **Fail open everywhere:** a missing marker does nothing, invalid or missing data leaves the baked page as it is, an unknown slug keeps the baked fallback. 1. **List regions** `…`, and for the banners `…` and `…`: the host replaces the content between the markers by simple crawlable HTML from the live data (C# template, everything HTML-encoded); the markers stay. No live data or a provider error keeps the baked fallback. Spec and golden files below. -2. **Data** `` directly followed by the baked ``: the host replaces the pair by the live block `{"siteUrl":"…","offerings":[…],"banners":{"top":…|null,"bottom":…|null}}` (offerings and banners exactly as the public GETs; `<`, `>`, `&`, U+2028 and U+2029 written as `\uXXXX` escapes). Without a block after the marker the live block replaces the marker. `siteUrl` is the effective public base URL (see 5), which the client needs because the JS bundle cannot be rewritten (immutable assets). +2. **Data** `` directly followed by the baked ``: the host replaces the pair by the live block `{"siteUrl":"…","offerings":[…],"banners":{"top":…|null,"bottom":…|null}}` (offerings and banners exactly as the public GETs; `<`, `>`, `&`, U+2028 and U+2029 written as `\uXXXX` escapes). Without a block after the marker the live block replaces the marker. The block the build bakes carries `"source":"build"` (the host replaces the whole block, so the live one has no `source`); the site treats a block with that source as "no host data" and asks the API itself, as before the injection existed. `siteUrl` is the effective public base URL (see 5), which the client needs because the JS bundle cannot be rewritten (immutable assets). 3. **JSON-LD price** `` directly before ``: the host parses the block and sets `offers.price` (whole euros, our parsing: "€ 175", "€ 1.250", "175,-") on the node that has `offers`; when the package is gone, switched off, scheduled or has no readable price, `offers` is removed from that node. A database or provider failure is different: the baked block stays (fail open). A block that is not valid JSON stays. The marker comment is removed; property order is kept. Only the shoot pages of newborn, zwangerschap and gezin get this marker; loveshoot, portret ("Prijs op aanvraag"), the overview and the home page get none. 4. **Inline value** `€ 185`: the host replaces the text by "€" + U+00A0 + whole euros; an unknown slug or an unreadable price leaves the span alone. Only simple, non-nested spans with exactly this attribute. Used in the price block of a shoot page. 5. **Own address** (`Website:AuthoredBaseUrl`): the same injector replaces the written production address in every HTML page, `sitemap.xml` and `robots.txt` by `Website:PublicBaseUrl` when that is set on the host (test: `https://test.andreaslop.nl`; production: equal or empty, nothing to replace). One artifact then serves test and production, and `VITE_SITE_URL` no longer differs per environment. The ASF build is written with `https://andreaslop.nl` (the non-www canonical origin; IIS redirects www to it). The site has no web manifest. The client takes its address from `siteUrl` in the data block (fallback: the production address), not from the bundle, so canonical and `og:` tags stay right after hydration and on navigation. diff --git a/docs/cms-integration.md b/docs/cms-integration.md index 86e279f..083ec62 100644 --- a/docs/cms-integration.md +++ b/docs/cms-integration.md @@ -42,7 +42,10 @@ Decision (Bryan, 2026-11-15): the hosting package has one entry per website. The - **Test (ASF):** nginx on the proxy Pi forwards everything for `test.andreaslop.nl` to the CMS host (`web/deploy/nginx/test.andreaslop.nl.proxy.conf`), which serves the site files and the API. Nothing to add. - **Production: not in place yet.** The generated `web/deploy/iis/web.config` and the FTP upload of static files (`web/deploy/upload-production.sh`) still describe the old idea of IIS serving the files. They have to change with the production hosting: IIS keeps only the redirects (www, HTTPS) and the pass-through to the CMS host, and the prerendered `dist/` goes to the CMS host's prerendered-pages folder as on test. Security headers then come from the CMS host (as on test). This is part of the production hosting work, not of the packages feature. Until then production builds use the committed snapshot and the live calls fail safely (the baked list stays; the browser console shows a 404 for the API). Change generated server files only in `web/config/serverConfig.ts` and run `pnpm server-config`. -- **Next step (planned, separate feature after the current merges):** the CMS host injects the current packages, banners and later gallery and hero into the prerendered pages through markers, so a CMS change is visible to search engines at once and no rebuild is needed for it. The plan is in `aidlc-docs/features/asf-cms-host-injection/plan.md`; nothing of it is built yet. The browser-side live refresh described above stays as the safety net until then. +- **Host injection (built in the site; the host side is the CMS repo's work):** the build leaves markers in the prerendered pages and the CMS host fills them from live data, so a CMS change is visible to search engines at once without a rebuild. Contract and plan: `aidlc-docs/features/asf-cms-host-injection/plan.md`; golden files for the list HTML: `web/contract/host-injection/`. + - Markers: `` + `'; + + 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(''), + live([pakket('x', '€ 5', { title: '' })]), + ); + expect(out).toContain('`; + + 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 = + ''; + expect(run(page(broken), live([]))).toContain(broken); + }); + + it('sets the text of an inline price and leaves unknown slugs alone', () => { + const out = run( + page( + '€ 1€ 9', + ), + live([pakket('newborn', '€ 185')]), + ); + expect(out).toContain( + '€ 185'.replace( + '€ ', + '€' + String.fromCharCode(160), + ), + ); + expect(out).toContain('€ 9'); + }); +}); + +describe('injectCms address', () => { + it('replaces the written address everywhere when another one is set', () => { + const html = page(`${AUTHORED}/b`); + 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(`${AUTHORED}/b`); + expect(run(html, live([]))).toBe(html); + expect(run(html, live([]), AUTHORED)).toBe(html); + }); +}); diff --git a/web/config/hostInjector.ts b/web/config/hostInjector.ts new file mode 100644 index 0000000..ac17832 --- /dev/null +++ b/web/config/hostInjector.ts @@ -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, '\\u003e') + .replace(/&/g, '\\u0026'); + +const REGION = + /[\s\S]*?/g; +const DATA_BLOCK = + /(?:`, + ) + .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 ``; + }) + .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; +} diff --git a/web/config/previewServer.ts b/web/config/previewServer.ts index 203cc00..6b806e0 100644 --- a/web/config/previewServer.ts +++ b/web/config/previewServer.ts @@ -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=): + // 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 = { '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 = diff --git a/web/e2e/hostInjection.e2e.ts b/web/e2e/hostInjection.e2e.ts new file mode 100644 index 0000000..44d37ea --- /dev/null +++ b/web/e2e/hostInjection.e2e.ts @@ -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>; +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 = {}, +) => ({ + 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(``)).toHaveLength(2); + expect(home.split(``)).toHaveLength(2); + } + for (const path of [ + '/', + '/over-mij', + '/contact', + '/soorten-fotoshoots', + ]) { + const page = await html(path); + expect(page.split('')).toHaveLength(2); + expect(page).toMatch( + /'], + }, + ), + ], + banners: { + top: null, + bottom: { title: 'x', position: 'bottom' }, + }, + }); + const raw = await html('/'); + expect(raw).not.toContain('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( + '', + ); + 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([]); + }); +}); diff --git a/web/e2e/support/server.ts b/web/e2e/support/server.ts index 8fdcc8e..16f9ceb 100644 --- a/web/e2e/support/server.ts +++ b/web/e2e/support/server.ts @@ -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, diff --git a/web/src/client.tsx b/web/src/client.tsx index 20dc0d3..381eb8e2 100644 --- a/web/src/client.tsx +++ b/web/src/client.tsx @@ -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, diff --git a/web/src/components/CmsRegion/CmsDataIsland.tsx b/web/src/components/CmsRegion/CmsDataIsland.tsx new file mode 100644 index 0000000..5f5b9b9 --- /dev/null +++ b/web/src/components/CmsRegion/CmsDataIsland.tsx @@ -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: 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 ( +