@wwchen/stack 0.10.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 (71) hide show
  1. package/README.md +42 -25
  2. package/blocks/AGENTS.md +8 -20
  3. package/blocks/CLAUDE.md +9 -27
  4. package/blocks/env.example +1 -7
  5. package/blocks/gitignore +0 -6
  6. package/dist/cli/builtin.d.ts +4 -3
  7. package/dist/cli/builtin.js +31 -36
  8. package/dist/cli/check.d.ts +5 -0
  9. package/dist/cli/check.js +39 -0
  10. package/dist/cli/context.d.ts +1 -18
  11. package/dist/cli/context.js +0 -22
  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 +1 -1
  17. package/dist/cli/host.js +90 -72
  18. package/dist/cli/owned.d.ts +33 -0
  19. package/dist/cli/owned.js +151 -0
  20. package/dist/cli/{sync-blocks.d.ts → sync.d.ts} +6 -2
  21. package/dist/cli/{sync-blocks.js → sync.js} +46 -18
  22. package/dist/configs/vitest.d.ts +3 -1
  23. package/dist/configs/vitest.js +8 -6
  24. package/dist/index.d.ts +2 -2
  25. package/dist/index.js +1 -1
  26. package/dist/next/config.d.ts +2 -0
  27. package/dist/next/config.js +10 -6
  28. package/dist/next/health.d.ts +1 -1
  29. package/dist/next/health.js +1 -1
  30. package/dist/stack/contracts.d.ts +65 -15
  31. package/dist/stack/contracts.js +30 -6
  32. package/files/.claude/rules/stack-ui.md +24 -0
  33. package/files/next.config.ts +6 -0
  34. package/files/src/app/api/health/route.ts +9 -0
  35. package/package.json +6 -37
  36. package/dist/cli/db.d.ts +0 -4
  37. package/dist/cli/db.js +0 -43
  38. package/dist/cli/dev.d.ts +0 -4
  39. package/dist/cli/dev.js +0 -70
  40. package/dist/cli/neon.d.ts +0 -79
  41. package/dist/cli/neon.js +0 -394
  42. package/dist/cli/run.d.ts +0 -2
  43. package/dist/cli/run.js +0 -29
  44. package/dist/db/branches.d.ts +0 -11
  45. package/dist/db/branches.js +0 -19
  46. package/dist/db/doctor.d.ts +0 -9
  47. package/dist/db/doctor.js +0 -120
  48. package/dist/db/env.d.ts +0 -14
  49. package/dist/db/env.js +0 -15
  50. package/dist/db/explaining-pool.d.ts +0 -11
  51. package/dist/db/explaining-pool.js +0 -55
  52. package/dist/db/health.d.ts +0 -10
  53. package/dist/db/health.js +0 -26
  54. package/dist/db/index.d.ts +0 -21
  55. package/dist/db/index.js +0 -32
  56. package/dist/db/migration-status.d.ts +0 -5
  57. package/dist/db/migration-status.js +0 -38
  58. package/dist/db/schema-changes.d.ts +0 -13
  59. package/dist/db/schema-changes.js +0 -99
  60. package/dist/db/ssl.d.ts +0 -4
  61. package/dist/db/ssl.js +0 -17
  62. package/dist/db/target.d.ts +0 -19
  63. package/dist/db/target.js +0 -66
  64. package/dist/db/testing/index.d.ts +0 -23
  65. package/dist/db/testing/index.js +0 -67
  66. package/dist/db/testing/isolate.d.ts +0 -1
  67. package/dist/db/testing/isolate.js +0 -3
  68. package/dist/db/testing/pglite.d.ts +0 -20
  69. package/dist/db/testing/pglite.js +0 -79
  70. package/dist/env/testing.d.ts +0 -6
  71. package/dist/env/testing.js +0 -13
@@ -0,0 +1,151 @@
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { BLOCK_FILES, BUILTIN_PACKAGE, CORE_PACKAGE, FILES_RECORD, } from "../stack/contracts.js";
5
+ import { CliError } from "./context.js";
6
+ /** The name a package owns files under: the built-in package is the core. */
7
+ export const ownerOf = (pkg) => pkg.name === BUILTIN_PACKAGE ? CORE_PACKAGE : pkg.name;
8
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error));
9
+ /** Each package's `files`, read from their sources and made by their `render` where they have one, in package order. */
10
+ export function ownedOutputs(packages) {
11
+ return packages.flatMap((pkg) => (pkg.files ?? []).map(({ path, source, render }) => {
12
+ let text;
13
+ try {
14
+ text = readFileSync(fileURLToPath(source), "utf8");
15
+ }
16
+ catch (error) {
17
+ throw new CliError(`${ownerOf(pkg)}: its file ${path} cannot be read from ${source.href} (${messageOf(error)}). Reinstall the package; nothing was changed.`);
18
+ }
19
+ if (render === undefined)
20
+ return { path, owner: ownerOf(pkg), text };
21
+ try {
22
+ return { path, owner: ownerOf(pkg), text: render(text) };
23
+ }
24
+ catch (error) {
25
+ throw new CliError(`${ownerOf(pkg)}: its file ${path} cannot be written from its source (${messageOf(error)}). Reinstall the package; nothing was changed.`);
26
+ }
27
+ }));
28
+ }
29
+ /** Whether `path` stays under the app's root: relative, `/`-separated, with no empty, `.` or `..` segment. */
30
+ const isSafePath = (path) => path !== "" &&
31
+ !path.includes("\\") &&
32
+ !/^[A-Za-z]:/.test(path) &&
33
+ path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
34
+ /** What is at `file`, without following a link: nothing, a regular file, or anything else. */
35
+ function kindOf(file) {
36
+ try {
37
+ return lstatSync(file).isFile() ? "file" : "other";
38
+ }
39
+ catch {
40
+ return "absent";
41
+ }
42
+ }
43
+ /** The paths the plan changes, each named once, in the order they are applied. */
44
+ export const changedPaths = (plan) => [
45
+ ...plan.writes.map((w) => w.path),
46
+ ...plan.deletes.map((d) => d.path),
47
+ ...(plan.recordChanged ? [FILES_RECORD] : []),
48
+ ];
49
+ /** The record on disk: path to owner; empty when there is none. */
50
+ function readRecord(cwd, problems) {
51
+ const path = join(cwd, FILES_RECORD);
52
+ if (!existsSync(path))
53
+ return {};
54
+ const fix = "Restore it from version control, or delete it and every file it names.";
55
+ try {
56
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
57
+ const files = parsed?.files;
58
+ const entries = typeof files === "object" && files !== null && !Array.isArray(files)
59
+ ? Object.entries(files)
60
+ : undefined;
61
+ if (!entries || entries.some(([, owner]) => typeof owner !== "string")) {
62
+ problems.push(`${FILES_RECORD} has no "files" object of paths to package names. ${fix}`);
63
+ return {};
64
+ }
65
+ return Object.fromEntries(entries);
66
+ }
67
+ catch (error) {
68
+ problems.push(`${FILES_RECORD} cannot be read (${messageOf(error)}). ${fix}`);
69
+ return {};
70
+ }
71
+ }
72
+ /**
73
+ * Plans the owned files against the app's disk and its record: writes a path only when it is absent or recorded, deletes every recorded path no output claims, and refuses, with nothing planned, an unsafe path, a path two packages own and an existing file the record does not name. Every refusal is reported together.
74
+ */
75
+ export function planFiles(cwd, outputs) {
76
+ const problems = [];
77
+ const recorded = readRecord(cwd, problems);
78
+ const claimed = new Map();
79
+ for (const { path, owner } of outputs) {
80
+ const first = claimed.get(path);
81
+ if (first !== undefined) {
82
+ problems.push(`${path} is owned by both ${first} and ${owner}: a path has one owner.`);
83
+ }
84
+ else if (path === FILES_RECORD) {
85
+ problems.push(`${owner}: ${FILES_RECORD} is the stack's own record, so no package can own it.`);
86
+ }
87
+ else if (Object.values(BLOCK_FILES).includes(path)) {
88
+ problems.push(`${owner}: ${path} holds the stack's marked blocks, so no package can own it whole.`);
89
+ }
90
+ else if (!isSafePath(path)) {
91
+ problems.push(`${owner}: its file ${path} is not a path the stack can own: give a path under the app's root, with / separators and no "." or ".." segment.`);
92
+ }
93
+ else {
94
+ claimed.set(path, owner);
95
+ }
96
+ }
97
+ const writes = [];
98
+ for (const output of outputs) {
99
+ if (claimed.get(output.path) !== output.owner)
100
+ continue;
101
+ const file = join(cwd, output.path);
102
+ const kind = kindOf(file);
103
+ if (kind === "absent") {
104
+ writes.push(output);
105
+ }
106
+ else if (kind === "other") {
107
+ problems.push(`${output.path} is a link, a directory or another file that is not a regular file, and the stack writes only regular files: move it out of the way, then run \`stack sync\`.`);
108
+ }
109
+ else if (!(output.path in recorded)) {
110
+ problems.push(`${output.path} exists and the stack does not own it: move your code out of it or delete it, then run \`stack sync\`.`);
111
+ }
112
+ else if (readFileSync(file, "utf8") !== output.text) {
113
+ writes.push(output);
114
+ }
115
+ }
116
+ const deletes = [];
117
+ for (const [path, owner] of Object.entries(recorded)) {
118
+ if (claimed.has(path))
119
+ continue;
120
+ if (path === FILES_RECORD || !isSafePath(path)) {
121
+ problems.push(`${FILES_RECORD} records ${path}, which is not a path the stack can own. Remove that entry.`);
122
+ }
123
+ else if (kindOf(join(cwd, path)) === "other") {
124
+ problems.push(`${path} is recorded as owned by ${owner} but is a link, a directory or another file that is not a regular file: move it out of the way, then run \`stack sync\`.`);
125
+ }
126
+ else {
127
+ deletes.push({ path, owner });
128
+ }
129
+ }
130
+ if (problems.length > 0)
131
+ throw new CliError([...problems, "Nothing was run."].join("\n"));
132
+ const now = Object.fromEntries([...claimed].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
133
+ const record = claimed.size > 0 ? `${JSON.stringify({ files: now }, null, 2)}\n` : null;
134
+ const file = join(cwd, FILES_RECORD);
135
+ const onDisk = existsSync(file) ? readFileSync(file, "utf8") : null;
136
+ return { writes, deletes, record, recordChanged: record !== onDisk };
137
+ }
138
+ /** Applies a plan: writes the files, deletes the recorded ones, then writes or removes the record. */
139
+ export function applyFiles(cwd, plan) {
140
+ for (const { path, text } of plan.writes) {
141
+ const file = join(cwd, path);
142
+ mkdirSync(dirname(file), { recursive: true });
143
+ writeFileSync(file, text);
144
+ }
145
+ for (const { path } of plan.deletes)
146
+ rmSync(join(cwd, path), { force: true });
147
+ if (plan.record === null)
148
+ rmSync(join(cwd, FILES_RECORD), { force: true });
149
+ else if (plan.recordChanged)
150
+ writeFileSync(join(cwd, FILES_RECORD), plan.record);
151
+ }
@@ -1,4 +1,6 @@
1
1
  import { type Command, type StackPackage } from "../stack/contracts.ts";
2
+ import { type Output, ownedOutputs, ownerOf } from "./owned.ts";
3
+ export { type Output, ownedOutputs, ownerOf };
2
4
  /**
3
5
  * Brings every composed package's marked blocks in AGENTS.md, CLAUDE.md, .gitignore and .env.example up to date, removes the blocks of packages the app no longer composes, and returns the files that were (or, with `check`, would be) changed, and each block that was (or would be) removed. Every file is checked before any is written, so a malformed one leaves all of them untouched.
4
6
  */
@@ -11,5 +13,7 @@ export declare function syncBlocks(cwd: string, packages: readonly StackPackage[
11
13
  name: string;
12
14
  }[];
13
15
  }>;
14
- /** `stack sync-blocks [--check]`: writes each composed package's blocks; exits 1 when `--check` finds a stale file. */
15
- export declare const syncBlocksCommand: Command;
16
+ /**
17
+ * `stack sync [--check]`: writes each composed package's blocks and the whole files packages own, records the files in stack.files.json, and deletes a recorded file whose package is gone. Every write and deletion is planned before any happens, so a refusal leaves everything untouched; `--check` exits 1, naming each stale file, and writes nothing.
18
+ */
19
+ export declare const syncCommand: Command;
@@ -3,6 +3,9 @@ import { join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { BLOCK_FILES, BUILTIN_PACKAGE, } from "../stack/contracts.js";
5
5
  import { CliError } from "./context.js";
6
+ import { generatedModules } from "./generate.js";
7
+ import { applyFiles, changedPaths, ownedOutputs, ownerOf, planFiles, } from "./owned.js";
8
+ export { ownedOutputs, ownerOf };
6
9
  const MARKDOWN = {
7
10
  begin: (name) => `<!-- BEGIN:${name} -->`,
8
11
  end: (name) => `<!-- END:${name} -->`,
@@ -20,7 +23,7 @@ const STYLES = {
20
23
  [BLOCK_FILES.gitignore]: HASH,
21
24
  [BLOCK_FILES.envExample]: HASH,
22
25
  };
23
- /** The files `sync-blocks` manages, in the order it reports them, and each one's marker style. */
26
+ /** The files `sync` manages, in the order it reports them, and each one's marker style. */
24
27
  const TARGETS = Object.values(BLOCK_FILES).map((file) => ({ file, style: STYLES[file] }));
25
28
  /**
26
29
  * Whether a marker name is a package's: the built-in one, or a scoped npm name. Every package that writes blocks has one of these names, so a block left by a package the app no longer composes is still recognised, while another tool's marked block (Next's `nextjs-agent-rules`) is never the stack's to touch.
@@ -151,7 +154,7 @@ function wantedBlocks(packages) {
151
154
  for (const { file, source } of pkg.blocks) {
152
155
  const list = wanted.get(file);
153
156
  if (!list) {
154
- throw new CliError(`${pkg.name}: sync-blocks writes no block into ${file}; it manages ${TARGETS.map((t) => t.file).join(", ")}. Nothing was changed.`);
157
+ throw new CliError(`${pkg.name}: sync writes no block into ${file}; it manages ${TARGETS.map((t) => t.file).join(", ")}. Nothing was changed.`);
155
158
  }
156
159
  if (list.some((b) => b.name === pkg.name)) {
157
160
  throw new CliError(`${pkg.name}: gives two blocks for ${file}. Nothing was changed.`);
@@ -161,10 +164,8 @@ function wantedBlocks(packages) {
161
164
  }
162
165
  return wanted;
163
166
  }
164
- /**
165
- * Brings every composed package's marked blocks in AGENTS.md, CLAUDE.md, .gitignore and .env.example up to date, removes the blocks of packages the app no longer composes, and returns the files that were (or, with `check`, would be) changed, and each block that was (or would be) removed. Every file is checked before any is written, so a malformed one leaves all of them untouched.
166
- */
167
- export async function syncBlocks(cwd, packages, opts = {}) {
167
+ /** Every block file's new text, planned before any is written: a malformed file throws and leaves all untouched. */
168
+ function planBlocks(cwd, packages) {
168
169
  const wanted = wantedBlocks(packages);
169
170
  const writes = [];
170
171
  const removed = [];
@@ -176,28 +177,55 @@ export async function syncBlocks(cwd, packages, opts = {}) {
176
177
  writes.push({ path, file, text: after.text });
177
178
  removed.push(...after.removed.map((name) => ({ file, name })));
178
179
  }
180
+ return { writes, removed };
181
+ }
182
+ /**
183
+ * Brings every composed package's marked blocks in AGENTS.md, CLAUDE.md, .gitignore and .env.example up to date, removes the blocks of packages the app no longer composes, and returns the files that were (or, with `check`, would be) changed, and each block that was (or would be) removed. Every file is checked before any is written, so a malformed one leaves all of them untouched.
184
+ */
185
+ export async function syncBlocks(cwd, packages, opts = {}) {
186
+ const { writes, removed } = planBlocks(cwd, packages);
179
187
  if (!opts.check)
180
188
  for (const w of writes)
181
189
  writeFileSync(w.path, w.text);
182
190
  return { changed: writes.map((w) => w.file), removed };
183
191
  }
184
- /** `stack sync-blocks [--check]`: writes each composed package's blocks; exits 1 when `--check` finds a stale file. */
185
- export const syncBlocksCommand = async (ctx, args) => {
192
+ /**
193
+ * `stack sync [--check]`: writes each composed package's blocks and the whole files packages own, records the files in stack.files.json, and deletes a recorded file whose package is gone. Every write and deletion is planned before any happens, so a refusal leaves everything untouched; `--check` exits 1, naming each stale file, and writes nothing.
194
+ */
195
+ export const syncCommand = async (ctx, args) => {
186
196
  const unknown = args.filter((a) => a !== "--check");
187
197
  if (unknown.length > 0)
188
- throw new CliError(`sync-blocks: unknown argument ${unknown[0]}`);
198
+ throw new CliError(`sync: unknown argument ${unknown[0]}`);
189
199
  const check = args.includes("--check");
190
- const { changed, removed } = await syncBlocks(ctx.cwd, ctx.packages, { check });
191
- if (check && changed.length > 0) {
192
- ctx.error(`stale stack blocks: ${changed.join(", ")}. Run \`stack sync-blocks\`.`);
193
- return 1;
200
+ const blocks = planBlocks(ctx.cwd, ctx.packages);
201
+ const files = planFiles(ctx.cwd, [
202
+ ...ownedOutputs(ctx.packages),
203
+ ...generatedModules(ctx.packages),
204
+ ]);
205
+ const staleBlocks = blocks.writes.map((w) => w.file);
206
+ const staleFiles = changedPaths(files);
207
+ if (check) {
208
+ if (staleBlocks.length > 0) {
209
+ ctx.error(`stale stack blocks: ${staleBlocks.join(", ")}. Run \`stack sync\`.`);
210
+ }
211
+ if (staleFiles.length > 0) {
212
+ ctx.error(`stale stack files: ${staleFiles.join(", ")}. Run \`stack sync\`.`);
213
+ }
214
+ return staleBlocks.length + staleFiles.length > 0 ? 1 : 0;
194
215
  }
195
- // Removing a block is the one thing sync-blocks deletes, so each is said: a package the app composes no longer, or one stack.config.ts drops by mistake.
196
- for (const { file, name } of removed)
216
+ applyFiles(ctx.cwd, files);
217
+ for (const w of blocks.writes)
218
+ writeFileSync(w.path, w.text);
219
+ // Removing a block or a file is something sync deletes, so each is said: a package the app no longer lists in package.json, or one dropped from it by mistake.
220
+ for (const { file, name } of blocks.removed)
197
221
  ctx.log(`removed ${name}'s block from ${file}`);
198
- for (const file of changed)
222
+ for (const file of staleBlocks)
199
223
  ctx.log(`updated ${file}`);
200
- if (changed.length === 0)
201
- ctx.log("stack blocks are up to date");
224
+ for (const { path, owner } of files.writes)
225
+ ctx.log(`wrote ${path} (${owner})`);
226
+ for (const { path, owner } of files.deletes)
227
+ ctx.log(`deleted ${path} (${owner})`);
228
+ if (staleBlocks.length + staleFiles.length === 0)
229
+ ctx.log("stack is up to date");
202
230
  return 0;
203
231
  };
@@ -1,4 +1,6 @@
1
1
  import type { ViteUserConfig as UserConfig } from "vitest/config";
2
- export declare function stackVitestConfig(overrides?: UserConfig, options?: {
2
+ import type { EnvFragment } from "../stack/contracts.ts";
3
+ export declare function stackVitestConfig(overrides: UserConfig, options: {
3
4
  root?: string;
5
+ fragments: readonly EnvFragment[];
4
6
  }): UserConfig;
@@ -1,9 +1,12 @@
1
1
  import { resolve as resolvePath } from "node:path";
2
2
  const toArray = (value) => value === undefined ? [] : Array.isArray(value) ? value : [value];
3
- // Vitest settings shared by every app. `overrides` is merged, not substituted: an app's `setupFiles`, `include`, `exclude` and `env` are added to the preset's, and any other key the app sets wins.
4
- export function stackVitestConfig(overrides = {}, options = {}) {
3
+ // Vitest settings shared by every app. `overrides` is merged, not substituted: an app's `setupFiles`, `include`, `exclude` and `env` are added to the preset's, and any other key the app sets wins. `fragments` put each package's test values in `test.env`, under the app's own `env`, and are required, so an app's tests never run without them (a database package's keep every test off a real database): an app passes its generated `src/stack/env.ts`'s, whatever packages it has, and a package's own test config passes its own list or `[]`.
4
+ export function stackVitestConfig(overrides, options) {
5
+ if (!Array.isArray(options?.fragments)) {
6
+ throw new Error('stackVitestConfig: pass the packages\' test values: stackVitestConfig(…, { fragments }), with `fragments` from "./src/stack/env.ts".');
7
+ }
5
8
  const { test: appTest = {}, resolve: appResolve, ...appRest } = overrides;
6
- const { root = process.cwd() } = options;
9
+ const { root = process.cwd(), fragments } = options;
7
10
  const alias = { "@": resolvePath(root, "src") };
8
11
  const appAlias = appResolve?.alias;
9
12
  const { setupFiles, include, exclude, env, ...appTestRest } = appTest;
@@ -24,8 +27,7 @@ export function stackVitestConfig(overrides = {}, options = {}) {
24
27
  testTimeout: 60000,
25
28
  hookTimeout: 60000,
26
29
  ...appTestRest,
27
- // Runs before anything loads `.env`, so a test can never reach a real database.
28
- setupFiles: ["@wwchen/stack/db/testing/isolate", ...toArray(setupFiles)],
30
+ setupFiles: toArray(setupFiles),
29
31
  include: [
30
32
  "tests/unit/**/*.test.{ts,tsx}",
31
33
  "tests/integration/**/*.test.{ts,tsx}",
@@ -33,7 +35,7 @@ export function stackVitestConfig(overrides = {}, options = {}) {
33
35
  ...toArray(include),
34
36
  ],
35
37
  exclude: ["node_modules/**", ".next/**", "dist/**", "tests/e2e/**", ...toArray(exclude)],
36
- env: { TZ: "UTC", ...env },
38
+ env: { TZ: "UTC", ...Object.assign({}, ...fragments.map((f) => f.testValues)), ...env },
37
39
  },
38
40
  };
39
41
  }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export type { Block, BlockFile, BuildStep, Command, CommandContext, DoctorCheck, DoctorFacts, Env, EnvFragment, EnvVarMeta, ExecOptions, ExecResult, Finding, Gate, GateResult, HealthCheck, NodeEnv, Severity, StackConfig, StackPackage, VariableOf, VercelTarget, } from "./stack/contracts.ts";
2
- export { BLOCK_FILES, BUILTIN_PACKAGE, defineStack, NODE_ENVS, packageBlocks, SEVERITY, STACK_CONFIG_FILE, VERCEL_TARGET, } from "./stack/contracts.ts";
1
+ export type { Block, BlockFile, BuildStep, Check, Command, CommandContext, DoctorCheck, DoctorFacts, Env, EnvFragment, EnvVarMeta, ExecOptions, ExecResult, Export, Finding, Gate, GateResult, HealthCheck, NodeEnv, OwnedFile, PackageSettings, Severity, StackConfig, StackFactory, StackPackage, VariableOf, VercelTarget, } from "./stack/contracts.ts";
2
+ export { BLOCK_FILES, BUILTIN_PACKAGE, CORE_PACKAGE, defineStack, FILES_RECORD, GENERATED, NODE_ENVS, packageBlocks, SEVERITY, STACK_CONFIG_FILE, starterFileChecks, VERCEL_TARGET, } from "./stack/contracts.ts";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { BLOCK_FILES, BUILTIN_PACKAGE, defineStack, NODE_ENVS, packageBlocks, SEVERITY, STACK_CONFIG_FILE, VERCEL_TARGET, } from "./stack/contracts.js";
1
+ export { BLOCK_FILES, BUILTIN_PACKAGE, CORE_PACKAGE, defineStack, FILES_RECORD, GENERATED, NODE_ENVS, packageBlocks, SEVERITY, STACK_CONFIG_FILE, starterFileChecks, VERCEL_TARGET, } from "./stack/contracts.js";
@@ -4,5 +4,7 @@ export type WithStackOptions = {
4
4
  isProduction?: boolean;
5
5
  /** Extra `connect-src` origins (an API or analytics host the browser calls). */
6
6
  cspConnectSrc?: string[];
7
+ /** Files a route reads at run time, by route, merged into `outputFileTracingIncludes`: Vercel bundles only traced files. The generated `src/stack/next.ts` holds the packages' share. */
8
+ tracing?: Record<string, string[]>;
7
9
  };
8
10
  export declare function withStack(appConfig?: NextConfig, opts?: WithStackOptions): NextConfig;
@@ -1,6 +1,6 @@
1
1
  import { isProductionEnv } from "../env/index.js";
2
2
  /**
3
- * `next.config.ts`: `export default withStack({ ...the app's own config })`.
3
+ * `next.config.ts`: `export default withStack({ ...the app's own config }, { tracing })`.
4
4
  *
5
5
  * Sentry (or any monitor) is initialised at runtime from `instrumentation.ts`, not through a build-time config wrapper, so there is nothing to compose here.
6
6
  */
@@ -51,6 +51,14 @@ function contentSecurityPolicy(connectSrc) {
51
51
  "upgrade-insecure-requests",
52
52
  ].join("; ");
53
53
  }
54
+ /** The app's tracing and the stack's, each route's globs joined without repeats. */
55
+ function mergeTracing(app = {}, stack = {}) {
56
+ const merged = { ...app };
57
+ for (const [route, globs] of Object.entries(stack)) {
58
+ merged[route] = [...new Set([...(merged[route] ?? []), ...globs])];
59
+ }
60
+ return merged;
61
+ }
54
62
  export function withStack(appConfig = {}, opts = {}) {
55
63
  const isProduction = opts.isProduction ?? isProductionEnv();
56
64
  const stackHeaders = isProduction
@@ -66,11 +74,7 @@ export function withStack(appConfig = {}, opts = {}) {
66
74
  reactStrictMode: true,
67
75
  ...appConfig,
68
76
  poweredByHeader: false,
69
- // The health route checks the migrations folder at runtime. Vercel bundles only traced files, so without this the read fails and migrations always report "unknown".
70
- outputFileTracingIncludes: {
71
- ...appConfig.outputFileTracingIncludes,
72
- "/api/health": ["./drizzle/**"],
73
- },
77
+ outputFileTracingIncludes: mergeTracing(appConfig.outputFileTracingIncludes, opts.tracing),
74
78
  // The stack's headers first, then the app's own.
75
79
  async headers() {
76
80
  return [
@@ -4,7 +4,7 @@ import type { HealthCheck } from "../stack/contracts.ts";
4
4
  *
5
5
  * Without the token the answer is `{ ok: true }` and no check runs, so an anonymous caller cannot make the app touch what the checks probe. With `Authorization: Bearer $HEALTH_TOKEN` each check runs in turn and its fields join the answer in order; a check that throws reports `{ [name]: "unknown" }`. `HEALTH_TOKEN` is its own secret, never `CRON_SECRET`.
6
6
  *
7
- * `export const GET = healthRoute({ token: env.HEALTH_TOKEN, checks: [databaseCheck(db)] })`, with `dynamic = "force-dynamic"`.
7
+ * `export const GET = healthRoute({ token: env.HEALTH_TOKEN, checks: healthChecks(env) })`, with `dynamic = "force-dynamic"`.
8
8
  */
9
9
  export declare function healthRoute(opts: {
10
10
  token?: string;
@@ -4,7 +4,7 @@ import { bearerMatches } from "../http/guards.js";
4
4
  *
5
5
  * Without the token the answer is `{ ok: true }` and no check runs, so an anonymous caller cannot make the app touch what the checks probe. With `Authorization: Bearer $HEALTH_TOKEN` each check runs in turn and its fields join the answer in order; a check that throws reports `{ [name]: "unknown" }`. `HEALTH_TOKEN` is its own secret, never `CRON_SECRET`.
6
6
  *
7
- * `export const GET = healthRoute({ token: env.HEALTH_TOKEN, checks: [databaseCheck(db)] })`, with `dynamic = "force-dynamic"`.
7
+ * `export const GET = healthRoute({ token: env.HEALTH_TOKEN, checks: healthChecks(env) })`, with `dynamic = "force-dynamic"`.
8
8
  */
9
9
  export function healthRoute(opts) {
10
10
  const checks = opts.checks ?? [];
@@ -1,9 +1,19 @@
1
1
  import type { z } from "zod";
2
- /** The file that composes the app's packages. */
2
+ /** The file that gives the app's packages their settings. */
3
3
  export declare const STACK_CONFIG_FILE = "stack.config.ts";
4
4
  /** The built-in package's name, which its blocks' markers carry. */
5
5
  export declare const BUILTIN_PACKAGE = "stack";
6
- /** The files `stack sync-blocks` writes packages' marked blocks into. */
6
+ /** The core's npm name, which owns its files in the files record and in headers. */
7
+ export declare const CORE_PACKAGE = "@wwchen/stack";
8
+ /** The file recording which package owns each file `stack sync` writes. */
9
+ export declare const FILES_RECORD = "stack.files.json";
10
+ /** The modules `stack sync` generates from the packages' runtime pieces, relative to the app's root. */
11
+ export declare const GENERATED: {
12
+ readonly env: "src/stack/env.ts";
13
+ readonly health: "src/stack/health.ts";
14
+ readonly next: "src/stack/next.ts";
15
+ };
16
+ /** The files `stack sync` writes packages' marked blocks into. */
7
17
  export declare const BLOCK_FILES: {
8
18
  readonly agents: "AGENTS.md";
9
19
  readonly claude: "CLAUDE.md";
@@ -11,7 +21,7 @@ export declare const BLOCK_FILES: {
11
21
  readonly envExample: ".env.example";
12
22
  };
13
23
  export type BlockFile = (typeof BLOCK_FILES)[keyof typeof BLOCK_FILES];
14
- /** A package's marked block: the file it goes in, and its text. */
24
+ /** A package's marked block: the file it goes in, and the URL of the file its text is read from. */
15
25
  export type Block = {
16
26
  file: BlockFile;
17
27
  source: URL;
@@ -63,6 +73,8 @@ export type CommandContext = {
63
73
  exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
64
74
  log(message: string): void;
65
75
  error(message: string): void;
76
+ /** Imports a file of the app by its root-relative path. */
77
+ importApp(path: string): Promise<Record<string, unknown>>;
66
78
  /** Every composed package, the built-in one first. */
67
79
  packages: readonly StackPackage[];
68
80
  };
@@ -99,27 +111,64 @@ export type DoctorFacts = {
99
111
  truncated?: boolean;
100
112
  };
101
113
  export type DoctorCheck = (facts: DoctorFacts) => Promise<Finding[]>;
102
- /** What a package's `/stack` entry gives the app's `stack.config.ts`. */
114
+ /** What a package's `./stack` entry gives the `stack` CLI. */
103
115
  export type StackPackage = {
104
- /** A composed package's npm name (`@scope/name`; the built-in package is `stack`): its blocks' markers, and how the host tells an installed package from a composed one. */
116
+ /** The package's npm name (`@scope/name`; the built-in package is `stack`), which its factory returns as its package.json names it: its blocks' markers, the owner `stack.files.json` records for its files, its settings' key in `stack.config.ts`, and how `stack` names it in the usage and in a failure. */
105
117
  name: string;
106
118
  /** Each command's loader, called only when that command runs. */
107
119
  commands?: Record<string, () => Promise<Command>>;
108
120
  buildSteps?: BuildStep[];
109
121
  doctorChecks?: DoctorCheck[];
110
- /** The marked blocks `sync-blocks` writes. */
122
+ /** The marked blocks `sync` writes. */
111
123
  blocks?: Block[];
124
+ /** Checks `stack check` runs, which CI runs. */
125
+ checks?: Check[];
126
+ /** Whole files `stack sync` owns in the app. */
127
+ files?: OwnedFile[];
128
+ /** The pieces `stack sync` wires into the app's generated modules. */
129
+ runtime?: {
130
+ /** An `EnvFragment`, for `src/stack/env.ts`. */
131
+ env?: Export;
132
+ /** A `(env) => HealthCheck`, for `src/stack/health.ts`. */
133
+ health?: Export;
134
+ /** Files a route reads at run time, by route, for `src/stack/next.ts`. */
135
+ tracing?: Record<string, string[]>;
136
+ };
137
+ };
138
+ /** A step of `stack check`; a throw fails it. */
139
+ export type Check = {
140
+ name: string;
141
+ run(ctx: CommandContext): Promise<void>;
112
142
  };
113
- export type StackConfig = {
114
- packages: StackPackage[];
143
+ /** A whole file `stack sync` owns: its path relative to the app's root, the URL of the file it is written from, and, for a file that carries the package's settings, `render`, which makes the text written from the source's. */
144
+ export type OwnedFile = {
145
+ path: string;
146
+ source: URL;
147
+ render?: (source: string) => string;
115
148
  };
116
- /** A function has `call`, so a package's factory listed without its call (`infra` for `infra()`) is a type error in `defineStack`. */
117
- type NotAFactory = {
118
- call?: never;
149
+ /** An import specifier and an export name. */
150
+ export type Export = {
151
+ from: string;
152
+ name: string;
153
+ };
154
+ /**
155
+ * `stack check`'s checks that the app has each of `paths`: files of the app's own that a package's owned files or commands read, which `pkg`'s README shows under `section`. One check per file, named by its path, so each missing file fails on a line of its own with where to find it.
156
+ */
157
+ export declare function starterFileChecks(pkg: string, section: string, paths: readonly string[]): Check[];
158
+ /** A package's `./stack` entry's default export: the package, from the app's settings for it (undefined when `stack.config.ts` gives none). It throws, naming the setting, when it needs settings and has none. */
159
+ export type StackFactory<S = never> = (settings: S | undefined) => StackPackage;
160
+ /** A package's settings in `stack.config.ts`, made by that package's helper (`authSettings({ … })`). */
161
+ export type PackageSettings<S = unknown> = {
162
+ package: string;
163
+ settings: S;
164
+ };
165
+ /** The app's `stack.config.ts`: the settings it gives the packages its package.json lists. */
166
+ export type StackConfig = {
167
+ settings: PackageSettings[];
119
168
  };
120
- /** The app's composition, the default export of its `stack.config.ts`. Throws on two packages with one name; the `stack` CLI refuses an entry that is not a package. */
169
+ /** The default export of the app's `stack.config.ts`. Throws on two settings for one package; the `stack` CLI refuses settings for a package package.json does not list. */
121
170
  export declare function defineStack(config: {
122
- packages: (StackPackage & NotAFactory)[];
171
+ settings: PackageSettings[];
123
172
  }): StackConfig;
124
173
  export type GateResult<P> = {
125
174
  ok: true;
@@ -135,7 +184,7 @@ export type HealthCheck = {
135
184
  name: string;
136
185
  check(): Promise<Record<string, string>>;
137
186
  };
138
- /** A fragment's variable names: a name checked against them (`"DATABASE_URL" satisfies VariableOf<typeof dbEnv>`) fails the typecheck when the fragment drops it. */
187
+ /** A fragment's variable names: a name checked against them (`"SOME_NAME" satisfies VariableOf<typeof someEnv>`) fails the typecheck when the fragment drops it. */
139
188
  export type VariableOf<F extends EnvFragment> = keyof F["schema"] & string;
140
189
  /** A package's share of the app's env schema, which the app merges in `defineEnv({ fragments })`. */
141
190
  export type EnvFragment<S extends z.ZodRawShape = z.ZodRawShape> = {
@@ -148,5 +197,6 @@ export type EnvFragment<S extends z.ZodRawShape = z.ZodRawShape> = {
148
197
  groups?: Readonly<Record<string, readonly (keyof S & string)[]>>;
149
198
  /** Values an unset variable takes during a build or with validation skipped, where nothing connects to what it names. */
150
199
  buildPlaceholders?: Partial<Record<keyof S & string, string>>;
200
+ /** Values `stackVitestConfig` puts in `test.env`. */
201
+ testValues?: Partial<Record<keyof S & string, string>>;
151
202
  };
152
- export {};
@@ -1,8 +1,18 @@
1
- /** The file that composes the app's packages. */
1
+ /** The file that gives the app's packages their settings. */
2
2
  export const STACK_CONFIG_FILE = "stack.config.ts";
3
3
  /** The built-in package's name, which its blocks' markers carry. */
4
4
  export const BUILTIN_PACKAGE = "stack";
5
- /** The files `stack sync-blocks` writes packages' marked blocks into. */
5
+ /** The core's npm name, which owns its files in the files record and in headers. */
6
+ export const CORE_PACKAGE = "@wwchen/stack";
7
+ /** The file recording which package owns each file `stack sync` writes. */
8
+ export const FILES_RECORD = "stack.files.json";
9
+ /** The modules `stack sync` generates from the packages' runtime pieces, relative to the app's root. */
10
+ export const GENERATED = {
11
+ env: "src/stack/env.ts",
12
+ health: "src/stack/health.ts",
13
+ next: "src/stack/next.ts",
14
+ };
15
+ /** The files `stack sync` writes packages' marked blocks into. */
6
16
  export const BLOCK_FILES = {
7
17
  agents: "AGENTS.md",
8
18
  claude: "CLAUDE.md",
@@ -27,15 +37,29 @@ export const VERCEL_TARGET = {
27
37
  preview: "preview",
28
38
  development: "development",
29
39
  };
30
- /** The app's composition, the default export of its `stack.config.ts`. Throws on two packages with one name; the `stack` CLI refuses an entry that is not a package. */
40
+ /**
41
+ * `stack check`'s checks that the app has each of `paths`: files of the app's own that a package's owned files or commands read, which `pkg`'s README shows under `section`. One check per file, named by its path, so each missing file fails on a line of its own with where to find it.
42
+ */
43
+ export function starterFileChecks(pkg, section, paths) {
44
+ return paths.map((path) => ({
45
+ name: path,
46
+ async run(ctx) {
47
+ const { existsSync } = await import("node:fs");
48
+ if (!existsSync(`${ctx.cwd}/${path}`)) {
49
+ throw new Error(`missing: write it as ${pkg}'s README shows it, under "${section}".`);
50
+ }
51
+ },
52
+ }));
53
+ }
54
+ /** The default export of the app's `stack.config.ts`. Throws on two settings for one package; the `stack` CLI refuses settings for a package package.json does not list. */
31
55
  export function defineStack(config) {
32
56
  const seen = new Set();
33
- for (const entry of config.packages) {
34
- const name = entry?.name;
57
+ for (const entry of config.settings ?? []) {
58
+ const name = entry?.package;
35
59
  if (typeof name !== "string")
36
60
  continue;
37
61
  if (seen.has(name))
38
- throw new Error(`${STACK_CONFIG_FILE}: two packages are named ${name}`);
62
+ throw new Error(`${STACK_CONFIG_FILE}: two settings for ${name}`);
39
63
  seen.add(name);
40
64
  }
41
65
  return config;
@@ -0,0 +1,24 @@
1
+ ---
2
+ description: LDS design system, layout and accessibility conventions for pages and components (owned by @wwchen/stack)
3
+ paths:
4
+ - "src/app/**"
5
+ - "src/components/**"
6
+ ---
7
+
8
+ <!-- Owned by @wwchen/stack: `stack sync` writes this file. Put this app's own UI rules in another file under .claude/rules/. -->
9
+
10
+ # UI conventions (stack)
11
+
12
+ - **LDS is the design system**: `@lew-ds/lds` and its React binding `@lew-ds/lds-react`. Import every component from `@wwchen/stack/ui`, never from the package directly: that module routes `Button`, `IconButton`, `Link` and `Row` hrefs through `next/link`. Components emit LDS's own markup and LDS's stylesheet paints them. **Never hand-roll a pill, badge, button, input, table or banner**, and never restyle an `lds-*` class from a call site. If LDS lacks something, fix it upstream in LDS.
13
+ - **Tailwind is for layout** (flex, grid, gap, width, alignment, truncation). Colour, type, radius and shadow utilities exist only as LDS roles, from `@wwchen/stack/ui/globals.css`: `bg-bg`, `bg-surface`, `border-border`, `border-border-subdued`, `text-fg`, `text-fg-subdued`, `text-icon`, `text-accent`, `text-link`, `text-danger`; `text-micro` · `text-secondary` · `text-small` · `text-copy` · `text-emphasis` · `text-section` · `text-headline`; `rounded-card`, `shadow-panel`. No raw hex or px in a component.
14
+ - Which component: an action is a **Button** (one `emphasis="strong"` per view for the main action; `variant="tertiary"` for quiet and cancel); an icon-only action is an **IconButton**, whose one `label` is both its `aria-label` and its Tooltip. Navigation is a **Link**. A list of like things is **Row**s; tabular data is a **Table** with a `<caption>` or `aria-label`. A condition the page states until it changes is a **Banner**; a one-line status beside a control is **Inline** (`role="alert"` for an error).
15
+ - **Icons:** a glyph the app names must be in `APP_ICONS` (`src/components/app-icons.ts`); only those, plus what LDS's components draw, are inlined into the page by `StackRoot`. The icons test (`checkIcons`) keeps the list exact.
16
+ - **Dark mode** is `theme-product mode-dark` on `<html>`, written by the server from the theme cookie in the first response (`resolveTheme`, `htmlClassName`). No client-side theme fix-up. The Tailwind `dark:` variant keys on `.mode-dark`.
17
+ - Every list and async surface specifies loading, empty and error. The empty state names the next action, never "No data".
18
+ - **Storybook** shows every UI state from fixtures: stories sit beside their component as `*.stories.tsx` and render the real components, never a hand-built look. A design change lands in the component and its stories (narrow and wide) in the same change. Check a changed story wide and narrow (`PHONE` and `SMALL_PHONE` from `@wwchen/stack/storybook`), in light and dark; CI's `pnpm storybook:build` only proves every story compiles.
19
+ - Server components by default; `"use client"` on the smallest leaf that needs state or an event handler, never on a layout.
20
+ - Content: sentence case, specific verbs on actions, errors that state the fix.
21
+ - `font-variant-numeric: tabular-nums` (`data-numeric`) on every money and count figure.
22
+ - **Layouts respond to the width a component has (container queries), never to the device.** No user-agent checks; prefer a fluid layout (wrap, `minmax`) to a hard switch.
23
+ - Accessibility is a build gate, not polish: one `h1` per page, landmarks on every layout, a visible focus ring at 3:1 or more, a label on every input, errors as text and not colour alone, 24×24 minimum pointer targets, usable at 200% zoom and 320 CSS px wide with no horizontal scroll.
24
+ - Never render free text from a URL. A page reads short codes from the query (`?sent=1`) and says its own fixed sentence.
@@ -0,0 +1,6 @@
1
+ // Owned by @wwchen/stack: `stack sync` writes this file. Put this app's own Next config in `next.config.app.ts`; `withStack` adds the security headers and the production CSP, and `tracing` (generated from the packages) names the files each route reads at run time.
2
+ import { withStack } from "@wwchen/stack/next";
3
+ import appConfig from "./next.config.app.ts";
4
+ import { tracing } from "./src/stack/next.ts";
5
+
6
+ export default withStack(appConfig, { tracing });
@@ -0,0 +1,9 @@
1
+ // Owned by @wwchen/stack: `stack sync` writes this file. Liveness: always 200, `{ ok: true }` without touching the database. With `Authorization: Bearer $HEALTH_TOKEN` it also reports what each package's health check probes.
2
+
3
+ import { healthRoute } from "@wwchen/stack/next";
4
+ import { env } from "@/lib/env";
5
+ import { healthChecks } from "@/stack/health";
6
+
7
+ export const dynamic = "force-dynamic";
8
+
9
+ export const GET = healthRoute({ token: env.HEALTH_TOKEN, checks: healthChecks(env) });