From b85b05861f10a8397c6200670e51fa7ecec752c5 Mon Sep 17 00:00:00 2001 From: Amiram_se Date: Thu, 8 Oct 2026 22:29:56 +0400 Subject: [PATCH] feat: update skill --- .claude/skills/front-end-architect/SKILL.md | 23 +- .../front-end-architect/references/b2c-b2b.md | 35 +- .../references/code-patterns.md | 16 +- .../references/design-patterns.md | 8 +- .../references/error-handling-code.md | 26 +- .../references/error-handling.md | 16 +- .../references/lib-error-handler.md | 39 +- .../references/lib-json-ld.md | 1023 +++++++++++++++++ .../front-end-architect/references/lib-pwa.md | 492 ++++++++ .../references/page-example.md | 15 +- .../references/project-structure.md | 20 +- .../references/rendering-patterns.md | 2 +- .../references/ui-rules.md | 8 +- 13 files changed, 1678 insertions(+), 45 deletions(-) create mode 100644 .claude/skills/front-end-architect/references/lib-json-ld.md create mode 100644 .claude/skills/front-end-architect/references/lib-pwa.md diff --git a/.claude/skills/front-end-architect/SKILL.md b/.claude/skills/front-end-architect/SKILL.md index 6d5f4b1..eb9bc5a 100644 --- a/.claude/skills/front-end-architect/SKILL.md +++ b/.claude/skills/front-end-architect/SKILL.md @@ -1,6 +1,6 @@ --- name: front-end-architect -description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of daily visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and token refresh; error handler; env; cookie; local storage), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner, and keeps each project's architecture and design decision records (ADR, DDR). Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects in these monorepos, when planning a feature, when the user states a lasting project rule or asks to record or change a decision, or when another skill such as a product designer or architect needs front-end input. +description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and refresh; error handler; env; cookie; local storage; PWA service worker; JSON-LD structured data), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner, and keeps each project's decision records (ADR, DDR). Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects, when planning a feature, when the user states a lasting rule or asks to record or change a decision, or when another skill (product designer, architect) needs front-end input. --- # Front-end Architect @@ -23,7 +23,7 @@ How you work: - Server entry: every project except apps has `src/server.ts`. - Critical: a fresh server render per request with no server cache, web vitals, bundle and chunk size, and hydration and navigation speed. -Read the playbook before designing or writing code: [references/b2c-b2b.md](references/b2c-b2b.md). When the work changes what the user sees or what search engines read (a page, template, organism, form, copy, upload, image, font, icon, or metadata), also read [references/ui-rules.md](references/ui-rules.md): UX, SEO, images, fonts, and the icon sprite. +Read the playbook before designing or writing code: [references/b2c-b2b.md](references/b2c-b2b.md). When the work changes what the user sees or what search engines read (a page, template, organism, form, copy, upload, image, font, icon, metadata, or structured data), also read [references/ui-rules.md](references/ui-rules.md): UX, SEO, images, fonts, and the icon sprite. ## 2. Stack @@ -43,6 +43,8 @@ Read the playbook before designing or writing code: [references/b2c-b2b.md](refe | Lint and format | oxlint, prettier | ESLint runs module-boundary rules only | | TS scripts and configs | jiti | Runs `tools/` scripts and TypeScript config files without a build step | | Icons | svgo | Through island's `icon-sprite-plugin`, into `symbol-defs.svg`, which no step hashes; linked with `?v=` | +| Service worker | Native Service Worker and Cache APIs | Only through the pwa lib: one worker per app that stores JS, CSS, fonts, and `symbol-defs.svg`, nothing else. No Workbox or Serwist | +| Structured data | schema.org JSON-LD | Only through the json-ld lib's builders, rendered on the server by island's `JsonLd` primitive. No schema-dts or next-seo | TanStack Query is implied by `configs/react-query.ts`; confirm the repo uses it before adding it. Don't add any dependency outside this stack without stating why and getting approval. @@ -54,13 +56,15 @@ The rules below are enough for work inside existing projects and features. Read - Component placement (its atomic level and the project and folder it belongs in), before you add or move a component: only the "Choosing where a component goes" section of [references/project-structure.md](references/project-structure.md#choosing-where-a-component-goes) - Code patterns, one section at a time: read only the section for the layer you write (island component, tokens, repository, action, form and model, mutation, store, persisted store, env), as its Contents line lists. Copy an existing file of the same kind when the repo has one: [references/code-patterns.md](references/code-patterns.md) -Shared libs have full specs. Read the matching one only when you build or change the lib itself, or when a feature needs lib behavior that "Env, HTTP, cookies, and storage" below doesn't describe. To use a lib from a feature, that section and code-patterns.md are enough: +Shared libs have full specs. Read the matching one only when you build or change the lib itself, or when a feature needs lib behavior that "Env, HTTP, cookies, storage, the service worker, and structured data" below doesn't describe. To use a lib from a feature, that section and code-patterns.md are enough: - HTTP client: [references/lib-http.md](references/lib-http.md) - Error handler: [references/lib-error-handler.md](references/lib-error-handler.md) - Env: [references/lib-env.md](references/lib-env.md) - Cookies: [references/lib-cookie.md](references/lib-cookie.md) - Local storage: [references/lib-local-storage.md](references/lib-local-storage.md) +- PWA and the service worker, also whenever work touches `/sw.js`, the web app manifest, or what the browser keeps between visits: [references/lib-pwa.md](references/lib-pwa.md) +- JSON-LD structured data, also whenever work adds an indexable page type or changes what a page tells search engines about the business, a product, its price, or its policies: [references/lib-json-ld.md](references/lib-json-ld.md) Error handling, patterns, and refactoring have their own references. Read each one only when its trigger applies: @@ -110,7 +114,7 @@ Error handling, patterns, and refactoring have their own references. Read each o - Client side (the parts of a page that load in the browser): repository → model → UI. Every page has a skeleton (`loading.tsx`). Every part that loads on its own has its own `` with a same-size skeleton and its own part boundary (EB-S), so one slow or failing part never blocks the others. - Server side: repository → cache → server components. Pages, `generateMetadata`, and server components read data only through caches. A client component gets server data as props, or through React Query hydration when it must stay live. Details: [references/b2c-b2b.md](references/b2c-b2b.md#data-flow). -**Env, HTTP, cookies, and storage** +**Env, HTTP, cookies, storage, the service worker, and structured data** - Env (`packages/libs/src/env`): only the app's `env/` files read `process.env`, through `createClientEnv` (public) and `createServerEnv` (server only). Other projects read their own values with `getEnv`, filled by the app's bootstrap. Libs never read env; the bootstrap passes their settings through `configure`. - No project hard-codes an env value: a value that changes between environments, such as a service or CDN address, a key, a third-party ID, or a feature flag. Not as a literal, a fallback (`?? 'http://localhost:3000'`), or a schema default. Every env value comes from the `.env` of the app that serves it, and only apps have `.env` files. Values that are the same in every environment stay in `constants/`. @@ -121,6 +125,10 @@ Error handling, patterns, and refactoring have their own references. Read each o - Cookies (`packages/libs/cookie`, the `cookie` instance): only small values the server needs on the request, such as locale and theme. Never tokens: auth cookies are HttpOnly and belong to the server. Browser only; server code reads cookies with `next/headers`. - Local storage (`packages/libs/local-storage`, the `storage` instance): client-only, non-critical data under the app's key prefix, and the storage behind persisted zustand stores. Never tokens or personal data. - `cookie` and `storage` are never read during render, at module top level, or in repositories. +- Service worker (`packages/libs/pwa`): each app serves one worker at `/sw.js`, written by the lib's `writeServiceWorker` and registered from the `AppShell` when the app's env turns it on. It stores only JS and CSS from `/_next/static/`, fonts from `/fonts/`, and `/icons/symbol-defs.svg`, by exact URL, stale-while-revalidate unless the developer explicitly chooses cache first. Pages, RSC payloads, API data, images, and every other SVG reach the network untouched. + - Storing any other kind of URL needs a recorded decision. `/sw.js` is never renamed or removed; turning the env flag off unregisters the worker for every visitor. +- Structured data (`packages/libs/json-ld`, server only): every indexable page renders one schema.org JSON-LD graph with island's `JsonLd`, in its page entry, from the data its first paint already awaits. The home page describes the business (`OnlineStore`) and the website from the app's `configs/seo.ts`; other page types get theirs from a builder in the platform's `app/json-ld/`, such as the product with its offer, rating, and breadcrumb. + - The graph says only what the page shows, the same for every visitor: never a member or personal price, and no rating on the business itself. `noindex` pages and not-found, no-access, and error states render none. **Design system (island)** @@ -135,9 +143,10 @@ Error handling, patterns, and refactoring have their own references. Read each o - Separate concerns: components render, models orchestrate, actions run operations, repositories talk to the network through their feature's HTTP client, and caches share server reads within a request. No `fetch` outside the HTTP lib. - Keep 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. +- 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 ([references/b2c-b2b.md](references/b2c-b2b.md#deploys-and-version-skew)). - Keep the UI stable: colocate state, split large contexts, never let an update unmount and remount a visible subtree, and never use random values or array indexes as keys for dynamic lists. - Model multi-step flows (wizards, imports, bulk actions) as explicit states, such as `idle → validating → uploading → processing → done | failed`, never as a set of booleans. -- Handle errors with one model ([references/error-handling.md](references/error-handling.md)): EB-W at the app root only, a page-size EB-S inside the shell for every page, and a part-size EB-S around every part that loads on its own, so one broken part never takes down the page. A failed read shows in its boundary or as an empty state (404 and 403) and never toasts. A failed action shows an error toast with its hint or a reference ID and the retry its cause allows. `ABORTED` and 401 stay silent. +- Handle errors with one model ([references/error-handling.md](references/error-handling.md)): EB-W at the app root only, a page-size EB-S inside the shell for every page, and a part-size EB-S around every part that loads on its own, so one broken part never takes down the page. A failed read shows in its boundary or as an empty state (404 and 403) and never toasts. A failed action shows an error toast with its hint or a 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. - Every text comes from i18next and is a simple, complete description of its purpose ("Save changes to this category", not "Save"). Support RTL and LTR: set `lang` and `dir` from the locale, and use logical utilities (`ms-*`, `pe-*`, `start-*`) instead of left and right. - Meet WCAG 2.1 AA: 4.5:1 text contrast, visible focus rings, full keyboard operation, and an `aria-label` on every icon-only button. @@ -196,6 +205,8 @@ Structure [ ] Each new or moved part went through rendering-patterns.md's "Choosing where a part loads"; every deferred part and its trigger is written in the PR [ ] 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 JS, CSS, fonts, and symbol-defs.svg, stale-while-revalidate unless the developer explicitly chose cache first; /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, from its first-paint data; it says only what the page shows, the same for every visitor; 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 @@ -221,4 +232,4 @@ Every review comment names the rule, shows the problem, and proposes the fix. Fo Name a code smell and its technique, with the target layer or file, as [references/refactoring.md](references/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 [references/design-patterns.md](references/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; 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 page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale. +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 page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale. diff --git a/.claude/skills/front-end-architect/references/b2c-b2b.md b/.claude/skills/front-end-architect/references/b2c-b2b.md index a04c652..05d9b22 100644 --- a/.claude/skills/front-end-architect/references/b2c-b2b.md +++ b/.claude/skills/front-end-architect/references/b2c-b2b.md @@ -2,7 +2,7 @@ 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. -Contents: Targets · No server cache · Rendering · Server and client entries · Data flow · Errors · State and auth · Bundle and code splitting · Hydration and navigation · Responsiveness and monitoring · Example: caches, page, and parts · Definition of Done +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 · Definition of Done ## Targets @@ -26,8 +26,16 @@ The Next.js server renders a fresh page for every request and keeps nothing betw - 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, like the TanStack Query cache and the router cache. +- 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 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 @@ -39,11 +47,12 @@ The Next.js server renders a fresh page for every request and keeps nothing betw - Pages are thin entrypoints. The page resolves the device on the server and renders the mobile or the desktop template. Only that view's client code ships, the markup matches on hydration, and nothing shifts. Never choose between layouts with viewport checks in components. - Stream: add `loading.tsx` per route group and `` with same-size skeletons around slow parts, each inside its own `PartBoundary`. One slow or failing backend call must never block the whole page. Record each route's streamed and auth-dependent parts in the plan. - 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, outside every ``, from the data its first paint already awaits, so structured data is in the initial HTML and costs no extra request ([lib-json-ld.md](lib-json-ld.md#rendering)). ## 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, 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`. +- `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. @@ -115,10 +124,23 @@ The model, the boundaries, and their code are in [error-handling.md](error-handl - Navigate with `next/link` so routes prefetch. Keep the header and footer in layouts, so navigation re-renders only the page segment. - 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), 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. +- 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 @@ -129,6 +151,7 @@ In [page-example.md](page-example.md). Read it when you add a new page, or a par ``` [ ] 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 } } [ ] 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 @@ -144,5 +167,7 @@ In [page-example.md](page-example.md). Read it when you add a new page, or a par [ ] 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, hreflang, and structured data where relevant +[ ] Metadata, canonical URL, and hreflang; every indexable page's JSON-LD follows lib-json-ld.md and passes the Rich Results Test +[ ] 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 ``` diff --git a/.claude/skills/front-end-architect/references/code-patterns.md b/.claude/skills/front-end-architect/references/code-patterns.md index ec8d835..0672d9c 100644 --- a/.claude/skills/front-end-architect/references/code-patterns.md +++ b/.claude/skills/front-end-architect/references/code-patterns.md @@ -155,6 +155,18 @@ This is an excerpt. The real file defines every semantic token the components us @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`. @@ -393,7 +405,9 @@ export function showActionError(error: unknown, { t, failedMessage, retry, reloa ? { label: t('errors:action.try-again'), onClick: retry } : errorClass.retry === 'reload' && reload ? { label: t('errors:action.reload'), onClick: reload } - : undefined; + : errorClass.retry === 'reload-page' + ? { label: t('errors:action.reload-page'), onClick: () => window.location.reload() } + : undefined; toast.error(failedMessage, { id: `action-error:${failedMessage}`, diff --git a/.claude/skills/front-end-architect/references/design-patterns.md b/.claude/skills/front-end-architect/references/design-patterns.md index e841e41..321106d 100644 --- a/.claude/skills/front-end-architect/references/design-patterns.md +++ b/.claude/skills/front-end-architect/references/design-patterns.md @@ -34,9 +34,9 @@ Reuse these before you add anything. | 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 | At a boundary whose shape you don't own. Translate once, at the edge, so no `*Dto`, vendor type, or cookie string syntax crosses it. Don't adapt two of your own modules to each other; change one of them | +| 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 | A cache dedupes calls within one request and never outlives it. `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 | +| 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 | @@ -367,7 +367,7 @@ 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`, 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. +- **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. @@ -383,7 +383,7 @@ Keep these out of designs, and flag each one in review with its alternative. A m - **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, Redux, or a context used as a store. Use the event emitter, the query cache (or `cache()` within one server request), and zustand. +- **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 index bfe2304..ebd4a0e 100644 --- a/.claude/skills/front-end-architect/references/error-handling-code.md +++ b/.claude/skills/front-end-architect/references/error-handling-code.md @@ -39,7 +39,7 @@ export class ErrorBoundary extends Component(null); - const { read, cause } = classifyError(error); + 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]); + }, [error, size, name, retry]); if (read === 'silent') return null; if (read !== 'boundary') return ; @@ -86,6 +89,23 @@ export function ErrorFallback({ error, size, name, onRetry }: ErrorFallbackProps } ``` +`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`. diff --git a/.claude/skills/front-end-architect/references/error-handling.md b/.claude/skills/front-end-architect/references/error-handling.md index d3b49f0..5699574 100644 --- a/.claude/skills/front-end-architect/references/error-handling.md +++ b/.claude/skills/front-end-architect/references/error-handling.md @@ -10,7 +10,8 @@ Contents: The model · What each failure shows · Boundaries · Reads · Actions 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 + ├─> 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 ─┐ @@ -44,6 +45,7 @@ Contents: The model · What each failure shows · Boundaries · Reads · Actions | 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. @@ -61,7 +63,7 @@ Every boundary renders the same `ErrorFallback`, which decides what the user see 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 fallback with Reload page. Both show the reference ID when there is one. +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: @@ -71,7 +73,8 @@ Rules: - 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)). +- `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 @@ -88,7 +91,7 @@ Rules: - `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`, and none for `wait`, `fix`, and `none`; + - 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. @@ -110,7 +113,7 @@ Server reads classify on the server, because a Server Component error reaches th - 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)). - `not-found` calls `notFound()`, which renders the group's `not-found.tsx`. When the page has already started streaming (it has a `loading.tsx`), the status stays 200 and Next.js adds a `noindex` robots tag, which search engines treat as not found. -- `no-access` renders the page-size `StatusEmptyState`, and `generateMetadata` returns `robots: { index: false }` for it. `forbidden()` and `unauthorized()` are experimental and not used ([rendering-patterns.md](rendering-patterns.md#rendering-patterns)). +- `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. @@ -126,7 +129,7 @@ Server reads classify on the server, because a Server Component error reaches th ## Copy, accessibility, and i18n - Every fallback, empty state, and toast says what happened and what the user can do, following the copy rules in [b2c-b2b.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, the `not-found` and `no-access` copy, and the button labels. +- 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). @@ -145,6 +148,7 @@ The boundaries, `ErrorFallback`, `readOnServer`, and the query client's error se [ ] 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 diff --git a/.claude/skills/front-end-architect/references/lib-error-handler.md b/.claude/skills/front-end-architect/references/lib-error-handler.md index 2b9f50d..fa7ecd8 100644 --- a/.claude/skills/front-end-architect/references/lib-error-handler.md +++ b/.claude/skills/front-end-architect/references/lib-error-handler.md @@ -12,7 +12,7 @@ Contents: Structure · Types · API · Classification · Messages and reference 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 +├── constants.ts # NOT_FOUND_STATUSES, LIB_MESSAGE_PREFIX, RETRY_AFTER_HINT_KEY, OUTDATED_MESSAGE_KEY, CHUNK_ERROR_PATTERN └── index.ts ``` @@ -22,10 +22,10 @@ packages/libs/src/error-handler/ ## Types ```ts -type ErrorCause = 'network' | 'logic'; // network: the API or the connection failed, retry helps; logic: a bug, retry rarely helps +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' | 'fix' | 'none'; +type RetryKind = 'again' | 'wait' | 'reload' | 'reload-page' | 'fix' | 'none'; interface ErrorClass { cause: ErrorCause; @@ -67,7 +67,7 @@ interface ErrorDescription { ## 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 server error that reached the browser with only its `digest`. +- `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. @@ -87,16 +87,18 @@ The first matching row wins. | 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. -- 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; `fix` offers none, because the user must change the input; `none` offers none. +- 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. +- `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. @@ -108,11 +110,17 @@ The first matching row wins. ## Implementation -`error-handler.ts`, the parts that decide. `constants.ts` holds `NOT_FOUND_STATUSES: readonly number[] = [404, 410]`, `LIB_MESSAGE_PREFIX = 'errors:'`, and `RETRY_AFTER_HINT_KEY = 'errors:http.retry-after'`. +`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 { LIB_MESSAGE_PREFIX, NOT_FOUND_STATUSES, RETRY_AFTER_HINT_KEY } from './constants'; +import { + CHUNK_ERROR_PATTERN, + LIB_MESSAGE_PREFIX, + NOT_FOUND_STATUSES, + OUTDATED_MESSAGE_KEY, + RETRY_AFTER_HINT_KEY, +} from './constants'; import type { ErrorClass, ErrorContext, @@ -131,6 +139,7 @@ export function configureErrorHandler(next: ErrorHandlerConfig): void { 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 }; @@ -141,8 +150,15 @@ function getDigest(error: unknown): string | 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)) return getDigest(error) ? apiError('boundary', 'again') : LOGIC; + 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'); @@ -156,7 +172,9 @@ export function classifyError(error: unknown): ErrorClass { } export function describeError(error: unknown, t: TranslateFn): ErrorDescription { - if (!isHttpError(error)) return { referenceId: getDigest(error) }; + 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'; @@ -230,6 +248,7 @@ 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 diff --git a/.claude/skills/front-end-architect/references/lib-json-ld.md b/.claude/skills/front-end-architect/references/lib-json-ld.md new file mode 100644 index 0000000..2b79718 --- /dev/null +++ b/.claude/skills/front-end-architect/references/lib-json-ld.md @@ -0,0 +1,1023 @@ +# 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` | + +- 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. 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 and outside every ``, 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. An element inside `` arrives at the end of the stream, in a hidden `
` that client JavaScript moves into place. Never in a layout, where every page under it would repeat it; in a template, which the page has in two versions; in a streamed part; 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 "