diff --git a/.claude/settings.json b/.claude/settings.json index 0b7a79a..7e7bb1f 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,28 +1,37 @@ { + "enabledPlugins": { + "nx@nx-claude-plugins": true, + "amiram@amiram-skills": true + }, "extraKnownMarketplaces": { "nx-claude-plugins": { "source": { "source": "github", "repo": "nrwl/nx-ai-agents-config" } + }, + "amiram-skills": { + "source": { + "source": "git", + "url": "git@github.com:Amiram-sf/skills.git", + "ref": "main" + }, + "autoUpdate": true } }, - "enabledPlugins": { - "nx@nx-claude-plugins": true - }, "sandbox": { - "filesystem": { - "allowRead": [ - "/tmp/.nx", - "~/.nx" - ], - "allowWrite": [ + "network": { + "allowUnixSockets": [ "/tmp/.nx", "~/.nx" ] }, - "network": { - "allowUnixSockets": [ + "filesystem": { + "allowWrite": [ + "/tmp/.nx", + "~/.nx" + ], + "allowRead": [ "/tmp/.nx", "~/.nx" ] diff --git a/.claude/skills/front-end-architect/SKILL.md b/.claude/skills/front-end-architect/SKILL.md deleted file mode 100644 index 748b2e7..0000000 --- a/.claude/skills/front-end-architect/SKILL.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -name: front-end-architect -description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites on Next.js App Router (server rendering, what search engines read, web vitals, bundle and hydration budgets). Applies a fixed architecture (apps, platforms, the island design system, shared libs, DDD features), its stack (Tailwind v4, cva, valibot, react-hook-form, zustand, TanStack Query, i18next, sonner), each project's decision records (ADR, DDR), and one rendering doc per page. Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, SEO, PWA, or Nx projects, when documenting or auditing how a page renders and what crawlers get from it, when planning a feature, when the user states a lasting rule or asks to record or change a decision, or when another skill needs front-end input. ---- - -# Front-end Architect - -Act as a principal front-end architect for Nx monorepos that ship B2C/B2B websites. Design, scaffold, implement, and review front-end code so it stays fast, maintainable, and consistent across projects. - -- Explain *why*, not only *what*. Present designs and reviews as checklists. -- When a requirement is ambiguous, state your assumption and continue. Ask only when a wrong guess would be expensive to undo. -- When a request conflicts with a rule here, follow the rule and explain the trade-off, unless an accepted project decision overrides it. When something isn't covered, reason from these principles and say so. -- When `docs/decisions/README.md` exists, read it once per session before any task: each line is one rule, and the project's decisions win. When the user states a lasting rule, or you make a choice that is hard to undo, record it as [references/decisions.md](references/decisions.md) describes. -- Prefer boring, proven technology, fewer re-renders, and the user's time. - -## How to read references - -The rules below cover most work. References hold the details and are long, so load as little as the task needs: - -1. Open a reference only when its row in section 5, What to read, matches the task. -2. Read only the sections the task touches, not the whole file. A link's `#anchor` names one section; otherwise pick them from the file's `Contents:` line (in code-patterns.md, its section table). Find them with `grep -n '^## ' ` and read each from its heading to the next. -3. Read a whole reference only when the task covers all of it, such as building the lib it specifies. - -## 1. The project - -Public websites with 1–20 million visitors a day (Amazon, eBay, Digikala). Apps are thin Next.js App Router apps (`apps//src/app/`); each product's logic lives in one platform (`platforms//`) shared by its apps. Critical: a fresh server render per request with no server cache, web vitals, bundle and chunk size, and hydration and navigation speed. - -## 2. Stack - -| Concern | Tool | Rule | -|---|---|---| -| Monorepo | Nx | Scaffold with generators (local ones in `tools/` when present), so every component, feature, and repository has the same shape | -| App | Next.js App Router | Server Components by default | -| Styling | Tailwind CSS v4 | Tokens in island `styles/theme.css`; no raw colors or sizes where a token exists | -| Variants | class-variance-authority (cva), clsx, tailwind-merge | cva in each component's `variants.ts`; merge classes with island's `cn` | -| Validation | valibot | Forms, env, and untrusted input. Not Zod | -| Forms | react-hook-form + @hookform/resolvers | `valibotResolver` with schemas from `shared/validations/` | -| Client state | zustand + immer | One store per feature or domain; subscribe through selectors | -| Server state | TanStack Query | `configs/react-query.ts` (confirm the repo uses it first); keys in the repository's `constants.ts`; no query retries, because the HTTP lib retries; a failed first load throws to its boundary | -| Toasts | sonner | After every completed or failed action; never for reads | -| i18n | i18next + react-i18next | No hard-coded UI text | -| Env | @t3-oss/env-core + valibot | Only through `packages/libs/env` | -| Lint and format | oxlint, prettier | ESLint runs module-boundary rules only | -| Scripts and TS configs | jiti | Runs `tools/` scripts and TypeScript configs without a build | -| Icons | svgo | island's `icon-sprite-plugin` writes `symbol-defs.svg` | -| Service worker | Native Service Worker and Cache APIs | Only through the pwa lib. No Workbox or Serwist | -| Structured data | schema.org JSON-LD | Only through the json-ld lib and island's `JsonLd`. No schema-dts or next-seo | - -Any dependency outside this stack needs a stated reason and approval. - -## 3. Architecture rules - -**Naming and exports** - -- Files and directories are kebab-case; component files PascalCase (`ProductCard.tsx`); hooks `use-hook-name.ts`. Next.js entry files keep their names (`page.tsx`, `layout.tsx`, `loading.tsx`, `error.tsx`, `not-found.tsx`); route groups are kebab-case: `(auth)`. -- Code lives under `src/`. Every module's `index.ts` re-exports its public API by name (`export { Button } from './Button';`, `export type { ButtonProps } from './types';`), never `export *`. Modules are importable from the project root and their own subpath; code imports by subpath (`@project/island/atoms/button`). -- Every project except apps has `src/server.ts`: it starts with `import 'server-only';`, is the `/server` subpath, holds server-only capabilities, and `index.ts` never imports it. A module with server-only parts has its own `server.ts` beside `index.ts` (the env lib); a server-only module has only `server.ts` (a feature's `caches/`); the project's `server.ts` re-exports them by name. - -**Dependency direction** - -- apps → platforms → packages. Nothing imports upward, apps never import each other, and no product imports another's app or platform (ESLint with Nx tags). -- island is atomic: atoms → molecules → organisms → templates; no level imports a higher one. `primitives/` (non-visual, such as a portal) sit outside the ladder. An organism's `components/` and `hooks/` are private, except a compound component's named parts. - -**Features are DDD** (`features//`) - -- `entities/`: back-end types, enums, and unions only. -- `http.ts`: `export const catalogHttp = http.extend({ ... })`, imported only by the feature's repositories, not exported. It sets base URL, headers, timeout, retry, and feature interceptors, never refresh or cookie settings; at least `http.extend({})`. -- `repositories/`: request through the feature's client and return data, with no client-side dependencies (hooks, stores, `window`, `cookie`, `storage`), so they run on the server too. Each endpoint has `*Args` (input), `*Dto` (request body), `*ResponseDto` (raw response), and `*Payload` (what apps and stores use); `mappers.ts` converts, and no `*Dto` leaves the repository. -- `caches/` (server-only, entry `server.ts`): React `cache()` wrappers, so each distinct call runs once per request. -- `actions/`: one operation from start to end, for any operation with side effects beyond the request (login: request, store, local storage, follow-up calls, emit `auth.login`, return `'ok'`). Every action emits its event on success unless called with `{ emit: false }`, so other features and integrations react without the action knowing them. -- `models/`: page and part logic as hooks: one page model (`use-login-page.ts`), plus one per part when parts load or change on their own (`use-shipment-address-part.ts`). Pages, templates, and parts stay presentational. -- Beside `features/`: `stores/` (zustand + immer, one per feature or domain, `*Payload` data) and `shared/` (`constants/`, `utils/`, `validations/` with `base-validations.ts` and one `-validations.ts` each). - -**Rendering and data** - -- The server render never depends on auth: no session read, no auth cookies, the same HTML for every visitor of a URL. UI that depends on the viewer (needs a logged-in user, differs for guests, members, and paying members, or shows the viewer's data) renders in the browser behind a same-size skeleton that stays until the viewer is known; only the smallest differing piece. Everything else renders on the server. An explicit developer request overrides either default: follow it, state the trade-off, and write it in the plan. -- Every page has a rendering doc, `docs/pages//.md`, listed in `docs/pages/README.md`: section by section, what each template's server HTML holds for search engines and when each section's JavaScript loads. Read it before you change the page, write it before the code for a new page and link it from the plan, and update it in the same PR as a rendering change ([page-rendering.md](references/page-rendering.md)). -- Client side: repository → model → UI. A `noindex` or blocked page has a skeleton (`loading.tsx`). An indexable page has none, and no `` around `children` above it, so its content is in place in the first flush, and a link to it is the platform's `NavLink`, which shows a pending hint; an entity page (product, category, brand, seller, article, store branch, campaign) also answers a missing entity with a real 404 and a replaced one with a 308 ([b2c-b2b.md](references/b2c-b2b.md#rendering)). Every part that loads on its own has its own `` with a same-size skeleton and part boundary (EB-S). -- Server side: repository → cache → server components. Pages, `generateMetadata`, and server components read only through caches. Client components get server data as props, or through React Query hydration when it must stay live. -- Metadata: fixed values use the `metadata` export, and `generateMetadata` only values that depend on the request or on data (params, locale, a cache read); the same for `viewport` and `generateViewport`. Every app's `next.config.ts` sets `htmlLimitedBots: /.*/`, so metadata is always in ``, never streamed into ``. -- Every root layout's viewport is `width: 'device-width', initialScale: 1, maximumScale: 1`, so iOS doesn't zoom in on a focused input. -- Deploys never break open tabs: build once per release, mark it with `NEXT_DEPLOYMENT_ID` from CI, and keep old releases' `/_next/static/` files for 30 days. - -**Libs** (to use one from a feature, these rules and [code-patterns.md](references/code-patterns.md) are enough) - -- Env (`packages/libs/env`): only the app's `env/` files read `process.env`, through `createClientEnv` (public) and `createServerEnv` (server). Other projects use their own `getEnv`, filled by the app's bootstrap; libs get settings through `configure`. Never hard-code an env value (a service or CDN address, key, third-party ID, or flag) as a literal, a fallback (`?? 'http://localhost:3000'`), or a schema default: it comes from the serving app's `.env`, and only apps have `.env` files. Values equal in every environment go in `constants/`. -- HTTP (`packages/libs/http`): one root `http` configured in bootstrap, one `http.extend(...)` per feature, and no `fetch` elsewhere. Cookie auth: on a 401 one refresh runs for the whole app, waiting requests replay once, a failed refresh logs out; the server never refreshes or sends auth cookies. Only idempotent requests retry, with backoff. Every request is abortable; aborts are silent. Uploads report progress. Every failure is an `HttpError` (`{ code, message, status, fieldErrors, hint, requestId, retryAfter }`) that the error handler lib shows and reports. -- `cookie`: browser only, small values the server needs (such as the theme), never tokens (auth cookies are HttpOnly and server-owned), and never the locale or currency of an indexable page, which its URL decides. Server code uses `next/headers`. `storage` (local storage): client-only, non-critical data under the app's prefix and persisted stores, never tokens or personal data. Neither is read during render, at module top level, or in repositories. -- Service worker (`packages/libs/pwa`): one worker per app at `/sw.js`, written by `writeServiceWorker`, registered from the `AppShell` when the app's env turns it on. It stores only `/_next/static/` JS and CSS, `/fonts/` woff2 files, and `/icons/symbol-defs.svg`. Content-hashed JS and CSS (`chunks/`, `css/`, `immutable/`) are cache first, keyed by origin and path without the query string, with no network request on a hit; the rest is stale-while-revalidate by exact URL. Everything else reaches the network untouched; storing another kind needs a recorded decision. `/sw.js` is never renamed or removed; the env flag off unregisters the worker for every visitor. -- PWA: each app is installable from its manifest (`configs/pwa.ts`), with a splash screen on Android (from the manifest) and on iOS (a startup image per device size). -- Structured data (`packages/libs/json-ld`, server only): every indexable page renders one schema.org graph with island's `JsonLd` in its page entry, in the first flush, from its first-paint data: the business (`OnlineStore`) and website on the home page from `configs/seo.ts`, other page types from a builder in the platform's `app/json-ld/`. It says only what the page shows, the same for every visitor: no member or personal price, no rating on the business. `noindex`, not-found, no-access, and error states render none. - -**Design system (island)** - -- Build UI from island. Never fork or restyle an island component in a feature; add a variant. -- Place a new component in three steps: reuse or add a variant; pick its level by what it renders and imports, never its size; pick its owner by whether it knows a domain. -- Components use semantic tokens (`--color-surface-card`) layered over primitive tokens in `theme.css`, so theming and dark mode need no rewrite. -- Every component defines variants, sizes, states (default, hover, focus-visible, active, disabled, loading, error, selected), and accessibility behavior, with `cursor: pointer` when enabled and `cursor: not-allowed` when disabled built in. -- Fonts and the icon sprite keep fixed names (`yekan-bakh-vf.woff2`, `symbol-defs.svg`) in each app's `public/`, served immutable, never hashed or renamed by any step (not `next/font`). A changed font gets a new name; every sprite change raises `ICON_SPRITE_VERSION` (`?v=`) in the same commit. -- Complex organisms are compound components (``) that share state through context, with slots or render props for per-entity parts. - -**Cross-cutting** - -- Components render, models orchestrate, actions run operations, repositories talk to the network, and caches share server reads within a request. -- One source of truth per kind of state: server state in the query cache, URL state in the URL, form state in react-hook-form, shared client state in zustand, and ephemeral UI state in the component. Never copy one into another. -- Keep the UI stable: colocate state, split large contexts, never remount a visible subtree on update, and never key dynamic lists by random values or indexes. -- Multi-step flows (wizards, imports, bulk actions) are explicit states (`idle → validating → uploading → processing → done | failed`), never sets of booleans. -- Errors ([error-handling.md](references/error-handling.md)): EB-W at the app root only, a page-size EB-S per page, a part-size EB-S per part that loads on its own. A failed read shows its boundary or empty state (404, 403) and never toasts. A failed action toasts with its hint or reference ID and the retry its cause allows. `ABORTED` and 401 stay silent. A chunk that fails to load after a deploy is outdated: a page reloads once, a part or toast offers Reload page, and nothing is reported. -- All text comes from i18next, each a complete description of its purpose ("Save changes to this category", not "Save"). RTL and LTR: `lang` and `dir` from the locale, logical utilities (`ms-*`, `pe-*`, `start-*`), never left and right. -- WCAG 2.1 AA: 4.5:1 text contrast, visible focus rings, full keyboard operation, an `aria-label` on every icon-only button. - -## 4. Workflow - -For any design or implementation task, write a short plan in the PR description: affected projects and paths; each new component's path, level, and reason; data types; a link to the rendering doc of each new or changed page, and the first-load JS and HTML size of key routes; each rendering override the developer asked for; each new non-obvious pattern. - -1. **Clarify the job:** who uses it, how often, and what they finish with it. State assumptions. -2. **Read** the playbook sections the task touches, ui-rules.md for UI work, and the rendering doc of each page the task changes (section 5). -3. **Map the data:** entities, repository types, caches and how each client part gets server data, page and part models, actions and events, query keys, and the query-cache update after each mutation. -4. **Place the code:** list the Nx projects and folders that change; reuse before creating. Give each component its level and owner. For each section of a page, decide what search engines need from it, whether it depends on the viewer, where it renders, and when its code loads, and write it as a row of the page's rendering doc. Add a pattern only for a signal you can name. Refactor code that resists the change first, in its own commit. -5. **Design every state first:** loading, empty (no data, no results, not found, no access), error, in progress, then populated. -6. **Build in layer order** with island components: setup (Nx projects, tags, subpath exports, env variables), foundation (entities, repositories with mappers and query keys, caches, island variants), then each user story (actions, models, templates and organisms, route entry). Fix a bug in the layer that owns it, not in the UI. -7. **Wire feedback:** a toast for every completed action; field errors, a form alert, and an error toast with hint or reference ID and retry for a failed action; a boundary or empty state for a failed read; progress for long operations. -8. **Check performance:** bundle, hydration, web vitals, re-renders, flicker. -9. **Verify and deliver:** `nx affected -t ` for lint, type-check, and tests (target names: `nx show project `). Check the crawler view of each changed page against a production build ([page-rendering.md](references/page-rendering.md#checking-the-crawler-view)). Tick the Definition of Done, and note trade-offs: each new non-obvious pattern with its signal and the simpler option rejected, and smells left as debt. - -## 5. What to read - -| When the task | Read | -|---|---| -| Designs or writes code | [b2c-b2b.md](references/b2c-b2b.md), the sections it touches | -| Changes what users see or search engines read: a page, template, organism, form, copy, upload, image, font, icon, metadata, or viewport | [ui-rules.md](references/ui-rules.md), the sections it touches | -| Adds an Nx project, a feature, or a top-level folder, or changes tags or exports | [project-structure.md](references/project-structure.md) | -| Adds or moves a component | [project-structure.md#choosing-where-a-component-goes](references/project-structure.md#choosing-where-a-component-goes) | -| Writes a layer: island component, tokens, repository, action, form and model, mutation, store, or env | [code-patterns.md](references/code-patterns.md), that layer's section; or copy an existing file of the same kind | -| Adds a page, part, query, action, or form, or catches or shows an error | [error-handling.md](references/error-handling.md); [error-handling-code.md](references/error-handling-code.md) only to build or change a boundary, `ErrorFallback`, `readOnServer`, or the query client's error settings | -| Adds a page | [page-example.md](references/page-example.md) | -| Adds or moves a part of a page, or changes where it renders or when its code loads | [rendering-patterns.md](references/rendering-patterns.md#choosing-where-a-part-loads), then the sections its steps name | -| Adds a page, or changes a page's sections, where one renders, when its code loads, or what crawlers get; or documents or audits how a page renders | The page's rendering doc in `docs/pages/` first. Then [page-rendering.md](references/page-rendering.md), the sections its intro names for the task, and the page type's section of [page-type-maps.md](references/page-type-maps.md) | -| Shows the current time or the time left, such as a countdown or an open-now badge | [rendering-patterns.md](references/rendering-patterns.md#time-dependent-ui) | -| Adds a pattern or shared abstraction (factory, `Record` map, state machine, adapter, context, generic hook) | [design-patterns.md](references/design-patterns.md) | -| Refactors or reviews code | [refactoring.md](references/refactoring.md): for a review, [Smells that are intended here](references/refactoring.md#smells-that-are-intended-here), [Front-end smells](references/refactoring.md#front-end-smells), and [Review comments](references/refactoring.md#review-comments), plus the catalog row of each smell you name; for a refactor, [When and how](references/refactoring.md#when-and-how) and the technique you use. Also [Not used here](references/design-patterns.md#not-used-here) | -| Builds or changes a lib, or needs lib behavior not described above | [lib-http.md](references/lib-http.md), [lib-error-handler.md](references/lib-error-handler.md), [lib-env.md](references/lib-env.md), [lib-cookie.md](references/lib-cookie.md), [lib-local-storage.md](references/lib-local-storage.md), [lib-pwa.md](references/lib-pwa.md), or [lib-json-ld.md](references/lib-json-ld.md) | -| Touches `/sw.js`, the manifest, splash screens, or what the browser keeps between visits | [lib-pwa.md](references/lib-pwa.md) | -| Adds an indexable page type, or changes what a page tells search engines about the business, a product, its price, or its policies | [lib-json-ld.md](references/lib-json-ld.md): What each page gets, What the markup may say, Values, Rendering, Not in this lib, and the Usage part for that page | -| Records or changes a decision | All of [decisions.md](references/decisions.md): its templates hold `##` lines, so a section read stops early | -| Finishes work, or reviews code or a PR | [definition-of-done.md](references/definition-of-done.md); a review starts at its [Review](references/definition-of-done.md#review) section: every comment names the rule, shows the problem, and proposes the fix | - -## 6. Other skills - -Before deciding alone outside front-end architecture, check the available skills; when one matches, read its `SKILL.md` and let it lead its area: product and UX design (flows, layouts, hierarchy, token values), system or back-end architecture (service boundaries, API contracts, auth flows), Figma (reading designs), Nx (generators, project graph, running targets), and review, security, and QA (their checks). You own mapping designs onto island, states, feasibility, performance cost, DTO mapping, the pagination, filter, and error contracts the UI needs, project and tag placement, and the rules here. - -Hand off with a short brief: context, the decision you need, and this skill's constraints. Asked for front-end input, reply with affected projects and folders, the data flow (repository → action → model → UI), required states, performance concerns, and open questions. With no matching skill, decide and label it an assumption. diff --git a/.claude/skills/front-end-architect/references/b2c-b2b.md b/.claude/skills/front-end-architect/references/b2c-b2b.md deleted file mode 100644 index f02816a..0000000 --- a/.claude/skills/front-end-architect/references/b2c-b2b.md +++ /dev/null @@ -1,160 +0,0 @@ -# B2C/B2B playbook - -Public websites with 1–20 million visitors a day, like Amazon, eBay, and Digikala. Every kilobyte and millisecond is multiplied by millions of sessions. Most visitors arrive from search on mid-range phones, and many are logged out. Performance and SEO decide the architecture, the server renders every page fresh and caches nothing, and the codebase must stay maintainable as teams and features grow. - -Its Definition of Done is in [definition-of-done.md](definition-of-done.md#b2cb2b-additions). - -Contents: Targets · No server cache · Rendering · Server and client entries · Data flow · Errors · State and auth · Bundle and code splitting · Hydration and navigation · Deploys and version skew · Responsiveness and monitoring · Example: caches, page, and parts - -## Targets - -These are defaults; tighten them per product in the plan. - -| Metric | Target | -|---|---| -| LCP, p75 of mobile field data | ≤ 2.5 s | -| INP, p75 | ≤ 200 ms | -| CLS, p75 | ≤ 0.1 | -| TTFB, p75 | ≤ 0.8 s | -| First-load JS per route, gzipped, framework included | ≤ 200 KB | -| Route-specific client JS, gzipped | ≤ 100 KB | -| HTML per template, uncompressed, headers included, on the route's largest page | ≤ 1 MB | - -Googlebot reads only the first 2 MB of a page's uncompressed HTML, headers included, and drops the rest. The inline RSC payload repeats most of the page, and streamed parts come last, so they are the first content cut. Cap the items per listing page to stay within the HTML target. - -`next build` stopped printing first-load JS in Next.js 16. Measure it and the HTML size as [page-rendering.md](page-rendering.md#checking-the-crawler-view) shows, and record both for key routes in the plan. Any increase on a key route needs a stated reason in the PR. - -## No server cache - -The Next.js server renders a fresh page for every request and keeps nothing between requests: no prerendered or revalidated pages, and no cached data. - -- Keep Cache Components (`cacheComponents` in `next.config.ts`) off, because it prerenders a static shell at build time. Every root layout declares `export const dynamic = 'force-dynamic'`, which renders each route at request time and sends every `fetch` with `no-store`. Metadata routes (`sitemap.ts`, `robots.ts`, generated icons and Open Graph images) are cached by default and no layout covers them, so each one declares it too. -- Never use `'use cache'`, `unstable_cache`, `fetch` caching (`cache: 'force-cache'`, `next: { revalidate, tags }`), the `revalidate` segment config, `dynamic = 'force-static'` or `'error'`, or `generateStaticParams`. The HTTP lib sends every server request with `cache: 'no-store'` (see [lib-http.md](lib-http.md#server-side)). -- Never keep back-end data or rendered output in module scope, such as a `Map`, an LRU, or a memoized promise. Settings made once at startup, like env and the root `http` client, are fine. -- Caches that end with the request are fine: React `cache()` (the features' `caches/`) and the per-request `QueryClient`. So are caches in the browser: the TanStack Query cache, the router cache, and the service worker's cache, which holds only JS, CSS, fonts, and the icon sprite, never pages or data ([lib-pwa.md](lib-pwa.md)). -- Nothing needs revalidating. After a mutation that changes server-rendered content, call `router.refresh()` and the server renders the page again. -- Every app's `next.config.ts` turns on fetch logging with full URLs, so the dev server prints each server `fetch` with its whole URL, status, time, and cache result. That shows which back-end calls a page makes and proves each one skips the cache: - - ```ts - logging: { - fetches: { fullUrl: true }, - }, - ``` - -- Every request pays for a full render, so keep it cheap: stream slow secondary parts, fetch in parallel, and when a back-end call is slow, fix or cache it in the back end, never in Next.js. - -## Rendering - -- Server Components by default. Put `'use client'` only on interactive leaves, never on a layout or page. -- The server render never depends on auth: every visitor of a URL gets the same server HTML. A page or part whose UI depends on the viewer (it needs a logged-in user, differs for guests, members, and paying members, or shows the viewer's own data) renders completely in the browser behind a same-size skeleton. What is the same for every visitor renders on the server. An explicit request from the developer overrides either default ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). -- Templates stay Server Components. Interactive parts are small client components, each driven by its part model (`use---part.ts`). Don't turn a whole template into a client component to use a page model when only part of it is interactive. -- Keep props passed to client components small and serializable; they are serialized into the page's RSC payload. -- Pages are thin entrypoints. The page resolves the device on the server and renders the mobile or the desktop template, so the markup matches on hydration and nothing shifts. Never choose between layouts with viewport checks in components. -- Choose the template by device class only: `userAgent().device.type === 'mobile'` gets the mobile template, and everything else, tablets included, gets the desktop one. Never branch on `isBot`: content that differs for crawlers is cloaking. Where the repo has a unit test runner, a unit test pins Googlebot Smartphone to the mobile template, because Google indexes that template ([page-example.md](page-example.md)); otherwise propose one, which needs approval ([refactoring.md](refactoring.md#when-and-how)). -- Both templates' client components ship in the route's first-load JavaScript to every device, because the bundler builds a route's chunks from its imports, not from what one request renders. A heavy client component that only one template renders loads through `next/dynamic` in a small client component, so only the device that renders it downloads it. -- The reverse proxy or the CDN adds `Vary: User-Agent` to every HTML response, because one URL serves two templates, and Google's dynamic serving relies on the header. Next.js 16.4 overwrites a `Vary` set in `next.config.ts` or `proxy.ts` on page responses, so the app can't add it. -- Stream: every slow part with secondary content gets `` with a same-size skeleton, inside its own `PartBoundary`, so one slow or failing back-end call never blocks the whole page. Primary content never streams: a slow read it needs is fixed in the back end ([ui-rules.md](ui-rules.md#crawlers)). -- Indexable pages have nothing above them that streams: no `loading.tsx`, and no `` around `children` in a layout or in a component that a layout renders around them, such as the `AppShell` or a provider. React writes a boundary that is complete by the first flush in place only while the HTML of the shell, of the boundaries already in place, and its own stays within 12,800 bytes (its `progressiveChunkSize`, which Next.js doesn't change), or when its own HTML is 500 bytes or less. Above that, it writes the fallback in place and the content after the footer, in a hidden `
`, whatever the page awaits. A `loading.tsx` above an indexable page would therefore move its H1, content, and JSON-LD after the footer. -- Entity pages (product, category, brand, seller, article, store branch, campaign) are indexable pages whose URL names one record. With nothing above them that streams, their `generateMetadata` answers a missing entity with a real 404, and a replaced one with a 308, before the first byte ([error-handling.md](error-handling.md#b2cb2b-server)). -- Only `noindex` and blocked pages (search, compare, cart, checkout, account, login) have a `loading.tsx`, so a click shows their skeleton at once. A `loading.tsx` wraps every page below its folder, so put it beside its page, or in a route group that holds only such pages, such as `(account)` or `(auth)`. A link to an indexable page is the platform's `NavLink`, which shows a pending hint instead (Hydration and navigation). -- First flush: on an indexable page, the first byte waits for every read outside a ``, and, with `htmlLimitedBots`, for `generateMetadata`. So the page entry, and every Server Component outside a ``, await only the First flush reads, the reads the page's primary content needs; `generateMetadata` reads the same caches when it needs data, so they share one request. Any other read there holds the status line and the first byte: a secondary section with a read of its own streams in a part inside ``. -- Server code reads data through the features' caches, so `generateMetadata`, the page, and every server component share one request per distinct call (see Data flow). -- Every indexable page renders its JSON-LD in the page entry, before the template, from the data its first paint already awaits. So structured data is in the first flush and costs no extra request ([lib-json-ld.md](lib-json-ld.md#rendering)). -- Each page's rendering doc records its sections, where each one renders, and when its code loads ([page-rendering.md](page-rendering.md)). - -## Server and client entries - -- Each project except apps exposes `src/index.ts`, safe to import anywhere, and `src/server.ts`, server only. `server.ts` starts with `import 'server-only';` and is exported as `@project//server`. Client code imports only `index.ts` entries, and `index.ts` never re-exports from `server.ts`. -- `server.ts` holds server-only capabilities: caches, page data loaders, SEO builders (the platform's `app/json-ld/`), device detection, the server HTTP configuration, and server-side integrations. Server-only files are exported only from `server.ts`, never from a module's `index.ts`. -- Repositories have no client-side dependencies, so they are exported from `index.ts` and run on both sides. -- A server page loader that combines several caches for one page's first paint sits in that page's `models//` folder (`load--page.ts`) and is exported only through `server.ts`. -- `bootstrap.server.ts` must run before server rendering: import it at the top of every root layout. `bootstrap.client.ts` must run before client components render, both during SSR and in the browser: import it first in the app's root client component, the one that renders the platform's `AppShell`. Client components render in a separate module graph, so values set by server-only code are invisible to them. Make both bootstraps idempotent. -- Never call `getEnv`, a repository, or a cache at module top level. Do it inside functions, so bootstrap has always run first. -- Bootstrap code for both sides, env included: [lib-env.md](lib-env.md#usage). - -## Data flow - -A request becomes a page in this order. The server steps run per request, keep nothing afterwards, and never depend on who the viewer is. - -1. Every root layout imports `bootstrap.server.ts` first. -2. The page resolves the device, awaits only the First flush reads (Rendering) through caches or a server page loader, and renders the mobile or the desktop template. -3. Server components that need more data read it through caches. A slow part is an async server component inside `` with a same-size skeleton, so the page streams around it. An auth-dependent part renders only its skeleton on the server. -4. Client components get server data as props or through query hydration (below). In the browser their models take over: queries through repositories, mutations through actions, and auth-dependent parts render their variant once the auth store knows the viewer. After a mutation that changes server-rendered content, `router.refresh()` renders the page again. - -**Caches** (`features//caches/`, server-only) - -- Each cache is React's `cache()` around one repository call: `export const getProduct = cache((id: string) => productsRepository.get({ id }))`. React keeps the result for the current request only, so it's an allowed server cache (see No server cache). -- On the server, pages, loaders, `generateMetadata`, and server components read data only through caches, never through a repository directly. That's why ten components that need the same product send one request. -- Cache arguments are primitives, such as ids and page numbers. React compares arguments by identity, so `getProducts({ page })` would miss every time. -- Define caches at module level. A `cache()` created inside a component is new on every render. -- The module's entry is `server.ts`, with no `index.ts`, and the platform's `server.ts` re-exports it. - -**Handing server data to client components** - -- Props, for data the client part only shows or starts from: pass the `*Payload`, small and serializable. To stream it, pass the un-awaited promise and read it with `use()` inside ``. -- Query hydration, for data the client part keeps live (refetches, pagination, filters, or mutations that update it): prefetch into a `QueryClient` from `getQueryClient()` in `configs/react-query.ts`, with the cache as the `queryFn`, and render the part inside ``. The part's model queries the same key and starts with the data. - - An awaited prefetch puts the data in the HTML. For a secondary part, wrap the server component in `` so the await streams. A primary section awaits its prefetch outside every ``, from a read the page entry also awaits, so the cache sends one request (Rendering). - - An un-awaited prefetch doesn't block the part: the pending query is dehydrated and streams in, and the model reads it with `useSuspenseQuery`. Page or filter changes then go through `startTransition`, so the part keeps its content instead of falling back to the skeleton. -- A server prefetch calls the cache, never the repository, so a server component that awaits the same data in the same request shares the request. - -**Data loaded only in the browser** - -- Render on the server what search engines and the first paint need. Load in the browser only what depends on the viewer, is below the fold, or is shown on interaction, through a part model inside `` with a skeleton. -- A browser-only part uses `useQuery` and shows its skeleton while pending, or is loaded with `next/dynamic` from a client component: with `ssr: false` and a same-size `loading` skeleton when it renders at once, and without `ssr: false` when `LoadOnVisible` or an interaction already delays it ([rendering-patterns.md](rendering-patterns.md)). `useSuspenseQuery` is only for queries the server prefetched: any other query would run during SSR, where requests carry none of the user's cookies. - -## Errors - -The model, the boundaries, and their code are in [error-handling.md](error-handling.md). What is special here: - -- Server reads classify on the server, because a Server Component error reaches the browser with only its digest. Pages and server parts read through `readOnServer`. `generateMetadata` and the page call `notFound()` for 404 and 410, which an indexable page answers with a real 404 ([error-handling.md](error-handling.md#b2cb2b-server)). The page renders the `no-access` empty state for 403, with `robots: { index: false }`. A part renders its empty state for 404 and 403. Everything else is rethrown to a boundary. -- Boundaries: `app/global-error.tsx` is EB-W; every route group has `error.tsx` (page EB-S) and, when it calls `notFound()`, `not-found.tsx`; each part has a `PartBoundary` built with `catchError`, which lets `notFound()` and `redirect()` through. Error pages render `noindex`. -- A part that must show an empty state awaits its read on the server; an un-awaited prefetch fits only reads that can't answer 404 or 403. -- `instrumentation.ts` configures the error handler for the server and reports what no server code caught; `bootstrap.client.ts` configures it for the browser. - -## State and auth - -- `configs/react-query.ts`: `getQueryClient()` returns a new `QueryClient` on every server call and one shared instance in the browser. `staleTime` is above zero (60 s) so hydrated data isn't refetched on mount, queries don't retry (the HTTP lib does), a failed first load throws to its boundary while a failed refetch keeps the data, and pending queries are dehydrated so they can stream. -- zustand stores hold client state only. Never write to a store during server render: on the server a module-level store is shared by every request, so one user's data would leak to another. Pass server data through props or the query cache. If a store must start from server data, create it per request with `createStore` inside a provider. -- Server-side requests forward only the incoming request's cookies that the render needs, such as the theme, and never the auth cookies. Configure the HTTP lib once in `bootstrap.server.ts` with `configureServerHttp`: the server `baseUrl` from the app's server env, and a cookie provider that calls `cookies()` from `next/headers` on each request and keeps only the app's forwarded cookie names ([lib-http.md](lib-http.md#server-side)). That configures the root client, so every feature client forwards the same cookies. Never keep a user's cookies in module state. -- On the server, the HTTP lib never refreshes, never calls `abortAll`, and retries at most once with a shorter timeout, so a slow back end doesn't hold up rendering (see [lib-http.md](lib-http.md#server-side)). -- The server never reads or refreshes the session. The browser learns who the viewer is once per load through the auth store's `status`, and the browser's HTTP lib refreshes an expired session on a 401 ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). -- The `cookie` and `storage` libs are browser-only. Never read them during render: client components also render on the server, and the value would differ between server and browser. A value the page needs while rendering, such as the theme, is read on the server with `cookies()` and passed down as a prop. On an indexable page, the URL decides the locale and the currency, never a cookie ([ui-rules.md](ui-rules.md#crawlers)). -- Persisted zustand stores set `skipHydration: true` and rehydrate in an effect of the platform's `AppShell`, so the first browser render matches the server's (code in code-patterns.md, Persisted store). - -## Bundle and code splitting - -- Import island, libs, and every other package by subpath (`@project/island/atoms/button`), never from a root barrel. -- Declare `sideEffects` in every package so unused modules are dropped. -- Load heavy client-only widgets (maps, charts, rich editors, galleries, video players, chat) with `next/dynamic` inside a client component, on interaction or when visible, with a same-size skeleton. -- Load third-party scripts from `packages/integrations` after hydration (`next/script` with `afterInteractive` or `lazyOnload`), never in the critical path. -- Check a dependency's gzipped size before adding it, and prefer what the stack already has. -- Load only the active locale and the namespaces the route uses. - -## Hydration and navigation - -- Render output must be identical on server and client: no `Date.now()`, `new Date()`, `Math.random()`, `typeof window` branches, or locale and time-zone differences in render. Format numbers with the locale the server chose. Format absolute dates on the server for everything the server renders, with every option pinned, and pass the text down; a browser-only part formats its own with `formatDateTime`. UI that shows the current time reads the shared clock ([rendering-patterns.md](rendering-patterns.md#time-dependent-ui)). -- Fewer and smaller client boundaries hydrate faster. -- Navigate with `next/link` so routes prefetch. Keep the header and footer in layouts, so navigation re-renders only the page segment. Indexable pages have no `loading.tsx`, so a link to one prefetches nothing, and the current page stays until the new one arrives: every link to an indexable page is the platform's `NavLink`, which shows a pending hint inside the clicked link ([rendering-patterns.md](rendering-patterns.md#loading-patterns)). -- Protect INP: keep event handlers light, wrap non-urgent updates in `startTransition`, debounce search input by 250–400 ms, and for long interactive lists try `content-visibility` first; a virtualization library needs approval ([rendering-patterns.md](rendering-patterns.md)). - -## Deploys and version skew - -A deploy doesn't end the sessions already open. A tab keeps running the old release's JavaScript until it reloads, while the servers already run the new release. These rules keep that tab working, or move it to the new release with a normal page load instead of an error. - -- Build once per release, and run that same output on every instance, so all of them share one build ID and one set of asset files. Never build on each server. -- Mark every release with Next.js's deployment ID. CI sets `NEXT_DEPLOYMENT_ID` to the release's commit SHA when it runs `next build`; Next.js reads it itself. It adds `?dpl=` to its asset URLs and sends the ID with every client-side navigation. When an old tab navigates and the IDs differ, Next.js does a full page load into the new release instead of a client-side navigation. The value changes on every release, so it comes from CI, never from `.env` or a literal `deploymentId` in `next.config.ts`; no app code reads it. -- Keep old releases' static files. Serve `/_next/static/` on the app's own origin from storage that every release adds to: on deploy, copy the build's `.next/static/` into it without deleting what's there, and delete a release's files only 30 days after it stopped serving. An old tab that loads a lazy chunk (`next/dynamic`, `LoadOnVisible`, or a route it hasn't visited) then still finds it. Replacing `.next/` in place, as a plain `next start` deploy does, deletes the old chunks, and those loads fail with 404. Keep the same origin: the service worker stores only same-origin files ([lib-pwa.md](lib-pwa.md)). -- During a rolling deploy, old and new instances serve side by side. Shared static storage lets every page find its chunks whichever instance rendered it, and a navigation that reaches the other release gets the deployment ID's full page load. -- The back-end contract changes compatibly: each back-end release keeps serving the previous front-end release for as long as its tabs live (additive fields, old endpoints kept), and each front-end release works with the back end it may meet during a rolling deploy. -- Feature actions run in the browser and Server Actions aren't used, so no action ID goes stale between releases. -- The service worker keeps the chunks each visitor already loaded, so an old tab often gets them from the device, and it never caches pages, so a reload always lands on the current release ([lib-pwa.md](lib-pwa.md)). -- What still fails, a chunk missing despite these rules, is classified as outdated by the error handler. A page or app boundary reloads the page once, a part boundary and an action's toast offer Reload page, and nothing is reported ([error-handling.md](error-handling.md#boundaries)). Watch 404s on `/_next/static/` in the CDN logs after each deploy instead: a rise means old files were deleted too early. - -## Responsiveness and monitoring - -- Each route has a mobile and a desktop template, and each template stays fluid across its device range. Touch targets are at least 44×44 px on mobile. -- Report field web vitals per route (`useReportWebVitals` into the analytics integration), each with whether the service worker controlled the page ([lib-pwa.md](lib-pwa.md#measuring)), report errors through the error handler to the Sentry integration (`instrumentation.ts` on the server, `bootstrap.client.ts` in the browser), and review p75 per release. - -## Example: caches, page, and parts - -In [page-example.md](page-example.md). Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet. diff --git a/.claude/skills/front-end-architect/references/code-patterns.md b/.claude/skills/front-end-architect/references/code-patterns.md deleted file mode 100644 index ea0c2fb..0000000 --- a/.claude/skills/front-end-architect/references/code-patterns.md +++ /dev/null @@ -1,649 +0,0 @@ -# Code patterns - -Reference implementations for each layer. Paths are relative to the project that owns the code: `platforms//src/` for a product's logic and `packages//src/` for shared packages. `@project` is the workspace scope. The `@project/libs/*` APIs shown follow the lib specs: `http` and `isHttpError` in [lib-http.md](lib-http.md), the error handler's functions in [lib-error-handler.md](lib-error-handler.md), `storage` in [lib-local-storage.md](lib-local-storage.md), `cookie` in [lib-cookie.md](lib-cookie.md). `eventEmitter` stands for the repo's own lib; match its real signature. - -Caches, the page entrypoint, and server-to-client data live in [b2c-b2b.md](b2c-b2b.md). - -This file is the house code for each layer. Which design pattern to use, when, and where it lives is in [design-patterns.md](design-patterns.md). Error boundaries, fallbacks, empty states, and the query client's error settings are in [error-handling.md](error-handling.md), and their code in [error-handling-code.md](error-handling-code.md). - -Read only the section you need: - -| You are writing | Section | -|---|---| -| An island component or a variant | [Island component module](#island-component-module) | -| Tokens, or a project's Tailwind sources | [Tokens and Tailwind wiring](#tokens-and-tailwind-wiring) | -| A repository, its types, mapper, or query keys | [Repository](#repository) | -| An action and its event | [Action](#action) | -| A form, a page or part model, or server errors on a form | [Validation, model, and server errors](#validation-model-and-server-errors) | -| A mutation and its cache update | [Mutation with a valid cache](#mutation-with-a-valid-cache) | -| A store | [Store](#store), and [Persisted store](#persisted-store) when it survives a reload | -| A project's env | [Env](#env) | - -## Island component module - -`atoms/button/variants.ts` - -```ts -import { cva } from 'class-variance-authority'; - -export const buttonVariants = cva( - 'inline-flex cursor-pointer items-center justify-center gap-2 rounded-md font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-action-primary disabled:cursor-not-allowed disabled:opacity-50', - { - variants: { - variant: { - primary: 'bg-action-primary text-on-action hover:bg-action-primary-hover', - secondary: 'border border-border-subtle bg-surface-card text-text-primary hover:bg-surface-muted', - danger: 'bg-status-danger text-on-action hover:bg-status-danger-hover', - }, - size: { - sm: 'h-8 px-3 text-sm', - md: 'h-10 px-4 text-sm', - lg: 'h-11 px-5 text-base', - }, - }, - defaultVariants: { variant: 'primary', size: 'md' }, - }, -); -``` - -`atoms/button/types.ts` - -```ts -import type { VariantProps } from 'class-variance-authority'; -import type { ComponentPropsWithRef } from 'react'; -import type { buttonVariants } from './variants'; - -export type ButtonProps = ComponentPropsWithRef<'button'> & - VariantProps & { - isLoading?: boolean; - }; -``` - -`atoms/button/Button.tsx` - -```tsx -import { cn } from '../../tools/cn'; -import { Spinner } from '../spinner'; -import type { ButtonProps } from './types'; -import { buttonVariants } from './variants'; - -export function Button({ - className, - variant, - size, - isLoading = false, - disabled, - type = 'button', - children, - ...props -}: ButtonProps) { - return ( - - ); -} -``` - -`atoms/button/index.ts` - -```ts -export { Button } from './Button'; -export type { ButtonProps } from './types'; -export { buttonVariants } from './variants'; -``` - -`tools/cn/cn.ts` - -```ts -import { clsx, type ClassValue } from 'clsx'; -import { twMerge } from 'tailwind-merge'; - -export function cn(...inputs: ClassValue[]): string { - return twMerge(clsx(inputs)); -} -``` - -tailwind-merge doesn't know the theme. If `theme.css` adds a token it can't classify, such as a font size `text-body-sm` (which it reads as a color and drops next to `text-text-primary`), build `cn` with `extendTailwindMerge` and register the token. - -## Tokens and Tailwind wiring - -`styles/theme.css`: primitives are plain theme values, semantic tokens point at primitives and switch per theme, and `@theme inline` turns the semantic tokens into utilities (`bg-surface-card`, `text-text-muted`). Components use only the semantic utilities, so they never need `dark:` variants. - -```css -@theme { - --color-neutral-0: #ffffff; - --color-neutral-50: #f4f6fa; - --color-neutral-900: #161b23; - --color-neutral-950: #0f1319; - --color-blue-500: #3b82f6; - --color-blue-600: #2563eb; -} - -:root { - --surface-page: var(--color-neutral-50); - --surface-card: var(--color-neutral-0); - --action-primary: var(--color-blue-600); -} - -.dark { - --surface-page: var(--color-neutral-950); - --surface-card: var(--color-neutral-900); - --action-primary: var(--color-blue-500); -} - -@theme inline { - --color-surface-page: var(--surface-page); - --color-surface-card: var(--surface-card); - --color-action-primary: var(--action-primary); -} -``` - -This is an excerpt. The real file defines every semantic token the components use, such as `text-primary`, `text-muted`, `border-subtle`, `on-action`, the `status-*` colors, and their hover states. - -`styles/island.css` - -```css -@import './theme.css'; -@import './fonts.css'; -@import './utilities.css'; -@source '../'; - -@layer base { - * { - scroll-behavior: smooth; - } - - @media (prefers-reduced-motion: reduce) { - * { - scroll-behavior: auto; - } - } -} -``` - -`styles/fonts.css`. Each `src` is a root path to the file in the app's `public/fonts/`, so no build step renames it ([ui-rules.md](ui-rules.md#fonts-and-the-icon-sprite)). The fallback face is a local font resized to the web font's metrics, so the swap doesn't shift layout. Measure the override values once for each face, and list the fallback after the web font in `--font-sans` in `theme.css`. - -```css -@font-face { - font-family: 'Yekan Bakh'; - src: url('/fonts/yekan-bakh-vf.woff2') format('woff2'); - font-weight: 100 900; - font-display: swap; -} - -@font-face { - font-family: 'Yekan Bakh Fallback'; - src: local('Tahoma'); - size-adjust: 102%; - ascent-override: 95%; - descent-override: 28%; - line-gap-override: 0%; -} -``` - -`apps//src/styles/app.css` - -```css -@import 'tailwindcss' source('../'); -@import '@project/island/styles/island.css'; -@source '../../../../platforms//src'; -``` - -Tailwind generates only the classes it finds in registered sources. island registers itself in `island.css`; the app registers its own `src/`, its platform, and any integration that renders UI. CSS `@import` resolves package names through package.json `exports`, not TypeScript path aliases, so path-alias workspaces import `island.css` by relative path. - -## Repository - -`features/auth/entities/user/types.ts` - -```ts -export type UserRole = 'customer' | 'seller'; - -export type User = { - id: string; - full_name: string; - role: UserRole; -}; -``` - -`features/auth/repositories/auth/types.ts` - -```ts -import type { User, UserRole } from '../../entities/user'; - -export type LoginArgs = { phone: string; password: string }; - -export type LoginDto = { mobile: string; password: string }; - -export type LoginResponseDto = { user: User; is_first_login: boolean }; - -export type LoginPayload = { - user: { id: string; fullName: string; role: UserRole }; - isFirstLogin: boolean; -}; -``` - -`features/auth/repositories/auth/mappers.ts` - -```ts -import type { LoginArgs, LoginDto, LoginPayload, LoginResponseDto } from './types'; - -export function toLoginDto(args: LoginArgs): LoginDto { - return { mobile: args.phone, password: args.password }; -} - -export function toLoginPayload(dto: LoginResponseDto): LoginPayload { - return { - user: { id: dto.user.id, fullName: dto.user.full_name, role: dto.user.role }, - isFirstLogin: dto.is_first_login, - }; -} -``` - -`features/auth/repositories/auth/constants.ts` - -```ts -export const AUTH_ENDPOINTS = { - login: '/auth/login', - logout: '/auth/logout', - refresh: '/auth/refresh', -} as const; -``` - -`features/auth/http.ts`. Every feature has one; this feature needs nothing special, so it only extends the root. A feature with its own service sets `baseUrl`, headers, timeout, or retry here (see [lib-http.md](lib-http.md#root-and-feature-clients)). - -```ts -import { http } from '@project/libs/http'; - -export const authHttp = http.extend({}); -``` - -`features/auth/repositories/auth/auth.ts`. Repositories send requests only through their feature's client and never through the root `http`. Login sends `skipRefresh: true`: the back end answers wrong credentials with 400 or 422 and field errors, so a 401 always means "no valid session" and never starts a refresh ([error-handling.md](error-handling.md#actions)). - -```ts -import { authHttp } from '../../http'; -import { AUTH_ENDPOINTS } from './constants'; -import { toLoginDto, toLoginPayload } from './mappers'; -import type { LoginArgs, LoginPayload, LoginResponseDto } from './types'; - -export const authRepository = { - async login(args: LoginArgs): Promise { - const response = await authHttp.post(AUTH_ENDPOINTS.login, toLoginDto(args), { - skipRefresh: true, - }); - return toLoginPayload(response); - }, -}; -``` - -Read methods take an optional last parameter `{ signal?: AbortSignal }` and forward it, so TanStack Query can cancel them (see Mutation with a valid cache). - -`features/auth/repositories/auth/index.ts` exports no `*Dto`: - -```ts -export { authRepository } from './auth'; -export { AUTH_ENDPOINTS } from './constants'; -export type { LoginArgs, LoginPayload } from './types'; -``` - -Query keys sit in the repository's `constants.ts`, start with the domain, and are hierarchical so invalidation is precise. `features/catalog/repositories/products/constants.ts`: - -```ts -import type { ListProductsArgs } from './types'; - -export const PRODUCTS_ENDPOINT = '/catalog/products'; - -export const productKeys = { - all: ['catalog', 'products'] as const, - lists: () => [...productKeys.all, 'list'] as const, - list: (args: ListProductsArgs) => [...productKeys.lists(), args] as const, - details: () => [...productKeys.all, 'detail'] as const, - detail: (id: string) => [...productKeys.details(), id] as const, -}; -``` - -## Action - -`features/auth/constants.ts`. Event names are `.`. - -```ts -export const AUTH_EVENTS = { - login: 'auth.login', - logout: 'auth.logout', -} as const; - -export const LAST_PHONE_STORAGE_KEY = 'last-phone'; -``` - -`features/auth/actions/login/actions.ts`. The repository throws the normalized `HttpError` when the request fails, so reaching the next line means the response was successful. The caller handles the error. - -```ts -import { eventEmitter } from '@project/libs/event-emitter'; -import { storage } from '@project/libs/local-storage'; -import { useAuthStore } from '../../../../stores/auth'; -import { AUTH_EVENTS, LAST_PHONE_STORAGE_KEY } from '../../constants'; -import { authRepository, type LoginArgs } from '../../repositories/auth'; - -export async function login(args: LoginArgs, { emit = true }: { emit?: boolean } = {}): Promise<'ok'> { - const { user, isFirstLogin } = await authRepository.login(args); - - useAuthStore.getState().setSession({ user, isFirstLogin }); - storage.setItem(LAST_PHONE_STORAGE_KEY, args.phone); - if (emit) eventEmitter.emit(AUTH_EVENTS.login, { userId: user.id }); - - return 'ok'; -} -``` - -- Every action emits its event as its last step, so a failed step throws before the emit and listeners only hear about completed operations. -- `{ emit: false }` is for callers that must not trigger listeners, such as an action that runs another action as one of its steps and emits its own event. -- Code that reacts to an action (analytics, another feature's refresh) subscribes to its event instead of being called from the action. Subscribe once, in an effect of the `AppShell`, and unsubscribe in its cleanup. - -## Validation, model, and server errors - -`shared/validations/base-validations.ts`. Messages are i18n keys; the field component translates them. Each message tells the user how to fix the value, for example "Enter an 11-digit mobile number that starts with 09." - -```ts -import { MOBILE_REGEX } from '@project/libs/regex'; -import * as v from 'valibot'; - -export const requiredString = (message: string) => v.pipe(v.string(), v.trim(), v.nonEmpty(message)); - -export const mobileNumber = (message: string) => - v.pipe(v.string(), v.trim(), v.regex(MOBILE_REGEX, message)); -``` - -`shared/validations/auth-validations.ts` - -```ts -import * as v from 'valibot'; -import { mobileNumber, requiredString } from './base-validations'; - -export const loginSchema = v.object({ - phone: mobileNumber('validation:phone.invalid'), - password: requiredString('validation:password.required'), -}); -``` - -`shared/validations/types.ts` - -```ts -import type * as v from 'valibot'; -import type { loginSchema } from './auth-validations'; - -export type LoginFormValues = v.InferOutput; -``` - -`shared/utils/show-action-error.ts`: the one error toast for a failed action ([error-handling.md](error-handling.md#actions)). It handles the error once, says what failed, adds the hint or a support sentence with the reference ID, and offers the button its retry kind allows. - -```ts -import { describeError, handleError, type TranslateFn } from '@project/libs/error-handler'; -import { toast } from 'sonner'; - -export type ShowActionErrorOptions = { - t: TranslateFn; - failedMessage: string; // what failed, naming the object: "Category 'Kitchenware' wasn't saved" - retry?: () => void; // only when running the action again is safe - reload?: () => void; // refetches the data the action changed, for 409 and 404 -}; - -export function showActionError(error: unknown, { t, failedMessage, retry, reload }: ShowActionErrorOptions): void { - const errorClass = handleError(error, { where: 'action' }); - if (errorClass.action === 'silent') return; - - const { message, hint, referenceId } = describeError(error, t); - const details = [message, hint].filter(Boolean).join(' '); - const button = - errorClass.retry === 'again' && retry - ? { label: t('errors:action.try-again'), onClick: retry } - : errorClass.retry === 'reload' && reload - ? { label: t('errors:action.reload'), onClick: reload } - : errorClass.retry === 'reload-page' - ? { label: t('errors:action.reload-page'), onClick: () => window.location.reload() } - : undefined; - - toast.error(failedMessage, { - id: `action-error:${failedMessage}`, - description: - details || t(referenceId ? 'errors:support.with-reference' : 'errors:support.without-reference', { referenceId }), - duration: Infinity, - testId: 'action-error', - action: button, - }); -} -``` - -`shared/utils/apply-server-errors.ts`: field errors go under the fields the form renders (the first one gets focus), field errors for fields it doesn't render and errors about the whole submission go to the form-level alert, and `showActionError` shows the toast. A field counts as rendered when it has a value, so every form sets `defaultValues` for every field. - -```ts -import { classifyError, describeError } from '@project/libs/error-handler'; -import { isHttpError } from '@project/libs/http'; -import type { FieldValues, Path, UseFormReturn } from 'react-hook-form'; -import { showActionError, type ShowActionErrorOptions } from './show-action-error'; - -export function applyServerErrors( - form: UseFormReturn, - error: unknown, - options: ShowActionErrorOptions, -): void { - if (classifyError(error).action === 'silent') return; - - const unmatched: string[] = []; - let hasFieldError = false; - for (const [field, message] of Object.entries(isHttpError(error) ? (error.fieldErrors ?? {}) : {})) { - if (form.getValues(field as Path) === undefined) { - unmatched.push(message); - continue; - } - form.setError(field as Path, { type: 'server', message }, { shouldFocus: !hasFieldError }); - hasFieldError = true; - } - - if (!hasFieldError && unmatched.length === 0) { - unmatched.push(describeError(error, options.t).message ?? options.failedMessage); - } - if (unmatched.length > 0) form.setError('root.server', { type: 'server', message: unmatched.join(' ') }); - - showActionError(error, options); -} -``` - -- Server field messages arrive translated; they are never passed through `t` again. The lib's own `errors:` keys are translated by `describeError`. -- The form keeps every value, so after a 5xx or a network error the user submits again, and after a 4xx they fix the field and resubmit. - -`features/auth/models/login/use-login-page.ts` - -```ts -import { valibotResolver } from '@hookform/resolvers/valibot'; -import { useRouter } from 'next/navigation'; -import { useForm } from 'react-hook-form'; -import { useTranslation } from 'react-i18next'; -import { toast } from 'sonner'; -import { applyServerErrors } from '../../../../shared/utils'; -import { loginSchema, type LoginFormValues } from '../../../../shared/validations'; -import { login } from '../../actions/login'; - -export function useLoginPage() { - const { t } = useTranslation('auth'); - const router = useRouter(); - const form = useForm({ - resolver: valibotResolver(loginSchema), - mode: 'onTouched', - defaultValues: { phone: '', password: '' }, - }); - - const submit = form.handleSubmit(async (values) => { - try { - await login(values); - toast.success(t('login.success')); - router.push('/'); - } catch (error) { - applyServerErrors(form, error, { t, failedMessage: t('login.failed') }); - } - }); - - return { form, submit, isSubmitting: form.formState.isSubmitting }; -} -``` - -`mode: 'onTouched'` validates a field on its first blur and on every change after that. The submit button is disabled only while `isSubmitting`, never because the form is invalid, so users can click it to find out what is wrong. Login passes no `retry`: submitting again is the retry, and sending credentials twice from a toast would surprise the user. - -## Mutation with a valid cache - -After every create, update, or delete, set the detail, patch the affected lists, then invalidate the lists to reconcile in the background. When patching isn't practical, invalidate every key that can contain the entity (details, lists, counts, dashboards). Never rely on `staleTime` expiring. - -Use optimistic updates only for quick toggles (active/inactive, favorite), always with a rollback in `onError` and `showActionError` explaining the failure. - -The query needs no error branch: a failed first load throws to the part's boundary, and a failed refetch keeps the data ([error-handling.md](error-handling.md#reads)). The mutation's `onError` shows the toast. Updating a product is a PUT, so running it again is safe and the toast offers Try again with the same input. - -`features/catalog/models/product-edit/use-product-edit-page.ts` - -```ts -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { useTranslation } from 'react-i18next'; -import { toast } from 'sonner'; -import { showActionError } from '../../../../shared/utils'; -import { productKeys, productsRepository, type ProductsPagePayload } from '../../repositories/products'; - -export function useProductEditPage(productId: string) { - const { t } = useTranslation('catalog'); - const queryClient = useQueryClient(); - - const product = useQuery({ - queryKey: productKeys.detail(productId), - queryFn: ({ signal }) => productsRepository.get({ id: productId }, { signal }), - }); - - const save = useMutation({ - mutationFn: productsRepository.update, - onSuccess: (updated) => { - queryClient.setQueryData(productKeys.detail(updated.id), updated); - queryClient.setQueriesData({ queryKey: productKeys.lists() }, (page) => - page ? { ...page, items: page.items.map((item) => (item.id === updated.id ? updated : item)) } : page, - ); - void queryClient.invalidateQueries({ queryKey: productKeys.lists() }); - toast.success(t('product.saved', { name: updated.name })); - }, - onError: (error, args) => - showActionError(error, { - t, - failedMessage: t('product.saveFailed', { name: args.name }), - retry: () => { - save.mutate(args); - }, - reload: () => { - void queryClient.invalidateQueries({ queryKey: productKeys.detail(productId) }); - }, - }), - }); - - return { product, save }; -} -``` - -A form that saves through the mutation awaits `mutateAsync` inside `form.handleSubmit` and calls `applyServerErrors` in its `catch` ([design-patterns.md](design-patterns.md#patterns-the-architecture-already-uses)). Leave `onError` out then, so the toast shows once. - -## Store - -`stores/auth/types.ts` - -```ts -import type { LoginPayload } from '../../features/auth'; - -export type Session = { - user: LoginPayload['user']; - isFirstLogin: boolean; -}; - -export type ViewerStatus = 'unknown' | 'guest' | 'member'; - -export type AuthState = { - status: ViewerStatus; - session: Session | null; - setSession: (session: Session) => void; - clearSession: () => void; -}; -``` - -`stores/auth/auth-store.ts`. Components subscribe to the smallest slice they render, never to the whole store. - -```ts -import { create } from 'zustand'; -import { immer } from 'zustand/middleware/immer'; -import type { AuthState } from './types'; - -export const useAuthStore = create()( - immer((set) => ({ - status: 'unknown', - session: null, - setSession: (session) => - set((state) => { - state.status = 'member'; - state.session = session; - }), - clearSession: () => - set((state) => { - state.status = 'guest'; - state.session = null; - }), - })), -); - -export const useCurrentUser = () => useAuthStore((state) => state.session?.user); -export const useViewerStatus = () => useAuthStore((state) => state.status); -``` - -Never write to a store during server render (see b2c-b2b.md). - -- `status` stays `'unknown'` on the server and in the first browser render, so auth-dependent parts render their skeleton until the browser knows the viewer, and `'unknown'` never reads as a guest. -- The `AppShell` calls the auth feature's `restoreSession` action once in an effect. It reads the session through the auth repository and calls `setSession` or `clearSession` ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). - -## Persisted store - -A store that survives a reload keeps its data in local storage through the `storage` adapter, so the key lands under the app's prefix (`shop.session.cart`). `stores/cart/cart-store.ts`: - -```ts -import { storage } from '@project/libs/local-storage'; -import { create } from 'zustand'; -import { createJSONStorage, persist } from 'zustand/middleware'; -import { immer } from 'zustand/middleware/immer'; -import type { CartState } from './types'; - -export const useCartStore = create()( - persist( - immer((set) => ({ - items: [], - addItem: (item) => - set((state) => { - state.items.push(item); - }), - clear: () => - set((state) => { - state.items = []; - }), - })), - { - name: 'session.cart', - storage: createJSONStorage(() => storage), - version: 1, - partialize: (state) => ({ items: state.items }), - skipHydration: true, - }, - ), -); -``` - -- `name` is the key. `session.` marks it as the logged-in user's data, so logout's `storage.clearByPrefix('session.')` removes it. -- `partialize` persists only what must survive a reload. Bump `version` and add `migrate` when the shape changes. -- Keep `skipHydration: true` and rehydrate after mount, so the server render and the first browser render match. In the platform's `AppShell`: `useEffect(() => { void useCartStore.persist.rehydrate(); }, []);`. - -## Env - -The app's `env/` files, a project's `setEnv` and `getEnv`, and both bootstraps: [lib-env.md](lib-env.md#usage). diff --git a/.claude/skills/front-end-architect/references/decisions.md b/.claude/skills/front-end-architect/references/decisions.md deleted file mode 100644 index 6562a9b..0000000 --- a/.claude/skills/front-end-architect/references/decisions.md +++ /dev/null @@ -1,81 +0,0 @@ -# Decisions - -How to keep a project's architecture decision records (ADR) and design decision records (DDR) in one log, so a decision made once is followed in every later task. Read this file only when you add, accept, reject, or supersede a decision. To follow decisions, the index is enough ([SKILL.md](../SKILL.md)). - -Contents: Layout · When to record · Writing a record · Changing a decision · Precedence - -## Layout - -`docs/decisions/` at the monorepo root holds one file per decision and one index. Create both with the first decision. - -``` -docs/decisions/ - README.md # the index - 0001-zod-instead-of-valibot.md - 0002-island-components-over-native-elements.md -``` - -The index lists only live decisions, one line each. The line is the rule itself, one imperative sentence with its scope, so a task follows it without opening the record. Open a record only to change it, or when a case isn't clear from its line. - -```markdown -# Decisions - -## Design (DDR) -- 0002 Build UI with island components; never use native interactive elements (`button`, `input`, `select`, `textarea`, `a`) in features or apps. - -## Architecture (ADR) -- 0001 Validate with Zod instead of valibot in every project. - -## Proposed -- 0003 architecture: Load the reviews part only on interaction, on every product page. -``` - -- The area is where the rule applies: design for UI, island, tokens, copy, and UX; architecture for everything else. -- Keep a line under about 30 words. A rule that needs more is two decisions, or its detail belongs in the record. -- Rejected and superseded decisions leave the index. Their files stay, with their status, as history. - -## When to record - -- The user states a lasting rule for the project: "always", "never", "use X instead of Y", "from now on". Write it as `Accepted`, because the user decides, and say so in one line: "Recorded as decision 0004." -- You make a choice that is hard to undo, adds a dependency, deviates from this skill, or sets a pattern beyond the current task. Write it as `Proposed` and list it in the PR's plan. It binds nothing until the user accepts it. - -Don't record a one-off instruction for the current task, a rule this skill already states, or detail that one file shows. When you can't tell whether an instruction is lasting, follow it for the task and ask in your final message whether to record it. - -Before you propose a decision, search `docs/decisions/` for its topic, so you don't propose again what the user rejected or superseded. - -## Writing a record - -Number: the highest number in the folder plus 1, four digits. File name: `NNNN-.md`. Keep a record under about 25 lines. - -```markdown -# 0002 Island components over native elements - -Status: Accepted · Area: design · Date: 2026-10-04 · Decided by: user - -## Context -Why the decision came up, in one to three sentences. - -## Decision -The rule in the imperative, with its scope and exceptions. - -## Alternatives -- The option, and why it lost. "Not discussed" when the user gave none. - -## Consequences -What becomes easier or harder, and which existing code doesn't follow it yet. -``` - -- `Decided by` is `user` or `agent`. Add `Supersedes: NNNN` to the status line when it applies. -- Add the record's line to its area in the index, or to Proposed. -- Existing code that breaks a new decision is debt. List it under Consequences, and fix it only when the user asks or a task touches that code. - -## Changing a decision - -- Accept: set `Status: Accepted`, and move the line from Proposed to its area. -- Reject: set `Status: Rejected`, add the reason in one line under Decision, and remove the line from the index. -- Supersede: never rewrite the body of an accepted record. Write a new record with `Supersedes: NNNN`, set the old one to `Status: Superseded by MMMM`, and replace the old index line with the new one. A typo fix or clearer wording that keeps the rule is fine in place. -- When the user asks for something an accepted decision forbids, name the decision and ask: supersede it, or make a one-time exception. Record only a supersede. - -## Precedence - -An accepted decision overrides this skill's rules and your own judgment. A proposed decision overrides nothing. When a decision would break a rule that blocks a merge ([definition-of-done.md](definition-of-done.md#review)), such as tokens readable by JavaScript, state the risk once before you record it, and write the risk under Consequences. diff --git a/.claude/skills/front-end-architect/references/definition-of-done.md b/.claude/skills/front-end-architect/references/definition-of-done.md deleted file mode 100644 index ba0812f..0000000 --- a/.claude/skills/front-end-architect/references/definition-of-done.md +++ /dev/null @@ -1,89 +0,0 @@ -# Definition of Done and review - -Read it when you finish a task and write the PR, or when you review code. - -Contents: Checklist · B2C/B2B additions · Review - -## Checklist - -Copy this list and the list in B2C/B2B additions below into the PR description, and tick every item. Error handling adds its own list ([error-handling.md](error-handling.md#definition-of-done)). - -``` -Structure -[ ] Code is in the right project and folder, under src/, named per the naming rules -[ ] Each new or moved component went through "Choosing where a component goes"; its path, level, and reason are in the PR -[ ] Public API is exported by name from index.ts (and server.ts); no export * -[ ] ESLint boundaries pass; no upward or cross-product imports -[ ] Repositories have no client-side dependencies; UI and stores use *Payload types only -[ ] Repositories send requests only through their feature's http.ts client; no fetch outside the HTTP lib -[ ] Env is read only in the app's env/ files and through each project's getEnv(); no process.env elsewhere -[ ] No hard-coded env value, fallback, or schema default; every env value comes from the app's .env, and only apps have .env files -[ ] Every action emits its event when it succeeds, unless called with { emit: false } -[ ] No tokens or personal data in cookies or local storage; neither is read during render -[ ] Every new pattern answers a named signal and sits where design-patterns.md puts it; none is on its "Not used here" list -[ ] Each new or moved section went through rendering-patterns.md's "Choosing where a part loads"; its row in the page's rendering doc names its HTML, JS, and Index values -[ ] Every new or changed page has its rendering doc in docs/pages// and its line in docs/pages/README.md, added or updated in this PR as page-rendering.md's "Keeping docs current" says; the doc passes its ready-for-review checks and matches the production HTML of both templates -[ ] The server render is the same for every visitor; every auth-dependent page or part renders in the browser behind a same-size skeleton, unless the developer asked otherwise and the PR says so -[ ] Fonts and the icon sprite keep fixed names that no step hashes; every sprite change raised ICON_SPRITE_VERSION in the same commit -[ ] The service worker stores only /_next/static/ JS and CSS, fonts, and symbol-defs.svg: content-hashed JS and CSS cache first, the rest stale-while-revalidate; /sw.js keeps its name and its no-cache header -[ ] Every indexable page renders one JSON-LD graph through the json-ld lib and island's JsonLd, in the first flush, from its first-paint data; it says only what the page shows, the same for every visitor and in both templates; noindex pages and error states have none -[ ] Refactors are in their own commits, and the PR states how unchanged behavior was checked; smells noticed but not fixed are listed as debt -[ ] Code follows every accepted decision in docs/decisions; lasting decisions made in this work are recorded - -States and feedback -[ ] Loading, empty, error, and in-progress states exist -[ ] Every noindex or blocked page has a skeleton (loading.tsx), and no indexable page has a loading.tsx above it; every part that loads on its own has its own Suspense skeleton and part boundary (EB-S); the app has EB-W -[ ] Every completed action shows a toast, and every failed one the action-error toast with its hint or reference ID; reads never toast -[ ] Errors follow error-handling.md: 404 and 403 reads show their empty state, ABORTED and 401 stay silent, retries follow the cause, 5xx and logic errors are reported once -[ ] Query cache is updated or invalidated after every mutation; no stale data is visible -[ ] Refetches never swap content for a spinner; keys are stable - -Quality -[ ] All UI text comes from i18next; RTL and LTR both render correctly -[ ] AA contrast, focus-visible rings, keyboard operation -[ ] oxlint, prettier, ESLint boundaries, and type-check pass for affected projects -``` - -## B2C/B2B additions - -``` -[ ] Fresh page per request: Cache Components off; every root layout and metadata route exports dynamic = 'force-dynamic' -[ ] next.config.ts sets logging: { fetches: { fullUrl: true } } and htmlLimitedBots: /.*/ -[ ] No server cache: no 'use cache', unstable_cache, fetch caching, revalidate, or generateStaticParams; no back-end data kept in module scope -[ ] Server code reads data only through caches with primitive arguments; no page, loader, or server component calls a repository directly -[ ] Each client part gets server data as props or through query hydration; server prefetches call the cache -[ ] useSuspenseQuery only on queries the server prefetched -[ ] global-error.tsx, error.tsx in every route group, and not-found.tsx where notFound() is called; error pages are noindex -[ ] Server reads that can answer 404 or 403 go through readOnServer; every streamed part has a PartBoundary -[ ] Each template's first flush holds the page's primary content: the H1, the main data, the breadcrumb, the LCP image, the JSON-LD, and the links that are the only path to other pages; the page entry and every Server Component outside a Suspense await only the First flush reads, the reads the primary content needs -[ ] Both templates hold the same H1, primary content, internal links, image URLs and alt texts, title, description, canonical, robots, JSON-LD, and status; collapsed content stays in the DOM -[ ] Links are with real URLs in the server HTML; menus, tabs, drawers, and sliders render the links and panels that search engines need while closed; pagination and indexable filters are links with self-canonical URLs -[ ] Indexable pages have no loading.tsx, and no Suspense around children, above them, and every link to them is the platform's NavLink; entity pages answer a missing entity with a real 404 and a replaced one with a 308 -[ ] robots.ts disallows /search, /compare, and, on listing paths only, sort orders and non-indexable filters; never product pages or their variant URLs, cart, or checkout -[ ] The template is chosen by device class only, never isBot; where the repo has a unit test runner, a unit test pins Googlebot Smartphone to the mobile template; the reverse proxy or CDN adds Vary: User-Agent to HTML responses -[ ] Time-dependent UI reads useClock behind a same-size skeleton; no clock in a client component's render; absolute dates in server-rendered output are formatted on the server; nothing refreshes when a countdown ends -[ ] The server render is the same for every visitor: no session reads, no auth cookies forwarded, no viewer-dependent variant picked on the server; auth-dependent parts render their skeleton until the browser knows the viewer, unless the developer asked otherwise -[ ] Page is a thin entrypoint that renders the server-chosen mobile or desktop template -[ ] 'use client' only on interactive leaves; no server-only code reachable from client bundles -[ ] New server-only code is exported through server.ts and starts with import 'server-only' -[ ] First-load JS and each template's uncompressed HTML within budget, measured as page-rendering.md shows (next build no longer prints first-load JS); heavy widgets and third-party scripts deferred; a heavy client component that one template renders loads through next/dynamic -[ ] No hydration warnings; LCP image not lazy; images, fonts, and banners cause no layout shift -[ ] No store writes during server render; per-request QueryClient on the server -[ ] No cookie or local-storage reads during render; persisted stores rehydrate after mount -[ ] Metadata, canonical URL, and hreflang; every indexable page's JSON-LD follows lib-json-ld.md and passes the Rich Results Test -[ ] Fixed metadata and viewport values use the metadata and viewport exports; generateMetadata and generateViewport only for values that depend on the request or on data -[ ] Every root layout's viewport spreads ROOT_VIEWPORT (width=device-width, initial-scale=1, maximum-scale=1); never userScalable: false -[ ] The manifest's background_color and theme_color match theme.css, and it has the maskable 512 icon; every root layout's metadata includes APPLE_WEB_APP from configs/pwa.ts, and every startup image it lists exists in public/pwa/splash/ -[ ] Each release is built once, runs the same output on every instance, and is marked with NEXT_DEPLOYMENT_ID from CI -[ ] /_next/static/ keeps every release's files until 30 days after that release stopped serving -``` - -## Review - -Every review comment names the rule, shows the problem, and proposes the fix. For example: - -> **Repositories stay server-safe:** `products.ts` reads the page size with `storage.getItem`, which breaks server rendering. Pass `pageSize` in `ListProductsArgs` and read the stored value in an effect of the `use-products-page` model. - -Name a code smell and its technique, with the target layer or file, as [refactoring.md](refactoring.md#review-comments) does. A smell is a suggestion; when it also breaks a rule on the list below, lead with that rule, mark it blocking, and name the smell in the body. In a feature PR, raise smells only in the code the PR touches. Flag a pattern from the "Not used here" list in [design-patterns.md](design-patterns.md#not-used-here) with its alternative. Never flag the smells that refactoring.md marks as intended. - -Block a merge only for: code that breaks an accepted project decision; a boundary or layer violation; a client-side dependency in a repository; server-only code reachable from a client bundle; tokens or personal data readable by JavaScript (a non-HttpOnly cookie or local storage); stale cache after a mutation; a sprite change without a version bump, a font changed under its old name, or a font or sprite name that a build step hashes; a service worker that stores anything beyond JS, CSS, fonts, and the icon sprite, or a renamed or removed `/sw.js`; structured data that says what the page doesn't show or depends on the viewer, or an `application/ld+json` script written outside island's `JsonLd`; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; a server render that depends on auth without the developer's explicit request; a change to what a page's server HTML holds, or to when its code loads, without the matching rendering doc change; primary content, JSON-LD, or the only link to a page missing from the first flush of either template; an indexable page with a `loading.tsx`, or a `` around `children`, above it; a page not rendered per request, or a web-vitals, bundle-budget, or HTML-size regression. Everything else is a suggestion with a rationale. diff --git a/.claude/skills/front-end-architect/references/design-patterns.md b/.claude/skills/front-end-architect/references/design-patterns.md deleted file mode 100644 index e852845..0000000 --- a/.claude/skills/front-end-architect/references/design-patterns.md +++ /dev/null @@ -1,389 +0,0 @@ -# Design patterns - -How to pick and apply the GoF patterns from refactoring.guru and the JavaScript and React patterns from patterns.dev in this architecture. You already know the patterns, so this file gives only the decisions for this codebase: the signal that calls for each pattern, where it lives, its TypeScript shape, and when not to use it. Rendering and loading patterns are in [rendering-patterns.md](rendering-patterns.md), and code smells and refactoring techniques are in [refactoring.md](refactoring.md). Names match the source pages under refactoring.guru/design-patterns/ and patterns.dev/vanilla/ or patterns.dev/react/. - -Contents: How to choose · Patterns the architecture already uses · Adding a pattern · React and JavaScript patterns · Other GoF patterns · Not used here - -## How to choose - -1. **Start from a problem you have now, never from a pattern.** Name the signal, then use the smallest pattern that removes it: - - The same `switch` on a type in several places → Strategy as a `Record` map. - - The same object built in several places with small differences → a factory function. - - Several booleans that describe one flow (`isUploading`, `isProcessing`, `hasFailed`) → State as a discriminated union. - - A vendor SDK's types and calls spreading through the code → Adapter in an integration. - - A back-end field name reaching a component → Adapter in the repository's `mappers.ts`. - - One feature must react to another feature's completed operation → Observer through the action's event. - - Parts of one page that must stay in step → Mediator in the page model. - - The pieces of one widget passing the same state to each other through props → Compound component. - - Without a signal, write the direct code. -2. **Reuse the pattern the architecture already has for the job** (next section). A second event bus, HTTP wrapper, store library, or cache layer is a design error. -3. **Shape it with functions, closures, modules, and object literals.** Use a class only in a stateful lib whose spec already has one: `HttpClient`, `InterceptorManager`, `CookieAdapter`, or `LocalStorageAdapter`. Compose instead of inheriting. Error classes such as `HttpError` extend `Error`, and island's error-boundary primitive (`packages/island/src/primitives/error-boundary/ErrorBoundary.tsx`) extends React's `Component`, because React has no hook for catching render errors. Nothing else inherits, and no component inherits from another component. -4. **Keep a pattern inside its layer.** No pattern justifies an upward or cross-product import, or a break in the feature's layer order ([project-structure.md](project-structure.md#feature-anatomy)). When two layers must meet, wire them one level up: the AppShell subscribes, and the bootstrap configures. -5. **On the server, module scope holds only startup configuration and immutable helpers built from a fixed set, such as one `Intl` formatter per supported locale and time zone.** A singleton, a flyweight pool, or a memoized value in module scope serves every request, so it never holds back-end data, rendered output, or per-request or per-user data, even when every user would see the same value ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). -6. **Wait for the third case before you extract an abstraction.** Two similar blocks can stay duplicated; the third one shows what really varies. island is the exception: a second style becomes a variant at once ([refactoring.md](refactoring.md)). -7. **Make the role visible in the name**, following the repo's conventions. Factories are camelCase `create*` functions (`createHttpClient`; `makeQueryClient` keeps the name from TanStack's docs). Key factories are camelCase objects (`productKeys`). Constant maps are UPPER_SNAKE_CASE (`AUTH_EVENTS`). A class or type that wraps a browser or vendor API ends in `Adapter` (`CookieAdapter`, `AnalyticsAdapter`), and its instance takes the domain name (`cookie`, `analytics`). A strategy map is a constant map named `_` (`ORDER_STATUS_BADGES`). A state machine lives in `-flow.ts` and exports `State`, `Event`, `Reducer`, and `INITIAL__STATE`, with dotted event types that name what happened (`file.selected`). -8. **Record a new, non-obvious pattern** in the PR description: the signal, the pattern, and the simpler option you rejected. - -## Patterns the architecture already uses - -Reuse these before you add anything. - -| Pattern | Where it lives | Rule | -|---|---|---| -| Module | Every module's `index.ts`; `server.ts` for server-only code | Every module. Re-export the public API by name and keep the rest private: never `export *`, never import another module's internal file, and never re-export `server.ts` from `index.ts` ([project-structure.md](project-structure.md#exports-and-tree-shaking)) | -| Singleton | The root `http`, `cookie`, `storage`, `eventEmitter`, zustand stores, and the browser `QueryClient` from `getQueryClient()` | For a service the whole app shares: a module instance that the bootstrap configures (`export const cookie = new CookieAdapter()`), never a class with `getInstance`. On the server one instance serves every request, so per-request objects come from a function (a new `QueryClient` per `getQueryClient()` call, a per-request i18next instance), and nothing writes to a store during server render ([b2c-b2b.md](b2c-b2b.md#state-and-auth)) | -| Factory functions | `createHttpClient`, `createClientEnv`, `createServerEnv`, `makeQueryClient`, and key factories such as `productKeys` | When several callers build the same kind of object from different inputs: a function that returns a new object or closure. Query keys always come from the repository's key factory ([code-patterns.md](code-patterns.md#repository)). Don't add a factory for an object built in one place | -| Adapter | `CookieAdapter` over `document.cookie`; each repository's `mappers.ts`; each integration over its vendor API; the json-ld lib over the schema.org vocabulary | At a boundary whose shape you don't own. Translate once, at the edge, so no `*Dto`, vendor type, cookie string syntax, or schema.org shape crosses it. Don't adapt two of your own modules to each other; change one of them | -| Facade | The `http` client over `fetch`, `XMLHttpRequest`, retry, refresh, and abort; feature actions over repositories, stores, storage, and events | When callers would repeat the same sequence of calls into several parts: one function, or one object with a few verbs. Callers never reach past it: no `fetch` outside the HTTP lib, and no model that repeats an action's steps | -| Proxy | Features' `caches/` (React `cache()`); `LocalStorageAdapter`; route guards; lazy widgets; the pwa lib's service worker | A cache dedupes calls within one request and never outlives it. The service worker stands in front of the network only for JS, CSS, fonts, and the icon sprite ([lib-pwa.md](lib-pwa.md)). `LocalStorageAdapter` keeps the `Storage` interface while it namespaces keys and absorbs blocked storage, so it works as a Proxy; keep the name its spec gives it. A guard lets a route through only when its check passes. When lazy loading pays off is in rendering-patterns.md | -| Decorator | zustand middleware: `immer` and `persist` | When a store needs cross-cutting behavior: wrap the creator and keep its shape, as in `persist(immer(...))` ([code-patterns.md](code-patterns.md#persisted-store)). No TypeScript decorator syntax, and no higher-order components that wrap components (see HOC below) | -| Chain of Responsibility | HTTP request and response interceptors; Next.js `proxy.ts`; nested error boundaries | For steps that every request or error passes through. Interceptors run root first and carry only cross-cutting concerns ([lib-http.md](lib-http.md#interceptors)). `proxy.ts` either answers (a redirect) or passes the request on, after it refreshes an expired session. An error stops at the nearest error boundary: part, then page, then app ([error-handling.md](error-handling.md#boundaries)). Never put business logic in a link | -| Observer | Action events through `eventEmitter`; zustand selectors; the TanStack Query cache and the queries that observe it | When code must react to a change that its source shouldn't know about. Events fire only after an operation completes. A listener subscribes once in an AppShell effect and unsubscribes in its cleanup, and a component subscribes to the smallest slice. The emitter only broadcasts, so coordination stays in actions and models | -| Mediator | The page model, between its part models | When parts of one page must stay in step. Parts never import or call each other: the page model owns what they share (the current step, the final submit) and passes it down as props. Don't add a context or a store for one page's parts. Run the page model in the smallest client component that contains the coordinated parts, never in the template or the page, which stay Server Components ([b2c-b2b.md](b2c-b2b.md#rendering)). State that must survive a reload or a shared link goes in the URL | -| Command | `useMutation` around a repository call or a feature action | When the UI triggers an operation and shows its progress. The mutation holds the operation; the UI calls `mutate` and reads `isPending` and `error`, and an error toast's retry calls it again when running it twice is safe ([error-handling.md](error-handling.md#actions)). Feature actions are client-side operations, not Next.js Server Actions. No hand-made command objects with `execute` and `undo`; undo is a back-end operation offered in the toast. A multi-step flow with its own states runs the request from its State reducer's model instead; don't wrap the same call in `useMutation` as well. A form whose submit runs a feature action awaits it inside `form.handleSubmit` and uses `formState.isSubmitting` as its pending state ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)); don't wrap the action in `useMutation` as well. A form that saves through one repository call keeps the model's `useMutation` ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)) and awaits `mutateAsync` inside `form.handleSubmit`, catching the error for `applyServerErrors`, so `isSubmitting` and `isPending` agree | -| State | Multi-step flows: wizards, imports, bulk actions | When a flow has steps that carry different data: a state union, an event union, and a pure reducer in the model's folder (example below). Never a set of booleans | -| Strategy | Function-valued options such as the HTTP lib's `mapErrorBody` and `shouldRefresh`; sort comparators; the mobile or desktop template that the page picks on the server | When one contract has interchangeable implementations: pass a function, or pick an entry from a `Record` map (example below). Choose once, at the top: the page picks the template, and no component branches on viewport size. Don't add a strategy for behavior that never varies | -| Composite | Navigation menus, sidebar groups, and category trees | When a tree mixes leaves and groups: one node type (`children?: MenuNode[]`) and one recursive component. Filter the tree before rendering, so a group with no visible items disappears, and key nodes by id, never by index | -| Bridge | Semantic tokens over primitive tokens in island `theme.css` | For every component and theme. Components use semantic tokens only, and each theme maps them to primitives, so components and themes vary independently and a new theme touches only `theme.css` ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)). Never add a theme prop, `dark:` classes, or theme-specific variants to a component | -| Flyweight | The icon sprite, where every `` points at one ``; `Intl` formatters shared per locale and time zone in `packages/tools` | When many uses share heavy, immutable data: share that part and pass the rest per use (size and color for an icon, the value for a formatter). Date formatters always set `timeZone` explicitly to the one the server chose, never the runtime default ([b2c-b2b.md](b2c-b2b.md#hydration-and-navigation)). On the server, build a pool only from a fixed set such as the app's locales and supported time zones, never from user input, and never store formatted output | -| Memento | Persisted stores (`partialize`, `version`, `migrate`); react-hook-form `defaultValues` and `reset` | When state must be restored later. Snapshot only what must survive, and migrate old snapshots ([code-patterns.md](code-patterns.md#persisted-store)). After a successful save, `reset` the form with the saved values, so dirty tracking and the unsaved-changes warning start from the saved data. Never snapshot server data or loading flags | -| Iterator | `useInfiniteQuery` for feeds; an async generator in a repository | When code walks a paged collection without caring how the pages load. Infinite queries serve feeds only. Use an async generator over pages only when a flow must visit every page and the back end has no bulk endpoint | -| Container/Presentational with Hooks | Models with presentational pages, templates, and organisms; on the server, async server components that read caches | For every page and part. The model holds the data and handlers, and the page calls it and renders a template that only takes props. On the server, the container is an async server component that reads caches and passes `*Payload` props ([b2c-b2b.md](b2c-b2b.md#data-flow)). Components never call repositories or actions directly | -| Provider | The AppShell's providers; compound component contexts | For app-wide services, such as the query client and i18next, and for the parts of one compound component. Render `` and read it with `use(Context)` or `useContext` (React 19). Keep app-wide providers in the AppShell, and keep shared state out of context (see Provider below) | -| Compound | `DataTable` and other complex island organisms | When a widget's parts share state and the caller arranges them: the parts share state through context and are also exported by name (example below). A component with one fixed layout takes props instead | -| Render props | Slots for `DataTable` cells, empty states, and toolbars | When the caller varies part of an organism: a `ReactNode` slot by default, and a render function (`cell: (row: TRow) => ReactNode`) only when the slot needs the organism's data. Never use one to share logic; write a hook | - -## Adding a pattern - -Where a new implementation goes: - -| Pattern | Home | Shape | -|---|---|---| -| Strategy map | The owning module's `constants.ts`. Other features import it through that feature's `index.ts`. Use `shared/constants/` only when neither its keys nor its values come from a feature, because `shared/` never imports from `features/` | A constant map named `_`, typed with `satisfies Record`. Styles that vary by a prop are cva variants instead | -| State machine | The page or part model's folder, such as `models/product-import/product-import-flow.ts` | The state union, the event union, and a pure reducer. The model runs it with `useReducer`. When the flow must outlive the page, move the flow file into the store's folder (`stores//-flow.ts`), have the store's action call the reducer, and have the model read the state through a selector. A store never imports from `models/` | -| Adapter for a vendor SDK | `packages/integrations/src//` | An object literal or functions typed by the integration's own `types.ts`, with no vendor type in its public API | -| Adapter for an API shape | The repository's `mappers.ts` | `toDto(args)` and `toPayload(dto)` ([code-patterns.md](code-patterns.md#repository)) | -| Facade over several repositories or side effects | An action in the feature that owns the operation: `actions//actions.ts` | One async function with the `{ emit }` option that emits its event last ([code-patterns.md](code-patterns.md#action)) | -| Observer listener | An effect of the AppShell | Subscribe once, and return the unsubscribe function as the effect's cleanup | -| Factory | Beside what it builds: in the module's main file when the module exists to build that thing (`createHttpClient` in `http.ts`), otherwise its own `create-.ts` in the owning module | `create(options): Thing`, returning an object literal or a closure | -| Exhaustive check | `assertNever` in `packages/tools/src/assert-never/` | `assertNever(value: never): never` throws. Call it in the `default` of every `switch` over a union | -| Generic hook with no feature data, such as `useDebouncedValue` or `useClock` ([rendering-patterns.md](rendering-patterns.md#time-dependent-ui)) | `packages/tools/src/use-debounced-value/use-debounced-value.ts` when more than one project needs it; otherwise beside its only user, such as an organism's `hooks/` | A `use-.ts` hook that takes plain values and imports only React. A hook that reads a store, a query, or a `*Payload` belongs in the owning feature's `models/` or beside its store | - -The examples use feature paths relative to `platforms//src/`, as code-patterns.md does. - -**Strategy.** An order's status picks its badge in the order list, the order header, and the timeline. One map replaces the three switches, and `satisfies` makes a new status fail type-check until it has an entry. - -`features/orders/constants.ts` - -```ts -import type { BadgeProps } from '@project/island/atoms/badge'; -import type { OrderStatus } from './entities/order'; - -export const ORDER_STATUS_BADGES = { - pending: { variant: 'warning', labelKey: 'orders:status.pending' }, - paid: { variant: 'info', labelKey: 'orders:status.paid' }, - shipped: { variant: 'info', labelKey: 'orders:status.shipped' }, - delivered: { variant: 'success', labelKey: 'orders:status.delivered' }, - cancelled: { variant: 'danger', labelKey: 'orders:status.cancelled' }, -} as const satisfies Record; labelKey: string }>; -``` - -A component reads `const badge = ORDER_STATUS_BADGES[order.status]` and renders `{t(badge.labelKey)}`. - -**State.** A product import goes `idle → validating → uploading → processing → done | failed`. The flow file holds the states, the events, and a pure reducer. An event that doesn't fit the current state returns the state unchanged. - -`features/catalog/models/product-import/product-import-flow.ts` - -```ts -import { assertNever } from '@project/tools/assert-never'; -import type { ProductImportReportPayload } from '../../repositories/product-imports'; - -export type ProductImportState = - | { status: 'idle' } - | { status: 'validating'; file: File } - | { status: 'uploading'; file: File; percent: number } - | { status: 'processing'; file: File } - | { status: 'done'; report: ProductImportReportPayload } - | { status: 'failed'; error: unknown }; - -export type ProductImportEvent = - | { type: 'file.selected'; file: File } - | { type: 'file.validated' } - | { type: 'upload.progressed'; percent: number } - | { type: 'import.succeeded'; report: ProductImportReportPayload } - | { type: 'import.failed'; error: unknown } - | { type: 'import.cancelled' }; - -export const INITIAL_PRODUCT_IMPORT_STATE: ProductImportState = { status: 'idle' }; - -export function isProductImportBusy(state: ProductImportState): boolean { - return state.status === 'validating' || state.status === 'uploading' || state.status === 'processing'; -} - -export function productImportReducer(state: ProductImportState, event: ProductImportEvent): ProductImportState { - switch (event.type) { - case 'file.selected': - return isProductImportBusy(state) ? state : { status: 'validating', file: event.file }; - case 'file.validated': - return state.status === 'validating' ? { status: 'uploading', file: state.file, percent: 0 } : state; - case 'upload.progressed': - if (state.status !== 'uploading') return state; - return event.percent < 100 ? { ...state, percent: event.percent } : { status: 'processing', file: state.file }; - case 'import.succeeded': - return state.status === 'uploading' || state.status === 'processing' - ? { status: 'done', report: event.report } - : state; - case 'import.failed': - return isProductImportBusy(state) ? { status: 'failed', error: event.error } : state; - case 'import.cancelled': - return INITIAL_PRODUCT_IMPORT_STATE; - default: - return assertNever(event); - } -} -``` - -`features/catalog/models/product-import/use-product-import-page.ts`. The progress comes from the feature client's `upload()` through the repository ([lib-http.md](lib-http.md#files)). The server answers with the report after it processes the file, so the flow enters `processing` when the upload reaches 100%. - -```ts -import { useReducer, useRef } from 'react'; -import * as v from 'valibot'; -import { productImportFileSchema } from '../../../../shared/validations'; -import { productImportsRepository } from '../../repositories/product-imports'; -import { INITIAL_PRODUCT_IMPORT_STATE, productImportReducer } from './product-import-flow'; - -export function useProductImportPage() { - const [state, dispatch] = useReducer(productImportReducer, INITIAL_PRODUCT_IMPORT_STATE); - const controllerRef = useRef(null); - - async function start(file: File) { - if (controllerRef.current) return; - const controller = new AbortController(); - controllerRef.current = controller; - dispatch({ type: 'file.selected', file }); - try { - await v.parseAsync(productImportFileSchema, file); - if (controller.signal.aborted) return; - dispatch({ type: 'file.validated' }); - const report = await productImportsRepository.upload( - { file }, - { - signal: controller.signal, - onProgress: ({ percent }) => dispatch({ type: 'upload.progressed', percent }), - }, - ); - if (controller.signal.aborted) return; - dispatch({ type: 'import.succeeded', report }); - } catch (error) { - if (!controller.signal.aborted) dispatch({ type: 'import.failed', error }); - } finally { - if (controllerRef.current === controller) controllerRef.current = null; - } - } - - function cancel() { - controllerRef.current?.abort(); - controllerRef.current = null; - dispatch({ type: 'import.cancelled' }); - } - - return { state, start, cancel }; -} -``` - -- The controller is the in-flight guard: it exists from the first step, so a second `start` (a double click) returns at once. `cancel` aborts it and clears the ref, so a cancel during validation never starts the upload, and a new file can start right away. -- An aborted run dispatches nothing, so the `ABORTED` error is never shown and a late event from the old run can't touch the new one. -- After `import.succeeded`, the model also shows a toast and invalidates the product lists ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)). Both are left out here. -- The template switches on `state.status`, with `assertNever` in the `default`. - -**Observer with Adapter.** The analytics integration adapts a tag manager's `dataLayer`, which needs no npm dependency. Integrations can't import features, so the AppShell wires the auth feature's event to the integration. - -`packages/integrations/src/analytics/types.ts` - -```ts -export type AnalyticsEvent = { name: 'login' | 'logout' | 'purchase'; params?: Record }; - -export type AnalyticsAdapter = { track: (event: AnalyticsEvent) => void }; - -declare global { - interface Window { - dataLayer?: Record[]; - } -} -``` - -`packages/integrations/src/analytics/analytics.ts`. The rest of the code calls `analytics.track`, so a change of vendor touches only this file. - -```ts -import type { AnalyticsAdapter } from './types'; - -export const analytics: AnalyticsAdapter = { - track(event) { - if (typeof window === 'undefined') return; - (window.dataLayer ??= []).push({ event: event.name, ...event.params }); - }, -}; -``` - -`platforms//src/app/app-shell/AppShell.tsx`, reduced to the subscription. - -```tsx -'use client'; - -import { analytics } from '@project/integrations/analytics'; -import { eventEmitter } from '@project/libs/event-emitter'; -import { useEffect } from 'react'; -import { AUTH_EVENTS } from '../../features/auth'; -import type { AppShellProps } from './types'; - -export function AppShell({ children }: AppShellProps) { - useEffect(() => { - const unsubscribe = eventEmitter.on(AUTH_EVENTS.login, () => analytics.track({ name: 'login' })); - return unsubscribe; - }, []); - - return children; -} -``` - -This assumes that `on` returns an unsubscribe function. Match the repo's real event-emitter signature, for example by calling its `off` in the cleanup. Loading the tag manager's script is a loading decision, covered in rendering-patterns.md. - -**Compound component.** island's `Tabs` organism: the root owns the state, the parts read it from a context, and every part is exported by name. - -`packages/island/src/organisms/tabs/hooks/use-tabs-context.ts`, private to the organism: - -```ts -import { createContext, useContext } from 'react'; -import type { TabsContextValue } from '../types'; - -export const TabsContext = createContext(null); - -export function useTabsContext(): TabsContextValue { - const context = useContext(TabsContext); - if (!context) throw new Error('Tabs parts must be rendered inside .'); - return context; -} -``` - -`packages/island/src/organisms/tabs/Tabs.tsx`. Memoize the context value, so a root re-render that keeps the same tab doesn't re-render parts that sit behind a `memo` boundary. Skip `useMemo` when the repo enables the React Compiler. - -```tsx -'use client'; - -import { useId, useMemo, useState } from 'react'; -import { TabsList } from './components/tabs-list'; -import { TabsPanel } from './components/tabs-panel'; -import { TabsTrigger } from './components/tabs-trigger'; -import { TabsContext } from './hooks/use-tabs-context'; -import type { TabsProps } from './types'; - -function TabsRoot({ defaultValue, children }: TabsProps) { - const [activeValue, setActiveValue] = useState(defaultValue); - const baseId = useId(); - const context = useMemo(() => ({ activeValue, select: setActiveValue, baseId }), [activeValue, baseId]); - return {children}; -} - -export const Tabs = Object.assign(TabsRoot, { List: TabsList, Trigger: TabsTrigger, Panel: TabsPanel }); -``` - -`packages/island/src/organisms/tabs/components/tabs-trigger/TabsTrigger.tsx`. `TabsPanel` reads the same context. It renders its children the first time its tab is selected, then keeps them mounted inside `` while another tab is active, so switching tabs never remounts a visited panel. A panel whose content must be in the server HTML, such as product details for search engines, takes `forceMount` and is hidden with the `hidden` attribute instead. `TabsList` only renders `role="tablist"`. Arrow-key movement between tabs is left out to keep the example short. - -```tsx -'use client'; - -import { useTabsContext } from '../../hooks/use-tabs-context'; -import type { TabsTriggerProps } from './types'; -import { tabsTriggerVariants } from './variants'; - -export function TabsTrigger({ value, children }: TabsTriggerProps) { - const { activeValue, select, baseId } = useTabsContext(); - const isSelected = activeValue === value; - return ( - - ); -} -``` - -`packages/island/src/organisms/tabs/index.ts` - -```ts -export { Tabs } from './Tabs'; -export { TabsList, type TabsListProps } from './components/tabs-list'; -export { TabsPanel, type TabsPanelProps } from './components/tabs-panel'; -export { TabsTrigger, type TabsTriggerProps } from './components/tabs-trigger'; -export type { TabsProps } from './types'; -``` - -Pitfall: a Server Component can't reach a part through the root. island modules are ES modules, so on the server each export of a `'use client'` file is only a client reference. `Tabs.List` is `undefined` there, so the render fails, and the error message depends on the bundler. So Server Components compose the named parts, and `Tabs.List` stays for client components. The panels' content can stay server-rendered, and panels that search engines must read take `forceMount`: - -`apps//src/app/(shop)/product/[id]/templates/product-desktop/ProductDesktop.tsx`, excerpt: - -```tsx - - - {t('catalog:product.tabs.details')} - {t('catalog:product.tabs.shipping')} - - - - - - - - -``` - -## React and JavaScript patterns - -Decisions for the patterns.dev design patterns that the table above leaves open: - -- **HOC**: not used for new code. Put cross-cutting behavior in a hook or a wrapper component, such as an error boundary. React's own `memo` and `lazy` are fine, and so is Next.js's `catchError`, which builds the `PartBoundary` ([error-handling.md](error-handling.md#boundaries)). `ref` is a regular prop in React 19, so new components skip `forwardRef` too. -- **Render props versus slots**: a Server Component can't pass a plain function to a client component, so it passes only `ReactNode` slots. An organism that needs render functions, such as a `DataTable` with custom cells, is rendered from a client component that defines them. -- **Provider**: context carries services and one compound component's state, never app data. Shared client state goes to a zustand store read through selectors, server state to the query cache, and form state to react-hook-form; never mirror any of them into a context. Split large contexts. The one store-in-context case is a store that must start from server data ([b2c-b2b.md](b2c-b2b.md#state-and-auth)). -- **Hooks added in React 19**: `useActionState`, `useFormStatus`, and `useOptimistic` are built for React's actions. Forms here run on react-hook-form with the model's `submit`, and optimistic toggles go through the query cache with a rollback ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)), so don't add a second pending or optimistic state for the same data. `use()` reads a streamed promise inside `` ([b2c-b2b.md](b2c-b2b.md#data-flow)). -- **Mixin**: not used. Share behavior with functions, hooks, and composition, and never copy methods onto a class or a prototype. -- **Proxy object** (JavaScript `Proxy` and `Reflect`): not used in app code, because it hides behavior from readers and from the type checker. immer uses it inside zustand's `set`, so never keep a draft after `set` returns. For guarded configuration, write explicit functions, like a project's `getEnv` that throws before `setEnv` has run. -- **Prototype** (the prototype chain): only the custom prototypes lib (`packages/libs/src/custom-prototypes/`) extends built-ins. It adds each method with `Object.defineProperty` (non-enumerable), skips a name that already exists so it never overwrites a native or third-party method, declares the methods in a `declare global` block, and is listed in `sideEffects` ([project-structure.md](project-structure.md#exports-and-tree-shaking)). Import it at the top of each bootstrap. Everywhere else, write plain functions. -- **Mediator/Middleware**: patterns.dev joins two rows of the table: Mediator (the page model) and Chain of Responsibility (interceptors and `proxy.ts`). Don't add a central hub that components send messages through. -- **Server push**, such as a live order status or the progress of an import's `processing` step: poll first, with the part model's `useQuery` and a `refetchInterval` that stops when the status is final. Push is a lib change with its own spec and approval: SSE is a streaming method in the HTTP lib, as for AI UI below, so it shares the one refresh and abort, and a WebSocket client is a new lib in `packages/libs`. Never a raw `EventSource` or `WebSocket` in a model. The part model subscribes in an effect and writes each message to the query cache with `setQueryData`, never to a store. -- **AI UI Patterns**: only when the product has a chat or assistant page. The conversation is a part model's state, with each message a union by status (`streaming`, `done`, `failed`). Streamed replies need a streaming method in the HTTP lib, which is a lib change ([lib-http.md](lib-http.md)), never `fetch` in a model. The AI SDK is outside the stack, so state the reason and get approval before adding it. -- **React Stack Patterns**: a survey of tool choices, not a design pattern. The stack is fixed in [SKILL.md](../SKILL.md#2-stack), and any other pick needs a stated reason and approval. - -## Other GoF patterns - -The GoF patterns that the architecture doesn't already use: - -- **Factory Method**: not used in its class form, because nothing here inherits. When a caller needs one of several implementations by key, use a factory function (table above) or a `Record` from key to implementation in the owning module's `constants.ts`. A map of components inside a client component bundles every entry, so heavy entries map to lazy components; a map in a Server Component ships only the client entries it renders (rendering-patterns.md). -- **Abstract Factory**: rarely needed, because matching families are already chosen once, higher up: the theme through tokens (Bridge) and the device through the template. Don't build a context that swaps whole component kits; a second brand is a theme in `theme.css`. A real need for different component sets, such as white-label apps, is decided in the plan first. -- **Builder**: rarely needed. When a value has many optional parts, such as metadata from `configs/seo.ts` or JSON-LD built from a `*Payload` (the json-ld lib's `build*` functions and the platform's `app/json-ld/`, [lib-json-ld.md](lib-json-ld.md)), write a pure function that takes an options object with defaults and returns the finished value. No chained, mutable builder classes; valibot's `pipe` already composes schemas step by step. -- **Prototype**: copying is an immutable update: spread for a shallow copy, `structuredClone` for a deep copy of plain data, and immer drafts inside stores. `http.extend` isn't a Prototype: it delegates to the root live instead of copying it, so settings made later in bootstrap still apply ([lib-http.md](lib-http.md#api)). Never `structuredClone` an object that holds functions or class instances; it throws on functions and drops prototypes. -- **Template Method**: not used in its class form. Its component form already exists: island templates and organisms such as `PageHeader` fix the layout and take the varying parts as slots. For logic, write a function that owns the sequence and takes the varying steps as callbacks, such as `runImport({ validate, upload, dispatch })`, and move it to `shared/utils/` only when a third feature needs the same sequence. -- **Visitor**: rarely needed in app code. To run type-specific logic over mixed nodes, such as CMS content blocks or filter expressions, switch exhaustively over the discriminated union with `assertNever`, or use a `Record` from `type` to handler. A new operation is a new function, and a new node type fails type-check at every switch. No `accept` and `visit` double dispatch. - -## Not used here - -Keep these out of designs, and flag each one in review with its alternative. A merge blocks only for the reasons in [definition-of-done.md](definition-of-done.md#review), which include the server-side cache and boundary cases below. - -- **`getInstance` singleton classes.** Export a module instance. On the server, create per-request objects with a function such as `getQueryClient()`. -- **Module-scope per-request or per-user state on the server**, such as a `Map` of users, a memoized promise of back-end data, or a store written during render. Use a feature cache (React `cache()`), the per-request `QueryClient`, or props ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). -- **A service locator or DI container.** The bootstrap is the composition root: it passes settings to libs with `configure` and values to projects with `setEnv`, and each module imports what it uses by name. -- **Base classes** such as `BaseRepository` or `BaseService`. A repository is an object literal. Shared request behavior lives in the feature client and its interceptors ([lib-http.md](lib-http.md#root-and-feature-clients)), and shared logic lives in small functions. -- **Inheritance between components.** Compose with `children`, slots, cva variants, and compound parts. -- **HOCs and mixins in new code.** Use a hook or a wrapper component. -- **Events for request and response flows**, such as emitting `cart.totalRequested` and waiting for a reply event. Call the action or repository and await it; events only fan out after an operation completes. -- **A second event bus, cache layer, or state library**, such as RxJS subjects, a hand-made fetch cache, a service worker that stores pages or data, Redux, or a context used as a store. Use the event emitter, the query cache (or `cache()` within one server request), the pwa lib's worker for JS, CSS, fonts, and the icon sprite only, and zustand. -- **A pattern for a future that isn't planned.** Write the direct code, and extract the pattern when the third case arrives (refactoring.md). -- **A pattern that needs an upward or cross-product import, or `export *`**, such as an integration that imports a feature to listen to it. Wire it one level up, in the AppShell or the bootstrap, and re-export by name. -- **A pattern library without approval**, such as XState or InversifyJS. Use the in-stack alternative first: a discriminated union and a pure reducer in `useReducer` or a zustand store instead of XState, and the bootstrap's `configure` and `setEnv` instead of InversifyJS. Any dependency outside [the stack](../SKILL.md#2-stack) needs a stated reason and approval. diff --git a/.claude/skills/front-end-architect/references/error-handling-code.md b/.claude/skills/front-end-architect/references/error-handling-code.md deleted file mode 100644 index f87ce03..0000000 --- a/.claude/skills/front-end-architect/references/error-handling-code.md +++ /dev/null @@ -1,328 +0,0 @@ -# Error handling code - -The code for [error-handling.md](error-handling.md): island's error boundary, `ErrorFallback`, the part, page, and app boundaries, `readOnServer`, and the query client's error settings. Read it only when you build or change one of these. A feature that uses them needs only error-handling.md. - -Contents: island's error boundary · The fallback · Part boundary · Page and app boundaries · Query client · Server reads · Actions - -Paths are relative to `platforms//src/`, as in [code-patterns.md](code-patterns.md). Each `error-boundaries//` module is shaped like `guards/`: the component or function, its `types.ts`, and `index.ts`. - -## island's error boundary - -`packages/island/src/primitives/error-boundary/ErrorBoundary.tsx` is a class, because React has no hook for catching render errors. It knows nothing about HTTP or reporting; the fallback does that. Its `types.ts` declares `ErrorBoundaryProps`: `children`, `fallback: (props: { error: unknown; reset: () => void }) => ReactNode`, `onReset?`, and `resetKeys?: readonly unknown[]`. - -```tsx -'use client'; - -import { Component } from 'react'; -import type { ErrorBoundaryProps } from './types'; - -type ErrorBoundaryState = { hasError: boolean; error: unknown }; - -export class ErrorBoundary extends Component { - state: ErrorBoundaryState = { hasError: false, error: null }; - - static getDerivedStateFromError(error: unknown): ErrorBoundaryState { - return { hasError: true, error }; - } - - componentDidUpdate(previous: ErrorBoundaryProps) { - const keys = this.props.resetKeys ?? []; - const changed = keys.some((key, index) => !Object.is(key, previous.resetKeys?.[index])); - if (this.state.hasError && changed) this.reset(); - } - - reset = () => { - this.props.onReset?.(); - this.setState({ hasError: false, error: null }); - }; - - render() { - if (!this.state.hasError) return this.props.children; - return this.props.fallback({ error: this.state.error, reset: this.reset }); - } -} -``` - -## The fallback - -`app/error-boundaries/error-fallback/ErrorFallback.tsx`. `size` is `'app' | 'page' | 'part'`; island's molecules take `'page' | 'part'`. The outdated fallback needs no branch of its own: `cause` picks its copy, and it gets Reload page like the logic fallback. - -```tsx -'use client'; - -import { Button } from '@project/island/atoms/button'; -import { ErrorState } from '@project/island/molecules/error-state'; -import { classifyError, describeError, handleError } from '@project/libs/error-handler'; -import { useEffect, useRef } from 'react'; -import { useTranslation } from 'react-i18next'; -import { StatusEmptyState } from '../status-empty-state'; -import { reloadOnce } from './reload-once'; -import type { ErrorFallbackProps } from './types'; - -export function ErrorFallback({ error, size, name, onRetry }: ErrorFallbackProps) { - const { t } = useTranslation('errors'); - const headingRef = useRef(null); - const { read, cause, retry } = classifyError(error); - const islandSize = size === 'part' ? 'part' : 'page'; - - useEffect(() => { - handleError(error, { where: size, name }); - // Code from an older deploy: a failed page or app reloads into the current deploy. A part never does. - if (retry === 'reload-page' && size !== 'part' && reloadOnce()) return; - if (size !== 'part') headingRef.current?.focus(); - }, [error, size, name, retry]); - - if (read === 'silent') return null; - if (read !== 'boundary') return ; - - const { referenceId } = describeError(error, t); - return ( - {t('fallback.try-again')} - ) : ( - - ) - } - /> - ); -} -``` - -`error-fallback/reload-once.ts`. `constants.ts` holds `OUTDATED_RELOAD_STORAGE_KEY = 'outdated-reload-at'` and `OUTDATED_RELOAD_WINDOW_MS = 60_000`. - -```ts -import { storage } from '@project/libs/local-storage'; -import { OUTDATED_RELOAD_STORAGE_KEY, OUTDATED_RELOAD_WINDOW_MS } from './constants'; - -// At most one reload a minute, so a deploy that is still missing files shows the fallback instead of a reload loop. -export function reloadOnce(): boolean { - if (!navigator.onLine) return false; - const last = storage.getJSON(OUTDATED_RELOAD_STORAGE_KEY); - if (typeof last === 'number' && Date.now() - last < OUTDATED_RELOAD_WINDOW_MS) return false; - storage.setJSON(OUTDATED_RELOAD_STORAGE_KEY, Date.now()); - window.location.reload(); - return true; -} -``` - -`StatusEmptyState` (`error-boundaries/status-empty-state/`) renders island's `EmptyState` with the `errors:empty.` copy and, at page size, the link back. It is a client component, so the server page and parts can render it too. - -## Part boundary - -`app/error-boundaries/part-boundary/PartBoundary.tsx`. `PartBoundaryProps` is `{ name: string }`; `catchError` adds `children`. - -```tsx -'use client'; - -import { useQueryErrorResetBoundary } from '@tanstack/react-query'; -import { catchError, type ErrorInfo } from 'next/error'; -import { ErrorFallback } from '../error-fallback'; -import type { PartBoundaryProps } from './types'; - -function PartFallback({ name }: PartBoundaryProps, { error, retry, reset }: ErrorInfo) { - const queryErrors = useQueryErrorResetBoundary(); - const isServerError = 'digest' in error; - return ( - { - queryErrors.reset(); - if (isServerError) retry(); - else reset(); - }} - /> - ); -} - -export const PartBoundary = catchError(PartFallback); -``` - -A part in a template: - -```tsx - - }> - - - -``` - -## Page and app boundaries - -`apps//src/app/(account)/error.tsx`: - -```tsx -'use client'; - -import { ErrorFallback } from '@project//app/error-boundaries'; -import { useQueryErrorResetBoundary } from '@tanstack/react-query'; - -type AccountErrorProps = { error: Error & { digest?: string }; retry: () => void }; - -export default function AccountError({ error, retry }: AccountErrorProps) { - const queryErrors = useQueryErrorResetBoundary(); - return ( - <> - - { - queryErrors.reset(); - retry(); - }} - /> - - ); -} -``` - -`apps//src/app/global-error.tsx`. `i18n` is the app's client i18n instance, so `useTranslation` works without providers. - -```tsx -'use client'; - -import '../styles/app.css'; -import { ErrorFallback } from '@project//app/error-boundaries'; -import { i18n } from '../i18n'; - -export default function GlobalError({ error }: { error: Error & { digest?: string } }) { - return ( - - - - window.location.reload()} /> - - - ); -} -``` - -The `AppShell` renders the one `Toaster`: - -```tsx -const { i18n } = useTranslation(); -const dir = i18n.dir(); - -// in the returned JSX: - -``` - -## Query client - -`configs/react-query.ts` keeps its `getQueryClient()` and dehydrate settings ([page-example.md](page-example.md)) and adds the lines below. - -```ts -import { handleError } from '@project/libs/error-handler'; -import { defaultShouldDehydrateQuery, QueryCache, QueryClient } from '@tanstack/react-query'; - -function makeQueryClient(): QueryClient { - return new QueryClient({ - queryCache: new QueryCache({ - onError: (error, query) => { - if (query.state.data !== undefined) handleError(error, { where: 'refetch' }); - }, - }), - defaultOptions: { - queries: { - staleTime: 60_000, - retry: false, - networkMode: 'offlineFirst', - throwOnError: (_error, query) => query.state.data === undefined, - }, - mutations: { networkMode: 'offlineFirst' }, - dehydrate: { - shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending', - shouldRedactErrors: () => false, - }, - }, - }); -} -``` - -## Server reads - -`app/error-boundaries/read-on-server/read-on-server.ts`, exported only through the platform's `server.ts`. `types.ts` declares `ServerRead = { status: 'ok'; data: T } | { status: 'not-found' | 'no-access' }`. - -```ts -import 'server-only'; -import { classifyError } from '@project/libs/error-handler'; -import type { ServerRead } from './types'; - -export async function readOnServer(read: () => Promise): Promise> { - try { - return { status: 'ok', data: await read() }; - } catch (error) { - const outcome = classifyError(error).read; - if (outcome === 'not-found' || outcome === 'no-access') return { status: outcome }; - throw error; - } -} -``` - -`apps//src/app/(shop)/seller/[slug]/page.tsx`. A seller page is the same for every visitor, so it reads on the server. A page that depends on the viewer, such as an order page, loads in the browser instead, and its reads reach the fallback as browser errors ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). A seller page is an entity page: no `loading.tsx` sits above it, so when `generateMetadata` calls `readSeller`, the status is decided before the first byte. A missing seller answers 404, and an old slug 308 ([error-handling.md](error-handling.md#b2cb2b-server)). `getSeller` is a cache, so the metadata and the page share one request, and the cache keeps a failure for the request too. `movedTo` stands for the current slug, which the back end sends when the URL used an old one. - -```tsx -import { StatusEmptyState } from '@project//app/error-boundaries'; -import { paths } from '@project//app/navigation'; -import { getDevice, getSeller, readOnServer } from '@project//server'; -import type { Metadata } from 'next'; -import { notFound, permanentRedirect } from 'next/navigation'; -import { SellerDesktop } from './templates/seller-desktop'; -import { SellerMobile } from './templates/seller-mobile'; - -type SellerPageProps = { params: Promise<{ slug: string }> }; - -// Throws for a missing or moved seller; returns 'ok' or 'no-access'. -async function readSeller(slug: string) { - const seller = await readOnServer(() => getSeller(slug)); - if (seller.status === 'not-found') notFound(); - if (seller.status === 'ok' && seller.data.movedTo) permanentRedirect(paths.seller(seller.data.movedTo)); - return seller; -} - -export async function generateMetadata({ params }: SellerPageProps): Promise { - const { slug } = await params; - const seller = await readSeller(slug); - if (seller.status !== 'ok') return { robots: { index: false } }; - return { title: seller.data.name }; -} - -export default async function SellerPage({ params }: SellerPageProps) { - const { slug } = await params; - const [device, seller] = await Promise.all([getDevice(), readSeller(slug)]); - if (seller.status !== 'ok') return ; - return device === 'mobile' ? : ; -} -``` - -- Both functions call `readSeller`. `generateMetadata` runs before the first byte, so its call sets the real status for every request that sends a `User-Agent`. The page's call decides it for a request without one, whose metadata streams, and narrows the type. -- Narrow with `status !== 'ok'` before touching `data`. Two checks such as `=== 'not-found'` and then `=== 'no-access'` never narrow the `{ status: 'not-found' | 'no-access' }` member away, so `seller.data` fails type-check. At run time `variant` is `'no-access'`, because `readSeller` has already thrown for `'not-found'`. - -A server part, `.../seller/[slug]/organisms/seller-ratings/SellerRatings.tsx`: - -```tsx -import { StatusEmptyState } from '@project//app/error-boundaries'; -import { getSellerRatings, readOnServer } from '@project//server'; -import { RatingsSummary } from './components/ratings-summary'; -import type { SellerRatingsProps } from './types'; - -export async function SellerRatings({ sellerId }: SellerRatingsProps) { - const ratings = await readOnServer(() => getSellerRatings(sellerId)); - if (ratings.status !== 'ok') return ; - return ; -} -``` - -## Actions - -`showActionError` and `applyServerErrors`, with a login model and a mutation that use them: [code-patterns.md](code-patterns.md#validation-model-and-server-errors). diff --git a/.claude/skills/front-end-architect/references/error-handling.md b/.claude/skills/front-end-architect/references/error-handling.md deleted file mode 100644 index 9cf9df5..0000000 --- a/.claude/skills/front-end-architect/references/error-handling.md +++ /dev/null @@ -1,179 +0,0 @@ -# Error handling - -One model for every error, so each variant looks and behaves the same in every project: error boundaries at two sizes, API errors decided by status and by whether the request read data or ran an action, and one empty state. The decisions live in the error handler lib ([lib-error-handler.md](lib-error-handler.md)); this file says where each piece goes and what the user sees. The HTTP lib's `HttpError` and its codes are in [lib-http.md](lib-http.md#errors). - -Contents: The model · What each failure shows · Boundaries · Reads · Actions · Empty states · B2C/B2B server · Reporting · Copy, accessibility, and i18n · Code · Definition of Done - -## The model - -``` -1) Error boundary ─┬─> Whole app (EB-W) - └─> Section (EB-S): a page or a part - Fallback types ─┬─> Network: the API or the connection failed; retry helps - ├─> Logic: a JavaScript bug; retry rarely helps; reported - └─> Outdated: the page runs code from an older deploy; a page reload fixes it - -2) API error ─┬─> 5xx ─┬─> Read ───> EB-X - │ └─> Action ─┐ - └─> 4xx ─┬─> Action ─┴─> 1. Toast 2. Retry, by cause 3. Guide (the hint) - └─> Read ───> ES (404, 410, 403) | EB-X (the rest) - -3) Empty state (ES) -``` - -- **EB-X** is the nearest boundary around the code that failed: the part's EB-S, else the page's EB-S, else EB-W. -- **EB-W** sits only at the app root, above the root layout, and catches only what nothing below it caught. It replaces the whole app, so it is the last resort. -- **EB-S** has two sizes. A page-size EB-S sits inside the layouts, so a failed page keeps the header, navigation, and breadcrumbs usable. A part-size EB-S (`PartBoundary`) wraps each part that loads on its own, so one failed part never takes down the page ([SKILL.md](../SKILL.md#3-architecture-rules)). -- **Read** means getting information: queries, server component reads, and the data a page loads. **Action** means a write the user started: a mutation or a feature action. -- Reads never toast. A failed read shows where its data would be, as an empty state or a fallback. Actions always toast, because the user is waiting for the result and the page they started from is still there. -- **Empty state** covers every "nothing to show" case: a successful response with no items, a filter with no matches, a 404 or 410, and a 403. - -## What each failure shows - -`classifyError` in the lib turns every error into these outcomes ([lib-error-handler.md](lib-error-handler.md#classification)). - -| Failure | Read | Action | -|---|---|---| -| 5xx | EB-X, network fallback with Try again; reported | Toast with the support sentence and reference ID; Try again re-runs it when that is safe; reported | -| No response, timeout | EB-X, network fallback with Try again | Toast with the message and hint; Try again when safe | -| 404, 410 | ES `not-found` | Toast; Reload loads the latest data | -| 403 | ES `no-access` | Toast | -| 400, 422 | EB-X | Field errors, form alert, and toast; the user fixes and resubmits | -| 408 | EB-X, Try again | Toast; the form stays filled and submit is the retry | -| 409 | EB-X | Toast; Reload loads the latest data before the user tries again | -| 429 | EB-X | Toast whose hint says how long to wait; no button | -| 401 | Never reaches the UI: the HTTP lib refreshes, or a failed refresh logs out | Same | -| `ABORTED` | Nothing | Nothing | -| Logic error (a bug) | EB-X, logic fallback with Reload page and the reference ID; reported | Toast with the support sentence; reported | -| A chunk that failed to load (code from an older deploy) | A page or app boundary reloads the page once; a part boundary shows the outdated fallback with Reload page | Toast that the page was updated, with Reload page; the form keeps its values | -| Success with no items | ES `no-data`, or `no-results` when filters or a search are active | Not an error | - -- A failed refetch keeps the data on screen and shows nothing. Only a first load that fails reaches a boundary. -- "When safe" means the action can run twice without harm: an idempotent request (PUT, DELETE, or a POST with an idempotency key the back end honors), or a read-only step. Otherwise the toast has no button, the form keeps its values, and submitting again is the retry. - -## Boundaries - -| Boundary | Where | -|---|---| -| EB-W | `apps//src/app/global-error.tsx` | -| EB-S, page | `app//error.tsx` in every route group, and `not-found.tsx` at the root and in each group that calls `notFound()` | -| EB-S, part | `PartBoundary`, built with Next.js's `catchError` | - -Every boundary renders the same `ErrorFallback`, which decides what the user sees: - -1. It classifies the error. A `silent` read renders nothing: an `ABORTED` request, or a 401 whose logout redirect is already on its way. -2. `not-found` and `no-access` render the `StatusEmptyState` at the boundary's size. -3. Everything else renders island's `ErrorState`: the network fallback with Try again, or the logic or outdated fallback with Reload page. They show the reference ID when there is one. -4. It calls `handleError` once, in an effect, so the error that stopped here is reported once. - -Rules: - -- Part boundaries use `catchError`, not island's `ErrorBoundary`: `catchError` lets `notFound()` and `redirect()` through, clears itself on client navigation, and its `retry()` renders server parts again on the server. It is a higher-order function, the one exception to "no HOCs in new code" next to React's `memo` and `lazy` ([design-patterns.md](design-patterns.md#react-and-javascript-patterns)). -- `global-error.tsx` replaces the root layout, so it has no providers and no styles: it renders its own `` and ``, imports `app.css` and the client i18n setup itself, and offers Reload page. -- Retry resets the failed queries first, then the boundary. Otherwise a query that threw keeps its error and throws again at once. There is no provider for this: `useQueryErrorResetBoundary()` returns the global reset. -- In a part boundary, an error with a `digest` came from the server, so Try again calls `retry()`. A browser-side error calls `reset()`, which re-renders without a server round trip. -- Put `PartBoundary` outside the part's ``, so the fallback replaces the skeleton and the part together. Widgets that load inside a form, such as select options and lazy tabs, get their own `PartBoundary`, so their failure never unmounts the form and loses what the user typed. -- `LoadOnVisible` and dynamic imports need nothing extra: a chunk that fails to load throws to the part's boundary ([rendering-patterns.md](rendering-patterns.md#loading-patterns)), and the error handler classifies it as outdated. -- An outdated error at page or app size reloads the page at once, because the page is already gone: at most once a minute, with the time kept in local storage, and only while the browser is online. Otherwise the boundary shows the outdated fallback. A part boundary never reloads on its own, because the user may be typing elsewhere on the page; it offers Reload page. The deploy rules that keep these errors rare are in [b2c-b2b.md](b2c-b2b.md#deploys-and-version-skew). - -## Reads - -- `configs/react-query.ts` sets `throwOnError: (_error, query) => query.state.data === undefined`. A first load that fails throws to its boundary; a refetch that fails keeps the data and shows nothing. Parts guard only `isPending`, never `isError`, so no component has an error branch. -- `useSuspenseQuery` always throws on a failed first load, whatever `throwOnError` says, so it reaches the same boundary. -- `QueryCache.onError` calls `handleError(error, { where: 'refetch' })` only when the query still has data: that is the one place a failed refetch stops. A first load is handled by its fallback instead. -- Queries don't retry on their own (`retry: false`), because the HTTP lib already retried idempotent requests. The user retries from the fallback. -- `networkMode: 'offlineFirst'` for queries and mutations, so an offline request fails at once and shows the network fallback or toast, instead of pausing with a skeleton or spinner that never ends. -- A read whose 404 or 403 is an expected answer (a detail page, an order that may belong to someone else) needs no special code: the fallback turns it into the `not-found` or `no-access` empty state. - -## Actions - -- A form catches the action's error in `form.handleSubmit` and calls `applyServerErrors`. Anything else calls `showActionError` in its `catch` or in `useMutation`'s `onError`. Code: [code-patterns.md](code-patterns.md#validation-model-and-server-errors). -- `showActionError` is the one error toast: it calls `handleError`, returns early for `silent` errors, and shows `toast.error` with: - - the title: what failed, from the caller's `failedMessage`, naming the object ("Category 'Kitchenware' wasn't saved"); - - the description: the error's message and hint (the guide), or, when there is neither (5xx, unknown, logic), one support sentence with the reference ID; - - a button from the retry kind: Try again for `again` when the caller passes `retry`, Reload for `reload` when the caller passes `reload`, Reload page for `reload-page`, and none for `wait`, `fix`, and `none`; - - `duration: Infinity`, an `id` built from `failedMessage` so a repeated failure replaces its toast instead of stacking, and `testId: 'action-error'`. -- `applyServerErrors` puts each server field error under its field and focuses the first, puts field errors for fields the form doesn't render (and whole-submission errors) in the form alert, and then calls `showActionError`. The form keeps every value. -- The caller passes `retry` only when running the action again is safe (see What each failure shows). Pass `reload` for actions on data that can change underneath the user (409, 404): it invalidates or refetches the affected queries, and the user tries again on fresh data. -- An action that runs inside `startTransition` catches its error inside the transition. An error thrown out of a transition goes to the nearest error boundary and replaces the part, which is wrong for an action. -- Uploads and multi-step flows keep a `failed` state in their reducer and also call `showActionError`, with a `retry` that starts the flow again with the same file ([design-patterns.md](design-patterns.md#adding-a-pattern)). -- Login and OTP requests send `skipRefresh: true`, and the back-end contract answers wrong credentials with 400 or 422 and field errors. So a 401 always means "no valid session", and the login form never triggers a refresh. - -## Empty states - -- island has one `EmptyState` molecule (`packages/island/src/molecules/empty-state/`) with the variants `no-data`, `no-results`, `not-found`, and `no-access`, and the sizes `part` and `page`. Each variant has its own illustration. It takes the title, description, and an optional action as props, so each use gives its own copy. -- Its sibling `ErrorState` molecule has the same sizes and slots, plus a `referenceId` line, for the fallbacks. -- `no-data` and `no-results` come from successful responses: the template renders them from the model's data, with feature copy and a primary action ("No categories yet. Create your first category to start organizing products." and "Create category"). `no-results` offers "Clear filters". -- `not-found` and `no-access` come from errors. The app's `StatusEmptyState` renders them with shared copy from the `errors` namespace; the page size adds a link to the home page. -- A list part that hides itself when empty, such as a related-products rail, may render nothing instead. Decide it in the plan, not per render. - -## B2C/B2B server - -Server reads classify on the server, because a Server Component error reaches the browser with only its digest. - -- The page reads its main data through `readOnServer`, a server-only helper in the platform's `app/error-boundaries/`. It returns `{ status: 'ok', data }`, or `not-found` for 404 and 410 and `no-access` for 403, and rethrows the rest to the page's `error.tsx`. Server reads send no auth cookies, so only pages that are the same for every visitor read on the server; a page that needs a logged-in user loads in the browser ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). -- Where `notFound()` runs decides the status: - - An indexable page has nothing above it that streams: no `loading.tsx`, and no `` around `children` in a layout or in a component that a layout renders around them ([b2c-b2b.md](b2c-b2b.md#rendering)). On an entity page (product, category, brand, seller, article, store branch, campaign), `generateMetadata` and the page call one read helper. The helper reads through `readOnServer` and the page's cache, calls `notFound()` for `not-found`, and calls `permanentRedirect()` when the payload names a replacement ([error-handling-code.md](error-handling-code.md#server-reads)). `generateMetadata` runs before the first byte, so crawlers get a real 404 with `noindex` in ``, at no extra read, or a 308 with `Location`. The page's call covers a request without a `User-Agent`, whose metadata streams. - - The server HTML of a real 404 has an empty ``, and the group's `not-found.tsx` renders in the browser. Google needs only the status, and it may not render a non-200 page at all. - - Moves known in advance, such as a renamed category tree, go in `redirects()` in `next.config.ts`, which answers before any render. A redirect thrown while the shell renders, or a failed read that `generateMetadata` rethrows, makes Next.js render again with a fresh cache, so the read runs twice. A back-end outage therefore doubles the reads that `generateMetadata` awaits, as on entity pages. - - A `noindex` or blocked page keeps its `loading.tsx`, so its status is already 200 when `notFound()` runs. Next.js then adds a `noindex` robots tag, in `` when `generateMetadata` throws and at the end of `` when the page throws, and renders the not-found UI only in the browser. A redirect becomes a ``. -- `no-access` renders the page-size `StatusEmptyState`, and `generateMetadata` returns `robots: { index: false }` for it. Like `not-found` and every error page, it renders no JSON-LD ([lib-json-ld.md](lib-json-ld.md#rendering)). `forbidden()` and `unauthorized()` are experimental and not used ([rendering-patterns.md](rendering-patterns.md#rendering-patterns)). -- A server part reads through `readOnServer` too: it renders the part-size `StatusEmptyState` for `not-found` and `no-access`, and rethrows the rest to its `PartBoundary`. -- A part that must show an empty state awaits its read on the server. An un-awaited prefetch streams its error to the browser as a digest, so use it only for reads that can't answer 404 or 403. `shouldRedactErrors: () => false` in the dehydrate options keeps the real error on the server, so Next.js reports it and the browser gets its digest instead of a generic "redacted" error. -- `error.tsx` and `global-error.tsx` render ``, so an error page is never indexed. -- `instrumentation.ts` configures the error handler for the server and calls `handleError` from `onRequestError` ([lib-error-handler.md](lib-error-handler.md#usage)). - -Status per case, measured on Next.js 16.4. No page answers 410: Google treats it like 404, and Next.js has no API for it. - -| Case | Status | The server HTML holds | -|---|---|---| -| Entity missing | 404 | `noindex` in `` and an empty ``; `not-found.tsx` renders in the browser | -| Entity replaced by another | 308 to the replacement | nothing that matters | -| Product out of stock, or discontinued with its content kept | 200, indexable | the page, with its stock text, and its availability in the JSON-LD | -| Listing page past the last; empty, duplicate, or unknown combination of indexable filters | 404 | as for a missing entity | -| Empty listing whose URL includes a filter that `robots.ts` blocks | 200 | the listing, with the `no-results` empty state and Clear filters | -| Category with no products | 200 with `noindex` while the menu links it; 404 once it leaves the menu | the page, with the `no-data` empty state | -| Search with no results | 200; `/search` is blocked in `robots.ts` | the `no-results` empty state; never 5xx for an unknown query | -| A failed read on an indexable page, in `generateMetadata`, the page entry, or another Server Component outside every `` | 500 | `noindex` and an empty ``; `error.tsx` renders in the browser | -| A failed read in a part inside its `` and `PartBoundary` | 200 | the part's skeleton; the `PartBoundary` fallback renders in the browser | -| A failed read in a layout above the page, such as the `(shop)` layout's `getMenu()` | 500, on every page under that layout | `noindex` and an empty `` | -| `notFound()` on a `noindex` or blocked page, under its `loading.tsx` | 200 | the skeleton and `noindex`; the not-found UI renders in the browser | -| A failed read on a `noindex` or blocked page, under its `loading.tsx` | 200 | the skeleton; a `noindex` page keeps the `noindex` of its `metadata` export, and a blocked page has no robots tag; `error.tsx` and its `noindex` render in the browser | -| Overload | 503 with `Retry-After`, from the reverse proxy or the CDN | — | - -## Reporting - -- `handleError` runs once per error, where it stops: a fallback, `showActionError`, `QueryCache.onError`, or the server's `onRequestError`. Never call it in a repository, an action, or a `catch` that rethrows. -- It reports 5xx and logic errors only, with the request id and digest. 4xx, network, and timeout errors aren't bugs; the HTTP lib's breadcrumbs keep them visible next to a reported error. -- The bootstrap passes the Sentry integration's adapter as `report`. The adapter maps an `ErrorReport` to the vendor's event (tags: `where`, `status`, `code`; context: `requestId`, `digest`, `name`) and filters noise that isn't the app's bug, such as errors thrown by browser extensions. -- No failure events on the event emitter: events announce completed operations only ([design-patterns.md](design-patterns.md#not-used-here)). - -## Copy, accessibility, and i18n - -- Every fallback, empty state, and toast says what happened and what the user can do, following the copy rules in [ui-rules.md](ui-rules.md#copy). Unknown errors say: "Something went wrong on our side. Try again in a moment. If it keeps happening, contact support and mention reference ID `a1b2c3`." -- The `errors` namespace loads on every route, because any route can fail. It holds the HTTP lib's keys (`http.network`, `http.timeout`, their hints, and `http.retry-after`), the support sentences, the fallback copy (`network`, `logic`, and `outdated`), the `app.outdated` message, the `not-found` and `no-access` copy, and the button labels. -- Server field errors and messages arrive translated; never pass them through `t` again. -- Page and app fallbacks move focus to their heading (`tabIndex={-1}`), so keyboard and screen-reader users land on the explanation. Part fallbacks don't take focus and have no live role, so a failed part never interrupts what the user is doing elsewhere. -- One `` in the AppShell, with `dir` from the locale and its position on the logical end side (`bottom-right` in LTR, `bottom-left` in RTL). - -## Code - - -The boundaries, `ErrorFallback`, `readOnServer`, and the query client's error settings are in [error-handling-code.md](error-handling-code.md). Read it only when you build or change one of them. - -## Definition of Done - -``` -[ ] The app has EB-W; every page and every part that loads on its own has an EB-S, and every boundary renders ErrorFallback -[ ] Reads never toast: 404 and 410 show the not-found empty state, 403 no-access, and other failures their boundary's fallback -[ ] A failed refetch keeps its data; no component has an isError branch -[ ] Every failed action shows the action-error toast with its hint or the support sentence and reference ID; the form keeps its values -[ ] Server field errors sit under their rendered fields and the rest in the form alert -[ ] Retry follows the retry kind: again only when safe, reload for 409 and 404, a wait hint for 429, fix and resubmit for other 4xx -[ ] A chunk that failed to load reloads the page once at page or app size, offers Reload page in parts and toasts, and isn't reported -[ ] ABORTED and 401 never show anything -[ ] Successful empty responses show the no-data or no-results empty state with a next step -[ ] handleError runs once per error, where it stops; 5xx and logic errors reach the tracker with requestId or digest -[ ] Server reads go through readOnServer; error pages and no-access pages are noindex -[ ] Indexable pages have no loading.tsx, and no Suspense around children, above them; an entity page's generateMetadata answers a missing entity with notFound() (404) and a replaced one with permanentRedirect() (308) before the first byte -``` diff --git a/.claude/skills/front-end-architect/references/lib-cookie.md b/.claude/skills/front-end-architect/references/lib-cookie.md deleted file mode 100644 index d1a78aa..0000000 --- a/.claude/skills/front-end-architect/references/lib-cookie.md +++ /dev/null @@ -1,109 +0,0 @@ -# Cookie lib (`packages/libs/src/cookie`) - -One small `CookieAdapter` class over `document.cookie`: get, set, and remove with encoding, safe defaults (`path=/`, `SameSite=Lax`, `Secure`), and per-call options. Browser only; framework-agnostic; no dependency (no js-cookie). - -Contents: What cookies are for · Structure · Types · API · Keys · Browser only · Server side · Usage · Acceptance checklist - -## What cookies are for - -- Only small values the server must see on the request: `theme` (so the server renders it without a flash), a `locale` preference, and the consent choice. A locale cookie never decides the locale of an indexable page, which its URL decides ([ui-rules.md](ui-rules.md#crawlers)), and no cookie picks the mobile or desktop template, which comes from the User-Agent's device class only ([b2c-b2b.md](b2c-b2b.md#rendering)). -- Every cookie is sent with every request to its domain and path and holds about 4 KB. Anything the server doesn't need goes to local storage ([lib-local-storage.md](lib-local-storage.md)). -- Never auth tokens. Auth cookies are `HttpOnly`, set and rotated by the server, and JavaScript can't and mustn't read them (see [lib-http.md](lib-http.md), Refresh token). Never secrets or personal data. - -## Structure - -``` -packages/libs/src/cookie/ -├── cookie.ts # CookieAdapter class and the shared `cookie` instance -├── types.ts # CookieAdapterAbstraction, CookieOptions -├── constants.ts # DEFAULT_COOKIE_OPTIONS -└── index.ts -``` - -- `index.ts` exports `CookieAdapter`, `cookie`, `DEFAULT_COOKIE_OPTIONS`, and the types `CookieAdapterAbstraction` and `CookieOptions`. Nothing goes in `server.ts`: the lib is browser-only. -- Import by subpath: `import { cookie } from '@project/libs/cookie'`. - -## Types - -```ts -interface CookieOptions { - path?: string; // default '/' - domain?: string; // default: none (current host only); set it to share with subdomains, e.g. '.example.com' - maxAgeDays?: number; // lifetime in days; omit for a session cookie - sameSite?: 'Strict' | 'Lax' | 'None'; // default 'Lax' - secure?: boolean; // default true; forced to true when sameSite is 'None' -} - -interface CookieAdapterAbstraction { - get(key: string): string | null; - set(key: string, value: string, options?: CookieOptions): void; - remove(key: string, options?: Pick): void; -} -``` - -## API - -- `get(key)` returns the decoded value, or `null` when the cookie doesn't exist. It finds the `encodeURIComponent(key)=` entry in `document.cookie` split by `'; '` and decodes the rest, so values containing `=` stay whole. A value with broken percent-encoding (written by other code) is returned raw instead of throwing. -- `set(key, value, options?)` writes `key=value` with `encodeURIComponent` on both, plus the attributes: - - Options merge in this order: `DEFAULT_COOKIE_OPTIONS` → `configure` defaults → call options. - - `maxAgeDays` becomes `max-age` in seconds (`Math.floor(days * 24 * 60 * 60)`); without it the cookie is a session cookie. - - `sameSite: 'None'` always adds `Secure`, because browsers reject it otherwise. -- `remove(key, options?)` writes the cookie empty with `max-age=0`. It must use the same `path` and `domain` the cookie was set with, or the browser keeps the original. Defaults come from `configure`, so keep them the same for set and remove. -- `configure(defaults: CookieOptions)` sets the defaults once, in the app's bootstrap. It only stores options and never touches `document`, so it's safe in `bootstrap.client.ts` during SSR. For example, `cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE })`, from the app's env, lets local development over plain `http` on a non-localhost host turn `Secure` off. -- There is no public mutable `options` property: on a shared instance, any code could change every other caller's cookies at any time. Per-call differences go in the call's options. -- The shared instance is `export const cookie = new CookieAdapter();`. Create another `CookieAdapter` only in tests. - -## Keys - -- Cookie names are constants in the owning project's `constants.ts` (`LOCALE_COOKIE`, `THEME_COOKIE`), never string literals at call sites. -- Names are a contract with the server: `proxy.ts`, Server Components, and the back end read the same names, so renaming one is a breaking change. -- Names are not prefixed automatically (unlike local-storage keys), because the server reads them by their exact name. - -## Browser only - -- Every method except `configure` checks `typeof document === 'undefined'` and throws a clear error ("cookie is browser-only; on the server read cookies with next/headers") instead of the unclear "document is not defined". -- Call it only in event handlers, effects, actions, and client bootstrap code. Never during render and never at module top level: client components also render on the server, and a value read during render differs between server and browser, which breaks hydration. - -## Server side - -- Server code reads cookies with `cookies()` from `next/headers` (Server Components, Route Handlers, Server Functions) or `request.cookies` in `proxy.ts`, inside the app or platform. The lib never imports Next.js. -- Server Components can't set cookies. Set them in `proxy.ts`, a Route Handler, or a Server Function on the server, or with `cookie.set` in the browser. -- A value the page needs while rendering (theme) is read on the server and passed down as a prop. The browser writes it with `cookie.set` when the user changes it, then refreshes or updates the UI. - -## Usage - -Bootstrap (`bootstrap.client.ts`): - -```ts -cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE }); -``` - -`features/preferences/actions/change-theme/actions.ts` - -```ts -import { cookie } from '@project/libs/cookie'; -import { usePreferencesStore } from '../../../../stores/preferences'; -import { THEME_COOKIE, THEME_COOKIE_MAX_AGE_DAYS } from '../../constants'; -import type { Theme } from '../../entities/theme'; - -export function changeTheme(theme: Theme): 'ok' { - cookie.set(THEME_COOKIE, theme, { maxAgeDays: THEME_COOKIE_MAX_AGE_DAYS }); - usePreferencesStore.getState().setTheme(theme); - return 'ok'; -} -``` - -## Acceptance checklist - -For building or changing the lib: - -``` -[ ] set, get, and remove round-trip a value, including values with "=", ";", spaces, and non-Latin text (e.g. Persian) -[ ] get returns null for a missing cookie and doesn't match a cookie whose name only starts with the key ("theme" vs "theme-v2") -[ ] A value with broken percent-encoding is returned raw, not thrown -[ ] maxAgeDays writes the right max-age; no maxAgeDays writes a session cookie -[ ] sameSite 'None' always writes Secure -[ ] Call options win over configure defaults, which win over DEFAULT_COOKIE_OPTIONS -[ ] remove with the configured path and domain deletes the cookie -[ ] get, set, and remove throw the clear browser-only error on the server; configure doesn't -``` diff --git a/.claude/skills/front-end-architect/references/lib-env.md b/.claude/skills/front-end-architect/references/lib-env.md deleted file mode 100644 index c5cd33b..0000000 --- a/.claude/skills/front-end-architect/references/lib-env.md +++ /dev/null @@ -1,285 +0,0 @@ -# Env lib (`packages/libs/src/env`) - -Validates the app's environment variables and gives apps typed, read-only values. `createClientEnv` validates the public variables and is safe on both sides; `createServerEnv` validates the server variables and runs only on the server. Built on @t3-oss/env-core with valibot schemas. Framework-agnostic: the app passes its prefix and its runtime values, so the lib never reads `process.env` itself. - -Only apps call it. Every other project gets its values from the app's bootstrap through its own `env/` (`setEnv` and `getEnv`), so no project below the app reads the environment. - -No project hard-codes an env value. An env value is a value that changes between environments: a service or CDN address, a key, a third-party ID, a feature flag. Every env value comes from the `.env` of the app that serves it, and only apps have `.env` files. - -Contents: Structure · Types · API · Validation · The app's env · Project env · Bootstrap · Implementation · Usage · Acceptance checklist - -## Structure - -``` -packages/libs/src/env/ -├── env.client.ts # createClientEnv, and the error formatter both functions use -├── env.server.ts # createServerEnv; starts with import 'server-only' -├── types.ts # EnvSchema, EnvValues, ClientEnvOptions, ServerEnvOptions -├── index.ts # createClientEnv and the types -└── server.ts # import 'server-only'; createServerEnv -``` - -- The project's `src/server.ts` re-exports `createServerEnv` by name. -- Import by subpath: `import { createClientEnv } from '@project/libs/env'` and `import { createServerEnv } from '@project/libs/env/server'`. - -## Types - -```ts -import type { StandardSchemaDictionary } from '@t3-oss/env-core'; - -export type EnvSchema = StandardSchemaDictionary; // variable name → valibot schema - -export type EnvValues = Readonly>; - -export type ClientEnvOptions = { - prefix: TPrefix; // 'NEXT_PUBLIC_' - schema: TSchema & { - [TKey in keyof TSchema]: TKey extends `${TPrefix}${string}` ? TSchema[TKey] : `${TKey & string} must start with ${TPrefix}`; - }; - runtimeEnv: NoInfer>; // every declared variable, each read literally -}; - -export type ServerEnvOptions = { - schema: TSchema; - runtimeEnv: Record; // process.env - skipValidation?: boolean; // only for steps that run without the real env (see Validation) -}; -``` - -## API - -- `createClientEnv(options)` returns `EnvValues`. - - Every variable name must start with `prefix`. A name that doesn't is a type error: `API_SECRET must start with NEXT_PUBLIC_`. - - `runtimeEnv` lists every declared variable with a literal reference, `NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL`, because bundlers inline only literal references and the browser has no real `process.env`. Leaving one out is a type error. - - It has no `skipValidation`: public variables are inlined when the app is built, so they must be present at build time anyway. -- `createServerEnv(options)` returns `EnvValues`. It is server-only, so a client import fails the build, and it reads `runtimeEnv: process.env` at runtime. -- Both: - - Empty strings count as missing (`emptyStringAsUndefined`), so `API_URL=` in a `.env` file fails instead of passing as `''`. - - The values are the schema outputs, so transforms apply: `v.pipe(v.string(), v.transform(Number), v.integer())` turns `'24'` into the number `24`. - - On failure they throw one `Error` that lists every invalid variable and why: - - ``` - Invalid environment variables: - - NEXT_PUBLIC_API_URL: Invalid URL: Received "not-a-url" - - NEXT_PUBLIC_CDN_URL: Invalid type: Expected string but received undefined - ``` - - - The result is read-only, and reading an undeclared variable is a type error. - -## Validation - -- Validation runs when the app's env module first loads. Both bootstraps import it first, so a bad variable stops the app with one clear error before any page renders. -- Next.js: to fail the build instead, load `env/env.client.ts` from `next.config.ts` (with jiti when the config can't resolve it). Never load `env.server.ts` there: `server-only` throws outside the React server graph. -- `skipValidation` (server env only) is for steps that run without the real env: lint, type-check, and a Docker image build without runtime secrets. The app sets it from a flag (`SKIP_ENV_VALIDATION=true`). Skipped validation returns the raw strings without transforms, so a running app never sets it. -- Messages come from the schemas, and valibot's default messages repeat the received value. Give every secret's schema its own message (`v.minLength(32, 'Use at least 32 characters')`), and never log env values. - -## The app's env - -``` -apps//src/env/ -├── env.client.ts # public variables: export const clientEnv = createClientEnv({ ... }) -├── env.server.ts # server variables: export const serverEnv = createServerEnv({ ... }); import 'server-only' -├── index.ts # clientEnv -└── server.ts # import 'server-only'; serverEnv -``` - -- These files are the only code in the repo that reads `process.env`. -- App code (bootstrap, configs) reads `clientEnv` and `serverEnv` directly. Only server code imports `../env/server`. -- Every value comes from the app's `.env` files. Only apps that serve in production have `.env` files; platforms, island, libs, integrations, and tools have none. -- Every variable is required. Never give a schema a default (`v.optional(schema, 'http://localhost:3000')`) or add a fallback in code (`clientEnv.NEXT_PUBLIC_API_URL ?? '...'`). A default or a fallback is a hard-coded value that hides a missing variable. - -## Project env - -Every project except apps that reads env has: - -``` -/src/env/ -├── env.ts # setEnv and getEnv, for this project's values only -├── types.ts # the project's env type, e.g. IslandEnv -└── index.ts -``` - -- `setEnv(env)` stores the project's values. `getEnv()` returns them, and throws a clear error when called before `setEnv`. -- The type uses the project's own names (`cdnUrl`, `catalogApiUrl`), not variable names. The bootstrap maps one to the other, so renaming a variable only touches the app. -- Read `getEnv()` inside functions, never at module top level, because bootstrap may not have run yet: `baseUrl: () => getEnv().catalogApiUrl`. -- The project never imports the app or reads the raw environment, so the dependency graph stays acyclic. -- The project never hard-codes an env value: no literal address, key, ID, or flag, and no fallback for a `getEnv()` value. A new env value goes in the project's env type, and the app fills it from its `.env`. -- Libs have no project env; they never read env. The bootstrap passes their settings through `configure`: `http.configure({ baseUrl })`, `configureServerHttp({ baseUrl, getCookieHeader })`, `cookie.configure({ secure })`. A lib never has a default address, key, or ID; it gets them through `configure`. - -## Bootstrap - -- The app's bootstrap calls each project's `setEnv` at startup with the values that project needs. Bootstraps are idempotent, so `setEnv` may run again with the same values. -- Every project exports the same names, so import each under its project's name: `import { setEnv as setIslandEnv } from '@project/island/env'`. -- The server module graph and the client module graph each hold their own copy of every project env. - - `bootstrap.server.ts` fills the server copy. It may pass server-side values, such as an internal service address. - - `bootstrap.client.ts` fills the client copy, with public values only. - - Both must provide every field of a project's env type, so a project env never holds a secret. A secret stays in the app's `serverEnv`, and only the app's server code uses it (for example a header in `configureServerHttp`). - -## Implementation - -`env.client.ts` - -```ts -import { createEnv, type StandardSchemaV1 } from '@t3-oss/env-core'; -import type { ClientEnvOptions, EnvSchema, EnvValues } from './types'; - -export function throwInvalidEnv(issues: readonly StandardSchemaV1.Issue[]): never { - const lines = issues.map((issue) => { - const name = issue.path?.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.'); - return `- ${name ?? 'env'}: ${issue.message}`; - }); - throw new Error(`Invalid environment variables:\n${lines.join('\n')}`); -} - -export function createClientEnv( - options: ClientEnvOptions, -): EnvValues { - return createEnv({ - clientPrefix: options.prefix, - client: options.schema, - // env-core deletes empty strings from the object it gets, so it gets a copy - runtimeEnvStrict: { ...options.runtimeEnv }, - emptyStringAsUndefined: true, - onValidationError: throwInvalidEnv, - }) as EnvValues; -} -``` - -`env.server.ts` - -```ts -import 'server-only'; -import { createEnv } from '@t3-oss/env-core'; -import { throwInvalidEnv } from './env.client'; -import type { EnvSchema, EnvValues, ServerEnvOptions } from './types'; - -export function createServerEnv(options: ServerEnvOptions): EnvValues { - return createEnv({ - server: options.schema, - // env-core deletes empty strings from the object it gets, so process.env gets a copy - runtimeEnv: { ...options.runtimeEnv }, - isServer: true, - emptyStringAsUndefined: true, - skipValidation: options.skipValidation ?? false, - onValidationError: throwInvalidEnv, - }) as EnvValues; -} -``` - -The explicit type arguments on `createEnv` are needed, because env-core's option types can't be checked against a generic schema. Call sites stay fully typed through `ClientEnvOptions` and `ServerEnvOptions`. - -## Usage - -`apps//src/env/env.client.ts` - -```ts -import { createClientEnv } from '@project/libs/env'; -import * as v from 'valibot'; - -export const clientEnv = createClientEnv({ - prefix: 'NEXT_PUBLIC_', - schema: { - NEXT_PUBLIC_API_URL: v.pipe(v.string(), v.url()), - NEXT_PUBLIC_CDN_URL: v.pipe(v.string(), v.url()), - NEXT_PUBLIC_CATALOG_API_URL: v.pipe(v.string(), v.url()), - }, - runtimeEnv: { - NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL, - NEXT_PUBLIC_CDN_URL: process.env.NEXT_PUBLIC_CDN_URL, - NEXT_PUBLIC_CATALOG_API_URL: process.env.NEXT_PUBLIC_CATALOG_API_URL, - }, -}); -``` - -`apps//src/env/env.server.ts` - -```ts -import 'server-only'; -import { createServerEnv } from '@project/libs/env/server'; -import * as v from 'valibot'; - -export const serverEnv = createServerEnv({ - schema: { - API_INTERNAL_URL: v.pipe(v.string(), v.url()), - CATALOG_API_INTERNAL_URL: v.pipe(v.string(), v.url()), - }, - runtimeEnv: process.env, - skipValidation: process.env.SKIP_ENV_VALIDATION === 'true', -}); -``` - -`packages/island/src/env/env.ts`. `types.ts` declares `IslandEnv`, and `index.ts` exports both functions and the type. - -```ts -import type { IslandEnv } from './types'; - -let islandEnv: IslandEnv | undefined; - -export function setEnv(env: IslandEnv): void { - islandEnv = env; -} - -export function getEnv(): Readonly { - if (!islandEnv) { - throw new Error('island env is not set. The app bootstrap must call setEnv from @project/island/env first.'); - } - return islandEnv; -} -``` - -`apps//src/bootstrap/bootstrap.server.ts` - -```ts -import 'server-only'; -import { setEnv as setIslandEnv } from '@project/island/env'; -import { configureServerHttp } from '@project/libs/server'; -import { setEnv as setPlatformEnv } from '@project//env'; -import { cookies } from 'next/headers'; -import { clientEnv } from '../env'; -import { serverEnv } from '../env/server'; - -setIslandEnv({ cdnUrl: clientEnv.NEXT_PUBLIC_CDN_URL }); -setPlatformEnv({ catalogApiUrl: serverEnv.CATALOG_API_INTERNAL_URL }); -configureServerHttp({ - baseUrl: serverEnv.API_INTERNAL_URL, - getCookieHeader: async () => (await cookies()).toString(), -}); -``` - -`apps//src/bootstrap/bootstrap.client.ts`. It also turns on refresh and registers the shared interceptors (see [lib-http.md](lib-http.md#usage)). - -```ts -import { setEnv as setIslandEnv } from '@project/island/env'; -import { http } from '@project/libs/http'; -import { setEnv as setPlatformEnv } from '@project//env'; -import { clientEnv } from '../env'; - -setIslandEnv({ cdnUrl: clientEnv.NEXT_PUBLIC_CDN_URL }); -setPlatformEnv({ catalogApiUrl: clientEnv.NEXT_PUBLIC_CATALOG_API_URL }); -http.configure({ baseUrl: clientEnv.NEXT_PUBLIC_API_URL }); -``` - -`platforms//src/features/catalog/http.ts` reads the platform's env. The server copy holds the internal address and the client copy the public one. - -```ts -import { http } from '@project/libs/http'; -import { getEnv } from '../../env'; - -export const catalogHttp = http.extend({ baseUrl: () => getEnv().catalogApiUrl }); -``` - -## Acceptance checklist - -For building or changing the lib: - -``` -[ ] createClientEnv and createServerEnv return typed, read-only values; transforms apply -[ ] A public variable without the prefix, or a declared variable missing from runtimeEnv, is a type error -[ ] A missing, empty, or invalid variable throws one Error that lists every invalid variable and why -[ ] Importing @project/libs/env/server outside the React server graph throws (server-only), so a client import fails the build -[ ] process.env is unchanged after createServerEnv runs -[ ] skipValidation returns the raw values without validating -[ ] A project's getEnv throws the clear error before setEnv and returns the values after it -[ ] No process.env outside the app's env/ files -[ ] No hard-coded env value, fallback, or schema default; every env value comes from the app's .env, and only apps have .env files -``` diff --git a/.claude/skills/front-end-architect/references/lib-error-handler.md b/.claude/skills/front-end-architect/references/lib-error-handler.md deleted file mode 100644 index c636628..0000000 --- a/.claude/skills/front-end-architect/references/lib-error-handler.md +++ /dev/null @@ -1,259 +0,0 @@ -# Error handler lib (`packages/libs/src/error-handler`) - -Four functions that every project uses to decide what an error shows, what it says, and whether it is reported: `configureErrorHandler`, `classifyError`, `describeError`, and `handleError`. The model they implement (error boundaries, API errors by status, empty states) is in [error-handling.md](error-handling.md). - -It is framework-agnostic (no React, Next.js, TanStack, i18next, or sonner imports), runs in the browser and on the server, and has no dependency. It imports only `isHttpError` from the HTTP lib ([lib-http.md](lib-http.md#errors)). It never shows anything: boundaries, empty states, and toasts live in the apps and platforms. - -Contents: Structure · Types · API · Classification · Messages and reference ID · Reporting · Implementation · Usage · Acceptance checklist - -## Structure - -``` -packages/libs/src/error-handler/ -├── error-handler.ts # configureErrorHandler, classifyError, describeError, handleError -├── types.ts # ErrorClass and its unions, ErrorContext, ErrorReport, ErrorHandlerConfig, TranslateFn, ErrorDescription -├── constants.ts # NOT_FOUND_STATUSES, LIB_MESSAGE_PREFIX, RETRY_AFTER_HINT_KEY, OUTDATED_MESSAGE_KEY, CHUNK_ERROR_PATTERN -└── index.ts -``` - -- `index.ts` exports the four functions and the types. Nothing goes in `server.ts`: the lib has no server-only capability, so both sides import it from `index.ts`. -- Import by subpath: `import { classifyError } from '@project/libs/error-handler'`. - -## Types - -```ts -type ErrorCause = 'network' | 'logic' | 'outdated'; // network: the API or the connection failed, retry helps; logic: a bug, retry rarely helps; outdated: the page runs code from an older deploy, a page reload fixes it -type ReadOutcome = 'silent' | 'not-found' | 'no-access' | 'boundary'; // what a failed read shows -type ActionOutcome = 'silent' | 'toast'; // what a failed action shows -type RetryKind = 'again' | 'wait' | 'reload' | 'reload-page' | 'fix' | 'none'; - -interface ErrorClass { - cause: ErrorCause; - read: ReadOutcome; - action: ActionOutcome; - retry: RetryKind; - report: boolean; // true for 5xx and logic errors -} - -type ErrorWhere = 'app' | 'page' | 'part' | 'action' | 'refetch' | 'server'; - -interface ErrorContext { - where: ErrorWhere; // where the error stopped - name?: string; // the part, action, or route, e.g. 'seller-ratings'; never personal data -} - -interface ErrorReport extends Partial { - error: unknown; - status?: number; - code?: string; - requestId?: string; - digest?: string; // Next.js's id for a server error -} - -interface ErrorHandlerConfig { - report?: (report: ErrorReport) => void; // the error-tracking integration's adapter - onForbidden?: () => void; // runs on every 403 that handleError handles -} - -type TranslateFn = (key: string, options?: Record) => string; // i18next's t fits - -interface ErrorDescription { - message?: string; // what went wrong, only when the user can understand it - hint?: string; // how to fix it: the guide - referenceId?: string; // requestId, or the server digest -} -``` - -## API - -- `configureErrorHandler(config)`: once per module graph, in the app's browser bootstrap (`bootstrap.client.ts`) and in `instrumentation.ts`'s `register()` for the server. It merges `config` into the stored settings, so calling it again is safe. Libs never read env; the bootstrap passes everything in. -- `classifyError(error): ErrorClass`: pure. It decides from the status first, then the code (table below). Anything that isn't an `HttpError` is a logic error, except a chunk that failed to load (outdated) and a server error that reached the browser with only its `digest`. -- `describeError(error, t): ErrorDescription`: the words for a toast or a fallback. Only strings that start with `errors:` go through `t`: those are the keys the HTTP lib creates. Server messages and hints arrive translated and pass through as they are. -- `handleError(error, context?): ErrorClass`: call it once, where the error stops (the fallback that renders it, the toast that shows it, the refetch that swallows it, or the server's `onRequestError`). It classifies the error, sends a report when `report` is true, runs `onForbidden` on a 403, and returns the class. It never throws: a failing reporter or callback is swallowed, so handling an error never causes a second one. - -## Classification - -The first matching row wins. - -| Error | `cause` | `read` | `action` | `retry` | `report` | -|---|---|---|---|---|---| -| `ABORTED` | network | silent | silent | none | no | -| 401 | network | silent | silent | none | no | -| 403 | network | no-access | toast | none | no | -| 404, 410 | network | not-found | toast | reload | no | -| 409 | network | boundary | toast | reload | no | -| 429 | network | boundary | toast | wait | no | -| 5xx | network | boundary | toast | again | yes | -| Other 4xx (400, 408, 422, …) | network | boundary | toast | fix | no | -| `NETWORK_ERROR`, `TIMEOUT` | network | boundary | toast | again | no | -| `PARSE_ERROR`, `INTERCEPTOR_ERROR`, `UNKNOWN` | logic | boundary | toast | none | yes | -| Not an `HttpError`: a chunk that failed to load | outdated | boundary | toast | reload-page | no | -| Not an `HttpError`, with a `digest` | network | boundary | toast | again | no | -| Anything else | logic | boundary | toast | none | yes | - -- 401 never reaches the UI: the HTTP lib refreshes, and a failed refresh logs out ([lib-http.md](lib-http.md#refresh-token)). The server has no refresh and sends no auth cookies, so a server read never expects a 401; `readOnServer` rethrows one to its boundary like any other error ([error-handling.md](error-handling.md#b2cb2b-server)). -- A `digest` without `HttpError` fields is a Server Component error seen in the browser: Next.js sends only the digest in production, so the browser can't classify it. The server already classified and reported it, and a retry renders the part again on the server. -- A chunk that failed to load means the page runs code from an older deploy whose file is gone, or the connection dropped while the code loaded. It isn't a bug, so it isn't reported, and a page reload fixes both. The lib matches webpack's `ChunkLoadError` and both bundlers' messages (`CHUNK_ERROR_PATTERN`); check the pattern once against the repo's bundler by deleting a chunk in a production build. Deploy rules that keep it rare: [b2c-b2b.md](b2c-b2b.md#deploys-and-version-skew). -- Retry kinds: `again` offers a button that runs the same thing again; `wait` offers none and the hint says how long; `reload` offers a button that loads the latest data first; `reload-page` offers a button that reloads the whole page; `fix` offers none, because the user must change the input; `none` offers none. - -## Messages and reference ID - -- `message` is set for 4xx statuses (the back end localizes them from `Accept-Language`) and for `NETWORK_ERROR` and `TIMEOUT` (the lib's `errors:` keys). It is left out for 5xx and logic errors, whose text means nothing to users and can leak internals. A chunk that failed to load gets `t('errors:app.outdated')`: the page was updated, and reloading it continues. -- `hint` is the error's hint. When there is none and the error has `retryAfter`, it is `t('errors:http.retry-after', { seconds })`. -- `referenceId` is `requestId`, or the `digest` when there is no request id. Support finds the report by either. - -## Reporting - -- Reports go only to the `report` callback that the bootstrap passes in, never to an event on the event emitter. -- `report` is true for 5xx and logic errors. 4xx, network, and timeout failures are the user's or the connection's, so they aren't reported; the HTTP lib's breadcrumbs keep them visible in the tracker when a reported error follows. -- An `ErrorReport` carries the error, the context, and the status, code, request id, and digest, so the tracker can group by status and code and search by reference ID. It never carries form values, cookies, or headers. - -## Implementation - -`error-handler.ts`, the parts that decide. `constants.ts` holds `NOT_FOUND_STATUSES: readonly number[] = [404, 410]`, `LIB_MESSAGE_PREFIX = 'errors:'`, `RETRY_AFTER_HINT_KEY = 'errors:http.retry-after'`, `OUTDATED_MESSAGE_KEY = 'errors:app.outdated'`, and `CHUNK_ERROR_PATTERN = /Loading (CSS )?chunk .+ failed|Failed to load chunk/`. - -```ts -import { isHttpError } from '../http'; -import { - CHUNK_ERROR_PATTERN, - LIB_MESSAGE_PREFIX, - NOT_FOUND_STATUSES, - OUTDATED_MESSAGE_KEY, - RETRY_AFTER_HINT_KEY, -} from './constants'; -import type { - ErrorClass, - ErrorContext, - ErrorDescription, - ErrorHandlerConfig, - ReadOutcome, - RetryKind, - TranslateFn, -} from './types'; - -let config: ErrorHandlerConfig = {}; - -export function configureErrorHandler(next: ErrorHandlerConfig): void { - config = { ...config, ...next }; -} - -const SILENT: ErrorClass = { cause: 'network', read: 'silent', action: 'silent', retry: 'none', report: false }; -const LOGIC: ErrorClass = { cause: 'logic', read: 'boundary', action: 'toast', retry: 'none', report: true }; -const OUTDATED: ErrorClass = { cause: 'outdated', read: 'boundary', action: 'toast', retry: 'reload-page', report: false }; - -function apiError(read: ReadOutcome, retry: RetryKind, report = false): ErrorClass { - return { cause: 'network', read, action: 'toast', retry, report }; -} - -function getDigest(error: unknown): string | undefined { - if (typeof error !== 'object' || error === null || !('digest' in error)) return undefined; - return typeof error.digest === 'string' ? error.digest : undefined; -} - -function isChunkLoadError(error: unknown): boolean { - return error instanceof Error && (error.name === 'ChunkLoadError' || CHUNK_ERROR_PATTERN.test(error.message)); -} - -export function classifyError(error: unknown): ErrorClass { - if (!isHttpError(error)) { - if (isChunkLoadError(error)) return OUTDATED; - return getDigest(error) ? apiError('boundary', 'again') : LOGIC; - } - const { status, code } = error; - if (code === 'ABORTED' || status === 401) return SILENT; - if (status === 403) return apiError('no-access', 'none'); - if (NOT_FOUND_STATUSES.includes(status)) return apiError('not-found', 'reload'); - if (status === 409) return apiError('boundary', 'reload'); - if (status === 429) return apiError('boundary', 'wait'); - if (status >= 500) return apiError('boundary', 'again', true); - if (status >= 400) return apiError('boundary', 'fix'); - if (code === 'NETWORK_ERROR' || code === 'TIMEOUT') return apiError('boundary', 'again'); - return LOGIC; -} - -export function describeError(error: unknown, t: TranslateFn): ErrorDescription { - if (!isHttpError(error)) { - return isChunkLoadError(error) ? { message: t(OUTDATED_MESSAGE_KEY) } : { referenceId: getDigest(error) }; - } - const translate = (text?: string) => (text?.startsWith(LIB_MESSAGE_PREFIX) ? t(text) : text); - const isUserFacing = - (error.status >= 400 && error.status < 500) || error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT'; - return { - message: isUserFacing ? translate(error.message) : undefined, - hint: - translate(error.hint) ?? - (error.retryAfter ? t(RETRY_AFTER_HINT_KEY, { seconds: error.retryAfter }) : undefined), - referenceId: error.requestId ?? getDigest(error), - }; -} - -export function handleError(error: unknown, context?: ErrorContext): ErrorClass { - const errorClass = classifyError(error); - try { - if (errorClass.report) { - config.report?.({ - ...context, - error, - status: isHttpError(error) ? error.status : undefined, - code: isHttpError(error) ? error.code : undefined, - requestId: isHttpError(error) ? error.requestId : undefined, - digest: getDigest(error), - }); - } - if (isHttpError(error) && error.status === 403) config.onForbidden?.(); - } catch { - // Handling an error must never throw a second one. - } - return errorClass; -} -``` - -- `config` is startup configuration, set by the bootstrap, so module scope is allowed to hold it on the server ([design-patterns.md](design-patterns.md#how-to-choose)). It never holds errors or anything per request. -- On the server, `onRequestError` sees the real `HttpError`, with the digest Next.js gave it, so the report has both ids and matches what the browser shows. - -## Usage - -Browser bootstrap (`bootstrap.client.ts`). The Sentry integration adapts `ErrorReport` to its vendor's event. - -```ts -import { captureError } from '@project/integrations/sentry'; -import { configureErrorHandler } from '@project/libs/error-handler'; - -configureErrorHandler({ report: captureError }); -``` - -Server, `apps//src/instrumentation.ts`. `register()` runs once when the server starts, and `onRequestError` runs for every error that no server code caught. - -```ts -import { captureServerError } from '@project/integrations/server'; -import { configureErrorHandler, handleError } from '@project/libs/error-handler'; -import type { Instrumentation } from 'next'; - -export function register(): void { - configureErrorHandler({ report: captureServerError }); -} - -export const onRequestError: Instrumentation.onRequestError = (error, _request, context) => { - handleError(error, { where: 'server', name: context.routePath }); -}; -``` - -Where the other calls go, with code, is in [error-handling-code.md](error-handling-code.md): `ErrorFallback` classifies, describes, and handles what reaches a boundary; `showActionError` does the same for actions; the query client's `QueryCache.onError` handles failed refetches. - -## Acceptance checklist - -For building or changing the lib: - -``` -[ ] Every row of the classification table returns its class, with status checked before code -[ ] ABORTED and 401 are silent for reads and actions; 403 runs onForbidden once per handleError call -[ ] A plain Error is a reported logic error; an object with only a digest is a network error that isn't reported -[ ] A webpack ChunkLoadError and a Turbopack "Failed to load chunk" error are outdated, retry reload-page, not reported, and describeError gives them the errors:app.outdated message -[ ] describeError translates only errors:-prefixed strings; server messages pass through unchanged -[ ] describeError leaves out the message for 5xx and logic errors and keeps it for 4xx, network, and timeout -[ ] A 429 or 503 with retryAfter and no hint gets the retry-after hint with its seconds -[ ] referenceId is requestId, else digest -[ ] handleError reports 5xx and logic errors with status, code, requestId, and digest, and nothing else -[ ] handleError never throws, even when report or onForbidden throws -[ ] The lib imports nothing but the HTTP lib: no React, Next.js, TanStack, i18next, or sonner -``` diff --git a/.claude/skills/front-end-architect/references/lib-http.md b/.claude/skills/front-end-architect/references/lib-http.md deleted file mode 100644 index 3d30e0b..0000000 --- a/.claude/skills/front-end-architect/references/lib-http.md +++ /dev/null @@ -1,378 +0,0 @@ -# HTTP lib (`packages/libs/src/http`) - -The only way code talks to the network. One `HttpClient` class handles requests (GET, POST, PUT, PATCH, DELETE), file upload and download, request and response interceptors, retry, automatic refresh on 401, abort, and one normalized `HttpError`. - -It is framework-agnostic (no React, Next.js, TanStack, i18next, sonner, or zustand imports), runs in the browser and on the server, and is built on native `fetch`, `AbortController`, `AbortSignal.any`, `AbortSignal.timeout`, and `XMLHttpRequest` (uploads only). No axios, ky, or other dependency. - -Contents: Structure · Types · API · Root and feature clients · Request pipeline · Body and params · Interceptors · Retry · Refresh token · Abort · Files · Errors · Server side · Usage · Acceptance checklist - -## Structure - -``` -packages/libs/src/http/ -├── http-client.ts # HttpClient: config, verbs, request pipeline, extend, abortAll -├── http.ts # the root `http` instance and the createHttpClient factory -├── http-error.ts # HttpError, isHttpError, and normalization of anything thrown or returned -├── interceptors.ts # InterceptorManager; use() returns an eject function -├── retry.ts # shouldRetry, backoff with jitter and Retry-After -├── refresh.ts # single-flight refresh coordinator -├── body.ts # body and query serialization, response parsing -├── upload.ts # XMLHttpRequest transport with upload progress -├── server-http.ts # configureServerHttp; exported only from src/server.ts -├── types.ts -├── constants.ts # defaults, HTTP_ERROR_CODES, header names -└── index.ts -``` - -- `index.ts` exports `HttpClient`, `createHttpClient`, `http`, `HttpError`, `isHttpError`, `HTTP_ERROR_CODES`, and the types (`HttpClientConfig`, `FeatureHttpConfig`, `RequestOptions`, `HttpResponse`, `UploadOptions`, `UploadProgress`, `DownloadResult`, `RetryConfig`, `RefreshConfig`, `RequestInterceptor`, `ResponseInterceptor`, `ErrorInterceptor`, `HttpErrorCode`). -- `server.ts` exports `configureServerHttp`. -- Import by subpath: `import { http } from '@project/libs/http'` and `import { configureServerHttp } from '@project/libs/server'`. - -## Types - -A sketch. The implementation may add fields but keeps these names and meanings. - -```ts -type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; - -interface HttpClientConfig { - baseUrl: string | (() => string); // a function is read on each request, so env is never read at module load - headers?: Record; - timeout?: number | false; // ms per attempt, default 15_000 - credentials?: RequestCredentials; // default 'include' (auth is cookie-based) - retry?: RetryConfig | false; // default: enabled with the defaults below - refresh?: RefreshConfig | false; // default: false until bootstrap sets it - getCookieHeader?: () => string | Promise; // server only, set through configureServerHttp - mapErrorBody?: (body: unknown, response: Response) => Partial; // adapts the back end's error contract -} - -interface RetryConfig { - attempts: number; // retries after the first try, default 2 (3 tries at most) - methods: HttpMethod[]; // default ['GET', 'HEAD', 'OPTIONS'] - statuses: number[]; // default [408, 429, 502, 503, 504] - networkErrors: boolean; // default true (no response) - baseDelay: number; // default 300 ms - maxDelay: number; // default 5_000 ms -} - -interface RefreshConfig { - endpoint: string; // relative to baseUrl or absolute, e.g. '/auth/refresh' - method?: 'POST' | 'GET'; // default 'POST' - shouldRefresh?: (error: HttpError) => boolean; // default: error.status === 401 - onFailure?: () => void; // called once per failed refresh, e.g. emit the logout event -} - -// What a feature may set in http.extend(). Auth settings are left out, so a feature cannot break them. -type FeatureHttpConfig = Omit, 'refresh' | 'credentials' | 'getCookieHeader' | 'retry'> & { - retry?: Partial | false; // merged field by field over the root's retry -}; - -interface RequestOptions { - params?: Record; - headers?: Record; - signal?: AbortSignal; - timeout?: number | false; - retry?: Partial | boolean; // false disables; true or an object opts in (see Retry) - skipRefresh?: boolean; // this request never triggers a refresh - responseType?: 'auto' | 'json' | 'text' | 'blob' | 'arrayBuffer'; // default 'auto' - init?: Omit; // passthrough, e.g. keepalive or priority; never Next.js caching options -} - -interface HttpResponse { - data: T; - status: number; - headers: Headers; - requestId: string; -} - -interface HttpErrorShape { - code: HttpErrorCode | string; // the server's code wins when the body has one - message: string; - status: number; // 0 when there was no response (network, timeout, abort) - fieldErrors?: Record; // field path → message, e.g. { 'address.city': '...' } - hint?: string; // how the user can fix it - requestId?: string; - retryAfter?: number; // seconds, from Retry-After on 429 and 503 -} -``` - -## API - -- Verbs resolve with the parsed body, typed by the caller (the repository passes its `*ResponseDto`): `get(url, options?)`, `delete(url, options?)`, `post(url, body?, options?)`, `put(url, body?, options?)`, `patch(url, body?, options?)`. -- `request({ method, url, body, ...options })` resolves with `HttpResponse`, for when the caller needs the status, headers, or request id (pagination headers, HEAD requests). -- `upload(url, input, options?)` and `download(url, options?)`: see Files. -- `interceptors.request.use(fn)` and `interceptors.response.use(onSuccess?, onError?)` both return an eject function. -- `configure(partial)`: root client only, at bootstrap (for example to set `baseUrl` and `refresh`). Never after the app has started. -- `extend(config: FeatureHttpConfig)`: returns a feature client. It reads the root's config live (settings made later in bootstrap still apply), runs the root's interceptors before its own, and shares the root's refresh coordinator and abort-all controller. -- `abortAll(reason?)`: browser only. On the root it aborts every in-flight request of every feature (logout); on a feature client, only that feature's requests (leaving its page). New requests work right after. - -## Root and feature clients - -- **Root:** `http` is created once in `http.ts` with retry on with defaults and refresh off. The app's bootstrap sets its `baseUrl` from the app's env (libs never read env, see [lib-env.md](lib-env.md)), turns on refresh, and registers the shared interceptors. Bootstraps are idempotent, so each interceptor is registered once. A request sent before `baseUrl` is set throws a clear error instead of calling a relative URL. -- **Feature:** every feature has `features//http.ts` exporting one client made with `http.extend(...)` and named after the feature (`catalogHttp`, `ordersHttp`). A feature with nothing special still has one: `export const ordersHttp = http.extend({});`. That keeps one shape everywhere, and moving a feature to its own service is a one-line change. -- Only the feature's repositories import its client (`../../http` from a repository folder). The feature's `index.ts` does not export it. -- The root `http` is imported only by feature `http.ts` files, the app's bootstrap (configure and shared interceptors), and the logout action (`abortAll`). Repositories never use the root client directly. - -What a feature may set: - -| Setting | Example | Merge | -|---|---|---| -| `baseUrl` | Its own service: `() => getEnv().catalogApiUrl` | Replaces the root's | -| `headers` | An API version header only this service needs | By key; the feature wins | -| `timeout` | Reports and exports that need 60 s | Replaces the root's | -| `retry` | Search retries more; payments use `retry: false` | Field by field | -| Feature-only interceptors | Unwrapping an envelope only this service uses | Run after the root's | -| `mapErrorBody` | Only for a back end with a different error contract | Replaces the root's | - -A feature never sets `refresh`, `credentials`, or `getCookieHeader`: auth works the same for the whole app, and all clients share one refresh, so two features never refresh at once. - -- One-off needs of a single endpoint (a longer timeout, no retry, `skipRefresh`) go in that request's options, not in the feature config. -- Merge order per request: lib defaults → root config → feature config → request options. Headers and retry merge by key; everything else is replaced by the more specific value. -- `createHttpClient(config)` makes an independent client that inherits nothing. Use it only for third-party APIs that don't use the app's auth (a maps provider), in the feature's `http.ts`, with `refresh: false`. - -## Request pipeline - -1. Merge the config (lib defaults → root → feature → request options). Generate one request id with `crypto.randomUUID()`, kept across retries and the refresh replay, and send it as `X-Request-Id`. -2. Run request interceptors in registration order, root first. They run again on every attempt, so retries and the replay after a refresh get fresh headers. -3. Serialize the body and query params. On the server, add the `Cookie` header from `getCookieHeader()`. -4. Send with one signal combined by `AbortSignal.any` from the caller's `signal`, the per-attempt timeout, the feature client's abort-all controller, and the root's. -5. A non-2xx status or no response is normalized to `HttpError`. -6. If refresh applies, refresh and replay once. The replay doesn't count as a retry attempt. -7. If retry applies, wait and go back to step 2. -8. On success, parse the body, run the `onSuccess` interceptors, and resolve. On failure, run the `onError` interceptors and throw the final `HttpError`. - -## Body and params - -- A plain object or array is sent as `JSON.stringify` with `Content-Type: application/json`. -- `FormData` is sent as is, and `Content-Type` is never set, so the platform adds the multipart boundary. -- `URLSearchParams`, `Blob`, `File`, `ArrayBuffer`, and strings are sent as is. `undefined` sends no body. GET, HEAD, and DELETE bodies are not supported. -- Query params drop `undefined` and `null`, repeat the key for arrays (`?tag=a&tag=b`), encode with `URLSearchParams`, and merge with any query string already in the URL. -- `responseType: 'auto'`: 204, 205, or an empty body resolves with `undefined`; a JSON content type is parsed; anything else resolves as text. Invalid JSON throws `PARSE_ERROR`. -- Unwrapping a back-end envelope (`{ data, meta }`) is a response interceptor's job: on the root when every service uses it, on the feature client when only that service does. Never in each repository. - -## Interceptors - -- Request: `(config: RequestConfig) => RequestConfig | Promise`. Return a new config; never mutate the argument. -- Response: `onSuccess(response: HttpResponse)` returns a response, and `onError(error: HttpError)` returns an `HttpError`. `onError` may change the error but can't turn a failure into a success, so a resolved promise always means success. -- Both run in registration order, root before feature. A throwing interceptor fails the request with `INTERCEPTOR_ERROR`. -- Use them for cross-cutting concerns: `Accept-Language` from the current locale, envelope unwrapping, dev logging, Sentry breadcrumbs (method, URL, status, request id). -- Never put business logic, toasts, navigation, store writes, or per-user module state in them (on the server one client serves every user), and never log cookies or auth headers. -- Shared interceptors are registered on the root in bootstrap; feature-only interceptors in the feature's `http.ts`, right after `extend`. Never in components, models, or repositories. - -## Retry - -- An attempt is retried when its method is in `retry.methods`, the failure is a network error or a status in `retry.statuses`, attempts are left, and the request wasn't aborted. -- The default methods are idempotent reads. POST and PATCH are never retried by default; a request may opt in with `retry: true` only when it sends an idempotency key the back end honors. -- Delay: exponential backoff with full jitter, `random(0, min(maxDelay, baseDelay * 2 ** attempt))`. When the response has `Retry-After` (seconds or a date), wait that long instead, capped at `maxDelay`. Aborting during the wait rejects at once with `ABORTED`. -- Never retried: 4xx other than 408 and 429, `ABORTED`, `TIMEOUT` on non-idempotent methods, and uploads (the UI offers a retry button). -- On the server the defaults are `attempts: 1` and a shorter timeout (about 5 s), so one slow back end doesn't hold up rendering; the page streams around it. -- TanStack Query must not retry on top: `configs/react-query.ts` sets queries' `retry: false`, and the user retries from the error fallback or the toast ([error-handling.md](error-handling.md#reads)). Otherwise one failure multiplies into attempts × query retries. - -## Refresh token - -- Auth is cookie-based: the refresh endpoint reads the refresh cookie and the server sets new cookies. The lib never reads or stores tokens. -- Trigger: `shouldRefresh(error)` is true (default: 401), refresh is configured, the request didn't set `skipRefresh`, it isn't the refresh request itself, and it hasn't already been replayed after a refresh. -- Single flight: one refresh at a time for the whole app, because the root and every feature client share one coordinator. Requests that get a 401 while a refresh runs wait for it. -- Stale 401: each successful refresh increments a generation number. A request sent before the latest successful refresh that returns 401 is replayed right away, without another refresh. -- On success, every waiting request is replayed once. A replay that gets 401 again fails with `UNAUTHORIZED` without refreshing again, so there are no loops. -- On failure, every waiting request fails with `UNAUTHORIZED` and `onFailure()` runs once (the app emits its logout event; the auth feature clears the store, and on a page that needs a logged-in user the `AuthGuard` sends the user to login). Later requests try normally, so logging in again works without a reload. -- The refresh request is sent with `skipRefresh: true`, `retry: false`, and the normal timeout, and runs request interceptors like any request. -- Waiting is abortable per request: an aborted waiter rejects with `ABORTED` while the refresh continues for the others. -- In the browser, run the refresh inside `navigator.locks.request('http-refresh', ...)` when available, so two tabs never send the same refresh cookie at once (the back end may rotate and revoke it). -- On the server refresh is disabled. Server requests send no auth cookies (Server side), so the server render never reads or refreshes the session, and a 401 there throws `UNAUTHORIZED` to its boundary. - -## Abort - -- Per request: pass `signal`. Repositories take an optional last parameter `{ signal?: AbortSignal }` and forward it, so `queryFn: ({ signal }) => productsRepository.list(args, { signal })` cancels stale requests on unmount or key change. -- Timeout: per attempt, from `timeout` (request option → feature → root → default). `timeout: false` disables it. Uploads and downloads default to no timeout; the user cancels them instead. -- Whole app: `http.abortAll()` in the logout action, so no request from the old session finishes after logout. One feature: `catalogHttp.abortAll()`, for example when leaving a page with long-running requests. -- Never call `abortAll` on the server: clients are shared by every user's requests. -- The caller's or abort-all's signal produces `ABORTED`; the timeout produces `TIMEOUT`. Tell them apart by which signal fired, not by the message. -- Aborted requests are never retried, never trigger a refresh, and never call `onFailure`. The UI ignores `ABORTED` errors: no toast, no error state. - -## Files - -```ts -upload(url: string, input: File | Blob | File[] | FormData, options?: UploadOptions): Promise; - -interface UploadOptions extends Omit { - method?: 'POST' | 'PUT' | 'PATCH'; // default 'POST' - fieldName?: string; // default 'file', used when input is a File, Blob, or File[] - fields?: Record; // extra form fields sent with the file - onProgress?: (progress: UploadProgress) => void; -} - -interface UploadProgress { - loaded: number; - total: number; - percent: number; // integer 0–100 -} - -download(url: string, options?: DownloadOptions): Promise; - -interface DownloadOptions extends Omit { - onProgress?: (progress: UploadProgress) => void; -} - -interface DownloadResult { - blob: Blob; - fileName?: string; - contentType?: string; -} -``` - -- `upload` wraps a File, Blob, or File[] in `FormData` under `fieldName` (repeated for arrays) with `fields`. It uses `XMLHttpRequest`, because `fetch` can't report upload progress, and still runs interceptors, sends cookies (`withCredentials`), uses the request id, normalizes errors, and joins the refresh flow (the file is re-sent after a successful refresh). `signal` calls `xhr.abort()`. No automatic retry. -- The UI shows the percentage, file name and size, and a cancel button wired to the signal (see [ui-rules.md](ui-rules.md#file-uploads)). -- `download` uses `fetch`. `fileName` comes from `Content-Disposition` (`filename*` first, then `filename`). Progress is reported while reading the body stream when `Content-Length` is known. Saving the blob (object URL and link click) is a small browser util in `shared/utils`, not in the lib. -- `post(url, formData)` is fine for a small file when the UI needs no progress or cancel. - -## Errors - -- Every failure from every step is thrown as one `HttpError`: it extends `Error` and has the `HttpErrorShape` fields plus `method`, `url`, and `cause`. The lib throws nothing else. -- `isHttpError(error)` checks a brand such as `Symbol.for('project.http-error')`, not only `instanceof`, because server and client bundles can hold separate copies of the class. -- `toJSON()` returns the plain shape for logs and Sentry. -- `mapErrorBody` reads the error body (default: `code`, `message`, `hint`, and `fieldErrors` or `errors` from a JSON body). Set it once on the root when the back-end contract differs; a feature sets its own only for a back end with a different contract. -- `requestId` is the server's `X-Request-Id` response header when present, otherwise the id the client sent, so even network errors can be traced. -- `retryAfter` is the `Retry-After` header of a 429 or 503 in seconds (a date is converted), so the UI can say how long to wait. -- Server messages pass through as is; the back end localizes them from `Accept-Language`. Messages the lib creates (network, timeout, parse, unknown) are i18n keys such as `errors:http.network`, with a matching hint key, and the UI translates them. The lib never imports i18next. -- The lib never shows errors. The error handler lib decides what each one shows and reports it ([lib-error-handler.md](lib-error-handler.md)): a failed read reaches its error boundary or an empty state, a failed action goes through `applyServerErrors` or `showActionError` (fields, form alert, toast), and the auth feature handles logout ([error-handling.md](error-handling.md)). - -| Code | When | -|---|---| -| `NETWORK_ERROR` | No response | -| `TIMEOUT` | The per-attempt timeout fired | -| `ABORTED` | The caller or `abortAll` aborted it | -| `VALIDATION` | 400 or 422 with field errors | -| `BAD_REQUEST` | Other 400 | -| `UNAUTHORIZED` | 401 | -| `FORBIDDEN` | 403 | -| `NOT_FOUND` | 404 | -| `CONFLICT` | 409 | -| `RATE_LIMITED` | 429 | -| `SERVER_ERROR` | 5xx | -| `PARSE_ERROR` | The body couldn't be parsed | -| `INTERCEPTOR_ERROR` | An interceptor threw | -| `UNKNOWN` | Anything else | - -## Server side - -- `bootstrap.server.ts` calls `configureServerHttp` once (code below). It sets the root's server `baseUrl` (from the app's server env, for example an internal service address) and the cookie provider on the root, so every feature client forwards the same cookies. A feature with its own `baseUrl` reads it through its project's `getEnv()`, which the server bootstrap fills with the server-side address. -- `getCookieHeader` runs on every server request and forwards only the names in the app's `FORWARDED_COOKIES`, the cookies the server render needs, such as `THEME_COOKIE`. An indexable page's locale comes from its URL, never from a forwarded cookie ([ui-rules.md](ui-rules.md#crawlers)). In an app with more than one locale, the page passes its URL's locale to its cache calls, and the repository sends it as the back-end request's `Accept-Language` header, in that request's `headers` option. The server registers no `Accept-Language` interceptor: an interceptor never sees the URL, and a module-level language would serve every request. It never forwards the auth cookies, so no back-end response on the server depends on who the viewer is ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). Never keep cookies, users, or tokens in module state. -- On the server, refresh is off, `abortAll` is unavailable, retry defaults to one attempt with a shorter timeout, `credentials` is ignored, and every request is sent with `cache: 'no-store'`, whatever `init` says. -- `init` never carries Next.js caching options (`next: { revalidate, tags }`): the Next.js server keeps no cache between requests (see [b2c-b2b.md](b2c-b2b.md#no-server-cache)). - -`bootstrap.server.ts`: - -```ts -configureServerHttp({ - baseUrl: serverEnv.API_INTERNAL_URL, - getCookieHeader: async () => - (await cookies()) - .getAll() - .filter(({ name }) => FORWARDED_COOKIES.has(name)) - .map(({ name, value }) => `${name}=${encodeURIComponent(value)}`) - .join('; '), -}); -``` - -`FORWARDED_COOKIES` is a `ReadonlySet` in the app's `constants/`, built from the cookie name constants ([lib-cookie.md](lib-cookie.md)). Adding an auth cookie to it is an override of rendering-patterns.md's Auth-dependent UI rule and needs a recorded decision. - -## Usage - -`features/catalog/http.ts`. `getEnv` is the owning project's env getter (see [lib-env.md](lib-env.md#project-env)). - -```ts -import { http } from '@project/libs/http'; -import { getEnv } from '../../env'; - -export const catalogHttp = http.extend({ - baseUrl: () => getEnv().catalogApiUrl, - timeout: 30_000, - retry: { attempts: 3 }, -}); - -catalogHttp.interceptors.response.use((response) => ({ - ...response, - data: (response.data as CatalogEnvelope).result, -})); -``` - -`features/orders/http.ts`, a feature with nothing special: - -```ts -import { http } from '@project/libs/http'; - -export const ordersHttp = http.extend({}); -``` - -`features/catalog/repositories/products/products.ts` - -```ts -import type { DownloadResult, UploadProgress } from '@project/libs/http'; -import { catalogHttp } from '../../http'; - -export const productsRepository = { - async list(args: ListProductsArgs, options?: { signal?: AbortSignal }): Promise { - const response = await catalogHttp.get(PRODUCTS_ENDPOINT, { - params: toListProductsParams(args), - signal: options?.signal, - }); - return toListProductsPayload(response); - }, - - async uploadImage( - args: UploadProductImageArgs, - options?: { signal?: AbortSignal; onProgress?: (progress: UploadProgress) => void }, - ): Promise { - const response = await catalogHttp.upload( - productImageEndpoint(args.productId), - args.file, - options, - ); - return toProductImagePayload(response); - }, - - exportReport(args: ExportProductsArgs): Promise { - return catalogHttp.download(PRODUCTS_EXPORT_ENDPOINT, { params: toExportParams(args), timeout: 120_000 }); - }, -}; -``` - -The export's long timeout applies to that one request, so it is a request option, not feature config. - -Bootstrap, root client only (`bootstrap.client.ts`). The refresh endpoint and logout event come from the auth feature's public API. - -```ts -http.configure({ - baseUrl: clientEnv.NEXT_PUBLIC_API_URL, - refresh: { endpoint: AUTH_ENDPOINTS.refresh, onFailure: () => eventEmitter.emit(AUTH_EVENTS.logout) }, -}); - -http.interceptors.request.use((config) => ({ - ...config, - headers: { ...config.headers, 'Accept-Language': i18n.language }, -})); -``` - -## Acceptance checklist - -For building or changing the lib: - -``` -[ ] GET, POST, PUT, PATCH, DELETE send the right method, headers, JSON or FormData body, and query params, and resolve with the parsed body -[ ] A request sent before bootstrap sets the root's baseUrl throws a clear "not configured" error -[ ] 204 resolves with undefined; invalid JSON throws PARSE_ERROR -[ ] Request and response interceptors run in order, re-run on retry and replay, and eject works -[ ] A GET that gets 503 twice then 200 resolves after 3 tries; a POST that gets 503 fails at once -[ ] Retry-After is respected; aborting during the backoff wait rejects at once with ABORTED -[ ] Five parallel requests that all get 401 cause exactly one refresh, then all five replay and resolve, also across feature clients -[ ] http.extend rejects refresh, credentials, and getCookieHeader at type level; feature headers and retry merge over the root's; request options win over both -[ ] A feature client runs the root's interceptors before its own and sees root settings made after it was created -[ ] A failed refresh rejects all waiters with UNAUTHORIZED and calls onFailure exactly once -[ ] A replay that gets 401 again fails without a second refresh -[ ] Caller abort gives ABORTED and timeout gives TIMEOUT; http.abortAll() aborts every feature's requests, a feature's abortAll() only its own, and new requests still work -[ ] Upload reports progress from 0 to 100, can be cancelled, and joins the refresh flow -[ ] Download returns the blob and the file name from Content-Disposition -[ ] Every failure is an HttpError with code, message, status, fieldErrors, hint, and requestId, plus retryAfter on a 429 or 503 that sends Retry-After; isHttpError works across bundles -[ ] On the server, each request forwards only its own allowed cookies and never the auth cookies, is sent with cache: 'no-store', refresh never runs, and no state leaks between requests -``` diff --git a/.claude/skills/front-end-architect/references/lib-json-ld.md b/.claude/skills/front-end-architect/references/lib-json-ld.md deleted file mode 100644 index 82ca6e7..0000000 --- a/.claude/skills/front-end-architect/references/lib-json-ld.md +++ /dev/null @@ -1,1010 +0,0 @@ -# JSON-LD lib (`packages/libs/src/json-ld`) - -Builds the schema.org JSON-LD that introduces the business and every indexable page to Google, focused on ecommerce: the business and the website on the home page, a product or a product with variants on its page, with its offer, sale price, rating, and reviews, the store-wide return and shipping policies on their own pages, the breadcrumb trail, and a physical store. Server only: JSON-LD is part of the server render and the same for every visitor, and island's `JsonLd` primitive writes it into the page. Framework-agnostic; no dependency. schema-dts makes every property optional, so it accepts a product with no price, `IRT`, and Jalali dates; next-seo's serializer escapes only ``, which `` gets past; react-schemaorg turns `&` into `&` inside values. - -Sources: the vocabulary at schema.org/docs/schemas.html; what Google reads, requires, and shows at developers.google.com/search/docs/appearance/structured-data. - -Contents: What each page gets · What the markup may say · Structure · Types · API · Values · Rendering · Not in this lib · Adding a type · Implementation · Usage · Testing and monitoring · Acceptance checklist - -## What each page gets - -| Page | Nodes | What Google does with them | -|---|---|---| -| Home, in every locale | `buildOrganization` (an `OnlineStore`) and `buildWebSite` | The logo, contact details, and identifiers in the knowledge panel; the site name beside every result | -| Product | `buildProduct`, or `buildProductGroup` when the page sells variants; `buildBreadcrumbList` | Merchant listings and product snippets: price, sale price, availability, rating, and the product's own shipping and returns; the trail on desktop results | -| Category, brand, and other listings | `buildBreadcrumbList` | The trail on desktop results | -| Returns policy | `buildOrganization` with `returnPolicy` | The store's return window and fees on its product results | -| Shipping policy | `buildOrganization` with `shipping` | The store's delivery cost and time on its product results | -| Store branch | `buildStore` and `buildBreadcrumbList` | The branch's address, opening hours, and phone | -| Search results, cart, checkout, account, compare, and every not-found, no-access, or error state | Nothing | Nothing: these pages are `noindex`, or blocked in `robots.ts` | - -- One graph per page: the page passes its nodes to `buildGraph` and renders the result with one ``. -- The platform's `app/json-ld/` holds one builder per page type that maps a `*Payload`, such as `buildProductPageJsonLd(product)`. The home and policy pages build theirs from the business facts in the app's `configs/seo.ts` (Usage). - -## What the markup may say - -Google shows rich results only from markup it trusts, and a manual action for misleading markup makes it ignore the site's markup. So: - -- Only what the page shows. The name, price, sale price, availability, rating, review count, reviews, and policies match the server HTML of the same URL, in both templates. They come from the same `*Payload` in the same request, so they match by construction. Never add a value the page doesn't show; identifiers (`sku`, `gtin`, `mpn`) and the brand may stay invisible. -- The same for every visitor. Build it only from what the server render reads, never from the viewer: no member price, personal price, cart, or recommendation. A page whose price depends on the viewer, such as a B2B price list after login, has no `offer`; its product can still carry its rating. -- The page's main thing. A product page marks up its product, never the products in its rails, which have their own pages. -- No self-serving ratings. `rating` and `reviews` go on products only, never on the organization or a store: Google ignores what a business shows about itself. -- One name for the business. `buildOrganization` and `buildWebSite` take the same `name` and `alternateName`, and every locale's home page renders the same `buildWebSite`, because Google keeps one site name per domain. -- Nothing Google stopped showing: no `FAQPage` (FAQ rich results ended on May 7, 2026), no `SearchAction` (the sitelinks search box ended on November 21, 2024), and no `HowTo` (ended in September 2023). - -## Structure - -``` -packages/libs/src/json-ld/ -├── json-ld.ts # configureJsonLd, buildGraph, serializeJsonLd -├── organization.ts # buildOrganization (an OnlineStore), buildWebSite -├── product.ts # buildProduct, buildProductGroup -├── offer.ts # Offer with its struck-through price, and AggregateOffer; used by product.ts -├── policies.ts # return policy and shipping: store-wide for organization.ts, per product for offer.ts -├── breadcrumb.ts # buildBreadcrumbList -├── store.ts # buildStore: a physical branch -├── values.ts # absolute URLs, enumeration URLs, @id values, plain text; not exported -├── types.ts # every builder's input, and the nodes and graph they return -├── constants.ts # JSON_LD_CONTEXT, SCHEMA_ORG_URL, JSON_LD_LIMITS -└── server.ts # the module's only entry; import 'server-only' -``` - -- The module is server-only, like a feature's `caches/`: it has only `server.ts`, exposed as the `@project/libs/json-ld/server` subpath and re-exported by the project's `server.ts`. A client component that imports it fails the build, so JSON-LD stays in the server render and its builders stay out of client bundles. -- `server.ts` exports `configureJsonLd`, `buildGraph`, `serializeJsonLd`, `buildOrganization`, `buildWebSite`, `buildProduct`, `buildProductGroup`, `buildBreadcrumbList`, `buildStore`, `JSON_LD_LIMITS`, and the types. -- It reads no env and imports no React or Next.js. island's `JsonLd` primitive renders its graph, and the platform's `app/json-ld/` calls its builders. - -## Types - -Inputs are plain values: what the page shows, in the shape a payload gives it. The builders write the schema.org shape. Enumeration members are schema.org names (`'InStock'`), which the lib writes as full URLs (`https://schema.org/InStock`). Google's required values are required in the types, so a missing one fails type-check before it fails in Search Console. - -```ts -import type { JSON_LD_CONTEXT } from './constants'; - -// An absolute URL, or a root-relative path ('/product/123') that resolves against siteUrl. -export type Url = string; - -export type JsonLdOptions = { - siteUrl: string; // the site's origin from the app's env; the same value as metadataBase -}; - -// What the builders return. Callers pass nodes to buildGraph and never read them. -export type JsonLdValue = string | number | boolean | JsonLdNode | readonly JsonLdValue[] | null | undefined; -export type JsonLdNode = { readonly [property: string]: JsonLdValue }; -export type JsonLdGraph = { readonly '@context': typeof JSON_LD_CONTEXT; readonly '@graph': readonly JsonLdNode[] }; - -// schema.org enumeration members, written as https://schema.org/. -// Only the members Google reads; schema.org has more. -export type ItemAvailability = - | 'InStock' | 'LimitedAvailability' | 'OutOfStock' | 'SoldOut' | 'BackOrder' - | 'PreOrder' | 'PreSale' | 'InStoreOnly' | 'OnlineOnly' | 'Discontinued'; -export type OfferItemCondition = 'NewCondition' | 'UsedCondition' | 'RefurbishedCondition'; -export type ReturnMethod = 'ReturnByMail' | 'ReturnInStore' | 'ReturnAtKiosk'; -export type ReturnFees = 'FreeReturn' | 'ReturnFeesCustomerResponsibility' | 'ReturnShippingFees'; -export type DayOfWeek = 'Saturday' | 'Sunday' | 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday'; -// The properties a group's variants differ in, written as https://schema.org/. -export type VariesBy = 'color' | 'size' | 'material' | 'pattern'; - -export type MoneyInput = { value: number; currency: string }; // currency: ISO 4217 -export type DaysInput = { min: number; max: number }; // whole days - -export type PostalAddressInput = { - country: string; // ISO 3166-1 alpha-2, e.g. 'IR' - region?: string; - locality?: string; - street?: string; - postalCode?: string; -}; - -export type ShippingConditionInput = { - country: string; // where it ships, ISO 3166-1 alpha-2 - rate: MoneyInput; // value 0 is free - transitDays?: DaysInput; // from the dispatch to the door -}; - -// Store-wide shipping. When several conditions match an order, Google uses the cheapest. -export type ShippingServiceInput = { - handlingDays?: DaysInput; // from the order to the dispatch - conditions: readonly (ShippingConditionInput & { orderValueFrom?: number })[]; // orderValueFrom: in rate.currency -}; - -// A product's own shipping, when it differs from the store's. Google needs both times here. -export type ShippingInput = Required & { handlingDays: DaysInput }; - -type ReturnWindow = { - country: string | readonly string[]; // where the policy applies - returnCountry: string; // where the items go back to - method?: ReturnMethod; - fees?: ReturnFees; - shippingFee?: MoneyInput; // only with fees 'ReturnShippingFees' -}; - -export type ReturnPolicyInput = - | (ReturnWindow & { category: 'MerchantReturnFiniteReturnWindow'; days: number }) - | (ReturnWindow & { category: 'MerchantReturnUnlimitedWindow' }) - | { category: 'MerchantReturnNotPermitted'; country: string | readonly string[] }; - -export type OfferInput = { - price: number; // the price the page shows, greater than 0: on a marketplace, the buy box's - priceCurrency: string; // ISO 4217 - availability: ItemAvailability; - itemCondition?: OfferItemCondition; // omit for new items - listPrice?: number; // the struck-through price the page shows beside a discount - saleStarts?: string; // the sale's window: ISO 8601 date-time with offset, e.g. '2026-10-31T23:59:59+03:30' - saleEnds?: string; - shipping?: readonly ShippingInput[]; // only when they differ from the store's policies - returnPolicy?: ReturnPolicyInput; -}; - -// A page that shows a price range from several sellers and no single price. Product snippets only: -// merchant listings need one Offer. Never for variants. -export type OfferRangeInput = { lowPrice: number; highPrice: number; offerCount: number; priceCurrency: string }; - -export type RatingInput = { - value: number; // the average the page shows - count: number; // how many ratings it averages - best?: number; // default 5 - worst?: number; // default 1 -}; - -export type ReviewInput = { - author: string; // the name the page shows, under 100 characters - rating: number; - best?: number; // default 5 - body?: string; - datePublished?: string; // ISO 8601 -}; - -export type ProductInput = { - url: Url; // the page's canonical URL - name: string; - image: readonly Url[]; // the gallery, main image first - description?: string; // plain text the page shows - sku?: string; - gtin?: string; // 8, 12, 13 or 14 digits - mpn?: string; - brand?: string; - category?: string; // the shop's category path, e.g. 'Electronics > Mobile phones' - color?: string; - size?: string; - material?: string; - pattern?: string; - offer?: OfferInput | OfferRangeInput; - rating?: RatingInput; - reviews?: readonly ReviewInput[]; // every review the server HTML shows, or none -}; - -// A variant: its own name ('Wool coat, green, small'), images, unique sku, attributes, and offer. -// url is the page with the variant selected, such as '/product/12?color=green&size=s'. -export type VariantInput = Omit & { sku: string }; - -// The variants of one product, on one page that preselects a variant from its URL. -export type ProductGroupInput = { - url: Url; // the page's canonical URL, with no variant selected - groupId: string; // the parent SKU - name: string; - variesBy: readonly VariesBy[]; - variants: readonly VariantInput[]; - image?: readonly Url[]; - description?: string; - brand?: string; - rating?: RatingInput; // ratings and reviews that cover every variant - reviews?: readonly ReviewInput[]; -}; - -export type BreadcrumbInput = { name: string; url: Url }; - -export type ContactPointInput = { - contactType: string; // e.g. 'customer service' - telephone?: string; // with the country code, e.g. '+98-21-12345678' - email?: string; - areaServed?: string | readonly string[]; - availableLanguage?: readonly string[]; -}; - -export type OrganizationInput = { - name: string; // the site name, as in WebSiteInput - logo: Url; // at least 112x112 px, crawlable, readable on white - url?: Url; // default '/' - alternateName?: string | readonly string[]; - legalName?: string; - description?: string; - sameAs?: readonly Url[]; // official profiles on other sites - telephone?: string; - email?: string; - address?: PostalAddressInput; - contactPoints?: readonly ContactPointInput[]; - iso6523Code?: string; // e.g. '0060:123456789' (DUNS); Google prefers it to vatId and taxId - vatId?: string; - taxId?: string; - foundingDate?: string; // ISO 8601 - returnPolicy?: ReturnPolicyInput; // only on the page that shows the policy - shipping?: readonly ShippingServiceInput[]; // only on the page that shows the rates -}; - -export type WebSiteInput = { - name: string; // one per domain: the same in every locale - alternateName?: string | readonly string[]; // most preferred first - inLanguage?: string; // BCP 47, e.g. 'fa-IR' -}; - -export type OpeningHoursInput = { days: readonly DayOfWeek[]; opens: string; closes: string }; // 'HH:MM', local time - -export type StoreInput = { - type?: `${string}Store`; // the most specific subtype, e.g. 'ElectronicsStore'; default 'Store' - url: Url; // the branch's page - name: string; - address: PostalAddressInput; - image?: readonly Url[]; - telephone?: string; - geo?: { latitude: number; longitude: number }; // at least 5 decimal places - openingHours?: readonly OpeningHoursInput[]; - priceRange?: string; -}; -``` - -## API - -- `configureJsonLd({ siteUrl })` runs once, in `bootstrap.server.ts`, with the site's origin from the app's env (`NEXT_PUBLIC_SITE_URL`, the value that also sets `metadataBase`). It keeps only the origin and throws on an invalid URL, so a bad value stops the app at startup. A builder called before it throws "json-ld is not configured. bootstrap.server.ts must call configureJsonLd first." -- Every `build*` function is pure: it takes one input and returns one node, or `null` when a value Google requires is missing or invalid. It never throws on data, because a page renders the same with or without its markup: - - `buildProduct` returns `null` without a name, an image, and at least one of a valid offer, rating, or review: Google shows no product without one of them. - - `buildProductGroup` returns `null` without a name, a valid variant, or one of a priced variant, a rating, or a review. A variant needs a name and an image; a variant without its own images gets the group's from the caller. - - `buildBreadcrumbList` returns `null` for a trail of fewer than two items, which Google ignores. - - Inside a node, the lib drops an offer whose price isn't greater than 0, a rating with no count or a value outside its scale, a review without an author or a valid rating, a GTIN with a wrong length or check digit, and a URL that isn't `http` or `https`. -- `buildGraph(...nodes)` drops `null` nodes and empty values (`undefined`, `null`, `NaN`, blank strings, empty arrays, and objects left with only their `@type`) and returns `{ '@context': 'https://schema.org', '@graph': [...] }`, or `null` when no node is left. -- `serializeJsonLd(graph)` returns the JSON text with `<`, `>`, `&`, U+2028, and U+2029 written as `\u` escapes, so no value can end the script element or open an HTML comment, and `JSON.parse` returns the same values. Only island's `JsonLd` calls it. -- URLs: every URL input takes a root-relative path (`/product/123`) or an absolute URL. A path resolves against `siteUrl`; an absolute URL, such as an image on the CDN, keeps its origin. Non-ASCII paths come out percent-encoded, as Google recommends. -- `@id`: the organization is `/#organization`, the website `/#website`, a product or group `#product`, and a store `#store`. The website points at the organization as its `publisher` through that `@id`, and every page and locale gives the organization the same one. - -## Values - -JSON-LD is read by machines in every locale, so its values keep their machine form whatever the page's language: - -- Text: plain text the page shows, in the page's language, never HTML or entities. Use the payload's plain fields, such as a summary, not the HTML description. The lib collapses whitespace and cuts descriptions at `JSON_LD_LIMITS.descriptionLength` characters. It never cuts a review, which must match the page. -- Numbers: JavaScript numbers, never formatted strings. No thousands separators, currency signs, or Persian digits: `'۱۲٬۹۰۰٬۰۰۰ تومان'` is what the page shows, and `129000000` with `'IRR'` is the value. The page formats with `Intl`; JSON-LD keeps the raw number. -- Prices: greater than 0, in the currency's main unit, with `priceCurrency` as an ISO 4217 code. Toman has no ISO 4217 code, and Search Console flags `IRT`, so a site that shows toman writes rials: the price times 10, with `'IRR'`. Google shows a toman price labelled `IRR` as rials, at a tenth of the real price. The currency code and the multiplier are constants in one place, because the rial redenomination may bring a new ISO code. One URL has one currency: a site that sells in two currencies serves them on different URLs, never by cookie or location. On a marketplace, the offer is the buy box: the seller and price the page shows first. -- Dates: ISO 8601 in the Gregorian calendar, as the API sends them (`2026-10-31`, or `2026-10-31T23:59:59+03:30`). Never a Jalali date, a date formatted for display, or a date without zero padding (`2026-10-9`). A date-time always carries its offset, Iran's being `+03:30`, because Google reads one without it in Googlebot's time zone. A sale's `saleStarts` comes before its `saleEnds`. -- Codes: countries in ISO 3166-1 alpha-2 (`'IR'`), languages in BCP 47 (`'fa-IR'`), and telephones with the country code (`'+98-21-12345678'`). Days of the week and every enumeration member stay in English. -- Identifiers: `gtin` in its numeric form, never a GS1 Digital Link URL; the lib fixes Persian and Arabic digits, spaces, and dashes. `sku` has no spaces, and every variant has its own. `mpn` is the manufacturer's part number. -- Images: absolute URLs that Googlebot can crawl and index, the main image first. Never a URL that `robots.txt` blocks or that needs a cookie. -- URLs: canonical. A page's `url` is the path that `generateMetadata` gives `alternates.canonical`, both from the platform's navigation paths. - -## Rendering - -- Where: in the page entry (`page.tsx`), once, before the mobile or desktop template, in the first flush, so it's near the top of the HTML. Google prefers product markup in the initial HTML and reads only the first 2 MB of a page. What streams arrives at the end of the document, in a hidden `
` that client JavaScript moves into place. An indexable page has nothing above it that streams, no `loading.tsx` included, so its page entry is always in the first flush ([b2c-b2b.md](b2c-b2b.md#rendering)). Never in a layout, where every page under it would repeat it; in a template, which the page has in two versions; in a part inside ``; or in a client component, which can't import the lib. -- Inside an element: the root layout renders page content inside an element such as `
`, so no JSON-LD is a direct child of `` or ``. When the root fails to hydrate, React renders the document again in the browser but keeps the scripts that sit directly under `` and ``, and Google then reads two copies. -- A native `..." would end the element. -const UNSAFE_IN_HTML = /[<>&\u2028\u2029]/g; - -export function serializeJsonLd(graph: JsonLdGraph): string { - return JSON.stringify(graph).replace(UNSAFE_IN_HTML, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`); -} - -// Drops what says nothing: undefined, null, NaN, blank strings, empty arrays, -// and objects left with nothing but their @type. -function compact(value: unknown): unknown { - if (Array.isArray(value)) { - const items = value.map(compact).filter((item) => item !== undefined); - return items.length > 0 ? items : undefined; - } - if (value !== null && typeof value === 'object') { - const entries = Object.entries(value) - .map(([key, item]) => [key, compact(item)] as const) - .filter(([, item]) => item !== undefined); - return entries.some(([key]) => key !== '@type') ? Object.fromEntries(entries) : undefined; - } - if (typeof value === 'string') return value.trim() || undefined; - if (typeof value === 'number') return Number.isFinite(value) ? value : undefined; - return value ?? undefined; -} -``` - -`values.ts` - -```ts -import { SCHEMA_ORG_URL } from './constants'; -import { getJsonLdOptions } from './json-ld'; -import type { JsonLdNode, MoneyInput, PostalAddressInput, Url } from './types'; - -// '/product/12' becomes 'https://www.example.com/product/12'; absolute URLs keep their origin. -// A value that isn't an http(s) URL is dropped, never thrown: bad data never breaks the page. -export function absoluteUrl(url: Url | undefined): string | undefined { - const value = url?.trim(); - if (!value) return undefined; // a blank URL would resolve to the home page - const { siteUrl } = getJsonLdOptions(); // outside the try: a missing configureJsonLd must throw - try { - const parsed = new URL(value, siteUrl); - return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? parsed.href : undefined; - } catch { - return undefined; - } -} - -// 'InStock' becomes 'https://schema.org/InStock'. -export function schemaUrl(name: string): string { - return `${SCHEMA_ORG_URL}${name}`; -} - -// A stable @id, so nodes in one graph can point at each other: 'https://www.example.com/#organization'. -export function nodeId(url: Url, name: string): string | undefined { - const absolute = absoluteUrl(url); - return absolute && `${absolute}#${name}`; -} - -// One line of plain text, cut at maxLength characters. -export function plainText(value: string | undefined, maxLength = Number.POSITIVE_INFINITY): string | undefined { - const text = value?.replace(/\s+/g, ' ').trim(); - if (!text) return undefined; - const chars = Array.from(text); - return chars.length <= maxLength ? text : `${chars.slice(0, maxLength - 1).join('').trimEnd()}…`; -} - -// A GTIN as Google reads it: 8, 12, 13 or 14 Latin digits with a valid GS1 check digit. -// Persian and Arabic digits, spaces and dashes are fixed; anything else is dropped. -export function gtin(value: string | undefined): string | undefined { - const digits = value - ?.replace(/[۰-۹]/g, (digit) => String(digit.charCodeAt(0) - 0x06f0)) - .replace(/[٠-٩]/g, (digit) => String(digit.charCodeAt(0) - 0x0660)) - .replace(/[\s-]/g, ''); - if (!digits || !/^(\d{8}|\d{12,14})$/.test(digits)) return undefined; - // From the right, the check digit has weight 1, the next digit 3, then 1, 3, and so on. - const sum = Array.from(digits) - .reverse() - .reduce((total, digit, index) => total + Number(digit) * (index % 2 === 0 ? 1 : 3), 0); - return sum % 10 === 0 ? digits : undefined; -} - -export function money({ value, currency }: MoneyInput): JsonLdNode { - return { '@type': 'MonetaryAmount', value, currency }; -} - -export function postalAddress(address: PostalAddressInput): JsonLdNode { - return { - '@type': 'PostalAddress', - addressCountry: address.country, - addressRegion: address.region, - addressLocality: address.locality, - streetAddress: address.street, - postalCode: address.postalCode, - }; -} - -export function isNode(node: JsonLdNode | null | undefined): node is JsonLdNode { - return node !== null && node !== undefined; -} -``` - -`policies.ts` - -```ts -import type { DaysInput, JsonLdNode, ReturnPolicyInput, ShippingInput, ShippingServiceInput } from './types'; -import { money, schemaUrl } from './values'; - -export function returnPolicy(input: ReturnPolicyInput): JsonLdNode { - if (input.category === 'MerchantReturnNotPermitted') { - return { - '@type': 'MerchantReturnPolicy', - applicableCountry: input.country, - returnPolicyCategory: schemaUrl(input.category), - }; - } - return { - '@type': 'MerchantReturnPolicy', - applicableCountry: input.country, - returnPolicyCategory: schemaUrl(input.category), - returnPolicyCountry: input.returnCountry, - merchantReturnDays: input.category === 'MerchantReturnFiniteReturnWindow' ? input.days : undefined, - returnMethod: input.method && schemaUrl(input.method), - returnFees: input.fees && schemaUrl(input.fees), - returnShippingFeesAmount: input.fees === 'ReturnShippingFees' && input.shippingFee ? money(input.shippingFee) : undefined, - }; -} - -// The store-wide shipping, on the organization. -export function shippingService(input: ShippingServiceInput): JsonLdNode { - return { - '@type': 'ShippingService', - handlingTime: input.handlingDays && servicePeriod(input.handlingDays), - shippingConditions: input.conditions.map((condition) => ({ - '@type': 'ShippingConditions', - shippingDestination: { '@type': 'DefinedRegion', addressCountry: condition.country }, - orderValue: - condition.orderValueFrom === undefined - ? undefined - : { '@type': 'MonetaryAmount', minValue: condition.orderValueFrom, currency: condition.rate.currency }, - shippingRate: money(condition.rate), - transitTime: condition.transitDays && servicePeriod(condition.transitDays), - })), - }; -} - -// A product's own shipping, on its offer, when it differs from the store's. -export function shippingDetails(input: ShippingInput): JsonLdNode { - return { - '@type': 'OfferShippingDetails', - shippingDestination: { '@type': 'DefinedRegion', addressCountry: input.country }, - shippingRate: money(input.rate), - deliveryTime: { - '@type': 'ShippingDeliveryTime', - handlingTime: days(input.handlingDays), - transitTime: days(input.transitDays), - }, - }; -} - -function servicePeriod(range: DaysInput): JsonLdNode { - return { '@type': 'ServicePeriod', duration: days(range) }; -} - -function days({ min, max }: DaysInput): JsonLdNode { - return { '@type': 'QuantitativeValue', minValue: min, maxValue: max, unitCode: 'DAY' }; -} -``` - -`offer.ts` - -```ts -import { returnPolicy, shippingDetails } from './policies'; -import type { JsonLdNode, OfferInput, OfferRangeInput, Url } from './types'; -import { absoluteUrl, schemaUrl } from './values'; - -// null when the price can't be shown: missing, zero, negative, or not a number. -export function offerNode(input: OfferInput | OfferRangeInput, url: Url): JsonLdNode | null { - if ('lowPrice' in input) { - if (!(input.lowPrice > 0) || !(input.highPrice >= input.lowPrice)) return null; - return { - '@type': 'AggregateOffer', - lowPrice: input.lowPrice, - highPrice: input.highPrice, - offerCount: input.offerCount, - priceCurrency: input.priceCurrency, - }; - } - if (!(input.price > 0)) return null; - return { - '@type': 'Offer', - url: absoluteUrl(url), - price: input.price, - priceCurrency: input.priceCurrency, - availability: schemaUrl(input.availability), - itemCondition: input.itemCondition && schemaUrl(input.itemCondition), - // Product snippets read priceValidUntil, a date; merchant listings read validFrom and validThrough. - validFrom: input.saleStarts, - validThrough: input.saleEnds, - priceValidUntil: input.saleEnds?.slice(0, 10), - // The price before the discount, which the page shows struck through. - priceSpecification: - input.listPrice !== undefined && input.listPrice > input.price - ? { - '@type': 'UnitPriceSpecification', - priceType: schemaUrl('StrikethroughPrice'), - price: input.listPrice, - priceCurrency: input.priceCurrency, - } - : undefined, - shippingDetails: input.shipping?.map(shippingDetails), - hasMerchantReturnPolicy: input.returnPolicy && returnPolicy(input.returnPolicy), - }; -} -``` - -`product.ts` - -```ts -import { JSON_LD_LIMITS } from './constants'; -import { offerNode } from './offer'; -import type { JsonLdNode, ProductGroupInput, ProductInput, RatingInput, ReviewInput, VariantInput } from './types'; -import { absoluteUrl, gtin, isNode, nodeId, plainText, schemaUrl } from './values'; - -// null when Google can't show the product: no name, no image, or none of a price, a rating, and a review. -export function buildProduct(input: ProductInput): JsonLdNode | null { - const product = productNode(input); - if (!product) return null; - const offers = input.offer ? offerNode(input.offer, input.url) : null; - const aggregateRating = input.rating ? ratingNode(input.rating) : null; - const review = reviewNodes(input.reviews); - if (!offers && !aggregateRating && review.length === 0) return null; - return { '@type': 'Product', '@id': nodeId(input.url, 'product'), ...product, offers, aggregateRating, review }; -} - -// Variants that share one page. Each variant has its own URL (the page with it selected) and offer. -export function buildProductGroup(input: ProductGroupInput): JsonLdNode | null { - const name = plainText(input.name); - const variants = input.variants.map(variantNode).filter(isNode); - const aggregateRating = input.rating ? ratingNode(input.rating) : null; - const review = reviewNodes(input.reviews); - const hasPrice = variants.some((variant) => variant.offers); - if (!name || variants.length === 0 || (!hasPrice && !aggregateRating && review.length === 0)) return null; - return { - '@type': 'ProductGroup', - '@id': nodeId(input.url, 'product'), - url: absoluteUrl(input.url), - name, - productGroupID: input.groupId, - variesBy: input.variesBy.map(schemaUrl), - image: images(input.image), - description: plainText(input.description, JSON_LD_LIMITS.descriptionLength), - brand: input.brand && { '@type': 'Brand', name: plainText(input.brand) }, - aggregateRating, - review, - hasVariant: variants, - }; -} - -function productNode(input: Omit): JsonLdNode | null { - const name = plainText(input.name); - const image = images(input.image); - if (!name || image.length === 0) return null; - return { - '@type': 'Product', - name, - image, - description: plainText(input.description, JSON_LD_LIMITS.descriptionLength), - sku: input.sku, - gtin: gtin(input.gtin), - mpn: input.mpn, - brand: input.brand && { '@type': 'Brand', name: plainText(input.brand) }, - category: input.category, - color: input.color, - size: input.size, - material: input.material, - pattern: input.pattern, - }; -} - -function variantNode(input: VariantInput): JsonLdNode | null { - const variant = productNode(input); - if (!variant) return null; - return { ...variant, offers: input.offer ? offerNode(input.offer, input.url) : null }; -} - -function images(urls: readonly string[] | undefined): string[] { - return (urls ?? []) - .map(absoluteUrl) - .filter((url): url is string => url !== undefined) - .slice(0, JSON_LD_LIMITS.images); -} - -function ratingNode({ value, count, best = 5, worst = 1 }: RatingInput): JsonLdNode | null { - if (!(count > 0) || !(value >= worst && value <= best)) return null; - return { - '@type': 'AggregateRating', - ratingValue: value, - ratingCount: count, - bestRating: best === 5 ? undefined : best, - worstRating: worst === 1 ? undefined : worst, - }; -} - -function reviewNodes(reviews: readonly ReviewInput[] | undefined): JsonLdNode[] { - return (reviews ?? []).map(reviewNode).filter(isNode); -} - -function reviewNode({ author, rating, best = 5, body, datePublished }: ReviewInput): JsonLdNode | null { - const name = plainText(author); - if (!name || name.length > JSON_LD_LIMITS.authorNameLength || !(rating >= 1 && rating <= best)) return null; - return { - '@type': 'Review', - author: { '@type': 'Person', name }, - reviewRating: { '@type': 'Rating', ratingValue: rating, bestRating: best === 5 ? undefined : best }, - reviewBody: plainText(body), - datePublished, - }; -} -``` - -`organization.ts` - -```ts -import { returnPolicy, shippingService } from './policies'; -import type { ContactPointInput, JsonLdNode, OrganizationInput, WebSiteInput } from './types'; -import { absoluteUrl, nodeId, plainText, postalAddress } from './values'; - -// The business, for the home page. OnlineStore is the Organization subtype Google recommends for a shop. -export function buildOrganization(input: OrganizationInput): JsonLdNode | null { - const name = plainText(input.name); - const logo = absoluteUrl(input.logo); - if (!name || !logo) return null; - return { - '@type': 'OnlineStore', - '@id': nodeId('/', 'organization'), - url: absoluteUrl(input.url ?? '/'), - name, - alternateName: input.alternateName, - legalName: plainText(input.legalName), - description: plainText(input.description), - logo, - sameAs: input.sameAs?.map(absoluteUrl), - telephone: input.telephone, - email: input.email, - address: input.address && postalAddress(input.address), - contactPoint: input.contactPoints?.map(contactPoint), - iso6523Code: input.iso6523Code, - vatID: input.vatId, - taxID: input.taxId, - foundingDate: input.foundingDate, - hasMerchantReturnPolicy: input.returnPolicy && returnPolicy(input.returnPolicy), - hasShippingService: input.shipping?.map(shippingService), - }; -} - -// The site name Google shows beside each result, for the home page. -export function buildWebSite(input: WebSiteInput): JsonLdNode | null { - const name = plainText(input.name); - if (!name) return null; - return { - '@type': 'WebSite', - '@id': nodeId('/', 'website'), - url: absoluteUrl('/'), - name, - alternateName: input.alternateName, - inLanguage: input.inLanguage, - publisher: { '@id': nodeId('/', 'organization') }, - }; -} - -function contactPoint(input: ContactPointInput): JsonLdNode { - return { - '@type': 'ContactPoint', - contactType: input.contactType, - telephone: input.telephone, - email: input.email, - areaServed: input.areaServed, - availableLanguage: input.availableLanguage, - }; -} -``` - -`breadcrumb.ts` - -```ts -import type { BreadcrumbInput, JsonLdNode } from './types'; -import { absoluteUrl, plainText } from './values'; - -// The trail the page shows. Google needs at least two items. -export function buildBreadcrumbList(items: readonly BreadcrumbInput[]): JsonLdNode | null { - const trail = items - .map((item) => ({ name: plainText(item.name), url: absoluteUrl(item.url) })) - .filter((item) => item.name && item.url); - if (trail.length < 2) return null; - return { - '@type': 'BreadcrumbList', - itemListElement: trail.map((item, index) => ({ - '@type': 'ListItem', - position: index + 1, - name: item.name, - item: item.url, - })), - }; -} -``` - -`store.ts` - -```ts -import type { JsonLdNode, OpeningHoursInput, StoreInput } from './types'; -import { absoluteUrl, nodeId, plainText, postalAddress, schemaUrl } from './values'; - -// A physical branch, on its own page. Never with ratings: Google ignores reviews a business shows about itself. -export function buildStore(input: StoreInput): JsonLdNode | null { - const name = plainText(input.name); - if (!name) return null; - return { - '@type': input.type ?? 'Store', - '@id': nodeId(input.url, 'store'), - url: absoluteUrl(input.url), - name, - address: postalAddress(input.address), - image: input.image?.map(absoluteUrl), - telephone: input.telephone, - geo: input.geo && { '@type': 'GeoCoordinates', latitude: input.geo.latitude, longitude: input.geo.longitude }, - openingHoursSpecification: input.openingHours?.map(openingHours), - priceRange: input.priceRange, - }; -} - -function openingHours(input: OpeningHoursInput): JsonLdNode { - return { - '@type': 'OpeningHoursSpecification', - dayOfWeek: input.days.map(schemaUrl), - opens: input.opens, - closes: input.closes, - }; -} -``` - -## Usage - -`apps//src/env/env.client.ts` declares the site's origin. Like every env value, it's required and has no default ([lib-env.md](lib-env.md#the-apps-env)). The root layout's `metadataBase` uses the same value. - -```ts -// in schema -NEXT_PUBLIC_SITE_URL: v.pipe(v.string(), v.url()), - -// in runtimeEnv -NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, -``` - -`bootstrap.server.ts` - -```ts -import { configureJsonLd } from '@project/libs/json-ld/server'; - -configureJsonLd({ siteUrl: clientEnv.NEXT_PUBLIC_SITE_URL }); -``` - -The libs `package.json` exposes the module as `"./json-ld/server": "./src/json-ld/server.ts"`, and the project's `server.ts` re-exports it by name ([project-structure.md](project-structure.md#exports-and-tree-shaking)). - -### island's `JsonLd` primitive - -`packages/island/src/primitives/json-ld/`: a non-visual primitive with no styles, so no `variants.ts`, and server-only, so `server.ts` and no `index.ts`. island's `package.json` exposes it as `"./primitives/json-ld/server": "./src/primitives/json-ld/server.ts"`, and island's `server.ts` re-exports it. - -`types.ts` - -```ts -import type { JsonLdGraph } from '@project/libs/json-ld/server'; - -export type JsonLdProps = { - data: JsonLdGraph | null; // from buildGraph; null renders nothing -}; -``` - -`JsonLd.tsx` - -```tsx -import { serializeJsonLd } from '@project/libs/json-ld/server'; -import type { JsonLdProps } from './types'; - -export function JsonLd({ data }: JsonLdProps) { - if (!data) return null; - // serializeJsonLd escapes <, > and &, so no value can end the element. - return ` in a name. -- Before a new or changed page type ships: run a rendered page from staging through the Rich Results Test in URL mode, and fix every error and the warnings the data allows. The Rich Results Test doesn't cover site names or `noindex` pages; check the home page's `WebSite` and `OnlineStore` with the Schema Markup Validator (validator.schema.org) and URL Inspection. -- After each release, with the web vitals: Search Console's Merchant listings and Product snippets reports (under Shopping), and its Breadcrumbs, Review snippets, and Unparsable structured data reports. A rise in invalid items means a broken builder or bad data; a drop in valid items means a page stopped rendering its markup. The Manual actions report must stay empty. -- Google documents no merchant listings for Iran, and Merchant Center serves neither Iran nor Persian, so an Iran-facing shop counts on product snippets (rating, price, availability) and treats merchant listings as a bonus. The markup is the same either way. - -## Acceptance checklist - -For building or changing the lib: - -``` -[ ] Each builder returns the expected node for a full input, with enumeration members as https://schema.org/ -[ ] buildProduct returns null without a name, an image, or one of a valid offer, rating, and review; buildProductGroup without a name or a valid variant; buildBreadcrumbList for fewer than two items -[ ] An offer whose price is 0, negative, or NaN is dropped; a list price at or below the price adds no StrikethroughPrice -[ ] A rating with count 0 or a value outside its scale, and a review without an author, with a 100-character author name, or with a rating outside its scale, are dropped -[ ] Paths resolve against siteUrl; absolute URLs keep their origin; javascript:, data:, and unparsable URLs are dropped; non-ASCII paths come out percent-encoded -[ ] configureJsonLd keeps only the origin and throws on an invalid URL; a builder called before it throws the clear error -[ ] buildGraph drops null nodes, undefined, null, NaN, blank strings, empty arrays, and objects left with only @type; it keeps 0 and false; it returns null when no node is left -[ ] serializeJsonLd output has no <, >, &, U+2028, or U+2029 character, and JSON.parse of it equals the graph, also for a name containing "` separators removed and its HTML escapes decoded, so a search for a value the page shows matches. - - ```bash - S='<(?:div hidden |table hidden(?: |><(?:tbody|tr|colgroup) )|svg aria-hidden="true" style="display:none" |math aria-hidden="true" style="display:none" )id="S:' - D='s///g; s/'/\x27/g; s/"/"/g; s/<//g; s/&/&/g' - for t in mobile desktop; do - perl -0pe 's///gs; s/'"$S"'.*//s' $t.html > $t.first-flush.html - perl -0ne 'print $1 if /('"$S"'.*)/s' $t.html | perl -0pe 's///gs' > $t.streamed.html - perl -0ne 'print $1 if /]*>(.*)/s' $t.first-flush.html | perl -pe "$D" > $t.first-flush.txt - perl -pe "$D" $t.streamed.html > $t.streamed.txt - done - ``` - -3. Check the rows. Every `primary` row's text is in `*.first-flush.txt` of both templates, and every `secondary` row's text in `*.first-flush.txt` or `*.streamed.txt`. Search for one value that the page shows, such as `grep -c '' mobile.first-flush.txt desktop.first-flush.txt`. Each file is one line, so each count is 0 or 1. - -4. Head, H1, and JSON-LD. Both templates have the same title, description, canonical, and robots tags, one H1 with the same text, and the same JSON-LD element. The diff proves only that the templates match, and the H1 count proves that each has one. The first offset that the last command prints must be the JSON-LD element, so it is in the first flush. - - ```bash - for t in mobile desktop; do - perl -0ne 'print "$1\n" if /(.*?)<\/head>/s' $t.html | grep -o '[^<]*\|]*>\|]*>\|]*>' > $t.head - perl -0ne 'print "$1\n" while /]*>(.*?)<\/h1>/gs' $t.first-flush.html | sed 's/<[^>]*>//g' >> $t.head - perl -0ne 'print "$1\n" while /