@wwchen/stack 0.7.1 → 0.9.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.
- package/README.md +2 -6
- package/blocks/AGENTS.md +2 -2
- package/blocks/CLAUDE.md +3 -3
- package/blocks/env.example +0 -2
- package/dist/cli/db.d.ts +1 -0
- package/dist/cli/db.js +18 -1
- package/dist/cli/index.js +4 -1
- package/dist/cli/migrate-suite.js +3 -299
- package/dist/db/schema-changes.js +1 -1
- package/dist/env/stack-env.d.ts +0 -1
- package/dist/env/stack-env.js +1 -3
- package/package.json +6 -19
- package/dist/auth/better-auth/index.d.ts +0 -2
- package/dist/auth/better-auth/index.js +0 -2
- package/dist/auth/index.d.ts +0 -2
- package/dist/auth/index.js +0 -2
- package/dist/auth/proxy.d.ts +0 -2
- package/dist/auth/proxy.js +0 -2
- package/dist/mail/index.d.ts +0 -4
- package/dist/mail/index.js +0 -4
package/README.md
CHANGED
|
@@ -11,10 +11,6 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
|
|
|
11
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
12
|
| `@wwchen/stack/db` | the pooled client, `migrationStatus`, the dev-database guard that refuses production |
|
|
13
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/mail` | deprecated: re-exports [`@wwchen/stack-notify`](../notify); import that instead |
|
|
15
|
-
| `@wwchen/stack/auth` | deprecated: re-exports [`@wwchen/stack-auth`](../auth); import that instead |
|
|
16
|
-
| `@wwchen/stack/auth/better-auth` | deprecated: re-exports `@wwchen/stack-auth/better-auth`; import that instead |
|
|
17
|
-
| `@wwchen/stack/auth/proxy` | deprecated: re-exports `@wwchen/stack-auth/proxy`; import that instead |
|
|
18
14
|
| `@wwchen/stack/next` | `withStack(appConfig)` for `next.config.ts`, `apiHandler` and `readJson`, `cronRoute` (answers 500 when the job returns `alerting: true`) and `healthRoute` |
|
|
19
15
|
| `@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` |
|
|
20
16
|
| `@wwchen/stack/jobs` | multi-person scheduled jobs: `failingSince` and `isNewFailure` (alert on a failure's first 24 hours only), `mapLimit` |
|
|
@@ -23,7 +19,7 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
|
|
|
23
19
|
| `@wwchen/stack/configs/tsconfig.next.json`, `/configs/biome.json`, `/configs/vitest` | shared tool configs, consumed with `extends` or an import |
|
|
24
20
|
| `@wwchen/stack/testing/next` | tests only: `inServerAction` runs a function in a real Next server-action scope, `thrownBy` reads a `redirect()`/`notFound()` |
|
|
25
21
|
|
|
26
|
-
|
|
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.
|
|
27
23
|
|
|
28
24
|
### Connected accounts
|
|
29
25
|
|
|
@@ -62,7 +58,7 @@ The callback lands on `next` with `?connection=<provider>&result=<code>`, where
|
|
|
62
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") |
|
|
63
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 |
|
|
64
60
|
| `stack sync-blocks [--check]` | refreshes the stack blocks in `AGENTS.md`, `CLAUDE.md`, `.gitignore`, `.env.example` |
|
|
65
|
-
| `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
|
|
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 |
|
|
66
62
|
|
|
67
63
|
`NEON_PROJECT_ID` comes from the environment; nothing in the package names a project or domain.
|
|
68
64
|
|
package/blocks/AGENTS.md
CHANGED
|
@@ -55,7 +55,7 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
|
|
|
55
55
|
- Local tooling refuses the production database unless you opt in deliberately.
|
|
56
56
|
- Tests run on PGlite (one connection only) and, in CI, a real Postgres.
|
|
57
57
|
- Every user has an email: required, unique, lower-cased and trimmed.
|
|
58
|
-
- Schema changes go through `pnpm db:generate
|
|
58
|
+
- Schema changes go through `pnpm db:generate <name>` and a reviewed migration, never through the Neon console or a database MCP server.
|
|
59
59
|
|
|
60
60
|
## Security
|
|
61
61
|
|
|
@@ -63,7 +63,7 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
|
|
|
63
63
|
2. Never render free text from a URL; redirects carry short codes.
|
|
64
64
|
3. Sign-in links are single-use and expire. OAuth `state` is signed and bound to the browser that started the flow.
|
|
65
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
|
|
66
|
+
5. Magic links are anti-enumeration, with hashed tokens.
|
|
67
67
|
6. Connected-account tokens are encrypted at rest; Better Auth never stores third-party API tokens.
|
|
68
68
|
7. Previews get their own secrets and no production third-party keys.
|
|
69
69
|
8. Never write a deployment's domain in the repo. Name variables (`APP_URL`, `EMAIL_FROM`), never a host.
|
package/blocks/CLAUDE.md
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
| Lint / format | `pnpm lint` · `pnpm lint:fix` |
|
|
15
15
|
| Tests | `pnpm test` · one file: `pnpm test tests/unit/<name>.test.ts` |
|
|
16
16
|
| Storybook | `pnpm storybook` (http://localhost:6006) · every story built, as CI does: `pnpm storybook:build` |
|
|
17
|
-
| DB generate / apply migration | `pnpm db:generate` · `pnpm db:migrate` |
|
|
17
|
+
| DB generate / apply migration | `pnpm db:generate <name>` (snake_case, what it does: `add_widgets`) · `pnpm db:migrate` |
|
|
18
18
|
| Seed the shared `seed` branch | `stack neon seed` (runs the app's `db/seed.ts`) |
|
|
19
19
|
| Reset the shared preview branch | `stack neon reset-preview` (`--set-vercel` also writes its URLs into Vercel's Preview variables) |
|
|
20
20
|
| Check the Vercel project's setup | `stack doctor` (read-only; exits 1 on an error) |
|
|
@@ -60,7 +60,7 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
|
|
|
60
60
|
|
|
61
61
|
## Database rules
|
|
62
62
|
|
|
63
|
-
- Drizzle schema and migrations: generate with `pnpm db:generate
|
|
63
|
+
- 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.
|
|
64
64
|
- 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.
|
|
65
65
|
- The app uses `pg` on the pooled `DATABASE_URL`; migrations use `DATABASE_URL_UNPOOLED` when set.
|
|
66
66
|
- 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.
|
|
@@ -73,7 +73,7 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
|
|
|
73
73
|
2. No free text from URLs is ever rendered; redirects carry short codes.
|
|
74
74
|
3. Sign-in links are single-use and expire; OAuth `state` is signed and bound to the browser that started the flow.
|
|
75
75
|
4. Sessions: HttpOnly, Secure (when https), SameSite=Lax; mutations require JSON and same-origin.
|
|
76
|
-
5. Anti-enumeration on magic links; hashed tokens
|
|
76
|
+
5. Anti-enumeration on magic links; hashed tokens.
|
|
77
77
|
6. Local tooling refuses the production database unless explicitly opted in.
|
|
78
78
|
7. Connected-account tokens are encrypted at rest (AES-256-GCM); Better Auth never stores third-party API tokens.
|
|
79
79
|
8. Other people's data stays out of dev and previews.
|
package/blocks/env.example
CHANGED
package/dist/cli/db.d.ts
CHANGED
package/dist/cli/db.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// `stack db:check` — fails when the app's `src/db/schema.ts` has changes `drizzle/` has no migration for: a package table that changed in an upgrade, or the app's own, never generated. App CI runs it.
|
|
2
2
|
//
|
|
3
|
+
// `stack db:generate <name> [drizzle-kit flags]` — the app's `pnpm db:generate`: drizzle-kit generate with a name the person chose, so `drizzle/` says what each migration does instead of drizzle-kit's random words. Flags after the name pass through (`--custom` for an empty migration to write by hand).
|
|
4
|
+
//
|
|
3
5
|
// `stack db:upgrade` — after the stack is upgraded, generates the migration for its tables' changes (`stack_<version>`), so the app's one history carries them. Copier runs it after `pnpm install`.
|
|
4
6
|
//
|
|
5
7
|
// Both run in the app's root and import its schema with Node's type stripping, so it must use relative `.ts` imports.
|
|
@@ -14,9 +16,24 @@ export async function dbCheck(cli) {
|
|
|
14
16
|
const statements = await pending(cli);
|
|
15
17
|
if (statements.length === 0)
|
|
16
18
|
return 0;
|
|
17
|
-
cli.error(`src/db/schema.ts has changes drizzle/ has no migration for:\n\n${statements.join("\n")}\n\nRun \`pnpm
|
|
19
|
+
cli.error(`src/db/schema.ts has changes drizzle/ has no migration for:\n\n${statements.join("\n")}\n\nRun \`pnpm db:generate <name>\`, review the SQL and commit it.`);
|
|
18
20
|
return 1;
|
|
19
21
|
}
|
|
22
|
+
/** A name says what the migration does, in snake_case. `stack_` is the upgrade's, so an app's own migration never reads as the stack's. */
|
|
23
|
+
const MIGRATION_NAME = /^[a-z][a-z0-9_]*$/;
|
|
24
|
+
export async function dbGenerate(cli, [name, ...flags]) {
|
|
25
|
+
if (!name || !MIGRATION_NAME.test(name)) {
|
|
26
|
+
cli.error("usage: stack db:generate <name> [drizzle-kit flags]\nName the migration for what it does, in snake_case: add_widgets, drop_legacy_tokens.");
|
|
27
|
+
return 2;
|
|
28
|
+
}
|
|
29
|
+
if (name.startsWith("stack_")) {
|
|
30
|
+
cli.error(`${name}: names starting stack_ are the stack upgrade's own; name the change itself.`);
|
|
31
|
+
return 2;
|
|
32
|
+
}
|
|
33
|
+
return (await cli.exec("pnpm", ["exec", "drizzle-kit", "generate", "--name", name, ...flags], {
|
|
34
|
+
inherit: true,
|
|
35
|
+
})).code;
|
|
36
|
+
}
|
|
20
37
|
export async function dbUpgrade(cli) {
|
|
21
38
|
if ((await pending(cli)).length === 0)
|
|
22
39
|
return 0;
|
package/dist/cli/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import { spawn } from "node:child_process";
|
|
|
3
3
|
import { realpathSync } from "node:fs";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { CliError, resolveDeps } from "./context.js";
|
|
6
|
-
import { dbCheck, dbUpgrade } from "./db.js";
|
|
6
|
+
import { dbCheck, dbGenerate, dbUpgrade } from "./db.js";
|
|
7
7
|
import { dev } from "./dev.js";
|
|
8
8
|
import { doctor } from "./doctor.js";
|
|
9
9
|
import { migrateSuite } from "./migrate-suite.js";
|
|
@@ -27,6 +27,7 @@ const USAGE = `usage: stack <command>
|
|
|
27
27
|
user:role <email> <admin|user> change a user's role through the app's auth; --preview as above
|
|
28
28
|
sync-blocks [--check] refresh the stack-owned blocks in AGENTS.md, CLAUDE.md, .gitignore, .env.example
|
|
29
29
|
db:check fail when src/db/schema.ts has changes drizzle/ has no migration for
|
|
30
|
+
db:generate <name> [flags] drizzle-kit generate, named for what the migration does (snake_case)
|
|
30
31
|
db:upgrade generate drizzle/'s migration for the schema's changes, named stack_<version>
|
|
31
32
|
migrate-suite [--expect <version>] move the app onto the suite's packages (@wwchen/stack-auth, -notify);
|
|
32
33
|
--expect: refuse unless the installed stack is that version`;
|
|
@@ -62,6 +63,8 @@ export async function runCli(argv, deps) {
|
|
|
62
63
|
return await syncBlocksCommand(cli, args);
|
|
63
64
|
case "db:check":
|
|
64
65
|
return await dbCheck(cli);
|
|
66
|
+
case "db:generate":
|
|
67
|
+
return await dbGenerate(cli, args);
|
|
65
68
|
case "db:upgrade":
|
|
66
69
|
return await dbUpgrade(cli);
|
|
67
70
|
case "migrate-suite":
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
// `stack migrate-suite [--expect <version>]` — moves an app onto the suite's packages, as the installed stack knows them: adds the `@wwchen/stack-*` packages to package.json and to pnpm-workspace.yaml's release-age exemptions, moves imports of the stack's old paths to them
|
|
1
|
+
// `stack migrate-suite [--expect <version>]` — moves an app onto the suite's packages, as the installed stack knows them: adds the `@wwchen/stack-*` packages to package.json and to pnpm-workspace.yaml's release-age exemptions, and moves imports of the stack's old paths to them. Copier runs it after `pnpm install`; it changes nothing on an app already moved.
|
|
2
2
|
//
|
|
3
3
|
// Imports are found with the TypeScript compiler API, never by searching text: a comment or a string that names an old path stays as it is. Every change is worked out before any file is written.
|
|
4
|
-
//
|
|
5
|
-
// It exits non-zero, after making every change it can, when the auth provider would get the `rate_limit` table from `authTables()` while the schema does not export it: drizzle-kit would never create the table and every sign-in would answer `unavailable`, so the upgrade must fail where someone sees it.
|
|
6
4
|
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
5
|
import { dirname, join, relative, sep } from "node:path";
|
|
8
6
|
import { CliError, STACK_PACKAGE } from "./context.js";
|
|
@@ -27,12 +25,6 @@ const VI_MODULE_CALLS = new Set([
|
|
|
27
25
|
]);
|
|
28
26
|
/** The one name `@wwchen/stack/mail` exports that lives in auth, not notify. */
|
|
29
27
|
const MAGIC = "waitForMagicLink";
|
|
30
|
-
const BETTER_AUTH = new Set(["@wwchen/stack/auth/better-auth", `${AUTH}/better-auth`]);
|
|
31
|
-
const SCHEMA = "src/db/schema.ts";
|
|
32
|
-
const AUTH_FILE = "src/lib/auth.ts";
|
|
33
|
-
const SCHEMA_IMPORT = "../db/schema.ts";
|
|
34
|
-
const TEMPLATE_TABLES = ["account", "appUser", "session", "verification"];
|
|
35
|
-
const RATE_LIMIT = "rateLimit";
|
|
36
28
|
const STACK_PACKAGE_NAME = "@wwchen/stack";
|
|
37
29
|
const WORKSPACE = "pnpm-workspace.yaml";
|
|
38
30
|
const RELEASE_AGE_EXCLUDE = "minimumReleaseAgeExclude";
|
|
@@ -57,11 +49,6 @@ export async function migrateSuite(cli, args) {
|
|
|
57
49
|
writes.set(path, moved.text);
|
|
58
50
|
}
|
|
59
51
|
const moved = [...writes.keys()];
|
|
60
|
-
const current = (path) => writes.get(path) ??
|
|
61
|
-
(existsSync(join(cli.cwd, path)) ? readFileSync(join(cli.cwd, path), "utf8") : undefined);
|
|
62
|
-
const tables = rateLimitEdits(ts, current(SCHEMA), current(AUTH_FILE), new Set(moved));
|
|
63
|
-
for (const [path, text] of Object.entries(tables.writes))
|
|
64
|
-
writes.set(path, text);
|
|
65
52
|
const workspacePath = join(cli.cwd, WORKSPACE);
|
|
66
53
|
const workspace = releaseAgeEdit(existsSync(workspacePath) ? readFileSync(workspacePath, "utf8") : undefined, suitePackages(packages.text));
|
|
67
54
|
if (packages.added.length > 0)
|
|
@@ -82,7 +69,7 @@ export async function migrateSuite(cli, args) {
|
|
|
82
69
|
if (moved.length > 0) {
|
|
83
70
|
lines.push(`imports moved to the suite's packages in ${moved.length} ${moved.length === 1 ? "file" : "files"}:`, ...moved.sort().map((path) => ` ${path}`));
|
|
84
71
|
}
|
|
85
|
-
lines.push(...
|
|
72
|
+
lines.push(...notes);
|
|
86
73
|
if (!sorted) {
|
|
87
74
|
lines.push("Biome could not sort the imports of the files above; run `pnpm lint:fix`.");
|
|
88
75
|
}
|
|
@@ -101,10 +88,7 @@ export async function migrateSuite(cli, args) {
|
|
|
101
88
|
if (code !== 0)
|
|
102
89
|
cli.error("migrate-suite: pnpm install failed; run it again in the app.");
|
|
103
90
|
}
|
|
104
|
-
|
|
105
|
-
return code;
|
|
106
|
-
cli.error(`migrate-suite: ${tables.refusal}`);
|
|
107
|
-
return code === 0 ? 1 : code;
|
|
91
|
+
return code;
|
|
108
92
|
}
|
|
109
93
|
function parseArgs(args) {
|
|
110
94
|
if (args.length === 0)
|
|
@@ -332,17 +316,6 @@ function applyEdits(text, edits) {
|
|
|
332
316
|
return out;
|
|
333
317
|
}
|
|
334
318
|
const newlines = (text) => text.split("\n").length - 1;
|
|
335
|
-
/** An edit made against the whole file, moved to apply to the slice of it that starts at `offset`. */
|
|
336
|
-
const within = (edit, offset) => ({
|
|
337
|
-
...edit,
|
|
338
|
-
start: edit.start - offset,
|
|
339
|
-
end: edit.end - offset,
|
|
340
|
-
});
|
|
341
|
-
/** A statement's text with `edits` applied, for a line to print. */
|
|
342
|
-
const statementWith = (sf, node, edits) => {
|
|
343
|
-
const start = node.getStart(sf);
|
|
344
|
-
return applyEdits(sf.text.slice(start, node.end), edits.map((edit) => within(edit, start)));
|
|
345
|
-
};
|
|
346
319
|
/** Moves every import and export specifier (static, dynamic, `import type`, `import x = require`) off the old paths. Comments and other strings are never changed; a string that is exactly an old path is pointed out. */
|
|
347
320
|
function moveImports(ts, path, text) {
|
|
348
321
|
const sf = parse(ts, path, text);
|
|
@@ -516,272 +489,3 @@ function splitMail(ts, sf, decl) {
|
|
|
516
489
|
const notifyPart = applyEdits(original, [{ ...names, text: list(rest) }, specifier(NOTIFY)]);
|
|
517
490
|
return { start, end: decl.end, text: `${authPart}\n${indent}${notifyPart}` };
|
|
518
491
|
}
|
|
519
|
-
/**
|
|
520
|
-
* Adds `rateLimit` to the schema's `authTables()` export and to auth's `tables` and its import, each only when it has exactly the template's shape; otherwise the file is left as it is and the lines to write are given. Auth is edited only once the schema exports the table. A refusal when auth hands the provider an `authTables()` result, which carries the table, and the schema will not export it.
|
|
521
|
-
*/
|
|
522
|
-
function rateLimitEdits(ts, schemaText, authText, moved) {
|
|
523
|
-
const result = { writes: {}, done: [], manual: [] };
|
|
524
|
-
const heldBack = (path) => `rateLimit is not added to it${moved.has(path) ? " (only its imports were moved)" : ""}`;
|
|
525
|
-
if (schemaText === undefined)
|
|
526
|
-
return result;
|
|
527
|
-
const schema = schemaEdit(ts, schemaText);
|
|
528
|
-
if (schema.kind === "edit") {
|
|
529
|
-
result.writes[SCHEMA] = schema.text;
|
|
530
|
-
result.done.push(`${SCHEMA}: exports rateLimit`);
|
|
531
|
-
}
|
|
532
|
-
else if (schema.kind === "manual") {
|
|
533
|
-
result.manual.push(`${SCHEMA} does not have the template's shape, so ${heldBack(SCHEMA)}. Export the rate_limit table by hand, ${schema.replace ? "so this line reads" : "adding this line"}:`, ...schema.lines.map((line) => ` ${line}`));
|
|
534
|
-
}
|
|
535
|
-
if (authText === undefined)
|
|
536
|
-
return result;
|
|
537
|
-
const auth = authEdit(ts, authText);
|
|
538
|
-
if (auth.kind === "has")
|
|
539
|
-
return result;
|
|
540
|
-
if (auth.kind === "carries") {
|
|
541
|
-
if (schema.kind === "manual") {
|
|
542
|
-
result.refusal = `${AUTH_FILE} gives betterAuthProvider the rate_limit table from authTables(), and ${SCHEMA} does not export it: every sign-in would answer \`unavailable\` until the table is exported and migrated. Make ${SCHEMA} read as printed above, run this command again, then \`pnpm exec stack db:upgrade\` and \`pnpm exec stack sync-blocks\`, and commit the migration with the rest. As a Copier task, this stopped \`copier update\` before it put back the app's own changes to the template's files, so commit nothing from this run: discard it (\`git reset --hard && git clean -fd\`), run \`copier update\` again with \`--skip-tasks\`, then \`pnpm install\` and the steps above.`;
|
|
543
|
-
}
|
|
544
|
-
return result;
|
|
545
|
-
}
|
|
546
|
-
if (auth.kind === "edit" && schema.kind !== "manual") {
|
|
547
|
-
result.writes[AUTH_FILE] = auth.text;
|
|
548
|
-
result.done.push(`${AUTH_FILE}: passes rateLimit to betterAuthProvider`);
|
|
549
|
-
return result;
|
|
550
|
-
}
|
|
551
|
-
result.manual.push(auth.kind === "edit"
|
|
552
|
-
? `${AUTH_FILE} gets no rateLimit until ${SCHEMA} exports it${moved.has(AUTH_FILE) ? " (only its imports were moved)" : ""}. Then make these lines read:`
|
|
553
|
-
: `${AUTH_FILE} does not have the template's shape, so ${heldBack(AUTH_FILE)}. Pass the rate_limit table to betterAuthProvider by hand, so these lines read:`, ...auth.lines.map((line) => ` ${line}`));
|
|
554
|
-
return result;
|
|
555
|
-
}
|
|
556
|
-
/** The name a file binds an export of the better-auth entry to, if it imports it. */
|
|
557
|
-
function importedFromBetterAuth(ts, sf, name) {
|
|
558
|
-
for (const statement of sf.statements) {
|
|
559
|
-
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
|
|
560
|
-
continue;
|
|
561
|
-
if (!BETTER_AUTH.has(statement.moduleSpecifier.text))
|
|
562
|
-
continue;
|
|
563
|
-
const bindings = statement.importClause?.namedBindings;
|
|
564
|
-
if (!bindings || !ts.isNamedImports(bindings))
|
|
565
|
-
continue;
|
|
566
|
-
const element = bindings.elements.find((e) => (e.propertyName ?? e.name).text === name);
|
|
567
|
-
if (element)
|
|
568
|
-
return element.name.text;
|
|
569
|
-
}
|
|
570
|
-
return undefined;
|
|
571
|
-
}
|
|
572
|
-
/** Names the file's top level binds, and those it exports. */
|
|
573
|
-
function topLevel(ts, sf) {
|
|
574
|
-
const bound = new Set();
|
|
575
|
-
const exported = new Set();
|
|
576
|
-
const bind = (name, isExported) => {
|
|
577
|
-
if (ts.isIdentifier(name)) {
|
|
578
|
-
bound.add(name.text);
|
|
579
|
-
if (isExported)
|
|
580
|
-
exported.add(name.text);
|
|
581
|
-
}
|
|
582
|
-
else {
|
|
583
|
-
for (const element of name.elements) {
|
|
584
|
-
if (!ts.isOmittedExpression(element))
|
|
585
|
-
bind(element.name, isExported);
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
};
|
|
589
|
-
for (const statement of sf.statements) {
|
|
590
|
-
const isExported = ts.canHaveModifiers(statement) &&
|
|
591
|
-
(ts.getModifiers(statement) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
|
|
592
|
-
if (ts.isImportDeclaration(statement)) {
|
|
593
|
-
const clause = statement.importClause;
|
|
594
|
-
if (clause?.name)
|
|
595
|
-
bound.add(clause.name.text);
|
|
596
|
-
const bindings = clause?.namedBindings;
|
|
597
|
-
if (bindings && ts.isNamespaceImport(bindings))
|
|
598
|
-
bound.add(bindings.name.text);
|
|
599
|
-
if (bindings && ts.isNamedImports(bindings)) {
|
|
600
|
-
for (const element of bindings.elements)
|
|
601
|
-
bound.add(element.name.text);
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
else if (ts.isVariableStatement(statement)) {
|
|
605
|
-
for (const declaration of statement.declarationList.declarations) {
|
|
606
|
-
bind(declaration.name, isExported);
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
else if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) &&
|
|
610
|
-
statement.name) {
|
|
611
|
-
bind(statement.name, isExported);
|
|
612
|
-
}
|
|
613
|
-
else if (ts.isExportDeclaration(statement) &&
|
|
614
|
-
statement.exportClause &&
|
|
615
|
-
ts.isNamedExports(statement.exportClause)) {
|
|
616
|
-
for (const element of statement.exportClause.elements)
|
|
617
|
-
exported.add(element.name.text);
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
return { bound, exported };
|
|
621
|
-
}
|
|
622
|
-
/** `, rateLimit` after the last element of a list. */
|
|
623
|
-
const appendTo = (list) => {
|
|
624
|
-
const last = list[list.length - 1];
|
|
625
|
-
return { start: last.end, end: last.end, text: `, ${RATE_LIMIT}` };
|
|
626
|
-
};
|
|
627
|
-
const isTemplateNames = (names) => names.length === TEMPLATE_TABLES.length &&
|
|
628
|
-
[...names].sort().every((name, i) => name === TEMPLATE_TABLES[i]);
|
|
629
|
-
function schemaEdit(ts, text) {
|
|
630
|
-
const sf = parse(ts, SCHEMA, text);
|
|
631
|
-
const { bound, exported } = topLevel(ts, sf);
|
|
632
|
-
if (exported.has(RATE_LIMIT))
|
|
633
|
-
return { kind: "has" };
|
|
634
|
-
const local = importedFromBetterAuth(ts, sf, "authTables");
|
|
635
|
-
// Each `export const { … } = authTables(…)`.
|
|
636
|
-
const exports = sf.statements.flatMap((statement) => {
|
|
637
|
-
if (!ts.isVariableStatement(statement))
|
|
638
|
-
return [];
|
|
639
|
-
const declaration = statement.declarationList.declarations[0];
|
|
640
|
-
const isExportedConst = (ts.getModifiers(statement) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword) &&
|
|
641
|
-
(statement.declarationList.flags & ts.NodeFlags.Const) !== 0 &&
|
|
642
|
-
statement.declarationList.declarations.length === 1;
|
|
643
|
-
if (!isExportedConst ||
|
|
644
|
-
!declaration ||
|
|
645
|
-
!ts.isObjectBindingPattern(declaration.name) ||
|
|
646
|
-
!declaration.initializer ||
|
|
647
|
-
!ts.isCallExpression(declaration.initializer) ||
|
|
648
|
-
!ts.isIdentifier(declaration.initializer.expression) ||
|
|
649
|
-
declaration.initializer.expression.text !== local) {
|
|
650
|
-
return [];
|
|
651
|
-
}
|
|
652
|
-
return [{ statement, pattern: declaration.name }];
|
|
653
|
-
});
|
|
654
|
-
const only = exports.length === 1 ? exports[0] : undefined;
|
|
655
|
-
if (only && !bound.has(RATE_LIMIT)) {
|
|
656
|
-
const { elements } = only.pattern;
|
|
657
|
-
const plain = elements.every((e) => !e.dotDotDotToken && !e.propertyName && !e.initializer && ts.isIdentifier(e.name));
|
|
658
|
-
if (plain && isTemplateNames(elements.map((e) => e.name.text))) {
|
|
659
|
-
return { kind: "edit", text: applyEdits(text, [appendTo(elements)]), lines: [] };
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
if (only && only.pattern.elements.length > 0) {
|
|
663
|
-
const line = statementWith(sf, only.statement, [appendTo(only.pattern.elements)]);
|
|
664
|
-
return { kind: "manual", lines: [line], replace: true };
|
|
665
|
-
}
|
|
666
|
-
return {
|
|
667
|
-
kind: "manual",
|
|
668
|
-
lines: [
|
|
669
|
-
...(local ? [] : [`import { authTables } from "${AUTH}/better-auth";`]),
|
|
670
|
-
`export const { ${RATE_LIMIT} } = ${local ?? "authTables"}();`,
|
|
671
|
-
],
|
|
672
|
-
replace: false,
|
|
673
|
-
};
|
|
674
|
-
}
|
|
675
|
-
function authEdit(ts, text) {
|
|
676
|
-
const sf = parse(ts, AUTH_FILE, text);
|
|
677
|
-
const provider = importedFromBetterAuth(ts, sf, "betterAuthProvider");
|
|
678
|
-
const tablesFn = importedFromBetterAuth(ts, sf, "authTables");
|
|
679
|
-
const calls = [];
|
|
680
|
-
const visit = (node) => {
|
|
681
|
-
if (ts.isCallExpression(node) &&
|
|
682
|
-
ts.isIdentifier(node.expression) &&
|
|
683
|
-
node.expression.text === provider) {
|
|
684
|
-
calls.push(node);
|
|
685
|
-
}
|
|
686
|
-
ts.forEachChild(node, visit);
|
|
687
|
-
};
|
|
688
|
-
if (provider)
|
|
689
|
-
visit(sf);
|
|
690
|
-
const options = calls.length === 1 ? calls[0]?.arguments[0] : undefined;
|
|
691
|
-
const tablesProps = options && ts.isObjectLiteralExpression(options)
|
|
692
|
-
? options.properties.filter((p) => p.name && ts.isIdentifier(p.name) && p.name.text === "tables")
|
|
693
|
-
: [];
|
|
694
|
-
const tables = tablesProps.length === 1 ? tablesProps[0] : undefined;
|
|
695
|
-
const value = tables && ts.isPropertyAssignment(tables)
|
|
696
|
-
? tables.initializer
|
|
697
|
-
: tables && ts.isShorthandPropertyAssignment(tables)
|
|
698
|
-
? tables.name
|
|
699
|
-
: undefined;
|
|
700
|
-
if (value && ts.isObjectLiteralExpression(value)) {
|
|
701
|
-
const names = value.properties.map((p) => p.name && ts.isIdentifier(p.name) ? p.name.text : "");
|
|
702
|
-
if (names.includes(RATE_LIMIT))
|
|
703
|
-
return { kind: "has" };
|
|
704
|
-
}
|
|
705
|
-
if (value && tablesFn) {
|
|
706
|
-
// Top-level `const x = authTables(…)`.
|
|
707
|
-
const results = new Set(sf.statements.flatMap((s) => ts.isVariableStatement(s) && (s.declarationList.flags & ts.NodeFlags.Const) !== 0
|
|
708
|
-
? s.declarationList.declarations.flatMap((d) => ts.isIdentifier(d.name) && d.initializer && callsTables(ts, d.initializer, tablesFn)
|
|
709
|
-
? [d.name.text]
|
|
710
|
-
: [])
|
|
711
|
-
: []));
|
|
712
|
-
const isResult = (node) => {
|
|
713
|
-
const inner = unwrap(ts, node);
|
|
714
|
-
return (callsTables(ts, inner, tablesFn) || (ts.isIdentifier(inner) && results.has(inner.text)));
|
|
715
|
-
};
|
|
716
|
-
const inner = unwrap(ts, value);
|
|
717
|
-
if (isResult(inner) ||
|
|
718
|
-
(ts.isObjectLiteralExpression(inner) &&
|
|
719
|
-
inner.properties.some((p) => ts.isSpreadAssignment(p) && isResult(p.expression)))) {
|
|
720
|
-
return { kind: "carries" };
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
const imports = sf.statements.filter((s) => ts.isImportDeclaration(s) &&
|
|
724
|
-
ts.isStringLiteral(s.moduleSpecifier) &&
|
|
725
|
-
s.moduleSpecifier.text === SCHEMA_IMPORT &&
|
|
726
|
-
!!s.importClause?.namedBindings &&
|
|
727
|
-
ts.isNamedImports(s.importClause.namedBindings));
|
|
728
|
-
const schemaImport = imports.length === 1 ? imports[0] : undefined;
|
|
729
|
-
const elements = schemaImport?.importClause?.namedBindings
|
|
730
|
-
?.elements;
|
|
731
|
-
const importEdit = () => {
|
|
732
|
-
if (!elements || elements.length === 0)
|
|
733
|
-
return undefined;
|
|
734
|
-
// Sorted in, as the app's formatter keeps a named import.
|
|
735
|
-
const after = elements.find((e) => e.name.text.toLowerCase() > RATE_LIMIT.toLowerCase());
|
|
736
|
-
if (after) {
|
|
737
|
-
const start = after.getStart(sf);
|
|
738
|
-
return { start, end: start, text: `${RATE_LIMIT}, ` };
|
|
739
|
-
}
|
|
740
|
-
return appendTo(elements);
|
|
741
|
-
};
|
|
742
|
-
const importLine = () => {
|
|
743
|
-
const edit = importEdit();
|
|
744
|
-
if (!schemaImport || !edit)
|
|
745
|
-
return `import { ${RATE_LIMIT} } from "${SCHEMA_IMPORT}";`;
|
|
746
|
-
return statementWith(sf, schemaImport, [edit]);
|
|
747
|
-
};
|
|
748
|
-
const tablesLine = () => {
|
|
749
|
-
if (value && ts.isObjectLiteralExpression(value) && value.properties.length > 0 && tables) {
|
|
750
|
-
return `${statementWith(sf, tables, [appendTo(value.properties)])},`;
|
|
751
|
-
}
|
|
752
|
-
return value
|
|
753
|
-
? `tables: { ...${value.getText(sf)}, ${RATE_LIMIT} },`
|
|
754
|
-
: `tables: { appUser, session, account, verification, ${RATE_LIMIT} },`;
|
|
755
|
-
};
|
|
756
|
-
const lines = [importLine(), tablesLine()];
|
|
757
|
-
const isTemplate = value &&
|
|
758
|
-
ts.isObjectLiteralExpression(value) &&
|
|
759
|
-
value.properties.every((p) => ts.isShorthandPropertyAssignment(p) && !p.objectAssignmentInitializer) &&
|
|
760
|
-
isTemplateNames(value.properties.map((p) => p.name.text)) &&
|
|
761
|
-
!!schemaImport &&
|
|
762
|
-
schemaImport.importClause?.phaseModifier === undefined &&
|
|
763
|
-
TEMPLATE_TABLES.every((name) => elements?.some((e) => !e.propertyName && !e.isTypeOnly && e.name.text === name)) &&
|
|
764
|
-
!topLevel(ts, sf).bound.has(RATE_LIMIT);
|
|
765
|
-
if (!isTemplate || !value || !ts.isObjectLiteralExpression(value)) {
|
|
766
|
-
return { kind: "manual", lines, replace: true };
|
|
767
|
-
}
|
|
768
|
-
const edits = [appendTo(value.properties), importEdit()];
|
|
769
|
-
return { kind: "edit", text: applyEdits(text, edits), lines };
|
|
770
|
-
}
|
|
771
|
-
/** An expression without the parentheses, `as`, `satisfies` and `!` around it. */
|
|
772
|
-
function unwrap(ts, node) {
|
|
773
|
-
let at = node;
|
|
774
|
-
while (ts.isParenthesizedExpression(at) ||
|
|
775
|
-
ts.isAsExpression(at) ||
|
|
776
|
-
ts.isSatisfiesExpression(at) ||
|
|
777
|
-
ts.isNonNullExpression(at)) {
|
|
778
|
-
at = at.expression;
|
|
779
|
-
}
|
|
780
|
-
return at;
|
|
781
|
-
}
|
|
782
|
-
const callsTables = (ts, node, tablesFn) => {
|
|
783
|
-
const inner = unwrap(ts, node);
|
|
784
|
-
return (ts.isCallExpression(inner) &&
|
|
785
|
-
ts.isIdentifier(inner.expression) &&
|
|
786
|
-
inner.expression.text === tablesFn);
|
|
787
|
-
};
|
|
@@ -42,7 +42,7 @@ export async function pendingStatements(schema, migrationsFolder) {
|
|
|
42
42
|
catch (error) {
|
|
43
43
|
// drizzle-kit asks whether a dropped and an added table or column are a rename, and cannot ask without a terminal.
|
|
44
44
|
if (error instanceof Error && /Interactive prompts require a TTY/.test(error.message)) {
|
|
45
|
-
throw new Error("the schema both drops and adds a table or column, and only a person can say whether it is a rename: run `
|
|
45
|
+
throw new Error("the schema both drops and adds a table or column, and only a person can say whether it is a rename: run `pnpm db:generate <name>` in a terminal.", { cause: error });
|
|
46
46
|
}
|
|
47
47
|
throw error;
|
|
48
48
|
}
|
package/dist/env/stack-env.d.ts
CHANGED
|
@@ -23,7 +23,6 @@ export declare const stackEnvSchema: {
|
|
|
23
23
|
GOOGLE_CLIENT_ID: z.ZodOptional<z.ZodString>;
|
|
24
24
|
GOOGLE_CLIENT_SECRET: z.ZodOptional<z.ZodString>;
|
|
25
25
|
TRUSTED_PROXY_HOPS: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
|
|
26
|
-
AUTH_RATE_LIMIT_PER_HOUR: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
|
|
27
26
|
LOG_LEVEL: z.ZodDefault<z.ZodString>;
|
|
28
27
|
};
|
|
29
28
|
/** Required (raw, non-blank) when NODE_ENV is production. Spread it to extend. */
|
package/dist/env/stack-env.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { defineEnv } from "./define-env.js";
|
|
3
|
-
const count = (fallback) => z.coerce.number().int().positive().default(fallback);
|
|
4
3
|
/**
|
|
5
4
|
* The variables every stack app shares. Apps extend it: `defineEnv({ schema: { ...stackEnvSchema, MY_VAR: z.string() }, ... })`. Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
|
|
6
5
|
*/
|
|
@@ -30,9 +29,8 @@ export const stackEnvSchema = {
|
|
|
30
29
|
// Sign in with Google. Both or neither (group `google`).
|
|
31
30
|
GOOGLE_CLIENT_ID: z.string().optional(),
|
|
32
31
|
GOOGLE_CLIENT_SECRET: z.string().optional(),
|
|
33
|
-
// 0 on Vercel, which terminates the proxy chain itself.
|
|
32
|
+
// For `clientIp`: 0 on Vercel, which terminates the proxy chain itself.
|
|
34
33
|
TRUSTED_PROXY_HOPS: z.coerce.number().int().nonnegative().default(0),
|
|
35
|
-
AUTH_RATE_LIMIT_PER_HOUR: count(10),
|
|
36
34
|
LOG_LEVEL: z.string().default("info"),
|
|
37
35
|
};
|
|
38
36
|
/** Required (raw, non-blank) when NODE_ENV is production. Spread it to extend. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wwchen/stack",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Shared Next.js, Neon, Better Auth, Resend and lew-ds building blocks.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -20,6 +20,9 @@
|
|
|
20
20
|
"bin": {
|
|
21
21
|
"stack": "dist/cli/index.js"
|
|
22
22
|
},
|
|
23
|
+
"stack": {
|
|
24
|
+
"requiresDeployed": "0.8.0"
|
|
25
|
+
},
|
|
23
26
|
"exports": {
|
|
24
27
|
".": {
|
|
25
28
|
"types": "./dist/index.d.ts",
|
|
@@ -41,22 +44,6 @@
|
|
|
41
44
|
"types": "./dist/db/testing/isolate.d.ts",
|
|
42
45
|
"default": "./dist/db/testing/isolate.js"
|
|
43
46
|
},
|
|
44
|
-
"./mail": {
|
|
45
|
-
"types": "./dist/mail/index.d.ts",
|
|
46
|
-
"default": "./dist/mail/index.js"
|
|
47
|
-
},
|
|
48
|
-
"./auth": {
|
|
49
|
-
"types": "./dist/auth/index.d.ts",
|
|
50
|
-
"default": "./dist/auth/index.js"
|
|
51
|
-
},
|
|
52
|
-
"./auth/better-auth": {
|
|
53
|
-
"types": "./dist/auth/better-auth/index.d.ts",
|
|
54
|
-
"default": "./dist/auth/better-auth/index.js"
|
|
55
|
-
},
|
|
56
|
-
"./auth/proxy": {
|
|
57
|
-
"types": "./dist/auth/proxy.d.ts",
|
|
58
|
-
"default": "./dist/auth/proxy.js"
|
|
59
|
-
},
|
|
60
47
|
"./connections": {
|
|
61
48
|
"types": "./dist/connections/index.d.ts",
|
|
62
49
|
"default": "./dist/connections/index.js"
|
|
@@ -97,8 +84,8 @@
|
|
|
97
84
|
},
|
|
98
85
|
"dependencies": {
|
|
99
86
|
"@vercel/functions": "3.12.0",
|
|
100
|
-
"@wwchen/stack-auth": "0.
|
|
101
|
-
"@wwchen/stack-notify": "0.
|
|
87
|
+
"@wwchen/stack-auth": "0.9.0",
|
|
88
|
+
"@wwchen/stack-notify": "0.9.0",
|
|
102
89
|
"pg": "8.23.1",
|
|
103
90
|
"zod": "4.6.7"
|
|
104
91
|
},
|
package/dist/auth/index.d.ts
DELETED
package/dist/auth/index.js
DELETED
package/dist/auth/proxy.d.ts
DELETED
package/dist/auth/proxy.js
DELETED
package/dist/mail/index.d.ts
DELETED
package/dist/mail/index.js
DELETED