suppa-mcp-2 1.4.1 → 1.5.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.
@@ -1,1550 +1,1626 @@
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, isAbsolute, 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
- /**
23
- * Field options the platform already applies. Writing one of these with its
24
- * default value adds noise to every field and says nothing — only a DEPARTURE
25
- * from the default is worth declaring. (W612.)
26
- */
27
- export const DEFAULT_FIELD_OPTIONS = {
28
- canGroup: true,
29
- canSort: true,
30
- showInTable: true,
31
- editFromTable: true,
32
- canFilter: true,
33
- readOnly: false,
34
- searchable: false,
35
- };
36
- export const DOC_COLUMN_OPTIONS = ["type", "subType", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask",
37
- // Field options. The decorator tables do not list them, but migrations.txt:218
38
- // names them as options a column carries — encryption "makes the searchable,
39
- // canFilter, canSort and canGroup options become false" — and the builder's
40
- // Field Options table (api-entity-builder-builder.txt:66-73) gives all seven.
41
- // Without these the validator hard-errored (E502) on a legitimate
42
- // `searchable: true`. A repo's own SDK typings still override this fallback.
43
- ...Object.keys(DEFAULT_FIELD_OPTIONS)];
44
- /**
45
- * The doc's subType matrix — "it means three unrelated things depending on the
46
- * base type". Keyed by the CANONICAL FieldTypeEnum value, so E112 can be decided
47
- * from whatever `checkColumn` resolved `type` to. The Enum/MultiEnum row of that
48
- * matrix is deliberately absent: `subType` there is the enum's global name, set
49
- * by @Enum()/@MultiEnum() and never written by hand — that is E113, not E112.
50
- */
51
- export const DOC_SUBTYPES_BY_TYPE = {
52
- timestamp: ["date", "time", "timestamp"],
53
- text: ["encrypted"],
54
- };
55
- export const DOC_FIELD_TYPES = {
56
- Text: "text", Numeric: "numeric", Integer: "integer", Serial: "serial",
57
- Boolean: "boolean", Timestamp: "timestamp", JSON: "json", UUID: "uuid",
58
- MultiLang: "multi-language", Bytea: "bytea", TsVector: "tsvector",
59
- MultiType: "multi-type", Icon: "icon",
60
- };
61
- const NON_SCALAR_TYPE_STRINGS = new Set([
62
- "enum", "multi-enum", "file", "multi-file",
63
- "many-to-one", "one-to-many", "many-to-many", "many-to-many-backref",
64
- "relation", "attachment",
65
- ]);
66
- const RELATION_KIND_BY_DECORATOR = {
67
- ManyToOne: "many-to-one", ManyToMany: "many-to-many",
68
- ManyToManyBackRef: "many-to-many-backref", OneToMany: "one-to-many",
69
- };
70
- const RELATION_KINDS = new Set(Object.values(RELATION_KIND_BY_DECORATOR));
71
- // `inverse` is REQUIRED on these two (the reverse sides) and OPTIONAL — usually
72
- // omitted — on @ManyToOne/@ManyToMany; W609 only ever fires on the latter pair.
73
- const OPTIONAL_INVERSE_DECORATORS = new Set(["ManyToOne", "ManyToMany"]);
74
-
75
- /**
76
- * How many rows the property holds — which fixes the TypeScript type it must
77
- * carry. @ManyToOne points at ONE row (`owner: ProductMatrixEntity`); the other
78
- * three hold many (`envs: ApplicationEnvsEntity[]`).
79
- */
80
- const RELATION_ARITY = {
81
- ManyToOne: "one",
82
- ManyToMany: "many",
83
- ManyToManyBackRef: "many",
84
- OneToMany: "many",
85
- };
86
-
87
- const ENUM_DECORATORS = new Set(["Enum", "MultiEnum"]);
88
- const FILE_DECORATORS = new Set(["File", "MultiFile"]);
89
-
90
- // ── typescript resolution: target app, then cwd, then this package ──
91
- // The app repo is the expected source: a Suppa application compiles to dist/,
92
- // so it has typescript. This package lists typescript as a devDependency only,
93
- // so the last candidate resolves in a checkout but never in an install.
94
- export function loadTypescript(rootDir) {
95
- const froms = [];
96
- if (rootDir) froms.push(join(resolve(rootDir), "package.json"));
97
- froms.push(join(process.cwd(), "package.json"));
98
- froms.push(import.meta.url);
99
- let sawStub = false;
100
- for (const from of froms) {
101
- let mod;
102
- try {
103
- mod = createRequire(from)("typescript");
104
- } catch {
105
- continue; // not resolvable from here — try the next candidate
106
- }
107
- // Resolvability is NOT proof the compiler API is there. TypeScript 7 — what
108
- // plain `npm i -D typescript` installs today — maps exports["."] to
109
- // lib/version.cjs, which exports only { version, versionMajorMinor }; the
110
- // parser moved behind ./unstable/*. That require SUCCEEDS and used to be
111
- // handed straight to the parser, which then died on `ts.ScriptTarget.Latest`
112
- // being undefined. Check the two members this validator actually uses, and
113
- // keep looking: a usable TS 5 further down the list still rescues the run.
114
- if (typeof mod?.createSourceFile === "function" && mod?.ScriptTarget) {
115
- return mod;
116
- }
117
- sawStub = true;
118
- }
119
- // Tagged so the CLI can report it as an environment problem — one actionable
120
- // line and exit 2 — instead of an uncaught stack trace.
121
- throw Object.assign(new Error(
122
- sawStub
123
- ? "validate-suppa-schema: the 'typescript' found here is TypeScript 7 (or newer), whose " +
124
- "main entry exports only version info — it has no createSourceFile/ScriptTarget, so " +
125
- "this validator cannot parse with it. Install the 5.x line in the app repo being " +
126
- "validated: `npm i -D typescript@5`."
127
- : "validate-suppa-schema: cannot resolve 'typescript'. It is read from the app repo " +
128
- "being validated (a Suppa application compiles with tsc, so it normally has it). " +
129
- "Install it there — `npm i -D typescript@5` — or run this from a directory where it " +
130
- "resolves.",
131
- ), { code: "SUPPA_VALIDATOR_ENV" });
132
- }
133
-
134
- /**
135
- * Path to print for a finding. A relative path is friendlier and clickable, but
136
- * only when it actually stays inside cwd — across drives or above cwd, Windows
137
- * `relative()` yields an unusable `..\..\..` chain with no drive letter.
138
- */
139
- export function displayPath(cwd, file) {
140
- const rel = relative(cwd, file);
141
- return !rel || rel.startsWith("..") || isAbsolute(rel) ? file : rel;
142
- }
143
-
144
- // ── small AST helpers ──
145
- function finding(ts, sf, node, code, message) {
146
- const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
147
- return {
148
- file: sf.fileName, line: line + 1, col: character + 1, code,
149
- level: code.startsWith("W") ? "warning" : "error", message,
150
- };
151
- }
152
- function decoratorsOf(ts, node) {
153
- return (ts.canHaveDecorators?.(node) ? ts.getDecorators(node) : undefined) ?? [];
154
- }
155
- function decoratorCall(ts, dec, sf) {
156
- const e = dec.expression;
157
- if (ts.isCallExpression(e)) {
158
- const name = calleeIdentity(ts, sf, e.expression);
159
- return name ? { name, args: [...e.arguments] } : null;
160
- }
161
- const name = calleeIdentity(ts, sf, e);
162
- return name ? { name, args: [] } : null;
163
- }
164
- function objectMap(ts, node) {
165
- const map = new Map();
166
- if (!node || !ts.isObjectLiteralExpression(node)) return map;
167
- for (const p of node.properties) {
168
- if (ts.isPropertyAssignment(p)) {
169
- const name =
170
- ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : null;
171
- if (name !== null) map.set(name, p.initializer);
172
- } else if (ts.isShorthandPropertyAssignment(p)) {
173
- map.set(p.name.text, p.name);
174
- }
175
- }
176
- return map;
177
- }
178
- function stringValue(ts, node) {
179
- return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
180
- ? node.text
181
- : null;
182
- }
183
- function stringArray(ts, node) {
184
- if (!node || !ts.isArrayLiteralExpression(node)) return null;
185
- const out = [];
186
- for (const el of node.elements) {
187
- const s = stringValue(ts, el);
188
- if (s === null) return null;
189
- out.push(s);
190
- }
191
- return out;
192
- }
193
- function thunkTarget(ts, sf, arg) {
194
- if (arg && ts.isArrowFunction(arg)) {
195
- const b = arg.body;
196
- if (ts.isIdentifier(b)) return resolveLocalName(sf, b.text);
197
- if (ts.isPropertyAccessExpression(b)) return b.name.text;
198
- }
199
- return null;
200
- }
201
- /**
202
- * The `inverse` selector — `(target, inverse, options?)` — is whichever
203
- * function expression sits in argument position 1; it is distinguished from
204
- * `(target, options?)` by NOT being an object literal.
205
- */
206
- function isFunctionLike(ts, n) {
207
- return !!n && (ts.isArrowFunction(n) || ts.isFunctionExpression(n));
208
- }
209
- /**
210
- * The TypeScript type a property declares, reduced to what the relation rules
211
- * need: the entity name it names, whether it is an array, and whether it is
212
- * optional. `null` when the property carries no annotation at all.
213
- *
214
- * Reads `T`, `T[]`, `Array<T>`, and unions with `null`/`undefined` (`T | null`);
215
- * anything else yields `{name: null}` so the caller reports "cannot read"
216
- * rather than inventing a mismatch.
217
- */
218
- function propertyTypeInfo(ts, member) {
219
- const node = member.type;
220
- if (!node) return null;
221
- let t = node;
222
- let nullable = !!member.questionToken;
223
- if (ts.isUnionTypeNode(t)) {
224
- const parts = t.types.filter((p) => {
225
- const isNullish =
226
- p.kind === ts.SyntaxKind.NullKeyword ||
227
- p.kind === ts.SyntaxKind.UndefinedKeyword ||
228
- (ts.isLiteralTypeNode(p) && p.literal.kind === ts.SyntaxKind.NullKeyword);
229
- if (isNullish) nullable = true;
230
- return !isNullish;
231
- });
232
- if (parts.length !== 1) return { node, name: null, isArray: false, nullable };
233
- t = parts[0];
234
- }
235
- let isArray = false;
236
- if (ts.isArrayTypeNode(t)) {
237
- isArray = true;
238
- t = t.elementType;
239
- } else if (
240
- ts.isTypeReferenceNode(t) &&
241
- ts.isIdentifier(t.typeName) &&
242
- t.typeName.text === "Array" &&
243
- t.typeArguments?.length === 1
244
- ) {
245
- isArray = true;
246
- t = t.typeArguments[0];
247
- }
248
- let name = null;
249
- if (ts.isTypeReferenceNode(t)) {
250
- name = ts.isIdentifier(t.typeName) ? t.typeName.text : t.typeName.getText(member.getSourceFile());
251
- }
252
- return { node, name, isArray, nullable };
253
- }
254
- /** A boolean literal's value, or null when the node is not one. */
255
- function booleanValue(ts, node) {
256
- if (!node) return null;
257
- if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
258
- if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
259
- return null;
260
- }
261
- /** PascalCase: starts upper, letters/digits only, no separators. */
262
- function isPascalCase(name) {
263
- return /^[A-Z][A-Za-z0-9]*$/.test(name);
264
- }
265
- /**
266
- * The property name an inverse selector's body accesses off its own single
267
- * parameter — `(t) => t.prop` (or `(t) => { return t.prop; }`) -> "prop".
268
- * Anything else (destructuring, no single-parameter self-access, …) is not a
269
- * shape this AST-only checker can read, so it returns null rather than guess.
270
- */
271
- function inverseAccessedProperty(ts, fn) {
272
- if (!fn || fn.parameters.length !== 1) return null;
273
- const param = fn.parameters[0].name;
274
- if (!ts.isIdentifier(param)) return null;
275
- let body = fn.body;
276
- if (ts.isBlock(body)) {
277
- const stmts = body.statements;
278
- if (stmts.length !== 1 || !ts.isReturnStatement(stmts[0]) || !stmts[0].expression) return null;
279
- body = stmts[0].expression;
280
- }
281
- if (ts.isPropertyAccessExpression(body) && ts.isIdentifier(body.expression) &&
282
- body.expression.text === param.text) {
283
- return body.name.text;
284
- }
285
- return null;
286
- }
287
- function spreadElements(ts, node) {
288
- if (!node || !ts.isObjectLiteralExpression(node)) return [];
289
- return node.properties.filter((p) => ts.isSpreadAssignment(p));
290
- }
291
- function arraySpreadElements(ts, node) {
292
- if (!node || !ts.isArrayLiteralExpression(node)) return [];
293
- return node.elements.filter((e) => ts.isSpreadElement(e));
294
- }
295
-
296
- // ── identity: aliased named imports and '@suppa/sdk' namespace imports ──
297
- // `import { Things as Thing }` / `import * as sdk from '@suppa/sdk'` name the
298
- // very same declarations; matching bare identifiers alone misses them.
299
- function analyzeImports(ts, sf) {
300
- const alias = new Map(); // local name -> imported (exported) name
301
- const namespaces = new Set(); // local name of `import * as X from '@suppa/sdk'`
302
- for (const st of sf.statements) {
303
- if (!ts.isImportDeclaration(st) || !st.importClause) continue;
304
- const from = ts.isStringLiteral(st.moduleSpecifier) ? st.moduleSpecifier.text : "";
305
- const bindings = st.importClause.namedBindings;
306
- if (bindings && ts.isNamespaceImport(bindings)) {
307
- if (from === "@suppa/sdk") namespaces.add(bindings.name.text);
308
- } else if (bindings && ts.isNamedImports(bindings)) {
309
- for (const el of bindings.elements) {
310
- alias.set(el.name.text, (el.propertyName ?? el.name).text);
311
- }
312
- }
313
- }
314
- sf.suppaImports = { alias, namespaces };
315
- }
316
- function importsOf(sf) {
317
- return sf.suppaImports ?? { alias: new Map(), namespaces: new Set() };
318
- }
319
- /** local identifier text -> the name it was imported under (or itself) */
320
- function resolveLocalName(sf, text) {
321
- return importsOf(sf).alias.get(text) ?? text;
322
- }
323
- /** node is `name`, an alias of it, or `<sdkNamespace>.name` */
324
- function isSdkQualified(ts, sf, node, name) {
325
- if (!node) return false;
326
- if (ts.isIdentifier(node)) return resolveLocalName(sf, node.text) === name;
327
- if (ts.isPropertyAccessExpression(node) && node.name.text === name &&
328
- ts.isIdentifier(node.expression)) {
329
- return importsOf(sf).namespaces.has(node.expression.text);
330
- }
331
- return false;
332
- }
333
- function calleeIdentity(ts, sf, expr) {
334
- if (ts.isIdentifier(expr)) return resolveLocalName(sf, expr.text);
335
- if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression) &&
336
- importsOf(sf).namespaces.has(expr.expression.text)) {
337
- return expr.name.text;
338
- }
339
- return null;
340
- }
341
-
342
- // ── string-ness of an expression (no type checker available) ──
343
- /** provably NOT a string at runtime */
344
- function isProvableNonString(ts, n) {
345
- if (n.kind === ts.SyntaxKind.TrueKeyword || n.kind === ts.SyntaxKind.FalseKeyword ||
346
- n.kind === ts.SyntaxKind.NullKeyword) return true;
347
- if (ts.isNumericLiteral(n) || ts.isBigIntLiteral(n)) return true;
348
- if (ts.isPrefixUnaryExpression(n) &&
349
- (ts.isNumericLiteral(n.operand) || ts.isBigIntLiteral(n.operand))) return true;
350
- if (ts.isArrayLiteralExpression(n) || ts.isObjectLiteralExpression(n)) return true;
351
- if (ts.isNewExpression(n)) return true;
352
- return false;
353
- }
354
- /** provably a string at runtime (literal, template, or a `+` chain with one) */
355
- function isProvableString(ts, n) {
356
- if (ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n) ||
357
- ts.isTemplateExpression(n)) return true;
358
- if (ts.isParenthesizedExpression(n)) return isProvableString(ts, n.expression);
359
- if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.PlusToken) {
360
- return isProvableString(ts, n.left) || isProvableString(ts, n.right);
361
- }
362
- return false;
363
- }
364
- /** strip `(x)`, `x as T`, `x!` — they do not change the runtime value */
365
- function unwrapExpr(ts, n) {
366
- let cur = n;
367
- while (cur && (ts.isParenthesizedExpression(cur) || ts.isAsExpression(cur) ||
368
- ts.isNonNullExpression(cur) || ts.isSatisfiesExpression?.(cur) === true)) {
369
- cur = cur.expression;
370
- }
371
- return cur;
372
- }
373
- /** an expression whose value this AST-only checker cannot see */
374
- function isOpaqueExpression(ts, n) {
375
- return ts.isIdentifier(n) || ts.isCallExpression(n) ||
376
- ts.isPropertyAccessExpression(n) || ts.isElementAccessExpression(n) ||
377
- ts.isAwaitExpression(n) || ts.isConditionalExpression(n);
378
- }
379
-
380
- // ── extraction: entities ──
381
- function analyzeEntities(ts, sf, model) {
382
- sf.forEachChild(function walk(node) {
383
- if (ts.isClassDeclaration(node)) {
384
- const decs = decoratorsOf(ts, node).map((d) => decoratorCall(ts, d, sf)).filter(Boolean);
385
- const entityDec = decs.find((d) => d.name === "Entity");
386
- if (entityDec) {
387
- const className = node.name ? node.name.text : "<anonymous>";
388
- const options = objectMap(ts, entityDec.args[0]);
389
- const keysNode = options.get("importKeyFields");
390
- const info = {
391
- className,
392
- entityName: stringValue(ts, options.get("name")) ?? className,
393
- sf, node, options, optionsNode: entityDec.args[0],
394
- importKeyFields: stringArray(ts, keysNode),
395
- // present but not a readable array of string literals: the key checks
396
- // cannot run, but claiming it is missing would be a lie (CB-8)
397
- importKeyFieldsUnreadable: !!keysNode && stringArray(ts, keysNode) === null,
398
- importKeyFieldsNode: keysNode ?? null,
399
- hasKey: options.has("key"),
400
- properties: new Map(),
401
- columnNames: new Set(), // literal `name` options of @Column/relations
402
- };
403
- for (const member of node.members) {
404
- if (!ts.isPropertyDeclaration(member) || !member.name) continue;
405
- const propName =
406
- ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)
407
- ? member.name.text
408
- : member.name.getText(sf);
409
- for (const d of decoratorsOf(ts, member).map((x) => decoratorCall(ts, x, sf)).filter(Boolean)) {
410
- if (d.name === "Column") {
411
- const columnOptions = objectMap(ts, d.args[0]);
412
- info.properties.set(propName, {
413
- kind: "column", node: member, decorator: d,
414
- columnOptions, optionsNode: d.args[0],
415
- nameNode: columnOptions.get("name") ?? null,
416
- });
417
- } else if (ENUM_DECORATORS.has(d.name)) {
418
- // (globalName?, Enum, titles?, options?) — the options object is
419
- // the LAST argument when that is an object literal. An inline
420
- // titles map occupies the same slot when options are omitted, so
421
- // this node is only ever read for keys options own (E113's
422
- // `subType`); a titles map never carries one.
423
- const last = d.args[d.args.length - 1];
424
- const enumOptionsNode =
425
- d.args.length >= 2 && last && ts.isObjectLiteralExpression(last) ? last : null;
426
- info.properties.set(propName, {
427
- kind: d.name === "Enum" ? "enum" : "multi-enum",
428
- node: member, decorator: d,
429
- enumGlobalName: stringValue(ts, d.args[0]),
430
- optionsNode: enumOptionsNode,
431
- enumOptions: objectMap(ts, enumOptionsNode),
432
- });
433
- } else if (FILE_DECORATORS.has(d.name)) {
434
- info.properties.set(propName, {
435
- kind: d.name === "File" ? "file" : "multi-file",
436
- node: member, decorator: d,
437
- });
438
- } else if (d.name in RELATION_KIND_BY_DECORATOR) {
439
- // (target, options?) or (target, inverse, options?) — the options
440
- // object is whichever trailing argument is an object literal; the
441
- // inverse (when present) is argument 1 whenever it is NOT that
442
- // options object, i.e. it is an arrow/function expression instead.
443
- const relOptions = objectMap(
444
- ts, [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)),
445
- );
446
- const inverseNode = isFunctionLike(ts, d.args[1]) ? d.args[1] : null;
447
- info.properties.set(propName, {
448
- kind: RELATION_KIND_BY_DECORATOR[d.name],
449
- node: member, decorator: d,
450
- targetClass: thunkTarget(ts, sf, d.args[0]),
451
- nameNode: relOptions.get("name") ?? null,
452
- inverseNode,
453
- relOptions,
454
- optionsNode: [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)) ?? null,
455
- typeInfo: propertyTypeInfo(ts, member),
456
- });
457
- }
458
- }
459
- const prop = info.properties.get(propName);
460
- const colName = prop && stringValue(ts, prop.nameNode);
461
- if (colName) info.columnNames.add(colName);
462
- }
463
- model.entities.set(className, info);
464
- model.entityByName.set(info.entityName, info);
465
- }
466
- }
467
- ts.forEachChild(node, walk);
468
- });
469
- }
470
-
471
- // ── rules: tabular parts ──
472
- /**
473
- * Doc: "Three things make an entity a tabular part. All three are required,
474
- * and the platform does not infer any of them: type: 'tabular-part' on
475
- * @Entity(), relationEntityName — the name of the parent entity, and a
476
- * @ManyToOne field named owner pointing at the parent class."
477
- * Conversely, relationEntityName without type: 'tabular-part' is the doc's
478
- * own mistake row: "type: 'tabular-part' or relationEntityName is missing,
479
- * so it is listed under /related instead."
480
- */
481
- function checkTabularPart(ts, info, model, findings) {
482
- const sf = info.sf;
483
- const anchor = info.node.name ?? info.node;
484
- 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)`;
485
-
486
- const hasType = info.options.has("type");
487
- const typeNode = info.options.get("type");
488
- const typeLiteral = hasType ? stringValue(ts, typeNode) : null;
489
- const typeUnreadable = hasType && typeLiteral === null;
490
-
491
- const hasRelName = info.options.has("relationEntityName");
492
- const relNode = info.options.get("relationEntityName");
493
- const relLiteral = hasRelName ? stringValue(ts, relNode) : null;
494
- const relUnreadable = hasRelName && relLiteral === null;
495
-
496
- // an unreadable type/relationEntityName (identifier, expression, …) means
497
- // this checker cannot tell whether the entity is a tabular part at all —
498
- // warn instead of guessing E108 one way or the other.
499
- if (typeUnreadable || relUnreadable) {
500
- const badNode = typeUnreadable ? typeNode : relNode;
501
- const badOpt = typeUnreadable ? "type" : "relationEntityName";
502
- findings.push(finding(ts, sf, badNode, "W606",
503
- `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`));
504
- return;
505
- }
506
-
507
- const isTabularPart = typeLiteral === "tabular-part";
508
- // `owner` is a @ManyToOne relation named 'owner' by PROPERTY name, or one
509
- // whose literal @ManyToOne({ name: 'owner' }) column-name option is 'owner'
510
- // (F4) — E106 (DA-2) already accepts a column name as a field identity, so
511
- // E108's notion of "the owner relation" must agree.
512
- const ownerProp = [...info.properties.entries()].find(
513
- ([propName, p]) => p.kind === "many-to-one" &&
514
- (propName === "owner" || stringValue(ts, p.nameNode) === "owner"),
515
- )?.[1];
516
- const hasOwner = !!ownerProp;
517
-
518
- // an @Entity() options spread may hide `type`/`relationEntityName` (they are
519
- // spread properties, not readable PropertyAssignments) — the W606 already
520
- // fired for the spread promises these doc-rule checks are skipped, so the
521
- // two option-presence branches below must not also false-positive E108. The
522
- // missing-`owner` branch is a class member a spread cannot deliver, so it
523
- // stays ungated.
524
- const optionsSpread = spreadElements(ts, info.optionsNode).length > 0;
525
-
526
- if (isTabularPart) {
527
- if (!hasRelName && !optionsSpread) {
528
- findings.push(finding(ts, sf, anchor, "E108",
529
- `tabular part '${info.className}' (type: 'tabular-part') is missing relationEntityName — ${TRIAD}`));
530
- }
531
- if (!hasOwner) {
532
- findings.push(finding(ts, sf, anchor, "E108",
533
- `tabular part '${info.className}' (type: 'tabular-part') has no @ManyToOne relation named 'owner' pointing at the parent — ${TRIAD}`));
534
- }
535
- } else if (hasRelName && !optionsSpread) {
536
- findings.push(finding(ts, sf, relNode, "E108",
537
- `entity '${info.className}' sets relationEntityName but not type: 'tabular-part' — "type: 'tabular-part' or relationEntityName is missing, so it is listed under /related instead"`));
538
- }
539
-
540
- if (hasRelName && hasOwner && ownerProp.targetClass) {
541
- const target = model.entities.get(ownerProp.targetClass);
542
- if (target && target.entityName !== relLiteral) {
543
- findings.push(finding(ts, sf, ownerProp.node, "E109",
544
- `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`));
545
- }
546
- }
547
-
548
- if (isTabularPart && hasOwner && !info.importKeyFieldsUnreadable && info.importKeyFields) {
549
- const idx = info.importKeyFields.indexOf("owner");
550
- if (idx === -1) {
551
- findings.push(finding(ts, sf, info.importKeyFieldsNode, "E110",
552
- `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`));
553
- } else if (idx !== 0) {
554
- findings.push(finding(ts, sf, info.importKeyFieldsNode, "W607",
555
- `tabular part '${info.className}': "Put owner first in importKeyFields" — it is at position ${idx}`));
556
- }
557
- }
558
- }
559
-
560
- // ── rules: entities ──
561
- function checkEntity(ts, info, sdk, model, findings) {
562
- const sf = info.sf;
563
- const anchor = info.node.name ?? info.node;
564
-
565
- const heritage = (info.node.heritageClauses ?? []).find(
566
- (h) => h.token === ts.SyntaxKind.ExtendsKeyword,
567
- );
568
- const base = heritage?.types?.[0]?.expression;
569
- if (!isSdkQualified(ts, sf, base, "SystemBaseEntity")) {
570
- findings.push(finding(ts, sf, anchor, "E101",
571
- `entity class '${info.className}' must extend SystemBaseEntity — it contributes id/createdAt/updatedAt/deletedAt/createdBy/removedBy (doc: "Every entity must extend SystemBaseEntity")`));
572
- }
573
-
574
- for (const [opt, valNode] of info.options) {
575
- if (!sdk.entityOptions.includes(opt)) {
576
- findings.push(finding(ts, sf, valNode, "E501",
577
- `unknown @Entity() option '${opt}' — valid options: ${sdk.entityOptions.join(", ")}. If it isn't in the table, it isn't an option.`));
578
- }
579
- }
580
-
581
- for (const spread of spreadElements(ts, info.optionsNode)) {
582
- findings.push(finding(ts, sf, spread, "W606",
583
- `@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`));
584
- }
585
-
586
- if (info.importKeyFieldsUnreadable) {
587
- findings.push(finding(ts, sf, info.importKeyFieldsNode, "W606",
588
- `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`));
589
- } else if (info.importKeyFields) {
590
- for (const f of info.importKeyFields) {
591
- // a field may be named by its property name or by its @Column({ name }) (DA-2)
592
- if (!info.properties.has(f) && !info.columnNames.has(f)) {
593
- findings.push(finding(ts, sf, info.importKeyFieldsNode, "E106",
594
- `importKeyFields names '${f}' but the class declares no such property or column name — seeds would have nothing to match on`));
595
- }
596
- }
597
- }
598
-
599
- if (!info.hasKey) {
600
- findings.push(finding(ts, sf, anchor, "W602",
601
- `entity '${info.className}' has no 'key' option — a rename will be treated as drop-and-create instead of a rename (doc TIP)`));
602
- }
603
-
604
- checkTabularPart(ts, info, model, findings);
605
-
606
- for (const [propName, prop] of info.properties) {
607
- if (SYSTEM_COLUMNS.includes(propName)) {
608
- findings.push(finding(ts, sf, prop.node, "E102",
609
- `system column '${propName}' is provided by SystemBaseEntity — "you never declare them yourself"`));
610
- }
611
- // the table-level conflict is on the COLUMN name, which `name` overrides
612
- const colName = stringValue(ts, prop.nameNode);
613
- if (colName && SYSTEM_COLUMNS.includes(colName)) {
614
- findings.push(finding(ts, sf, prop.nameNode, "E102",
615
- `column name '${colName}' on property '${propName}' collides with the system column of the same name provided by SystemBaseEntity — "you never declare them yourself"`));
616
- }
617
- if (prop.kind === "column") checkColumn(ts, sf, propName, prop, sdk, findings);
618
- if (prop.kind === "enum" || prop.kind === "multi-enum") {
619
- checkEnumSubType(ts, sf, propName, prop, findings);
620
- }
621
- checkDefaultFieldOptions(ts, sf, propName, prop, findings);
622
- if (prop.kind === "enum" || prop.kind === "multi-enum") {
623
- checkEnumGlobalName(ts, sf, propName, prop, model, findings);
624
- }
625
- if (RELATION_KINDS.has(prop.kind)) {
626
- checkRelationTyping(ts, sf, propName, prop, findings);
627
- if (prop.targetClass === null) {
628
- findings.push(finding(ts, sf, prop.node, "E105",
629
- `relation '${propName}' must receive a thunk returning the target class — write @${prop.decorator.name}(() => Target); a direct class reference breaks circular imports`));
630
- }
631
- if (prop.inverseNode) {
632
- if (OPTIONAL_INVERSE_DECORATORS.has(prop.decorator.name)) {
633
- findings.push(finding(ts, sf, prop.inverseNode, "W609",
634
- `'${propName}' (@${prop.decorator.name}) passes an inverse selector — it is optional on @ManyToOne/@ManyToMany and usually omitted; pass only the thunk and the options object (@${prop.decorator.name}(() => Target, { ... })) unless you are deliberately pairing an explicit back-reference declared on the target`));
635
- }
636
- checkInverseSelector(ts, sf, propName, prop, model, findings);
637
- }
638
- }
639
- }
640
- }
641
-
642
- /**
643
- * A relation property must declare its TypeScript type, and that type must say
644
- * the same thing the decorator does: @ManyToOne holds ONE target row, the other
645
- * three hold many.
646
- *
647
- * @ManyToOne(() => ProductMatrixEntity, { nullable: false })
648
- * owner: ProductMatrixEntity;
649
- *
650
- * @ManyToMany(() => ProductMatrixEntity, { … }) @OneToMany(() => X, i, { … })
651
- * owners: ProductMatrixEntity[]; envs: X[];
652
- *
653
- * Without the annotation the property is `any` to every consumer of the entity,
654
- * and nothing catches a relation read as the wrong shape.
655
- */
656
- function checkRelationTyping(ts, sf, propName, prop, findings) {
657
- const arity = RELATION_ARITY[prop.decorator.name];
658
- const target = prop.targetClass;
659
- const info = prop.typeInfo;
660
- const expected = target ? (arity === "many" ? `${target}[]` : target) : null;
661
-
662
- if (!info) {
663
- findings.push(finding(ts, sf, prop.node, "E114",
664
- `relation '${propName}' (@${prop.decorator.name}) has no TypeScript type — write ` +
665
- `${propName}${arity === "one" ? "" : ""}: ${expected ?? (arity === "many" ? "Target[]" : "Target")};` +
666
- ` an untyped relation property is 'any' to every consumer of this entity`));
667
- return;
668
- }
669
- if (info.name === null) return; // a shape this AST-only checker cannot read
670
-
671
- if (target && info.name !== target) {
672
- findings.push(finding(ts, sf, info.node, "E115",
673
- `relation '${propName}' (@${prop.decorator.name}) points at '${target}' but the property is typed ` +
674
- `'${info.name}${info.isArray ? "[]" : ""}' — the type must name the same class the thunk returns: ${expected}`));
675
- return;
676
- }
677
- if (arity === "many" && !info.isArray) {
678
- findings.push(finding(ts, sf, info.node, "E115",
679
- `'${propName}' (@${prop.decorator.name}) holds MANY rows but is typed '${info.name}' — write '${info.name}[]'`));
680
- } else if (arity === "one" && info.isArray) {
681
- findings.push(finding(ts, sf, info.node, "E115",
682
- `'${propName}' (@ManyToOne) holds ONE row but is typed '${info.name}[]' — write '${info.name}'. ` +
683
- `The many side is @OneToMany on the other class.`));
684
- }
685
-
686
- // Optionality should agree with the column: a NOT NULL relation always has a
687
- // value, anything else may be absent.
688
- if (arity === "one") {
689
- const notNull = booleanValue(ts, prop.relOptions?.get("nullable")) === false;
690
- if (notNull && info.nullable) {
691
- findings.push(finding(ts, sf, info.node, "W610",
692
- `'${propName}' is declared nullable: false but typed as optional — drop the '?' (and any '| null'): the column always has a value`));
693
- } else if (!notNull && !info.nullable) {
694
- findings.push(finding(ts, sf, info.node, "W610",
695
- `'${propName}' is nullable (no 'nullable: false') but typed as always present — write '${propName}?: ${info.name}' so callers handle the empty case`));
696
- }
697
- }
698
- }
699
-
700
- /**
701
- * Field options the platform already applies by default. Repeating one per
702
- * field is noise that hides the options that DO differ.
703
- */
704
- function checkDefaultFieldOptions(ts, sf, propName, prop, findings) {
705
- const scopes = [];
706
- if (prop.optionsNode) scopes.push(prop.optionsNode);
707
- // …and a nested `options: { … }` object, whichever shape the SDK takes.
708
- for (const scope of [...scopes]) {
709
- const nested = objectMap(ts, scope).get("options");
710
- if (nested && ts.isObjectLiteralExpression(nested)) scopes.push(nested);
711
- }
712
- for (const scope of scopes) {
713
- for (const [key, valNode] of objectMap(ts, scope)) {
714
- if (!(key in DEFAULT_FIELD_OPTIONS)) continue;
715
- const value = booleanValue(ts, valNode);
716
- if (value !== null && value === DEFAULT_FIELD_OPTIONS[key]) {
717
- findings.push(finding(ts, sf, valNode, "W612",
718
- `'${propName}' sets '${key}: ${value}', which is already the platform default — remove it; ` +
719
- `declare an option only where it DEPARTS from the default (defaults: ` +
720
- `${Object.entries(DEFAULT_FIELD_OPTIONS).map(([k, v]) => `${k}=${v}`).join(", ")})`));
721
- }
722
- }
723
- }
724
- }
725
-
726
- /**
727
- * @Enum()/@MultiEnum() take the enum's global name as an optional FIRST
728
- * argument. A global name is what lets seeds and other entities reference the
729
- * value set; without one the decorator derives <ClassName>.<propertyName> and
730
- * the enum stays local to this field. Pass it only when the enum really is
731
- * shared — so a name nothing references is a name that should not be there.
732
- */
733
- function checkEnumGlobalName(ts, sf, propName, prop, model, findings) {
734
- const name = prop.enumGlobalName;
735
- if (!name) return; // local enum — the default, and nothing to check
736
- // The literal occurs once: here, in this decorator. Nothing — no seed record,
737
- // no other entity — refers to it, so the name buys nothing.
738
- const occurrences = model.stringLiteralCounts.get(name) ?? 0;
739
- if (occurrences <= 1) {
740
- findings.push(finding(ts, sf, prop.decorator.args[0], "W613",
741
- `'${propName}' (@${prop.decorator.name}) declares the global enum name '${name}', but nothing in the ` +
742
- `analyzed files references it. A global name is for enums shared across entities or referenced from ` +
743
- `seeds ({ name: '${name}', value: … }); for an enum used only by this field, omit the first argument ` +
744
- `— @${prop.decorator.name}(${prop.decorator.name === "Enum" ? "StatusEnum, StatusTitles, " : "…, "}{ … }) — and the decorator derives the name`));
745
- }
746
- }
747
-
748
- /**
749
- * "An inverse must select the property on the target that holds the OTHER
750
- * SIDE of this relation" — e.g. (task) => task.project. Applies to the
751
- * `inverse` argument of any of the four relation decorators, required or not.
752
- * Skipped silently when the target class is not among the analyzed entities
753
- * (platform/SDK entities such as IconsEntity) — no guessing without a model
754
- * of that class, and when the selector's shape (destructuring, a computed
755
- * body, …) is not one this AST-only checker can read.
756
- */
757
- function checkInverseSelector(ts, sf, propName, prop, model, findings) {
758
- if (!prop.targetClass) return;
759
- const target = model.entities.get(prop.targetClass);
760
- if (!target) return;
761
- const accessed = inverseAccessedProperty(ts, prop.inverseNode);
762
- if (accessed === null) return;
763
- const targetProp = target.properties.get(accessed);
764
- if (targetProp && RELATION_KINDS.has(targetProp.kind)) return; // valid pairing
765
-
766
- let reason;
767
- if (SYSTEM_COLUMNS.includes(accessed)) {
768
- reason = `'${accessed}' is a system column provided by SystemBaseEntity, not a relation`;
769
- } else if (!targetProp) {
770
- reason = `'${target.entityName}' declares no property named '${accessed}'`;
771
- } else {
772
- reason = `'${target.entityName}.${accessed}' is a '${targetProp.kind}' property, not a relation`;
773
- }
774
- findings.push(finding(ts, sf, prop.inverseNode, "E111",
775
- `inverse selector on '${propName}' (@${prop.decorator.name}) targets '${target.entityName}.${accessed}', but ${reason} — an inverse selector must select the RELATION property on the target that holds the OTHER SIDE of this relation, e.g. (task) => task.project`));
776
- }
777
-
778
- /**
779
- * E113 — "@Enum() and @MultiEnum() fill it from their first argument […] do not
780
- * pass subType yourself on an enum field". Passing one by hand either duplicates
781
- * what the decorator already writes or silently disagrees with it, and the value
782
- * it disagrees with is the one that resolves { value: 'active' } to an enum
783
- * record on insert.
784
- */
785
- function checkEnumSubType(ts, sf, propName, prop, findings) {
786
- const subTypeNode = prop.enumOptions?.get("subType");
787
- if (!subTypeNode) return;
788
- findings.push(finding(ts, sf, subTypeNode, "E113",
789
- `'${propName}' (@${prop.decorator.name}) passes 'subType' by hand — on an enum field subType holds the enum's global name and is "Set by the decorator — never by hand"; @Enum()/@MultiEnum() fill it from their first argument (or derive <ClassName>.<propertyName>). Remove the option.`));
790
- }
791
-
792
- function checkColumn(ts, sf, propName, prop, sdk, findings) {
793
- const opts = prop.columnOptions;
794
- for (const [opt, valNode] of opts) {
795
- if (!sdk.columnOptions.includes(opt)) {
796
- findings.push(finding(ts, sf, valNode, "E502",
797
- `unknown @Column() option '${opt}' — valid options: ${sdk.columnOptions.join(", ")}. If it isn't in the table, it isn't an option.`));
798
- }
799
- }
800
-
801
- for (const spread of spreadElements(ts, prop.optionsNode)) {
802
- findings.push(finding(ts, sf, spread, "W606",
803
- `@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`));
804
- }
805
-
806
- let typeValue = null; // canonical string value, e.g. "text"
807
- const typeNode = opts.get("type");
808
- if (typeNode) {
809
- if (ts.isPropertyAccessExpression(typeNode) &&
810
- ts.isIdentifier(typeNode.expression) &&
811
- typeNode.expression.text === "FieldTypeEnum") {
812
- const member = typeNode.name.text;
813
- typeValue = sdk.fieldTypes[member] ?? null;
814
- if (typeValue === null) {
815
- findings.push(finding(ts, sf, typeNode, "E107",
816
- `FieldTypeEnum.${member} is not a known member — valid: ${Object.keys(sdk.fieldTypes).join(", ")}`));
817
- }
818
- } else {
819
- const raw = stringValue(ts, typeNode);
820
- if (raw !== null) {
821
- if (NON_SCALAR_TYPE_STRINGS.has(raw)) {
822
- findings.push(finding(ts, sf, typeNode, "E104",
823
- `@Column type '${raw}' — relations, enums and files are declared with their own decorators (@ManyToOne/@Enum/@File/…) "and never with @Column({ type: ... })"`));
824
- } else {
825
- const member = Object.keys(sdk.fieldTypes).find((k) => sdk.fieldTypes[k] === raw);
826
- if (member) {
827
- typeValue = raw;
828
- findings.push(finding(ts, sf, typeNode, "W601",
829
- `raw string type '${raw}' — use FieldTypeEnum.${member} so a typo fails in the editor instead of at migration time`));
830
- } else {
831
- findings.push(finding(ts, sf, typeNode, "E107",
832
- `unknown column type '${raw}' — "a misspelled one ('txet') compiles too and only fails when the migration runs"`));
833
- }
834
- }
835
- }
836
- }
837
- }
838
-
839
- const def = opts.get("default");
840
- if (def) {
841
- const val = unwrapExpr(ts, def);
842
- if (isProvableNonString(ts, val)) {
843
- findings.push(finding(ts, sf, def, "E103",
844
- `'default' must be a SQL expression STRING — "Write default: 'false', not default: false, and default: \\"'draft'\\" for a string literal"`));
845
- } else if (!isProvableString(ts, val)) {
846
- findings.push(finding(ts, sf, def, "W606",
847
- `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`));
848
- }
849
- }
850
- checkSubType(ts, sf, propName, prop, typeValue, findings);
851
-
852
- if (opts.has("length") && typeValue !== null && typeValue !== "text") {
853
- findings.push(finding(ts, sf, opts.get("length"), "W603",
854
- `'length' caps Text columns; this column is '${typeValue}'`));
855
- }
856
- if (opts.has("decimalPlaces") && typeValue !== null && typeValue !== "numeric") {
857
- findings.push(finding(ts, sf, opts.get("decimalPlaces"), "W604",
858
- `'decimalPlaces' pairs with Numeric columns; this column is '${typeValue}'`));
859
- }
860
- }
861
-
862
- /**
863
- * E112 — a subType string that the doc's matrix does not pair with this base
864
- * type. Only two rows of that matrix belong to @Column(): Timestamp takes
865
- * 'date' | 'time' | 'timestamp' ("Chooses the physical column type"), Text takes
866
- * 'encrypted'. Anything else is rejected by the platform, not by tsc — `subType`
867
- * is typed as a plain string, so a wrong pairing compiles.
868
- *
869
- * `subType: null` is the DOCUMENTED way to clear a subtype ("write subType: null
870
- * explicitly") and is always clean. A value this AST-only checker cannot read
871
- * takes the usual W606 unverifiable path — never E112. An unresolved `type`
872
- * leaves nothing to judge the pairing against, so the check is skipped.
873
- */
874
- function checkSubType(ts, sf, propName, prop, typeValue, findings) {
875
- const node = prop.columnOptions.get("subType");
876
- if (!node) return;
877
- const val = unwrapExpr(ts, node);
878
- if (val.kind === ts.SyntaxKind.NullKeyword) return; // the documented "clear it"
879
- const raw = stringValue(ts, val);
880
- if (raw === null) {
881
- findings.push(finding(ts, sf, node, "W606",
882
- `cannot statically verify 'subType' of '${propName}' — it is delivered by reference or by an expression this checker cannot evaluate, so the base-type pairing check (E112) is skipped; inline the string literal to restore checking`));
883
- return;
884
- }
885
- if (typeValue === null) return; // no readable `type` to pair it against
886
- const allowed = DOC_SUBTYPES_BY_TYPE[typeValue];
887
- if (allowed && allowed.includes(raw)) return;
888
- findings.push(finding(ts, sf, node, "E112",
889
- `subType '${raw}' is not valid on a '${typeValue}' column ('${propName}') — the doc's matrix pairs subType with exactly two @Column base types: Timestamp takes 'date', 'time' or 'timestamp', and Text takes 'encrypted'. No other (type, subType) combination exists.`));
890
- }
891
-
892
- // ── extraction: string enums (createSeed(EnumName.Member) resolution) ──
893
- function analyzeEnums(ts, sf, model) {
894
- sf.forEachChild(function walk(node) {
895
- // Every string literal in the analyzed set, counted. A global enum name that
896
- // occurs exactly once is written in its decorator and referenced nowhere —
897
- // which is what W613 is looking for.
898
- if (ts.isStringLiteral(node)) {
899
- model.stringLiteralCounts.set(node.text, (model.stringLiteralCounts.get(node.text) ?? 0) + 1);
900
- }
901
- if (ts.isEnumDeclaration(node)) {
902
- const members = new Map();
903
- const memberNodes = [];
904
- for (const m of node.members) {
905
- const name = ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)
906
- ? m.name.text : m.name.getText(sf);
907
- memberNodes.push({ name, node: m.name });
908
- const value = stringValue(ts, m.initializer);
909
- if (value !== null) members.set(name, value);
910
- }
911
- if (members.size) model.stringEnums.set(node.name.text, members);
912
- model.enumDeclarations.push({ name: node.name.text, sf, members: memberNodes });
913
- }
914
- ts.forEachChild(node, walk);
915
- });
916
- }
917
-
918
- /**
919
- * Enum MEMBER keys are PascalCase — `NotFilled = 'Not filled'`. The key is the
920
- * name the code reads; the string on the right is what the platform stores, and
921
- * the two are free to differ. A snake_case or lowercase key reads as data
922
- * rather than as an identifier and drifts from every other enum in the repo.
923
- */
924
- function checkEnumDeclarations(ts, model, findings) {
925
- for (const decl of model.enumDeclarations) {
926
- for (const m of decl.members) {
927
- if (!isPascalCase(m.name)) {
928
- findings.push(finding(ts, decl.sf, m.node, "W611",
929
- `enum member '${decl.name}.${m.name}' is not PascalCase — write '${pascalize(m.name)}'. ` +
930
- `The member KEY is PascalCase; its stored value is the string on the right and need not match ` +
931
- `(e.g. NotFilled = 'Not filled')`));
932
- }
933
- }
934
- }
935
- }
936
-
937
- /** Best-effort PascalCase suggestion for an existing member key. */
938
- function pascalize(name) {
939
- return name
940
- .split(/[^A-Za-z0-9]+/)
941
- .filter(Boolean)
942
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
943
- .join("") || name;
944
- }
945
-
946
- // ── extraction: seeds ──
947
- function analyzeSeeds(ts, sf, model) {
948
- sf.forEachChild(function walk(node) {
949
- if (ts.isVariableStatement(node)) {
950
- for (const decl of node.declarationList.declarations) {
951
- const init = decl.initializer;
952
- if (init && ts.isCallExpression(init) &&
953
- isSdkQualified(ts, sf, init.expression, "createSeed")) {
954
- const exportName = ts.isIdentifier(decl.name) ? decl.name.text : decl.name.getText(sf);
955
- const arg0 = init.arguments[0];
956
- let entityName = stringValue(ts, arg0);
957
- let enumRef = null;
958
- if (entityName === null && arg0 && ts.isPropertyAccessExpression(arg0) &&
959
- ts.isIdentifier(arg0.expression)) {
960
- // EntityNamesEnum.Workflows — the VALUE is what createSeed receives;
961
- // the member name is only a fallback (resolved after every file is read)
962
- enumRef = { enumName: arg0.expression.text, member: arg0.name.text };
963
- }
964
- const arg1 = init.arguments[1];
965
- let records = null; // null = thin seed (imported payload) — record checks impossible
966
- if (arg1 && ts.isArrayLiteralExpression(arg1)) {
967
- records = arg1.elements.map((e) =>
968
- ts.isObjectLiteralExpression(e)
969
- ? { node: e, map: objectMap(ts, e), hasSpread: spreadElements(ts, e).length > 0, spreads: spreadElements(ts, e), byRef: false }
970
- : { node: e, map: new Map(), hasSpread: false, spreads: [], byRef: true },
971
- );
972
- }
973
- model.seeds.push({ exportName, entityName, enumRef, sf, node: init, records });
974
- }
975
- }
976
- }
977
- ts.forEachChild(node, walk);
978
- });
979
- }
980
-
981
- // ── rules: seeds ──
982
- /**
983
- * `{ name: '<global enum name>', value: '<enum value>' }`. Extra keys are legal
984
- * (the doc gives the shape, it never forbids more). A reference or a spread is
985
- * unverifiable — warn instead of hard-erroring on code that may well be correct.
986
- */
987
- function checkEnumRef(ts, sf, key, valNode, prop, findings) {
988
- const root = unwrapExpr(ts, valNode);
989
- if (root.kind === ts.SyntaxKind.NullKeyword) return;
990
- const multi = prop.kind === "multi-enum";
991
- const shapeHint = multi ? " — an array of those for @MultiEnum" : "";
992
- const unverifiable = () => findings.push(finding(ts, sf, valNode, "W606",
993
- `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`));
994
- const wrongShape = (n) => findings.push(finding(ts, sf, n, "E206",
995
- `enum reference '${key}' must be { name: '<global enum name>', value: '<enum value>' }${shapeHint}`));
996
-
997
- let refs;
998
- if (multi) {
999
- if (!ts.isArrayLiteralExpression(root)) {
1000
- if (isOpaqueExpression(ts, root)) return unverifiable();
1001
- return wrongShape(valNode);
1002
- }
1003
- if (arraySpreadElements(ts, root).length > 0) return unverifiable();
1004
- refs = root.elements.map((e) => unwrapExpr(ts, e));
1005
- } else {
1006
- refs = [root];
1007
- }
1008
-
1009
- for (const ref of refs) {
1010
- if (!ts.isObjectLiteralExpression(ref)) {
1011
- if (isOpaqueExpression(ts, ref)) { unverifiable(); continue; }
1012
- wrongShape(ref);
1013
- continue;
1014
- }
1015
- if (spreadElements(ts, ref).length > 0) { unverifiable(); continue; }
1016
- const m = objectMap(ts, ref);
1017
- if (!m.has("name") || !m.has("value")) { wrongShape(ref); continue; }
1018
- const given = stringValue(ts, m.get("name"));
1019
- if (prop.enumGlobalName && given !== null && given !== prop.enumGlobalName) {
1020
- findings.push(finding(ts, sf, m.get("name"), "E206",
1021
- `enum reference '${key}' names global enum '${given}', but the property is declared as @${multi ? "MultiEnum" : "Enum"}('${prop.enumGlobalName}') — the names must match`));
1022
- }
1023
- }
1024
- }
1025
-
1026
- function checkSeed(ts, seed, model, findings) {
1027
- const sf = seed.sf;
1028
- const entity = seed.entityName ? model.entityByName.get(seed.entityName) : undefined;
1029
- if (!entity) {
1030
- // platform entity, a typo, or simply a file outside the analyzed set — say so
1031
- findings.push(finding(ts, sf, seed.node, "W606",
1032
- `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`));
1033
- } else if (!entity.importKeyFieldsUnreadable &&
1034
- (!entity.importKeyFields || entity.importKeyFields.length === 0)) {
1035
- findings.push(finding(ts, sf, seed.node, "W605",
1036
- `entity '${seed.entityName}' has a seed but no importKeyFields — "seeds have nothing to match on and cannot stay idempotent"`));
1037
- }
1038
- if (!seed.records) return;
1039
- for (const rec of seed.records) {
1040
- if (rec.byRef) {
1041
- findings.push(finding(ts, sf, rec.node, "W606",
1042
- `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`));
1043
- continue;
1044
- }
1045
- for (const [key, valNode] of rec.map) {
1046
- if (SYSTEM_COLUMNS.includes(key)) {
1047
- findings.push(finding(ts, sf, valNode, "E201",
1048
- `seed record contains system column '${key}' — "they differ per tenant and corrupt matching"`));
1049
- }
1050
- if (ACCESS_METADATA_KEYS.includes(key)) {
1051
- findings.push(finding(ts, sf, valNode, "E202",
1052
- `seed record contains '${key}' — "access metadata, not data"`));
1053
- }
1054
- const prop = entity?.properties.get(key);
1055
- if (!prop) continue;
1056
- if (prop.kind === "many-to-one" || prop.kind === "many-to-many") {
1057
- const isNum = (n) =>
1058
- ts.isNumericLiteral(n) ||
1059
- (ts.isPrefixUnaryExpression(n) && ts.isNumericLiteral(n.operand));
1060
- const bad = isNum(valNode) ||
1061
- (ts.isArrayLiteralExpression(valNode) && valNode.elements.some(isNum));
1062
- if (bad) {
1063
- findings.push(finding(ts, sf, valNode, "E203",
1064
- `relation '${key}' referenced by numeric id — ids "do not match across tenants"; reference through the target's importKeyFields, e.g. { name: 'Default' }`));
1065
- }
1066
- }
1067
- if (prop.kind === "one-to-many" || prop.kind === "many-to-many-backref") {
1068
- findings.push(finding(ts, sf, valNode, "E204",
1069
- `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.`));
1070
- }
1071
- if (prop.kind === "enum" || prop.kind === "multi-enum") {
1072
- checkEnumRef(ts, sf, key, valNode, prop, findings);
1073
- }
1074
- }
1075
- for (const spread of rec.spreads ?? []) {
1076
- findings.push(finding(ts, sf, spread, "W606",
1077
- `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`));
1078
- }
1079
- if (rec.hasSpread) continue; // spread may deliver the import key — E205 would false-positive
1080
- if (!entity) continue;
1081
-
1082
- // $key overrides identity per record — but only if it can establish one
1083
- if (rec.map.has("$key")) {
1084
- const keyNode = rec.map.get("$key");
1085
- const keyValue = unwrapExpr(ts, keyNode);
1086
- if (ts.isObjectLiteralExpression(keyValue)) {
1087
- if (keyValue.properties.length === 0) {
1088
- findings.push(finding(ts, sf, keyNode, "E205",
1089
- `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.`));
1090
- }
1091
- } else if (isOpaqueExpression(ts, keyValue)) {
1092
- findings.push(finding(ts, sf, keyNode, "W606",
1093
- `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`));
1094
- } else {
1095
- findings.push(finding(ts, sf, keyNode, "E205",
1096
- `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.`));
1097
- }
1098
- continue;
1099
- }
1100
-
1101
- if (entity.importKeyFields?.length) {
1102
- for (const f of entity.importKeyFields) {
1103
- if (!rec.map.has(f)) {
1104
- findings.push(finding(ts, sf, rec.node, "E205",
1105
- `seed record is missing importKeyField '${f}' of '${seed.entityName}' — nothing matches ⇒ duplicate rows after every restart. Provide it or override identity with $key.`));
1106
- }
1107
- }
1108
- }
1109
- }
1110
- }
1111
-
1112
- // ── extraction: EntityModule.forFeature ──
1113
- /**
1114
- * Doc resolution order: "If the entities array is passed AND NOT EMPTY it is
1115
- * used and entitiesPath is ignored; otherwise entities are loaded from
1116
- * entitiesPath" — same for seeds/seedsPath. The two sides are independent, so
1117
- * each gets its own mode: "explicit" | "autoload" | "unverifiable".
1118
- */
1119
- function analyzeModules(ts, sf, model) {
1120
- sf.forEachChild(function walk(node) {
1121
- if (ts.isCallExpression(node) &&
1122
- ts.isPropertyAccessExpression(node.expression) &&
1123
- node.expression.name.text === "forFeature" &&
1124
- isSdkQualified(ts, sf, node.expression.expression, "EntityModule")) {
1125
- const a0 = node.arguments[0] ? unwrapExpr(ts, node.arguments[0]) : undefined;
1126
- const a0IsArray = a0 && ts.isArrayLiteralExpression(a0);
1127
- const a0IsOptions = a0 && ts.isObjectLiteralExpression(a0);
1128
- // options live in argument 1 next to an entities array, or ARE argument 0
1129
- const optionsNode = a0IsOptions ? a0 : node.arguments[1];
1130
- const opts = objectMap(ts, optionsNode);
1131
-
1132
- const side = (label, arrayNode, pathNode, unreadableNode) => {
1133
- const s = {
1134
- label, mode: "autoload", names: [], spreads: [],
1135
- node, refNode: null, paths: null, pathNode: pathNode ?? null,
1136
- };
1137
- if (unreadableNode) {
1138
- s.mode = "unverifiable";
1139
- s.refNode = unreadableNode;
1140
- return s;
1141
- }
1142
- if (arrayNode && arrayNode.elements.length > 0) {
1143
- s.mode = "explicit";
1144
- s.node = arrayNode;
1145
- s.names = arrayNode.elements
1146
- .filter((e) => ts.isIdentifier(e))
1147
- .map((e) => resolveLocalName(sf, e.text)); // aliases resolve to the exported name
1148
- s.spreads = arraySpreadElements(ts, arrayNode);
1149
- return s;
1150
- }
1151
- // absent or empty array -> the path decides; read it when it is readable
1152
- if (pathNode) {
1153
- const single = stringValue(ts, pathNode);
1154
- s.paths = single !== null ? [single] : stringArray(ts, pathNode);
1155
- }
1156
- return s;
1157
- };
1158
-
1159
- const seedsNode = opts.get("seeds") ? unwrapExpr(ts, opts.get("seeds")) : undefined;
1160
- const m = {
1161
- sf, node,
1162
- // `entities` as an OPTION is not one of the two documented shapes: the
1163
- // classes go in argument 0. Recorded so E306 can say so, instead of the
1164
- // array being silently unread — which degraded the module to "autoload"
1165
- // and switched E301/E302/E304 off for the whole run.
1166
- entitiesOptionNode: a0IsOptions ? (opts.get("entities") ?? null) : null,
1167
- entities: side(
1168
- "entitiesPath",
1169
- a0IsArray ? a0 : null,
1170
- opts.get("entitiesPath"),
1171
- a0 && !a0IsArray && !a0IsOptions ? a0 : null,
1172
- ),
1173
- seeds: side(
1174
- "seedsPath",
1175
- seedsNode && ts.isArrayLiteralExpression(seedsNode) ? seedsNode : null,
1176
- opts.get("seedsPath"),
1177
- seedsNode && !ts.isArrayLiteralExpression(seedsNode) ? seedsNode
1178
- : (a0 && !a0IsArray && !a0IsOptions && !optionsNode ? a0 : null),
1179
- ),
1180
- };
1181
- model.modules.push(m);
1182
- }
1183
- ts.forEachChild(node, walk);
1184
- });
1185
- }
1186
-
1187
- // ── rules: registration ──
1188
- /**
1189
- * E301/E302 fire on the entity/seed source file, far from the module file
1190
- * that actually needs the edit — name it explicitly so the finding is
1191
- * actionable instead of just "unregistered". `side` selects which half of
1192
- * forFeature() (`entities` or `seeds`) determines the classes-shape modules;
1193
- * paths are shown relative to rootDir when derivable, else just the basename,
1194
- * deduped, capped at 3 so the message stays short.
1195
- */
1196
- function classShapeModulePaths(modules, side, rootDir) {
1197
- const shapeModules = modules.filter((m) => m[side].mode === "explicit");
1198
- if (shapeModules.length === 0) return "";
1199
- const root = rootDir ? resolve(rootDir).replace(/\\/g, "/") : null;
1200
- const raw = [...new Set(shapeModules.map((m) => m.sf.fileName))];
1201
- const shown = raw.map((p) => {
1202
- const norm = p.replace(/\\/g, "/");
1203
- if (root && norm.startsWith(`${root}/`)) return norm.slice(root.length + 1);
1204
- const parts = norm.split("/");
1205
- return parts[parts.length - 1];
1206
- });
1207
- return shown.slice(0, 3).join(", ");
1208
- }
1209
-
1210
- function checkRegistration(ts, model, findings, rootDir) {
1211
- // E303/W606 on autoload paths — only for the side that actually autoloads:
1212
- // a path the resolution order ignores is dead config, not a mistake.
1213
- for (const m of model.modules) {
1214
- for (const side of [m.entities, m.seeds]) {
1215
- if (side.mode !== "autoload" || !side.pathNode) continue;
1216
- if (side.paths === null) {
1217
- findings.push(finding(ts, m.sf, side.pathNode, "W606",
1218
- `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`));
1219
- continue;
1220
- }
1221
- for (const p of side.paths) {
1222
- if (/(^|\/)src(\/|$)/.test(p.replace(/\\/g, "/"))) {
1223
- findings.push(finding(ts, m.sf, side.pathNode, "E303",
1224
- `${side.label} '${p}' points at src/ — autoloading reads compiled output: "entitiesPath / seedsPath points at src/ instead of compiled dist/"`));
1225
- }
1226
- }
1227
- }
1228
- }
1229
-
1230
- for (const m of model.modules) {
1231
- if (m.entitiesOptionNode) {
1232
- findings.push(finding(ts, m.sf, m.entitiesOptionNode, "E306",
1233
- `EntityModule.forFeature({ entities: [...] }) is not a supported shape — the options object takes only ` +
1234
- `seeds, entitiesPath and seedsPath. Entity classes are the FIRST argument: ` +
1235
- `forFeature([A, B], { seeds: [...] }). As written, nothing registers these classes and no table is ` +
1236
- `created for them`));
1237
- }
1238
- // Neither an explicit array nor a path: this module registers no entities,
1239
- // and E301 cannot know what is covered. Say so rather than fall silent.
1240
- if (m.entities.mode === "autoload" && !m.entities.pathNode && !m.entitiesOptionNode) {
1241
- findings.push(finding(ts, m.sf, m.entities.node, "W614",
1242
- `EntityModule.forFeature() names neither an entities array (first argument) nor entitiesPath, so this ` +
1243
- `module registers no entity classes — E301 (unregistered entity) is skipped for the whole run. Pass the ` +
1244
- `classes as the first argument, or set entitiesPath to the compiled dist/ directory`));
1245
- }
1246
- }
1247
-
1248
- if (model.entities.size > 0 && model.modules.length === 0) {
1249
- const first = [...model.entities.values()][0];
1250
- findings.push(finding(ts, first.sf, first.node.name ?? first.node, "E305",
1251
- `no EntityModule.forFeature() found — "An entity class that is never passed to forFeature() is invisible — no table is created for it"`));
1252
- return;
1253
- }
1254
-
1255
- for (const m of model.modules) {
1256
- for (const spread of m.entities.spreads) {
1257
- findings.push(finding(ts, m.sf, spread, "W606",
1258
- `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`));
1259
- }
1260
- for (const spread of m.seeds.spreads) {
1261
- findings.push(finding(ts, m.sf, spread, "W606",
1262
- `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`));
1263
- }
1264
- if (m.entities.mode === "unverifiable") {
1265
- findings.push(finding(ts, m.sf, m.entities.refNode, "W606",
1266
- `EntityModule.forFeature() entities are delivered by reference — membership cannot be statically verified: E301 (unregistered entity) is skipped; inline the array to restore checking`));
1267
- }
1268
- if (m.seeds.mode === "unverifiable" && m.seeds.refNode !== m.entities.refNode) {
1269
- findings.push(finding(ts, m.sf, m.seeds.refNode, "W606",
1270
- `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`));
1271
- }
1272
- }
1273
-
1274
- // an autoload (or unverifiable) module anywhere may cover any entity/seed not
1275
- // named explicitly — membership becomes the platform's job, so E301/E302 would
1276
- // only false-positive.
1277
- const entitiesUnknown = model.modules.some((m) => m.entities.mode !== "explicit" || m.entities.spreads.length > 0);
1278
- const seedsUnknown = model.modules.some((m) => m.seeds.mode !== "explicit" || m.seeds.spreads.length > 0);
1279
-
1280
- if (!entitiesUnknown) {
1281
- const registeredEntities = new Set(model.modules.flatMap((m) => m.entities.names));
1282
- const modulePaths = classShapeModulePaths(model.modules, "entities", rootDir);
1283
- for (const [className, info] of model.entities) {
1284
- if (!registeredEntities.has(className)) {
1285
- findings.push(finding(ts, info.sf, info.node.name ?? info.node, "E301",
1286
- `entity class '${className}' is not in any forFeature() entities array — no table will be created for it` +
1287
- (modulePaths ? ` — add it to the entities array in ${modulePaths}` : "")));
1288
- }
1289
- }
1290
- }
1291
- if (!seedsUnknown) {
1292
- const registeredSeeds = new Set(model.modules.flatMap((m) => m.seeds.names));
1293
- const modulePaths = classShapeModulePaths(model.modules, "seeds", rootDir);
1294
- for (const seed of model.seeds) {
1295
- if (!registeredSeeds.has(seed.exportName)) {
1296
- findings.push(finding(ts, seed.sf, seed.node, "E302",
1297
- `seed '${seed.exportName}' is not in any forFeature() seeds array — it will never run` +
1298
- (modulePaths ? ` — add it to the seeds array in ${modulePaths}` : "")));
1299
- }
1300
- }
1301
- }
1302
-
1303
- for (const m of model.modules) {
1304
- if (m.seeds.mode !== "explicit" || m.seeds.spreads.length > 0) continue;
1305
- const order = new Map(m.seeds.names.map((n, i) => [n, i]));
1306
- const reported = new Set();
1307
- for (const seed of model.seeds) {
1308
- if (!order.has(seed.exportName) || !seed.records) continue;
1309
- const entity = seed.entityName ? model.entityByName.get(seed.entityName) : undefined;
1310
- if (!entity) continue;
1311
- const myIdx = order.get(seed.exportName);
1312
- for (const rec of seed.records) {
1313
- for (const [key] of rec.map) {
1314
- const prop = entity.properties.get(key);
1315
- if (!prop || (prop.kind !== "many-to-one" && prop.kind !== "many-to-many") || !prop.targetClass) continue;
1316
- const target = model.entities.get(prop.targetClass);
1317
- if (!target || target === entity) continue;
1318
- // an entity may have several seeds — what matters is the EARLIEST
1319
- // registered one, since it is the one that creates the rows first
1320
- const candidates = model.seeds.filter(
1321
- (s) => s.entityName === target.entityName && order.has(s.exportName),
1322
- );
1323
- if (candidates.length === 0) continue;
1324
- const earliest = candidates.reduce((a, b) =>
1325
- order.get(a.exportName) <= order.get(b.exportName) ? a : b);
1326
- const dedupe = `${seed.exportName}->${target.entityName}`;
1327
- if (order.get(earliest.exportName) > myIdx && !reported.has(dedupe)) {
1328
- reported.add(dedupe);
1329
- findings.push(finding(ts, m.sf, m.seeds.node, "E304",
1330
- `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"`));
1331
- }
1332
- }
1333
- }
1334
- }
1335
- }
1336
- }
1337
-
1338
- // ── rules: tsconfig ──
1339
- function checkTsconfig(ts, rootDir, findings) {
1340
- if (!rootDir) return;
1341
- // ts.readConfigFile compares the path it is given against its own normalized
1342
- // form while attaching a syntax diagnostic — a Windows path throws a Debug
1343
- // Failure there, so normalize, and never let this check kill the run.
1344
- try {
1345
- const root = resolve(rootDir).replace(/\\/g, "/");
1346
- const p = `${root}/tsconfig.json`;
1347
- if (!existsSync(p)) {
1348
- findings.push({
1349
- file: root, line: 1, col: 1, code: "W608", level: "warning",
1350
- message: `no tsconfig.json at ${root} — cannot verify experimentalDecorators/emitDecoratorMetadata, both of which entities rely on`,
1351
- });
1352
- return;
1353
- }
1354
- const read = ts.readConfigFile(p, (f) => readFileSync(f, "utf-8"));
1355
- if (read.error) return;
1356
- const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, root);
1357
- const missing = [];
1358
- if (!parsed.options.experimentalDecorators) missing.push("experimentalDecorators");
1359
- if (!parsed.options.emitDecoratorMetadata) missing.push("emitDecoratorMetadata");
1360
- if (missing.length) {
1361
- findings.push({
1362
- file: p, line: 1, col: 1, code: "E401", level: "error",
1363
- message: `tsconfig.json must enable ${missing.join(" and ")} — entities rely on decorator metadata`,
1364
- });
1365
- }
1366
- } catch {
1367
- /* unreadable/malformed tsconfig — degrade silently rather than crash the run */
1368
- }
1369
- }
1370
-
1371
- // ── SDK catalog: real @suppa/sdk typings when resolvable, doc list otherwise ──
1372
- function loadSdkCatalog(ts, rootDir) {
1373
- const catalog = {
1374
- entityOptions: [...DOC_ENTITY_OPTIONS],
1375
- columnOptions: [...DOC_COLUMN_OPTIONS],
1376
- fieldTypes: { ...DOC_FIELD_TYPES },
1377
- source: "doc",
1378
- };
1379
- if (!rootDir) return catalog;
1380
- let dir = resolve(rootDir);
1381
- let sdkDir = null;
1382
- for (let i = 0; i < 8; i++) {
1383
- const cand = join(dir, "node_modules", "@suppa", "sdk");
1384
- if (existsSync(cand)) { sdkDir = cand; break; }
1385
- const parent = dirname(dir);
1386
- if (parent === dir) break;
1387
- dir = parent;
1388
- }
1389
- if (!sdkDir) return catalog;
1390
- let typesPath = join(sdkDir, "index.d.ts");
1391
- try {
1392
- const pkg = JSON.parse(readFileSync(join(sdkDir, "package.json"), "utf-8"));
1393
- if (pkg.types || pkg.typings) typesPath = join(sdkDir, pkg.types ?? pkg.typings);
1394
- } catch { /* fall back to index.d.ts */ }
1395
- if (!existsSync(typesPath)) return catalog;
1396
- try {
1397
- const sf = ts.createSourceFile(typesPath, readFileSync(typesPath, "utf-8"), ts.ScriptTarget.Latest, true);
1398
- const fieldTypes = {};
1399
- let entityOptions = [];
1400
- let columnOptions = [];
1401
- sf.forEachChild(function walk(node) {
1402
- if (ts.isEnumDeclaration(node) && node.name.text === "FieldTypeEnum") {
1403
- for (const m of node.members) {
1404
- const name = ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)
1405
- ? m.name.text : m.name.getText(sf);
1406
- fieldTypes[name] = m.initializer && ts.isStringLiteral(m.initializer)
1407
- ? m.initializer.text : name;
1408
- }
1409
- }
1410
- if (ts.isInterfaceDeclaration(node)) {
1411
- const props = node.members
1412
- .filter((mm) => ts.isPropertySignature(mm) && mm.name)
1413
- .map((mm) => mm.name.getText(sf).replace(/['"]/g, ""));
1414
- if (/EntityOptions$/i.test(node.name.text)) entityOptions = props;
1415
- if (/ColumnOptions$/i.test(node.name.text)) columnOptions = props;
1416
- }
1417
- ts.forEachChild(node, walk);
1418
- });
1419
- let got = 0;
1420
- // fieldTypes are enum VALUES, not option names — an older SDK enum member
1421
- // set is the true, current set for this install, so replace outright.
1422
- // entityOptions/columnOptions are OPTION NAMES: an SDK whose typings
1423
- // predate a doc-documented option (e.g. relationEntityName) must not make
1424
- // that option look unknown (E501) — union with the doc list instead of
1425
- // replacing it (F1).
1426
- if (Object.keys(fieldTypes).length) { catalog.fieldTypes = fieldTypes; got++; }
1427
- if (entityOptions.length) {
1428
- catalog.entityOptions = [...new Set([...entityOptions, ...DOC_ENTITY_OPTIONS])];
1429
- got++;
1430
- }
1431
- if (columnOptions.length) {
1432
- catalog.columnOptions = [...new Set([...columnOptions, ...DOC_COLUMN_OPTIONS])];
1433
- got++;
1434
- }
1435
- catalog.source = got === 3 ? "sdk" : got > 0 ? "partial-sdk" : "doc";
1436
- } catch { /* typings unreadable — doc fallback stands */ }
1437
- return catalog;
1438
- }
1439
-
1440
- // ── public API ──
1441
- export function validateSchema({ files = [], rootDir = null } = {}) {
1442
- const ts = loadTypescript(rootDir);
1443
- const sdk = loadSdkCatalog(ts, rootDir);
1444
- const model = {
1445
- entities: new Map(), entityByName: new Map(),
1446
- seeds: [], modules: [], stringEnums: new Map(),
1447
- enumDeclarations: [], stringLiteralCounts: new Map(),
1448
- };
1449
- const findings = [];
1450
- // the CLI deduped; the exported API did not, and duplicated seeds duplicated findings
1451
- const uniqueFiles = [...new Set(files.map((f) => resolve(f)))];
1452
- const sources = uniqueFiles.map((f) =>
1453
- ts.createSourceFile(f, readFileSync(f, "utf-8"), ts.ScriptTarget.Latest, true),
1454
- );
1455
- for (const sf of sources) analyzeImports(ts, sf);
1456
- for (const sf of sources) analyzeEnums(ts, sf, model);
1457
- for (const sf of sources) {
1458
- analyzeEntities(ts, sf, model);
1459
- analyzeSeeds(ts, sf, model);
1460
- analyzeModules(ts, sf, model);
1461
- }
1462
- // createSeed(EnumName.Member) passes the member's VALUE; the member name is
1463
- // only a fallback for enums declared outside the analyzed file set
1464
- for (const seed of model.seeds) {
1465
- if (seed.entityName === null && seed.enumRef) {
1466
- seed.entityName =
1467
- model.stringEnums.get(seed.enumRef.enumName)?.get(seed.enumRef.member) ??
1468
- seed.enumRef.member;
1469
- }
1470
- }
1471
- checkEnumDeclarations(ts, model, findings);
1472
- for (const info of model.entities.values()) checkEntity(ts, info, sdk, model, findings);
1473
- for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
1474
- checkRegistration(ts, model, findings, rootDir);
1475
- checkTsconfig(ts, rootDir, findings);
1476
- findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.col - b.col);
1477
- return {
1478
- findings,
1479
- errors: findings.filter((f) => f.level === "error"),
1480
- warnings: findings.filter((f) => f.level === "warning"),
1481
- sdkSource: sdk.source,
1482
- };
1483
- }
1484
-
1485
- // ── discovery ──
1486
- export function discoverFiles(rootDir) {
1487
- const files = [];
1488
- (function walk(dir) {
1489
- for (const name of readdirSync(dir)) {
1490
- if (name === "node_modules" || name === "dist" || name.startsWith(".")) continue;
1491
- const p = join(dir, name);
1492
- if (statSync(p).isDirectory()) {
1493
- walk(p);
1494
- } else if (name.endsWith(".entity.ts") || name.endsWith(".seed.ts")) {
1495
- files.push(p);
1496
- } else if (name.endsWith(".ts") &&
1497
- readFileSync(p, "utf-8").includes("EntityModule.forFeature")) {
1498
- files.push(p);
1499
- }
1500
- }
1501
- })(resolve(rootDir));
1502
- return files.sort();
1503
- }
1504
-
1505
- // ── CLI ──
1506
- const isMain =
1507
- process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
1508
- if (isMain) {
1509
- const args = process.argv.slice(2);
1510
- if (args.length === 0) {
1511
- console.error("usage: node validate-suppa-schema.mjs <app-root-or-files...>");
1512
- process.exit(2);
1513
- }
1514
- let rootDir = null;
1515
- const files = [];
1516
- for (const a of args) {
1517
- const p = resolve(a);
1518
- if (!existsSync(p)) {
1519
- console.error(`validate-suppa-schema: path not found: ${a}`);
1520
- process.exit(2);
1521
- }
1522
- if (statSync(p).isDirectory()) {
1523
- rootDir = rootDir ?? p;
1524
- files.push(...discoverFiles(p));
1525
- } else {
1526
- files.push(p);
1527
- }
1528
- }
1529
- const dedupedFiles = [...new Set(files)];
1530
- let res;
1531
- try {
1532
- res = validateSchema({ files: dedupedFiles, rootDir });
1533
- } catch (err) {
1534
- // A missing/unusable toolchain is the caller's to fix: one actionable line,
1535
- // same exit code as the other argument problems. Anything else is a bug in
1536
- // this validator and keeps its stack trace.
1537
- if (err?.code !== "SUPPA_VALIDATOR_ENV") throw err;
1538
- console.error(err.message);
1539
- process.exit(2);
1540
- }
1541
- for (const f of res.findings) {
1542
- console.log(
1543
- `${displayPath(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`,
1544
- );
1545
- }
1546
- console.log(
1547
- `\n${res.errors.length} error(s), ${res.warnings.length} warning(s) across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
1548
- );
1549
- process.exit(res.errors.length > 0 ? 1 : 0);
1550
- }
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, isAbsolute, 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
+ /**
23
+ * Field options the platform already applies. Writing one of these with its
24
+ * default value adds noise to every field and says nothing — only a DEPARTURE
25
+ * from the default is worth declaring. (W612.)
26
+ */
27
+ export const DEFAULT_FIELD_OPTIONS = {
28
+ canGroup: true,
29
+ canSort: true,
30
+ showInTable: true,
31
+ editFromTable: true,
32
+ canFilter: true,
33
+ readOnly: false,
34
+ searchable: false,
35
+ };
36
+ export const DOC_COLUMN_OPTIONS = ["type", "subType", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask",
37
+ // Field options. The decorator tables do not list them, but migrations.txt:245
38
+ // names four of them as options a column carries — encryption makes "the
39
+ // searchable, canFilter, canSort and canGroup options become false" — and the
40
+ // builder's Field Options table (api-entity-builder-builder.txt:66-73) gives
41
+ // all seven plus searchPriority. Without these the validator hard-errored
42
+ // (E502) on a legitimate `searchable: true`.
43
+ //
44
+ // Both spellings are accepted: flat on the decorator, and nested under
45
+ // `options` (builder.txt:60 — "options | object | false | Field options
46
+ // configuration", and DOC_ENTITY_OPTIONS already whitelists `options` on
47
+ // @Entity). searchPriority is listed separately because it is a NUMBER
48
+ // (builder.txt:67, "1-4"), so the boolean defaults map cannot carry it.
49
+ // A repo's own SDK typings still override this fallback.
50
+ "options", "searchPriority",
51
+ ...Object.keys(DEFAULT_FIELD_OPTIONS)];
52
+ /**
53
+ * The doc's subType matrix — "it means three unrelated things depending on the
54
+ * base type". Keyed by the CANONICAL FieldTypeEnum value, so E112 can be decided
55
+ * from whatever `checkColumn` resolved `type` to. The Enum/MultiEnum row of that
56
+ * matrix is deliberately absent: `subType` there is the enum's global name, set
57
+ * by @Enum()/@MultiEnum() and never written by hand — that is E113, not E112.
58
+ */
59
+ export const DOC_SUBTYPES_BY_TYPE = {
60
+ timestamp: ["date", "time", "timestamp"],
61
+ text: ["encrypted"],
62
+ };
63
+ export const DOC_FIELD_TYPES = {
64
+ Text: "text", Numeric: "numeric", Integer: "integer", Serial: "serial",
65
+ Boolean: "boolean", Timestamp: "timestamp", JSON: "json", UUID: "uuid",
66
+ MultiLang: "multi-language", Bytea: "bytea", TsVector: "tsvector",
67
+ MultiType: "multi-type", Icon: "icon",
68
+ };
69
+ const NON_SCALAR_TYPE_STRINGS = new Set([
70
+ "enum", "multi-enum", "file", "multi-file",
71
+ "many-to-one", "one-to-many", "many-to-many", "many-to-many-backref",
72
+ "relation", "attachment",
73
+ ]);
74
+ const RELATION_KIND_BY_DECORATOR = {
75
+ ManyToOne: "many-to-one", ManyToMany: "many-to-many",
76
+ ManyToManyBackRef: "many-to-many-backref", OneToMany: "one-to-many",
77
+ };
78
+ const RELATION_KINDS = new Set(Object.values(RELATION_KIND_BY_DECORATOR));
79
+ // `inverse` is REQUIRED on these two (the reverse sides) and OPTIONAL — usually
80
+ // omitted — on @ManyToOne/@ManyToMany; W609 only ever fires on the latter pair.
81
+ const OPTIONAL_INVERSE_DECORATORS = new Set(["ManyToOne", "ManyToMany"]);
82
+
83
+ /**
84
+ * How many rows the property holds — which fixes the TypeScript type it must
85
+ * carry. @ManyToOne points at ONE row (`owner: ProductMatrixEntity`); the other
86
+ * three hold many (`envs: ApplicationEnvsEntity[]`).
87
+ */
88
+ const RELATION_ARITY = {
89
+ ManyToOne: "one",
90
+ ManyToMany: "many",
91
+ ManyToManyBackRef: "many",
92
+ OneToMany: "many",
93
+ };
94
+
95
+ const ENUM_DECORATORS = new Set(["Enum", "MultiEnum"]);
96
+ const FILE_DECORATORS = new Set(["File", "MultiFile"]);
97
+
98
+ // ── typescript resolution: target app, then cwd, then this package ──
99
+ // The app repo is the expected source: a Suppa application compiles to dist/,
100
+ // so it has typescript. This package lists typescript as a devDependency only,
101
+ // so the last candidate resolves in a checkout but never in an install.
102
+ export function loadTypescript(rootDir) {
103
+ const froms = [];
104
+ if (rootDir) froms.push(join(resolve(rootDir), "package.json"));
105
+ froms.push(join(process.cwd(), "package.json"));
106
+ froms.push(import.meta.url);
107
+ let sawStub = false;
108
+ for (const from of froms) {
109
+ let mod;
110
+ try {
111
+ mod = createRequire(from)("typescript");
112
+ } catch {
113
+ continue; // not resolvable from here — try the next candidate
114
+ }
115
+ // Resolvability is NOT proof the compiler API is there. TypeScript 7 — what
116
+ // plain `npm i -D typescript` installs today — maps exports["."] to
117
+ // lib/version.cjs, which exports only { version, versionMajorMinor }; the
118
+ // parser moved behind ./unstable/*. That require SUCCEEDS and used to be
119
+ // handed straight to the parser, which then died on `ts.ScriptTarget.Latest`
120
+ // being undefined. Check the two members this validator actually uses, and
121
+ // keep looking: a usable TS 5 further down the list still rescues the run.
122
+ // Every entity/column/relation/seed rule reaches the AST through
123
+ // decoratorsOf, which calls canHaveDecorators/getDecorators (TypeScript
124
+ // 4.8+). Guarding only createSourceFile/ScriptTarget let TS <= 4.7 through,
125
+ // where those are undefined: every node yielded zero decorators, the model
126
+ // came out empty, and the run reported "0 error(s)" on unparsed schema.
127
+ const REQUIRED = ["createSourceFile", "canHaveDecorators", "getDecorators", "forEachChild",
128
+ "readConfigFile", "isIdentifier", "isCallExpression"];
129
+ if (REQUIRED.every((k) => typeof mod?.[k] === "function") && mod?.ScriptTarget && mod?.SyntaxKind) {
130
+ return mod;
131
+ }
132
+ sawStub = true;
133
+ }
134
+ // Tagged so the CLI can report it as an environment problem — one actionable
135
+ // line and exit 2 — instead of an uncaught stack trace.
136
+ throw Object.assign(new Error(
137
+ sawStub
138
+ ? "validate-suppa-schema: the 'typescript' found here is TypeScript 7 (or newer), whose " +
139
+ "main entry exports only version info — it has no createSourceFile/ScriptTarget, so " +
140
+ "this validator cannot parse with it. Install the 5.x line in the app repo being " +
141
+ "validated: `npm i -D typescript@5`."
142
+ : "validate-suppa-schema: cannot resolve 'typescript'. It is read from the app repo " +
143
+ "being validated (a Suppa application compiles with tsc, so it normally has it). " +
144
+ "Install it there — `npm i -D typescript@5` — or run this from a directory where it " +
145
+ "resolves.",
146
+ ), { code: "SUPPA_VALIDATOR_ENV" });
147
+ }
148
+
149
+ /**
150
+ * Path to print for a finding. A relative path is friendlier and clickable, but
151
+ * only when it actually stays inside cwd — across drives or above cwd, Windows
152
+ * `relative()` yields an unusable `..\..\..` chain with no drive letter.
153
+ */
154
+ export function displayPath(cwd, file) {
155
+ const rel = relative(cwd, file);
156
+ return !rel || rel.startsWith("..") || isAbsolute(rel) ? file : rel;
157
+ }
158
+
159
+ // ── small AST helpers ──
160
+ function finding(ts, sf, node, code, message) {
161
+ const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
162
+ return {
163
+ file: sf.fileName, line: line + 1, col: character + 1, code,
164
+ level: code.startsWith("W") ? "warning" : "error", message,
165
+ };
166
+ }
167
+ function decoratorsOf(ts, node) {
168
+ // Not optional-chained on purpose: a TypeScript without this API must throw
169
+ // here rather than return [] and let the whole run pass as "0 errors".
170
+ // loadTypescript refuses such a build up front; this is the backstop.
171
+ return (ts.canHaveDecorators(node) ? ts.getDecorators(node) : undefined) ?? [];
172
+ }
173
+ function decoratorCall(ts, dec, sf) {
174
+ const e = dec.expression;
175
+ if (ts.isCallExpression(e)) {
176
+ const name = calleeIdentity(ts, sf, e.expression);
177
+ return name ? { name, args: [...e.arguments] } : null;
178
+ }
179
+ const name = calleeIdentity(ts, sf, e);
180
+ return name ? { name, args: [] } : null;
181
+ }
182
+ function objectMap(ts, node) {
183
+ const map = new Map();
184
+ if (!node || !ts.isObjectLiteralExpression(node)) return map;
185
+ for (const p of node.properties) {
186
+ if (ts.isPropertyAssignment(p)) {
187
+ const name =
188
+ ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : null;
189
+ if (name !== null) map.set(name, p.initializer);
190
+ } else if (ts.isShorthandPropertyAssignment(p)) {
191
+ map.set(p.name.text, p.name);
192
+ }
193
+ }
194
+ return map;
195
+ }
196
+ function stringValue(ts, node) {
197
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
198
+ ? node.text
199
+ : null;
200
+ }
201
+ function stringArray(ts, node) {
202
+ if (!node || !ts.isArrayLiteralExpression(node)) return null;
203
+ const out = [];
204
+ for (const el of node.elements) {
205
+ const s = stringValue(ts, el);
206
+ if (s === null) return null;
207
+ out.push(s);
208
+ }
209
+ return out;
210
+ }
211
+ function thunkTarget(ts, sf, arg) {
212
+ if (arg && ts.isArrowFunction(arg)) {
213
+ // `() => (Target)` and `() => Target as any` are thunks too; reading
214
+ // arg.body raw reported E105 "a direct class reference breaks circular
215
+ // imports" about code that passed a perfectly good thunk — and, worse, left
216
+ // targetClass null, which silently switched the E115 type check off.
217
+ const b = unwrapExpr(ts, arg.body);
218
+ if (ts.isIdentifier(b)) return resolveLocalName(sf, b.text);
219
+ if (ts.isPropertyAccessExpression(b)) return b.name.text;
220
+ }
221
+ return null;
222
+ }
223
+ /**
224
+ * The `inverse` selector — `(target, inverse, options?)` — is whichever
225
+ * function expression sits in argument position 1; it is distinguished from
226
+ * `(target, options?)` by NOT being an object literal.
227
+ */
228
+ function isFunctionLike(ts, n) {
229
+ return !!n && (ts.isArrowFunction(n) || ts.isFunctionExpression(n));
230
+ }
231
+ /**
232
+ * The TypeScript type a property declares, reduced to what the relation rules
233
+ * need: the entity name it names, whether it is an array, and whether it is
234
+ * optional. `null` when the property carries no annotation at all.
235
+ *
236
+ * Reads `T`, `T[]`, `Array<T>`, and unions with `null`/`undefined` (`T | null`);
237
+ * anything else yields `{name: null}` so the caller reports "cannot read"
238
+ * rather than inventing a mismatch.
239
+ */
240
+ function propertyTypeInfo(ts, member) {
241
+ const node = member.type;
242
+ if (!node) return null;
243
+ const sf = member.getSourceFile();
244
+ let t = node;
245
+ let nullable = !!member.questionToken;
246
+ const unwrapParens = (x) => {
247
+ while (ts.isParenthesizedTypeNode(x)) x = x.type;
248
+ return x;
249
+ };
250
+ t = unwrapParens(t);
251
+ if (ts.isUnionTypeNode(t)) {
252
+ const parts = t.types.filter((p) => {
253
+ const isNullish =
254
+ p.kind === ts.SyntaxKind.NullKeyword ||
255
+ p.kind === ts.SyntaxKind.UndefinedKeyword ||
256
+ (ts.isLiteralTypeNode(p) && p.literal.kind === ts.SyntaxKind.NullKeyword);
257
+ if (isNullish) nullable = true;
258
+ return !isNullish;
259
+ });
260
+ if (parts.length !== 1) return { node, name: null, isArray: false, nullable };
261
+ t = unwrapParens(parts[0]);
262
+ }
263
+ let isArray = false;
264
+ // `readonly T[]` is a type operator wrapping the array.
265
+ if (ts.isTypeOperatorNode(t) && t.operator === ts.SyntaxKind.ReadonlyKeyword) {
266
+ t = unwrapParens(t.type);
267
+ }
268
+ if (ts.isArrayTypeNode(t)) {
269
+ isArray = true;
270
+ t = unwrapParens(t.elementType);
271
+ } else if (
272
+ ts.isTypeReferenceNode(t) &&
273
+ ts.isIdentifier(t.typeName) &&
274
+ (t.typeName.text === "Array" || t.typeName.text === "ReadonlyArray") &&
275
+ t.typeArguments?.length === 1
276
+ ) {
277
+ isArray = true;
278
+ t = unwrapParens(t.typeArguments[0]);
279
+ }
280
+ let name = null;
281
+ if (ts.isTypeReferenceNode(t)) {
282
+ // Resolve exactly as thunkTarget does, or the two sides compare a local
283
+ // alias against an exported name and E115 hard-errors on correct code —
284
+ // telling the author to write a name that is not even bound in the file.
285
+ // `import { IconsEntity as Icons }` -> Icons resolves to IconsEntity;
286
+ // `ns.IconsEntity` -> the rightmost segment, like thunkTarget's
287
+ // PropertyAccess branch.
288
+ name = ts.isIdentifier(t.typeName)
289
+ ? resolveLocalName(sf, t.typeName.text)
290
+ : (ts.isQualifiedName(t.typeName) ? t.typeName.right.text : null);
291
+ }
292
+ return { node, name, isArray, nullable };
293
+ }
294
+ /** A boolean literal's value, or null when the node is not one. */
295
+ function booleanValue(ts, node) {
296
+ if (!node) return null;
297
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
298
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
299
+ return null;
300
+ }
301
+ /**
302
+ * PascalCase: starts with an uppercase letter, letters and digits only, no
303
+ * separators. Unicode-aware — an ASCII-only test flagged 'Значення' and then
304
+ * suggested 'Значення', a warning with no action in it.
305
+ */
306
+ function isPascalCase(name) {
307
+ return /^\p{Lu}[\p{L}\p{N}]*$/u.test(name);
308
+ }
309
+ /**
310
+ * The property name an inverse selector's body accesses off its own single
311
+ * parameter — `(t) => t.prop` (or `(t) => { return t.prop; }`) -> "prop".
312
+ * Anything else (destructuring, no single-parameter self-access, …) is not a
313
+ * shape this AST-only checker can read, so it returns null rather than guess.
314
+ */
315
+ function inverseAccessedProperty(ts, fn) {
316
+ if (!fn || fn.parameters.length !== 1) return null;
317
+ const param = fn.parameters[0].name;
318
+ if (!ts.isIdentifier(param)) return null;
319
+ let body = fn.body;
320
+ if (ts.isBlock(body)) {
321
+ const stmts = body.statements;
322
+ if (stmts.length !== 1 || !ts.isReturnStatement(stmts[0]) || !stmts[0].expression) return null;
323
+ body = stmts[0].expression;
324
+ }
325
+ if (ts.isPropertyAccessExpression(body) && ts.isIdentifier(body.expression) &&
326
+ body.expression.text === param.text) {
327
+ return body.name.text;
328
+ }
329
+ return null;
330
+ }
331
+ function spreadElements(ts, node) {
332
+ if (!node || !ts.isObjectLiteralExpression(node)) return [];
333
+ return node.properties.filter((p) => ts.isSpreadAssignment(p));
334
+ }
335
+ function arraySpreadElements(ts, node) {
336
+ if (!node || !ts.isArrayLiteralExpression(node)) return [];
337
+ return node.elements.filter((e) => ts.isSpreadElement(e));
338
+ }
339
+
340
+ // ── identity: aliased named imports and '@suppa/sdk' namespace imports ──
341
+ // `import { Things as Thing }` / `import * as sdk from '@suppa/sdk'` name the
342
+ // very same declarations; matching bare identifiers alone misses them.
343
+ function analyzeImports(ts, sf) {
344
+ const alias = new Map(); // local name -> imported (exported) name
345
+ const namespaces = new Set(); // local name of `import * as X from '@suppa/sdk'`
346
+ for (const st of sf.statements) {
347
+ if (!ts.isImportDeclaration(st) || !st.importClause) continue;
348
+ const from = ts.isStringLiteral(st.moduleSpecifier) ? st.moduleSpecifier.text : "";
349
+ const bindings = st.importClause.namedBindings;
350
+ if (bindings && ts.isNamespaceImport(bindings)) {
351
+ if (from === "@suppa/sdk") namespaces.add(bindings.name.text);
352
+ } else if (bindings && ts.isNamedImports(bindings)) {
353
+ for (const el of bindings.elements) {
354
+ alias.set(el.name.text, (el.propertyName ?? el.name).text);
355
+ }
356
+ }
357
+ }
358
+ sf.suppaImports = { alias, namespaces };
359
+ }
360
+ function importsOf(sf) {
361
+ return sf.suppaImports ?? { alias: new Map(), namespaces: new Set() };
362
+ }
363
+ /** local identifier text -> the name it was imported under (or itself) */
364
+ function resolveLocalName(sf, text) {
365
+ return importsOf(sf).alias.get(text) ?? text;
366
+ }
367
+ /** node is `name`, an alias of it, or `<sdkNamespace>.name` */
368
+ function isSdkQualified(ts, sf, node, name) {
369
+ if (!node) return false;
370
+ if (ts.isIdentifier(node)) return resolveLocalName(sf, node.text) === name;
371
+ if (ts.isPropertyAccessExpression(node) && node.name.text === name &&
372
+ ts.isIdentifier(node.expression)) {
373
+ return importsOf(sf).namespaces.has(node.expression.text);
374
+ }
375
+ return false;
376
+ }
377
+ function calleeIdentity(ts, sf, expr) {
378
+ if (ts.isIdentifier(expr)) return resolveLocalName(sf, expr.text);
379
+ if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression) &&
380
+ importsOf(sf).namespaces.has(expr.expression.text)) {
381
+ return expr.name.text;
382
+ }
383
+ return null;
384
+ }
385
+
386
+ // ── string-ness of an expression (no type checker available) ──
387
+ /** provably NOT a string at runtime */
388
+ function isProvableNonString(ts, n) {
389
+ if (n.kind === ts.SyntaxKind.TrueKeyword || n.kind === ts.SyntaxKind.FalseKeyword ||
390
+ n.kind === ts.SyntaxKind.NullKeyword) return true;
391
+ if (ts.isNumericLiteral(n) || ts.isBigIntLiteral(n)) return true;
392
+ if (ts.isPrefixUnaryExpression(n) &&
393
+ (ts.isNumericLiteral(n.operand) || ts.isBigIntLiteral(n.operand))) return true;
394
+ if (ts.isArrayLiteralExpression(n) || ts.isObjectLiteralExpression(n)) return true;
395
+ if (ts.isNewExpression(n)) return true;
396
+ return false;
397
+ }
398
+ /** provably a string at runtime (literal, template, or a `+` chain with one) */
399
+ function isProvableString(ts, n) {
400
+ if (ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n) ||
401
+ ts.isTemplateExpression(n)) return true;
402
+ if (ts.isParenthesizedExpression(n)) return isProvableString(ts, n.expression);
403
+ if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.PlusToken) {
404
+ return isProvableString(ts, n.left) || isProvableString(ts, n.right);
405
+ }
406
+ return false;
407
+ }
408
+ /** strip `(x)`, `x as T`, `x!` — they do not change the runtime value */
409
+ function unwrapExpr(ts, n) {
410
+ let cur = n;
411
+ while (cur && (ts.isParenthesizedExpression(cur) || ts.isAsExpression(cur) ||
412
+ ts.isNonNullExpression(cur) || ts.isSatisfiesExpression?.(cur) === true)) {
413
+ cur = cur.expression;
414
+ }
415
+ return cur;
416
+ }
417
+ /** an expression whose value this AST-only checker cannot see */
418
+ function isOpaqueExpression(ts, n) {
419
+ return ts.isIdentifier(n) || ts.isCallExpression(n) ||
420
+ ts.isPropertyAccessExpression(n) || ts.isElementAccessExpression(n) ||
421
+ ts.isAwaitExpression(n) || ts.isConditionalExpression(n);
422
+ }
423
+
424
+ // ── extraction: entities ──
425
+ function analyzeEntities(ts, sf, model) {
426
+ sf.forEachChild(function walk(node) {
427
+ if (ts.isClassDeclaration(node)) {
428
+ const decs = decoratorsOf(ts, node).map((d) => decoratorCall(ts, d, sf)).filter(Boolean);
429
+ const entityDec = decs.find((d) => d.name === "Entity");
430
+ if (entityDec) {
431
+ const className = node.name ? node.name.text : "<anonymous>";
432
+ const options = objectMap(ts, entityDec.args[0]);
433
+ const keysNode = options.get("importKeyFields");
434
+ const info = {
435
+ className,
436
+ entityName: stringValue(ts, options.get("name")) ?? className,
437
+ sf, node, options, optionsNode: entityDec.args[0],
438
+ importKeyFields: stringArray(ts, keysNode),
439
+ // present but not a readable array of string literals: the key checks
440
+ // cannot run, but claiming it is missing would be a lie (CB-8)
441
+ importKeyFieldsUnreadable: !!keysNode && stringArray(ts, keysNode) === null,
442
+ importKeyFieldsNode: keysNode ?? null,
443
+ hasKey: options.has("key"),
444
+ properties: new Map(),
445
+ columnNames: new Set(), // literal `name` options of @Column/relations
446
+ };
447
+ for (const member of node.members) {
448
+ if (!ts.isPropertyDeclaration(member) || !member.name) continue;
449
+ const propName =
450
+ ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)
451
+ ? member.name.text
452
+ : member.name.getText(sf);
453
+ for (const d of decoratorsOf(ts, member).map((x) => decoratorCall(ts, x, sf)).filter(Boolean)) {
454
+ if (d.name === "Column") {
455
+ const columnOptions = objectMap(ts, d.args[0]);
456
+ info.properties.set(propName, {
457
+ kind: "column", node: member, decorator: d,
458
+ columnOptions, optionsNode: d.args[0],
459
+ nameNode: columnOptions.get("name") ?? null,
460
+ });
461
+ } else if (ENUM_DECORATORS.has(d.name)) {
462
+ // (globalName?, Enum, titles?, options?) — the options object is
463
+ // the LAST argument when that is an object literal. An inline
464
+ // titles map occupies the same slot when options are omitted, so
465
+ // this node is only ever read for keys options own (E113's
466
+ // `subType`); a titles map never carries one.
467
+ const last = d.args[d.args.length - 1];
468
+ const enumOptionsNode =
469
+ d.args.length >= 2 && last && ts.isObjectLiteralExpression(last) ? last : null;
470
+ info.properties.set(propName, {
471
+ kind: d.name === "Enum" ? "enum" : "multi-enum",
472
+ node: member, decorator: d,
473
+ enumGlobalName: stringValue(ts, d.args[0]),
474
+ optionsNode: enumOptionsNode,
475
+ enumOptions: objectMap(ts, enumOptionsNode),
476
+ });
477
+ } else if (FILE_DECORATORS.has(d.name)) {
478
+ info.properties.set(propName, {
479
+ kind: d.name === "File" ? "file" : "multi-file",
480
+ node: member, decorator: d,
481
+ });
482
+ } else if (d.name in RELATION_KIND_BY_DECORATOR) {
483
+ // (target, options?) or (target, inverse, options?) — the options
484
+ // object is whichever trailing argument is an object literal; the
485
+ // inverse (when present) is argument 1 whenever it is NOT that
486
+ // options object, i.e. it is an arrow/function expression instead.
487
+ const relOptions = objectMap(
488
+ ts, [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)),
489
+ );
490
+ const inverseNode = isFunctionLike(ts, d.args[1]) ? d.args[1] : null;
491
+ info.properties.set(propName, {
492
+ kind: RELATION_KIND_BY_DECORATOR[d.name],
493
+ node: member, decorator: d,
494
+ targetClass: thunkTarget(ts, sf, d.args[0]),
495
+ nameNode: relOptions.get("name") ?? null,
496
+ inverseNode,
497
+ relOptions,
498
+ optionsNode: [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)) ?? null,
499
+ typeInfo: propertyTypeInfo(ts, member),
500
+ });
501
+ }
502
+ }
503
+ const prop = info.properties.get(propName);
504
+ const colName = prop && stringValue(ts, prop.nameNode);
505
+ if (colName) info.columnNames.add(colName);
506
+ }
507
+ model.entities.set(className, info);
508
+ model.entityByName.set(info.entityName, info);
509
+ }
510
+ }
511
+ ts.forEachChild(node, walk);
512
+ });
513
+ }
514
+
515
+ // ── rules: tabular parts ──
516
+ /**
517
+ * Doc: "Three things make an entity a tabular part. All three are required,
518
+ * and the platform does not infer any of them: type: 'tabular-part' on
519
+ * @Entity(), relationEntityName — the name of the parent entity, and a
520
+ * @ManyToOne field named owner pointing at the parent class."
521
+ * Conversely, relationEntityName without type: 'tabular-part' is the doc's
522
+ * own mistake row: "type: 'tabular-part' or relationEntityName is missing,
523
+ * so it is listed under /related instead."
524
+ */
525
+ function checkTabularPart(ts, info, model, findings) {
526
+ const sf = info.sf;
527
+ const anchor = info.node.name ?? info.node;
528
+ 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)`;
529
+
530
+ const hasType = info.options.has("type");
531
+ const typeNode = info.options.get("type");
532
+ const typeLiteral = hasType ? stringValue(ts, typeNode) : null;
533
+ const typeUnreadable = hasType && typeLiteral === null;
534
+
535
+ const hasRelName = info.options.has("relationEntityName");
536
+ const relNode = info.options.get("relationEntityName");
537
+ const relLiteral = hasRelName ? stringValue(ts, relNode) : null;
538
+ const relUnreadable = hasRelName && relLiteral === null;
539
+
540
+ // an unreadable type/relationEntityName (identifier, expression, …) means
541
+ // this checker cannot tell whether the entity is a tabular part at all —
542
+ // warn instead of guessing E108 one way or the other.
543
+ if (typeUnreadable || relUnreadable) {
544
+ const badNode = typeUnreadable ? typeNode : relNode;
545
+ const badOpt = typeUnreadable ? "type" : "relationEntityName";
546
+ findings.push(finding(ts, sf, badNode, "W606",
547
+ `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`));
548
+ return;
549
+ }
550
+
551
+ const isTabularPart = typeLiteral === "tabular-part";
552
+ // `owner` is a @ManyToOne relation named 'owner' by PROPERTY name, or one
553
+ // whose literal @ManyToOne({ name: 'owner' }) column-name option is 'owner'
554
+ // (F4) — E106 (DA-2) already accepts a column name as a field identity, so
555
+ // E108's notion of "the owner relation" must agree.
556
+ const ownerProp = [...info.properties.entries()].find(
557
+ ([propName, p]) => p.kind === "many-to-one" &&
558
+ (propName === "owner" || stringValue(ts, p.nameNode) === "owner"),
559
+ )?.[1];
560
+ const hasOwner = !!ownerProp;
561
+
562
+ // an @Entity() options spread may hide `type`/`relationEntityName` (they are
563
+ // spread properties, not readable PropertyAssignments) — the W606 already
564
+ // fired for the spread promises these doc-rule checks are skipped, so the
565
+ // two option-presence branches below must not also false-positive E108. The
566
+ // missing-`owner` branch is a class member a spread cannot deliver, so it
567
+ // stays ungated.
568
+ const optionsSpread = spreadElements(ts, info.optionsNode).length > 0;
569
+
570
+ if (isTabularPart) {
571
+ if (!hasRelName && !optionsSpread) {
572
+ findings.push(finding(ts, sf, anchor, "E108",
573
+ `tabular part '${info.className}' (type: 'tabular-part') is missing relationEntityName — ${TRIAD}`));
574
+ }
575
+ if (!hasOwner) {
576
+ findings.push(finding(ts, sf, anchor, "E108",
577
+ `tabular part '${info.className}' (type: 'tabular-part') has no @ManyToOne relation named 'owner' pointing at the parent — ${TRIAD}`));
578
+ }
579
+ } else if (hasRelName && !optionsSpread) {
580
+ findings.push(finding(ts, sf, relNode, "E108",
581
+ `entity '${info.className}' sets relationEntityName but not type: 'tabular-part' — "type: 'tabular-part' or relationEntityName is missing, so it is listed under /related instead"`));
582
+ }
583
+
584
+ if (hasRelName && hasOwner && ownerProp.targetClass) {
585
+ const target = model.entities.get(ownerProp.targetClass);
586
+ if (target && target.entityName !== relLiteral) {
587
+ findings.push(finding(ts, sf, ownerProp.node, "E109",
588
+ `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`));
589
+ }
590
+ }
591
+
592
+ if (isTabularPart && hasOwner && !info.importKeyFieldsUnreadable && info.importKeyFields) {
593
+ const idx = info.importKeyFields.indexOf("owner");
594
+ if (idx === -1) {
595
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "E110",
596
+ `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`));
597
+ } else if (idx !== 0) {
598
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "W607",
599
+ `tabular part '${info.className}': "Put owner first in importKeyFields" — it is at position ${idx}`));
600
+ }
601
+ }
602
+ }
603
+
604
+ // ── rules: entities ──
605
+ function checkEntity(ts, info, sdk, model, findings) {
606
+ const sf = info.sf;
607
+ const anchor = info.node.name ?? info.node;
608
+
609
+ const heritage = (info.node.heritageClauses ?? []).find(
610
+ (h) => h.token === ts.SyntaxKind.ExtendsKeyword,
611
+ );
612
+ const base = heritage?.types?.[0]?.expression;
613
+ if (!isSdkQualified(ts, sf, base, "SystemBaseEntity")) {
614
+ findings.push(finding(ts, sf, anchor, "E101",
615
+ `entity class '${info.className}' must extend SystemBaseEntity — it contributes id/createdAt/updatedAt/deletedAt/createdBy/removedBy (doc: "Every entity must extend SystemBaseEntity")`));
616
+ }
617
+
618
+ for (const [opt, valNode] of info.options) {
619
+ if (!sdk.entityOptions.includes(opt)) {
620
+ findings.push(finding(ts, sf, valNode, "E501",
621
+ `unknown @Entity() option '${opt}' — valid options: ${sdk.entityOptions.join(", ")}. If it isn't in the table, it isn't an option.`));
622
+ }
623
+ }
624
+
625
+ for (const spread of spreadElements(ts, info.optionsNode)) {
626
+ findings.push(finding(ts, sf, spread, "W606",
627
+ `@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`));
628
+ }
629
+
630
+ if (info.importKeyFieldsUnreadable) {
631
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "W606",
632
+ `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`));
633
+ } else if (info.importKeyFields) {
634
+ for (const f of info.importKeyFields) {
635
+ // a field may be named by its property name or by its @Column({ name }) (DA-2)
636
+ if (!info.properties.has(f) && !info.columnNames.has(f)) {
637
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "E106",
638
+ `importKeyFields names '${f}' but the class declares no such property or column name — seeds would have nothing to match on`));
639
+ }
640
+ }
641
+ }
642
+
643
+ if (!info.hasKey) {
644
+ findings.push(finding(ts, sf, anchor, "W602",
645
+ `entity '${info.className}' has no 'key' option — a rename will be treated as drop-and-create instead of a rename (doc TIP)`));
646
+ }
647
+
648
+ checkTabularPart(ts, info, model, findings);
649
+
650
+ for (const [propName, prop] of info.properties) {
651
+ if (SYSTEM_COLUMNS.includes(propName)) {
652
+ findings.push(finding(ts, sf, prop.node, "E102",
653
+ `system column '${propName}' is provided by SystemBaseEntity — "you never declare them yourself"`));
654
+ }
655
+ // the table-level conflict is on the COLUMN name, which `name` overrides
656
+ const colName = stringValue(ts, prop.nameNode);
657
+ if (colName && SYSTEM_COLUMNS.includes(colName)) {
658
+ findings.push(finding(ts, sf, prop.nameNode, "E102",
659
+ `column name '${colName}' on property '${propName}' collides with the system column of the same name provided by SystemBaseEntity — "you never declare them yourself"`));
660
+ }
661
+ if (prop.kind === "column") checkColumn(ts, sf, propName, prop, sdk, findings);
662
+ if (prop.kind === "enum" || prop.kind === "multi-enum") {
663
+ checkEnumSubType(ts, sf, propName, prop, findings);
664
+ }
665
+ checkDefaultFieldOptions(ts, sf, propName, prop, findings);
666
+ if (prop.kind === "enum" || prop.kind === "multi-enum") {
667
+ checkEnumGlobalName(ts, sf, propName, prop, model, findings);
668
+ }
669
+ if (RELATION_KINDS.has(prop.kind)) {
670
+ checkRelationTyping(ts, sf, propName, prop, findings);
671
+ if (prop.targetClass === null) {
672
+ findings.push(finding(ts, sf, prop.node, "E105",
673
+ `relation '${propName}' must receive a thunk returning the target class — write @${prop.decorator.name}(() => Target); a direct class reference breaks circular imports`));
674
+ }
675
+ if (prop.inverseNode) {
676
+ if (OPTIONAL_INVERSE_DECORATORS.has(prop.decorator.name)) {
677
+ findings.push(finding(ts, sf, prop.inverseNode, "W609",
678
+ `'${propName}' (@${prop.decorator.name}) passes an inverse selector — it is optional on @ManyToOne/@ManyToMany and usually omitted; pass only the thunk and the options object (@${prop.decorator.name}(() => Target, { ... })) unless you are deliberately pairing an explicit back-reference declared on the target`));
679
+ }
680
+ checkInverseSelector(ts, sf, propName, prop, model, findings);
681
+ }
682
+ }
683
+ }
684
+ }
685
+
686
+ /**
687
+ * A relation property must declare its TypeScript type, and that type must say
688
+ * the same thing the decorator does: @ManyToOne holds ONE target row, the other
689
+ * three hold many.
690
+ *
691
+ * @ManyToOne(() => ProductMatrixEntity, { nullable: false })
692
+ * owner: ProductMatrixEntity;
693
+ *
694
+ * @ManyToMany(() => ProductMatrixEntity, { … }) @OneToMany(() => X, i, { … })
695
+ * owners: ProductMatrixEntity[]; envs: X[];
696
+ *
697
+ * Without the annotation the property is `any` to every consumer of the entity,
698
+ * and nothing catches a relation read as the wrong shape.
699
+ */
700
+ function checkRelationTyping(ts, sf, propName, prop, findings) {
701
+ const arity = RELATION_ARITY[prop.decorator.name];
702
+ const target = prop.targetClass;
703
+ const info = prop.typeInfo;
704
+ const expected = target ? (arity === "many" ? `${target}[]` : target) : null;
705
+
706
+ if (!info) {
707
+ findings.push(finding(ts, sf, prop.node, "E114",
708
+ `relation '${propName}' (@${prop.decorator.name}) has no TypeScript type — write ` +
709
+ `${propName}${arity === "one" ? "" : ""}: ${expected ?? (arity === "many" ? "Target[]" : "Target")};` +
710
+ ` an untyped relation property is 'any' to every consumer of this entity`));
711
+ return;
712
+ }
713
+ if (info.name === null) return; // a shape this AST-only checker cannot read
714
+
715
+ if (target && info.name !== target) {
716
+ findings.push(finding(ts, sf, info.node, "E115",
717
+ `relation '${propName}' (@${prop.decorator.name}) points at '${target}' but the property is typed ` +
718
+ `'${info.name}${info.isArray ? "[]" : ""}' — the type must name the same class the thunk returns: ${expected}`));
719
+ return;
720
+ }
721
+ if (arity === "many" && !info.isArray) {
722
+ findings.push(finding(ts, sf, info.node, "E115",
723
+ `'${propName}' (@${prop.decorator.name}) holds MANY rows but is typed '${info.name}' — write '${info.name}[]'`));
724
+ } else if (arity === "one" && info.isArray) {
725
+ findings.push(finding(ts, sf, info.node, "E115",
726
+ `'${propName}' (@ManyToOne) holds ONE row but is typed '${info.name}[]' — write '${info.name}'. ` +
727
+ `The many side is @OneToMany on the other class.`));
728
+ }
729
+
730
+ // Optionality should agree with the column: a NOT NULL relation always has a
731
+ // value, anything else may be absent.
732
+ if (arity === "one") {
733
+ const notNull = booleanValue(ts, prop.relOptions?.get("nullable")) === false;
734
+ if (notNull && info.nullable) {
735
+ findings.push(finding(ts, sf, info.node, "W610",
736
+ `'${propName}' is declared nullable: false but typed as optional — drop the '?' (and any '| null'): the column always has a value`));
737
+ } else if (!notNull && !info.nullable) {
738
+ findings.push(finding(ts, sf, info.node, "W610",
739
+ `'${propName}' is nullable (no 'nullable: false') but typed as always present — write '${propName}?: ${info.name}' so callers handle the empty case`));
740
+ }
741
+ }
742
+ }
743
+
744
+ /**
745
+ * Field options the platform already applies by default. Repeating one per
746
+ * field is noise that hides the options that DO differ.
747
+ */
748
+ function checkDefaultFieldOptions(ts, sf, propName, prop, findings) {
749
+ const scopes = [];
750
+ if (prop.optionsNode) scopes.push(prop.optionsNode);
751
+ // …and a nested `options: { … }` object, whichever shape the SDK takes.
752
+ for (const scope of [...scopes]) {
753
+ const nested = objectMap(ts, scope).get("options");
754
+ if (nested && ts.isObjectLiteralExpression(nested)) scopes.push(nested);
755
+ }
756
+ for (const scope of scopes) {
757
+ for (const [key, valNode] of objectMap(ts, scope)) {
758
+ if (!(key in DEFAULT_FIELD_OPTIONS)) continue;
759
+ const value = booleanValue(ts, valNode);
760
+ if (value !== null && value === DEFAULT_FIELD_OPTIONS[key]) {
761
+ findings.push(finding(ts, sf, valNode, "W612",
762
+ `'${propName}' sets '${key}: ${value}', which is already the platform default — remove it; ` +
763
+ `declare an option only where it DEPARTS from the default (defaults: ` +
764
+ `${Object.entries(DEFAULT_FIELD_OPTIONS).map(([k, v]) => `${k}=${v}`).join(", ")})`));
765
+ }
766
+ }
767
+ }
768
+ }
769
+
770
+ /**
771
+ * @Enum()/@MultiEnum() take the enum's global name as an optional FIRST
772
+ * argument. A global name is what lets seeds and other entities reference the
773
+ * value set; without one the decorator derives <ClassName>.<propertyName> and
774
+ * the enum stays local to this field. Pass it only when the enum really is
775
+ * shared — so a name nothing references is a name that should not be there.
776
+ */
777
+ function checkEnumGlobalName(ts, sf, propName, prop, model, findings) {
778
+ const name = prop.enumGlobalName;
779
+ if (!name) return; // local enum — the default, and nothing to check
780
+ // The literal occurs once: here, in this decorator. Nothing — no seed record,
781
+ // no other entity — refers to it, so the name buys nothing.
782
+ const occurrences = model.stringLiteralCounts.get(name) ?? 0;
783
+ if (occurrences <= 1) {
784
+ findings.push(finding(ts, sf, prop.decorator.args[0], "W613",
785
+ `'${propName}' (@${prop.decorator.name}) declares the global enum name '${name}', but nothing in the ` +
786
+ `analyzed files references it. A global name is for enums shared across entities or referenced from ` +
787
+ `seeds ({ name: '${name}', value: … }); for an enum used only by this field, omit the first argument ` +
788
+ `— @${prop.decorator.name}(${prop.decorator.name === "Enum" ? "StatusEnum, StatusTitles, " : "…, "}{ … }) — and the decorator derives the name`));
789
+ }
790
+ }
791
+
792
+ /**
793
+ * "An inverse must select the property on the target that holds the OTHER
794
+ * SIDE of this relation" — e.g. (task) => task.project. Applies to the
795
+ * `inverse` argument of any of the four relation decorators, required or not.
796
+ * Skipped silently when the target class is not among the analyzed entities
797
+ * (platform/SDK entities such as IconsEntity) — no guessing without a model
798
+ * of that class, and when the selector's shape (destructuring, a computed
799
+ * body, …) is not one this AST-only checker can read.
800
+ */
801
+ function checkInverseSelector(ts, sf, propName, prop, model, findings) {
802
+ if (!prop.targetClass) return;
803
+ const target = model.entities.get(prop.targetClass);
804
+ if (!target) return;
805
+ const accessed = inverseAccessedProperty(ts, prop.inverseNode);
806
+ if (accessed === null) return;
807
+ const targetProp = target.properties.get(accessed);
808
+ if (targetProp && RELATION_KINDS.has(targetProp.kind)) return; // valid pairing
809
+
810
+ let reason;
811
+ if (SYSTEM_COLUMNS.includes(accessed)) {
812
+ reason = `'${accessed}' is a system column provided by SystemBaseEntity, not a relation`;
813
+ } else if (!targetProp) {
814
+ reason = `'${target.entityName}' declares no property named '${accessed}'`;
815
+ } else {
816
+ reason = `'${target.entityName}.${accessed}' is a '${targetProp.kind}' property, not a relation`;
817
+ }
818
+ findings.push(finding(ts, sf, prop.inverseNode, "E111",
819
+ `inverse selector on '${propName}' (@${prop.decorator.name}) targets '${target.entityName}.${accessed}', but ${reason} — an inverse selector must select the RELATION property on the target that holds the OTHER SIDE of this relation, e.g. (task) => task.project`));
820
+ }
821
+
822
+ /**
823
+ * E113 — "@Enum() and @MultiEnum() fill it from their first argument […] do not
824
+ * pass subType yourself on an enum field". Passing one by hand either duplicates
825
+ * what the decorator already writes or silently disagrees with it, and the value
826
+ * it disagrees with is the one that resolves { value: 'active' } to an enum
827
+ * record on insert.
828
+ */
829
+ function checkEnumSubType(ts, sf, propName, prop, findings) {
830
+ const subTypeNode = prop.enumOptions?.get("subType");
831
+ if (!subTypeNode) return;
832
+ findings.push(finding(ts, sf, subTypeNode, "E113",
833
+ `'${propName}' (@${prop.decorator.name}) passes 'subType' by hand — on an enum field subType holds the enum's global name and is "Set by the decorator — never by hand"; @Enum()/@MultiEnum() fill it from their first argument (or derive <ClassName>.<propertyName>). Remove the option.`));
834
+ }
835
+
836
+ function checkColumn(ts, sf, propName, prop, sdk, findings) {
837
+ const opts = prop.columnOptions;
838
+ for (const [opt, valNode] of opts) {
839
+ if (!sdk.columnOptions.includes(opt)) {
840
+ findings.push(finding(ts, sf, valNode, "E502",
841
+ `unknown @Column() option '${opt}' — valid options: ${sdk.columnOptions.join(", ")}. If it isn't in the table, it isn't an option.`));
842
+ }
843
+ }
844
+
845
+ for (const spread of spreadElements(ts, prop.optionsNode)) {
846
+ findings.push(finding(ts, sf, spread, "W606",
847
+ `@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`));
848
+ }
849
+
850
+ let typeValue = null; // canonical string value, e.g. "text"
851
+ const typeNode = opts.get("type");
852
+ if (typeNode) {
853
+ if (ts.isPropertyAccessExpression(typeNode) &&
854
+ ts.isIdentifier(typeNode.expression) &&
855
+ typeNode.expression.text === "FieldTypeEnum") {
856
+ const member = typeNode.name.text;
857
+ typeValue = sdk.fieldTypes[member] ?? null;
858
+ if (typeValue === null) {
859
+ findings.push(finding(ts, sf, typeNode, "E107",
860
+ `FieldTypeEnum.${member} is not a known member — valid: ${Object.keys(sdk.fieldTypes).join(", ")}`));
861
+ }
862
+ } else {
863
+ const raw = stringValue(ts, typeNode);
864
+ if (raw !== null) {
865
+ if (NON_SCALAR_TYPE_STRINGS.has(raw)) {
866
+ findings.push(finding(ts, sf, typeNode, "E104",
867
+ `@Column type '${raw}' — relations, enums and files are declared with their own decorators (@ManyToOne/@Enum/@File/…) "and never with @Column({ type: ... })"`));
868
+ } else {
869
+ const member = Object.keys(sdk.fieldTypes).find((k) => sdk.fieldTypes[k] === raw);
870
+ if (member) {
871
+ typeValue = raw;
872
+ findings.push(finding(ts, sf, typeNode, "W601",
873
+ `raw string type '${raw}' — use FieldTypeEnum.${member} so a typo fails in the editor instead of at migration time`));
874
+ } else {
875
+ findings.push(finding(ts, sf, typeNode, "E107",
876
+ `unknown column type '${raw}' — "a misspelled one ('txet') compiles too and only fails when the migration runs"`));
877
+ }
878
+ }
879
+ }
880
+ }
881
+ }
882
+
883
+ const def = opts.get("default");
884
+ if (def) {
885
+ const val = unwrapExpr(ts, def);
886
+ if (isProvableNonString(ts, val)) {
887
+ findings.push(finding(ts, sf, def, "E103",
888
+ `'default' must be a SQL expression STRING — "Write default: 'false', not default: false, and default: \\"'draft'\\" for a string literal"`));
889
+ } else if (!isProvableString(ts, val)) {
890
+ findings.push(finding(ts, sf, def, "W606",
891
+ `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`));
892
+ }
893
+ }
894
+ checkSubType(ts, sf, propName, prop, typeValue, findings);
895
+
896
+ if (opts.has("length") && typeValue !== null && typeValue !== "text") {
897
+ findings.push(finding(ts, sf, opts.get("length"), "W603",
898
+ `'length' caps Text columns; this column is '${typeValue}'`));
899
+ }
900
+ if (opts.has("decimalPlaces") && typeValue !== null && typeValue !== "numeric") {
901
+ findings.push(finding(ts, sf, opts.get("decimalPlaces"), "W604",
902
+ `'decimalPlaces' pairs with Numeric columns; this column is '${typeValue}'`));
903
+ }
904
+ }
905
+
906
+ /**
907
+ * E112 — a subType string that the doc's matrix does not pair with this base
908
+ * type. Only two rows of that matrix belong to @Column(): Timestamp takes
909
+ * 'date' | 'time' | 'timestamp' ("Chooses the physical column type"), Text takes
910
+ * 'encrypted'. Anything else is rejected by the platform, not by tsc — `subType`
911
+ * is typed as a plain string, so a wrong pairing compiles.
912
+ *
913
+ * `subType: null` is the DOCUMENTED way to clear a subtype ("write subType: null
914
+ * explicitly") and is always clean. A value this AST-only checker cannot read
915
+ * takes the usual W606 unverifiable path — never E112. An unresolved `type`
916
+ * leaves nothing to judge the pairing against, so the check is skipped.
917
+ */
918
+ function checkSubType(ts, sf, propName, prop, typeValue, findings) {
919
+ const node = prop.columnOptions.get("subType");
920
+ if (!node) return;
921
+ const val = unwrapExpr(ts, node);
922
+ if (val.kind === ts.SyntaxKind.NullKeyword) return; // the documented "clear it"
923
+ const raw = stringValue(ts, val);
924
+ if (raw === null) {
925
+ findings.push(finding(ts, sf, node, "W606",
926
+ `cannot statically verify 'subType' of '${propName}' — it is delivered by reference or by an expression this checker cannot evaluate, so the base-type pairing check (E112) is skipped; inline the string literal to restore checking`));
927
+ return;
928
+ }
929
+ if (typeValue === null) return; // no readable `type` to pair it against
930
+ const allowed = DOC_SUBTYPES_BY_TYPE[typeValue];
931
+ if (allowed && allowed.includes(raw)) return;
932
+ findings.push(finding(ts, sf, node, "E112",
933
+ `subType '${raw}' is not valid on a '${typeValue}' column ('${propName}') — the doc's matrix pairs subType with exactly two @Column base types: Timestamp takes 'date', 'time' or 'timestamp', and Text takes 'encrypted'. No other (type, subType) combination exists.`));
934
+ }
935
+
936
+ // ── extraction: string enums (createSeed(EnumName.Member) resolution) ──
937
+ function analyzeEnums(ts, sf, model) {
938
+ sf.forEachChild(function walk(node) {
939
+ // Every string literal in the analyzed set, counted. A global enum name that
940
+ // occurs exactly once is written in its decorator and referenced nowhere —
941
+ // which is what W613 is looking for.
942
+ if (ts.isStringLiteral(node)) {
943
+ model.stringLiteralCounts.set(node.text, (model.stringLiteralCounts.get(node.text) ?? 0) + 1);
944
+ }
945
+ if (ts.isEnumDeclaration(node)) {
946
+ const members = new Map();
947
+ const memberNodes = [];
948
+ for (const m of node.members) {
949
+ const name = ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)
950
+ ? m.name.text : m.name.getText(sf);
951
+ memberNodes.push({ name, node: m.name });
952
+ const value = stringValue(ts, m.initializer);
953
+ if (value !== null) members.set(name, value);
954
+ }
955
+ if (members.size) model.stringEnums.set(node.name.text, members);
956
+ model.enumDeclarations.push({ name: node.name.text, sf, members: memberNodes });
957
+ }
958
+ ts.forEachChild(node, walk);
959
+ });
960
+ }
961
+
962
+ /**
963
+ * Enum MEMBER keys are PascalCase — `NotFilled = 'Not filled'`. The key is the
964
+ * name the code reads; the string on the right is what the platform stores, and
965
+ * the two are free to differ. A snake_case or lowercase key reads as data
966
+ * rather than as an identifier and drifts from every other enum in the repo.
967
+ */
968
+ function checkEnumDeclarations(ts, model, findings) {
969
+ for (const decl of model.enumDeclarations) {
970
+ for (const m of decl.members) {
971
+ if (!isPascalCase(m.name)) {
972
+ findings.push(finding(ts, decl.sf, m.node, "W611",
973
+ `enum member '${decl.name}.${m.name}' is not PascalCase — write '${pascalize(m.name)}'. ` +
974
+ `The member KEY is PascalCase; its stored value is the string on the right and need not match ` +
975
+ `(e.g. NotFilled = 'Not filled')`));
976
+ }
977
+ }
978
+ }
979
+ }
980
+
981
+ /** Best-effort PascalCase suggestion for an existing member key. */
982
+ function pascalize(name) {
983
+ return name
984
+ .split(/[^\p{L}\p{N}]+/u)
985
+ .filter(Boolean)
986
+ // an all-caps segment becomes Caps, not CAPS: ALL_CAPS -> AllCaps
987
+ .map((part) => (part === part.toUpperCase() && part.length > 1 ? part.toLowerCase() : part))
988
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
989
+ .join("") || name;
990
+ }
991
+
992
+ // ── extraction: seeds ──
993
+ function analyzeSeeds(ts, sf, model) {
994
+ sf.forEachChild(function walk(node) {
995
+ if (ts.isVariableStatement(node)) {
996
+ for (const decl of node.declarationList.declarations) {
997
+ const init = decl.initializer;
998
+ if (init && ts.isCallExpression(init) &&
999
+ isSdkQualified(ts, sf, init.expression, "createSeed")) {
1000
+ const exportName = ts.isIdentifier(decl.name) ? decl.name.text : decl.name.getText(sf);
1001
+ const arg0 = init.arguments[0];
1002
+ let entityName = stringValue(ts, arg0);
1003
+ let enumRef = null;
1004
+ if (entityName === null && arg0 && ts.isPropertyAccessExpression(arg0) &&
1005
+ ts.isIdentifier(arg0.expression)) {
1006
+ // EntityNamesEnum.Workflows — the VALUE is what createSeed receives;
1007
+ // the member name is only a fallback (resolved after every file is read)
1008
+ enumRef = { enumName: arg0.expression.text, member: arg0.name.text };
1009
+ }
1010
+ const arg1 = init.arguments[1];
1011
+ let records = null; // null = thin seed (imported payload) — record checks impossible
1012
+ if (arg1 && ts.isArrayLiteralExpression(arg1)) {
1013
+ records = arg1.elements.map((e) =>
1014
+ ts.isObjectLiteralExpression(e)
1015
+ ? { node: e, map: objectMap(ts, e), hasSpread: spreadElements(ts, e).length > 0, spreads: spreadElements(ts, e), byRef: false }
1016
+ : { node: e, map: new Map(), hasSpread: false, spreads: [], byRef: true },
1017
+ );
1018
+ }
1019
+ model.seeds.push({ exportName, entityName, enumRef, sf, node: init, records });
1020
+ }
1021
+ }
1022
+ }
1023
+ ts.forEachChild(node, walk);
1024
+ });
1025
+ }
1026
+
1027
+ // ── rules: seeds ──
1028
+ /**
1029
+ * `{ name: '<global enum name>', value: '<enum value>' }`. Extra keys are legal
1030
+ * (the doc gives the shape, it never forbids more). A reference or a spread is
1031
+ * unverifiable — warn instead of hard-erroring on code that may well be correct.
1032
+ */
1033
+ function checkEnumRef(ts, sf, key, valNode, prop, findings) {
1034
+ const root = unwrapExpr(ts, valNode);
1035
+ if (root.kind === ts.SyntaxKind.NullKeyword) return;
1036
+ const multi = prop.kind === "multi-enum";
1037
+ const shapeHint = multi ? " — an array of those for @MultiEnum" : "";
1038
+ const unverifiable = () => findings.push(finding(ts, sf, valNode, "W606",
1039
+ `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`));
1040
+ const wrongShape = (n) => findings.push(finding(ts, sf, n, "E206",
1041
+ `enum reference '${key}' must be { name: '<global enum name>', value: '<enum value>' }${shapeHint}`));
1042
+
1043
+ let refs;
1044
+ if (multi) {
1045
+ if (!ts.isArrayLiteralExpression(root)) {
1046
+ if (isOpaqueExpression(ts, root)) return unverifiable();
1047
+ return wrongShape(valNode);
1048
+ }
1049
+ if (arraySpreadElements(ts, root).length > 0) return unverifiable();
1050
+ refs = root.elements.map((e) => unwrapExpr(ts, e));
1051
+ } else {
1052
+ refs = [root];
1053
+ }
1054
+
1055
+ for (const ref of refs) {
1056
+ if (!ts.isObjectLiteralExpression(ref)) {
1057
+ if (isOpaqueExpression(ts, ref)) { unverifiable(); continue; }
1058
+ wrongShape(ref);
1059
+ continue;
1060
+ }
1061
+ if (spreadElements(ts, ref).length > 0) { unverifiable(); continue; }
1062
+ const m = objectMap(ts, ref);
1063
+ if (!m.has("name") || !m.has("value")) { wrongShape(ref); continue; }
1064
+ const given = stringValue(ts, m.get("name"));
1065
+ if (prop.enumGlobalName && given !== null && given !== prop.enumGlobalName) {
1066
+ findings.push(finding(ts, sf, m.get("name"), "E206",
1067
+ `enum reference '${key}' names global enum '${given}', but the property is declared as @${multi ? "MultiEnum" : "Enum"}('${prop.enumGlobalName}') — the names must match`));
1068
+ }
1069
+ }
1070
+ }
1071
+
1072
+ function checkSeed(ts, seed, model, findings) {
1073
+ const sf = seed.sf;
1074
+ const entity = seed.entityName ? model.entityByName.get(seed.entityName) : undefined;
1075
+ if (!entity) {
1076
+ // platform entity, a typo, or simply a file outside the analyzed set — say so
1077
+ findings.push(finding(ts, sf, seed.node, "W606",
1078
+ `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`));
1079
+ } else if (!entity.importKeyFieldsUnreadable &&
1080
+ (!entity.importKeyFields || entity.importKeyFields.length === 0)) {
1081
+ findings.push(finding(ts, sf, seed.node, "W605",
1082
+ `entity '${seed.entityName}' has a seed but no importKeyFields — "seeds have nothing to match on and cannot stay idempotent"`));
1083
+ }
1084
+ if (!seed.records) return;
1085
+ for (const rec of seed.records) {
1086
+ if (rec.byRef) {
1087
+ findings.push(finding(ts, sf, rec.node, "W606",
1088
+ `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`));
1089
+ continue;
1090
+ }
1091
+ for (const [key, valNode] of rec.map) {
1092
+ if (SYSTEM_COLUMNS.includes(key)) {
1093
+ findings.push(finding(ts, sf, valNode, "E201",
1094
+ `seed record contains system column '${key}' — "they differ per tenant and corrupt matching"`));
1095
+ }
1096
+ if (ACCESS_METADATA_KEYS.includes(key)) {
1097
+ findings.push(finding(ts, sf, valNode, "E202",
1098
+ `seed record contains '${key}' — "access metadata, not data"`));
1099
+ }
1100
+ const prop = entity?.properties.get(key);
1101
+ if (!prop) continue;
1102
+ if (prop.kind === "many-to-one" || prop.kind === "many-to-many") {
1103
+ const isNum = (n) =>
1104
+ ts.isNumericLiteral(n) ||
1105
+ (ts.isPrefixUnaryExpression(n) && ts.isNumericLiteral(n.operand));
1106
+ const bad = isNum(valNode) ||
1107
+ (ts.isArrayLiteralExpression(valNode) && valNode.elements.some(isNum));
1108
+ if (bad) {
1109
+ findings.push(finding(ts, sf, valNode, "E203",
1110
+ `relation '${key}' referenced by numeric id — ids "do not match across tenants"; reference through the target's importKeyFields, e.g. { name: 'Default' }`));
1111
+ }
1112
+ }
1113
+ if (prop.kind === "one-to-many" || prop.kind === "many-to-many-backref") {
1114
+ findings.push(finding(ts, sf, valNode, "E204",
1115
+ `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.`));
1116
+ }
1117
+ if (prop.kind === "enum" || prop.kind === "multi-enum") {
1118
+ checkEnumRef(ts, sf, key, valNode, prop, findings);
1119
+ }
1120
+ }
1121
+ for (const spread of rec.spreads ?? []) {
1122
+ findings.push(finding(ts, sf, spread, "W606",
1123
+ `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`));
1124
+ }
1125
+ if (rec.hasSpread) continue; // spread may deliver the import key — E205 would false-positive
1126
+ if (!entity) continue;
1127
+
1128
+ // $key overrides identity per record — but only if it can establish one
1129
+ if (rec.map.has("$key")) {
1130
+ const keyNode = rec.map.get("$key");
1131
+ const keyValue = unwrapExpr(ts, keyNode);
1132
+ if (ts.isObjectLiteralExpression(keyValue)) {
1133
+ if (keyValue.properties.length === 0) {
1134
+ findings.push(finding(ts, sf, keyNode, "E205",
1135
+ `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.`));
1136
+ }
1137
+ } else if (isOpaqueExpression(ts, keyValue)) {
1138
+ findings.push(finding(ts, sf, keyNode, "W606",
1139
+ `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`));
1140
+ } else {
1141
+ findings.push(finding(ts, sf, keyNode, "E205",
1142
+ `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.`));
1143
+ }
1144
+ continue;
1145
+ }
1146
+
1147
+ if (entity.importKeyFields?.length) {
1148
+ for (const f of entity.importKeyFields) {
1149
+ if (!rec.map.has(f)) {
1150
+ findings.push(finding(ts, sf, rec.node, "E205",
1151
+ `seed record is missing importKeyField '${f}' of '${seed.entityName}' — nothing matches ⇒ duplicate rows after every restart. Provide it or override identity with $key.`));
1152
+ }
1153
+ }
1154
+ }
1155
+ }
1156
+ }
1157
+
1158
+ // ── extraction: EntityModule.forFeature ──
1159
+ /**
1160
+ * Doc resolution order: "If the entities array is passed AND NOT EMPTY it is
1161
+ * used and entitiesPath is ignored; otherwise entities are loaded from
1162
+ * entitiesPath" — same for seeds/seedsPath. The two sides are independent, so
1163
+ * each gets its own mode: "explicit" | "autoload" | "unverifiable".
1164
+ */
1165
+ function analyzeModules(ts, sf, model) {
1166
+ sf.forEachChild(function walk(node) {
1167
+ if (ts.isCallExpression(node) &&
1168
+ ts.isPropertyAccessExpression(node.expression) &&
1169
+ node.expression.name.text === "forFeature" &&
1170
+ isSdkQualified(ts, sf, node.expression.expression, "EntityModule")) {
1171
+ const a0 = node.arguments[0] ? unwrapExpr(ts, node.arguments[0]) : undefined;
1172
+ const a0IsArray = a0 && ts.isArrayLiteralExpression(a0);
1173
+ const a0IsOptions = a0 && ts.isObjectLiteralExpression(a0);
1174
+ // options live in argument 1 next to an entities array, or ARE argument 0
1175
+ const optionsNode = a0IsOptions ? a0 : node.arguments[1];
1176
+ const opts = objectMap(ts, optionsNode);
1177
+
1178
+ const side = (label, arrayNode, pathNode, unreadableNode) => {
1179
+ const s = {
1180
+ label, mode: "autoload", names: [], spreads: [],
1181
+ node, refNode: null, paths: null, pathNode: pathNode ?? null,
1182
+ };
1183
+ if (unreadableNode) {
1184
+ s.mode = "unverifiable";
1185
+ s.refNode = unreadableNode;
1186
+ return s;
1187
+ }
1188
+ if (arrayNode && arrayNode.elements.length > 0) {
1189
+ s.mode = "explicit";
1190
+ s.node = arrayNode;
1191
+ s.names = arrayNode.elements
1192
+ .filter((e) => ts.isIdentifier(e))
1193
+ .map((e) => resolveLocalName(sf, e.text)); // aliases resolve to the exported name
1194
+ s.spreads = arraySpreadElements(ts, arrayNode);
1195
+ return s;
1196
+ }
1197
+ // absent or empty array -> the path decides; read it when it is readable
1198
+ if (pathNode) {
1199
+ const single = stringValue(ts, pathNode);
1200
+ s.paths = single !== null ? [single] : stringArray(ts, pathNode);
1201
+ }
1202
+ return s;
1203
+ };
1204
+
1205
+ const seedsNode = opts.get("seeds") ? unwrapExpr(ts, opts.get("seeds")) : undefined;
1206
+ // Read wherever it sits — an options object in argument 0 OR argument 1.
1207
+ const entitiesOptNode = opts.get("entities") ? unwrapExpr(ts, opts.get("entities")) : null;
1208
+ const entitiesOptArray =
1209
+ entitiesOptNode && ts.isArrayLiteralExpression(entitiesOptNode) ? entitiesOptNode : null;
1210
+ const m = {
1211
+ sf, node,
1212
+ // `entities` as an OPTION is not one of the two documented shapes: the
1213
+ // classes go in argument 0. E306 reports the shape — but the array is
1214
+ // still READ below, because leaving it unread degraded the module to
1215
+ // "autoload" and switched E301/E302/E304 off for the whole run. 1.4.1
1216
+ // added the message and left that suppression in place; this is the
1217
+ // actual fix.
1218
+ entitiesOptionNode: entitiesOptNode,
1219
+ entities: side(
1220
+ "entitiesPath",
1221
+ a0IsArray ? a0 : entitiesOptArray,
1222
+ opts.get("entitiesPath"),
1223
+ a0 && !a0IsArray && !a0IsOptions ? a0 : null,
1224
+ ),
1225
+ seeds: side(
1226
+ "seedsPath",
1227
+ seedsNode && ts.isArrayLiteralExpression(seedsNode) ? seedsNode : null,
1228
+ opts.get("seedsPath"),
1229
+ seedsNode && !ts.isArrayLiteralExpression(seedsNode) ? seedsNode
1230
+ : (a0 && !a0IsArray && !a0IsOptions && !optionsNode ? a0 : null),
1231
+ ),
1232
+ };
1233
+ model.modules.push(m);
1234
+ }
1235
+ ts.forEachChild(node, walk);
1236
+ });
1237
+ }
1238
+
1239
+ // ── rules: registration ──
1240
+ /**
1241
+ * E301/E302 fire on the entity/seed source file, far from the module file
1242
+ * that actually needs the edit — name it explicitly so the finding is
1243
+ * actionable instead of just "unregistered". `side` selects which half of
1244
+ * forFeature() (`entities` or `seeds`) determines the classes-shape modules;
1245
+ * paths are shown relative to rootDir when derivable, else just the basename,
1246
+ * deduped, capped at 3 so the message stays short.
1247
+ */
1248
+ function classShapeModulePaths(modules, side, rootDir) {
1249
+ const shapeModules = modules.filter((m) => m[side].mode === "explicit");
1250
+ if (shapeModules.length === 0) return "";
1251
+ const root = rootDir ? resolve(rootDir).replace(/\\/g, "/") : null;
1252
+ const raw = [...new Set(shapeModules.map((m) => m.sf.fileName))];
1253
+ const shown = raw.map((p) => {
1254
+ const norm = p.replace(/\\/g, "/");
1255
+ if (root && norm.startsWith(`${root}/`)) return norm.slice(root.length + 1);
1256
+ const parts = norm.split("/");
1257
+ return parts[parts.length - 1];
1258
+ });
1259
+ return shown.slice(0, 3).join(", ");
1260
+ }
1261
+
1262
+ function checkRegistration(ts, model, findings, rootDir) {
1263
+ // E303/W606 on autoload paths — only for the side that actually autoloads:
1264
+ // a path the resolution order ignores is dead config, not a mistake.
1265
+ for (const m of model.modules) {
1266
+ for (const side of [m.entities, m.seeds]) {
1267
+ if (side.mode !== "autoload" || !side.pathNode) continue;
1268
+ if (side.paths === null) {
1269
+ findings.push(finding(ts, m.sf, side.pathNode, "W606",
1270
+ `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`));
1271
+ continue;
1272
+ }
1273
+ for (const p of side.paths) {
1274
+ if (/(^|\/)src(\/|$)/.test(p.replace(/\\/g, "/"))) {
1275
+ findings.push(finding(ts, m.sf, side.pathNode, "E303",
1276
+ `${side.label} '${p}' points at src/ — autoloading reads compiled output: "entitiesPath / seedsPath points at src/ instead of compiled dist/"`));
1277
+ }
1278
+ }
1279
+ }
1280
+ }
1281
+
1282
+ for (const m of model.modules) {
1283
+ // The call returns a DynamicModule that something must consume — normally
1284
+ // the imports array of an @Module. As a bare expression statement the
1285
+ // result is discarded and NOTHING is registered, while every other check
1286
+ // here still sees a well-formed forFeature and stays quiet.
1287
+ // (migrations.txt:19-31 and overview-app-module.txt:12.)
1288
+ if (m.node.parent && ts.isExpressionStatement(m.node.parent)) {
1289
+ findings.push(finding(ts, m.sf, m.node, "E307",
1290
+ `EntityModule.forFeature() is called as a bare statement, so the module it returns is ` +
1291
+ `thrown away and no entity is registered. It belongs in the imports of an @Module: ` +
1292
+ `@Module({ imports: [EntityModule.forFeature([...], { seeds: [...] })] }) export class ` +
1293
+ `AppModule {} — and src/index.ts must export AppModule, because the runner imports your ` +
1294
+ `package from there`));
1295
+ }
1296
+ if (m.entitiesOptionNode) {
1297
+ findings.push(finding(ts, m.sf, m.entitiesOptionNode, "E306",
1298
+ `EntityModule.forFeature({ entities: [...] }) is not a supported shape — the options object takes only ` +
1299
+ `seeds, entitiesPath and seedsPath. Entity classes are the FIRST argument: ` +
1300
+ `forFeature([A, B], { seeds: [...] }). As written, nothing registers these classes and no table is ` +
1301
+ `created for them`));
1302
+ }
1303
+ // Neither an explicit array nor a path: this module registers no entities,
1304
+ // and E301 cannot know what is covered. Say so rather than fall silent.
1305
+ if (m.entities.mode === "autoload" && !m.entities.pathNode) {
1306
+ findings.push(finding(ts, m.sf, m.entities.node, "W614",
1307
+ `EntityModule.forFeature() names neither an entities array (first argument) nor entitiesPath, so this ` +
1308
+ `module registers no entity classes — E301 (unregistered entity) is skipped for the whole run. Pass the ` +
1309
+ `classes as the first argument, or set entitiesPath to the compiled dist/ directory`));
1310
+ }
1311
+ }
1312
+
1313
+ if (model.entities.size > 0 && model.modules.length === 0) {
1314
+ const first = [...model.entities.values()][0];
1315
+ findings.push(finding(ts, first.sf, first.node.name ?? first.node, "E305",
1316
+ `no EntityModule.forFeature() found — "An entity class that is never passed to forFeature() is invisible — no table is created for it"`));
1317
+ return;
1318
+ }
1319
+
1320
+ for (const m of model.modules) {
1321
+ for (const spread of m.entities.spreads) {
1322
+ findings.push(finding(ts, m.sf, spread, "W606",
1323
+ `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`));
1324
+ }
1325
+ for (const spread of m.seeds.spreads) {
1326
+ findings.push(finding(ts, m.sf, spread, "W606",
1327
+ `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`));
1328
+ }
1329
+ if (m.entities.mode === "unverifiable") {
1330
+ findings.push(finding(ts, m.sf, m.entities.refNode, "W606",
1331
+ `EntityModule.forFeature() entities are delivered by reference — membership cannot be statically verified: E301 (unregistered entity) is skipped; inline the array to restore checking`));
1332
+ }
1333
+ if (m.seeds.mode === "unverifiable" && m.seeds.refNode !== m.entities.refNode) {
1334
+ findings.push(finding(ts, m.sf, m.seeds.refNode, "W606",
1335
+ `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`));
1336
+ }
1337
+ }
1338
+
1339
+ // an autoload (or unverifiable) module anywhere may cover any entity/seed not
1340
+ // named explicitly — membership becomes the platform's job, so E301/E302 would
1341
+ // only false-positive.
1342
+ const entitiesUnknown = model.modules.some((m) => m.entities.mode !== "explicit" || m.entities.spreads.length > 0);
1343
+ const seedsUnknown = model.modules.some((m) => m.seeds.mode !== "explicit" || m.seeds.spreads.length > 0);
1344
+
1345
+ if (!entitiesUnknown) {
1346
+ const registeredEntities = new Set(model.modules.flatMap((m) => m.entities.names));
1347
+ const modulePaths = classShapeModulePaths(model.modules, "entities", rootDir);
1348
+ for (const [className, info] of model.entities) {
1349
+ if (!registeredEntities.has(className)) {
1350
+ findings.push(finding(ts, info.sf, info.node.name ?? info.node, "E301",
1351
+ `entity class '${className}' is not in any forFeature() entities array — no table will be created for it` +
1352
+ (modulePaths ? ` — add it to the entities array in ${modulePaths}` : "")));
1353
+ }
1354
+ }
1355
+ }
1356
+ if (!seedsUnknown) {
1357
+ const registeredSeeds = new Set(model.modules.flatMap((m) => m.seeds.names));
1358
+ const modulePaths = classShapeModulePaths(model.modules, "seeds", rootDir);
1359
+ for (const seed of model.seeds) {
1360
+ if (!registeredSeeds.has(seed.exportName)) {
1361
+ findings.push(finding(ts, seed.sf, seed.node, "E302",
1362
+ `seed '${seed.exportName}' is not in any forFeature() seeds array — it will never run` +
1363
+ (modulePaths ? ` — add it to the seeds array in ${modulePaths}` : "")));
1364
+ }
1365
+ }
1366
+ }
1367
+
1368
+ for (const m of model.modules) {
1369
+ if (m.seeds.mode !== "explicit" || m.seeds.spreads.length > 0) continue;
1370
+ const order = new Map(m.seeds.names.map((n, i) => [n, i]));
1371
+ const reported = new Set();
1372
+ for (const seed of model.seeds) {
1373
+ if (!order.has(seed.exportName) || !seed.records) continue;
1374
+ const entity = seed.entityName ? model.entityByName.get(seed.entityName) : undefined;
1375
+ if (!entity) continue;
1376
+ const myIdx = order.get(seed.exportName);
1377
+ for (const rec of seed.records) {
1378
+ for (const [key] of rec.map) {
1379
+ const prop = entity.properties.get(key);
1380
+ if (!prop || (prop.kind !== "many-to-one" && prop.kind !== "many-to-many") || !prop.targetClass) continue;
1381
+ const target = model.entities.get(prop.targetClass);
1382
+ if (!target || target === entity) continue;
1383
+ // an entity may have several seeds — what matters is the EARLIEST
1384
+ // registered one, since it is the one that creates the rows first
1385
+ const candidates = model.seeds.filter(
1386
+ (s) => s.entityName === target.entityName && order.has(s.exportName),
1387
+ );
1388
+ if (candidates.length === 0) continue;
1389
+ const earliest = candidates.reduce((a, b) =>
1390
+ order.get(a.exportName) <= order.get(b.exportName) ? a : b);
1391
+ const dedupe = `${seed.exportName}->${target.entityName}`;
1392
+ if (order.get(earliest.exportName) > myIdx && !reported.has(dedupe)) {
1393
+ reported.add(dedupe);
1394
+ findings.push(finding(ts, m.sf, m.seeds.node, "E304",
1395
+ `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"`));
1396
+ }
1397
+ }
1398
+ }
1399
+ }
1400
+ }
1401
+ }
1402
+
1403
+ // ── rules: tsconfig ──
1404
+ function checkTsconfig(ts, rootDir, findings) {
1405
+ if (!rootDir) return;
1406
+ // ts.readConfigFile compares the path it is given against its own normalized
1407
+ // form while attaching a syntax diagnostic — a Windows path throws a Debug
1408
+ // Failure there, so normalize, and never let this check kill the run.
1409
+ try {
1410
+ const root = resolve(rootDir).replace(/\\/g, "/");
1411
+ const p = `${root}/tsconfig.json`;
1412
+ if (!existsSync(p)) {
1413
+ findings.push({
1414
+ file: root, line: 1, col: 1, code: "W608", level: "warning",
1415
+ message: `no tsconfig.json at ${root} — cannot verify experimentalDecorators/emitDecoratorMetadata, both of which entities rely on`,
1416
+ });
1417
+ return;
1418
+ }
1419
+ const read = ts.readConfigFile(p, (f) => readFileSync(f, "utf-8"));
1420
+ if (read.error) return;
1421
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, root);
1422
+ const missing = [];
1423
+ if (!parsed.options.experimentalDecorators) missing.push("experimentalDecorators");
1424
+ if (!parsed.options.emitDecoratorMetadata) missing.push("emitDecoratorMetadata");
1425
+ if (missing.length) {
1426
+ findings.push({
1427
+ file: p, line: 1, col: 1, code: "E401", level: "error",
1428
+ message: `tsconfig.json must enable ${missing.join(" and ")} — entities rely on decorator metadata`,
1429
+ });
1430
+ }
1431
+ } catch {
1432
+ /* unreadable/malformed tsconfig — degrade silently rather than crash the run */
1433
+ }
1434
+ }
1435
+
1436
+ // ── SDK catalog: real @suppa/sdk typings when resolvable, doc list otherwise ──
1437
+ function loadSdkCatalog(ts, rootDir) {
1438
+ const catalog = {
1439
+ entityOptions: [...DOC_ENTITY_OPTIONS],
1440
+ columnOptions: [...DOC_COLUMN_OPTIONS],
1441
+ fieldTypes: { ...DOC_FIELD_TYPES },
1442
+ source: "doc",
1443
+ };
1444
+ if (!rootDir) return catalog;
1445
+ let dir = resolve(rootDir);
1446
+ let sdkDir = null;
1447
+ for (let i = 0; i < 8; i++) {
1448
+ const cand = join(dir, "node_modules", "@suppa", "sdk");
1449
+ if (existsSync(cand)) { sdkDir = cand; break; }
1450
+ const parent = dirname(dir);
1451
+ if (parent === dir) break;
1452
+ dir = parent;
1453
+ }
1454
+ if (!sdkDir) return catalog;
1455
+ let typesPath = join(sdkDir, "index.d.ts");
1456
+ try {
1457
+ const pkg = JSON.parse(readFileSync(join(sdkDir, "package.json"), "utf-8"));
1458
+ if (pkg.types || pkg.typings) typesPath = join(sdkDir, pkg.types ?? pkg.typings);
1459
+ } catch { /* fall back to index.d.ts */ }
1460
+ if (!existsSync(typesPath)) return catalog;
1461
+ try {
1462
+ const sf = ts.createSourceFile(typesPath, readFileSync(typesPath, "utf-8"), ts.ScriptTarget.Latest, true);
1463
+ const fieldTypes = {};
1464
+ let entityOptions = [];
1465
+ let columnOptions = [];
1466
+ sf.forEachChild(function walk(node) {
1467
+ if (ts.isEnumDeclaration(node) && node.name.text === "FieldTypeEnum") {
1468
+ for (const m of node.members) {
1469
+ const name = ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)
1470
+ ? m.name.text : m.name.getText(sf);
1471
+ fieldTypes[name] = m.initializer && ts.isStringLiteral(m.initializer)
1472
+ ? m.initializer.text : name;
1473
+ }
1474
+ }
1475
+ if (ts.isInterfaceDeclaration(node)) {
1476
+ const props = node.members
1477
+ .filter((mm) => ts.isPropertySignature(mm) && mm.name)
1478
+ .map((mm) => mm.name.getText(sf).replace(/['"]/g, ""));
1479
+ if (/EntityOptions$/i.test(node.name.text)) entityOptions = props;
1480
+ if (/ColumnOptions$/i.test(node.name.text)) columnOptions = props;
1481
+ }
1482
+ ts.forEachChild(node, walk);
1483
+ });
1484
+ let got = 0;
1485
+ // fieldTypes are enum VALUES, not option names — an older SDK enum member
1486
+ // set is the true, current set for this install, so replace outright.
1487
+ // entityOptions/columnOptions are OPTION NAMES: an SDK whose typings
1488
+ // predate a doc-documented option (e.g. relationEntityName) must not make
1489
+ // that option look unknown (E501) — union with the doc list instead of
1490
+ // replacing it (F1).
1491
+ if (Object.keys(fieldTypes).length) { catalog.fieldTypes = fieldTypes; got++; }
1492
+ if (entityOptions.length) {
1493
+ catalog.entityOptions = [...new Set([...entityOptions, ...DOC_ENTITY_OPTIONS])];
1494
+ got++;
1495
+ }
1496
+ if (columnOptions.length) {
1497
+ catalog.columnOptions = [...new Set([...columnOptions, ...DOC_COLUMN_OPTIONS])];
1498
+ got++;
1499
+ }
1500
+ catalog.source = got === 3 ? "sdk" : got > 0 ? "partial-sdk" : "doc";
1501
+ } catch { /* typings unreadable — doc fallback stands */ }
1502
+ return catalog;
1503
+ }
1504
+
1505
+ // ── public API ──
1506
+ export function validateSchema({ files = [], rootDir = null } = {}) {
1507
+ const ts = loadTypescript(rootDir);
1508
+ const sdk = loadSdkCatalog(ts, rootDir);
1509
+ const model = {
1510
+ entities: new Map(), entityByName: new Map(),
1511
+ seeds: [], modules: [], stringEnums: new Map(),
1512
+ enumDeclarations: [], stringLiteralCounts: new Map(),
1513
+ };
1514
+ const findings = [];
1515
+ // the CLI deduped; the exported API did not, and duplicated seeds duplicated findings
1516
+ const uniqueFiles = [...new Set(files.map((f) => resolve(f)))];
1517
+ const sources = uniqueFiles.map((f) =>
1518
+ ts.createSourceFile(f, readFileSync(f, "utf-8"), ts.ScriptTarget.Latest, true),
1519
+ );
1520
+ for (const sf of sources) analyzeImports(ts, sf);
1521
+ for (const sf of sources) analyzeEnums(ts, sf, model);
1522
+ for (const sf of sources) {
1523
+ analyzeEntities(ts, sf, model);
1524
+ analyzeSeeds(ts, sf, model);
1525
+ analyzeModules(ts, sf, model);
1526
+ }
1527
+ // createSeed(EnumName.Member) passes the member's VALUE; the member name is
1528
+ // only a fallback for enums declared outside the analyzed file set
1529
+ for (const seed of model.seeds) {
1530
+ if (seed.entityName === null && seed.enumRef) {
1531
+ seed.entityName =
1532
+ model.stringEnums.get(seed.enumRef.enumName)?.get(seed.enumRef.member) ??
1533
+ seed.enumRef.member;
1534
+ }
1535
+ }
1536
+ checkEnumDeclarations(ts, model, findings);
1537
+ for (const info of model.entities.values()) checkEntity(ts, info, sdk, model, findings);
1538
+ for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
1539
+ checkRegistration(ts, model, findings, rootDir);
1540
+ checkTsconfig(ts, rootDir, findings);
1541
+ findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.col - b.col);
1542
+ return {
1543
+ findings,
1544
+ errors: findings.filter((f) => f.level === "error"),
1545
+ warnings: findings.filter((f) => f.level === "warning"),
1546
+ sdkSource: sdk.source,
1547
+ };
1548
+ }
1549
+
1550
+ // ── discovery ──
1551
+ export function discoverFiles(rootDir) {
1552
+ const files = [];
1553
+ (function walk(dir) {
1554
+ for (const name of readdirSync(dir)) {
1555
+ if (name === "node_modules" || name === "dist" || name.startsWith(".")) continue;
1556
+ const p = join(dir, name);
1557
+ if (statSync(p).isDirectory()) {
1558
+ walk(p);
1559
+ } else if (name.endsWith(".entity.ts") || name.endsWith(".seed.ts")) {
1560
+ files.push(p);
1561
+ } else if (name.endsWith(".ts") &&
1562
+ readFileSync(p, "utf-8").includes("EntityModule.forFeature")) {
1563
+ files.push(p);
1564
+ }
1565
+ }
1566
+ })(resolve(rootDir));
1567
+ return files.sort();
1568
+ }
1569
+
1570
+ // ── CLI ──
1571
+ const isMain =
1572
+ process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
1573
+ if (isMain) {
1574
+ const args = process.argv.slice(2);
1575
+ if (args.length === 0) {
1576
+ console.error("usage: node validate-suppa-schema.mjs <app-root-or-files...>");
1577
+ process.exit(2);
1578
+ }
1579
+ let rootDir = null;
1580
+ const files = [];
1581
+ for (const a of args) {
1582
+ const p = resolve(a);
1583
+ if (!existsSync(p)) {
1584
+ console.error(`validate-suppa-schema: path not found: ${a}`);
1585
+ process.exit(2);
1586
+ }
1587
+ if (statSync(p).isDirectory()) {
1588
+ rootDir = rootDir ?? p;
1589
+ files.push(...discoverFiles(p));
1590
+ } else {
1591
+ files.push(p);
1592
+ }
1593
+ }
1594
+ const dedupedFiles = [...new Set(files)];
1595
+ if (dedupedFiles.length === 0) {
1596
+ // Exit 0 here meant a mistyped root passed the close-out gate: SKILL.md
1597
+ // makes that exit code the whole gate, so "0 error(s) across 0 file(s)"
1598
+ // read as "the schema is clean".
1599
+ console.error(
1600
+ `validate-suppa-schema: no schema files found under ${args.join(", ")}. ` +
1601
+ "Expected *.entity.ts, *.seed.ts, or a .ts file containing EntityModule.forFeature. " +
1602
+ "Check the path — nothing was analyzed, so nothing was verified.",
1603
+ );
1604
+ process.exit(2);
1605
+ }
1606
+ let res;
1607
+ try {
1608
+ res = validateSchema({ files: dedupedFiles, rootDir });
1609
+ } catch (err) {
1610
+ // A missing/unusable toolchain is the caller's to fix: one actionable line,
1611
+ // same exit code as the other argument problems. Anything else is a bug in
1612
+ // this validator and keeps its stack trace.
1613
+ if (err?.code !== "SUPPA_VALIDATOR_ENV") throw err;
1614
+ console.error(err.message);
1615
+ process.exit(2);
1616
+ }
1617
+ for (const f of res.findings) {
1618
+ console.log(
1619
+ `${displayPath(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`,
1620
+ );
1621
+ }
1622
+ console.log(
1623
+ `\n${res.errors.length} error(s), ${res.warnings.length} warning(s) across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
1624
+ );
1625
+ process.exit(res.errors.length > 0 ? 1 : 0);
1626
+ }