suppa-mcp-2 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -293,11 +293,13 @@ node <this-skill-dir>/scripts/validate-suppa-schema.mjs <app-root>
293
293
  # (installed via npm: node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs)
294
294
  ```
295
295
 
296
- Checks: SQL-string defaults, decorator misuse, thunk-less relations, seed
297
- idempotency (importKeyFields / `$key`), forbidden seed keys, numeric relation
298
- ids, reverse `@OneToMany` references, `forFeature` membership, seed dependency
299
- order, `dist/` autoload paths, tsconfig decorator flags, unknown
300
- `@Entity()`/`@Column()` options or field types, and tabular-part rules —
296
+ Checks: SQL-string defaults, decorator misuse, thunk-less relations, an
297
+ `inverse` selector wrongly passed to `@ManyToOne`/`@ManyToMany` (W609) or
298
+ pointing at a non-relation property such as `id` on any of the four relation
299
+ decorators (E111), seed idempotency (importKeyFields / `$key`), forbidden
300
+ seed keys, numeric relation ids, reverse `@OneToMany` references, `forFeature`
301
+ membership, seed dependency order, `dist/` autoload paths, tsconfig decorator
302
+ flags, unknown `@Entity()`/`@Column()` options or field types, and tabular-part rules —
301
303
  the `type: 'tabular-part'` + `relationEntityName` + `owner` triad, `owner`
302
304
  resolving to the right parent, and `owner` first in `importKeyFields`
303
305
  (E108/E109/E110/W607) — validated against the installed `@suppa/sdk` typings
package/dist/server.js CHANGED
@@ -1655,7 +1655,8 @@ export function buildServer() {
1655
1655
  "2. Resolve the blocking questions BEFORE writing any file: importKeyFields (the stable business key — wrong means duplicate seed rows on every restart), " +
1656
1656
  "representativeFieldName, and per-field nullable.\n" +
1657
1657
  "3. Write src/common/database/entities/*.entity.ts — @Entity class extending SystemBaseEntity; scalars via @Column({ type: FieldTypeEnum.X }); " +
1658
- "relations via thunks (@ManyToOne(() => Target)); fixed choices via @Enum('Entity.field', ...); attachments via @File/@MultiFile; " +
1658
+ "relations via thunks (@ManyToOne(() => Target)) — pass the thunk and the options object only; do not add the optional inverse selector to @ManyToOne/@ManyToMany; " +
1659
+ "fixed choices via @Enum('Entity.field', ...); attachments via @File/@MultiFile; " +
1659
1660
  "'default' is a SQL expression STRING ('false', \"'draft'\") — never a JS value. Repeating rows owned by one parent record " +
1660
1661
  "(checklist items, order lines) are a TABULAR PART, not a plain entity: type: 'tabular-part' + relationEntityName + a @ManyToOne " +
1661
1662
  "field named owner, with owner first in importKeyFields (see references/tabular-parts.md). " +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.2.2",
3
+ "version": "1.2.3",
4
4
  "description": "MCP server for the Suppa platform (modern.suppa.me) — Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file attachments, with multi-tenant Google auth. Node port of PyPI suppa-mcp.",
5
5
  "type": "module",
6
6
  "bin": { "suppa-mcp": "dist/bin.js" },
@@ -44,12 +44,13 @@ Confirm all 5 before writing anything:
44
44
  3. `default` is a SQL expression string — `'false'`, `"'draft'"` — never a JS value; a JS value is rejected at migration time.
45
45
  4. Scalars only via `@Column({ type: FieldTypeEnum.X })`; relations/enums/files are NEVER declared via `@Column` — use the `@ManyToOne`/`@ManyToMany`/`@OneToMany`/`@ManyToManyBackRef`/`@Enum`/`@MultiEnum`/`@File`/`@MultiFile` families.
46
46
  5. Relation targets are thunks — `() => Target`, never the class itself — or circular imports break.
47
- 6. If an option isn't in the reference tables (`references/entities.md`, `references/seeds.md`, `references/registration.md`), it doesn't exist — stop and ask, don't guess.
48
- 7. Every entity class must appear in some `forFeature()`'s `entities` array; every seed in its `seeds` array, dependencies first — `workflowsSeed` before `stageWorkflowsSeed`.
49
- 8. Seeds: every record carries all `importKeyFields` (or `$key`); relations are referenced by the target's import-key object, never a numeric id; no system columns; no `$readAccess`/`$updateAccess`/`$instanceAccess`; no reverse `@OneToMany` field, even as `[]`.
50
- 9. Autoload paths (`entitiesPath`/`seedsPath`) point at `dist/`, never `src/` — autoloading reads compiled output.
51
- 10. Renames need `key` set on `@Entity()`/`@Column()` BEFORE the rename ships — otherwise it's a drop-and-create, not a rename.
52
- 11. Repeating rows owned by one parent record are a **tabular part**, never a plain entity: `type: 'tabular-part'` + `relationEntityName` (the parent's `@Entity()` name) + a `@ManyToOne` field named exactly `owner` pointing at the parent class — all three required, the platform infers none of them. Put `owner` FIRST in `importKeyFields` — it scopes the business key to the parent, or rows collide across different parents.
47
+ 6. Do not pass the optional `inverse` selector to `@ManyToOne`/`@ManyToMany` — write `@ManyToOne(() => Target, { … })`. Add one only when the target class declares the paired back-reference and you are deliberately linking the two sides. An `inverse` must select a RELATION property on the target (`(task) => task.project`); `(e) => e.id` is always wrong — `id` is a system column, not a back-reference.
48
+ 7. If an option isn't in the reference tables (`references/entities.md`, `references/seeds.md`, `references/registration.md`), it doesn't exist — stop and ask, don't guess.
49
+ 8. Every entity class must appear in some `forFeature()`'s `entities` array; every seed in its `seeds` array, dependencies first — `workflowsSeed` before `stageWorkflowsSeed`.
50
+ 9. Seeds: every record carries all `importKeyFields` (or `$key`); relations are referenced by the target's import-key object, never a numeric id; no system columns; no `$readAccess`/`$updateAccess`/`$instanceAccess`; no reverse `@OneToMany` field, even as `[]`.
51
+ 10. Autoload paths (`entitiesPath`/`seedsPath`) point at `dist/`, never `src/` — autoloading reads compiled output.
52
+ 11. Renames need `key` set on `@Entity()`/`@Column()` BEFORE the rename ships — otherwise it's a drop-and-create, not a rename.
53
+ 12. Repeating rows owned by one parent record are a **tabular part**, never a plain entity: `type: 'tabular-part'` + `relationEntityName` (the parent's `@Entity()` name) + a `@ManyToOne` field named exactly `owner` pointing at the parent class — all three required, the platform infers none of them. Put `owner` FIRST in `importKeyFields` — it scopes the business key to the parent, or rows collide across different parents.
53
54
 
54
55
  ## Decorator decision table
55
56
 
@@ -59,14 +60,14 @@ Confirm all 5 before writing anything:
59
60
  | Scalar column (text/numeric/integer/boolean/timestamp/json/uuid/multi-language/bytea/tsvector/multi-type/icon) | `@Column({ type: FieldTypeEnum.<Member> })` |
60
61
  | Fixed single-select value set | `@Enum('<Entity>.<field>', <Field>Enum, <Field>Titles?, options?)` |
61
62
  | Fixed multi-select value set | `@MultiEnum(...)` — same signature as `@Enum` |
62
- | Foreign key on this entity | `@ManyToOne(target, options?)` or `@ManyToOne(target, inverse, options?)` |
63
- | Pivot table between two entities | `@ManyToMany(target, options?)` or `@ManyToMany(target, inverse, options?)` |
64
- | Reverse side of a `@ManyToMany` | `@ManyToManyBackRef(target, inverse, options?)` |
65
- | Reverse side of a `@ManyToOne` | `@OneToMany(target, inverse, options?)` |
63
+ | Foreign key on this entity | `@ManyToOne(() => Target, options?)` — **no inverse** |
64
+ | Pivot table between two entities | `@ManyToMany(() => Target, options?)` — **no inverse** |
65
+ | Reverse side of a `@ManyToMany` | `@ManyToManyBackRef(() => Target, (t) => t.<thisRelationProp>, options?)` |
66
+ | Reverse side of a `@ManyToOne` | `@OneToMany(() => Target, (t) => t.<thisRelationProp>, options?)` |
66
67
  | Single attachment | `@File({ title })` |
67
68
  | Multiple attachments | `@MultiFile({ title })` |
68
69
 
69
- `target` is always a thunk, `() => Target`. `inverse` is a property selector on the target entity, e.g. `(task) => task.project`.
70
+ `target` is always a thunk, `() => Target`. The `inverse` selector is REQUIRED on `@OneToMany`/`@ManyToManyBackRef` and OPTIONAL on `@ManyToOne`/`@ManyToMany` — omit it there by default. When you do write one, it must select the property on the TARGET class that holds the other side of this relation (e.g. `(task) => task.project`) — never `.id`, never a scalar column.
70
71
 
71
72
  ## Naming conventions
72
73
 
@@ -150,6 +151,8 @@ Step 1 exists to catch exactly this: an unregistered class is E301 and the gate
150
151
 
151
152
  `validate-suppa-schema.mjs` exits `0` on a clean run, `1` when errors are found, `2` on a usage error or a missing path. The gate requires exit `0` — warnings alone do not block.
152
153
 
154
+ The validator parses with the TypeScript compiler API, read from the app repo you point it at (a Suppa application compiles with `tsc`, so it has one). If it reports `cannot resolve 'typescript'`, run `npm install` in that repo — or `npm i -D typescript` if it genuinely has none.
155
+
153
156
  ## Troubleshooting
154
157
 
155
158
  | Symptom | Cause | Validator code |
@@ -161,6 +164,8 @@ Step 1 exists to catch exactly this: an unregistered class is E301 and the gate
161
164
  | Back reference can't insert | A reverse `@OneToMany` field is present in a seed record, possibly as `[]` | E204 |
162
165
  | A renamed entity or field appears as a new one | No `key` option was set | W602 |
163
166
  | `default` value is rejected | A JavaScript value was passed instead of a SQL expression string | E103 |
167
+ | Generated relation has an inverse selector that fails to typecheck | An `inverse` was passed to `@ManyToOne`/`@ManyToMany`, where it's optional and usually omitted | W609/E111 — drop the selector, write `@ManyToOne(() => Target, { … })` |
168
+ | `inverse` points at `id` | `id` is a system column, never a back-reference — an `inverse` must select the RELATION property on the target holding the other side | E111 |
164
169
  | A re-added field already contains old data | Same name means the same key, so the soft-deleted field was restored with its column — this is a runtime migration outcome, not statically checkable | documented-only, see references/registration.md |
165
170
  | A removed field is still present after a reload | The removal pass was skipped because the system user could not be resolved | documented-only, see references/registration.md |
166
171
  | The table has columns such as `title_1730457600000` | Leftovers from removed fields — renaming is how the platform removes a column; nothing cleans them up | documented-only, see references/registration.md |
@@ -12,7 +12,7 @@
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) ──
@@ -35,13 +35,21 @@ const RELATION_KIND_BY_DECORATOR = {
35
35
  ManyToOne: "many-to-one", ManyToMany: "many-to-many",
36
36
  ManyToManyBackRef: "many-to-many-backref", OneToMany: "one-to-many",
37
37
  };
38
+ const RELATION_KINDS = new Set(Object.values(RELATION_KIND_BY_DECORATOR));
39
+ // `inverse` is REQUIRED on these two (the reverse sides) and OPTIONAL — usually
40
+ // omitted — on @ManyToOne/@ManyToMany; W609 only ever fires on the latter pair.
41
+ const OPTIONAL_INVERSE_DECORATORS = new Set(["ManyToOne", "ManyToMany"]);
38
42
  const ENUM_DECORATORS = new Set(["Enum", "MultiEnum"]);
39
43
  const FILE_DECORATORS = new Set(["File", "MultiFile"]);
40
44
 
41
- // ── typescript resolution: target app first, this package as fallback ──
45
+ // ── typescript resolution: target app, then cwd, then this package ──
46
+ // The app repo is the expected source: a Suppa application compiles to dist/,
47
+ // so it has typescript. This package lists typescript as a devDependency only,
48
+ // so the last candidate resolves in a checkout but never in an install.
42
49
  export function loadTypescript(rootDir) {
43
50
  const froms = [];
44
51
  if (rootDir) froms.push(join(resolve(rootDir), "package.json"));
52
+ froms.push(join(process.cwd(), "package.json"));
45
53
  froms.push(import.meta.url);
46
54
  for (const from of froms) {
47
55
  try {
@@ -51,10 +59,22 @@ export function loadTypescript(rootDir) {
51
59
  }
52
60
  }
53
61
  throw new Error(
54
- "validate-suppa-schema: cannot resolve 'typescript' — run `npm install` in the app repo first.",
62
+ "validate-suppa-schema: cannot resolve 'typescript'. It is read from the app repo " +
63
+ "being validated (a Suppa application compiles with tsc, so it normally has it). " +
64
+ "Install it there — `npm i -D typescript` — or run this from a directory where it resolves.",
55
65
  );
56
66
  }
57
67
 
68
+ /**
69
+ * Path to print for a finding. A relative path is friendlier and clickable, but
70
+ * only when it actually stays inside cwd — across drives or above cwd, Windows
71
+ * `relative()` yields an unusable `..\..\..` chain with no drive letter.
72
+ */
73
+ export function displayPath(cwd, file) {
74
+ const rel = relative(cwd, file);
75
+ return !rel || rel.startsWith("..") || isAbsolute(rel) ? file : rel;
76
+ }
77
+
58
78
  // ── small AST helpers ──
59
79
  function finding(ts, sf, node, code, message) {
60
80
  const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
@@ -112,6 +132,36 @@ function thunkTarget(ts, sf, arg) {
112
132
  }
113
133
  return null;
114
134
  }
135
+ /**
136
+ * The `inverse` selector — `(target, inverse, options?)` — is whichever
137
+ * function expression sits in argument position 1; it is distinguished from
138
+ * `(target, options?)` by NOT being an object literal.
139
+ */
140
+ function isFunctionLike(ts, n) {
141
+ return !!n && (ts.isArrowFunction(n) || ts.isFunctionExpression(n));
142
+ }
143
+ /**
144
+ * The property name an inverse selector's body accesses off its own single
145
+ * parameter — `(t) => t.prop` (or `(t) => { return t.prop; }`) -> "prop".
146
+ * Anything else (destructuring, no single-parameter self-access, …) is not a
147
+ * shape this AST-only checker can read, so it returns null rather than guess.
148
+ */
149
+ function inverseAccessedProperty(ts, fn) {
150
+ if (!fn || fn.parameters.length !== 1) return null;
151
+ const param = fn.parameters[0].name;
152
+ if (!ts.isIdentifier(param)) return null;
153
+ let body = fn.body;
154
+ if (ts.isBlock(body)) {
155
+ const stmts = body.statements;
156
+ if (stmts.length !== 1 || !ts.isReturnStatement(stmts[0]) || !stmts[0].expression) return null;
157
+ body = stmts[0].expression;
158
+ }
159
+ if (ts.isPropertyAccessExpression(body) && ts.isIdentifier(body.expression) &&
160
+ body.expression.text === param.text) {
161
+ return body.name.text;
162
+ }
163
+ return null;
164
+ }
115
165
  function spreadElements(ts, node) {
116
166
  if (!node || !ts.isObjectLiteralExpression(node)) return [];
117
167
  return node.properties.filter((p) => ts.isSpreadAssignment(p));
@@ -255,15 +305,19 @@ function analyzeEntities(ts, sf, model) {
255
305
  });
256
306
  } else if (d.name in RELATION_KIND_BY_DECORATOR) {
257
307
  // (target, options?) or (target, inverse, options?) — the options
258
- // object is whichever trailing argument is an object literal
308
+ // object is whichever trailing argument is an object literal; the
309
+ // inverse (when present) is argument 1 whenever it is NOT that
310
+ // options object, i.e. it is an arrow/function expression instead.
259
311
  const relOptions = objectMap(
260
312
  ts, [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)),
261
313
  );
314
+ const inverseNode = isFunctionLike(ts, d.args[1]) ? d.args[1] : null;
262
315
  info.properties.set(propName, {
263
316
  kind: RELATION_KIND_BY_DECORATOR[d.name],
264
317
  node: member, decorator: d,
265
318
  targetClass: thunkTarget(ts, sf, d.args[0]),
266
319
  nameNode: relOptions.get("name") ?? null,
320
+ inverseNode,
267
321
  });
268
322
  }
269
323
  }
@@ -426,14 +480,52 @@ function checkEntity(ts, info, sdk, model, findings) {
426
480
  `column name '${colName}' on property '${propName}' collides with the system column of the same name provided by SystemBaseEntity — "you never declare them yourself"`));
427
481
  }
428
482
  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`));
483
+ if (RELATION_KINDS.has(prop.kind)) {
484
+ if (prop.targetClass === null) {
485
+ findings.push(finding(ts, sf, prop.node, "E105",
486
+ `relation '${propName}' must receive a thunk returning the target class — write @${prop.decorator.name}(() => Target); a direct class reference breaks circular imports`));
487
+ }
488
+ if (prop.inverseNode) {
489
+ if (OPTIONAL_INVERSE_DECORATORS.has(prop.decorator.name)) {
490
+ findings.push(finding(ts, sf, prop.inverseNode, "W609",
491
+ `'${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`));
492
+ }
493
+ checkInverseSelector(ts, sf, propName, prop, model, findings);
494
+ }
433
495
  }
434
496
  }
435
497
  }
436
498
 
499
+ /**
500
+ * "An inverse must select the property on the target that holds the OTHER
501
+ * SIDE of this relation" — e.g. (task) => task.project. Applies to the
502
+ * `inverse` argument of any of the four relation decorators, required or not.
503
+ * Skipped silently when the target class is not among the analyzed entities
504
+ * (platform/SDK entities such as IconsEntity) — no guessing without a model
505
+ * of that class, and when the selector's shape (destructuring, a computed
506
+ * body, …) is not one this AST-only checker can read.
507
+ */
508
+ function checkInverseSelector(ts, sf, propName, prop, model, findings) {
509
+ if (!prop.targetClass) return;
510
+ const target = model.entities.get(prop.targetClass);
511
+ if (!target) return;
512
+ const accessed = inverseAccessedProperty(ts, prop.inverseNode);
513
+ if (accessed === null) return;
514
+ const targetProp = target.properties.get(accessed);
515
+ if (targetProp && RELATION_KINDS.has(targetProp.kind)) return; // valid pairing
516
+
517
+ let reason;
518
+ if (SYSTEM_COLUMNS.includes(accessed)) {
519
+ reason = `'${accessed}' is a system column provided by SystemBaseEntity, not a relation`;
520
+ } else if (!targetProp) {
521
+ reason = `'${target.entityName}' declares no property named '${accessed}'`;
522
+ } else {
523
+ reason = `'${target.entityName}.${accessed}' is a '${targetProp.kind}' property, not a relation`;
524
+ }
525
+ findings.push(finding(ts, sf, prop.inverseNode, "E111",
526
+ `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`));
527
+ }
528
+
437
529
  function checkColumn(ts, sf, prop, sdk, findings) {
438
530
  const opts = prop.columnOptions;
439
531
  for (const [opt, valNode] of opts) {
@@ -1080,7 +1172,9 @@ if (isMain) {
1080
1172
  const dedupedFiles = [...new Set(files)];
1081
1173
  const res = validateSchema({ files: dedupedFiles, rootDir });
1082
1174
  for (const f of res.findings) {
1083
- console.log(`${relative(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`);
1175
+ console.log(
1176
+ `${displayPath(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`,
1177
+ );
1084
1178
  }
1085
1179
  console.log(
1086
1180
  `\n${res.errors.length} error(s), ${res.warnings.length} warning(s) across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
@@ -56,6 +56,7 @@ export class __EntityName__ extends SystemBaseEntity {
56
56
  amount: number;
57
57
 
58
58
  // Relation — ALWAYS a thunk (() => Target), never the class itself.
59
+ // No inverse passed — it's optional on @ManyToOne and omitted by default.
59
60
  @ManyToOne(() => __TargetEntity__, { nullable: false })
60
61
  __target__: __TargetEntity__;
61
62
 
@@ -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: '__Батьківська назва__' },