suppa-mcp-2 1.1.4 → 1.2.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.
@@ -0,0 +1,1063 @@
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", "relationEntityName", "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, sf) {
70
+ const e = dec.expression;
71
+ if (ts.isCallExpression(e)) {
72
+ const name = calleeIdentity(ts, sf, e.expression);
73
+ return name ? { name, args: [...e.arguments] } : null;
74
+ }
75
+ const name = calleeIdentity(ts, sf, e);
76
+ return name ? { name, args: [] } : null;
77
+ }
78
+ function objectMap(ts, node) {
79
+ const map = new Map();
80
+ if (!node || !ts.isObjectLiteralExpression(node)) return map;
81
+ for (const p of node.properties) {
82
+ if (ts.isPropertyAssignment(p)) {
83
+ const name =
84
+ ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : null;
85
+ if (name !== null) map.set(name, p.initializer);
86
+ } else if (ts.isShorthandPropertyAssignment(p)) {
87
+ map.set(p.name.text, p.name);
88
+ }
89
+ }
90
+ return map;
91
+ }
92
+ function stringValue(ts, node) {
93
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
94
+ ? node.text
95
+ : null;
96
+ }
97
+ function stringArray(ts, node) {
98
+ if (!node || !ts.isArrayLiteralExpression(node)) return null;
99
+ const out = [];
100
+ for (const el of node.elements) {
101
+ const s = stringValue(ts, el);
102
+ if (s === null) return null;
103
+ out.push(s);
104
+ }
105
+ return out;
106
+ }
107
+ function thunkTarget(ts, sf, arg) {
108
+ if (arg && ts.isArrowFunction(arg)) {
109
+ const b = arg.body;
110
+ if (ts.isIdentifier(b)) return resolveLocalName(sf, b.text);
111
+ if (ts.isPropertyAccessExpression(b)) return b.name.text;
112
+ }
113
+ return null;
114
+ }
115
+ function spreadElements(ts, node) {
116
+ if (!node || !ts.isObjectLiteralExpression(node)) return [];
117
+ return node.properties.filter((p) => ts.isSpreadAssignment(p));
118
+ }
119
+ function arraySpreadElements(ts, node) {
120
+ if (!node || !ts.isArrayLiteralExpression(node)) return [];
121
+ return node.elements.filter((e) => ts.isSpreadElement(e));
122
+ }
123
+
124
+ // ── identity: aliased named imports and '@suppa/sdk' namespace imports ──
125
+ // `import { Things as Thing }` / `import * as sdk from '@suppa/sdk'` name the
126
+ // very same declarations; matching bare identifiers alone misses them.
127
+ function analyzeImports(ts, sf) {
128
+ const alias = new Map(); // local name -> imported (exported) name
129
+ const namespaces = new Set(); // local name of `import * as X from '@suppa/sdk'`
130
+ for (const st of sf.statements) {
131
+ if (!ts.isImportDeclaration(st) || !st.importClause) continue;
132
+ const from = ts.isStringLiteral(st.moduleSpecifier) ? st.moduleSpecifier.text : "";
133
+ const bindings = st.importClause.namedBindings;
134
+ if (bindings && ts.isNamespaceImport(bindings)) {
135
+ if (from === "@suppa/sdk") namespaces.add(bindings.name.text);
136
+ } else if (bindings && ts.isNamedImports(bindings)) {
137
+ for (const el of bindings.elements) {
138
+ alias.set(el.name.text, (el.propertyName ?? el.name).text);
139
+ }
140
+ }
141
+ }
142
+ sf.suppaImports = { alias, namespaces };
143
+ }
144
+ function importsOf(sf) {
145
+ return sf.suppaImports ?? { alias: new Map(), namespaces: new Set() };
146
+ }
147
+ /** local identifier text -> the name it was imported under (or itself) */
148
+ function resolveLocalName(sf, text) {
149
+ return importsOf(sf).alias.get(text) ?? text;
150
+ }
151
+ /** node is `name`, an alias of it, or `<sdkNamespace>.name` */
152
+ function isSdkQualified(ts, sf, node, name) {
153
+ if (!node) return false;
154
+ if (ts.isIdentifier(node)) return resolveLocalName(sf, node.text) === name;
155
+ if (ts.isPropertyAccessExpression(node) && node.name.text === name &&
156
+ ts.isIdentifier(node.expression)) {
157
+ return importsOf(sf).namespaces.has(node.expression.text);
158
+ }
159
+ return false;
160
+ }
161
+ function calleeIdentity(ts, sf, expr) {
162
+ if (ts.isIdentifier(expr)) return resolveLocalName(sf, expr.text);
163
+ if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression) &&
164
+ importsOf(sf).namespaces.has(expr.expression.text)) {
165
+ return expr.name.text;
166
+ }
167
+ return null;
168
+ }
169
+
170
+ // ── string-ness of an expression (no type checker available) ──
171
+ /** provably NOT a string at runtime */
172
+ function isProvableNonString(ts, n) {
173
+ if (n.kind === ts.SyntaxKind.TrueKeyword || n.kind === ts.SyntaxKind.FalseKeyword ||
174
+ n.kind === ts.SyntaxKind.NullKeyword) return true;
175
+ if (ts.isNumericLiteral(n) || ts.isBigIntLiteral(n)) return true;
176
+ if (ts.isPrefixUnaryExpression(n) &&
177
+ (ts.isNumericLiteral(n.operand) || ts.isBigIntLiteral(n.operand))) return true;
178
+ if (ts.isArrayLiteralExpression(n) || ts.isObjectLiteralExpression(n)) return true;
179
+ if (ts.isNewExpression(n)) return true;
180
+ return false;
181
+ }
182
+ /** provably a string at runtime (literal, template, or a `+` chain with one) */
183
+ function isProvableString(ts, n) {
184
+ if (ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n) ||
185
+ ts.isTemplateExpression(n)) return true;
186
+ if (ts.isParenthesizedExpression(n)) return isProvableString(ts, n.expression);
187
+ if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.PlusToken) {
188
+ return isProvableString(ts, n.left) || isProvableString(ts, n.right);
189
+ }
190
+ return false;
191
+ }
192
+ /** strip `(x)`, `x as T`, `x!` — they do not change the runtime value */
193
+ function unwrapExpr(ts, n) {
194
+ let cur = n;
195
+ while (cur && (ts.isParenthesizedExpression(cur) || ts.isAsExpression(cur) ||
196
+ ts.isNonNullExpression(cur) || ts.isSatisfiesExpression?.(cur) === true)) {
197
+ cur = cur.expression;
198
+ }
199
+ return cur;
200
+ }
201
+ /** an expression whose value this AST-only checker cannot see */
202
+ function isOpaqueExpression(ts, n) {
203
+ return ts.isIdentifier(n) || ts.isCallExpression(n) ||
204
+ ts.isPropertyAccessExpression(n) || ts.isElementAccessExpression(n) ||
205
+ ts.isAwaitExpression(n) || ts.isConditionalExpression(n);
206
+ }
207
+
208
+ // ── extraction: entities ──
209
+ function analyzeEntities(ts, sf, model) {
210
+ sf.forEachChild(function walk(node) {
211
+ if (ts.isClassDeclaration(node)) {
212
+ const decs = decoratorsOf(ts, node).map((d) => decoratorCall(ts, d, sf)).filter(Boolean);
213
+ const entityDec = decs.find((d) => d.name === "Entity");
214
+ if (entityDec) {
215
+ const className = node.name ? node.name.text : "<anonymous>";
216
+ const options = objectMap(ts, entityDec.args[0]);
217
+ const keysNode = options.get("importKeyFields");
218
+ const info = {
219
+ className,
220
+ entityName: stringValue(ts, options.get("name")) ?? className,
221
+ sf, node, options, optionsNode: entityDec.args[0],
222
+ importKeyFields: stringArray(ts, keysNode),
223
+ // present but not a readable array of string literals: the key checks
224
+ // cannot run, but claiming it is missing would be a lie (CB-8)
225
+ importKeyFieldsUnreadable: !!keysNode && stringArray(ts, keysNode) === null,
226
+ importKeyFieldsNode: keysNode ?? null,
227
+ hasKey: options.has("key"),
228
+ properties: new Map(),
229
+ columnNames: new Set(), // literal `name` options of @Column/relations
230
+ };
231
+ for (const member of node.members) {
232
+ if (!ts.isPropertyDeclaration(member) || !member.name) continue;
233
+ const propName =
234
+ ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)
235
+ ? member.name.text
236
+ : member.name.getText(sf);
237
+ for (const d of decoratorsOf(ts, member).map((x) => decoratorCall(ts, x, sf)).filter(Boolean)) {
238
+ if (d.name === "Column") {
239
+ const columnOptions = objectMap(ts, d.args[0]);
240
+ info.properties.set(propName, {
241
+ kind: "column", node: member, decorator: d,
242
+ columnOptions, optionsNode: d.args[0],
243
+ nameNode: columnOptions.get("name") ?? null,
244
+ });
245
+ } else if (ENUM_DECORATORS.has(d.name)) {
246
+ info.properties.set(propName, {
247
+ kind: d.name === "Enum" ? "enum" : "multi-enum",
248
+ node: member, decorator: d,
249
+ enumGlobalName: stringValue(ts, d.args[0]),
250
+ });
251
+ } else if (FILE_DECORATORS.has(d.name)) {
252
+ info.properties.set(propName, {
253
+ kind: d.name === "File" ? "file" : "multi-file",
254
+ node: member, decorator: d,
255
+ });
256
+ } else if (d.name in RELATION_KIND_BY_DECORATOR) {
257
+ // (target, options?) or (target, inverse, options?) — the options
258
+ // object is whichever trailing argument is an object literal
259
+ const relOptions = objectMap(
260
+ ts, [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)),
261
+ );
262
+ info.properties.set(propName, {
263
+ kind: RELATION_KIND_BY_DECORATOR[d.name],
264
+ node: member, decorator: d,
265
+ targetClass: thunkTarget(ts, sf, d.args[0]),
266
+ nameNode: relOptions.get("name") ?? null,
267
+ });
268
+ }
269
+ }
270
+ const prop = info.properties.get(propName);
271
+ const colName = prop && stringValue(ts, prop.nameNode);
272
+ if (colName) info.columnNames.add(colName);
273
+ }
274
+ model.entities.set(className, info);
275
+ model.entityByName.set(info.entityName, info);
276
+ }
277
+ }
278
+ ts.forEachChild(node, walk);
279
+ });
280
+ }
281
+
282
+ // ── rules: tabular parts ──
283
+ /**
284
+ * Doc: "Three things make an entity a tabular part. All three are required,
285
+ * and the platform does not infer any of them: type: 'tabular-part' on
286
+ * @Entity(), relationEntityName — the name of the parent entity, and a
287
+ * @ManyToOne field named owner pointing at the parent class."
288
+ * Conversely, relationEntityName without type: 'tabular-part' is the doc's
289
+ * own mistake row: "type: 'tabular-part' or relationEntityName is missing,
290
+ * so it is listed under /related instead."
291
+ */
292
+ function checkTabularPart(ts, info, model, findings) {
293
+ const sf = info.sf;
294
+ const anchor = info.node.name ?? info.node;
295
+ const TRIAD = `"All three are required, and the platform does not infer any of them" (type: 'tabular-part', relationEntityName, and a @ManyToOne field named owner)`;
296
+
297
+ const hasType = info.options.has("type");
298
+ const typeNode = info.options.get("type");
299
+ const typeLiteral = hasType ? stringValue(ts, typeNode) : null;
300
+ const typeUnreadable = hasType && typeLiteral === null;
301
+
302
+ const hasRelName = info.options.has("relationEntityName");
303
+ const relNode = info.options.get("relationEntityName");
304
+ const relLiteral = hasRelName ? stringValue(ts, relNode) : null;
305
+ const relUnreadable = hasRelName && relLiteral === null;
306
+
307
+ // an unreadable type/relationEntityName (identifier, expression, …) means
308
+ // this checker cannot tell whether the entity is a tabular part at all —
309
+ // warn instead of guessing E108 one way or the other.
310
+ if (typeUnreadable || relUnreadable) {
311
+ const badNode = typeUnreadable ? typeNode : relNode;
312
+ const badOpt = typeUnreadable ? "type" : "relationEntityName";
313
+ findings.push(finding(ts, sf, badNode, "W606",
314
+ `cannot statically verify '${badOpt}' of '${info.className}' — it is delivered by reference or an expression this checker cannot evaluate, so the tabular-part checks (E108-E110, W607) are skipped; inline the literal to restore checking`));
315
+ return;
316
+ }
317
+
318
+ const isTabularPart = typeLiteral === "tabular-part";
319
+ // `owner` is a @ManyToOne relation named 'owner' by PROPERTY name, or one
320
+ // whose literal @ManyToOne({ name: 'owner' }) column-name option is 'owner'
321
+ // (F4) — E106 (DA-2) already accepts a column name as a field identity, so
322
+ // E108's notion of "the owner relation" must agree.
323
+ const ownerProp = [...info.properties.entries()].find(
324
+ ([propName, p]) => p.kind === "many-to-one" &&
325
+ (propName === "owner" || stringValue(ts, p.nameNode) === "owner"),
326
+ )?.[1];
327
+ const hasOwner = !!ownerProp;
328
+
329
+ // an @Entity() options spread may hide `type`/`relationEntityName` (they are
330
+ // spread properties, not readable PropertyAssignments) — the W606 already
331
+ // fired for the spread promises these doc-rule checks are skipped, so the
332
+ // two option-presence branches below must not also false-positive E108. The
333
+ // missing-`owner` branch is a class member a spread cannot deliver, so it
334
+ // stays ungated.
335
+ const optionsSpread = spreadElements(ts, info.optionsNode).length > 0;
336
+
337
+ if (isTabularPart) {
338
+ if (!hasRelName && !optionsSpread) {
339
+ findings.push(finding(ts, sf, anchor, "E108",
340
+ `tabular part '${info.className}' (type: 'tabular-part') is missing relationEntityName — ${TRIAD}`));
341
+ }
342
+ if (!hasOwner) {
343
+ findings.push(finding(ts, sf, anchor, "E108",
344
+ `tabular part '${info.className}' (type: 'tabular-part') has no @ManyToOne relation named 'owner' pointing at the parent — ${TRIAD}`));
345
+ }
346
+ } else if (hasRelName && !optionsSpread) {
347
+ findings.push(finding(ts, sf, relNode, "E108",
348
+ `entity '${info.className}' sets relationEntityName but not type: 'tabular-part' — "type: 'tabular-part' or relationEntityName is missing, so it is listed under /related instead"`));
349
+ }
350
+
351
+ if (hasRelName && hasOwner && ownerProp.targetClass) {
352
+ const target = model.entities.get(ownerProp.targetClass);
353
+ if (target && target.entityName !== relLiteral) {
354
+ findings.push(finding(ts, sf, ownerProp.node, "E109",
355
+ `tabular part '${info.className}': owner points at '${target.entityName}' but relationEntityName is '${relLiteral}' — the owner relation's target and relationEntityName must name the same parent entity`));
356
+ }
357
+ }
358
+
359
+ if (isTabularPart && hasOwner && !info.importKeyFieldsUnreadable && info.importKeyFields) {
360
+ const idx = info.importKeyFields.indexOf("owner");
361
+ if (idx === -1) {
362
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "E110",
363
+ `tabular part '${info.className}' importKeyFields ${JSON.stringify(info.importKeyFields)} does not include 'owner' — "owner is missing from importKeyFields, so the key is matched globally" ⇒ duplicate rows across different parents`));
364
+ } else if (idx !== 0) {
365
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "W607",
366
+ `tabular part '${info.className}': "Put owner first in importKeyFields" — it is at position ${idx}`));
367
+ }
368
+ }
369
+ }
370
+
371
+ // ── rules: entities ──
372
+ function checkEntity(ts, info, sdk, model, findings) {
373
+ const sf = info.sf;
374
+ const anchor = info.node.name ?? info.node;
375
+
376
+ const heritage = (info.node.heritageClauses ?? []).find(
377
+ (h) => h.token === ts.SyntaxKind.ExtendsKeyword,
378
+ );
379
+ const base = heritage?.types?.[0]?.expression;
380
+ if (!isSdkQualified(ts, sf, base, "SystemBaseEntity")) {
381
+ findings.push(finding(ts, sf, anchor, "E101",
382
+ `entity class '${info.className}' must extend SystemBaseEntity — it contributes id/createdAt/updatedAt/deletedAt/createdBy/removedBy (doc: "Every entity must extend SystemBaseEntity")`));
383
+ }
384
+
385
+ for (const [opt, valNode] of info.options) {
386
+ if (!sdk.entityOptions.includes(opt)) {
387
+ findings.push(finding(ts, sf, valNode, "E501",
388
+ `unknown @Entity() option '${opt}' — valid options: ${sdk.entityOptions.join(", ")}. If it isn't in the table, it isn't an option.`));
389
+ }
390
+ }
391
+
392
+ for (const spread of spreadElements(ts, info.optionsNode)) {
393
+ findings.push(finding(ts, sf, spread, "W606",
394
+ `@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`));
395
+ }
396
+
397
+ if (info.importKeyFieldsUnreadable) {
398
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "W606",
399
+ `cannot statically verify importKeyFields of '${info.className}' — it is delivered by reference or spread, so record-level key checks (E106, E205) are skipped; inline the array of field names to restore checking`));
400
+ } else if (info.importKeyFields) {
401
+ for (const f of info.importKeyFields) {
402
+ // a field may be named by its property name or by its @Column({ name }) (DA-2)
403
+ if (!info.properties.has(f) && !info.columnNames.has(f)) {
404
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "E106",
405
+ `importKeyFields names '${f}' but the class declares no such property or column name — seeds would have nothing to match on`));
406
+ }
407
+ }
408
+ }
409
+
410
+ if (!info.hasKey) {
411
+ findings.push(finding(ts, sf, anchor, "W602",
412
+ `entity '${info.className}' has no 'key' option — a rename will be treated as drop-and-create instead of a rename (doc TIP)`));
413
+ }
414
+
415
+ checkTabularPart(ts, info, model, findings);
416
+
417
+ for (const [propName, prop] of info.properties) {
418
+ if (SYSTEM_COLUMNS.includes(propName)) {
419
+ findings.push(finding(ts, sf, prop.node, "E102",
420
+ `system column '${propName}' is provided by SystemBaseEntity — "you never declare them yourself"`));
421
+ }
422
+ // the table-level conflict is on the COLUMN name, which `name` overrides
423
+ const colName = stringValue(ts, prop.nameNode);
424
+ if (colName && SYSTEM_COLUMNS.includes(colName)) {
425
+ findings.push(finding(ts, sf, prop.nameNode, "E102",
426
+ `column name '${colName}' on property '${propName}' collides with the system column of the same name provided by SystemBaseEntity — "you never declare them yourself"`));
427
+ }
428
+ if (prop.kind === "column") checkColumn(ts, sf, prop, sdk, findings);
429
+ if (prop.kind in { "many-to-one": 1, "many-to-many": 1, "many-to-many-backref": 1, "one-to-many": 1 } &&
430
+ prop.targetClass === null) {
431
+ findings.push(finding(ts, sf, prop.node, "E105",
432
+ `relation '${propName}' must receive a thunk returning the target class — write @${prop.decorator.name}(() => Target); a direct class reference breaks circular imports`));
433
+ }
434
+ }
435
+ }
436
+
437
+ function checkColumn(ts, sf, prop, sdk, findings) {
438
+ const opts = prop.columnOptions;
439
+ for (const [opt, valNode] of opts) {
440
+ if (!sdk.columnOptions.includes(opt)) {
441
+ findings.push(finding(ts, sf, valNode, "E502",
442
+ `unknown @Column() option '${opt}' — valid options: ${sdk.columnOptions.join(", ")}. If it isn't in the table, it isn't an option.`));
443
+ }
444
+ }
445
+
446
+ for (const spread of spreadElements(ts, prop.optionsNode)) {
447
+ findings.push(finding(ts, sf, spread, "W606",
448
+ `@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`));
449
+ }
450
+
451
+ let typeValue = null; // canonical string value, e.g. "text"
452
+ const typeNode = opts.get("type");
453
+ if (typeNode) {
454
+ if (ts.isPropertyAccessExpression(typeNode) &&
455
+ ts.isIdentifier(typeNode.expression) &&
456
+ typeNode.expression.text === "FieldTypeEnum") {
457
+ const member = typeNode.name.text;
458
+ typeValue = sdk.fieldTypes[member] ?? null;
459
+ if (typeValue === null) {
460
+ findings.push(finding(ts, sf, typeNode, "E107",
461
+ `FieldTypeEnum.${member} is not a known member — valid: ${Object.keys(sdk.fieldTypes).join(", ")}`));
462
+ }
463
+ } else {
464
+ const raw = stringValue(ts, typeNode);
465
+ if (raw !== null) {
466
+ if (NON_SCALAR_TYPE_STRINGS.has(raw)) {
467
+ findings.push(finding(ts, sf, typeNode, "E104",
468
+ `@Column type '${raw}' — relations, enums and files are declared with their own decorators (@ManyToOne/@Enum/@File/…) "and never with @Column({ type: ... })"`));
469
+ } else {
470
+ const member = Object.keys(sdk.fieldTypes).find((k) => sdk.fieldTypes[k] === raw);
471
+ if (member) {
472
+ typeValue = raw;
473
+ findings.push(finding(ts, sf, typeNode, "W601",
474
+ `raw string type '${raw}' — use FieldTypeEnum.${member} so a typo fails in the editor instead of at migration time`));
475
+ } else {
476
+ findings.push(finding(ts, sf, typeNode, "E107",
477
+ `unknown column type '${raw}' — "a misspelled one ('txet') compiles too and only fails when the migration runs"`));
478
+ }
479
+ }
480
+ }
481
+ }
482
+ }
483
+
484
+ const def = opts.get("default");
485
+ if (def) {
486
+ const val = unwrapExpr(ts, def);
487
+ if (isProvableNonString(ts, val)) {
488
+ findings.push(finding(ts, sf, def, "E103",
489
+ `'default' must be a SQL expression STRING — "Write default: 'false', not default: false, and default: \\"'draft'\\" for a string literal"`));
490
+ } else if (!isProvableString(ts, val)) {
491
+ findings.push(finding(ts, sf, def, "W606",
492
+ `cannot statically verify that 'default' is a SQL expression string — it is delivered by reference or by an expression this checker cannot evaluate, so the check is skipped; inline a literal SQL string to restore checking`));
493
+ }
494
+ }
495
+ if (opts.has("length") && typeValue !== null && typeValue !== "text") {
496
+ findings.push(finding(ts, sf, opts.get("length"), "W603",
497
+ `'length' caps Text columns; this column is '${typeValue}'`));
498
+ }
499
+ if (opts.has("decimalPlaces") && typeValue !== null && typeValue !== "numeric") {
500
+ findings.push(finding(ts, sf, opts.get("decimalPlaces"), "W604",
501
+ `'decimalPlaces' pairs with Numeric columns; this column is '${typeValue}'`));
502
+ }
503
+ }
504
+
505
+ // ── extraction: string enums (createSeed(EnumName.Member) resolution) ──
506
+ function analyzeEnums(ts, sf, model) {
507
+ sf.forEachChild(function walk(node) {
508
+ if (ts.isEnumDeclaration(node)) {
509
+ const members = new Map();
510
+ for (const m of node.members) {
511
+ const name = ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)
512
+ ? m.name.text : m.name.getText(sf);
513
+ const value = stringValue(ts, m.initializer);
514
+ if (value !== null) members.set(name, value);
515
+ }
516
+ if (members.size) model.stringEnums.set(node.name.text, members);
517
+ }
518
+ ts.forEachChild(node, walk);
519
+ });
520
+ }
521
+
522
+ // ── extraction: seeds ──
523
+ function analyzeSeeds(ts, sf, model) {
524
+ sf.forEachChild(function walk(node) {
525
+ if (ts.isVariableStatement(node)) {
526
+ for (const decl of node.declarationList.declarations) {
527
+ const init = decl.initializer;
528
+ if (init && ts.isCallExpression(init) &&
529
+ isSdkQualified(ts, sf, init.expression, "createSeed")) {
530
+ const exportName = ts.isIdentifier(decl.name) ? decl.name.text : decl.name.getText(sf);
531
+ const arg0 = init.arguments[0];
532
+ let entityName = stringValue(ts, arg0);
533
+ let enumRef = null;
534
+ if (entityName === null && arg0 && ts.isPropertyAccessExpression(arg0) &&
535
+ ts.isIdentifier(arg0.expression)) {
536
+ // EntityNamesEnum.Workflows — the VALUE is what createSeed receives;
537
+ // the member name is only a fallback (resolved after every file is read)
538
+ enumRef = { enumName: arg0.expression.text, member: arg0.name.text };
539
+ }
540
+ const arg1 = init.arguments[1];
541
+ let records = null; // null = thin seed (imported payload) — record checks impossible
542
+ if (arg1 && ts.isArrayLiteralExpression(arg1)) {
543
+ records = arg1.elements.map((e) =>
544
+ ts.isObjectLiteralExpression(e)
545
+ ? { node: e, map: objectMap(ts, e), hasSpread: spreadElements(ts, e).length > 0, spreads: spreadElements(ts, e), byRef: false }
546
+ : { node: e, map: new Map(), hasSpread: false, spreads: [], byRef: true },
547
+ );
548
+ }
549
+ model.seeds.push({ exportName, entityName, enumRef, sf, node: init, records });
550
+ }
551
+ }
552
+ }
553
+ ts.forEachChild(node, walk);
554
+ });
555
+ }
556
+
557
+ // ── rules: seeds ──
558
+ /**
559
+ * `{ name: '<global enum name>', value: '<enum value>' }`. Extra keys are legal
560
+ * (the doc gives the shape, it never forbids more). A reference or a spread is
561
+ * unverifiable — warn instead of hard-erroring on code that may well be correct.
562
+ */
563
+ function checkEnumRef(ts, sf, key, valNode, prop, findings) {
564
+ const root = unwrapExpr(ts, valNode);
565
+ if (root.kind === ts.SyntaxKind.NullKeyword) return;
566
+ const multi = prop.kind === "multi-enum";
567
+ const shapeHint = multi ? " — an array of those for @MultiEnum" : "";
568
+ const unverifiable = () => findings.push(finding(ts, sf, valNode, "W606",
569
+ `cannot statically verify enum reference '${key}' — it is delivered by reference or spread, so the shape check (E206) is skipped; inline { name, value } to restore checking`));
570
+ const wrongShape = (n) => findings.push(finding(ts, sf, n, "E206",
571
+ `enum reference '${key}' must be { name: '<global enum name>', value: '<enum value>' }${shapeHint}`));
572
+
573
+ let refs;
574
+ if (multi) {
575
+ if (!ts.isArrayLiteralExpression(root)) {
576
+ if (isOpaqueExpression(ts, root)) return unverifiable();
577
+ return wrongShape(valNode);
578
+ }
579
+ if (arraySpreadElements(ts, root).length > 0) return unverifiable();
580
+ refs = root.elements.map((e) => unwrapExpr(ts, e));
581
+ } else {
582
+ refs = [root];
583
+ }
584
+
585
+ for (const ref of refs) {
586
+ if (!ts.isObjectLiteralExpression(ref)) {
587
+ if (isOpaqueExpression(ts, ref)) { unverifiable(); continue; }
588
+ wrongShape(ref);
589
+ continue;
590
+ }
591
+ if (spreadElements(ts, ref).length > 0) { unverifiable(); continue; }
592
+ const m = objectMap(ts, ref);
593
+ if (!m.has("name") || !m.has("value")) { wrongShape(ref); continue; }
594
+ const given = stringValue(ts, m.get("name"));
595
+ if (prop.enumGlobalName && given !== null && given !== prop.enumGlobalName) {
596
+ findings.push(finding(ts, sf, m.get("name"), "E206",
597
+ `enum reference '${key}' names global enum '${given}', but the property is declared as @${multi ? "MultiEnum" : "Enum"}('${prop.enumGlobalName}') — the names must match`));
598
+ }
599
+ }
600
+ }
601
+
602
+ function checkSeed(ts, seed, model, findings) {
603
+ const sf = seed.sf;
604
+ const entity = seed.entityName ? model.entityByName.get(seed.entityName) : undefined;
605
+ if (!entity) {
606
+ // platform entity, a typo, or simply a file outside the analyzed set — say so
607
+ findings.push(finding(ts, sf, seed.node, "W606",
608
+ `target entity '${seed.entityName ?? "<unresolved>"}' of seed '${seed.exportName}' is not among the analyzed entities — record-level checks (E203-E206, W605) are skipped for it`));
609
+ } else if (!entity.importKeyFieldsUnreadable &&
610
+ (!entity.importKeyFields || entity.importKeyFields.length === 0)) {
611
+ findings.push(finding(ts, sf, seed.node, "W605",
612
+ `entity '${seed.entityName}' has a seed but no importKeyFields — "seeds have nothing to match on and cannot stay idempotent"`));
613
+ }
614
+ if (!seed.records) return;
615
+ for (const rec of seed.records) {
616
+ if (rec.byRef) {
617
+ findings.push(finding(ts, sf, rec.node, "W606",
618
+ `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`));
619
+ continue;
620
+ }
621
+ for (const [key, valNode] of rec.map) {
622
+ if (SYSTEM_COLUMNS.includes(key)) {
623
+ findings.push(finding(ts, sf, valNode, "E201",
624
+ `seed record contains system column '${key}' — "they differ per tenant and corrupt matching"`));
625
+ }
626
+ if (ACCESS_METADATA_KEYS.includes(key)) {
627
+ findings.push(finding(ts, sf, valNode, "E202",
628
+ `seed record contains '${key}' — "access metadata, not data"`));
629
+ }
630
+ const prop = entity?.properties.get(key);
631
+ if (!prop) continue;
632
+ if (prop.kind === "many-to-one" || prop.kind === "many-to-many") {
633
+ const isNum = (n) =>
634
+ ts.isNumericLiteral(n) ||
635
+ (ts.isPrefixUnaryExpression(n) && ts.isNumericLiteral(n.operand));
636
+ const bad = isNum(valNode) ||
637
+ (ts.isArrayLiteralExpression(valNode) && valNode.elements.some(isNum));
638
+ if (bad) {
639
+ findings.push(finding(ts, sf, valNode, "E203",
640
+ `relation '${key}' referenced by numeric id — ids "do not match across tenants"; reference through the target's importKeyFields, e.g. { name: 'Default' }`));
641
+ }
642
+ }
643
+ if (prop.kind === "one-to-many" || prop.kind === "many-to-many-backref") {
644
+ findings.push(finding(ts, sf, valNode, "E204",
645
+ `reverse relation field '${key}' (@${prop.decorator.name}) in a seed (even as []) — "back references cannot be inserted; the import throws". Seed the owning entity with its own seed.`));
646
+ }
647
+ if (prop.kind === "enum" || prop.kind === "multi-enum") {
648
+ checkEnumRef(ts, sf, key, valNode, prop, findings);
649
+ }
650
+ }
651
+ for (const spread of rec.spreads ?? []) {
652
+ findings.push(finding(ts, sf, spread, "W606",
653
+ `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`));
654
+ }
655
+ if (rec.hasSpread) continue; // spread may deliver the import key — E205 would false-positive
656
+ if (!entity) continue;
657
+
658
+ // $key overrides identity per record — but only if it can establish one
659
+ if (rec.map.has("$key")) {
660
+ const keyNode = rec.map.get("$key");
661
+ const keyValue = unwrapExpr(ts, keyNode);
662
+ if (ts.isObjectLiteralExpression(keyValue)) {
663
+ if (keyValue.properties.length === 0) {
664
+ findings.push(finding(ts, sf, keyNode, "E205",
665
+ `seed record's $key is an empty object — it cannot establish identity for '${seed.entityName}' ⇒ duplicate rows after every restart. Give $key the fields that identify the record.`));
666
+ }
667
+ } else if (isOpaqueExpression(ts, keyValue)) {
668
+ findings.push(finding(ts, sf, keyNode, "W606",
669
+ `cannot statically verify the $key of this '${seed.entityName}' record — it is delivered by reference, so the identity check (E205) is skipped; inline the $key object to restore checking`));
670
+ } else {
671
+ findings.push(finding(ts, sf, keyNode, "E205",
672
+ `seed record's $key must be an object of identifying fields, e.g. $key: { name: 'Default' } — this value cannot establish identity for '${seed.entityName}' ⇒ duplicate rows after every restart.`));
673
+ }
674
+ continue;
675
+ }
676
+
677
+ if (entity.importKeyFields?.length) {
678
+ for (const f of entity.importKeyFields) {
679
+ if (!rec.map.has(f)) {
680
+ findings.push(finding(ts, sf, rec.node, "E205",
681
+ `seed record is missing importKeyField '${f}' of '${seed.entityName}' — nothing matches ⇒ duplicate rows after every restart. Provide it or override identity with $key.`));
682
+ }
683
+ }
684
+ }
685
+ }
686
+ }
687
+
688
+ // ── extraction: EntityModule.forFeature ──
689
+ /**
690
+ * Doc resolution order: "If the entities array is passed AND NOT EMPTY it is
691
+ * used and entitiesPath is ignored; otherwise entities are loaded from
692
+ * entitiesPath" — same for seeds/seedsPath. The two sides are independent, so
693
+ * each gets its own mode: "explicit" | "autoload" | "unverifiable".
694
+ */
695
+ function analyzeModules(ts, sf, model) {
696
+ sf.forEachChild(function walk(node) {
697
+ if (ts.isCallExpression(node) &&
698
+ ts.isPropertyAccessExpression(node.expression) &&
699
+ node.expression.name.text === "forFeature" &&
700
+ isSdkQualified(ts, sf, node.expression.expression, "EntityModule")) {
701
+ const a0 = node.arguments[0] ? unwrapExpr(ts, node.arguments[0]) : undefined;
702
+ const a0IsArray = a0 && ts.isArrayLiteralExpression(a0);
703
+ const a0IsOptions = a0 && ts.isObjectLiteralExpression(a0);
704
+ // options live in argument 1 next to an entities array, or ARE argument 0
705
+ const optionsNode = a0IsOptions ? a0 : node.arguments[1];
706
+ const opts = objectMap(ts, optionsNode);
707
+
708
+ const side = (label, arrayNode, pathNode, unreadableNode) => {
709
+ const s = {
710
+ label, mode: "autoload", names: [], spreads: [],
711
+ node, refNode: null, paths: null, pathNode: pathNode ?? null,
712
+ };
713
+ if (unreadableNode) {
714
+ s.mode = "unverifiable";
715
+ s.refNode = unreadableNode;
716
+ return s;
717
+ }
718
+ if (arrayNode && arrayNode.elements.length > 0) {
719
+ s.mode = "explicit";
720
+ s.node = arrayNode;
721
+ s.names = arrayNode.elements
722
+ .filter((e) => ts.isIdentifier(e))
723
+ .map((e) => resolveLocalName(sf, e.text)); // aliases resolve to the exported name
724
+ s.spreads = arraySpreadElements(ts, arrayNode);
725
+ return s;
726
+ }
727
+ // absent or empty array -> the path decides; read it when it is readable
728
+ if (pathNode) {
729
+ const single = stringValue(ts, pathNode);
730
+ s.paths = single !== null ? [single] : stringArray(ts, pathNode);
731
+ }
732
+ return s;
733
+ };
734
+
735
+ const seedsNode = opts.get("seeds") ? unwrapExpr(ts, opts.get("seeds")) : undefined;
736
+ const m = {
737
+ sf, node,
738
+ entities: side(
739
+ "entitiesPath",
740
+ a0IsArray ? a0 : null,
741
+ opts.get("entitiesPath"),
742
+ a0 && !a0IsArray && !a0IsOptions ? a0 : null,
743
+ ),
744
+ seeds: side(
745
+ "seedsPath",
746
+ seedsNode && ts.isArrayLiteralExpression(seedsNode) ? seedsNode : null,
747
+ opts.get("seedsPath"),
748
+ seedsNode && !ts.isArrayLiteralExpression(seedsNode) ? seedsNode
749
+ : (a0 && !a0IsArray && !a0IsOptions && !optionsNode ? a0 : null),
750
+ ),
751
+ };
752
+ model.modules.push(m);
753
+ }
754
+ ts.forEachChild(node, walk);
755
+ });
756
+ }
757
+
758
+ // ── rules: registration ──
759
+ function checkRegistration(ts, model, findings) {
760
+ // E303/W606 on autoload paths — only for the side that actually autoloads:
761
+ // a path the resolution order ignores is dead config, not a mistake.
762
+ for (const m of model.modules) {
763
+ for (const side of [m.entities, m.seeds]) {
764
+ if (side.mode !== "autoload" || !side.pathNode) continue;
765
+ if (side.paths === null) {
766
+ findings.push(finding(ts, m.sf, side.pathNode, "W606",
767
+ `cannot statically verify ${side.label} — it is delivered by reference or by an expression this checker cannot evaluate, so the dist/-vs-src/ check (E303) is skipped; inline the path string to restore checking`));
768
+ continue;
769
+ }
770
+ for (const p of side.paths) {
771
+ if (/(^|\/)src(\/|$)/.test(p.replace(/\\/g, "/"))) {
772
+ findings.push(finding(ts, m.sf, side.pathNode, "E303",
773
+ `${side.label} '${p}' points at src/ — autoloading reads compiled output: "entitiesPath / seedsPath points at src/ instead of compiled dist/"`));
774
+ }
775
+ }
776
+ }
777
+ }
778
+
779
+ if (model.entities.size > 0 && model.modules.length === 0) {
780
+ const first = [...model.entities.values()][0];
781
+ findings.push(finding(ts, first.sf, first.node.name ?? first.node, "E305",
782
+ `no EntityModule.forFeature() found — "An entity class that is never passed to forFeature() is invisible — no table is created for it"`));
783
+ return;
784
+ }
785
+
786
+ for (const m of model.modules) {
787
+ for (const spread of m.entities.spreads) {
788
+ findings.push(finding(ts, m.sf, spread, "W606",
789
+ `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`));
790
+ }
791
+ for (const spread of m.seeds.spreads) {
792
+ findings.push(finding(ts, m.sf, spread, "W606",
793
+ `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`));
794
+ }
795
+ if (m.entities.mode === "unverifiable") {
796
+ findings.push(finding(ts, m.sf, m.entities.refNode, "W606",
797
+ `EntityModule.forFeature() entities are delivered by reference — membership cannot be statically verified: E301 (unregistered entity) is skipped; inline the array to restore checking`));
798
+ }
799
+ if (m.seeds.mode === "unverifiable" && m.seeds.refNode !== m.entities.refNode) {
800
+ findings.push(finding(ts, m.sf, m.seeds.refNode, "W606",
801
+ `EntityModule.forFeature() seeds are delivered by reference — membership and ordering cannot be statically verified: E302 (unregistered seed) and E304 (seed ordering) are skipped; inline the array to restore checking`));
802
+ }
803
+ }
804
+
805
+ // an autoload (or unverifiable) module anywhere may cover any entity/seed not
806
+ // named explicitly — membership becomes the platform's job, so E301/E302 would
807
+ // only false-positive.
808
+ const entitiesUnknown = model.modules.some((m) => m.entities.mode !== "explicit" || m.entities.spreads.length > 0);
809
+ const seedsUnknown = model.modules.some((m) => m.seeds.mode !== "explicit" || m.seeds.spreads.length > 0);
810
+
811
+ if (!entitiesUnknown) {
812
+ const registeredEntities = new Set(model.modules.flatMap((m) => m.entities.names));
813
+ for (const [className, info] of model.entities) {
814
+ if (!registeredEntities.has(className)) {
815
+ findings.push(finding(ts, info.sf, info.node.name ?? info.node, "E301",
816
+ `entity class '${className}' is not in any forFeature() entities array — no table will be created for it`));
817
+ }
818
+ }
819
+ }
820
+ if (!seedsUnknown) {
821
+ const registeredSeeds = new Set(model.modules.flatMap((m) => m.seeds.names));
822
+ for (const seed of model.seeds) {
823
+ if (!registeredSeeds.has(seed.exportName)) {
824
+ findings.push(finding(ts, seed.sf, seed.node, "E302",
825
+ `seed '${seed.exportName}' is not in any forFeature() seeds array — it will never run`));
826
+ }
827
+ }
828
+ }
829
+
830
+ for (const m of model.modules) {
831
+ if (m.seeds.mode !== "explicit" || m.seeds.spreads.length > 0) continue;
832
+ const order = new Map(m.seeds.names.map((n, i) => [n, i]));
833
+ const reported = new Set();
834
+ for (const seed of model.seeds) {
835
+ if (!order.has(seed.exportName) || !seed.records) continue;
836
+ const entity = seed.entityName ? model.entityByName.get(seed.entityName) : undefined;
837
+ if (!entity) continue;
838
+ const myIdx = order.get(seed.exportName);
839
+ for (const rec of seed.records) {
840
+ for (const [key] of rec.map) {
841
+ const prop = entity.properties.get(key);
842
+ if (!prop || (prop.kind !== "many-to-one" && prop.kind !== "many-to-many") || !prop.targetClass) continue;
843
+ const target = model.entities.get(prop.targetClass);
844
+ if (!target || target === entity) continue;
845
+ // an entity may have several seeds — what matters is the EARLIEST
846
+ // registered one, since it is the one that creates the rows first
847
+ const candidates = model.seeds.filter(
848
+ (s) => s.entityName === target.entityName && order.has(s.exportName),
849
+ );
850
+ if (candidates.length === 0) continue;
851
+ const earliest = candidates.reduce((a, b) =>
852
+ order.get(a.exportName) <= order.get(b.exportName) ? a : b);
853
+ const dedupe = `${seed.exportName}->${target.entityName}`;
854
+ if (order.get(earliest.exportName) > myIdx && !reported.has(dedupe)) {
855
+ reported.add(dedupe);
856
+ findings.push(finding(ts, m.sf, m.seeds.node, "E304",
857
+ `seed '${seed.exportName}' references '${target.entityName}' but '${earliest.exportName}' runs after it — "Register a seed after the seed that creates the records it points at"`));
858
+ }
859
+ }
860
+ }
861
+ }
862
+ }
863
+ }
864
+
865
+ // ── rules: tsconfig ──
866
+ function checkTsconfig(ts, rootDir, findings) {
867
+ if (!rootDir) return;
868
+ // ts.readConfigFile compares the path it is given against its own normalized
869
+ // form while attaching a syntax diagnostic — a Windows path throws a Debug
870
+ // Failure there, so normalize, and never let this check kill the run.
871
+ try {
872
+ const root = resolve(rootDir).replace(/\\/g, "/");
873
+ const p = `${root}/tsconfig.json`;
874
+ if (!existsSync(p)) {
875
+ findings.push({
876
+ file: root, line: 1, col: 1, code: "W608", level: "warning",
877
+ message: `no tsconfig.json at ${root} — cannot verify experimentalDecorators/emitDecoratorMetadata, both of which entities rely on`,
878
+ });
879
+ return;
880
+ }
881
+ const read = ts.readConfigFile(p, (f) => readFileSync(f, "utf-8"));
882
+ if (read.error) return;
883
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, root);
884
+ const missing = [];
885
+ if (!parsed.options.experimentalDecorators) missing.push("experimentalDecorators");
886
+ if (!parsed.options.emitDecoratorMetadata) missing.push("emitDecoratorMetadata");
887
+ if (missing.length) {
888
+ findings.push({
889
+ file: p, line: 1, col: 1, code: "E401", level: "error",
890
+ message: `tsconfig.json must enable ${missing.join(" and ")} — entities rely on decorator metadata`,
891
+ });
892
+ }
893
+ } catch {
894
+ /* unreadable/malformed tsconfig — degrade silently rather than crash the run */
895
+ }
896
+ }
897
+
898
+ // ── SDK catalog: real @suppa/sdk typings when resolvable, doc list otherwise ──
899
+ function loadSdkCatalog(ts, rootDir) {
900
+ const catalog = {
901
+ entityOptions: [...DOC_ENTITY_OPTIONS],
902
+ columnOptions: [...DOC_COLUMN_OPTIONS],
903
+ fieldTypes: { ...DOC_FIELD_TYPES },
904
+ source: "doc",
905
+ };
906
+ if (!rootDir) return catalog;
907
+ let dir = resolve(rootDir);
908
+ let sdkDir = null;
909
+ for (let i = 0; i < 8; i++) {
910
+ const cand = join(dir, "node_modules", "@suppa", "sdk");
911
+ if (existsSync(cand)) { sdkDir = cand; break; }
912
+ const parent = dirname(dir);
913
+ if (parent === dir) break;
914
+ dir = parent;
915
+ }
916
+ if (!sdkDir) return catalog;
917
+ let typesPath = join(sdkDir, "index.d.ts");
918
+ try {
919
+ const pkg = JSON.parse(readFileSync(join(sdkDir, "package.json"), "utf-8"));
920
+ if (pkg.types || pkg.typings) typesPath = join(sdkDir, pkg.types ?? pkg.typings);
921
+ } catch { /* fall back to index.d.ts */ }
922
+ if (!existsSync(typesPath)) return catalog;
923
+ try {
924
+ const sf = ts.createSourceFile(typesPath, readFileSync(typesPath, "utf-8"), ts.ScriptTarget.Latest, true);
925
+ const fieldTypes = {};
926
+ let entityOptions = [];
927
+ let columnOptions = [];
928
+ sf.forEachChild(function walk(node) {
929
+ if (ts.isEnumDeclaration(node) && node.name.text === "FieldTypeEnum") {
930
+ for (const m of node.members) {
931
+ const name = ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)
932
+ ? m.name.text : m.name.getText(sf);
933
+ fieldTypes[name] = m.initializer && ts.isStringLiteral(m.initializer)
934
+ ? m.initializer.text : name;
935
+ }
936
+ }
937
+ if (ts.isInterfaceDeclaration(node)) {
938
+ const props = node.members
939
+ .filter((mm) => ts.isPropertySignature(mm) && mm.name)
940
+ .map((mm) => mm.name.getText(sf).replace(/['"]/g, ""));
941
+ if (/EntityOptions$/i.test(node.name.text)) entityOptions = props;
942
+ if (/ColumnOptions$/i.test(node.name.text)) columnOptions = props;
943
+ }
944
+ ts.forEachChild(node, walk);
945
+ });
946
+ let got = 0;
947
+ // fieldTypes are enum VALUES, not option names — an older SDK enum member
948
+ // set is the true, current set for this install, so replace outright.
949
+ // entityOptions/columnOptions are OPTION NAMES: an SDK whose typings
950
+ // predate a doc-documented option (e.g. relationEntityName) must not make
951
+ // that option look unknown (E501) — union with the doc list instead of
952
+ // replacing it (F1).
953
+ if (Object.keys(fieldTypes).length) { catalog.fieldTypes = fieldTypes; got++; }
954
+ if (entityOptions.length) {
955
+ catalog.entityOptions = [...new Set([...entityOptions, ...DOC_ENTITY_OPTIONS])];
956
+ got++;
957
+ }
958
+ if (columnOptions.length) {
959
+ catalog.columnOptions = [...new Set([...columnOptions, ...DOC_COLUMN_OPTIONS])];
960
+ got++;
961
+ }
962
+ catalog.source = got === 3 ? "sdk" : got > 0 ? "partial-sdk" : "doc";
963
+ } catch { /* typings unreadable — doc fallback stands */ }
964
+ return catalog;
965
+ }
966
+
967
+ // ── public API ──
968
+ export function validateSchema({ files = [], rootDir = null } = {}) {
969
+ const ts = loadTypescript(rootDir);
970
+ const sdk = loadSdkCatalog(ts, rootDir);
971
+ const model = {
972
+ entities: new Map(), entityByName: new Map(),
973
+ seeds: [], modules: [], stringEnums: new Map(),
974
+ };
975
+ const findings = [];
976
+ // the CLI deduped; the exported API did not, and duplicated seeds duplicated findings
977
+ const uniqueFiles = [...new Set(files.map((f) => resolve(f)))];
978
+ const sources = uniqueFiles.map((f) =>
979
+ ts.createSourceFile(f, readFileSync(f, "utf-8"), ts.ScriptTarget.Latest, true),
980
+ );
981
+ for (const sf of sources) analyzeImports(ts, sf);
982
+ for (const sf of sources) analyzeEnums(ts, sf, model);
983
+ for (const sf of sources) {
984
+ analyzeEntities(ts, sf, model);
985
+ analyzeSeeds(ts, sf, model);
986
+ analyzeModules(ts, sf, model);
987
+ }
988
+ // createSeed(EnumName.Member) passes the member's VALUE; the member name is
989
+ // only a fallback for enums declared outside the analyzed file set
990
+ for (const seed of model.seeds) {
991
+ if (seed.entityName === null && seed.enumRef) {
992
+ seed.entityName =
993
+ model.stringEnums.get(seed.enumRef.enumName)?.get(seed.enumRef.member) ??
994
+ seed.enumRef.member;
995
+ }
996
+ }
997
+ for (const info of model.entities.values()) checkEntity(ts, info, sdk, model, findings);
998
+ for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
999
+ checkRegistration(ts, model, findings);
1000
+ checkTsconfig(ts, rootDir, findings);
1001
+ findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.col - b.col);
1002
+ return {
1003
+ findings,
1004
+ errors: findings.filter((f) => f.level === "error"),
1005
+ warnings: findings.filter((f) => f.level === "warning"),
1006
+ sdkSource: sdk.source,
1007
+ };
1008
+ }
1009
+
1010
+ // ── discovery ──
1011
+ export function discoverFiles(rootDir) {
1012
+ const files = [];
1013
+ (function walk(dir) {
1014
+ for (const name of readdirSync(dir)) {
1015
+ if (name === "node_modules" || name === "dist" || name.startsWith(".")) continue;
1016
+ const p = join(dir, name);
1017
+ if (statSync(p).isDirectory()) {
1018
+ walk(p);
1019
+ } else if (name.endsWith(".entity.ts") || name.endsWith(".seed.ts")) {
1020
+ files.push(p);
1021
+ } else if (name.endsWith(".ts") &&
1022
+ readFileSync(p, "utf-8").includes("EntityModule.forFeature")) {
1023
+ files.push(p);
1024
+ }
1025
+ }
1026
+ })(resolve(rootDir));
1027
+ return files.sort();
1028
+ }
1029
+
1030
+ // ── CLI ──
1031
+ const isMain =
1032
+ process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
1033
+ if (isMain) {
1034
+ const args = process.argv.slice(2);
1035
+ if (args.length === 0) {
1036
+ console.error("usage: node validate-suppa-schema.mjs <app-root-or-files...>");
1037
+ process.exit(2);
1038
+ }
1039
+ let rootDir = null;
1040
+ const files = [];
1041
+ for (const a of args) {
1042
+ const p = resolve(a);
1043
+ if (!existsSync(p)) {
1044
+ console.error(`validate-suppa-schema: path not found: ${a}`);
1045
+ process.exit(2);
1046
+ }
1047
+ if (statSync(p).isDirectory()) {
1048
+ rootDir = rootDir ?? p;
1049
+ files.push(...discoverFiles(p));
1050
+ } else {
1051
+ files.push(p);
1052
+ }
1053
+ }
1054
+ const dedupedFiles = [...new Set(files)];
1055
+ const res = validateSchema({ files: dedupedFiles, rootDir });
1056
+ for (const f of res.findings) {
1057
+ console.log(`${relative(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`);
1058
+ }
1059
+ console.log(
1060
+ `\n${res.errors.length} error(s), ${res.warnings.length} warning(s) across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
1061
+ );
1062
+ process.exit(res.errors.length > 0 ? 1 : 0);
1063
+ }