suppa-mcp-2 1.2.2 → 1.2.4

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.
@@ -12,14 +12,25 @@
12
12
  */
13
13
  import { createRequire } from "node:module";
14
14
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
15
- import { dirname, join, relative, resolve } from "node:path";
15
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
16
16
  import { pathToFileURL } from "node:url";
17
17
 
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
21
  export const DOC_ENTITY_OPTIONS = ["name", "title", "comment", "representativeFieldName", "importKeyFields", "key", "icon", "type", "relationEntityName", "options"];
22
- export const DOC_COLUMN_OPTIONS = ["type", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask"];
22
+ export const DOC_COLUMN_OPTIONS = ["type", "subType", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask"];
23
+ /**
24
+ * The doc's subType matrix — "it means three unrelated things depending on the
25
+ * base type". Keyed by the CANONICAL FieldTypeEnum value, so E112 can be decided
26
+ * from whatever `checkColumn` resolved `type` to. The Enum/MultiEnum row of that
27
+ * matrix is deliberately absent: `subType` there is the enum's global name, set
28
+ * by @Enum()/@MultiEnum() and never written by hand — that is E113, not E112.
29
+ */
30
+ export const DOC_SUBTYPES_BY_TYPE = {
31
+ timestamp: ["date", "time", "timestamp"],
32
+ text: ["encrypted"],
33
+ };
23
34
  export const DOC_FIELD_TYPES = {
24
35
  Text: "text", Numeric: "numeric", Integer: "integer", Serial: "serial",
25
36
  Boolean: "boolean", Timestamp: "timestamp", JSON: "json", UUID: "uuid",
@@ -35,13 +46,21 @@ const RELATION_KIND_BY_DECORATOR = {
35
46
  ManyToOne: "many-to-one", ManyToMany: "many-to-many",
36
47
  ManyToManyBackRef: "many-to-many-backref", OneToMany: "one-to-many",
37
48
  };
49
+ const RELATION_KINDS = new Set(Object.values(RELATION_KIND_BY_DECORATOR));
50
+ // `inverse` is REQUIRED on these two (the reverse sides) and OPTIONAL — usually
51
+ // omitted — on @ManyToOne/@ManyToMany; W609 only ever fires on the latter pair.
52
+ const OPTIONAL_INVERSE_DECORATORS = new Set(["ManyToOne", "ManyToMany"]);
38
53
  const ENUM_DECORATORS = new Set(["Enum", "MultiEnum"]);
39
54
  const FILE_DECORATORS = new Set(["File", "MultiFile"]);
40
55
 
41
- // ── typescript resolution: target app first, this package as fallback ──
56
+ // ── typescript resolution: target app, then cwd, then this package ──
57
+ // The app repo is the expected source: a Suppa application compiles to dist/,
58
+ // so it has typescript. This package lists typescript as a devDependency only,
59
+ // so the last candidate resolves in a checkout but never in an install.
42
60
  export function loadTypescript(rootDir) {
43
61
  const froms = [];
44
62
  if (rootDir) froms.push(join(resolve(rootDir), "package.json"));
63
+ froms.push(join(process.cwd(), "package.json"));
45
64
  froms.push(import.meta.url);
46
65
  for (const from of froms) {
47
66
  try {
@@ -51,10 +70,22 @@ export function loadTypescript(rootDir) {
51
70
  }
52
71
  }
53
72
  throw new Error(
54
- "validate-suppa-schema: cannot resolve 'typescript' — run `npm install` in the app repo first.",
73
+ "validate-suppa-schema: cannot resolve 'typescript'. It is read from the app repo " +
74
+ "being validated (a Suppa application compiles with tsc, so it normally has it). " +
75
+ "Install it there — `npm i -D typescript` — or run this from a directory where it resolves.",
55
76
  );
56
77
  }
57
78
 
79
+ /**
80
+ * Path to print for a finding. A relative path is friendlier and clickable, but
81
+ * only when it actually stays inside cwd — across drives or above cwd, Windows
82
+ * `relative()` yields an unusable `..\..\..` chain with no drive letter.
83
+ */
84
+ export function displayPath(cwd, file) {
85
+ const rel = relative(cwd, file);
86
+ return !rel || rel.startsWith("..") || isAbsolute(rel) ? file : rel;
87
+ }
88
+
58
89
  // ── small AST helpers ──
59
90
  function finding(ts, sf, node, code, message) {
60
91
  const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
@@ -112,6 +143,36 @@ function thunkTarget(ts, sf, arg) {
112
143
  }
113
144
  return null;
114
145
  }
146
+ /**
147
+ * The `inverse` selector — `(target, inverse, options?)` — is whichever
148
+ * function expression sits in argument position 1; it is distinguished from
149
+ * `(target, options?)` by NOT being an object literal.
150
+ */
151
+ function isFunctionLike(ts, n) {
152
+ return !!n && (ts.isArrowFunction(n) || ts.isFunctionExpression(n));
153
+ }
154
+ /**
155
+ * The property name an inverse selector's body accesses off its own single
156
+ * parameter — `(t) => t.prop` (or `(t) => { return t.prop; }`) -> "prop".
157
+ * Anything else (destructuring, no single-parameter self-access, …) is not a
158
+ * shape this AST-only checker can read, so it returns null rather than guess.
159
+ */
160
+ function inverseAccessedProperty(ts, fn) {
161
+ if (!fn || fn.parameters.length !== 1) return null;
162
+ const param = fn.parameters[0].name;
163
+ if (!ts.isIdentifier(param)) return null;
164
+ let body = fn.body;
165
+ if (ts.isBlock(body)) {
166
+ const stmts = body.statements;
167
+ if (stmts.length !== 1 || !ts.isReturnStatement(stmts[0]) || !stmts[0].expression) return null;
168
+ body = stmts[0].expression;
169
+ }
170
+ if (ts.isPropertyAccessExpression(body) && ts.isIdentifier(body.expression) &&
171
+ body.expression.text === param.text) {
172
+ return body.name.text;
173
+ }
174
+ return null;
175
+ }
115
176
  function spreadElements(ts, node) {
116
177
  if (!node || !ts.isObjectLiteralExpression(node)) return [];
117
178
  return node.properties.filter((p) => ts.isSpreadAssignment(p));
@@ -243,10 +304,20 @@ function analyzeEntities(ts, sf, model) {
243
304
  nameNode: columnOptions.get("name") ?? null,
244
305
  });
245
306
  } else if (ENUM_DECORATORS.has(d.name)) {
307
+ // (globalName?, Enum, titles?, options?) — the options object is
308
+ // the LAST argument when that is an object literal. An inline
309
+ // titles map occupies the same slot when options are omitted, so
310
+ // this node is only ever read for keys options own (E113's
311
+ // `subType`); a titles map never carries one.
312
+ const last = d.args[d.args.length - 1];
313
+ const enumOptionsNode =
314
+ d.args.length >= 2 && last && ts.isObjectLiteralExpression(last) ? last : null;
246
315
  info.properties.set(propName, {
247
316
  kind: d.name === "Enum" ? "enum" : "multi-enum",
248
317
  node: member, decorator: d,
249
318
  enumGlobalName: stringValue(ts, d.args[0]),
319
+ optionsNode: enumOptionsNode,
320
+ enumOptions: objectMap(ts, enumOptionsNode),
250
321
  });
251
322
  } else if (FILE_DECORATORS.has(d.name)) {
252
323
  info.properties.set(propName, {
@@ -255,15 +326,19 @@ function analyzeEntities(ts, sf, model) {
255
326
  });
256
327
  } else if (d.name in RELATION_KIND_BY_DECORATOR) {
257
328
  // (target, options?) or (target, inverse, options?) — the options
258
- // object is whichever trailing argument is an object literal
329
+ // object is whichever trailing argument is an object literal; the
330
+ // inverse (when present) is argument 1 whenever it is NOT that
331
+ // options object, i.e. it is an arrow/function expression instead.
259
332
  const relOptions = objectMap(
260
333
  ts, [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)),
261
334
  );
335
+ const inverseNode = isFunctionLike(ts, d.args[1]) ? d.args[1] : null;
262
336
  info.properties.set(propName, {
263
337
  kind: RELATION_KIND_BY_DECORATOR[d.name],
264
338
  node: member, decorator: d,
265
339
  targetClass: thunkTarget(ts, sf, d.args[0]),
266
340
  nameNode: relOptions.get("name") ?? null,
341
+ inverseNode,
267
342
  });
268
343
  }
269
344
  }
@@ -425,16 +500,71 @@ function checkEntity(ts, info, sdk, model, findings) {
425
500
  findings.push(finding(ts, sf, prop.nameNode, "E102",
426
501
  `column name '${colName}' on property '${propName}' collides with the system column of the same name provided by SystemBaseEntity — "you never declare them yourself"`));
427
502
  }
428
- if (prop.kind === "column") checkColumn(ts, sf, prop, sdk, findings);
429
- if (prop.kind in { "many-to-one": 1, "many-to-many": 1, "many-to-many-backref": 1, "one-to-many": 1 } &&
430
- prop.targetClass === null) {
431
- findings.push(finding(ts, sf, prop.node, "E105",
432
- `relation '${propName}' must receive a thunk returning the target class — write @${prop.decorator.name}(() => Target); a direct class reference breaks circular imports`));
503
+ if (prop.kind === "column") checkColumn(ts, sf, propName, prop, sdk, findings);
504
+ if (prop.kind === "enum" || prop.kind === "multi-enum") {
505
+ checkEnumSubType(ts, sf, propName, prop, findings);
506
+ }
507
+ if (RELATION_KINDS.has(prop.kind)) {
508
+ if (prop.targetClass === null) {
509
+ findings.push(finding(ts, sf, prop.node, "E105",
510
+ `relation '${propName}' must receive a thunk returning the target class — write @${prop.decorator.name}(() => Target); a direct class reference breaks circular imports`));
511
+ }
512
+ if (prop.inverseNode) {
513
+ if (OPTIONAL_INVERSE_DECORATORS.has(prop.decorator.name)) {
514
+ findings.push(finding(ts, sf, prop.inverseNode, "W609",
515
+ `'${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`));
516
+ }
517
+ checkInverseSelector(ts, sf, propName, prop, model, findings);
518
+ }
433
519
  }
434
520
  }
435
521
  }
436
522
 
437
- function checkColumn(ts, sf, prop, sdk, findings) {
523
+ /**
524
+ * "An inverse must select the property on the target that holds the OTHER
525
+ * SIDE of this relation" — e.g. (task) => task.project. Applies to the
526
+ * `inverse` argument of any of the four relation decorators, required or not.
527
+ * Skipped silently when the target class is not among the analyzed entities
528
+ * (platform/SDK entities such as IconsEntity) — no guessing without a model
529
+ * of that class, and when the selector's shape (destructuring, a computed
530
+ * body, …) is not one this AST-only checker can read.
531
+ */
532
+ function checkInverseSelector(ts, sf, propName, prop, model, findings) {
533
+ if (!prop.targetClass) return;
534
+ const target = model.entities.get(prop.targetClass);
535
+ if (!target) return;
536
+ const accessed = inverseAccessedProperty(ts, prop.inverseNode);
537
+ if (accessed === null) return;
538
+ const targetProp = target.properties.get(accessed);
539
+ if (targetProp && RELATION_KINDS.has(targetProp.kind)) return; // valid pairing
540
+
541
+ let reason;
542
+ if (SYSTEM_COLUMNS.includes(accessed)) {
543
+ reason = `'${accessed}' is a system column provided by SystemBaseEntity, not a relation`;
544
+ } else if (!targetProp) {
545
+ reason = `'${target.entityName}' declares no property named '${accessed}'`;
546
+ } else {
547
+ reason = `'${target.entityName}.${accessed}' is a '${targetProp.kind}' property, not a relation`;
548
+ }
549
+ findings.push(finding(ts, sf, prop.inverseNode, "E111",
550
+ `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`));
551
+ }
552
+
553
+ /**
554
+ * E113 — "@Enum() and @MultiEnum() fill it from their first argument […] do not
555
+ * pass subType yourself on an enum field". Passing one by hand either duplicates
556
+ * what the decorator already writes or silently disagrees with it, and the value
557
+ * it disagrees with is the one that resolves { value: 'active' } to an enum
558
+ * record on insert.
559
+ */
560
+ function checkEnumSubType(ts, sf, propName, prop, findings) {
561
+ const subTypeNode = prop.enumOptions?.get("subType");
562
+ if (!subTypeNode) return;
563
+ findings.push(finding(ts, sf, subTypeNode, "E113",
564
+ `'${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.`));
565
+ }
566
+
567
+ function checkColumn(ts, sf, propName, prop, sdk, findings) {
438
568
  const opts = prop.columnOptions;
439
569
  for (const [opt, valNode] of opts) {
440
570
  if (!sdk.columnOptions.includes(opt)) {
@@ -492,6 +622,8 @@ function checkColumn(ts, sf, prop, sdk, findings) {
492
622
  `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
623
  }
494
624
  }
625
+ checkSubType(ts, sf, propName, prop, typeValue, findings);
626
+
495
627
  if (opts.has("length") && typeValue !== null && typeValue !== "text") {
496
628
  findings.push(finding(ts, sf, opts.get("length"), "W603",
497
629
  `'length' caps Text columns; this column is '${typeValue}'`));
@@ -502,6 +634,36 @@ function checkColumn(ts, sf, prop, sdk, findings) {
502
634
  }
503
635
  }
504
636
 
637
+ /**
638
+ * E112 — a subType string that the doc's matrix does not pair with this base
639
+ * type. Only two rows of that matrix belong to @Column(): Timestamp takes
640
+ * 'date' | 'time' | 'timestamp' ("Chooses the physical column type"), Text takes
641
+ * 'encrypted'. Anything else is rejected by the platform, not by tsc — `subType`
642
+ * is typed as a plain string, so a wrong pairing compiles.
643
+ *
644
+ * `subType: null` is the DOCUMENTED way to clear a subtype ("write subType: null
645
+ * explicitly") and is always clean. A value this AST-only checker cannot read
646
+ * takes the usual W606 unverifiable path — never E112. An unresolved `type`
647
+ * leaves nothing to judge the pairing against, so the check is skipped.
648
+ */
649
+ function checkSubType(ts, sf, propName, prop, typeValue, findings) {
650
+ const node = prop.columnOptions.get("subType");
651
+ if (!node) return;
652
+ const val = unwrapExpr(ts, node);
653
+ if (val.kind === ts.SyntaxKind.NullKeyword) return; // the documented "clear it"
654
+ const raw = stringValue(ts, val);
655
+ if (raw === null) {
656
+ findings.push(finding(ts, sf, node, "W606",
657
+ `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`));
658
+ return;
659
+ }
660
+ if (typeValue === null) return; // no readable `type` to pair it against
661
+ const allowed = DOC_SUBTYPES_BY_TYPE[typeValue];
662
+ if (allowed && allowed.includes(raw)) return;
663
+ findings.push(finding(ts, sf, node, "E112",
664
+ `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.`));
665
+ }
666
+
505
667
  // ── extraction: string enums (createSeed(EnumName.Member) resolution) ──
506
668
  function analyzeEnums(ts, sf, model) {
507
669
  sf.forEachChild(function walk(node) {
@@ -1080,7 +1242,9 @@ if (isMain) {
1080
1242
  const dedupedFiles = [...new Set(files)];
1081
1243
  const res = validateSchema({ files: dedupedFiles, rootDir });
1082
1244
  for (const f of res.findings) {
1083
- console.log(`${relative(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`);
1245
+ console.log(
1246
+ `${displayPath(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`,
1247
+ );
1084
1248
  }
1085
1249
  console.log(
1086
1250
  `\n${res.errors.length} error(s), ${res.warnings.length} warning(s) across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
@@ -55,7 +55,21 @@ export class __EntityName__ extends SystemBaseEntity {
55
55
  @Column({ name: 'amount', type: FieldTypeEnum.Numeric, decimalPlaces: 2 })
56
56
  amount: number;
57
57
 
58
+ // Date-only column — there is no FieldTypeEnum.Date; it is Timestamp + subType.
59
+ // CAVEAT: subType is fixed at creation — getting 'date' vs plain timestamp
60
+ // wrong later means a NEW field, not a conversion.
61
+ // @Column({ name: 'birthday', type: FieldTypeEnum.Timestamp, subType: 'date' })
62
+ // birthday: string;
63
+
64
+ // Encrypted at rest — Text only.
65
+ // CAVEAT: the platform forces unique/searchable/canFilter/canSort/canGroup to
66
+ // false and clears maxLength/minLength/mask — keep anything users must search
67
+ // in a separate plaintext column.
68
+ // @Column({ name: 'payload', type: FieldTypeEnum.Text, subType: 'encrypted' })
69
+ // payload: string;
70
+
58
71
  // Relation — ALWAYS a thunk (() => Target), never the class itself.
72
+ // No inverse passed — it's optional on @ManyToOne and omitted by default.
59
73
  @ManyToOne(() => __TargetEntity__, { nullable: false })
60
74
  __target__: __TargetEntity__;
61
75
 
@@ -44,6 +44,7 @@ export class __EntityName__ extends SystemBaseEntity {
44
44
  // (SystemBaseEntity provides them).
45
45
 
46
46
  // 3/3 — the property MUST be named `owner`, pointing at the parent via a thunk.
47
+ // No inverse passed — it's optional on @ManyToOne and omitted by default.
47
48
  @ManyToOne(() => __ParentEntity__, {
48
49
  name: 'owner',
49
50
  title: { en: '__Parent title__', uk: '__Батьківська назва__' },