@wwchen/stack 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +50 -23
  2. package/blocks/AGENTS.md +11 -31
  3. package/blocks/CLAUDE.md +10 -36
  4. package/blocks/env.example +1 -18
  5. package/blocks/gitignore +1 -8
  6. package/dist/cli/builtin.d.ts +7 -0
  7. package/dist/cli/builtin.js +42 -0
  8. package/dist/cli/check.d.ts +5 -0
  9. package/dist/cli/check.js +39 -0
  10. package/dist/cli/context.d.ts +4 -35
  11. package/dist/cli/context.js +1 -23
  12. package/dist/cli/discover.d.ts +15 -0
  13. package/dist/cli/discover.js +156 -0
  14. package/dist/cli/generate.d.ts +6 -0
  15. package/dist/cli/generate.js +94 -0
  16. package/dist/cli/host.d.ts +8 -0
  17. package/dist/cli/host.js +146 -0
  18. package/dist/cli/index.js +4 -71
  19. package/dist/cli/owned.d.ts +33 -0
  20. package/dist/cli/owned.js +151 -0
  21. package/dist/cli/sync.d.ts +19 -0
  22. package/dist/cli/sync.js +231 -0
  23. package/dist/configs/vitest.d.ts +3 -1
  24. package/dist/configs/vitest.js +8 -11
  25. package/dist/connections/env.d.ts +8 -0
  26. package/dist/connections/env.js +15 -0
  27. package/dist/connections/index.d.ts +1 -1
  28. package/dist/connections/index.js +1 -1
  29. package/dist/connections/table.d.ts +5 -3
  30. package/dist/connections/table.js +3 -3
  31. package/dist/env/core-env.d.ts +23 -0
  32. package/dist/env/core-env.js +24 -0
  33. package/dist/env/define-env.d.ts +22 -10
  34. package/dist/env/define-env.js +72 -17
  35. package/dist/env/index.d.ts +2 -2
  36. package/dist/env/index.js +1 -1
  37. package/dist/http/client-ip.d.ts +6 -0
  38. package/dist/http/client-ip.js +21 -0
  39. package/dist/http/index.d.ts +2 -0
  40. package/dist/http/index.js +2 -0
  41. package/dist/http/safe-next.d.ts +11 -0
  42. package/dist/http/safe-next.js +30 -0
  43. package/dist/index.d.ts +2 -1
  44. package/dist/index.js +1 -1
  45. package/dist/next/api.d.ts +9 -8
  46. package/dist/next/api.js +10 -8
  47. package/dist/next/config.d.ts +2 -0
  48. package/dist/next/config.js +10 -6
  49. package/dist/next/health.d.ts +5 -7
  50. package/dist/next/health.js +16 -17
  51. package/dist/stack/contracts.d.ts +202 -0
  52. package/dist/stack/contracts.js +66 -0
  53. package/dist/vercel/index.d.ts +28 -0
  54. package/dist/vercel/index.js +90 -0
  55. package/files/.claude/rules/stack-ui.md +24 -0
  56. package/files/next.config.ts +6 -0
  57. package/files/src/app/api/health/route.ts +9 -0
  58. package/package.json +16 -29
  59. package/dist/cli/db.d.ts +0 -4
  60. package/dist/cli/db.js +0 -43
  61. package/dist/cli/dev.d.ts +0 -4
  62. package/dist/cli/dev.js +0 -70
  63. package/dist/cli/doctor.d.ts +0 -40
  64. package/dist/cli/doctor.js +0 -166
  65. package/dist/cli/migrate-suite.d.ts +0 -2
  66. package/dist/cli/migrate-suite.js +0 -491
  67. package/dist/cli/neon.d.ts +0 -79
  68. package/dist/cli/neon.js +0 -384
  69. package/dist/cli/run.d.ts +0 -2
  70. package/dist/cli/run.js +0 -29
  71. package/dist/cli/sync-blocks.d.ts +0 -14
  72. package/dist/cli/sync-blocks.js +0 -93
  73. package/dist/cli/user-create.d.ts +0 -6
  74. package/dist/cli/user-create.js +0 -77
  75. package/dist/cli/vercel-build.d.ts +0 -4
  76. package/dist/cli/vercel-build.js +0 -61
  77. package/dist/db/explaining-pool.d.ts +0 -11
  78. package/dist/db/explaining-pool.js +0 -55
  79. package/dist/db/index.d.ts +0 -20
  80. package/dist/db/index.js +0 -31
  81. package/dist/db/migration-status.d.ts +0 -5
  82. package/dist/db/migration-status.js +0 -38
  83. package/dist/db/schema-changes.d.ts +0 -13
  84. package/dist/db/schema-changes.js +0 -99
  85. package/dist/db/ssl.d.ts +0 -4
  86. package/dist/db/ssl.js +0 -17
  87. package/dist/db/target.d.ts +0 -19
  88. package/dist/db/target.js +0 -65
  89. package/dist/db/testing/index.d.ts +0 -23
  90. package/dist/db/testing/index.js +0 -67
  91. package/dist/db/testing/isolate.d.ts +0 -1
  92. package/dist/db/testing/isolate.js +0 -3
  93. package/dist/db/testing/pglite.d.ts +0 -20
  94. package/dist/db/testing/pglite.js +0 -79
  95. package/dist/env/stack-env.d.ts +0 -37
  96. package/dist/env/stack-env.js +0 -54
  97. package/dist/env/testing.d.ts +0 -6
  98. package/dist/env/testing.js +0 -13
package/README.md CHANGED
@@ -1,25 +1,27 @@
1
1
  # @wwchen/stack
2
2
 
3
- Shared building blocks for Next.js 16 apps on Neon, Better Auth, Resend and lew-ds. Sign-in is [`@wwchen/stack-auth`](../auth) and mail is [`@wwchen/stack-notify`](../notify), released with this package under the same version. Apps are normally created from the Copier template in [wwchen/bootstrap-stack](https://github.com/wwchen/bootstrap-stack), which wires everything below; this README is the package's reference.
3
+ Shared building blocks for Next.js 16 apps on lew-ds, and the `stack` command that runs the packages an app composes. The database is [`@wwchen/stack-db`](../db), sign-in is [`@wwchen/stack-auth`](../auth), mail is [`@wwchen/stack-notify`](../notify) and hosting on Vercel is [`@wwchen/stack-infra`](../infra), released with this package under the same version, as is [`@wwchen/stack-upgrade`](../upgrade), which moves an app onto a release. Apps are normally created from the Copier template in [wwchen/bootstrap-stack](https://github.com/wwchen/bootstrap-stack), which wires everything below; this README is the package's reference.
4
4
 
5
- Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-dom`, `drizzle-orm`, `@lew-ds/lds`, `@lew-ds/lds-react`, `@lew-ds/open-icons`; `typescript` takes patch releases (`~`), and `stack migrate-suite` parses the app's imports with it. `@electric-sql/pglite` and `@electric-sql/pglite-socket` are optional peers for tests and local development, and `storybook` and `@storybook/nextjs-vite` for an app's Storybook.
5
+ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-dom`, `@lew-ds/lds`, `@lew-ds/lds-react`, `@lew-ds/open-icons`; `typescript` takes patch releases (`~`). `drizzle-orm` is an optional peer, for connected accounts, and `storybook` and `@storybook/nextjs-vite` for an app's Storybook.
6
6
 
7
7
  ## Entry points
8
8
 
9
9
  | Import | What it gives you |
10
10
  |---|---|
11
- | `@wwchen/stack/env` | `stackEnvSchema` and `stackEnv()`: the shared variables, validated; production requires `APP_URL` (derived on Vercel when unset), `DATABASE_URL`, `BETTER_AUTH_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM`. `SKIP_ENV_VALIDATION=1` skips it in builds (never at production runtime). |
12
- | `@wwchen/stack/db` | the pooled client, `migrationStatus`, the dev-database guard that refuses production |
13
- | `@wwchen/stack/db/testing`, `/db/testing/isolate` | test databases: PGlite by default, a real Postgres when `TEST_DATABASE_URL` is set |
14
- | `@wwchen/stack/next` | `withStack(appConfig)` for `next.config.ts`, `apiHandler` and `readJson`, `cronRoute` (answers 500 when the job returns `alerting: true`) and `healthRoute` |
11
+ | `@wwchen/stack` | `defineStack({ settings })` for the app's `stack.config.ts`, and the types a package implements for it (`StackPackage`, `Command`, `BuildStep`, `DoctorCheck`, `EnvFragment`, `Gate`, `HealthCheck`, …) |
12
+ | `@wwchen/stack/env` | `defineEnv({ fragments, schema })`: the app's variables, validated, from each package's env fragment plus the app's own `schema` (a name defined twice is an error naming both); `coreEnv`, the shared variables (production requires `APP_URL`, derived on Vercel when unset). `SKIP_ENV_VALIDATION=1` skips it in builds (never at production runtime). |
13
+ | `@wwchen/stack/next` | `withStack(appConfig, { tracing })` for `next.config.ts`, `apiHandler({ label, gate }, fn)` (the `Gate` decides the caller: its 401 answers `unauthenticated`, its 404 `not_found`, its principal reaches `fn`) and `readJson`, `cronRoute` (answers 500 when the job returns `alerting: true`) and `healthRoute({ token, checks })` (each `HealthCheck`'s fields join the answer for the token) |
14
+ | `@wwchen/stack/http` | `safeNext(raw, fallback?)` (a `?next=` kept only when it is a path on this site) and `clientIp(headers, hops)` (the caller, read from `X-Forwarded-For` counted from the right) |
15
+ | `@wwchen/stack/vercel` | the linked Vercel project's metadata through the Vercel CLI, for a package's `stack` command: `linkedProject` (`.vercel/project.json`), `vercelApi`, `listEnvs` and `envVarMeta` (each variable's metadata, never its value), `readJsonFile`; never part of the app's runtime |
15
16
  | `@wwchen/stack/connections` | connected accounts (not sign-in): `connectionTable`, `createConnections` (start and callback route handlers, `token`, `list`, `connected`, `disconnect`), the `ConnectionProvider` type each app implements for its own services, AES-256-GCM token encryption under `TOKEN_ENCRYPTION_KEY` |
17
+ | `@wwchen/stack/connections/env` | `connectionsEnv`: `TOKEN_ENCRYPTION_KEY` |
16
18
  | `@wwchen/stack/jobs` | multi-person scheduled jobs: `failingSince` and `isNewFailure` (alert on a failure's first 24 hours only), `mapLimit` |
17
19
  | `@wwchen/stack/ui`, `/ui/icons`, `/ui/globals.css`, `/ui/app.css` | lew-ds wiring, theme cookie, icon sprite and its usage check, and the CSS partials |
18
20
  | `@wwchen/stack/storybook` | an app's Storybook set up as its root layout sets up a page: `stackPreview({ icons, fontVariable, bodyClassName })` (the `<html>` theme classes with a light/dark toolbar, the icon sprite, a logging stand-in for the App Router's `useRouter()`, the viewports), and `PHONE` and `SMALL_PHONE` story globals |
19
- | `@wwchen/stack/configs/tsconfig.next.json`, `/configs/biome.json`, `/configs/vitest` | shared tool configs, consumed with `extends` or an import |
21
+ | `@wwchen/stack/configs/tsconfig.next.json`, `/configs/biome.json`, `/configs/vitest` | shared tool configs, consumed with `extends` or an import; `/configs/vitest` is `stackVitestConfig(overrides, { fragments })`, whose `fragments` are required (an app passes the generated `src/stack/env.ts`'s, whatever packages it has, so each package's test values reach its tests; a package's own test config passes its own list or `[]`) |
20
22
  | `@wwchen/stack/testing/next` | tests only: `inServerAction` runs a function in a real Next server-action scope, `thrownBy` reads a `redirect()`/`notFound()` |
21
23
 
22
- Sign-in and mail are [`@wwchen/stack-auth`](../auth) and [`@wwchen/stack-notify`](../notify); the old paths (`@wwchen/stack/auth`, `/auth/better-auth`, `/auth/proxy`, `/mail`) are gone, and `stack migrate-suite` moves an app's imports off them. Sign-in never creates users: every user is added first (`stack user:create`), has an email, and the email is unique, trimmed and lower-cased.
24
+ Sign-in and mail are [`@wwchen/stack-auth`](../auth) and [`@wwchen/stack-notify`](../notify). Sign-in never creates users: every user is added first (`stack user:create`, a command of `@wwchen/stack-auth`), has an email, and the email is unique, trimmed and lower-cased.
23
25
 
24
26
  ### Connected accounts
25
27
 
@@ -47,21 +49,46 @@ The callback lands on `next` with `?connection=<provider>&result=<code>`, where
47
49
 
48
50
  | Command | Does |
49
51
  |---|---|
50
- | `stack dev-setup` | creates your Neon dev branch from `seed` and migrates it |
51
- | `stack with-neon <cmd>` | runs `<cmd>` against your dev branch; refuses production, `seed` and `preview` |
52
- | `stack dev [--pglite]` | `next dev` on your dev branch; `--pglite`: on PGlite in `.local-db/` (migrated, seeded once), no Neon |
53
- | `stack run <script> [args]` | runs an app script with Node (type stripping) and the app's database and `.env`; `ENV_FILE` opts in to another |
54
- | `stack neon seed` | rebuilds the `seed` branch (fake data) and runs the app's `db/seed.ts` |
55
- | `stack neon reset-preview [--set-vercel]` | re-cuts the shared `preview` branch from `seed`; `--set-vercel` writes its URLs as Vercel's sensitive Preview `DATABASE_URL`/`DATABASE_URL_UNPOOLED` |
56
- | `stack vercel-build` | Vercel's build command: migrate the deployment's database, then `next build` |
57
- | `stack doctor` | read-only audit of the linked Vercel project (framework, Neon integration, shared secrets, database variables); exits 1 on an error |
58
- | `stack user:create <email> [--admin] [--preview]` | adds a user through the app's `src/lib/auth.ts`; `--preview` adds your own email to the shared `preview` branch so you can sign in on a preview (`docs/runbook.md`, "Signing in on a preview") |
59
- | `stack user:role <email> <admin\|user> [--preview]` | changes a user's role through the app's `src/lib/auth.ts`; never leaves the app without an admin |
60
- | `stack sync-blocks [--check]` | refreshes the stack blocks in `AGENTS.md`, `CLAUDE.md`, `.gitignore`, `.env.example` |
61
- | `stack migrate-suite [--expect <version>]` | moves the app onto `@wwchen/stack-auth` and `@wwchen/stack-notify`: adds them to `package.json` and the suite's packages to `pnpm-workspace.yaml`'s `minimumReleaseAgeExclude` (where the app has that list, or sets `minimumReleaseAge`), rewrites import and export specifiers of the old paths (and `vi.mock`-style module names), sorts the imports it touched with the app's Biome; changes nothing on an app already moved. `--expect` refuses unless the installed stack is that version |
62
-
63
- `NEON_PROJECT_ID` comes from the environment; nothing in the package names a project or domain.
52
+ | `stack check` | runs `stack sync --check`, then every composed package's checks in package order (each package's check of the files it reads from the app, below, and the database package's `db:check` among them), all of them even after a failure; names each failure as `<package>: <check>: <message>` and exits 1 if any failed; app CI runs it |
53
+ | `stack sync [--check]` | writes each composed package's marked block (`stack` first, then the packages in the order `package.json`'s dependencies need) in `AGENTS.md`, `CLAUDE.md`, `.gitignore`, `.env.example`; the files each package owns, recorded in `stack.files.json`; and the generated modules `src/stack/env.ts` (the `fragments` the app's `defineEnv` and `stackVitestConfig` take), `src/stack/health.ts` and `src/stack/next.ts`. It removes the block and the files of a package the app no longer composes, saying each one it removes; `--check` exits 1 when anything is missing, stale or orphaned. It refuses, changing nothing, an existing file at an owned path that `stack.files.json` does not record (move your code out of it or delete it), and a path two packages own. `stack sync-blocks` is the same command under a second name, which the copier-update workflow and the tests of apps made before 0.11 run; the bare `stack` lists it once, as `sync` |
54
+
55
+ The `stack` command finds the app's packages in `package.json`: each package in its `dependencies` or `devDependencies` whose `package.json` has `exports["./stack"]` is composed, and the core reads nothing else of a package but npm's fields.
56
+
57
+ Any dependency that exports `./stack` is composed, whoever publishes it, and is held to the suite's version: `stack` runs nothing until it is at the version `@wwchen/stack` is.
58
+
59
+ It runs only from the app's root: a folder with no `package.json` is refused, with nothing written. It refuses, one line per problem with its fix and exit 1, a stack peer the app does not list, a listed package that is not installed, two versions of the suite and a dependency cycle. Each stack package the app's `package.json` lists adds its own commands: `@wwchen/stack-db` gives the Neon branch and migration commands (`stack with-neon`, `stack dev`, `stack dev-setup`, `stack run`, `stack neon`, `stack db:check`, `stack db:generate`, `stack db:upgrade`), `@wwchen/stack-auth` gives `stack user:create` and `stack user:role`, and `@wwchen/stack-infra` gives `stack vercel-build` and `stack doctor` (their READMEs). When two composed packages give one command, `stack` runs nothing and names both; so too for a package whose `./stack` entry's default export is not a factory, or whose factory throws or returns something other than a package named as its `package.json`.
60
+
61
+ The core owns `next.config.ts` (the app's own settings are in `next.config.app.ts`), `src/app/api/health/route.ts` and `.claude/rules/stack-ui.md` in an app (the route imports the app's `src/lib/env.ts`, and `next.config.ts` its `next.config.app.ts`: "Files the app writes", below), and its blocks hold the rules every app follows. It has no database code, text or variable. The core gives `stack doctor` one check of its own: a warning when `CRON_SECRET` or `TOKEN_ENCRYPTION_KEY` is one variable for Production and Preview, so a preview never holds production's secret. Each composed package checks its own variables (`@wwchen/stack-db` the database's and the Neon integration's, `@wwchen/stack-auth` sign-in's secrets, `@wwchen/stack-notify` `RESEND_API_KEY`).
62
+
63
+ `stack.config.ts` is optional: it gives the listed packages their settings (`defineStack({ settings: [authSettings({ … })] })`), and `stack` refuses settings for a package `package.json` does not list. A package that needs settings and has none refuses to build, saying what to write.
64
+
65
+ ## Files the app writes
66
+
67
+ The core's owned files import two files that are the app's own code, which `stack sync` never writes. `stack check` names either one that is missing (`@wwchen/stack: src/lib/env.ts: missing: …`), and the template writes both.
68
+
69
+ `src/lib/env.ts` exports `env`, the app's validated variables. The health route imports it as `@/lib/env`, reads `env.HEALTH_TOKEN` and hands `env` to each package's health check, so it is `defineEnv` over the generated `fragments` plus the app's own variables:
70
+
71
+ ```ts
72
+ // The app's one validated config. Imported by the CLI with Node's type stripping, so imports here are relative and carry `.ts` (no `@/`).
73
+ import { defineEnv } from "@wwchen/stack/env";
74
+ import { fragments } from "../stack/env.ts";
75
+
76
+ export const env = defineEnv({
77
+ fragments,
78
+ schema: {},
79
+ });
80
+ ```
81
+
82
+ `next.config.app.ts` default-exports the app's own Next config, which the owned `next.config.ts` imports and wraps with `withStack`:
83
+
84
+ ```ts
85
+ import type { NextConfig } from "next";
86
+
87
+ const appConfig: NextConfig = {};
88
+
89
+ export default appConfig;
90
+ ```
64
91
 
65
92
  ## Versioning
66
93
 
67
- The package, `@wwchen/stack-auth`, `@wwchen/stack-notify`, the Copier template and the shared CI workflow share one version, tagged `vX.Y.Z`. Releases are published to npm with provenance.
94
+ The package, `@wwchen/stack-db`, `@wwchen/stack-auth`, `@wwchen/stack-notify`, `@wwchen/stack-infra`, `@wwchen/stack-upgrade`, the Copier template and the shared CI workflow share one version, tagged `vX.Y.Z`. Releases are published to npm with provenance.
package/blocks/AGENTS.md CHANGED
@@ -1,4 +1,4 @@
1
- <!-- Owned by @wwchen/stack: `stack sync-blocks` rewrites everything between these markers. Put your own text outside them. -->
1
+ <!-- Owned by @wwchen/stack: `stack sync` rewrites everything between these markers. Put your own text outside them. -->
2
2
 
3
3
  ## Commands (stack apps)
4
4
 
@@ -6,33 +6,23 @@
6
6
  |---|---|
7
7
  | Install | `pnpm install --frozen-lockfile` |
8
8
  | Dev server | `pnpm dev` (http://localhost:3000) |
9
- | Your own Neon dev branch | `stack dev-setup` once; `stack with-neon <command>` runs a command against it |
10
- | Dev server with no Neon | `stack dev --pglite` (PGlite in `.local-db/`, migrated and seeded) |
11
- | Run an app script | `stack run <script> [args]` (your dev branch and `.env`, like `with-neon`) |
12
9
  | Build | `pnpm build` |
13
10
  | Typecheck | `pnpm typecheck` |
14
11
  | Lint / format | `pnpm lint` · `pnpm lint:fix` |
15
12
  | Tests | `pnpm test` · one file: `pnpm test tests/unit/<name>.test.ts` |
16
13
  | Storybook | `pnpm storybook` (http://localhost:6006) · every story built, as CI does: `pnpm storybook:build` |
17
- | Migrate | `pnpm db:migrate` (your dev branch) |
18
- | Rebuild the `seed` branch (fake data; every dev and preview branch is cut from it) | `pnpm exec stack neon seed` |
19
- | Add a user | `stack user:create <email> [--admin]` (on your dev branch; production: the runbook's "First admin") |
20
- | Sign in on a preview | `stack user:create <your email> --admin --preview` (your own email only; `stack neon reset-preview` drops it) |
21
- | Change a user's role | `stack user:role <email> <admin\|user>` |
22
- | Check the Vercel project's setup | `stack doctor` (read-only; exits 1 on an error) |
23
- | Refresh the stack blocks in this file | `stack sync-blocks` (`--check` in CI) |
14
+ | Refresh what the stack writes: its blocks in this file, the files it owns and its generated modules (recorded in `stack.files.json`) | `stack sync` |
15
+ | Check the app against the stack: `stack sync --check`, then every package's checks (what CI runs) | `stack check` |
24
16
 
25
17
  **Gate:** `pnpm typecheck && pnpm lint && pnpm test` must pass before any task is marked done.
26
18
 
27
19
  ## Stack rules
28
20
 
29
21
  1. Never commit secrets or `.env`. `.env.example` lists names only, with empty values.
30
- 2. Never edit a generated migration by hand. Migrations run in the build or as an explicit command, never on app boot, and every migration is expand-then-contract.
31
- 3. Relative imports carry `.ts`. The `@/` alias is only for `src/app/**`, `src/components/**` and `tests/**`; code the CLI imports as plain Node (`src/lib/**`, `src/db/**`, `db/seed.ts`) uses relative imports.
32
- 4. Server components by default. `"use client"` only for state, effects or event handlers, on the smallest leaf, never on a layout.
33
- 5. Validate at the edge: parse every route handler's input with zod before any logic.
34
- 6. Authorization is server-side on every request. Another user's row answers 404, never 403.
35
- 7. Everyone signs in by email; sign-in never creates a user.
22
+ 2. Relative imports carry `.ts`. The `@/` alias is only for `src/app/**`, `src/components/**` and `tests/**`; code the CLI imports as plain Node (`src/lib/**`) uses relative imports.
23
+ 3. Server components by default. `"use client"` only for state, effects or event handlers, on the smallest leaf, never on a layout.
24
+ 4. Validate at the edge: parse every route handler's input with zod before any logic.
25
+ 5. Authorization is server-side on every request. Another user's row answers 404, never 403.
36
26
 
37
27
  ## Next.js notes
38
28
 
@@ -49,21 +39,11 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
49
39
  - A design change lands in the component and its stories (narrow and wide) in the same change, and carries to every component that shows the same thing.
50
40
  - Stories live beside their component as `*.stories.tsx` and render the real components from fixture data; a story never hand-builds a look. `PHONE` (390px) and `SMALL_PHONE` (320px) from `@wwchen/stack/storybook` open a story narrow, and the toolbar switches light and dark.
51
41
 
52
- ## Database
53
-
54
- - Postgres on Neon, with Drizzle. Local dev runs on your own Neon branch cut from `seed`, never from production; previews get their own branch, also from `seed`. Other people's data stays out of dev and previews.
55
- - Local tooling refuses the production database unless you opt in deliberately.
56
- - Tests run on PGlite (one connection only) and, in CI, a real Postgres.
57
- - Every user has an email: required, unique, lower-cased and trimmed.
58
- - Schema changes go through `pnpm db:generate <name>` and a reviewed migration, never through the Neon console or a database MCP server.
59
-
60
42
  ## Security
61
43
 
62
44
  1. `CRON_SECRET` can only trigger scheduled jobs; admin and data access never accept it.
63
45
  2. Never render free text from a URL; redirects carry short codes.
64
- 3. Sign-in links are single-use and expire. OAuth `state` is signed and bound to the browser that started the flow.
65
- 4. Sessions are HttpOnly, Secure (when https), SameSite=Lax. Mutations require JSON and a same-origin request.
66
- 5. Magic links are anti-enumeration, with hashed tokens.
67
- 6. Connected-account tokens are encrypted at rest; Better Auth never stores third-party API tokens.
68
- 7. Previews get their own secrets and no production third-party keys.
69
- 8. Never write a deployment's domain in the repo. Name variables (`APP_URL`, `EMAIL_FROM`), never a host.
46
+ 3. Mutations require JSON and a same-origin request.
47
+ 4. Connected-account tokens are encrypted at rest.
48
+ 5. Previews get their own secrets and no production third-party keys.
49
+ 6. Never write a deployment's domain in the repo. Name variables (`APP_URL`), never a host.
package/blocks/CLAUDE.md CHANGED
@@ -1,4 +1,4 @@
1
- <!-- Owned by @wwchen/stack: `stack sync-blocks` rewrites everything between these markers. Put your own text outside them. -->
1
+ <!-- Owned by @wwchen/stack: `stack sync` rewrites everything between these markers. Put your own text outside them. -->
2
2
 
3
3
  ## Commands
4
4
 
@@ -6,22 +6,12 @@
6
6
  |---|---|
7
7
  | Install | `pnpm install --frozen-lockfile` |
8
8
  | Dev server | `pnpm dev` (http://localhost:3000) |
9
- | Local database | Your own Neon dev branch: `stack dev-setup` once, then `stack with-neon <command>` |
10
- | No Neon at hand | `stack dev --pglite`: PGlite in `.local-db/`, migrated and seeded, then `next dev` |
11
- | Run an app script | `stack run <script> [args]` (your dev branch and `.env`, like `with-neon`) |
12
- | Build | `pnpm build` · on Vercel: `stack vercel-build` (migrates the deployment's own database first) |
13
9
  | Typecheck | `pnpm typecheck` |
14
10
  | Lint / format | `pnpm lint` · `pnpm lint:fix` |
15
11
  | Tests | `pnpm test` · one file: `pnpm test tests/unit/<name>.test.ts` |
16
12
  | Storybook | `pnpm storybook` (http://localhost:6006) · every story built, as CI does: `pnpm storybook:build` |
17
- | DB generate / apply migration | `pnpm db:generate <name>` (snake_case, what it does: `add_widgets`) · `pnpm db:migrate` |
18
- | Seed the shared `seed` branch | `stack neon seed` (runs the app's `db/seed.ts`) |
19
- | Reset the shared preview branch | `stack neon reset-preview` (`--set-vercel` also writes its URLs into Vercel's Preview variables) |
20
- | Check the Vercel project's setup | `stack doctor` (read-only; exits 1 on an error) |
21
- | Add a user / an admin | `stack user:create <email> [--admin]` (on your dev branch; production: the runbook's "First admin") |
22
- | Sign in on a preview | `stack user:create <your email> --admin --preview` (your own email only; `stack neon reset-preview` drops it) |
23
- | Change a user's role | `stack user:role <email> <admin\|user>` (keeps at least one admin) |
24
- | Refresh the stack blocks in this file | `stack sync-blocks` (`--check` in CI) |
13
+ | Refresh what the stack writes: its blocks in this file, the files it owns and its generated modules (recorded in `stack.files.json`) | `stack sync` |
14
+ | Check the app against the stack: `stack sync --check`, then every package's checks (what CI runs) | `stack check` |
25
15
 
26
16
  **Gate:** `pnpm typecheck && pnpm lint && pnpm test` must pass before any task is marked done. Never mark a task done with a failing gate command.
27
17
 
@@ -29,15 +19,11 @@ Node is pinned in `.nvmrc`; pnpm is installed with `npm install -g pnpm@<version
29
19
 
30
20
  ## Stack
31
21
 
32
- Next.js (App Router) · TypeScript · Tailwind CSS v4 (layout only) · LDS, product theme (`@lew-ds/lds`) · Postgres on Neon (PGlite in tests) · Drizzle ORM · Better Auth, self-hosted (email magic link through Resend, optional Google for added users) · Vercel · `@wwchen/stack` for the shared code, configs and CLI.
33
-
34
- **Local dev runs on a Neon dev branch** (`dev/<os-user>`), cut from `seed`, which holds fake users and fixture data. `stack with-neon` reads the branch's connection strings on every run and refuses the production database. Check the `[neon] <branch>` line it prints before running a database command.
35
-
36
- **One connection on PGlite.** The tests run on PGlite: a single backend. A script run while another process holds that connection is refused; stop the other process first.
22
+ Next.js (App Router) · TypeScript · Tailwind CSS v4 (layout only) · LDS, product theme (`@lew-ds/lds`) · Vercel · `@wwchen/stack` for the shared code, configs and CLI.
37
23
 
38
24
  ## Code rules
39
25
 
40
- 1. Relative imports carry `.ts`. The `@/` alias is allowed only in `src/app/**`, `src/components/**` and `tests/**`; in `src/lib/**`, `src/db/**`, `db/seed.ts` and `scripts/**` it is forbidden, because those files also run as plain Node.
26
+ 1. Relative imports carry `.ts`. The `@/` alias is allowed only in `src/app/**`, `src/components/**` and `tests/**`; in `src/lib/**` and `scripts/**` it is forbidden, because those files also run as plain Node.
41
27
  2. Server components by default. `"use client"` only for state, effects or event handlers, on the smallest leaf. Never on a layout.
42
28
  3. Validate at the edge: every route handler reads its body with `readJson(req, schema)` (a zod schema) before any logic. It answers a failed parse with 422 `invalid_input` and a `details` array, and a body that is not JSON with 400 `invalid_json`. A parse error anywhere else is a bug: `apiHandler` logs it and answers 500.
43
29
  4. Authorization is server-side on every request. A hidden button is not a permission. Another user's row answers 404, never 403.
@@ -59,29 +45,17 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
59
45
  - A design change lands in the component and its stories (narrow and wide) in the same change, and carries to every component that shows the same thing.
60
46
  - Stories live beside their component as `*.stories.tsx` and render the real components from fixture data; a story never hand-builds a look. `PHONE` (390px) and `SMALL_PHONE` (320px) from `@wwchen/stack/storybook` open a story narrow, and the toolbar switches light and dark.
61
47
 
62
- ## Database rules
63
-
64
- - Drizzle schema and migrations: generate with `pnpm db:generate <name>`, review the SQL, never edit a generated migration by hand. Every migration is expand-then-contract, because the old deployment serves while the build migrates.
65
- - Migrations run in the Vercel build (`stack vercel-build`) or as an explicit command, never on app boot. A preview build migrates its own Neon branch and refuses production's endpoint; a production build migrates production's database before building.
66
- - The app uses `pg` on the pooled `DATABASE_URL`; migrations use `DATABASE_URL_UNPOOLED` when set.
67
- - Dev and preview branches come from `seed`, never from production, so other people's data stays out of dev and previews. Previews get their own secrets and no production third-party keys.
68
- - Money, if any, is stored as integer minor units, never floats.
69
- - Every user has an email: required, unique, lower-cased and trimmed.
70
-
71
48
  ## Security rules
72
49
 
73
50
  1. `CRON_SECRET` can only trigger scheduled jobs (counts-only responses); admin and data access never accept it.
74
51
  2. No free text from URLs is ever rendered; redirects carry short codes.
75
- 3. Sign-in links are single-use and expire; OAuth `state` is signed and bound to the browser that started the flow.
76
- 4. Sessions: HttpOnly, Secure (when https), SameSite=Lax; mutations require JSON and same-origin.
77
- 5. Anti-enumeration on magic links; hashed tokens.
78
- 6. Local tooling refuses the production database unless explicitly opted in.
79
- 7. Connected-account tokens are encrypted at rest (AES-256-GCM); Better Auth never stores third-party API tokens.
80
- 8. Other people's data stays out of dev and previews.
81
- 9. Never commit secrets, `.env` or build output. No deployment's domain, Neon project id or key in the repo: code, docs and this file name variables (`APP_URL`, `EMAIL_FROM`, `NEON_PROJECT_ID`), never a value. `.env.example` is committed and stays in sync; `.env` never is.
52
+ 3. Mutations require JSON and same-origin.
53
+ 4. Connected-account tokens are encrypted at rest (AES-256-GCM).
54
+ 5. Previews get their own secrets and no production third-party keys.
55
+ 6. Never commit secrets, `.env` or build output. No deployment's domain or key in the repo: code, docs and this file name variables (`APP_URL`), never a value. `.env.example` is committed and stays in sync; `.env` never is.
82
56
 
83
57
  ## Non-negotiable
84
58
 
85
- 1. Never commit secrets or `.env`. Never edit a generated migration by hand.
59
+ 1. Never commit secrets or `.env`.
86
60
  2. Never mark a task done with a failing gate command.
87
61
  3. Never merge a pull request into `main` for the owner. Open the PR, get its checks green, and stop; the owner merges.
@@ -2,29 +2,12 @@
2
2
 
3
3
  # Public URL of this deployment (default http://localhost:3000; on Vercel, derived from its domain when unset)
4
4
  APP_URL=
5
- # Pooled Postgres URL (required)
6
- DATABASE_URL=
7
- # Direct (unpooled) URL, used by migrations when set
8
- DATABASE_URL_UNPOOLED=
9
- # Production database host, so local tooling can refuse it
10
- PRODUCTION_DATABASE_HOST=
11
- # Signs session cookies and tokens, at least 32 characters (required in production)
12
- BETTER_AUTH_SECRET=
13
- # Sign-in mail through Resend (required in production; elsewhere the link goes to the sink file)
14
- RESEND_API_KEY=
15
- # Sender on a domain verified in Resend (required in production)
16
- EMAIL_FROM=
17
- # Where development writes sign-in links (default .magic-links.log)
18
- MAGIC_LINK_SINK_PATH=
19
5
  # Bearer secret for scheduled jobs only
20
6
  CRON_SECRET=
21
7
  # Encrypts connected-account tokens: openssl rand -base64 32. Keep it forever (a new key orphans every token)
22
8
  TOKEN_ENCRYPTION_KEY=
23
- # Bearer token for the health route's database probe
9
+ # Bearer token for the health route's detailed checks
24
10
  HEALTH_TOKEN=
25
- # Sign in with Google: set both or neither
26
- GOOGLE_CLIENT_ID=
27
- GOOGLE_CLIENT_SECRET=
28
11
  # Proxy hops to trust for the client IP (0 on Vercel)
29
12
  TRUSTED_PROXY_HOPS=
30
13
  # Log level (default info)
package/blocks/gitignore CHANGED
@@ -7,13 +7,6 @@ next-env.d.ts
7
7
  .vercel
8
8
  storybook-static
9
9
 
10
- # Local state
11
- .neon
12
- .pglite/
13
- .pglite.lock
14
- .local-db/
15
- .magic-links.log
16
-
17
- # Secrets: only the example is committed. Keep this last.
10
+ # Secrets: only the example is committed. No pattern after these may match `.env.example`.
18
11
  .env*
19
12
  !.env.example
@@ -0,0 +1,7 @@
1
+ import { type StackPackage } from "../stack/contracts.ts";
2
+ /** `sync`'s second name, which the copier-update workflow and the tests of apps made before 0.11 run; the bare `stack` lists the command once, as `sync`. */
3
+ export declare const SYNC_SECOND_NAME = "sync-blocks";
4
+ /**
5
+ * The core's own commands, checks, doctor check, blocks and files, as the package the host always runs first: `sync` (also run as `sync-blocks`), which loads its module when it runs and writes every composed package's blocks, files and generated modules; `check`, which loads its module when it runs, checks that sync is current and runs every package's checks; its checks that the app has the files its owned files import; the check of the core's secrets, which a hosting package's `stack doctor` runs; the core's blocks; `next.config.ts`, the health route and its UI rules, which it owns; and its env fragment, for the app's generated env module.
6
+ */
7
+ export declare function builtinPackage(): StackPackage;
@@ -0,0 +1,42 @@
1
+ import { BLOCK_FILES, BUILTIN_PACKAGE, CORE_PACKAGE, packageBlocks, starterFileChecks, } from "../stack/contracts.js";
2
+ /** The package's `blocks/`, beside `src/` and `dist/`, so one relative path serves both and an installed package. */
3
+ const BLOCKS = new URL("../../blocks/", import.meta.url);
4
+ /** The package's `files/`, which mirrors the app's paths, beside `src/` and `dist/`. */
5
+ const FILES = new URL("../../files/", import.meta.url);
6
+ /** The core's secrets, which a preview must hold its own values of. */
7
+ const PREVIEW_OWN_SECRETS = [
8
+ "CRON_SECRET",
9
+ "TOKEN_ENCRYPTION_KEY",
10
+ ];
11
+ /** `stack doctor`'s check of the core's secrets, which a preview must hold its own values of, never production's (runbook §3); named, so a failure names it. The Vercel reader loads only when the doctor runs it. */
12
+ const previewOwnSecrets = async (facts) => (await import("../vercel/index.js")).previewOwnSecretsCheck(PREVIEW_OWN_SECRETS)(facts);
13
+ /** The files the core owns in an app, each read from `files/` at its own path. */
14
+ const OWNED_FILES = [
15
+ "next.config.ts",
16
+ "src/app/api/health/route.ts",
17
+ ".claude/rules/stack-ui.md",
18
+ ];
19
+ /** `sync`'s second name, which the copier-update workflow and the tests of apps made before 0.11 run; the bare `stack` lists the command once, as `sync`. */
20
+ export const SYNC_SECOND_NAME = "sync-blocks";
21
+ /** The app's own files the core's owned files import: the health route's `env` (`@/lib/env`) and `next.config.ts`'s `next.config.app.ts`. */
22
+ const STARTER_FILES = ["src/lib/env.ts", "next.config.app.ts"];
23
+ /** The section of the core's README that shows its starter files. */
24
+ const STARTER_SECTION = "Files the app writes";
25
+ /**
26
+ * The core's own commands, checks, doctor check, blocks and files, as the package the host always runs first: `sync` (also run as `sync-blocks`), which loads its module when it runs and writes every composed package's blocks, files and generated modules; `check`, which loads its module when it runs, checks that sync is current and runs every package's checks; its checks that the app has the files its owned files import; the check of the core's secrets, which a hosting package's `stack doctor` runs; the core's blocks; `next.config.ts`, the health route and its UI rules, which it owns; and its env fragment, for the app's generated env module.
27
+ */
28
+ export function builtinPackage() {
29
+ return {
30
+ name: BUILTIN_PACKAGE,
31
+ commands: {
32
+ sync: async () => (await import("./sync.js")).syncCommand,
33
+ [SYNC_SECOND_NAME]: async () => (await import("./sync.js")).syncCommand,
34
+ check: async () => (await import("./check.js")).checkCommand,
35
+ },
36
+ checks: starterFileChecks(CORE_PACKAGE, STARTER_SECTION, STARTER_FILES),
37
+ doctorChecks: [previewOwnSecrets],
38
+ blocks: packageBlocks(BLOCKS, Object.values(BLOCK_FILES)),
39
+ files: OWNED_FILES.map((path) => ({ path, source: new URL(path, FILES) })),
40
+ runtime: { env: { from: "@wwchen/stack/env", name: "coreEnv" } },
41
+ };
42
+ }
@@ -0,0 +1,5 @@
1
+ import { type Command } from "../stack/contracts.ts";
2
+ /**
3
+ * `stack check`: `stack sync --check`, then every composed package's checks in package order, all of them even after a failure. Each failure prints as `<package>: <check>: <message>` on stderr; exit 1 when any failed.
4
+ */
5
+ export declare const checkCommand: Command;
@@ -0,0 +1,39 @@
1
+ import { CORE_PACKAGE } from "../stack/contracts.js";
2
+ import { CliError } from "./context.js";
3
+ import { ownerOf, syncCommand } from "./sync.js";
4
+ /** What a thrown value says: an Error's message, anything else as text. */
5
+ const messageOf = (thrown) => (thrown instanceof Error ? thrown.message : String(thrown));
6
+ /**
7
+ * `stack check`: `stack sync --check`, then every composed package's checks in package order, all of them even after a failure. Each failure prints as `<package>: <check>: <message>` on stderr; exit 1 when any failed.
8
+ */
9
+ export const checkCommand = async (ctx, args) => {
10
+ if (args.length > 0)
11
+ throw new CliError(`check: unknown argument ${args[0]}`);
12
+ const failures = [];
13
+ try {
14
+ if ((await syncCommand(ctx, ["--check"])) !== 0) {
15
+ failures.push(`${CORE_PACKAGE}: sync --check: files are stale: run \`stack sync\``);
16
+ }
17
+ }
18
+ catch (error) {
19
+ failures.push(`${CORE_PACKAGE}: sync --check: ${messageOf(error)}`);
20
+ }
21
+ for (const pkg of ctx.packages) {
22
+ for (const check of pkg.checks ?? []) {
23
+ try {
24
+ await check.run(ctx);
25
+ }
26
+ catch (error) {
27
+ failures.push(`${ownerOf(pkg)}: ${check.name}: ${messageOf(error)}`);
28
+ }
29
+ }
30
+ }
31
+ if (failures.length === 0) {
32
+ ctx.log("stack check: all passed");
33
+ return 0;
34
+ }
35
+ for (const failure of failures)
36
+ ctx.error(failure);
37
+ ctx.error(`stack check: ${failures.length} failed`);
38
+ return 1;
39
+ };
@@ -1,28 +1,9 @@
1
- /** The stack's own package.json: the installed version, and the suite packages it depends on. It sits two levels above both `src/cli/` and `dist/cli/`. */
1
+ import type { Env, ExecOptions, ExecResult } from "../stack/contracts.ts";
2
+ /** The stack's own package.json, for the installed version. It sits two levels above both `src/cli/` and `dist/cli/`. */
2
3
  export declare const STACK_PACKAGE: {
3
4
  version: string;
4
- dependencies: Record<string, string>;
5
- };
6
- export type Env = Record<string, string | undefined>;
7
- export type ExecResult = {
8
- stdout: string;
9
- code: number;
10
- };
11
- export type ExecOptions = {
12
- /** The child's environment; defaults to the CLI's own. */
13
- env?: Env;
14
- /** Hand the child this terminal (a dev server, a build) instead of capturing its stdout. */
15
- inherit?: boolean;
16
- /**
17
- * Written to the child's stdin, then closed: how a secret reaches another CLI without appearing in its arguments. Pass a value already held in full, never a stream still arriving: a CLI that reads stdin at start-up takes whatever is there, which may be nothing yet.
18
- */
19
- input?: string;
20
- };
21
- /** A Postgres served on loopback for `stack dev --pglite`. */
22
- export type LocalDatabase = {
23
- url: string;
24
- stop(): Promise<void>;
25
5
  };
6
+ export type { Env, ExecOptions, ExecResult };
26
7
  /**
27
8
  * Everything the CLI touches outside its own process, so a test can replace it. Only the entry point reads `process.env`: it passes it in as `env`, and nothing below reads it directly. `exec` runs a program with an argument array, never a shell string.
28
9
  */
@@ -30,25 +11,13 @@ export type CliDeps = {
30
11
  env: Env;
31
12
  exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
32
13
  cwd: string;
33
- /** The OS user, for the default `dev/<user>` branch name. */
34
- username?: string;
35
14
  log?(message: string): void;
36
15
  error?(message: string): void;
37
- /** Imports the app's own TypeScript (`src/lib/auth.ts`, `db/seed.ts`) with Node's type stripping. */
16
+ /** Imports the app's own TypeScript (`stack.config.ts`, a package's `./stack` entry) with Node's type stripping. */
38
17
  importModule?(specifier: string): Promise<Record<string, unknown>>;
39
- /** Runs one SQL statement against a database, for emptying the new `seed` branch. */
40
- sql?(url: string, statement: string): Promise<Record<string, unknown>[]>;
41
- /** The Node binary `stack run` starts an app script with. */
42
- execPath?: string;
43
- /**
44
- * Serves PGlite on a free loopback port with its data in `dataDir`, for `stack dev --pglite`. PGlite and pglite-socket are loaded from the app (its devDependencies), never from this package.
45
- */
46
- startLocalDatabase?(dataDir: string): Promise<LocalDatabase>;
47
18
  };
48
19
  export type Cli = Required<CliDeps>;
49
20
  export declare function resolveDeps(deps: CliDeps): Cli;
50
- /** Loads the app's `.env` (or the file `ENV_FILE` names) into `env`; real variables always win. */
51
- export declare function loadAppEnv(cli: Cli): void;
52
21
  /** Imports a file of the app by path relative to its root. */
53
22
  export declare function importApp(cli: Cli, path: string): Promise<Record<string, unknown>>;
54
23
  /** A failure the CLI reports as one line and a non-zero exit, with no stack trace. */
@@ -7,40 +7,18 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
7
7
  return path;
8
8
  };
9
9
  import { readFileSync } from "node:fs";
10
- import { userInfo } from "node:os";
11
10
  import { join } from "node:path";
12
11
  import { pathToFileURL } from "node:url";
13
- import pg from "pg";
14
- import { explicitSslMode } from "../db/ssl.js";
15
- import { startPgliteServer } from "../db/testing/pglite.js";
16
- import { loadEnvFile } from "../env/index.js";
17
- /** The stack's own package.json: the installed version, and the suite packages it depends on. It sits two levels above both `src/cli/` and `dist/cli/`. */
12
+ /** The stack's own package.json, for the installed version. It sits two levels above both `src/cli/` and `dist/cli/`. */
18
13
  export const STACK_PACKAGE = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
19
14
  export function resolveDeps(deps) {
20
15
  return {
21
16
  log: (message) => console.log(message),
22
17
  error: (message) => console.error(message),
23
- username: userInfo().username,
24
- execPath: process.execPath,
25
- startLocalDatabase: (dataDir) => startPgliteServer({ dataDir, resolveFrom: deps.cwd }),
26
18
  importModule: (specifier) => import(__rewriteRelativeImportExtension(specifier)),
27
- sql: async (url, statement) => {
28
- const client = new pg.Client({ connectionString: explicitSslMode(url) });
29
- await client.connect();
30
- try {
31
- return (await client.query(statement)).rows;
32
- }
33
- finally {
34
- await client.end();
35
- }
36
- },
37
19
  ...deps,
38
20
  };
39
21
  }
40
- /** Loads the app's `.env` (or the file `ENV_FILE` names) into `env`; real variables always win. */
41
- export function loadAppEnv(cli) {
42
- loadEnvFile(cli.env.ENV_FILE?.trim() ? undefined : join(cli.cwd, ".env"), cli.env);
43
- }
44
22
  /** Imports a file of the app by path relative to its root. */
45
23
  export function importApp(cli, path) {
46
24
  return cli.importModule(pathToFileURL(join(cli.cwd, path)).href);
@@ -0,0 +1,15 @@
1
+ /** A stack package an app lists and has installed. */
2
+ export type Installed = {
3
+ name: string;
4
+ version: string;
5
+ /** The installed package's real path. */
6
+ dir: string;
7
+ /** The file the app resolves for `<name>/stack`. */
8
+ entry: string;
9
+ /** The stack packages among its non-optional peers. */
10
+ needs: string[];
11
+ };
12
+ /**
13
+ * The stack packages the app at `cwd` lists in `dependencies` and `devDependencies`, each after the ones it needs (ties by name). Refuses with a `CliError` when `cwd` has no package.json, a listed package is not installed, a package is not at `coreVersion`, a stack peer is not listed, packages need each other, a package.json does not parse, or a package's `./stack` entry does not exist.
14
+ */
15
+ export declare function discover(cwd: string, coreVersion: string): Installed[];