# Architecture — `@codefast/tracking`

How the package is built: its layers, the client/server split, and how the evidence is produced. What it promises is in
[`spec/`](./spec/README.md); why it is shaped this way is in [`DECISIONS.md`](./DECISIONS.md).

## Layers

`src/` groups modules by layer, and every module is its own published subpath (`@codefast/tracking/<layer>/<module>`).
Value imports point only down this list:

| Layer           | Owns                                                                                                            | Imports from                                  |
| --------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| `core/`         | Consent model, consent config, receipt model, event catalog and validation, envelope, cookie parsing            | `core/`                                       |
| `client/`       | Tracker, consent storage, initial-consent store, consent runtime, anonymous-id cookies, GPC, CMP reconciler     | `core/`, `client/`                            |
| `destinations/` | GA4 + Consent Mode helpers, Vercel Analytics, the ad-platform destinations and their shared frame               | `core/`, `destinations/`                      |
| `react/`        | `useConsent`, `useInitialConsent`, `useGoogleConsentSync`, the consent banner, `GtagConsentBootstrap`           | `core/`, `client/`, `destinations/`, `react/` |
| `server/`       | Region → initial consent, anonymous-id `Set-Cookie` builders, receipts, Measurement Protocol, GA4 user deletion | `core/`, `server/`                            |
| `adapters/`     | TanStack Start request/response glue over `@tanstack/react-start/server`                                        | `core/`, `server/`                            |
| `tooling/`      | `SERVER_ONLY_SUBPATHS`, the client-bundle deny-list                                                             | nothing                                       |

`core/` does no I/O and reads no clock; its one source of randomness is `generateEventId`. Client and server both call
the same `core/` guards and normalizers, so a rule is written once.

## Entry points

The root `.` export (`src/index.ts`) is the **client entry**: it re-exports `core/` plus the browser surface —
`client/`, `react/`, and the client-lane destinations. It never re-exports `server/` or `adapters/`. The Vercel
destination stays off the root so its optional `@vercel/analytics` peer is only resolved when imported; `css/*` ships
`src/css` as-is.

`package.json#exports` is generated from `dist/` by `codefast exports:generate`, so adding a module adds its subpath.

## The client/server split

`server/**` and `adapters/**` must never reach a client bundle; nothing at runtime guards it. The boundary is a build
rule: `@codefast/tracking/tooling/import-protection` exports `SERVER_ONLY_SUBPATHS`, picomatch patterns covering whole
families rather than entry points, so a new server module is denied the moment it exists. `apps/web/vite.config.ts`
spreads it into TanStack Start's `importProtection.client.specifiers`; nothing inside the package imports it.

A server lane is reached from the client only through a server function the app defines, whose handler body the Start
compiler strips from the client transform. The ISR lane (`resolveInitialConsentFromRequest`), the anonymous-id re-issue
(`setAnonymousIdResponseCookie`) and receipt recording (`recordConsentReceiptFromRequest`) are adapters an app wraps
that way.

## Client runtime state

- **Consent storage** is `localStorage`, keyed by `ConsentConfig.storageKey`, falling back to memory when storage is
  blocked. `load()` parses and validates at most once per raw value, so per-event gates and per-render snapshots read
  memory. Cross-tab saves arrive through the `storage` event.
- **The initial-consent store** caches the resolved region default in `sessionStorage` and retries a failed resolve on
  `visibilitychange`, `pageshow` and `online`.
- **`createConsentRuntime`** composes one storage, one initial-consent store and one effective-consent reader from a
  single `ConsentConfig`; the reader is the tracker's `getConsent`.
- **React bindings** subscribe through `useSyncExternalStore` over those same instances, so the UI, the tracker gate and
  the tag bootstrap read one source.

## Evidence

- `tests/unit/**` mirrors `src/**`. Every file runs under jsdom, which adds browser globals without removing Node's, and
  each test file is isolated so module state models one page load.
- The Google tag is tested behaviourally: a gtag stub, with assertions on what reaches the `dataLayer`.
- `apps/web/tests/integration/features/tracking` exercises the wiring in the reference consumer.
- The [conformance vectors](./spec/vectors/README.md) have no runner in this repo. The unit tests implement the same
  contract independently, so agreement between a vector and a test is evidence rather than a tautology.
- There is no browser end-to-end suite; behaviour that needs a real browser is unproven.

## License

Released under the [MIT License](./LICENSE).
