Since 815dcc3 the api service only joined the stack-private `internal`
network, so it could no longer resolve the database host on
`dokploy-network` and `prisma migrate deploy` failed with P1001.
api joins `dokploy-network` again, only to reach the database. nginx
still proxies to the `superlist-api` alias, which is declared only on
`internal`, so the shared network never routes our traffic elsewhere.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
287 lines
20 KiB
Markdown
287 lines
20 KiB
Markdown
# AGENTS.md
|
|
|
|
## Status
|
|
|
|
Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web` and `packages/shared`,
|
|
Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed with Docker Compose on
|
|
Dokploy (`docker-compose.yml`); there is no hosted CI.
|
|
|
|
Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist;
|
|
there is no Google login and no email verification). The `health` module is the reference example.
|
|
|
|
## Stack (source of truth: `STACK.md`)
|
|
|
|
- Monorepo orchestrated with **Turborepo** (see the managed block at the end of this file)
|
|
- Backend: **Bun** + **Hono**, **Prisma 7** against **Postgres** (via `@prisma/adapter-pg`), **Zod** for
|
|
validation, **Pino** for logging, **BetterAuth** for auth
|
|
- Frontend: **React + Vite + TypeScript**, **Tailwind v4**, UI components from **shadcn/ui**
|
|
- Frontend routing: **TanStack Router** (file-based) · server state: **TanStack Query** ·
|
|
forms: **React Hook Form + Zod**
|
|
- Tooling: Bun workspaces, **Biome** (lint + format + import sorting), **TypeScript 6**
|
|
|
|
## Repository layout
|
|
|
|
```
|
|
apps/api/ Bun + Hono API (owns the Prisma schema and migrations)
|
|
prisma/ schema.prisma and (once created) migrations/
|
|
src/app.ts createApp(): middleware chain, BetterAuth mount, module mounting
|
|
src/index.ts Bun entrypoint: exports { port, fetch }
|
|
src/lib/ logger, prisma, auth, problem-details, validate, result-json
|
|
src/modules/ modules/<name>/<feature>/{route.ts,use-case.ts} (+ schema.ts, *.test.ts)
|
|
src/types.ts AppEnv: c.get('logger') / c.get('requestId')
|
|
apps/web/ React + Vite frontend
|
|
src/routes/ file-based routes; routeTree.gen.ts is generated
|
|
src/components/ ui/ (shadcn, vendored source) + layout/ (app shell)
|
|
src/hooks/ TanStack Query hooks (e.g. use-health.ts)
|
|
src/lib/ api-client, auth-client, query-client, utils
|
|
packages/shared/ @superlist/shared: Result pattern + Problem Details helpers/types
|
|
```
|
|
|
|
## Commands
|
|
|
|
Run from the repo root. Verification order is `build`, then `lint` → `typecheck` → `test`.
|
|
|
|
| Command | Effect |
|
|
| --------------------- | ----------------------------------------------------------------------------- |
|
|
| `bun run dev` | API on `:4100`, web on `:7153` (`bun run dev --filter=@superlist/web` for one) |
|
|
| `bun run build` | `turbo run build` (API bundle + web production build) |
|
|
| `bun run lint` | `biome check .` per package via turbo — fails on lint, format or import order |
|
|
| `bun run lint:fix` | `biome check --write .` across the repo (lint fixes, formatting, imports) |
|
|
| `bun run lint:ci` | `biome ci .` — whole repo, works without a git index |
|
|
| `bun run format` | `biome format --write .` (`format:check` to verify only) |
|
|
| `bun run typecheck` | `tsc` per package (`apps/web` regenerates the route tree first) |
|
|
| `bun run test` | `bun test` in the API, `vitest` in web and shared |
|
|
| `bun run db:generate` | `prisma generate` (also needed after a fresh clone, before typechecking the API) |
|
|
| `bun run db:migrate` | `prisma migrate dev` — needs a reachable Postgres |
|
|
| `bun run db:studio` | Prisma Studio (long-running) |
|
|
|
|
## Conventions
|
|
|
|
- **Package manager: Bun** — `bun install`, `bun run <script>`. Do not introduce npm/pnpm/yarn lockfiles.
|
|
- The committed lockfile is the text one (`bun.lock`), enabled by the repo-level `bunfig.toml`
|
|
(`saveTextLockfile = true`). Turborepo reads it to resolve the workspace graph, so keep it in sync and never
|
|
hand-edit it.
|
|
- Bun is configured with `minimumReleaseAge` (see `~/.bunfig.toml`), so brand new releases are rejected during
|
|
install. If a dependency fails to resolve, pin the newest version that is at least a few days old instead of
|
|
reaching for the very latest.
|
|
- **Biome is the only JS/TS tooling: linting, formatting and import sorting.** One `biome.json` at the repo
|
|
root applies to every workspace, and each package's `lint` script is `biome check .`.
|
|
- `apps/web/src/components/ui/**` is exempt from the recommended lint preset through an `overrides` entry and
|
|
`noArrayIndexKey` / `useExhaustiveDependencies` are off there: those files are vendored shadcn/ui source
|
|
regenerated by the CLI. They are still formatted.
|
|
- Markdown (`README.md`, `AGENTS.md`) is not covered: Biome does not format prose.
|
|
- **Environment variables and Turborepo Strict Mode.** Turbo only passes the variables a task declares, so
|
|
every task that needs one lists it in `turbo.json`: `db:*` use `env: ["DATABASE_URL"]`, `test` declares the
|
|
API variables, `dev` uses `passThroughEnv` (they must reach the process but don't change its output).
|
|
`VITE_*` is covered by Vite framework inference. **When you introduce a new variable, add it to `turbo.json`**
|
|
or the task will fail (or worse, hit a stale cache).
|
|
- Env files: `cp apps/api/.env.example apps/api/.env` and `cp apps/web/.env.example apps/web/.env` (both
|
|
gitignored, and `.env.example` at the root documents every variable). Bun loads `.env` automatically; the
|
|
Prisma CLI does not, which is why `prisma.config.ts` imports `dotenv/config`.
|
|
- Dev ports: API `4100`, web `7153`. They live in the `.env.example` files and `apps/web/vite.config.ts`
|
|
— change them together.
|
|
- **TypeScript 6 specifics:** `baseUrl` no longer exists (aliases are declared with `paths` only), and
|
|
`apps/web/tsconfig.app.json` enables `erasableSyntaxOnly` — no enums, namespaces or constructor parameter
|
|
properties in the web app. Both apps use `@/*` → `src/*` and `verbatimModuleSyntax` (use `import type`).
|
|
- **Database naming (Prisma):** tables are **plural snake_case** (`shopping_lists`, `users`),
|
|
columns are **snake_case** (`owner_id`, `created_at`) and enum types are **snake_case** (`list_role`) — all
|
|
declared with `@@map` / `@map` in `schema.prisma`. The Prisma *model* and *field* names stay
|
|
PascalCase/camelCase, because BetterAuth and the generated client address models by those names, so a column
|
|
rename never changes the TypeScript API. Default constraint/index names follow the mapped names, so do not
|
|
set `map:` unless you have a reason to.
|
|
- **Deployment: Docker Compose on Dokploy** (`docker-compose.yml` at the repo root). Two services, `api` and
|
|
`web`; the database is external (Dokploy's). Both join the external `dokploy-network` — `web` for Traefik,
|
|
`api` to reach the database (without it `prisma migrate deploy` fails with P1001). nginx reaches the API
|
|
over the stack-private `internal` network, where it has the alias `superlist-api`, declared only there
|
|
(never rely on a generic service name on the shared network: other projects can answer to it). The
|
|
`api` image (`apps/api/Dockerfile`) builds the Bun bundle and runs `prisma migrate deploy` before
|
|
`bun run start`; the `web` image (`apps/web/Dockerfile`) builds with Vite and serves `dist/` with
|
|
`apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through
|
|
Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated
|
|
by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them
|
|
in Dokploy. There is no hosted CI.
|
|
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
|
`apps/api/src/generated/`.
|
|
- Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`,
|
|
module-level `use-case.test.ts`); web and shared use Vitest.
|
|
|
|
## Backend architecture (Hono)
|
|
|
|
Endpoints are grouped into **modules**, and each module into **features**. Example: an `alerts` module with
|
|
features `list`, `create`, `update`, `delete`:
|
|
|
|
```
|
|
apps/api/src/modules/alerts/
|
|
index.ts # exports alertsModule: mounts every feature route
|
|
list/
|
|
route.ts # Hono route declaration + Zod validation + call to the use case
|
|
use-case.ts # class with a single execute() method
|
|
schema.ts # Zod schemas for this feature (when it has input)
|
|
create/
|
|
route.ts
|
|
use-case.ts
|
|
```
|
|
|
|
- `route.ts` holds **only** the Hono route declaration, input validation (Zod), and the call to the use case's
|
|
`execute`. No business logic, no DB access.
|
|
- Business logic lives in a **use case class with a single `execute` method** (one class per feature), named
|
|
after the action: `ListAlerts`, `CreateAlert`, `GetStatus`. Dependencies (e.g. the shared Prisma client) are
|
|
injected through the constructor and instantiated in the route.
|
|
- Use cases return the **Result** pattern (`Ok` / `Failure` / `Result` from `@superlist/shared`). Never throw
|
|
for expected outcomes; reserve exceptions for truly unexpected failures.
|
|
- Failures are Problem Details payloads built with the `problems` factories from `@superlist/shared`:
|
|
`problems.badRequest`, `problems.unauthorized`, `problems.forbidden`, `problems.notFound`,
|
|
`problems.conflict`, `problems.validation(errors)`, `problems.internal`, `problems.unavailable`.
|
|
- **Routes never check `result.ok` by hand**: every route ends with `resultJson(c, result)`, which serializes
|
|
`Ok` as JSON (200 by default, override with `{ status: 201 }`, `204` sends an empty body) and maps `Failure`
|
|
to the matching RFC 9457 `application/problem+json` response.
|
|
- Wire the module in `createApp()` (`apps/api/src/app.ts`): `app.route('/api/alerts', alertsModule)`.
|
|
**Every API route is mounted under `/api`** (BetterAuth already owns `/api/auth/*`) because nginx proxies
|
|
`/api/*` to the API while serving the SPA at the root — an unprefixed path such as `/lists` would be
|
|
swallowed by the frontend router.
|
|
|
|
```ts
|
|
// apps/api/src/modules/alerts/list/route.ts
|
|
import { resultJson } from '@/lib/result-json'
|
|
import { validate } from '@/lib/validate'
|
|
import type { AppEnv } from '@/types'
|
|
|
|
import { ListAlerts } from './use-case'
|
|
import { AlertQuerySchema } from './schema'
|
|
|
|
export const listAlertsRoute = new Hono<AppEnv>().get(
|
|
'/',
|
|
validate.query(AlertQuerySchema),
|
|
async (c) => {
|
|
const query = c.req.valid('query') // typed straight from the schema, no cast
|
|
const result = await new ListAlerts(prisma).execute(query)
|
|
|
|
return resultJson(c, result)
|
|
},
|
|
)
|
|
```
|
|
|
|
```ts
|
|
// apps/api/src/modules/alerts/create/use-case.ts
|
|
import { Failure, Ok, problems, type ProblemDetails, type Result } from '@superlist/shared'
|
|
|
|
import type { Database } from '@/lib/prisma'
|
|
|
|
export class CreateAlert {
|
|
constructor(private readonly db: Database) {}
|
|
|
|
async execute(input: CreateAlertInput): Promise<Result<Alert, ProblemDetails>> {
|
|
const existing = await this.db.alert.findUnique({ where: { slug: input.slug } })
|
|
|
|
if (existing) return Failure(problems.conflict('An alert with that slug already exists.'))
|
|
|
|
const alert = await this.db.alert.create({ data: input })
|
|
|
|
return Ok(alert)
|
|
}
|
|
}
|
|
```
|
|
|
|
- Validation always goes through `validate.*` (`validate.json`, `validate.query`, `validate.param`,
|
|
`validate.header`, `validate.cookie`, `validate.form`). It answers invalid input with a 422 Problem Details
|
|
payload containing per-field `errors` (built from the Zod issues; nested paths are dotted, root issues land
|
|
under `_root`).
|
|
- **All responses follow RFC 9457 (Problem Details)** — errors use the `application/problem+json` media type
|
|
with `type`, `title`, `status`, `detail`, plus the optional `errors` extension. The schema and the `problem` /
|
|
`problems` builders live in `packages/shared/src/problem-details.ts`; the HTTP helpers
|
|
(`problemResponse`, `notFoundHandler`, `errorHandler`) in `apps/api/src/lib/problem-details.ts`.
|
|
- Zod is the only validation library, and Zod 4 is what is installed. Define schemas next to the feature that
|
|
uses them (`schema.ts`); share them through `@superlist/shared` only when more than one module needs them.
|
|
- **Logging: Pino** — one shared logger in `apps/api/src/lib/logger.ts`, reachable from handlers as
|
|
`c.get('logger')` (already enriched with the request id); never `console.log` in the backend. Level comes from
|
|
`LOG_LEVEL`, defaulting to `debug` (pretty) outside production and `info` (JSON) in production.
|
|
- Unexpected throws are turned into Problem Details by `app.onError`; unmatched routes by `app.notFound`
|
|
(both in `apps/api/src/lib/problem-details.ts`).
|
|
- `createApp()` middleware order matters: `secureHeaders` → `cors` (origins from `CORS_ORIGIN`, credentials on)
|
|
→ `requestId` → request logger → BetterAuth → modules.
|
|
- **Auth**: BetterAuth is configured in `apps/api/src/lib/auth.ts` (Prisma adapter, `baseURL` from
|
|
`BETTER_AUTH_URL`, `secret` from `BETTER_AUTH_SECRET`, `trustedOrigins` from `CORS_ORIGIN`,
|
|
email+password enabled) and owns every route under `/api/auth/*`.
|
|
- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so
|
|
import it as `@/generated/prisma/client` — never `@prisma/client` directly. The client uses the
|
|
`@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from
|
|
`apps/api/src/lib/prisma.ts`; pass it into use cases instead of creating clients per request.
|
|
- After changing `prisma/schema.prisma`, run `bun run db:migrate` (from `apps/api`, or at the root) and commit
|
|
the generated migration under `apps/api/prisma/migrations` — never edit migration files by hand. The
|
|
datasource has no `url` in the schema: it comes from `prisma.config.ts` (`env('DATABASE_URL')`). For
|
|
production, `apps/api` also has `db:deploy` (`prisma migrate deploy`), which is not wired to a turbo task yet.
|
|
- The BetterAuth models (`User`, `Session`, `Account`, `Verification`) are already in the schema and follow the
|
|
naming convention above (`users`, `sessions`, `accounts`, `verifications` with snake_case columns); regenerate
|
|
them with the BetterAuth CLI rather than by hand if the auth config changes, then re-apply the mapping.
|
|
|
|
## Shared package (`@superlist/shared`)
|
|
|
|
- Source-only internal package (`bun` resolves the TypeScript through the `exports` map; there is no build step).
|
|
Two entrypoints: `@superlist/shared` (everything) and `@superlist/shared/problem-details`.
|
|
- Contents: `result.ts` (`Ok`, `Failure`, `Ok<T>`, `Failure<E>`, `Result<T, E>`) and `problem-details.ts`
|
|
(Zod schema, `ProblemDetails` type, `PROBLEM_CONTENT_TYPE`, `problemTypes`, `FieldErrors`, `problem()`,
|
|
`problems.*`).
|
|
- Add code here only when more than one workspace needs it; feature-specific schemas stay next to the feature.
|
|
It is dependency-light on purpose (`zod` only) because both the API and the browser bundle it.
|
|
- Tests use Vitest (`src/*.test.ts`), so new test files here follow that runner, not `bun test`.
|
|
|
|
## Frontend architecture (React + Vite)
|
|
|
|
```
|
|
apps/web/src/
|
|
routes/ # file-based TanStack Router routes; routeTree.gen.ts is generated
|
|
components/ui/ # shadcn/ui components (checked in, editable source)
|
|
components/layout # app shell: sidebar, header, user menu
|
|
hooks/ # query hooks (e.g. use-health.ts)
|
|
lib/ # api-client, auth-client, query-client, utils
|
|
```
|
|
|
|
- **Routing: TanStack Router with file-based routes.** Add a file under `src/routes` and the route tree is
|
|
regenerated (`bun run routes:generate`, also run by `dev`, `build` and `typecheck`; the Vite plugin watches
|
|
the directory in dev). Never edit `routeTree.gen.ts`; `tsr.config.json` holds the generator config.
|
|
- `(auth)/sign-in.tsx` — public routes.
|
|
- `_authenticated/route.tsx` — pathless layout for signed-in pages; it guards on the BetterAuth session
|
|
(`authClient.useSession()`) and redirects to `/sign-in` when there is none. Add authenticated pages inside
|
|
`_authenticated/`.
|
|
- **Providers**: `src/main.tsx` creates the router with `createQueryClient()` in its context (so loaders can
|
|
prefetch), renders `QueryClientProvider` + `RouterProvider`, and registers the router type. `__root.tsx`
|
|
wraps everything in `ThemeProvider` + `TooltipProvider`, mounts the Sonner `Toaster` and lazy-loads the router
|
|
and query devtools in development only.
|
|
- **Theme**: hand-rolled in `src/components/theme-provider.tsx` — `useTheme()` exposes `theme`, `resolvedTheme`
|
|
and `setTheme`, and the provider toggles the `.dark` class and `color-scheme` on `<html>`. The pre-paint script
|
|
in `apps/web/index.html` applies the stored theme before React mounts; both share the `superlist-theme`
|
|
storage key, so keep them in sync. Do not swap this for `next-themes`: it renders a `<script>` from React, and
|
|
React 19 never executes (and warns about) scripts rendered on the client.
|
|
- **Server state: TanStack Query only.** Never call `fetch` from a component; add a hook under `src/hooks` that
|
|
exports `queryOptions` (`<entity>QueryOptions()`) plus a `use<Entity>()` wrapper, and use `apiFetch` from
|
|
`src/lib/api-client.ts` as the `queryFn`. Exporting the options lets route loaders prefetch with
|
|
`context.queryClient.ensureQueryData(...)` (`use-health.ts` is the reference).
|
|
- `apiFetch` returns parsed JSON, sends `credentials: 'include'` (BetterAuth sessions are cookies) and throws
|
|
`ApiError` carrying the parsed `ProblemDetails` for non-2xx responses; `204` resolves to `undefined`. Error
|
|
UIs read `error.problem.detail`.
|
|
- **Same-origin `/api` in every environment.** `apiBaseUrl` is `` `${VITE_API_URL || ''}/api` `` and the SSE
|
|
hook (`use-list-events.ts`) reuses it, so the browser calls `/api/*` on the current origin: Vite proxies it
|
|
to `:4100` in dev and nginx does in production. `VITE_API_URL` is an optional override for a separate API
|
|
origin, and `auth-client.ts` defaults `baseURL` to `window.location.origin` (BetterAuth appends `/api/auth`).
|
|
- **Forms: React Hook Form + Zod** (`zodResolver`). Render errors with the shadcn `Field`/`FieldError`
|
|
components — this registry version ships `field` instead of the older `form` component.
|
|
- **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them
|
|
directly (then re-run `bun run lint:fix` so Biome's formatting sticks). Add new ones with
|
|
`cd apps/web && ../../node_modules/.bin/shadcn add <component>` (this registry needs the `@shadcn/` prefix for
|
|
some items, e.g. `@shadcn/field`).
|
|
- `cn` comes from the `cn` package; `src/lib/utils.ts` re-exports it for local imports.
|
|
- Prefer small feature components over one large route file; route files export the `Route` object, which Biome
|
|
does not flag.
|
|
- Tests use Vitest (`vitest run --passWithNoTests`), currently `src/lib/api-client.test.ts`.
|
|
|
|
<!-- BEGIN:turborepo-agent-rules -->
|
|
|
|
# This is NOT the Turborepo you know
|
|
|
|
Turborepo configuration, task behavior, and CLI commands can vary between installed versions and may differ from your training data. Resolve the `turbo` package from this file's directory or relevant workspace; in monorepos, it may not be visible from the repository root. For example, run `node -p "require.resolve('turbo/package.json')"` from a workspace that depends on `turbo`.
|
|
|
|
Read `docs/README.md` inside that installed package first, then read the relevant pages from its `docs/` directory before changing Turborepo configuration or commands. Heed deprecation notices. These bundled docs match the installed package version and are available without network access.
|
|
|
|
This block is written and re-added by `turbo` before repository-scoped commands when an AI agent is detected. In the Turborepo source repository, its template is defined in `crates/turborepo-cli/src/cli/agent_guidance.rs`. Removing the managed block while updates are enabled means a later qualifying invocation will add it again. Set `"agentGuidance": false` in the root `turbo.json` or `turbo.jsonc` to opt out; this does not remove an existing block. Keep the block committed with your work to avoid an uncommitted change on the next agent invocation.
|
|
<!-- END:turborepo-agent-rules -->
|