@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
@@ -1,491 +0,0 @@
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
- //
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
- import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
5
- import { dirname, join, relative, sep } from "node:path";
6
- import { CliError, STACK_PACKAGE } from "./context.js";
7
- const AUTH = "@wwchen/stack-auth";
8
- const NOTIFY = "@wwchen/stack-notify";
9
- const MAIL = "@wwchen/stack/mail";
10
- /** Each old path and the specifier that replaces it. A Map, so no string matches an inherited property name. */
11
- const MOVED = new Map([
12
- ["@wwchen/stack/auth", AUTH],
13
- ["@wwchen/stack/auth/better-auth", `${AUTH}/better-auth`],
14
- ["@wwchen/stack/auth/proxy", `${AUTH}/proxy`],
15
- [MAIL, NOTIFY],
16
- ]);
17
- /** Vitest's calls whose first argument is a module specifier: a mock left on an old path stops applying once the code imports the new one. */
18
- const VI_MODULE_CALLS = new Set([
19
- "mock",
20
- "doMock",
21
- "unmock",
22
- "doUnmock",
23
- "importActual",
24
- "importMock",
25
- ]);
26
- /** The one name `@wwchen/stack/mail` exports that lives in auth, not notify. */
27
- const MAGIC = "waitForMagicLink";
28
- const STACK_PACKAGE_NAME = "@wwchen/stack";
29
- const WORKSPACE = "pnpm-workspace.yaml";
30
- const RELEASE_AGE_EXCLUDE = "minimumReleaseAgeExclude";
31
- export async function migrateSuite(cli, args) {
32
- const expected = parseArgs(args);
33
- if (expected !== undefined && expected !== "workspace:*" && expected !== STACK_PACKAGE.version) {
34
- throw new CliError(`Upgrade @wwchen/stack to ${expected} first: ${STACK_PACKAGE.version} is installed.`);
35
- }
36
- const ts = await loadTypeScript();
37
- const pkgPath = join(cli.cwd, "package.json");
38
- if (!existsSync(pkgPath))
39
- throw new CliError(`migrate-suite: no package.json in ${cli.cwd}`);
40
- const pkgText = readFileSync(pkgPath, "utf8");
41
- const packages = addPackages(pkgText);
42
- const writes = new Map();
43
- const notes = [];
44
- for (const path of await sourceFiles(cli)) {
45
- const text = readFileSync(join(cli.cwd, path), "utf8");
46
- const moved = moveImports(ts, path, text);
47
- notes.push(...moved.notes);
48
- if (moved.text !== text)
49
- writes.set(path, moved.text);
50
- }
51
- const moved = [...writes.keys()];
52
- const workspacePath = join(cli.cwd, WORKSPACE);
53
- const workspace = releaseAgeEdit(existsSync(workspacePath) ? readFileSync(workspacePath, "utf8") : undefined, suitePackages(packages.text));
54
- if (packages.added.length > 0)
55
- writeFileSync(pkgPath, packages.text);
56
- if (workspace.text !== undefined)
57
- writeFileSync(workspacePath, workspace.text);
58
- for (const [path, text] of writes)
59
- writeFileSync(join(cli.cwd, path), text);
60
- const sorted = await sortImports(cli, [...writes.keys()]);
61
- const lines = [];
62
- if (packages.added.length > 0) {
63
- lines.push(`package.json: added ${packages.added.map((name) => `${name} ${packages.spec}`).join(", ")}`);
64
- }
65
- if (workspace.added.length > 0) {
66
- lines.push(`${WORKSPACE}: ${RELEASE_AGE_EXCLUDE} now lists ${workspace.added.join(", ")}`);
67
- }
68
- lines.push(...workspace.manual);
69
- if (moved.length > 0) {
70
- lines.push(`imports moved to the suite's packages in ${moved.length} ${moved.length === 1 ? "file" : "files"}:`, ...moved.sort().map((path) => ` ${path}`));
71
- }
72
- lines.push(...notes);
73
- if (!sorted) {
74
- lines.push("Biome could not sort the imports of the files above; run `pnpm lint:fix`.");
75
- }
76
- if (lines.length === 0) {
77
- cli.log("migrate-suite: nothing to change");
78
- return 0;
79
- }
80
- cli.log(lines.map((line) => (line.startsWith(" ") ? line : `migrate-suite: ${line}`)).join("\n"));
81
- let code = 0;
82
- // A new package, or a new exemption from the release-age hold, takes an install to settle the lockfile.
83
- if (packages.added.length > 0 || workspace.text !== undefined) {
84
- // In CI pnpm defaults to a frozen lockfile, which the packages just added would fail.
85
- ({ code } = await cli.exec("pnpm", ["--dir", cli.cwd, "install", "--no-frozen-lockfile"], {
86
- inherit: true,
87
- }));
88
- if (code !== 0)
89
- cli.error("migrate-suite: pnpm install failed; run it again in the app.");
90
- }
91
- return code;
92
- }
93
- function parseArgs(args) {
94
- if (args.length === 0)
95
- return undefined;
96
- if (args.length === 2 && args[0] === "--expect" && args[1])
97
- return args[1];
98
- throw new CliError("usage: stack migrate-suite [--expect <version>]");
99
- }
100
- /** TypeScript is a peer, loaded only here, so the other commands run without it. */
101
- async function loadTypeScript() {
102
- try {
103
- return (await import("typescript")).default;
104
- }
105
- catch {
106
- throw new CliError("migrate-suite needs typescript, a peer of @wwchen/stack: install it.");
107
- }
108
- }
109
- /**
110
- * The app's package.json with every suite package the installed stack depends on, sorted in among `dependencies`; nothing else moves. Each is added at the stack's version, or at the app's own `workspace:` spec for the stack when it takes the stack from its workspace.
111
- */
112
- function addPackages(text) {
113
- const pkg = JSON.parse(text);
114
- const sections = [
115
- "dependencies",
116
- "devDependencies",
117
- "peerDependencies",
118
- "optionalDependencies",
119
- ].map((s) => pkg[s] ?? {});
120
- const has = (name) => sections.some((section) => Object.hasOwn(section, name));
121
- const stackSpec = sections.map((section) => section["@wwchen/stack"]).find(Boolean);
122
- const spec = stackSpec?.startsWith("workspace:") ? stackSpec : STACK_PACKAGE.version;
123
- const added = Object.keys(STACK_PACKAGE.dependencies)
124
- .filter((name) => name.startsWith("@wwchen/stack-") && !has(name))
125
- .sort();
126
- if (added.length === 0)
127
- return { text, added, spec };
128
- const entries = Object.entries(pkg.dependencies ?? {});
129
- for (const name of added) {
130
- const at = entries.findIndex(([existing]) => existing > name);
131
- entries.splice(at === -1 ? entries.length : at, 0, [name, spec]);
132
- }
133
- pkg.dependencies = Object.fromEntries(entries);
134
- return { text: `${JSON.stringify(pkg, null, 2)}\n`, added, spec };
135
- }
136
- /** `@wwchen/stack` and every `@wwchen/stack-*` package the app's package.json names, sorted. */
137
- function suitePackages(pkgText) {
138
- const pkg = JSON.parse(pkgText);
139
- const names = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]
140
- .flatMap((s) => Object.keys(pkg[s] ?? {}))
141
- .filter((name) => name === STACK_PACKAGE_NAME || name.startsWith(`${STACK_PACKAGE_NAME}-`));
142
- return [...new Set(names)].sort();
143
- }
144
- /** A single-line scalar and an optional comment after it; undefined for anything else (an anchor, an alias, a nested collection). */
145
- function readScalar(raw) {
146
- const text = raw.trim();
147
- const double = /^"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$/.exec(text);
148
- if (double)
149
- return { value: double[1], quote: '"' };
150
- const single = /^'((?:[^']|'')*)'\s*(?:#.*)?$/.exec(text);
151
- if (single)
152
- return { value: single[1].replace(/''/g, "'"), quote: "'" };
153
- const plain = /^([^\s#&*!|>[\]{},'"%@`-][^#]*?|-[^\s#][^#]*?)(?:\s+#.*)?$/.exec(text);
154
- return plain ? { value: plain[1], quote: "" } : undefined;
155
- }
156
- /** Whether an exemption names a package: exactly, or by a `*` pattern (`@scope/*`). */
157
- const exempts = (entry, name) => entry === name ||
158
- (entry.includes("*") &&
159
- new RegExp(`^${entry.split("*").map(escapeRegExp).join(".*")}$`).test(name));
160
- const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
161
- /**
162
- * pnpm-workspace.yaml with every suite package in `minimumReleaseAgeExclude`, so an upgrade installs a release on the day it ships: missing names go in after the list's last `@wwchen/` entry (or its end), quoted and indented as its items are. Where only `minimumReleaseAge` is set, the key is added after it. Nothing where neither key is set (no name is exempt from the hold), the hold is off, or there is no file; the names to add when the key holds something else.
163
- */
164
- function releaseAgeEdit(text, names) {
165
- const none = { added: [], manual: [] };
166
- if (text === undefined || names.length === 0)
167
- return none;
168
- const lines = text.split("\n");
169
- const quoted = (name, quote) => `${quote || '"'}${name}${quote || '"'}`;
170
- const keyAt = lines.findIndex((line) => line.startsWith(`${RELEASE_AGE_EXCLUDE}:`));
171
- if (keyAt === -1) {
172
- const ageAt = lines.findIndex((line) => /^minimumReleaseAge\s*:/.test(line));
173
- const age = ageAt === -1 ? undefined : lines[ageAt].replace(/^[^:]*:|#.*$/g, "");
174
- if (age === undefined || /^\s*0*\s*$/.test(age))
175
- return none;
176
- const block = [`${RELEASE_AGE_EXCLUDE}:`, ...names.map((name) => ` - ${quoted(name, '"')}`)];
177
- lines.splice(ageAt + 1, 0, ...block);
178
- return { text: lines.join("\n"), added: names, manual: [] };
179
- }
180
- const unreadable = {
181
- added: [],
182
- manual: [
183
- `${WORKSPACE}'s ${RELEASE_AGE_EXCLUDE} is not a list migrate-suite can read; add these to it by hand, or a release of them is held for a day:`,
184
- ...names.map((name) => ` - ${quoted(name, '"')}`),
185
- ],
186
- };
187
- const keyLine = lines[keyAt];
188
- const rest = keyLine.slice(RELEASE_AGE_EXCLUDE.length + 1);
189
- const missingFrom = (entries) => names.filter((name) => !entries.some((entry) => exempts(entry.value, name)));
190
- /** Where the new names go: after the last `@wwchen/` entry, else after the last entry. */
191
- const insertAfter = (entries) => {
192
- const at = entries.findLastIndex((entry) => entry.value.startsWith("@wwchen/"));
193
- return at === -1 ? entries.length - 1 : at;
194
- };
195
- // A flow list on the key's line: `[a, "b"]`.
196
- const flow = /^(\s*\[)(.*)\](\s*(?:#.*)?)$/.exec(rest);
197
- if (flow) {
198
- const inner = flow[2];
199
- const pieces = inner.trim() === "" ? [] : inner.split(",");
200
- const entries = pieces.map(readScalar);
201
- if (entries.some((entry) => entry === undefined))
202
- return unreadable;
203
- const read = entries;
204
- const missing = missingFrom(read);
205
- if (missing.length === 0)
206
- return none;
207
- const quote = read.at(-1)?.quote ?? '"';
208
- const list = missing.map((name) => quoted(name, quote)).join(", ");
209
- let rewritten;
210
- if (pieces.length === 0) {
211
- rewritten = list;
212
- }
213
- else {
214
- const after = insertAfter(read);
215
- const end = pieces
216
- .slice(0, after + 1)
217
- .join(",")
218
- .trimEnd().length;
219
- rewritten = `${inner.slice(0, end)}, ${list}${inner.slice(end)}`;
220
- }
221
- lines[keyAt] = `${RELEASE_AGE_EXCLUDE}:${flow[1]}${rewritten}]${flow[3]}`;
222
- return { text: lines.join("\n"), added: missing, manual: [] };
223
- }
224
- if (!/^\s*(#.*)?$/.test(rest))
225
- return unreadable;
226
- // A block list under the key: `- item` lines, with blank and comment lines among them.
227
- const items = [];
228
- for (let at = keyAt + 1; at < lines.length; at++) {
229
- const line = lines[at];
230
- if (/^\s*(#.*)?$/.test(line))
231
- continue;
232
- const item = /^(\s*)-\s+(.*)$/.exec(line);
233
- if (!item) {
234
- // An indented line that is not an item belongs to the value: something this cannot read.
235
- if (/^\s/.test(line))
236
- return unreadable;
237
- break;
238
- }
239
- const scalar = readScalar(item[2]);
240
- if (!scalar || (items[0] && items[0].indent !== item[1]))
241
- return unreadable;
242
- items.push({ at, indent: item[1], scalar });
243
- }
244
- const read = items.map((item) => item.scalar);
245
- const missing = missingFrom(read);
246
- if (missing.length === 0)
247
- return none;
248
- const last = items[insertAfter(read)];
249
- const indent = last?.indent ?? " ";
250
- const quote = items.at(-1)?.scalar.quote ?? '"';
251
- lines.splice((last?.at ?? keyAt) + 1, 0, ...missing.map((name) => `${indent}- ${quoted(name, quote)}`));
252
- return { text: lines.join("\n"), added: missing, manual: [] };
253
- }
254
- /**
255
- * Sorts the imports of the files just rewritten with the app's own Biome, its formatter and linter off: a moved specifier can sort differently (`@wwchen/stack/ui` before `@wwchen/stack-auth`), and the app's lint checks the order. Skipped when the app has no Biome; false when Biome failed.
256
- */
257
- async function sortImports(cli, paths) {
258
- if (paths.length === 0)
259
- return true;
260
- if (!existsSync(join(cli.cwd, "node_modules", "@biomejs", "biome", "package.json")))
261
- return true;
262
- const { code } = await cli.exec("pnpm", [
263
- "--dir",
264
- cli.cwd,
265
- "exec",
266
- "biome",
267
- "check",
268
- "--write",
269
- "--formatter-enabled=false",
270
- "--linter-enabled=false",
271
- "--no-errors-on-unmatched",
272
- "--files-ignore-unknown=true",
273
- ...paths.sort().map((path) => join(cli.cwd, path)),
274
- ]);
275
- return code === 0;
276
- }
277
- const SOURCE = /\.(ts|tsx|mts)$/;
278
- const SKIPPED_DIRS = new Set(["node_modules", ".next", "dist"]);
279
- /** The app's TypeScript files, relative to its root: those git tracks, or, outside a repository, every one outside dependencies and build output. */
280
- async function sourceFiles(cli) {
281
- const isSource = (path) => SOURCE.test(path) &&
282
- !path.split("/").includes("node_modules") &&
283
- existsSync(join(cli.cwd, path));
284
- if (!insideGit(cli.cwd))
285
- return walk(cli.cwd).filter(isSource);
286
- const { stdout, code } = await cli.exec("git", ["-C", cli.cwd, "ls-files", "-z"]);
287
- if (code !== 0)
288
- throw new CliError(`migrate-suite: git ls-files failed in ${cli.cwd}`);
289
- return stdout.split("\0").filter(Boolean).filter(isSource);
290
- }
291
- function insideGit(dir) {
292
- for (let at = dir;; at = dirname(at)) {
293
- if (existsSync(join(at, ".git")))
294
- return true;
295
- if (dirname(at) === at)
296
- return false;
297
- }
298
- }
299
- function walk(root, dir = root) {
300
- return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
301
- const path = join(dir, entry.name);
302
- if (entry.isDirectory())
303
- return SKIPPED_DIRS.has(entry.name) ? [] : walk(root, path);
304
- return entry.isFile() ? [relative(root, path).split(sep).join("/")] : [];
305
- });
306
- }
307
- function parse(ts, path, text) {
308
- const kind = path.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
309
- return ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, kind);
310
- }
311
- function applyEdits(text, edits) {
312
- let out = text;
313
- for (const edit of [...edits].sort((a, b) => b.start - a.start)) {
314
- out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
315
- }
316
- return out;
317
- }
318
- const newlines = (text) => text.split("\n").length - 1;
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. */
320
- function moveImports(ts, path, text) {
321
- const sf = parse(ts, path, text);
322
- const edits = [];
323
- const specifiers = new Set();
324
- const pending = [];
325
- let usesMagic;
326
- const mentionsMagic = () => {
327
- usesMagic ??= hasIdentifier(ts, sf, MAGIC);
328
- return usesMagic;
329
- };
330
- const replace = (literal, to) => edits.push({ start: literal.getStart(sf) + 1, end: literal.end - 1, text: to });
331
- /** A specifier that brings in the module whole (namespace, dynamic, `require`, type query). */
332
- const whole = (literal) => {
333
- const to = MOVED.get(literal.text);
334
- if (!to)
335
- return;
336
- if (literal.text === MAIL && mentionsMagic()) {
337
- pending.push({
338
- pos: literal.getStart(sf),
339
- note: (line) => `${path}:${line}: "${MAIL}" is imported whole and the file uses ${MAGIC}; left as is. Import ${MAGIC} from "${AUTH}" and the rest from "${NOTIFY}".`,
340
- });
341
- return;
342
- }
343
- replace(literal, to);
344
- };
345
- const visit = (node) => {
346
- if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
347
- node.moduleSpecifier &&
348
- ts.isStringLiteral(node.moduleSpecifier)) {
349
- specifiers.add(node.moduleSpecifier);
350
- const literal = node.moduleSpecifier;
351
- if (literal.text !== MAIL) {
352
- const to = MOVED.get(literal.text);
353
- if (to)
354
- replace(literal, to);
355
- }
356
- else {
357
- const split = splitMail(ts, sf, node);
358
- if (split === "whole")
359
- whole(literal);
360
- else
361
- edits.push(split);
362
- }
363
- }
364
- else if (ts.isImportEqualsDeclaration(node) &&
365
- ts.isExternalModuleReference(node.moduleReference) &&
366
- ts.isStringLiteralLike(node.moduleReference.expression)) {
367
- specifiers.add(node.moduleReference.expression);
368
- whole(node.moduleReference.expression);
369
- }
370
- else if (ts.isCallExpression(node) &&
371
- node.expression.kind === ts.SyntaxKind.ImportKeyword &&
372
- node.arguments[0] &&
373
- ts.isStringLiteralLike(node.arguments[0])) {
374
- specifiers.add(node.arguments[0]);
375
- whole(node.arguments[0]);
376
- }
377
- else if (ts.isImportTypeNode(node) &&
378
- ts.isLiteralTypeNode(node.argument) &&
379
- ts.isStringLiteral(node.argument.literal)) {
380
- specifiers.add(node.argument.literal);
381
- whole(node.argument.literal);
382
- }
383
- else if (ts.isCallExpression(node) &&
384
- ts.isPropertyAccessExpression(node.expression) &&
385
- ts.isIdentifier(node.expression.expression) &&
386
- node.expression.expression.text === "vi" &&
387
- VI_MODULE_CALLS.has(node.expression.name.text) &&
388
- node.arguments[0] &&
389
- ts.isStringLiteralLike(node.arguments[0])) {
390
- specifiers.add(node.arguments[0]);
391
- whole(node.arguments[0]);
392
- }
393
- else if (ts.isStringLiteralLike(node) && !specifiers.has(node) && MOVED.has(node.text)) {
394
- const { text: name } = node;
395
- pending.push({
396
- pos: node.getStart(sf),
397
- note: (line) => `${path}:${line}: a string names "${name}" outside an import; if it names the module, change it to "${MOVED.get(name)}"`,
398
- });
399
- }
400
- ts.forEachChild(node, visit);
401
- };
402
- visit(sf);
403
- // A note's line is counted in the file as rewritten.
404
- const lineAfterEdits = (pos) => sf.getLineAndCharacterOfPosition(pos).line +
405
- 1 +
406
- edits
407
- .filter((edit) => edit.end <= pos)
408
- .reduce((sum, edit) => sum + newlines(edit.text) - newlines(text.slice(edit.start, edit.end)), 0);
409
- const notes = pending
410
- .sort((a, b) => a.pos - b.pos)
411
- .map(({ pos, note }) => note(lineAfterEdits(pos)));
412
- return { text: applyEdits(text, edits), notes };
413
- }
414
- function hasIdentifier(ts, sf, name) {
415
- const visit = (node) => (ts.isIdentifier(node) && node.text === name) || (ts.forEachChild(node, visit) ?? false);
416
- return visit(sf);
417
- }
418
- /**
419
- * An import or export of `@wwchen/stack/mail` as one edit: `waitForMagicLink` from auth, the rest from notify, split in two declarations when it names both. `"whole"` for a namespace import or export, which names nothing.
420
- */
421
- function splitMail(ts, sf, decl) {
422
- const literal = decl.moduleSpecifier;
423
- const start = decl.getStart(sf);
424
- const original = sf.text.slice(start, decl.end);
425
- const at = (node) => node.getStart(sf) - start;
426
- const specifier = (to) => ({
427
- start: at(literal) + 1,
428
- end: literal.end - start - 1,
429
- text: to,
430
- });
431
- const indent = sf.text.slice(sf.text.lastIndexOf("\n", start - 1) + 1, start);
432
- const whole = (to) => ({
433
- start,
434
- end: decl.end,
435
- text: applyEdits(original, [specifier(to)]),
436
- });
437
- let named;
438
- let defaultName;
439
- if (ts.isImportDeclaration(decl)) {
440
- const clause = decl.importClause;
441
- if (!clause)
442
- return whole(NOTIFY);
443
- if (clause.namedBindings && ts.isNamespaceImport(clause.namedBindings))
444
- return "whole";
445
- named = clause.namedBindings;
446
- defaultName = clause.name;
447
- }
448
- else if (!decl.exportClause) {
449
- // `export *` re-exports every name mail did: notify's, and waitForMagicLink from auth.
450
- const magic = applyEdits(original, [
451
- {
452
- start: 0,
453
- end: at(literal),
454
- text: `export ${decl.isTypeOnly ? "type " : ""}{ ${MAGIC} } from `,
455
- },
456
- specifier(AUTH),
457
- ]);
458
- return {
459
- start,
460
- end: decl.end,
461
- text: `${magic}\n${indent}${applyEdits(original, [specifier(NOTIFY)])}`,
462
- };
463
- }
464
- else if (ts.isNamespaceExport(decl.exportClause)) {
465
- return "whole";
466
- }
467
- else {
468
- named = decl.exportClause;
469
- }
470
- const elements = [...(named?.elements ?? [])];
471
- const magic = elements.filter((e) => (e.propertyName ?? e.name).text === MAGIC);
472
- const rest = elements.filter((e) => !magic.includes(e));
473
- if (magic.length === 0)
474
- return whole(NOTIFY);
475
- if (!named || (rest.length === 0 && !defaultName))
476
- return whole(AUTH);
477
- // The names between the braces, first to last.
478
- const names = {
479
- start: at(elements[0]),
480
- end: elements.at(-1).end - start,
481
- };
482
- const list = (picked) => picked.map((e) => e.getText(sf)).join(", ");
483
- const authPart = applyEdits(original, [
484
- // `import x, { waitForMagicLink }` keeps the default import with the rest.
485
- ...(defaultName ? [{ start: at(defaultName), end: at(named), text: "" }] : []),
486
- { ...names, text: list(magic) },
487
- specifier(AUTH),
488
- ]);
489
- const notifyPart = applyEdits(original, [{ ...names, text: list(rest) }, specifier(NOTIFY)]);
490
- return { start, end: decl.end, text: `${authPart}\n${indent}${notifyPart}` };
491
- }
@@ -1,79 +0,0 @@
1
- import { type Cli, type Env } from "./context.ts";
2
- export declare const SEED = "seed";
3
- export declare const PREVIEW = "preview";
4
- export type Branch = {
5
- id: string;
6
- name: string;
7
- default: boolean;
8
- parent_id?: string;
9
- };
10
- /** Where the new seed is built; it takes the name `seed` only once it is clean. */
11
- export declare const SEED_NEXT = "seed-next";
12
- export declare function projectId(env: Env): string;
13
- /**
14
- * 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.
15
- */
16
- export declare function assertDevBranchName(name: string, production: Branch): void;
17
- /** `dev/<os user>` unless NEON_DEV_BRANCH names another. */
18
- export declare const devBranchName: (cli: Cli) => string;
19
- export declare function findBranch(cli: Cli, name: string): Promise<Branch | undefined>;
20
- /** Production: the project's default branch (Neon's `default` flag), not a branch name. */
21
- export declare function defaultBranch(branches: Branch[]): Branch;
22
- /**
23
- * 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).
24
- */
25
- export declare function branchEnv(cli: Cli, branch: string, production?: Branch): Promise<Record<string, string>>;
26
- /** The migrations, run against whatever database `env` names, through the direct endpoint. */
27
- export declare function migrate(cli: Cli, env: Env): Promise<number>;
28
- /**
29
- * `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.
30
- *
31
- * 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.
32
- */
33
- export declare function withNeon(cli: Cli, [command, ...args]: string[]): Promise<number>;
34
- /**
35
- * 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.
36
- */
37
- export declare function devBranchEnv(cli: Cli): Promise<Record<string, string>>;
38
- /**
39
- * 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.
40
- */
41
- export declare function previewBranchEnv(cli: Cli): Promise<Record<string, string>>;
42
- /**
43
- * `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.
44
- */
45
- export declare function devSetup(cli: Cli): Promise<number>;
46
- /**
47
- * 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.
48
- */
49
- export declare const NEON_SCHEMAS: readonly string[];
50
- /**
51
- * 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.
52
- *
53
- * 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.
54
- */
55
- export declare function emptyDatabase(sql: (statement: string) => Promise<Record<string, unknown>[]>): Promise<string[]>;
56
- /**
57
- * `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)`.
58
- *
59
- * 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).
60
- */
61
- export declare function neonSeed(cli: Cli): Promise<number>;
62
- /**
63
- * 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.
64
- */
65
- export declare function runAppSeed(cli: Cli): Promise<void>;
66
- /** The Preview variables `--set-vercel` writes, and which of the branch's URLs each holds. */
67
- export declare const PREVIEW_VARIABLES: readonly [{
68
- readonly name: "DATABASE_URL";
69
- readonly pooled: true;
70
- }, {
71
- readonly name: "DATABASE_URL_UNPOOLED";
72
- readonly pooled: false;
73
- }];
74
- /**
75
- * `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.
76
- *
77
- * 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.
78
- */
79
- export declare function resetPreview(cli: Cli, args?: string[]): Promise<number>;