- 顶层新增 bin.ts 作为编译入口,citty 懒加载 src/cli/ 下子命令 - src/cli/serve.ts 通过 _serve-nitro.mjs 桥接启动 Nitro(规避 .output/server/index.mjs 顶层 serve(...) 的副作用导入) - src/cli/migrate.ts 显式跑 drizzle migrate;env / drizzle 都在 run() 里 await import,避免 citty --help 遍历 subCommands 时触发 env 校验 - compile.ts 入口切到 bin.ts;移除 src/server/plugins/migrate.ts 与 vite.config.ts 中的启动时自动迁移 - compose.yaml 新增一次性 migrate 服务,app depends_on service_completed_successfully,保证迁移先行再起服 - tsconfig 排除 .output / out;AGENTS.md 补充 CLI 与部署规约
12 KiB
AGENTS.md
Compact, repo-specific notes for AI agents. Generic language/framework knowledge is omitted — only things that will bite you if you don't know.
Stack & runtime
- Bun-only (
mise.tomlpinsbun = 1.3.13). Never invokenpm/npx/node/yarn/pnpm. Usebun run <script>(barebun <script>can collide with Bun built-in subcommands). - TanStack Start (React 19 SSR, file-routed) + Vite 8 + Nitro (nightly, preset
bun). Vite dev port is strict 3000. - PostgreSQL + Drizzle ORM
0.45.2(0.x, NOT 1.0 beta) — see "Drizzle" section, this matters a lot. - ORPC (contract-first), TanStack Query v5, Tailwind v4.
Scripts
bun run dev # bunx --bun vite dev (localhost:3000)
bun run build # bunx --bun vite build → .output/
bun run compile # bun compile.ts → out/server-<target> (standalone CLI binary)
bun run cli <cmd> # bun bin.ts <cmd> — run a CLI subcommand in source (dev)
bun run typecheck # tsc --noEmit
bun run fix # biome check --write (lint + format + organize imports)
bun run db:push # dev only — push schema to DB, no migration file
bun run db:generate # produce SQL migration files in ./drizzle
bun run db:migrate # apply migrations via drizzle-kit (local convenience)
bun run db:studio # Drizzle Studio
Cross-compile targets live under compile:{linux,darwin,windows}[:arch]. compile.ts accepts --target bun-<os>-<arch>; default derives from host.
Before committing: bun run fix && bun run typecheck. No CI, no pre-commit hooks, no lint-staged — so these are on you.
Drizzle (v0.x — critical)
Why it matters: the project was on 1.0 beta and was rolled back. Online docs default to 1.0 beta APIs that do NOT exist here. If typecheck complains, you are probably importing a 1.0 beta API.
- Driver:
drizzle-orm/postgres-js. Do NOT usedrizzle-orm/bun-sql. drizzle()is called with{ connection, schema }whereschema = import * as schema from '@/server/db/schema'. There is norelations.tsand nodefineRelationsin 0.x.- Zod generators live in the separate
drizzle-zodpackage (^0.8.3). Import fromdrizzle-zod, notdrizzle-orm/zod(that subpath only exists in 1.0 beta). - Relational queries use RQB v1 callback syntax:
Do NOT use the v2 object form (
db.query.todoTable.findMany({ orderBy: (t, { desc }) => desc(t.createdAt), })orderBy: { createdAt: 'desc' },where: { id }) — it won't type-check. - To add relations later: declare per-table with
relations()fromdrizzle-ormand export them from the same file as the table; they get picked up automatically becauseindex.tsdoesdrizzle({ schema })viaimport *. - Every table must spread
...generatedFieldsfromsrc/server/db/fields.ts(givesidUUIDv7 with$defaultFnfallback,createdAt,updatedAtwith$onUpdateFn). There's also ageneratedFieldKeyshelper to feedcreateInsertSchema(...).omit(...). drizzle.config.tsruns outside Vite —@/*path aliases do NOT resolve there. It currently doesimport { env } from './src/env'(relative). Preserve that.- The
./drizzle/migrations directory is gitignored-by-absence right now (no migrations yet). Migrations are applied via the CLI (./server migrate, see "CLI & single-binary deploy" below), NOT at server startup. Dev usesdb:push. Don't mixpushandmigrateon the same DB.
CLI & single-binary deploy
bun run compile produces a single executable that dispatches subcommands via citty. Entry is bin.ts at repo root, subcommands live in src/cli/.
./server [serve] # default — start the HTTP server
./server migrate # apply migrations from ./drizzle
./server --help
Nitro side-effect pitfall (important). Under the bun preset, .output/server/index.mjs has a top-level serve(...) call — merely importing it starts the HTTP server. bin.ts therefore must not eager-import any subcommand module, and src/cli/serve.ts reaches .output/server/index.mjs through the src/cli/_serve-nitro.mjs bridge (with _serve-nitro.d.mts for types, since .output/ doesn't exist at typecheck time). Citty's subCommands: { x: () => import('...') } lazy-loader is what keeps --help and migrate from booting the server.
Citty eager-loads subcommand modules for --help to read each subcommand's meta. So every src/cli/*.ts module body must be side-effect-free: do NOT static-import @/env, @/server/db/*, or anything that reads env at module-load time. Use await import('@/env') inside run(). Otherwise ./server --help (or any subcommand's help) will fail with env validation errors before printing.
Add a subcommand: drop a file in src/cli/ that default-exports defineCommand({...}), then register it in bin.ts's subCommands with a () => import(...) thunk. Keep top-level imports limited to citty + Node built-ins; pull env / db / etc. via await import(...) inside run().
Deploy flow is always migrate-then-serve. The compiled binary bundles neither the ./drizzle/ SQL files nor the app schema migrations at runtime — they're read from disk next to the binary. Dockerfile copies drizzle/ alongside ./server, and compose.yaml models this with a one-shot migrate service that app depends_on: service_completed_successfully. On k8s, run ./server migrate as an initContainer or a Helm pre-upgrade Job; run ./server (= ./server serve) as the main container.
ORPC
Contract → Router → Handler → Client, all type-safe from a single contract.
osis built insrc/server/api/server.tsviaimplement(contract).$context<BaseContext>(). Always importosfrom@/server/api/server, never from@orpc/serverdirectly.ORPCError,onError,ValidationErrorcome from@orpc/server.- Contracts (
src/server/api/contracts/*.contract.ts) generate Zod from Drizzle tables viadrizzle-zod:Barrel-aggregated inconst insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)contracts/index.tsasexport const contract = { todo }. - Routers chain the
dbmiddleware (src/server/api/middlewares/db.middleware.ts, injects thegetDB()singleton into context). Barrel inrouters/index.tsbuildsos.router({ todo }). - Interceptors are attached at the handler level, not in
server.tsand not onos. Bothsrc/routes/api/rpc.$.ts(RPCHandler) andsrc/routes/api/$.ts(OpenAPIHandler) register[onError(logError)](server) and[onError(handleValidationError)](client). The validation interceptor rewritesBAD_REQUEST + ValidationErrorintoINPUT_VALIDATION_FAILED(422) and output validation errors intoOUTPUT_VALIDATION_FAILED. - OpenAPI/Scalar: docs at
/api/docs, spec at/api/spec.json(handler prefix/api, plugin paths/docsand/spec.json). - SSR isomorphism (
src/client/orpc.ts):createIsomorphicFn().server(createRouterClient(...)).client(new RPCLink(...)). Server branch readsgetRequestHeaders()for context; client branch POSTs to${origin}/api/rpc. - Global mutation invalidation uses
experimental_defaultsincreateTanstackQueryUtils(...)— currently invalidatesorpc.todo.list.key()on everytodo.{create,update,remove}success. Add new features here rather than in each mutation site. - SSR prefetch in route loaders:
await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions()). Components useuseSuspenseQuery(orpc.feature.list.queryOptions()).
Code style (Biome)
- 2-space, LF, single quotes, semicolons as-needed (omitted unless required), 120-col, arrow parens always,
useArrowFunction: "error"— so React components must beconst Foo = () => {...}notfunction Foo() {}. AlsonoReactPropAssignments: "error". - Imports are auto-organized into two groups (external, then
@/*), each alphabetical, withimport typeinterleaved (NOT a separate group).bun run fixhandles this; don't hand-sort. - Files: utils
kebab-case.ts, componentsPascalCase.tsx. routeTree.gen.tsis generated — ignored by Biome, never edit.
TypeScript
Strict mode, plus noUncheckedIndexedAccess, verbatimModuleSyntax, erasableSyntaxOnly, noImplicitOverride. No as any / @ts-ignore / @ts-expect-error.
Path alias: @/* → src/*. For files outside src/ use @/../<file> (example in the codebase: src/routes/api/$.ts imports name, version from @/../package.json).
Env
src/env.ts via @t3-oss/env-core. Server: DATABASE_URL (required, z.url()). Client needs VITE_ prefix (VITE_APP_TITLE optional). Never commit .env.
Docker / deploy
- Multi-stage:
oven/bun:1.3.13builds and runsbun compile.ts, thengcr.io/distroless/cc-debian13:nonrootruns the single./serverbinary. Thecc(glibc) distroless variant is required because Bun's compiled binary links glibc. drizzle/folder is copied into the runtime image so./server migratecan find migrations at runtime.compose.yaml: one-shotmigrateservice runs./server migratewithrestart: "no", thenappstarts (depends_on: migrate: service_completed_successfully).DATABASE_URL=postgres://postgres:postgres@db:5432/postgresfor both.- Distroless has no shell, so any init-then-serve pattern must use exec-form
command: [...], notsh -c.
Layout (non-obvious parts only)
src/
├── client/orpc.ts # isomorphic ORPC client + experimental_defaults invalidation
├── cli/ # CLI subcommands (loaded lazily by bin.ts via citty)
│ ├── serve.ts # `./server serve` — imports the Nitro bridge on demand
│ ├── migrate.ts # `./server migrate` — drizzle migrate against ./drizzle
│ ├── _serve-nitro.mjs # bridge: `import('../../.output/server/index.mjs')`
│ └── _serve-nitro.d.mts # types for the bridge (build output has no .d.ts)
├── routes/api/
│ ├── $.ts # OpenAPI + Scalar; interceptors registered here
│ └── rpc.$.ts # RPC; interceptors registered here
├── server/
│ ├── api/
│ │ ├── server.ts # the ONLY place to build `os`
│ │ ├── context.ts # BaseContext / DBContext types
│ │ ├── interceptors.ts # logError, handleValidationError
│ │ ├── contracts/ # Zod schemas from Drizzle tables (barrel: contract)
│ │ ├── routers/ # os.* handlers (barrel: router)
│ │ └── middlewares/ # db middleware injects getDB() singleton
│ ├── db/
│ │ ├── index.ts # createDB({ connection, schema }) + getDB()/closeDB() singleton
│ │ ├── fields.ts # pk (UUIDv7), createdAt, updatedAt, generatedFields(Keys)
│ │ └── schema/ # pgTable definitions; also put `relations()` here when adding
│ └── plugins/
│ └── shutdown.ts # SIGINT/SIGTERM → closeDB() with 500ms delay
├── env.ts # t3-oss env validation
├── router.tsx # QueryClient + setupRouterSsrQueryIntegration
└── routeTree.gen.ts # auto-generated, do not edit
bin.ts # citty entry (root) — keep imports minimal (see "CLI" section)
Nitro plugins are wired in vite.config.ts (nitro({ plugins: [...] })), not via a Nitro config file.
Don'ts (specific, non-obvious)
- Don't edit
routeTree.gen.ts. - Don't eager-import anything from
.output/inbin.tsor any module it statically imports — it starts the HTTP server as a side effect. Subcommands must be lazy via citty's() => import(...)thunks. - Don't re-add an auto-migrate Nitro plugin. Migrations are an explicit deploy step via
./server migrate. - Don't import
osfrom@orpc/serverin middleware/routers — always@/server/api/server. - Don't import from
drizzle-orm/zod(1.0 beta only). Usedrizzle-zod. - Don't use RQB v2 object syntax,
defineRelations, or passrelationstodrizzle(). All are 1.0 beta. - Don't use
drizzle-orm/bun-sql. - Don't use
@/*aliases indrizzle.config.ts. - Don't commit
.env.