@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/dist/cli/neon.js DELETED
@@ -1,384 +0,0 @@
1
- // Your Neon branches, driven through the Neon CLI rather than a `.env` file. `stack dev-setup` makes your dev branch, `stack with-neon` hands its connection to every local command, and `stack neon seed` / `reset-preview` keep the two shared branches. Needs the Neon CLI signed in (`neon auth`) or NEON_API_KEY, and NEON_PROJECT_ID in the environment.
2
- //
3
- // Runs before any database is set, so it reads its own `deps.env`, never the app's validated env.
4
- //
5
- // The branch tree: production -> `seed` (the app's migrations and seed rows, no production data) -> `dev/<user>` for each developer and one shared `preview`. Nothing local or preview is ever cut from production, so production's data never leaves it. Production is the project's default branch, whatever it is named (Neon calls a new project's `main`): `defaultBranch`.
6
- import { endpointOf } from "../db/index.js";
7
- import { CliError, importApp, loadAppEnv } from "./context.js";
8
- import { readHosting } from "./doctor.js";
9
- export const SEED = "seed";
10
- export const PREVIEW = "preview";
11
- /** Where the new seed is built; it takes the name `seed` only once it is clean. */
12
- export const SEED_NEXT = "seed-next";
13
- export function projectId(env) {
14
- const id = env.NEON_PROJECT_ID?.trim();
15
- if (!id) {
16
- throw new CliError("NEON_PROJECT_ID is not set. Export your Neon project's id (Neon console -> Project settings).");
17
- }
18
- return id;
19
- }
20
- /**
21
- * Refuses a dev branch name that is not a dev branch: production (whatever this project calls its default branch, and the name `production` itself), the shared `seed` and `preview`, and `seed-next` (the seed being built, which may briefly hold production's data). One check for every command that uses your dev branch: with-neon, dev-setup and user:create.
22
- */
23
- export function assertDevBranchName(name, production) {
24
- const yours = "set NEON_DEV_BRANCH to your own branch (default dev/<os user>)";
25
- if (name === production.name || name === "production") {
26
- throw new CliError(`${name} is production, not a dev branch: production commands use ENV_FILE=<production env file>; ${yours}.`);
27
- }
28
- if (name === SEED || name === SEED_NEXT || name === PREVIEW) {
29
- throw new CliError(`${name} is a shared branch, not a dev branch; ${yours}.`);
30
- }
31
- }
32
- /** `dev/<os user>` unless NEON_DEV_BRANCH names another. */
33
- export const devBranchName = (cli) => cli.env.NEON_DEV_BRANCH?.trim() || `dev/${cli.username}`;
34
- /** Runs `neon <args> --project-id <id>`; stdout trimmed, a failure is the CLI's own message plus the exit code. */
35
- async function neon(cli, args) {
36
- const { stdout, code } = await cli.exec("neon", [...args, "--project-id", projectId(cli.env)]);
37
- return { stdout: stdout.trim(), code };
38
- }
39
- async function neonOk(cli, args) {
40
- const { stdout, code } = await neon(cli, args);
41
- if (code !== 0)
42
- throw new CliError(`neon ${args.slice(0, 2).join(" ")} failed (exit ${code}).`);
43
- return stdout;
44
- }
45
- async function neonJson(cli, args) {
46
- return JSON.parse(await neonOk(cli, [...args, "--output", "json"]));
47
- }
48
- const listBranches = (cli) => neonJson(cli, ["branches", "list"]);
49
- export async function findBranch(cli, name) {
50
- return (await listBranches(cli)).find((b) => b.name === name);
51
- }
52
- /** Production: the project's default branch (Neon's `default` flag), not a branch name. */
53
- export function defaultBranch(branches) {
54
- const production = branches.find((b) => b.default);
55
- if (!production) {
56
- throw new CliError("the Neon project has no default branch, so there is no production to tell apart; set one in the Neon console.");
57
- }
58
- return production;
59
- }
60
- /**
61
- * The variables local work needs: `branch`'s URLs, and the host of production (the default branch; `production` when the caller already has it, else listed).
62
- */
63
- export async function branchEnv(cli, branch, production) {
64
- const productionId = (production ?? defaultBranch(await listBranches(cli))).id;
65
- const [pooled, direct, productionUrl] = await Promise.all([
66
- neonOk(cli, ["connection-string", branch, "--pooled"]),
67
- neonOk(cli, ["connection-string", branch]),
68
- neonOk(cli, ["connection-string", productionId]),
69
- ]);
70
- return {
71
- DATABASE_URL: pooled,
72
- DATABASE_URL_UNPOOLED: direct,
73
- // Keeps assertDevDatabase armed: it refuses this host and allows the dev branch.
74
- PRODUCTION_DATABASE_HOST: new URL(productionUrl).hostname,
75
- };
76
- }
77
- /** Cuts `name` from `parent`; undefined when the Neon CLI refuses. */
78
- async function createBranch(cli, name, parent, extra = []) {
79
- const created = await neon(cli, [
80
- "branches",
81
- "create",
82
- "--name",
83
- name,
84
- "--parent",
85
- parent,
86
- ...extra,
87
- "--output",
88
- "json",
89
- ]);
90
- if (created.code !== 0)
91
- return undefined;
92
- return JSON.parse(created.stdout).branch;
93
- }
94
- /** Deletes `name` if it exists, then cuts it afresh from `parent`; the new branch. */
95
- async function recreate(cli, name, parent) {
96
- const existing = await findBranch(cli, name);
97
- if (existing)
98
- await neonOk(cli, ["branches", "delete", existing.id]);
99
- return createBranch(cli, name, parent);
100
- }
101
- /** The migrations, run against whatever database `env` names, through the direct endpoint. */
102
- export async function migrate(cli, env) {
103
- return (await cli.exec("pnpm", ["exec", "drizzle-kit", "migrate"], { env, inherit: true })).code;
104
- }
105
- /**
106
- * `stack with-neon <command> [args]` — runs a local command against your Neon dev branch with no `.env`: the connection strings and production's host come from the Neon CLI on every run.
107
- *
108
- * Steps aside, and runs the command untouched, when something else already says where the database is: DATABASE_URL in the environment (Vercel, an e2e run, a local Postgres), ENV_FILE (a deliberate production command). A `.env` never decides: what this sets wins over it, in Next and in `loadEnvFile` alike.
109
- */
110
- export async function withNeon(cli, [command, ...args]) {
111
- if (!command) {
112
- cli.error("usage: stack with-neon <command> [args]");
113
- return 2;
114
- }
115
- const env = { ...cli.env, ...(await devBranchEnv(cli)) };
116
- return (await cli.exec(command, args, { env, inherit: true })).code;
117
- }
118
- /**
119
- * Your dev branch's `branchEnv`, as `with-neon` hands it to a command; nothing (`{}`) when DATABASE_URL or ENV_FILE already says where the database is. Refuses the default branch.
120
- */
121
- export async function devBranchEnv(cli) {
122
- if (cli.env.DATABASE_URL || cli.env.ENV_FILE)
123
- return {};
124
- const name = devBranchName(cli);
125
- const branches = await listBranches(cli);
126
- const production = defaultBranch(branches);
127
- assertDevBranchName(name, production);
128
- const branch = branches.find((b) => b.name === name);
129
- if (!branch) {
130
- throw new CliError(`no branch ${name} yet; run \`stack dev-setup\` once.`);
131
- }
132
- const env = await branchEnv(cli, branch.id, production);
133
- cli.error(`[neon] ${name}`);
134
- return env;
135
- }
136
- /**
137
- * The shared `preview` branch's `branchEnv`, for `user:create --preview` and `user:role --preview`: previews hold only `db/seed.ts`'s fake users, so this is how a developer adds their own email to sign in on one. `--preview` names the database, so DATABASE_URL or ENV_FILE set as well is refused rather than overridden, as is a `preview` that is the default branch or answers with production's endpoint.
138
- */
139
- export async function previewBranchEnv(cli) {
140
- if (cli.env.DATABASE_URL || cli.env.ENV_FILE) {
141
- throw new CliError("--preview names the database itself; unset DATABASE_URL and ENV_FILE.");
142
- }
143
- const branches = await listBranches(cli);
144
- const production = defaultBranch(branches);
145
- const branch = branches.find((b) => b.name === PREVIEW);
146
- if (!branch) {
147
- throw new CliError(`no ${PREVIEW} branch yet; run \`stack neon reset-preview\` first.`);
148
- }
149
- const env = await branchEnv(cli, branch.id, production);
150
- const productionEndpoint = endpointOf(env.PRODUCTION_DATABASE_HOST);
151
- if (branch.default ||
152
- endpointOf(env.DATABASE_URL) === productionEndpoint ||
153
- endpointOf(env.DATABASE_URL_UNPOOLED) === productionEndpoint) {
154
- throw new CliError(`${PREVIEW} is production's database; refusing to change it.`);
155
- }
156
- cli.error(`[neon] ${PREVIEW}`);
157
- return env;
158
- }
159
- /**
160
- * `stack dev-setup` — once per developer: makes your Neon dev branch from `seed` (never from production) if it does not exist yet (`dev/<os user>`, or NEON_DEV_BRANCH) and migrates it. Safe to re-run. Sign-in needs nothing on the branch: Better Auth runs in the app, with a development BETTER_AUTH_SECRET and magic links written to the sink file. There is no `.env` to write: `stack with-neon` reads the branch from the Neon CLI on every command.
161
- */
162
- export async function devSetup(cli) {
163
- const name = devBranchName(cli);
164
- const branches = await listBranches(cli);
165
- const production = defaultBranch(branches);
166
- assertDevBranchName(name, production);
167
- let branch = branches.find((b) => b.name === name);
168
- if (branch) {
169
- cli.log(`[dev-setup] using ${name} (${branch.id})`);
170
- }
171
- else {
172
- if (!branches.some((b) => b.name === SEED)) {
173
- throw new CliError(`no \`${SEED}\` branch to cut ${name} from; run \`stack neon seed\` first.`);
174
- }
175
- branch = (await recreate(cli, name, SEED)) ?? undefined;
176
- if (!branch)
177
- throw new CliError(`could not create ${name} from ${SEED}.`);
178
- cli.log(`[dev-setup] created ${name} (${branch.id}) from ${SEED}`);
179
- }
180
- const status = await migrate(cli, {
181
- ...cli.env,
182
- ...(await branchEnv(cli, branch.id, production)),
183
- });
184
- if (status === 0)
185
- cli.log("[dev-setup] done — `stack with-neon pnpm dev` serves the app");
186
- return status;
187
- }
188
- /**
189
- * Schemas Neon's own services install, which hold functions and settings rather than anyone's rows: `auth` is the pg_session_jwt extension the Data API installs (Neon: "do not install this extension manually"), `pgrst` is the Data API's PostgREST configuration. Left in place so the branch keeps working like any other. Neon Auth's `neon_auth` is *not* here: it holds users.
190
- */
191
- export const NEON_SCHEMAS = ["auth", "pgrst"];
192
- const isKept = (schema) => schema === "information_schema" || schema.startsWith("pg_") || NEON_SCHEMAS.includes(schema);
193
- const quoteIdent = (name) => `"${name.replaceAll('"', '""')}"`;
194
- const quoteLiteral = (value) => `'${value.replaceAll("'", "''")}'`;
195
- /**
196
- * Empties a database down to an empty `public`: drops every schema but Postgres's own (`pg_catalog`, `pg_toast*`, `information_schema`, any `pg_*`) and Neon's service schemas, with everything in them — tables, rows, drizzle's journal, Neon Auth's users. Then the migrations run from nothing, as on a new database. A schema-only branch needs this as much as a full copy: it keeps drizzle's journal *table* but not its rows, so migrate would re-run 0000 into tables that already exist. Large objects belong to the database rather than to a schema, so no drop removes them: every one is unlinked too.
197
- *
198
- * Neon's schemas are kept by name, so first it checks they hold what Neon puts there: functions and settings, no rows. A table, partitioned table, materialized view, sequence or foreign table in one (an app's own `auth.accounts`, say) would carry production's rows into the seed, so it refuses before dropping anything.
199
- */
200
- export async function emptyDatabase(sql) {
201
- const held = await sql("SELECT n.nspname, c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " +
202
- `WHERE n.nspname IN (${NEON_SCHEMAS.map(quoteLiteral).join(", ")}) ` +
203
- "AND c.relkind IN ('r', 'p', 'm', 'S', 'f') ORDER BY 1, 2");
204
- if (held.length > 0) {
205
- const names = held.map((r) => `${String(r.nspname)}.${String(r.relname)}`);
206
- throw new CliError(`${names.join(", ")} ${names.length === 1 ? "is a relation" : "are relations"} in a schema kept as Neon's own (${NEON_SCHEMAS.join(", ")}), ` +
207
- "so it could carry production's rows into the seed. Refusing; move the app's tables out of those schemas.");
208
- }
209
- const rows = await sql("SELECT nspname FROM pg_namespace");
210
- const dropped = rows.map((r) => String(r.nspname)).filter((name) => !isKept(name));
211
- if (dropped.length > 0)
212
- await sql(`DROP SCHEMA ${dropped.map(quoteIdent).join(", ")} CASCADE`);
213
- await sql("SELECT lo_unlink(oid) FROM pg_largeobject_metadata");
214
- await sql("CREATE SCHEMA public");
215
- await sql("GRANT USAGE ON SCHEMA public TO PUBLIC");
216
- return dropped;
217
- }
218
- /**
219
- * `stack neon seed` — (re)creates the `seed` branch: exactly the app's migrations plus its seed rows, and none of production's data. Cuts it from production (the project's default branch) as Neon's `--schema-only` branch (a normal branch where that is unsupported), empties it of every non-system schema either way (`emptyDatabase`), migrates it from nothing and runs the app's `db/seed.ts`: `export default async function seed(db)`.
220
- *
221
- * The new seed is built as `seed-next` and takes the name `seed` only once it is clean, so a failure part-way never leaves a branch holding production's data under the name every dev and preview branch is cut from; `seed-next` is deleted on any failure. Neon will not delete a branch that has children, so a seed with dev/preview branches on it is refused up front: remove them yourself (this never deletes them).
222
- */
223
- export async function neonSeed(cli) {
224
- projectId(cli.env);
225
- const branches = await listBranches(cli);
226
- const production = defaultBranch(branches);
227
- const old = branches.find((b) => b.name === SEED);
228
- const children = old ? branches.filter((b) => b.parent_id === old.id) : [];
229
- if (children.length > 0) {
230
- const names = children.map((b) => b.name);
231
- throw new CliError(`${SEED} has child branches (${names.join(", ")}), and Neon will not delete a branch that has children. ` +
232
- `Delete them first (${names.map((n) => `\`neon branches delete ${n}\``).join(", ")}), ` +
233
- `then re-run; re-cut ${PREVIEW} with \`stack neon reset-preview\` and your dev branch with \`stack dev-setup\` afterwards.`);
234
- }
235
- const stale = branches.find((b) => b.name === SEED_NEXT);
236
- if (stale)
237
- await neonOk(cli, ["branches", "delete", stale.id]);
238
- let next = await createBranch(cli, SEED_NEXT, production.name, ["--schema-only"]);
239
- const schemaOnly = next !== undefined;
240
- next ??= await createBranch(cli, SEED_NEXT, production.name);
241
- if (!next)
242
- throw new CliError(`could not create the ${SEED} branch from ${production.name}.`);
243
- try {
244
- cli.log(schemaOnly
245
- ? `[seed] built ${SEED_NEXT} (schema only)`
246
- : `[seed] built ${SEED_NEXT}; --schema-only is unsupported here, so it is a full copy`);
247
- const env = await branchEnv(cli, next.id, production);
248
- const direct = env.DATABASE_URL_UNPOOLED;
249
- // The destructive step below must be pointed at the new branch, never at production.
250
- if (endpointOf(direct) === endpointOf(env.PRODUCTION_DATABASE_HOST)) {
251
- throw new CliError(`${SEED_NEXT} resolves to production's endpoint (${new URL(direct).hostname}); refusing to touch it.`);
252
- }
253
- const dropped = await emptyDatabase((statement) => cli.sql(direct, statement));
254
- cli.log(`[seed] emptied ${SEED_NEXT} (dropped ${dropped.join(", ") || "nothing"})`);
255
- // The app's modules read process.env: the branch's connection wins over its `.env`.
256
- Object.assign(cli.env, env);
257
- loadAppEnv(cli);
258
- const status = await migrate(cli, cli.env);
259
- if (status !== 0) {
260
- await deleteOrWarn(cli, next);
261
- return status;
262
- }
263
- await runAppSeed(cli);
264
- }
265
- catch (error) {
266
- await deleteOrWarn(cli, next);
267
- throw error;
268
- }
269
- // Clean: now it replaces the old seed. From here `seed-next` holds only the fixtures, so a failure leaves it in place and says how to finish.
270
- const rename = `\`neon branches rename ${SEED_NEXT} ${SEED}\``;
271
- if (old) {
272
- const deleted = await neon(cli, ["branches", "delete", old.id]);
273
- if (deleted.code !== 0) {
274
- throw new CliError(`could not delete the old ${SEED} (exit ${deleted.code}); it is unchanged. ${SEED_NEXT} is built and clean: ` +
275
- `finish by hand with \`neon branches delete ${SEED}\`, then ${rename}.`);
276
- }
277
- }
278
- const renamed = await neon(cli, ["branches", "rename", next.id, SEED]);
279
- if (renamed.code !== 0) {
280
- throw new CliError(`could not rename ${SEED_NEXT} to ${SEED} (exit ${renamed.code})${old ? `; the old ${SEED} is already deleted` : ""}. ` +
281
- `${SEED_NEXT} is built and clean: finish by hand with ${rename}.`);
282
- }
283
- cli.log(`[seed] ${SEED} is ready`);
284
- return 0;
285
- }
286
- /**
287
- * Runs the app's `db/seed.ts` (`export default async function seed(db)`) on the app's own `db` (`src/lib/db.ts`), wherever `cli.env` points it, then closes that client's pool: on PGlite it holds the one connection the server allows.
288
- */
289
- export async function runAppSeed(cli) {
290
- const { db } = await importApp(cli, "src/lib/db.ts");
291
- const seedFn = (await importApp(cli, "db/seed.ts")).default;
292
- if (!db || typeof seedFn !== "function") {
293
- throw new CliError("src/lib/db.ts must export `db` and db/seed.ts a default `seed(db)` function.");
294
- }
295
- try {
296
- await seedFn(db);
297
- }
298
- finally {
299
- const client = db.$client;
300
- if (typeof client?.end === "function")
301
- await client.end();
302
- }
303
- }
304
- /**
305
- * Deletes a half-built `seed-next`; the failure being reported comes first, so this only warns. But loudly: until it is emptied, a full-copy `seed-next` holds production's data.
306
- */
307
- async function deleteOrWarn(cli, branch) {
308
- const code = await neon(cli, ["branches", "delete", branch.id]).then((result) => result.code, () => -1);
309
- if (code !== 0) {
310
- cli.error(`[seed] DELETE ${branch.name} BY HAND — it may hold production data. ` +
311
- `Cleanup failed (exit ${code}); run \`neon branches delete ${branch.name}\` now.`);
312
- }
313
- }
314
- /**
315
- * Refuses `--set-vercel` when a variable it would replace is one Vercel variable for Preview and another environment. Reads metadata only (`stack doctor`'s reader), never a value.
316
- */
317
- async function refuseSharedPreviewVariables(cli) {
318
- const { envs } = await readHosting(cli);
319
- for (const { name } of PREVIEW_VARIABLES) {
320
- for (const v of envs) {
321
- if (v.key !== name || !v.target.includes("preview"))
322
- continue;
323
- const others = v.target.filter((t) => t !== "preview");
324
- if (others.length > 0) {
325
- throw new CliError(`${name} is one Vercel variable for Preview and ${others.join(", ")}; --set-vercel would change it there too. In Vercel, take Preview off it (Settings, Environment Variables), then run this again. Nothing was changed.`);
326
- }
327
- }
328
- }
329
- }
330
- /** The Preview variables `--set-vercel` writes, and which of the branch's URLs each holds. */
331
- export const PREVIEW_VARIABLES = [
332
- { name: "DATABASE_URL", pooled: true },
333
- { name: "DATABASE_URL_UNPOOLED", pooled: false },
334
- ];
335
- /**
336
- * `stack neon reset-preview [--set-vercel]` — (re)creates the one shared `preview` branch from `seed`. A build cannot change the DATABASE_URL a preview deployment uses at runtime, so previews share this branch, and `stack vercel-build` migrates it on each preview build; run this again to start it clean.
337
- *
338
- * Without `--set-vercel` it prints the pooled URL, to set by hand as Preview's DATABASE_URL. With it, it writes the pooled URL as DATABASE_URL and the direct one as DATABASE_URL_UNPOOLED into the linked Vercel project, Preview only, as sensitive variables replacing any there, and prints neither. Each value is read from the Neon CLI in full before `vercel env add` starts, then handed over on its stdin: never in its arguments, where `ps` would show it, and never piped from a command still running, which `vercel env add` would read as empty.
339
- */
340
- export async function resetPreview(cli, args = []) {
341
- const setVercel = args.includes("--set-vercel");
342
- // Before anything changes: `vercel env add --environment preview --force` on a variable that Production (or Development) shares with Preview could rewrite it for them too, pointing production at the preview branch. Only a Preview-only variable may be replaced.
343
- if (setVercel)
344
- await refuseSharedPreviewVariables(cli);
345
- if (!(await findBranch(cli, SEED))) {
346
- throw new CliError(`no \`${SEED}\` branch to cut ${PREVIEW} from; run \`stack neon seed\` first.`);
347
- }
348
- const preview = await recreate(cli, PREVIEW, SEED);
349
- if (!preview)
350
- throw new CliError(`could not create ${PREVIEW} from ${SEED}.`);
351
- if (!setVercel) {
352
- cli.error(`[preview] created ${PREVIEW} from ${SEED}; set this as Preview DATABASE_URL on Vercel:`);
353
- cli.log(await neonOk(cli, ["connection-string", preview.id, "--pooled"]));
354
- return 0;
355
- }
356
- cli.error(`[preview] created ${PREVIEW} from ${SEED}`);
357
- const production = defaultBranch(await listBranches(cli));
358
- const productionUrl = await neonOk(cli, ["connection-string", production.id]);
359
- const values = [];
360
- for (const { name, pooled } of PREVIEW_VARIABLES) {
361
- const value = await neonOk(cli, [
362
- "connection-string",
363
- preview.id,
364
- ...(pooled ? ["--pooled"] : []),
365
- ]);
366
- if (!value)
367
- throw new CliError(`neon connection-string returned nothing for ${PREVIEW}.`);
368
- // The same backstop `vercel-build` applies: Preview must never be handed production.
369
- if (endpointOf(value) === endpointOf(productionUrl)) {
370
- throw new CliError(`${PREVIEW}'s ${pooled ? "pooled" : "direct"} URL resolves to production's endpoint; refusing to set it on Vercel.`);
371
- }
372
- values.push({ name, value });
373
- }
374
- for (const { name, value } of values) {
375
- const { code } = await cli.exec("vercel", ["env", "add", name, "--environment", "preview", "--sensitive", "--force", "--yes"], { input: value });
376
- if (code !== 0) {
377
- throw new CliError(`vercel env add ${name} failed (exit ${code}). Is the Vercel CLI signed in (\`vercel login\`) ` +
378
- "and this directory linked (`vercel link`)? Re-run with --set-vercel once it is.");
379
- }
380
- cli.error(`[preview] set ${name} on Vercel (Preview, sensitive)`);
381
- }
382
- cli.log(`[preview] Vercel's Preview DATABASE_URL and DATABASE_URL_UNPOOLED now point at ${PREVIEW}; redeploy a preview to use them.`);
383
- return 0;
384
- }
package/dist/cli/run.d.ts DELETED
@@ -1,2 +0,0 @@
1
- import { type Cli } from "./context.ts";
2
- export declare function runScript(cli: Cli, [script, ...args]: string[]): Promise<number>;
package/dist/cli/run.js DELETED
@@ -1,29 +0,0 @@
1
- // `stack run <script> [args...]` — runs one of the app's own scripts (`scripts/backfill.ts`, say) with this Node, type stripping and all, and the environment every other command gives the app: your Neon dev branch unless DATABASE_URL or ENV_FILE says otherwise, then the app's `.env` (or the file ENV_FILE names) for whatever is still unset. ENV_FILE is also the deliberate production opt-in, exactly as for `user:create`. The arguments and the exit code pass through.
2
- import { resolve } from "node:path";
3
- import { assertDevDatabase } from "../db/index.js";
4
- import { loadAppEnv } from "./context.js";
5
- import { devBranchEnv } from "./neon.js";
6
- export async function runScript(cli, [script, ...args]) {
7
- if (!script) {
8
- cli.error("usage: stack run <script> [args...]");
9
- return 2;
10
- }
11
- Object.assign(cli.env, await devBranchEnv(cli));
12
- loadAppEnv(cli);
13
- // The same refusal the app's own db.ts makes, applied before the script starts: production only with ENV_FILE.
14
- for (const url of [cli.env.DATABASE_URL, cli.env.DATABASE_URL_UNPOOLED]) {
15
- if (!url?.trim())
16
- continue;
17
- assertDevDatabase(url, {
18
- nodeEnv: cli.env.NODE_ENV,
19
- allowRemote: cli.env.ALLOW_REMOTE_DATABASE,
20
- envFile: cli.env.ENV_FILE,
21
- productionHost: cli.env.PRODUCTION_DATABASE_HOST,
22
- });
23
- }
24
- const { code } = await cli.exec(cli.execPath, [resolve(cli.cwd, script), ...args], {
25
- env: cli.env,
26
- inherit: true,
27
- });
28
- return code;
29
- }
@@ -1,14 +0,0 @@
1
- /**
2
- * Brings the stack-owned blocks in AGENTS.md, CLAUDE.md, .gitignore and .env.example up to date and returns the files that were (or, with `check`, would be) changed. Every file is checked before any is written, so a malformed one leaves all of them untouched.
3
- */
4
- export declare function syncBlocks(cwd: string, opts?: {
5
- check?: boolean;
6
- }): Promise<{
7
- changed: string[];
8
- }>;
9
- /** `stack sync-blocks [--check]`: exits 1 when `--check` finds a stale file. */
10
- export declare function syncBlocksCommand(cli: {
11
- cwd: string;
12
- log(m: string): void;
13
- error(m: string): void;
14
- }, args: string[]): Promise<number>;
@@ -1,93 +0,0 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { CliError } from "./context.js";
5
- const MARKDOWN = { begin: "<!-- BEGIN:stack -->", end: "<!-- END:stack -->" };
6
- const HASH = { begin: "# BEGIN:stack", end: "# END:stack" };
7
- /** Each target file, the block file it takes its contents from, and its marker style. */
8
- const TARGETS = [
9
- { file: "AGENTS.md", block: "AGENTS.md", style: MARKDOWN },
10
- { file: "CLAUDE.md", block: "CLAUDE.md", style: MARKDOWN },
11
- { file: ".gitignore", block: "gitignore", style: HASH },
12
- { file: ".env.example", block: "env.example", style: HASH },
13
- ];
14
- /** `blocks/` sits beside `src/` and `dist/`, so one relative path serves both and an installed package. */
15
- const BLOCKS_DIR = fileURLToPath(new URL("../../blocks/", import.meta.url));
16
- /** The lines of `source` with their offsets; `end` includes the line break, `text` does not. */
17
- function linesOf(source) {
18
- const lines = [];
19
- let start = 0;
20
- while (start < source.length) {
21
- const nl = source.indexOf("\n", start);
22
- const end = nl === -1 ? source.length : nl + 1;
23
- lines.push({ start, end, text: source.slice(start, nl === -1 ? end : nl).replace(/\r$/, "") });
24
- start = end;
25
- }
26
- return lines;
27
- }
28
- /**
29
- * Replaces the text between the markers, or appends a marked block when there are none. Anything ambiguous (a marker without its partner, reversed or repeated markers) throws: guessing which text the stack owns could delete the app's own.
30
- */
31
- function apply(file, source, body, style) {
32
- const eol = source.includes("\r\n") ? "\r\n" : "\n";
33
- const block = body.map((line) => line + eol).join("");
34
- const lines = linesOf(source);
35
- const near = lines.find((l) => (l.text.trim() === style.begin && l.text !== style.begin) ||
36
- (l.text.trim() === style.end && l.text !== style.end));
37
- if (near) {
38
- throw new CliError(`${file}: marker "${near.text.trim()}" has leading or trailing whitespace. Fix the markers by hand; nothing was changed.`);
39
- }
40
- const begins = lines.filter((l) => l.text === style.begin);
41
- const ends = lines.filter((l) => l.text === style.end);
42
- if (begins.length === 0 && ends.length === 0) {
43
- const lead = source === "" ? "" : source.endsWith("\n") ? eol : eol + eol;
44
- return `${source}${lead}${style.begin}${eol}${block}${style.end}${eol}`;
45
- }
46
- const [begin] = begins;
47
- const [end] = ends;
48
- if (begins.length !== 1 || ends.length !== 1 || !begin || !end) {
49
- throw new CliError(`${file}: expected exactly one "${style.begin}" and one "${style.end}", found ${begins.length} and ${ends.length}. Fix the markers by hand; nothing was changed.`);
50
- }
51
- if (end.start < begin.start) {
52
- throw new CliError(`${file}: "${style.end}" comes before "${style.begin}". Fix the markers by hand; nothing was changed.`);
53
- }
54
- return source.slice(0, begin.end) + block + source.slice(end.start);
55
- }
56
- /** The block's inner lines, without trailing blank lines. */
57
- function readBody(name) {
58
- return readFileSync(join(BLOCKS_DIR, name), "utf8").replace(/\s+$/, "").split(/\r?\n/);
59
- }
60
- /**
61
- * Brings the stack-owned blocks in AGENTS.md, CLAUDE.md, .gitignore and .env.example up to date and returns the files that were (or, with `check`, would be) changed. Every file is checked before any is written, so a malformed one leaves all of them untouched.
62
- */
63
- export async function syncBlocks(cwd, opts = {}) {
64
- const writes = [];
65
- for (const { file, block, style } of TARGETS) {
66
- const path = join(cwd, file);
67
- const before = existsSync(path) ? readFileSync(path, "utf8") : "";
68
- const after = apply(file, before, readBody(block), style);
69
- if (after !== before)
70
- writes.push({ path, file, text: after });
71
- }
72
- if (!opts.check)
73
- for (const w of writes)
74
- writeFileSync(w.path, w.text);
75
- return { changed: writes.map((w) => w.file) };
76
- }
77
- /** `stack sync-blocks [--check]`: exits 1 when `--check` finds a stale file. */
78
- export async function syncBlocksCommand(cli, args) {
79
- const unknown = args.filter((a) => a !== "--check");
80
- if (unknown.length > 0)
81
- throw new CliError(`sync-blocks: unknown argument ${unknown[0]}`);
82
- const check = args.includes("--check");
83
- const { changed } = await syncBlocks(cli.cwd, { check });
84
- if (check && changed.length > 0) {
85
- cli.error(`stale stack blocks: ${changed.join(", ")}. Run \`stack sync-blocks\`.`);
86
- return 1;
87
- }
88
- for (const file of changed)
89
- cli.log(`updated ${file}`);
90
- if (changed.length === 0)
91
- cli.log("stack blocks are up to date");
92
- return 0;
93
- }
@@ -1,6 +0,0 @@
1
- import { type Cli } from "./context.ts";
2
- export declare function userCreate(cli: Cli, args: string[]): Promise<number>;
3
- /**
4
- * `stack user:role <email> <admin|user>`. The email is matched as it is stored (trimmed, lower-cased). The rule that the app always keeps an admin is `setRole`'s, enforced in its own transaction: its refusal is reported as is, and nothing changes.
5
- */
6
- export declare function userRole(cli: Cli, args: string[]): Promise<number>;
@@ -1,77 +0,0 @@
1
- import { CliError, importApp, loadAppEnv } from "./context.js";
2
- import { devBranchEnv, PREVIEW, previewBranchEnv } from "./neon.js";
3
- const PREVIEW_FLAG = "--preview";
4
- /**
5
- * The app's `auth.users`, with the database every command here uses: the dev branch's connection (when nothing else names a database), or the `preview` branch's with `--preview`, wins over `.env`, which fills in only what is still unset. The app's modules read process.env, so this sets it before importing them.
6
- */
7
- async function appUsers(cli, preview) {
8
- Object.assign(cli.env, preview ? await previewBranchEnv(cli) : await devBranchEnv(cli));
9
- loadAppEnv(cli);
10
- const auth = (await importApp(cli, "src/lib/auth.ts")).auth;
11
- if (!auth?.users)
12
- throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
13
- return auth.users;
14
- }
15
- export async function userCreate(cli, args) {
16
- const admin = args.includes("--admin");
17
- const preview = args.includes(PREVIEW_FLAG);
18
- const [email, ...rest] = args.filter((arg) => arg !== "--admin" && arg !== PREVIEW_FLAG);
19
- if (!email || rest.length > 0) {
20
- cli.error("usage: stack user:create <email> [--admin] [--preview]");
21
- return 2;
22
- }
23
- const users = await appUsers(cli, preview);
24
- if (!users.add)
25
- throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
26
- try {
27
- const user = await users.add(email, admin ? "admin" : "user");
28
- cli.log(preview
29
- ? `created ${user.email}${admin ? " as an admin" : ""} on ${PREVIEW}: sign in on a preview with a magic link. \`stack neon reset-preview\` drops it.`
30
- : `created ${user.email}${admin ? " as an admin" : ""}. They can sign in now.`);
31
- return 0;
32
- }
33
- catch (error) {
34
- if (error instanceof Error && error.name === "DuplicateUserError") {
35
- throw new CliError(`${error.message}. Nothing changed.`);
36
- }
37
- throw error;
38
- }
39
- }
40
- const ROLES = ["admin", "user"];
41
- const isRole = (value) => ROLES.includes(value);
42
- /**
43
- * `stack user:role <email> <admin|user>`. The email is matched as it is stored (trimmed, lower-cased). The rule that the app always keeps an admin is `setRole`'s, enforced in its own transaction: its refusal is reported as is, and nothing changes.
44
- */
45
- export async function userRole(cli, args) {
46
- const preview = args.includes(PREVIEW_FLAG);
47
- const [email, role, ...rest] = args.filter((arg) => arg !== PREVIEW_FLAG);
48
- if (!email || !isRole(role) || rest.length > 0) {
49
- cli.error("usage: stack user:role <email> <admin|user> [--preview]");
50
- return 2;
51
- }
52
- const users = await appUsers(cli, preview);
53
- if (!users.list || !users.setRole) {
54
- throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
55
- }
56
- const wanted = email.trim().toLowerCase();
57
- const user = (await users.list()).find((u) => u.email === wanted);
58
- if (!user) {
59
- throw new CliError(`no user with the email ${wanted}; add them with \`stack user:create\`. Nothing changed.`);
60
- }
61
- const as = role === "admin" ? "an admin" : "a user";
62
- if (user.role === role) {
63
- cli.log(`${user.email} is already ${as}. Nothing changed.`);
64
- return 0;
65
- }
66
- try {
67
- await users.setRole(user.id, role);
68
- }
69
- catch (error) {
70
- if (error instanceof Error && error.name === "LastAdminError") {
71
- throw new CliError(`${error.message}: ${user.email} is the only admin. Make someone else an admin first. Nothing changed.`);
72
- }
73
- throw error;
74
- }
75
- cli.log(`${user.email} is now ${as}.`);
76
- return 0;
77
- }
@@ -1,4 +0,0 @@
1
- import { type Cli } from "./context.ts";
2
- /** Every variable the stack's env reads a database connection from. */
3
- export declare const DATABASE_URL_VARIABLES: readonly ["DATABASE_URL", "DATABASE_URL_UNPOOLED"];
4
- export declare function vercelBuild(cli: Cli): Promise<number>;