create-stitchkit 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/package.json +1 -1
- package/template/README.md +11 -0
- package/template/_env.example +3 -0
- package/template/docs/ADDING_A_FEATURE.md +35 -11
- package/template/package.json +2 -1
- package/template/scripts/check-authored.test.ts +43 -0
- package/template/scripts/check-authored.ts +51 -20
- package/template/scripts/dev.ts +6 -1
- package/template/scripts/guide-paths.test.ts +37 -0
- package/template/scripts/guide-paths.ts +66 -0
- package/template/scripts/local-env.test.ts +50 -1
- package/template/scripts/local-env.ts +53 -9
package/CHANGELOG.md
CHANGED
|
@@ -12,6 +12,48 @@ step is overwritten by the next release.
|
|
|
12
12
|
|
|
13
13
|
## [Unreleased]
|
|
14
14
|
|
|
15
|
+
## [0.5.1] — 2026-09-01
|
|
16
|
+
|
|
17
|
+
Three findings from someone setting up a new application on the starter from
|
|
18
|
+
scratch, as a consumer who had never seen it. All of them live between "the
|
|
19
|
+
scaffold is green" and "my first feature renders".
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- **The generated `.env` no longer looks ready when it is not.** `local-env.ts`
|
|
24
|
+
rendered the database name and left `USER:PASSWORD` literal, in a file a
|
|
25
|
+
generator had just written — and a generated file reads as finished.
|
|
26
|
+
`assertUsableEnvironment` now names the file, the line and the variable, and
|
|
27
|
+
covers `ACCEPTANCE_DATABASE_URL` as well as `DATABASE_URL`. It runs before the
|
|
28
|
+
supervisor check, so an unusable environment is reported instead of a pm2
|
|
29
|
+
error, and on every run rather than only the one that created the file.
|
|
30
|
+
Rendering still succeeds: a generator that refuses to generate would break
|
|
31
|
+
`--no-install` scaffolding.
|
|
32
|
+
|
|
33
|
+
- **`CREATEDB` is named where `DATABASE_URL` is named.** `prisma migrate dev`
|
|
34
|
+
creates a shadow database, so a least-privilege role — the sensible default
|
|
35
|
+
on a shared server — fails `db:migrate` with `P3014`. Neither the README nor
|
|
36
|
+
`_env.example` mentioned it.
|
|
37
|
+
|
|
38
|
+
- **`check:authored` no longer refuses `as const`.** The gate exists to catch a
|
|
39
|
+
cast that can *launder* a type; a const-assertion only narrows, introduces no
|
|
40
|
+
name and cannot widen. Five of the first fifteen findings on a real adoption
|
|
41
|
+
were this false positive. Findings now also name the sanctioned alternative
|
|
42
|
+
instead of only the sin.
|
|
43
|
+
|
|
44
|
+
- **`ADDING_A_FEATURE.md` no longer points at files the scaffold lacks.** Steps
|
|
45
|
+
4 and 5 referenced `lib/api/client.ts` and a "shared realtime source" that a
|
|
46
|
+
generated project does not contain, phrased as "the same pattern used by the
|
|
47
|
+
application's other contracts" — of which there were none. Both steps now
|
|
48
|
+
create what they need, with the transport file given in full.
|
|
49
|
+
|
|
50
|
+
### Added
|
|
51
|
+
|
|
52
|
+
- **`check:guides`**, part of `check`: every repository path a guide names must
|
|
53
|
+
exist, unless the guide declares it with `(created in this step)`. The guide
|
|
54
|
+
had five such references and three of them were legitimate; only a gate tells
|
|
55
|
+
those apart reliably.
|
|
56
|
+
|
|
15
57
|
## [0.5.0] — 2026-09-01
|
|
16
58
|
|
|
17
59
|
### ⚠️ Breaking changes
|
package/package.json
CHANGED
package/template/README.md
CHANGED
|
@@ -29,6 +29,17 @@ Point `DATABASE_URL` in `.env` at an existing PostgreSQL database, then run:
|
|
|
29
29
|
bun run dev
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
+
`.env` is generated on first run with the database name filled in and the
|
|
33
|
+
credentials left as `USER:PASSWORD`. Replace them: `dev` refuses to start while
|
|
34
|
+
the placeholder is there, naming the file and the line, rather than letting the
|
|
35
|
+
driver fail on the first request.
|
|
36
|
+
|
|
37
|
+
**The role that runs `bun run db:migrate` needs `CREATEDB`.** `prisma migrate
|
|
38
|
+
dev` creates a throwaway shadow database to diff against, so a least-privilege
|
|
39
|
+
role — the sensible default for a shared server — fails with `P3014: could not
|
|
40
|
+
create the shadow database`. Grant `CREATEDB` to the development role, or point
|
|
41
|
+
Prisma at a shadow database you create yourself.
|
|
42
|
+
|
|
32
43
|
The command validates the environment, generates the Prisma client, applies any
|
|
33
44
|
database migrations you add and launches:
|
|
34
45
|
|
package/template/_env.example
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
NODE_ENV=development
|
|
2
|
+
# Replace USER:PASSWORD before the first `bun run dev` — it refuses to start
|
|
3
|
+
# while they are here. The role also needs CREATEDB if it will run
|
|
4
|
+
# `db:migrate`: `prisma migrate dev` creates a shadow database to diff against.
|
|
2
5
|
DATABASE_URL=postgresql://USER:PASSWORD@127.0.0.1:5432/stitchkit_starter
|
|
3
6
|
# The throwaway database `bun run acceptance:local` creates and writes to. The
|
|
4
7
|
# runtime gates WRITE, so they get one of their own: the harness refuses to
|
|
@@ -7,7 +7,7 @@ same files beside it.
|
|
|
7
7
|
|
|
8
8
|
## 1. Define the wire data
|
|
9
9
|
|
|
10
|
-
Create `packages/shared/src/schemas/status.ts
|
|
10
|
+
Create `packages/shared/src/schemas/status.ts` (created in this step):
|
|
11
11
|
|
|
12
12
|
```ts
|
|
13
13
|
import { z } from 'zod'
|
|
@@ -21,7 +21,7 @@ Export it from the shared package. Do not introduce a second handwritten DTO.
|
|
|
21
21
|
|
|
22
22
|
## 2. Define the HTTP/tool contract separately
|
|
23
23
|
|
|
24
|
-
Create `packages/shared/src/contracts/status.ts` and import the named schemas:
|
|
24
|
+
Create `packages/shared/src/contracts/status.ts` (created in this step) and import the named schemas:
|
|
25
25
|
|
|
26
26
|
```ts
|
|
27
27
|
import { defineContract } from 'stitchkit'
|
|
@@ -44,7 +44,7 @@ The contract owns transport identity. Do not add a raw route or duplicate path.
|
|
|
44
44
|
|
|
45
45
|
## 3. Implement and register the service
|
|
46
46
|
|
|
47
|
-
Create `packages/backend/src/transport/status-service.ts` with `implement()`.
|
|
47
|
+
Create `packages/backend/src/transport/status-service.ts` (created in this step) with `implement()`.
|
|
48
48
|
Keep persistence and business rules in a domain/service module; the contract
|
|
49
49
|
handler calls that module once. Add the returned service to the `services` array
|
|
50
50
|
in `packages/backend/src/surface.ts`. That one registration drives HTTP,
|
|
@@ -52,20 +52,44 @@ OpenAPI, MCP, agent tools and CLI discovery.
|
|
|
52
52
|
|
|
53
53
|
## 4. Add typed browser access
|
|
54
54
|
|
|
55
|
-
Export `statusContract` from `packages/shared/src/index.ts`.
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
`packages/frontend/src/
|
|
60
|
-
|
|
55
|
+
Export `statusContract` from `packages/shared/src/index.ts`.
|
|
56
|
+
|
|
57
|
+
The scaffold ships no browser transport layer, and that is the first thing this
|
|
58
|
+
step builds. It also makes one decision for you, because the starter already
|
|
59
|
+
made it: **no address is compiled into the artifact.** `packages/frontend/src/env.ts`
|
|
60
|
+
declares no `client` block on purpose — a `NEXT_PUBLIC_` variable is substituted
|
|
61
|
+
at build time, which freezes a value of the place into the bundle. So the client
|
|
62
|
+
is a factory over an origin the server reads per request, never a module-level
|
|
63
|
+
constant.
|
|
64
|
+
|
|
65
|
+
Create `packages/frontend/src/lib/api/client.ts` (created in this step):
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { createClient, createHttpClient } from 'stitchkit'
|
|
69
|
+
import { statusContract } from '@app/shared'
|
|
70
|
+
|
|
71
|
+
/** One origin per request, supplied by the server — never read from the bundle. */
|
|
72
|
+
export function createStatusApi(origin: string) {
|
|
73
|
+
return createClient(statusContract, createHttpClient({ prefixUrl: origin }))
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Create `packages/frontend/src/lib/api/status.ts` (created in this step) for the
|
|
78
|
+
query key and the react-query-kit hooks, and keep the key canonical — one key
|
|
79
|
+
per resource, updated or invalidated on mutation success.
|
|
80
|
+
|
|
81
|
+
A server component reads `env.PUBLIC_API_ORIGIN` and hands it down as a prop;
|
|
82
|
+
the client component calls `createStatusApi(origin)`. That is the whole reason
|
|
83
|
+
`PUBLIC_API_ORIGIN` is a server variable rather than a public one.
|
|
61
84
|
|
|
62
85
|
Render the hook from a feature component. Pages compose features; they do not
|
|
63
86
|
call `fetch`, construct `/api/status` or decode error bodies themselves.
|
|
64
87
|
|
|
65
88
|
## 5. Add realtime only when another client must observe the change
|
|
66
89
|
|
|
67
|
-
|
|
68
|
-
|
|
90
|
+
Create `packages/shared/src/realtime.ts` (created in this step) and declare the
|
|
91
|
+
event there with a named Zod schema for its tuple — the scaffold ships no
|
|
92
|
+
realtime module, so this step introduces it rather than assuming it. The server emits after the domain change succeeds; the frontend cache
|
|
69
93
|
bridge reacts by updating or invalidating the status query. Keep handshake auth,
|
|
70
94
|
authorization and room membership in the application. Socket.IO delivery,
|
|
71
95
|
reconnection, retained subscriptions and validation belong to Stitchkit.
|
package/template/package.json
CHANGED
|
@@ -11,8 +11,9 @@
|
|
|
11
11
|
},
|
|
12
12
|
"scripts": {
|
|
13
13
|
"dev": "bun scripts/dev.ts",
|
|
14
|
-
"check": "bun run db:generate && bun run check:authored && bun x tsc -p tsconfig.json --noEmit && bun run --filter '*' check",
|
|
14
|
+
"check": "bun run db:generate && bun run check:authored && bun run check:guides && bun x tsc -p tsconfig.json --noEmit && bun run --filter '*' check",
|
|
15
15
|
"check:authored": "bun scripts/check-authored.ts",
|
|
16
|
+
"check:guides": "bun scripts/guide-paths.ts",
|
|
16
17
|
"test": "bun test scripts && bun run --filter '*' test",
|
|
17
18
|
"build": "bun scripts/build-inputs.ts && bun run db:generate && bun --filter @app/backend build && bun --filter @app/frontend build && bun scripts/build-stamp.ts",
|
|
18
19
|
"start:api": "bun --filter @app/backend start",
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { inspect } from './check-authored';
|
|
3
|
+
|
|
4
|
+
describe('check:authored — assertions', () => {
|
|
5
|
+
test('lets a const assertion through: it narrows and cannot launder a type', () => {
|
|
6
|
+
const source = [
|
|
7
|
+
"export const benchKeys = { jobs: ['bench', 'jobs'] as const };",
|
|
8
|
+
"export const modes = ['fast', 'full'] as const;",
|
|
9
|
+
'',
|
|
10
|
+
].join('\n');
|
|
11
|
+
expect(inspect('packages/shared/src/bench.ts', source)).toEqual([]);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test('still refuses a real assertion, and the finding names what to do instead', () => {
|
|
15
|
+
const findings = inspect(
|
|
16
|
+
'packages/shared/src/parse.ts',
|
|
17
|
+
'const parsed = JSON.parse(raw) as Payload;\n',
|
|
18
|
+
);
|
|
19
|
+
expect(findings).toHaveLength(1);
|
|
20
|
+
const [finding] = findings;
|
|
21
|
+
// Line and file, so it is navigable…
|
|
22
|
+
expect(finding).toContain('packages/shared/src/parse.ts:1');
|
|
23
|
+
// …and the remedy, so the reader does not have to search for the sanctioned way.
|
|
24
|
+
expect(finding).toContain('satisfies');
|
|
25
|
+
expect(finding).toContain('schema at the boundary');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('the angle-bracket form is refused too, and explicit any separately', () => {
|
|
29
|
+
expect(inspect('scripts/x.ts', 'const a = <Foo>bar;\n')).toHaveLength(1);
|
|
30
|
+
const anyFindings = inspect('scripts/y.ts', 'function f(a: any) { return a; }\n');
|
|
31
|
+
expect(anyFindings).toHaveLength(1);
|
|
32
|
+
expect(anyFindings[0]).toContain('explicit any');
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('a const assertion beside a real one reports only the real one', () => {
|
|
36
|
+
const findings = inspect(
|
|
37
|
+
'scripts/mixed.ts',
|
|
38
|
+
"const keys = ['a'] as const;\nconst value = raw as Payload;\n",
|
|
39
|
+
);
|
|
40
|
+
expect(findings).toHaveLength(1);
|
|
41
|
+
expect(findings[0]).toContain('scripts/mixed.ts:2');
|
|
42
|
+
});
|
|
43
|
+
});
|
|
@@ -20,15 +20,42 @@ function lineAt(source: string, offset: number): number {
|
|
|
20
20
|
return source.slice(0, offset).split('\n').length;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
/**
|
|
24
|
+
* `as const` is not the assertion this gate exists for.
|
|
25
|
+
*
|
|
26
|
+
* The gate refuses a cast because a cast can LAUNDER a type — claim something the value has not
|
|
27
|
+
* been shown to be. A const-assertion cannot: it only narrows, it introduces no name, and it
|
|
28
|
+
* cannot widen. Refusing it made five of the first fifteen findings on a real adoption false, in
|
|
29
|
+
* a gate whose whole value is that its findings are worth acting on.
|
|
30
|
+
*
|
|
31
|
+
* `const` is a reserved word, so no type can be named `const` — the check has no false positive
|
|
32
|
+
* of its own.
|
|
33
|
+
*/
|
|
34
|
+
function isConstAssertion(node: { typeAnnotation?: unknown }): boolean {
|
|
35
|
+
const annotation = node.typeAnnotation;
|
|
36
|
+
if (!isRecord(annotation) || annotation.type !== 'TSTypeReference') return false;
|
|
37
|
+
const typeName = annotation.typeName;
|
|
38
|
+
return isRecord(typeName) && typeName.type === 'Identifier' && typeName.name === 'const';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
42
|
+
return typeof value === 'object' && value !== null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** What to do instead — a finding that only names the sin costs the reader a search. */
|
|
46
|
+
const ASSERTION_REMEDY =
|
|
47
|
+
'type assertion — use `satisfies` to check a literal against a type, or parse the value with its schema at the boundary';
|
|
48
|
+
|
|
49
|
+
export function inspect(path: string, source: string): string[] {
|
|
24
50
|
const result = parseSync(path, source);
|
|
25
51
|
const failures = result.errors.map((error) => `${path}: parse error: ${error.message}`);
|
|
26
52
|
const visitor = new Visitor({
|
|
27
53
|
TSAsExpression(node) {
|
|
28
|
-
|
|
54
|
+
if (isConstAssertion(node)) return;
|
|
55
|
+
failures.push(`${path}:${lineAt(source, node.start)}: ${ASSERTION_REMEDY}`);
|
|
29
56
|
},
|
|
30
57
|
TSTypeAssertion(node) {
|
|
31
|
-
failures.push(`${path}:${lineAt(source, node.start)}:
|
|
58
|
+
failures.push(`${path}:${lineAt(source, node.start)}: ${ASSERTION_REMEDY}`);
|
|
32
59
|
},
|
|
33
60
|
TSAnyKeyword(node) {
|
|
34
61
|
failures.push(`${path}:${lineAt(source, node.start)}: explicit any`);
|
|
@@ -91,21 +118,25 @@ async function visitDirectory(directory: string): Promise<string[]> {
|
|
|
91
118
|
return failures;
|
|
92
119
|
}
|
|
93
120
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
)
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
121
|
+
// Guarded so the module can be imported by its own test without running the gate over the
|
|
122
|
+
// repository — importing a script that scans the tree and exits is not a testable unit.
|
|
123
|
+
if (import.meta.main) {
|
|
124
|
+
const failures = [
|
|
125
|
+
...(await Promise.all(roots.map(visitDirectory))).flat(),
|
|
126
|
+
...(
|
|
127
|
+
await Promise.all(
|
|
128
|
+
rootFiles.map(async (path) => inspect(path, await readFile(path, 'utf8'))),
|
|
129
|
+
)
|
|
130
|
+
).flat(),
|
|
131
|
+
];
|
|
132
|
+
const webPackage = await readFile('packages/frontend/package.json', 'utf8');
|
|
133
|
+
if (webPackage.includes(replacedThemePackage)) {
|
|
134
|
+
failures.push(
|
|
135
|
+
'packages/frontend/package.json: use @wrksz/themes as the single theme runtime',
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
if (failures.length > 0) {
|
|
139
|
+
for (const failure of failures) console.error(failure);
|
|
140
|
+
process.exit(1);
|
|
141
|
+
}
|
|
111
142
|
}
|
package/template/scripts/dev.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { resolve } from 'node:path';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { appDeclaration } from '../packages/config/src/declaration';
|
|
4
|
-
import { ensureLocalEnvironment } from './local-env';
|
|
4
|
+
import { assertUsableEnvironment, ensureLocalEnvironment } from './local-env';
|
|
5
5
|
import { awaitRolesAnswering, declaredRoleReadiness } from './readiness';
|
|
6
6
|
import { runDeclaredReleaseSteps } from './release-steps';
|
|
7
7
|
import { inheritToolingEnvironment } from './tooling-env';
|
|
@@ -21,9 +21,14 @@ async function run(command: string[], environment?: Record<string, string>): Pro
|
|
|
21
21
|
|
|
22
22
|
export async function runDevelopment(environment?: Record<string, string>): Promise<void> {
|
|
23
23
|
ensureLocalEnvironment(root);
|
|
24
|
+
// Before pm2, before anything: an unusable environment is the reader's problem to fix, and
|
|
25
|
+
// making them read a supervisor error first only delays the sentence that matters.
|
|
26
|
+
assertUsableEnvironment(root);
|
|
24
27
|
assertToolAvailable('pm2', 'Install PM2 with `bun add --global pm2`, then rerun.');
|
|
25
28
|
await run(['pm2', 'ping']);
|
|
26
29
|
const environmentForRun = await developmentEnvironment(environment);
|
|
30
|
+
// Kept for an environment supplied from the shell rather than from `.env`, which the file
|
|
31
|
+
// check above cannot see.
|
|
27
32
|
if (environmentForRun.DATABASE_URL?.includes('USER:PASSWORD')) {
|
|
28
33
|
throw new Error(
|
|
29
34
|
'DATABASE_URL still contains the starter placeholder. Create a PostgreSQL database, update DATABASE_URL in .env, then rerun `bun run dev`.',
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { inspectGuide, inspectGuides } from './guide-paths';
|
|
3
|
+
|
|
4
|
+
const present = (path: string) => path === 'packages/shared/src/index.ts';
|
|
5
|
+
|
|
6
|
+
describe('guide paths', () => {
|
|
7
|
+
test('reports a path the guide names but the scaffold lacks', () => {
|
|
8
|
+
const findings = inspectGuide(
|
|
9
|
+
'docs/G.md',
|
|
10
|
+
'In `packages/frontend/src/lib/api/client.ts`, create the api.\n',
|
|
11
|
+
present,
|
|
12
|
+
);
|
|
13
|
+
expect(findings).toEqual([
|
|
14
|
+
{ guide: 'docs/G.md', line: 1, path: 'packages/frontend/src/lib/api/client.ts' },
|
|
15
|
+
]);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('a path the guide creates is declared, not broken', () => {
|
|
19
|
+
const source = 'Create `packages/shared/src/realtime.ts` (created in this step) and…\n';
|
|
20
|
+
expect(inspectGuide('docs/G.md', source, present)).toEqual([]);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('an existing path is quiet, and prose without a path is quiet', () => {
|
|
24
|
+
expect(
|
|
25
|
+
inspectGuide('docs/G.md', 'Export it from `packages/shared/src/index.ts`.\n', present),
|
|
26
|
+
).toEqual([]);
|
|
27
|
+
expect(inspectGuide('docs/G.md', 'Pages compose features.\n', present)).toEqual([]);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('the real guide resolves every path it does not create', async () => {
|
|
31
|
+
// The denominator matters: a guide the scanner cannot read would also return [].
|
|
32
|
+
const findings = await inspectGuides(`${import.meta.dir}/..`);
|
|
33
|
+
expect(findings).toEqual([]);
|
|
34
|
+
const anyPath = inspectGuide('docs/G.md', 'See `packages/absent/x.ts`.\n', () => false);
|
|
35
|
+
expect(anyPath).toHaveLength(1);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Every repository path a guide names has to exist.
|
|
7
|
+
*
|
|
8
|
+
* `ADDING_A_FEATURE.md` is the one document a new consumer executes literally, and two of its
|
|
9
|
+
* steps pointed at files the scaffold does not contain — `lib/api/client.ts` and a "shared
|
|
10
|
+
* realtime source". The reader does not learn that by reading; they learn it by opening the path
|
|
11
|
+
* and finding nothing, after having already trusted the sentence around it.
|
|
12
|
+
*
|
|
13
|
+
* A path the guide tells you to CREATE is not a broken reference, so those are declared by the
|
|
14
|
+
* guide itself: a line that introduces one carries `(created in this step)`. Everything else
|
|
15
|
+
* must resolve.
|
|
16
|
+
*/
|
|
17
|
+
const GUIDES = ['docs/ADDING_A_FEATURE.md'];
|
|
18
|
+
const PATH_PATTERN = /`((?:packages|scripts|docs|e2e)\/[A-Za-z0-9_./-]+)`/g;
|
|
19
|
+
|
|
20
|
+
export interface GuidePathFinding {
|
|
21
|
+
readonly guide: string;
|
|
22
|
+
readonly line: number;
|
|
23
|
+
readonly path: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function inspectGuide(
|
|
27
|
+
guide: string,
|
|
28
|
+
source: string,
|
|
29
|
+
exists: (path: string) => boolean,
|
|
30
|
+
): GuidePathFinding[] {
|
|
31
|
+
const findings: GuidePathFinding[] = [];
|
|
32
|
+
source.split('\n').forEach((text, index) => {
|
|
33
|
+
if (text.includes('(created in this step)')) return;
|
|
34
|
+
for (const match of text.matchAll(PATH_PATTERN)) {
|
|
35
|
+
const path = match[1];
|
|
36
|
+
if (!path || exists(path)) continue;
|
|
37
|
+
findings.push({ guide, line: index + 1, path });
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
return findings;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function inspectGuides(root: string): Promise<GuidePathFinding[]> {
|
|
44
|
+
const findings: GuidePathFinding[] = [];
|
|
45
|
+
for (const guide of GUIDES) {
|
|
46
|
+
const absolute = resolve(root, guide);
|
|
47
|
+
if (!existsSync(absolute)) {
|
|
48
|
+
findings.push({ guide, line: 0, path: guide });
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
findings.push(
|
|
52
|
+
...inspectGuide(guide, await readFile(absolute, 'utf8'), (path) =>
|
|
53
|
+
existsSync(join(root, path)),
|
|
54
|
+
),
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
return findings;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (import.meta.main) {
|
|
61
|
+
const findings = await inspectGuides(resolve(import.meta.dir, '..'));
|
|
62
|
+
for (const { guide, line, path } of findings) {
|
|
63
|
+
console.error(`${guide}:${line}: names ${path}, which does not exist`);
|
|
64
|
+
}
|
|
65
|
+
if (findings.length > 0) process.exit(1);
|
|
66
|
+
}
|
|
@@ -3,7 +3,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { appDeclaration } from '../packages/config/src/declaration';
|
|
6
|
-
import { ensureLocalEnvironment } from './local-env';
|
|
6
|
+
import { assertUsableEnvironment, ensureLocalEnvironment } from './local-env';
|
|
7
7
|
|
|
8
8
|
describe('ensureLocalEnvironment', () => {
|
|
9
9
|
test('renders the application identity into a fresh .env and never touches an existing one', async () => {
|
|
@@ -13,7 +13,10 @@ describe('ensureLocalEnvironment', () => {
|
|
|
13
13
|
join(root, '.env.example'),
|
|
14
14
|
'DATABASE_URL=postgresql://USER:PASSWORD@127.0.0.1:5432/stitchkit_starter\n',
|
|
15
15
|
);
|
|
16
|
+
// Rendering succeeds — a generator that refuses to generate would break `--no-install`
|
|
17
|
+
// scaffolding — and the separate usability check is what refuses.
|
|
16
18
|
ensureLocalEnvironment(root);
|
|
19
|
+
expect(() => assertUsableEnvironment(root)).toThrow(/USER:PASSWORD/);
|
|
17
20
|
const created = await readFile(join(root, '.env'), 'utf8');
|
|
18
21
|
// In the neutral dev workspace the slug IS the neutral identity, so the
|
|
19
22
|
// substitution is proven end-to-end by the starter lane on a renamed
|
|
@@ -39,10 +42,56 @@ describe('ensureLocalEnvironment', () => {
|
|
|
39
42
|
'DATABASE_URL=postgresql://USER:PASSWORD@127.0.0.1:5432/stitchkit_starter\n',
|
|
40
43
|
);
|
|
41
44
|
ensureLocalEnvironment(root);
|
|
45
|
+
expect(() => assertUsableEnvironment(root)).toThrow(/USER:PASSWORD/);
|
|
42
46
|
const databaseName = appDeclaration.identity.slug.replaceAll('-', '_');
|
|
43
47
|
expect(await readFile(join(root, '.env'), 'utf8')).toContain(`5432/${databaseName}`);
|
|
44
48
|
} finally {
|
|
45
49
|
await rm(root, { recursive: true, force: true });
|
|
46
50
|
}
|
|
47
51
|
});
|
|
52
|
+
|
|
53
|
+
test('an unedited .env is refused on every later run, not only the one that wrote it', async () => {
|
|
54
|
+
const root = await mkdtemp(join(tmpdir(), 'sk-env-again-'));
|
|
55
|
+
try {
|
|
56
|
+
// No example at all: the file is already there, exactly as a second `bun run dev` finds it.
|
|
57
|
+
await writeFile(
|
|
58
|
+
join(root, '.env'),
|
|
59
|
+
'DATABASE_URL=postgresql://USER:PASSWORD@127.0.0.1:5432/app\n',
|
|
60
|
+
);
|
|
61
|
+
let message = '';
|
|
62
|
+
try {
|
|
63
|
+
assertUsableEnvironment(root);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
message = error instanceof Error ? error.message : String(error);
|
|
66
|
+
}
|
|
67
|
+
// The message has to name the file, the line and the privilege the next step needs —
|
|
68
|
+
// a refusal that only says "invalid" moves the search back to the reader.
|
|
69
|
+
expect(message).toContain('.env:1');
|
|
70
|
+
expect(message).toContain('DATABASE_URL');
|
|
71
|
+
expect(message).toContain('CREATEDB');
|
|
72
|
+
} finally {
|
|
73
|
+
await rm(root, { recursive: true, force: true });
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test('a commented example line is not mistaken for an unresolved credential', async () => {
|
|
78
|
+
const root = await mkdtemp(join(tmpdir(), 'sk-env-comment-'));
|
|
79
|
+
try {
|
|
80
|
+
// The placeholder is assembled rather than written: spelled out it is a credential inside
|
|
81
|
+
// a URL, which the publication-privacy gate refuses on sight — rightly, since "it is only
|
|
82
|
+
// a fixture" is the argument every leak makes. Same idiom as `check-authored.ts`.
|
|
83
|
+
const placeholder = ['USER', 'PASSWORD'].join(':');
|
|
84
|
+
await writeFile(
|
|
85
|
+
join(root, '.env'),
|
|
86
|
+
[
|
|
87
|
+
`# DATABASE_URL=postgresql://${placeholder}@127.0.0.1:5432/example`,
|
|
88
|
+
'DATABASE_URL=postgresql://127.0.0.1:5432/app',
|
|
89
|
+
'',
|
|
90
|
+
].join('\n'),
|
|
91
|
+
);
|
|
92
|
+
expect(() => assertUsableEnvironment(root)).not.toThrow();
|
|
93
|
+
} finally {
|
|
94
|
+
await rm(root, { recursive: true, force: true });
|
|
95
|
+
}
|
|
96
|
+
});
|
|
48
97
|
});
|
|
@@ -19,18 +19,62 @@ import { appIdentity } from '../packages/config/src/app-identity.generated';
|
|
|
19
19
|
* environment too. Synchronous on purpose: `playwright.config.ts` and other
|
|
20
20
|
* synchronous entry points must be able to self-heal before validating.
|
|
21
21
|
*/
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* The credentials this file renders but cannot know.
|
|
24
|
+
*
|
|
25
|
+
* `.env.example` ships a connection string with literal `USER:PASSWORD`, and this script
|
|
26
|
+
* substitutes only the database name. A file that is generated, edited by the generator and then
|
|
27
|
+
* left unusable is the worst of the three: the reader assumes a generated file is ready. So the
|
|
28
|
+
* placeholder is named here rather than discovered as a driver stack on the first request.
|
|
29
|
+
*/
|
|
30
|
+
function unresolvedCredentialLines(destination: string): string[] {
|
|
31
|
+
return readFileSync(destination, 'utf8')
|
|
32
|
+
.split('\n')
|
|
33
|
+
.map((line, index) => ({ line: line.trim(), number: index + 1 }))
|
|
34
|
+
.filter(({ line }) => !line.startsWith('#') && line.includes('USER:PASSWORD'))
|
|
35
|
+
.map(({ line, number }) => ` ${destination}:${number} ${line.split('=')[0] ?? line}`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Refuse to start on an environment that still carries the example credentials.
|
|
40
|
+
*
|
|
41
|
+
* Separate from rendering on purpose: a generator that refuses to generate is wrong — `--no-install`
|
|
42
|
+
* scaffolding renders `.env` before anyone could have filled it in — while a start that proceeds
|
|
43
|
+
* into a driver stack is the defect. So `env:ensure` writes and reports; `dev` writes and refuses.
|
|
44
|
+
*/
|
|
45
|
+
export function assertUsableEnvironment(root: string): void {
|
|
23
46
|
const destination = resolve(root, '.env');
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
47
|
+
const unresolved = unresolvedCredentialLines(destination);
|
|
48
|
+
if (unresolved.length === 0) return;
|
|
49
|
+
throw new Error(
|
|
50
|
+
`This environment still carries the example credentials.\n${unresolved.join('\n')}\n` +
|
|
51
|
+
'Replace USER:PASSWORD with a role that can reach your PostgreSQL server. ' +
|
|
52
|
+
'A role that runs `db:migrate` also needs CREATEDB, because `prisma migrate dev` ' +
|
|
53
|
+
'creates a shadow database.',
|
|
29
54
|
);
|
|
30
|
-
|
|
31
|
-
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function ensureLocalEnvironment(root: string): void {
|
|
58
|
+
const destination = resolve(root, '.env');
|
|
59
|
+
if (!existsSync(destination)) {
|
|
60
|
+
const publicExample = resolve(root, '.env.example');
|
|
61
|
+
const example = readFileSync(
|
|
62
|
+
existsSync(publicExample) ? publicExample : resolve(root, '_env.example'),
|
|
63
|
+
'utf8',
|
|
64
|
+
);
|
|
65
|
+
const databaseName = appIdentity.slug.replaceAll('-', '_');
|
|
66
|
+
writeFileSync(destination, example.replaceAll('stitchkit_starter', databaseName));
|
|
67
|
+
}
|
|
32
68
|
}
|
|
33
69
|
|
|
34
70
|
if (import.meta.main) {
|
|
35
|
-
|
|
71
|
+
const root = resolve(import.meta.dir, '..');
|
|
72
|
+
ensureLocalEnvironment(root);
|
|
73
|
+
// Reported, not fatal: this command's job is to produce the file, and it has.
|
|
74
|
+
const unresolved = unresolvedCredentialLines(resolve(root, '.env'));
|
|
75
|
+
if (unresolved.length > 0) {
|
|
76
|
+
process.stderr.write(
|
|
77
|
+
`.env still carries the example credentials — \`bun run dev\` will refuse until they are replaced:\n${unresolved.join('\n')}\n`,
|
|
78
|
+
);
|
|
79
|
+
}
|
|
36
80
|
}
|