suppa-mcp-2 1.1.3 → 1.2.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/LICENSE +21 -21
- package/README.md +379 -342
- package/dist/auth.js +29 -25
- package/dist/server.js +92 -51
- package/dist/tools/entity.js +343 -40
- package/dist/tools/migrate.js +459 -144
- package/package.json +50 -50
- package/skills/suppa-entity-code/SKILL.md +122 -0
- package/skills/suppa-entity-code/references/entities.md +289 -0
- package/skills/suppa-entity-code/references/registration.md +174 -0
- package/skills/suppa-entity-code/references/seeds.md +134 -0
- package/skills/suppa-entity-code/references/v1-mapping.md +78 -0
- package/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs +692 -0
- package/skills/suppa-entity-code/templates/entity.template.ts +79 -0
- package/skills/suppa-entity-code/templates/seed.template.ts +41 -0
|
@@ -0,0 +1,692 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* validate-suppa-schema.mjs — static checker for Suppa v2 application schema
|
|
3
|
+
* code (entities, seeds, EntityModule registration). AST-only via the
|
|
4
|
+
* TypeScript compiler API; no type-checking, no module resolution.
|
|
5
|
+
*
|
|
6
|
+
* Every rule quotes the migrations doc
|
|
7
|
+
* (docs.modern-expo.com/backend/application-developing/migrations.html):
|
|
8
|
+
* these mistakes compile under tsc and only fail at migration time.
|
|
9
|
+
*
|
|
10
|
+
* Usage: node validate-suppa-schema.mjs <app-root-or-files...>
|
|
11
|
+
* Import: import { validateSchema } from "./validate-suppa-schema.mjs"
|
|
12
|
+
*/
|
|
13
|
+
import { createRequire } from "node:module";
|
|
14
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
15
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
16
|
+
import { pathToFileURL } from "node:url";
|
|
17
|
+
|
|
18
|
+
// ── Doc-derived catalogs (fallback when @suppa/sdk typings are absent) ──
|
|
19
|
+
export const SYSTEM_COLUMNS = ["id", "createdAt", "updatedAt", "deletedAt", "createdBy", "removedBy"];
|
|
20
|
+
export const ACCESS_METADATA_KEYS = ["$readAccess", "$updateAccess", "$instanceAccess"];
|
|
21
|
+
export const DOC_ENTITY_OPTIONS = ["name", "title", "comment", "representativeFieldName", "importKeyFields", "key", "icon", "type", "options"];
|
|
22
|
+
export const DOC_COLUMN_OPTIONS = ["type", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask"];
|
|
23
|
+
export const DOC_FIELD_TYPES = {
|
|
24
|
+
Text: "text", Numeric: "numeric", Integer: "integer", Serial: "serial",
|
|
25
|
+
Boolean: "boolean", Timestamp: "timestamp", JSON: "json", UUID: "uuid",
|
|
26
|
+
MultiLang: "multi-language", Bytea: "bytea", TsVector: "tsvector",
|
|
27
|
+
MultiType: "multi-type", Icon: "icon",
|
|
28
|
+
};
|
|
29
|
+
const NON_SCALAR_TYPE_STRINGS = new Set([
|
|
30
|
+
"enum", "multi-enum", "file", "multi-file",
|
|
31
|
+
"many-to-one", "one-to-many", "many-to-many", "many-to-many-backref",
|
|
32
|
+
"relation", "attachment",
|
|
33
|
+
]);
|
|
34
|
+
const RELATION_KIND_BY_DECORATOR = {
|
|
35
|
+
ManyToOne: "many-to-one", ManyToMany: "many-to-many",
|
|
36
|
+
ManyToManyBackRef: "many-to-many-backref", OneToMany: "one-to-many",
|
|
37
|
+
};
|
|
38
|
+
const ENUM_DECORATORS = new Set(["Enum", "MultiEnum"]);
|
|
39
|
+
const FILE_DECORATORS = new Set(["File", "MultiFile"]);
|
|
40
|
+
|
|
41
|
+
// ── typescript resolution: target app first, this package as fallback ──
|
|
42
|
+
export function loadTypescript(rootDir) {
|
|
43
|
+
const froms = [];
|
|
44
|
+
if (rootDir) froms.push(join(resolve(rootDir), "package.json"));
|
|
45
|
+
froms.push(import.meta.url);
|
|
46
|
+
for (const from of froms) {
|
|
47
|
+
try {
|
|
48
|
+
return createRequire(from)("typescript");
|
|
49
|
+
} catch {
|
|
50
|
+
/* try next */
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
throw new Error(
|
|
54
|
+
"validate-suppa-schema: cannot resolve 'typescript' — run `npm install` in the app repo first.",
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ── small AST helpers ──
|
|
59
|
+
function finding(ts, sf, node, code, message) {
|
|
60
|
+
const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
|
|
61
|
+
return {
|
|
62
|
+
file: sf.fileName, line: line + 1, col: character + 1, code,
|
|
63
|
+
level: code.startsWith("W") ? "warning" : "error", message,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function decoratorsOf(ts, node) {
|
|
67
|
+
return (ts.canHaveDecorators?.(node) ? ts.getDecorators(node) : undefined) ?? [];
|
|
68
|
+
}
|
|
69
|
+
function decoratorCall(ts, dec) {
|
|
70
|
+
const e = dec.expression;
|
|
71
|
+
if (ts.isCallExpression(e) && ts.isIdentifier(e.expression)) {
|
|
72
|
+
return { name: e.expression.text, args: [...e.arguments] };
|
|
73
|
+
}
|
|
74
|
+
if (ts.isIdentifier(e)) return { name: e.text, args: [] };
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
function objectMap(ts, node) {
|
|
78
|
+
const map = new Map();
|
|
79
|
+
if (!node || !ts.isObjectLiteralExpression(node)) return map;
|
|
80
|
+
for (const p of node.properties) {
|
|
81
|
+
if (ts.isPropertyAssignment(p)) {
|
|
82
|
+
const name =
|
|
83
|
+
ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : null;
|
|
84
|
+
if (name !== null) map.set(name, p.initializer);
|
|
85
|
+
} else if (ts.isShorthandPropertyAssignment(p)) {
|
|
86
|
+
map.set(p.name.text, p.name);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return map;
|
|
90
|
+
}
|
|
91
|
+
function stringValue(ts, node) {
|
|
92
|
+
return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
|
|
93
|
+
? node.text
|
|
94
|
+
: null;
|
|
95
|
+
}
|
|
96
|
+
function stringArray(ts, node) {
|
|
97
|
+
if (!node || !ts.isArrayLiteralExpression(node)) return null;
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const el of node.elements) {
|
|
100
|
+
const s = stringValue(ts, el);
|
|
101
|
+
if (s === null) return null;
|
|
102
|
+
out.push(s);
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
function thunkTarget(ts, arg) {
|
|
107
|
+
if (arg && ts.isArrowFunction(arg)) {
|
|
108
|
+
const b = arg.body;
|
|
109
|
+
if (ts.isIdentifier(b)) return b.text;
|
|
110
|
+
if (ts.isPropertyAccessExpression(b)) return b.name.text;
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
function spreadElements(ts, node) {
|
|
115
|
+
if (!node || !ts.isObjectLiteralExpression(node)) return [];
|
|
116
|
+
return node.properties.filter((p) => ts.isSpreadAssignment(p));
|
|
117
|
+
}
|
|
118
|
+
function arraySpreadElements(ts, node) {
|
|
119
|
+
if (!node || !ts.isArrayLiteralExpression(node)) return [];
|
|
120
|
+
return node.elements.filter((e) => ts.isSpreadElement(e));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ── extraction: entities ──
|
|
124
|
+
function analyzeEntities(ts, sf, model) {
|
|
125
|
+
sf.forEachChild(function walk(node) {
|
|
126
|
+
if (ts.isClassDeclaration(node)) {
|
|
127
|
+
const decs = decoratorsOf(ts, node).map((d) => decoratorCall(ts, d)).filter(Boolean);
|
|
128
|
+
const entityDec = decs.find((d) => d.name === "Entity");
|
|
129
|
+
if (entityDec) {
|
|
130
|
+
const className = node.name ? node.name.text : "<anonymous>";
|
|
131
|
+
const options = objectMap(ts, entityDec.args[0]);
|
|
132
|
+
const info = {
|
|
133
|
+
className,
|
|
134
|
+
entityName: stringValue(ts, options.get("name")) ?? className,
|
|
135
|
+
sf, node, options, optionsNode: entityDec.args[0],
|
|
136
|
+
importKeyFields: stringArray(ts, options.get("importKeyFields")),
|
|
137
|
+
hasKey: options.has("key"),
|
|
138
|
+
properties: new Map(),
|
|
139
|
+
};
|
|
140
|
+
for (const member of node.members) {
|
|
141
|
+
if (!ts.isPropertyDeclaration(member) || !member.name) continue;
|
|
142
|
+
const propName =
|
|
143
|
+
ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)
|
|
144
|
+
? member.name.text
|
|
145
|
+
: member.name.getText(sf);
|
|
146
|
+
for (const d of decoratorsOf(ts, member).map((x) => decoratorCall(ts, x)).filter(Boolean)) {
|
|
147
|
+
if (d.name === "Column") {
|
|
148
|
+
info.properties.set(propName, {
|
|
149
|
+
kind: "column", node: member, decorator: d,
|
|
150
|
+
columnOptions: objectMap(ts, d.args[0]), optionsNode: d.args[0],
|
|
151
|
+
});
|
|
152
|
+
} else if (ENUM_DECORATORS.has(d.name)) {
|
|
153
|
+
info.properties.set(propName, {
|
|
154
|
+
kind: d.name === "Enum" ? "enum" : "multi-enum",
|
|
155
|
+
node: member, decorator: d,
|
|
156
|
+
enumGlobalName: stringValue(ts, d.args[0]),
|
|
157
|
+
});
|
|
158
|
+
} else if (FILE_DECORATORS.has(d.name)) {
|
|
159
|
+
info.properties.set(propName, {
|
|
160
|
+
kind: d.name === "File" ? "file" : "multi-file",
|
|
161
|
+
node: member, decorator: d,
|
|
162
|
+
});
|
|
163
|
+
} else if (d.name in RELATION_KIND_BY_DECORATOR) {
|
|
164
|
+
info.properties.set(propName, {
|
|
165
|
+
kind: RELATION_KIND_BY_DECORATOR[d.name],
|
|
166
|
+
node: member, decorator: d,
|
|
167
|
+
targetClass: thunkTarget(ts, d.args[0]),
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
model.entities.set(className, info);
|
|
173
|
+
model.entityByName.set(info.entityName, info);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
ts.forEachChild(node, walk);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ── rules: entities ──
|
|
181
|
+
function checkEntity(ts, info, sdk, findings) {
|
|
182
|
+
const sf = info.sf;
|
|
183
|
+
const anchor = info.node.name ?? info.node;
|
|
184
|
+
|
|
185
|
+
const heritage = (info.node.heritageClauses ?? []).find(
|
|
186
|
+
(h) => h.token === ts.SyntaxKind.ExtendsKeyword,
|
|
187
|
+
);
|
|
188
|
+
const base = heritage?.types?.[0]?.expression;
|
|
189
|
+
const baseName = base && ts.isIdentifier(base) ? base.text : null;
|
|
190
|
+
if (baseName !== "SystemBaseEntity") {
|
|
191
|
+
findings.push(finding(ts, sf, anchor, "E101",
|
|
192
|
+
`entity class '${info.className}' must extend SystemBaseEntity — it contributes id/createdAt/updatedAt/deletedAt/createdBy/removedBy (doc: "Every entity must extend SystemBaseEntity")`));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
for (const [opt, valNode] of info.options) {
|
|
196
|
+
if (!sdk.entityOptions.includes(opt)) {
|
|
197
|
+
findings.push(finding(ts, sf, valNode, "E501",
|
|
198
|
+
`unknown @Entity() option '${opt}' — valid options: ${sdk.entityOptions.join(", ")}. If it isn't in the table, it isn't an option.`));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
for (const spread of spreadElements(ts, info.optionsNode)) {
|
|
203
|
+
findings.push(finding(ts, sf, spread, "W606",
|
|
204
|
+
`@Entity() options include a spread — options delivered via spread cannot be statically validated: the doc-rule checks (unknown options, default-as-SQL-string, type checks) are skipped for spread content; inline the options to restore checking`));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (info.importKeyFields) {
|
|
208
|
+
for (const f of info.importKeyFields) {
|
|
209
|
+
if (!info.properties.has(f)) {
|
|
210
|
+
findings.push(finding(ts, sf, info.options.get("importKeyFields"), "E106",
|
|
211
|
+
`importKeyFields names '${f}' but the class declares no such property — seeds would have nothing to match on`));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (!info.hasKey) {
|
|
217
|
+
findings.push(finding(ts, sf, anchor, "W602",
|
|
218
|
+
`entity '${info.className}' has no 'key' option — a rename will be treated as drop-and-create instead of a rename (doc TIP)`));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
for (const [propName, prop] of info.properties) {
|
|
222
|
+
if (SYSTEM_COLUMNS.includes(propName)) {
|
|
223
|
+
findings.push(finding(ts, sf, prop.node, "E102",
|
|
224
|
+
`system column '${propName}' is provided by SystemBaseEntity — "you never declare them yourself"`));
|
|
225
|
+
}
|
|
226
|
+
if (prop.kind === "column") checkColumn(ts, sf, prop, sdk, findings);
|
|
227
|
+
if (prop.kind in { "many-to-one": 1, "many-to-many": 1, "many-to-many-backref": 1, "one-to-many": 1 } &&
|
|
228
|
+
prop.targetClass === null) {
|
|
229
|
+
findings.push(finding(ts, sf, prop.node, "E105",
|
|
230
|
+
`relation '${propName}' must receive a thunk returning the target class — write @${prop.decorator.name}(() => Target); a direct class reference breaks circular imports`));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function checkColumn(ts, sf, prop, sdk, findings) {
|
|
236
|
+
const opts = prop.columnOptions;
|
|
237
|
+
for (const [opt, valNode] of opts) {
|
|
238
|
+
if (!sdk.columnOptions.includes(opt)) {
|
|
239
|
+
findings.push(finding(ts, sf, valNode, "E502",
|
|
240
|
+
`unknown @Column() option '${opt}' — valid options: ${sdk.columnOptions.join(", ")}. If it isn't in the table, it isn't an option.`));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
for (const spread of spreadElements(ts, prop.optionsNode)) {
|
|
245
|
+
findings.push(finding(ts, sf, spread, "W606",
|
|
246
|
+
`@Column() options include a spread — options delivered via spread cannot be statically validated: the doc-rule checks (unknown options, default-as-SQL-string, type checks) are skipped for spread content; inline the options to restore checking`));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
let typeValue = null; // canonical string value, e.g. "text"
|
|
250
|
+
const typeNode = opts.get("type");
|
|
251
|
+
if (typeNode) {
|
|
252
|
+
if (ts.isPropertyAccessExpression(typeNode) &&
|
|
253
|
+
ts.isIdentifier(typeNode.expression) &&
|
|
254
|
+
typeNode.expression.text === "FieldTypeEnum") {
|
|
255
|
+
const member = typeNode.name.text;
|
|
256
|
+
typeValue = sdk.fieldTypes[member] ?? null;
|
|
257
|
+
if (typeValue === null) {
|
|
258
|
+
findings.push(finding(ts, sf, typeNode, "E107",
|
|
259
|
+
`FieldTypeEnum.${member} is not a known member — valid: ${Object.keys(sdk.fieldTypes).join(", ")}`));
|
|
260
|
+
}
|
|
261
|
+
} else {
|
|
262
|
+
const raw = stringValue(ts, typeNode);
|
|
263
|
+
if (raw !== null) {
|
|
264
|
+
if (NON_SCALAR_TYPE_STRINGS.has(raw)) {
|
|
265
|
+
findings.push(finding(ts, sf, typeNode, "E104",
|
|
266
|
+
`@Column type '${raw}' — relations, enums and files are declared with their own decorators (@ManyToOne/@Enum/@File/…) "and never with @Column({ type: ... })"`));
|
|
267
|
+
} else {
|
|
268
|
+
const member = Object.keys(sdk.fieldTypes).find((k) => sdk.fieldTypes[k] === raw);
|
|
269
|
+
if (member) {
|
|
270
|
+
typeValue = raw;
|
|
271
|
+
findings.push(finding(ts, sf, typeNode, "W601",
|
|
272
|
+
`raw string type '${raw}' — use FieldTypeEnum.${member} so a typo fails in the editor instead of at migration time`));
|
|
273
|
+
} else {
|
|
274
|
+
findings.push(finding(ts, sf, typeNode, "E107",
|
|
275
|
+
`unknown column type '${raw}' — "a misspelled one ('txet') compiles too and only fails when the migration runs"`));
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const def = opts.get("default");
|
|
283
|
+
if (def && stringValue(ts, def) === null) {
|
|
284
|
+
findings.push(finding(ts, sf, def, "E103",
|
|
285
|
+
`'default' must be a SQL expression STRING — "Write default: 'false', not default: false, and default: \\"'draft'\\" for a string literal"`));
|
|
286
|
+
}
|
|
287
|
+
if (opts.has("length") && typeValue !== null && typeValue !== "text") {
|
|
288
|
+
findings.push(finding(ts, sf, opts.get("length"), "W603",
|
|
289
|
+
`'length' caps Text columns; this column is '${typeValue}'`));
|
|
290
|
+
}
|
|
291
|
+
if (opts.has("decimalPlaces") && typeValue !== null && typeValue !== "numeric") {
|
|
292
|
+
findings.push(finding(ts, sf, opts.get("decimalPlaces"), "W604",
|
|
293
|
+
`'decimalPlaces' pairs with Numeric columns; this column is '${typeValue}'`));
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// ── extraction: seeds ──
|
|
298
|
+
function analyzeSeeds(ts, sf, model) {
|
|
299
|
+
sf.forEachChild(function walk(node) {
|
|
300
|
+
if (ts.isVariableStatement(node)) {
|
|
301
|
+
for (const decl of node.declarationList.declarations) {
|
|
302
|
+
const init = decl.initializer;
|
|
303
|
+
if (init && ts.isCallExpression(init) &&
|
|
304
|
+
ts.isIdentifier(init.expression) && init.expression.text === "createSeed") {
|
|
305
|
+
const exportName = ts.isIdentifier(decl.name) ? decl.name.text : decl.name.getText(sf);
|
|
306
|
+
const arg0 = init.arguments[0];
|
|
307
|
+
let entityName = stringValue(ts, arg0);
|
|
308
|
+
if (entityName === null && arg0 && ts.isPropertyAccessExpression(arg0)) {
|
|
309
|
+
entityName = arg0.name.text; // EntityNamesEnum.Workflows → "Workflows"
|
|
310
|
+
}
|
|
311
|
+
const arg1 = init.arguments[1];
|
|
312
|
+
let records = null; // null = thin seed (imported payload) — record checks impossible
|
|
313
|
+
if (arg1 && ts.isArrayLiteralExpression(arg1)) {
|
|
314
|
+
records = arg1.elements.map((e) =>
|
|
315
|
+
ts.isObjectLiteralExpression(e)
|
|
316
|
+
? { node: e, map: objectMap(ts, e), hasSpread: spreadElements(ts, e).length > 0, spreads: spreadElements(ts, e), byRef: false }
|
|
317
|
+
: { node: e, map: new Map(), hasSpread: false, spreads: [], byRef: true },
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
model.seeds.push({ exportName, entityName, sf, node: init, records });
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
ts.forEachChild(node, walk);
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ── rules: seeds ──
|
|
329
|
+
function checkSeed(ts, seed, model, findings) {
|
|
330
|
+
const sf = seed.sf;
|
|
331
|
+
const entity = seed.entityName ? model.entityByName.get(seed.entityName) : undefined;
|
|
332
|
+
if (entity && (!entity.importKeyFields || entity.importKeyFields.length === 0)) {
|
|
333
|
+
findings.push(finding(ts, sf, seed.node, "W605",
|
|
334
|
+
`entity '${seed.entityName}' has a seed but no importKeyFields — "seeds have nothing to match on and cannot stay idempotent"`));
|
|
335
|
+
}
|
|
336
|
+
if (!seed.records) return;
|
|
337
|
+
for (const rec of seed.records) {
|
|
338
|
+
if (rec.byRef) {
|
|
339
|
+
findings.push(finding(ts, sf, rec.node, "W606",
|
|
340
|
+
`seed record passed by reference cannot be statically validated — E201-E206 and importKeyFields checks are skipped for it; inline the record object to restore checking`));
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
for (const [key, valNode] of rec.map) {
|
|
344
|
+
if (SYSTEM_COLUMNS.includes(key)) {
|
|
345
|
+
findings.push(finding(ts, sf, valNode, "E201",
|
|
346
|
+
`seed record contains system column '${key}' — "they differ per tenant and corrupt matching"`));
|
|
347
|
+
}
|
|
348
|
+
if (ACCESS_METADATA_KEYS.includes(key)) {
|
|
349
|
+
findings.push(finding(ts, sf, valNode, "E202",
|
|
350
|
+
`seed record contains '${key}' — "access metadata, not data"`));
|
|
351
|
+
}
|
|
352
|
+
const prop = entity?.properties.get(key);
|
|
353
|
+
if (!prop) continue;
|
|
354
|
+
if (prop.kind === "many-to-one" || prop.kind === "many-to-many") {
|
|
355
|
+
const isNum = (n) =>
|
|
356
|
+
ts.isNumericLiteral(n) ||
|
|
357
|
+
(ts.isPrefixUnaryExpression(n) && ts.isNumericLiteral(n.operand));
|
|
358
|
+
const bad = isNum(valNode) ||
|
|
359
|
+
(ts.isArrayLiteralExpression(valNode) && valNode.elements.some(isNum));
|
|
360
|
+
if (bad) {
|
|
361
|
+
findings.push(finding(ts, sf, valNode, "E203",
|
|
362
|
+
`relation '${key}' referenced by numeric id — ids "do not match across tenants"; reference through the target's importKeyFields, e.g. { name: 'Default' }`));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
if (prop.kind === "one-to-many") {
|
|
366
|
+
findings.push(finding(ts, sf, valNode, "E204",
|
|
367
|
+
`reverse @OneToMany field '${key}' in a seed (even as []) — "back references cannot be inserted; the import throws". Seed the child entity with its own seed.`));
|
|
368
|
+
}
|
|
369
|
+
if (prop.kind === "enum" || prop.kind === "multi-enum") {
|
|
370
|
+
const okRef = (n) => {
|
|
371
|
+
if (!ts.isObjectLiteralExpression(n)) return false;
|
|
372
|
+
const m = objectMap(ts, n);
|
|
373
|
+
return m.has("name") && m.has("value") && m.size === 2;
|
|
374
|
+
};
|
|
375
|
+
const ok = prop.kind === "enum"
|
|
376
|
+
? okRef(valNode)
|
|
377
|
+
: ts.isArrayLiteralExpression(valNode) && valNode.elements.every(okRef);
|
|
378
|
+
if (!ok && valNode.kind !== ts.SyntaxKind.NullKeyword) {
|
|
379
|
+
findings.push(finding(ts, sf, valNode, "E206",
|
|
380
|
+
`enum reference '${key}' must be { name: '<global enum name>', value: '<enum value>' }${prop.kind === "multi-enum" ? " — an array of those for @MultiEnum" : ""}`));
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
for (const spread of rec.spreads ?? []) {
|
|
385
|
+
findings.push(finding(ts, sf, spread, "W606",
|
|
386
|
+
`seed record content delivered via spread cannot be statically validated — E201-E206 checks are skipped for spread content; inline the record fields to restore checking`));
|
|
387
|
+
}
|
|
388
|
+
if (rec.hasSpread) continue; // spread may deliver the import key — E205 would false-positive
|
|
389
|
+
if (entity?.importKeyFields?.length && !rec.map.has("$key")) {
|
|
390
|
+
for (const f of entity.importKeyFields) {
|
|
391
|
+
if (!rec.map.has(f)) {
|
|
392
|
+
findings.push(finding(ts, sf, rec.node, "E205",
|
|
393
|
+
`seed record is missing importKeyField '${f}' of '${seed.entityName}' — nothing matches ⇒ duplicate rows after every restart. Provide it or override identity with $key.`));
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ── extraction: EntityModule.forFeature ──
|
|
401
|
+
function analyzeModules(ts, sf, model) {
|
|
402
|
+
sf.forEachChild(function walk(node) {
|
|
403
|
+
if (ts.isCallExpression(node) &&
|
|
404
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
405
|
+
node.expression.name.text === "forFeature" &&
|
|
406
|
+
ts.isIdentifier(node.expression.expression) &&
|
|
407
|
+
node.expression.expression.text === "EntityModule") {
|
|
408
|
+
const m = {
|
|
409
|
+
sf, node, shape: null,
|
|
410
|
+
entityClassNames: [], seedExportNames: [], seedsNode: node,
|
|
411
|
+
entitiesPath: null, seedsPath: null, entitiesPathNode: null, seedsPathNode: null,
|
|
412
|
+
entitiesSpreads: [], seedsSpreads: [],
|
|
413
|
+
};
|
|
414
|
+
const a0 = node.arguments[0];
|
|
415
|
+
if (a0 && ts.isArrayLiteralExpression(a0)) {
|
|
416
|
+
m.shape = "classes";
|
|
417
|
+
m.entityClassNames = a0.elements.filter((e) => ts.isIdentifier(e)).map((e) => e.text);
|
|
418
|
+
m.entitiesSpreads = arraySpreadElements(ts, a0);
|
|
419
|
+
const opts = objectMap(ts, node.arguments[1]);
|
|
420
|
+
const seeds = opts.get("seeds");
|
|
421
|
+
if (seeds && ts.isArrayLiteralExpression(seeds)) {
|
|
422
|
+
m.seedExportNames = seeds.elements.filter((e) => ts.isIdentifier(e)).map((e) => e.text);
|
|
423
|
+
m.seedsNode = seeds;
|
|
424
|
+
m.seedsSpreads = arraySpreadElements(ts, seeds);
|
|
425
|
+
}
|
|
426
|
+
} else if (a0 && ts.isObjectLiteralExpression(a0)) {
|
|
427
|
+
m.shape = "options";
|
|
428
|
+
const opts = objectMap(ts, a0);
|
|
429
|
+
for (const [key, prop] of [["entitiesPath", "entitiesPath"], ["seedsPath", "seedsPath"]]) {
|
|
430
|
+
const n = opts.get(key);
|
|
431
|
+
if (!n) continue;
|
|
432
|
+
const single = stringValue(ts, n);
|
|
433
|
+
m[prop] = single !== null ? [single] : stringArray(ts, n);
|
|
434
|
+
m[`${prop}Node`] = n;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
model.modules.push(m);
|
|
438
|
+
}
|
|
439
|
+
ts.forEachChild(node, walk);
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// ── rules: registration ──
|
|
444
|
+
function checkRegistration(ts, model, findings) {
|
|
445
|
+
const classModules = model.modules.filter((m) => m.shape === "classes");
|
|
446
|
+
const optionModules = model.modules.filter((m) => m.shape === "options");
|
|
447
|
+
|
|
448
|
+
for (const m of optionModules) {
|
|
449
|
+
for (const [label, paths, pnode] of [
|
|
450
|
+
["entitiesPath", m.entitiesPath, m.entitiesPathNode],
|
|
451
|
+
["seedsPath", m.seedsPath, m.seedsPathNode],
|
|
452
|
+
]) {
|
|
453
|
+
for (const p of paths ?? []) {
|
|
454
|
+
if (/(^|\/)src(\/|$)/.test(p.replace(/\\/g, "/"))) {
|
|
455
|
+
findings.push(finding(ts, m.sf, pnode ?? m.node, "E303",
|
|
456
|
+
`${label} '${p}' points at src/ — autoloading reads compiled output: "entitiesPath / seedsPath points at src/ instead of compiled dist/"`));
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
if (model.entities.size > 0 && model.modules.length === 0) {
|
|
463
|
+
const first = [...model.entities.values()][0];
|
|
464
|
+
findings.push(finding(ts, first.sf, first.node.name ?? first.node, "E305",
|
|
465
|
+
`no EntityModule.forFeature() found — "An entity class that is never passed to forFeature() is invisible — no table is created for it"`));
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
if (classModules.length === 0) return; // autoload shape: membership is the platform's job
|
|
469
|
+
|
|
470
|
+
for (const m of classModules) {
|
|
471
|
+
for (const spread of m.entitiesSpreads) {
|
|
472
|
+
findings.push(finding(ts, m.sf, spread, "W606",
|
|
473
|
+
`EntityModule.forFeature() entities array includes a spread — membership cannot be statically verified: E301 (unregistered entity) is skipped for entities potentially covered by it; inline the array to restore checking`));
|
|
474
|
+
}
|
|
475
|
+
for (const spread of m.seedsSpreads) {
|
|
476
|
+
findings.push(finding(ts, m.sf, spread, "W606",
|
|
477
|
+
`EntityModule.forFeature() seeds array includes a spread — membership and ordering cannot be statically verified: E302 (unregistered seed) and E304 (seed ordering) are skipped for seeds potentially covered by it; inline the array to restore checking`));
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// an autoload module anywhere may cover any entity/seed not named explicitly —
|
|
482
|
+
// membership becomes the platform's job, so E301/E302 would only false-positive.
|
|
483
|
+
const hasAutoload = optionModules.length > 0;
|
|
484
|
+
const hasEntitiesSpread = classModules.some((m) => m.entitiesSpreads.length > 0);
|
|
485
|
+
const hasSeedsSpread = classModules.some((m) => m.seedsSpreads.length > 0);
|
|
486
|
+
|
|
487
|
+
if (!hasAutoload && !hasEntitiesSpread) {
|
|
488
|
+
const registeredEntities = new Set(classModules.flatMap((m) => m.entityClassNames));
|
|
489
|
+
for (const [className, info] of model.entities) {
|
|
490
|
+
if (!registeredEntities.has(className)) {
|
|
491
|
+
findings.push(finding(ts, info.sf, info.node.name ?? info.node, "E301",
|
|
492
|
+
`entity class '${className}' is not in any forFeature() entities array — no table will be created for it`));
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (!hasAutoload && !hasSeedsSpread) {
|
|
497
|
+
const registeredSeeds = new Set(classModules.flatMap((m) => m.seedExportNames));
|
|
498
|
+
for (const seed of model.seeds) {
|
|
499
|
+
if (!registeredSeeds.has(seed.exportName)) {
|
|
500
|
+
findings.push(finding(ts, seed.sf, seed.node, "E302",
|
|
501
|
+
`seed '${seed.exportName}' is not in any forFeature() seeds array — it will never run`));
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
for (const m of classModules) {
|
|
507
|
+
if (m.seedsSpreads.length > 0) continue; // ordering indices are unreliable with a spread present
|
|
508
|
+
const order = new Map(m.seedExportNames.map((n, i) => [n, i]));
|
|
509
|
+
const reported = new Set();
|
|
510
|
+
for (const seed of model.seeds) {
|
|
511
|
+
if (!order.has(seed.exportName) || !seed.records) continue;
|
|
512
|
+
const entity = seed.entityName ? model.entityByName.get(seed.entityName) : undefined;
|
|
513
|
+
if (!entity) continue;
|
|
514
|
+
const myIdx = order.get(seed.exportName);
|
|
515
|
+
for (const rec of seed.records) {
|
|
516
|
+
for (const [key] of rec.map) {
|
|
517
|
+
const prop = entity.properties.get(key);
|
|
518
|
+
if (!prop || (prop.kind !== "many-to-one" && prop.kind !== "many-to-many") || !prop.targetClass) continue;
|
|
519
|
+
const target = model.entities.get(prop.targetClass);
|
|
520
|
+
if (!target || target === entity) continue;
|
|
521
|
+
const targetSeed = model.seeds.find(
|
|
522
|
+
(s) => s.entityName === target.entityName && order.has(s.exportName),
|
|
523
|
+
);
|
|
524
|
+
const dedupe = `${seed.exportName}->${targetSeed?.exportName}`;
|
|
525
|
+
if (targetSeed && order.get(targetSeed.exportName) > myIdx && !reported.has(dedupe)) {
|
|
526
|
+
reported.add(dedupe);
|
|
527
|
+
findings.push(finding(ts, m.sf, m.seedsNode, "E304",
|
|
528
|
+
`seed '${seed.exportName}' references '${target.entityName}' but '${targetSeed.exportName}' runs after it — "Register a seed after the seed that creates the records it points at"`));
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// ── rules: tsconfig ──
|
|
537
|
+
function checkTsconfig(ts, rootDir, findings) {
|
|
538
|
+
if (!rootDir) return;
|
|
539
|
+
const p = join(resolve(rootDir), "tsconfig.json");
|
|
540
|
+
if (!existsSync(p)) return;
|
|
541
|
+
const read = ts.readConfigFile(p, (f) => readFileSync(f, "utf-8"));
|
|
542
|
+
if (read.error) return;
|
|
543
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, resolve(rootDir));
|
|
544
|
+
const missing = [];
|
|
545
|
+
if (!parsed.options.experimentalDecorators) missing.push("experimentalDecorators");
|
|
546
|
+
if (!parsed.options.emitDecoratorMetadata) missing.push("emitDecoratorMetadata");
|
|
547
|
+
if (missing.length) {
|
|
548
|
+
findings.push({
|
|
549
|
+
file: p, line: 1, col: 1, code: "E401", level: "error",
|
|
550
|
+
message: `tsconfig.json must enable ${missing.join(" and ")} — entities rely on decorator metadata`,
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// ── SDK catalog: real @suppa/sdk typings when resolvable, doc list otherwise ──
|
|
556
|
+
function loadSdkCatalog(ts, rootDir) {
|
|
557
|
+
const catalog = {
|
|
558
|
+
entityOptions: [...DOC_ENTITY_OPTIONS],
|
|
559
|
+
columnOptions: [...DOC_COLUMN_OPTIONS],
|
|
560
|
+
fieldTypes: { ...DOC_FIELD_TYPES },
|
|
561
|
+
source: "doc",
|
|
562
|
+
};
|
|
563
|
+
if (!rootDir) return catalog;
|
|
564
|
+
let dir = resolve(rootDir);
|
|
565
|
+
let sdkDir = null;
|
|
566
|
+
for (let i = 0; i < 8; i++) {
|
|
567
|
+
const cand = join(dir, "node_modules", "@suppa", "sdk");
|
|
568
|
+
if (existsSync(cand)) { sdkDir = cand; break; }
|
|
569
|
+
const parent = dirname(dir);
|
|
570
|
+
if (parent === dir) break;
|
|
571
|
+
dir = parent;
|
|
572
|
+
}
|
|
573
|
+
if (!sdkDir) return catalog;
|
|
574
|
+
let typesPath = join(sdkDir, "index.d.ts");
|
|
575
|
+
try {
|
|
576
|
+
const pkg = JSON.parse(readFileSync(join(sdkDir, "package.json"), "utf-8"));
|
|
577
|
+
if (pkg.types || pkg.typings) typesPath = join(sdkDir, pkg.types ?? pkg.typings);
|
|
578
|
+
} catch { /* fall back to index.d.ts */ }
|
|
579
|
+
if (!existsSync(typesPath)) return catalog;
|
|
580
|
+
try {
|
|
581
|
+
const sf = ts.createSourceFile(typesPath, readFileSync(typesPath, "utf-8"), ts.ScriptTarget.Latest, true);
|
|
582
|
+
const fieldTypes = {};
|
|
583
|
+
let entityOptions = [];
|
|
584
|
+
let columnOptions = [];
|
|
585
|
+
sf.forEachChild(function walk(node) {
|
|
586
|
+
if (ts.isEnumDeclaration(node) && node.name.text === "FieldTypeEnum") {
|
|
587
|
+
for (const m of node.members) {
|
|
588
|
+
const name = ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)
|
|
589
|
+
? m.name.text : m.name.getText(sf);
|
|
590
|
+
fieldTypes[name] = m.initializer && ts.isStringLiteral(m.initializer)
|
|
591
|
+
? m.initializer.text : name;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
if (ts.isInterfaceDeclaration(node)) {
|
|
595
|
+
const props = node.members
|
|
596
|
+
.filter((mm) => ts.isPropertySignature(mm) && mm.name)
|
|
597
|
+
.map((mm) => mm.name.getText(sf).replace(/['"]/g, ""));
|
|
598
|
+
if (/EntityOptions$/i.test(node.name.text)) entityOptions = props;
|
|
599
|
+
if (/ColumnOptions$/i.test(node.name.text)) columnOptions = props;
|
|
600
|
+
}
|
|
601
|
+
ts.forEachChild(node, walk);
|
|
602
|
+
});
|
|
603
|
+
let got = 0;
|
|
604
|
+
if (Object.keys(fieldTypes).length) { catalog.fieldTypes = fieldTypes; got++; }
|
|
605
|
+
if (entityOptions.length) { catalog.entityOptions = entityOptions; got++; }
|
|
606
|
+
if (columnOptions.length) { catalog.columnOptions = columnOptions; got++; }
|
|
607
|
+
catalog.source = got === 3 ? "sdk" : got > 0 ? "partial-sdk" : "doc";
|
|
608
|
+
} catch { /* typings unreadable — doc fallback stands */ }
|
|
609
|
+
return catalog;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// ── public API ──
|
|
613
|
+
export function validateSchema({ files = [], rootDir = null } = {}) {
|
|
614
|
+
const ts = loadTypescript(rootDir);
|
|
615
|
+
const sdk = loadSdkCatalog(ts, rootDir);
|
|
616
|
+
const model = { entities: new Map(), entityByName: new Map(), seeds: [], modules: [] };
|
|
617
|
+
const findings = [];
|
|
618
|
+
const sources = files.map((f) =>
|
|
619
|
+
ts.createSourceFile(resolve(f), readFileSync(f, "utf-8"), ts.ScriptTarget.Latest, true),
|
|
620
|
+
);
|
|
621
|
+
for (const sf of sources) {
|
|
622
|
+
analyzeEntities(ts, sf, model);
|
|
623
|
+
analyzeSeeds(ts, sf, model);
|
|
624
|
+
analyzeModules(ts, sf, model);
|
|
625
|
+
}
|
|
626
|
+
for (const info of model.entities.values()) checkEntity(ts, info, sdk, findings);
|
|
627
|
+
for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
|
|
628
|
+
checkRegistration(ts, model, findings);
|
|
629
|
+
checkTsconfig(ts, rootDir, findings);
|
|
630
|
+
findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.col - b.col);
|
|
631
|
+
return {
|
|
632
|
+
findings,
|
|
633
|
+
errors: findings.filter((f) => f.level === "error"),
|
|
634
|
+
warnings: findings.filter((f) => f.level === "warning"),
|
|
635
|
+
sdkSource: sdk.source,
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// ── discovery ──
|
|
640
|
+
export function discoverFiles(rootDir) {
|
|
641
|
+
const files = [];
|
|
642
|
+
(function walk(dir) {
|
|
643
|
+
for (const name of readdirSync(dir)) {
|
|
644
|
+
if (name === "node_modules" || name === "dist" || name.startsWith(".")) continue;
|
|
645
|
+
const p = join(dir, name);
|
|
646
|
+
if (statSync(p).isDirectory()) {
|
|
647
|
+
walk(p);
|
|
648
|
+
} else if (name.endsWith(".entity.ts") || name.endsWith(".seed.ts")) {
|
|
649
|
+
files.push(p);
|
|
650
|
+
} else if (name.endsWith(".ts") &&
|
|
651
|
+
readFileSync(p, "utf-8").includes("EntityModule.forFeature")) {
|
|
652
|
+
files.push(p);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
})(resolve(rootDir));
|
|
656
|
+
return files.sort();
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// ── CLI ──
|
|
660
|
+
const isMain =
|
|
661
|
+
process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
|
|
662
|
+
if (isMain) {
|
|
663
|
+
const args = process.argv.slice(2);
|
|
664
|
+
if (args.length === 0) {
|
|
665
|
+
console.error("usage: node validate-suppa-schema.mjs <app-root-or-files...>");
|
|
666
|
+
process.exit(2);
|
|
667
|
+
}
|
|
668
|
+
let rootDir = null;
|
|
669
|
+
const files = [];
|
|
670
|
+
for (const a of args) {
|
|
671
|
+
const p = resolve(a);
|
|
672
|
+
if (!existsSync(p)) {
|
|
673
|
+
console.error(`validate-suppa-schema: path not found: ${a}`);
|
|
674
|
+
process.exit(2);
|
|
675
|
+
}
|
|
676
|
+
if (statSync(p).isDirectory()) {
|
|
677
|
+
rootDir = rootDir ?? p;
|
|
678
|
+
files.push(...discoverFiles(p));
|
|
679
|
+
} else {
|
|
680
|
+
files.push(p);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
const dedupedFiles = [...new Set(files)];
|
|
684
|
+
const res = validateSchema({ files: dedupedFiles, rootDir });
|
|
685
|
+
for (const f of res.findings) {
|
|
686
|
+
console.log(`${relative(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`);
|
|
687
|
+
}
|
|
688
|
+
console.log(
|
|
689
|
+
`\n${res.errors.length} error(s), ${res.warnings.length} warning(s) across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
|
|
690
|
+
);
|
|
691
|
+
process.exit(res.errors.length > 0 ? 1 : 0);
|
|
692
|
+
}
|