Compare commits

..

No commits in common. "5e35fbd6f29fb531eff5b2e96e89f3189da1397f" and "a4f5a941379cd89857bca4edbdbd04e175fd8dc5" have entirely different histories.

310 changed files with 0 additions and 20250 deletions

View File

@ -1,31 +0,0 @@
{
"extraKnownMarketplaces": {
"nx-claude-plugins": {
"source": {
"source": "github",
"repo": "nrwl/nx-ai-agents-config"
}
}
},
"enabledPlugins": {
"nx@nx-claude-plugins": true
},
"sandbox": {
"filesystem": {
"allowRead": [
"/tmp/.nx",
"~/.nx"
],
"allowWrite": [
"/tmp/.nx",
"~/.nx"
]
},
"network": {
"allowUnixSockets": [
"/tmp/.nx",
"~/.nx"
]
}
}
}

View File

@ -1,207 +0,0 @@
---
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. Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects in these monorepos, when planning a feature, or when another skill such as a product designer or architect needs front-end input.
---
# Front-end Architect
Act as a principal front-end architect for Nx monorepos that ship B2C/B2B websites. You design, scaffold, implement, and review front-end code so it stays fast, maintainable, and consistent across projects.
How you work:
- Explain *why*, not only *what*. Present designs and reviews as checklists.
- When a requirement is ambiguous, state your assumption and continue. Ask only when a wrong guess would be expensive to undo.
- When a request conflicts with a rule here, follow the rule and explain the trade-off. When something isn't covered, reason from these principles and say so.
- Prefer boring, proven technology, fewer re-renders, and the user's time.
## 1. The project
- Who uses it: the public, 1–20 million visitors a day (Amazon, eBay, Digikala).
- App: Next.js App Router, routes in `apps/<app>/src/app/`.
- Business logic: `platforms/<app>/`; the app stays thin.
- 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, or metadata), also read [references/ui-rules.md](references/ui-rules.md): UX, SEO, images, and fonts.
## 2. Stack
| Concern | Tool | Rule |
|---|---|---|
| Monorepo | Nx | Scaffold with generators (local ones in `tools/` when the repo has them) so every component, feature, and repository has the same shape |
| App | Next.js App Router | Server Components by default |
| Styling | Tailwind CSS v4 | Tokens live in island `styles/theme.css`; no raw colors or sizes where a token exists |
| Variants | class-variance-authority, clsx, tailwind-merge | cva in each component's `variants.ts`; merge classes with island's `cn` tool |
| Validation | valibot | Forms, env, and untrusted input. Not Zod |
| Forms | react-hook-form + @hookform/resolvers | `valibotResolver` with schemas from `shared/validations/` |
| Client state | zustand + immer | One store per feature or domain; components subscribe through selectors |
| Server state | TanStack Query | Configured in `configs/react-query.ts`; query keys live in the repository's `constants.ts`; queries don't retry on their own, because the HTTP lib does, and a failed first load throws to its error boundary, where the user retries |
| Toasts | sonner | After every completed or failed action; never for reads |
| i18n | i18next + react-i18next | No hard-coded UI text |
| Env | @t3-oss/env-core + valibot | The app validates its variables with `createClientEnv` and `createServerEnv` from `packages/libs/env`; other projects read only their own `env/` |
| 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` |
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.
## 3. Architecture rules
The rules below are enough for work inside existing projects and features. Read the rest only when its trigger applies:
- Project structure (full trees, Nx tags, the env flow, export mechanics), only when you add an Nx project, a feature, or a top-level folder, or change tags or exports: [references/project-structure.md](references/project-structure.md)
- 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:
- 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)
Error handling, patterns, and refactoring have their own references. Read each one only when its trigger applies:
- Error handling (error boundaries EB-W and EB-S, API errors by status for reads and actions, empty states, reporting), before you add a page, a part, a query, an action, or a form, and whenever code catches or shows an error: [references/error-handling.md](references/error-handling.md)
- Design patterns (GoF, JavaScript, and React: which one, where it lives, its shape, and what isn't used), before you add a pattern or a shared abstraction such as a factory, a `Record` map, a state machine, an adapter, a context, or a generic hook: [references/design-patterns.md](references/design-patterns.md)
- Rendering and loading patterns, before you add or move a part of a page or change when its code loads: [references/rendering-patterns.md](references/rendering-patterns.md)
- Code smells and refactoring (safe steps, smells mapped to layers, smells that are intended), before you refactor and when you review code, together with design-patterns.md's "Not used here" list: [references/refactoring.md](references/refactoring.md)
**Naming**
- Files and directories are kebab-case. Component files are PascalCase (`Button.tsx`, `AppShell.tsx`, `ProductCard.tsx`). Hooks are `use-hook-name.ts`.
- Entry files with fixed names keep them: Next.js `page.tsx`, `layout.tsx`, `loading.tsx`, `error.tsx`, and `not-found.tsx`. Route groups are kebab-case too: `(auth)`.
**Projects and exports**
- Every project keeps its code under `src/`.
- Every module has an `index.ts` that re-exports its public API by name: `export { Button } from './Button';` and `export type { ButtonProps } from './types';`. Never `export *`.
- Exports are tree-shakeable. Each module is importable from the project root and from its own subpath: `import { Button } from '@project/island'` or `import { Button } from '@project/island/atoms/button'`. Code always imports by subpath.
- Every project except apps has `src/server.ts` beside `src/index.ts`. It starts with `import 'server-only';`, is exposed as the `/server` subpath, and holds server-only capabilities. `index.ts` never imports from `server.ts`.
- A module with server-only capabilities has its own `server.ts` beside its `index.ts` (the env lib), and a server-only module has only `server.ts` (a feature's `caches/`). Both start with `import 'server-only';`, and the project's `server.ts` re-exports them by name.
**Dependency direction**
- apps → platforms → packages. Nothing imports upward, and one product's app or platform never imports another's. ESLint enforces this through Nx tags.
- island follows atomic design: atoms → molecules → organisms → templates, and a level never imports a level above it. `primitives/` are non-visual structural pieces (for example a portal) outside that ladder. The `components/` and `hooks/` inside an organism are private to it, except a compound component's named parts, which its `index.ts` re-exports.
**Features are DDD** (`features/<feature>/`)
- `entities/`: back-end data model types, enums, and unions. Types only.
- `http.ts`: the feature's HTTP client, `export const catalogHttp = http.extend({ ... })`. Only the feature's repositories import it, and its `index.ts` doesn't export it. It may set the base URL, headers, timeout, retry, and feature-only interceptors, never refresh or cookie settings. A feature with nothing special still has `http.extend({})`.
- `repositories/`: make the request through the feature's HTTP client and return the data. They never use client-side dependencies (hooks, stores, `window`, `cookie`, `storage`), so they also run on the server. Each endpoint has four types: `*Args` (caller input), `*Dto` (request body), `*ResponseDto` (raw response), and `*Payload` (the shape apps and stores use). `mappers.ts` turns `*Args` into `*Dto` and `*ResponseDto` into `*Payload`. No `*Dto` leaves the repository.
- `caches/` (server-only): React `cache()` wrappers around repository calls, so each distinct call runs once per request however many server components need it. Its entry is `server.ts`, not `index.ts`.
- `actions/`: one operation from start to end, for any operation with side effects beyond the request. The login action sends the request, updates the store and local storage, makes follow-up calls, emits `auth.login`, and returns `'ok'`. Every action emits its event when it succeeds, unless the caller passes `{ emit: false }`, so other features and integrations react without the action knowing them.
- `models/`: page and part logic as hooks. A page has one page model (`models/login/use-login-page.ts`), or a page model plus one model per part when its parts load or change on their own (`use-shipment-page.ts`, `use-shipment-address-part.ts`, `use-shipment-bill-part.ts`). Pages, templates, and parts get their data and handlers from their model and stay presentational.
- `stores/` sits beside `features/`: zustand + immer, one store per feature or domain, holding `*Payload` data.
- `shared/` holds `constants/`, `utils/`, and `validations/` (valibot: `base-validations.ts` plus one `<feature>-validations.ts` per feature).
**Data flow**
- 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 `<Suspense>` 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 (`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`.
- HTTP (`packages/libs/http`): one root `http` client, configured in the app's bootstrap, and one client per feature made with `http.extend(...)`, so every feature shares one token refresh, the interceptors, and error normalization.
- Auth is cookie-based. On a 401, one refresh runs for the whole app, the waiting requests replay once, and a failed refresh triggers logout. The server side never refreshes.
- Retry covers only idempotent requests, with backoff. Every request is abortable, and aborted requests are silent. Uploads report progress.
- Every failure is an `HttpError`: `{ code, message, status, fieldErrors, hint, requestId, retryAfter }`. The error handler lib (`packages/libs/error-handler`) decides what each one shows and reports it.
- 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.
**Design system (island)**
- Build UI from island. Never fork or restyle an island component inside a feature; add a variant to island and use it.
- Components use semantic tokens (`--color-surface-card`, `--color-text-muted`, `--color-action-primary`) layered over primitive tokens in `theme.css`. That layering is what makes theming and dark mode possible without a rewrite.
- Every component defines its variants, sizes, and states (default, hover, focus-visible, active, disabled, loading, error, selected) and its accessibility behavior. Enabled interactive elements show `cursor: pointer` and disabled ones `cursor: not-allowed`, built into the component so no page can forget them.
- Complex organisms are compound components (`<DataTable>`, `<DataTable.Toolbar>`, `<DataTable.Pagination>`) that share state through context, with slots or render props for the parts that vary per entity, such as cells, empty states, and toolbars.
**Cross-cutting**
- 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.
- 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.
- 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.
## 4. Workflow
Follow these steps for any design or implementation task. Write a short plan in the PR description: affected projects and paths, data types, each route's streamed and deferred parts, and each new non-obvious pattern.
1. **Clarify the job.** Who uses it, how often, and what they finish with it. State assumptions.
2. **Read the playbook** ([b2c-b2b.md](references/b2c-b2b.md)), plus [ui-rules.md](references/ui-rules.md) for UI work.
3. **Map the data.** Entities, repository types (`*Args`, `*Dto`, `*ResponseDto`, `*Payload`), caches and how each client part gets its server data, page and part models, actions and their events, query keys, and how the query cache is updated after each mutation.
4. **Place the code.** List the Nx projects and folders that change. Reuse what exists before creating anything. For each part you add or move, decide where it renders and when its code loads ([rendering-patterns.md](references/rendering-patterns.md)), and add a pattern only for a signal you can name ([design-patterns.md](references/design-patterns.md)). When existing code resists the change, refactor it first, in its own commit ([refactoring.md](references/refactoring.md)).
5. **Design every state first:** loading, empty (no data, no results, not found, no access), error, in progress, then populated.
6. **Build in layer order,** with island components, adding variants to island when needed:
1. Setup: Nx projects, tags, subpath exports, and new env variables.
2. Foundation: entities, repositories with mappers and query keys, caches, and island components or variants.
3. Each user story: actions, then models, then templates and organisms, then the route entry.
For a bug, fix the fault in the layer that owns it (repository, mapper, action, model, or component) instead of patching the symptom in the UI.
7. **Wire feedback:** a toast for every completed action; for a failed action, field errors, a form alert, and an error toast with the hint or reference ID and its retry; for a failed read, its boundary or empty state ([error-handling.md](references/error-handling.md)); and progress for long operations.
8. **Check performance:** bundle, hydration, web vitals, re-renders, and flicker.
9. **Verify and deliver.** Run lint, type-check, and tests for the affected projects through Nx (`nx affected -t <targets>`; check target names with `nx show project <name>`). Finish with the Definition of Done and a short note on trade-offs, including each new non-obvious pattern with its signal and the simpler option you rejected, and the smells you noticed but left as debt.
## 5. Collaborating with other skills
Before deciding alone on something outside front-end architecture, check the available skills. When one matches, read its `SKILL.md` and let it lead in its area:
| Area | Skills like | They own | You own |
|---|---|---|---|
| Product and UX design | product-designer, ux, ui-design | User flows, layouts, visual hierarchy, token values | Mapping the design onto island, states, feasibility, performance cost |
| System or back-end architecture | architect, solution-architect, backend | Service boundaries, API contracts, auth flows | DTO mapping, and the pagination, filter, and error contracts the UI needs |
| Figma | figma-design-to-code and other figma-* skills | Reading the design | Adapting it to island components and tokens |
| Nx | nx-workspace, nx-generate, nx-run-tasks | Generators, project graph, running targets | Which project and tags new code gets |
| Review, security, QA | Review, security, and testing skills | Their checks | The rules in this skill |
When you hand off, send a short brief: the context, the decision you need, and the constraints from this skill (stack, structure, budgets). When another skill asks for front-end input, reply with a front-end brief: affected projects and folders, data flow (repository → action → model → UI), required states, performance concerns, and open questions.
If no matching skill is available, make the call yourself and label it as an assumption.
## 6. Definition of Done
Copy this into the PR description, add the list from the playbook, and tick every item.
```
Structure
[ ] Code is in the right project and folder, under src/, named per the naming rules
[ ] Public API is exported by name from index.ts (and server.ts); no export *
[ ] ESLint boundaries pass; no upward or cross-product imports
[ ] Repositories have no client-side dependencies; UI and stores use *Payload types only
[ ] Repositories send requests only through their feature's http.ts client; no fetch outside the HTTP lib
[ ] Env is read only in the app's env/ files and through each project's getEnv(); no process.env elsewhere
[ ] Every action emits its event when it succeeds, unless called with { emit: false }
[ ] No tokens or personal data in cookies or local storage; neither is read during render
[ ] Every new pattern answers a named signal and sits where design-patterns.md puts it; none is on its "Not used here" list
[ ] Each new or moved part went through rendering-patterns.md's "Choosing where a part loads"; every deferred part and its trigger is written in the PR
[ ] Refactors are in their own commits, and the PR states how unchanged behavior was checked; smells noticed but not fixed are listed as debt
States and feedback
[ ] Loading, empty, error, and in-progress states exist
[ ] Every page has a skeleton; every part that loads on its own has its own Suspense skeleton and part boundary (EB-S); the app has EB-W
[ ] Every completed action shows a toast, and every failed one the action-error toast with its hint or reference ID; reads never toast
[ ] Errors follow error-handling.md: 404 and 403 reads show their empty state, ABORTED and 401 stay silent, retries follow the cause, 5xx and logic errors are reported once
[ ] Query cache is updated or invalidated after every mutation; no stale data is visible
[ ] Refetches never swap content for a spinner; keys are stable
Quality
[ ] All UI text comes from i18next; RTL and LTR both render correctly
[ ] AA contrast, focus-visible rings, keyboard operation
[ ] oxlint, prettier, ESLint boundaries, and type-check pass for affected projects
```
## 7. Review stance
Every review comment names the rule, shows the problem, and proposes the fix. For example:
> **Repositories stay server-safe:** `products.ts` reads the page size with `storage.getItem`, which breaks server rendering. Pass `pageSize` in `ListProductsArgs` and read the stored value in an effect of the `use-products-page` model.
Name a code smell and its technique, with the target layer or file, as [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: 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; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; a page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale.

View File

@ -1,147 +0,0 @@
# B2C/B2B playbook
Public websites with 1–20 million visitors a day, like Amazon, eBay, and Digikala. Every kilobyte and millisecond is multiplied by millions of sessions. Most visitors arrive from search on mid-range phones, and many are logged out. Performance and SEO decide the architecture, the server renders every page fresh and caches nothing, and the codebase must stay maintainable as teams and features grow.
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
## Targets
These are defaults; tighten them per product in the plan.
| Metric | Target |
|---|---|
| LCP, p75 of mobile field data | ≤ 2.5 s |
| INP, p75 | ≤ 200 ms |
| CLS, p75 | ≤ 0.1 |
| TTFB, p75 | ≤ 0.8 s |
| First-load JS per route, gzipped, framework included | ≤ 200 KB |
| Route-specific client JS, gzipped | ≤ 100 KB |
Record the first-load JS of key routes from `next build` in the plan. Any increase on a key route needs a stated reason in the PR.
## No server cache
The Next.js server renders a fresh page for every request and keeps nothing between requests: no prerendered or revalidated pages, and no cached data.
- Keep Cache Components (`cacheComponents` in `next.config.ts`) off, because it prerenders a static shell at build time. Every root layout declares `export const dynamic = 'force-dynamic'`, which renders each route at request time and sends every `fetch` with `no-store`. Metadata routes (`sitemap.ts`, `robots.ts`, generated icons and Open Graph images) are cached by default and no layout covers them, so each one declares it too.
- Never use `'use cache'`, `unstable_cache`, `fetch` caching (`cache: 'force-cache'`, `next: { revalidate, tags }`), the `revalidate` segment config, `dynamic = 'force-static'` or `'error'`, or `generateStaticParams`. The HTTP lib sends every server request with `cache: 'no-store'` (see [lib-http.md](lib-http.md#server-side)).
- Never keep back-end data or rendered output in module scope, such as a `Map`, an LRU, or a memoized promise. Settings made once at startup, like env and the root `http` client, are fine.
- Caches that end with the request are fine: React `cache()` (the features' `caches/`) and the per-request `QueryClient`. So are caches in the browser, like the TanStack Query cache and the router cache.
- Nothing needs revalidating. After a mutation that changes server-rendered content, call `router.refresh()` and the server renders the page again.
- 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
- Server Components by default. Put `'use client'` only on interactive leaves, never on a layout or page.
- Templates stay Server Components. Interactive parts are small client components, each driven by its part model (`use-<page>-<part>-part.ts`). Don't turn a whole template into a client component to use a page model when only part of it is interactive.
- Keep props passed to client components small and serializable; they are serialized into the page's RSC payload.
- Pages are thin entrypoints. The page resolves the device on the server and renders the mobile or the desktop template. 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 `<Suspense>` 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 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).
## 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/<name>/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`.
- 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/<page>/` folder (`load-<page>-page.ts`) and is exported only through `server.ts`.
- `bootstrap.server.ts` must run before server rendering: import it at the top of every root layout. `bootstrap.client.ts` must run before client components render, both during SSR and in the browser: import it first in the app's root client component, the one that renders the platform's `AppShell`. Client components render in a separate module graph, so values set by server-only code are invisible to them. Make both bootstraps idempotent.
- Never call `getEnv`, a repository, or a cache at module top level. Do it inside functions, so bootstrap has always run first.
- Bootstrap code for both sides, env included: [lib-env.md](lib-env.md#usage).
## Data flow
A request becomes a page in this order. The server steps run per request and keep nothing afterwards.
1. `proxy.ts` refreshes an expired session before rendering.
2. Every root layout imports `bootstrap.server.ts` first.
3. The page resolves the device, awaits only what the first paint needs through caches or a server page loader, and renders the mobile or the desktop template.
4. Server components that need more data read it through caches. A slow part is an async server component inside `<Suspense>` with a same-size skeleton, so the page streams around it.
5. Client components get server data as props or through query hydration (below). In the browser their models take over: queries through repositories, mutations through actions. After a mutation that changes server-rendered content, `router.refresh()` renders the page again.
**Caches** (`features/<feature>/caches/`, server-only)
- Each cache is React's `cache()` around one repository call: `export const getProduct = cache((id: string) => productsRepository.get({ id }))`. React keeps the result for the current request only, so it's an allowed server cache (see No server cache).
- On the server, pages, loaders, `generateMetadata`, and server components read data only through caches, never through a repository directly. That's why ten components that need the same product send one request.
- Cache arguments are primitives, such as ids and page numbers. React compares arguments by identity, so `getProducts({ page })` would miss every time.
- Define caches at module level. A `cache()` created inside a component is new on every render.
- The module's entry is `server.ts`, with no `index.ts`, and the platform's `server.ts` re-exports it.
**Handing server data to client components**
- Props, for data the client part only shows or starts from: pass the `*Payload`, small and serializable. To stream it, pass the un-awaited promise and read it with `use()` inside `<Suspense>`.
- Query hydration, for data the client part keeps live (refetches, pagination, filters, or mutations that update it): prefetch into a `QueryClient` from `getQueryClient()` in `configs/react-query.ts`, with the cache as the `queryFn`, and render the part inside `<HydrationBoundary state={dehydrate(queryClient)}>`. The part's model queries the same key and starts with the data.
- An awaited prefetch puts the data in the HTML. Wrap the server component in `<Suspense>` so the await streams.
- An un-awaited prefetch doesn't block the part: the pending query is dehydrated and streams in, and the model reads it with `useSuspenseQuery`. Page or filter changes then go through `startTransition`, so the part keeps its content instead of falling back to the skeleton.
- A server prefetch calls the cache, never the repository, so a server component that awaits the same data in the same request shares the request.
**Data loaded only in the browser**
- Render on the server what search engines and the first paint need. Load in the browser only what's personal, below the fold, or shown on interaction, through a part model inside `<Suspense>` with a skeleton.
- A browser-only part uses `useQuery` and shows its skeleton while pending, or is loaded with `next/dynamic` from a client component: with `ssr: false` and a same-size `loading` skeleton when it renders at once, and without `ssr: false` when `LoadOnVisible` or an interaction already delays it ([rendering-patterns.md](rendering-patterns.md)). `useSuspenseQuery` is only for queries the server prefetched: any other query would run during SSR, where requests carry none of the user's cookies.
## Errors
The model, the boundaries, and their code are in [error-handling.md](error-handling.md). What is special here:
- Server reads classify on the server, because a Server Component error reaches the browser with only its digest. Pages and server parts read through `readOnServer`: the page calls `notFound()` for 404 and 410, renders the `no-access` empty state for 403 with `robots: { index: false }`, and redirects a 401 to login; a part renders its empty state for 404 and 403. Everything else is rethrown to a boundary.
- Boundaries: `app/global-error.tsx` is EB-W; every route group has `error.tsx` (page EB-S) and, when it calls `notFound()`, `not-found.tsx`; each part has a `PartBoundary` built with `catchError`, which lets `notFound()` and `redirect()` through. Error pages render `noindex`.
- A part that must show an empty state awaits its read on the server; an un-awaited prefetch fits only reads that can't answer 404 or 403.
- `instrumentation.ts` configures the error handler for the server and reports what no server code caught; `bootstrap.client.ts` configures it for the browser.
## State and auth
- `configs/react-query.ts`: `getQueryClient()` returns a new `QueryClient` on every server call and one shared instance in the browser. `staleTime` is above zero (60 s) so hydrated data isn't refetched on mount, queries don't retry (the HTTP lib does), a failed first load throws to its boundary while a failed refetch keeps the data, and pending queries are dehydrated so they can stream.
- zustand stores hold client state only. Never write to a store during server render: on the server a module-level store is shared by every request, so one user's data would leak to another. Pass server data through props or the query cache. If a store must start from server data, create it per request with `createStore` inside a provider.
- Server-side requests forward the incoming request's cookies. Configure the HTTP lib once in `bootstrap.server.ts` with `configureServerHttp`: the server `baseUrl` from the app's server env, and a cookie provider that calls `cookies()` from `next/headers` on each request. That configures the root client, so every feature client forwards cookies too. Never keep a user's cookies in module state.
- On the server, the HTTP lib never refreshes, never calls `abortAll`, and retries at most once with a shorter timeout, so a slow back end doesn't hold up rendering (see [lib-http.md](lib-http.md#server-side)).
- Server Components can't set cookies. Refresh an expired session in `proxy.ts` before rendering, or in a Route Handler or Server Function, never during render.
- The `cookie` and `storage` libs are browser-only. Never read them during render: client components also render on the server, and the value would differ between server and browser. A value the page needs while rendering (theme, locale) is read on the server with `cookies()` and passed down as a prop.
- Persisted zustand stores set `skipHydration: true` and rehydrate in an effect of the platform's `AppShell`, so the first browser render matches the server's (code in code-patterns.md, Persisted store).
## Bundle and code splitting
- Import island, libs, and every other package by subpath (`@project/island/atoms/button`), never from a root barrel.
- Declare `sideEffects` in every package so unused modules are dropped.
- Load heavy client-only widgets (maps, charts, rich editors, galleries, video players, chat) with `next/dynamic` inside a client component, on interaction or when visible, with a same-size skeleton.
- Load third-party scripts from `packages/integrations` after hydration (`next/script` with `afterInteractive` or `lazyOnload`), never in the critical path.
- Check a dependency's gzipped size before adding it, and prefer what the stack already has.
- Load only the active locale and the namespaces the route uses.
## Hydration and navigation
- Render output must be identical on server and client: no `Date.now()`, `Math.random()`, `typeof window` branches, or locale and time-zone differences in render. Format dates and numbers with the locale and time zone the server chose.
- Fewer and smaller client boundaries hydrate faster.
- Navigate with `next/link` so routes prefetch. Keep the header and footer in layouts, so navigation re-renders only the page segment.
- 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)).
## 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.
## Example: caches, page, and parts
In [page-example.md](page-example.md). Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet.
## Definition of Done (B2C/B2B additions)
```
[ ] Fresh page per request: Cache Components off; every root layout and metadata route exports dynamic = 'force-dynamic'
[ ] No server cache: no 'use cache', unstable_cache, fetch caching, revalidate, or generateStaticParams; no back-end data kept in module scope
[ ] Server code reads data only through caches with primitive arguments; no page, loader, or server component calls a repository directly
[ ] Each client part gets server data as props or through query hydration; server prefetches call the cache
[ ] useSuspenseQuery only on queries the server prefetched
[ ] global-error.tsx, error.tsx in every route group, and not-found.tsx where notFound() is called; error pages are noindex
[ ] Server reads that can answer 404 or 403 go through readOnServer; every streamed part has a PartBoundary
[ ] Each route's streamed parts are decided and written in the plan
[ ] Page is a thin entrypoint that renders the server-chosen mobile or desktop template
[ ] 'use client' only on interactive leaves; no server-only code reachable from client bundles
[ ] New server-only code is exported through server.ts and starts with import 'server-only'
[ ] First-load JS within budget; heavy widgets and third-party scripts deferred
[ ] 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
```

View File

@ -1,604 +0,0 @@
# Code patterns
Reference implementations for each layer. Paths are relative to the project that owns the code: `platforms/<app>/src/` for an app's logic and `packages/<name>/src/` for shared packages. `@project` is the workspace scope. The `@project/libs/*` APIs shown follow the lib specs: `http` and `isHttpError` in [lib-http.md](lib-http.md), the error handler's functions in [lib-error-handler.md](lib-error-handler.md), `storage` in [lib-local-storage.md](lib-local-storage.md), `cookie` in [lib-cookie.md](lib-cookie.md). `eventEmitter` stands for the repo's own lib; match its real signature.
Caches, the page entrypoint, and server-to-client data live in [b2c-b2b.md](b2c-b2b.md).
This file is the house code for each layer. Which design pattern to use, when, and where it lives is in [design-patterns.md](design-patterns.md). Error boundaries, fallbacks, empty states, and the query client's error settings are in [error-handling.md](error-handling-code.md).
Read only the section you need:
| You are writing | Section |
|---|---|
| An island component or a variant | [Island component module](#island-component-module) |
| Tokens, or a project's Tailwind sources | [Tokens and Tailwind wiring](#tokens-and-tailwind-wiring) |
| A repository, its types, mapper, or query keys | [Repository](#repository) |
| An action and its event | [Action](#action) |
| A form, a page or part model, or server errors on a form | [Validation, model, and server errors](#validation-model-and-server-errors) |
| A mutation and its cache update | [Mutation with a valid cache](#mutation-with-a-valid-cache) |
| A store | [Store](#store), and [Persisted store](#persisted-store) when it survives a reload |
| A project's env | [Env](#env) |
## Island component module
`atoms/button/variants.ts`
```ts
import { cva } from 'class-variance-authority';
export const buttonVariants = cva(
'inline-flex cursor-pointer items-center justify-center gap-2 rounded-md font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-action-primary disabled:cursor-not-allowed disabled:opacity-50',
{
variants: {
variant: {
primary: 'bg-action-primary text-on-action hover:bg-action-primary-hover',
secondary: 'border border-border-subtle bg-surface-card text-text-primary hover:bg-surface-muted',
danger: 'bg-status-danger text-on-action hover:bg-status-danger-hover',
},
size: {
sm: 'h-8 px-3 text-sm',
md: 'h-10 px-4 text-sm',
lg: 'h-11 px-5 text-base',
},
},
defaultVariants: { variant: 'primary', size: 'md' },
},
);
```
`atoms/button/types.ts`
```ts
import type { VariantProps } from 'class-variance-authority';
import type { ComponentPropsWithRef } from 'react';
import type { buttonVariants } from './variants';
export type ButtonProps = ComponentPropsWithRef<'button'> &
VariantProps<typeof buttonVariants> & {
isLoading?: boolean;
};
```
`atoms/button/Button.tsx`
```tsx
import { cn } from '../../tools/cn';
import { Spinner } from '../spinner';
import type { ButtonProps } from './types';
import { buttonVariants } from './variants';
export function Button({
className,
variant,
size,
isLoading = false,
disabled,
type = 'button',
children,
...props
}: ButtonProps) {
return (
<button
type={type}
className={cn(buttonVariants({ variant, size }), className)}
disabled={disabled || isLoading}
aria-busy={isLoading || undefined}
{...props}
>
{isLoading && <Spinner size="sm" />}
{children}
</button>
);
}
```
`atoms/button/index.ts`
```ts
export { Button } from './Button';
export type { ButtonProps } from './types';
export { buttonVariants } from './variants';
```
`tools/cn/cn.ts`
```ts
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
```
tailwind-merge doesn't know the theme. If `theme.css` adds a token it can't classify, such as a font size `text-body-sm` (which it reads as a color and drops next to `text-text-primary`), build `cn` with `extendTailwindMerge` and register the token.
## Tokens and Tailwind wiring
`styles/theme.css`: primitives are plain theme values, semantic tokens point at primitives and switch per theme, and `@theme inline` turns the semantic tokens into utilities (`bg-surface-card`, `text-text-muted`). Components use only the semantic utilities, so they never need `dark:` variants.
```css
@theme {
--color-neutral-0: #ffffff;
--color-neutral-50: #f4f6fa;
--color-neutral-900: #161b23;
--color-neutral-950: #0f1319;
--color-blue-500: #3b82f6;
--color-blue-600: #2563eb;
}
:root {
--surface-page: var(--color-neutral-50);
--surface-card: var(--color-neutral-0);
--action-primary: var(--color-blue-600);
}
.dark {
--surface-page: var(--color-neutral-950);
--surface-card: var(--color-neutral-900);
--action-primary: var(--color-blue-500);
}
@theme inline {
--color-surface-page: var(--surface-page);
--color-surface-card: var(--surface-card);
--color-action-primary: var(--action-primary);
}
```
This is an excerpt. The real file defines every semantic token the components use, such as `text-primary`, `text-muted`, `border-subtle`, `on-action`, the `status-*` colors, and their hover states.
`styles/island.css`
```css
@import './theme.css';
@import './utilities.css';
@source '../';
```
`apps/<app>/src/styles/app.css`
```css
@import 'tailwindcss' source('../');
@import '@project/island/styles/island.css';
@source '../../../../platforms/<app>/src';
```
Tailwind generates only the classes it finds in registered sources. island registers itself in `island.css`; the app registers its own `src/`, its platform, and any integration that renders UI. CSS `@import` resolves package names through package.json `exports`, not TypeScript path aliases, so path-alias workspaces import `island.css` by relative path.
## Repository
`features/auth/entities/user/types.ts`
```ts
export type UserRole = 'customer' | 'seller';
export type User = {
id: string;
full_name: string;
role: UserRole;
};
```
`features/auth/repositories/auth/types.ts`
```ts
import type { User, UserRole } from '../../entities/user';
export type LoginArgs = { phone: string; password: string };
export type LoginDto = { mobile: string; password: string };
export type LoginResponseDto = { user: User; is_first_login: boolean };
export type LoginPayload = {
user: { id: string; fullName: string; role: UserRole };
isFirstLogin: boolean;
};
```
`features/auth/repositories/auth/mappers.ts`
```ts
import type { LoginArgs, LoginDto, LoginPayload, LoginResponseDto } from './types';
export function toLoginDto(args: LoginArgs): LoginDto {
return { mobile: args.phone, password: args.password };
}
export function toLoginPayload(dto: LoginResponseDto): LoginPayload {
return {
user: { id: dto.user.id, fullName: dto.user.full_name, role: dto.user.role },
isFirstLogin: dto.is_first_login,
};
}
```
`features/auth/repositories/auth/constants.ts`
```ts
export const AUTH_ENDPOINTS = {
login: '/auth/login',
logout: '/auth/logout',
refresh: '/auth/refresh',
} as const;
```
`features/auth/http.ts`. Every feature has one; this feature needs nothing special, so it only extends the root. A feature with its own service sets `baseUrl`, headers, timeout, or retry here (see [lib-http.md](lib-http.md#root-and-feature-clients)).
```ts
import { http } from '@project/libs/http';
export const authHttp = http.extend({});
```
`features/auth/repositories/auth/auth.ts`. Repositories send requests only through their feature's client and never through the root `http`. Login sends `skipRefresh: true`: the back end answers wrong credentials with 400 or 422 and field errors, so a 401 always means "no valid session" and never starts a refresh ([error-handling.md](error-handling.md#actions)).
```ts
import { authHttp } from '../../http';
import { AUTH_ENDPOINTS } from './constants';
import { toLoginDto, toLoginPayload } from './mappers';
import type { LoginArgs, LoginPayload, LoginResponseDto } from './types';
export const authRepository = {
async login(args: LoginArgs): Promise<LoginPayload> {
const response = await authHttp.post<LoginResponseDto>(AUTH_ENDPOINTS.login, toLoginDto(args), {
skipRefresh: true,
});
return toLoginPayload(response);
},
};
```
Read methods take an optional last parameter `{ signal?: AbortSignal }` and forward it, so TanStack Query can cancel them (see Mutation with a valid cache).
`features/auth/repositories/auth/index.ts` exports no `*Dto`:
```ts
export { authRepository } from './auth';
export { AUTH_ENDPOINTS } from './constants';
export type { LoginArgs, LoginPayload } from './types';
```
Query keys sit in the repository's `constants.ts`, start with the domain, and are hierarchical so invalidation is precise. `features/catalog/repositories/products/constants.ts`:
```ts
import type { ListProductsArgs } from './types';
export const PRODUCTS_ENDPOINT = '/catalog/products';
export const productKeys = {
all: ['catalog', 'products'] as const,
lists: () => [...productKeys.all, 'list'] as const,
list: (args: ListProductsArgs) => [...productKeys.lists(), args] as const,
details: () => [...productKeys.all, 'detail'] as const,
detail: (id: string) => [...productKeys.details(), id] as const,
};
```
## Action
`features/auth/constants.ts`. Event names are `<feature>.<action>`.
```ts
export const AUTH_EVENTS = {
login: 'auth.login',
logout: 'auth.logout',
} as const;
export const LAST_PHONE_STORAGE_KEY = 'last-phone';
```
`features/auth/actions/login/actions.ts`. The repository throws the normalized `HttpError` when the request fails, so reaching the next line means the response was successful. The caller handles the error.
```ts
import { eventEmitter } from '@project/libs/event-emitter';
import { storage } from '@project/libs/local-storage';
import { useAuthStore } from '../../../../stores/auth';
import { AUTH_EVENTS, LAST_PHONE_STORAGE_KEY } from '../../constants';
import { authRepository, type LoginArgs } from '../../repositories/auth';
export async function login(args: LoginArgs, { emit = true }: { emit?: boolean } = {}): Promise<'ok'> {
const { user, isFirstLogin } = await authRepository.login(args);
useAuthStore.getState().setSession({ user, isFirstLogin });
storage.setItem(LAST_PHONE_STORAGE_KEY, args.phone);
if (emit) eventEmitter.emit(AUTH_EVENTS.login, { userId: user.id });
return 'ok';
}
```
- Every action emits its event as its last step, so a failed step throws before the emit and listeners only hear about completed operations.
- `{ emit: false }` is for callers that must not trigger listeners, such as an action that runs another action as one of its steps and emits its own event.
- Code that reacts to an action (analytics, another feature's refresh) subscribes to its event instead of being called from the action. Subscribe once, in an effect of the `AppShell`, and unsubscribe in its cleanup.
## Validation, model, and server errors
`shared/validations/base-validations.ts`. Messages are i18n keys; the field component translates them. Each message tells the user how to fix the value, for example "Enter an 11-digit mobile number that starts with 09."
```ts
import { MOBILE_REGEX } from '@project/libs/regex';
import * as v from 'valibot';
export const requiredString = (message: string) => v.pipe(v.string(), v.trim(), v.nonEmpty(message));
export const mobileNumber = (message: string) =>
v.pipe(v.string(), v.trim(), v.regex(MOBILE_REGEX, message));
```
`shared/validations/auth-validations.ts`
```ts
import * as v from 'valibot';
import { mobileNumber, requiredString } from './base-validations';
export const loginSchema = v.object({
phone: mobileNumber('validation:phone.invalid'),
password: requiredString('validation:password.required'),
});
```
`shared/validations/types.ts`
```ts
import type * as v from 'valibot';
import type { loginSchema } from './auth-validations';
export type LoginFormValues = v.InferOutput<typeof loginSchema>;
```
`shared/utils/show-action-error.ts`: the one error toast for a failed action ([error-handling.md](error-handling.md#actions)). It handles the error once, says what failed, adds the hint or a support sentence with the reference ID, and offers the button its retry kind allows.
```ts
import { describeError, handleError, type TranslateFn } from '@project/libs/error-handler';
import { toast } from 'sonner';
export type ShowActionErrorOptions = {
t: TranslateFn;
failedMessage: string; // what failed, naming the object: "Category 'Kitchenware' wasn't saved"
retry?: () => void; // only when running the action again is safe
reload?: () => void; // refetches the data the action changed, for 409 and 404
};
export function showActionError(error: unknown, { t, failedMessage, retry, reload }: ShowActionErrorOptions): void {
const errorClass = handleError(error, { where: 'action' });
if (errorClass.action === 'silent') return;
const { message, hint, referenceId } = describeError(error, t);
const details = [message, hint].filter(Boolean).join(' ');
const button =
errorClass.retry === 'again' && retry
? { label: t('errors:action.try-again'), onClick: retry }
: errorClass.retry === 'reload' && reload
? { label: t('errors:action.reload'), onClick: reload }
: undefined;
toast.error(failedMessage, {
id: `action-error:${failedMessage}`,
description:
details || t(referenceId ? 'errors:support.with-reference' : 'errors:support.without-reference', { referenceId }),
duration: Infinity,
testId: 'action-error',
action: button,
});
}
```
`shared/utils/apply-server-errors.ts`: field errors go under the fields the form renders (the first one gets focus), field errors for fields it doesn't render and errors about the whole submission go to the form-level alert, and `showActionError` shows the toast. A field counts as rendered when it has a value, so every form sets `defaultValues` for every field.
```ts
import { classifyError, describeError } from '@project/libs/error-handler';
import { isHttpError } from '@project/libs/http';
import type { FieldValues, Path, UseFormReturn } from 'react-hook-form';
import { showActionError, type ShowActionErrorOptions } from './show-action-error';
export function applyServerErrors<T extends FieldValues>(
form: UseFormReturn<T>,
error: unknown,
options: ShowActionErrorOptions,
): void {
if (classifyError(error).action === 'silent') return;
const unmatched: string[] = [];
let hasFieldError = false;
for (const [field, message] of Object.entries(isHttpError(error) ? (error.fieldErrors ?? {}) : {})) {
if (form.getValues(field as Path<T>) === undefined) {
unmatched.push(message);
continue;
}
form.setError(field as Path<T>, { type: 'server', message }, { shouldFocus: !hasFieldError });
hasFieldError = true;
}
if (!hasFieldError && unmatched.length === 0) {
unmatched.push(describeError(error, options.t).message ?? options.failedMessage);
}
if (unmatched.length > 0) form.setError('root.server', { type: 'server', message: unmatched.join(' ') });
showActionError(error, options);
}
```
- Server field messages arrive translated; they are never passed through `t` again. The lib's own `errors:` keys are translated by `describeError`.
- The form keeps every value, so after a 5xx or a network error the user submits again, and after a 4xx they fix the field and resubmit.
`features/auth/models/login/use-login-page.ts`
```ts
import { valibotResolver } from '@hookform/resolvers/valibot';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { applyServerErrors } from '../../../../shared/utils';
import { loginSchema, type LoginFormValues } from '../../../../shared/validations';
import { login } from '../../actions/login';
export function useLoginPage() {
const { t } = useTranslation('auth');
const router = useRouter();
const form = useForm<LoginFormValues>({
resolver: valibotResolver(loginSchema),
mode: 'onTouched',
defaultValues: { phone: '', password: '' },
});
const submit = form.handleSubmit(async (values) => {
try {
await login(values);
toast.success(t('login.success'));
router.push('/');
} catch (error) {
applyServerErrors(form, error, { t, failedMessage: t('login.failed') });
}
});
return { form, submit, isSubmitting: form.formState.isSubmitting };
}
```
`mode: 'onTouched'` validates a field on its first blur and on every change after that. The submit button is disabled only while `isSubmitting`, never because the form is invalid, so users can click it to find out what is wrong. Login passes no `retry`: submitting again is the retry, and sending credentials twice from a toast would surprise the user.
## Mutation with a valid cache
After every create, update, or delete, set the detail, patch the affected lists, then invalidate the lists to reconcile in the background. When patching isn't practical, invalidate every key that can contain the entity (details, lists, counts, dashboards). Never rely on `staleTime` expiring.
Use optimistic updates only for quick toggles (active/inactive, favorite), always with a rollback in `onError` and `showActionError` explaining the failure.
The query needs no error branch: a failed first load throws to the part's boundary, and a failed refetch keeps the data ([error-handling.md](error-handling.md#reads)). The mutation's `onError` shows the toast. Updating a product is a PUT, so running it again is safe and the toast offers Try again with the same input.
`features/catalog/models/product-edit/use-product-edit-page.ts`
```ts
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { showActionError } from '../../../../shared/utils';
import { productKeys, productsRepository, type ProductsPagePayload } from '../../repositories/products';
export function useProductEditPage(productId: string) {
const { t } = useTranslation('catalog');
const queryClient = useQueryClient();
const product = useQuery({
queryKey: productKeys.detail(productId),
queryFn: ({ signal }) => productsRepository.get({ id: productId }, { signal }),
});
const save = useMutation({
mutationFn: productsRepository.update,
onSuccess: (updated) => {
queryClient.setQueryData(productKeys.detail(updated.id), updated);
queryClient.setQueriesData<ProductsPagePayload>({ queryKey: productKeys.lists() }, (page) =>
page ? { ...page, items: page.items.map((item) => (item.id === updated.id ? updated : item)) } : page,
);
void queryClient.invalidateQueries({ queryKey: productKeys.lists() });
toast.success(t('product.saved', { name: updated.name }));
},
onError: (error, args) =>
showActionError(error, {
t,
failedMessage: t('product.saveFailed', { name: args.name }),
retry: () => {
save.mutate(args);
},
reload: () => {
void queryClient.invalidateQueries({ queryKey: productKeys.detail(productId) });
},
}),
});
return { product, save };
}
```
A form that saves through the mutation awaits `mutateAsync` inside `form.handleSubmit` and calls `applyServerErrors` in its `catch` ([design-patterns.md](design-patterns.md#patterns-the-architecture-already-uses)). Leave `onError` out then, so the toast shows once.
## Store
`stores/auth/types.ts`
```ts
import type { LoginPayload } from '../../features/auth';
export type Session = {
user: LoginPayload['user'];
isFirstLogin: boolean;
};
export type AuthState = {
session: Session | null;
setSession: (session: Session) => void;
clearSession: () => void;
};
```
`stores/auth/auth-store.ts`. Components subscribe to the smallest slice they render, never to the whole store.
```ts
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import type { AuthState } from './types';
export const useAuthStore = create<AuthState>()(
immer((set) => ({
session: null,
setSession: (session) =>
set((state) => {
state.session = session;
}),
clearSession: () =>
set((state) => {
state.session = null;
}),
})),
);
export const useCurrentUser = () => useAuthStore((state) => state.session?.user);
```
Never write to a store during server render (see b2c-b2b.md).
## Persisted store
A store that survives a reload keeps its data in local storage through the `storage` adapter, so the key lands under the app's prefix (`shop.session.cart`). `stores/cart/cart-store.ts`:
```ts
import { storage } from '@project/libs/local-storage';
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type { CartState } from './types';
export const useCartStore = create<CartState>()(
persist(
immer((set) => ({
items: [],
addItem: (item) =>
set((state) => {
state.items.push(item);
}),
clear: () =>
set((state) => {
state.items = [];
}),
})),
{
name: 'session.cart',
storage: createJSONStorage(() => storage),
version: 1,
partialize: (state) => ({ items: state.items }),
skipHydration: true,
},
),
);
```
- `name` is the key. `session.` marks it as the logged-in user's data, so logout's `storage.clearByPrefix('session.')` removes it.
- `partialize` persists only what must survive a reload. Bump `version` and add `migrate` when the shape changes.
- Keep `skipHydration: true` and rehydrate after mount, so the server render and the first browser render match. In the platform's `AppShell`: `useEffect(() => { void useCartStore.persist.rehydrate(); }, []);`.
## Env
The app's `env/` files, a project's `setEnv` and `getEnv`, and both bootstraps: [lib-env.md](lib-env.md#usage).

View File

@ -1,389 +0,0 @@
# Design patterns
How to pick and apply the GoF patterns from refactoring.guru and the JavaScript and React patterns from patterns.dev in this architecture. You already know the patterns, so this file gives only the decisions for this codebase: the signal that calls for each pattern, where it lives, its TypeScript shape, and when not to use it. Rendering and loading patterns are in [rendering-patterns.md](rendering-patterns.md), and code smells and refactoring techniques are in [refactoring.md](refactoring.md). Names match the source pages under refactoring.guru/design-patterns/ and patterns.dev/vanilla/ or patterns.dev/react/.
Contents: How to choose · Patterns the architecture already uses · Adding a pattern · React and JavaScript patterns · Other GoF patterns · Not used here
## How to choose
1. **Start from a problem you have now, never from a pattern.** Name the signal, then use the smallest pattern that removes it:
- The same `switch` on a type in several places → Strategy as a `Record` map.
- The same object built in several places with small differences → a factory function.
- Several booleans that describe one flow (`isUploading`, `isProcessing`, `hasFailed`) → State as a discriminated union.
- A vendor SDK's types and calls spreading through the code → Adapter in an integration.
- A back-end field name reaching a component → Adapter in the repository's `mappers.ts`.
- One feature must react to another feature's completed operation → Observer through the action's event.
- Parts of one page that must stay in step → Mediator in the page model.
- The pieces of one widget passing the same state to each other through props → Compound component.
Without a signal, write the direct code.
2. **Reuse the pattern the architecture already has for the job** (next section). A second event bus, HTTP wrapper, store library, or cache layer is a design error.
3. **Shape it with functions, closures, modules, and object literals.** Use a class only in a stateful lib whose spec already has one: `HttpClient`, `InterceptorManager`, `CookieAdapter`, or `LocalStorageAdapter`. Compose instead of inheriting. Error classes such as `HttpError` extend `Error`, and island's error-boundary primitive (`packages/island/src/primitives/error-boundary/ErrorBoundary.tsx`) extends React's `Component`, because React has no hook for catching render errors. Nothing else inherits, and no component inherits from another component.
4. **Keep a pattern inside its layer.** No pattern justifies an upward or cross-product import, or a break in the feature's layer order ([project-structure.md](project-structure.md#feature-anatomy)). When two layers must meet, wire them one level up: the AppShell subscribes, and the bootstrap configures.
5. **On the server, module scope holds only startup configuration and immutable helpers built from a fixed set, such as one `Intl` formatter per supported locale and time zone.** A singleton, a flyweight pool, or a memoized value in module scope serves every request, so it never holds back-end data, rendered output, or per-request or per-user data, even when every user would see the same value ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
6. **Wait for the third case before you extract an abstraction.** Two similar blocks can stay duplicated; the third one shows what really varies. island is the exception: a second style becomes a variant at once ([refactoring.md](refactoring.md)).
7. **Make the role visible in the name**, following the repo's conventions. Factories are camelCase `create*` functions (`createHttpClient`; `makeQueryClient` keeps the name from TanStack's docs). Key factories are camelCase objects (`productKeys`). Constant maps are UPPER_SNAKE_CASE (`AUTH_EVENTS`). A class or type that wraps a browser or vendor API ends in `Adapter` (`CookieAdapter`, `AnalyticsAdapter`), and its instance takes the domain name (`cookie`, `analytics`). A strategy map is a constant map named `<SUBJECT>_<ROLE>` (`ORDER_STATUS_BADGES`). A state machine lives in `<flow>-flow.ts` and exports `<Flow>State`, `<Flow>Event`, `<flow>Reducer`, and `INITIAL_<FLOW>_STATE`, with dotted event types that name what happened (`file.selected`).
8. **Record a new, non-obvious pattern** in the PR description: the signal, the pattern, and the simpler option you rejected.
## Patterns the architecture already uses
Reuse these before you add anything.
| Pattern | Where it lives | Rule |
|---|---|---|
| Module | Every module's `index.ts`; `server.ts` for server-only code | Every module. Re-export the public API by name and keep the rest private: never `export *`, never import another module's internal file, and never re-export `server.ts` from `index.ts` ([project-structure.md](project-structure.md#exports-and-tree-shaking)) |
| Singleton | The root `http`, `cookie`, `storage`, `eventEmitter`, zustand stores, and the browser `QueryClient` from `getQueryClient()` | For a service the whole app shares: a module instance that the bootstrap configures (`export const cookie = new CookieAdapter()`), never a class with `getInstance`. On the server one instance serves every request, so per-request objects come from a function (a new `QueryClient` per `getQueryClient()` call, a per-request i18next instance), and nothing writes to a store during server render ([b2c-b2b.md](b2c-b2b.md#state-and-auth)) |
| Factory functions | `createHttpClient`, `createClientEnv`, `createServerEnv`, `makeQueryClient`, and key factories such as `productKeys` | When several callers build the same kind of object from different inputs: a function that returns a new object or closure. Query keys always come from the repository's key factory ([code-patterns.md](code-patterns.md#repository)). Don't add a factory for an object built in one place |
| Adapter | `CookieAdapter` over `document.cookie`; each repository's `mappers.ts`; each integration over its vendor API | 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 |
| 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 |
| Decorator | zustand middleware: `immer` and `persist` | When a store needs cross-cutting behavior: wrap the creator and keep its shape, as in `persist(immer(...))` ([code-patterns.md](code-patterns.md#persisted-store)). No TypeScript decorator syntax, and no higher-order components that wrap components (see HOC below) |
| Chain of Responsibility | HTTP request and response interceptors; Next.js `proxy.ts`; nested error boundaries | For steps that every request or error passes through. Interceptors run root first and carry only cross-cutting concerns ([lib-http.md](lib-http.md#interceptors)). `proxy.ts` either answers (a redirect) or passes the request on, after it refreshes an expired session. An error stops at the nearest error boundary: part, then page, then app ([error-handling.md](error-handling.md#boundaries)). Never put business logic in a link |
| Observer | Action events through `eventEmitter`; zustand selectors; the TanStack Query cache and the queries that observe it | When code must react to a change that its source shouldn't know about. Events fire only after an operation completes. A listener subscribes once in an AppShell effect and unsubscribes in its cleanup, and a component subscribes to the smallest slice. The emitter only broadcasts, so coordination stays in actions and models |
| Mediator | The page model, between its part models | When parts of one page must stay in step. Parts never import or call each other: the page model owns what they share (the current step, the final submit) and passes it down as props. Don't add a context or a store for one page's parts. Run the page model in the smallest client component that contains the coordinated parts, never in the template or the page, which stay Server Components ([b2c-b2b.md](b2c-b2b.md#rendering)). State that must survive a reload or a shared link goes in the URL |
| Command | `useMutation` around a repository call or a feature action | When the UI triggers an operation and shows its progress. The mutation holds the operation; the UI calls `mutate` and reads `isPending` and `error`, and an error toast's retry calls it again when running it twice is safe ([error-handling.md](error-handling.md#actions)). Feature actions are client-side operations, not Next.js Server Actions. No hand-made command objects with `execute` and `undo`; undo is a back-end operation offered in the toast. A multi-step flow with its own states runs the request from its State reducer's model instead; don't wrap the same call in `useMutation` as well. A form whose submit runs a feature action awaits it inside `form.handleSubmit` and uses `formState.isSubmitting` as its pending state ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)); don't wrap the action in `useMutation` as well. A form that saves through one repository call keeps the model's `useMutation` ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)) and awaits `mutateAsync` inside `form.handleSubmit`, catching the error for `applyServerErrors`, so `isSubmitting` and `isPending` agree |
| State | Multi-step flows: wizards, imports, bulk actions | When a flow has steps that carry different data: a state union, an event union, and a pure reducer in the model's folder (example below). Never a set of booleans |
| Strategy | Function-valued options such as the HTTP lib's `mapErrorBody` and `shouldRefresh`; sort comparators; the mobile or desktop template that the page picks on the server | When one contract has interchangeable implementations: pass a function, or pick an entry from a `Record` map (example below). Choose once, at the top: the page picks the template, and no component branches on viewport size. Don't add a strategy for behavior that never varies |
| Composite | Navigation menus, sidebar groups, and category trees | When a tree mixes leaves and groups: one node type (`children?: MenuNode[]`) and one recursive component. Filter the tree before rendering, so a group with no visible items disappears, and key nodes by id, never by index |
| Bridge | Semantic tokens over primitive tokens in island `theme.css` | For every component and theme. Components use semantic tokens only, and each theme maps them to primitives, so components and themes vary independently and a new theme touches only `theme.css` ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)). Never add a theme prop, `dark:` classes, or theme-specific variants to a component |
| Flyweight | The icon sprite, where every `<use>` points at one `<symbol>`; `Intl` formatters shared per locale and time zone in `packages/tools` | When many uses share heavy, immutable data: share that part and pass the rest per use (size and color for an icon, the value for a formatter). Date formatters always set `timeZone` explicitly to the one the server chose, never the runtime default ([b2c-b2b.md](b2c-b2b.md#hydration-and-navigation)). On the server, build a pool only from a fixed set such as the app's locales and supported time zones, never from user input, and never store formatted output |
| Memento | Persisted stores (`partialize`, `version`, `migrate`); react-hook-form `defaultValues` and `reset` | When state must be restored later. Snapshot only what must survive, and migrate old snapshots ([code-patterns.md](code-patterns.md#persisted-store)). After a successful save, `reset` the form with the saved values, so dirty tracking and the unsaved-changes warning start from the saved data. Never snapshot server data or loading flags |
| Iterator | `useInfiniteQuery` for feeds; an async generator in a repository | When code walks a paged collection without caring how the pages load. Infinite queries serve feeds only. Use an async generator over pages only when a flow must visit every page and the back end has no bulk endpoint |
| Container/Presentational with Hooks | Models with presentational pages, templates, and organisms; on the server, async server components that read caches | For every page and part. The model holds the data and handlers, and the page calls it and renders a template that only takes props. On the server, the container is an async server component that reads caches and passes `*Payload` props ([b2c-b2b.md](b2c-b2b.md#data-flow)). Components never call repositories or actions directly |
| Provider | The AppShell's providers; compound component contexts | For app-wide services, such as the query client and i18next, and for the parts of one compound component. Render `<Context value>` and read it with `use(Context)` or `useContext` (React 19). Keep app-wide providers in the AppShell, and keep shared state out of context (see Provider below) |
| Compound | `DataTable` and other complex island organisms | When a widget's parts share state and the caller arranges them: the parts share state through context and are also exported by name (example below). A component with one fixed layout takes props instead |
| Render props | Slots for `DataTable` cells, empty states, and toolbars | When the caller varies part of an organism: a `ReactNode` slot by default, and a render function (`cell: (row: TRow) => ReactNode`) only when the slot needs the organism's data. Never use one to share logic; write a hook |
## Adding a pattern
Where a new implementation goes:
| Pattern | Home | Shape |
|---|---|---|
| Strategy map | The owning module's `constants.ts`. Other features import it through that feature's `index.ts`. Use `shared/constants/` only when neither its keys nor its values come from a feature, because `shared/` never imports from `features/` | A constant map named `<SUBJECT>_<ROLE>`, typed with `satisfies Record<Union, Entry>`. Styles that vary by a prop are cva variants instead |
| State machine | The page or part model's folder, such as `models/product-import/product-import-flow.ts` | The state union, the event union, and a pure reducer. The model runs it with `useReducer`. When the flow must outlive the page, move the flow file into the store's folder (`stores/<domain>/<flow>-flow.ts`), have the store's action call the reducer, and have the model read the state through a selector. A store never imports from `models/` |
| Adapter for a vendor SDK | `packages/integrations/src/<name>/` | An object literal or functions typed by the integration's own `types.ts`, with no vendor type in its public API |
| Adapter for an API shape | The repository's `mappers.ts` | `to<Name>Dto(args)` and `to<Name>Payload(dto)` ([code-patterns.md](code-patterns.md#repository)) |
| Facade over several repositories or side effects | An action in the feature that owns the operation: `actions/<action-name>/actions.ts` | One async function with the `{ emit }` option that emits its event last ([code-patterns.md](code-patterns.md#action)) |
| Observer listener | An effect of the AppShell | Subscribe once, and return the unsubscribe function as the effect's cleanup |
| Factory | Beside what it builds: in the module's main file when the module exists to build that thing (`createHttpClient` in `http.ts`), otherwise its own `create-<thing>.ts` in the owning module | `create<Thing>(options): Thing`, returning an object literal or a closure |
| Exhaustive check | `assertNever` in `packages/tools/src/assert-never/` | `assertNever(value: never): never` throws. Call it in the `default` of every `switch` over a union |
| Generic hook with no feature data, such as `useDebouncedValue` | `packages/tools/src/use-debounced-value/use-debounced-value.ts` when more than one project needs it; otherwise beside its only user, such as an organism's `hooks/` | A `use-<name>.ts` hook that takes plain values and imports only React. A hook that reads a store, a query, or a `*Payload` belongs in the owning feature's `models/` or beside its store |
The examples use feature paths relative to `platforms/<app>/src/`, as code-patterns.md does.
**Strategy.** An order's status picks its badge in the order list, the order header, and the timeline. One map replaces the three switches, and `satisfies` makes a new status fail type-check until it has an entry.
`features/orders/constants.ts`
```ts
import type { BadgeProps } from '@project/island/atoms/badge';
import type { OrderStatus } from './entities/order';
export const ORDER_STATUS_BADGES = {
pending: { variant: 'warning', labelKey: 'orders:status.pending' },
paid: { variant: 'info', labelKey: 'orders:status.paid' },
shipped: { variant: 'info', labelKey: 'orders:status.shipped' },
delivered: { variant: 'success', labelKey: 'orders:status.delivered' },
cancelled: { variant: 'danger', labelKey: 'orders:status.cancelled' },
} as const satisfies Record<OrderStatus, { variant: NonNullable<BadgeProps['variant']>; labelKey: string }>;
```
A component reads `const badge = ORDER_STATUS_BADGES[order.status]` and renders `<Badge variant={badge.variant}>{t(badge.labelKey)}</Badge>`.
**State.** A product import goes `idle → validating → uploading → processing → done | failed`. The flow file holds the states, the events, and a pure reducer. An event that doesn't fit the current state returns the state unchanged.
`features/catalog/models/product-import/product-import-flow.ts`
```ts
import { assertNever } from '@project/tools/assert-never';
import type { ProductImportReportPayload } from '../../repositories/product-imports';
export type ProductImportState =
| { status: 'idle' }
| { status: 'validating'; file: File }
| { status: 'uploading'; file: File; percent: number }
| { status: 'processing'; file: File }
| { status: 'done'; report: ProductImportReportPayload }
| { status: 'failed'; error: unknown };
export type ProductImportEvent =
| { type: 'file.selected'; file: File }
| { type: 'file.validated' }
| { type: 'upload.progressed'; percent: number }
| { type: 'import.succeeded'; report: ProductImportReportPayload }
| { type: 'import.failed'; error: unknown }
| { type: 'import.cancelled' };
export const INITIAL_PRODUCT_IMPORT_STATE: ProductImportState = { status: 'idle' };
export function isProductImportBusy(state: ProductImportState): boolean {
return state.status === 'validating' || state.status === 'uploading' || state.status === 'processing';
}
export function productImportReducer(state: ProductImportState, event: ProductImportEvent): ProductImportState {
switch (event.type) {
case 'file.selected':
return isProductImportBusy(state) ? state : { status: 'validating', file: event.file };
case 'file.validated':
return state.status === 'validating' ? { status: 'uploading', file: state.file, percent: 0 } : state;
case 'upload.progressed':
if (state.status !== 'uploading') return state;
return event.percent < 100 ? { ...state, percent: event.percent } : { status: 'processing', file: state.file };
case 'import.succeeded':
return state.status === 'uploading' || state.status === 'processing'
? { status: 'done', report: event.report }
: state;
case 'import.failed':
return isProductImportBusy(state) ? { status: 'failed', error: event.error } : state;
case 'import.cancelled':
return INITIAL_PRODUCT_IMPORT_STATE;
default:
return assertNever(event);
}
}
```
`features/catalog/models/product-import/use-product-import-page.ts`. The progress comes from the feature client's `upload()` through the repository ([lib-http.md](lib-http.md#files)). The server answers with the report after it processes the file, so the flow enters `processing` when the upload reaches 100%.
```ts
import { useReducer, useRef } from 'react';
import * as v from 'valibot';
import { productImportFileSchema } from '../../../../shared/validations';
import { productImportsRepository } from '../../repositories/product-imports';
import { INITIAL_PRODUCT_IMPORT_STATE, productImportReducer } from './product-import-flow';
export function useProductImportPage() {
const [state, dispatch] = useReducer(productImportReducer, INITIAL_PRODUCT_IMPORT_STATE);
const controllerRef = useRef<AbortController | null>(null);
async function start(file: File) {
if (controllerRef.current) return;
const controller = new AbortController();
controllerRef.current = controller;
dispatch({ type: 'file.selected', file });
try {
await v.parseAsync(productImportFileSchema, file);
if (controller.signal.aborted) return;
dispatch({ type: 'file.validated' });
const report = await productImportsRepository.upload(
{ file },
{
signal: controller.signal,
onProgress: ({ percent }) => dispatch({ type: 'upload.progressed', percent }),
},
);
if (controller.signal.aborted) return;
dispatch({ type: 'import.succeeded', report });
} catch (error) {
if (!controller.signal.aborted) dispatch({ type: 'import.failed', error });
} finally {
if (controllerRef.current === controller) controllerRef.current = null;
}
}
function cancel() {
controllerRef.current?.abort();
controllerRef.current = null;
dispatch({ type: 'import.cancelled' });
}
return { state, start, cancel };
}
```
- The controller is the in-flight guard: it exists from the first step, so a second `start` (a double click) returns at once. `cancel` aborts it and clears the ref, so a cancel during validation never starts the upload, and a new file can start right away.
- An aborted run dispatches nothing, so the `ABORTED` error is never shown and a late event from the old run can't touch the new one.
- After `import.succeeded`, the model also shows a toast and invalidates the product lists ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)). Both are left out here.
- The template switches on `state.status`, with `assertNever` in the `default`.
**Observer with Adapter.** The analytics integration adapts a tag manager's `dataLayer`, which needs no npm dependency. Integrations can't import features, so the AppShell wires the auth feature's event to the integration.
`packages/integrations/src/analytics/types.ts`
```ts
export type AnalyticsEvent = { name: 'login' | 'logout' | 'purchase'; params?: Record<string, string | number> };
export type AnalyticsAdapter = { track: (event: AnalyticsEvent) => void };
declare global {
interface Window {
dataLayer?: Record<string, unknown>[];
}
}
```
`packages/integrations/src/analytics/analytics.ts`. The rest of the code calls `analytics.track`, so a change of vendor touches only this file.
```ts
import type { AnalyticsAdapter } from './types';
export const analytics: AnalyticsAdapter = {
track(event) {
if (typeof window === 'undefined') return;
(window.dataLayer ??= []).push({ event: event.name, ...event.params });
},
};
```
`platforms/<app>/src/app/app-shell/AppShell.tsx`, reduced to the subscription.
```tsx
'use client';
import { analytics } from '@project/integrations/analytics';
import { eventEmitter } from '@project/libs/event-emitter';
import { useEffect } from 'react';
import { AUTH_EVENTS } from '../../features/auth';
import type { AppShellProps } from './types';
export function AppShell({ children }: AppShellProps) {
useEffect(() => {
const unsubscribe = eventEmitter.on(AUTH_EVENTS.login, () => analytics.track({ name: 'login' }));
return unsubscribe;
}, []);
return children;
}
```
This assumes that `on` returns an unsubscribe function. Match the repo's real event-emitter signature, for example by calling its `off` in the cleanup. Loading the tag manager's script is a loading decision, covered in rendering-patterns.md.
**Compound component.** island's `Tabs` organism: the root owns the state, the parts read it from a context, and every part is exported by name.
`packages/island/src/organisms/tabs/hooks/use-tabs-context.ts`, private to the organism:
```ts
import { createContext, useContext } from 'react';
import type { TabsContextValue } from '../types';
export const TabsContext = createContext<TabsContextValue | null>(null);
export function useTabsContext(): TabsContextValue {
const context = useContext(TabsContext);
if (!context) throw new Error('Tabs parts must be rendered inside <Tabs>.');
return context;
}
```
`packages/island/src/organisms/tabs/Tabs.tsx`. Memoize the context value, so a root re-render that keeps the same tab doesn't re-render parts that sit behind a `memo` boundary. Skip `useMemo` when the repo enables the React Compiler.
```tsx
'use client';
import { useId, useMemo, useState } from 'react';
import { TabsList } from './components/tabs-list';
import { TabsPanel } from './components/tabs-panel';
import { TabsTrigger } from './components/tabs-trigger';
import { TabsContext } from './hooks/use-tabs-context';
import type { TabsProps } from './types';
function TabsRoot({ defaultValue, children }: TabsProps) {
const [activeValue, setActiveValue] = useState(defaultValue);
const baseId = useId();
const context = useMemo(() => ({ activeValue, select: setActiveValue, baseId }), [activeValue, baseId]);
return <TabsContext value={context}>{children}</TabsContext>;
}
export const Tabs = Object.assign(TabsRoot, { List: TabsList, Trigger: TabsTrigger, Panel: TabsPanel });
```
`packages/island/src/organisms/tabs/components/tabs-trigger/TabsTrigger.tsx`. `TabsPanel` reads the same context. It renders its children the first time its tab is selected, then keeps them mounted inside `<Activity mode="hidden">` while another tab is active, so switching tabs never remounts a visited panel. A panel whose content must be in the server HTML, such as product details for search engines, takes `forceMount` and is hidden with the `hidden` attribute instead. `TabsList` only renders `role="tablist"`. Arrow-key movement between tabs is left out to keep the example short.
```tsx
'use client';
import { useTabsContext } from '../../hooks/use-tabs-context';
import type { TabsTriggerProps } from './types';
import { tabsTriggerVariants } from './variants';
export function TabsTrigger({ value, children }: TabsTriggerProps) {
const { activeValue, select, baseId } = useTabsContext();
const isSelected = activeValue === value;
return (
<button
type="button"
role="tab"
id={`${baseId}-tab-${value}`}
aria-selected={isSelected}
aria-controls={`${baseId}-panel-${value}`}
className={tabsTriggerVariants({ isSelected })}
onClick={() => select(value)}
>
{children}
</button>
);
}
```
`packages/island/src/organisms/tabs/index.ts`
```ts
export { Tabs } from './Tabs';
export { TabsList, type TabsListProps } from './components/tabs-list';
export { TabsPanel, type TabsPanelProps } from './components/tabs-panel';
export { TabsTrigger, type TabsTriggerProps } from './components/tabs-trigger';
export type { TabsProps } from './types';
```
Pitfall: a Server Component can't reach a part through the root. island modules are ES modules, so on the server each export of a `'use client'` file is only a client reference. `Tabs.List` is `undefined` there, so the render fails, and the error message depends on the bundler. So Server Components compose the named parts, and `Tabs.List` stays for client components. The panels' content can stay server-rendered, and panels that search engines must read take `forceMount`:
`apps/<app>/src/app/(shop)/product/[id]/templates/product-desktop/ProductDesktop.tsx`, excerpt:
```tsx
<Tabs defaultValue="details">
<TabsList>
<TabsTrigger value="details">{t('catalog:product.tabs.details')}</TabsTrigger>
<TabsTrigger value="shipping">{t('catalog:product.tabs.shipping')}</TabsTrigger>
</TabsList>
<TabsPanel value="details" forceMount>
<ProductSpecs product={product} />
</TabsPanel>
<TabsPanel value="shipping" forceMount>
<ShippingInfo product={product} />
</TabsPanel>
</Tabs>
```
## React and JavaScript patterns
Decisions for the patterns.dev design patterns that the table above leaves open:
- **HOC**: not used for new code. Put cross-cutting behavior in a hook or a wrapper component, such as an error boundary. React's own `memo` and `lazy` are fine, and so is Next.js's `catchError`, which builds the `PartBoundary` ([error-handling.md](error-handling.md#boundaries)). `ref` is a regular prop in React 19, so new components skip `forwardRef` too.
- **Render props versus slots**: a Server Component can't pass a plain function to a client component, so it passes only `ReactNode` slots. An organism that needs render functions, such as a `DataTable` with custom cells, is rendered from a client component that defines them.
- **Provider**: context carries services and one compound component's state, never app data. Shared client state goes to a zustand store read through selectors, server state to the query cache, and form state to react-hook-form; never mirror any of them into a context. Split large contexts. The one store-in-context case is a store that must start from server data ([b2c-b2b.md](b2c-b2b.md#state-and-auth)).
- **Hooks added in React 19**: `useActionState`, `useFormStatus`, and `useOptimistic` are built for React's actions. Forms here run on react-hook-form with the model's `submit`, and optimistic toggles go through the query cache with a rollback ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)), so don't add a second pending or optimistic state for the same data. `use()` reads a streamed promise inside `<Suspense>` ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- **Mixin**: not used. Share behavior with functions, hooks, and composition, and never copy methods onto a class or a prototype.
- **Proxy object** (JavaScript `Proxy` and `Reflect`): not used in app code, because it hides behavior from readers and from the type checker. immer uses it inside zustand's `set`, so never keep a draft after `set` returns. For guarded configuration, write explicit functions, like a project's `getEnv` that throws before `setEnv` has run.
- **Prototype** (the prototype chain): only the custom prototypes lib (`packages/libs/src/custom-prototypes/`) extends built-ins. It adds each method with `Object.defineProperty` (non-enumerable), skips a name that already exists so it never overwrites a native or third-party method, declares the methods in a `declare global` block, and is listed in `sideEffects` ([project-structure.md](project-structure.md#exports-and-tree-shaking)). Import it at the top of each bootstrap. Everywhere else, write plain functions.
- **Mediator/Middleware**: patterns.dev joins two rows of the table: Mediator (the page model) and Chain of Responsibility (interceptors and `proxy.ts`). Don't add a central hub that components send messages through.
- **Server push**, such as a live order status or the progress of an import's `processing` step: poll first, with the part model's `useQuery` and a `refetchInterval` that stops when the status is final. Push is a lib change with its own spec and approval: SSE is a streaming method in the HTTP lib, as for AI UI below, so it shares the one refresh and abort, and a WebSocket client is a new lib in `packages/libs`. Never a raw `EventSource` or `WebSocket` in a model. The part model subscribes in an effect and writes each message to the query cache with `setQueryData`, never to a store.
- **AI UI Patterns**: only when the product has a chat or assistant page. The conversation is a part model's state, with each message a union by status (`streaming`, `done`, `failed`). Streamed replies need a streaming method in the HTTP lib, which is a lib change ([lib-http.md](lib-http.md)), never `fetch` in a model. The AI SDK is outside the stack, so state the reason and get approval before adding it.
- **React Stack Patterns**: a survey of tool choices, not a design pattern. The stack is fixed in [SKILL.md](../SKILL.md#2-stack), and any other pick needs a stated reason and approval.
## Other GoF patterns
The GoF patterns that the architecture doesn't already use:
- **Factory Method**: not used in its class form, because nothing here inherits. When a caller needs one of several implementations by key, use a factory function (table above) or a `Record` from key to implementation in the owning module's `constants.ts`. A map of components inside a client component bundles every entry, so heavy entries map to lazy components; a map in a Server Component ships only the client entries it renders (rendering-patterns.md).
- **Abstract Factory**: rarely needed, because matching families are already chosen once, higher up: the theme through tokens (Bridge) and the device through the template. Don't build a context that swaps whole component kits; a second brand is a theme in `theme.css`. A real need for different component sets, such as white-label apps, is decided in the plan first.
- **Builder**: rarely needed. When a value has many optional parts, such as metadata from `configs/seo.ts` or JSON-LD built from a `*Payload`, write a pure function that takes an options object with defaults and returns the finished value. No chained, mutable builder classes; valibot's `pipe` already composes schemas step by step.
- **Prototype**: copying is an immutable update: spread for a shallow copy, `structuredClone` for a deep copy of plain data, and immer drafts inside stores. `http.extend` isn't a Prototype: it delegates to the root live instead of copying it, so settings made later in bootstrap still apply ([lib-http.md](lib-http.md#api)). Never `structuredClone` an object that holds functions or class instances; it throws on functions and drops prototypes.
- **Template Method**: not used in its class form. Its component form already exists: island templates and organisms such as `PageHeader` fix the layout and take the varying parts as slots. For logic, write a function that owns the sequence and takes the varying steps as callbacks, such as `runImport({ validate, upload, dispatch })`, and move it to `shared/utils/` only when a third feature needs the same sequence.
- **Visitor**: rarely needed in app code. To run type-specific logic over mixed nodes, such as CMS content blocks or filter expressions, switch exhaustively over the discriminated union with `assertNever`, or use a `Record` from `type` to handler. A new operation is a new function, and a new node type fails type-check at every switch. No `accept` and `visit` double dispatch.
## Not used here
Keep these out of designs, and flag each one in review with its alternative. A merge blocks only for the reasons in [SKILL.md](../SKILL.md#7-review-stance), which include the server-side cache and boundary cases below.
- **`getInstance` singleton classes.** Export a module instance. On the server, create per-request objects with a function such as `getQueryClient()`.
- **Module-scope per-request or per-user state on the server**, such as a `Map` of users, a memoized promise of back-end data, or a store written during render. Use a feature cache (React `cache()`), the per-request `QueryClient`, or props ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
- **A service locator or DI container.** The bootstrap is the composition root: it passes settings to libs with `configure` and values to projects with `setEnv`, and each module imports what it uses by name.
- **Base classes** such as `BaseRepository` or `BaseService`. A repository is an object literal. Shared request behavior lives in the feature client and its interceptors ([lib-http.md](lib-http.md#root-and-feature-clients)), and shared logic lives in small functions.
- **Inheritance between components.** Compose with `children`, slots, cva variants, and compound parts.
- **HOCs and mixins in new code.** Use a hook or a wrapper component.
- **Events for request and response flows**, such as emitting `cart.totalRequested` and waiting for a reply event. Call the action or repository and await it; events only fan out after an operation completes.
- **A second event bus, cache layer, or state library**, such as RxJS subjects, a hand-made fetch cache, Redux, or a context used as a store. Use the event emitter, the query cache (or `cache()` within one server request), 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.

View File

@ -1,293 +0,0 @@
# Error handling code
The code for [error-handling.md](error-handling.md): island's error boundary, `ErrorFallback`, the part, page, and app boundaries, `readOnServer`, and the query client's error settings. Read it only when you build or change one of these. A feature that uses them needs only error-handling.md.
Paths are relative to `platforms/<app>/src/`, as in [code-patterns.md](code-patterns.md). Each `error-boundaries/<name>/` module is shaped like `guards/`: the component or function, its `types.ts`, and `index.ts`.
**island's error boundary.** `packages/island/src/primitives/error-boundary/ErrorBoundary.tsx` is a class, because React has no hook for catching render errors. It knows nothing about HTTP or reporting; the fallback does that. Its `types.ts` declares `ErrorBoundaryProps`: `children`, `fallback: (props: { error: unknown; reset: () => void }) => ReactNode`, `onReset?`, and `resetKeys?: readonly unknown[]`.
```tsx
'use client';
import { Component } from 'react';
import type { ErrorBoundaryProps } from './types';
type ErrorBoundaryState = { hasError: boolean; error: unknown };
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
state: ErrorBoundaryState = { hasError: false, error: null };
static getDerivedStateFromError(error: unknown): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidUpdate(previous: ErrorBoundaryProps) {
const keys = this.props.resetKeys ?? [];
const changed = keys.some((key, index) => !Object.is(key, previous.resetKeys?.[index]));
if (this.state.hasError && changed) this.reset();
}
reset = () => {
this.props.onReset?.();
this.setState({ hasError: false, error: null });
};
render() {
if (!this.state.hasError) return this.props.children;
return this.props.fallback({ error: this.state.error, reset: this.reset });
}
}
```
**The fallback.** `app/error-boundaries/error-fallback/ErrorFallback.tsx`. `size` is `'app' | 'page' | 'part'`; island's molecules take `'page' | 'part'`.
```tsx
'use client';
import { Button } from '@project/island/atoms/button';
import { ErrorState } from '@project/island/molecules/error-state';
import { classifyError, describeError, handleError } from '@project/libs/error-handler';
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { StatusEmptyState } from '../status-empty-state';
import type { ErrorFallbackProps } from './types';
export function ErrorFallback({ error, size, name, onRetry }: ErrorFallbackProps) {
const { t } = useTranslation('errors');
const headingRef = useRef<HTMLHeadingElement>(null);
const { read, cause } = classifyError(error);
const islandSize = size === 'part' ? 'part' : 'page';
useEffect(() => {
handleError(error, { where: size, name });
if (size !== 'part') headingRef.current?.focus();
}, [error, size, name]);
if (read === 'silent') return null;
if (read !== 'boundary') return <StatusEmptyState variant={read} size={islandSize} headingRef={headingRef} />;
const { referenceId } = describeError(error, t);
return (
<ErrorState
size={islandSize}
headingRef={headingRef}
title={t(`fallback.${cause}.title`)}
description={t(`fallback.${cause}.description`)}
referenceId={referenceId && t('fallback.reference', { referenceId })}
action={
cause === 'network' ? (
<Button onClick={onRetry}>{t('fallback.try-again')}</Button>
) : (
<Button onClick={() => window.location.reload()}>{t('fallback.reload')}</Button>
)
}
/>
);
}
```
`StatusEmptyState` (`error-boundaries/status-empty-state/`) renders island's `EmptyState` with the `errors:empty.<variant>` copy and, at page size, the link back. It is a client component, so the server page and parts can render it too.
**Part boundary.** `app/error-boundaries/part-boundary/PartBoundary.tsx`. `PartBoundaryProps` is `{ name: string }`; `catchError` adds `children`.
```tsx
'use client';
import { useQueryErrorResetBoundary } from '@tanstack/react-query';
import { catchError, type ErrorInfo } from 'next/error';
import { ErrorFallback } from '../error-fallback';
import type { PartBoundaryProps } from './types';
function PartFallback({ name }: PartBoundaryProps, { error, retry, reset }: ErrorInfo) {
const queryErrors = useQueryErrorResetBoundary();
const isServerError = 'digest' in error;
return (
<ErrorFallback
error={error}
size="part"
name={name}
onRetry={() => {
queryErrors.reset();
if (isServerError) retry();
else reset();
}}
/>
);
}
export const PartBoundary = catchError(PartFallback);
```
A part in a template:
```tsx
<PartBoundary name="order-invoice">
<Suspense fallback={<OrderInvoiceSkeleton />}>
<OrderInvoice orderId={order.id} />
</Suspense>
</PartBoundary>
```
**Page and app boundaries.** `apps/<app>/src/app/(account)/error.tsx`:
```tsx
'use client';
import { ErrorFallback } from '@project/<platform>/app/error-boundaries';
import { useQueryErrorResetBoundary } from '@tanstack/react-query';
type AccountErrorProps = { error: Error & { digest?: string }; retry: () => void };
export default function AccountError({ error, retry }: AccountErrorProps) {
const queryErrors = useQueryErrorResetBoundary();
return (
<>
<meta name="robots" content="noindex" />
<ErrorFallback
error={error}
size="page"
onRetry={() => {
queryErrors.reset();
retry();
}}
/>
</>
);
}
```
`apps/<app>/src/app/global-error.tsx`. `i18n` is the app's client i18n instance, so `useTranslation` works without providers.
```tsx
'use client';
import '../styles/app.css';
import { ErrorFallback } from '@project/<platform>/app/error-boundaries';
import { i18n } from '../i18n';
export default function GlobalError({ error }: { error: Error & { digest?: string } }) {
return (
<html lang={i18n.language} dir={i18n.dir()}>
<body>
<meta name="robots" content="noindex" />
<ErrorFallback error={error} size="app" onRetry={() => window.location.reload()} />
</body>
</html>
);
}
```
The `AppShell` renders the one `Toaster`:
```tsx
const { i18n } = useTranslation();
const dir = i18n.dir();
// in the returned JSX:
<Toaster dir={dir} position={dir === 'rtl' ? 'bottom-left' : 'bottom-right'} />
```
**Query client.** `configs/react-query.ts` keeps its `getQueryClient()` and dehydrate settings ([b2c-b2b.md](page-example.md)) and adds the lines below.
```ts
import { handleError } from '@project/libs/error-handler';
import { defaultShouldDehydrateQuery, QueryCache, QueryClient } from '@tanstack/react-query';
function makeQueryClient(): QueryClient {
return new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
if (query.state.data !== undefined) handleError(error, { where: 'refetch' });
},
}),
defaultOptions: {
queries: {
staleTime: 60_000,
retry: false,
networkMode: 'offlineFirst',
throwOnError: (_error, query) => query.state.data === undefined,
},
mutations: { networkMode: 'offlineFirst' },
dehydrate: {
shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending',
shouldRedactErrors: () => false,
},
},
});
}
```
**Server reads.** `app/error-boundaries/read-on-server/read-on-server.ts`, exported only through the platform's `server.ts`. `types.ts` declares `ServerRead<T> = { status: 'ok'; data: T } | { status: 'not-found' | 'no-access' }`.
```ts
import 'server-only';
import { classifyError } from '@project/libs/error-handler';
import { isHttpError } from '@project/libs/http';
import { redirect } from 'next/navigation';
import { ROUTES } from '../../navigation';
import type { ServerRead } from './types';
export async function readOnServer<T>(
read: () => Promise<T>,
options: { returnTo?: string } = {},
): Promise<ServerRead<T>> {
try {
return { status: 'ok', data: await read() };
} catch (error) {
const outcome = classifyError(error).read;
if (outcome === 'not-found' || outcome === 'no-access') return { status: outcome };
if (options.returnTo && isHttpError(error) && error.status === 401) {
redirect(`${ROUTES.login}?redirect=${encodeURIComponent(options.returnTo)}`);
}
throw error;
}
}
```
`apps/<app>/src/app/(account)/orders/[id]/page.tsx`. `getOrder` is a cache, so the metadata and the page share one request, and the cache keeps a failure for the request too.
```tsx
import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { getDevice, getOrder, readOnServer } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { OrderDesktop } from './templates/order-desktop';
import { OrderMobile } from './templates/order-mobile';
type OrderPageProps = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: OrderPageProps): Promise<Metadata> {
const { id } = await params;
const order = await readOnServer(() => getOrder(id));
if (order.status !== 'ok') return { robots: { index: false } };
return { title: order.data.title };
}
export default async function OrderPage({ params }: OrderPageProps) {
const { id } = await params;
const [device, order] = await Promise.all([
getDevice(),
readOnServer(() => getOrder(id), { returnTo: `/orders/${id}` }),
]);
if (order.status === 'not-found') notFound();
if (order.status === 'no-access') return <StatusEmptyState variant="no-access" size="page" />;
return device === 'mobile' ? <OrderMobile order={order.data} /> : <OrderDesktop order={order.data} />;
}
```
A server part, `.../orders/[id]/organisms/order-invoice/OrderInvoice.tsx`:
```tsx
import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { getOrderInvoice, readOnServer } from '@project/<platform>/server';
import { InvoiceSummary } from './components/invoice-summary';
import type { OrderInvoiceProps } from './types';
export async function OrderInvoice({ orderId }: OrderInvoiceProps) {
const invoice = await readOnServer(() => getOrderInvoice(orderId));
if (invoice.status !== 'ok') return <StatusEmptyState variant={invoice.status} size="part" />;
return <InvoiceSummary invoice={invoice.data} />;
}
```
**Actions.** `showActionError` and `applyServerErrors`, with a login model and a mutation that use them: [code-patterns.md](code-patterns.md#validation-model-and-server-errors).

View File

@ -1,152 +0,0 @@
# Error handling
One model for every error, so each variant looks and behaves the same in every project: error boundaries at two sizes, API errors decided by status and by whether the request read data or ran an action, and one empty state. The decisions live in the error handler lib ([lib-error-handler.md](lib-error-handler.md)); this file says where each piece goes and what the user sees. The HTTP lib's `HttpError` and its codes are in [lib-http.md](lib-http.md#errors).
Contents: The model · What each failure shows · Boundaries · Reads · Actions · Empty states · B2C/B2B server · Reporting · Copy, accessibility, and i18n · Code · Definition of Done
## The model
```
1) Error boundary ─┬─> Whole app (EB-W)
└─> Section (EB-S): a page or a part
Fallback types ─┬─> Network: the API or the connection failed; retry helps
└─> Logic: a JavaScript bug; retry rarely helps; reported
2) API error ─┬─> 5xx ─┬─> Read ───> EB-X
│ └─> Action ─┐
└─> 4xx ─┬─> Action ─┴─> 1. Toast 2. Retry, by cause 3. Guide (the hint)
└─> Read ───> ES (404, 410, 403) | EB-X (the rest)
3) Empty state (ES)
```
- **EB-X** is the nearest boundary around the code that failed: the part's EB-S, else the page's EB-S, else EB-W.
- **EB-W** sits only at the app root, above the shell, and catches only what nothing below it caught. It replaces the whole app, so it is the last resort.
- **EB-S** has two sizes. A page-size EB-S sits inside the shell, so a failed page keeps the header, navigation, and breadcrumbs usable. A part-size EB-S (`PartBoundary`) wraps each part that loads on its own, so one failed part never takes down the page ([SKILL.md](../SKILL.md#3-architecture-rules)).
- **Read** means getting information: queries, server component reads, and the data a page loads. **Action** means a write the user started: a mutation or a feature action.
- Reads never toast. A failed read shows where its data would be, as an empty state or a fallback. Actions always toast, because the user is waiting for the result and the page they started from is still there.
- **Empty state** covers every "nothing to show" case: a successful response with no items, a filter with no matches, a 404 or 410, and a 403.
## What each failure shows
`classifyError` in the lib turns every error into these outcomes ([lib-error-handler.md](lib-error-handler.md#classification)).
| Failure | Read | Action |
|---|---|---|
| 5xx | EB-X, network fallback with Try again; reported | Toast with the support sentence and reference ID; Try again re-runs it when that is safe; reported |
| No response, timeout | EB-X, network fallback with Try again | Toast with the message and hint; Try again when safe |
| 404, 410 | ES `not-found` | Toast; Reload loads the latest data |
| 403 | ES `no-access` | Toast |
| 400, 422 | EB-X | Field errors, form alert, and toast; the user fixes and resubmits |
| 408 | EB-X, Try again | Toast; the form stays filled and submit is the retry |
| 409 | EB-X | Toast; Reload loads the latest data before the user tries again |
| 429 | EB-X | Toast whose hint says how long to wait; no button |
| 401 | Never reaches the UI: the HTTP lib refreshes, or a failed refresh logs out | Same |
| `ABORTED` | Nothing | Nothing |
| Logic error (a bug) | EB-X, logic fallback with Reload page and the reference ID; reported | Toast with the support sentence; reported |
| Success with no items | ES `no-data`, or `no-results` when filters or a search are active | Not an error |
- A failed refetch keeps the data on screen and shows nothing. Only a first load that fails reaches a boundary.
- "When safe" means the action can run twice without harm: an idempotent request (PUT, DELETE, or a POST with an idempotency key the back end honors), or a read-only step. Otherwise the toast has no button, the form keeps its values, and submitting again is the retry.
## Boundaries
| Boundary | Where |
|---|---|
| EB-W | `apps/<app>/src/app/global-error.tsx` |
| EB-S, page | `app/<route-group>/error.tsx` in every route group, and `not-found.tsx` at the root and in each group that calls `notFound()` |
| EB-S, part | `PartBoundary`, built with Next.js's `catchError` |
Every boundary renders the same `ErrorFallback`, which decides what the user sees:
1. It classifies the error. A `silent` read renders nothing: an `ABORTED` request, or a 401 whose logout redirect is already on its way.
2. `not-found` and `no-access` render the `StatusEmptyState` at the boundary's size.
3. Everything else renders island's `ErrorState`: the network fallback with Try again, or the logic fallback with Reload page. Both show the reference ID when there is one.
4. It calls `handleError` once, in an effect, so the error that stopped here is reported once.
Rules:
- Part boundaries use `catchError`, not island's `ErrorBoundary`: `catchError` lets `notFound()` and `redirect()` through, clears itself on client navigation, and its `retry()` renders server parts again on the server. It is a higher-order function, the one exception to "no HOCs in new code" next to React's `memo` and `lazy` ([design-patterns.md](design-patterns.md#react-and-javascript-patterns)).
- `global-error.tsx` replaces the root layout, so it has no providers and no styles: it renders its own `<html>` and `<body>`, imports `app.css` and the client i18n setup itself, and offers Reload page.
- Retry resets the failed queries first, then the boundary. Otherwise a query that threw keeps its error and throws again at once. There is no provider for this: `useQueryErrorResetBoundary()` returns the global reset.
- In a part boundary, an error with a `digest` came from the server, so Try again calls `retry()`. A browser-side error calls `reset()`, which re-renders without a server round trip.
- Put `PartBoundary` outside the part's `<Suspense>`, 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)).
## Reads
- `configs/react-query.ts` sets `throwOnError: (_error, query) => query.state.data === undefined`. A first load that fails throws to its boundary; a refetch that fails keeps the data and shows nothing. Parts guard only `isPending`, never `isError`, so no component has an error branch.
- `useSuspenseQuery` always throws on a failed first load, whatever `throwOnError` says, so it reaches the same boundary.
- `QueryCache.onError` calls `handleError(error, { where: 'refetch' })` only when the query still has data: that is the one place a failed refetch stops. A first load is handled by its fallback instead.
- Queries don't retry on their own (`retry: false`), because the HTTP lib already retried idempotent requests. The user retries from the fallback.
- `networkMode: 'offlineFirst'` for queries and mutations, so an offline request fails at once and shows the network fallback or toast, instead of pausing with a skeleton or spinner that never ends.
- A read whose 404 or 403 is an expected answer (a detail page, an order that may belong to someone else) needs no special code: the fallback turns it into the `not-found` or `no-access` empty state.
## Actions
- A form catches the action's error in `form.handleSubmit` and calls `applyServerErrors`. Anything else calls `showActionError` in its `catch` or in `useMutation`'s `onError`. Code: [code-patterns.md](code-patterns.md#validation-model-and-server-errors).
- `showActionError` is the one error toast: it calls `handleError`, returns early for `silent` errors, and shows `toast.error` with:
- the title: what failed, from the caller's `failedMessage`, naming the object ("Category 'Kitchenware' wasn't saved");
- the description: the error's message and hint (the guide), or, when there is neither (5xx, unknown, logic), one support sentence with the reference ID;
- a button from the retry kind: Try again for `again` when the caller passes `retry`, Reload for `reload` when the caller passes `reload`, and none for `wait`, `fix`, and `none`;
- `duration: Infinity`, an `id` built from `failedMessage` so a repeated failure replaces its toast instead of stacking, and `testId: 'action-error'`.
- `applyServerErrors` puts each server field error under its field and focuses the first, puts field errors for fields the form doesn't render (and whole-submission errors) in the form alert, and then calls `showActionError`. The form keeps every value.
- The caller passes `retry` only when running the action again is safe (see What each failure shows). Pass `reload` for actions on data that can change underneath the user (409, 404): it invalidates or refetches the affected queries, and the user tries again on fresh data.
- An action that runs inside `startTransition` catches its error inside the transition. An error thrown out of a transition goes to the nearest error boundary and replaces the part, which is wrong for an action.
- Uploads and multi-step flows keep a `failed` state in their reducer and also call `showActionError`, with a `retry` that starts the flow again with the same file ([design-patterns.md](design-patterns.md#adding-a-pattern)).
- Login and OTP requests send `skipRefresh: true`, and the back-end contract answers wrong credentials with 400 or 422 and field errors. So a 401 always means "no valid session", and the login form never triggers a refresh.
## Empty states
- island has one `EmptyState` molecule (`packages/island/src/molecules/empty-state/`) with the variants `no-data`, `no-results`, `not-found`, and `no-access`, and the sizes `part` and `page`. Each variant has its own illustration. It takes the title, description, and an optional action as props, so each use gives its own copy.
- Its sibling `ErrorState` molecule has the same sizes and slots, plus a `referenceId` line, for the fallbacks.
- `no-data` and `no-results` come from successful responses: the template renders them from the model's data, with feature copy and a primary action ("No categories yet. Create your first category to start organizing products." and "Create category"). `no-results` offers "Clear filters".
- `not-found` and `no-access` come from errors. The app's `StatusEmptyState` renders them with shared copy from the `errors` namespace; the page size adds a link to the home page.
- A list part that hides itself when empty, such as a related-products rail, may render nothing instead. Decide it in the plan, not per render.
## B2C/B2B server
Server reads classify on the server, because a Server Component error reaches the browser with only its digest.
- The page reads its main data through `readOnServer`, a server-only helper in the platform's `app/error-boundaries/`. It returns `{ status: 'ok', data }`, or `not-found` for 404 and 410 and `no-access` for 403, redirects a 401 to login with a return URL when the page passes `returnTo`, and rethrows the rest to the page's `error.tsx`.
- `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)).
- 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 `<meta name="robots" content="noindex" />`, so an error page is never indexed.
- `instrumentation.ts` configures the error handler for the server and calls `handleError` from `onRequestError` ([lib-error-handler.md](lib-error-handler.md#usage)).
## Reporting
- `handleError` runs once per error, where it stops: a fallback, `showActionError`, `QueryCache.onError`, or the server's `onRequestError`. Never call it in a repository, an action, or a `catch` that rethrows.
- It reports 5xx and logic errors only, with the request id and digest. 4xx, network, and timeout errors aren't bugs; the HTTP lib's breadcrumbs keep them visible next to a reported error.
- The bootstrap passes the Sentry integration's adapter as `report`. The adapter maps an `ErrorReport` to the vendor's event (tags: `where`, `status`, `code`; context: `requestId`, `digest`, `name`) and filters noise that isn't the app's bug, such as errors thrown by browser extensions.
- No failure events on the event emitter: events announce completed operations only ([design-patterns.md](design-patterns.md#not-used-here)).
## Copy, accessibility, and i18n
- Every fallback, empty state, and toast says what happened and what the user can do, following the copy rules in [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.
- 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 `<Toaster>` in the AppShell, with `dir` from the locale and its position on the logical end side (`bottom-right` in LTR, `bottom-left` in RTL).
## Code
The boundaries, `ErrorFallback`, `readOnServer`, and the query client's error settings are in [error-handling-code.md](error-handling-code.md). Read it only when you build or change one of them.
## Definition of Done
```
[ ] The app has EB-W; every page and every part that loads on its own has an EB-S, and every boundary renders ErrorFallback
[ ] Reads never toast: 404 and 410 show the not-found empty state, 403 no-access, and other failures their boundary's fallback
[ ] A failed refetch keeps its data; no component has an isError branch
[ ] Every failed action shows the action-error toast with its hint or the support sentence and reference ID; the form keeps its values
[ ] Server field errors sit under their rendered fields and the rest in the form alert
[ ] Retry follows the retry kind: again only when safe, reload for 409 and 404, a wait hint for 429, fix and resubmit for other 4xx
[ ] ABORTED and 401 never show anything
[ ] Successful empty responses show the no-data or no-results empty state with a next step
[ ] handleError runs once per error, where it stops; 5xx and logic errors reach the tracker with requestId or digest
[ ] Server reads go through readOnServer; error pages and no-access pages are noindex
```

View File

@ -1,109 +0,0 @@
# Cookie lib (`packages/libs/src/cookie`)
One small `CookieAdapter` class over `document.cookie`: get, set, and remove with encoding, safe defaults (`path=/`, `SameSite=Lax`, `Secure`), and per-call options. Browser only; framework-agnostic; no dependency (no js-cookie).
Contents: What cookies are for · Structure · Types · API · Keys · Browser only · Server side · Usage · Acceptance checklist
## What cookies are for
- Only small values the server must see on the request: `locale`, `theme`, and device preference (so the server renders the right version without a flash), and the consent choice.
- Every cookie is sent with every request to its domain and path and holds about 4 KB. Anything the server doesn't need goes to local storage ([lib-local-storage.md](lib-local-storage.md)).
- Never auth tokens. Auth cookies are `HttpOnly`, set and rotated by the server, and JavaScript can't and mustn't read them (see [lib-http.md](lib-http.md), Refresh token). Never secrets or personal data.
## Structure
```
packages/libs/src/cookie/
├── cookie.ts # CookieAdapter class and the shared `cookie` instance
├── types.ts # CookieAdapterAbstraction, CookieOptions
├── constants.ts # DEFAULT_COOKIE_OPTIONS
└── index.ts
```
- `index.ts` exports `CookieAdapter`, `cookie`, `DEFAULT_COOKIE_OPTIONS`, and the types `CookieAdapterAbstraction` and `CookieOptions`. Nothing goes in `server.ts`: the lib is browser-only.
- Import by subpath: `import { cookie } from '@project/libs/cookie'`.
## Types
```ts
interface CookieOptions {
path?: string; // default '/'
domain?: string; // default: none (current host only); set it to share with subdomains, e.g. '.example.com'
maxAgeDays?: number; // lifetime in days; omit for a session cookie
sameSite?: 'Strict' | 'Lax' | 'None'; // default 'Lax'
secure?: boolean; // default true; forced to true when sameSite is 'None'
}
interface CookieAdapterAbstraction {
get(key: string): string | null;
set(key: string, value: string, options?: CookieOptions): void;
remove(key: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void;
}
```
## API
- `get(key)` returns the decoded value, or `null` when the cookie doesn't exist. It finds the `encodeURIComponent(key)=` entry in `document.cookie` split by `'; '` and decodes the rest, so values containing `=` stay whole. A value with broken percent-encoding (written by other code) is returned raw instead of throwing.
- `set(key, value, options?)` writes `key=value` with `encodeURIComponent` on both, plus the attributes:
- Options merge in this order: `DEFAULT_COOKIE_OPTIONS` → `configure` defaults → call options.
- `maxAgeDays` becomes `max-age` in seconds (`Math.floor(days * 24 * 60 * 60)`); without it the cookie is a session cookie.
- `sameSite: 'None'` always adds `Secure`, because browsers reject it otherwise.
- `remove(key, options?)` writes the cookie empty with `max-age=0`. It must use the same `path` and `domain` the cookie was set with, or the browser keeps the original. Defaults come from `configure`, so keep them the same for set and remove.
- `configure(defaults: CookieOptions)` sets the defaults once, in the app's bootstrap. It only stores options and never touches `document`, so it's safe in `bootstrap.client.ts` during SSR. For example, `cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE })`, from the app's env, lets local development over plain `http` on a non-localhost host turn `Secure` off.
- There is no public mutable `options` property: on a shared instance, any code could change every other caller's cookies at any time. Per-call differences go in the call's options.
- The shared instance is `export const cookie = new CookieAdapter();`. Create another `CookieAdapter` only in tests.
## Keys
- Cookie names are constants in the owning project's `constants.ts` (`LOCALE_COOKIE`, `THEME_COOKIE`), never string literals at call sites.
- Names are a contract with the server: `proxy.ts`, Server Components, and the back end read the same names, so renaming one is a breaking change.
- Names are not prefixed automatically (unlike local-storage keys), because the server reads them by their exact name.
## Browser only
- Every method except `configure` checks `typeof document === 'undefined'` and throws a clear error ("cookie is browser-only; on the server read cookies with next/headers") instead of the unclear "document is not defined".
- Call it only in event handlers, effects, actions, and client bootstrap code. Never during render and never at module top level: client components also render on the server, and a value read during render differs between server and browser, which breaks hydration.
## Server side
- Server code reads cookies with `cookies()` from `next/headers` (Server Components, Route Handlers, Server Functions) or `request.cookies` in `proxy.ts`, inside the app or platform. The lib never imports Next.js.
- Server Components can't set cookies. Set them in `proxy.ts`, a Route Handler, or a Server Function on the server, or with `cookie.set` in the browser.
- A value the page needs while rendering (theme) is read on the server and passed down as a prop. The browser writes it with `cookie.set` when the user changes it, then refreshes or updates the UI.
## Usage
Bootstrap (`bootstrap.client.ts`):
```ts
cookie.configure({ secure: clientEnv.NEXT_PUBLIC_COOKIE_SECURE });
```
`features/preferences/actions/change-theme/actions.ts`
```ts
import { cookie } from '@project/libs/cookie';
import { usePreferencesStore } from '../../../../stores/preferences';
import { THEME_COOKIE, THEME_COOKIE_MAX_AGE_DAYS } from '../../constants';
import type { Theme } from '../../entities/theme';
export function changeTheme(theme: Theme): 'ok' {
cookie.set(THEME_COOKIE, theme, { maxAgeDays: THEME_COOKIE_MAX_AGE_DAYS });
usePreferencesStore.getState().setTheme(theme);
return 'ok';
}
```
## Acceptance checklist
For building or changing the lib:
```
[ ] set, get, and remove round-trip a value, including values with "=", ";", spaces, and non-Latin text (e.g. Persian)
[ ] get returns null for a missing cookie and doesn't match a cookie whose name only starts with the key ("theme" vs "theme-v2")
[ ] A value with broken percent-encoding is returned raw, not thrown
[ ] maxAgeDays writes the right max-age; no maxAgeDays writes a session cookie
[ ] sameSite 'None' always writes Secure
[ ] Call options win over configure defaults, which win over DEFAULT_COOKIE_OPTIONS
[ ] remove with the configured path and domain deletes the cookie
[ ] get, set, and remove throw the clear browser-only error on the server; configure doesn't
```

View File

@ -1,279 +0,0 @@
# Env lib (`packages/libs/src/env`)
Validates the app's environment variables and gives apps typed, read-only values. `createClientEnv` validates the public variables and is safe on both sides; `createServerEnv` validates the server variables and runs only on the server. Built on @t3-oss/env-core with valibot schemas. Framework-agnostic: the app passes its prefix and its runtime values, so the lib never reads `process.env` itself.
Only apps call it. Every other project gets its values from the app's bootstrap through its own `env/` (`setEnv` and `getEnv`), so no project below the app reads the environment.
Contents: Structure · Types · API · Validation · The app's env · Project env · Bootstrap · Implementation · Usage · Acceptance checklist
## Structure
```
packages/libs/src/env/
├── env.client.ts # createClientEnv, and the error formatter both functions use
├── env.server.ts # createServerEnv; starts with import 'server-only'
├── types.ts # EnvSchema, EnvValues, ClientEnvOptions, ServerEnvOptions
├── index.ts # createClientEnv and the types
└── server.ts # import 'server-only'; createServerEnv
```
- The project's `src/server.ts` re-exports `createServerEnv` by name.
- Import by subpath: `import { createClientEnv } from '@project/libs/env'` and `import { createServerEnv } from '@project/libs/env/server'`.
## Types
```ts
import type { StandardSchemaDictionary } from '@t3-oss/env-core';
export type EnvSchema = StandardSchemaDictionary; // variable name → valibot schema
export type EnvValues<TSchema extends EnvSchema> = Readonly<StandardSchemaDictionary.InferOutput<TSchema>>;
export type ClientEnvOptions<TPrefix extends string, TSchema extends EnvSchema> = {
prefix: TPrefix; // 'NEXT_PUBLIC_'
schema: TSchema & {
[TKey in keyof TSchema]: TKey extends `${TPrefix}${string}` ? TSchema[TKey] : `${TKey & string} must start with ${TPrefix}`;
};
runtimeEnv: NoInfer<Record<keyof TSchema, string | undefined>>; // every declared variable, each read literally
};
export type ServerEnvOptions<TSchema extends EnvSchema> = {
schema: TSchema;
runtimeEnv: Record<string, string | undefined>; // process.env
skipValidation?: boolean; // only for steps that run without the real env (see Validation)
};
```
## API
- `createClientEnv(options)` returns `EnvValues<TSchema>`.
- Every variable name must start with `prefix`. A name that doesn't is a type error: `API_SECRET must start with NEXT_PUBLIC_`.
- `runtimeEnv` lists every declared variable with a literal reference, `NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL`, because bundlers inline only literal references and the browser has no real `process.env`. Leaving one out is a type error.
- It has no `skipValidation`: public variables are inlined when the app is built, so they must be present at build time anyway.
- `createServerEnv(options)` returns `EnvValues<TSchema>`. It is server-only, so a client import fails the build, and it reads `runtimeEnv: process.env` at runtime.
- Both:
- Empty strings count as missing (`emptyStringAsUndefined`), so `API_URL=` in a `.env` file fails instead of passing as `''`, and an optional variable gets its default.
- The values are the schema outputs, so defaults and transforms apply: `v.optional(v.pipe(v.string(), v.transform(Number), v.integer()), '24')` gives the number `24`.
- On failure they throw one `Error` that lists every invalid variable and why:
```
Invalid environment variables:
- NEXT_PUBLIC_API_URL: Invalid URL: Received "not-a-url"
- NEXT_PUBLIC_CDN_URL: Invalid type: Expected string but received undefined
```
- The result is read-only, and reading an undeclared variable is a type error.
## Validation
- Validation runs when the app's env module first loads. Both bootstraps import it first, so a bad variable stops the app with one clear error before any page renders.
- Next.js: to fail the build instead, load `env/env.client.ts` from `next.config.ts` (with jiti when the config can't resolve it). Never load `env.server.ts` there: `server-only` throws outside the React server graph.
- `skipValidation` (server env only) is for steps that run without the real env: lint, type-check, and a Docker image build without runtime secrets. The app sets it from a flag (`SKIP_ENV_VALIDATION=true`). Skipped validation returns the raw strings without defaults or transforms, so a running app never sets it.
- Messages come from the schemas, and valibot's default messages repeat the received value. Give every secret's schema its own message (`v.minLength(32, 'Use at least 32 characters')`), and never log env values.
## The app's env
```
apps/<app>/src/env/
├── env.client.ts # public variables: export const clientEnv = createClientEnv({ ... })
├── env.server.ts # server variables: export const serverEnv = createServerEnv({ ... }); import 'server-only'
├── index.ts # clientEnv
└── server.ts # import 'server-only'; serverEnv
```
- These files are the only code in the repo that reads `process.env`.
- App code (bootstrap, configs) reads `clientEnv` and `serverEnv` directly. Only server code imports `../env/server`.
## Project env
Every project except apps that reads env has:
```
<project>/src/env/
├── env.ts # setEnv and getEnv, for this project's values only
├── types.ts # the project's env type, e.g. IslandEnv
└── index.ts
```
- `setEnv(env)` stores the project's values. `getEnv()` returns them, and throws a clear error when called before `setEnv`.
- The type uses the project's own names (`cdnUrl`, `catalogApiUrl`), not variable names. The bootstrap maps one to the other, so renaming a variable only touches the app.
- Read `getEnv()` inside functions, never at module top level, because bootstrap may not have run yet: `baseUrl: () => getEnv().catalogApiUrl`.
- The project never imports the app or reads the raw environment, so the dependency graph stays acyclic.
- Libs have no project env; they never read env. The bootstrap passes their settings through `configure`: `http.configure({ baseUrl })`, `configureServerHttp({ baseUrl, getCookieHeader })`, `cookie.configure({ secure })`.
## Bootstrap
- The app's bootstrap calls each project's `setEnv` at startup with the values that project needs. Bootstraps are idempotent, so `setEnv` may run again with the same values.
- Every project exports the same names, so import each under its project's name: `import { setEnv as setIslandEnv } from '@project/island/env'`.
- The server module graph and the client module graph each hold their own copy of every project env.
- `bootstrap.server.ts` fills the server copy. It may pass server-side values, such as an internal service address.
- `bootstrap.client.ts` fills the client copy, with public values only.
- Both must provide every field of a project's env type, so a project env never holds a secret. A secret stays in the app's `serverEnv`, and only the app's server code uses it (for example a header in `configureServerHttp`).
## Implementation
`env.client.ts`
```ts
import { createEnv, type StandardSchemaV1 } from '@t3-oss/env-core';
import type { ClientEnvOptions, EnvSchema, EnvValues } from './types';
export function throwInvalidEnv(issues: readonly StandardSchemaV1.Issue[]): never {
const lines = issues.map((issue) => {
const name = issue.path?.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.');
return `- ${name ?? 'env'}: ${issue.message}`;
});
throw new Error(`Invalid environment variables:\n${lines.join('\n')}`);
}
export function createClientEnv<const TPrefix extends string, TSchema extends EnvSchema>(
options: ClientEnvOptions<TPrefix, TSchema>,
): EnvValues<TSchema> {
return createEnv<string, {}, EnvSchema>({
clientPrefix: options.prefix,
client: options.schema,
// env-core deletes empty strings from the object it gets, so it gets a copy
runtimeEnvStrict: { ...options.runtimeEnv },
emptyStringAsUndefined: true,
onValidationError: throwInvalidEnv,
}) as EnvValues<TSchema>;
}
```
`env.server.ts`
```ts
import 'server-only';
import { createEnv } from '@t3-oss/env-core';
import { throwInvalidEnv } from './env.client';
import type { EnvSchema, EnvValues, ServerEnvOptions } from './types';
export function createServerEnv<TSchema extends EnvSchema>(options: ServerEnvOptions<TSchema>): EnvValues<TSchema> {
return createEnv<undefined, EnvSchema>({
server: options.schema,
// env-core deletes empty strings from the object it gets, so process.env gets a copy
runtimeEnv: { ...options.runtimeEnv },
isServer: true,
emptyStringAsUndefined: true,
skipValidation: options.skipValidation ?? false,
onValidationError: throwInvalidEnv,
}) as EnvValues<TSchema>;
}
```
The explicit type arguments on `createEnv` are needed, because env-core's option types can't be checked against a generic schema. Call sites stay fully typed through `ClientEnvOptions` and `ServerEnvOptions`.
## Usage
`apps/<app>/src/env/env.client.ts`
```ts
import { createClientEnv } from '@project/libs/env';
import * as v from 'valibot';
export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_',
schema: {
NEXT_PUBLIC_API_URL: v.pipe(v.string(), v.url()),
NEXT_PUBLIC_CDN_URL: v.pipe(v.string(), v.url()),
NEXT_PUBLIC_CATALOG_API_URL: v.pipe(v.string(), v.url()),
},
runtimeEnv: {
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
NEXT_PUBLIC_CDN_URL: process.env.NEXT_PUBLIC_CDN_URL,
NEXT_PUBLIC_CATALOG_API_URL: process.env.NEXT_PUBLIC_CATALOG_API_URL,
},
});
```
`apps/<app>/src/env/env.server.ts`
```ts
import 'server-only';
import { createServerEnv } from '@project/libs/env/server';
import * as v from 'valibot';
export const serverEnv = createServerEnv({
schema: {
API_INTERNAL_URL: v.pipe(v.string(), v.url()),
CATALOG_API_INTERNAL_URL: v.pipe(v.string(), v.url()),
},
runtimeEnv: process.env,
skipValidation: process.env.SKIP_ENV_VALIDATION === 'true',
});
```
`packages/island/src/env/env.ts`. `types.ts` declares `IslandEnv`, and `index.ts` exports both functions and the type.
```ts
import type { IslandEnv } from './types';
let islandEnv: IslandEnv | undefined;
export function setEnv(env: IslandEnv): void {
islandEnv = env;
}
export function getEnv(): Readonly<IslandEnv> {
if (!islandEnv) {
throw new Error('island env is not set. The app bootstrap must call setEnv from @project/island/env first.');
}
return islandEnv;
}
```
`apps/<app>/src/bootstrap/bootstrap.server.ts`
```ts
import 'server-only';
import { setEnv as setIslandEnv } from '@project/island/env';
import { configureServerHttp } from '@project/libs/server';
import { setEnv as setPlatformEnv } from '@project/<platform>/env';
import { cookies } from 'next/headers';
import { clientEnv } from '../env';
import { serverEnv } from '../env/server';
setIslandEnv({ cdnUrl: clientEnv.NEXT_PUBLIC_CDN_URL });
setPlatformEnv({ catalogApiUrl: serverEnv.CATALOG_API_INTERNAL_URL });
configureServerHttp({
baseUrl: serverEnv.API_INTERNAL_URL,
getCookieHeader: async () => (await cookies()).toString(),
});
```
`apps/<app>/src/bootstrap/bootstrap.client.ts`. It also turns on refresh and registers the shared interceptors (see [lib-http.md](lib-http.md#usage)).
```ts
import { setEnv as setIslandEnv } from '@project/island/env';
import { http } from '@project/libs/http';
import { setEnv as setPlatformEnv } from '@project/<platform>/env';
import { clientEnv } from '../env';
setIslandEnv({ cdnUrl: clientEnv.NEXT_PUBLIC_CDN_URL });
setPlatformEnv({ catalogApiUrl: clientEnv.NEXT_PUBLIC_CATALOG_API_URL });
http.configure({ baseUrl: clientEnv.NEXT_PUBLIC_API_URL });
```
`platforms/<app>/src/features/catalog/http.ts` reads the platform's env. The server copy holds the internal address and the client copy the public one.
```ts
import { http } from '@project/libs/http';
import { getEnv } from '../../env';
export const catalogHttp = http.extend({ baseUrl: () => getEnv().catalogApiUrl });
```
## Acceptance checklist
For building or changing the lib:
```
[ ] createClientEnv and createServerEnv return typed, read-only values; defaults and transforms apply
[ ] A public variable without the prefix, or a declared variable missing from runtimeEnv, is a type error
[ ] A missing, empty, or invalid variable throws one Error that lists every invalid variable and why
[ ] Importing @project/libs/env/server outside the React server graph throws (server-only), so a client import fails the build
[ ] process.env is unchanged after createServerEnv runs
[ ] skipValidation returns the raw values without validating
[ ] A project's getEnv throws the clear error before setEnv and returns the values after it
[ ] No process.env outside the app's env/ files
```

View File

@ -1,240 +0,0 @@
# Error handler lib (`packages/libs/src/error-handler`)
Four functions that every project uses to decide what an error shows, what it says, and whether it is reported: `configureErrorHandler`, `classifyError`, `describeError`, and `handleError`. The model they implement (error boundaries, API errors by status, empty states) is in [error-handling.md](error-handling.md).
It is framework-agnostic (no React, Next.js, TanStack, i18next, or sonner imports), runs in the browser and on the server, and has no dependency. It imports only `isHttpError` from the HTTP lib ([lib-http.md](lib-http.md#errors)). It never shows anything: boundaries, empty states, and toasts live in the apps and platforms.
Contents: Structure · Types · API · Classification · Messages and reference ID · Reporting · Implementation · Usage · Acceptance checklist
## Structure
```
packages/libs/src/error-handler/
├── error-handler.ts # configureErrorHandler, classifyError, describeError, handleError
├── types.ts # ErrorClass and its unions, ErrorContext, ErrorReport, ErrorHandlerConfig, TranslateFn, ErrorDescription
├── constants.ts # NOT_FOUND_STATUSES, LIB_MESSAGE_PREFIX, RETRY_AFTER_HINT_KEY
└── index.ts
```
- `index.ts` exports the four functions and the types. Nothing goes in `server.ts`: the lib has no server-only capability, so both sides import it from `index.ts`.
- Import by subpath: `import { classifyError } from '@project/libs/error-handler'`.
## Types
```ts
type ErrorCause = 'network' | 'logic'; // network: the API or the connection failed, retry helps; logic: a bug, retry rarely helps
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';
interface ErrorClass {
cause: ErrorCause;
read: ReadOutcome;
action: ActionOutcome;
retry: RetryKind;
report: boolean; // true for 5xx and logic errors
}
type ErrorWhere = 'app' | 'page' | 'part' | 'action' | 'refetch' | 'server';
interface ErrorContext {
where: ErrorWhere; // where the error stopped
name?: string; // the part, action, or route, e.g. 'order-invoice'; never personal data
}
interface ErrorReport extends Partial<ErrorContext> {
error: unknown;
status?: number;
code?: string;
requestId?: string;
digest?: string; // Next.js's id for a server error
}
interface ErrorHandlerConfig {
report?: (report: ErrorReport) => void; // the error-tracking integration's adapter
onForbidden?: () => void; // runs on every 403 that handleError handles
}
type TranslateFn = (key: string, options?: Record<string, unknown>) => string; // i18next's t fits
interface ErrorDescription {
message?: string; // what went wrong, only when the user can understand it
hint?: string; // how to fix it: the guide
referenceId?: string; // requestId, or the server digest
}
```
## API
- `configureErrorHandler(config)`: once per module graph, in the app's browser bootstrap (`bootstrap.client.ts`) and in `instrumentation.ts`'s `register()` for the server. It merges `config` into the stored settings, so calling it again is safe. Libs never read env; the bootstrap passes everything in.
- `classifyError(error): ErrorClass`: pure. It decides from the status first, then the code (table below). Anything that isn't an `HttpError` is a logic error, except a server error that reached the browser with only its `digest`.
- `describeError(error, t): ErrorDescription`: the words for a toast or a fallback. Only strings that start with `errors:` go through `t`: those are the keys the HTTP lib creates. Server messages and hints arrive translated and pass through as they are.
- `handleError(error, context?): ErrorClass`: call it once, where the error stops (the fallback that renders it, the toast that shows it, the refetch that swallows it, or the server's `onRequestError`). It classifies the error, sends a report when `report` is true, runs `onForbidden` on a 403, and returns the class. It never throws: a failing reporter or callback is swallowed, so handling an error never causes a second one.
## Classification
The first matching row wins.
| Error | `cause` | `read` | `action` | `retry` | `report` |
|---|---|---|---|---|---|
| `ABORTED` | network | silent | silent | none | no |
| 401 | network | silent | silent | none | no |
| 403 | network | no-access | toast | none | no |
| 404, 410 | network | not-found | toast | reload | no |
| 409 | network | boundary | toast | reload | no |
| 429 | network | boundary | toast | wait | no |
| 5xx | network | boundary | toast | again | yes |
| Other 4xx (400, 408, 422, …) | network | boundary | toast | fix | no |
| `NETWORK_ERROR`, `TIMEOUT` | network | boundary | toast | again | no |
| `PARSE_ERROR`, `INTERCEPTOR_ERROR`, `UNKNOWN` | logic | boundary | toast | none | yes |
| Not an `HttpError`, 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, so server code checks for 401 itself and redirects to login ([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.
## 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.
- `hint` is the error's hint. When there is none and the error has `retryAfter`, it is `t('errors:http.retry-after', { seconds })`.
- `referenceId` is `requestId`, or the `digest` when there is no request id. Support finds the report by either.
## Reporting
- Reports go only to the `report` callback that the bootstrap passes in, never to an event on the event emitter.
- `report` is true for 5xx and logic errors. 4xx, network, and timeout failures are the user's or the connection's, so they aren't reported; the HTTP lib's breadcrumbs keep them visible in the tracker when a reported error follows.
- An `ErrorReport` carries the error, the context, and the status, code, request id, and digest, so the tracker can group by status and code and search by reference ID. It never carries form values, cookies, or headers.
## Implementation
`error-handler.ts`, the parts that decide. `constants.ts` holds `NOT_FOUND_STATUSES: readonly number[] = [404, 410]`, `LIB_MESSAGE_PREFIX = 'errors:'`, and `RETRY_AFTER_HINT_KEY = 'errors:http.retry-after'`.
```ts
import { isHttpError } from '../http';
import { LIB_MESSAGE_PREFIX, NOT_FOUND_STATUSES, RETRY_AFTER_HINT_KEY } from './constants';
import type {
ErrorClass,
ErrorContext,
ErrorDescription,
ErrorHandlerConfig,
ReadOutcome,
RetryKind,
TranslateFn,
} from './types';
let config: ErrorHandlerConfig = {};
export function configureErrorHandler(next: ErrorHandlerConfig): void {
config = { ...config, ...next };
}
const SILENT: ErrorClass = { cause: 'network', read: 'silent', action: 'silent', retry: 'none', report: false };
const LOGIC: ErrorClass = { cause: 'logic', read: 'boundary', action: 'toast', retry: 'none', report: true };
function apiError(read: ReadOutcome, retry: RetryKind, report = false): ErrorClass {
return { cause: 'network', read, action: 'toast', retry, report };
}
function getDigest(error: unknown): string | undefined {
if (typeof error !== 'object' || error === null || !('digest' in error)) return undefined;
return typeof error.digest === 'string' ? error.digest : undefined;
}
export function classifyError(error: unknown): ErrorClass {
if (!isHttpError(error)) return getDigest(error) ? apiError('boundary', 'again') : LOGIC;
const { status, code } = error;
if (code === 'ABORTED' || status === 401) return SILENT;
if (status === 403) return apiError('no-access', 'none');
if (NOT_FOUND_STATUSES.includes(status)) return apiError('not-found', 'reload');
if (status === 409) return apiError('boundary', 'reload');
if (status === 429) return apiError('boundary', 'wait');
if (status >= 500) return apiError('boundary', 'again', true);
if (status >= 400) return apiError('boundary', 'fix');
if (code === 'NETWORK_ERROR' || code === 'TIMEOUT') return apiError('boundary', 'again');
return LOGIC;
}
export function describeError(error: unknown, t: TranslateFn): ErrorDescription {
if (!isHttpError(error)) return { referenceId: getDigest(error) };
const translate = (text?: string) => (text?.startsWith(LIB_MESSAGE_PREFIX) ? t(text) : text);
const isUserFacing =
(error.status >= 400 && error.status < 500) || error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT';
return {
message: isUserFacing ? translate(error.message) : undefined,
hint:
translate(error.hint) ??
(error.retryAfter ? t(RETRY_AFTER_HINT_KEY, { seconds: error.retryAfter }) : undefined),
referenceId: error.requestId ?? getDigest(error),
};
}
export function handleError(error: unknown, context?: ErrorContext): ErrorClass {
const errorClass = classifyError(error);
try {
if (errorClass.report) {
config.report?.({
...context,
error,
status: isHttpError(error) ? error.status : undefined,
code: isHttpError(error) ? error.code : undefined,
requestId: isHttpError(error) ? error.requestId : undefined,
digest: getDigest(error),
});
}
if (isHttpError(error) && error.status === 403) config.onForbidden?.();
} catch {
// Handling an error must never throw a second one.
}
return errorClass;
}
```
- `config` is startup configuration, set by the bootstrap, so module scope is allowed to hold it on the server ([design-patterns.md](design-patterns.md#how-to-choose)). It never holds errors or anything per request.
- On the server, `onRequestError` sees the real `HttpError`, with the digest Next.js gave it, so the report has both ids and matches what the browser shows.
## Usage
Browser bootstrap (`bootstrap.client.ts`). The Sentry integration adapts `ErrorReport` to its vendor's event.
```ts
import { captureError } from '@project/integrations/sentry';
import { configureErrorHandler } from '@project/libs/error-handler';
configureErrorHandler({ report: captureError });
```
Server, `apps/<app>/src/instrumentation.ts`. `register()` runs once when the server starts, and `onRequestError` runs for every error that no server code caught.
```ts
import { captureServerError } from '@project/integrations/server';
import { configureErrorHandler, handleError } from '@project/libs/error-handler';
import type { Instrumentation } from 'next';
export function register(): void {
configureErrorHandler({ report: captureServerError });
}
export const onRequestError: Instrumentation.onRequestError = (error, _request, context) => {
handleError(error, { where: 'server', name: context.routePath });
};
```
Where the other calls go, with code, is in [error-handling.md](error-handling-code.md): `ErrorFallback` classifies, describes, and handles what reaches a boundary; `showActionError` does the same for actions; the query client's `QueryCache.onError` handles failed refetches.
## Acceptance checklist
For building or changing the lib:
```
[ ] Every row of the classification table returns its class, with status checked before code
[ ] ABORTED and 401 are silent for reads and actions; 403 runs onForbidden once per handleError call
[ ] A plain Error is a reported logic error; an object with only a digest is a network error that isn't reported
[ ] describeError translates only errors:-prefixed strings; server messages pass through unchanged
[ ] describeError leaves out the message for 5xx and logic errors and keeps it for 4xx, network, and timeout
[ ] A 429 or 503 with retryAfter and no hint gets the retry-after hint with its seconds
[ ] referenceId is requestId, else digest
[ ] handleError reports 5xx and logic errors with status, code, requestId, and digest, and nothing else
[ ] handleError never throws, even when report or onForbidden throws
[ ] The lib imports nothing but the HTTP lib: no React, Next.js, TanStack, i18next, or sonner
```

View File

@ -1,362 +0,0 @@
# HTTP lib (`packages/libs/src/http`)
The only way code talks to the network. One `HttpClient` class handles requests (GET, POST, PUT, PATCH, DELETE), file upload and download, request and response interceptors, retry, automatic refresh on 401, abort, and one normalized `HttpError`.
It is framework-agnostic (no React, Next.js, TanStack, i18next, sonner, or zustand imports), runs in the browser and on the server, and is built on native `fetch`, `AbortController`, `AbortSignal.any`, `AbortSignal.timeout`, and `XMLHttpRequest` (uploads only). No axios, ky, or other dependency.
Contents: Structure · Types · API · Root and feature clients · Request pipeline · Body and params · Interceptors · Retry · Refresh token · Abort · Files · Errors · Server side · Usage · Acceptance checklist
## Structure
```
packages/libs/src/http/
├── http-client.ts # HttpClient: config, verbs, request pipeline, extend, abortAll
├── http.ts # the root `http` instance and the createHttpClient factory
├── http-error.ts # HttpError, isHttpError, and normalization of anything thrown or returned
├── interceptors.ts # InterceptorManager; use() returns an eject function
├── retry.ts # shouldRetry, backoff with jitter and Retry-After
├── refresh.ts # single-flight refresh coordinator
├── body.ts # body and query serialization, response parsing
├── upload.ts # XMLHttpRequest transport with upload progress
├── server-http.ts # configureServerHttp; exported only from src/server.ts
├── types.ts
├── constants.ts # defaults, HTTP_ERROR_CODES, header names
└── index.ts
```
- `index.ts` exports `HttpClient`, `createHttpClient`, `http`, `HttpError`, `isHttpError`, `HTTP_ERROR_CODES`, and the types (`HttpClientConfig`, `FeatureHttpConfig`, `RequestOptions`, `HttpResponse`, `UploadOptions`, `UploadProgress`, `DownloadResult`, `RetryConfig`, `RefreshConfig`, `RequestInterceptor`, `ResponseInterceptor`, `ErrorInterceptor`, `HttpErrorCode`).
- `server.ts` exports `configureServerHttp`.
- Import by subpath: `import { http } from '@project/libs/http'` and `import { configureServerHttp } from '@project/libs/server'`.
## Types
A sketch. The implementation may add fields but keeps these names and meanings.
```ts
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
interface HttpClientConfig {
baseUrl: string | (() => string); // a function is read on each request, so env is never read at module load
headers?: Record<string, string>;
timeout?: number | false; // ms per attempt, default 15_000
credentials?: RequestCredentials; // default 'include' (auth is cookie-based)
retry?: RetryConfig | false; // default: enabled with the defaults below
refresh?: RefreshConfig | false; // default: false until bootstrap sets it
getCookieHeader?: () => string | Promise<string>; // server only, set through configureServerHttp
mapErrorBody?: (body: unknown, response: Response) => Partial<HttpErrorShape>; // adapts the back end's error contract
}
interface RetryConfig {
attempts: number; // retries after the first try, default 2 (3 tries at most)
methods: HttpMethod[]; // default ['GET', 'HEAD', 'OPTIONS']
statuses: number[]; // default [408, 429, 502, 503, 504]
networkErrors: boolean; // default true (no response)
baseDelay: number; // default 300 ms
maxDelay: number; // default 5_000 ms
}
interface RefreshConfig {
endpoint: string; // relative to baseUrl or absolute, e.g. '/auth/refresh'
method?: 'POST' | 'GET'; // default 'POST'
shouldRefresh?: (error: HttpError) => boolean; // default: error.status === 401
onFailure?: () => void; // called once per failed refresh, e.g. emit the logout event
}
// What a feature may set in http.extend(). Auth settings are left out, so a feature cannot break them.
type FeatureHttpConfig = Omit<Partial<HttpClientConfig>, 'refresh' | 'credentials' | 'getCookieHeader' | 'retry'> & {
retry?: Partial<RetryConfig> | false; // merged field by field over the root's retry
};
interface RequestOptions {
params?: Record<string, QueryValue | QueryValue[] | null | undefined>;
headers?: Record<string, string>;
signal?: AbortSignal;
timeout?: number | false;
retry?: Partial<RetryConfig> | boolean; // false disables; true or an object opts in (see Retry)
skipRefresh?: boolean; // this request never triggers a refresh
responseType?: 'auto' | 'json' | 'text' | 'blob' | 'arrayBuffer'; // default 'auto'
init?: Omit<RequestInit, 'body' | 'method' | 'headers' | 'signal'>; // passthrough, e.g. keepalive or priority; never Next.js caching options
}
interface HttpResponse<T> {
data: T;
status: number;
headers: Headers;
requestId: string;
}
interface HttpErrorShape {
code: HttpErrorCode | string; // the server's code wins when the body has one
message: string;
status: number; // 0 when there was no response (network, timeout, abort)
fieldErrors?: Record<string, string>; // field path → message, e.g. { 'address.city': '...' }
hint?: string; // how the user can fix it
requestId?: string;
retryAfter?: number; // seconds, from Retry-After on 429 and 503
}
```
## API
- Verbs resolve with the parsed body, typed by the caller (the repository passes its `*ResponseDto`): `get<T>(url, options?)`, `delete<T>(url, options?)`, `post<T>(url, body?, options?)`, `put<T>(url, body?, options?)`, `patch<T>(url, body?, options?)`.
- `request<T>({ method, url, body, ...options })` resolves with `HttpResponse<T>`, for when the caller needs the status, headers, or request id (pagination headers, HEAD requests).
- `upload<T>(url, input, options?)` and `download(url, options?)`: see Files.
- `interceptors.request.use(fn)` and `interceptors.response.use(onSuccess?, onError?)` both return an eject function.
- `configure(partial)`: root client only, at bootstrap (for example to set `baseUrl` and `refresh`). Never after the app has started.
- `extend(config: FeatureHttpConfig)`: returns a feature client. It reads the root's config live (settings made later in bootstrap still apply), runs the root's interceptors before its own, and shares the root's refresh coordinator and abort-all controller.
- `abortAll(reason?)`: browser only. On the root it aborts every in-flight request of every feature (logout); on a feature client, only that feature's requests (leaving its page). New requests work right after.
## Root and feature clients
- **Root:** `http` is created once in `http.ts` with retry on with defaults and refresh off. The app's bootstrap sets its `baseUrl` from the app's env (libs never read env, see [lib-env.md](lib-env.md)), turns on refresh, and registers the shared interceptors. Bootstraps are idempotent, so each interceptor is registered once. A request sent before `baseUrl` is set throws a clear error instead of calling a relative URL.
- **Feature:** every feature has `features/<feature>/http.ts` exporting one client made with `http.extend(...)` and named after the feature (`catalogHttp`, `ordersHttp`). A feature with nothing special still has one: `export const ordersHttp = http.extend({});`. That keeps one shape everywhere, and moving a feature to its own service is a one-line change.
- Only the feature's repositories import its client (`../../http` from a repository folder). The feature's `index.ts` does not export it.
- The root `http` is imported only by feature `http.ts` files, the app's bootstrap (configure and shared interceptors), and the logout action (`abortAll`). Repositories never use the root client directly.
What a feature may set:
| Setting | Example | Merge |
|---|---|---|
| `baseUrl` | Its own service: `() => getEnv().catalogApiUrl` | Replaces the root's |
| `headers` | An API version header only this service needs | By key; the feature wins |
| `timeout` | Reports and exports that need 60 s | Replaces the root's |
| `retry` | Search retries more; payments use `retry: false` | Field by field |
| Feature-only interceptors | Unwrapping an envelope only this service uses | Run after the root's |
| `mapErrorBody` | Only for a back end with a different error contract | Replaces the root's |
A feature never sets `refresh`, `credentials`, or `getCookieHeader`: auth works the same for the whole app, and all clients share one refresh, so two features never refresh at once.
- One-off needs of a single endpoint (a longer timeout, no retry, `skipRefresh`) go in that request's options, not in the feature config.
- Merge order per request: lib defaults → root config → feature config → request options. Headers and retry merge by key; everything else is replaced by the more specific value.
- `createHttpClient(config)` makes an independent client that inherits nothing. Use it only for third-party APIs that don't use the app's auth (a maps provider), in the feature's `http.ts`, with `refresh: false`.
## Request pipeline
1. Merge the config (lib defaults → root → feature → request options). Generate one request id with `crypto.randomUUID()`, kept across retries and the refresh replay, and send it as `X-Request-Id`.
2. Run request interceptors in registration order, root first. They run again on every attempt, so retries and the replay after a refresh get fresh headers.
3. Serialize the body and query params. On the server, add the `Cookie` header from `getCookieHeader()`.
4. Send with one signal combined by `AbortSignal.any` from the caller's `signal`, the per-attempt timeout, the feature client's abort-all controller, and the root's.
5. A non-2xx status or no response is normalized to `HttpError`.
6. If refresh applies, refresh and replay once. The replay doesn't count as a retry attempt.
7. If retry applies, wait and go back to step 2.
8. On success, parse the body, run the `onSuccess` interceptors, and resolve. On failure, run the `onError` interceptors and throw the final `HttpError`.
## Body and params
- A plain object or array is sent as `JSON.stringify` with `Content-Type: application/json`.
- `FormData` is sent as is, and `Content-Type` is never set, so the platform adds the multipart boundary.
- `URLSearchParams`, `Blob`, `File`, `ArrayBuffer`, and strings are sent as is. `undefined` sends no body. GET, HEAD, and DELETE bodies are not supported.
- Query params drop `undefined` and `null`, repeat the key for arrays (`?tag=a&tag=b`), encode with `URLSearchParams`, and merge with any query string already in the URL.
- `responseType: 'auto'`: 204, 205, or an empty body resolves with `undefined`; a JSON content type is parsed; anything else resolves as text. Invalid JSON throws `PARSE_ERROR`.
- Unwrapping a back-end envelope (`{ data, meta }`) is a response interceptor's job: on the root when every service uses it, on the feature client when only that service does. Never in each repository.
## Interceptors
- Request: `(config: RequestConfig) => RequestConfig | Promise<RequestConfig>`. Return a new config; never mutate the argument.
- Response: `onSuccess(response: HttpResponse<unknown>)` returns a response, and `onError(error: HttpError)` returns an `HttpError`. `onError` may change the error but can't turn a failure into a success, so a resolved promise always means success.
- Both run in registration order, root before feature. A throwing interceptor fails the request with `INTERCEPTOR_ERROR`.
- Use them for cross-cutting concerns: `Accept-Language` from the current locale, envelope unwrapping, dev logging, Sentry breadcrumbs (method, URL, status, request id).
- Never put business logic, toasts, navigation, store writes, or per-user module state in them (on the server one client serves every user), and never log cookies or auth headers.
- Shared interceptors are registered on the root in bootstrap; feature-only interceptors in the feature's `http.ts`, right after `extend`. Never in components, models, or repositories.
## Retry
- An attempt is retried when its method is in `retry.methods`, the failure is a network error or a status in `retry.statuses`, attempts are left, and the request wasn't aborted.
- The default methods are idempotent reads. POST and PATCH are never retried by default; a request may opt in with `retry: true` only when it sends an idempotency key the back end honors.
- Delay: exponential backoff with full jitter, `random(0, min(maxDelay, baseDelay * 2 ** attempt))`. When the response has `Retry-After` (seconds or a date), wait that long instead, capped at `maxDelay`. Aborting during the wait rejects at once with `ABORTED`.
- Never retried: 4xx other than 408 and 429, `ABORTED`, `TIMEOUT` on non-idempotent methods, and uploads (the UI offers a retry button).
- On the server the defaults are `attempts: 1` and a shorter timeout (about 5 s), so one slow back end doesn't hold up rendering; the page streams around it.
- TanStack Query must not retry on top: `configs/react-query.ts` sets queries' `retry: false`, and the user retries from the error fallback or the toast ([error-handling.md](error-handling.md#reads)). Otherwise one failure multiplies into attempts × query retries.
## Refresh token
- Auth is cookie-based: the refresh endpoint reads the refresh cookie and the server sets new cookies. The lib never reads or stores tokens.
- Trigger: `shouldRefresh(error)` is true (default: 401), refresh is configured, the request didn't set `skipRefresh`, it isn't the refresh request itself, and it hasn't already been replayed after a refresh.
- Single flight: one refresh at a time for the whole app, because the root and every feature client share one coordinator. Requests that get a 401 while a refresh runs wait for it.
- Stale 401: each successful refresh increments a generation number. A request sent before the latest successful refresh that returns 401 is replayed right away, without another refresh.
- On success, every waiting request is replayed once. A replay that gets 401 again fails with `UNAUTHORIZED` without refreshing again, so there are no loops.
- On failure, every waiting request fails with `UNAUTHORIZED` and `onFailure()` runs once (the app emits its logout event; the auth feature clears the store and redirects). Later requests try normally, so logging in again works without a reload.
- The refresh request is sent with `skipRefresh: true`, `retry: false`, and the normal timeout, and runs request interceptors like any request.
- Waiting is abortable per request: an aborted waiter rejects with `ABORTED` while the refresh continues for the others.
- In the browser, run the refresh inside `navigator.locks.request('http-refresh', ...)` when available, so two tabs never send the same refresh cookie at once (the back end may rotate and revoke it).
- On the server refresh is disabled. Server Components can't set cookies, so a 401 throws `UNAUTHORIZED`, and `proxy.ts` refreshes an expired session before rendering.
## Abort
- Per request: pass `signal`. Repositories take an optional last parameter `{ signal?: AbortSignal }` and forward it, so `queryFn: ({ signal }) => productsRepository.list(args, { signal })` cancels stale requests on unmount or key change.
- Timeout: per attempt, from `timeout` (request option → feature → root → default). `timeout: false` disables it. Uploads and downloads default to no timeout; the user cancels them instead.
- Whole app: `http.abortAll()` in the logout action, so no request from the old session finishes after logout. One feature: `catalogHttp.abortAll()`, for example when leaving a page with long-running requests.
- Never call `abortAll` on the server: clients are shared by every user's requests.
- The caller's or abort-all's signal produces `ABORTED`; the timeout produces `TIMEOUT`. Tell them apart by which signal fired, not by the message.
- Aborted requests are never retried, never trigger a refresh, and never call `onFailure`. The UI ignores `ABORTED` errors: no toast, no error state.
## Files
```ts
upload<T>(url: string, input: File | Blob | File[] | FormData, options?: UploadOptions): Promise<T>;
interface UploadOptions extends Omit<RequestOptions, 'responseType'> {
method?: 'POST' | 'PUT' | 'PATCH'; // default 'POST'
fieldName?: string; // default 'file', used when input is a File, Blob, or File[]
fields?: Record<string, string>; // extra form fields sent with the file
onProgress?: (progress: UploadProgress) => void;
}
interface UploadProgress {
loaded: number;
total: number;
percent: number; // integer 0–100
}
download(url: string, options?: DownloadOptions): Promise<DownloadResult>;
interface DownloadOptions extends Omit<RequestOptions, 'responseType'> {
onProgress?: (progress: UploadProgress) => void;
}
interface DownloadResult {
blob: Blob;
fileName?: string;
contentType?: string;
}
```
- `upload` wraps a File, Blob, or File[] in `FormData` under `fieldName` (repeated for arrays) with `fields`. It uses `XMLHttpRequest`, because `fetch` can't report upload progress, and still runs interceptors, sends cookies (`withCredentials`), uses the request id, normalizes errors, and joins the refresh flow (the file is re-sent after a successful refresh). `signal` calls `xhr.abort()`. No automatic retry.
- The UI shows the percentage, file name and size, and a cancel button wired to the signal (see [b2c-b2b.md](ui-rules.md#file-uploads)).
- `download` uses `fetch`. `fileName` comes from `Content-Disposition` (`filename*` first, then `filename`). Progress is reported while reading the body stream when `Content-Length` is known. Saving the blob (object URL and link click) is a small browser util in `shared/utils`, not in the lib.
- `post(url, formData)` is fine for a small file when the UI needs no progress or cancel.
## Errors
- Every failure from every step is thrown as one `HttpError`: it extends `Error` and has the `HttpErrorShape` fields plus `method`, `url`, and `cause`. The lib throws nothing else.
- `isHttpError(error)` checks a brand such as `Symbol.for('project.http-error')`, not only `instanceof`, because server and client bundles can hold separate copies of the class.
- `toJSON()` returns the plain shape for logs and Sentry.
- `mapErrorBody` reads the error body (default: `code`, `message`, `hint`, and `fieldErrors` or `errors` from a JSON body). Set it once on the root when the back-end contract differs; a feature sets its own only for a back end with a different contract.
- `requestId` is the server's `X-Request-Id` response header when present, otherwise the id the client sent, so even network errors can be traced.
- `retryAfter` is the `Retry-After` header of a 429 or 503 in seconds (a date is converted), so the UI can say how long to wait.
- Server messages pass through as is; the back end localizes them from `Accept-Language`. Messages the lib creates (network, timeout, parse, unknown) are i18n keys such as `errors:http.network`, with a matching hint key, and the UI translates them. The lib never imports i18next.
- The lib never shows errors. The error handler lib decides what each one shows and reports it ([lib-error-handler.md](lib-error-handler.md)): a failed read reaches its error boundary or an empty state, a failed action goes through `applyServerErrors` or `showActionError` (fields, form alert, toast), and the auth feature handles logout ([error-handling.md](error-handling.md)).
| Code | When |
|---|---|
| `NETWORK_ERROR` | No response |
| `TIMEOUT` | The per-attempt timeout fired |
| `ABORTED` | The caller or `abortAll` aborted it |
| `VALIDATION` | 400 or 422 with field errors |
| `BAD_REQUEST` | Other 400 |
| `UNAUTHORIZED` | 401 |
| `FORBIDDEN` | 403 |
| `NOT_FOUND` | 404 |
| `CONFLICT` | 409 |
| `RATE_LIMITED` | 429 |
| `SERVER_ERROR` | 5xx |
| `PARSE_ERROR` | The body couldn't be parsed |
| `INTERCEPTOR_ERROR` | An interceptor threw |
| `UNKNOWN` | Anything else |
## Server side
- `bootstrap.server.ts` calls `configureServerHttp({ baseUrl: serverEnv.API_INTERNAL_URL, getCookieHeader: async () => (await cookies()).toString() })` once. It sets the root's server `baseUrl` (from the app's server env, for example an internal service address) and the cookie provider on the root, so every feature client forwards cookies too. A feature with its own `baseUrl` reads it through its project's `getEnv()`, which the server bootstrap fills with the server-side address.
- `getCookieHeader` runs on every server request, so each request forwards its own user's cookies. Never keep cookies, users, or tokens in module state.
- On the server, refresh is off, `abortAll` is unavailable, retry defaults to one attempt with a shorter timeout, `credentials` is ignored, and every request is sent with `cache: 'no-store'`, whatever `init` says.
- `init` never carries Next.js caching options (`next: { revalidate, tags }`): the Next.js server keeps no cache between requests (see [b2c-b2b.md](b2c-b2b.md#no-server-cache)).
## Usage
`features/catalog/http.ts`. `getEnv` is the owning project's env getter (see [lib-env.md](lib-env.md#project-env)).
```ts
import { http } from '@project/libs/http';
import { getEnv } from '../../env';
export const catalogHttp = http.extend({
baseUrl: () => getEnv().catalogApiUrl,
timeout: 30_000,
retry: { attempts: 3 },
});
catalogHttp.interceptors.response.use((response) => ({
...response,
data: (response.data as CatalogEnvelope).result,
}));
```
`features/orders/http.ts`, a feature with nothing special:
```ts
import { http } from '@project/libs/http';
export const ordersHttp = http.extend({});
```
`features/catalog/repositories/products/products.ts`
```ts
import type { DownloadResult, UploadProgress } from '@project/libs/http';
import { catalogHttp } from '../../http';
export const productsRepository = {
async list(args: ListProductsArgs, options?: { signal?: AbortSignal }): Promise<ListProductsPayload> {
const response = await catalogHttp.get<ListProductsResponseDto>(PRODUCTS_ENDPOINT, {
params: toListProductsParams(args),
signal: options?.signal,
});
return toListProductsPayload(response);
},
async uploadImage(
args: UploadProductImageArgs,
options?: { signal?: AbortSignal; onProgress?: (progress: UploadProgress) => void },
): Promise<ProductImagePayload> {
const response = await catalogHttp.upload<UploadImageResponseDto>(
productImageEndpoint(args.productId),
args.file,
options,
);
return toProductImagePayload(response);
},
exportReport(args: ExportProductsArgs): Promise<DownloadResult> {
return catalogHttp.download(PRODUCTS_EXPORT_ENDPOINT, { params: toExportParams(args), timeout: 120_000 });
},
};
```
The export's long timeout applies to that one request, so it is a request option, not feature config.
Bootstrap, root client only (`bootstrap.client.ts`). The refresh endpoint and logout event come from the auth feature's public API.
```ts
http.configure({
baseUrl: clientEnv.NEXT_PUBLIC_API_URL,
refresh: { endpoint: AUTH_ENDPOINTS.refresh, onFailure: () => eventEmitter.emit(AUTH_EVENTS.logout) },
});
http.interceptors.request.use((config) => ({
...config,
headers: { ...config.headers, 'Accept-Language': i18n.language },
}));
```
## Acceptance checklist
For building or changing the lib:
```
[ ] GET, POST, PUT, PATCH, DELETE send the right method, headers, JSON or FormData body, and query params, and resolve with the parsed body
[ ] A request sent before bootstrap sets the root's baseUrl throws a clear "not configured" error
[ ] 204 resolves with undefined; invalid JSON throws PARSE_ERROR
[ ] Request and response interceptors run in order, re-run on retry and replay, and eject works
[ ] A GET that gets 503 twice then 200 resolves after 3 tries; a POST that gets 503 fails at once
[ ] Retry-After is respected; aborting during the backoff wait rejects at once with ABORTED
[ ] Five parallel requests that all get 401 cause exactly one refresh, then all five replay and resolve, also across feature clients
[ ] http.extend rejects refresh, credentials, and getCookieHeader at type level; feature headers and retry merge over the root's; request options win over both
[ ] A feature client runs the root's interceptors before its own and sees root settings made after it was created
[ ] A failed refresh rejects all waiters with UNAUTHORIZED and calls onFailure exactly once
[ ] A replay that gets 401 again fails without a second refresh
[ ] Caller abort gives ABORTED and timeout gives TIMEOUT; http.abortAll() aborts every feature's requests, a feature's abortAll() only its own, and new requests still work
[ ] Upload reports progress from 0 to 100, can be cancelled, and joins the refresh flow
[ ] Download returns the blob and the file name from Content-Disposition
[ ] Every failure is an HttpError with code, message, status, fieldErrors, hint, and requestId, plus retryAfter on a 429 or 503 that sends Retry-After; isHttpError works across bundles
[ ] On the server, each request forwards its own cookies, is sent with cache: 'no-store', refresh never runs, and no state leaks between requests
```

View File

@ -1,111 +0,0 @@
# Local-storage lib (`packages/libs/src/local-storage`)
One `LocalStorageAdapter` class over `window.localStorage` that puts every key under the app's prefix (`shop.cart`), so apps and third-party scripts on the same origin never overwrite each other. It implements the native `Storage` interface, so it drops into anything that expects `localStorage`, including zustand's `createJSONStorage`. Browser only; framework-agnostic; no dependency.
Contents: What local storage is for · Structure · API · Keys · Blocked storage · Browser only · Persisted zustand stores · Usage · Acceptance checklist
## What local storage is for
- Client-only data that should survive a reload and that the server never needs: UI preferences (table page size, collapsed sidebar), form drafts, recently viewed items, the last used phone number, persisted zustand stores.
- Data the server needs while rendering goes in a cookie ([lib-cookie.md](lib-cookie.md)). Server state goes in the TanStack Query cache, not here.
- Never tokens, secrets, or personal data that would hurt if leaked: any script on the page, including an XSS payload, can read local storage. Auth uses HttpOnly cookies ([lib-http.md](lib-http.md)).
- About 5 MB per origin, shared by every app on it. Keep values small and never cache large API responses here.
## Structure
```
packages/libs/src/local-storage/
├── local-storage.ts # LocalStorageAdapter class and the shared `storage` instance
├── types.ts # LocalStorageOptions
├── constants.ts # DEFAULT_STORAGE_PREFIX, STORAGE_KEY_SEPARATOR ('.')
└── index.ts
```
- `index.ts` exports `LocalStorageAdapter`, `storage`, `DEFAULT_STORAGE_PREFIX`, and the type `LocalStorageOptions`. Nothing goes in `server.ts`: the lib is browser-only.
- Import by subpath: `import { storage } from '@project/libs/local-storage'`.
- The instance is named `storage`, never `localStorage`, so it never shadows the global.
## API
```ts
interface LocalStorageOptions {
prefix: string; // the app's namespace, e.g. 'shop'; default DEFAULT_STORAGE_PREFIX
}
```
- Every key a caller passes is stored as `<prefix>.<key>`. Callers always use the short key; only the adapter knows the full one.
- `getItem(key)` returns the value or `null`; `setItem(key, value)` stores a string; `removeItem(key)` removes one key.
- The rest of `Storage` works inside the prefix only, so the adapter behaves like its own storage:
- `length` counts the keys under the prefix.
- `key(index)` returns the short key at that index among the prefixed keys, or `null`.
- `clear()` removes only the keys under the prefix. It never calls `window.localStorage.clear()`, which would delete other apps' and libraries' data.
- `clearByPrefix(subPrefix)` removes every key under `<prefix>.<subPrefix>`, for example `storage.clearByPrefix('session.')` on logout. Collect the matching keys first, then remove them, because removing while iterating shifts the indexes.
- `getJSON<T>(key)` parses the stored JSON and returns `null` for a missing key or invalid JSON (removing the broken value). The result is untrusted, since the data may be old or edited by the user, so callers that depend on its shape validate it with a valibot schema.
- `setJSON(key, value)` runs `JSON.stringify`, then `setItem`.
- `configure(options: LocalStorageOptions)` sets the prefix once, in the app's bootstrap. It only stores options and never touches `window`, so it's safe in `bootstrap.client.ts` during SSR. Changing a prefix later leaves the old keys behind, so pick it once per app.
- The shared instance is `export const storage = new LocalStorageAdapter();`. Create another `LocalStorageAdapter` only in tests.
## Keys
- Keys are constants in the owning project's `constants.ts` (`LAST_PHONE_STORAGE_KEY` in the auth feature), never string literals at call sites.
- Group keys by lifetime with a sub-prefix. `session.*` holds data that belongs to the logged-in user (drafts, recent items), and the logout action clears it with `storage.clearByPrefix('session.')`. Other keys are device preferences that survive logout.
- When the shape of a stored value changes, change the key (`cart.v2`) or use zustand persist's `version` and `migrate`, and remove the old key, so old data never breaks new code.
- Data written through the adapter isn't readable with `window.localStorage.getItem(key)` and the short key. Always read it back through `storage`.
## Blocked storage
- Browsers can block or limit storage: Safari private mode, storage disabled by the user or a policy, or a full quota. Access then throws `SecurityError` or `QuotaExceededError`.
- The adapter catches these: `getItem` returns `null`, `setItem` and `removeItem` do nothing, and a warning is logged in development only. Persisted data is a convenience, so the app keeps working without it.
- Features never depend on local storage for correctness. Anything that must not be lost goes to the server.
## Browser only
- Every method except `configure` checks `typeof window === 'undefined'` and throws a clear error ("storage is browser-only; never read it during render or on the server") instead of the unclear "window is not defined". Server access is a programming mistake, so it throws; blocked storage is the user's environment, so it's handled quietly.
- Call it only in event handlers, effects, actions, and client bootstrap code. Never during render and never at module top level: client components also render on the server, and a value read during render differs between server and browser, which breaks hydration.
- Repositories never use it, so they stay server-safe.
## Persisted zustand stores
- Use the adapter as the storage: `persist(creator, { name: 'cart', storage: createJSONStorage(() => storage), version: 1, migrate })`. The name becomes the key, stored as `<prefix>.cart`; put it under `session.` when it belongs to the logged-in user.
- Persist only what must survive a reload, with `partialize`. Never loading flags or server data.
- Set `skipHydration: true` and call `useCartStore.persist.rehydrate()` in an effect of the platform's `AppShell`, so the server render and the first browser render match. Stores are never written during server render, so storage is never touched on the server.
Code: [code-patterns.md](code-patterns.md#persisted-store).
## Usage
Bootstrap (`bootstrap.client.ts`):
```ts
storage.configure({ prefix: 'shop' });
```
A model reading a preference in an effect, `features/catalog/models/products/use-products-page.ts`:
```ts
useEffect(() => {
const stored = storage.getJSON<number>(PRODUCTS_PAGE_SIZE_STORAGE_KEY);
if (stored !== null && PAGE_SIZES.includes(stored)) setPageSize(stored);
}, []);
```
The logout action:
```ts
storage.clearByPrefix(SESSION_STORAGE_PREFIX); // 'session.'
```
## Acceptance checklist
For building or changing the lib:
```
[ ] setItem('token', 'abc') writes '<prefix>.token'; getItem('token') reads it; window.localStorage.getItem('token') is null
[ ] removeItem removes only the prefixed key
[ ] length, key(index), and clear work inside the prefix only; keys of other prefixes and unprefixed keys survive clear
[ ] clearByPrefix('session.') removes every '<prefix>.session.*' key and nothing else
[ ] getJSON returns the parsed value, and null (removing the value) for a missing key or invalid JSON
[ ] With storage blocked or full, getItem returns null and setItem doesn't throw
[ ] Every method except configure throws the clear browser-only error on the server
[ ] zustand createJSONStorage(() => storage) persists and rehydrates a store under '<prefix>.<name>'
```

View File

@ -1,187 +0,0 @@
# Page example: caches, page, and parts
A full page for [b2c-b2b.md](b2c-b2b.md): device detection, caches, a server page loader, the page entrypoint, streamed parts, and query hydration. Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet. Otherwise copy the shape of an existing page.
`platforms/<app>/src/shared/utils/get-device.ts`
```ts
import 'server-only';
import { headers } from 'next/headers';
import { userAgent } from 'next/server';
export async function getDevice(): Promise<'mobile' | 'desktop'> {
const { device } = userAgent({ headers: await headers() });
return device.type === 'mobile' ? 'mobile' : 'desktop';
}
```
`platforms/<app>/src/features/catalog/caches/products.ts`
```ts
import 'server-only';
import { cache } from 'react';
import { productsRepository } from '../repositories/products';
import { RELATED_PRODUCTS_LIMIT } from './constants';
export const getProduct = cache((id: string) => productsRepository.get({ id }));
export const getRelatedProducts = cache((id: string) =>
productsRepository.listRelated({ id, limit: RELATED_PRODUCTS_LIMIT }),
);
export const getProductReviews = cache((id: string, page: number) => productsRepository.listReviews({ id, page }));
```
`platforms/<app>/src/features/catalog/caches/server.ts`
```ts
import 'server-only';
export { getProduct, getProductReviews, getRelatedProducts } from './products';
```
`platforms/<app>/src/server.ts`
```ts
import 'server-only';
export { getProduct, getProductReviews, getRelatedProducts } from './features/catalog/caches/server';
export { getDevice } from './shared/utils/get-device';
```
`apps/<app>/src/app/(shop)/product/[id]/page.tsx`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the order page in [error-handling.md](error-handling-code.md) does.
```tsx
import { getDevice, getProduct } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { ProductDesktop } from './templates/product-desktop';
import { ProductMobile } from './templates/product-mobile';
type ProductPageProps = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: ProductPageProps): Promise<Metadata> {
const { id } = await params;
const product = await getProduct(id);
return { title: product.name, description: product.summary };
}
export default async function ProductPage({ params }: ProductPageProps) {
const { id } = await params;
const [device, product] = await Promise.all([getDevice(), getProduct(id)]);
return device === 'mobile' ? <ProductMobile product={product} /> : <ProductDesktop product={product} />;
}
```
The desktop template, a Server Component, renders the product at once and streams the two slower parts, each behind its own part boundary ([error-handling.md](error-handling.md#boundaries)):
```tsx
<ProductSummary product={product} />
<PartBoundary name="related-products">
<Suspense fallback={<RelatedProductsSkeleton />}>
<RelatedProducts productId={product.id} />
</Suspense>
</PartBoundary>
<PartBoundary name="product-reviews">
<Suspense fallback={<ProductReviewsSkeleton />}>
<ProductReviews productId={product.id} />
</Suspense>
</PartBoundary>
```
`.../product/[id]/organisms/related-products/RelatedProducts.tsx`. The client only shows this part, so it stays a Server Component.
```tsx
import { getRelatedProducts } from '@project/<platform>/server';
import { ProductRail } from '@project/island/organisms/product-rail';
import type { RelatedProductsProps } from './types';
export async function RelatedProducts({ productId }: RelatedProductsProps) {
const products = await getRelatedProducts(productId);
return <ProductRail products={products} />;
}
```
`.../product/[id]/organisms/product-reviews/ProductReviews.tsx`. The client pages through reviews, so this part hands its first page over through query hydration. `ReviewsList` is a client component that calls the part model.
```tsx
import { reviewKeys } from '@project/<platform>/features/catalog';
import { getProductReviews } from '@project/<platform>/server';
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { getQueryClient } from '../../../../../../configs';
import { ReviewsList } from './components/reviews-list';
import type { ProductReviewsProps } from './types';
export async function ProductReviews({ productId }: ProductReviewsProps) {
const queryClient = getQueryClient();
await queryClient.prefetchQuery({
queryKey: reviewKeys.list(productId, 1),
queryFn: () => getProductReviews(productId, 1),
});
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ReviewsList productId={productId} />
</HydrationBoundary>
);
}
```
`platforms/<app>/src/features/catalog/models/product/use-product-reviews-part.ts`. Page 1 comes from the server; later pages load in the browser while the current page stays visible.
```ts
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { productsRepository, reviewKeys } from '../../repositories/products';
export function useProductReviewsPart(productId: string) {
const [page, setPage] = useState(1);
const reviews = useQuery({
queryKey: reviewKeys.list(productId, page),
queryFn: ({ signal }) => productsRepository.listReviews({ id: productId, page }, { signal }),
placeholderData: keepPreviousData,
});
return { reviews, page, setPage };
}
```
`apps/<app>/src/configs/react-query.ts`. The app's root client component passes `getQueryClient()` to `QueryClientProvider`. Older TanStack Query v5 releases use the `isServer` constant instead of `environmentManager.isServer()`. The error settings are explained in [error-handling.md](error-handling.md#reads).
```ts
import { handleError } from '@project/libs/error-handler';
import {
defaultShouldDehydrateQuery,
environmentManager,
QueryCache,
QueryClient,
} from '@tanstack/react-query';
function makeQueryClient(): QueryClient {
return new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
if (query.state.data !== undefined) handleError(error, { where: 'refetch' });
},
}),
defaultOptions: {
queries: {
staleTime: 60_000,
retry: false,
networkMode: 'offlineFirst',
throwOnError: (_error, query) => query.state.data === undefined,
},
mutations: { networkMode: 'offlineFirst' },
dehydrate: {
shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending',
shouldRedactErrors: () => false,
},
},
});
}
let browserQueryClient: QueryClient | undefined;
export function getQueryClient(): QueryClient {
if (environmentManager.isServer()) return makeQueryClient();
browserQueryClient ??= makeQueryClient();
return browserQueryClient;
}
```

View File

@ -1,342 +0,0 @@
# Project structure
`<placeholders>` are names you choose. `@project` stands for the workspace's npm scope.
Contents: Top level · App · Platform · Feature anatomy · Shared · island · libs, integrations, and tools packages · Env flow · Nx tags and boundaries · Exports and tree-shaking
## Top level
```
apps/ # deployable apps
platforms/ # each app's logic, one project per app
packages/
├── island/ # design system (atomic design)
├── libs/ # framework-agnostic libraries, e.g. http and env
├── integrations/ # third-party integrations
└── tools/ # shared runtime tools
tools/ # workspace scripts for AI, Nx, and the repo, e.g. a doc validator
```
Three folders are named `tools`. Keep them apart:
- Root `tools/`: scripts that run in a terminal, in CI, or through Nx (generators, validators). App code never imports them. TypeScript scripts run with jiti.
- `packages/tools/`: shared runtime tools that apps and projects import.
- `packages/island/src/tools/`: design-system tools such as `cn`, `icon-sprite-plugin`, and `icon-name-extraction`.
## App (Next.js)
```
apps/<app>/src/
├── bootstrap/
│ ├── bootstrap.client.ts # runs before client components render (SSR and browser)
│ ├── bootstrap.server.ts # runs once on the server before rendering
│ └── index.ts
├── i18n/
│ ├── i18n.ts
│ └── index.ts
├── instrumentation.ts # configures the error handler on the server; onRequestError reports
├── app/ # Next.js App Router
│ ├── global-error.tsx # EB-W: replaces the root layout; own <html> and <body>
│ ├── not-found.tsx
│ └── (auth)/
│ ├── layout.tsx
│ ├── loading.tsx
│ ├── error.tsx # page-size EB-S for the group
│ └── auth/
│ └── login/
│ ├── page.tsx
│ ├── organisms/ # optional: organisms only this route uses
│ └── templates/ # optional: this route's mobile and desktop templates
├── styles/
│ ├── app.css # Tailwind entry; imports island.css
│ ├── fonts.ts # next/font/local faces from island fonts/, set as CSS variables on <html>
│ └── index.ts
├── configs/
│ ├── seo.ts
│ ├── react-query.ts
│ └── index.ts
├── constants/
│ ├── auth.ts # e.g. the OTP re-send timeout
│ └── index.ts
└── env/ # the only code that reads process.env (see lib-env.md)
├── env.client.ts # public variables: createClientEnv
├── env.server.ts # server variables: createServerEnv; import 'server-only'
├── index.ts # clientEnv
└── server.ts # serverEnv; import 'server-only'
```
- Pages are thin entrypoints. A page picks the mobile or the desktop template on the server, so no component branches on viewport size.
- Every route level may keep its own `organisms/` and `templates/`, shaped like island organisms. They are not routable because they contain no `page.tsx`.
- `styles/`, `configs/`, and `constants/` grow as needed; each keeps an `index.ts`.
- The app holds no features, stores, or business logic; those live in `platforms/<app>/`.
## Platform
```
platforms/<app>/src/
├── app/
│ ├── app-shell/ # top-level provider shell shared by the mobile and desktop views
│ │ ├── AppShell.tsx
│ │ ├── types.ts
│ │ └── index.ts
│ ├── guards/ # e.g. the route authentication guard
│ │ └── <guard-name>/
│ │ ├── <guard-name>.ts or <GuardName>.tsx
│ │ └── index.ts
│ ├── error-boundaries/ # see error-handling.md
│ │ ├── part-boundary/ # PartBoundary: catchError around a part
│ │ ├── error-fallback/ # ErrorFallback: what every boundary renders
│ │ ├── status-empty-state/ # the not-found and no-access empty states
│ │ └── read-on-server/ # readOnServer; server-only, exported through server.ts
│ └── navigation/
│ ├── navigation.ts # typed route paths and navigation menus
│ ├── constants.ts
│ ├── types.ts
│ ├── hooks/
│ │ └── use-<hook-name>.ts
│ ├── components/ # navigation UI, shaped like organisms
│ └── index.ts
├── features/ # DDD, see Feature anatomy
├── stores/ # one store per feature or domain
├── shared/ # see Shared
├── index.ts
└── server.ts
```
## Feature anatomy
```
features/<feature>/
├── entities/ # back-end data model: types, enums, unions
│ └── <entity-name>/
│ ├── types.ts
│ └── index.ts
├── repositories/ # request + return data; no client-side dependencies
│ └── <repository-name>/
│ ├── <repository-name>.ts
│ ├── types.ts # e.g. LoginArgs, LoginDto, LoginResponseDto, LoginPayload
│ ├── mappers.ts # *Args → *Dto (outgoing), *ResponseDto → *Payload (incoming)
│ ├── constants.ts # endpoints and query keys
│ └── index.ts
├── caches/ # server-only React cache() reads
│ ├── <cache-name>.ts
│ ├── types.ts
│ ├── constants.ts
│ └── server.ts # the module's entry; no index.ts
├── actions/
│ └── <action-name>/
│ ├── actions.ts # the operation from start to end; emits its event
│ └── index.ts
├── models/ # logic per page and per part, as hooks
│ ├── login/ # a page with one model
│ │ ├── use-login-page.ts
│ │ ├── types.ts
│ │ ├── constants.ts
│ │ └── index.ts
│ └── shipment/ # a page model plus one model per part
│ ├── use-shipment-page.ts
│ ├── use-shipment-address-part.ts
│ ├── use-shipment-legal-part.ts
│ ├── use-shipment-bill-part.ts
│ └── index.ts
├── http.ts # the feature's HTTP client: http.extend(...); used only by its repositories
├── types.ts
├── constants.ts
└── index.ts # never exports the http.ts client
```
Rules inside a feature:
- Layers import only from earlier layers: entities → repositories → actions → models → UI.
- Repositories import only entities, libs, the feature's `http.ts`, and their own files. Actions may also use stores and browser libs such as `storage`, `cookie`, and the event emitter. Models may also use actions, stores, and validations.
- Caches sit beside that chain, on the server: they import only entities, repositories, and their own files, and only server code imports them (server page loaders in `models/`, pages, `generateMetadata`, and server components). Details: [b2c-b2b.md](b2c-b2b.md#data-flow).
- Every action takes an optional last parameter `{ emit?: boolean }`, default `true`, and emits its `<feature>.<action>` event from the feature's `constants.ts` when its steps succeed.
- A page model owns what its parts share, such as the current step and the final submit. Each part model owns its part's data and form.
- `http.ts` exports one client, `http.extend(...)`, named after the feature (`catalogHttp`). It may set the base URL, headers, timeout, retry, and feature-only interceptors. It never sets refresh, credentials, or cookie forwarding; the type of `extend` rejects them. Details: [lib-http.md](lib-http.md#root-and-feature-clients).
- Models call repositories directly for queries. Mutations with side effects beyond the request go through an action.
- `*Payload` is the only repository type used outside the repository. If server field names differ from `*Args` names, the mappers translate the server's `fieldErrors` keys too.
- Another feature is imported only through its `index.ts`.
## Shared
```
shared/
├── constants/
│ ├── <constant-name>.ts
│ └── index.ts
├── utils/
│ ├── <util-name>.ts
│ └── index.ts
└── validations/
├── types.ts
├── constants.ts
├── base-validations.ts
├── <feature>-validations.ts
└── index.ts
```
`shared/utils/` holds `apply-server-errors.ts` and `show-action-error.ts`, the two functions every failed action goes through ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)).
`shared/` never imports from `features/`, `stores/`, or `app/`.
## island (`packages/island`)
```
packages/island/src/
├── atoms/
│ └── <component-name>/ # component module
├── molecules/ # like atoms, e.g. empty-state and error-state
├── organisms/
│ └── <component-name>/ # component module + private components/ and hooks/
├── templates/ # like organisms
├── primitives/ # non-visual structural pieces, e.g. portal, error-boundary; like organisms
├── tools/
│ └── <tool-name>/ # e.g. cn, icon-sprite-plugin, icon-name-extraction
│ ├── <tool-name>.ts or <tool-name>.tsx
│ ├── types.ts
│ ├── constants.ts
│ └── index.ts
├── styles/
│ ├── island.css # entry that apps import into their Tailwind v4 CSS
│ ├── theme.css # primitive and semantic tokens
│ └── utilities.css # custom @utility definitions
├── env/ # island's env: setEnv and getEnv, filled by the app's bootstrap
│ ├── env.ts
│ ├── types.ts
│ └── index.ts
├── icons/
│ ├── symbol-defs.svg # sprite generated by Icomoon
│ └── selection.json # Icomoon snapshot; re-import it into Icomoon to update the set
├── fonts/ # every app's fonts, e.g. yekan-bakh-vf.woff2; each app loads them with next/font/local
├── constants.ts # island-level constants
├── index.ts
└── server.ts
```
Component module:
| Entry | Required | Holds |
|---|---|---|
| `<ComponentName>.tsx` | Yes | The component |
| `types.ts` | Yes | Every type the component needs, including its props |
| `variants.ts` | Yes | The cva definitions. A non-visual primitive with no styles may skip it |
| `constants.ts` | No | Component-level constants |
| `index.ts` | Yes | The public API, re-exported by name |
| `components/` | Organisms, templates, primitives | Private sub-components shaped like atoms; never imported from outside, except a compound component's named parts, which its `index.ts` re-exports ([design-patterns.md](design-patterns.md)) |
| `hooks/` | Organisms, templates, primitives | Private `use-<hook-name>.ts` hooks |
Tools:
- `icon-sprite-plugin` is a build and dev plugin. It optimizes the SVGs with svgo and writes the final sprite into each app's `public/` folder. Build-time tools are imported only from build configs, never from app code.
- `icon-name-extraction` extracts icon names from the Icomoon files, for example to type the `Icon` component's `name` prop.
## libs, integrations, and tools packages
```
packages/libs/src/<lib-name>/ # e.g. http, env, error-handler, cookie, local-storage,
├── <lib-name>.ts # custom prototypes, regex, event-emitter
├── types.ts
├── constants.ts
└── index.ts
packages/integrations/src/<integration-name>/ # e.g. sentry, analytics
├── <integration-name>.ts
├── components/ # shaped like organisms
├── hooks/
│ └── use-<hook-name>.ts
├── constants.ts
├── types.ts
└── index.ts
packages/tools/src/<tool-name>/ # shared runtime tools
├── <tool-name>.ts
├── types.ts
├── constants.ts
└── index.ts
```
- libs are framework-agnostic: no React, Next.js, or TanStack imports. They never read env; the app's bootstrap passes their settings through `configure`.
- A lib may split its main file into more files when it grows. `http` does; its layout is in lib-http.md.
- Side-effect modules such as custom prototype extensions must be listed in `sideEffects` (see Exports).
Fundamental libs have full specs:
| Lib | Instance | Owns | Spec |
|---|---|---|---|
| `http` | Root `http`; one `http.extend(...)` client per feature | Every request: verbs, upload and download, interceptors, retry, one refresh at a time on 401, abort, `HttpError`; cookie forwarding on the server | [lib-http.md](lib-http.md) |
| `error-handler` | `configureErrorHandler`, `classifyError`, `describeError`, `handleError` | What each error shows (boundary, empty state, toast), its words and reference ID, its retry kind, and reporting 5xx and logic errors once | [lib-error-handler.md](lib-error-handler.md) |
| `env` | `createClientEnv`; `createServerEnv` (server) | Validating the app's env: public variables on both sides, server variables on the server only | [lib-env.md](lib-env.md) |
| `cookie` | `cookie` | Browser cookies for small values the server needs (locale, theme); never tokens | [lib-cookie.md](lib-cookie.md) |
| `local-storage` | `storage` | Prefixed, client-only, non-critical data and persisted zustand stores; never tokens or personal data | [lib-local-storage.md](lib-local-storage.md) |
`cookie` and `storage` are browser-only and export nothing from `server.ts`; `error-handler` runs on both sides and exports nothing from it either. `http` exports `configureServerHttp` from `server.ts`. `env` exports `createServerEnv` from its own `env/server.ts`, which the project's `server.ts` re-exports.
## Env flow
1. The app declares its variables in `apps/<app>/src/env/` and validates them with the env lib: `createClientEnv` for public variables and `createServerEnv` for server variables. These files are the only code that reads `process.env`, and a bad variable stops the app with one error that lists every problem.
2. Every other project that reads env has `src/env/` (`env.ts`, `types.ts`, `index.ts`) with `setEnv`, which stores its own values, and `getEnv`, which returns them and throws a clear error before `setEnv` has run. Its code reads env only through `getEnv`, inside functions, never at module top level.
3. At startup the app's bootstrap calls each project's `setEnv` with the values that project needs. Projects never import the app, so the dependency graph stays acyclic. Libs never read env: the bootstrap passes their settings through `configure`.
4. `bootstrap.server.ts` fills the server module graph and may pass server-side values, such as an internal service address; `bootstrap.client.ts` fills the client module graph with public values only. Public variables use the `NEXT_PUBLIC_` prefix and are listed one by one in `runtimeEnv`, because Next.js inlines only literal `process.env.NEXT_PUBLIC_*` references.
Code: [lib-env.md](lib-env.md).
## Nx tags and boundaries
Default tags. Reuse the repo's own tags if it already has them.
| Project | Tags |
|---|---|
| `apps/<app>` | `type:app`, `scope:<app>` |
| `platforms/<app>` | `type:platform`, `scope:<app>` |
| `packages/integrations` | `type:integration`, `scope:shared` |
| `packages/island` | `type:ui`, `scope:shared` |
| `packages/libs` | `type:lib`, `scope:shared` |
| `packages/tools` | `type:tool`, `scope:shared` |
`@nx/enforce-module-boundaries` constraints, the only ESLint rules the repo runs:
| Source tag | May depend on |
|---|---|
| `type:app` | `type:platform`, `type:integration`, `type:ui`, `type:lib`, `type:tool` |
| `type:platform` | `type:integration`, `type:ui`, `type:lib`, `type:tool` |
| `type:integration` | `type:ui`, `type:lib`, `type:tool` |
| `type:ui` | `type:lib`, `type:tool` |
| `type:lib` | `type:tool` |
| `type:tool` | Nothing |
| `scope:<app>` | `scope:<app>`, `scope:shared` |
| `scope:shared` | `scope:shared` |
Layer rules inside a project are checked in review, or by `eslint-plugin-boundaries` when the repo configures it:
- island: no import from a higher atomic level; an organism's `components/` and `hooks/` stay private.
- features: the layer order in Feature anatomy.
- `shared/`: imports nothing above it.
## Exports and tree-shaking
Expose each module on its own subpath. With package.json `exports` (Nx workspaces that use TypeScript project references):
```json
{
"name": "@project/island",
"sideEffects": ["**/*.css"],
"exports": {
".": "./src/index.ts",
"./server": "./src/server.ts",
"./atoms/*": "./src/atoms/*/index.ts",
"./molecules/*": "./src/molecules/*/index.ts",
"./organisms/*": "./src/organisms/*/index.ts",
"./templates/*": "./src/templates/*/index.ts",
"./primitives/*": "./src/primitives/*/index.ts",
"./tools/*": "./src/tools/*/index.ts",
"./env": "./src/env/index.ts",
"./styles/*": "./src/styles/*"
}
}
```
Workspaces that use `tsconfig.base.json` path aliases instead map `"@project/island": ["packages/island/src/index.ts"]` and `"@project/island/*": ["packages/island/src/*"]`.
- `sideEffects`: pure TypeScript modules have none. List every file that must run on import, such as CSS and custom prototype extensions; otherwise bundlers drop it.
- The root `index.ts` re-exports every module by name, so `@project/island` and `@project/island/atoms/button` expose the same symbols.
- A module with its own `server.ts` also gets a `<module>/server` subpath, for example `"./env/server": "./src/env/server.ts"` in libs. The project's `server.ts` re-exports it, so `@project/libs/server` and `@project/libs/env/server` expose the same symbols.

View File

@ -1,254 +0,0 @@
# Refactoring
Code smells and refactoring techniques from refactoring.guru, mapped to this architecture. Use this file when code resists a change, while you fix a bug, and in review. It doesn't explain the smells and techniques. It says what each one looks like here and which layer or file the fix belongs in. Pattern choices are in [design-patterns.md](design-patterns.md) and [rendering-patterns.md](rendering-patterns.md). Names match the source pages: refactoring.guru/smells/<smell> and refactoring.guru/<technique>, in kebab-case.
Contents: When and how · Smells that are intended here · Smell catalog · Front-end smells · Techniques used most · Review comments
## When and how
A refactor changes the structure of code and keeps its behavior. Here, behavior also covers what the server renders, what the network sees, and the bundle budgets.
- Never put a refactor in the same commit as a behavior change. Separate commits in one PR are fine. Commit the refactor first, so the behavior change reads as a small diff.
- Cover the behavior first: check it by hand on both templates, mobile and desktop, and say so in the PR. Fix a bug you find this way in a commit of its own. Add a unit test only if the repo already has a unit test runner. The stack has none, so adding one needs approval.
- Take small steps. After each one, type-check, lint, and tests pass for the affected projects through Nx: `nx affected -t <targets>` ([SKILL.md](../SKILL.md#4-workflow)). Never reach green with `any`, a cast, `@ts-expect-error`, or a disabled lint rule.
- Rename symbols and move files with the TypeScript language service (the editor's rename, Move to file, and import updates on file move), never with text replace. Keep the naming rules while you rename: `use-<page>-page.ts`, `<feature>Http`, `*Payload`. The language service can't follow strings such as i18n keys, event names, and route paths, so search for those and check each hit, including every locale's resource file.
- A cookie or storage key is a contract with the server or with data already on users' devices, so renaming one is a behavior change ([lib-cookie.md](lib-cookie.md#keys), [lib-local-storage.md](lib-local-storage.md#keys)).
- A change to a package's public API, such as an island prop or a lib signature, updates every caller in the same PR. `nx affected` then checks every app that uses it.
- To move or rename a whole Nx project, run the Nx move generator (`@nx/workspace:move`), then check the project's tags and its subpath entries (package.json `exports`, or the `tsconfig.base.json` path aliases).
- To move a module into another project, such as a route's organism into island, first check that the target's tags allow every import the module makes. island, for example, imports only libs and tools ([project-structure.md](project-structure.md#nx-tags-and-boundaries)). Then move the files, export the module from the target's `index.ts` (or its `server.ts`, when the module is server-only) and its subpath, and switch every importer to that subpath. Never silence the boundary rule to make a move compile.
- A refactor that spans several features or projects is planned work: give it a written plan and its own PR. Bring legacy code into this architecture one feature at a time, in layer order: entities and repositories first, then actions, models, and UI ([SKILL.md](../SKILL.md#4-workflow)).
- State in the PR description that behavior doesn't change, and how you checked: the check by hand on both templates, and the first-load JS of key routes.
Some moves that look safe change behavior here:
- Hoisting a call to module scope. `getEnv()`, a repository, a cache, `cookie`, or `storage` then runs at import time, which can be before bootstrap or, for `cookie` and `storage`, on the server. On the server, the value it produces is shared by every request ([b2c-b2b.md](b2c-b2b.md#server-and-client-entries)).
- Moving code across a `'use client'` boundary, or importing from a root barrel instead of a subpath. The client bundle changes, so compare the first-load JS of key routes from `next build` before and after ([b2c-b2b.md](b2c-b2b.md#targets)).
- Lifting state to a parent or into a context. The parent re-renders its subtree on each change, and a context re-renders every consumer, so check the INP of the heaviest interaction.
- Extracting a component inside another component's body. It becomes a new component type on every render, so React remounts it and drops its state. Define extracted components at module level.
- Reshaping data that outlives the code: a persisted store's state, which users' devices still hold (bump `version` and add `migrate`, as in [code-patterns.md](code-patterns.md#persisted-store)), or an event's payload, which listeners in other features and integrations read.
- Changing a query key's shape. Invalidation matches keys by prefix, and a part finds its hydrated server data only under the exact key the server used. Change the key factory in the repository's `constants.ts`, never the call sites ([code-patterns.md](code-patterns.md#repository)).
A component that fetches, holds state, and renders is the most common case. Split it in this order, with a green run after each step:
1. Record its behavior by hand on both templates.
2. Move its state, effects, and handlers into a part model (`use-<page>-<part>-part.ts`) as they are, and leave the component presentational.
3. Move the request into a repository method on the feature's client, with its types, mapper, and query key, and read it through `useQuery` in the model. When the first paint or search engines need the data, read it on the server through a cache in `caches/` instead, and pass it as props or prefetch it for query hydration ([b2c-b2b.md](b2c-b2b.md#data-flow)). The HTTP lib and the query cache change retries, errors, and caching, so this step changes behavior: give it its own commit and test the error path.
4. In another behavior commit, add what the rules require and the code lacked, such as a same-size skeleton and a part boundary ([error-handling.md](error-handling.md)).
When to refactor:
- Before a feature the code resists: reshape the code until the feature is a small, obvious edit, then make that edit.
- While fixing a bug, in the layer that owns the fault ([SKILL.md](../SKILL.md#4-workflow)), and only as far as the fix needs.
- In review (see Review comments).
- At the third duplication, not the second (the rule of three), because by then the copies show what actually varies. island is the exception: a component that needs a second style gets an island variant at once, never a copy ([SKILL.md](../SKILL.md#3-architecture-rules)).
Refactor only the code the change touches, unless the plan says otherwise. Record other smells you notice as debt in the PR's trade-offs note.
When not to refactor:
- Code that is about to be deleted or rewritten.
- Generated files, such as the icon sprite and Icomoon's `selection.json`. Change their source or their generator instead.
- Library code in `node_modules`. Wrap it instead (see Incomplete Library Class).
- Untested code when there is no time to add a test. Record it as technical debt in the PR instead.
## Smells that are intended here
The catalog would flag these, but the architecture requires them, so never "fix" them. When a tool or a reviewer flags one, point to the reason in the last column.
| What you see | Looks like | Why it stays |
|---|---|---|
| Types-only entities, `*Dto`, and `*Payload` | Data Class | The types carry the back-end contract and the UI's shape; mappers, models, and actions do the work |
| A mapper that copies fields unchanged, or `*Args` and `*Dto` (or `*ResponseDto` and `*Payload`) with the same fields | Duplicate Code | The mapper is where a back-end change stops, so no `*Dto` reaches the UI |
| Named re-exports in every `index.ts` and `server.ts` | Middle Man | They give each module a subpath and keep server-only code out of client bundles. Never collapse them into `export *` |
| `http.extend({})` in a feature that needs nothing special | Lazy Class | Every feature has the same shape, and moving one to its own service is a one-line change ([lib-http.md](lib-http.md#root-and-feature-clients)) |
| A cache that wraps one repository call | Middle Man | Every server reader in the request shares one call ([b2c-b2b.md](b2c-b2b.md#data-flow)) |
| A thin page entry | Middle Man | The entry picks the template and hands it data from the model or the caches, so the logic stays there |
| One-line selector hooks such as `useCurrentUser` | Lazy Class | They hide the store's shape and keep each subscription small |
| Compound components that read their root's private context | Inappropriate Intimacy | The coupling stays inside one organism, and outside code sees only the compound API |
| A mobile and a desktop template per route | Parallel Inheritance Hierarchies | The server picks one, so only that view's code ships. This holds only while both templates render from the same models and hold no logic of their own |
| A same-size skeleton beside every part that loads on its own | Parallel Inheritance Hierarchies | It keeps the layout still while the part loads, so nothing shifts or flickers |
| A new endpoint that touches `types.ts`, `mappers.ts`, `constants.ts`, the repository, and `index.ts` | Shotgun Surgery | It is the fixed recipe. Scaffold it with the repo's Nx generator when it has one |
| The `{ emit }` and `{ signal }` options, and an event that nothing listens to yet | Speculative Generality | Actions can run other actions without double events, TanStack Query cancels stale reads, and new listeners never touch the action |
| State styles that no page uses yet, such as `loading` or `selected` | Speculative Generality | island builds every state into the component, so no page can forget one ([SKILL.md](../SKILL.md#3-architecture-rules)) |
| A page model plus one part model per part that loads or changes on its own | Shotgun Surgery | Each part owns its data and form, and the page model owns only what the parts share, such as the current step |
| A `<Suspense>` and a `PartBoundary` around each part that loads on its own | Duplicate Code | One shared boundary would let a slow or failing part block the others |
## Smell catalog
Every smell in refactoring.guru's smell catalog, in its groups. Size thresholds, such as the 80 lines below, are guides, not rules. Before you act on a row, check Smells that are intended here.
### Bloaters
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Long Method | A model hook over about 80 lines; a component that fetches, holds state, and renders; one `useEffect` that does several jobs | Extract Method: part models (`use-<page>-<part>-part.ts`), functions in `mappers.ts` or `shared/utils/`, private components in the organism's `components/`, and one effect per job |
| Large Class | One store that holds several domains; a page model that owns every part's data and form; an organism with many modes and optional props | Extract Class: one store per feature or domain, one part model per part, or a compound component with slots ([design-patterns.md](design-patterns.md)) |
| Primitive Obsession | Statuses and roles typed as `string`; query keys, event names, route paths, and storage keys written as literals at call sites | Replace Type Code with Class: a union in `entities/<entity>/types.ts`, like `OrderStatus`. Replace Magic Number with Symbolic Constant: the owning `constants.ts`, like `productKeys`, `AUTH_EVENTS`, and `ROUTES` |
| Long Parameter List | A repository method or action with several positional parameters; a component with many flat props, often style flags such as `isCompact` and `hideIcon` | Introduce Parameter Object: the endpoint's `*Args`, with options last. For a component: one cva `variant` instead of style flags, `children` or slots, or two components when a flag switches behavior (Replace Parameter with Explicit Methods) |
| Data Clumps | `page`, `pageSize`, `sort`, and filters passed together through models, query keys, and requests; the same address fields in several forms | Introduce Parameter Object: one `*Args` type such as `ListProductsArgs`, which the model builds once and passes whole to the query key and the repository. For forms: one valibot object schema in `shared/validations/` |
### Object-orientation abusers
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Alternative Classes with Different Interfaces | Two components for the same job with different props (`onClose` and `onDismiss`); two repositories that name one operation differently (`fetchAll` and `list`) | Rename Method to one vocabulary, then keep one island component with a variant (Parameterize Method) |
| Refused Bequest | A props type that extends a base type or `ComponentPropsWithRef<'input'>` but neither uses nor forwards most of it (an island atom that spreads the rest onto its native element is fine, as in [code-patterns.md](code-patterns.md#island-component-module)); a `*Payload` declared as its `*ResponseDto` plus extra fields, which hands every server field to the UI | Replace Inheritance with Delegation: `Pick` the props the component uses, and declare the `*Payload` in full so the mapper builds it |
| Switch Statements | The same `switch` or `if` chain on a status, role, or kind in several components, for labels, colors, icons, or allowed actions | Replace Conditional with Polymorphism: one `Record` keyed by the union in the feature's `constants.ts`, a cva variant in island, or one exhaustive `switch` ([design-patterns.md](design-patterns.md)) |
| Temporary Field | State that means something in one mode only, such as `editDraft` that is `null` unless editing, or `uploadProgress` outside an upload | Replace Type Code with State/Strategy: a discriminated union such as `{ status: 'editing'; draft: ProductDraft } \| { status: 'viewing' }`. Move Field into the part model that uses it |
### Change preventers
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Divergent Change | One file edited for unrelated reasons: a catch-all `shared/utils/helpers.ts`, a page model that changes for every part, an island component with branches for one page | Extract Class by reason to change: one util per file, one part model per part. Move Method page-only code into that route's `organisms/`, and give island a variant or a slot instead |
| Parallel Inheritance Hierarchies | Each new status or entity kind needs a matching card, row, and form file; a route's mobile and desktop templates each hold their own logic or data calls | Move Method: the logic into the page or part model, so both templates render one model. When a per-kind split must stay, keep one `Record` per concern keyed by the union, so a missing member fails type-check |
| Shotgun Surgery | One business rule spread across components, validations, and mappers; a cross-cutting concern, such as a header, a log line, or an analytics call, repeated in every repository or action | Move Method and Move Field to one owner: the rule into a model, a util, or a validation; a request concern into the feature's `http.ts` (headers or a feature-only interceptor), or into an interceptor on the root client in bootstrap when every feature needs it ([lib-http.md](lib-http.md#interceptors)); an analytics call into a listener on the action's event, subscribed in the `AppShell`. Inline Class merges scattered fragments |
### Dispensables
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Comments | A comment that explains what a JSX block, an effect, or a condition does | Extract Method into a named hook, component, or predicate, or Extract Variable. Keep comments that explain why, such as a back-end quirk or a browser bug |
| Duplicate Code | Copied JSX or class strings; the same mapping in two mappers; the same query and cache update in several models; a page and its `generateMetadata` that combine the same caches; the same code in two products | A copied or restyled island component: an island variant at once. Other copies, at the third one: an island component, a mapper, a `shared/utils/` function, or a hook in the owning feature's `models/`. A server page loader, `load-<page>-page.ts`, for the page and its metadata ([b2c-b2b.md](b2c-b2b.md#server-and-client-entries)). Parameterize Method when copies differ in one value. Code that two products share moves down to a package, never across to the other product |
| Data Class | The same derivation from a `*Payload`, such as a display name, a total, or a status flag, repeated in several components | Move Method: a field the mapper computes, when every consumer needs it and it doesn't depend on the locale; otherwise a selector hook or a util in the owning feature |
| Dead Code | Exports nobody imports, props no caller passes, cva variants and i18n keys nobody uses, and flag branches that always go one way | Delete it, with Remove Parameter for props and arguments. TypeScript's `noUnusedLocals` and `noUnusedParameters` find unused locals and parameters, and Find All References finds unused exports. knip automates the export search, but it is outside the stack and needs approval |
| Lazy Class | A wrapper component that only forwards props to one island component; a hook or util with one line and one caller | Inline Class or Inline Method into the caller |
| Speculative Generality | A config-driven component or generic hook with one caller; props, variants, or `*Args` fields that nobody passes; a wrapper over TanStack Query or zustand in case the library changes | Inline Class, Inline Method, or Remove Parameter. Add the generality at the third real use |
### Couplers
| Smell | Signal in this codebase | Refactor to |
|---|---|---|
| Feature Envy | A model or component that computes from another feature's `*Payload` fields or another store's raw state, or builds another feature's query keys by hand | Move Method to the owner of the data: a util or the key factory (such as `productKeys`), exported through that feature's `index.ts`, or a selector hook beside the store in `stores/<store>/` |
| Inappropriate Intimacy | Imports from another feature's internals (its `http.ts`, mappers, or repository folders) or from an organism's private `components/` and `hooks/`; two features that import each other | Import through the owner's `index.ts`, and let Hide Method keep the rest private, or move the shared piece to island or `shared/`. Break a cycle by letting one side react to the other's event (Change Bidirectional Association to Unidirectional) |
| Incomplete Library Class | The same work-around for a library repeated at call sites, such as extra classes that work around tailwind-merge dropping a theme token, identical `toast.error` options, or the same `Intl` setup | Introduce Local Extension: a wrapper like `cn` in island `tools/`; a shared helper that imports no other project, such as the `Intl` formatters, in `packages/tools`; a framework-agnostic library of the kinds [project-structure.md](project-structure.md#libs-integrations-and-tools-packages) lists for `packages/libs`, such as `http`, `cookie`, or `regex`, in `packages/libs`. Introduce Foreign Method: one helper in `shared/utils/`, like `applyServerErrors` |
| Message Chains | Deep paths in components, such as the selector `(state) => state.session?.user.role` repeated across components, or `order.customer.address.city` in JSX | Hide Delegate: a selector hook beside the store, such as `useCurrentUser`, and a flatter `*Payload` built by the mapper |
| Middle Man | A `services/` or `api/` layer between models and repositories; a hook or organism that only forwards to one other | Remove Middle Man: call the repository or render the component directly |
## Front-end smells
The catalog doesn't name these, but this stack has them. Each line gives the smell, the fix, and the rule behind it.
- Props passed down more than two levels → the part reads its own data from its part model or a selector hook, or the parent passes `children` ([SKILL.md](../SKILL.md#3-architecture-rules)).
- State derived from other state, or synced with it, in `useEffect` → derive it during render from props, the query, or a selector. Reset state with a `key` only on a subtree that isn't visible across the change, such as a dialog's form when the dialog opens ([SKILL.md](../SKILL.md#3-architecture-rules)).
- Server state copied into zustand or component state → read it from the query cache through the model ([SKILL.md](../SKILL.md#3-architecture-rules)).
- Several booleans for one flow → one status union with explicit states ([SKILL.md](../SKILL.md#3-architecture-rules)).
- `fetch`, HTTP calls, or data loading in a component or its `useEffect` → a repository method on the feature's client, read through `useQuery` in the model ([lib-http.md](lib-http.md#root-and-feature-clients)); first-paint data goes through a cache on the server ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- Array-index or random keys in a dynamic list → stable ids from the `*Payload` ([SKILL.md](../SKILL.md#3-architecture-rules)).
- One large context → one context per concern.
- A component that subscribes to a whole store → a selector for the smallest slice it renders ([code-patterns.md](code-patterns.md#store)).
- Hard-coded text, colors, or sizes → i18n keys and semantic tokens ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)).
- `'use client'` on a page, layout, or template → only on the interactive leaf, driven by its part model ([b2c-b2b.md](b2c-b2b.md#rendering)).
- Business logic in components → the model, action, mapper, or util that owns it ([SKILL.md](../SKILL.md#3-architecture-rules)).
- Viewport checks choosing layouts → the template the server picks ([b2c-b2b.md](b2c-b2b.md#rendering)).
- Cookie or storage reads during render → an effect or an event handler, or `cookies()` on the server passed down as a prop ([lib-cookie.md](lib-cookie.md#browser-only), [lib-local-storage.md](lib-local-storage.md#browser-only)).
- Module-scope data on the server → React `cache()`, props, or the per-request `QueryClient` ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
- A page, loader, or server component that calls a repository directly → a cache, so every reader in the request shares one call ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- A cache called with an object argument, or created inside a component → primitive arguments, and `cache()` defined at module level ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- A store written during server render → props or the query cache, or a store created per request ([b2c-b2b.md](b2c-b2b.md#state-and-auth)).
- `useSuspenseQuery` on a query the server didn't prefetch → `useQuery` with a skeleton ([b2c-b2b.md](b2c-b2b.md#data-flow)).
- A mutation that leaves stale queries, or relies on `staleTime` expiring → set the detail, patch the lists, and invalidate them ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)); also call `router.refresh()` when the change shows in server-rendered content ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
- Query retries on top of the HTTP lib's retries → queries don't retry; `configs/react-query.ts` sets `retry: false` ([lib-http.md](lib-http.md#retry)).
- A refetch that swaps content for a spinner → keep the data and show `isFetching` inline ([b2c-b2b.md](ui-rules.md#stability)).
- A `catch` that swallows the error or shows a hand-made `toast.error` → in a form, `applyServerErrors`; elsewhere, `showActionError`, which adds the hint or reference ID and the retry the cause allows ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)).
- An `isError` branch in a component, or a toast for a failed read → let the read throw to its part boundary, which shows the fallback or the `not-found` and `no-access` empty states ([error-handling.md](error-handling.md#reads)).
- `handleError`, or a report to the tracker, in a repository, an action, or a `catch` that rethrows → call it once, where the error stops: the fallback, `showActionError`, `QueryCache.onError`, or `onRequestError` ([error-handling.md](error-handling.md#reporting)).
- A server read whose 404 or 403 reaches the browser as a digest → read it through `readOnServer` and decide on the server ([error-handling.md](error-handling.md#b2cb2b-server)).
- An `ABORTED` error shown as a toast or an error state → ignore it ([lib-http.md](lib-http.md#abort)).
- Toasts, navigation, business logic, or store writes in an HTTP interceptor → a model or an action ([lib-http.md](lib-http.md#interceptors)).
- An action that runs another action as one of its steps, emits its own event, and still lets the inner action emit → pass `{ emit: false }` to the inner action, so listeners hear one event per operation ([code-patterns.md](code-patterns.md#action)).
- An event subscription in a component or at module top level, or one without an unsubscribe → subscribe once in an effect of the `AppShell` and unsubscribe in its cleanup ([code-patterns.md](code-patterns.md#action)).
- `process.env` outside the app's `env/` → the app's env, or the project's `getEnv()` inside a function ([lib-env.md](lib-env.md#project-env)).
Many of these show up in a plain text search, which makes a quick first pass in review: `export *`, `'use client'` in a `page.tsx` or `layout.tsx`, `process.env` outside `env/`, `fetch(` outside the HTTP lib, and `key={index}`.
## Techniques used most
Grouped as in refactoring.guru's technique catalog. Each line says how the technique looks in this codebase.
### Composing methods
- Extract Method: extract a function, a hook, or a component. Logic goes to a model hook, a mapper, or a util, markup to a private component, and each job of a long effect to its own effect.
- Inline Method: fold a one-line wrapper hook or util back into its only caller.
- Extract Variable: name a condition before the JSX, or return it from the model: `const canEdit = canUpdate && !order.isLocked;`.
- Replace Temp with Query: derive a value during render from props, the query, or a selector instead of mirroring it in `useState`.
- Remove Assignments to Parameters: never reassign or mutate an argument. Mappers build a new object, interceptors return a new config ([lib-http.md](lib-http.md#interceptors)), and props and query data stay read-only.
- Substitute Algorithm: replace hand-built date and number formatting with `Intl`, using the locale and time zone the server chose ([b2c-b2b.md](b2c-b2b.md#hydration-and-navigation)).
### Moving features between objects
- Move Method and Move Field: move code to the layer that owns it, following the layer order in [project-structure.md](project-structure.md#feature-anatomy). Requests go to a repository, locale-free shaping to a mapper, operations with side effects beyond the request to an action, orchestration to a model, and shared UI to island. State moves down to the component or part model that uses it, or up to the page model when parts share it.
- Extract Class: extract a module, a hook, or a component, such as one store per domain, part models out of a page model, or private components out of an organism.
- Inline Class: merge a module that does almost nothing into its only user.
- Hide Delegate: selector hooks beside the store, such as `useCurrentUser`, so components never walk the store's shape.
- Remove Middle Man: delete pass-through hooks, wrappers, and layers, except the intended ones.
- Introduce Foreign Method: one helper for what a library lacks, in `shared/utils/`, like `applyServerErrors` for react-hook-form and `HttpError`.
- Introduce Local Extension: a wrapper module over a library, like `cn` over clsx and tailwind-merge in island `tools/`. A shared helper that imports no other project goes in `packages/tools`, and a framework-agnostic library of the kinds [project-structure.md](project-structure.md#libs-integrations-and-tools-packages) lists for `packages/libs` goes there.
### Organizing data
- Replace Magic Number with Symbolic Constant: name it in the owning `constants.ts`, like `RELATED_PRODUCTS_LIMIT`. A color, size, or breakpoint becomes a token in island `theme.css` instead.
- Replace Type Code with Class: a string-literal union in the entity, like `OrderStatus`, or an `as const` object when code needs the values at runtime.
- Replace Type Code with Subclasses: a discriminated union with one component per member, chosen through one map.
- Replace Type Code with State/Strategy: a discriminated-union status for a flow, and a `Record` of handlers for behavior that varies per member.
- Encapsulate Collection: only the store's actions change its arrays. Type the arrays `readonly` in the store's `types.ts`. For the persisted cart store in [code-patterns.md](code-patterns.md#persisted-store), its state becomes the one below. As in code-patterns.md, the path is relative to `platforms/<app>/src/`.
`stores/cart/types.ts`
```ts
import type { CartItemPayload } from '../../features/cart';
export type CartState = {
items: readonly CartItemPayload[];
addItem: (item: CartItemPayload) => void;
clear: () => void;
};
```
Outside the store, `useCartStore.getState().items.push(item)` no longer compiles. Inside `set`, `state.items.push(item)` still does, because immer's draft type drops `readonly`.
### Simplifying conditional expressions
- Decompose Conditional: move each branch of a large conditional JSX block into a named private component, and the condition into a predicate the model returns.
- Consolidate Conditional Expression: one named boolean from the model, such as `canSubmit`, instead of the same chain of checks in several places.
- Replace Nested Conditional with Guard Clauses: early returns right after the component's hook calls for pending, error, and empty. Guard on `isPending`, never on `isFetching`, so a refetch keeps the content.
- Replace Conditional with Polymorphism: a `Record` map, a cva variant, or a discriminated union with one exhaustive `switch` ([design-patterns.md](design-patterns.md)), never a class hierarchy.
- Introduce Null Object: use it only in mappers, for a list the server may leave out (`items: dto.items ?? []`), so the UI never checks for `null`. Never give a query an empty `*Payload` as `initialData`, because the cache treats it as real, fresh data and skips the fetch until `staleTime` ends. Never give one as `placeholderData` either, because the UI would show the empty state while loading. Never replace `session: null` with a guest user, because the guards send a `null` session to login.
- Introduce Assertion: parse data you don't control with a valibot schema instead of an `as` cast, such as `storage.getJSON` results.
### Simplifying method calls
- Introduce Parameter Object: the endpoint's `*Args` type. Repositories take `(args, { signal })` and actions `(args, { emit })`, so a new field changes one type instead of every call.
- Preserve Whole Object: pass the `*Payload` item instead of several of its fields, between server components and inside a module. At a client boundary, pass only what the leaf needs, because props are serialized into the page ([b2c-b2b.md](b2c-b2b.md#rendering)).
- Replace Parameter with Method Call: a part gets its own data from its part model or a selector hook instead of props passed through several levels. What the page model shares still reaches the parts as props.
- Parameterize Method: merge near-identical components into one with a cva variant.
- Replace Parameter with Explicit Methods: split a component whose boolean prop switches its behavior into two components.
- Remove Parameter: delete a prop or `*Args` field that nobody passes. The `{ emit }` and `{ signal }` options stay.
- Separate Query from Modifier: reads live in models as queries. A mutation that only sends the request runs through `useMutation` in the model, and an operation with side effects beyond the request (store writes, storage, follow-up calls, its event) lives in an action. Render, selectors, mappers, and repository read methods never change state.
- Hide Method: keep internals out of `index.ts`. A feature never exports its `http.ts` client or any `*Dto`, and an organism never exports its `components/` or `hooks/`. The one exception is a compound component, whose `index.ts` re-exports its named parts ([design-patterns.md](design-patterns.md)).
- Replace Error Code with Exception: repositories throw the lib's `HttpError` and never return `null`, `false`, or `{ error }` for a failure. Actions let it propagate. For an action, the model catches it: `applyServerErrors` in a form, `showActionError` elsewhere. A failed read throws to its part or page boundary, which shows the `not-found` or `no-access` empty state for 404 and 403 and a fallback with Try again otherwise ([error-handling.md](error-handling.md)). The one place that turns errors back into values is `readOnServer` on the server, because a page must decide between `notFound()`, an empty state, and a boundary before it renders.
### Dealing with generalization
- Extract Interface: a type for a contract with more than one implementation or a test double, like `CookieAdapterAbstraction` ([lib-cookie.md](lib-cookie.md#types)).
- Replace Inheritance with Delegation: compose instead of extending. Use an island component through its `children`, slots, compound parts, or a new island variant, never a feature-level wrapper that restyles it. Build props types from existing ones with `Pick` and `Omit`.
The class-hierarchy techniques rarely apply, because the codebase avoids inheritance. Use these instead:
- Pull Up Method and Pull Up Field: a shared hook, util, or props type.
- Push Down Method and Push Down Field: move the code into the one component, or the field into the one union member, that uses it.
- Extract Superclass and Extract Subclass: a shared hook or base component that others compose, and a specialized component that composes the general one.
- Collapse Hierarchy: one component with a variant instead of near-identical ones.
- Form Template Method: a template with slots, or a hook that takes step callbacks.
## Review comments
Phrase a refactoring finding in the review format from [SKILL.md](../SKILL.md#7-review-stance): name the smell, or the rule when one is broken; show the problem with its file and its cost; and propose the technique with its target layer or file.
- A smell is a suggestion with a rationale. It blocks a merge only when it also breaks a rule on that section's blocking list, such as a boundary or layer violation or a stale cache after a mutation. Then lead with the rule, mark it blocking, and name the smell in the body.
- In a feature PR, raise smells only in the code the PR touches, and suggest a follow-up PR for the rest.
- Never flag the smells that are intended here.
> **Switch Statements (suggestion):** `OrderRow.tsx`, `OrderCard.tsx`, and `OrderHeader.tsx` each switch on `order.status` to pick a label and a badge color, so a new status needs three edits and nothing checks that all three were made. Replace Conditional with Polymorphism: one `Record` keyed by `OrderStatus`, holding the label key and the Badge variant, in `features/orders/constants.ts` (like `ORDER_STATUS_BADGES` in design-patterns.md), and island's `Badge` `variant` for the color. A new status then fails type-check until the map covers it.
> **Features import each other only through index.ts (blocking):** `features/cart/models/cart/use-cart-page.ts` imports `catalogHttp` and the catalog mappers to load the cart's products itself. That is Inappropriate Intimacy: the request skips catalog's repository, and any change inside catalog can break the cart. Move Method: add `listByIds` to the repository in `features/catalog/repositories/products/`, and import `productsRepository` through `features/catalog/index.ts`.

View File

@ -1,152 +0,0 @@
# Rendering and loading patterns
This file takes the rendering and performance patterns from patterns.dev and decides whether to use each one and which tool implements it. The playbook, [b2c-b2b.md](b2c-b2b.md), holds the details and wins on any conflict. Code-level patterns are in [design-patterns.md](design-patterns.md), and code smells in [refactoring.md](refactoring.md). Names match the source pages under patterns.dev/react/ and patterns.dev/vanilla/.
Contents: Rendering patterns · Loading patterns · Choosing where a part loads
## Rendering patterns
Apps render every page on the server for each request and stream it.
| Pattern | Use | How here |
|---|---|---|
| Client-side rendering | Parts only | A page renders only its browser-only parts in the browser ([b2c-b2b.md](b2c-b2b.md#data-flow)). |
| Server-side rendering | Always | Render every page fresh for each request, and read data through caches ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). |
| Static rendering | Never | Nothing renders at build time. Keep each request cheap instead (first note below). |
| Incremental static generation | Never | Nothing needs revalidating: after a mutation, `router.refresh()` renders the page again ([b2c-b2b.md](b2c-b2b.md#no-server-cache)). |
| Partial prerendering | Never | It needs Cache Components, which stay off. `loading.tsx` and `<Suspense>` give an early first paint instead ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| Streaming server-side rendering | Always | Stream every route as [b2c-b2b.md](b2c-b2b.md#rendering) describes, and make sure nothing buffers the response (second note below). |
| React Server Components | Default | Keep components on the server. Only interactive leaves get `'use client'` ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| Selective hydration | Automatic | Give each independent part its own `<Suspense>` boundary, so it hydrates on its own ([b2c-b2b.md](b2c-b2b.md#rendering)). |
| Progressive hydration | Through Suspense | Suspense boundaries already hydrate in pieces. To delay a part's JavaScript, keep its markup in a Server Component and load its client piece on visibility or interaction. A lazy-hydration library would be outside the stack. |
| Islands architecture | Through Server Components | It's unrelated to the island design system; only the name is shared. Server Components with small client leaves give its benefit: only the interactive parts ship JavaScript and hydrate. |
| View transitions | Rare, on Next.js 16.3 or later | React's `<ViewTransition>` with `next/link`'s `transitionTypes`. The App Router ships its own React, so the Next.js version decides: before 16.3 it needs an experimental flag, so wait. Animate only what helps orientation, such as a product image moving into its detail page, and turn it off under `prefers-reduced-motion`. |
- Apps render a fresh page for every request ([b2c-b2b.md](b2c-b2b.md#no-server-cache)), so static rendering, incremental static generation, and partial prerendering are not used. When a page is slow, stream its slow parts, fetch independent data in parallel with `Promise.all`, and fix or cache the slow call in the back end.
- Streaming works only when nothing between Next.js and the browser buffers the response. Turn buffering off in the reverse proxy and the CDN (for nginx, return `X-Accel-Buffering: no` from `headers()` in `next.config.ts`), or every page waits for its slowest part.
- Experimental APIs, such as `unstable_*` exports, canary-only React features, and Next.js `experimental.*` flags, stay unused until they're stable, unless the repo already enables them. `<ViewTransition>` counts as stable from React 19.3 and Next.js 16.3 (View transitions row). [SKILL.md](../SKILL.md) prefers boring, proven technology.
- Many patterns.dev examples use the Pages Router (`getServerSideProps`, `getStaticProps`, `next/head`), APIs removed in React 19, or libraries such as loadable-components and react-window. Take the idea and write the code with this stack's APIs.
## Loading patterns
The budgets these patterns protect are in [b2c-b2b.md](b2c-b2b.md#targets). Record each route's deferred parts and what triggers them in the plan (the PR description).
| Pattern | Use | How here |
|---|---|---|
| Static import | Default | A static import in a `'use client'` file ships to the browser. Put heavy modules behind a dynamic import. |
| Dynamic import | `next/dynamic` in a client component | Select the named export: `.then((mod) => mod.Chart)`. For code that isn't a component, use `await import()` in the event handler. In a `Record` map from key to component inside a client component, such as a CMS block type, make each heavy entry a `next/dynamic` component, so the map doesn't pull every entry into the route's bundle. A map in a Server Component needs nothing: only the client entries it renders ship. |
| Import on visibility | Widgets below the fold | Wrap the lazy component in island's `LoadOnVisible` primitive (code below). |
| Import on interaction | Heavy widgets and embeds | Start the download on `pointerenter` or `focus`, and render on click. A static facade (patterns.dev's word for a placeholder, unrelated to the GoF Facade in design-patterns.md) stands in for video, maps, and chat until then (code below). |
| Route-based splitting | Automatic | The App Router splits each route segment. |
| Bundle splitting | Automatic | Steer it with small client boundaries and dynamic imports rather than the bundler's chunk settings, and check each route against its budget. |
| Tree shaking | Always | Use named re-exports without `export *`, subpath imports, and `sideEffects` in every package ([project-structure.md](project-structure.md#exports-and-tree-shaking)). |
| PRPL | Built in | Preload critical files (next row). Render the route with the streamed server render. Pre-cache only through prefetch, because a service worker is outside the stack and needs approval. Lazy-load the rest with route splitting and dynamic imports. |
| Preload | LCP image, critical font | Preload what [b2c-b2b.md](ui-rules.md#images-fonts-and-css) lists, and use React 19's resource functions for other origins and late files (notes below). |
| Prefetch | `next/link` default | Keep `next/link`'s default prefetch (notes below). |
| Loading sequence | Always | Load the stylesheet, the critical font, and the LCP image first, then first-party JavaScript, then third parties after hydration. |
| Third-party loading | After hydration | Load from `packages/integrations` with `next/script` and `afterInteractive` or `lazyOnload` ([b2c-b2b.md](b2c-b2b.md#bundle-and-code-splitting)). `@next/third-parties` is outside the stack, and the `worker` strategy is experimental, doesn't work in the App Router, and needs Partytown, which is outside the stack. |
| List virtualization | Long interactive lists, with approval | Paginate on the server and try `content-visibility` first. The library is outside the stack (notes below). |
| Compressing JavaScript | CDN or proxy | Serve Brotli, with gzip as fallback, from the CDN or the reverse proxy. Budgets are measured gzipped. When the proxy compresses, set `compress: false` in `next.config.ts`. |
- On these dynamic routes, `next/link`'s default prefetch stops at the nearest `loading.tsx`, so a click shows the skeleton at once ([b2c-b2b.md](b2c-b2b.md#hydration-and-navigation)). Never set `prefetch={true}`: every link in the viewport would then ask the server for a full render, and the server caches nothing.
- The LCP image and the critical font follow [b2c-b2b.md](ui-rules.md#images-fonts-and-css). For anything else, use React 19's resource functions from `react-dom`: `preconnect` for an origin the first screen needs, `prefetchDNS` for one it needs later (such as an embed's host), and `preload` for a critical file the HTML references late. Call them during render or in an event handler; React dedupes the tags.
- Paginate lists on the server first. Give each row of a long, mostly static list a functional utility from island's `styles/utilities.css`, `@utility content-auto-* { content-visibility: auto; contain-intrinsic-size: auto calc(var(--spacing) * --value(integer)); }`, used as `content-auto-16`: off-screen rows skip rendering but stay in the DOM, so find-in-page and screen readers keep working. When an interactive list still renders more than about 200 rows, such as a feed, a log, or a large tree, propose `@tanstack/react-virtual` with the reason and its gzipped size, and add it only after approval ([SKILL.md](../SKILL.md#2-stack)).
`packages/island/src/primitives/load-on-visible/LoadOnVisible.tsx`. It shows the fallback until the element comes within the root margin of the viewport, then renders the children inside `<Suspense>` with the same fallback. The primitive doesn't import `next/dynamic`: the caller passes the lazy component as children, and the import starts when the child first renders. A chunk that fails to load reaches the part's own error boundary.
```tsx
'use client';
import { Suspense, useEffect, useRef, useState } from 'react';
import { LOAD_ON_VISIBLE_ROOT_MARGIN } from './constants';
import type { LoadOnVisibleProps } from './types';
export function LoadOnVisible({ children, fallback, rootMargin = LOAD_ON_VISIBLE_ROOT_MARGIN }: LoadOnVisibleProps) {
const ref = useRef<HTMLDivElement>(null);
const [isNear, setIsNear] = useState(false);
useEffect(() => {
const element = ref.current;
if (isNear || !element) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) setIsNear(true);
},
{ rootMargin },
);
observer.observe(element);
return () => observer.disconnect();
}, [isNear, rootMargin]);
return <div ref={ref}>{isNear ? <Suspense fallback={fallback}>{children}</Suspense> : fallback}</div>;
}
```
The module also has `types.ts` (`LoadOnVisibleProps`: `children`, `fallback`, and an optional `rootMargin`), `constants.ts` (`LOAD_ON_VISIBLE_ROOT_MARGIN = '200px 0px'`), and `index.ts`. It has no `variants.ts`, because it has no styles.
`apps/<app>/src/app/(shop)/product/[id]/organisms/price-history/PriceHistory.tsx`. The product template, a Server Component, renders this client leaf below the fold. Call `next/dynamic` in the same client component as `LoadOnVisible`: a client component that a Server Component imports already ships with the route, so wrapping it would defer only its render. Leave out `ssr: false` here, as [b2c-b2b.md](b2c-b2b.md#data-flow) allows: `LoadOnVisible` or the interaction already keeps the child out of the server render, and with `ssr: false` `next/dynamic` adds its own `<Suspense>` with an empty fallback, which would replace the skeleton or the facade. Where the dynamic component renders unconditionally, keep `ssr: false` and pass `loading: () => <SameSizeSkeleton />`, so its boundary never renders blank.
```tsx
'use client';
import { LoadOnVisible } from '@project/island/primitives/load-on-visible';
import dynamic from 'next/dynamic';
import { PriceHistorySkeleton } from './components/price-history-skeleton';
import type { PriceHistoryProps } from './types';
const PriceHistoryChart = dynamic(() =>
import('./components/price-history-chart').then((mod) => mod.PriceHistoryChart),
);
export function PriceHistory({ productId }: PriceHistoryProps) {
return (
<LoadOnVisible fallback={<PriceHistorySkeleton />}>
<PriceHistoryChart productId={productId} />
</LoadOnVisible>
);
}
```
`apps/<app>/src/app/(shop)/product/[id]/organisms/product-video/ProductVideo.tsx`. One module-level function holds the import, so the facade's intent events (`pointerenter` and `focus`) start the download before the click, and the dynamic component reuses that download. The click sets state inside a transition: React keeps the facade on screen until the chunk arrives, and `isStarting` drives its loading state. The intent download ignores its own failure; the click retries through `next/dynamic`, and a failure there reaches the part's error boundary. A facade lives with its widget, in a route organism or, for a third-party embed such as chat, in the integration's `components/`.
```tsx
'use client';
import dynamic from 'next/dynamic';
import { useState, useTransition } from 'react';
import { useTranslation } from 'react-i18next';
import { VideoFacade } from './components/video-facade';
import type { ProductVideoProps } from './types';
const loadVideoPlayer = () => import('./components/video-player');
const VideoPlayer = dynamic(() => loadVideoPlayer().then((mod) => mod.VideoPlayer));
export function ProductVideo({ video }: ProductVideoProps) {
const { t } = useTranslation('catalog');
const [isPlaying, setIsPlaying] = useState(false);
const [isStarting, startTransition] = useTransition();
if (isPlaying) return <VideoPlayer src={video.url} autoPlay />;
return (
<VideoFacade
posterUrl={video.posterUrl}
label={t('product.video.play', { name: video.title })}
isLoading={isStarting}
onIntent={() => {
loadVideoPlayer().catch(() => undefined);
}}
onPlay={() => startTransition(() => setIsPlaying(true))}
/>
);
}
```
## Choosing where a part loads
Ask about each part of a page in this order. Every match adds to the answer, so one part can use several steps: a product gallery renders its first image on the server (1), makes its thumbnails a small client leaf (2), and loads its zoom viewer only when the user opens it (3 and 4). Data details are in [b2c-b2b.md](b2c-b2b.md#data-flow).
1. Search engines or the first paint need it → a Server Component that reads caches, inside `<Suspense>` with a same-size skeleton when it's slow.
2. The user interacts with it → only the interactive piece becomes a client leaf, driven by its part model, with server data as props or through query hydration.
3. It's personal, below the fold, or shown only on interaction, and search engines don't need it → a browser-only part: `useQuery` with a skeleton, or `next/dynamic`: with `ssr: false` when it renders unconditionally, without it inside `LoadOnVisible` or behind an interaction (see the `PriceHistory` note).
4. Its code is heavy, or it's a third party → a dynamic import that starts on visibility or interaction, behind a same-size skeleton or a facade. Third-party scripts use `next/script` with `afterInteractive` or `lazyOnload`.

View File

@ -1,60 +0,0 @@
# UI rules
UX, SEO, and asset rules for [b2c-b2b.md](b2c-b2b.md). Read it when you build or change what the user sees or what search engines read: a page, template, organism, form, copy, upload, image, font, or metadata. Work only on repositories, caches, actions, stores, or libs doesn't need it.
Contents: Images, fonts, and CSS · SEO and i18n · Copy · Feedback · Stability · Loading, progress, and empty states · File uploads · Forms · Keyboard and context
## Images, fonts, and CSS
- Use `next/image` with explicit dimensions and `sizes`. Never lazy-load the LCP image: give it `loading="eager"` and `fetchPriority="high"`, or `preload` when it's discovered late. `priority` is deprecated in Next.js 16. Everything below the fold stays lazy.
- Fonts come from `island/fonts` as variable woff2. Preload only the critical face, use `font-display: swap`, and use a size-adjusted fallback so the swap doesn't shift layout. `next/font/local` does both.
- Reserve space for images, banners, ads, and embeds with fixed aspect ratios.
- Register every project whose components use Tailwind classes as a source (see code-patterns.md).
## SEO and i18n
- Build `generateMetadata` from `configs/seo.ts`: title, description, canonical URL, `hreflang` alternates, and Open Graph. Add JSON-LD for products, breadcrumbs, and the organization. Provide `sitemap.ts` and `robots.ts`.
- Server Components translate with a per-request i18next instance from `apps/<app>/src/i18n/`; react-i18next hooks run only in client components. Set `lang` and `dir` on `<html>` from the locale.
## Copy
- Every label, button, tooltip, and message is a simple, complete description of its purpose. Buttons name the action and its object ("Add this item to the cart", not "Add"). Headings describe their content. Tooltips describe the outcome, not the control.
- Error messages have three parts: what went wrong, why (if known), and what the user can do. "The file could not be uploaded because it is larger than 10 MB. Compress the image or choose a smaller file, then try again."
- Empty states say what would normally be here, why it is empty, and the next step, with a primary action when there is one: "Your cart is empty. Browse today's offers to find something you like." plus a "See offers" button.
## Feedback
- Every completed action shows a toast that says exactly what was done, naming the object when possible: "'Wireless headphones' was added to your cart". Success toasts auto-dismiss after 4–6 s. Error toasts come from `showActionError` ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)): they stay until dismissed, name what failed, carry the hint or a support sentence with the reference ID, and offer Try again or Reload when the error's cause allows it.
- Destructive actions ask for confirmation, naming the object and the consequence: "Remove the saved address 'Home'? This cannot be undone."
- Prefer reversible designs: "Undo" in the toast when the back end supports it.
## Stability
Refetches, state updates, and re-renders must never make the UI disappear and reappear.
- Never switch between `isLoading ? <Spinner /> : <List />` on refetch. Keep showing the data with a subtle inline indicator driven by `isFetching`.
- Keep layout containers mounted and swap only their contents.
- Use skeletons with the final content's dimensions, and reserve space for images and embeds with fixed aspect ratios.
- A part whose model uses `useSuspenseQuery` changes its query key inside `startTransition`, so a page or filter change keeps the current content instead of falling back to the skeleton.
## Loading, progress, and empty states
- Design the loading and empty states together with the populated state. Loading states are skeletons that match the final layout. Empty states use island's `EmptyState` (`no-data`, `no-results`, `not-found`, `no-access`) with one sentence and a primary action when there is one ([error-handling.md](error-handling.md#empty-states)).
- Anything that takes more than about 2 seconds shows progress and the current step. Never show a bare spinner for more than 3 seconds.
- The clicked button shows a spinner, becomes disabled, and changes its label to the in-progress form ("Placing order…"). The rest of the form stays visible and read-only.
## File uploads
- Every upload shows a progress bar with a numeric percentage ("Uploading… 63%"), the file name and size, a cancel button while uploading, and a clear success or failure state with a retry action. Uploads go through the feature client's `upload()`: its `onProgress` drives the bar, and the cancel button aborts the `signal`. Uploads never retry automatically; the retry action sends the file again (see [lib-http.md](lib-http.md#files)).
## Forms
- Validate on the client with valibot before submitting, and show errors inline under the field in plain language that says how to fix them ("Enter a 10-digit postal code without spaces."). Validate on blur first, then on change (`mode: 'onTouched'`).
- Put server errors in the right place (code in code-patterns.md) and scroll to and focus the first invalid field.
- Disable the submit button only while submitting, never because the form is invalid; users need to click it to find out what's wrong.
## Keyboard and context
- Tab order follows reading order, Enter submits, and Esc closes. Set sensible default focus and keep primary actions in consistent places.
- Preserve context: filters, sort, page, and scroll position survive navigating to a detail page and back. Filters, sort, and page live in the URL, so views are shareable and survive a refresh.
- Respect `prefers-reduced-motion` and `prefers-color-scheme`.

59
.gitignore vendored
View File

@ -1,59 +0,0 @@
# Dependencies
node_modules
.pnpm-store
# Nx
.nx/installation
.nx/cache
.nx/workspace-data
.nx/self-healing
.nx/migrate-runs
.nx/polygraph
# Claude Code
.claude/worktrees
.claude/settings.local.json
# Build output
dist
out
out-tsc
tmp
build
*.tsbuildinfo
# Next.js
.next
next-env.d.ts
.vercel
# Testing
coverage
test-output
.vitest
playwright-report
test-results
# Env (keep examples committed)
.env
.env.*
!.env.example
# Logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
# OS / editors
.DS_Store
Thumbs.db
*.swp
.idea
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
# graft's local graph cache — regenerable, not committed (run `graft build`).
/graft/

View File

@ -1,5 +0,0 @@
# graft's cards are gitignored but should stay greppable: ripgrep reads
# .ignore before .gitignore, so this re-admits the tree to search only.
!graft/
graft/.cache/
graft/.graph/

View File

@ -1,27 +0,0 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": [
"typescript",
"unicorn",
"oxc",
"react",
"nextjs",
"jsx-a11y",
"import"
],
"categories": {
"correctness": "error"
},
"rules": {},
"env": {
"builtin": true,
"browser": true,
"node": true
},
"ignorePatterns": [
"**/.next/**",
"**/dist/**",
"**/out-tsc/**",
"**/next-env.d.ts"
]
}

View File

@ -1,6 +0,0 @@
# Add files here to ignore them from prettier formatting
/dist
/coverage
/.nx/cache
/.nx/workspace-data
pnpm-lock.yamlgraft/

View File

@ -1,3 +0,0 @@
{
"singleQuote": true
}

View File

@ -1,24 +0,0 @@
<!-- nx configuration start-->
<!-- Leave the start & end comments to automatically receive updates. -->
# General Guidelines for working with Nx
- For navigating/exploring the workspace, invoke the `nx-workspace` skill first - it has patterns for querying projects, targets, and dependencies
- When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task through `nx` (i.e. `nx run`, `nx run-many`, `nx affected`) instead of using the underlying tooling directly
- Prefix nx commands with the workspace's package manager (e.g., `pnpm nx build`, `npm exec nx test`) - avoids using globally installed CLI
- You have access to the Nx MCP server and its tools, use them to help the user
- For Nx plugin best practices, check `node_modules/@nx/<plugin>/PLUGIN.md`. Not all plugins have this file - proceed without it if unavailable.
- NEVER guess CLI flags - always check nx_docs or `--help` first when unsure
## Scaffolding & Generators
- For scaffolding tasks (creating apps, libs, project structure, setup), ALWAYS invoke the `nx-generate` skill FIRST before exploring or calling MCP tools
## When to use nx_docs
- USE for: advanced config options, unfamiliar flags, migration guides, plugin configuration, edge cases
- DON'T USE for: basic generator syntax (`nx g @nx/react:app`), standard commands, things you already know
- The `nx-generate` skill handles generator discovery internally - don't call nx_docs just to look up generator syntax
<!-- nx configuration end-->

View File

@ -1,30 +0,0 @@
{
"jsc": {
"target": "es2017",
"parser": {
"syntax": "typescript",
"decorators": true,
"dynamicImport": true
},
"transform": {
"decoratorMetadata": true,
"legacyDecorator": true
},
"keepClassNames": true,
"externalHelpers": true,
"loose": true
},
"module": {
"type": "commonjs"
},
"sourceMaps": true,
"exclude": [
"jest.config.[ct]s",
".*\\.spec.tsx?$",
".*\\.test.tsx?$",
"./src/jest-setup.ts$",
"./**/jest-setup.ts$",
".*.js$",
".*.d.ts$"
]
}

View File

@ -1,3 +0,0 @@
import baseConfig from '../../eslint.config.mjs';
export default baseConfig;

View File

@ -1 +0,0 @@
/// <reference types="@nx/next/typings/style.d.ts" />

View File

@ -1,35 +0,0 @@
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
// Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [
'@lumina/market',
'@lumina/integrations',
'@lumina/island',
'@lumina/libs',
'@lumina/tools',
],
// `/@{username}` is the public channel URL. A folder named `@…` is a
// parallel-route slot in the App Router, so the routes live under
// `channels/[username]` and the public URL is rewritten onto them.
async rewrites() {
return [
{
source: '/@:username/:path*',
destination: '/channels/:username/:path*',
},
];
},
// One canonical URL per channel: send direct `/channels/…` hits to `/@…`.
async redirects() {
return [
{
source: '/channels/:username/:path*',
destination: '/@:username/:path*',
permanent: true,
},
];
},
};
export default nextConfig;

View File

@ -1,23 +0,0 @@
{
"name": "@lumina/bear",
"version": "0.0.1",
"private": true,
"nx": {
"name": "bear",
"sourceRoot": "apps/bear/src",
"tags": [
"type:app",
"scope:market"
]
},
"dependencies": {
"@lumina/market": "workspace:*",
"@lumina/integrations": "workspace:*",
"@lumina/island": "workspace:*",
"@lumina/libs": "workspace:*",
"@lumina/tools": "workspace:*",
"next": "~16.1.6",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
}

View File

@ -1,5 +0,0 @@
export default {
plugins: {
'@tailwindcss/postcss': {},
},
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1,16 +0,0 @@
import type { ReactNode } from 'react';
import { yekanBakh, yekanBakhLatin } from '../styles';
import '../styles/app.css';
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html
lang="fa"
dir="rtl"
className={`${yekanBakh.variable} ${yekanBakhLatin.variable}`}
>
<body>{children}</body>
</html>
);
}

View File

View File

@ -1,6 +0,0 @@
@import 'tailwindcss' source('../');
@import '@lumina/island/styles/island.css';
/* Workspace projects that render UI in this app. island registers itself. */
@source '../../../../platforms/market/src';
@source '../../../../packages/integrations/src';

View File

@ -1,23 +0,0 @@
import localFont from 'next/font/local';
// Variable fonts from island. next/font self-hosts them, preloads the critical face,
// and adds a size-adjusted fallback so the swap doesn't shift the layout.
/** Yekan Bakh with Persian digit shapes: every UI text. */
export const yekanBakh = localFont({
src: '../../../../packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2',
variable: '--font-yekan-bakh',
weight: '100 950',
display: 'swap',
adjustFontFallback: 'Arial',
});
/** Yekan Bakh with Latin digits: شبا and other bank codes. Loaded only where used. */
export const yekanBakhLatin = localFont({
src: '../../../../packages/island/src/fonts/yekan-bakh-vf.woff2',
variable: '--font-yekan-bakh-latin',
weight: '100 950',
display: 'swap',
preload: false,
adjustFontFallback: 'Arial',
});

View File

@ -1 +0,0 @@
export { yekanBakh, yekanBakhLatin } from './fonts';

View File

@ -1,66 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "preserve",
"noEmit": true,
"emitDeclarationOnly": false,
"esModuleInterop": true,
"resolveJsonModule": true,
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
},
"outDir": "dist",
"rootDir": "src",
"tsBuildInfoFile": "dist/tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.js",
"src/**/*.jsx",
"../../apps/bear/.next/types/**/*.ts",
"../../dist/apps/bear/.next/types/**/*.ts",
"index.d.ts",
"next-env.d.ts"
],
"exclude": [
"out-tsc",
"dist",
"node_modules",
"jest.config.ts",
"jest.config.cts",
"src/**/*.spec.ts",
"src/**/*.test.ts",
".next",
"eslint.config.js",
"eslint.config.cjs",
"eslint.config.mjs"
],
"references": [
{
"path": "../../packages/tools"
},
{
"path": "../../packages/libs"
},
{
"path": "../../packages/island"
},
{
"path": "../../packages/integrations"
},
{
"path": "../../platforms/market"
}
]
}

View File

@ -1,30 +0,0 @@
{
"jsc": {
"target": "es2017",
"parser": {
"syntax": "typescript",
"decorators": true,
"dynamicImport": true
},
"transform": {
"decoratorMetadata": true,
"legacyDecorator": true
},
"keepClassNames": true,
"externalHelpers": true,
"loose": true
},
"module": {
"type": "commonjs"
},
"sourceMaps": true,
"exclude": [
"jest.config.[ct]s",
".*\\.spec.tsx?$",
".*\\.test.tsx?$",
"./src/jest-setup.ts$",
"./**/jest-setup.ts$",
".*.js$",
".*.d.ts$"
]
}

View File

@ -1,3 +0,0 @@
import baseConfig from '../../eslint.config.mjs';
export default baseConfig;

View File

@ -1 +0,0 @@
/// <reference types="@nx/next/typings/style.d.ts" />

View File

@ -1,35 +0,0 @@
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
// Workspace packages export TypeScript source, so Next.js compiles them.
transpilePackages: [
'@lumina/market',
'@lumina/integrations',
'@lumina/island',
'@lumina/libs',
'@lumina/tools',
],
// `/@{username}` is the public channel URL. A folder named `@…` is a
// parallel-route slot in the App Router, so the routes live under
// `channels/[username]` and the public URL is rewritten onto them.
async rewrites() {
return [
{
source: '/@:username/:path*',
destination: '/channels/:username/:path*',
},
];
},
// One canonical URL per channel: send direct `/channels/…` hits to `/@…`.
async redirects() {
return [
{
source: '/channels/:username/:path*',
destination: '/@:username/:path*',
permanent: true,
},
];
},
};
export default nextConfig;

View File

@ -1,23 +0,0 @@
{
"name": "@lumina/bull",
"version": "0.0.1",
"private": true,
"nx": {
"name": "bull",
"sourceRoot": "apps/bull/src",
"tags": [
"type:app",
"scope:market"
]
},
"dependencies": {
"@lumina/market": "workspace:*",
"@lumina/integrations": "workspace:*",
"@lumina/island": "workspace:*",
"@lumina/libs": "workspace:*",
"@lumina/tools": "workspace:*",
"next": "~16.1.6",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
}

View File

@ -1,5 +0,0 @@
export default {
plugins: {
'@tailwindcss/postcss': {},
},
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1,16 +0,0 @@
import type { ReactNode } from 'react';
import { yekanBakh, yekanBakhLatin } from '../styles';
import '../styles/app.css';
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html
lang="fa"
dir="rtl"
className={`${yekanBakh.variable} ${yekanBakhLatin.variable}`}
>
<body>{children}</body>
</html>
);
}

View File

View File

@ -1,6 +0,0 @@
@import 'tailwindcss' source('../');
@import '@lumina/island/styles/island.css';
/* Workspace projects that render UI in this app. island registers itself. */
@source '../../../../platforms/market/src';
@source '../../../../packages/integrations/src';

View File

@ -1,23 +0,0 @@
import localFont from 'next/font/local';
// Variable fonts from island. next/font self-hosts them, preloads the critical face,
// and adds a size-adjusted fallback so the swap doesn't shift the layout.
/** Yekan Bakh with Persian digit shapes: every UI text. */
export const yekanBakh = localFont({
src: '../../../../packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2',
variable: '--font-yekan-bakh',
weight: '100 950',
display: 'swap',
adjustFontFallback: 'Arial',
});
/** Yekan Bakh with Latin digits: شبا and other bank codes. Loaded only where used. */
export const yekanBakhLatin = localFont({
src: '../../../../packages/island/src/fonts/yekan-bakh-vf.woff2',
variable: '--font-yekan-bakh-latin',
weight: '100 950',
display: 'swap',
preload: false,
adjustFontFallback: 'Arial',
});

View File

@ -1 +0,0 @@
export { yekanBakh, yekanBakhLatin } from './fonts';

View File

@ -1,66 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "preserve",
"noEmit": true,
"emitDeclarationOnly": false,
"esModuleInterop": true,
"resolveJsonModule": true,
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
},
"outDir": "dist",
"rootDir": "src",
"tsBuildInfoFile": "dist/tsconfig.tsbuildinfo"
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.js",
"src/**/*.jsx",
"../../apps/bull/.next/types/**/*.ts",
"../../dist/apps/bull/.next/types/**/*.ts",
"index.d.ts",
"next-env.d.ts"
],
"exclude": [
"out-tsc",
"dist",
"node_modules",
"jest.config.ts",
"jest.config.cts",
"src/**/*.spec.ts",
"src/**/*.test.ts",
".next",
"eslint.config.js",
"eslint.config.cjs",
"eslint.config.mjs"
],
"references": [
{
"path": "../../packages/tools"
},
{
"path": "../../packages/libs"
},
{
"path": "../../packages/island"
},
{
"path": "../../packages/integrations"
},
{
"path": "../../platforms/market"
}
]
}

View File

@ -1,426 +0,0 @@
# Design Brief — Lumina (لومینا) · Verified Financial Creator Platform · MVP Phase 0
> Sources: PRD MVP Phase 0 v3.1 + ClickUp stories (23 tasks) + back-end codebase (`trading-platform` @ `3553719`).
> **Precedence:** ClickUp story > PRD for *behaviour*. The back end is used for *data shapes* and wherever a story is silent. Where a story and the back end conflict, **design to the story** and treat the conflict as an open decision (§9).
> Full acceptance criteria and exact Farsi copy for each story are in the `round-*.md` files. Attach the matching round file with this brief.
---
## 1. Product in one paragraph
Lumina is a platform for Iranian financial creators (analysts, signal providers) and the investors who follow them. Creators get a verified professional profile, a channel with free and premium posts, invite-only paid subscriptions, and **structured, immutable predictions** that the system tracks automatically. Investors can judge a creator by a **verifiable track record** before paying.
The core positioning is **performance proof over social proof**. The product must feel credible and professional, not like another Telegram channel. Because of this, follower counts are never shown publicly, and prediction outcomes are never hidden behind the paywall.
Phase 0 is a **closed beta**: 5–10 hand-picked creators and about 50 paying subscribers.
---
## 2. Platform and locale (confirmed)
| Topic | Decision |
|---|---|
| Stack | NX monorepo + Next.js, one responsive web app for **mobile and desktop** |
| Priority | **Mobile-first** for investor and creator surfaces; **desktop-first** for the admin panel (mobile = simplified card list) |
| Direction | **RTL** throughout. LTR exceptions: شبا field, URLs, usernames, tickers, signed amounts (§4.4) |
| Language | Persian. Persian digits (۰–۹) in UI, `٬` as thousands separator |
| Currency | تومان, whole numbers only |
| Dates | Shamsi (Jalali), e.g. `۱۵ خرداد ۱۴۰۴، ساعت ۱۴:۳۰`. Relative for recent items: همین الان · ۵ دقیقه پیش · ۲ ساعت پیش · دیروز. Timezone Asia/Tehran |
| Auth | Iranian mobile number (09XXXXXXXXX) + 5-digit SMS OTP. One entry screen for login and registration. Investor and creator accounts are separate (one number = one role) |
| Notifications | SMS + in-app only (push is deferred to Phase 1) |
| Payment | ZarinPal only |
| URLs | Channel `lumina.ir/@{username}`, post `lumina.ir/@{username}/posts/{post_id}`, finance `lumina.ir/dashboard/finance` |
---
## 3. Navigation and information architecture
### 3.1 Investor
- **Top bar:** notification bell with unread badge (99+). It opens a slide-in panel from the right on mobile.
- **Bottom nav:** خانه (feed + creator search) · داشبورد
- **داشبورد sub-sections:** اشتراک‌ها · تراکنش‌ها · دنبال‌شده‌ها
- **Reached from links:** creator channel, standalone post, checkout, track record page
- **Logged-out visitors** can browse channels and free posts via shared links. Every gated action leads to one CTA, **ورود/ثبت‌نام**, and the user returns to the same page after auth.
### 3.2 Creator
- **Top bar:** avatar opens **اطلاعات کاربری** (profile edit + verification status, C3). The notification bell is assumed to be shared with investors.
- **Bottom nav:** داشبورد · کانال, plus a center **FAB `+ انتشار`** that opens a mini menu with **پست جدید** and **پیشبینی جدید**.
- **داشبورد contents:** overview stats (C9, not yet specced) · **قیمت‌گذاری اشتراک** (C7) · **مالی** (C19 + C20).
- **First-run onboarding** (C1 then C2) is mandatory and can't be exited. There is no back button, and the Android back gesture is suppressed.
### 3.3 Admin (desktop)
- **Sidebar:** احراز هویت کریتورها (with a red pending-count badge) · مدیریت کریتورها · then the other sections from PRD Epic 3/11 (not yet specced).
---
## 4. Design system ("Stripe-inspired")
> Only the tokens referenced in the stories are listed here. **If you have the full design-system file, attach it.** It fills in the values marked "?".
### 4.1 Tokens
| Token | Value | Used for |
|---|---|---|
| `colors.primary` | `#533afd` | Primary CTA, verified, active, success, selected |
| `colors.primary-deep` | ? | Text on soft tags |
| `colors.primary-bg-subdued-hover` | `#b9b9f9` | Soft tag background, unread notification border |
| `colors.brand-dark-900` | `#1c1e54` | **پریمیوم** badge, primary financial figure |
| `colors.ink` | ? | Body text |
| `colors.ink-mute` | `#64748d` | Secondary text, pending, neutral and expired badges, icons |
| `colors.canvas` | `#ffffff` | Cards, sheets |
| `colors.canvas-soft` | `#f6f9fc` | Page backgrounds, locked placeholders, highlighted blocks |
| `colors.hairline` / `hairline-input` | ? | Borders, dividers, input borders |
| `colors.ruby` | `#ea2261` | Errors, critical/urgent, destructive, rejected, suspended, negative balance, **and the تخفیف badge** (its only affirmative use) |
| `colors.warning` | `#f59e0b` | Time-sensitive warnings, pending payment, non-blocking cautions, preview-mode banner |
| Typography | `heading-md`, `heading-sm`, `body-md`, `caption`, `micro` | Font **Yekan Bakh** for all Farsi |
| Radius | `rounded.md`, `rounded.lg`, `rounded.xl`, pill | |
| Shadow | Level 1 (cards), Level 2 (menus, popovers, sheets) | |
### 4.2 Components
`button-primary-pill` · `button-secondary` (outline, primary text; **ruby variant** for destructive admin actions) · `pill-tag-soft` · `card-feature-light` (canvas, hairline border, rounded.lg, Level 1) · `text-input` (focus border = primary) · `link-on-light` · snackbar/toast · modal · bottom sheet (mobile) / popover or side panel (desktop) · full-screen image lightbox (black background, swipe, pinch-zoom, `۱ / ۳` counter) · status badge · countdown.
### 4.3 Global rules
- **Tabular figures** (`font-feature-settings: "tnum"`) on every number: prices, dates, OTP, stats, reference numbers, countdowns. This is non-negotiable and part of the brand's financial look.
- **Frozen controls** stay visible at `opacity: 0.4` with `cursor: not-allowed`, and show an explanatory tooltip or message on tap. Controls are never hidden just because they're unavailable.
- **Dimmed or unavailable items** (for example a suspended creator) use `opacity: 0.5` with a lock icon. Any action that still works inside the item renders at full opacity.
- **Touch targets** are at least 44×44px.
- **Desktop column widths:** forms 560px · content and post pages 640px · checkout 480px.
- **Data safety:** on any network failure the entered data is kept. Errors appear inline under fields, and an error banner appears at the top for submit failures.
### 4.4 Numbers and RTL
- Signed amounts are wrapped in an LTR isolate, so the minus sign stays left of the digits: `−۱۲۰٬۰۰۰ تومان`. The word تومان sits outside the isolate.
- شبا renders LTR in groups of four: `IR62 0120 0000 0010 1234 5678 90`.
---
## 5. Cross-cutting patterns
### 5.1 Viewer states (channel, post page, feed)
| Viewer | Content | Follow | Subscribe |
|---|---|---|---|
| Logged-out | Free posts in full, premium as locked teasers | Shown; leads to auth | Shown; leads to auth |
| Logged in, not following | Same | دنبال کردن | اشتراک |
| Following, not subscribed | Same | دنبال نکردن | اشتراک |
| Waitlisted | Same | As applicable | **اشتراک stays live**, with a quiet note underneath and a لغو اطلاع‌رسانی link |
| Payment pending | Same | As applicable | Frozen indicator «پرداخت در حال بررسی» with a clock icon |
| Active subscriber | Everything unlocked, پریمیوم badge still shown | **Frozen** (can't unfollow while subscribed) | Replaced by the indicator «مشترک هستید ✓» |
| Creator (own channel) | Everything, plus share/edit/delete | Hidden | Hidden |
| Creator in "view as visitor" preview | Locked teaser, with an amber banner and «خروج از پیش‌نمایش» | n/a | n/a |
### 5.2 Locked premium post (one shared component everywhere: channel, post page, feed)
- The header row (avatar, username, timestamp, **پریمیوم** badge) is always visible.
- **Text:** only the first 2 lines are shown, fading into the canvas color with a centered lock icon. Two lines is a hard limit, so no analysis leaks.
- **Images:** never shown and never blurred. A generic lock placeholder on canvas-soft replaces them, with an optional «۳ تصویر» count badge.
- **Premium prediction:** asset, direction, entry, targets, stop loss and horizon are all hidden. Only the card frame, the پریمیوم badge and the status remain.
- **Data note:** the API sends `captionPreview` (first 140 characters) and `mediaPreview` with a `blurHash`. **Clamp the preview visually to 2 lines and never render the blurHash.** The rule against blurred images comes first.
- Below the locked content: one message and one CTA, depending on auth state. Logged-out users see «ورود/ثبت‌نام». Logged-in users see «اشتراک در کانال». The two are never shown together.
- There is no "you used to have access" variant after a subscription lapses.
### 5.3 Creator verification gating
- **States:** در انتظار احراز هویت (ink-mute, clock icon) · تأییدشده ✓ (primary, check icon) · رد شده (ruby, warning icon). Suspended is a separate admin state that can coexist with these.
- **For a creator who isn't yet Verified:**
- A persistent, non-dismissible banner sits on the کانال tab. It's informational when Pending. When Rejected, it shows the reason and is tappable to C3.
- A compact badge shows on داشبورد.
- The FAB and the channel share icon are frozen.
- Pricing and profile can still be edited.
- Payout details (شبا) are locked.
- **Identity fields** lock at first submission and reopen only on rejection. The username can never be changed. The national ID card image field is always empty when the form opens.
### 5.4 Time-based states
- **Post edit window:** 15 minutes after publishing. After that the edit icon is frozen and shows a tooltip. Edited posts show a «ویرایش‌شده» label in micro type. Posts can be deleted at any time; predictions can't (per the PRD).
- **Subscription remaining time:**
| Remaining | Label | Color | Warning under card |
|---|---|---|---|
| More than 7 days | {n} روز مانده | ink-mute | — |
| 4–7 days | {n} روز مانده | warning | — |
| 3 days or less | کمتر از {n} روز مانده | ruby | Yes |
- **Promotion countdown:** a plain date when more than 48 hours remain, a live «{n} ساعت باقی مانده» in warning color at 48 hours or less, and nothing at all for an indefinite promotion. There is no fake urgency.
- **OTP:** a 2-minute countdown that turns ruby in the last 30 seconds. Resend is available only after expiry. After 3 failed attempts the user is blocked for 10 minutes.
### 5.5 Status vocabulary
| Domain | States (Farsi label · color) |
|---|---|
| Subscription | فعال · primary — منقضی‌شده · ink-mute (neutral, not an error) — suspended creator: card dimmed + «درخواست بازگشت وجه» action — refund requested: «درخواست بازگشت وجه در حال بررسی» |
| Transaction | موفق · primary — ناموفق · ruby (ruby start border on row) — در حال بررسی · warning (warning start border, pinned to top) |
| Transaction type | اشتراک جدید · تمدید اشتراک · فعال‌سازی مجدد |
| Tier | ماهانه · سه‌ماهه · شش‌ماهه · سالانه |
| Payout | در حال انجام · ink-mute pill — انجام شده · no pill — لغو شده · ruby pill + struck-through amount |
| Ledger entry | درآمد اشتراک (+) · واریز به حساب (−) · کسر بازگشت وجه (−) · اصلاحیه (±). Amounts in ink color; the sign carries the meaning |
| Creator account (admin) | Active · primary + check — Suspended · ruby + ban icon, row tinted `rgba(234,34,97,0.05)` |
### 5.6 Prediction card (no ClickUp story yet; fields from the back end, rules from the PRD)
**Fields as the API returns them:**
| Field | Shape | Display |
|---|---|---|
| `symbol` | free text, uppercased (`XAUUSD`, `BTCUSDT`, `TEDPIX`) | LTR, prominent |
| `market` | one of the market keys (§10.2) | soft tag with its Farsi label |
| `direction` | `long` / `short` | Labels خرید / فروش (Long / Short) with an arrow icon. Never rely on color alone |
| `entryPrice` | number | tabular |
| `targetPrices[]` | **1 or more** numbers | Design for 1–3 targets (T1, T2, T3) |
| `stopLoss` | number, optional | Show when present; hide the row when absent |
| `horizon` | free label, for example `2w`, `45d` | Shown as a label. Show time remaining only when `expiresAt` exists |
| `caption` | text | Acts as the creator's note / rationale |
| `publishedAt` | system timestamp | **Prominent**; it is the trust signal |
| `status` | `open` / `closed` | |
| `outcome` | `win` / `loss` / **`breakeven`** | Three closed states |
| `closedPrice`, `closedAt` | on close | Show with the outcome |
| ROI | computed: (closed − entry) / entry, reversed for short | Signed percent, LTR-isolated |
- **States to design:** open · closed-win · closed-loss · closed-breakeven · premium-locked (§5.2) · owner view (with a «بستن پیشبینی» action that asks for the closing price, since closing is currently done by the creator).
- **Immutability:** prediction fields can't be edited after publishing. Show a lock cue and the timestamp. The PRD's 15-minute window and edit history don't exist yet (§9).
- **Variants:** compact (feed, channel) and expanded (post page). It also appears on the track record page, the creator dashboard and admin screens.
- **No market snapshot image for now:** a prediction post can't carry media in the API.
**Creator stats block** (U6, channel header):
- **Metrics:** نرخ موفقیت (`winRate`, already a percent such as `62.86` → `۶۲٫۹٪`) · کل پیشبینی‌ها · پیشبینی‌های فعال · بازدهی (`avgRoiPercent`) · روند دقت · and a CTA «مشاهده کارنامه کامل».
- **روند دقت is the last 10 outcomes** (`["win","loss","win",…]`). Design it as a row of 10 small outcome markers (win / loss / breakeven), not a line chart. A wins / losses / breakeven split is also available.
- **When the block shows:** the U6 rule is all or nothing. It's absent until the activation threshold is met or when the creator hides it. No zeros, no placeholder.
---
## 6. Screen inventory
Status key: ✅ fully specced in ClickUp · 📄 PRD only (design at lower fidelity, expect changes).
### 6.1 Auth and onboarding
| # | Screen | Story | Key states |
|---|---|---|---|
| 1 | ورود یا ثبت‌نام (mobile number) | U1, C1 | Invalid format · number belongs to the other role · network error |
| 2 | OTP | U1, C1 | Countdown · wrong code · expired · blocked 10 min (full screen) · resend |
| 3 | Investor تکمیل پروفایل (first and last name in Persian, username) | U1 | Live username check (available ✓, taken, invalid) · immutability note · step indicator without a total count |
| 4 | Login success modal / suspended-account screen | U1, A2 | |
| 5 | Creator KYC form (username, first and last name, national ID, ID card image) | C1 | Field validation · upload errors · no exit |
| 6 | Creator تکمیل پروفایل (bio, avatar crop, links, market tags, T&C) | C2 | Toast on load · 8-link limit (frozen add button) · drag reorder · quick-add (Telegram, Instagram, X, YouTube) · success screen «پروفایل ذخیره شد» |
| 7 | اطلاعات کاربری (creator profile edit) | C3 | Verified/Pending (identity locked) · Rejected (banner + editable identity + «ارسال مجدد اطلاعات هویتی») · two independent save actions · unsaved-changes dialog |
### 6.2 Investor
| # | Screen | Story | Key states |
|---|---|---|---|
| 8 | **Creator channel** `/@username` (header + post list) | U6, C4 §12, U8 | All viewer states (§5.1) · stats present or absent · empty channel · suspended channel |
| 9 | **Standalone post page** | C4b | Free · locked · subscriber · owner · visitor preview · deleted (404) · channel suspended · desktop share popover / mobile native share |
| 10 | خانه feed + creator search | 📄 Epic 7, U7 | Empty state «follow someone» + CTA · locked cards inline in chronological order |
| 11 | **Checkout** «خرید اشتراک» (one screen) | U9 | Tier cards with total, per-month and strike-through · promotion badge and countdown · referral code (valid ✓ / invalid) · frozen CTA · no code · price-changed modal · waitlist offer modal · already-waitlisted modal · pay CTA pinned to the bottom · link to «شرایط اشتراک» |
| 12 | Payment return | U10 | Non-dismissible «در حال تأیید پرداخت...» · success toast on the channel · pending · failure (back to checkout with selections kept) |
| 13 | شرایط اشتراک (terms page) | U9 comment | Static long-form text |
| 14 | داشبورد → اشتراک‌ها | U2, U3, A2 | Summary line «{n} اشتراک فعال» · active cards sorted by soonest expiry · expiry escalation · expired section · suspended-creator card with refund action · empty state |
| 15 | Renew / reactivate bottom sheet | U3 | Tier selector · date preview block (renew: from current expiry; reactivate: from today) · price-changed note · promotion · success checkmark animation · failure |
| 16 | داشبورد → تراکنش‌ها + detail sheet | U4 | Filter chips (همه · موفق · ناموفق · در حال بررسی) · pending rows pinned · tap-to-copy reference number · support CTA · pagination of 20 |
| 17 | داشبورد → دنبال‌شده‌ها | U8 | Unfollow with confirmation · frozen unfollow for subscribed creators · suspended row · empty state |
| 18 | Notification center | U5 | Unread (start border) / read · CTA chips · relative timestamps · empty state |
| 19 | Track record page | 📄 Epic 10 | Public · not yet available · hidden |
| 20 | Refund request + status | 📄 U21 (only the suspension case is specced, in A2 §6) | |
### 6.3 Creator
| # | Screen | Story | Key states |
|---|---|---|---|
| 21 | کانال tab (own channel) | C4, C5 | Verification banner · post cards with share/edit/delete (+ preview icon on premium posts) · empty state |
| 22 | FAB + mini menu | C4 | Frozen when not Verified, with a blocking message per state |
| 23 | Post composer (full-screen modal) | C4, C5 | Free/premium toggle · 2,000-character counter · up to 4 images (thumbnail strip, frozen add button) · empty error · discard dialog · publishing state · failed image |
| 24 | Prediction composer | 📄 C12–C15 | Structured form · free/premium · preview · warning that it locks after 15 min |
| 25 | Share channel | C6 | Mobile bottom sheet / desktop popover · editable caption (150 characters, default «من را در لومینا دنبال کن 👇») · copy link |
| 26 | داشبورد overview | 📄 C9–C11, C16 | Subscribers · revenue (label gross or net) · prediction summary · open predictions · compact verification badge |
| 27 | **قیمت‌گذاری اشتراک** | C7 | 4 tier cards (monthly always on) · per-month equivalent · floors · suggestions · validation that per-month cost can't increase with duration · promotion section per tier · cooldown lock (standing prices dimmed, promotions still live) · confirmation dialog |
| 28 | **مالی** — schedule notice · balance · next payout · شبا · ledger | C19, C20 | See §7 |
### 6.4 Admin (desktop-first)
| # | Screen | Story |
|---|---|---|
| 29 | Verification queue (tabs: در انتظار بررسی · تأییدشده · رد شده, search, sort, pagination of 20) | A1 |
| 30 | Verification detail (ID image lightbox and download, previous/next request, submission history, audit log, approve, reject with reason templates) | A1 |
| 31 | Creator management list and detail (suspend dialog showing subscriber impact, reinstate dialog showing extension summary, audit log) | A2 |
| 32 | Users · subscriptions · transactions · reconciliation · refunds · payout run (amount + receipt upload) · predictions moderation · feature flags | 📄 Epic 3/11 |
---
## 7. Creator finance model (from C19/C20, which replace the PRD's Epic 11 numbers)
- **Payouts are weekly on Thursday** (`{payout_day}` is configurable). A static notice explains bank cycles and holidays.
- **There is no minimum payout threshold, and income is available immediately** on payment confirmation. There is no 7-day pending state.
- **Balance summary:**
- **قابل واریز** is the primary figure in brand-dark-900.
- **مجموع واریزشده** is a secondary line.
- **در حال واریز** appears only while a transfer is in flight.
- A negative balance shows in ruby with an explanation underneath.
- **Next payout line** has several states: date · «register شبا first» · «nothing to pay» · suspended/frozen.
- **شبا:**
- The field is LTR with a fixed `IR` prefix, auto-grouped into fours, and normalizes Persian/Arabic digits.
- The bank name is detected and shown underneath.
- It's checked with a mod-97 checksum.
- A responsibility checkbox is mandatory.
- A read-back confirmation dialog appears before saving.
- A duplicate شبا shows an amber warning; it doesn't block.
- **No admin approval.** Every edit sends an SMS alert.
- Saved state shows the شبا, bank and last-updated date, with an edit action.
- **Ledger «گردش حساب»:**
- Tabs همه · واریزها, 20 rows plus «نمایش بیشتر».
- Two-line rows.
- A detail view opens as a bottom sheet on mobile and a side panel on desktop. Income detail shows price → discount → amount paid → commission → «سهم شما». Payout detail shows a masked شبا and the receipt (view/download).
- **Subscriber privacy:** creators only ever see `@username`. Phone numbers and real names are never shown.
---
## 8. Sample data (for realistic mockups)
Keys follow the real API (§10). Raw dates are ISO UTC and money is Toman where shown. Display everything per §2 (Shamsi, Persian digits, `٬`).
```json
{
"creator": {
"username": "ali_gold",
"displayName": "تحلیل‌گر طلا",
"bio": "تحلیل تکنیکال طلا و دلار، ۸ سال سابقه",
"markets": ["gold", "forex", "crypto"],
"socialLinks": [{ "label": "کانال تلگرام", "url": "https://t.me/ali_gold" }, { "label": "اینستاگرام", "url": "https://instagram.com/ali_gold" }],
"stats": { "totalPredictions": 42, "activePredictions": 7, "pastPredictions": 35, "wins": 22, "losses": 12, "breakeven": 1,
"winRate": 62.86, "avgRoiPercent": 8.7,
"accuracyTrend": ["win", "loss", "win", "win", "breakeven", "win", "loss", "win", "win", "win"] },
"tiers": [
{ "billingPeriod": "monthly", "priceToman": 490000, "perMonthToman": 490000 },
{ "billingPeriod": "quarterly", "priceToman": 1161000, "standingPriceToman": 1290000, "perMonthToman": 387000,
"promotion": { "percent": 10, "endsAt": "2026-10-12T20:30:00Z" } },
{ "billingPeriod": "semi_annual", "priceToman": 2352000, "perMonthToman": 392000 },
{ "billingPeriod": "yearly", "priceToman": 4116000, "perMonthToman": 343000 }
]
},
"posts": [
{ "type": "text", "accessLevel": "free", "publishedAt": "2026-10-01T11:00:00Z", "caption": "دلار در محدوده حمایتی؛ منتظر تأیید باشید." },
{ "type": "image", "accessLevel": "premium", "locked": true, "captionPreview": "تحلیل هفتگی انس جهانی و دلار آزاد؛ سطوح کلیدی…", "mediaCount": 3 },
{ "type": "prediction", "accessLevel": "free", "caption": "شکست مقاومت ۲۴۰۰ دلار",
"prediction": { "symbol": "XAUUSD", "market": "gold", "direction": "long", "entryPrice": 2310, "targetPrices": [2400, 2450],
"stopLoss": 2280, "horizon": "2w", "status": "closed", "outcome": "win", "closedPrice": 2402 } },
{ "type": "prediction", "accessLevel": "free",
"prediction": { "symbol": "BTCUSDT", "market": "crypto", "direction": "short", "entryPrice": 68000, "targetPrices": [61000],
"horizon": "45d", "status": "open" } },
{ "type": "prediction", "accessLevel": "premium", "locked": true, "prediction": { "status": "open" } }
],
"investorSubscriptions": [
{ "creator": "ali_gold", "tier": "quarterly", "status": "active", "daysRemaining": 2 },
{ "creator": "gold_signal", "tier": "monthly", "status": "active", "daysRemaining": 5 },
{ "creator": "crypto_mina", "tier": "monthly", "status": "active", "creatorSuspended": true },
{ "creator": "bourse_pro", "tier": "yearly", "status": "expired", "expiryDate": "2026-09-21T08:00:00Z" }
],
"transactions": [
{ "type": "subscribe", "tier": "quarterly", "toman": 1161000, "status": "pending", "reference": "201234567" },
{ "type": "renew", "tier": "monthly", "toman": 490000, "status": "successful", "reference": "201230011" },
{ "type": "subscribe", "tier": "yearly", "toman": 4116000, "status": "failed", "reference": null }
],
"creatorFinance (C20 target shape; no API yet)": {
"available": 3420000, "inTransfer": 1250000, "totalPaidOut": 14300000,
"nextPayout": "پنجشنبه ۱۶ مهر ۱۴۰۵",
"sheba": "IR620120000000101234567890", "bank": "بانک ملت",
"ledger": [
{ "type": "income", "amount": 203150, "subscriber": "@reza_inv", "tier": "quarterly", "date": "2026-09-27" },
{ "type": "payout", "amount": -1250000, "status": "in_progress", "date": "2026-10-01" },
{ "type": "refund_deduction", "amount": -600000, "date": "2026-09-30" },
{ "type": "payout", "amount": -900000, "status": "cancelled", "date": "2026-09-19" }
]
}
}
```
---
## 9. Decisions and open points
**Story decisions that override the PRD**
- Subscriptions are **invite-only**. A referral code from the creator is required, and capacity is limited. When capacity is full, users with a valid code can join a waitlist (a notification subscription with opt-out). Following stays free.
- Creator payouts are weekly, with no threshold, no clearing period and no شبا approval (see §7).
- There is no public follower count anywhere.
- Prediction stats show in full or not at all.
- Pricing uses 4 fixed tiers with per-month floors (ماهانه ۲۹۹٬۰۰۰ · سه‌ماهه ۲۶۵٬۰۰۰ · شش‌ماهه ۲۳۰٬۰۰۰ · سالانه ۱۹۹٬۰۰۰ per month), promotions, and a 7-day cooldown.
- Suspension is a full blackout. Subscribers choose between a pro-rated refund and extension by the paused time.
**Inconsistencies to resolve (design with the first option until told otherwise)**
1. **Brand name:** «لومینا / lumina.ir» appears in C4, C6, C19 and C20, while other stories use the placeholder `[نام پلتفرم]`. Use **Lumina**.
2. **Pending label:** C1 uses «در انتظار تأیید», while C3 and the PRD use «در انتظار احراز هویت». Use the latter.
3. **Thousands separator:** C7 examples use `,`, while C20 specifies `٬`. Use `٬`.
4. **Push notifications:** C20 §8.1 mentions push, but push is deferred to Phase 1. Design for SMS + in-app.
5. **Prediction outcome:** the back end has `win` / `loss` / `breakeven`, closed by the creator. Design those three states.
**Story vs back-end conflicts (design to the story; the team must decide)**
| # | Topic | Story | Back end today |
|---|---|---|---|
| 6 | OTP | 5 digits, 2-minute expiry | 6 digits, 10-minute expiry, 60 s resend cooldown |
| 7 | National ID images | Front only | Front **and back** required |
| 8 | Public name | `@username` only (no nickname in C2) | Also a required `displayName` (max 80) |
| 9 | Post edit window | 15 minutes, then frozen; «ویرایش‌شده» label | Caption/media/access editable forever; no edited flag; predictions frozen at publish |
| 10 | Drafts | None (local draft only) | Server drafts, soft delete, purge |
| 11 | Locked prediction teaser | Everything hidden | Leaks `symbol` + `direction` |
| 12 | Locked image teaser | Never blurred | Sends `blurHash` |
| 13 | Follower count | Never public | Public endpoint exists |
| 14 | Promotions | Apply to new, renew and reactivate | New subscriptions only |
| 15 | Pending payment | Stays «در حال بررسی» until resolved | Auto-expires after 30 min and shows as **failed** |
| 16 | Creator profile field | — | Extra `tradingStyle` (not in stories, don't design it) |
| 17 | Brand | Lumina | `OnlyT` in SMS and config |
---
## 10. Back-end data model (design-relevant summary)
> The full analysis is in `backend-context.md` (for engineering). This section only keeps what changes how a screen looks or what content it shows.
### 10.1 Formats
- **Money:** stored in Rial, but every response has a Toman field (`toman`, `priceToman`, `perMonthToman`). The UI always shows Toman.
- **Dates:** ISO UTC. Server-made Farsi labels look like `۱۴۰۵/۳/۶` (no zero padding, no time). Designs use the §2 format; the front end formats dates itself.
- **Percentages:** `winRate` and `avgRoiPercent` are already percentages (`62.86`), not fractions.
- **Server copy:** many subscription, pricing, checkout and notification responses carry ready Farsi strings (`*Fa`) and color hints that match the tokens in §4.1. They agree with the story copy, so the round files stay the copy source.
### 10.2 Enums (exact keys)
| Enum | Keys |
|---|---|
| Market | `crypto` کریپتو · `gold` طلا و سکه · `equities` بورس · `forex` فارکس · `funds` صندوق‌های سرمایه‌گذاری · `real_estate` مسکن · `automotive` خودرو · `USDT` تتر |
| Billing period | `monthly` · `quarterly` · `semi_annual` · `yearly` |
| Post | type `text` / `image` / `prediction` · access `free` / `premium` |
| Prediction | status `open` / `closed` · outcome `win` / `loss` / `breakeven` · direction `long` / `short` |
| Subscription | `active` / `expired`. "Expiring" is computed: amber at 4–7 days, ruby with warning at ≤3 days |
| Payment (UI) | `successful` / `pending` / `failed` · type `subscribe` / `renew` / `reactivate` |
| Checkout CTA | `subscribe` · `active` (مشترک هستید ✓) · `pending_review` (frozen) · `own` (hidden) |
| Payment return | `processing` → `granted` (land on channel) / `pending_review` / `failed` (back to checkout) |
| Verification | `pending` / `approved` / `rejected` (+ account `suspended`) |
### 10.3 Limits that affect layouts
- Bio 300 characters, max 3 line breaks.
- Links: max 8, label max 30 characters.
- Display name max 80 characters (if used, §9 #8).
- Avatar and ID images: JPG/PNG, max 5 MB.
- Post text: the story limit of 2,000 applies (the API accepts 5,000). Max 4 images per post (the API has no limit).
- Pagination: 20 per page for feed, posts and transactions. Notifications: latest 100, no paging.
### 10.4 Back-end support by screen
Designs still follow the stories for every screen. This list only shows what can be built against real data now.
| Supported | Not implemented yet |
|---|---|
| Auth, investor registration, creator registration + profile setup/edit | Verification approve/reject, resubmit, rejection reason (creators stay `pending`) |
| Channel, posts, post page, follow/unfollow (frozen while subscribed, auto-follow on subscribe) | Creator search · track record gate/history/hide · prediction auto-tracking (manual close only) |
| Pricing (floors, suggestions, promotions, cooldown, validation) | Earnings ledger, شبا, payouts, receipts, commission (C19/C20) |
| Checkout with invite code, waitlist, price-change guard, ZarinPal return | Refunds · reconciliation · subscription cancel |
| اشتراک‌ها, renew/reactivate, تراکنش‌ها, notification center | Whole admin panel · audit log · feature flags |
| Creator dashboard: active subscribers, gross revenue, recent payments | Net revenue (only gross exists, so label it «درآمد ناخالص») |
---
## 11. Design rounds
| Round | File | Goal |
|---|---|---|
| 1 | `round-1-channel-and-posts.md` | **Visual language.** Channel header, post card (free / locked / subscriber / owner), standalone post page, composer, share, follow, prediction card (from §5.6) |
| 2 | `round-2-auth-and-onboarding.md` | Entry, OTP, investor profile, creator KYC, profile setup, اطلاعات کاربری |
| 3 | `round-3-investor-subscriptions.md` | Checkout, payment return, waitlist, اشتراک‌ها, renew/reactivate, تراکنش‌ها, notifications |
| 4 | `round-4-creator-money.md` | Pricing, مالی (شبا + ledger) |
| 5 | `round-5-admin.md` | Verification queue and detail, suspend/reinstate |
| 6 | (PRD only) | Feed + search, track record, creator dashboard overview, prediction composer, other admin screens |
**For each round:** mobile (390px) and desktop, RTL, real Farsi copy from the stories, and every listed state (loading, empty, error, success, frozen, edge).

View File

@ -1,944 +0,0 @@
# Round 1 — Channel, posts & visual language
> Attach together with `design-brief.md`. The brief defines the design system, shared patterns and status vocabulary; this file holds the full acceptance criteria and exact Farsi copy.
> Establish the visual language that every later round reuses.
## Deliver in this round
- Creator channel page `/@username`: header (U6) with all viewer states (brief §5.1), stats block present and absent, empty channel, suspended channel
- Post card: free text, free image (1 and 3 images), locked premium, unlocked premium (subscriber), owner view with actions, edit window active vs frozen, «ویرایش‌شده» label
- Prediction card (brief §5.6, no story yet): compact and expanded, all states including premium-locked
- Standalone post page: free, locked (logged-out and logged-in), owner, visitor-preview banner, deleted, suspended
- Creator کانال tab: Pending and Rejected banners, FAB + mini menu (live and frozen)
- Post composer (full-screen modal): free/premium toggle, images, counter, errors, discard dialog
- Share: creator caption sheet (mobile) and popover (desktop); plain share for visitors
- Image lightbox
For every screen: mobile and desktop, RTL, real Farsi copy from below, and all listed states.
## Stories included
- **C4** — Creator Post Publishing (Free Content) _(ClickUp status: ready for development)_
- **C4b** — Standalone Post Page _(ClickUp status: ready for development)_
- **C5** — Premium Post Publishing _(ClickUp status: ready for development)_
- **U6** — Investor: Creator Profile Header _(ClickUp status: ready for development)_
- **U7** — Investor: Premium Content Lock Indication (Cross-Surface) _(ClickUp status: ready for development)_
- **U8** — Investor: Follow a Creator _(ClickUp status: ready for development)_
- **C6** — Creator Channel Sharing (External Promotion) _(ClickUp status: ready for development)_
---
## C4 — Creator Post Publishing (Free Content)
C4 — Creator Post Publishing (Free Content)
Story:
As a creator, I want to publish free text and image posts to my channel so that I can attract new followers with publicly visible content.
Note: This story covers free text and image posts only. Premium posts are covered in C5. Prediction posts are covered in C8. Posts in this story are always publicly visible to all users — logged in or not.
⚠️ Forward dependency note: The creator channel public URL structure (lumina.ir/@{username}) and post URL structure (lumina.ir/@{username}/posts/{post_id}) are introduced in this story. Standalone post page behaviour is covered in C4b.
⚠️ Phase 1 backlog item: Text truncation on long posts is intentionally not implemented in Phase 0 — full post text is always shown in every context.
Acceptance Criteria:
1. Access & Entry Point
Happy Path:
The post composer is accessed via the FAB (Floating Action Button) labeled + انتشار in the bottom navigation bar — visible to creators from all tabs at all times
Tapping + انتشار expands a mini menu with two options:
پست جدید → opens the post composer (this story)
پیشبینی جدید → opens the prediction composer (C8)
The creator's published posts are managed from the کانال tab in the bottom navigation bar — posts appear chronologically and share/edit/delete actions are accessible inline on each post card
Only Verified creators can publish posts
Edge Cases:
If a creator's account is Pending Verification, the FAB is visible but frozen (opacity: 0.4, cursor: not-allowed) — tapping it shows a context-appropriate blocking message
If a creator's account is Rejected, the FAB is also frozen — tapping it shows a message directing the creator to resubmit their identity verification via C3
If a creator's account is Suspended, the FAB is also frozen — tapping it shows a different context-appropriate blocking message. (In practice, per A2, a Suspended creator cannot log in at all, so this state is largely theoretical within the app itself — kept here for completeness/defense-in-depth)
Tapping anywhere outside the expanded FAB mini menu collapses it without any action
Error States:
Pending verification: blocking message shown on FAB tap
Rejected: blocking message shown on FAB tap
Suspended: blocking message shown on FAB tap
Farsi copy:
FAB label: + انتشار
FAB menu option 1: پست جدید
FAB menu option 2: پیشبینی جدید
Pending verification blocking message: برای انتشار پست، ابتدا باید احراز هویت شما تأیید شود.
Rejected blocking message: احراز هویت شما تأیید نشد. برای انتشار پست، ابتدا اطلاعات هویتی خود را اصلاح و ارسال مجدد کنید.
Suspended blocking message: حساب شما تعلیق شده است. امکان انتشار پست وجود ندارد.
2. Persistent Verification Status Banner (کانال tab)
⚠️ This section fulfills the forward reference established in C1 Section 7.
Happy Path:
A banner is shown at the top of the کانال tab, directly beneath the top navigation bar, for any creator who is Pending or Rejected
The banner does not appear for Verified creators — it disappears entirely and permanently once verification succeeds
Banner content and tap behavior differ by state:
State Message Tappable? Tap Destination
Pending حساب شما در انتظار تأیید است. پس از تأیید تیم پشتیبانی می‌توانید محتوا منتشر کنید. No — informational only —
Rejected احراز هویت شما تأیید نشد. دلیل: {admin_reason} Yes Navigates to C3 (اطلاعات کاربری), landing at the top of اطلاعات هویتی, per C1 Section 7
Edge Cases:
This banner is scoped to the creator's own view of their own کانال tab — entirely separate from what other users see on the creator's public channel page (Section 12)
The banner is non-dismissible — the creator cannot close or hide it; it remains until their verification state changes
If the creator has no posts yet (empty کانال), the banner still renders above the empty state
Error States: None specific — this is a display-only state, no user input involved
Farsi copy:
Pending banner message: حساب شما در انتظار تأیید است. پس از تأیید تیم پشتیبانی می‌توانید محتوا منتشر کنید.
Rejected banner message: احراز هویت شما تأیید نشد. دلیل: {admin_reason}
3. Post Composer
Happy Path:
The composer opens as a full-screen modal on mobile
The composer contains:
A free-text input area for the post body
An image attachment area supporting up to 4 images
A visibility toggle: Free (رایگان) / Premium (پریمیوم) — defaults to Free in C4; Premium behaviour is covered in C5
A Publish CTA button
A Discard option to cancel without publishing
Creator can write text only, attach images only, or combine both — the post cannot be empty (at least one of text or image must be present)
Edge Cases:
If the creator closes the composer with unsaved content, a confirmation dialog appears before discarding
Composer preserves draft content if the app is backgrounded or the device locks — content is not lost on accidental exit
If the creator switches the visibility toggle to Premium during composition, the flow transitions to C5 — text and images already entered are preserved
Error States:
If the post is empty (no text, no images) and the creator taps Publish, an inline error appears
If the network fails during publish, an error banner appears and the draft is preserved — creator can retry
Farsi copy:
Composer heading: پست جدید
Text input placeholder: تحلیل یا دیدگاه خود را بنویسید...
Visibility toggle — free: رایگان
Visibility toggle — premium: پریمیوم
Publish CTA: انتشار
Discard CTA: انصراف
Discard confirmation dialog: پست شما ذخیره نشده است. آیا می‌خواهید خارج شوید؟
Discard confirm CTA: خروج
Discard cancel CTA: ادامه ویرایش
Empty post error: پست نمی‌تواند خالی باشد. متن یا تصویر اضافه کنید.
Network error banner: انتشار پست ناموفق بود. اتصال اینترنت خود را بررسی کنید.
4. Text Content
Happy Path:
Creator enters post text of up to 2000 characters
Persian, English, or mixed text accepted
Line breaks accepted
A live character counter is shown as the creator types
Edge Cases:
Input stops accepting new characters at 2000
URLs typed into the text are displayed as plain text in Phase 0 — not hyperlinked
Hashtags and mentions typed into the text are displayed as plain text in Phase 0
Error States:
Counter turns {colors.ruby} (#ea2261) at 0 remaining characters
Farsi copy:
Character counter: {n}/۲۰۰۰
Counter at limit: به حداکثر تعداد کاراکتر رسیدید.
5. Image Attachments
Happy Path:
Creator can attach up to 4 images per post
Accepted formats: JPG, PNG, WebP
Maximum size per image: 5 MB
A helper text note is shown below the image upload area informing creators of the file specs
After selecting images, thumbnails are shown in a horizontal strip beneath the text input
Creator can remove any individual image before publishing by tapping a remove icon on the thumbnail
Images are displayed in the published post in the order they were attached
Images are displayed at their original aspect ratio — no cropping or forced ratio applied
A maximum height cap of 400px is applied in the feed — images taller than this are letterboxed; the full image is viewable in the lightbox
Edge Cases:
Creator can attach images without any text — image-only posts are valid
If the creator attempts to attach a 5th image, the add image button is frozen/disabled with a message
If an image fails to upload during publish, the entire post publish is blocked — the creator is shown which image failed and can remove or replace it
Image compression is deferred to Phase 1
Error States:
Wrong format: inline error shown, upload rejected
File too large: inline error shown, upload rejected
5th image attempted: add button frozen with message shown
Image upload failure on publish: specific error identifying the failed image
Farsi copy:
Add image CTA: افزودن تصویر
File specs helper text: فرمت‌های مجاز: JPG، PNG، WebP — حداکثر حجم هر تصویر: ۵ مگابایت
Remove image tooltip: حذف تصویر
Wrong format error: فقط فایل‌های JPG، PNG و WebP مجاز هستند.
Too large error: حجم هر تصویر نباید بیشتر از ۵ مگابایت باشد.
Max images reached (frozen button message): امکان افزودن بیش از ۴ تصویر وجود ندارد.
Image upload failure: آپلود تصویر {n} ناموفق بود. تصویر را حذف یا جایگزین کنید.
6. Publishing & Post State
Happy Path:
Creator taps انتشار
System validates content
Post is published immediately and appears at the top of the creator's channel feed
Post is visible to all users — logged in or logged out — immediately upon publishing
A success toast message appears briefly after publishing
Creator is returned to the کانال tab where the new post is visible at the top
Edge Cases:
Post publish timestamp is system-generated — not editable by the creator
If the creator is on a slow connection, a loading indicator is shown on the Publish button during upload — button is disabled to prevent double submission
Published post appears immediately on the خانه feed of all investors who follow the creator
Error States:
If publish fails due to network error, draft is preserved and error banner shown with retry option
Farsi copy:
Publishing loading state: در حال انتشار...
Publish success toast: پست شما با موفقیت منتشر شد.
7. Image Display in Feed & Channel
Happy Path:
Images are displayed at their original aspect ratio in the feed and channel
A maximum height cap of 400px is applied — images taller than this are letterboxed; full image viewable in lightbox
Multi-image display uses a swipe carousel:
1 image: Full width, original aspect ratio
2–4 images: Swipe carousel — each image displayed full width at its original ratio, with a dot indicator showing current position
Tapping any image opens the full-screen lightbox viewer
Full-Screen Lightbox:
Image fills the screen at full resolution
Swipe left/right to navigate between images in the same post
Swipe down to close the lightbox
A back button (←) in the top corner serves as a secondary close option
Image position indicator shown (e.g., ۱ / ۳)
Pinch to zoom supported
Edge Cases:
If the post has only 1 image, no dot indicator or swipe gesture is shown
If the creator attaches images of mixed aspect ratios, each displays at its own ratio within the carousel
Dot indicator uses filled/unfilled dots — maximum 4 dots
Farsi copy:
Image position indicator in lightbox: {current} / {total}
8. Post Display on Channel (Scrollable List)
Happy Path:
The کانال tab shows all published posts as a scrollable chronological list — most recent at the top
Each post card in the list displays:
Creator avatar and username
Post timestamp — Shamsi calendar, relative format for recent posts, absolute for older ones
Full post text — no truncation
Image carousel (if images attached) — as defined in Section 7
Visibility badge: shown only if the post is پریمیوم — free posts carry no badge
Three inline action icons below each post card: share, edit, delete — no labels
Tapping the post body or images navigates to the standalone post page (C4b)
Edge Cases:
If the post has no text, no text area is rendered on the card
If the post has no images, no carousel area is rendered
Action icons (share, edit, delete) are visible only to the creator on their own channel — investors see only the share icon
On the creator's own کانال tab, all of the creator's own posts (free and premium) are shown with full content — no lock or teaser applies
For premium posts specifically, a fourth action icon (مشاهده به عنوان کاربر) is also shown to the creator, alongside share/edit/delete — full behavior defined in C5 Section 6. This icon does not appear on free posts, since there is nothing to preview
The persistent verification banner (Section 2), when applicable, is shown above this list
Farsi copy:
Visibility badge (premium only): پریمیوم
Timestamp examples: همین الان · {n} دقیقه پیش · {n} ساعت پیش · دیروز · {date}
9. Share Action
Happy Path:
Creator or investor taps the share icon on a post card (in the list or on the standalone post page)
The native share sheet opens on mobile — shows whichever apps are already installed on the user's device, plus a copy link option
The shared link is the post's standalone permalink: lumina.ir/@{username}/posts/{post_id}
Copying the link via the share sheet shows a brief confirmation toast
Edge Cases:
Share is available to all users — creators and investors alike
Share is available on both the scrollable list and the standalone post page
If the post is deleted after a link is shared, the permalink returns a پست یافت نشد page
Farsi copy:
Copy link confirmation toast: لینک پست کپی شد.
Deleted post permalink page: این پست حذف شده یا وجود ندارد.
10. Edit Action
Happy Path:
Creator taps the edit icon on a post card within 15 minutes of publishing
Composer reopens with existing content pre-populated
Saving updates the post immediately; a subtle ویرایش‌شده label appears on the post
Post retains its original publish timestamp after editing
Edge Cases:
After 15 minutes, the edit icon remains visible but is frozen (opacity: 0.4) — tapping it shows a tooltip explaining editing is no longer possible
Edit is available on both the scrollable list and the standalone post page
If edit save fails due to network error, error banner shown and original content preserved
Error States:
Edit window expired: frozen icon with tooltip on tap
Network error on save: error banner shown
Farsi copy:
Edit icon tooltip (within window): ویرایش پست
Edit icon tooltip (frozen, after 15 min): مهلت ویرایش این پست به پایان رسیده است.
Edited label: ویرایش‌شده
Edit network error: خطا در ذخیره تغییرات. دوباره تلاش کنید.
11. Delete Action
Happy Path:
Creator taps the delete icon on a post card at any time
A confirmation dialog appears before permanent removal
On confirm, post is permanently removed from the channel and all feeds
Deleted posts disappear from investors' feeds on next refresh — no message shown to investors
Edge Cases:
Delete is available at any time — no time restriction
Delete is available on both the scrollable list and the standalone post page
Deleted posts are permanently removed — no soft delete or recovery in Phase 0
If delete fails due to network error, error banner shown and post remains
Farsi copy:
Delete icon tooltip: حذف پست
Delete confirmation dialog: آیا از حذف این پست اطمینان دارید؟ این عملیات غیرقابل بازگشت است.
Delete confirm CTA: بله، حذف کن
Delete cancel CTA: انصراف
Delete network error: خطا در حذف پست. دوباره تلاش کنید.
12. Channel Page & Creator Public URL
Creator's public channel is accessible at lumina.ir/@{username}
The channel page displays:
Creator profile header: avatar, username, bio, market specialization tags, social links, verified badge
Prediction stats summary — pulled from Epic 9; shown as placeholder zeros until prediction data exists
Follow / unfollow button — available to any investor regardless of subscription status; no referral code required to follow
Subscribe button — referral-code-gated (links to Epic 5 paid access flow)
Scrollable post list — as defined in Section 8, with locked-teaser rendering for premium posts as defined in C5
The channel URL is shareable externally — opens correctly for logged-out users
Share button on the channel page copies the channel URL to clipboard
This public-facing view is distinct from the creator's own کانال tab (Section 2 and Section 8) — external visitors never see the persistent verification banner
Edge Cases:
If a creator has no posts yet, a contextual empty state is shown
If the creator's account is suspended, the channel page shows a suspended message
If a logged-out user taps Follow or Subscribe, they are redirected to the unified auth entry flow with the channel URL preserved as the return destination
Following a creator never requires a referral code; only subscription is referral-gated
Farsi copy:
Channel empty state: این کریتور هنوز پستی منتشر نکرده است.
Suspended channel message: این کانال در حال حاضر در دسترس نیست.
Share channel CTA: اشتراک‌گذاری کانال
Channel URL copied toast: لینک کانال کپی شد.
Follow CTA: دنبال کردن
Unfollow CTA: دنبال نکردن
Subscribe CTA: اشتراک
13. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
FAB uses button-primary-pill style (#533afd, pill radius); frozen state uses opacity: 0.4
FAB expanded mini menu uses card-feature-light style with {rounded.lg} radius and Level 2 shadow
Persistent verification banner spans full width, sits directly beneath the top nav bar on the کانال tab: Pending — {colors.ink-mute} (#64748d) background tint with clock icon; Rejected — {colors.ruby} (#ea2261) background tint with warning icon and chevron
Post composer opens as a full-screen modal with {colors.canvas} (#ffffff) background
Post cards use card-feature-light style
Only the پریمیوم badge is ever rendered — {colors.brand-dark-900} (#1c1e54) background with white text — free posts carry no badge
Character counter uses {colors.ink-mute} (#64748d), switches to {colors.ruby} (#ea2261) at 0 remaining
Carousel dot indicator uses {colors.primary} for active dot, {colors.hairline} for inactive dots
Full-screen lightbox uses a pure black (#000000) background
Action icons use {colors.ink-mute} (#64748d) — frozen edit icon uses opacity: 0.4
ویرایش‌شده label uses {colors.ink-mute} in {typography.micro} size
Minimum touch target for all interactive elements: 44×44px
Channel page and post composer are mobile-first
---
## C4b — Standalone Post Page
C4b — Standalone Post Page
Story: As a user, I want to view a post on its own dedicated page so that I can access it directly via a shared link and see its full content.
Note: The standalone post page is the canonical destination for any shared post link. It serves both internal navigation (tapping a post from the channel or feed) and external deep linking (shared permalink on Telegram, WhatsApp, etc.). This story applies to all post types — free text/image posts (C4), premium posts (C5), and prediction posts (C8) — with access rules per post type applying as defined in their respective stories.
⚠️ Forward reference: Creator referral code visibility and sharing (needed for the subscription-gated referral system defined in U1 Section 7) is addressed in C9 (Creator Dashboard) — not in this story.
Acceptance Criteria:
1. URL Structure & Access
Happy Path:
Every post has a unique, permanent permalink: lumina.ir/@{username}/posts/{post_id}
The standalone post page is accessible to:
Logged-out users — can view free content in full; premium content shown as locked teaser
Logged-in investors (non-subscribers) — can view free content in full; premium content shown as locked teaser with subscribe prompt
Logged-in subscribers — can view all content including premium
The creator themselves — can view all content plus edit/delete actions, and can toggle a visitor-view preview on their own premium posts (see Section 6)
The page loads correctly when accessed via external link — no login required to view free content
Edge Cases:
If the post has been deleted, the permalink returns a not found page — clean and informative, with a CTA to visit the creator's channel
If the creator's account has been suspended, the permalink returns a channel unavailable page — post content is not shown
If a logged-out user taps a locked premium content prompt, they are redirected to the unified auth entry flow with the post URL preserved as the return destination (as defined in U1 Section 5)
Farsi copy:
Deleted post page heading: این پست حذف شده است.
Deleted post page body: پست مورد نظر حذف شده یا وجود ندارد.
Deleted post page CTA: مشاهده کانال {username}
Suspended channel page: این کانال در حال حاضر در دسترس نیست.
2. Page Structure & Content
Happy Path:
The standalone post page displays the following sections in order from top to bottom:
Section A — Creator Mini Profile Header:
Creator avatar (circular)
Creator username (tappable — navigates to lumina.ir/@{username})
Verified badge (if applicable)
Follow / Unfollow button (for investors — no referral code required)
Subscribe button (for non-subscribers) — see Section 4 for exact CTA logic by auth state
Section B — Post Content:
Badge placement: The پریمیوم badge sits at the top of the content area, alongside the timestamp — same placement rule as C5
Post timestamp — Shamsi calendar, absolute format (e.g., ۱۵ خرداد ۱۴۰۴، ساعت ۱۴:۳۰) — shown prominently near the top, directly beneath the creator header. Deliberate placement: timestamp is a trust signal central to the platform's Proof-of-Performance positioning, not incidental metadata
ویرایش‌شده label if the post was edited within the 15-minute window
Full post text — no truncation, full content shown (for free posts; premium post teaser rules in Section 4)
Image carousel (if images attached) — same display rules as C4 Section 7 apply
For prediction posts: structured prediction fields — covered in C8
Section C — Action Bar:
Share, edit (creator only), delete (creator only) icons — same rules as C4 Sections 9, 10, 11 apply
مشاهده به عنوان کاربر (View as Visitor) icon — shown only to the creator, only on their own premium posts — see Section 6
No labels under any icon in this bar
Section D — Comments:
Not implemented in Phase 0 — this section is omitted entirely, no placeholder shown
Edge Cases:
If the post has no images, Section B renders text only — no empty carousel
If the post is text-only, the image area is not rendered at all
If the post is image-only, the text area is not rendered
The creator mini profile header is always shown — even if the post is premium and locked
Farsi copy:
Follow CTA: دنبال کردن
Unfollow CTA: دنبال نکردن
Subscribe CTA: اشتراک
Visibility badge (premium only): پریمیوم
3. Navigation & Back Behaviour
Happy Path:
If the user arrived at the standalone post page from within the app (tapping a post in the channel list or feed), the back button returns them to the previous screen they came from — channel tab, خانه tab, or search results
If the user arrived via an external link (shared permalink), the back button navigates to the creator's channel page (lumina.ir/@{username}) — not to a blank previous state
Edge Cases:
If the user arrived via external link and has no browsing history within the app, the back button always falls back to the creator's channel page
If the creator's channel is suspended when the user attempts to navigate back from a shared link, the back button navigates to the خانه tab instead
4. Locked Premium Content (Non-Subscribers)
Happy Path:
If the post is premium and the user is not a subscriber, the same locked teaser pattern defined in C5 Section 3 applies here — unified across every surface where a premium post can appear:
Text teaser: First 2 lines of the post text, then gradient blur fade with a lock icon overlay
Image teaser: Images not shown — generic locked placeholder with an optional count badge (e.g., ۳ تصویر)
The پریمیوم badge, timestamp, and creator mini profile header remain fully visible — only the content body is restricted
Directly beneath the locked content, a contextual message and a single CTA are shown, determined by auth state
Message & CTA Logic by Auth State (single message + single CTA — never both states shown simultaneously):
User State Message Shown CTA Shown
Logged-out برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید. ورود/ثبت‌نام
Logged-in, not subscribed برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید. اشتراک در کانال
Logged-in, subscribed — No lock — full content shown
The creator (own post) — No lock — full content always shown by default (see Section 6 for the visitor-preview toggle)
Edge Cases:
A logged-out user never sees a Subscribe CTA — authentication must happen first, subscription is a separate step after
If the user subscribes and returns to the same permalink, content is immediately accessible without needing to refresh
Arriving at a locked premium post via a shared link vs. tapping into it from a feed/channel list produces identical locked-teaser behavior — no distinction by entry path
Farsi copy:
Locked teaser image badge: {n} تصویر
Lock overlay small label (optional): محتوای پریمیوم
Message (logged-in, not subscribed): برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید.
Subscribe CTA (logged-in, not subscribed): اشتراک در کانال
Message (logged-out): برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید.
Unified auth CTA (logged-out): ورود/ثبت‌نام
5. Share Action on Standalone Post Page
Happy Path — Mobile:
Share icon is visible to all users on the standalone post page
Tapping share opens the native OS share sheet — shows whichever apps are already installed on the user's device, plus a copy link option
The platform does not construct or call any specific third-party share URL — it hands the permalink to the OS and lets the user's own device decide the available destinations
The shared link is the current page's permalink: lumina.ir/@{username}/posts/{post_id}
Happy Path — Desktop:
Clicking share opens a minimal popover containing a single action: کپی لینک (copy link)
No direct-share buttons to specific third-party platforms are included on desktop
Clicking outside the popover closes it without action
Edge Cases:
Share is available for both free and premium posts — sharing a premium post link will show the locked teaser (Section 4) to non-subscribers who open it, which is a deliberate conversion mechanic, not a gap
Copy link action shows a brief confirmation toast on both mobile and desktop
This is precisely the moment the "View as Visitor" preview (Section 6) is most useful — a creator preparing to share their own premium post externally can check exactly what a stranger clicking that link will see, without leaving this page
Farsi copy:
Copy link confirmation toast: لینک پست کپی شد.
Desktop popover — copy link option: کپی لینک
6. Creator Preview — "View as Visitor" (مشاهده به عنوان کاربر)
Happy Path:
On the standalone page of any premium post the creator owns, the مشاهده به عنوان کاربر icon appears in the Action Bar (Section 2, Section C), alongside share/edit/delete
Tapping it renders the exact same locked-teaser view defined in Section 4 — the identical component/template a non-subscriber would see, not a separate mock
This is the same feature introduced in C5 Section 6, scoped there to the کانال tab list view — this section extends its availability to the standalone post page as well, since a creator is often on this exact page (about to share the link, per Section 5) when the need to check the visitor's view is highest
A visible banner while active: شما در حال مشاهده این پست به شکلی هستید که کاربران غیر عضو می‌بینند.
A dismissible خروج از پیش‌نمایش action returns the creator to their normal full-access view
Edge Cases:
This action is not shown for free posts — there is nothing to preview, since free posts render identically for everyone
This action is not shown to anyone other than the post's owning creator — investors, subscribers, and logged-out users never see this icon
No actual impersonation or session-switching occurs — it is a conditional render of the visitor-facing template within the creator's own authenticated session
Toggling this preview does not affect what the URL shows to anyone else — it is a local, client-side view state for the creator only
Farsi copy:
Action icon label (tooltip): مشاهده به عنوان کاربر
Preview mode banner (shown while active): شما در حال مشاهده این پست به شکلی هستید که کاربران غیر عضو می‌بینند.
Exit preview CTA: خروج از پیش‌نمایش
7. Edit & Delete on Standalone Post Page
Edit and delete icons are visible only to the creator on the standalone post page
All edit/delete rules from C4 Sections 10 and 11 apply identically here
After a successful delete from the standalone post page, the creator is navigated back to their کانال tab — the deleted post is no longer visible
Farsi copy: Same as C4 Sections 10 and 11.
8. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Page background uses {colors.canvas-soft} (#f6f9fc) — slightly off-white to distinguish the page from the post card content area
Post content area uses card-feature-light style — {colors.canvas} background, {colors.hairline} border, {rounded.lg} radius, Level 1 shadow
Creator mini profile header is separated from post content by a {colors.hairline} divider
Timestamp rendered directly beneath the creator header in {colors.ink-mute} (#64748d), {typography.caption} size
پریمیوم badge uses {colors.brand-dark-900} (#1c1e54) background with white text, positioned at the top of the content area alongside the timestamp — shown only when applicable, no badge for free posts
Locked text teaser fade uses a linear gradient from transparent to {colors.canvas} (#ffffff), with the lock icon in {colors.ink-mute} (#64748d) centered on the fade
Locked image placeholder uses {colors.canvas-soft} background, lock icon in {colors.ink-mute}, image count badge in pill-tag-soft style
Contextual message (logged-out or not-subscribed) renders in {colors.ink-mute} (#64748d), {typography.body-md}, centered above the CTA
Subscribe CTA and auth CTA both use button-primary-pill style (#533afd, pill radius)
Action icons (share, edit, delete, view-as-visitor) use {colors.ink-mute} (#64748d) — consistent with C4
ویرایش‌شده label uses {colors.ink-mute} in {typography.micro} size
View-as-visitor preview banner uses {colors.warning} (#f59e0b) background with dark text — signals a temporary/altered viewing mode without implying an error, consistent with the same treatment in C5 Section 7
Desktop share popover is minimal — single row, card-feature-light style with Level 2 shadow, {rounded.md} radius
Image carousel and lightbox behaviour identical to C4 Section 7
Minimum touch target for all interactive elements: 44×44px
Page is mobile-first; on desktop, content is centered in a single column with max-width of 640px
---
## C5 — Premium Post Publishing
C5 — Premium Post Publishing
Story:
As a creator, I want to publish premium posts visible only to subscribers so that I can provide exclusive value that justifies the subscription price.
Note: This story extends the composer introduced in C4 — the visibility toggle (رایگان / پریمیوم) is shared infrastructure between both stories. C5 owns the premium-specific behavior: access control, locked teaser rendering, and the paywall logic. Standalone post page behavior is defined in C4b Section 4, using the identical teaser pattern specified here.
⚠️ Forward dependency note: Premium access in Phase 0 is gated purely by active channel subscription — there is no per-post pricing (PPV). One subscription unlocks all premium content on that creator's channel. PPV is explicitly deferred to Phase 1 per the PRD. Subscription itself is referral-code-gated (Epic 5); following a creator is free and requires no referral code.
Acceptance Criteria:
1. Marking a Post as Premium
Happy Path:
In the post composer (C4 Section 3), the creator switches the visibility toggle from رایگان to پریمیوم
All composition rules (text limit, image limits, formats) remain identical to C4 — only the visibility and access control differ
On publish, the post is immediately locked for all non-subscribers and fully visible to subscribers and the creator
Edge Cases:
A creator with zero subscribers can still publish premium posts — content accumulates for whenever their first subscriber joins
The visibility toggle (رایگان ⇄ پریمیوم) can be changed in either direction within the same 15-minute edit window established in C4 — consistent with all other post edits
After the 15-minute window closes, visibility is locked along with the rest of the post content — a creator cannot convert a free post to premium (or vice versa) after this window
Error States:
Same network/validation error states as C4 apply — no additional error states specific to the toggle itself
Farsi copy: Same visibility toggle copy as C4 Section 3 (رایگان / پریمیوم).
2. Access Control Logic
Viewer Access
The creator (post owner), viewing their own کانال tab Full content, always — no lock, no teaser
Active subscriber to this creator Full content
Logged-in investor, not subscribed Locked teaser (Section 3)
Logged-out user Locked teaser (Section 3)
Edge Cases:
If a subscriber's subscription expires, premium posts immediately revert to locked teaser state for that user on next load — no grace period
If a non-subscriber subscribes, previously locked posts become immediately accessible without needing to refresh the app
If the creator's account is suspended, all content (free and premium) becomes inaccessible per the suspension rules already defined in A2 and C4 — premium-specific access control is irrelevant in this state
Following a creator does not grant premium access — following is free and ungated; only an active, referral-code-originated subscription unlocks premium content
3. Locked Teaser Display (Investor-Facing Surfaces)
Scope clarification: This locked teaser applies exclusively to investor-facing surfaces — the public channel page (lumina.ir/@{username}) and the خانه feed (Epic 7). It does not apply to the creator's own کانال tab, where the creator always sees full content for their own posts (per Section 2).
Happy Path:
Badge placement: The پریمیوم badge sits at the top of the post card, in the header area alongside the creator avatar, username, and timestamp — identical placement whether the post is locked or unlocked
Text teaser: The first 2 lines of the post text are shown, then fade into a gradient blur with a lock icon overlay centered on the fade. Kept intentionally short — even a longer excerpt risks revealing directional analysis, which undermines the platform's core value proposition
Image teaser: Images are not shown at all — replaced with a generic locked placeholder (a branded lock icon on {colors.canvas-soft} background), not a blurred version of the actual image, to avoid any risk of leaking directional information. If multiple images, a count badge indicates richness (e.g., ۳ تصویر)
Directly beneath the locked content, a contextual message and a single CTA are shown, determined by auth state (see table below)
Tapping the card body (text or image placeholder area) navigates to the standalone post page (C4b), where the identical locked-teaser pattern is shown
Edge Cases:
If the premium post has no text (image-only), only the image placeholder is shown
If the premium post has no images (text-only), only the text teaser is shown
Post timestamp, creator info, and the پریمیوم badge remain fully visible on locked cards — only the content body is restricted
Message & CTA Logic by Auth State (single message + single CTA — never both states shown simultaneously):
User State Message Shown CTA Shown
Logged-out برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید. ورود/ثبت‌نام
Logged-in, not subscribed برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید. اشتراک در کانال
Logged-in, subscribed — No lock — full content shown
Error States: None specific — this is a display-only state, no user input involved
Farsi copy:
Locked teaser image badge: {n} تصویر
Lock overlay small label (optional): محتوای پریمیوم
Message (logged-in, not subscribed): برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید.
Subscribe CTA (logged-in, not subscribed): اشتراک در کانال
Message (logged-out): برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید.
Unified auth CTA (logged-out): ورود/ثبت‌نام
4. Standalone Post Page Behavior
Full lock behavior — including badge placement, the 2-line text teaser, image placeholder, contextual message, and auth-state CTA logic — is fully specified in C4b Section 4, using the exact same pattern defined in Section 3 above. No divergence between list/feed teasers and standalone page teasers
Arriving at a premium post's standalone page from a locked teaser tap vs. a direct shared link produces identical behavior — the lock does not differentiate by entry path
5. Subscriber View
Happy Path:
An active subscriber sees premium posts identically to free posts — full text, full image carousel, no visual distinction in content rendering
The پریمیوم badge remains visible at the top of the post, as a status indicator, even to subscribers who have full access — this reinforces the perceived value of their subscription
Edge Cases:
If a subscriber's subscription expires while they are actively viewing a premium post, the content does not disappear mid-session — the lock takes effect on the next page load or refresh, not retroactively within an open session
6. Creator Preview — "View as Visitor"
Happy Path:
On every premium post the creator owns (visible from their کانال tab), a "مشاهده به عنوان کاربر" action is available alongside the standard share/edit/delete icons
Tapping it opens a read-only preview rendering the exact locked-teaser view a non-subscriber would see — using the identical component/template defined in Section 3, not a separate mock
This gives creators direct visibility into what their non-subscribing audience actually sees, closing the trust gap of publishing premium content on faith
This same action is also available on the standalone post page for the identical premium post — fully specified in C4b Section 6. Both surfaces use the same underlying preview template; a creator can trigger it from wherever they happen to be reviewing that specific post
Edge Cases:
This preview is available only to the creator, only on their own premium posts
No actual impersonation or session-switching occurs — it is a conditional render of the visitor-facing template within the creator's own authenticated session
The preview is dismissible via a clear "خروج از پیش‌نمایش" action, returning the creator to their normal full-access view
Farsi copy:
Preview action label: مشاهده به عنوان کاربر
Preview mode banner (shown while active): شما در حال مشاهده این پست به شکلی هستید که کاربران غیر عضو می‌بینند.
Exit preview CTA: خروج از پیش‌نمایش
7. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Locked teaser text fade uses a linear gradient from transparent to {colors.canvas} (#ffffff), with the lock icon in {colors.ink-mute} (#64748d) centered on the fade
Image placeholder uses {colors.canvas-soft} (#f6f9fc) background, lock icon in {colors.ink-mute}, with the image count badge in pill-tag-soft style
پریمیوم badge uses {colors.brand-dark-900} (#1c1e54) background with white text, positioned at the top of the post card in the header row — consistent with C4/C4b; no badge is ever shown for free posts
Contextual message (logged-out or not-subscribed) renders in {colors.ink-mute} (#64748d), {typography.body-md}, centered above the CTA
Subscribe CTA and auth CTA both use button-primary-pill style (#533afd, pill radius) for visual consistency
"View as Visitor" preview banner uses {colors.warning} (#f59e0b) background with dark text — signals a temporary/altered viewing mode without implying an error
Minimum touch target for all interactive elements: 44×44px
Locked card layout is otherwise identical in structure to a free post card (avatar, username, timestamp, badge) — only the content body area differs
---
## U6 — Investor: Creator Profile Header
U6 — Investor: Creator Profile Header
Story: As an investor, I want to view a creator's public profile including their prediction stats (win rate, ROI, accuracy trend) so that I can evaluate a creator's credibility before subscribing.
Scope note: This story owns the investor-facing profile header on the public channel page (lumina.ir/@{username}) — the block above the post feed. The page itself, its URL structure, and the post list below are defined in C4 Section 12; the locked-teaser rendering of premium posts within that feed is defined in C5. U6 does not re-specify those.
⚠️ Forward dependency note: Prediction statistics originate from Epic 9 (Prediction Tracking Engine) and the visibility gate from Epic 10 (Public Track Record Page). Until Epic 9 exists, the entire statistics block is hidden per Section 3 — the header renders without it, not with placeholder values.
Acceptance Criteria:
1. Access & Context
Happy Path:
The profile header is the first block on a creator's public channel page (lumina.ir/@{username}), directly above the post feed
Accessible to all viewer types — logged-out visitors, logged-in non-subscribers, active subscribers, and the creator themselves
Reached by navigating from any surface where the creator's identity appears as a link — a shared channel link (external), a shared post permalink, tapping a creator's avatar or username on a post card (in the خانه feed or a channel's post list), or in-app creator search (Epic 7). The خانه feed itself never displays this header directly — it shows only posts from followed creators; it is simply one of several starting points an investor navigates from on their way to a creator's channel
Edge Cases:
If the creator's account is suspended, the header is not rendered at all — the page shows the channel-unavailable message instead (per C4 Section 12)
If the creator is Pending Verification or Rejected, their channel is not publicly discoverable and this header is not reachable by investors — the creator's own persistent status banner (C4 Section 2) is a separate, creator-only surface and never appears here
2. Header Content — Always Visible
Happy Path:
The header displays, in order:
Avatar — circular; falls back to the default placeholder (initials on {colors.primary} background) if the creator uploaded none (per C2 Section 3)
Username — @{username}, the creator's permanent public identifier
Verified badge — shown only for Verified creators
Bio — full text as entered in C2/C3; up to 300 characters
Market specialization tags — rendered as pill-tag-soft chips, in the order the creator selected them
Social & web links — as icons/labels, in the creator's saved order, opening in a new tab
Prediction statistics block — conditional, see Section 3
Follow / Unfollow button — see Section 4
Subscribe button — see Section 5
Edge Cases:
If the creator left bio empty (optional per C2), the bio area is not rendered — no empty placeholder
If the creator added no social links (optional per C2), that row is not rendered
Market specializations are always present — at least one tag is mandatory in C2, so this block always renders
Long bios render in full — no truncation, consistent with the no-truncation decision in C4
Farsi copy:
Verified badge label/tooltip: تأییدشده
3. Prediction Statistics Block (Conditional)
This block is governed by a strict two-state rule — it is either fully absent or fully present. There is no partial, placeholder, or zero-value rendering at any point.
Condition Rendering
Creator has not met the Epic 10 activation threshold (no predictions at all, or predictions exist but the threshold is unmet) Block entirely hidden. No heading, no empty state, no zeros, no "coming soon" text — the header renders as though the block does not exist
Creator has met the Epic 10 activation threshold Full summary displayed (see below)
Rationale (documented so this isn't later mistaken for an oversight): showing zeros would make a creator with no prediction history visually near-identical to one with a genuinely poor record — directly undermining the platform's credibility thesis. Showing partial activity counts below the threshold was considered and rejected in favour of a simpler two-state model: statistics appear only once they are aggregated enough to be meaningful.
Full summary contents (threshold met):
Win rate — wins ÷ total closed predictions, as a percentage
Total predictions — count of all predictions published
Active predictions — count currently open
ROI — average return across closed predictions
Accuracy trend — directional indicator over time
A CTA linking through to the creator's full public track record page (Epic 10 / U19)
Edge Cases:
The activation threshold itself is owned by Epic 10 — U6 only consumes the resulting boolean (threshold met: yes/no) and must not reimplement or hardcode the threshold logic. The exact minimum-closed-predictions value remains an Open Question in the PRD
If a creator has opted to hide their public track record page (C18), the statistics block is hidden here as well, and no CTA is shown — a creator's choice to stay private must be honoured consistently across surfaces, not just on the track record page itself
All statistics are read-only on this header — no filtering, sorting, or interaction beyond the CTA
Statistics reflect all of the creator's predictions, free and premium alike — the paywall governs access to prediction content and reasoning, never to their recorded outcomes. Hiding losing outcomes behind a paywall would defeat the entire proof-of-performance model
Farsi copy:
Section heading: عملکرد پیشبینی‌ها
Win rate label: نرخ موفقیت
Total predictions label: کل پیشبینی‌ها
Active predictions label: پیشبینی‌های فعال
ROI label: بازدهی
Accuracy trend label: روند دقت
Track record CTA: مشاهده کارنامه کامل
4. Follow / Unfollow
Happy Path:
Following is free and ungated — no referral code, no payment, no subscription required
Button reflects current state: دنبال کردن when not following, دنبال نکردن when already following
Tapping toggles the state immediately with optimistic UI update
Edge Cases:
Logged-out visitor tapping Follow → redirected to the unified auth entry flow, with the channel URL preserved as the return destination (U1 Sections 5–6). A single ورود/ثبت‌نام CTA is shown — never separate Register and Login options
Following does not grant access to premium content — that requires an active subscription (C5 Section 2)
Full follow-interaction mechanics (state persistence, effect on the خانه feed, notification behaviour) are owned by U8 — U6 owns only the button's presence and appearance within this header
Farsi copy:
Follow CTA: دنبال کردن
Unfollow CTA: دنبال نکردن
5. Subscribe
Happy Path:
Subscribe button is displayed in the header for any viewer who is not an active subscriber
Tapping initiates the subscription flow (Epic 5), which is referral-code-gated in Phase 0
Edge Cases:
Logged-out visitor tapping Subscribe → same unified auth redirect as Follow (Section 4), with the channel URL preserved. Authentication happens first; subscription is a separate subsequent step
Active subscriber → the Subscribe button is replaced with a subscription status indicator rather than shown as a redundant action
If the creator's referral code is at capacity, the investor enters the waitlist flow (specified in Epic 5, referenced in U1 Section 7) — U6 does not own that behaviour
Farsi copy:
Subscribe CTA: اشتراک
Active subscriber status indicator: مشترک هستید ✓
6. Viewer-State Summary
Viewer Header Content Follow Subscribe
Logged-out Full header (stats per Section 3) Shown — tap → auth flow Shown — tap → auth flow
Logged-in, not following, not subscribed Full header دنبال کردن اشتراک
Logged-in, following, not subscribed Full header دنبال نکردن اشتراک
Active subscriber Full header Follow state as applicable Replaced with مشترک هستید ✓
The creator themselves Full header Not shown Not shown
7. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Header sits on {colors.canvas} with a {colors.hairline} divider separating it from the post feed below
Avatar rendered circular; default placeholder uses {colors.primary} background with white initials
Username in {typography.heading-md}; bio in {typography.body-md}, {colors.ink}
Verified badge uses {colors.primary} (#533afd) with a checkmark icon, positioned inline beside the username
Market specialization tags use pill-tag-soft — {colors.primary-bg-subdued-hover} background, {colors.primary-deep} text
Social link icons use {colors.ink-mute} (#64748d), shifting to {colors.primary} on hover/press
All prediction statistics use font-feature-settings: "tnum" — non-negotiable per the design system's tabular-figures rule for any numeric or performance value, and is the brand's quiet financial-data signature
Statistics block sits within a card-feature-light container to visually distinguish it as a distinct credibility artifact rather than ordinary profile text
Track record CTA uses link-on-light style — {colors.primary} text, no underline by default
Subscribe CTA uses button-primary-pill (#533afd, pill radius); Follow uses button-secondary (outline, {colors.primary} text) so the paid action stays visually dominant
Active subscriber indicator uses {colors.primary} text with checkmark — not a button, no press state
Minimum touch target for all interactive elements: 44×44px
Header is mobile-first; on desktop it centers in a single column matching the post feed's max-width
---
## U7 — Investor: Premium Content Lock Indication (Cross-Surface)
Good — writing U7 as the cross-surface consistency spec. It owns the principle and the currently-orphaned feed case; C5 and C4b remain the source of truth for the pattern's visual details.
U7 — Investor: Premium Content Lock Indication (Cross-Surface)
Story: As an investor, I want to see a clear visual indicator when a post is premium and locked so that I understand what I'm missing and can decide whether to subscribe.
Scope note: This story owns the consistency principle for how locked premium content is presented to investors across every surface where it can appear, and fully specifies the one surface not yet owned by any other story: the خانه feed. The locked-teaser pattern itself (badge placement, 2-line text fade, image placeholder, message/CTA logic) is defined in C5 Section 3 and applied identically on the standalone post page in C4b Section 4 — U7 references that pattern rather than redefining it.
⚠️ Forward dependency note: The خانه feed as a container — its composition, ordering, empty states, pagination, and refresh behaviour — is owned by Epic 7 (User Feed), which is not yet written. U7 specifies only how a locked premium post renders and behaves once it appears within that feed. Epic 7 must not redefine locked-post rendering; it inherits it from here.
Acceptance Criteria:
1. The Consistency Principle
Happy Path:
A locked premium post presents identically to the investor on every surface where it can appear. There is exactly one locked-post pattern platform-wide, implemented as a single shared component — not re-created per surface
The pattern is defined in C5 Section 3 and consists of:
پریمیوم badge at the top of the card/content area, in the header row alongside avatar, username, and timestamp
Text teaser — first 2 lines only, fading into a gradient blur with a lock icon overlay
Image treatment — images are not shown at all; replaced by a generic locked placeholder (branded lock icon), never a blurred version of the real image. An optional count badge indicates how many images are behind the lock
Contextual message + single CTA, determined by the viewer's auth state (Section 3)
Creator identity, timestamp, and the پریمیوم badge always remain fully visible — only the content body is restricted
Surfaces this applies to:
Surface Owning Story Status
Public channel page (lumina.ir/@{username}) post list C5 Section 3 Specified
Standalone post page (lumina.ir/@{username}/posts/{post_id}) C4b Section 4 Specified
خانه feed U7 (this story), Section 2 Specified here
Edge Cases:
If any future surface renders posts (search results, discovery, notifications), it inherits this same pattern by default — new surfaces do not get to invent their own locked-post treatment
The pattern does not vary by how the investor arrived — tapping a locked card from the feed, opening a shared permalink, or browsing a channel all produce identical rendering
2. Locked Posts in the خانه Feed
Happy Path:
Premium posts from creators the investor follows but is not subscribed to appear in the خانه feed as locked cards, using the pattern from Section 1
They are not filtered out or hidden — an investor should see that a creator they follow is actively publishing premium analysis, since that awareness is the primary conversion trigger
Locked cards sit inline in normal chronological order alongside free posts — no separate section, no grouping, no reordering
The اشتراک در کانال CTA appears directly on the locked card, allowing subscription to be initiated without leaving the feed
Edge Cases:
If an investor follows a creator and is subscribed to them, that creator's premium posts appear fully unlocked in the feed — identical to free posts apart from the retained پریمیوم badge
If an investor's subscription expires, previously unlocked posts already in their feed revert to locked cards on next feed load or refresh — no grace period, consistent with C5 Section 2
If a creator is suspended, none of their posts (free or premium) appear in the feed at all — suspension is a full blackout per A2, and takes precedence over any locked/unlocked logic
A locked card is fully tappable — tapping the card body navigates to the standalone post page (C4b), where the same locked pattern is shown with its own CTA
Locked and free posts are counted identically for feed pagination purposes — locking affects presentation only, never feed composition or ordering
Error States:
No error states specific to locking — this is a display state derived from subscription status, involving no user input
3. Message & CTA Logic by Auth State
Identical across all three surfaces. A single message and a single CTA are shown — never two competing calls to action.
Viewer State Message CTA
Logged-out برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید. ورود/ثبت‌نام
Logged-in, not subscribed برای مشاهده این محتوا، نیاز به اشتراک در کانال آن دارید. اشتراک در کانال
Logged-in, subscribed — No lock — full content shown
Edge Cases:
A logged-out visitor never sees a Subscribe CTA — authentication must complete first; subscription is a separate subsequent step (consistent with U1 Section 6)
Tapping the logged-out CTA preserves the current page as the post-auth return destination (U1 Section 5)
On successful subscription, locked content unlocks immediately without requiring a manual refresh
The logged-out message deliberately reads "وارد شوید یا ثبت‌نام کنید" — never assuming the visitor is a new user, since the platform's auth entry screen silently handles both cases
4. What the Lock Must Never Reveal
Happy Path:
The 2-line text limit is a hard ceiling, not a guideline. It exists because a longer excerpt risks revealing the directional substance of an analysis — which would let a non-subscriber extract the value without subscribing, defeating the entire monetization model
Images are never blurred versions of the real image. A blurred chart can still leak directional information (e.g. red vs. green candle patterns, an obvious trend line), so a generic placeholder is used instead — this is a deliberate content-security decision, not a visual style choice
Edge Cases:
For prediction posts (C8) marked premium, the structured prediction fields (asset, direction, entry, target, horizon) are treated as locked content and are not shown in the teaser — direction and target are precisely the values a non-subscriber must not obtain for free
The prediction's recorded outcome, however, is never hidden — aggregate statistics on the creator's profile header (U6 Section 3) and public track record page (Epic 10) reflect all predictions regardless of their free/premium status. The paywall governs access to reasoning and calls, never to results
5. Creator-Side Verification
A creator can confirm exactly what an investor sees on a locked post via مشاهده به عنوان کاربر, available on their own premium posts — specified in C5 Section 6 (کانال tab) and C4b Section 6 (standalone post page)
Because U7 mandates a single shared component, this preview is accurate for every surface — what the creator previews is what an investor sees in the feed, on the channel page, and on the standalone page alike
6. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
پریمیوم badge: {colors.brand-dark-900} (#1c1e54) background with white text, pill-tag-soft style — positioned at the top of the card in the header row. No badge is ever rendered for free posts; only the exception is marked
Locked text fade: linear gradient from transparent to {colors.canvas} (#ffffff), with the lock icon in {colors.ink-mute} (#64748d) centered on the fade
Locked image placeholder: {colors.canvas-soft} (#f6f9fc) background, lock icon in {colors.ink-mute}, optional image count badge in pill-tag-soft style
Contextual message: {colors.ink-mute} (#64748d), {typography.body-md}, centered above the CTA
Both the subscribe CTA and the logged-out auth CTA use button-primary-pill (#533afd, pill radius) — visually consistent, since both are the primary conversion action in their respective states
Locked card structure is otherwise identical to a free post card (avatar, username, timestamp, badge row) — only the content body area differs, so locking never disrupts the feed's visual rhythm
Minimum touch target for all interactive elements: 44×44px
All surfaces are mobile-first
---
## U8 — Investor: Follow a Creator
U8 — Investor: Follow a Creator
Story:
As an investor, I want to follow a creator for free to see their public content so that I can track their quality before committing to a paid subscription.
Scope note: This story owns the follow mechanic end-to-end — the action itself, what it does, and the دنبال‌شده‌ها management surface. The Follow button's presence and appearance within the creator profile header is defined in U6 Section 4; this story defines what happens when it's tapped.
⚠️ Forward dependency note: The خانه feed as a container is owned by Epic 7 (User Feed). U8 defines only that following is what populates it — feed composition, ordering, and pagination belong to Epic 7.
Acceptance Criteria:
1. What Following Is (and Isn't)
Happy Path:
Following is free and completely ungated — no referral code, no payment, no subscription, no capacity limit. Any registered investor can follow any Verified creator
Following a creator causes that creator's posts to appear in the investor's خانه feed
There is no limit on how many creators an investor can follow
What following explicitly does NOT do:
Does not grant access to premium content — that requires an active, referral-code-originated subscription (C5 Section 2). A follower sees premium posts as locked cards in their feed (U7 Section 2)
Does not notify the creator (Section 6)
Does not affect the creator's public profile in any visible way (Section 6)
Edge Cases:
Follow and subscription are related but distinct states — see Section 2 for how they interact
Follow state is per-account, not per-device — it syncs across any device the investor logs into
2. Follow ↔ Subscription Relationship
Subscription is treated as a strict superset of following. An investor who pays for a creator's premium content necessarily wants that creator's posts in their feed.
Happy Path:
Subscribing auto-follows. On successful subscription, if the investor is not already following that creator, the follow relationship is created automatically as part of the same transaction — no separate action required
While a subscription is active, the investor cannot unfollow that creator — the unfollow control is frozen everywhere it appears (profile header, post page mini-header, دنبال‌شده‌ها list), with a tooltip explaining why
When the subscription expires, the follow relationship persists but becomes a normal, unfollowable follow — the control unfreezes automatically with no action needed from the investor
Rationale: without auto-follow, the fastest-converting investors — those who land via a shared link and subscribe immediately without following first — would pay for content and then see none of it in their feed, and reasonably conclude the product is broken. Freezing unfollow while subscribed prevents that same nonsensical state from being reached deliberately.
Edge Cases:
If the investor was already following before subscribing, nothing changes on subscribe except that the unfollow control freezes
Unfollowing does not cancel a subscription — but since unfollow is unavailable while subscribed, this combination cannot arise in Phase 0
Reactivating an expired subscription (U3) re-freezes the unfollow control; if the investor unfollowed during the expired window, reactivation re-applies the auto-follow
Auto-follow applies to new subscriptions, renewals, and reactivations alike
Phase 1+ consideration: allowing subscribers to unfollow (treating follow purely as a feed-delivery preference, useful for an investor subscribed to many creators who wants to mute one) was considered and deliberately deferred. Phase 0 prioritizes eliminating a confusing state over granting that flexibility.
Farsi copy:
Frozen unfollow tooltip: تا زمانی که اشتراک این کانال فعال است، امکان لغو دنبال‌کردن وجود ندارد.
3. Following — Entry Points & Behaviour
Happy Path:
Follow/Unfollow is available from:
The creator profile header on the public channel page (U6 Section 4)
The creator mini profile header on a standalone post page (C4b Section 2)
The دنبال‌شده‌ها list in داشبورد — unfollow only (Section 5)
Tapping دنبال کردن applies immediately with an optimistic UI update — the button switches to دنبال نکردن without waiting for server confirmation
The creator's subsequent posts begin appearing in the investor's خانه feed
Edge Cases:
Logged-out visitor tapping Follow → redirected to the unified auth entry flow with the current page preserved as the return destination (U1 Sections 5–6). A single ورود/ثبت‌نام CTA is shown. The follow action is not auto-applied on return — the investor lands back on the channel page with the Follow button in its normal untapped state and taps it deliberately. Silently performing an action the user initiated before authenticating is surprising; the redirect exists to enable the action, not to complete it on their behalf
If the creator is suspended after being followed, their posts disappear from the investor's feed (full blackout per A2) but the follow relationship is preserved — if the creator is reinstated, their posts reappear without the investor needing to re-follow
Error States:
If the follow action fails server-side after the optimistic update, the button reverts to its previous state and a brief error toast is shown
Network unavailable: same revert-and-notify behaviour
Farsi copy:
Follow CTA: دنبال کردن
Unfollow CTA: دنبال نکردن
Follow failure toast: عملیات ناموفق بود. دوباره تلاش کنید.
4. Unfollowing from a Channel or Post Page
Happy Path:
Tapping دنبال نکردن from the profile header or post page mini-header unfollows immediately, with no confirmation dialog
The creator's posts stop appearing in the investor's خانه feed
The button reverts to دنبال کردن — re-following is a single tap away
Edge Cases:
No confirmation is required here because the creator's identity is directly visible on screen, making an accidental unfollow immediately obvious and trivially reversible. This deliberately differs from the list-based unfollow in Section 5
If the investor has an active subscription, the unfollow control is frozen here per Section 2 — tapping it shows the explanatory tooltip and takes no action
Unfollowing does not delete any history — transaction records (U4) and subscription records (U2/U3) are unaffected
5. دنبال‌شده‌ها — Followed Creators List
Happy Path:
A third sub-section is added to the داشبورد tab, alongside اشتراک‌ها and تراکنش‌ها:
داشبورد
├── اشتراک‌ها
├── تراکنش‌ها
└── دنبال‌شده‌ها
Displays a simple list of every creator the investor currently follows
Each row shows: creator avatar, username, verified badge, and an inline unfollow action
Tapping a row (anywhere except the unfollow action) navigates to that creator's channel page
Sorted by most recently followed first — no sorting controls, no search, no filters. Deliberately minimal for Phase 0
Unfollowing from the list — with confirmation:
Tapping the unfollow action opens a confirmation dialog naming the specific creator
On confirm: creator unfollowed, row removed, posts stop appearing in خانه
On cancel: dialog closes, nothing changes
Confirmation is required only here — a list of avatars makes mistaps easy and less immediately noticeable than on a channel page, so the friction is placed where the actual risk is
Edge Cases:
If the investor follows no one, an empty state is shown with a CTA to the خانه tab
If a followed creator is suspended, their row is visually dimmed and non-navigable (tapping the row body does nothing, since the channel is unavailable) — but the unfollow action remains fully functional, with the same confirmation dialog. A creator being suspended is a plausible moment for an investor to want to clean up their list, so the action must stay available
If the investor has an active subscription to a listed creator, the unfollow action on that row is frozen per Section 2, with the explanatory tooltip
The list has no pagination in Phase 0 — with 5–10 creators platform-wide, the maximum possible list length is trivially short
Error States:
If the list fails to load, an error message is shown with a retry option
If the unfollow fails, the row remains in the list and an error toast is shown
Farsi copy:
Sub-section label: دنبال‌شده‌ها
Empty state message: هنوز کریتوری را دنبال نکرده‌اید.
Empty state CTA: رفتن به خانه
Suspended creator note: کانال این کریتور موقتاً در دسترس نیست.
Unfollow action tooltip: دنبال نکردن
Confirmation dialog heading: دنبال نکردن {username}
Confirmation dialog body: با این کار، پست‌های این کریتور دیگر در خانه شما نمایش داده نمی‌شود. آیا مطمئن هستید؟
Confirm CTA: بله، دنبال نکن
Cancel CTA: انصراف
List load error: خطا در بارگذاری لیست. دوباره تلاش کنید.
Unfollow failure toast: عملیات ناموفق بود. دوباره تلاش کنید.
6. Follower Visibility — Deliberate Omissions
Two decisions here are intentional and should not be mistaken for oversights:
No follow notification to the creator.
Creators receive no notification when someone follows them. Notifications are reserved for events that carry real signal — chiefly paid subscriptions
Rationale: a founding creator driving their existing Telegram or Instagram audience onto the platform could receive dozens of follow events in a single day. That is noise, and it would train creators to ignore notifications entirely — devaluing the subscription notifications that actually matter
The creator's own follower count is available privately on their dashboard (C9), which serves the same informational need without the interruption
No public follower count on the creator profile.
The follower count is not displayed to investors anywhere — not on the profile header (U6), not on post cards, not in search results
Rationale: the platform's entire positioning is credibility earned through verified performance, not follower counts — performance proof over social proof. Displaying a follower count would partially reimport the vanity metric the product is built to replace
This matters acutely in Phase 0: every founding creator would display a number close to zero, which reads as "nobody trusts this person" when the actual situation is "the platform launched last week." The absence of the metric is more honest than the presence of a misleading one
Revisit in Phase 1+, once counts are meaningful and the reputation layer exists to contextualize them
7. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Follow button uses button-secondary style (outline, {colors.primary} text) so the paid Subscribe action remains visually dominant — consistent with U6 Section 7
Followed state (دنبال نکردن) uses the same button-secondary geometry with {colors.ink-mute} text, signalling an already-completed action rather than a call to action
Frozen unfollow control (active subscriber) uses opacity: 0.4 with cursor: not-allowed, consistent with the frozen-control pattern established for the FAB in C4 and the edit icon in C4 Section 10 — visible but non-interactive, with an explanatory tooltip on tap
دنبال‌شده‌ها list rows use card-feature-light style — {colors.canvas} background, {colors.hairline} border, {rounded.lg} radius, Level 1 shadow
Creator avatar in list rows rendered circular, falling back to the default initials placeholder on {colors.primary} where no avatar was uploaded
Verified badge in list rows uses {colors.primary} (#533afd) with a checkmark icon
Inline unfollow action uses {colors.ink-mute} (#64748d) — deliberately understated, not a {colors.ruby} destructive treatment, since unfollowing is low-stakes and fully reversible
Suspended creator rows use opacity: 0.5 with a lock icon (consistent with U2 Section 7) — but the unfollow action within the row renders at full opacity, since it remains functional
Confirmation dialog uses the standard modal pattern; confirm CTA uses button-primary-pill
Minimum touch target for all interactive elements: 44×44px
All surfaces mobile-first; دنبال‌شده‌ها list stacks in a single column
---
## C6 — Creator Channel Sharing (External Promotion)
C6 — Creator Channel Sharing (External Promotion)
Story: As a creator, I want to share my channel link externally (Telegram, Instagram, X, etc.) so that I can drive my existing audience to the platform.
Note: This story defines the enhanced, creator-specific share behavior — a pre-filled, editable promotional caption combined with the channel link. It extends the same share icon already defined in C4 Section 12, which remains unchanged for non-creator viewers (investors, logged-out visitors get a plain link-only share with no caption). The icon is one control; its behavior branches by who is viewing. There is only one entry point for the enhanced flow — the کانال tab is the creator's own rendering of their channel page, not a separate screen.
Acceptance Criteria:
1. Access & Entry Point
Happy Path:
The enhanced share action is available to the creator (channel owner) via a dedicated share icon in the header of the creator's own کانال tab
Tapping/clicking the icon opens the enhanced share flow (Sections 2–3)
Only Verified creators can access this enhanced flow
Edge Cases:
If the creator's account is Pending Verification, the share icon is frozen (opacity: 0.4) — tapping shows a contextual blocking message, consistent with the FAB pattern in C4 Section 1
If the creator's account is Suspended, the share icon is also frozen with a different contextual message
For any user other than the channel owner (investors, logged-out visitors) viewing the same channel page, tapping the share icon triggers the simple share behavior already defined in C4 Section 12 — unchanged, no caption
Error States:
Pending verification: blocking message shown on tap
Suspended: blocking message shown on tap
Farsi copy:
Share icon tooltip (creator, own channel): اشتراک‌گذاری کانال
Pending verification blocking message: برای اشتراک‌گذاری کانال، ابتدا باید احراز هویت شما تأیید شود.
Suspended blocking message: حساب شما تعلیق شده است. امکان اشتراک‌گذاری کانال وجود ندارد.
2. Caption Composition
Happy Path:
On first use, a default suggested caption is pre-filled: من را در لومینا دنبال کن 👇
The caption is fully editable — the creator can rewrite it entirely or adjust the default
Maximum caption length: 150 characters — a live counter is shown
On subsequent uses, the field is pre-filled with the creator's last-used caption (not the default) — the system remembers their most recent edit
The channel link (lumina.ir/@{username}) is appended automatically below the caption when shared — the creator does not type or edit the link itself
Edge Cases:
If the creator clears the caption field entirely (empty string), sharing proceeds with link only — this is a valid state, not an error
If saving the "last-used caption" fails due to a network error, this fails silently — it does not block the share action itself; the next attempt simply falls back to the default suggestion
The default suggested caption is a fixed, hardcoded string in Phase 0 — not admin-configurable (flagged as a potential Phase 1 enhancement)
Error States:
Input stops accepting new characters at 150 — counter turning {colors.ruby} (#ea2261) communicates the limit
Farsi copy:
Default suggested caption: من را در لومینا دنبال کن 👇
Caption field label: پیام اشتراک‌گذاری کانال
Character counter: {n}/۱۵۰
Counter at limit: به حداکثر تعداد کاراکتر رسیدید.
3. Sharing Mechanics — Mobile
Happy Path:
Tapping the share icon opens a bottom sheet containing:
The editable caption field (Section 2)
A primary CTA: اشتراک‌گذاری — closes the bottom sheet immediately, then invokes the native OS share sheet, passing the caption and link combined as the shared text (caption on one line, link below it)
A secondary action: کپی لینک — copies the bare channel link only (bypassing the caption), shows a confirmation toast, and closes the bottom sheet
Tapping the dimmed overlay behind the bottom sheet dismisses it without action — consistent with other dismissible overlays in the product (e.g., the FAB mini-menu in C4)
Edge Cases:
The native OS share sheet shows whichever apps are installed on the creator's device — the platform does not construct or call any specific third-party URL directly, consistent with the approach in C4/C4b
If the creator dismisses the native share sheet without selecting an app, no caption is saved as "last-used" — only a confirmed share (an app was actually selected) updates the remembered caption
Tapping کپی لینک does not update the "last-used caption" — since no caption was actually used in that action
Error States:
None specific to this mechanism — native share sheet failures are handled at the OS level, outside the platform's control
Farsi copy:
Bottom sheet heading: اشتراک‌گذاری کانال
Primary CTA: اشتراک‌گذاری
Secondary CTA: کپی لینک
Copy link confirmation toast: لینک کانال کپی شد.
4. Sharing Mechanics — Desktop
Happy Path:
Clicking the share icon opens a popover containing:
The editable caption field (Section 2)
A primary CTA: کپی همه — copies the caption and link together as a single combined text block, shows a confirmation toast, and closes the popover
A secondary CTA: کپی لینک — copies the bare channel link only, shows a confirmation toast, and closes the popover
Clicking outside the popover closes it without action
Edge Cases:
Only a successful کپی همه action updates the "last-used caption" for next time — کپی لینک does not, consistent with the mobile behavior in Section 3
Error States:
If the clipboard write fails (rare browser permission issue), an inline error is shown with a retry option — the popover remains open in this case so the creator can retry
Farsi copy:
Popover heading: اشتراک‌گذاری کانال
Primary CTA: کپی همه
Secondary CTA: کپی لینک
Copy all confirmation toast: متن و لینک کپی شد.
Copy link confirmation toast: لینک کانال کپی شد.
Clipboard error: کپی ناموفق بود. دوباره تلاش کنید.
5. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Mobile bottom sheet uses {colors.canvas} (#ffffff) background, {rounded.xl} radius on top corners, Level 2 shadow, with a dimmed scrim overlay behind it
Desktop popover uses card-feature-light style with Level 2 shadow, {rounded.md} radius
Caption input field uses standard text-input style — {colors.hairline-input} border, focus state swaps to {colors.primary}
Character counter uses {colors.ink-mute} (#64748d), switches to {colors.ruby} (#ea2261) at 0 remaining
Primary CTA (اشتراک‌گذاری / کپی همه) uses button-primary-pill style (#533afd, pill radius)
Secondary CTA (کپی لینک) uses button-secondary style — outline, {colors.primary} text
Frozen share icon (Pending/Suspended states) uses opacity: 0.4, consistent with the FAB pattern in C4
Minimum touch target for all interactive elements: 44×44px
Mobile bottom sheet and desktop popover are both compact, single-purpose, no unnecessary scrolling

View File

@ -1,680 +0,0 @@
# Round 2 — Auth & onboarding
> Attach together with `design-brief.md`. The brief defines the design system, shared patterns and status vocabulary; this file holds the full acceptance criteria and exact Farsi copy.
> Reuse round-1 components. Mobile-first forms; desktop single column, 560px max (C3: 640px).
## Deliver in this round
- Entry screen (shared login/registration), OTP with countdown, blocked state, login success modal, suspended-account screen
- Investor تکمیل پروفایل with live username check and step indicator
- Creator KYC form (no exit), ID card upload
- Creator تکمیل پروفایل: bio, avatar crop, links (quick-add, reorder, 8-link limit), market tags, T&C, success screen
- اطلاعات کاربری (C3) in Verified, Pending and Rejected states, with the unsaved-changes dialog
For every screen: mobile and desktop, RTL, real Farsi copy from below, and all listed states.
## Stories included
- **U1** — Investor Registration & Login _(ClickUp status: in review)_
- **C1** — Creator Registration & Identity Verification _(ClickUp status: in review)_
- **C2** — Creator Profile Setup _(ClickUp status: in review)_
- **C3** — Creator Profile Edit _(ClickUp status: in review)_
---
## U1 — Investor Registration & Login
Story:
As an investor, I want to register and log in with my mobile number so that I can access the platform securely.
Acceptance Criteria:
1. Entry Screen — Mobile Number Input
Happy Path:
A single entry screen handles both registration and login — the user does not need to explicitly choose between the two
The screen accepts Iranian mobile numbers only (format: 09XXXXXXXXX — 11 digits starting with 09)
Input field triggers numeric keyboard on mobile
On submission, the system checks whether the number is already registered:
Number not registered → moves to OTP step → then profile setup → then redirect (context-aware, see Section 5)
Number already registered as investor → moves to OTP step → then redirect (context-aware, see Section 5)
Number already registered as creator → inline error, no redirect
Edge Cases:
The user does not know whether they are registering or logging in — the system handles this silently after number submission
A creator cannot register as an investor using the same mobile number in Phase 0
Error States:
Invalid format: inline error shown, no OTP sent
Number belongs to a creator account: specific inline error shown
Farsi copy:
Screen heading: ورود یا ثبت‌نام
Field label: شماره موبایل
Placeholder: ۰۹۱۲ ۳۴۵ ۶۷۸۹
Invalid format error: شماره موبایل وارد‌شده معتبر نیست.
Creator account error: این شماره به یک حساب کریتور تعلق دارد و امکان ثبت‌نام به عنوان سرمایه‌گذار را ندارد.
CTA button: ادامه
2. OTP Verification
Happy Path:
A 5-digit OTP is sent via SMS immediately after a valid number is submitted
OTP expires after 2 minutes
A visible countdown timer shows remaining time
On correct OTP entry:
New user → proceeds to profile setup (Section 3)
Returning user → login success modal shown → redirected based on context (Section 5)
Edge Cases:
User can request a resend only after the countdown expires — not before
After 3 consecutive failed OTP attempts, the session is blocked for 10 minutes
If the user navigates back to change their mobile number, the current OTP is invalidated — a new one is sent after re-submission
Error States:
Wrong OTP: inline error shown, remaining attempts decremented
Expired OTP: inline error with resend prompt
Blocked session: full-screen message with countdown to unblock
Network error on OTP send: inline error with retry option
Farsi copy:
Screen heading: کد تأیید را وارد کنید
Screen subheading: کد ۵ رقمی ارسال‌شده به {mobile_number} را وارد کنید.
SMS body: کد تأیید شما: ۴۵۲۱۸ — این کد تا ۲ دقیقه معتبر است.
Countdown label: انقضای کد: {mm:ss}
Wrong OTP error: کد وارد‌شده اشتباه است. لطفاً دوباره تلاش کنید.
Expired OTP error: کد منقضی شده. یک کد جدید دریافت کنید.
Resend CTA: ارسال مجدد کد
Blocked state: تعداد تلاش‌های مجاز به پایان رسید. ۱۰ دقیقه دیگر تلاش کنید.
Network error: ارسال کد تأیید ناموفق بود. دوباره تلاش کنید.
Returning user login success modal: شما وارد حساب کاربری خود شدید.
3. Registration — Profile Setup
This step is shown to new users only, immediately after OTP verification. It is mandatory and cannot be skipped — the user cannot access the platform without completing it.
3.1 Full Name
Happy Path:
Two separate fields: first name (نام) and last name (نام خانوادگی)
Persian characters only — Latin characters are not accepted
Both fields are mandatory
Full name is stored for payment reconciliation with ZarinPal — not publicly displayed in Phase 0
Full name can be edited later from the user's profile settings
Edge Cases:
Full name does not need to be unique across the platform
Error States:
Empty first name field: inline error shown
Empty last name field: inline error shown
Latin characters entered: inline error shown on that specific field
Farsi copy:
First name field label: نام
First name placeholder: مثال: علی
Last name field label: نام خانوادگی
Last name placeholder: مثال: رضایی
Empty error: این فیلد الزامی است.
Latin characters error: لطفاً نام را به فارسی وارد کنید.
3.2 Username
Happy Path:
User chooses a unique username that serves as their public identifier on the platform
Username rules:
3–30 characters
Allowed characters: Latin letters (a–z, A–Z), digits (0–9), and underscores (_)
No spaces, no special characters other than underscore
Case-insensitive — Ali and ali are treated as the same username
Must be unique across both investor and creator accounts
Real-time availability check fires after the user stops typing for 500ms (debounced)
Username is immutable after submission — a clear note is shown before submission
Edge Cases:
A user cannot take a username already held by a creator, and vice versa
Real-time availability check is debounced to avoid excessive API calls
Error States:
Taken username: inline error with availability indicator turning red
Invalid characters: inline error shown
Too short: inline error shown
Too long: input stops accepting characters at 30
Empty field on submission: inline error shown
Farsi copy:
Field label: نام کاربری
Field hint: نام کاربری شناسه عمومی شما در پلتفرم است و پس از ثبت قابل تغییر نیست.
Placeholder: مثال: ali_investor
Taken error: این نام کاربری قبلاً انتخاب شده. نام دیگری امتحان کنید.
Invalid characters error: نام کاربری فقط می‌تواند شامل حروف انگلیسی، اعداد و آندرلاین باشد.
Too short error: نام کاربری باید حداقل ۳ کاراکتر باشد.
Available confirmation: این نام کاربری در دسترس است. ✓
Immutability note: نام کاربری پس از ثبت قابل تغییر نیست.
Empty error: وارد کردن نام کاربری الزامی است.
3.3 Form Submission
Happy Path:
All fields are valid and filled
User taps the submit CTA
Account is fully created
User is redirected based on context (Section 5)
Edge Cases:
If the network fails on submission, an error banner appears at the top and all entered data is preserved — not lost
Error States:
Any invalid or empty mandatory field is highlighted with an inline error on submission attempt
Network error: error banner at top of screen with retry option
Farsi copy:
Screen heading: تکمیل پروفایل
Screen subheading: برای ورود به پلتفرم، اطلاعات زیر را تکمیل کنید.
Submit CTA: ورود به پلتفرم
Network error banner: خطا در ثبت اطلاعات. اتصال اینترنت خود را بررسی کنید.
4. Login — Returning User
Happy Path:
Returning investor enters their registered mobile number on the entry screen
System silently detects the number is registered and sends an OTP
On correct OTP entry, login success modal is shown and user is redirected based on context (Section 5)
Edge Cases:
If a returning user's account has been suspended, they are shown a suspended account screen after OTP verification — no redirect occurs
The entry screen is identical for new and returning users — no distinction is made until after number submission
Error States:
Same OTP error states as Section 2 apply
Suspended account: full-screen suspended message shown after OTP verification
Farsi copy:
Login success modal: شما وارد حساب کاربری خود شدید.
Suspended account screen heading: حساب شما تعلیق شده است.
Suspended account screen body: برای اطلاعات بیشتر با پشتیبانی تماس بگیرید.
Support CTA: تماس با پشتیبانی
5. Post-Authentication Redirect (Context-Aware)
⚠️ Forward dependency note: Full implementation of context-aware redirect — including creator profile URL structure, deep link handling, and locked content rendering — is fully specified in Epic 4 (Creator Channel: C4, C4b, C5). The principle is stated here so the authentication flow is built with this behaviour in mind from day one.
Principle:
After successful registration or login, the redirect destination is context-aware:
If the user entered the auth flow from a creator's public channel or a specific post → redirect back to that exact page after completing registration or login
If the user entered the auth flow directly (no creator channel context) → redirect to خانه tab
The originating context must be preserved throughout all registration steps so it is available at the moment of redirect
Farsi copy:
Welcome message for new users: به [نام پلتفرم] خوش آمدید.
6. Logged-Out User Access
⚠️ Forward dependency note: Full specification of the locked content teaser rendering (what is shown vs. hidden, exact layout) is defined in C4, C4b, and C5. This section states only the authentication-related principle: what happens when a logged-out user attempts to act on locked content.
Principle:
Unauthenticated users can browse creator public channels and view free content via a shared link or direct visit — no registration required
Premium content is shown to logged-out users as a locked teaser (full rendering specified in C5)
Any action requiring authentication — subscribing, following, interacting — shows a single unified prompt directing the user to the entry screen (Section 1)
There is only one CTA shown to logged-out users in any locked-content context — the platform never shows separate "Register" and "Login" buttons, since the entry screen itself silently determines which flow applies
After completing registration or login, the user is redirected back to the exact page they were on — as defined in Section 5
Farsi copy:
Locked content prompt (logged-out, shown across all locked-content contexts): برای دسترسی به این محتوا، ابتدا وارد شوید یا ثبت‌نام کنید.
Unified auth CTA: ورود/ثبت‌نام
7. Subscription Access & Waitlist
⚠️ Forward dependency note: Full specification of referral code validation, subscription access control, waitlist entry, and waitlist notification mechanics are deferred to Epic 5 (Paid Access Infrastructure). The following principles are stated here for awareness only.
Principles:
Subscription access to a creator's premium content is controlled via a referral code tied to that creator
Each referral code has a configurable maximum number of uses — set and adjusted manually by the admin in the database
If a referral code has reached its maximum use limit at the time an investor attempts to subscribe, the investor is placed on a waitlist for that creator's channel
When the admin increases the max_uses of a referral code, all waitlisted users for that creator are notified simultaneously via in-app notification and SMS — first to act gets the available slot
Existing subscribers can renew their subscriptions freely regardless of referral code capacity — capacity limits apply to new subscriptions only
8. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text
Numeric fields (mobile number, OTP) use font-feature-settings: "tnum" per design system
Primary CTA buttons use button-primary-pill style (#533afd, pill radius)
Error messages render in {colors.ruby} (#ea2261)
Username availability confirmation renders in {colors.primary} (#533afd) with a checkmark
OTP countdown timer renders in {colors.ink-mute} (#64748d), switching to {colors.ruby} in the last 30 seconds
Progress through registration steps is communicated via a simple step indicator at the top — current step highlighted, no total step count shown to avoid overwhelming new users
Minimum touch target for all interactive elements: 44×44px
All registration and login screens are mobile-first
---
## C1 — Creator Registration & Identity Verification
C1 — Creator Registration & Identity Verification
Story: As a creator, I want to register with my mobile number and complete identity verification so that I have a verified, credible identity on the platform.
Acceptance Criteria:
1. Mobile Number Entry
The registration screen accepts Iranian mobile numbers only (format: 09XXXXXXXXX — 11 digits starting with 09)
Input field triggers numeric keyboard on mobile
If the number is already registered, the system shows an error and directs the user to the login flow
If the format is invalid, an inline error appears before the OTP is sent
On correct OTP entry:
New user → proceeds directly to profile & KYC step (no modal)
Returning user (login flow) → a confirmation modal appears before redirecting to the داشبورد tab
Farsi copy:
Field label: شماره موبایل
Placeholder: ۰۹۱۲ ۳۴۵ ۶۷۸۹
Invalid format error: شماره موبایل وارد‌شده معتبر نیست.
Already registered error: این شماره قبلاً ثبت شده. وارد شوید.
CTA button: ارسال کد تأیید
Login success modal: شما وارد حساب کاربری خود شدید.
2. OTP Verification
A 5-digit OTP is sent via SMS immediately after the creator submits their number
OTP expires after 2 minutes
A visible countdown timer shows remaining time
Creator can request a resend only after the countdown expires
After 3 consecutive failed OTP attempts, the session is blocked for 10 minutes
On correct OTP entry, behaviour follows Section 1 (new vs. returning user)
On expired OTP entry, system rejects it and prompts a resend
Farsi copy:
SMS body: کد تأیید شما: ۴۵۲۱۸ — این کد تا ۲ دقیقه معتبر است.
Countdown label: انقضای کد: {mm:ss}
Wrong OTP error: کد وارد‌شده اشتباه است. لطفاً دوباره تلاش کنید.
Expired OTP error: کد منقضی شده. یک کد جدید دریافت کنید.
Resend CTA: ارسال مجدد کد
Blocked state: تعداد تلاش‌های مجاز به پایان رسید. ۱۰ دقیقه دیگر تلاش کنید.
3. Profile Setup & KYC Submission
After OTP is verified, the creator fills in a single form with the following fields before submitting for admin review.
3.1 Username
Creator must choose a unique username serving as their public identifier (channel, profile URL, all public-facing surfaces)
Rules: 3–30 characters, Latin letters/digits/underscore only, case-insensitive, unique across the platform (checked against both investor and creator accounts), checked in real time (debounced)
Locked immediately upon first submission — this is permanent. Once a creator submits their KYC form for the first time, the username is reserved and can never be changed again through any later edit or resubmission flow, including after a rejection
Farsi copy:
Field label: نام کاربری
Field hint: نام کاربری شناسه عمومی شما در پلتفرم است و پس از ثبت اولیه قابل تغییر نیست.
Placeholder: مثال: ali_trader
Taken error: این نام کاربری قبلاً انتخاب شده. نام دیگری امتحان کنید.
Invalid characters error: نام کاربری فقط می‌تواند شامل حروف انگلیسی، اعداد و آندرلاین باشد.
Too short error: نام کاربری باید حداقل ۳ کاراکتر باشد.
Available confirmation: این نام کاربری در دسترس است. ✓
3.2 First Name
Persian characters only — matches the format of the national ID card
Mandatory
Locked immediately upon first submission — through both Pending and Verified states. Reopens for editing only if the submission is Rejected (see Section 8)
Farsi copy:
Field label: نام
Placeholder: مثال: علی
Empty error: این فیلد الزامی است.
Latin characters error: لطفاً نام را به فارسی وارد کنید.
3.3 Last Name
Persian characters only — matches the format of the national ID card
Mandatory
Locked immediately upon first submission — through both Pending and Verified states. Reopens for editing only if the submission is Rejected (see Section 8)
Farsi copy:
Field label: نام خانوادگی
Placeholder: مثال: رضایی
Empty error: این فیلد الزامی است.
Latin characters error: لطفاً نام خانوادگی را به فارسی وارد کنید.
3.4 National ID Number
Exactly 10 digits, numeric only — used by admin for verification, never publicly displayed
Locked immediately upon first submission — through both Pending and Verified states. Reopens for editing only if the submission is Rejected (see Section 8)
Farsi copy:
Field label: کد ملی
Invalid format error: کد ملی باید ۱۰ رقم باشد.
3.5 National ID Card Image Upload
Clear photo of the front side of the national ID card — stored securely, visible only to admins, never displayed publicly
Format: JPG, PNG, or PDF; max 5 MB; mandatory
This field always starts empty and requires a fresh selection every time the creator reaches it — on first submission, after any interrupted/resumed session, and on any resubmission following rejection. No previously selected or submitted image is ever pre-filled or restored, under any circumstance (see Section 8 for full rationale)
Farsi copy:
Upload field label: تصویر کارت ملی (رو)
Upload hint: یک تصویر واضح از روی کارت ملی خود آپلود کنید.
Upload error – wrong format: فقط فایل‌های JPG، PNG یا PDF مجاز هستند.
Upload error – too large: حجم فایل نباید بیشتر از ۵ مگابایت باشد.
3.6 Form Submission & Transition to Channel Setup
All fields mandatory
Creator taps ادامه
On successful submission, creator status is set to Pending Verification; username and all identity fields (first name, last name, national ID) are now locked
The creator is moved directly and seamlessly into channel/profile setup (C2 — تکمیل پروفایل) — no intermediate screen, no wizard, no separate confirmation page
A toast message confirming receipt is shown overlaid on top of the تکمیل پروفایل screen as it loads
Creator cannot publish content, set up payments, or be discovered while Pending — but can complete their channel/profile info immediately, since C2 explicitly allows this in Pending state
Farsi copy:
Submit CTA: ادامه
Toast (shown on the تکمیل پروفایل screen): اطلاعات شما دریافت شد. پس از تأیید، حساب شما فعال می‌شود.
4. Admin Review
Admin receives a new verification request notification in the Admin Panel
For each pending request, admin can view: first name, last name, username, phone number, uploaded national ID card image (full-size, zoomable) — first and last name displayed together as a single combined field in the Admin Panel UI, even though stored as two separate fields
Admin can Approve (→ Verified, notified) or Reject (→ must provide written reason → Rejected, notified with reason)
All admin actions timestamped and logged with admin's account ID
Farsi copy (Admin Panel):
Pending requests section heading: درخواست‌های احراز هویت
Approve CTA: تأیید
Reject CTA: رد کردن
Rejection reason field label: دلیل رد درخواست
Rejection reason placeholder: دلیل رد را بنویسید...
Rejection reason empty error: وارد کردن دلیل رد الزامی است.
5. Verification States
State Trigger Creator Access Identity Fields (name, national ID, username)
Pending Verification KYC form submitted; awaiting admin review Can complete/edit channel & profile via C3 (اطلاعات کاربری); cannot publish or monetize; can browse platform Fully locked — no self-service edits
Verified Admin approved Full creator access unlocked Fully locked, permanently
Rejected Admin rejected Can view rejection reason and resubmit — resubmission happens via the same C3 screen, not a separate form First name, last name, national ID reopen for editing; username remains permanently locked
Account state is visible to the creator across three surfaces (see Section 7)
On rejection, the admin-provided reason is shown both in-app and via SMS
Creator can resubmit — resubmission creates a new pending request in the Admin Panel
There is intentionally no self-service way to correct identity fields while Pending (e.g., a typo the creator spots before admin reviews it) — this is an accepted tradeoff for Phase 0, handled operationally via direct creator contact through the founding-creator support channel, with admin rejecting-with-reason to reopen the fields if needed
Farsi copy:
Pending label: در انتظار تأیید
Verified label: تأییدشده ✓
Rejected label: رد شده
Rejected message: احراز هویت شما تأیید نشد. دلیل: {admin_reason} — اطلاعات را اصلاح و مجدداً ارسال کنید.
Resubmit CTA: ارسال مجدد
6. Notifications
OTP sent: SMS with OTP code
KYC submitted: In-app notification confirming receipt
Admin approved: In-app notification + SMS
Admin rejected: In-app notification + SMS with rejection reason
Farsi copy:
KYC submitted in-app: اطلاعات شما دریافت شد. پس از بررسی، نتیجه به شما اطلاع داده می‌شود.
Approval SMS: حساب کریتور شما در [نام پلتفرم] تأیید شد. اکنون می‌توانید کانال خود را راه‌اندازی کنید.
Rejection SMS: احراز هویت شما در [نام پلتفرم] تأیید نشد. دلیل: {admin_reason} — برای اصلاح و ارسال مجدد وارد حساب خود شوید.
7. Persistent Verification Status Visibility & Resubmission Access (Principle)
⚠️ Forward dependency note: This section states the principle only. Full specification of placement, layout, copy, and interaction is owned by the following stories. C3 (اطلاعات کاربری) is the single, canonical, ongoing surface for viewing verification status, editing profile/channel info, and resubmitting KYC after rejection — کانال and داشبورد only ever navigate to C3, they never host a duplicate form themselves. C2's تکمیل پروفایل screen is a one-time, first-run screen only and is never a recurring destination.
Surface Treatment Tap Destination Full Spec Owned By
کانال tab Full banner with contextual message Navigates to C3, landing target per state below C4
اطلاعات کاربری (C3) Status badge under name/username — تأییدشده ✓ / در انتظار احراز هویت / رد شده (this is the destination itself) C3
داشبورد tab Compact status badge, visually consistent with the C3 badge Navigates to C3, landing target per state below C9 (Epic 6 — Creator Dashboard, not yet written)
Landing target within C3, by state:
Creator State Lands At Why
Rejected Top of screen — اطلاعات هویتی (identity block) Text identity fields (first name, last name, national ID) pre-fill with previously submitted values — creator only fixes what's wrong. The ID card image field always starts empty (Section 8)
Pending (Not applicable — under the mandatory onboarding sequence in Section 8, a Pending creator's profile is always complete) —
Pending, informational only Not tappable Nothing actionable left for the creator to do but wait
Principle (applies to all three surfaces):
The signal is persistent and non-dismissible for any creator not yet Verified
Once Verified, all three signals disappear entirely and do not reappear
This signal does not appear on the standalone post page (C4b)
C2 is a one-time, first-run screen only — reached exactly once via Section 3.6. It is not a recurring destination from کانال or داشبورد; C3 is
8. Onboarding Completeness & Draft Persistence (Cross-Story Principle)
⚠️ Forward dependency note: This principle applies to C1 (this story), C2 (channel/profile setup), and C3 (Rejected resubmission editing). It is documented once here as the shared source of truth.
Mandatory, uninterruptible first-run sequence:
KYC (C1) and channel/profile setup (C2) together form a single mandatory onboarding sequence for first-time creators — there is no in-app exit or back-navigation available until C2 is submitted
This means a Pending creator's profile is always complete by definition — the "incomplete profile" state does not exist for first-run onboarding
Fields that are optional within C2 (bio, avatar, social links) remain optional as content, but the screen itself cannot be abandoned mid-flow
Resumption after OS-level interruption (app killed, backgrounded, call received, etc.) — this is outside our control and must be handled regardless of the "no exit" rule above:
After submission (server-committed state): if KYC has been successfully submitted, re-authenticating (even on a different device) always routes the creator to the correct next step — C2 if channel setup is still pending, or C3 if Verified/Rejected
Before submission (client-side draft only): all text field values (username, first name, last name, national ID digits) are persisted locally as the creator types (e.g., on field blur) and restored if the app is reopened on the same device
Different device, pre-submission: no draft carries over; the form starts blank — acceptable, since nothing has been submitted yet
Resumption is step-level, not field-position-level — the creator returns to the top of whichever screen (C1 or C2) they were on, with text fields pre-filled; no attempt is made to restore exact scroll position or cursor location
No special "welcome back" screen or messaging — resumption happens silently, as if the creator had simply navigated away and returned
National ID card image — never persisted, under any circumstance:
The ID card image field always starts empty and requires a fresh selection, in every scenario without exception: first submission, a resumed draft after interruption, or a Rejected resubmission via C3
This is a deliberate policy, not just a technical limitation: since the image itself is a common source of rejection, silently carrying forward a previously selected (possibly flawed) file risks a creator unknowingly resubmitting the same bad image. Requiring a fresh, conscious selection every time closes that gap entirely
This also removes the need for any fragile "best-effort" file-handle restoration logic across app kills
Rejected resubmission via C3, specifically:
On a fresh (non-interrupted) visit, text identity fields (first name, last name, national ID) pre-fill with the creator's previously submitted values — they edit only what needs correcting
Username is not editable at this stage — it was permanently reserved at first submission (Section 3.1)
The ID card image field is empty and requires fresh selection (see above)
Once resubmitted, the flow is functionally identical to the original C1 submission: status flips to Pending, a new entry appears in the Admin Panel review queue, and all identity fields lock again immediately
9. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Numeric fields (OTP, national ID, phone) use font-feature-settings: "tnum" per design system
Primary CTA buttons use button-primary-pill style (#533afd, pill radius)
Error messages render in {colors.ruby} (#ea2261)
Verified badge/state uses {colors.primary} (#533afd) with a checkmark icon
Pending badge/state uses {colors.ink-mute} (#64748d) with a clock/hourglass icon
Rejected badge/state uses {colors.ruby} (#ea2261) with a warning icon
Toast on the تکمیل پروفایل screen uses the standard snackbar component style, auto-dismissing after a few seconds
Minimum touch target for all interactive elements: 44×44px
All screens in this story are mobile-first
Design note for Figma handoff: the existing locked-field captions in the C3 mockups currently read این اطلاعات پس از تأیید هویت قابل تغییر نیست ("cannot be changed after verification"). Per the rule above, fields actually lock at submission, not verification, and reopen only on rejection. Recommend updating the caption to: این اطلاعات پس از ثبت اولیه قابل تغییر نیست، مگر در صورت رد درخواست.
---
## C2 — Creator Profile Setup
C2 — Creator Profile Setup
Story:
As a creator, I want to set up my channel's public profile — bio, avatar, social links, and market specializations — as part of onboarding, so that investors can evaluate my expertise before subscribing.
Acceptance Criteria:
1. Screen Context & Onboarding Flow
Happy Path:
This screen (تکمیل پروفایل) is reached directly and automatically immediately after KYC submission in C1 Section 3.6 — there is no separate navigation step
This is a one-time, first-run screen only. Once submitted, the creator will never see this exact screen again — all future edits to this same data (bio, avatar, links, specializations) happen exclusively through C3 (اطلاعات کاربری)
On load, a toast is shown (triggered by the KYC submission in C1, not owned by this screen): اطلاعات شما دریافت شد. پس از تأیید، حساب شما فعال می‌شود.
All fields are presented as a single continuous scrolling form — not paginated, not a multi-step wizard
The creator's account status is Pending Verification throughout this screen — admin has not yet reviewed their KYC submission
This screen is part of the mandatory onboarding sequence established in C1 Section 8: there is no back button, no in-app exit, and no way to skip or defer this screen
Edge Cases:
If the app is interrupted (backgrounded, killed, call received) while filling this screen, resumption is governed entirely by C1 Section 8 — text field values restore on the same device; a different device starts the screen blank; no special "welcome back" messaging is shown
If the network fails on final submission, an error banner appears and all entered data is preserved — the creator can retry (see Section 6)
Farsi copy:
Screen heading: تکمیل پروفایل
Toast on load (inherited from C1 Section 3.6): اطلاعات شما دریافت شد. پس از تأیید، حساب شما فعال می‌شود.
2. Bio
Happy Path:
Creator enters a free-text bio of up to 300 characters
Persian, English, or mixed text accepted
Bio is displayed on the creator's public profile page below their username
A live character counter is shown as the creator types
Edge Cases:
Bio is optional — creator can submit the form without a bio
Line breaks are allowed (max 3 line breaks to prevent abuse)
URLs typed into the bio are displayed as plain text — not hyperlinked in Phase 0
Error States:
If the character count exceeds 300, the input stops accepting new characters, the counter turns red, and an inline message appears
Farsi copy:
Field label: بیو
Field hint: خود و حوزه تخصصی‌تان را معرفی کنید.
Placeholder: تحلیلگر بازار کریپتو و طلا با ۵ سال سابقه...
Character counter: {n}/۳۰۰
Max length indicator: به حداکثر تعداد کاراکتر رسیدید.
3. Avatar
Happy Path:
Creator uploads a square profile image
Accepted formats: JPG, PNG; maximum size: 5 MB
After upload, a circular crop preview is shown before the form is submitted
Avatar is displayed on the profile page, channel header, post cards, feed, and search results
Edge Cases:
Avatar is optional — if no avatar is uploaded, a default placeholder is shown (initials of the username on a {colors.primary} background)
Non-square images are accepted but the system applies a centered circular crop — a preview is shown so the creator can re-upload if unhappy
Creator can remove an uploaded avatar and revert to the default placeholder at any time
Error States:
Wrong format: inline error shown, upload rejected
File too large: inline error shown, upload rejected
Upload fails due to network error: inline error shown with a retry option
Farsi copy:
Field label: تصویر پروفایل
Field hint: تصویر مربعی با کیفیت بالا توصیه می‌شود.
Upload CTA: انتخاب تصویر
Remove CTA: حذف تصویر
Wrong format error: فقط فایل‌های JPG و PNG مجاز هستند.
Too large error: حجم فایل نباید بیشتر از ۵ مگابایت باشد.
Network error: آپلود ناموفق بود. دوباره تلاش کنید.
4. Social & Web Links
Happy Path:
Creator adds links using a dynamic list — each entry has two fields:
Label — free text, max 30 characters (e.g., کانال تلگرام, لینک‌تری, وب‌سایت شخصی)
URL — the full link
Four quick-add shortcut buttons are shown at the top of this section for the most common platforms: Telegram, Instagram, X, YouTube — tapping one adds a new entry with the label pre-filled, cursor lands on the URL field
For any other platform or link type (Linktree, personal website, etc.), creator taps "افزودن لینک" and fills both fields manually
Links are displayed on the public profile page in the order the creator added them
Creator can reorder links via drag-and-drop
Links go live on the public profile immediately upon saving — no moderation step
If no protocol is entered (i.e., the URL does not start with http:// or https://), the system automatically prepends https:// before saving and displaying the link
Constraints:
Maximum 8 links total
URL must contain at least a domain and a top-level domain (e.g., t.me/ali, linktr.ee/ali) — plain text with no dot is rejected
Label is mandatory for each entry — a link cannot be saved without a label
URL is mandatory for each entry — a label cannot be saved without a URL
T&C Agreement:
A one-time T&C checkbox is shown at the bottom of this form (Section 6) — since this is the creator's first-ever encounter with this data, the checkbox is always shown here, unconditionally
The checkbox must be ticked before the form can be submitted
The T&C text explicitly states that the creator is solely responsible for any links they add — including compliance with Iranian law and platform content policy
Edge Cases:
All link fields are optional — creator can submit the form with no links added
Quick-add shortcuts can be used multiple times (e.g., a creator could add two Telegram links)
If a creator deletes all entries, the section shows an empty state with the shortcut buttons and the add button visible
Creator can delete any individual link entry at any time via a remove icon on that entry
If the creator enters a URL without a protocol (e.g., t.me/ali_trader), https:// is silently prepended on save — no notification needed
Error States:
If a URL field contains plain text with no dot (e.g., alitrader), an inline error appears beneath that entry on submission
If a label is filled but URL is empty (or vice versa), an inline error appears on that entry on submission
Once 8 links are added, the add button is frozen/disabled — it remains visible but non-interactive, with a message shown beneath it
If the network fails on save, the error banner from Section 6 applies — no link data is lost
Farsi copy:
Section label: لینک‌ها
Section hint: لینک کانال‌ها، صفحات یا وب‌سایت خود را اضافه کنید.
Quick-add buttons: تلگرام · اینستاگرام · ایکس · یوتیوب
Label field placeholder: نام لینک (مثال: کانال تلگرام)
URL field placeholder: آدرس لینک (مثال: t.me/alitrader)
Add link CTA: + افزودن لینک
Remove link icon tooltip: حذف لینک
Max links reached (shown beneath frozen button): امکان افزودن بیش از ۸ لینک وجود ندارد!
Invalid URL error: آدرس وارد‌شده معتبر نیست.
Missing label error: وارد کردن نام برای این لینک الزامی است.
Missing URL error: وارد کردن آدرس لینک الزامی است.
T&C checkbox label: مسئولیت تمامی لینک‌های افزوده‌شده، از جمله انطباق آن‌ها با قوانین جمهوری اسلامی ایران و قوانین پلتفرم، به‌عهده من است.
T&C not checked error: برای ادامه، باید شرایط فوق را بپذیرید.
5. Market Specializations
Happy Path:
Creator selects one or more market specialization tags from a predefined list
Available tags in Phase 0:
Tag (Farsi) Tag (English key)
کریپتو crypto
طلا و سکه gold
بورس equities
فارکس forex
صندوق‌های سرمایه‌گذاری funds
مسکن real_estate
خودرو automotive
تتر (دلار و ارز) USDT
Selected tags are displayed as pill-tag-soft chips on the public profile
At least 1 tag must be selected — this is the only mandatory field in this form
Creator can select all tags if applicable (e.g., an institute covering all markets)
Edge Cases:
There is no maximum tag selection limit — creator can select all available tags
Tags are displayed in the same order as selected by the creator
Tags are stored and used internally in Phase 1+ for discovery and filtering — not exposed in Phase 0 discovery UI but must be stored correctly from day one
Error States:
If no tag is selected and the creator attempts to submit, an inline error appears beneath the section
Farsi copy:
Section label: تخصص بازارها
Section hint: بازارهایی که در آن‌ها تحلیل ارائه می‌دهید را انتخاب کنید.
Empty selection error: انتخاب حداقل یک تخصص الزامی است.
6. Form Submission & Transition to Channel
Happy Path:
At least 1 market specialization tag is selected and the T&C checkbox is ticked — these are the only two hard requirements to submit
Creator taps the submit CTA
On successful submission:
A success confirmation is shown: heading پروفایل ذخیره شد with a primary CTA رفتن به کانال
Tapping رفتن به کانال navigates the creator to the کانال tab
Since the creator is still Pending Verification at this moment (admin has not yet reviewed their KYC), the persistent verification banner (fully specified in C4) is visible on the کانال tab — this screen does not duplicate that messaging
This is the only forward path out of this screen — there is no discard, skip, or "complete later" option
Edge Cases:
Bio, avatar, and links remain optional as content — the creator can submit with all three left empty — but the screen itself cannot be abandoned without submitting
If the creator is already Verified by the time they reach this point (extremely unlikely given admin review timing, but technically possible), the same success flow applies — no special-casing needed
Error States:
If the mandatory market specialization field is empty on submission, it is highlighted with an inline error
If the T&C checkbox is not ticked, an inline error appears beneath it
If the network fails on submission, an error banner appears at the top of the form and all entered data is preserved — not lost, and no partial submission occurs
Farsi copy:
Submit CTA: ذخیره و تکمیل
Success screen heading: پروفایل ذخیره شد
Success screen CTA: رفتن به کانال
Network error banner: خطا در ذخیره‌سازی. اتصال اینترنت خود را بررسی کنید.
7. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
No back arrow or close icon is shown in the top bar on this screen — since no legitimate exit exists, a visible-but-non-functional control would be confusing. The Android hardware back gesture is intercepted and suppressed for the same reason
Market specialization tags use pill-tag-soft style ({colors.primary-bg-subdued-hover} background, {colors.primary-deep} text) when unselected
Selected tags use {colors.primary} fill with white text
Primary CTA uses button-primary-pill style (#533afd, pill radius)
Error messages render in {colors.ruby} (#ea2261)
Character counter for bio uses {colors.ink-mute} and switches to {colors.ruby} when limit is reached
Avatar upload area is a circular dashed-border zone — tappable on mobile
Platform quick-add shortcut buttons use button-secondary style with their respective platform icon
Frozen add link button renders at reduced opacity (0.4) with cursor: not-allowed
Success screen (Section 6) uses a calm, celebratory layout — checkmark or similar affirming visual, generous whitespace, consistent with card-feature-light styling
Minimum touch target for all interactive elements: 44×44px
Form is mobile-first; on desktop, fields are in a single column with a max-width of 560px
---
## C3 — Creator Profile Edit
C3 — Creator Profile Edit (اطلاعات کاربری)
Story:
As a creator, I want to edit my profile information and, if rejected, resubmit my identity verification, so that my profile stays current and I can correct issues that blocked my approval.
Acceptance Criteria:
1. Access & Entry Point
Happy Path:
Accessed by tapping the avatar icon from the top bar — available on both داشبورد and کانال tabs, for any creator regardless of verification state
The screen's top-bar title is اطلاعات کاربری — this is the screen-level label, distinct from the section-level heading introduced in Section 5 below
The screen renders as a single continuous scroll, structured in two independently functioning blocks: اطلاعات هویتی (identity — top) and اطلاعات پروفایل (profile info — below it)
Landing scroll position on entry depends on verification state, per C1 Section 7: Rejected creators land at the top of اطلاعات هویتی; Verified/Pending creators land at the top of the screen normally (no forced scroll)
Edge Cases:
Unlike C2, this screen is exitable — a standard back button is shown, since this is an ongoing edit surface, not mandatory onboarding
If the creator has unsaved changes in either block and attempts to exit, a confirmation dialog appears (Section 8)
2. Verification Status Badge
Happy Path:
Displayed directly beneath the creator's name and username, at the top of the screen
Three states:
State Label Tappable?
Verified تأییدشده ✓ No
Pending در انتظار احراز هویت No — informational only
Rejected رد شده No — the rejection reason and resubmission action are already visible inline in اطلاعات هویتی below; no separate tap action needed since the creator is already on this screen
Edge Cases:
Since C3 is itself the canonical destination referenced by کانال/داشبورد banners (per C1 Section 7), the badge here doesn't need its own navigation — it's a status display, not a link
Farsi copy:
Verified: تأییدشده ✓
Pending: در انتظار احراز هویت
Rejected: رد شده
3. اطلاعات هویتی (Identity Block) — Display by State
Verified state:
Username, first name, last name, national ID — all shown read-only, each with a lock icon and the caption: این اطلاعات پس از ثبت اولیه قابل تغییر نیست، مگر در صورت رد درخواست
No action button — nothing to do here
Pending state:
Identical read-only rendering to Verified — locked, same caption
No action button — per C1 Section 5, there is intentionally no self-service edit while Pending
Rejected state:
A rejection banner is shown at the top of this block: احراز هویت شما تأیید نشد. دلیل: {admin_reason}
First name, last name, national ID unlock and become editable — pre-filled with the creator's previously submitted values (per C1 Section 8) so they only correct what's wrong
National ID card image field is shown empty — always requires a fresh selection, never pre-filled, regardless of prior submissions (per C1 Section 8)
Username remains permanently locked and read-only, even here — it was reserved at first submission and never reopens
A dedicated CTA appears directly beneath this block: ارسال مجدد اطلاعات هویتی
A helper caption sits beneath that CTA: این عملیات فقط اطلاعات هویتی شما را برای بررسی مجدد ارسال می‌کند.
Edge Cases:
The resubmit CTA is disabled until all four identity fields (first name, last name, national ID, ID card image) are validly filled — same validation rules as C1 Sections 3.2–3.5
If the creator edits identity fields but does not tap ارسال مجدد اطلاعات هویتی, and instead only interacts with اطلاعات پروفایل below, the identity edits are not saved — they remain as unsaved local state until that specific CTA is tapped, and trigger the exit-confirmation dialog if the creator tries to leave
Error States:
Same field-level validation errors as C1 Sections 3.2–3.5 (empty fields, Latin characters, invalid national ID format, wrong image format/size)
If resubmission fails due to network error: error banner shown, all entered data preserved, creator can retry
Farsi copy:
Rejection banner: احراز هویت شما تأیید نشد. دلیل: {admin_reason}
Resubmit CTA: ارسال مجدد اطلاعات هویتی
Helper caption: این عملیات فقط اطلاعات هویتی شما را برای بررسی مجدد ارسال می‌کند.
Locked field caption (Verified/Pending): این اطلاعات پس از ثبت اولیه قابل تغییر نیست، مگر در صورت رد درخواست
Username locked caption (all states): نام کاربری پس از ثبت اولیه قابل تغییر نیست.
4. اطلاعات هویتی — Resubmission Success
Happy Path:
On successful resubmission, the creator stays on C3 — no navigation away
A success toast appears: اطلاعات شما مجدداً ارسال شد. پس از بررسی، نتیجه به شما اطلاع داده می‌شود.
The identity block immediately re-locks (read-only again) and the badge flips to در انتظار احراز هویت
This creates a new Pending entry in the Admin Panel review queue, identical in structure to the original C1 submission (per C1 Section 8)
Standard notifications apply per C1 Section 6 (in-app confirmation; later, SMS + in-app on the next admin decision)
Farsi copy:
Resubmission success toast: اطلاعات شما مجدداً ارسال شد. پس از بررسی، نتیجه به شما اطلاع داده می‌شود.
5. اطلاعات پروفایل (Profile Info Block) — Always Editable
This block is functionally identical to C2 Sections 2–5 (Bio, Avatar, Social & Web Links, Market Specializations) — same fields, same validation rules, same limits. It is fully independent of verification state: editable and savable whether the creator is Pending, Verified, or Rejected.
Key difference from C2: the T&C checkbox does not appear here. Since C2's mandatory onboarding sequence already requires T&C agreement before a creator can ever reach C3 for the first time, re-showing it on every edit would be redundant. The creator's original agreement, given once in C2, covers all future edits made through this screen.
Happy Path:
Existing values (bio, avatar, links, specialization tags) are pre-populated from what was saved in C2 or any prior C3 edit
Creator edits any combination of fields and taps the dedicated CTA: ذخیره اطلاعات پروفایل
On success: toast confirmation, values update immediately, and — if the creator is Verified — the public profile reflects changes instantly
Edge Cases:
If the creator is Pending or Rejected, changes save normally but remain not publicly visible until the account reaches Verified status
All field-level rules (bio 300-char limit, avatar format/size, max 8 links, market specialization minimum 1 tag) carry over unchanged from C2
Error States:
Same as C2 Sections 2, 3, 4, 5 respectively (bio overflow, avatar format/size errors, link validation errors, empty specialization error)
Network failure on save: error banner, entered data preserved, retry available
Farsi copy:
Section header: اطلاعات پروفایل
Section CTA: ذخیره اطلاعات پروفایل
Success toast: اطلاعات پروفایل با موفقیت ذخیره شد.
All field-level copy: identical to C2 Sections 2–5 (bio, avatar, links, specializations)
6. Two Independent Save Actions — Rationale & Behavior
اطلاعات هویتی and اطلاعات پروفایل are deliberately decoupled, each with its own CTA, its own validation, and its own success/error handling
The top-bar **ذخیره** button present in the original design is removed entirely — it created ambiguity about scope once the screen had two genuinely independent save actions; removing it avoids that ambiguity rather than trying to define what a combined "save everything" would even mean
A creator can save either block without needing to touch or complete the other
This decoupling is reinforced by distinct CTA language (ارسال مجدد اطلاعات هویتی vs. ذخیره اطلاعات پروفایل) specifically to prevent a Rejected creator from mistakenly believing an edit to their identity fields was saved by tapping the profile-info button, or vice versa
7. Field Editability Summary
Field Verified Pending Rejected
Username Locked Locked Locked
First name Locked Locked Editable (pre-filled)
Last name Locked Locked Editable (pre-filled)
National ID Locked Locked Editable (pre-filled)
National ID card image Locked (n/a — no re-upload) Locked (n/a) Editable (always empty)
Bio Editable Editable Editable
Avatar Editable Editable Editable
Social & web links Editable Editable Editable
Market specializations Editable Editable Editable
8. Exit & Unsaved Changes
Happy Path:
If the creator has no unsaved changes in either block and taps back, they exit immediately — no dialog
If the creator has unsaved changes in either block (identity edits not yet resubmitted, or profile info edits not yet saved), a confirmation dialog appears on exit attempt
Edge Cases:
The dialog checks both blocks independently — if only one block has unsaved changes, the dialog still appears, since any unsaved data would be lost
Dialog options: save-and-exit (triggers whichever block(s) have pending changes) or discard-and-exit
Farsi copy:
Exit confirmation dialog: تغییرات ذخیره‌نشده دارید. آیا می‌خواهید خارج شوید؟
Save-and-exit CTA: ذخیره و خروج
Discard-and-exit CTA: خروج بدون ذخیره
9. UI / UX
Layout is RTL throughout; Yekan Bakh is the typeface for all Farsi text, per the Stripi-inspired design system
Screen top-bar title: اطلاعات کاربری — do not confuse with the اطلاعات پروفایل section header within the page; the two operate at different scopes (screen-level vs. section-level)
Locked fields use {colors.ink-mute} (#64748d) text with a lock icon, background tinted {colors.canvas-soft} to visually read as non-interactive
Verification badge colors: Verified — {colors.primary} (#533afd) with checkmark; Pending — {colors.ink-mute} (#64748d) with clock icon; Rejected — {colors.ruby} (#ea2261) with warning icon
Rejection banner uses {colors.ruby} (#ea2261) background tint, positioned directly above the now-unlocked identity fields to draw immediate attention
Resubmit CTA (ارسال مجدد اطلاعات هویتی) uses button-primary-pill style (#533afd, pill radius) — visually distinct from the profile-info save CTA through label alone, not color, to avoid implying one action is "more correct" than the other
Profile info save CTA (ذخیره اطلاعات پروفایل) also uses button-primary-pill style, positioned at the bottom of that block, separated from the identity block by a clear divider/section break
Helper caption beneath the resubmit CTA uses {colors.ink-mute} (#64748d), smaller type size, non-bold
Minimum touch target for all interactive elements: 44×44px
Screen is mobile-first; on desktop, content is centered in a single column with max-width of 640px

Some files were not shown because too many files have changed in this diff Show More