# Business Logic Model - Unit 1: Start migration and script step Inputs: [requirements.md](../../../inception/requirements/requirements.md) (FR-PR-01 to 08, 19, 20, 22; the catch-all part of 14 and 15; NFR-PR-P-03, P-04, S-02, SEC-01 to 04, Q-01 to 05), [application-design.md](../../../inception/application-design/application-design.md) and its component files, the owner answer in [start-migration-fd-questions.md](../../plans/start-migration-fd-questions.md), the spike facts, and the real code in `web/src`, `web/config` and `node_modules` (Chakra `useMediaQuery` and `useBreakpointValue`, TanStack Router `Link` and `useHydrated`). Rules: [business-rules.md](business-rules.md). Data: [domain-entities.md](domain-entities.md). Components: [frontend-components.md](frontend-components.md). Scope: unit 1 only. Reveal, DeferredImage's no-JavaScript image, NoScriptNav and photo preload are unit 2; server configuration is unit 3. For those the unit-1 end state is in business-rules.md § 3. ## 1. Build flow ```mermaid graph TD tsc["tsc"] --> vb["vite build with Start: client and server bundles"] vb --> pre["Start prerender: one HTML file per page and 404.html"] pre --> plan["Runner reads dist/client and plans in memory"] plan --> chk{"Any violation?"} chk -->|"yes"| stop["Print all violations, exit 1, write nothing"] chk -->|"no"| wr["Write inline-hash.js files, then the changed HTML"] wr --> out["dist/client is the deployable output"] pre -.-> srv["dist/server: build only, never deployed"] classDef build fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; classDef check fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; classDef output fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; classDef excluded fill:#e2e8f0,stroke:#4a5568,stroke-width:1px,color:#000; class tsc,vb,pre,plan,wr build; class chk,stop check; class out output; class srv excluded; ``` Text alternative: after type checking and the Start build, the runner plans the rewrite in memory, stops on any violation without writing, and otherwise writes the moved scripts and HTML into dist/client; dist/server is never deployed. The pages are `Object.keys(sitePages)` plus `/404` rendered to `404.html`. File names follow `pageFile(path)`: `/` gives `index.html`, `/x` gives `x.html`. ## 2. Page lifetime: prerender, hydrating render, hydrated ```mermaid sequenceDiagram box rgba(99,179,237,0.4) Build machine participant S as Start prerender end box rgba(246,224,94,0.4) Browser participant B as First browser render participant H as After hydration end S->>S: Render with search none, hydrated false, defaults for media and load state S-->>B: HTML with moved scripts B->>B: Hydrate with the same defaults, hydrated false B->>H: useSyncExternalStore and effects run H->>H: Apply search, real media values, year, e-mail address, observers ``` Text alternative: the build and the first browser render use the same defaults, and only after hydration are the real search, media values, year and e-mail address applied. Browser-dependent values and their first-render contract are listed in [domain-entities.md § 3](domain-entities.md). The principle is BR-HYD-01: the first browser render equals the HTML. Hooks that read the browser use the pattern of BR-HYD-03, `useSyncExternalStore(subscribe, clientSnapshot, serverSnapshot)`, with the server snapshot equal to what the HTML shows. This gives the HTML value while hydrating and the real value at once for components that mount later (client navigation, tests). | Hook | Server and hydrating render | After hydration | |---|---|---| | `useHydrated` | `false` | `true` | | `usePageLoaded` | `false` | `document.readyState === 'complete'`, then the `load` event | | `useInView` | `inView = skip` | `skip`, or observed, or `true` without `IntersectionObserver` | | `useHeroSlider.hidden` | `false` | `document.hidden`, `visibilitychange` | | `useMediaQuery` (Chakra, default `ssr`) | `false` per query | real matches, set in Chakra's effect | | `useBreakpointValue` (Chakra, default `ssr`) | value of key `base` | value of the real breakpoint | ## 3. Script step ### 3.1 Scanner and classification The scanner (BR-SCR-02) walks the HTML once and yields script elements with their start-tag attribute text, body and byte range. Comments, `style`, `textarea`, `title`, `noscript`, `xmp`, `iframe`, `noembed`, `noframes` bodies and attribute values are skipped, so their text never matches. The classification is flowchart 1.1 of the business rules. `externalizeInlineScripts(html)`: 1. Scan. Throw UNTERMINATED_SCRIPT for a script without end tag. 2. For each executable script, check the unsupported forms (BR-SCR-05); throw UNSUPPORTED_SCRIPT on a hit. 3. Compute `hash` (BR-SCR-07) and the file name `inline-.js`; add `{ fileName, body }` to `moved` once per file name. 4. Build the output by copying every byte outside the replaced ranges and writing `` for each replaced one. `findExecutableInlineScripts(html)` runs steps 1 and the classification only and returns the bodies in document order. Worked example (shape only; the real bodies are Start's): | Input fragment | Output fragment | `moved` | |---|---|---| | `` | `` | one entry for A | | `` | unchanged (external) | none | | `` | `` | one entry | | `` | unchanged (data) | none | | `` | unchanged (skipped) | none | | `` | unchanged (comment) | none | ### 3.2 Runner ```mermaid graph TD r1["Read all .html under clientDir"] --> r2["Compute expected set: pageFile of each sitePages path, plus 404.html"] r2 --> r3["Per file: externalize, then find on the result"] r3 --> r4["Scan text files: e-mail address, source maps, build paths"] r4 --> r5["Check sitemap.xml equals sitemapXml of the register"] r5 --> r6{"Violations?"} r6 -->|"yes"| r7["Print file, code, detail for each; exit 1"] r6 -->|"no"| r8["Write script files, then HTML, print one summary line"] classDef step fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; classDef decision fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; classDef done fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; class r1,r2,r3,r4,r5 step; class r6 decision; class r7,r8 done; ``` Text alternative: the runner computes everything in memory, collects every violation, and writes files only when there are none. Violation codes (all in business-rules.md, BR-SCR-13 to 21): | Code | Raised when | |---|---| | NO_HTML | no `.html` file under `clientDir` | | PAGE_MISSING | a `sitePages` path has no `pageFile(path)` | | NOT_FOUND_PAGE_MISSING | no `404.html` | | UNEXPECTED_HTML | an `.html` file outside the expected set | | NO_SCRIPTS_MOVED | a page or `404.html` references no `/assets/inline-<12 hex>.js` after processing | | EXECUTABLE_REMAINS | an executable inline script survives the rewrite | | UNSUPPORTED_SCRIPT, UNTERMINATED_SCRIPT | forms the rewrite cannot move safely | | COLLISION | `inline-.js` exists with other content | | EMAIL_IN_OUTPUT | the assembled address occurs in a text file | | SITEMAP_MISSING, SITEMAP_DIFFERS | `sitemap.xml` absent or different from the register | | SOURCE_MAP_PRESENT, BUILD_PATH_LEAK | a `.map` file, or the repository root path in a text file | The pure core is `planExternalization(files, context)`, which takes a map of relative path to content plus the expected paths, the address and the sitemap text, and returns `{ writes, violations }`. The runner reads the directory into that map, calls it, and writes the result. This keeps all decisions testable without a file system. ## 4. The e-mail address ```mermaid graph TD p["Parts user and domain in siteContent"] --> a{"isEmailAddressValid?"} a -->|"no"| none["No column, item or link: nothing rendered"] a -->|"yes"| h{"hydrated?"} h -->|"no"| ph["Placeholder: empty, aria-hidden, reserved size"] h -->|"yes"| real["emailAddress assembles it: text and mailto link"] ph -->|"after hydration"| real ph --> guard["Build check: assembled address in any text file fails the build"] real -.-> only["Exists only in the browser"] classDef data fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000; classDef decision fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; classDef ui fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; classDef check fill:#e9d5ff,stroke:#6b21a8,stroke-width:1px,color:#000; class p data; class a,h decision; class none,ph,real,only ui; class guard check; ``` Text alternative: valid parts give an empty placeholder before hydration and the assembled address after it; invalid parts render nothing; a build check keeps the address out of every output file. Four call sites use it (verified in code): `Footer` (Contact column), `ContactDetails` through `contactChannels` (contact page, twice), `ContactFormGate` (sentence, link, button), `ContactForm` (failed state only). The slot per site is in [frontend-components.md](frontend-components.md). ## 5. Search parameters | Page | Search | First render (HTML and browser) | After hydration | |---|---|---|---| | `/` | `pakket` | no package chosen | `ContactPanel` takes the package (`pakket !== seenPakket`), loads the form, `ContactSection` tidies the URL (`navigate` to `/` with hash `contact`, smooth scroll, focus on the heading) | | `/contact` | `pakket` | no package chosen | same panel behaviour; the tidy effect `navigate({ to: '/contact', search: {}, replace: true })` runs when `pakket` becomes defined | | `/portfolio` | `shoot` | filter "Alles", all photos | filter and photo list follow `shoot`; `onShootChange` keeps `replace` and `resetScroll: false` | On client navigation to these URLs `hydrated` is already `true`, so the value applies in the first render of the new page, exactly as today. ## 6. Not found ```mermaid graph TD u["Unknown URL"] --> srv["Web server returns 404.html with status 404 (unit 3)"] srv --> html["HTML prerendered from /404: shell, title, noindex, one home button"] html --> hy["Hydration: router pathname is the real URL, NotFound ignores it while hydrated is false"] hy --> sec{"Path under /soorten-fotoshoots/?"} sec -->|"yes"| two["Two extra buttons appear"] sec -->|"no"| one["Stays with the home button"] nav["Client navigation to an unknown path"] --> hy2["Catch-all route renders NotFound with hydrated true"] hy2 --> sec classDef host fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000; classDef page fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; classDef decision fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; classDef ui fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; class u,nav page; class srv host; class html,hy,hy2 page; class sec decision; class two,one ui; ``` Text alternative: an unknown URL gets the prerendered 404 page, and after hydration `NotFound` adds the two shoot buttons under `/soorten-fotoshoots/`; client navigation to an unknown path renders the same route. ## 7. Preview server (unit 1 part) ```mermaid graph TD q["Request path"] --> dec{"Decodes once, no NUL, no backslash, no dot-dot segment?"} dec -->|"no"| nf["404.html, status 404"] dec -->|"yes"| root{"Path is /?"} root -->|"yes"| idx["index.html, 200"] root -->|"no"| dot{"Last segment has a dot?"} dot -->|"yes"| fe{"File exists?"} fe -->|"yes"| file["That file, 200"] fe -->|"no"| nf dot -->|"no"| pg{"pageFile exists?"} pg -->|"yes"| page["x.html, 200"] pg -->|"no"| nf classDef decision fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; classDef ok fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; classDef bad fill:#fbd38d,stroke:#92400e,stroke-width:1px,color:#000; classDef in fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; class dec,root,dot,fe,pg decision; class idx,file,page ok; class nf bad; class q in; ``` Text alternative: a safe path maps to index.html, an existing file, or its page file with status 200, and everything else, including unsafe paths, gets 404.html with status 404. Trailing slash and `/404` are final in unit 3 Infrastructure Design (BR-SRV-07). ## 8. Measurement and decision gate Before the first code change and after unit 1, on the same machine: entry and total JavaScript (gzip), mobile and desktop Lighthouse for every page, plus the moved scripts' count, size and timing (BR-MEA-01 to 03). The owner sees both sets; if any is worse, the owner decides before units 2 and 3 (NFR-PR-P-03). ## 9. Testable Properties (PBT-01) fast-check properties use the existing seed handling. Generators build HTML from known pieces (executable scripts, external scripts, data blocks, comments and style bodies containing script-like text, plain markup) and keep a model of what each piece is. | Id | Function | Category | Property | |---|---|---|---| | P1 | `externalizeInlineScripts` | Invariant | Removing the replaced script elements from the input and the output leaves identical text; everything else is byte-identical (BR-SCR-09) | | P2 | `externalizeInlineScripts` | Invariant | The references in the output appear in the same order as the executable scripts in the input (BR-SCR-06) | | P3 | `externalizeInlineScripts` | Round-trip | Replacing each moved reference by its body (looked up by file name) restores the input exactly, because attribute text is kept verbatim and only ` src="..."` was added | | P4 | `externalizeInlineScripts` | Idempotence | Applying it to its own output returns the same HTML and no moved files (BR-SCR-10) | | P5 | `externalizeInlineScripts` | Invariant | Data blocks, external scripts, empty scripts, comments and style bodies appear unchanged in the output | | P6 | both | Invariant | `findExecutableInlineScripts` of the output is empty (BR-SCR-11) | | P7 | `findExecutableInlineScripts` | Oracle | It returns exactly the bodies of the executable pieces of the generator model, in order, whatever decoys surround them | | P8 | `externalizeInlineScripts` | Invariant | The same body gives the same file name; different bodies give different names; names match `inline-[0-9a-f]{12}.js`; `moved` has no duplicate names | | P9 | `externalizeInlineScripts` | Commutativity (split and join) | For a list of independent fragments (each a complete element, comment or text), externalizing the concatenation equals concatenating the externalized fragments | | P10 | `pageFile` and its inverse | Round-trip | The path recovered from `pageFile(path)` equals `path`, for every `sitePages` path and generated route-like paths; the file never starts with `/` | | P11 | `planExternalization` | Idempotence | Applying a plan's writes to the file map and planning again gives no writes and no violations | | P12 | `planExternalization` | Oracle | Violations equal a simple model: missing pages, unexpected files, pages without references, address occurrences | | P13 | address scan (pure helper) | Oracle | For text built by inserting the address in any listed encoding at random positions, the scan finds it; text without it is never flagged | | P14 | `contactChannels` | Invariant | With `assemble` false the serialized result never contains the assembled address, and has the same number of channels as with `assemble` true | | P15 | `isEmailAddressValid` and `emailAddress` | Oracle | `isEmailAddressValid(p)` equals `emailAddress(p) !== null` for any parts | | P16 | `resolveRequest` | Invariant | For any path (including `..`, `%2e%2e`, `%00`, backslashes, unicode) the returned `file` has no `..` segment, is not absolute and has no backslash; status 404 comes only with `404.html` | | P17 | `resolveRequest` | Oracle | Against a small model over a generated set of existing files, `/`, `/x` and `/file.ext` resolve as BR-SRV-02 to 05 say | Components with no properties: | Component | Result | |---|---| | `startPreviewServer` | No PBT properties identified: thin HTTP wrapper around `resolveRequest`; example tests for headers and methods | | `externalizeOutput` (file system part) | No PBT properties identified: reading and writing files; its decisions are covered by P11 and P12 | | `useHydrated`, `usePageLoaded`, `useInView`, `useHeroSlider`, `useEmailAddress` | No PBT properties identified: React hooks with small state spaces and no pure transformation; example tests per phase (server snapshot, hydrated) | | `getRouter`, `client.tsx`, `__root.tsx` shell, `$` route | No PBT properties identified: configuration and wiring; covered by build, e2e and example tests | | Display and route components changed for hydration (Section 2 of frontend-components.md) | No PBT properties identified: markup with fixed small inputs; covered by example tests, axe and the e2e hydration checks | ## 10. Requirement coverage | Requirement | Where | |---|---| | FR-PR-01 to 04 | BR-BLD-02 to 06, 09; BR-SCR-14 to 16 | | FR-PR-05 to 07 | BR-HYD-01 to 21, BR-ENT-06 | | FR-PR-08 | BR-MON-01 to 04 | | FR-PR-19, 20 | BR-SCR-01 to 23 | | FR-PR-22 | BR-MAIL-01 to 11 | | FR-PR-14, 15 (route part) | BR-404-01 to 07 | | NFR-PR-P-03, P-04 | BR-MEA-01 to 04 | | NFR-PR-S-02 | BR-TST-06 | | NFR-PR-SEC-01 to 04 | BR-SEC-01 to 06, BR-BLD-11, BR-SRV-06 | | NFR-PR-Q-01 to 05 | BR-TST-01 to 07, BR-BLD-07, 12 | ## 11. Security Baseline and PBT compliance (unit 1) | Rule | Status | Note | |---|---|---| | SECURITY-04 | Compliant | CSP unchanged (BR-SEC-01); JSON-LD escaping kept (BR-SEC-06) | | SECURITY-09 | Compliant | No source maps, build paths or server output in `dist/client` (BR-SEC-02, 03, BLD-01) | | SECURITY-10 | Compliant | Lockfile, audit, overrides kept (BR-BLD-11) | | SECURITY-11 | Compliant | Path traversal is a tested property (P16) | | SECURITY-13 | Compliant | No external scripts added; moved scripts are same-origin files | | SECURITY-15 | Compliant | The runner fails closed and writes nothing on a violation (BR-SCR-12) | | PBT-01 | Compliant | Section 9 | | PBT-09 | Compliant | fast-check already in the project |