diff --git a/web/.prettierignore b/web/.prettierignore index dc18099..78aa15e 100644 --- a/web/.prettierignore +++ b/web/.prettierignore @@ -14,3 +14,6 @@ skills-lock.json # Copied package (source: SlpSoftware src/cms-client); keeps its own formatting src/cms-client + +# Golden files of the host injection contract: exact text, never reformatted +contract/host-injection/*.expected.html diff --git a/web/contract/host-injection/README.md b/web/contract/host-injection/README.md new file mode 100644 index 0000000..1fe37f5 --- /dev/null +++ b/web/contract/host-injection/README.md @@ -0,0 +1,28 @@ +# Host injection contract (ASF site and CMS host) + +The ASF build leaves markers in the prerendered pages; the CMS host fills them from live data. This folder holds the golden files for the two list regions. For every `NAME.input.json` there is a `NAME.expected.html`: the host's template must give exactly that text (the file ends with one newline that is not part of the HTML) for that input. The ASF repo tests its own implementation (`src/lib/cmsHtml.ts`) against the same files; to change the contract, change the code and run `UPDATE_GOLDEN=1 pnpm test src/lib/cmsHtml.test.ts`, then send the new files to the CMS session. The files come from ASF commit: see `git log -1 -- web/contract/host-injection` in the ASF repo. + +## Inputs + +- `offerings-*.input.json`: the answer of `GET /api/v1/offerings` (an array). +- `banner-*.input.json`: `{ "position": "top" | "bottom", "answer": | null }`; `null` is a 204. + +## Rules for the packages region (``) + +1. Keep a package only when all hold: `slug` is a string matching `^[a-z0-9-]+$`; `title` is a non-empty string after trimming; `features` is a non-empty array of non-empty strings (each trimmed); `price` is readable as whole euros above zero (below); the slug was not used by an earlier kept package (the first one wins). Trim all texts. Any other package is skipped. +2. Order by `displayOrder` (a number; missing counts as 0), ties keep the given order. +3. Price text to whole euros: trim, then the regex `^\D*?(\d{1,3}(?:\.\d{3})+|\d+)(?:,(?:-|0{1,2}))?\D*$`; group 1 without dots is the amount; it must be a whole number above zero. So "€ 175", "€ 1.250", "175,-", "€ 175,00" are readable; "op aanvraag", "€ 12,50", "€ 0", "175 of 185" are not. +4. Output: ``; nothing at all (empty string) when no package is kept. +5. Per package: `
  • ` + `

    NAME

    ` + `

    € AMOUNT

    ` + `` + `Boek NAME` + `
  • `. `data-featured="true"` only when `featured` is the boolean `true`. AMOUNT uses a dot as thousands separator (1.250). The literal text ` ` is written, not a character. `description`, `priceNote` and `ctaLabel` are not used. +6. Escape every text (name, features, slug, amount) as: `&` `&`, `<` `<`, `>` `>`, `"` `"`, `'` `'`. + +## Rules for the banner regions (``, ``) + +1. `null` answer: empty string. Bottom: the title is required, otherwise empty string. Top: title or text is required, otherwise empty string. +2. Output ``. Parts: `TITLE`, `TEXT`, `LABEL` (trim all texts; empty means absent). +3. The link is written only when label and URL are both present and the URL is safe: it starts with `https://` and parses as a URL, or it starts with one `/` (not `//`, no backslash). Otherwise the link part is left out. +4. Escape as above (also in the `href`). + +## Where the region sits + +`…` (and the two banner pairs) are written by the build; the host replaces what is between the markers and leaves the markers. See `aidlc-docs/features/asf-cms-host-injection/plan.md` for the other markers (data block, JSON-LD price, inline price). diff --git a/web/contract/host-injection/banner-bottom-full.expected.html b/web/contract/host-injection/banner-bottom-full.expected.html new file mode 100644 index 0000000..dee1360 --- /dev/null +++ b/web/contract/host-injection/banner-bottom-full.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/banner-bottom-full.input.json b/web/contract/host-injection/banner-bottom-full.input.json new file mode 100644 index 0000000..d724870 --- /dev/null +++ b/web/contract/host-injection/banner-bottom-full.input.json @@ -0,0 +1,10 @@ +{ + "position": "bottom", + "answer": { + "title": "Kerstactie", + "text": "Alleen in december", + "linkLabel": "Boek de actie", + "linkUrl": "/contact", + "position": "bottom" + } +} diff --git a/web/contract/host-injection/banner-bottom-title-only.expected.html b/web/contract/host-injection/banner-bottom-title-only.expected.html new file mode 100644 index 0000000..3c6ff7f --- /dev/null +++ b/web/contract/host-injection/banner-bottom-title-only.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/banner-bottom-title-only.input.json b/web/contract/host-injection/banner-bottom-title-only.input.json new file mode 100644 index 0000000..f5d76d1 --- /dev/null +++ b/web/contract/host-injection/banner-bottom-title-only.input.json @@ -0,0 +1,10 @@ +{ + "position": "bottom", + "answer": { + "title": "Past er niets bij?", + "text": null, + "linkLabel": null, + "linkUrl": null, + "position": "bottom" + } +} diff --git a/web/contract/host-injection/banner-hostile.expected.html b/web/contract/host-injection/banner-hostile.expected.html new file mode 100644 index 0000000..2d00e76 --- /dev/null +++ b/web/contract/host-injection/banner-hostile.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/banner-hostile.input.json b/web/contract/host-injection/banner-hostile.input.json new file mode 100644 index 0000000..71607bb --- /dev/null +++ b/web/contract/host-injection/banner-hostile.input.json @@ -0,0 +1,10 @@ +{ + "position": "bottom", + "answer": { + "title": "", + "text": "\"quote\" & 'single'", + "linkLabel": "Meer", + "linkUrl": "https://voorbeeld.nl/?a=1&b=2", + "position": "bottom" + } +} diff --git a/web/contract/host-injection/banner-none.expected.html b/web/contract/host-injection/banner-none.expected.html new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/web/contract/host-injection/banner-none.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/banner-none.input.json b/web/contract/host-injection/banner-none.input.json new file mode 100644 index 0000000..bb9ad06 --- /dev/null +++ b/web/contract/host-injection/banner-none.input.json @@ -0,0 +1,4 @@ +{ + "position": "bottom", + "answer": null +} diff --git a/web/contract/host-injection/banner-top-text-only.expected.html b/web/contract/host-injection/banner-top-text-only.expected.html new file mode 100644 index 0000000..fe80976 --- /dev/null +++ b/web/contract/host-injection/banner-top-text-only.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/banner-top-text-only.input.json b/web/contract/host-injection/banner-top-text-only.input.json new file mode 100644 index 0000000..dfe6a32 --- /dev/null +++ b/web/contract/host-injection/banner-top-text-only.input.json @@ -0,0 +1,10 @@ +{ + "position": "top", + "answer": { + "title": "", + "text": "Nog twee plekken in december", + "linkLabel": null, + "linkUrl": null, + "position": "top" + } +} diff --git a/web/contract/host-injection/banner-top-unsafe-link.expected.html b/web/contract/host-injection/banner-top-unsafe-link.expected.html new file mode 100644 index 0000000..07cbc33 --- /dev/null +++ b/web/contract/host-injection/banner-top-unsafe-link.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/banner-top-unsafe-link.input.json b/web/contract/host-injection/banner-top-unsafe-link.input.json new file mode 100644 index 0000000..b5b9292 --- /dev/null +++ b/web/contract/host-injection/banner-top-unsafe-link.input.json @@ -0,0 +1,10 @@ +{ + "position": "top", + "answer": { + "title": "Nieuw", + "text": "x", + "linkLabel": "Hier", + "linkUrl": "http://voorbeeld.nl", + "position": "top" + } +} diff --git a/web/contract/host-injection/offerings-featured.expected.html b/web/contract/host-injection/offerings-featured.expected.html new file mode 100644 index 0000000..28faf04 --- /dev/null +++ b/web/contract/host-injection/offerings-featured.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/offerings-featured.input.json b/web/contract/host-injection/offerings-featured.input.json new file mode 100644 index 0000000..14fa4b7 --- /dev/null +++ b/web/contract/host-injection/offerings-featured.input.json @@ -0,0 +1,18 @@ +[ + { + "slug": "newborn", + "title": "Newborn", + "price": "€ 185", + "features": ["1-2 uur fotografie"], + "displayOrder": 0, + "featured": true + }, + { + "slug": "gezin", + "title": "Gezin", + "price": "€ 1.250,-", + "features": ["Hele dag"], + "displayOrder": 1, + "featured": false + } +] diff --git a/web/contract/host-injection/offerings-hostile.expected.html b/web/contract/host-injection/offerings-hostile.expected.html new file mode 100644 index 0000000..48fa6e0 --- /dev/null +++ b/web/contract/host-injection/offerings-hostile.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/offerings-hostile.input.json b/web/contract/host-injection/offerings-hostile.input.json new file mode 100644 index 0000000..e4f1196 --- /dev/null +++ b/web/contract/host-injection/offerings-hostile.input.json @@ -0,0 +1,9 @@ +[ + { + "slug": "xss", + "title": " & \"co\"", + "price": "€ 100", + "features": ["vet", "o'brien & zoon"], + "displayOrder": 0 + } +] diff --git a/web/contract/host-injection/offerings-none.expected.html b/web/contract/host-injection/offerings-none.expected.html new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/web/contract/host-injection/offerings-none.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/offerings-none.input.json b/web/contract/host-injection/offerings-none.input.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/web/contract/host-injection/offerings-none.input.json @@ -0,0 +1 @@ +[] diff --git a/web/contract/host-injection/offerings-skipped.expected.html b/web/contract/host-injection/offerings-skipped.expected.html new file mode 100644 index 0000000..05a1f7d --- /dev/null +++ b/web/contract/host-injection/offerings-skipped.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/offerings-skipped.input.json b/web/contract/host-injection/offerings-skipped.input.json new file mode 100644 index 0000000..0329aca --- /dev/null +++ b/web/contract/host-injection/offerings-skipped.input.json @@ -0,0 +1,58 @@ +[ + { + "slug": "goed", + "title": "Goed", + "price": "€ 100", + "features": ["a"], + "displayOrder": 0 + }, + { + "slug": "Slecht Slug", + "title": "Fout", + "price": "€ 100", + "features": ["a"], + "displayOrder": 1 + }, + { + "slug": "goed", + "title": "Dubbel", + "price": "€ 100", + "features": ["a"], + "displayOrder": 2 + }, + { + "slug": "aanvraag", + "title": "Op aanvraag", + "price": "op aanvraag", + "features": ["a"], + "displayOrder": 3 + }, + { + "slug": "leeg", + "title": "Zonder kenmerken", + "price": "€ 100", + "features": [], + "displayOrder": 4 + }, + { + "slug": "zonder-titel", + "title": "", + "price": "€ 100", + "features": ["a"], + "displayOrder": 5 + }, + { + "slug": "nul", + "title": "Nul", + "price": "€ 0", + "features": ["a"], + "displayOrder": 6 + }, + { + "slug": "komma", + "title": "Komma", + "price": "€ 12,50", + "features": ["a"], + "displayOrder": 7 + } +] diff --git a/web/contract/host-injection/offerings-standard.expected.html b/web/contract/host-injection/offerings-standard.expected.html new file mode 100644 index 0000000..fedebf2 --- /dev/null +++ b/web/contract/host-injection/offerings-standard.expected.html @@ -0,0 +1 @@ + diff --git a/web/contract/host-injection/offerings-standard.input.json b/web/contract/host-injection/offerings-standard.input.json new file mode 100644 index 0000000..75fdd9c --- /dev/null +++ b/web/contract/host-injection/offerings-standard.input.json @@ -0,0 +1,29 @@ +[ + { + "slug": "gezin", + "title": "Gezin", + "price": "€ 175", + "features": [ + "1 uur fotografie", + "Minstens 30 zorgvuldig nabewerkte foto's" + ], + "displayOrder": 2, + "description": "Een shoot met het hele gezin!", + "priceNote": "eenmalig, incl. btw" + }, + { + "slug": "zwangerschap", + "title": "Zwangerschap", + "price": "€ 175", + "features": ["1 uur fotografie", "Persoonlijke online fotogalerij"], + "displayOrder": 0 + }, + { + "slug": "newborn", + "title": "Newborn", + "price": "€ 185", + "features": ["1-2 uur fotografie"], + "displayOrder": 1, + "ctaLabel": "Boek nu" + } +] diff --git a/web/src/lib/cmsData.test.ts b/web/src/lib/cmsData.test.ts new file mode 100644 index 0000000..9ba2080 --- /dev/null +++ b/web/src/lib/cmsData.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from 'vitest'; +import { + bakedCmsData, + parseCmsData, + rawBanner, + rawOfferings, + readCmsData, + scriptJson, +} from './cmsData'; +import { mapBanner, mapOfferings, mapTopBanner } from './offerings'; +import { PRODUCTION_SITE_URL } from './siteUrl'; + +const packages = [ + { + id: 'newborn', + name: 'Newborn', + price: 185, + features: ['a', 'b'], + featured: true, + description: 'd', + priceNote: 'n', + ctaLabel: 'c', + }, + { id: 'gezin', name: 'Gezin', price: 1250, features: ['x'] }, +]; + +describe('parseCmsData', () => { + it('reads the three parts and checks the address', () => { + const data = parseCmsData( + JSON.stringify({ + siteUrl: 'https://test.andreaslop.nl/', + offerings: [{ slug: 'x' }], + banners: { top: null, bottom: { title: 'T' } }, + }), + ); + expect(data).toEqual({ + siteUrl: 'https://test.andreaslop.nl', + offerings: [{ slug: 'x' }], + banners: { top: null, bottom: { title: 'T' } }, + }); + }); + + it('falls back to production for an address that is not an origin', () => { + expect( + parseCmsData(JSON.stringify({ siteUrl: 'ftp://x' }))?.siteUrl, + ).toBe(PRODUCTION_SITE_URL); + }); + + it('leaves out what is missing or of the wrong kind', () => { + expect( + parseCmsData(JSON.stringify({ offerings: 'x', siteUrl: '' })), + ).toEqual({ + siteUrl: undefined, + offerings: undefined, + banners: undefined, + }); + }); + + it.each([null, undefined, '', 'niet json', '[1]', '"x"', 'null'])( + 'gives null for %s', + (text) => expect(parseCmsData(text)).toBeNull(), + ); +}); + +describe('readCmsData', () => { + it('reads the block of the page', () => { + const doc = { + getElementById: (id: string) => + id === 'cms-data' ? { textContent: '{"offerings":[]}' } : null, + } as unknown as Document; + expect(readCmsData(doc)?.offerings).toEqual([]); + }); + + it('gives null without a block', () => { + const doc = { getElementById: () => null } as unknown as Document; + expect(readCmsData(doc)).toBeNull(); + }); +}); + +describe('scriptJson', () => { + it('cannot end the script element or contain a line separator', () => { + const text = scriptJson({ + a: ' +// marker, exactly in the shape of the public API: +// { "siteUrl": "...", "offerings": [...], "banners": { "top": ..., "bottom": ... } } +// The build writes the same block with the data it baked, so the page always +// has one. Everything here is lenient: a block that cannot be used is ignored +// and the page keeps what it was built with. + +export interface CmsData { + // Already checked by resolveSiteUrl + siteUrl?: string; + offerings?: unknown; + // undefined: not in the block; null: no active banner + banners?: { top?: unknown; bottom?: unknown }; +} + +const isObject = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + +export function parseCmsData(text: string | null | undefined): CmsData | null { + if (!text) return null; + let raw: unknown; + try { + raw = JSON.parse(text); + } catch { + return null; + } + if (!isObject(raw)) return null; + const banners = isObject(raw.banners) + ? { top: raw.banners.top, bottom: raw.banners.bottom } + : undefined; + return { + siteUrl: + typeof raw.siteUrl === 'string' && raw.siteUrl !== '' + ? resolveSiteUrl(raw.siteUrl) + : undefined, + offerings: Array.isArray(raw.offerings) ? raw.offerings : undefined, + banners, + }; +} + +export const CMS_DATA_ID = 'cms-data'; + +// The block of the page, or null without a usable one (a preview, a test, a +// host that does not inject) +export function readCmsData( + doc: Pick, +): CmsData | null { + return parseCmsData(doc.getElementById(CMS_DATA_ID)?.textContent); +} + +// 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 { + return JSON.stringify(value) + .replace(//g, '\\u003e') + .replace(/&/g, '\\u0026') + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); +} + +// The mapped packages back in the shape of GET /api/v1/offerings, for the +// block the build bakes (the price as the free text the CMS has) +export function rawOfferings(packages: readonly PricingPackage[]): unknown[] { + return packages.map((pkg, index) => ({ + slug: pkg.id, + title: pkg.name, + price: formatPrice(pkg.price).replace(/\u00a0/g, ' '), + features: pkg.features, + displayOrder: index, + ...(pkg.featured ? { featured: true } : {}), + ...(pkg.description ? { description: pkg.description } : {}), + ...(pkg.priceNote ? { priceNote: pkg.priceNote } : {}), + ...(pkg.ctaLabel ? { ctaLabel: pkg.ctaLabel } : {}), + })); +} + +// A banner back in the shape of GET /api/v1/offerings/banner, or null +export function rawBanner( + banner: PricingBanner | OfferingTopBanner | null, + position: 'top' | 'bottom', +): unknown { + if (!banner) return null; + return { + title: banner.title ?? '', + text: banner.text ?? null, + linkLabel: banner.link?.label ?? null, + linkUrl: banner.link?.url ?? null, + position, + }; +} + +export function bakedCmsData( + siteUrl: string, + packages: readonly PricingPackage[], + banner: PricingBanner | null, + topBanner: OfferingTopBanner | null, +): CmsData { + return { + siteUrl, + offerings: rawOfferings(packages), + banners: { + top: rawBanner(topBanner, 'top'), + bottom: rawBanner(banner, 'bottom'), + }, + }; +} diff --git a/web/src/lib/cmsHtml.test.ts b/web/src/lib/cmsHtml.test.ts new file mode 100644 index 0000000..3e2fdad --- /dev/null +++ b/web/src/lib/cmsHtml.test.ts @@ -0,0 +1,87 @@ +import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + bannerHtml, + escapeHtml, + offeringsHtml, + regionMarkers, +} from './cmsHtml'; +import { mapBanner, mapOfferings, mapTopBanner } from './offerings'; + +// The contract with the CMS host: for every *.input.json in +// contract/host-injection there is an *.expected.html, and the host's C# +// template must give exactly the same text for the same input. Regenerate the +// expected files after a deliberate change with UPDATE_GOLDEN=1 and send the +// new files to the CMS session. +const DIR = join(process.cwd(), 'contract', 'host-injection'); +const inputs = readdirSync(DIR).filter((name) => name.endsWith('.input.json')); + +interface BannerInput { + position: 'top' | 'bottom'; + answer: unknown; +} + +function render(name: string, input: unknown): string { + if (name.startsWith('offerings-')) { + const mapped = mapOfferings(input); + return offeringsHtml(mapped ? mapped.packages : []); + } + const { position, answer } = input as BannerInput; + return bannerHtml( + position === 'top' ? mapTopBanner(answer) : mapBanner(answer), + ); +} + +describe('host injection golden files', () => { + it('has inputs for the packages and for both banners', () => { + expect(inputs.length).toBeGreaterThanOrEqual(10); + expect(inputs.some((name) => name.startsWith('offerings-'))).toBe(true); + expect(inputs.some((name) => name.startsWith('banner-'))).toBe(true); + }); + + it.each(inputs)('%s gives the expected HTML', (file) => { + const name = file.replace('.input.json', ''); + const input: unknown = JSON.parse( + readFileSync(join(DIR, file), 'utf8'), + ); + const html = render(name, input); + const expectedFile = join(DIR, `${name}.expected.html`); + if (process.env.UPDATE_GOLDEN === '1') { + writeFileSync(expectedFile, html + '\n'); + } + expect(html + '\n').toBe(readFileSync(expectedFile, 'utf8')); + }); +}); + +describe('offeringsHtml and bannerHtml', () => { + it('writes nothing for no package and no banner', () => { + expect(offeringsHtml([])).toBe(''); + expect(bannerHtml(null)).toBe(''); + }); + + it('escapes what comes from the CMS', () => { + expect(escapeHtml(`'&'`)).toBe( + '<a href="x">'&'</a>', + ); + const html = offeringsHtml([ + { id: 'x', name: '', price: 10, features: ['"q"'] }, + ]); + expect(html).not.toContain(''); + expect(html).toContain('<b>'); + expect(html).toContain('"q"'); + }); + + it('puts a non-breaking space in the price, as an entity', () => { + const html = offeringsHtml([ + { id: 'x', name: 'X', price: 1250, features: ['a'] }, + ]); + expect(html).toContain('€ 1.250'); + }); + + it('wraps a region in its markers', () => { + expect(regionMarkers('OFFERINGS-HTML', '
      ')).toBe( + '
        ', + ); + }); +}); diff --git a/web/src/lib/cmsHtml.ts b/web/src/lib/cmsHtml.ts new file mode 100644 index 0000000..f644ee6 --- /dev/null +++ b/web/src/lib/cmsHtml.ts @@ -0,0 +1,70 @@ +import type { PricingBanner, PricingPackage } from '@/content/types'; +import type { OfferingTopBanner } from './offerings'; +import { formatPrice } from './formatPrice'; + +// The plain, crawlable HTML that sits between the CMS markers in the +// prerendered pages. The host (SLP Modular CMS) writes the same markup from +// live data with a C# template; the golden files in contract/host-injection +// are the contract between the two, so a change here changes them too. +// Everything that comes from the CMS is escaped. + +const ESCAPES: Record = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', +}; + +export const escapeHtml = (text: string): string => + text.replace(/[&<>"']/g, (char) => ESCAPES[char]); + +// "€ 185" with a non-breaking space, written as an entity so the golden files +// stay readable +const priceHtml = (price: number): string => + escapeHtml(formatPrice(price)).replace(/\u00a0/g, ' '); + +function packageHtml(pkg: PricingPackage): string { + const features = pkg.features + .map((feature) => `
      • ${escapeHtml(feature)}
      • `) + .join(''); + const featured = pkg.featured ? ' data-featured="true"' : ''; + return ( + `
      • ` + + `

        ${escapeHtml(pkg.name)}

        ` + + `

        ${priceHtml(pkg.price)}

        ` + + `
          ${features}
        ` + + `Boek ${escapeHtml(pkg.name)}` + + '
      • ' + ); +} + +// The cards as a plain list; nothing at all for no package. The packages are +// the mapped ones (mapOfferings), so order and skipping rules are the same as +// the site's. +export function offeringsHtml(packages: readonly PricingPackage[]): string { + if (packages.length === 0) return ''; + return `
          ${packages.map(packageHtml).join('')}
        `; +} + +type AnyBanner = PricingBanner | OfferingTopBanner; + +// A banner as one