wealth/.claude/skills/front-end-architect/references/project-structure.md

24 KiB

Project structure

<placeholders> are names you choose. @project stands for the workspace's npm scope. A product has one platform and one or more apps that share it: <app> names an app, <platform> the product's platform, and <product> the product.

Contents: Top level · App · Platform · Feature anatomy · Shared · island · Choosing where a component goes · libs, integrations, and tools packages · Env flow · Nx tags and boundaries · Exports and tree-shaking

Top level

apps/                 # deployable apps
platforms/            # each product's logic, one project per product, shared by its apps
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, cvx, icon-sprite-plugin, font-copy-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
│   └── 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. They hold only what this route uses; UI that knows a domain and serves several routes or apps lives in the platform's screens/.
  • 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/<platform>/. Apps never import each other.

Platform

platforms/<platform>/src/
├── app/
│   ├── app-shell/              # top-level provider shell shared by the mobile and desktop views
│   │   ├── AppShell.tsx
│   │   ├── types.ts
│   │   └── index.ts
│   ├── guards/                 # e.g. AuthGuard for pages that need a logged-in user
│   │   └── <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
│   └── screens/                # UI that knows a domain and serves several routes or apps
│       ├── organisms/          # shared by routes with no common route level
│       ├── templates/
│       └── (auth)/             # mirrors the apps' route tree
│           ├── organisms/      # shared by routes under (auth)
│           ├── templates/
│           └── auth/
│               └── login/
│                   ├── organisms/  # shared by the login route of several apps, or by routes under it
│                   └── templates/
├── features/                   # DDD, see Feature anatomy
├── stores/                     # one store per feature or domain
├── shared/                     # see Shared
├── index.ts
└── server.ts

screens/ holds organisms and templates that know a domain and that several routes, or the same route in several apps, use. They can't go to island, because island is domain-free. They can't go to an app's route level, because one route level can't serve another route or another app.

  • Its folders mirror the route tree. A component sits at the nearest route level that every route using it shares. Create a level's folder only when something lives in it.
  • organisms/ and templates/ hold component modules shaped like island organisms.
  • Its components know a domain: they call a model or an action, read a store, or take a *Payload. The logic itself stays in the feature's models and actions, so the components stay presentational.
  • It is UI: it may import features/, stores/, shared/, the rest of app/, island, and integrations. Nothing in features/, stores/, or shared/ imports it.
  • A module that reads caches is server-only, like read-on-server/: its entry is server.ts, and the platform's server.ts re-exports it.

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.
  • 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.
  • 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).

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, cvx, icon-sprite-plugin, font-copy-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
│   └── fonts.css               # @font-face rules; root paths to public/fonts/, never relative
├── 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; linked as symbol-defs.svg?v=<N>
│   └── selection.json          # Icomoon snapshot; re-import it into Icomoon to update the set
├── fonts/                      # every app's fonts, e.g. yekan-bakh-vf.woff2
├── constants.ts                # island-level constants, e.g. ICON_SPRITE_VERSION, CRITICAL_FONT_URL
├── 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)
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/icons/symbol-defs.svg.
  • font-copy-plugin is a build and dev plugin. It copies fonts/ byte for byte into each app's public/fonts/.
  • Neither plugin adds a hash or a version to a file name, and no later build step renames their files. The sprite's version lives only in its link (ui-rules.md). Their output in public/ is generated, so git ignores it.
  • 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.

Choosing where a component goes

Run these three steps for every component you add or move. Write one line per component in the plan: its path, its level, and the reason, for example packages/island/src/molecules/form-field/: molecule; a label, an input, and an error text for one field; domain-free.

1. Reuse. A component that already does the job is imported, not rebuilt. An island component that does the job but looks different gets a variant in its variants.ts, never a new component or a copy.

2. Level. Decide by what the component renders and what it imports, never by its size. First match wins.

  1. It renders no UI of its own, only structure or behavior (a portal, an error boundary, LoadOnVisible) → primitive.
  2. It wraps one native element or draws one visual unit, and uses only other atoms (Button shows the Spinner atom) → atom: Button, Input, Badge, Icon, Skeleton.
  3. It groups atoms for one job and holds no more than UI state, such as open or focused → molecule: FormField, SearchBox, EmptyState.
  4. It's a distinct section of a screen: it composes molecules, owns interaction state or a context, or is a compound component → organism: Tabs, DataTable, ProductRail.
  5. It arranges organisms into a page layout through slots and holds no data → template, such as a route's mobile or desktop template.

Then check the imports: nothing the component imports sits above its level. A component that needs a higher level belongs at that level. Move it up; never import upward.

3. Owner. A component is domain-free when it takes only plain props (strings, numbers, its own prop types, ReactNode slots, and callbacks) and imports only island, libs, and tools. It knows a domain when it takes a *Payload type, calls a model or an action, reads a store, or shows a feature's text. First match wins.

  1. Only one organism, template, or primitive uses it → that module's private components/, shaped like an atom.
  2. It's a route's mobile or desktop template → that route's templates/. When several apps render the same template for that route → screens/ at that route's path, such as screens/(auth)/auth/login/templates/.
  3. It knows a domain:
    • Navigation UI → platforms/<platform>/src/app/navigation/components/.
    • Third-party UI, such as a chat widget or its facade → the integration's components/.
    • One route in one app uses it → that route's organisms/ in the app.
    • Several routes, or the same route in several apps, use it → platforms/<platform>/src/app/screens/, in the organisms/ or templates/ of the nearest route level they share, such as screens/(shop)/organisms/. With no shared level, screens/organisms/.
  4. It's a domain-free organism that one route uses → that route's organisms/. When a second route needs it, move it to island's organisms/ at once, as refactoring.md describes; never copy it.
  5. Otherwise → island, in the folder of its level. Route levels hold only organisms/ and templates/, so every domain-free atom and molecule goes to island at once.

A piece that knows a domain but is smaller than an organism, such as a price line that formats a *Payload, is a private component of the organism that uses it. When other code needs it too, give it plain props instead and put it in island. A component that two products need also moves to island with plain props, because one product never imports another's code.

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
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
env createClientEnv; createServerEnv (server) Validating the app's env: public variables on both sides, server variables on the server only lib-env.md
cookie cookie Browser cookies for small values the server needs (locale, theme); never tokens 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

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. The values come only from the app's .env files; only apps have .env files, and no project hard-codes an env value, a fallback, or a schema default.
  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.

Nx tags and boundaries

Default tags. Reuse the repo's own tags if it already has them.

Project Tags
apps/<app> type:app, scope:<product>
platforms/<platform> type:platform, scope:<product>
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:<product> scope:<product>, 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.
  • platform app/: features/, stores/, and shared/ never import it, so screens/ stays the UI on top.

Exports and tree-shaking

Expose each module on its own subpath. With package.json exports (Nx workspaces that use TypeScript project references):

{
  "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.