import fc from 'fast-check'; import type { ContactField, ContactValues } from '../contact/types'; import type { ContactFormEvent } from '../lib/contactFormReducer'; import type { LightboxEvent } from '../lib/lightboxReducer'; import { shootPageView, type ShootPageView } from '../lib/shootPageView'; import type { Point } from '../lib/swipeDirection'; import type { ContentImage, EmailAddress, FaqItem, GalleryItem, InlineLink, PortfolioPhoto, FrameColor, PricingPackage, ProcessStepContent, ProcessStepId, RichText, ShootPageContent, ShootPageShared, ShootType, ShootTypeId, SiteContent, SocialLink, StoryBlock, Testimonial, } from '../content/types'; import type { RoutePath } from '../navigation'; import sitePages from '../sitePages'; // Gedeelde generators voor de property-based tests (fast-check) const platform = fc.constantFrom('facebook' as const, 'instagram' as const); // Een padsegment zoals in een route: kleine letters, cijfers en streepjes export const pathSegment = fc.stringMatching(/^[a-z0-9-]{1,12}$/); export const routePath = fc .array(pathSegment, { maxLength: 4 }) .map((segments) => '/' + segments.join('/')); export const httpsUrl = fc.webUrl({ validSchemes: ['https'] }); // Mix van geldige en ongeldige href's zoals het CMS ze zou kunnen leveren export const anyHref = fc.oneof( httpsUrl, fc.webUrl({ validSchemes: ['http'] }), fc.constantFrom( '', 'javascript:alert(1)', '/relatief', 'geen url', 'https://', ), fc.string(), ); export const socialLink: fc.Arbitrary = fc.record( { platform, href: anyHref, // Missing, blank, padded or ordinary, as an editor might type it label: fc.oneof( fc.constantFrom('', ' ', ' @andreaslopfotografie '), fc.string({ maxLength: 30 }), ), }, { requiredKeys: ['platform', 'href'] }, ); // Een geldig deel van een e-mailadres: geen spaties, geen @ const emailPart = fc.stringMatching(/^[a-z0-9._-]{1,20}$/); export const validEmail: fc.Arbitrary = fc.record({ user: emailPart, domain: fc .tuple(emailPart, fc.stringMatching(/^[a-z]{2,6}$/)) .map(([name, tld]) => `${name}.${tld}`), }); export const anyEmail: fc.Arbitrary = fc.oneof( validEmail, fc.record({ user: fc.string(), domain: fc.string() }), ); // Site-wide content as the CMS could deliver it; a valid e-mail address, so // tests can check it never leaks into output export const anySiteContent: fc.Arbitrary = fc.record({ footerIntro: fc.string(), socials: fc.array(socialLink, { maxLength: 4 }), email: validEmail, contactForm: fc.record({ enabled: fc.boolean(), replyTime: fc.string() }), serviceArea: fc.array( fc.record({ type: fc.constantFrom( 'City' as const, 'AdministrativeArea' as const, ), // Includes blanks and padding, as an editor might type name: fc.oneof( fc.constantFrom( 'Huizen', 'Gooi en Vechtstreek', '', ' ', ' Bussum ', ), fc.string({ maxLength: 20 }), ), }), { maxLength: 4 }, ), }); // Specialisations with padding, blanks and repeats, as an editor might type const specialisation = fc.oneof( fc.constantFrom('Newbornfotografie', 'Gezinsfotografie', '', ' '), fc.string({ maxLength: 20 }), ); export const knowsAboutEntries = fc.array( fc .tuple( fc.constantFrom('', ' ', ' '), specialisation, fc.constantFrom('', ' '), ) .map(([before, text, after]) => before + text + after), { maxLength: 8 }, ); // Package ids: a few fixed ones so lists contain duplicates, plus random slugs const packageId = fc.oneof( fc.constantFrom('newborn', 'gezin', 'zwangerschap'), fc.stringMatching(/^[a-z0-9-]{1,16}$/), ); const nonBlank = fc .string({ minLength: 1, maxLength: 30 }) .filter((text) => text.trim() !== ''); // A package that meets every invariant export const pricingPackage: fc.Arbitrary = fc.record({ id: packageId, name: nonBlank, price: fc.integer({ min: 1, max: 5000 }), features: fc.array(nonBlank, { minLength: 1, maxLength: 5 }), }); // Valid packages with unique ids, as a well-behaved CMS would deliver them export const uniquePackages = fc.uniqueArray(pricingPackage, { selector: (pkg) => pkg.id, maxLength: 6, }); // Valid and broken packages mixed, as a CMS might deliver them export const anyPackage: fc.Arbitrary = fc.oneof( pricingPackage, fc.record({ id: fc.oneof( packageId, fc.constantFrom('', 'Newborn', 'met spatie', 'a/b'), fc.string(), ), name: fc.oneof(nonBlank, fc.constantFrom('', ' ')), price: fc.oneof( fc.integer({ min: 1, max: 5000 }), fc.constantFrom(0, -5, 12.5, Number.NaN, Infinity), ), features: fc.oneof( fc.array(nonBlank, { maxLength: 3 }), fc.constant(['', 'x']), ), }), ); const image = fc.record({ src: fc.webPath().map((path) => `/assets${path}.jpg`), alt: fc.string({ maxLength: 40 }), width: fc.integer({ min: 1, max: 4000 }), height: fc.integer({ min: 1, max: 4000 }), }); export const shootTypeId = fc.constantFrom( 'newborn', 'zwangerschap', 'gezin', 'loveshoot', 'portret', ); const frameColor = fc.constantFrom( 'sand', 'accent', 'frame.stone', 'frame.rust', 'frame.taupe', 'frame.olive', ); // A shoot type as the CMS would deliver it; packageId may name a package // that does not exist export const shootType: fc.Arbitrary = fc.record( { id: shootTypeId, name: nonBlank, shootLabel: nonBlank, photosLabel: nonBlank, paragraphs: fc.array(nonBlank, { minLength: 1, maxLength: 3 }), image, frameColor, packageId: packageId, }, { requiredKeys: [ 'id', 'name', 'shootLabel', 'photosLabel', 'paragraphs', 'image', 'frameColor', ], }, ); // Shoot types with unique ids, in any order export const uniqueShootTypes = fc.uniqueArray(shootType, { selector: (shoot) => shoot.id, maxLength: 5, }); // A crop position the way content may write it: two percentages from 0 to // 100 (whole or with up to two decimals) with any whitespace around and // between. x and y are the numbers, text is how they are written. export const imagePositionValid = fc .tuple( fc.integer({ min: 0, max: 10000 }), fc.integer({ min: 0, max: 10000 }), fc.constantFrom('', ' ', '\t', '\n '), fc.constantFrom(' ', ' ', '\t', ' \n '), fc.constantFrom('', ' ', '\t'), ) .map(([hundredthsX, hundredthsY, before, between, after]) => { const [x, y] = [hundredthsX / 100, hundredthsY / 100]; return { x, y, text: `${before}${x}%${between}${y}%${after}`, }; }); // Crop positions that are not acceptable: out of range, one part, no percent // sign, a sign or exponent, extra parts, other text and non-strings export const imagePositionInvalid: fc.Arbitrary = fc.oneof( fc .tuple( fc.integer({ min: 10001, max: 99999 }), fc.integer({ min: 0, max: 10000 }), ) .map(([big, small]) => `${big / 100}% ${small / 100}%`), fc .tuple( fc.integer({ min: 0, max: 10000 }), fc.integer({ min: 10001, max: 99999 }), ) .map(([small, big]) => `${small / 100}% ${big / 100}%`), fc.constantFrom( '', ' ', '50%', '50 42', '50% 42', '50 42%', '-5% 10%', '+5% 10%', '1e1% 5%', '50% 42% 10%', '50%42%', 'center', 'top left', '50.% 42%', '.5% 42%', ), fc.constantFrom(undefined, null, 50, true, {}, ['50% 42%']), ); // Anything content might hold in imagePosition: good and bad export const imagePositionAny: fc.Arbitrary = fc.oneof( imagePositionValid.map(({ text }) => text), imagePositionInvalid, fc.string(), ); // The raw text of a crop position as a review field: valid, garbled or odd const imagePositionText = fc.oneof( imagePositionValid.map(({ text }) => text), fc.string(), ); // A review that meets every invariant, with or without a crop position export const testimonial: fc.Arbitrary = fc.record( { id: fc.oneof( fc.constantFrom('majella-mark', 'demi-kevin'), fc.stringMatching(/^[a-z0-9-]{1,16}$/), ), shoot: nonBlank, quote: nonBlank, author: nonBlank, image, imagePosition: imagePositionText, }, { requiredKeys: ['id', 'shoot', 'quote', 'author', 'image'] }, ); // Valid reviews with unique ids export const uniqueTestimonials = fc.uniqueArray(testimonial, { selector: (item) => item.id, maxLength: 6, }); // Valid and broken reviews mixed, as a CMS might deliver them export const anyTestimonial: fc.Arbitrary = fc.oneof( testimonial, fc.record( { id: fc.oneof(fc.constantFrom('majella-mark', '', ' '), fc.string()), shoot: fc.oneof(nonBlank, fc.constantFrom('', ' ')), quote: fc.oneof(nonBlank, fc.constantFrom('', ' ')), author: fc.oneof(nonBlank, fc.constantFrom('', ' ')), image: fc.record({ src: fc.oneof(fc.constant(''), fc.constant('/a.jpg')), alt: fc.string({ maxLength: 10 }), width: fc.integer({ min: -1, max: 10 }), height: fc.integer({ min: -1, max: 10 }), }), imagePosition: imagePositionText, }, { requiredKeys: ['id', 'shoot', 'quote', 'author', 'image'] }, ), ); // Shoot values as the form offers them for the live packages const shootValue = fc.constantFrom( 'zwangerschap', 'newborn', 'gezin', 'overig', ); // Values that pass every rule: realistic text within the limits export const contactValues: fc.Arbitrary = fc.record({ naam: nonBlank, email: validEmail.map(({ user, domain }) => `${user}@${domain}`), shoot: shootValue, bericht: fc .string({ minLength: 1, maxLength: 300 }) .filter((text) => text.trim() !== ''), }); // Valid and broken values mixed: empty, whitespace, too long, bad e-mail export const anyContactValues: fc.Arbitrary = fc.oneof( contactValues, fc.record({ naam: fc.oneof(nonBlank, fc.constantFrom('', ' ', 'x'.repeat(101))), email: fc.oneof( validEmail.map(({ user, domain }) => `${user}@${domain}`), fc.constantFrom( '', 'geen-adres', 'a@b', 'a b@c.nl', 'x'.repeat(255), ), fc.string({ maxLength: 20 }), ), shoot: fc.oneof(shootValue, fc.constantFrom('', 'bruiloft')), bericht: fc.oneof( nonBlank, fc.constantFrom('', ' ', 'x'.repeat(2001)), ), }), ); const contactField = fc.constantFrom( 'naam', 'email', 'shoot', 'bericht', ); // Anything that can happen to the form, for the state machine test export const contactEvent: fc.Arbitrary = fc.oneof( fc.record({ type: fc.constant('edit' as const), field: contactField, value: fc.oneof( nonBlank, fc.constantFrom('', 'a@b.nl', 'newborn', 'overig'), ), }), fc.record({ type: fc.constant('blur' as const), field: contactField }), fc.record({ type: fc.constant('preselect' as const), shoot: shootValue }), fc.record({ type: fc.constant('submit' as const), honeypot: fc.constantFrom('', '', '', 'http://spam.example'), shownAt: fc.constant(0), now: fc.constantFrom(500, 5000, 10000), }), fc.constant({ type: 'resolved' as const }), fc.constant({ type: 'rejected' as const }), ); // --- Gallery (portfolio) --- // A touch position on a screen, in CSS pixels export const point: fc.Arbitrary = fc.record({ x: fc.integer({ min: 0, max: 2000 }), y: fc.integer({ min: 0, max: 3000 }), }); // The intrinsic size of a photo: realistic pixel sizes, from very wide // panoramas to tall portraits export const imageSize = fc.record({ width: fc.integer({ min: 200, max: 4000 }), height: fc.integer({ min: 200, max: 4000 }), }); export const galleryItem: fc.Arbitrary = fc .tuple( fc.stringMatching(/^[a-z0-9-]{1,12}$/), imageSize, fc.integer({ min: 2, max: 3 }), nonBlank, fc.option(nonBlank, { nil: undefined }), ) .map(([id, size, factor, alt, caption]) => ({ id, thumb: { src: `/${id}-thumb.jpg`, alt, ...size }, full: { src: `/${id}.jpg`, width: size.width * factor, height: size.height * factor, }, caption, })); export const galleryItems = fc.uniqueArray(galleryItem, { selector: (item) => item.id, minLength: 1, maxLength: 12, }); // Anything that can happen to the lightbox, for the state machine test export const lightboxEvent: fc.Arbitrary = fc.oneof( fc.record({ type: fc.constant('open' as const), index: fc.integer({ min: -3, max: 15 }), count: fc.integer({ min: 0, max: 12 }), }), fc.constant({ type: 'next' as const }), fc.constant({ type: 'prev' as const }), fc.constant({ type: 'first' as const }), fc.constant({ type: 'last' as const }), fc.constant({ type: 'close' as const }), fc.record({ type: fc.constant('listChanged' as const), count: fc.integer({ min: 0, max: 12 }), }), ); // A portfolio photo of any shoot type; ids are made unique by the list export const portfolioPhoto: fc.Arbitrary = fc .tuple( fc.stringMatching(/^[a-z0-9]{1,10}$/), shootTypeId, imageSize, nonBlank, ) .map(([id, shootType, size, alt]) => ({ id, shootType, thumb: { src: `/${id}.jpg`, alt, ...size }, full: { src: `/${id}-groot.jpg`, width: size.width * 2, height: size.height * 2, }, })); export const portfolioPhotos = fc.uniqueArray(portfolioPhoto, { selector: (photo) => photo.id, maxLength: 15, }); // --- Shoot pages --- // The image shape of the content, as the shoot types and testimonials use it export const contentImage: fc.Arbitrary = image; // The placeholders the shoot pages fill in (see ShootPageShared) export const knownPlaceholders = [ 'reactietermijn', 'aanbetaling', 'locatie', 'duur', 'opleverduur', ] as const; // Known placeholder names and unknown ones, including names that exist on // every object (an own-property check must leave those alone) export const placeholderName = fc.oneof( fc.constantFrom(...knownPlaceholders), fc.constantFrom('constructor', 'toString', '__proto__', 'Duur', ' duur'), fc .stringMatching(/^[a-z]{1,12}$/) .filter( (name) => !(knownPlaceholders as readonly string[]).includes(name), ), ); // Text without braces, with the characters that matter in a script tag or // JSON: , <, >, &, quotes, backslashes and line separators export const plainText = fc.oneof( fc.string({ maxLength: 20 }).filter((text) => !/[{}]/.test(text)), fc.constantFrom('', '<', '>', '&', '"', '\\', '
', ' '), ); // Text with placeholders in it, as an editor might write it. A stray brace // is only ever an opening one: an opening and a closing brace around a // filled placeholder could otherwise form a new one, which content never // contains. export const textWithPlaceholders = fc .array( fc.oneof( plainText, placeholderName.map((name) => `{${name}}`), fc.constant('{'), ), { maxLength: 6 }, ) .map((pieces) => pieces.join('')); // Every route of the site export const knownRoutePath = fc.constantFrom( ...(Object.keys(sitePages) as RoutePath[]), ); // A link inside running text: a known route, optionally an anchor export const inlineLink: fc.Arbitrary = fc.record( { to: knownRoutePath, hash: pathSegment, text: textWithPlaceholders }, { requiredKeys: ['to', 'text'] }, ); // Running text as text pieces and links, hostile characters included export const richText: fc.Arbitrary = fc.array( fc.oneof(textWithPlaceholders, inlineLink), { maxLength: 5 }, ); const slug = fc.stringMatching(/^[a-z0-9-]{1,12}$/); // A story block, with or without an image export const storyBlock: fc.Arbitrary = fc.record( { id: slug, eyebrow: textWithPlaceholders, title: textWithPlaceholders, paragraphs: fc.array(richText, { minLength: 1, maxLength: 3 }), image: contentImage, }, { requiredKeys: ['id', 'eyebrow', 'title', 'paragraphs'] }, ); export const faqItem: fc.Arbitrary = fc.record({ id: slug, question: textWithPlaceholders, answer: richText, }); // FAQ items with unique ids, as one page has them export const faqItems = fc.uniqueArray(faqItem, { selector: (item) => item.id, maxLength: 6, }); const processStepIds: ProcessStepId[] = [ 'aanvragen', 'datum', 'aanbetaling', 'shoot', 'bewerking', 'oplevering', ]; const processStepContent: fc.Arbitrary = fc.record({ title: plainText, text: textWithPlaceholders, }); // All six steps, with the keys in a random order: the content's key order // must not decide the order on the page const processSteps: fc.Arbitrary> = fc .tuple( fc.shuffledSubarray(processStepIds, { minLength: processStepIds.length, maxLength: processStepIds.length, }), fc.array(processStepContent, { minLength: processStepIds.length, maxLength: processStepIds.length, }), ) .map( ([order, steps]) => Object.fromEntries( order.map((id, index) => [id, steps[index]]), ) as Record, ); // The shared shoot page texts as the CMS could deliver them export const shootPageShared: fc.Arbitrary = fc.record({ breadcrumb: fc.record({ label: plainText, home: plainText, overview: plainText, }), process: fc.record({ eyebrow: plainText, title: plainText, lead: plainText, steps: processSteps, }), deposit: fc.record({ amount: fc.integer({ min: 1, max: 999 }), note: textWithPlaceholders, }), photos: fc.record({ eyebrow: plainText }), faq: fc.record({ eyebrow: plainText, lead: richText }), offer: fc.record({ bookLabel: plainText, askLabel: plainText, onRequest: fc.record({ price: plainText, text: plainText, linkLabel: plainText, }), }), }); // One shoot page as the CMS could deliver it, for the given shoot or any. // The photos deliberately repeat each other, the story images and the // images in `reuse` (pass the shoot's main and detail photo), so the rule // that a photo appears once per page is put to the test. export function shootPageContent( id?: ShootTypeId, reuse: readonly ContentImage[] = [], ): fc.Arbitrary { const stories = fc.uniqueArray(storyBlock, { selector: (story) => story.id, maxLength: 6, }); return stories.chain((storyList) => { const used = [ ...storyList.flatMap((story) => story.image === undefined ? [] : [story.image], ), ...reuse, ]; const photo = used.length > 0 ? fc.oneof(contentImage, fc.constantFrom(...used)) : contentImage; const photos = fc .tuple( fc.array(photo, { maxLength: 6 }), fc.array(fc.nat(), { maxLength: 2 }), ) .map(([list, repeats]) => list.length === 0 ? list : [...list, ...repeats.map((n) => list[n % list.length])], ); return fc.record({ id: id === undefined ? shootTypeId : fc.constant(id), intro: fc.record({ eyebrow: plainText, title: plainText, text: plainText, }), stories: fc.constant(storyList), // The values of {locatie}, {duur} and {opleverduur} process: fc.record({ location: plainText, duration: plainText, deliveryTime: plainText, }), photos: fc.record({ title: plainText, images: photos }), faq: fc.record({ title: plainText, items: faqItems }), offer: fc.record({ eyebrow: plainText, title: plainText }), closing: fc.record({ title: plainText, lead: richText, buttonLabel: plainText, }), }); }); } // What could end up where a shoot slug is expected: the known ids, other // letter cases, slashes, '..', an encoded slash, whitespace, markup, any // string, and values that are no string at all export const slugInput: fc.Arbitrary = fc.oneof( shootTypeId, shootTypeId.map((id) => id.toUpperCase()), shootTypeId.map((id) => id[0].toUpperCase() + id.slice(1)), fc .tuple( fc.constantFrom('', '/', '//', ' ', '\t', '..', '../', '%2F'), shootTypeId, fc.constantFrom( '', '/', '//', ' ', '\n', '/..', '%2F', '', ), ) .map((parts) => parts.join('')), fc.constantFrom( '', '..', '%2F', '', 'newborn/extra', 'newborn%2Fextra', 'onzin', 'constructor', '__proto__', ), fc.string(), fc.oneof( fc.integer(), fc.boolean(), fc.constant(null), fc.constant(undefined), fc.array(shootTypeId, { maxLength: 2 }), fc.object(), ), ); // --- Shoot page UI (unit 2) --- // A photo whose proportions sit around the landscape threshold of 1.2: // exactly on it, just below and just above, and anywhere else export const imageWithOrientation: fc.Arbitrary = fc .tuple( contentImage, fc.integer({ min: 20, max: 1500 }), fc.constantFrom('exact', 'below', 'above', 'any'), fc.integer({ min: 20, max: 4000 }), ) .map(([base, step, kind, anyWidth]) => { // A height divisible by 5, so that 1.2 x height is a whole number const height = step * 5; const edge = step * 6; const width = kind === 'exact' ? edge : kind === 'below' ? edge - 1 : kind === 'above' ? edge + 1 : anyWidth; return { ...base, width, height }; }); // Counts around the mosaic sizes, below zero included export const mosaicCount = fc.integer({ min: -3, max: 12 }); // One step of a timeline with hostile strings const hostileText = fc.oneof( fc.string({ minLength: 1, maxLength: 30 }), fc.constantFrom( '', '<', '>', '&', 'x'.repeat(120), ' ', ' ', 'ac&d', ), ); // 1 to 8 timeline steps with unique ids export const timelineSteps = fc.uniqueArray( fc.record({ id: slug, title: hostileText, text: hostileText }), { selector: (step) => step.id, minLength: 1, maxLength: 8 }, ); // A shoot page view built the way the route builds it: stories 0 to 6, the // photos present or not, the FAQ present or not, a package or none export const shootPageViewArb: fc.Arbitrary = fc .tuple(shootType, uniquePackages, shootPageShared, anySiteContent) .chain(([shoot, packages, shared, site]) => shootPageContent(shoot.id, [ shoot.image, ...(shoot.detailImage ? [shoot.detailImage] : []), ]).map((page) => { const view = shootPageView(shoot.id, page, { shootTypes: [shoot], packages, shared, site, portfolioShoots: [shoot.id], }); if (view === undefined) throw new Error('no view for a valid case'); return view; }), );