diff --git a/AGENTS.md b/AGENTS.md index 2552c97..5d061a4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,19 +15,19 @@ Compact, repo-specific notes for AI agents. Generic language/framework knowledge ```bash 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- (standalone CLI binary) -bun run cli # bun bin.ts — run a CLI subcommand in source (dev) +bun run compile # bun scripts/compile.ts → out/server- (standalone CLI binary) +bun run cli # bun src/bin.ts — run a CLI subcommand in source (dev) bun run typecheck # tsc --noEmit bun run test # bun test — runs all *.test.ts files (colocated with source) 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 # drizzle-kit generate && embed-migrations.ts (regenerates migrations.gen.ts) -bun run db:embed # embed-migrations.ts only — regenerate migrations.gen.ts from ./drizzle/ +bun run db:generate # drizzle-kit generate && scripts/embed-migrations.ts (regenerates migrations.gen.ts) +bun run db:embed # scripts/embed-migrations.ts only — regenerate migrations.gen.ts from ./drizzle/ bun run db:migrate # apply migrations via drizzle-kit (local dev convenience; prod uses ./server migrate) bun run db:studio # Drizzle Studio ``` -Cross-compile targets live under `compile:{linux,darwin,windows}[:arch]`. `compile.ts` accepts `--target bun--`; default derives from host. +Cross-compile targets live under `compile:{linux,darwin,windows}[:arch]`. `scripts/compile.ts` accepts `--target bun--`; default derives from host. Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no pre-commit hooks, no lint-staged — so these are on you. @@ -49,11 +49,11 @@ Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no - Every table must spread `...generatedFields` from `src/server/db/fields.ts` (`id` UUIDv7 via `$defaultFn(uuidv7)`, `createdAt`, `updatedAt` with `$onUpdateFn`). `generatedFieldKeys` is hand-written and uses `satisfies Record` so any field-key drift fails typecheck; it feeds `createInsertSchema(...).omit(...)` / `createUpdateSchema(...).omit(...)`. - `src/server/db/index.ts` exports a module-level `const db = drizzle(...)` — not a lazy singleton. On Bun this is a long-lived process, so top-level side effects are fine and requested. Don't reintroduce `getDB/closeDB` ceremony; the Nitro shutdown plugin calls `db.$client.end()` directly. (Cloudflare Workers would need per-request init — we don't support that deployment target.) - `drizzle.config.ts` runs outside Vite — `@/*` path aliases do NOT resolve there. It currently does `import { env } from './src/env'` (relative). Preserve that. -- **Migrations are embedded in the binary, not read from disk.** `bun run db:generate` chains `drizzle-kit generate && bun embed-migrations.ts`, which regenerates `src/server/db/migrations.gen.ts` (committed, AUTO-GENERATED header) by `import sql_ from '../../../drizzle/.sql' with { type: 'text' }`. `src/cli/migrate.ts` reads `embeddedMigrations`, **validates SHA-256 hash of every already-applied migration against the embedded SQL** (rejects schema drift if anyone edited an applied migration), then applies pending entries via `db.execute(sql\`...\`)` + `db.transaction(...)` against the `drizzle.__drizzle_migrations` book-keeping table — public APIs only, no `db.dialect`/`db.session` (those are `@internal`). Each migration is split on `--> statement-breakpoint`; empty fragments are trimmed and skipped. Dev helpers `db:push` / `drizzle-kit migrate` still read `./drizzle/`. +- **Migrations are embedded in the binary, not read from disk.** `bun run db:generate` chains `drizzle-kit generate && bun scripts/embed-migrations.ts`, which regenerates `src/server/db/migrations.gen.ts` (committed, AUTO-GENERATED header) by `import sql_ from '#drizzle/.sql' with { type: 'text' }`. `src/cli/migrate.ts` reads `embeddedMigrations`, **validates SHA-256 hash of every already-applied migration against the embedded SQL** (rejects schema drift if anyone edited an applied migration), then applies pending entries via `db.execute(sql\`...\`)` + `db.transaction(...)` against the `drizzle.__drizzle_migrations` book-keeping table — public APIs only, no `db.dialect`/`db.session` (those are `@internal`). Each migration is split on `--> statement-breakpoint`; empty fragments are trimmed and skipped. Dev helpers `db:push` / `drizzle-kit migrate` still read `./drizzle/`. ## CLI & single-binary deploy -`bun run compile` produces a single executable that dispatches subcommands via [citty](https://github.com/unjs/citty). Entry is `bin.ts` at repo root, subcommands live in `src/cli/`. +`bun run compile` produces a single executable that dispatches subcommands via [citty](https://github.com/unjs/citty). Entry is `src/bin.ts`; subcommands live in `src/cli/`. ``` ./server [serve] # default — start the HTTP server @@ -61,21 +61,21 @@ Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no ./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. +**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. `src/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()`. +Add a subcommand: drop a file in `src/cli/` that default-exports `defineCommand({...})`, then register it in `src/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.** Migrations are embedded in the binary (see "Drizzle" section), so the binary is the only artifact — no `./drizzle/` directory at runtime. Dockerfile copies just `./server`. `compose.yaml` models the pattern 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. ## Compile flags -`compile.ts` builds with `--minify --bytecode --sourcemap=inline`: +`scripts/compile.ts` builds with `--minify --bytecode --sourcemap=inline`: - **`bytecode`** — pre-compiles JS to bytecode and embeds it in the binary; ~2x startup on app-sized binaries (Bun docs benchmark). Requires `--compile`; top-level `await` must live inside `async` functions (it already does in this repo). - **`minify`** — shrinks the binary and the bytecode it derives from. -- **`sourcemap: 'inline'`** — embeds the source map in the binary so error stack traces stay decodable. Bun also writes a residual `out/bin.js.map` next to the output; `compile.ts` removes it so the binary is the only artifact. +- **`sourcemap: 'inline'`** — embeds the source map in the binary so error stack traces stay decodable. Bun also writes a residual `out/bin.js.map` next to the output; `scripts/compile.ts` removes it so the binary is the only artifact. ## ORPC @@ -143,7 +143,7 @@ logger.error('DB write failed', { error }) ## Docker / deploy -- Multi-stage: `oven/bun:1.3.13` builds and runs `bun compile.ts`, then `gcr.io/distroless/cc-debian13:nonroot` runs the single `./server` binary. The `cc` (glibc) distroless variant is required because Bun's compiled binary links glibc. +- Multi-stage: `oven/bun:1.3.13` builds and runs `bun scripts/compile.ts`, then `gcr.io/distroless/cc-debian13:nonroot` runs the single `./server` binary. The `cc` (glibc) distroless variant is required because Bun's compiled binary links glibc. - `compose.yaml`: one-shot `migrate` service runs `./server migrate` with `restart: "no"`, then `app` starts (`depends_on: migrate: service_completed_successfully`). `DATABASE_URL=postgres://postgres:postgres@db:5432/postgres` for both. - Distroless has no shell, so any init-then-serve pattern must use exec-form `command: [...]`, not `sh -c`. @@ -151,13 +151,14 @@ logger.error('DB write failed', { error }) ``` src/ +├── bin.ts # citty entry — keep imports minimal (see "CLI" section) ├── client/ │ ├── orpc.ts # isomorphic ORPC client + TanStack Query utils (no global invalidation defaults) │ └── queries/ # per-feature query hooks: keys, options, `useInvalidate` helpers -├── cli/ # CLI subcommands (loaded lazily by bin.ts via citty) +├── cli/ # CLI subcommands (loaded lazily by src/bin.ts via citty) │ ├── serve.ts # `./server serve` — imports the Nitro bridge on demand │ ├── migrate.ts # `./server migrate` — applies embedded migrations via public `db.execute(sql)` + `db.transaction()` -│ ├── _serve-nitro.mjs # bridge: `import('../../.output/server/index.mjs')` +│ ├── _serve-nitro.mjs # bridge: `import('#server')` (subpath import → .output/server/index.mjs) │ └── _serve-nitro.d.mts # types for the bridge (build output has no .d.ts) ├── routes/ │ ├── __root.tsx # root route + RootDocument shell @@ -179,18 +180,18 @@ src/ │ │ ├── index.ts # module-level `export const db = drizzle({...})` │ │ ├── fields.ts # generatedFields (id/createdAt/updatedAt) + generatedFieldKeys │ │ ├── migrations.gen.ts # AUTO-GENERATED by `bun run db:embed`; embeds ./drizzle/*.sql via `with { type: 'text' }` +│ │ ├── sql.d.ts # ambient `declare module '*.sql'` — load-bearing for `with { type: 'text' }` imports in migrations.gen.ts │ │ └── schema/ # pgTable definitions; also put `relations()` here when adding │ └── plugins/ │ └── shutdown.ts # SIGINT/SIGTERM → db.$client.end() with 500ms delay (prod only) ├── components/ # non-route UI primitives (PascalCase, arrow const) ├── env.ts # t3-oss env validation ├── router.tsx # QueryClient + setupRouterSsrQueryIntegration -├── sql.d.ts # ambient `declare module '*.sql'` — load-bearing for `with { type: 'text' }` imports in migrations.gen.ts ├── styles.css # Tailwind v4 entry └── routeTree.gen.ts # auto-generated, do not edit -bin.ts # citty entry (root) — keep imports minimal (see "CLI" section) -compile.ts # `bun build --compile` driver; resolves --target; sets minify/bytecode/sourcemap -embed-migrations.ts # codegen: scans ./drizzle/meta/_journal.json → src/server/db/migrations.gen.ts +scripts/ +├── compile.ts # `bun build --compile` driver; resolves --target; sets minify/bytecode/sourcemap +└── embed-migrations.ts # codegen: scans ./drizzle/meta/_journal.json → src/server/db/migrations.gen.ts drizzle/ # SQL migrations (source of truth for `db:generate`; not shipped in binary) ``` @@ -199,7 +200,7 @@ Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not v ## Don'ts (specific, non-obvious) - Don't edit `routeTree.gen.ts` or `src/server/db/migrations.gen.ts`. -- Don't eager-import anything from `.output/` in `bin.ts` or 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 eager-import anything from `.output/` in `src/bin.ts` or 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 reach into `db.dialect`/`db.session` from `migrate.ts` — they're `@internal`. The current implementation uses public `db.execute(sql)` + `db.transaction(...)` against the documented `drizzle.__drizzle_migrations` schema. - Don't add `./drizzle/` back to the runtime image — migrations are embedded into the binary. @@ -223,5 +224,5 @@ These keep the starter from setting bad precedents as it grows. Append, don't re 6. One file per Drizzle table. Relations live in the same file and are exported as `Relations`. No global `relations.ts`. 7. One router file per feature (`routers/.router.ts`). Only introduce `routers//index.ts` when a domain grows past ~5 router files or needs shared domain helpers. 8. All server-side logging goes through `getLogger([...])` from `@/server/logger`. Use a hierarchical category (`['api']`, `['db']`, `['cli', 'migrate']`, etc.) — these become dot-paths in JSON output and let you filter by prefix. Use the `{name}` placeholder + properties form, not string interpolation. `console.*` is forbidden in business code. -9. CLI subcommand modules keep top-level imports to `citty` + Node built-ins. Env, db, and server code are `await import(...)`-ed inside `run()` (see `bin.ts` comment for why). +9. CLI subcommand modules keep top-level imports to `citty` + Node built-ins. Env, db, and server code are `await import(...)`-ed inside `run()` (see `src/bin.ts` comment for why). 10. Every new business feature ships with at least one `bun test` covering a contract schema, a pure helper, or a router behavior. diff --git a/package.json b/package.json index c7f3507..2aea2f9 100644 --- a/package.json +++ b/package.json @@ -10,18 +10,18 @@ }, "scripts": { "build": "bunx --bun vite build", - "cli": "bun bin.ts", - "compile": "bun compile.ts", + "cli": "bun src/bin.ts", + "compile": "bun scripts/compile.ts", "compile:darwin": "bun run compile:darwin:arm64 && bun run compile:darwin:x64", - "compile:darwin:arm64": "bun compile.ts --target bun-darwin-arm64", - "compile:darwin:x64": "bun compile.ts --target bun-darwin-x64", + "compile:darwin:arm64": "bun scripts/compile.ts --target bun-darwin-arm64", + "compile:darwin:x64": "bun scripts/compile.ts --target bun-darwin-x64", "compile:linux": "bun run compile:linux:x64 && bun run compile:linux:arm64", - "compile:linux:arm64": "bun compile.ts --target bun-linux-arm64", - "compile:linux:x64": "bun compile.ts --target bun-linux-x64", + "compile:linux:arm64": "bun scripts/compile.ts --target bun-linux-arm64", + "compile:linux:x64": "bun scripts/compile.ts --target bun-linux-x64", "compile:windows": "bun run compile:windows:x64", - "compile:windows:x64": "bun compile.ts --target bun-windows-x64", - "db:embed": "bun embed-migrations.ts", - "db:generate": "drizzle-kit generate && bun embed-migrations.ts", + "compile:windows:x64": "bun scripts/compile.ts --target bun-windows-x64", + "db:embed": "bun scripts/embed-migrations.ts", + "db:generate": "drizzle-kit generate && bun scripts/embed-migrations.ts", "db:migrate": "drizzle-kit migrate", "db:push": "drizzle-kit push", "db:studio": "drizzle-kit studio", diff --git a/compile.ts b/scripts/compile.ts similarity index 93% rename from compile.ts rename to scripts/compile.ts index 60bc990..7958da1 100644 --- a/compile.ts +++ b/scripts/compile.ts @@ -1,7 +1,8 @@ import { mkdir, rm } from 'node:fs/promises' +import { basename } from 'node:path' import { parseArgs } from 'node:util' -const ENTRYPOINT = 'bin.ts' +const ENTRYPOINT = 'src/bin.ts' const OUTDIR = 'out' const SUPPORTED_TARGETS: readonly Bun.Build.CompileTarget[] = [ @@ -61,7 +62,7 @@ const main = async () => { } // Bun bundler still writes *.js.map next to the binary even with inline sourcemap. - await rm(`${OUTDIR}/${ENTRYPOINT.replace(/\.ts$/, '')}.js.map`, { force: true }) + await rm(`${OUTDIR}/${basename(ENTRYPOINT, '.ts')}.js.map`, { force: true }) console.log(`✓ ${target} → ${OUTDIR}/${outfile}`) } diff --git a/embed-migrations.ts b/scripts/embed-migrations.ts similarity index 100% rename from embed-migrations.ts rename to scripts/embed-migrations.ts diff --git a/bin.ts b/src/bin.ts similarity index 72% rename from bin.ts rename to src/bin.ts index 67bb8bc..4e9a16d 100644 --- a/bin.ts +++ b/src/bin.ts @@ -1,5 +1,5 @@ import { defineCommand, runMain } from 'citty' -import { name, version } from './package.json' with { type: 'json' } +import { name, version } from '#package' // IMPORTANT: keep this file's static imports minimal. Nitro's bun preset // emits `.output/server/index.mjs` with a top-level `serve(...)` call, so any @@ -13,8 +13,8 @@ const main = defineCommand({ }, default: 'serve', subCommands: { - serve: () => import('./src/cli/serve').then((m) => m.default), - migrate: () => import('./src/cli/migrate').then((m) => m.default), + serve: () => import('@/cli/serve').then((m) => m.default), + migrate: () => import('@/cli/migrate').then((m) => m.default), }, }) diff --git a/src/sql.d.ts b/src/server/db/sql.d.ts similarity index 100% rename from src/sql.d.ts rename to src/server/db/sql.d.ts