suppa-mcp-2 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,7 @@ import { pathToFileURL } from "node:url";
18
18
  // ── Doc-derived catalogs (fallback when @suppa/sdk typings are absent) ──
19
19
  export const SYSTEM_COLUMNS = ["id", "createdAt", "updatedAt", "deletedAt", "createdBy", "removedBy"];
20
20
  export const ACCESS_METADATA_KEYS = ["$readAccess", "$updateAccess", "$instanceAccess"];
21
- export const DOC_ENTITY_OPTIONS = ["name", "title", "comment", "representativeFieldName", "importKeyFields", "key", "icon", "type", "options"];
21
+ export const DOC_ENTITY_OPTIONS = ["name", "title", "comment", "representativeFieldName", "importKeyFields", "key", "icon", "type", "relationEntityName", "options"];
22
22
  export const DOC_COLUMN_OPTIONS = ["type", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask"];
23
23
  export const DOC_FIELD_TYPES = {
24
24
  Text: "text", Numeric: "numeric", Integer: "integer", Serial: "serial",
@@ -66,13 +66,14 @@ function finding(ts, sf, node, code, message) {
66
66
  function decoratorsOf(ts, node) {
67
67
  return (ts.canHaveDecorators?.(node) ? ts.getDecorators(node) : undefined) ?? [];
68
68
  }
69
- function decoratorCall(ts, dec) {
69
+ function decoratorCall(ts, dec, sf) {
70
70
  const e = dec.expression;
71
- if (ts.isCallExpression(e) && ts.isIdentifier(e.expression)) {
72
- return { name: e.expression.text, args: [...e.arguments] };
71
+ if (ts.isCallExpression(e)) {
72
+ const name = calleeIdentity(ts, sf, e.expression);
73
+ return name ? { name, args: [...e.arguments] } : null;
73
74
  }
74
- if (ts.isIdentifier(e)) return { name: e.text, args: [] };
75
- return null;
75
+ const name = calleeIdentity(ts, sf, e);
76
+ return name ? { name, args: [] } : null;
76
77
  }
77
78
  function objectMap(ts, node) {
78
79
  const map = new Map();
@@ -103,10 +104,10 @@ function stringArray(ts, node) {
103
104
  }
104
105
  return out;
105
106
  }
106
- function thunkTarget(ts, arg) {
107
+ function thunkTarget(ts, sf, arg) {
107
108
  if (arg && ts.isArrowFunction(arg)) {
108
109
  const b = arg.body;
109
- if (ts.isIdentifier(b)) return b.text;
110
+ if (ts.isIdentifier(b)) return resolveLocalName(sf, b.text);
110
111
  if (ts.isPropertyAccessExpression(b)) return b.name.text;
111
112
  }
112
113
  return null;
@@ -120,22 +121,112 @@ function arraySpreadElements(ts, node) {
120
121
  return node.elements.filter((e) => ts.isSpreadElement(e));
121
122
  }
122
123
 
124
+ // ── identity: aliased named imports and '@suppa/sdk' namespace imports ──
125
+ // `import { Things as Thing }` / `import * as sdk from '@suppa/sdk'` name the
126
+ // very same declarations; matching bare identifiers alone misses them.
127
+ function analyzeImports(ts, sf) {
128
+ const alias = new Map(); // local name -> imported (exported) name
129
+ const namespaces = new Set(); // local name of `import * as X from '@suppa/sdk'`
130
+ for (const st of sf.statements) {
131
+ if (!ts.isImportDeclaration(st) || !st.importClause) continue;
132
+ const from = ts.isStringLiteral(st.moduleSpecifier) ? st.moduleSpecifier.text : "";
133
+ const bindings = st.importClause.namedBindings;
134
+ if (bindings && ts.isNamespaceImport(bindings)) {
135
+ if (from === "@suppa/sdk") namespaces.add(bindings.name.text);
136
+ } else if (bindings && ts.isNamedImports(bindings)) {
137
+ for (const el of bindings.elements) {
138
+ alias.set(el.name.text, (el.propertyName ?? el.name).text);
139
+ }
140
+ }
141
+ }
142
+ sf.suppaImports = { alias, namespaces };
143
+ }
144
+ function importsOf(sf) {
145
+ return sf.suppaImports ?? { alias: new Map(), namespaces: new Set() };
146
+ }
147
+ /** local identifier text -> the name it was imported under (or itself) */
148
+ function resolveLocalName(sf, text) {
149
+ return importsOf(sf).alias.get(text) ?? text;
150
+ }
151
+ /** node is `name`, an alias of it, or `<sdkNamespace>.name` */
152
+ function isSdkQualified(ts, sf, node, name) {
153
+ if (!node) return false;
154
+ if (ts.isIdentifier(node)) return resolveLocalName(sf, node.text) === name;
155
+ if (ts.isPropertyAccessExpression(node) && node.name.text === name &&
156
+ ts.isIdentifier(node.expression)) {
157
+ return importsOf(sf).namespaces.has(node.expression.text);
158
+ }
159
+ return false;
160
+ }
161
+ function calleeIdentity(ts, sf, expr) {
162
+ if (ts.isIdentifier(expr)) return resolveLocalName(sf, expr.text);
163
+ if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression) &&
164
+ importsOf(sf).namespaces.has(expr.expression.text)) {
165
+ return expr.name.text;
166
+ }
167
+ return null;
168
+ }
169
+
170
+ // ── string-ness of an expression (no type checker available) ──
171
+ /** provably NOT a string at runtime */
172
+ function isProvableNonString(ts, n) {
173
+ if (n.kind === ts.SyntaxKind.TrueKeyword || n.kind === ts.SyntaxKind.FalseKeyword ||
174
+ n.kind === ts.SyntaxKind.NullKeyword) return true;
175
+ if (ts.isNumericLiteral(n) || ts.isBigIntLiteral(n)) return true;
176
+ if (ts.isPrefixUnaryExpression(n) &&
177
+ (ts.isNumericLiteral(n.operand) || ts.isBigIntLiteral(n.operand))) return true;
178
+ if (ts.isArrayLiteralExpression(n) || ts.isObjectLiteralExpression(n)) return true;
179
+ if (ts.isNewExpression(n)) return true;
180
+ return false;
181
+ }
182
+ /** provably a string at runtime (literal, template, or a `+` chain with one) */
183
+ function isProvableString(ts, n) {
184
+ if (ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n) ||
185
+ ts.isTemplateExpression(n)) return true;
186
+ if (ts.isParenthesizedExpression(n)) return isProvableString(ts, n.expression);
187
+ if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.PlusToken) {
188
+ return isProvableString(ts, n.left) || isProvableString(ts, n.right);
189
+ }
190
+ return false;
191
+ }
192
+ /** strip `(x)`, `x as T`, `x!` — they do not change the runtime value */
193
+ function unwrapExpr(ts, n) {
194
+ let cur = n;
195
+ while (cur && (ts.isParenthesizedExpression(cur) || ts.isAsExpression(cur) ||
196
+ ts.isNonNullExpression(cur) || ts.isSatisfiesExpression?.(cur) === true)) {
197
+ cur = cur.expression;
198
+ }
199
+ return cur;
200
+ }
201
+ /** an expression whose value this AST-only checker cannot see */
202
+ function isOpaqueExpression(ts, n) {
203
+ return ts.isIdentifier(n) || ts.isCallExpression(n) ||
204
+ ts.isPropertyAccessExpression(n) || ts.isElementAccessExpression(n) ||
205
+ ts.isAwaitExpression(n) || ts.isConditionalExpression(n);
206
+ }
207
+
123
208
  // ── extraction: entities ──
124
209
  function analyzeEntities(ts, sf, model) {
125
210
  sf.forEachChild(function walk(node) {
126
211
  if (ts.isClassDeclaration(node)) {
127
- const decs = decoratorsOf(ts, node).map((d) => decoratorCall(ts, d)).filter(Boolean);
212
+ const decs = decoratorsOf(ts, node).map((d) => decoratorCall(ts, d, sf)).filter(Boolean);
128
213
  const entityDec = decs.find((d) => d.name === "Entity");
129
214
  if (entityDec) {
130
215
  const className = node.name ? node.name.text : "<anonymous>";
131
216
  const options = objectMap(ts, entityDec.args[0]);
217
+ const keysNode = options.get("importKeyFields");
132
218
  const info = {
133
219
  className,
134
220
  entityName: stringValue(ts, options.get("name")) ?? className,
135
221
  sf, node, options, optionsNode: entityDec.args[0],
136
- importKeyFields: stringArray(ts, options.get("importKeyFields")),
222
+ importKeyFields: stringArray(ts, keysNode),
223
+ // present but not a readable array of string literals: the key checks
224
+ // cannot run, but claiming it is missing would be a lie (CB-8)
225
+ importKeyFieldsUnreadable: !!keysNode && stringArray(ts, keysNode) === null,
226
+ importKeyFieldsNode: keysNode ?? null,
137
227
  hasKey: options.has("key"),
138
228
  properties: new Map(),
229
+ columnNames: new Set(), // literal `name` options of @Column/relations
139
230
  };
140
231
  for (const member of node.members) {
141
232
  if (!ts.isPropertyDeclaration(member) || !member.name) continue;
@@ -143,11 +234,13 @@ function analyzeEntities(ts, sf, model) {
143
234
  ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)
144
235
  ? member.name.text
145
236
  : member.name.getText(sf);
146
- for (const d of decoratorsOf(ts, member).map((x) => decoratorCall(ts, x)).filter(Boolean)) {
237
+ for (const d of decoratorsOf(ts, member).map((x) => decoratorCall(ts, x, sf)).filter(Boolean)) {
147
238
  if (d.name === "Column") {
239
+ const columnOptions = objectMap(ts, d.args[0]);
148
240
  info.properties.set(propName, {
149
241
  kind: "column", node: member, decorator: d,
150
- columnOptions: objectMap(ts, d.args[0]), optionsNode: d.args[0],
242
+ columnOptions, optionsNode: d.args[0],
243
+ nameNode: columnOptions.get("name") ?? null,
151
244
  });
152
245
  } else if (ENUM_DECORATORS.has(d.name)) {
153
246
  info.properties.set(propName, {
@@ -161,13 +254,22 @@ function analyzeEntities(ts, sf, model) {
161
254
  node: member, decorator: d,
162
255
  });
163
256
  } else if (d.name in RELATION_KIND_BY_DECORATOR) {
257
+ // (target, options?) or (target, inverse, options?) — the options
258
+ // object is whichever trailing argument is an object literal
259
+ const relOptions = objectMap(
260
+ ts, [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)),
261
+ );
164
262
  info.properties.set(propName, {
165
263
  kind: RELATION_KIND_BY_DECORATOR[d.name],
166
264
  node: member, decorator: d,
167
- targetClass: thunkTarget(ts, d.args[0]),
265
+ targetClass: thunkTarget(ts, sf, d.args[0]),
266
+ nameNode: relOptions.get("name") ?? null,
168
267
  });
169
268
  }
170
269
  }
270
+ const prop = info.properties.get(propName);
271
+ const colName = prop && stringValue(ts, prop.nameNode);
272
+ if (colName) info.columnNames.add(colName);
171
273
  }
172
274
  model.entities.set(className, info);
173
275
  model.entityByName.set(info.entityName, info);
@@ -177,8 +279,97 @@ function analyzeEntities(ts, sf, model) {
177
279
  });
178
280
  }
179
281
 
282
+ // ── rules: tabular parts ──
283
+ /**
284
+ * Doc: "Three things make an entity a tabular part. All three are required,
285
+ * and the platform does not infer any of them: type: 'tabular-part' on
286
+ * @Entity(), relationEntityName — the name of the parent entity, and a
287
+ * @ManyToOne field named owner pointing at the parent class."
288
+ * Conversely, relationEntityName without type: 'tabular-part' is the doc's
289
+ * own mistake row: "type: 'tabular-part' or relationEntityName is missing,
290
+ * so it is listed under /related instead."
291
+ */
292
+ function checkTabularPart(ts, info, model, findings) {
293
+ const sf = info.sf;
294
+ const anchor = info.node.name ?? info.node;
295
+ const TRIAD = `"All three are required, and the platform does not infer any of them" (type: 'tabular-part', relationEntityName, and a @ManyToOne field named owner)`;
296
+
297
+ const hasType = info.options.has("type");
298
+ const typeNode = info.options.get("type");
299
+ const typeLiteral = hasType ? stringValue(ts, typeNode) : null;
300
+ const typeUnreadable = hasType && typeLiteral === null;
301
+
302
+ const hasRelName = info.options.has("relationEntityName");
303
+ const relNode = info.options.get("relationEntityName");
304
+ const relLiteral = hasRelName ? stringValue(ts, relNode) : null;
305
+ const relUnreadable = hasRelName && relLiteral === null;
306
+
307
+ // an unreadable type/relationEntityName (identifier, expression, …) means
308
+ // this checker cannot tell whether the entity is a tabular part at all —
309
+ // warn instead of guessing E108 one way or the other.
310
+ if (typeUnreadable || relUnreadable) {
311
+ const badNode = typeUnreadable ? typeNode : relNode;
312
+ const badOpt = typeUnreadable ? "type" : "relationEntityName";
313
+ findings.push(finding(ts, sf, badNode, "W606",
314
+ `cannot statically verify '${badOpt}' of '${info.className}' — it is delivered by reference or an expression this checker cannot evaluate, so the tabular-part checks (E108-E110, W607) are skipped; inline the literal to restore checking`));
315
+ return;
316
+ }
317
+
318
+ const isTabularPart = typeLiteral === "tabular-part";
319
+ // `owner` is a @ManyToOne relation named 'owner' by PROPERTY name, or one
320
+ // whose literal @ManyToOne({ name: 'owner' }) column-name option is 'owner'
321
+ // (F4) — E106 (DA-2) already accepts a column name as a field identity, so
322
+ // E108's notion of "the owner relation" must agree.
323
+ const ownerProp = [...info.properties.entries()].find(
324
+ ([propName, p]) => p.kind === "many-to-one" &&
325
+ (propName === "owner" || stringValue(ts, p.nameNode) === "owner"),
326
+ )?.[1];
327
+ const hasOwner = !!ownerProp;
328
+
329
+ // an @Entity() options spread may hide `type`/`relationEntityName` (they are
330
+ // spread properties, not readable PropertyAssignments) — the W606 already
331
+ // fired for the spread promises these doc-rule checks are skipped, so the
332
+ // two option-presence branches below must not also false-positive E108. The
333
+ // missing-`owner` branch is a class member a spread cannot deliver, so it
334
+ // stays ungated.
335
+ const optionsSpread = spreadElements(ts, info.optionsNode).length > 0;
336
+
337
+ if (isTabularPart) {
338
+ if (!hasRelName && !optionsSpread) {
339
+ findings.push(finding(ts, sf, anchor, "E108",
340
+ `tabular part '${info.className}' (type: 'tabular-part') is missing relationEntityName — ${TRIAD}`));
341
+ }
342
+ if (!hasOwner) {
343
+ findings.push(finding(ts, sf, anchor, "E108",
344
+ `tabular part '${info.className}' (type: 'tabular-part') has no @ManyToOne relation named 'owner' pointing at the parent — ${TRIAD}`));
345
+ }
346
+ } else if (hasRelName && !optionsSpread) {
347
+ findings.push(finding(ts, sf, relNode, "E108",
348
+ `entity '${info.className}' sets relationEntityName but not type: 'tabular-part' — "type: 'tabular-part' or relationEntityName is missing, so it is listed under /related instead"`));
349
+ }
350
+
351
+ if (hasRelName && hasOwner && ownerProp.targetClass) {
352
+ const target = model.entities.get(ownerProp.targetClass);
353
+ if (target && target.entityName !== relLiteral) {
354
+ findings.push(finding(ts, sf, ownerProp.node, "E109",
355
+ `tabular part '${info.className}': owner points at '${target.entityName}' but relationEntityName is '${relLiteral}' — the owner relation's target and relationEntityName must name the same parent entity`));
356
+ }
357
+ }
358
+
359
+ if (isTabularPart && hasOwner && !info.importKeyFieldsUnreadable && info.importKeyFields) {
360
+ const idx = info.importKeyFields.indexOf("owner");
361
+ if (idx === -1) {
362
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "E110",
363
+ `tabular part '${info.className}' importKeyFields ${JSON.stringify(info.importKeyFields)} does not include 'owner' — "owner is missing from importKeyFields, so the key is matched globally" ⇒ duplicate rows across different parents`));
364
+ } else if (idx !== 0) {
365
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "W607",
366
+ `tabular part '${info.className}': "Put owner first in importKeyFields" — it is at position ${idx}`));
367
+ }
368
+ }
369
+ }
370
+
180
371
  // ── rules: entities ──
181
- function checkEntity(ts, info, sdk, findings) {
372
+ function checkEntity(ts, info, sdk, model, findings) {
182
373
  const sf = info.sf;
183
374
  const anchor = info.node.name ?? info.node;
184
375
 
@@ -186,8 +377,7 @@ function checkEntity(ts, info, sdk, findings) {
186
377
  (h) => h.token === ts.SyntaxKind.ExtendsKeyword,
187
378
  );
188
379
  const base = heritage?.types?.[0]?.expression;
189
- const baseName = base && ts.isIdentifier(base) ? base.text : null;
190
- if (baseName !== "SystemBaseEntity") {
380
+ if (!isSdkQualified(ts, sf, base, "SystemBaseEntity")) {
191
381
  findings.push(finding(ts, sf, anchor, "E101",
192
382
  `entity class '${info.className}' must extend SystemBaseEntity — it contributes id/createdAt/updatedAt/deletedAt/createdBy/removedBy (doc: "Every entity must extend SystemBaseEntity")`));
193
383
  }
@@ -204,11 +394,15 @@ function checkEntity(ts, info, sdk, findings) {
204
394
  `@Entity() options include a spread — options delivered via spread cannot be statically validated: the doc-rule checks (unknown options, default-as-SQL-string, type checks) are skipped for spread content; inline the options to restore checking`));
205
395
  }
206
396
 
207
- if (info.importKeyFields) {
397
+ if (info.importKeyFieldsUnreadable) {
398
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "W606",
399
+ `cannot statically verify importKeyFields of '${info.className}' — it is delivered by reference or spread, so record-level key checks (E106, E205) are skipped; inline the array of field names to restore checking`));
400
+ } else if (info.importKeyFields) {
208
401
  for (const f of info.importKeyFields) {
209
- if (!info.properties.has(f)) {
210
- findings.push(finding(ts, sf, info.options.get("importKeyFields"), "E106",
211
- `importKeyFields names '${f}' but the class declares no such property — seeds would have nothing to match on`));
402
+ // a field may be named by its property name or by its @Column({ name }) (DA-2)
403
+ if (!info.properties.has(f) && !info.columnNames.has(f)) {
404
+ findings.push(finding(ts, sf, info.importKeyFieldsNode, "E106",
405
+ `importKeyFields names '${f}' but the class declares no such property or column name — seeds would have nothing to match on`));
212
406
  }
213
407
  }
214
408
  }
@@ -218,11 +412,19 @@ function checkEntity(ts, info, sdk, findings) {
218
412
  `entity '${info.className}' has no 'key' option — a rename will be treated as drop-and-create instead of a rename (doc TIP)`));
219
413
  }
220
414
 
415
+ checkTabularPart(ts, info, model, findings);
416
+
221
417
  for (const [propName, prop] of info.properties) {
222
418
  if (SYSTEM_COLUMNS.includes(propName)) {
223
419
  findings.push(finding(ts, sf, prop.node, "E102",
224
420
  `system column '${propName}' is provided by SystemBaseEntity — "you never declare them yourself"`));
225
421
  }
422
+ // the table-level conflict is on the COLUMN name, which `name` overrides
423
+ const colName = stringValue(ts, prop.nameNode);
424
+ if (colName && SYSTEM_COLUMNS.includes(colName)) {
425
+ findings.push(finding(ts, sf, prop.nameNode, "E102",
426
+ `column name '${colName}' on property '${propName}' collides with the system column of the same name provided by SystemBaseEntity — "you never declare them yourself"`));
427
+ }
226
428
  if (prop.kind === "column") checkColumn(ts, sf, prop, sdk, findings);
227
429
  if (prop.kind in { "many-to-one": 1, "many-to-many": 1, "many-to-many-backref": 1, "one-to-many": 1 } &&
228
430
  prop.targetClass === null) {
@@ -280,9 +482,15 @@ function checkColumn(ts, sf, prop, sdk, findings) {
280
482
  }
281
483
 
282
484
  const def = opts.get("default");
283
- if (def && stringValue(ts, def) === null) {
284
- findings.push(finding(ts, sf, def, "E103",
285
- `'default' must be a SQL expression STRING — "Write default: 'false', not default: false, and default: \\"'draft'\\" for a string literal"`));
485
+ if (def) {
486
+ const val = unwrapExpr(ts, def);
487
+ if (isProvableNonString(ts, val)) {
488
+ findings.push(finding(ts, sf, def, "E103",
489
+ `'default' must be a SQL expression STRING — "Write default: 'false', not default: false, and default: \\"'draft'\\" for a string literal"`));
490
+ } else if (!isProvableString(ts, val)) {
491
+ findings.push(finding(ts, sf, def, "W606",
492
+ `cannot statically verify that 'default' is a SQL expression string — it is delivered by reference or by an expression this checker cannot evaluate, so the check is skipped; inline a literal SQL string to restore checking`));
493
+ }
286
494
  }
287
495
  if (opts.has("length") && typeValue !== null && typeValue !== "text") {
288
496
  findings.push(finding(ts, sf, opts.get("length"), "W603",
@@ -294,6 +502,23 @@ function checkColumn(ts, sf, prop, sdk, findings) {
294
502
  }
295
503
  }
296
504
 
505
+ // ── extraction: string enums (createSeed(EnumName.Member) resolution) ──
506
+ function analyzeEnums(ts, sf, model) {
507
+ sf.forEachChild(function walk(node) {
508
+ if (ts.isEnumDeclaration(node)) {
509
+ const members = new Map();
510
+ for (const m of node.members) {
511
+ const name = ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)
512
+ ? m.name.text : m.name.getText(sf);
513
+ const value = stringValue(ts, m.initializer);
514
+ if (value !== null) members.set(name, value);
515
+ }
516
+ if (members.size) model.stringEnums.set(node.name.text, members);
517
+ }
518
+ ts.forEachChild(node, walk);
519
+ });
520
+ }
521
+
297
522
  // ── extraction: seeds ──
298
523
  function analyzeSeeds(ts, sf, model) {
299
524
  sf.forEachChild(function walk(node) {
@@ -301,12 +526,16 @@ function analyzeSeeds(ts, sf, model) {
301
526
  for (const decl of node.declarationList.declarations) {
302
527
  const init = decl.initializer;
303
528
  if (init && ts.isCallExpression(init) &&
304
- ts.isIdentifier(init.expression) && init.expression.text === "createSeed") {
529
+ isSdkQualified(ts, sf, init.expression, "createSeed")) {
305
530
  const exportName = ts.isIdentifier(decl.name) ? decl.name.text : decl.name.getText(sf);
306
531
  const arg0 = init.arguments[0];
307
532
  let entityName = stringValue(ts, arg0);
308
- if (entityName === null && arg0 && ts.isPropertyAccessExpression(arg0)) {
309
- entityName = arg0.name.text; // EntityNamesEnum.Workflows → "Workflows"
533
+ let enumRef = null;
534
+ if (entityName === null && arg0 && ts.isPropertyAccessExpression(arg0) &&
535
+ ts.isIdentifier(arg0.expression)) {
536
+ // EntityNamesEnum.Workflows — the VALUE is what createSeed receives;
537
+ // the member name is only a fallback (resolved after every file is read)
538
+ enumRef = { enumName: arg0.expression.text, member: arg0.name.text };
310
539
  }
311
540
  const arg1 = init.arguments[1];
312
541
  let records = null; // null = thin seed (imported payload) — record checks impossible
@@ -317,7 +546,7 @@ function analyzeSeeds(ts, sf, model) {
317
546
  : { node: e, map: new Map(), hasSpread: false, spreads: [], byRef: true },
318
547
  );
319
548
  }
320
- model.seeds.push({ exportName, entityName, sf, node: init, records });
549
+ model.seeds.push({ exportName, entityName, enumRef, sf, node: init, records });
321
550
  }
322
551
  }
323
552
  }
@@ -326,10 +555,59 @@ function analyzeSeeds(ts, sf, model) {
326
555
  }
327
556
 
328
557
  // ── rules: seeds ──
558
+ /**
559
+ * `{ name: '<global enum name>', value: '<enum value>' }`. Extra keys are legal
560
+ * (the doc gives the shape, it never forbids more). A reference or a spread is
561
+ * unverifiable — warn instead of hard-erroring on code that may well be correct.
562
+ */
563
+ function checkEnumRef(ts, sf, key, valNode, prop, findings) {
564
+ const root = unwrapExpr(ts, valNode);
565
+ if (root.kind === ts.SyntaxKind.NullKeyword) return;
566
+ const multi = prop.kind === "multi-enum";
567
+ const shapeHint = multi ? " — an array of those for @MultiEnum" : "";
568
+ const unverifiable = () => findings.push(finding(ts, sf, valNode, "W606",
569
+ `cannot statically verify enum reference '${key}' — it is delivered by reference or spread, so the shape check (E206) is skipped; inline { name, value } to restore checking`));
570
+ const wrongShape = (n) => findings.push(finding(ts, sf, n, "E206",
571
+ `enum reference '${key}' must be { name: '<global enum name>', value: '<enum value>' }${shapeHint}`));
572
+
573
+ let refs;
574
+ if (multi) {
575
+ if (!ts.isArrayLiteralExpression(root)) {
576
+ if (isOpaqueExpression(ts, root)) return unverifiable();
577
+ return wrongShape(valNode);
578
+ }
579
+ if (arraySpreadElements(ts, root).length > 0) return unverifiable();
580
+ refs = root.elements.map((e) => unwrapExpr(ts, e));
581
+ } else {
582
+ refs = [root];
583
+ }
584
+
585
+ for (const ref of refs) {
586
+ if (!ts.isObjectLiteralExpression(ref)) {
587
+ if (isOpaqueExpression(ts, ref)) { unverifiable(); continue; }
588
+ wrongShape(ref);
589
+ continue;
590
+ }
591
+ if (spreadElements(ts, ref).length > 0) { unverifiable(); continue; }
592
+ const m = objectMap(ts, ref);
593
+ if (!m.has("name") || !m.has("value")) { wrongShape(ref); continue; }
594
+ const given = stringValue(ts, m.get("name"));
595
+ if (prop.enumGlobalName && given !== null && given !== prop.enumGlobalName) {
596
+ findings.push(finding(ts, sf, m.get("name"), "E206",
597
+ `enum reference '${key}' names global enum '${given}', but the property is declared as @${multi ? "MultiEnum" : "Enum"}('${prop.enumGlobalName}') — the names must match`));
598
+ }
599
+ }
600
+ }
601
+
329
602
  function checkSeed(ts, seed, model, findings) {
330
603
  const sf = seed.sf;
331
604
  const entity = seed.entityName ? model.entityByName.get(seed.entityName) : undefined;
332
- if (entity && (!entity.importKeyFields || entity.importKeyFields.length === 0)) {
605
+ if (!entity) {
606
+ // platform entity, a typo, or simply a file outside the analyzed set — say so
607
+ findings.push(finding(ts, sf, seed.node, "W606",
608
+ `target entity '${seed.entityName ?? "<unresolved>"}' of seed '${seed.exportName}' is not among the analyzed entities — record-level checks (E203-E206, W605) are skipped for it`));
609
+ } else if (!entity.importKeyFieldsUnreadable &&
610
+ (!entity.importKeyFields || entity.importKeyFields.length === 0)) {
333
611
  findings.push(finding(ts, sf, seed.node, "W605",
334
612
  `entity '${seed.entityName}' has a seed but no importKeyFields — "seeds have nothing to match on and cannot stay idempotent"`));
335
613
  }
@@ -362,23 +640,12 @@ function checkSeed(ts, seed, model, findings) {
362
640
  `relation '${key}' referenced by numeric id — ids "do not match across tenants"; reference through the target's importKeyFields, e.g. { name: 'Default' }`));
363
641
  }
364
642
  }
365
- if (prop.kind === "one-to-many") {
643
+ if (prop.kind === "one-to-many" || prop.kind === "many-to-many-backref") {
366
644
  findings.push(finding(ts, sf, valNode, "E204",
367
- `reverse @OneToMany field '${key}' in a seed (even as []) — "back references cannot be inserted; the import throws". Seed the child entity with its own seed.`));
645
+ `reverse relation field '${key}' (@${prop.decorator.name}) in a seed (even as []) — "back references cannot be inserted; the import throws". Seed the owning entity with its own seed.`));
368
646
  }
369
647
  if (prop.kind === "enum" || prop.kind === "multi-enum") {
370
- const okRef = (n) => {
371
- if (!ts.isObjectLiteralExpression(n)) return false;
372
- const m = objectMap(ts, n);
373
- return m.has("name") && m.has("value") && m.size === 2;
374
- };
375
- const ok = prop.kind === "enum"
376
- ? okRef(valNode)
377
- : ts.isArrayLiteralExpression(valNode) && valNode.elements.every(okRef);
378
- if (!ok && valNode.kind !== ts.SyntaxKind.NullKeyword) {
379
- findings.push(finding(ts, sf, valNode, "E206",
380
- `enum reference '${key}' must be { name: '<global enum name>', value: '<enum value>' }${prop.kind === "multi-enum" ? " — an array of those for @MultiEnum" : ""}`));
381
- }
648
+ checkEnumRef(ts, sf, key, valNode, prop, findings);
382
649
  }
383
650
  }
384
651
  for (const spread of rec.spreads ?? []) {
@@ -386,7 +653,28 @@ function checkSeed(ts, seed, model, findings) {
386
653
  `seed record content delivered via spread cannot be statically validated — E201-E206 checks are skipped for spread content; inline the record fields to restore checking`));
387
654
  }
388
655
  if (rec.hasSpread) continue; // spread may deliver the import key — E205 would false-positive
389
- if (entity?.importKeyFields?.length && !rec.map.has("$key")) {
656
+ if (!entity) continue;
657
+
658
+ // $key overrides identity per record — but only if it can establish one
659
+ if (rec.map.has("$key")) {
660
+ const keyNode = rec.map.get("$key");
661
+ const keyValue = unwrapExpr(ts, keyNode);
662
+ if (ts.isObjectLiteralExpression(keyValue)) {
663
+ if (keyValue.properties.length === 0) {
664
+ findings.push(finding(ts, sf, keyNode, "E205",
665
+ `seed record's $key is an empty object — it cannot establish identity for '${seed.entityName}' ⇒ duplicate rows after every restart. Give $key the fields that identify the record.`));
666
+ }
667
+ } else if (isOpaqueExpression(ts, keyValue)) {
668
+ findings.push(finding(ts, sf, keyNode, "W606",
669
+ `cannot statically verify the $key of this '${seed.entityName}' record — it is delivered by reference, so the identity check (E205) is skipped; inline the $key object to restore checking`));
670
+ } else {
671
+ findings.push(finding(ts, sf, keyNode, "E205",
672
+ `seed record's $key must be an object of identifying fields, e.g. $key: { name: 'Default' } — this value cannot establish identity for '${seed.entityName}' ⇒ duplicate rows after every restart.`));
673
+ }
674
+ continue;
675
+ }
676
+
677
+ if (entity.importKeyFields?.length) {
390
678
  for (const f of entity.importKeyFields) {
391
679
  if (!rec.map.has(f)) {
392
680
  findings.push(finding(ts, sf, rec.node, "E205",
@@ -398,42 +686,69 @@ function checkSeed(ts, seed, model, findings) {
398
686
  }
399
687
 
400
688
  // ── extraction: EntityModule.forFeature ──
689
+ /**
690
+ * Doc resolution order: "If the entities array is passed AND NOT EMPTY it is
691
+ * used and entitiesPath is ignored; otherwise entities are loaded from
692
+ * entitiesPath" — same for seeds/seedsPath. The two sides are independent, so
693
+ * each gets its own mode: "explicit" | "autoload" | "unverifiable".
694
+ */
401
695
  function analyzeModules(ts, sf, model) {
402
696
  sf.forEachChild(function walk(node) {
403
697
  if (ts.isCallExpression(node) &&
404
698
  ts.isPropertyAccessExpression(node.expression) &&
405
699
  node.expression.name.text === "forFeature" &&
406
- ts.isIdentifier(node.expression.expression) &&
407
- node.expression.expression.text === "EntityModule") {
408
- const m = {
409
- sf, node, shape: null,
410
- entityClassNames: [], seedExportNames: [], seedsNode: node,
411
- entitiesPath: null, seedsPath: null, entitiesPathNode: null, seedsPathNode: null,
412
- entitiesSpreads: [], seedsSpreads: [],
413
- };
414
- const a0 = node.arguments[0];
415
- if (a0 && ts.isArrayLiteralExpression(a0)) {
416
- m.shape = "classes";
417
- m.entityClassNames = a0.elements.filter((e) => ts.isIdentifier(e)).map((e) => e.text);
418
- m.entitiesSpreads = arraySpreadElements(ts, a0);
419
- const opts = objectMap(ts, node.arguments[1]);
420
- const seeds = opts.get("seeds");
421
- if (seeds && ts.isArrayLiteralExpression(seeds)) {
422
- m.seedExportNames = seeds.elements.filter((e) => ts.isIdentifier(e)).map((e) => e.text);
423
- m.seedsNode = seeds;
424
- m.seedsSpreads = arraySpreadElements(ts, seeds);
700
+ isSdkQualified(ts, sf, node.expression.expression, "EntityModule")) {
701
+ const a0 = node.arguments[0] ? unwrapExpr(ts, node.arguments[0]) : undefined;
702
+ const a0IsArray = a0 && ts.isArrayLiteralExpression(a0);
703
+ const a0IsOptions = a0 && ts.isObjectLiteralExpression(a0);
704
+ // options live in argument 1 next to an entities array, or ARE argument 0
705
+ const optionsNode = a0IsOptions ? a0 : node.arguments[1];
706
+ const opts = objectMap(ts, optionsNode);
707
+
708
+ const side = (label, arrayNode, pathNode, unreadableNode) => {
709
+ const s = {
710
+ label, mode: "autoload", names: [], spreads: [],
711
+ node, refNode: null, paths: null, pathNode: pathNode ?? null,
712
+ };
713
+ if (unreadableNode) {
714
+ s.mode = "unverifiable";
715
+ s.refNode = unreadableNode;
716
+ return s;
425
717
  }
426
- } else if (a0 && ts.isObjectLiteralExpression(a0)) {
427
- m.shape = "options";
428
- const opts = objectMap(ts, a0);
429
- for (const [key, prop] of [["entitiesPath", "entitiesPath"], ["seedsPath", "seedsPath"]]) {
430
- const n = opts.get(key);
431
- if (!n) continue;
432
- const single = stringValue(ts, n);
433
- m[prop] = single !== null ? [single] : stringArray(ts, n);
434
- m[`${prop}Node`] = n;
718
+ if (arrayNode && arrayNode.elements.length > 0) {
719
+ s.mode = "explicit";
720
+ s.node = arrayNode;
721
+ s.names = arrayNode.elements
722
+ .filter((e) => ts.isIdentifier(e))
723
+ .map((e) => resolveLocalName(sf, e.text)); // aliases resolve to the exported name
724
+ s.spreads = arraySpreadElements(ts, arrayNode);
725
+ return s;
435
726
  }
436
- }
727
+ // absent or empty array -> the path decides; read it when it is readable
728
+ if (pathNode) {
729
+ const single = stringValue(ts, pathNode);
730
+ s.paths = single !== null ? [single] : stringArray(ts, pathNode);
731
+ }
732
+ return s;
733
+ };
734
+
735
+ const seedsNode = opts.get("seeds") ? unwrapExpr(ts, opts.get("seeds")) : undefined;
736
+ const m = {
737
+ sf, node,
738
+ entities: side(
739
+ "entitiesPath",
740
+ a0IsArray ? a0 : null,
741
+ opts.get("entitiesPath"),
742
+ a0 && !a0IsArray && !a0IsOptions ? a0 : null,
743
+ ),
744
+ seeds: side(
745
+ "seedsPath",
746
+ seedsNode && ts.isArrayLiteralExpression(seedsNode) ? seedsNode : null,
747
+ opts.get("seedsPath"),
748
+ seedsNode && !ts.isArrayLiteralExpression(seedsNode) ? seedsNode
749
+ : (a0 && !a0IsArray && !a0IsOptions && !optionsNode ? a0 : null),
750
+ ),
751
+ };
437
752
  model.modules.push(m);
438
753
  }
439
754
  ts.forEachChild(node, walk);
@@ -442,18 +757,20 @@ function analyzeModules(ts, sf, model) {
442
757
 
443
758
  // ── rules: registration ──
444
759
  function checkRegistration(ts, model, findings) {
445
- const classModules = model.modules.filter((m) => m.shape === "classes");
446
- const optionModules = model.modules.filter((m) => m.shape === "options");
447
-
448
- for (const m of optionModules) {
449
- for (const [label, paths, pnode] of [
450
- ["entitiesPath", m.entitiesPath, m.entitiesPathNode],
451
- ["seedsPath", m.seedsPath, m.seedsPathNode],
452
- ]) {
453
- for (const p of paths ?? []) {
760
+ // E303/W606 on autoload paths — only for the side that actually autoloads:
761
+ // a path the resolution order ignores is dead config, not a mistake.
762
+ for (const m of model.modules) {
763
+ for (const side of [m.entities, m.seeds]) {
764
+ if (side.mode !== "autoload" || !side.pathNode) continue;
765
+ if (side.paths === null) {
766
+ findings.push(finding(ts, m.sf, side.pathNode, "W606",
767
+ `cannot statically verify ${side.label} — it is delivered by reference or by an expression this checker cannot evaluate, so the dist/-vs-src/ check (E303) is skipped; inline the path string to restore checking`));
768
+ continue;
769
+ }
770
+ for (const p of side.paths) {
454
771
  if (/(^|\/)src(\/|$)/.test(p.replace(/\\/g, "/"))) {
455
- findings.push(finding(ts, m.sf, pnode ?? m.node, "E303",
456
- `${label} '${p}' points at src/ — autoloading reads compiled output: "entitiesPath / seedsPath points at src/ instead of compiled dist/"`));
772
+ findings.push(finding(ts, m.sf, side.pathNode, "E303",
773
+ `${side.label} '${p}' points at src/ — autoloading reads compiled output: "entitiesPath / seedsPath points at src/ instead of compiled dist/"`));
457
774
  }
458
775
  }
459
776
  }
@@ -465,27 +782,34 @@ function checkRegistration(ts, model, findings) {
465
782
  `no EntityModule.forFeature() found — "An entity class that is never passed to forFeature() is invisible — no table is created for it"`));
466
783
  return;
467
784
  }
468
- if (classModules.length === 0) return; // autoload shape: membership is the platform's job
469
785
 
470
- for (const m of classModules) {
471
- for (const spread of m.entitiesSpreads) {
786
+ for (const m of model.modules) {
787
+ for (const spread of m.entities.spreads) {
472
788
  findings.push(finding(ts, m.sf, spread, "W606",
473
789
  `EntityModule.forFeature() entities array includes a spread — membership cannot be statically verified: E301 (unregistered entity) is skipped for entities potentially covered by it; inline the array to restore checking`));
474
790
  }
475
- for (const spread of m.seedsSpreads) {
791
+ for (const spread of m.seeds.spreads) {
476
792
  findings.push(finding(ts, m.sf, spread, "W606",
477
793
  `EntityModule.forFeature() seeds array includes a spread — membership and ordering cannot be statically verified: E302 (unregistered seed) and E304 (seed ordering) are skipped for seeds potentially covered by it; inline the array to restore checking`));
478
794
  }
795
+ if (m.entities.mode === "unverifiable") {
796
+ findings.push(finding(ts, m.sf, m.entities.refNode, "W606",
797
+ `EntityModule.forFeature() entities are delivered by reference — membership cannot be statically verified: E301 (unregistered entity) is skipped; inline the array to restore checking`));
798
+ }
799
+ if (m.seeds.mode === "unverifiable" && m.seeds.refNode !== m.entities.refNode) {
800
+ findings.push(finding(ts, m.sf, m.seeds.refNode, "W606",
801
+ `EntityModule.forFeature() seeds are delivered by reference — membership and ordering cannot be statically verified: E302 (unregistered seed) and E304 (seed ordering) are skipped; inline the array to restore checking`));
802
+ }
479
803
  }
480
804
 
481
- // an autoload module anywhere may cover any entity/seed not named explicitly —
482
- // membership becomes the platform's job, so E301/E302 would only false-positive.
483
- const hasAutoload = optionModules.length > 0;
484
- const hasEntitiesSpread = classModules.some((m) => m.entitiesSpreads.length > 0);
485
- const hasSeedsSpread = classModules.some((m) => m.seedsSpreads.length > 0);
805
+ // an autoload (or unverifiable) module anywhere may cover any entity/seed not
806
+ // named explicitly — membership becomes the platform's job, so E301/E302 would
807
+ // only false-positive.
808
+ const entitiesUnknown = model.modules.some((m) => m.entities.mode !== "explicit" || m.entities.spreads.length > 0);
809
+ const seedsUnknown = model.modules.some((m) => m.seeds.mode !== "explicit" || m.seeds.spreads.length > 0);
486
810
 
487
- if (!hasAutoload && !hasEntitiesSpread) {
488
- const registeredEntities = new Set(classModules.flatMap((m) => m.entityClassNames));
811
+ if (!entitiesUnknown) {
812
+ const registeredEntities = new Set(model.modules.flatMap((m) => m.entities.names));
489
813
  for (const [className, info] of model.entities) {
490
814
  if (!registeredEntities.has(className)) {
491
815
  findings.push(finding(ts, info.sf, info.node.name ?? info.node, "E301",
@@ -493,8 +817,8 @@ function checkRegistration(ts, model, findings) {
493
817
  }
494
818
  }
495
819
  }
496
- if (!hasAutoload && !hasSeedsSpread) {
497
- const registeredSeeds = new Set(classModules.flatMap((m) => m.seedExportNames));
820
+ if (!seedsUnknown) {
821
+ const registeredSeeds = new Set(model.modules.flatMap((m) => m.seeds.names));
498
822
  for (const seed of model.seeds) {
499
823
  if (!registeredSeeds.has(seed.exportName)) {
500
824
  findings.push(finding(ts, seed.sf, seed.node, "E302",
@@ -503,9 +827,9 @@ function checkRegistration(ts, model, findings) {
503
827
  }
504
828
  }
505
829
 
506
- for (const m of classModules) {
507
- if (m.seedsSpreads.length > 0) continue; // ordering indices are unreliable with a spread present
508
- const order = new Map(m.seedExportNames.map((n, i) => [n, i]));
830
+ for (const m of model.modules) {
831
+ if (m.seeds.mode !== "explicit" || m.seeds.spreads.length > 0) continue;
832
+ const order = new Map(m.seeds.names.map((n, i) => [n, i]));
509
833
  const reported = new Set();
510
834
  for (const seed of model.seeds) {
511
835
  if (!order.has(seed.exportName) || !seed.records) continue;
@@ -518,14 +842,19 @@ function checkRegistration(ts, model, findings) {
518
842
  if (!prop || (prop.kind !== "many-to-one" && prop.kind !== "many-to-many") || !prop.targetClass) continue;
519
843
  const target = model.entities.get(prop.targetClass);
520
844
  if (!target || target === entity) continue;
521
- const targetSeed = model.seeds.find(
845
+ // an entity may have several seeds — what matters is the EARLIEST
846
+ // registered one, since it is the one that creates the rows first
847
+ const candidates = model.seeds.filter(
522
848
  (s) => s.entityName === target.entityName && order.has(s.exportName),
523
849
  );
524
- const dedupe = `${seed.exportName}->${targetSeed?.exportName}`;
525
- if (targetSeed && order.get(targetSeed.exportName) > myIdx && !reported.has(dedupe)) {
850
+ if (candidates.length === 0) continue;
851
+ const earliest = candidates.reduce((a, b) =>
852
+ order.get(a.exportName) <= order.get(b.exportName) ? a : b);
853
+ const dedupe = `${seed.exportName}->${target.entityName}`;
854
+ if (order.get(earliest.exportName) > myIdx && !reported.has(dedupe)) {
526
855
  reported.add(dedupe);
527
- findings.push(finding(ts, m.sf, m.seedsNode, "E304",
528
- `seed '${seed.exportName}' references '${target.entityName}' but '${targetSeed.exportName}' runs after it — "Register a seed after the seed that creates the records it points at"`));
856
+ findings.push(finding(ts, m.sf, m.seeds.node, "E304",
857
+ `seed '${seed.exportName}' references '${target.entityName}' but '${earliest.exportName}' runs after it — "Register a seed after the seed that creates the records it points at"`));
529
858
  }
530
859
  }
531
860
  }
@@ -536,19 +865,33 @@ function checkRegistration(ts, model, findings) {
536
865
  // ── rules: tsconfig ──
537
866
  function checkTsconfig(ts, rootDir, findings) {
538
867
  if (!rootDir) return;
539
- const p = join(resolve(rootDir), "tsconfig.json");
540
- if (!existsSync(p)) return;
541
- const read = ts.readConfigFile(p, (f) => readFileSync(f, "utf-8"));
542
- if (read.error) return;
543
- const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, resolve(rootDir));
544
- const missing = [];
545
- if (!parsed.options.experimentalDecorators) missing.push("experimentalDecorators");
546
- if (!parsed.options.emitDecoratorMetadata) missing.push("emitDecoratorMetadata");
547
- if (missing.length) {
548
- findings.push({
549
- file: p, line: 1, col: 1, code: "E401", level: "error",
550
- message: `tsconfig.json must enable ${missing.join(" and ")} — entities rely on decorator metadata`,
551
- });
868
+ // ts.readConfigFile compares the path it is given against its own normalized
869
+ // form while attaching a syntax diagnostic — a Windows path throws a Debug
870
+ // Failure there, so normalize, and never let this check kill the run.
871
+ try {
872
+ const root = resolve(rootDir).replace(/\\/g, "/");
873
+ const p = `${root}/tsconfig.json`;
874
+ if (!existsSync(p)) {
875
+ findings.push({
876
+ file: root, line: 1, col: 1, code: "W608", level: "warning",
877
+ message: `no tsconfig.json at ${root} — cannot verify experimentalDecorators/emitDecoratorMetadata, both of which entities rely on`,
878
+ });
879
+ return;
880
+ }
881
+ const read = ts.readConfigFile(p, (f) => readFileSync(f, "utf-8"));
882
+ if (read.error) return;
883
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, root);
884
+ const missing = [];
885
+ if (!parsed.options.experimentalDecorators) missing.push("experimentalDecorators");
886
+ if (!parsed.options.emitDecoratorMetadata) missing.push("emitDecoratorMetadata");
887
+ if (missing.length) {
888
+ findings.push({
889
+ file: p, line: 1, col: 1, code: "E401", level: "error",
890
+ message: `tsconfig.json must enable ${missing.join(" and ")} — entities rely on decorator metadata`,
891
+ });
892
+ }
893
+ } catch {
894
+ /* unreadable/malformed tsconfig — degrade silently rather than crash the run */
552
895
  }
553
896
  }
554
897
 
@@ -601,9 +944,21 @@ function loadSdkCatalog(ts, rootDir) {
601
944
  ts.forEachChild(node, walk);
602
945
  });
603
946
  let got = 0;
947
+ // fieldTypes are enum VALUES, not option names — an older SDK enum member
948
+ // set is the true, current set for this install, so replace outright.
949
+ // entityOptions/columnOptions are OPTION NAMES: an SDK whose typings
950
+ // predate a doc-documented option (e.g. relationEntityName) must not make
951
+ // that option look unknown (E501) — union with the doc list instead of
952
+ // replacing it (F1).
604
953
  if (Object.keys(fieldTypes).length) { catalog.fieldTypes = fieldTypes; got++; }
605
- if (entityOptions.length) { catalog.entityOptions = entityOptions; got++; }
606
- if (columnOptions.length) { catalog.columnOptions = columnOptions; got++; }
954
+ if (entityOptions.length) {
955
+ catalog.entityOptions = [...new Set([...entityOptions, ...DOC_ENTITY_OPTIONS])];
956
+ got++;
957
+ }
958
+ if (columnOptions.length) {
959
+ catalog.columnOptions = [...new Set([...columnOptions, ...DOC_COLUMN_OPTIONS])];
960
+ got++;
961
+ }
607
962
  catalog.source = got === 3 ? "sdk" : got > 0 ? "partial-sdk" : "doc";
608
963
  } catch { /* typings unreadable — doc fallback stands */ }
609
964
  return catalog;
@@ -613,17 +968,33 @@ function loadSdkCatalog(ts, rootDir) {
613
968
  export function validateSchema({ files = [], rootDir = null } = {}) {
614
969
  const ts = loadTypescript(rootDir);
615
970
  const sdk = loadSdkCatalog(ts, rootDir);
616
- const model = { entities: new Map(), entityByName: new Map(), seeds: [], modules: [] };
971
+ const model = {
972
+ entities: new Map(), entityByName: new Map(),
973
+ seeds: [], modules: [], stringEnums: new Map(),
974
+ };
617
975
  const findings = [];
618
- const sources = files.map((f) =>
619
- ts.createSourceFile(resolve(f), readFileSync(f, "utf-8"), ts.ScriptTarget.Latest, true),
976
+ // the CLI deduped; the exported API did not, and duplicated seeds duplicated findings
977
+ const uniqueFiles = [...new Set(files.map((f) => resolve(f)))];
978
+ const sources = uniqueFiles.map((f) =>
979
+ ts.createSourceFile(f, readFileSync(f, "utf-8"), ts.ScriptTarget.Latest, true),
620
980
  );
981
+ for (const sf of sources) analyzeImports(ts, sf);
982
+ for (const sf of sources) analyzeEnums(ts, sf, model);
621
983
  for (const sf of sources) {
622
984
  analyzeEntities(ts, sf, model);
623
985
  analyzeSeeds(ts, sf, model);
624
986
  analyzeModules(ts, sf, model);
625
987
  }
626
- for (const info of model.entities.values()) checkEntity(ts, info, sdk, findings);
988
+ // createSeed(EnumName.Member) passes the member's VALUE; the member name is
989
+ // only a fallback for enums declared outside the analyzed file set
990
+ for (const seed of model.seeds) {
991
+ if (seed.entityName === null && seed.enumRef) {
992
+ seed.entityName =
993
+ model.stringEnums.get(seed.enumRef.enumName)?.get(seed.enumRef.member) ??
994
+ seed.enumRef.member;
995
+ }
996
+ }
997
+ for (const info of model.entities.values()) checkEntity(ts, info, sdk, model, findings);
627
998
  for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
628
999
  checkRegistration(ts, model, findings);
629
1000
  checkTsconfig(ts, rootDir, findings);