@fougere/cli 0.2.0-alpha.1 → 0.3.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -1
- package/app/commands/BuildCommand.ts +39 -0
- package/app/commands/CallCommand.ts +4 -4
- package/app/commands/CheckCommand.ts +3 -2
- package/app/commands/ExplainCommand.ts +77 -0
- package/app/commands/FreezeCommand.ts +107 -0
- package/app/commands/GrantCommand.ts +44 -0
- package/app/commands/GraphCommand.ts +1 -1
- package/app/commands/KeysCommand.ts +56 -0
- package/app/commands/MigrateCommand.ts +54 -0
- package/app/commands/NewCommand.ts +6 -6
- package/app/commands/ServeCommand.ts +85 -9
- package/app/commands/grant-material.ts +5 -0
- package/dist/bin.js +54 -8
- package/dist/bin.js.map +1 -1
- package/dist/bridge.d.ts.map +1 -1
- package/dist/bridge.js +6 -6
- package/dist/bridge.js.map +1 -1
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +7 -7
- package/dist/runner.js.map +1 -1
- package/dist/theme.d.ts +10 -0
- package/dist/theme.d.ts.map +1 -0
- package/dist/theme.js +10 -0
- package/dist/theme.js.map +1 -0
- package/dist/ui.d.ts +74 -0
- package/dist/ui.d.ts.map +1 -0
- package/dist/ui.js +111 -0
- package/dist/ui.js.map +1 -0
- package/fronds/analysis/entities/Build.ts +7 -0
- package/fronds/analysis/entities/Explain.ts +8 -0
- package/fronds/analysis/entities/Freeze.ts +7 -0
- package/fronds/analysis/entities/Migrate.ts +7 -0
- package/fronds/analysis/handlers/BuildHandler.ts +60 -0
- package/fronds/analysis/handlers/CheckHandler.ts +61 -35
- package/fronds/analysis/handlers/ExplainHandler.ts +214 -0
- package/fronds/analysis/handlers/FreezeHandler.ts +172 -0
- package/fronds/analysis/handlers/MigrateHandler.ts +97 -0
- package/fronds/analysis/services/ProjectScan.ts +23 -7
- package/fronds/analysis/versions.ts +58 -0
- package/fronds/scaffold/entities/Grant.ts +6 -0
- package/fronds/scaffold/entities/Keys.ts +4 -0
- package/fronds/scaffold/entities/Serve.ts +2 -1
- package/fronds/scaffold/handlers/BuildFrondHandler.ts +11 -13
- package/fronds/scaffold/handlers/GrantHandler.ts +8 -0
- package/fronds/scaffold/handlers/KeysHandler.ts +8 -0
- package/fronds/scaffold/handlers/SyncHandler.ts +27 -24
- package/fronds/scaffold/services/ProjectWriter.ts +29 -10
- package/package.json +10 -8
- package/templates/admin/fronds/admin/handlers/UserHandler.ts +3 -5
- package/templates/admin/fronds/admin/package.json +1 -1
- package/templates/api/fronds/api/handlers/TaskHandler.ts +3 -5
- package/templates/api/fronds/api/package.json +1 -1
- package/templates/apps/nuxt/app/pages/index.vue +1 -1
- package/templates/apps/nuxt/package.json +1 -1
- package/templates/blog/app/pages/posts/index.vue +1 -1
- package/templates/blog/app/pages/posts/manage.vue +1 -1
- package/templates/blog/app/pages/posts/new.vue +1 -1
- package/templates/blog/fronds/blog/handlers/PostHandler.ts +3 -5
- package/templates/blog/fronds/blog/package.json +1 -1
- package/templates/flat/AGENTS.md +14 -0
- package/templates/flat/CLAUDE.md +27 -5
- package/templates/flat/package.json +1 -1
- package/templates/frond/AGENTS.md +14 -0
- package/templates/frond/CLAUDE.md +27 -5
- package/templates/frond/fronds/__name__/handlers/PostHandler.ts +3 -5
- package/templates/frond/fronds/__name__/package.json +1 -1
- package/templates/frond/package.json +1 -1
- package/templates/frond/serve.mjs +4 -3
- package/templates/fronds/blank/package.json +1 -1
- package/templates/fronds/blog/handlers/PostHandler.ts +2 -4
- package/templates/fronds/blog/package.json +1 -1
- package/templates/workspace/AGENTS.md +14 -0
- package/templates/workspace/CLAUDE.md +27 -5
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
buildGraph,
|
|
3
|
+
clusterEntities,
|
|
4
|
+
resolveEffectiveOperations,
|
|
5
|
+
type ScanDiagnostic,
|
|
6
|
+
} from '@fougere/core';
|
|
7
|
+
import { crossFrondImports } from '@fougere/core/node';
|
|
2
8
|
import ProjectScan from '../services/ProjectScan.js';
|
|
3
9
|
|
|
4
10
|
/** One thing that does not hold, in the terms of whoever has to fix it. */
|
|
@@ -8,6 +14,12 @@ export interface Finding {
|
|
|
8
14
|
code: string;
|
|
9
15
|
/** Where to go and look. */
|
|
10
16
|
filePath: string;
|
|
17
|
+
/**
|
|
18
|
+
* What the finding is ABOUT — `PostHandler.whoNull(user)` — when the rule holds it
|
|
19
|
+
* as a fact rather than inside its sentence. Two ops of one handler breaking the
|
|
20
|
+
* same rule read as one repeated line without it.
|
|
21
|
+
*/
|
|
22
|
+
subject?: string;
|
|
11
23
|
/** What is wrong, and what it costs. One sentence. */
|
|
12
24
|
message: string;
|
|
13
25
|
}
|
|
@@ -18,52 +30,60 @@ export interface CheckResult {
|
|
|
18
30
|
findings: Finding[];
|
|
19
31
|
}
|
|
20
32
|
|
|
33
|
+
/** Shared with `fougere graph` — one threshold, so the two never disagree. */
|
|
34
|
+
const DOMAIN_SPLIT_MIN_ENTITIES = 6;
|
|
35
|
+
|
|
21
36
|
/**
|
|
22
37
|
* What does not hold in this app — derived from its declarations, not from tests.
|
|
23
38
|
*
|
|
24
39
|
* It scans rather than boots — see `ProjectScan`, which states what that costs.
|
|
25
40
|
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* receives nothing;
|
|
32
|
-
* - a relative import that resolves into another frond — a colocation constraint
|
|
33
|
-
* nothing declares, which holds until the day the other frond is not on this disk.
|
|
41
|
+
* It raises no operation-resolution rule of its own: those findings come from the same
|
|
42
|
+
* EffectiveOperation resolver boot consumes. The remaining findings come from their
|
|
43
|
+
* existing owners — scan diagnostics, the import reader and domain clustering. A second
|
|
44
|
+
* opinion here would report what the runtime does not serve, precisely what a checker
|
|
45
|
+
* must avoid.
|
|
34
46
|
*
|
|
35
|
-
* A rule about an ABSENCE is only sound if the analysis attests it looked, which
|
|
36
|
-
*
|
|
47
|
+
* A rule about an ABSENCE is only sound if the analysis attests it looked, which is
|
|
48
|
+
* why the scan's diagnostics had to exist before this command could.
|
|
37
49
|
*/
|
|
38
50
|
export default class CheckHandler {
|
|
39
51
|
constructor(private projectScan: ProjectScan) {}
|
|
40
52
|
|
|
41
53
|
/** Report what does not hold in a Fougere app, without booting it. */
|
|
42
54
|
async execute(input: { root?: string }): Promise<CheckResult> {
|
|
43
|
-
const { fronds, diagnostics } = await this.projectScan.at(input.root);
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const contracts = resolveContracts(handler, frond.operationsOverrides, collectorEntityNames);
|
|
55
|
+
const { fronds, diagnostics, config } = await this.projectScan.at(input.root);
|
|
56
|
+
// This is the same pure resolution the boot consumes. No app lifecycle, database,
|
|
57
|
+
// migration, seed or adapter mount is needed for a global semantic check.
|
|
58
|
+
const model = resolveEffectiveOperations(fronds, {
|
|
59
|
+
diagnostics,
|
|
60
|
+
remotes: config.remotes,
|
|
61
|
+
adapters: config.adapters,
|
|
62
|
+
});
|
|
63
|
+
const findings: Finding[] = model.diagnostics.map(asFinding);
|
|
64
|
+
const handlers = fronds.reduce((count, frond) => count + frond.handlers.length, 0);
|
|
54
65
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
66
|
+
/**
|
|
67
|
+
* Entity groups with no `ref()` between them, in one frond. Reported as a FACT, not a
|
|
68
|
+
* verdict: it means either a missing relation or a frond that has not been named, and
|
|
69
|
+
* nothing here can tell which. `fougere graph` shows the groups.
|
|
70
|
+
*/
|
|
71
|
+
if (fronds.length === 1) {
|
|
72
|
+
// `clusterEntities`, not `suggestSplit`: the latter invents a cut on a connected
|
|
73
|
+
// graph, which is its job and not this question. Here only real components count.
|
|
74
|
+
const nodes = buildGraph(fronds);
|
|
75
|
+
const clusters = clusterEntities(nodes);
|
|
76
|
+
// Same threshold as `fougere graph`'s own tip: below it, two components are a small
|
|
77
|
+
// app that has not grown its links yet, not a frond holding two domains.
|
|
78
|
+
if (clusters.length > 1 && nodes.size >= DOMAIN_SPLIT_MIN_ENTITIES) {
|
|
79
|
+
findings.push({
|
|
80
|
+
severity: 'warning',
|
|
81
|
+
code: 'frond-holds-several-domains',
|
|
82
|
+
filePath: fronds[0].source.path,
|
|
83
|
+
message: `'${fronds[0].name}': ${clusters.length} entity groups with no relation between `
|
|
84
|
+
+ `them (${clusters.map((c) => c.name).join(', ')}). Either a relation is missing, or `
|
|
85
|
+
+ `they are separate fronds — see \`fougere graph\`.`,
|
|
86
|
+
});
|
|
67
87
|
}
|
|
68
88
|
}
|
|
69
89
|
|
|
@@ -86,5 +106,11 @@ export default class CheckHandler {
|
|
|
86
106
|
|
|
87
107
|
/** A scan diagnostic IS a finding — same vocabulary, so the renderer has one shape. */
|
|
88
108
|
function asFinding(d: ScanDiagnostic): Finding {
|
|
89
|
-
return {
|
|
109
|
+
return {
|
|
110
|
+
severity: d.severity,
|
|
111
|
+
code: d.code,
|
|
112
|
+
filePath: d.filePath,
|
|
113
|
+
subject: d.subject,
|
|
114
|
+
message: d.message,
|
|
115
|
+
};
|
|
90
116
|
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import {
|
|
2
|
+
resolveEffectiveOperations,
|
|
3
|
+
type EffectiveOperation,
|
|
4
|
+
type OperationContract,
|
|
5
|
+
} from '@fougere/core';
|
|
6
|
+
import { relative } from 'node:path';
|
|
7
|
+
import ProjectScan from '../services/ProjectScan.js';
|
|
8
|
+
|
|
9
|
+
type Cardinality = NonNullable<OperationContract['cardinality']>;
|
|
10
|
+
type Binding = EffectiveOperation['binding'][number];
|
|
11
|
+
|
|
12
|
+
export type ExplainedBinding =
|
|
13
|
+
| { kind: 'collector'; typeName: string }
|
|
14
|
+
| { kind: 'fact'; factName: string }
|
|
15
|
+
| { kind: 'param'; name: string; coerce?: 'number' | 'boolean' }
|
|
16
|
+
| { kind: 'body' }
|
|
17
|
+
| { kind: 'context' }
|
|
18
|
+
| { kind: 'query' };
|
|
19
|
+
|
|
20
|
+
export interface ExplainedParameter {
|
|
21
|
+
name: string;
|
|
22
|
+
type: string | null;
|
|
23
|
+
optional: boolean;
|
|
24
|
+
nullable: boolean;
|
|
25
|
+
undefinable: boolean;
|
|
26
|
+
binding: ExplainedBinding | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ExplainedCollector {
|
|
30
|
+
typeName: string;
|
|
31
|
+
class: string;
|
|
32
|
+
file: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Stable, JSON-shaped projection of core's canonical EffectiveOperation. */
|
|
36
|
+
export interface ExplainResult {
|
|
37
|
+
operation: string;
|
|
38
|
+
handler: {
|
|
39
|
+
class: string;
|
|
40
|
+
address: string;
|
|
41
|
+
method: string;
|
|
42
|
+
file: string | null;
|
|
43
|
+
};
|
|
44
|
+
kind: 'query' | 'command';
|
|
45
|
+
description: string | null;
|
|
46
|
+
input: string | null;
|
|
47
|
+
output: { type: string; cardinality: Cardinality | null } | null;
|
|
48
|
+
parameters: ExplainedParameter[];
|
|
49
|
+
collectors: ExplainedCollector[];
|
|
50
|
+
contexts: string[];
|
|
51
|
+
semantics: EffectiveOperation['semantics'];
|
|
52
|
+
exposure: {
|
|
53
|
+
surfaces: string[];
|
|
54
|
+
adapters: string[];
|
|
55
|
+
};
|
|
56
|
+
placement: {
|
|
57
|
+
frond: string;
|
|
58
|
+
runtime: 'local' | 'remote';
|
|
59
|
+
remote: string | null;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface Selector {
|
|
64
|
+
frond?: string;
|
|
65
|
+
surface?: string;
|
|
66
|
+
address: string;
|
|
67
|
+
op: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Read one operation directly from the model boot and check also consume. */
|
|
71
|
+
export default class ExplainHandler {
|
|
72
|
+
constructor(private projectScan: ProjectScan) {}
|
|
73
|
+
|
|
74
|
+
async execute(input: { operation?: string; root?: string; json?: boolean }): Promise<ExplainResult> {
|
|
75
|
+
const requested = input.operation?.trim();
|
|
76
|
+
if (!requested) throw new Error('Usage: fougere explain <Operation> [--json] [--root <directory>]');
|
|
77
|
+
|
|
78
|
+
const selector = parseSelector(requested);
|
|
79
|
+
const scan = await this.projectScan.at(input.root);
|
|
80
|
+
const model = resolveEffectiveOperations(scan.fronds, {
|
|
81
|
+
diagnostics: scan.diagnostics,
|
|
82
|
+
remotes: scan.config.remotes,
|
|
83
|
+
adapters: scan.config.adapters,
|
|
84
|
+
});
|
|
85
|
+
const candidates = model.operations.filter((operation) => matches(operation, selector));
|
|
86
|
+
|
|
87
|
+
if (candidates.length === 0) {
|
|
88
|
+
const failed = model.resolutionDiagnostics.find((diagnostic) =>
|
|
89
|
+
diagnostic.subject?.toLowerCase().includes(`.${selector.op.toLowerCase()}`)
|
|
90
|
+
&& diagnostic.subject.toLowerCase().includes(selector.address.toLowerCase()));
|
|
91
|
+
if (failed) throw new Error(`[${failed.code}] ${failed.message}`);
|
|
92
|
+
|
|
93
|
+
const available = model.operations.map((operation) => operation.id).sort();
|
|
94
|
+
throw new Error(
|
|
95
|
+
`Unknown operation '${requested}'. `
|
|
96
|
+
+ (available.length > 0
|
|
97
|
+
? `Available operations: ${available.join(', ')}.`
|
|
98
|
+
: 'This project exposes no resolved operation.'),
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (candidates.length > 1) {
|
|
103
|
+
throw new Error(
|
|
104
|
+
`Ambiguous operation '${requested}'. Matches: `
|
|
105
|
+
+ `${candidates.map((operation) => operation.id).sort().join(', ')}. `
|
|
106
|
+
+ 'Use one of these qualified names.',
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const selected = candidates[0]!;
|
|
111
|
+
const invalid = model.resolutionDiagnostics.find((diagnostic) =>
|
|
112
|
+
diagnostic.subject?.startsWith(`${selected.handler.className}.${selected.name}`));
|
|
113
|
+
if (invalid) throw new Error(`[${invalid.code}] ${invalid.message}`);
|
|
114
|
+
|
|
115
|
+
return project(selected, scan.root);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function project(operation: EffectiveOperation, root: string): ExplainResult {
|
|
120
|
+
return {
|
|
121
|
+
operation: operation.operation,
|
|
122
|
+
handler: {
|
|
123
|
+
class: operation.implementation.className,
|
|
124
|
+
address: operation.handler.address,
|
|
125
|
+
method: operation.implementation.method,
|
|
126
|
+
file: operation.implementation.filePath
|
|
127
|
+
? relative(root, operation.implementation.filePath)
|
|
128
|
+
: null,
|
|
129
|
+
},
|
|
130
|
+
kind: operation.kind,
|
|
131
|
+
description: operation.description ?? null,
|
|
132
|
+
input: inputTypeOf(operation),
|
|
133
|
+
output: outputOf(operation),
|
|
134
|
+
parameters: operation.parameters.map((parameter) => ({
|
|
135
|
+
name: parameter.name,
|
|
136
|
+
type: parameter.type,
|
|
137
|
+
optional: parameter.optional,
|
|
138
|
+
nullable: parameter.nullable,
|
|
139
|
+
undefinable: parameter.undefinable,
|
|
140
|
+
binding: bindingOf(parameter.binding),
|
|
141
|
+
})),
|
|
142
|
+
collectors: operation.collectors.map((collector) => ({
|
|
143
|
+
typeName: collector.typeName,
|
|
144
|
+
class: collector.className,
|
|
145
|
+
file: relative(root, collector.filePath),
|
|
146
|
+
})),
|
|
147
|
+
contexts: operation.contexts,
|
|
148
|
+
semantics: operation.semantics,
|
|
149
|
+
exposure: operation.exposure,
|
|
150
|
+
placement: {
|
|
151
|
+
frond: operation.placement.frond,
|
|
152
|
+
runtime: operation.placement.runtime,
|
|
153
|
+
remote: operation.placement.remote ?? null,
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function parseSelector(value: string): Selector {
|
|
159
|
+
const dot = value.lastIndexOf('.');
|
|
160
|
+
if (dot <= 0 || dot === value.length - 1) {
|
|
161
|
+
throw new Error(`Invalid operation '${value}'. Expected '<Handler>.<method>', for example 'Post.publish'.`);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const path = value.slice(0, dot).split('/').filter(Boolean);
|
|
165
|
+
if (path.length === 0 || path.length > 3) {
|
|
166
|
+
throw new Error(`Invalid operation '${value}'. Expected 'Post.publish', 'blog/Post.publish', or 'blog/public/Post.publish'.`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const qualifiers = path.slice(0, -1);
|
|
170
|
+
return {
|
|
171
|
+
...(qualifiers[0] ? { frond: qualifiers[0] } : {}),
|
|
172
|
+
...(qualifiers[1] ? { surface: qualifiers[1] } : {}),
|
|
173
|
+
address: addressOf(path.at(-1)!),
|
|
174
|
+
op: value.slice(dot + 1),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function matches(operation: EffectiveOperation, selector: Selector): boolean {
|
|
179
|
+
return operation.handler.address.toLowerCase() === selector.address.toLowerCase()
|
|
180
|
+
&& operation.name === selector.op
|
|
181
|
+
&& (!selector.frond || operation.placement.frond === selector.frond)
|
|
182
|
+
&& (!selector.surface || operation.exposure.surfaces.includes(selector.surface));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function addressOf(value: string): string {
|
|
186
|
+
const base = value.endsWith('Handler') ? value.slice(0, -'Handler'.length) : value;
|
|
187
|
+
return base ? base[0]!.toLowerCase() + base.slice(1) : base;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function inputTypeOf(operation: EffectiveOperation): string | null {
|
|
191
|
+
const body = operation.parameters.find((parameter) => parameter.binding.source.kind === 'body');
|
|
192
|
+
return body?.type ?? schemaName(operation.input) ?? null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function outputOf(operation: EffectiveOperation): ExplainResult['output'] {
|
|
196
|
+
const type = schemaName(operation.output) ?? parsedOutput(operation.signature?.returnType?.raw);
|
|
197
|
+
return type ? { type, cardinality: operation.cardinality ?? null } : null;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function schemaName(schema: unknown): string | undefined {
|
|
201
|
+
const view = schema as { name?: string; source?: { name?: string } } | undefined;
|
|
202
|
+
if (!view) return undefined;
|
|
203
|
+
if (view.name && view.name !== 'Schema') return view.name;
|
|
204
|
+
return view.source?.name;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function parsedOutput(raw: string | undefined): string | undefined {
|
|
208
|
+
if (!raw) return undefined;
|
|
209
|
+
return raw.startsWith('Promise<') && raw.endsWith('>') ? raw.slice(8, -1) : raw;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function bindingOf(binding: Binding): ExplainedBinding {
|
|
213
|
+
return { ...binding.source } as ExplainedBinding;
|
|
214
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { describeSet, diffSet, registrationKeyOf, type SchemaBundle, type SetDiff } from '@fougere/schema';
|
|
4
|
+
import ProjectScan from '../services/ProjectScan.js';
|
|
5
|
+
import { VERSIONS, chainOf } from '../versions.js';
|
|
6
|
+
import type Freeze from '../entities/Freeze.js';
|
|
7
|
+
|
|
8
|
+
export interface FreezeInspection {
|
|
9
|
+
version: string;
|
|
10
|
+
/** The version this one follows, or absent when it is the first. */
|
|
11
|
+
previous?: string;
|
|
12
|
+
entities: string[];
|
|
13
|
+
/** What the step contains — absent when there is nothing before to step from. */
|
|
14
|
+
step?: SetDiff;
|
|
15
|
+
/** Per entity, the pairs the calculation refuses to decide. Empty means it was written. */
|
|
16
|
+
ambiguous: Record<string, Array<{ removed: string; added: string }>>;
|
|
17
|
+
/** Whether anything reached the disk — false while a question stands. */
|
|
18
|
+
written: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Freezing a version — the artefact three readers share.
|
|
23
|
+
*
|
|
24
|
+
* A snapshot alone loses the INTENT (a field gone plus a field appeared cannot be told
|
|
25
|
+
* from a rename), and a step alone corrupts in silence. Both are written, and replaying
|
|
26
|
+
* the step over the previous snapshot must reproduce this one — which is what catches a
|
|
27
|
+
* missing step or a hand-edited file.
|
|
28
|
+
*
|
|
29
|
+
* Nothing is written while an ambiguity stands: the only information the code does not
|
|
30
|
+
* hold is what the person who made the change meant, and this is the one place asking
|
|
31
|
+
* for it is justified.
|
|
32
|
+
*/
|
|
33
|
+
export default class FreezeHandler {
|
|
34
|
+
constructor(private projectScan: ProjectScan) {}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Record this version — or report what stops it, having written nothing.
|
|
38
|
+
*
|
|
39
|
+
* One op and not two: it is idempotent while it refuses, so a caller settles the
|
|
40
|
+
* ambiguities and calls again with `renamed`. Splitting it would let a caller write
|
|
41
|
+
* a version it never inspected.
|
|
42
|
+
*/
|
|
43
|
+
async execute(input: Freeze & { renamed?: Record<string, Record<string, string>> }): Promise<FreezeInspection> {
|
|
44
|
+
const fronds = await this.read(input);
|
|
45
|
+
const version = input.version;
|
|
46
|
+
const entities = fronds.flatMap(({ bundle }) => Object.keys(bundle.$defs ?? {}));
|
|
47
|
+
// Two entrances, one map: what the entities declare, and what a caller answered.
|
|
48
|
+
// The answer wins — it is the later word on a question the declaration left open.
|
|
49
|
+
const renamed = settled(fronds.map(({ declared }) => declared), input.renamed ?? {});
|
|
50
|
+
|
|
51
|
+
// Every frond is inspected before ANY of them writes: a question standing in one
|
|
52
|
+
// frond must not leave the others recorded, or a second run cuts half a version.
|
|
53
|
+
const inspected = fronds.map(({ path, bundle, previous }) => ({
|
|
54
|
+
path,
|
|
55
|
+
bundle,
|
|
56
|
+
previous,
|
|
57
|
+
step: previous ? diffSet(previous.bundle, bundle, { renamed }) : undefined,
|
|
58
|
+
}));
|
|
59
|
+
|
|
60
|
+
const ambiguous: FreezeInspection['ambiguous'] = {};
|
|
61
|
+
for (const { step } of inspected) {
|
|
62
|
+
for (const [name, answer] of Object.entries(step?.entities ?? {})) {
|
|
63
|
+
if (answer.ambiguous.length > 0) ambiguous[name] = answer.ambiguous;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// Nothing on disk while a question stands. The only information the code does not
|
|
67
|
+
// hold is what the person who made the change meant.
|
|
68
|
+
if (Object.keys(ambiguous).length > 0) {
|
|
69
|
+
return { version, previous: previousName(inspected), entities, step: merge(inspected), ambiguous, written: false };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
for (const { path, bundle, previous, step } of inspected) {
|
|
73
|
+
await this.record(path, version, bundle);
|
|
74
|
+
if (!previous || !step) continue;
|
|
75
|
+
// `previous` is recorded rather than re-derived: the chain is a fact of the moment
|
|
76
|
+
// this version was cut, and a later sort of directory names is not that fact.
|
|
77
|
+
await writeFile(
|
|
78
|
+
join(path, VERSIONS, version, 'from.json'),
|
|
79
|
+
`${JSON.stringify({ previous: previous.name, renamed, ...step }, null, 2)}\n`,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return { version, previous: previousName(inspected), entities, step: merge(inspected), ambiguous: {}, written: true };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
private async record(root: string, version: string, bundle: SchemaBundle): Promise<void> {
|
|
87
|
+
const directory = join(root, VERSIONS, version);
|
|
88
|
+
await mkdir(directory, { recursive: true });
|
|
89
|
+
await writeFile(join(directory, 'shape.json'), `${JSON.stringify(bundle, null, 2)}\n`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Today's shapes and the version before them, one entry per frond.
|
|
94
|
+
*
|
|
95
|
+
* `Fronds.schemas()` is deliberately flat — a fact heard in one frond is declared in
|
|
96
|
+
* another — so the per-frond map is built here, where the question IS per frond.
|
|
97
|
+
*/
|
|
98
|
+
private async read(input: Freeze) {
|
|
99
|
+
const scan = await this.projectScan.at(input.root ?? undefined);
|
|
100
|
+
return Promise.all(
|
|
101
|
+
scan.fronds
|
|
102
|
+
.filter((frond) => frond.entities.length > 0)
|
|
103
|
+
.map(async (frond) => ({
|
|
104
|
+
path: frond.source.path,
|
|
105
|
+
bundle: describeSet(Object.fromEntries(frond.entities.map((e) => [e.name, e.entityClass]))),
|
|
106
|
+
declared: declaredRenames(frond.entities),
|
|
107
|
+
previous: await previousOf(frond.source.path, input.version),
|
|
108
|
+
})),
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
type Inspected = { previous?: { name: string }; step?: SetDiff };
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* What the entities state about themselves — `previous` says what a field WAS, while
|
|
117
|
+
* `diff` reads old → new, so the pair is turned around here and nowhere else.
|
|
118
|
+
*/
|
|
119
|
+
function declaredRenames(
|
|
120
|
+
entities: ReadonlyArray<{ name: string; entityClass: unknown }>,
|
|
121
|
+
): Record<string, Record<string, string>> {
|
|
122
|
+
const out: Record<string, Record<string, string>> = {};
|
|
123
|
+
for (const { name, entityClass } of entities) {
|
|
124
|
+
const previous = (entityClass as { previous?: Record<string, string> }).previous;
|
|
125
|
+
// Keyed as `describeSet` keys `$defs`, which is what `diffSet` reads. Spelling the
|
|
126
|
+
// convention a second way here is the defect this repo has already recorded twice.
|
|
127
|
+
const key = registrationKeyOf(name);
|
|
128
|
+
if (previous) out[key] = Object.fromEntries(Object.entries(previous).map(([now, was]) => [was, now]));
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Every source of an answer, folded per entity — later sources win field by field. */
|
|
134
|
+
function settled(
|
|
135
|
+
sources: ReadonlyArray<Record<string, Record<string, string>>>,
|
|
136
|
+
answers: Record<string, Record<string, string>>,
|
|
137
|
+
): Record<string, Record<string, string>> {
|
|
138
|
+
const out: Record<string, Record<string, string>> = {};
|
|
139
|
+
for (const source of [...sources, answers]) {
|
|
140
|
+
for (const [entity, pairs] of Object.entries(source)) out[entity] = { ...(out[entity] ?? {}), ...pairs };
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The version every frond steps from. They are cut together, so they agree. */
|
|
146
|
+
function previousName(inspected: readonly Inspected[]): string | undefined {
|
|
147
|
+
return inspected.find(({ previous }) => previous)?.previous?.name;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* One report out of several fronds — entity names are unique across a scan, so the
|
|
152
|
+
* union loses nothing. Writing stays per frond; only the telling is gathered.
|
|
153
|
+
*/
|
|
154
|
+
function merge(inspected: readonly Inspected[]): SetDiff | undefined {
|
|
155
|
+
const steps = inspected.map(({ step }) => step).filter((step): step is SetDiff => Boolean(step));
|
|
156
|
+
if (steps.length === 0) return undefined;
|
|
157
|
+
return {
|
|
158
|
+
entities: Object.assign({}, ...steps.map((step) => step.entities)),
|
|
159
|
+
entitiesAdded: steps.flatMap((step) => step.entitiesAdded),
|
|
160
|
+
entitiesRemoved: steps.flatMap((step) => step.entitiesRemoved),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The version this one steps from: the tip of the chain, the links read rather than sorted. */
|
|
165
|
+
async function previousOf(root: string, version: string): Promise<{ name: string; bundle: SchemaBundle } | undefined> {
|
|
166
|
+
const chain = (await chainOf(root)).filter((cut) => cut.name !== version);
|
|
167
|
+
const last = chain.at(-1)?.name;
|
|
168
|
+
if (!last) return undefined;
|
|
169
|
+
|
|
170
|
+
const raw = await readFile(join(root, VERSIONS, last, 'shape.json'), 'utf8').catch(() => undefined);
|
|
171
|
+
return raw ? { name: last, bundle: JSON.parse(raw) as SchemaBundle } : undefined;
|
|
172
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { loadConfig } from '@fougere/core/node';
|
|
2
|
+
import { resolveStorage } from '@fougere/defaults';
|
|
3
|
+
import { actualState, desiredTables, planStep, collapseChain, applyStep, type Plan, type StepChange } from '@fougere/adapter-sql';
|
|
4
|
+
import type { SetDiff } from '@fougere/schema';
|
|
5
|
+
import ProjectScan from '../services/ProjectScan.js';
|
|
6
|
+
import { chainOf } from '../versions.js';
|
|
7
|
+
import type Migrate from '../entities/Migrate.js';
|
|
8
|
+
|
|
9
|
+
export interface MigrationPlan {
|
|
10
|
+
/** Versions whose step was read, oldest first. */
|
|
11
|
+
chain: string[];
|
|
12
|
+
changes: StepChange[];
|
|
13
|
+
refusals: Plan['refusals'];
|
|
14
|
+
/** The statements actually run — empty unless `apply` was asked for. */
|
|
15
|
+
ran: string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Catching the database up with the frozen chain.
|
|
20
|
+
*
|
|
21
|
+
* Every step is replayed in order and what has already happened is SKIPPED, read off the
|
|
22
|
+
* columns themselves rather than a ledger of applied migrations. That is what makes the
|
|
23
|
+
* chain safe to replay whole: nothing here has to know which version the database sits
|
|
24
|
+
* at, and a column renamed by hand is seen rather than contradicted.
|
|
25
|
+
*
|
|
26
|
+
* The additive pass is not repeated here — a boot already creates missing tables and
|
|
27
|
+
* columns. What this adds is the half that touches live data, and only what a human
|
|
28
|
+
* declared at `fougere freeze`.
|
|
29
|
+
*/
|
|
30
|
+
export default class MigrateHandler {
|
|
31
|
+
constructor(private projectScan: ProjectScan) {}
|
|
32
|
+
|
|
33
|
+
/** Realise the frozen steps this database has not caught up with. */
|
|
34
|
+
async execute(input: Migrate): Promise<MigrationPlan> {
|
|
35
|
+
const scan = await this.projectScan.at(input.root ?? undefined);
|
|
36
|
+
const perFrond = await Promise.all(scan.fronds.map((frond) => stepsOf(frond.source.path)));
|
|
37
|
+
const steps = perFrond.flat();
|
|
38
|
+
if (steps.length === 0) return { chain: [], changes: [], refusals: [], ran: [] };
|
|
39
|
+
|
|
40
|
+
const config = await loadConfig(scan.root);
|
|
41
|
+
const storage = resolveStorage(config.db ?? {});
|
|
42
|
+
if (!storage.db) {
|
|
43
|
+
return {
|
|
44
|
+
chain: versionsOf(steps),
|
|
45
|
+
changes: [],
|
|
46
|
+
refusals: [{ entity: '*', field: '*', reason: 'no `db` in fougere.config.ts — nothing to migrate' }],
|
|
47
|
+
ran: [],
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const tables = desiredTables(scan as never);
|
|
52
|
+
// Each frond's chain is composed on its own — its versions are its own line — and the
|
|
53
|
+
// results are gathered by SOURCE, because an engine is what a statement runs against.
|
|
54
|
+
const composed = collapseChain(perFrond.map((chain) => collapseChain(chain.map(({ step }) => step))));
|
|
55
|
+
const sourceOf = storage.sourceOf ?? (() => 'db');
|
|
56
|
+
|
|
57
|
+
const changes: StepChange[] = [];
|
|
58
|
+
const refusals: Plan['refusals'] = [];
|
|
59
|
+
const ran: string[] = [];
|
|
60
|
+
for (const source of storage.sources?.() ?? ['db']) {
|
|
61
|
+
const db = (source === 'db' ? storage.db : storage.dbOf?.(source)) as Parameters<typeof actualState>[0];
|
|
62
|
+
if (!db) continue;
|
|
63
|
+
|
|
64
|
+
const mine = onSource(composed, source, sourceOf);
|
|
65
|
+
if (Object.keys(mine.entities).length === 0) continue;
|
|
66
|
+
|
|
67
|
+
const plan = planStep(mine, tables, { actual: await actualState(db) });
|
|
68
|
+
changes.push(...plan.changes);
|
|
69
|
+
refusals.push(...plan.refusals);
|
|
70
|
+
// Held back: a refusal anywhere stops every engine, for the reason it stops every
|
|
71
|
+
// statement — half a chain is worse across two engines than within one.
|
|
72
|
+
if (input.apply && refusals.length === 0) ran.push(...(await applyStep(plan, db)));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return { chain: versionsOf(steps), changes, refusals, ran: refusals.length > 0 ? [] : ran };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The versions read, oldest first and each named once however many fronds cut it. */
|
|
80
|
+
function versionsOf(steps: ReadonlyArray<{ version: string }>): string[] {
|
|
81
|
+
return [...new Set(steps.map(({ version }) => version))].sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The part of a step whose entities live on one engine. */
|
|
85
|
+
function onSource(step: SetDiff, source: string, sourceOf: (entity: string) => string): SetDiff {
|
|
86
|
+
return {
|
|
87
|
+
...step,
|
|
88
|
+
entities: Object.fromEntries(Object.entries(step.entities).filter(([entity]) => sourceOf(entity) === source)),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Every recorded step, oldest first — the chain composes, so it is replayed whole. */
|
|
93
|
+
async function stepsOf(frondPath: string): Promise<Array<{ version: string; step: SetDiff }>> {
|
|
94
|
+
const chain = await chainOf(frondPath);
|
|
95
|
+
// The first version has a shape and no step — there was nothing before it to move from.
|
|
96
|
+
return chain.flatMap(({ name, step }) => (step ? [{ version: name, step }] : []));
|
|
97
|
+
}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { type FougereConfig, type ScanResult } from '@fougere/core';
|
|
2
|
+
import {
|
|
3
|
+
scanProject, frondAliases, setModuleLoader, loadConfig, resolveConventions,
|
|
4
|
+
} from '@fougere/core/node';
|
|
2
5
|
import { resolve } from 'node:path';
|
|
3
6
|
|
|
4
7
|
/**
|
|
@@ -18,18 +21,31 @@ export default class ProjectScan {
|
|
|
18
21
|
private cwd = process.cwd();
|
|
19
22
|
|
|
20
23
|
/** Scan the project at `root`, relative to where the command was invoked. */
|
|
21
|
-
async at(root?: string): Promise<ScanResult & { root: string }> {
|
|
24
|
+
async at(root?: string): Promise<ScanResult & { root: string; config: FougereConfig }> {
|
|
22
25
|
const target = resolve(this.cwd, root || '.');
|
|
23
26
|
|
|
24
27
|
// The scan reads `.ts` sources; the default loader is a plain `import`, which
|
|
25
28
|
// cannot. Installed once per call because the loader is module-global — the
|
|
26
29
|
// CLI's own app was loaded with its own, and this replaces it for the target.
|
|
27
30
|
const { createJiti } = await import('jiti');
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
31
|
+
const install = (alias?: Record<string, string>): void => {
|
|
32
|
+
const jiti = createJiti(import.meta.url, { interopDefault: true, ...(alias ? { alias } : {}) });
|
|
33
|
+
setModuleLoader((filePath) => jiti.import(filePath) as Promise<Record<string, unknown>>);
|
|
34
|
+
};
|
|
32
35
|
|
|
33
|
-
|
|
36
|
+
/**
|
|
37
|
+
* The config is read BEFORE the aliases, because it names the scope they are built
|
|
38
|
+
* from. Safe because nothing in `fougere.config.ts` may import `@fronds/*` — the one
|
|
39
|
+
* import that would need the name to read the file that declares it.
|
|
40
|
+
*/
|
|
41
|
+
install();
|
|
42
|
+
const config = await loadConfig(target);
|
|
43
|
+
const conventions = resolveConventions(config.conventions);
|
|
44
|
+
|
|
45
|
+
// The scope is the framework's own convention; the loader has to know it, or a frond
|
|
46
|
+
// naming its neighbour is unreadable to the very tool that checks it.
|
|
47
|
+
install(await frondAliases(target, conventions));
|
|
48
|
+
|
|
49
|
+
return { root: target, config, ...(await scanProject(target, undefined, conventions)) };
|
|
34
50
|
}
|
|
35
51
|
}
|