suppa-mcp-2 1.1.4 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +387 -342
- package/dist/auth.js +29 -25
- package/dist/server.js +93 -50
- package/dist/tools/entity.js +343 -40
- package/dist/tools/migrate.js +148 -11
- package/package.json +50 -50
- package/skills/suppa-entity-code/SKILL.md +133 -0
- package/skills/suppa-entity-code/references/entities.md +292 -0
- package/skills/suppa-entity-code/references/registration.md +224 -0
- package/skills/suppa-entity-code/references/seeds.md +136 -0
- package/skills/suppa-entity-code/references/tabular-parts.md +146 -0
- package/skills/suppa-entity-code/references/v1-mapping.md +78 -0
- package/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs +1063 -0
- package/skills/suppa-entity-code/templates/entity.template.ts +79 -0
- package/skills/suppa-entity-code/templates/seed.template.ts +41 -0
- package/skills/suppa-entity-code/templates/tabular-part.template.ts +93 -0
package/dist/tools/migrate.js
CHANGED
|
@@ -94,9 +94,99 @@ export function _setV1Request(fn) {
|
|
|
94
94
|
export function _resetV1Request() {
|
|
95
95
|
v1RequestImpl = _v1RequestReal;
|
|
96
96
|
}
|
|
97
|
+
/** POST request against the Suppa 1.0 API (used for instance-existence probes). */
|
|
98
|
+
async function _v1PostReal(path, body, timeout = 60) {
|
|
99
|
+
if (!config.V1_API_KEY && !config.V1_ACCESS_TOKEN) {
|
|
100
|
+
throw new Error("Suppa 1.0 credentials missing: set SUPPA_V1_API_KEY or SUPPA_V1_ACCESS_TOKEN");
|
|
101
|
+
}
|
|
102
|
+
const url = `${config.V1_BASE_URL}/${path.replace(/^\/+/, "")}`;
|
|
103
|
+
const controller = new AbortController();
|
|
104
|
+
const timer = setTimeout(() => controller.abort(), timeout * 1000);
|
|
105
|
+
let res;
|
|
106
|
+
try {
|
|
107
|
+
res = await fetch(url, {
|
|
108
|
+
method: "POST",
|
|
109
|
+
headers: _v1Headers(),
|
|
110
|
+
body: JSON.stringify(body ?? {}),
|
|
111
|
+
signal: controller.signal,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
116
|
+
throw new Error(`Suppa 1.0 connection error: ${reason}`);
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
clearTimeout(timer);
|
|
120
|
+
}
|
|
121
|
+
if (res.status >= 400) {
|
|
122
|
+
let text = "";
|
|
123
|
+
try {
|
|
124
|
+
text = await res.text();
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// ignore
|
|
128
|
+
}
|
|
129
|
+
throw new Error(`Suppa 1.0 HTTP ${res.status} ${res.statusText}: ${text}`);
|
|
130
|
+
}
|
|
131
|
+
const raw = await res.text();
|
|
132
|
+
return raw.trim() ? JSON.parse(raw) : null;
|
|
133
|
+
}
|
|
134
|
+
// Swappable v1 POST implementation (see the GET seam above). Tests replace it
|
|
135
|
+
// via `_setV1Post`; production uses `_v1PostReal`.
|
|
136
|
+
let v1PostImpl = _v1PostReal;
|
|
137
|
+
async function _v1Post(path, body, timeout = 60) {
|
|
138
|
+
return v1PostImpl(path, body, timeout);
|
|
139
|
+
}
|
|
140
|
+
/** TEST HOOK: swap the v1 POST client. */
|
|
141
|
+
export function _setV1Post(fn) {
|
|
142
|
+
v1PostImpl = fn;
|
|
143
|
+
}
|
|
144
|
+
/** TEST HOOK: restore the production v1 POST client. */
|
|
145
|
+
export function _resetV1Post() {
|
|
146
|
+
v1PostImpl = _v1PostReal;
|
|
147
|
+
}
|
|
97
148
|
function _isDict(v) {
|
|
98
149
|
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
99
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* Does at least one v1 record of `searchAlias` populate `v1FieldName`?
|
|
153
|
+
*
|
|
154
|
+
* Probes `POST /api/search/{alias}` with an "is not null" filter and limit 1.
|
|
155
|
+
* Returns true (a populated row exists), false (definitively none), or null
|
|
156
|
+
* when the check couldn't run (no v1 creds, endpoint error, unexpected shape).
|
|
157
|
+
* Callers treat null as "unknown" and never drop a field on it.
|
|
158
|
+
*/
|
|
159
|
+
async function _v1RelationPopulated(searchAlias, v1FieldName) {
|
|
160
|
+
if (!searchAlias || !v1FieldName) {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
let rows;
|
|
164
|
+
try {
|
|
165
|
+
rows = await _v1Post(`api/search/${searchAlias}`, {
|
|
166
|
+
filters: [{ field: v1FieldName, comparator: "is not null" }],
|
|
167
|
+
limit: 1,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return null; // fail-safe: unknown, never prune on a probe error
|
|
172
|
+
}
|
|
173
|
+
if (Array.isArray(rows)) {
|
|
174
|
+
return rows.length > 0;
|
|
175
|
+
}
|
|
176
|
+
if (_isDict(rows)) {
|
|
177
|
+
for (const k of ["data", "rows", "items", "result"]) {
|
|
178
|
+
const v = rows[k];
|
|
179
|
+
if (Array.isArray(v)) {
|
|
180
|
+
return v.length > 0;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const total = rows.total;
|
|
184
|
+
if (typeof total === "number") {
|
|
185
|
+
return total > 0;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
100
190
|
/**
|
|
101
191
|
* Resolve an enum field's option labels from a 1.0 property.
|
|
102
192
|
*
|
|
@@ -469,7 +559,7 @@ function _enumNameFor(entityName, fieldName) {
|
|
|
469
559
|
* part's `owner` field, which the platform auto-creates). Shared by top-level
|
|
470
560
|
* entities and their tabular-part children.
|
|
471
561
|
*/
|
|
472
|
-
async function _planFields(props, entName, v2EntName, targetResolver, entIndex, warnings, dropNames = new Set()) {
|
|
562
|
+
async function _planFields(props, entName, v2EntName, targetResolver, entIndex, warnings, dropNames = new Set(), searchAlias = "", checkInstances = false, skipEmptyRelations = false) {
|
|
473
563
|
const scalarFields = [];
|
|
474
564
|
const enumFields = [];
|
|
475
565
|
const relationFields = [];
|
|
@@ -482,7 +572,12 @@ async function _planFields(props, entName, v2EntName, targetResolver, entIndex,
|
|
|
482
572
|
continue; // e.g. a tabular part's `owner` (auto-created by the platform)
|
|
483
573
|
}
|
|
484
574
|
const v2Fname = normalizeFieldName(fname);
|
|
485
|
-
|
|
575
|
+
// Preserve a v1 multilingual title object ({en, uk, ...}) as-is so each
|
|
576
|
+
// language survives into 2.0; collapse only plain/absent titles to a string.
|
|
577
|
+
// (String(object) would otherwise store the literal "[object Object]".)
|
|
578
|
+
const ftitle = _isDict(p.title)
|
|
579
|
+
? p.title
|
|
580
|
+
: String(p.title ?? "") || fname;
|
|
486
581
|
const ftype = String(p.type ?? "");
|
|
487
582
|
const fsub = typeof p.sub_type === "string" ? p.sub_type : null;
|
|
488
583
|
const required = !["", "never", "false"].includes(String(p.required ?? "never").toLowerCase());
|
|
@@ -503,7 +598,7 @@ async function _planFields(props, entName, v2EntName, targetResolver, entIndex,
|
|
|
503
598
|
if (target && !inSet) {
|
|
504
599
|
warnings.push(`${entName}.${fname}: relation target '${target}' is not in the migration set`);
|
|
505
600
|
}
|
|
506
|
-
|
|
601
|
+
const relField = {
|
|
507
602
|
v1_name: fname,
|
|
508
603
|
name: v2Fname,
|
|
509
604
|
title: ftitle,
|
|
@@ -511,7 +606,20 @@ async function _planFields(props, entName, v2EntName, targetResolver, entIndex,
|
|
|
511
606
|
required,
|
|
512
607
|
relation_entity: v2Target ?? (target ? normalizeEntityName(target) : null),
|
|
513
608
|
target_in_set: inSet,
|
|
514
|
-
}
|
|
609
|
+
};
|
|
610
|
+
// Analyze whether this relation actually carries data in v1 before deciding
|
|
611
|
+
// the field is needed. `create:false` fields are reported but not created.
|
|
612
|
+
if (checkInstances) {
|
|
613
|
+
const populated = await _v1RelationPopulated(searchAlias, fname);
|
|
614
|
+
relField.v1_populated = populated;
|
|
615
|
+
const create = !(skipEmptyRelations && populated === false);
|
|
616
|
+
relField.create = create;
|
|
617
|
+
if (populated === false) {
|
|
618
|
+
warnings.push(`${entName}.${fname}: relation has no populated instances in v1 — ` +
|
|
619
|
+
(create ? "kept for review" : "excluded (skip_empty_relations)"));
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
relationFields.push(relField);
|
|
515
623
|
continue;
|
|
516
624
|
}
|
|
517
625
|
if (cls.kind === KIND_ENUM) {
|
|
@@ -575,7 +683,7 @@ async function _planFields(props, entName, v2EntName, targetResolver, entIndex,
|
|
|
575
683
|
// Planning
|
|
576
684
|
// ---------------------------------------------------------------------------
|
|
577
685
|
/** Fetch the 1.0 schema and build a structured migration plan. */
|
|
578
|
-
export async function _buildPlan(entityNames = "", includeBuiltin = false, skipRelations = false) {
|
|
686
|
+
export async function _buildPlan(entityNames = "", includeBuiltin = false, skipRelations = false, checkRelationInstances = false, skipEmptyRelations = false) {
|
|
579
687
|
const allEntities = await _v1Request("api/all_entities");
|
|
580
688
|
if (!Array.isArray(allEntities)) {
|
|
581
689
|
throw new Error("Unexpected response from api/all_entities (expected a list)");
|
|
@@ -703,8 +811,9 @@ export async function _buildPlan(entityNames = "", includeBuiltin = false, skipR
|
|
|
703
811
|
}
|
|
704
812
|
const entTitle = String(e.alias ?? "") || entName;
|
|
705
813
|
const v2EntName = normalizeEntityName(entName);
|
|
814
|
+
const searchAlias = String(e.alias ?? "") || entName;
|
|
706
815
|
const props = await fetchProps(String(e.id ?? ""), entName);
|
|
707
|
-
const pf = await _planFields(props, entName, v2EntName, targetResolver, entIndex, warnings);
|
|
816
|
+
const pf = await _planFields(props, entName, v2EntName, targetResolver, entIndex, warnings, new Set(), searchAlias, checkRelationInstances, skipEmptyRelations);
|
|
708
817
|
const tabularParts = [];
|
|
709
818
|
if (!isChild(entLower)) {
|
|
710
819
|
for (const c of selected) {
|
|
@@ -714,7 +823,9 @@ export async function _buildPlan(entityNames = "", includeBuiltin = false, skipR
|
|
|
714
823
|
}
|
|
715
824
|
const cprops = await fetchProps(String(c.id ?? ""), cName);
|
|
716
825
|
const cv2 = normalizeEntityName(cName);
|
|
717
|
-
const
|
|
826
|
+
const cSearchAlias = String(c.alias ?? "") || cName;
|
|
827
|
+
const cf = await _planFields(cprops, cName, cv2, targetResolver, entIndex, warnings, new Set(["owner", "owner_id"]), // auto-created by create_tabular_part
|
|
828
|
+
cSearchAlias, checkRelationInstances, skipEmptyRelations);
|
|
718
829
|
tabularParts.push({
|
|
719
830
|
v1_name: cName,
|
|
720
831
|
name: cv2,
|
|
@@ -1017,6 +1128,15 @@ export async function _execute(plan, mode = "create") {
|
|
|
1017
1128
|
});
|
|
1018
1129
|
continue;
|
|
1019
1130
|
}
|
|
1131
|
+
if (f.create === false) {
|
|
1132
|
+
details.push({
|
|
1133
|
+
entity: name,
|
|
1134
|
+
action: `add_relation:${f.name}`,
|
|
1135
|
+
status: "skipped",
|
|
1136
|
+
reason: "no populated instances in v1 (skip_empty_relations)",
|
|
1137
|
+
});
|
|
1138
|
+
continue;
|
|
1139
|
+
}
|
|
1020
1140
|
if (!f.relation_entity || !(f.target_in_set ?? true)) {
|
|
1021
1141
|
details.push({
|
|
1022
1142
|
entity: name,
|
|
@@ -1046,6 +1166,15 @@ export async function _execute(plan, mode = "create") {
|
|
|
1046
1166
|
details.push({ entity: tp.name, action: `add_relation:${f.name}`, status: "skipped", reason: "exists" });
|
|
1047
1167
|
continue;
|
|
1048
1168
|
}
|
|
1169
|
+
if (f.create === false) {
|
|
1170
|
+
details.push({
|
|
1171
|
+
entity: tp.name,
|
|
1172
|
+
action: `add_relation:${f.name}`,
|
|
1173
|
+
status: "skipped",
|
|
1174
|
+
reason: "no populated instances in v1 (skip_empty_relations)",
|
|
1175
|
+
});
|
|
1176
|
+
continue;
|
|
1177
|
+
}
|
|
1049
1178
|
if (!f.relation_entity || !(f.target_in_set ?? true)) {
|
|
1050
1179
|
details.push({
|
|
1051
1180
|
entity: tp.name,
|
|
@@ -1072,7 +1201,7 @@ export async function _execute(plan, mode = "create") {
|
|
|
1072
1201
|
...spec.scalar_fields.map((f) => f.name),
|
|
1073
1202
|
...spec.enum_fields.map((f) => f.name),
|
|
1074
1203
|
...(spec.relation_fields ?? [])
|
|
1075
|
-
.filter((f) => f.relation_entity && (f.target_in_set ?? true))
|
|
1204
|
+
.filter((f) => f.relation_entity && (f.target_in_set ?? true) && f.create !== false)
|
|
1076
1205
|
.map((f) => f.name),
|
|
1077
1206
|
];
|
|
1078
1207
|
const present = new Set(Object.keys(await _liveFields(name)));
|
|
@@ -1143,7 +1272,9 @@ export async function _reconcile(plan) {
|
|
|
1143
1272
|
const plannedFields = [
|
|
1144
1273
|
...ent.scalar_fields.map((f) => [f.name, f.type]),
|
|
1145
1274
|
...ent.enum_fields.map((f) => [f.name, f.type ?? "enum"]),
|
|
1146
|
-
...ent.relation_fields
|
|
1275
|
+
...ent.relation_fields
|
|
1276
|
+
.filter((f) => f.create !== false)
|
|
1277
|
+
.map((f) => [f.name, f.type]),
|
|
1147
1278
|
];
|
|
1148
1279
|
const present = [];
|
|
1149
1280
|
const missing = [];
|
|
@@ -1212,14 +1343,20 @@ function _validatePlan(plan) {
|
|
|
1212
1343
|
* plan_file: when set, load the plan from this JSON file instead of reading from Suppa 1.0.
|
|
1213
1344
|
* mode: 'create' (default) and 'gap-fill' both skip existing entities/fields (idempotent);
|
|
1214
1345
|
* 'reconcile' is a read-only diff of the plan vs. the live 2.0 tenant (writes nothing).
|
|
1346
|
+
* check_relation_instances: probe Suppa 1.0 (POST /api/search/{alias}) to see whether each
|
|
1347
|
+
* relation candidate is actually populated in the source; annotates the plan with
|
|
1348
|
+
* v1_populated + create flags (default true).
|
|
1349
|
+
* skip_empty_relations: when a probed relation has no populated instances in v1, exclude it
|
|
1350
|
+
* from creation (create:false) — the tool's decision that the field isn't needed. Probe
|
|
1351
|
+
* errors leave the field as create:true. Default true; set false to keep every relation.
|
|
1215
1352
|
*/
|
|
1216
|
-
export async function migrateEntities(dryRun = true, entityNames = "", includeBuiltin = false, skipRelations = false, outputFile = "", planFile = "", mode = "create") {
|
|
1353
|
+
export async function migrateEntities(dryRun = true, entityNames = "", includeBuiltin = false, skipRelations = false, outputFile = "", planFile = "", mode = "create", checkRelationInstances = true, skipEmptyRelations = true) {
|
|
1217
1354
|
let plan;
|
|
1218
1355
|
if (planFile) {
|
|
1219
1356
|
plan = _validatePlan(JSON.parse(readFileSync(planFile, { encoding: "utf-8" })));
|
|
1220
1357
|
}
|
|
1221
1358
|
else {
|
|
1222
|
-
plan = await _buildPlan(entityNames, includeBuiltin, skipRelations);
|
|
1359
|
+
plan = await _buildPlan(entityNames, includeBuiltin, skipRelations, checkRelationInstances, skipEmptyRelations);
|
|
1223
1360
|
}
|
|
1224
1361
|
let writtenTo = null;
|
|
1225
1362
|
if (outputFile) {
|
package/package.json
CHANGED
|
@@ -1,50 +1,50 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "suppa-mcp-2",
|
|
3
|
-
"version": "1.1
|
|
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
|
-
"type": "module",
|
|
6
|
-
"bin": { "suppa-mcp": "dist/bin.js" },
|
|
7
|
-
"main": "dist/bin.js",
|
|
8
|
-
"files": ["dist", "README.md", "LICENSE"],
|
|
9
|
-
"engines": { "node": ">=18" },
|
|
10
|
-
"scripts": {
|
|
11
|
-
"build": "tsc",
|
|
12
|
-
"clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
|
|
13
|
-
"rebuild": "npm run clean && npm run build",
|
|
14
|
-
"start": "node dist/bin.js",
|
|
15
|
-
"dev": "tsc --watch",
|
|
16
|
-
"test": "vitest run",
|
|
17
|
-
"test:watch": "vitest",
|
|
18
|
-
"prepublishOnly": "npm run build && npm test",
|
|
19
|
-
"inspect": "npx @modelcontextprotocol/inspector node dist/bin.js"
|
|
20
|
-
},
|
|
21
|
-
"keywords": [
|
|
22
|
-
"mcp",
|
|
23
|
-
"model-context-protocol",
|
|
24
|
-
"suppa",
|
|
25
|
-
"modern-expo",
|
|
26
|
-
"ai",
|
|
27
|
-
"llm",
|
|
28
|
-
"tools",
|
|
29
|
-
"claude",
|
|
30
|
-
"copilot",
|
|
31
|
-
"cursor"
|
|
32
|
-
],
|
|
33
|
-
"license": "MIT",
|
|
34
|
-
"repository": {
|
|
35
|
-
"type": "git",
|
|
36
|
-
"url": "https://git.modern-expo.com/asu/me-development/skills.git",
|
|
37
|
-
"directory": "suppa-mcp-node"
|
|
38
|
-
},
|
|
39
|
-
"homepage": "https://modern.suppa.me",
|
|
40
|
-
"dependencies": {
|
|
41
|
-
"@modelcontextprotocol/sdk": "^1.18.0",
|
|
42
|
-
"@napi-rs/keyring": "^1.1.0",
|
|
43
|
-
"zod": "^3.23.8"
|
|
44
|
-
},
|
|
45
|
-
"devDependencies": {
|
|
46
|
-
"@types/node": "^20.0.0",
|
|
47
|
-
"typescript": "^5.6.0",
|
|
48
|
-
"vitest": "^2.1.0"
|
|
49
|
-
}
|
|
50
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "suppa-mcp-2",
|
|
3
|
+
"version": "1.2.1",
|
|
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
|
+
"type": "module",
|
|
6
|
+
"bin": { "suppa-mcp": "dist/bin.js" },
|
|
7
|
+
"main": "dist/bin.js",
|
|
8
|
+
"files": ["dist", "skills", "README.md", "LICENSE"],
|
|
9
|
+
"engines": { "node": ">=18" },
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsc",
|
|
12
|
+
"clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
|
|
13
|
+
"rebuild": "npm run clean && npm run build",
|
|
14
|
+
"start": "node dist/bin.js",
|
|
15
|
+
"dev": "tsc --watch",
|
|
16
|
+
"test": "vitest run",
|
|
17
|
+
"test:watch": "vitest",
|
|
18
|
+
"prepublishOnly": "npm run build && npm test",
|
|
19
|
+
"inspect": "npx @modelcontextprotocol/inspector node dist/bin.js"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"mcp",
|
|
23
|
+
"model-context-protocol",
|
|
24
|
+
"suppa",
|
|
25
|
+
"modern-expo",
|
|
26
|
+
"ai",
|
|
27
|
+
"llm",
|
|
28
|
+
"tools",
|
|
29
|
+
"claude",
|
|
30
|
+
"copilot",
|
|
31
|
+
"cursor"
|
|
32
|
+
],
|
|
33
|
+
"license": "MIT",
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "https://git.modern-expo.com/asu/me-development/skills.git",
|
|
37
|
+
"directory": "suppa-mcp-node"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://modern.suppa.me",
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@modelcontextprotocol/sdk": "^1.18.0",
|
|
42
|
+
"@napi-rs/keyring": "^1.1.0",
|
|
43
|
+
"zod": "^3.23.8"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@types/node": "^20.0.0",
|
|
47
|
+
"typescript": "^5.6.0",
|
|
48
|
+
"vitest": "^2.1.0"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: suppa-entity-code
|
|
3
|
+
description: Write Suppa 2.0 application schema CODE — entity classes, seeds, and EntityModule registration — for a versioned application package, following the platform's declarative migration rules (the entity class IS the migration). Use whenever the user wants to create entities/tables/seeds as TypeScript code in an app repo instead of via API tools, port a Suppa 1.0 entity to v2 code, or asks about @Entity/@Column/@Enum/@ManyToOne decorators, createSeed, importKeyFields, or EntityModule.forFeature. Trigger phrases (English) — "write entity code", "entity class", "declarative migration", "create seed", "seed file", "register entity module", "port v1 entity to code"; (Ukrainian / Українська) — "написати код сутності", "клас сутності", "міграція", "сід", "seeds", "зареєструвати сутність", "перенести сутність у код".
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Suppa v2 Entity Code (declarative migrations)
|
|
7
|
+
|
|
8
|
+
The entity class **is** the migration — there is no separate migration file to write.
|
|
9
|
+
The platform converges every tenant's schema to your class definitions on every application start.
|
|
10
|
+
This skill writes `*.entity.ts` files, `*.seed.ts` files, and the `EntityModule.forFeature()` registration that wires them in.
|
|
11
|
+
|
|
12
|
+
## Which path — API tools or code?
|
|
13
|
+
|
|
14
|
+
| Situation | Use |
|
|
15
|
+
|---|---|
|
|
16
|
+
| Live tenant, no app repo — one-off schema change | `suppa_create_entity` / `suppa_add_field` (API tools) |
|
|
17
|
+
| Versioned application package — schema ships as code | **this skill** |
|
|
18
|
+
|
|
19
|
+
Code is authoritative: on every start, entity metadata is **overridden** to match the classes. Seed rows are **insert-only** — rows a user already edited in a tenant survive.
|
|
20
|
+
|
|
21
|
+
## Pre-flight (hard gate)
|
|
22
|
+
|
|
23
|
+
Confirm all 5 before writing anything:
|
|
24
|
+
|
|
25
|
+
1. Target app repo exists, with `src/index.ts` exporting `AppModule`.
|
|
26
|
+
2. `@suppa/sdk@latest` is installed (`pnpm add @suppa/sdk@latest`).
|
|
27
|
+
3. `tsconfig.json` has both `experimentalDecorators: true` and `emitDecoratorMetadata: true`.
|
|
28
|
+
4. Recommended layout is in place (or will be created): `src/common/database/{entities,seeds}`, each with an `index.ts` barrel.
|
|
29
|
+
5. A local module — conventionally `src/common/modules.ts` (imported as `'../../modules'` from `src/common/database/seeds/`) — exports `EntityNamesEnum` (one member per entity `name`).
|
|
30
|
+
|
|
31
|
+
## Blocking questions — ask BEFORE writing any file
|
|
32
|
+
|
|
33
|
+
| Ask | Get it wrong and… |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `importKeyFields` — the business key | Seeds have nothing to match on -> duplicate rows every restart |
|
|
36
|
+
| `representativeFieldName` | Records display incorrectly wherever the entity is referenced |
|
|
37
|
+
| Per-field `nullable` | The wrong constraint ships to every tenant |
|
|
38
|
+
| Flow B only — `inverse` selector for `@OneToMany` / `@ManyToManyBackRef` | v1 never reports it — it cannot be inferred, must ask |
|
|
39
|
+
|
|
40
|
+
## Hard rules
|
|
41
|
+
|
|
42
|
+
1. Every entity extends `SystemBaseEntity`; never declare `id`, `createdAt`, `updatedAt`, `deletedAt`, `createdBy`, `removedBy` yourself — it already provides them.
|
|
43
|
+
2. `default` is a SQL expression string — `'false'`, `"'draft'"` — never a JS value; a JS value is rejected at migration time.
|
|
44
|
+
3. 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.
|
|
45
|
+
4. Relation targets are thunks — `() => Target`, never the class itself — or circular imports break.
|
|
46
|
+
5. 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.
|
|
47
|
+
6. Every entity class must appear in some `forFeature()`'s `entities` array; every seed in its `seeds` array, dependencies first — `workflowsSeed` before `stageWorkflowsSeed`.
|
|
48
|
+
7. 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 `[]`.
|
|
49
|
+
8. Autoload paths (`entitiesPath`/`seedsPath`) point at `dist/`, never `src/` — autoloading reads compiled output.
|
|
50
|
+
9. Renames need `key` set on `@Entity()`/`@Column()` BEFORE the rename ships — otherwise it's a drop-and-create, not a rename.
|
|
51
|
+
10. 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.
|
|
52
|
+
|
|
53
|
+
## Decorator decision table
|
|
54
|
+
|
|
55
|
+
| You need | Decorator |
|
|
56
|
+
|---|---|
|
|
57
|
+
| Repeating rows owned by one parent record (checklist items, order lines, attendees) | **Tabular part** — `type: 'tabular-part'` + `relationEntityName` + a `@ManyToOne` field named `owner` on `@Entity()`; see `templates/tabular-part.template.ts` and `references/tabular-parts.md` |
|
|
58
|
+
| Scalar column (text/numeric/integer/boolean/timestamp/json/uuid/multi-language/bytea/tsvector/multi-type/icon) | `@Column({ type: FieldTypeEnum.<Member> })` |
|
|
59
|
+
| Fixed single-select value set | `@Enum('<Entity>.<field>', <Field>Enum, <Field>Titles?, options?)` |
|
|
60
|
+
| Fixed multi-select value set | `@MultiEnum(...)` — same signature as `@Enum` |
|
|
61
|
+
| Foreign key on this entity | `@ManyToOne(target, options?)` or `@ManyToOne(target, inverse, options?)` |
|
|
62
|
+
| Pivot table between two entities | `@ManyToMany(target, options?)` or `@ManyToMany(target, inverse, options?)` |
|
|
63
|
+
| Reverse side of a `@ManyToMany` | `@ManyToManyBackRef(target, inverse, options?)` |
|
|
64
|
+
| Reverse side of a `@ManyToOne` | `@OneToMany(target, inverse, options?)` |
|
|
65
|
+
| Single attachment | `@File({ title })` |
|
|
66
|
+
| Multiple attachments | `@MultiFile({ title })` |
|
|
67
|
+
|
|
68
|
+
`target` is always a thunk, `() => Target`. `inverse` is a property selector on the target entity, e.g. `(task) => task.project`.
|
|
69
|
+
|
|
70
|
+
## Naming conventions
|
|
71
|
+
|
|
72
|
+
| Thing | Convention | Example |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| Entity/seed file | kebab-case, plural | `stage-workflows.entity.ts` / `stage-workflows.seed.ts` |
|
|
75
|
+
| Entity class | PascalCase, plural = `@Entity()`'s `name` | `StageWorkflows` |
|
|
76
|
+
| Seed export | camelCase plural + `Seed` | `stageWorkflowsSeed` |
|
|
77
|
+
| Enum | PascalCase + `Enum` | `StageStatusEnum` |
|
|
78
|
+
| Titles map | PascalCase + `Titles` suffix — this doc's own worked examples drop the suffix (`StageStatus`); either is acceptable if used consistently within a repo | `StageStatusTitles` (or `StageStatus`) |
|
|
79
|
+
| Enum global name | `'<EntityName>.<field>'` | `'StageWorkflows.status'` |
|
|
80
|
+
| Index name | `idx_<table>_<cols>` | `idx_tasks_project` |
|
|
81
|
+
| Check name | `chk_<table>_<rule>` | `chk_tasks_positive_duration` |
|
|
82
|
+
|
|
83
|
+
## Flow A — new entity in an app repo
|
|
84
|
+
|
|
85
|
+
1. Pre-flight (above) — confirm repo, SDK version, tsconfig, layout.
|
|
86
|
+
2. Blocking questions (above) — get answers before writing any file.
|
|
87
|
+
3. Write the entity from `templates/entity.template.ts`, following `references/entities.md`.
|
|
88
|
+
4. Need default rows? Write the seed from `templates/seed.template.ts`, following `references/seeds.md`.
|
|
89
|
+
5. Update the `entities`/`seeds` barrels and the `EntityModule.forFeature()` call — `references/registration.md`.
|
|
90
|
+
6. Run the close-out gate (below) — do not report "done" before all 4 steps pass.
|
|
91
|
+
|
|
92
|
+
## Flow B — port a Suppa 1.0 entity to v2 code
|
|
93
|
+
|
|
94
|
+
1. `suppa_read_v1_entities` -> find the v1 entity.
|
|
95
|
+
2. `suppa_read_v1_entity_props` (+ `suppa_read_v1_enum` for enum fields) -> read its fields.
|
|
96
|
+
3. Map every field per `references/v1-mapping.md` — the same authority (`classifyV1Field`) as the API migration path.
|
|
97
|
+
4. Never silently drop a field: anything unmapped or unsupported gets `// SKIPPED: <field> — <reason>` inside the class body.
|
|
98
|
+
5. Continue with Flow A from the blocking questions onward (steps 2-6 above).
|
|
99
|
+
6. Record data migrates separately, via `suppa_migrate_entities_from_v1` — this skill only produces schema code.
|
|
100
|
+
|
|
101
|
+
## Close-out gate (all steps, in order — no "done" before all pass)
|
|
102
|
+
|
|
103
|
+
```
|
|
104
|
+
1. node <this-skill-dir>/scripts/validate-suppa-schema.mjs <app-root> # 0 errors
|
|
105
|
+
(installed via npm: node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs)
|
|
106
|
+
2. npx tsc --noEmit # in the app repo
|
|
107
|
+
3. push, then reload: POST /core/applications/:appId/reload
|
|
108
|
+
4. verify the tenant converged: suppa_describe_entity('<EntityName>')
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`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.
|
|
112
|
+
|
|
113
|
+
## Troubleshooting
|
|
114
|
+
|
|
115
|
+
| Symptom | Cause | Validator code |
|
|
116
|
+
|---|---|---|
|
|
117
|
+
| No table is created for an entity | The class was not passed to `EntityModule.forFeature()` | E301 |
|
|
118
|
+
| Autoloading finds nothing | `entitiesPath` / `seedsPath` points at `src/` instead of compiled `dist/` | E303 |
|
|
119
|
+
| Duplicate seed rows after a restart | Record is missing one or more `importKeyFields` | E205 |
|
|
120
|
+
| Seed relation is empty or fails to resolve | Relation referenced by numeric id, or the target seed runs later | E203 + E304 |
|
|
121
|
+
| Back reference can't insert | A reverse `@OneToMany` field is present in a seed record, possibly as `[]` | E204 |
|
|
122
|
+
| A renamed entity or field appears as a new one | No `key` option was set | W602 |
|
|
123
|
+
| `default` value is rejected | A JavaScript value was passed instead of a SQL expression string | E103 |
|
|
124
|
+
| 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 |
|
|
125
|
+
| 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 |
|
|
126
|
+
| 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 |
|
|
127
|
+
| A tabular part has no `ownerId` column and its tab stays empty | `relationEntityName` was set, but the `owner` `@ManyToOne` was not declared | E108 |
|
|
128
|
+
| A tabular part is missing from the parent's tabs | `type: 'tabular-part'` or `relationEntityName` is missing, so it is listed under `/related` instead | E108 |
|
|
129
|
+
| Duplicate tabular-part rows across different parents | `owner` is missing from `importKeyFields`, so the key is matched globally instead of per-parent | E110 |
|
|
130
|
+
| A tabular part's rows land on/read from the wrong parent | `owner`'s `@ManyToOne` target resolves to an entity whose `@Entity()` name doesn't match `relationEntityName` | E109 |
|
|
131
|
+
| A tabular part's business key isn't scoped to its parent | `owner` is present in `importKeyFields` but not first | W607 |
|
|
132
|
+
| Validator warns W606 | Content delivered via spread or reference — options, `default`, `importKeyFields`, seed records, enum refs, `$key`, autoload paths, registration arrays, tabular-part `type`/`relationEntityName` — is not statically verifiable; the matching check is skipped. Inline it so the validator can check | W606 |
|
|
133
|
+
| Validator warns W608 | No `tsconfig.json` at the given root, so `experimentalDecorators`/`emitDecoratorMetadata` could not be verified — point the validator at the app root | W608 |
|