suppa-mcp-2 1.33.0 → 1.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/customFieldHints.js +19 -0
- package/dist/server.js +1 -1
- package/dist/tools/customFieldSets.js +11 -1
- package/dist/tools/customFields.js +63 -1
- package/dist/tools/customFieldsAsCode.js +13 -1
- package/dist/tools/entity.js +74 -6
- package/package.json +1 -1
- package/skills/suppa-entity-code/SKILL.md +6 -1
- package/skills/suppa-entity-code/references/custom-fields.md +28 -0
- package/skills/suppa-entity-code/scripts/house-rules.mjs +8 -4
- package/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs +306 -0
- package/skills/suppa-entity-code/templates/custom-fields.template.ts +95 -0
package/dist/customFieldHints.js
CHANGED
|
@@ -61,6 +61,25 @@ const ERROR_HINTS = [
|
|
|
61
61
|
"reserved so the parked column can still be restored. Either bring the original back with " +
|
|
62
62
|
"suppa_restore_custom_field (its values come with it), or choose a different name.",
|
|
63
63
|
},
|
|
64
|
+
{
|
|
65
|
+
// Verified 2026-09-11 on modern-expo.dev.suppa.me, four shapes, all on the
|
|
66
|
+
// probe entity: a Localization object {en, uk} → 400 write.invalid_relation_value
|
|
67
|
+
// on path 'title'; {en} → 400 'Field "key" is required'; {key, en} → 400
|
|
68
|
+
// 'Field "category" is required' (the object is being written as a
|
|
69
|
+
// Localizations RECORD); a plain string → 201, echoed back, and stored as
|
|
70
|
+
// NULL; no title → 201. The last field whose title was stored dates from
|
|
71
|
+
// 2026-09-10 13:41. builder.txt:56 still says 'title | object | Localization
|
|
72
|
+
// object', so this is the platform, not the contract.
|
|
73
|
+
// The message arrives inside a stringified JSON body, so the quotes around
|
|
74
|
+
// the field name may carry a backslash: \"title\", \"key\".
|
|
75
|
+
match: /.?"title.?" must contain an integer id|invalid_relation_value[^]*"path":"title"|Field .?"(key|category).?" is required/i,
|
|
76
|
+
hint: "The builder is currently REJECTING field titles: the Localization object the doc prescribes " +
|
|
77
|
+
"(builder.txt:56) is being written as a Localizations record and fails, and a plain string is " +
|
|
78
|
+
"accepted but stored as null (verified on dev 2026-09-11; last title stored 2026-09-10 13:41). " +
|
|
79
|
+
"NOTHING was created. Re-send WITHOUT title — the field is created untitled and works; set the " +
|
|
80
|
+
"label in the UI or with suppa_update_field once the platform fix lands. This is a backend " +
|
|
81
|
+
"regression worth reporting with the traceId above.",
|
|
82
|
+
},
|
|
64
83
|
{
|
|
65
84
|
match: /HTTP 409|statusCode":409/,
|
|
66
85
|
hint: "Concurrent write: two writers created the values row for the same record at once (the " +
|
package/dist/server.js
CHANGED
|
@@ -1521,7 +1521,7 @@ export function buildServer() {
|
|
|
1521
1521
|
})));
|
|
1522
1522
|
reg("suppa_apply_custom_fields", {
|
|
1523
1523
|
description: "Custom fields DECLARED IN A REPO FILE, applied to a tenant — the file is the source of truth.\n" +
|
|
1524
|
-
"
|
|
1524
|
+
" On @suppa/sdk 1.38.0+ prefer @CustomFields in the entity class (SKILL.md rule 22).\n" +
|
|
1525
1525
|
' declaration: {"entity","context_field","fields":[{"name","type","title","contexts":["PL"]}]}.\n' +
|
|
1526
1526
|
" Idempotent — a second run answers already_converged. Creates per context in ONE atomic\n" +
|
|
1527
1527
|
" batch, then links existing fields into their other contexts.\n" +
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
import { insertEntity, makeRequest, removeEntity, searchEntity, updateEntity, } from "../httpClient.js";
|
|
30
30
|
import { confirmRequired, jsonResponse, parseJsonParam } from "../utils.js";
|
|
31
31
|
import { buildFieldDef } from "./entity.js";
|
|
32
|
-
import { customFieldsEntity, resolveBody } from "./customFields.js";
|
|
32
|
+
import { customFieldsEntity, customFieldsUsage, quotaNote, resolveBody, } from "./customFields.js";
|
|
33
33
|
const SET_ENTITY = "CustomFieldSets";
|
|
34
34
|
const LINK_ENTITY = "CustomFieldSetFields";
|
|
35
35
|
const META_ENTITY = "FieldMetadata";
|
|
@@ -326,6 +326,14 @@ export async function addCustomFieldsBatch(entityName, fieldsJson, sel) {
|
|
|
326
326
|
const envelope = { fields: defs };
|
|
327
327
|
if (hasContext)
|
|
328
328
|
envelope.context = { field: sel.contextField, value: sel.contextValue };
|
|
329
|
+
// Read before the write, so the number is what the batch adds TO.
|
|
330
|
+
let usage = null;
|
|
331
|
+
try {
|
|
332
|
+
usage = await customFieldsUsage(extension);
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
usage = null;
|
|
336
|
+
}
|
|
329
337
|
let result;
|
|
330
338
|
try {
|
|
331
339
|
result = await makeRequest("POST", `/api/core/builder/${entityName}/add-fields`, {
|
|
@@ -341,6 +349,8 @@ export async function addCustomFieldsBatch(entityName, fieldsJson, sel) {
|
|
|
341
349
|
});
|
|
342
350
|
}
|
|
343
351
|
const out = { created: defs.length, fields: defs.map((d) => d.name), result };
|
|
352
|
+
if (usage)
|
|
353
|
+
Object.assign(out, quotaNote(usage, defs.length));
|
|
344
354
|
if (hasContext) {
|
|
345
355
|
try {
|
|
346
356
|
const { body } = resolveBody(null, sel.contextField ?? null, sel.contextValue ?? null);
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
* field mandatory is `required` on the CustomFieldSetFields link row, which
|
|
43
43
|
* the platform enforces when the values row is created.
|
|
44
44
|
*/
|
|
45
|
-
import { makeRequest } from "../httpClient.js";
|
|
45
|
+
import { makeRequest, searchEntity } from "../httpClient.js";
|
|
46
46
|
import { customFieldsHint } from "../customFieldHints.js";
|
|
47
47
|
import { jsonResponse, confirmRequired } from "../utils.js";
|
|
48
48
|
import { buildFieldDef, CUSTOM_FIELDS_EXTENSION_SUFFIX, CUSTOM_FIELDS_KEY, CUSTOM_FIELDS_OPTION, } from "./entity.js";
|
|
@@ -74,6 +74,58 @@ export function customFieldsEntity(ownerEntity) {
|
|
|
74
74
|
: `${ownerEntity}${CUSTOM_FIELDS_EXTENSION_SUFFIX}`;
|
|
75
75
|
}
|
|
76
76
|
export { customFieldsHint };
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
// The per-table quota
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
/**
|
|
81
|
+
* api/entity-builder/custom-fields.html: "Active client fields per extension
|
|
82
|
+
* table capped at CUSTOM_FIELDS_LIMIT (default 200). Exceeding limit → 400 with
|
|
83
|
+
* usage numbers." And migrations.html: the cap "guards the API, not migrations"
|
|
84
|
+
* — a declaration can push a table past it, and the API then stops serving that
|
|
85
|
+
* table. The number is env-overridable and a product decision, so everything
|
|
86
|
+
* here REPORTS against the default and never refuses on it: the platform knows
|
|
87
|
+
* its own limit and says so in its 400.
|
|
88
|
+
*/
|
|
89
|
+
export const CUSTOM_FIELDS_DEFAULT_LIMIT = 200;
|
|
90
|
+
/** How many active client fields the extension table already carries. */
|
|
91
|
+
export async function customFieldsUsage(extension) {
|
|
92
|
+
const rows = (await searchEntity("FieldMetadata", [{ field: "entity.name", value: extension, comparator: "=" }],
|
|
93
|
+
// Only CLIENT fields count: the platform's own service columns on the
|
|
94
|
+
// extension table (owner, id, createdAt…) are not custom fields.
|
|
95
|
+
{ id: true, name: true, deletedAt: true, initiator: true }, 500));
|
|
96
|
+
let active = 0;
|
|
97
|
+
for (const r of Array.isArray(rows) ? rows : []) {
|
|
98
|
+
if (!r || r.deletedAt)
|
|
99
|
+
continue;
|
|
100
|
+
// A row that does not say who created it is counted: undercounting is the
|
|
101
|
+
// side that surprises.
|
|
102
|
+
if (r.initiator !== undefined && r.initiator !== null && r.initiator !== "client")
|
|
103
|
+
continue;
|
|
104
|
+
active++;
|
|
105
|
+
}
|
|
106
|
+
return { active_client_fields: active, default_limit: CUSTOM_FIELDS_DEFAULT_LIMIT };
|
|
107
|
+
}
|
|
108
|
+
/** The quota lines for a response that adds `adding` fields — a warning only when it earns one. */
|
|
109
|
+
export function quotaNote(usage, adding) {
|
|
110
|
+
const after = usage.active_client_fields + adding;
|
|
111
|
+
const out = {
|
|
112
|
+
custom_fields_on_table: after,
|
|
113
|
+
default_limit: usage.default_limit,
|
|
114
|
+
};
|
|
115
|
+
if (after > usage.default_limit) {
|
|
116
|
+
out.quota_warning =
|
|
117
|
+
`${after} active custom fields on this table is OVER the default CUSTOM_FIELDS_LIMIT of ` +
|
|
118
|
+
`${usage.default_limit}. The platform enforces its configured limit with a 400 carrying the usage ` +
|
|
119
|
+
"numbers; a tenant may run a higher one, so this is a flag, not a refusal. The cap guards the " +
|
|
120
|
+
"API, not migrations — a declaration can push a table past it and the API then stops serving it.";
|
|
121
|
+
}
|
|
122
|
+
else if (after >= Math.floor(usage.default_limit * 0.9)) {
|
|
123
|
+
out.quota_warning =
|
|
124
|
+
`${after} of the default CUSTOM_FIELDS_LIMIT (${usage.default_limit}) active custom fields on ` +
|
|
125
|
+
"this table — within 10% of the cap.";
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
77
129
|
/** Turn a thrown transport error into the tool's JSON answer, with a hint when there is one. */
|
|
78
130
|
function errorResponse(e, extra = {}) {
|
|
79
131
|
const message = e instanceof Error ? e.message : String(e);
|
|
@@ -220,6 +272,14 @@ export async function addCustomField(entityName, fieldName, fieldType, title, op
|
|
|
220
272
|
else {
|
|
221
273
|
fieldDef.sets = ids;
|
|
222
274
|
}
|
|
275
|
+
// Read BEFORE the write, so the number is what this field is added to.
|
|
276
|
+
let usage = null;
|
|
277
|
+
try {
|
|
278
|
+
usage = await customFieldsUsage(extension);
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
usage = null; // the quota line is a courtesy; a failed read is not a failed add
|
|
282
|
+
}
|
|
223
283
|
let result;
|
|
224
284
|
try {
|
|
225
285
|
result = await makeRequest("POST", `/api/core/builder/${entityName}/add-fields`, {
|
|
@@ -230,6 +290,8 @@ export async function addCustomField(entityName, fieldName, fieldType, title, op
|
|
|
230
290
|
return errorResponse(e, { sent: { customFields: envelope } });
|
|
231
291
|
}
|
|
232
292
|
const out = { result };
|
|
293
|
+
if (usage)
|
|
294
|
+
Object.assign(out, quotaNote(usage, 1));
|
|
233
295
|
if (built.notApplicable && built.notApplicable.length > 0) {
|
|
234
296
|
out.not_applicable = built.notApplicable;
|
|
235
297
|
}
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
* migration with data in it, and guessing at one from a diff is how data is
|
|
49
49
|
* lost.
|
|
50
50
|
*/
|
|
51
|
-
import { customFieldsEntity } from "./customFields.js";
|
|
51
|
+
import { customFieldsEntity, customFieldsUsage, quotaNote } from "./customFields.js";
|
|
52
52
|
import { addCustomFieldsBatch, extensionFields, linkCustomFields } from "./customFieldSets.js";
|
|
53
53
|
import { jsonResponse, parseJsonParam } from "../utils.js";
|
|
54
54
|
import { makeRequest } from "../httpClient.js";
|
|
@@ -204,10 +204,21 @@ export async function applyCustomFieldsDeclaration(declaration, opts = {}) {
|
|
|
204
204
|
const contexts = [...new Set(decl.fields.flatMap((f) => f.contexts.map(String)))];
|
|
205
205
|
const offered = await readOffered(decl.entity, decl.context_field, contexts);
|
|
206
206
|
const plan = diffDeclaration(decl, live, offered);
|
|
207
|
+
// Where the table stands after convergence — a port of a long list is exactly
|
|
208
|
+
// how a table is pushed past the cap (migrations.html: the cap "guards the API,
|
|
209
|
+
// not migrations").
|
|
210
|
+
let quota = {};
|
|
211
|
+
try {
|
|
212
|
+
quota = quotaNote(await customFieldsUsage(extension), plan.create.reduce((n, g) => n + g.fields.length, 0));
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
quota = {};
|
|
216
|
+
}
|
|
207
217
|
if (!opts.confirm) {
|
|
208
218
|
return jsonResponse({
|
|
209
219
|
status: planIsEmpty(plan) ? "already_converged" : "dry_run",
|
|
210
220
|
plan,
|
|
221
|
+
...quota,
|
|
211
222
|
next: planIsEmpty(plan)
|
|
212
223
|
? "Nothing to do — the tenant already matches the file."
|
|
213
224
|
: "Re-call with confirm=true to apply. Nothing has been created yet.",
|
|
@@ -248,6 +259,7 @@ export async function applyCustomFieldsDeclaration(declaration, opts = {}) {
|
|
|
248
259
|
entity: decl.entity,
|
|
249
260
|
extension,
|
|
250
261
|
applied,
|
|
262
|
+
...quota,
|
|
251
263
|
unchanged: plan.unchanged.length,
|
|
252
264
|
type_drift: plan.type_drift,
|
|
253
265
|
not_declared: plan.not_declared,
|
package/dist/tools/entity.js
CHANGED
|
@@ -1648,8 +1648,18 @@ export async function buildFieldDef(entityName, fieldName, fieldType, title, opt
|
|
|
1648
1648
|
const fieldDef = {
|
|
1649
1649
|
name: fieldName,
|
|
1650
1650
|
type: resolvedType,
|
|
1651
|
-
title: await _expandTitle(title, fieldName),
|
|
1652
1651
|
};
|
|
1652
|
+
// Sent ONLY when the caller gave one. builder.txt:56 marks title optional, and
|
|
1653
|
+
// the fallback that used to fill it from the field name did two things badly:
|
|
1654
|
+
// it stored a machine name as a human label, and since 2026-09-11 it makes
|
|
1655
|
+
// EVERY add fail on dev — the builder there answers 400 to any title object
|
|
1656
|
+
// (write.invalid_relation_value on path 'title'), accepts a plain string and
|
|
1657
|
+
// stores null for it, and last stored a title on 2026-09-10 13:41. A field
|
|
1658
|
+
// with no title is created; one with an invented title is not.
|
|
1659
|
+
const hasTitle = title !== null && title !== undefined && (isPlainObject(title) || String(title).trim() !== "");
|
|
1660
|
+
if (hasTitle) {
|
|
1661
|
+
fieldDef.title = await _expandTitle(title, fieldName);
|
|
1662
|
+
}
|
|
1653
1663
|
// Applicability is per the builder's own table, and a constraint that does not
|
|
1654
1664
|
// apply is DROPPED by the builder without complaint — so sending it would be
|
|
1655
1665
|
// reported back to the agent as applied while nothing changed. Each of these
|
|
@@ -1778,9 +1788,23 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
|
|
|
1778
1788
|
// Correct endpoint is /builder/{Entity}/add-fields and the body is the bare
|
|
1779
1789
|
// array of field defs (the old /builder/add-fields with an {entityName,fields}
|
|
1780
1790
|
// wrapper 404s).
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1791
|
+
let result;
|
|
1792
|
+
try {
|
|
1793
|
+
result = await makeRequest("POST", `/api/core/builder/${entityName}/add-fields`, [
|
|
1794
|
+
built.fieldDef,
|
|
1795
|
+
]);
|
|
1796
|
+
}
|
|
1797
|
+
catch (e) {
|
|
1798
|
+
// A platform refusal this server can explain comes back as JSON with the
|
|
1799
|
+
// next step, the way suppa_add_custom_field already answers. Anything else
|
|
1800
|
+
// propagates exactly as before.
|
|
1801
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
1802
|
+
const hint = customFieldsHint(message);
|
|
1803
|
+
if (hint) {
|
|
1804
|
+
return jsonResponse({ error: message, hint, sent: built.fieldDef });
|
|
1805
|
+
}
|
|
1806
|
+
throw e;
|
|
1807
|
+
}
|
|
1784
1808
|
// Plain result when everything asked for was applied — the shape callers and
|
|
1785
1809
|
// tests already read. The wrapper appears only when something was withheld,
|
|
1786
1810
|
// because that is the case a bare success would misreport.
|
|
@@ -2660,6 +2684,23 @@ async function _resolveEntity(name) {
|
|
|
2660
2684
|
if (ci) {
|
|
2661
2685
|
return { name: ci, names };
|
|
2662
2686
|
}
|
|
2687
|
+
// The platform hides its extension tables ('<Entity>CustomFields') from the
|
|
2688
|
+
// listing, so a name that is absent from it may still be readable by name —
|
|
2689
|
+
// describeEntityCompact learned this first. A write to one is legitimate
|
|
2690
|
+
// (api/entity-builder/custom-fields.html §6B), just not atomic with the owner,
|
|
2691
|
+
// and the write path says so; refusing it as "does not exist" was the listing
|
|
2692
|
+
// talking, not the tenant.
|
|
2693
|
+
if (name.endsWith(CUSTOM_FIELDS_EXTENSION_SUFFIX)) {
|
|
2694
|
+
try {
|
|
2695
|
+
const schema = await makeRequest("GET", `/api/core/schema/${name}`);
|
|
2696
|
+
if (_extractFields(schema).some((f) => f.name === "owner")) {
|
|
2697
|
+
return { name, names };
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
catch {
|
|
2701
|
+
// fall through to the refusal below — a failed read is not an entity
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2663
2704
|
const nl = name.toLowerCase();
|
|
2664
2705
|
const near = names
|
|
2665
2706
|
.filter((n) => n.toLowerCase().includes(nl) || nl.includes(n.toLowerCase()))
|
|
@@ -2706,6 +2747,11 @@ async function _validateRecordWrites(entityName, records) {
|
|
|
2706
2747
|
// Filled in below when a written enum value turns out to belong to another
|
|
2707
2748
|
// group. It rides back to the caller, which attaches it to the RESULT.
|
|
2708
2749
|
let enumWarning;
|
|
2750
|
+
// Set when the target IS an extension table. api/entity-builder/custom-fields.html:
|
|
2751
|
+
// both paths validate against the owner's active sets, but a direct write
|
|
2752
|
+
// "bridges into an owner update after the values row is written" and is NOT
|
|
2753
|
+
// atomic — the values commit first. Inline on the owner is the atomic path.
|
|
2754
|
+
let extensionWarning;
|
|
2709
2755
|
// The SAME schema read carries the entity's custom field definitions in its
|
|
2710
2756
|
// own `customFields` array (name, type, options, setIds) — so validating the
|
|
2711
2757
|
// inline custom values costs no extra request.
|
|
@@ -2719,6 +2765,17 @@ async function _validateRecordWrites(entityName, records) {
|
|
|
2719
2765
|
defs = null; // unreadable → can't validate fields; proceed
|
|
2720
2766
|
}
|
|
2721
2767
|
if (defs && defs.length > 0) {
|
|
2768
|
+
if (entityName.endsWith(CUSTOM_FIELDS_EXTENSION_SUFFIX) &&
|
|
2769
|
+
defs.some((f) => f.name === "owner" && /many.?to.?one/i.test(String(f.type ?? "")))) {
|
|
2770
|
+
const owner = entityName.slice(0, -CUSTOM_FIELDS_EXTENSION_SUFFIX.length);
|
|
2771
|
+
extensionWarning = {
|
|
2772
|
+
warning: `'${entityName}' is the custom-values table of '${owner}'. Writing it directly works, but it ` +
|
|
2773
|
+
"is NOT atomic with the owner: the values row commits first and the owner update is bridged " +
|
|
2774
|
+
"in afterwards, so a failing owner hook leaves the values changed.",
|
|
2775
|
+
prefer: `suppa_update_record("${owner}", <record id>, fields_json='{"customFields": {"<field>": <value>}}')` +
|
|
2776
|
+
" — one transaction, updatedAt bumped, triggers and automations see customFields among the changed fields.",
|
|
2777
|
+
};
|
|
2778
|
+
}
|
|
2722
2779
|
const many = records.length > 1;
|
|
2723
2780
|
const fieldNames = new Set(defs.map((f) => f.name).filter((n) => Boolean(n)));
|
|
2724
2781
|
const unknown = [
|
|
@@ -2801,7 +2858,7 @@ async function _validateRecordWrites(entityName, records) {
|
|
|
2801
2858
|
}
|
|
2802
2859
|
// The defs travel back so the caller does not re-read the schema to decide
|
|
2803
2860
|
// which written fields are actually list-valued (see `_replacedListNames`).
|
|
2804
|
-
return { entityName, defs: defs && defs.length > 0 ? defs : null, enumWarning };
|
|
2861
|
+
return { entityName, defs: defs && defs.length > 0 ? defs : null, enumWarning, extensionWarning };
|
|
2805
2862
|
}
|
|
2806
2863
|
// The only field types whose stored value IS a list, so the only ones an update
|
|
2807
2864
|
// can replace wholesale and the only ones merge/unmerge applies to. Types from
|
|
@@ -2929,7 +2986,13 @@ export async function createRecord(entityName, fieldsJson) {
|
|
|
2929
2986
|
// Namespaced with a leading underscore so it cannot collide with a field:
|
|
2930
2987
|
// the bare record IS the documented shape here, and this key only appears
|
|
2931
2988
|
// when there is something to say.
|
|
2932
|
-
return jsonResponse(v.enumWarning
|
|
2989
|
+
return jsonResponse(v.enumWarning || v.extensionWarning
|
|
2990
|
+
? {
|
|
2991
|
+
...returned[0],
|
|
2992
|
+
...(v.enumWarning ? { _enum_group_warning: v.enumWarning } : {}),
|
|
2993
|
+
...(v.extensionWarning ? { _direct_extension_write_warning: v.extensionWarning } : {}),
|
|
2994
|
+
}
|
|
2995
|
+
: returned[0]);
|
|
2933
2996
|
}
|
|
2934
2997
|
return jsonResponse({
|
|
2935
2998
|
created: returned.length,
|
|
@@ -2937,6 +3000,7 @@ export async function createRecord(entityName, fieldsJson) {
|
|
|
2937
3000
|
entity: v.entityName,
|
|
2938
3001
|
records: returned,
|
|
2939
3002
|
...(v.enumWarning ? { enum_group_warning: v.enumWarning } : {}),
|
|
3003
|
+
...(v.extensionWarning ? { direct_extension_write_warning: v.extensionWarning } : {}),
|
|
2940
3004
|
});
|
|
2941
3005
|
}
|
|
2942
3006
|
/** Parse a merge_json/unmerge_json parameter into a list of field names. */
|
|
@@ -3024,6 +3088,7 @@ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson =
|
|
|
3024
3088
|
// still chose it. Dropping the warning here hid it from every probe that
|
|
3025
3089
|
// targets a missing row — which is how this omission was found.
|
|
3026
3090
|
...(v.enumWarning ? { enum_group_warning: v.enumWarning } : {}),
|
|
3091
|
+
...(v.extensionWarning ? { direct_extension_write_warning: v.extensionWarning } : {}),
|
|
3027
3092
|
result,
|
|
3028
3093
|
});
|
|
3029
3094
|
}
|
|
@@ -3050,6 +3115,9 @@ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson =
|
|
|
3050
3115
|
if (v.enumWarning) {
|
|
3051
3116
|
out.enum_group_warning = v.enumWarning;
|
|
3052
3117
|
}
|
|
3118
|
+
if (v.extensionWarning) {
|
|
3119
|
+
out.direct_extension_write_warning = v.extensionWarning;
|
|
3120
|
+
}
|
|
3053
3121
|
out.result = Array.isArray(result) && result.length ? result[0] : result;
|
|
3054
3122
|
return jsonResponse(out);
|
|
3055
3123
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "suppa-mcp-2",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.35.0",
|
|
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": {
|
|
@@ -23,7 +23,7 @@ Code is authoritative: on every start, entity metadata is **overridden** to matc
|
|
|
23
23
|
Confirm all 5 before writing anything:
|
|
24
24
|
|
|
25
25
|
1. Target app repo exists, with `src/index.ts` exporting `AppModule`.
|
|
26
|
-
2. `@suppa/sdk@latest` is installed (`pnpm add @suppa/sdk@latest`).
|
|
26
|
+
2. `@suppa/sdk@latest` is installed (`pnpm add @suppa/sdk@latest`) — and **1.38.0 or newer if the schema declares custom fields** (`@CustomFields` does not exist below it; E129).
|
|
27
27
|
3. `tsconfig.json` has both `experimentalDecorators: true` and `emitDecoratorMetadata: true`.
|
|
28
28
|
4. Recommended layout is in place (or will be created): `src/common/database/{entities,seeds}`, each with an `index.ts` barrel.
|
|
29
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`).
|
|
@@ -131,11 +131,16 @@ Confirm all 5 before writing anything:
|
|
|
131
131
|
|
|
132
132
|
On an entity you do **not** own, the columns still come from your file — only the switch is out of reach: extension mode ignores entity options, so enable the feature once with `suppa_update_entity_options(entity_name, '{"customFields": true}')` (`POST /core/builder/<Entity>/update-options`). That is what W618 means when it fires on `options`.
|
|
133
133
|
|
|
134
|
+
The gate enforces all of it — E124 (nested class registered, decorated or extending a base class), E125 (property name), E126 (primary / reverse relation), E127 (`nullable: false` without a default), E128 (half a context), E129 (SDK below 1.38.0), E130 (one class shared by two owners), W621 (column with no set), W622 (`contextField` not on the owner), W623 (the option written beside the decorator), W625 (a number as `contextValue` on an enum context field — that is an Enums row id copied off one tenant, not the stored value). Start from `templates/custom-fields.template.ts`.
|
|
135
|
+
|
|
136
|
+
Two limits from the API reference: the extension table is capped at `CUSTOM_FIELDS_LIMIT` active custom fields (**default 200** — the cap guards the API, not migrations, so a long port can push a table past it and the API then stops serving it; the MCP tools that add fields report where the table stands), and a set declared for a context value applies to that value's **descendants** when the context field points at a hierarchical entity, so one entry covers a subtree.
|
|
137
|
+
|
|
134
138
|
## Decorator decision table
|
|
135
139
|
|
|
136
140
|
| You need | Decorator |
|
|
137
141
|
|---|---|
|
|
138
142
|
| 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` |
|
|
143
|
+
| A field only SOME records show, decided by another field's value (custom fields) | `@CustomFields(() => OwnerCustomFields)` on a property named `customFields`; the columns in a plain nested class with `options.customFieldSets` — rule 22, `templates/custom-fields.template.ts`, `references/custom-fields.md` |
|
|
139
144
|
| Scalar column (text/numeric/integer/boolean/timestamp/json/uuid/multi-language/bytea/tsvector/multi-type/icon) | `@Column({ type: FieldTypeEnum.<Member> })` |
|
|
140
145
|
| Date-only column (no time part) | `@Column({ type: FieldTypeEnum.Timestamp, subType: 'date' })` — there is **no** `FieldTypeEnum.Date` |
|
|
141
146
|
| Time-only column | `@Column({ type: FieldTypeEnum.Timestamp, subType: 'time' })` — there is **no** `FieldTypeEnum.Time` |
|
|
@@ -215,6 +215,34 @@ For a large port the platform ships a generator rather than asking you to type i
|
|
|
215
215
|
|
|
216
216
|
That dump shape is exactly the declaration `suppa_apply_custom_fields` reads, so a file written for the MCP tool ports to the decorator without being retyped — and vice versa.
|
|
217
217
|
|
|
218
|
+
## What the API reference adds
|
|
219
|
+
|
|
220
|
+
The migrations page links to a separate [custom fields API reference](https://docs.modern-expo.com/backend/api/entity-builder/custom-fields.html) for "the full contract — projections, search, per-set attributes". Captured as `docs/superpowers/specs/captures/api-custom-fields.txt`. Six things there change how you write the class:
|
|
221
|
+
|
|
222
|
+
- **There is a per-table cap.** Active client fields per extension table are limited by `CUSTOM_FIELDS_LIMIT`, **default 200**; exceeding it answers 400 with the usage numbers. The migrations page says the cap "guards the API, not migrations" — a declaration can push a table past it, and then the API stops serving that table. Count the properties before porting a large list.
|
|
223
|
+
- **Sets are inherited down a hierarchy.** "When the context field relates to a hierarchical entity with `parents`, sets also apply to descendants of the `contextValue`." So a field declared for a parent context shows on records of its children; you do not declare one entry per descendant.
|
|
224
|
+
- **A field in several sets merges its per-set attributes**, and the rules are not "last wins": `required` — any set demanding it wins; `readOnly` — an explicit editable beats a read-only, `null` defers to the field; `defaultValue` — the first non-null in set id order.
|
|
225
|
+
- **The owner's schema already lists the sets.** `GET /core/schema/<E>` carries a `customFieldSets` array (`id`, `title`, `contextFieldName`, `contextValue`) beside `customFields` with their `setIds` — the cheap way to see every context at once. It is schema only; the ACTIVE set for a given record still comes from `/custom-fields/<E>/resolve`.
|
|
226
|
+
- **You can sort and filter through a relation custom field** — `customFields.reviewer.fullName` — because each step of the chain yields at most one row. A multi-row collection in the chain is `400 query.planner_unsupported`. Full-text search covers the extension table's own searchable TEXT fields only (not a relation's content), and the base entity must have at least one searchable field of its own.
|
|
227
|
+
- **Write values inline on the owner, not on the extension table.** Both paths validate against the active sets, but a direct extension-table write "bridges into an owner update after the values row is written" and is **not atomic** — the values commit first. Inline writes run inside the owner's transaction, bump `updatedAt`, and fire triggers, socket events and automations with `customFields` among the changed fields.
|
|
228
|
+
|
|
229
|
+
## What the gate checks
|
|
230
|
+
|
|
231
|
+
| Code | Rule it enforces |
|
|
232
|
+
|---|---|
|
|
233
|
+
| E124 | the nested class is passed to `forFeature()`, carries `@Entity()`, or extends a base class |
|
|
234
|
+
| E125 | the property is not named `customFields` |
|
|
235
|
+
| E126 | `primary`, `@OneToMany()` or `@ManyToManyBackRef()` on a custom-field column |
|
|
236
|
+
| E127 | `nullable: false` with no `default` |
|
|
237
|
+
| E128 | a `customFieldSets` entry without `contextField` or `contextValue` |
|
|
238
|
+
| E129 | `@suppa/sdk` pinned below 1.38.0 in `package.json` |
|
|
239
|
+
| E130 | one class named by `@CustomFields` on two owners |
|
|
240
|
+
| W621 | a column with no `customFieldSets` — no record shows it |
|
|
241
|
+
| W622 | `contextField` names no field on the owner |
|
|
242
|
+
| W623 | `options: { customFields: true }` written beside the decorator that implies it |
|
|
243
|
+
| W624 | advisory: the nested class is declared in another file, or the SDK range cannot be read, so a check was skipped |
|
|
244
|
+
| W625 | a number as `contextValue` on an `@Enum` context field — an id, where the stored value belongs |
|
|
245
|
+
|
|
218
246
|
## Which route to take
|
|
219
247
|
|
|
220
248
|
| Situation | Route |
|
|
@@ -14,14 +14,15 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
export const HOUSE_RULES_DIGEST = `WRITING ENTITY CODE (*.entity.ts in an application repo — NOT the API tools above)
|
|
17
|
-
These
|
|
17
|
+
These seven rules are house rules of this platform. They OVERRIDE the platform's own migrations doc (which contradicts two of them) and the style of the entities already in the repo you are editing — a file that breaks them is the habit these rules exist to stop, not a convention to match. Full skill: skills/suppa-entity-code/SKILL.md in the installed suppa-mcp-2 package; the seven bind whether or not you open it.
|
|
18
18
|
1. TYPE EVERY RELATION PROPERTY to match its decorator: @ManyToOne -> \`owner: Target;\` (\`owner?: Target\` when the relation is nullable); @ManyToMany/@OneToMany/@ManyToManyBackRef -> \`peers: Target[];\`. Never \`any\`.
|
|
19
19
|
2. ENUM MEMBER KEYS ARE PascalCase — \`NotFilled = 'Not filled'\` — the stored value is the string on the right and need not match the key.
|
|
20
20
|
3. NEVER WRITE A FIELD OPTION AT ITS DEFAULT: canGroup, canSort, showInTable, editFromTable and canFilter are already true; readOnly and searchable are already false. Write one ONLY where the field departs from that (usually just \`searchable: true\`); all seven spelled out is wrong even though it works.
|
|
21
21
|
4. @Enum/@MultiEnum TAKE THE GLOBAL NAME ONLY WHEN THE ENUM IS GLOBAL — shared by another entity, or referenced from a seed record. Otherwise omit the first argument: \`@Enum(StatusEnum, StatusTitles, { … })\` derives <ClassName>.<propertyName>. A field's own \`key: 'Entity.field'\` is the rename key, NOT a reference, and does not make the enum global.
|
|
22
22
|
5. A RELATION TARGET THAT ALREADY EXISTS on the tenant (created earlier, or owned by another application) gets a STUB — three things at once: \`@Entity({ name: 'Accounts', key: 'Accounts' }) export class Accounts extends SystemBaseEntity {}\` with an EMPTY body, ALONE in a file named \`accounts.stub.entity.ts\`, and REGISTERED in forFeature() with the entities you create. Never a bare \`export class Accounts {}\` — it satisfies the thunk but registers nothing, so the platform cannot resolve the relation (E116). Never fields on a stub — it only lets a relation point at the table (E117); to ADD columns there, see rule 6. Platform system entities need no stub: import UsersEntity/FilesEntity/IconsEntity from @suppa/sdk.
|
|
23
23
|
6. TO ADD COLUMNS TO AN ENTITY YOU DO NOT OWN, DECLARE AN EXTENSION — not a stub; there is no separate API. Declare the entity by its EXISTING name with only your own columns, in \`<owner-entity>.extension.entity.ts\` (class \`<OwnerEntity>Extension\`), registered like any other entity: \`@Entity({ name: 'Users' }) export class UsersExtension extends SystemBaseEntity { @Column({ type: FieldTypeEnum.Numeric, nullable: true }) accountId?: number; }\`. The platform picks the mode by OWNERSHIP at start. In extension mode: entity options are IGNORED (title/icon/type/options/representativeFieldName/importKeyFields — W618); no @OneToMany or @ManyToManyBackRef (E118); no \`primary: true\` (E119); no \`nullable: false\` without a default (E120); @Index/@Check only over your own columns, listed as a literal array (E121/E122). Write @Entity()/@Column() options as literal objects — one passed by reference or through a spread cannot be read, so none of this can be checked on it (E123). A relation to an entity you do not own takes NO string target - name it on a raw column (W620): \`@Column({ type: RelationTypeEnum.ManyToOne, relationEntityName: 'Invoices', relationFieldName: 'id' }) invoice?: { id: number };\`.
|
|
24
|
-
|
|
24
|
+
7. CUSTOM FIELDS IN CODE need @suppa/sdk 1.38.0 (E129) and a nested class of columns that is NOT an entity — no @Entity(), never in forFeature() (E124: registering it breaks every custom-field read and write) — reached by a property that MUST be named customFields (E125): \`@CustomFields(() => TasksCustomFields) customFields?: TasksCustomFields;\`. Every column needs options.customFieldSets [{contextField (on the owner), contextValue (a value, not an id)}] or no record shows it (W621). SKILL.md rule 22; template custom-fields.template.ts.
|
|
25
|
+
Before reporting the file done, run the gate: suppa_validate_entity_code(path=<app-root>). It fails on every one of the seven and names file:line; passed=false means fix and re-run, not "note and move on". (CLI: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root>.)`;
|
|
25
26
|
|
|
26
27
|
/** What the gate blocks on, for a message that must not understate it. */
|
|
27
28
|
export const BLOCKING_SUMMARY =
|
|
@@ -30,5 +31,8 @@ export const BLOCKING_SUMMARY =
|
|
|
30
31
|
"(E116/E117/W616/W617), extension mode — ignored entity options, no reverse relations, no primary, " +
|
|
31
32
|
"no NOT NULL without a default, indexes over your own columns only (W618/E118/E119/E120/E121/E122/E123/W620), " +
|
|
32
33
|
"`owner` first in a tabular part's importKeyFields (W607), no second entity class of the same name — " +
|
|
33
|
-
"the other one is then analyzed by nothing (W619)
|
|
34
|
-
"`inverse` on @ManyToOne/@ManyToMany (W609)"
|
|
34
|
+
"the other one is then analyzed by nothing (W619), no " +
|
|
35
|
+
"`inverse` on @ManyToOne/@ManyToMany (W609) — and, on a @CustomFields class, never registering or " +
|
|
36
|
+
"decorating it, the `customFields` property name, a set on every column, no primary, no reverse " +
|
|
37
|
+
"relation, no NOT NULL without a default, the 1.38.0 SDK floor, one class per owner, a value not an id " +
|
|
38
|
+
"for an enum context (E124/E125/E126/E127/E128/E129/E130/W621/W622/W623/W625)";
|
|
@@ -71,6 +71,10 @@ export const RULE_WARNINGS = [
|
|
|
71
71
|
"W617", // field-less entity in a file not named <name>.stub.entity.ts
|
|
72
72
|
"W618", // extension declaring entity options extension mode ignores
|
|
73
73
|
"W620", // relation target named by string outside an extension
|
|
74
|
+
"W621", // custom-field column with no customFieldSets: no record shows it
|
|
75
|
+
"W622", // customFieldSets contextField names no field on the owner
|
|
76
|
+
"W623", // options: { customFields: true } written beside @CustomFields
|
|
77
|
+
"W625", // customFieldSets contextValue is a NUMBER on an @Enum context field (an id, not the value)
|
|
74
78
|
];
|
|
75
79
|
/**
|
|
76
80
|
* W613 argues from ABSENCE — "nothing references this name". That only holds
|
|
@@ -702,6 +706,14 @@ function analyzeEntities(ts, sf, model, opts = {}) {
|
|
|
702
706
|
optionsNode: d.args[0] ?? null,
|
|
703
707
|
nameNode: objectMap(ts, d.args[0]).get("name") ?? null,
|
|
704
708
|
});
|
|
709
|
+
} else if (d.name === "CustomFields") {
|
|
710
|
+
// Not a field: it names the class that becomes the columns of the
|
|
711
|
+
// platform-generated {Owner}CustomFields table. Kept off
|
|
712
|
+
// info.properties so no field rule treats it as a column.
|
|
713
|
+
info.customFieldsProp = {
|
|
714
|
+
propName, node: member, decorator: d,
|
|
715
|
+
targetClass: thunkTarget(ts, sf, d.args[0]),
|
|
716
|
+
};
|
|
705
717
|
} else if (d.name in RELATION_KIND_BY_DECORATOR) {
|
|
706
718
|
// (target, options?) or (target, inverse, options?) — the options
|
|
707
719
|
// object is whichever trailing argument is an object literal; the
|
|
@@ -757,6 +769,299 @@ function analyzeEntities(ts, sf, model, opts = {}) {
|
|
|
757
769
|
});
|
|
758
770
|
}
|
|
759
771
|
|
|
772
|
+
// ── rules: custom fields declared in code (@suppa/sdk 1.38.0) ──
|
|
773
|
+
/**
|
|
774
|
+
* `@CustomFields(() => Cls)` on an owner entity, with Cls a PLAIN class of
|
|
775
|
+
* columns. Transcribed from migrations.html#custom-fields (captured in
|
|
776
|
+
* docs/superpowers/specs/captures/migrations-custom-fields.txt).
|
|
777
|
+
*
|
|
778
|
+
* This is the one place where this checker's own habits point at the wall.
|
|
779
|
+
* Rule 19 says a class naming a table gets @Entity() and registration; rule 21
|
|
780
|
+
* says a class never passed to forFeature() is invisible. Neither reaches the
|
|
781
|
+
* nested class: it names no table of its own, and registering it makes the
|
|
782
|
+
* platform build a plain table where the generated extension table belongs —
|
|
783
|
+
* "writing an entity row of your own would replace it with a plain table and
|
|
784
|
+
* break every custom-field read and write". Nothing else would catch that, and
|
|
785
|
+
* the damage is silent, so it is an error rather than a warning.
|
|
786
|
+
*/
|
|
787
|
+
function checkCustomFieldsClasses(ts, model, findings, rootDir = null) {
|
|
788
|
+
const registered = new Set(model.modules.flatMap((m) => m.entities.names));
|
|
789
|
+
const owners = [...model.entities.values()].filter((i) => !i.outOfScope && i.customFieldsProp);
|
|
790
|
+
if (!owners.length) return;
|
|
791
|
+
|
|
792
|
+
// "Requires @suppa/sdk 1.38.0 — @CustomFields and the declarative sets land in
|
|
793
|
+
// 1.38.0. Older SDKs have no way to describe custom fields from an
|
|
794
|
+
// application." Below the floor the decorator does not exist, so the file
|
|
795
|
+
// fails at import — a compile error this gate can name first. Once per run.
|
|
796
|
+
const floor = sdkFloorProblem(rootDir);
|
|
797
|
+
if (floor) {
|
|
798
|
+
const first = owners[0];
|
|
799
|
+
findings.push(finding(ts, first.sf, first.customFieldsProp.node, floor.code, floor.message));
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// "one class serves one owner" — "the table is named after the OWNER, never
|
|
803
|
+
// after the class", so two owners sharing a class would both try to apply it
|
|
804
|
+
// to their own extension table, and "both rules fail the build loudly".
|
|
805
|
+
const byTarget = new Map();
|
|
806
|
+
for (const info of owners) {
|
|
807
|
+
const t = info.customFieldsProp.targetClass;
|
|
808
|
+
if (!t) continue;
|
|
809
|
+
if (!byTarget.has(t)) byTarget.set(t, []);
|
|
810
|
+
byTarget.get(t).push(info);
|
|
811
|
+
}
|
|
812
|
+
for (const [target, list] of byTarget) {
|
|
813
|
+
if (list.length < 2) continue;
|
|
814
|
+
for (const info of list.slice(1)) {
|
|
815
|
+
findings.push(finding(ts, info.sf, info.customFieldsProp.node, "E130",
|
|
816
|
+
`'${target}' is the @CustomFields class of BOTH '${list[0].className}' and '${info.className}', but ` +
|
|
817
|
+
`"one class serves one owner" — the table is named after the owner, so one class cannot be the ` +
|
|
818
|
+
`columns of two tables. Give '${info.className}' its own class (${info.className}CustomFields).`));
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
for (const info of owners) {
|
|
823
|
+
const cf = info.customFieldsProp;
|
|
824
|
+
if (!cf) continue;
|
|
825
|
+
|
|
826
|
+
// "The property must be named `customFields`, and one class serves one
|
|
827
|
+
// owner. That is the name the platform gives the back reference; both rules
|
|
828
|
+
// fail the build loudly."
|
|
829
|
+
if (cf.propName !== "customFields") {
|
|
830
|
+
findings.push(finding(ts, info.sf, cf.node, "E125",
|
|
831
|
+
`@CustomFields is on a property called '${cf.propName}', but the platform names the back ` +
|
|
832
|
+
`reference 'customFields' and accepts no other — the build fails loudly on this. Rename the ` +
|
|
833
|
+
`property to customFields; the extension table is named after the OWNER either way ` +
|
|
834
|
+
`('${info.entityName}CustomFields'), never after the class.`));
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// "The `@CustomFields` property implies `options: { customFields: true }`."
|
|
838
|
+
const optNode = info.options.get("options");
|
|
839
|
+
if (optNode) {
|
|
840
|
+
const entityOpts = objectMap(ts, optNode);
|
|
841
|
+
if (entityOpts.get("customFields")) {
|
|
842
|
+
findings.push(finding(ts, info.sf, entityOpts.get("customFields"), "W623",
|
|
843
|
+
`options: { customFields: … } is written beside @CustomFields, which already implies it. ` +
|
|
844
|
+
`Delete the option and keep the decorator — two statements of one fact drift apart.`));
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
const targetName = cf.targetClass;
|
|
849
|
+
if (!targetName) {
|
|
850
|
+
findings.push(finding(ts, info.sf, cf.node, "W624",
|
|
851
|
+
`@CustomFields target cannot be read as a thunk returning a class, so none of the ` +
|
|
852
|
+
`custom-field rules could run on it. Write it as @CustomFields(() => ${info.className}CustomFields).`));
|
|
853
|
+
continue;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// Registering it is the silent breaker.
|
|
857
|
+
if (registered.has(targetName)) {
|
|
858
|
+
findings.push(finding(ts, info.sf, cf.node, "E124",
|
|
859
|
+
`'${targetName}' is passed to EntityModule.forFeature(), but the class behind @CustomFields ` +
|
|
860
|
+
`is NOT an entity — "register only the owner". Registering it makes the platform build a ` +
|
|
861
|
+
`plain table where the generated '${info.entityName}CustomFields' belongs, which breaks every ` +
|
|
862
|
+
`custom-field read and write. Remove it from forFeature(); only '${info.className}' belongs there.`));
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
const binding = findLocalBinding(ts, info.sf, targetName);
|
|
866
|
+
if (!binding || binding.kind !== "class") {
|
|
867
|
+
// Declared elsewhere: the registration check above still applied, but the
|
|
868
|
+
// column rules need the class body. Say a check was skipped rather than
|
|
869
|
+
// implying the class is clean.
|
|
870
|
+
findings.push(finding(ts, info.sf, cf.node, "W624",
|
|
871
|
+
`the class '${targetName}' behind @CustomFields is not declared in this file, so its columns ` +
|
|
872
|
+
`were not checked (no-set columns, nullable without default, primary, reverse relations). ` +
|
|
873
|
+
`The doc keeps it beside the owner it serves.`));
|
|
874
|
+
continue;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
const cls = binding.node;
|
|
878
|
+
const clsDecs = decoratorsOf(ts, cls).map((d) => decoratorCall(ts, d, info.sf)).filter(Boolean);
|
|
879
|
+
if (clsDecs.some((d) => d.name === "Entity")) {
|
|
880
|
+
findings.push(finding(ts, info.sf, cls.name ?? cls, "E124",
|
|
881
|
+
`'${targetName}' carries @Entity(), but the class behind @CustomFields "is not an entity, has ` +
|
|
882
|
+
`no @Entity(), does not extend SystemBaseEntity and is never registered". With @Entity() the ` +
|
|
883
|
+
`platform builds a plain table instead of the generated extension table, breaking every ` +
|
|
884
|
+
`custom-field read and write. Delete the decorator.`));
|
|
885
|
+
}
|
|
886
|
+
const heritage = cls.heritageClauses ?? [];
|
|
887
|
+
const extendsSomething = heritage.some((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
|
|
888
|
+
if (extendsSomething) {
|
|
889
|
+
findings.push(finding(ts, info.sf, cls.name ?? cls, "E124",
|
|
890
|
+
`'${targetName}' extends a base class, but the class behind @CustomFields "does not extend ` +
|
|
891
|
+
`SystemBaseEntity" — the generated table already carries the owner relation and the standard ` +
|
|
892
|
+
`columns. Declare it as a plain class: export class ${targetName} { … }.`));
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
checkCustomFieldColumns(ts, info, cls, findings);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* Is the app's @suppa/sdk below the 1.38.0 floor @CustomFields needs?
|
|
901
|
+
*
|
|
902
|
+
* Reads the dependency RANGE from the app's package.json and takes its lowest
|
|
903
|
+
* version — the one a fresh install may resolve to. A range this cannot read
|
|
904
|
+
* (workspace:, latest, a git URL) is reported as unverified rather than as
|
|
905
|
+
* fine, and no package.json at all is silent: the tsconfig check already tells
|
|
906
|
+
* the caller what a rootDir without a project looks like.
|
|
907
|
+
*/
|
|
908
|
+
export function sdkFloorProblem(rootDir, floorText = "1.38.0") {
|
|
909
|
+
if (!rootDir) return null;
|
|
910
|
+
let pkg;
|
|
911
|
+
try {
|
|
912
|
+
pkg = JSON.parse(readFileSync(join(resolve(rootDir), "package.json"), "utf-8"));
|
|
913
|
+
} catch {
|
|
914
|
+
return null;
|
|
915
|
+
}
|
|
916
|
+
const range =
|
|
917
|
+
pkg?.dependencies?.["@suppa/sdk"] ??
|
|
918
|
+
pkg?.peerDependencies?.["@suppa/sdk"] ??
|
|
919
|
+
pkg?.devDependencies?.["@suppa/sdk"];
|
|
920
|
+
if (range === undefined) {
|
|
921
|
+
return {
|
|
922
|
+
code: "W624",
|
|
923
|
+
message:
|
|
924
|
+
"@CustomFields needs @suppa/sdk 1.38.0, but package.json lists no @suppa/sdk dependency, so the " +
|
|
925
|
+
"floor could not be checked. Older SDKs have no way to describe custom fields from an application.",
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
const m = String(range).match(/(\d+)\.(\d+)\.(\d+)/);
|
|
929
|
+
if (!m) {
|
|
930
|
+
return {
|
|
931
|
+
code: "W624",
|
|
932
|
+
message:
|
|
933
|
+
`@CustomFields needs @suppa/sdk ${floorText}, and the declared range '${range}' names no version this ` +
|
|
934
|
+
"checker can compare — confirm the installed SDK is 1.38.0 or newer before relying on the decorator.",
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
const have = m.slice(1, 4).map(Number);
|
|
938
|
+
const want = floorText.split(".").map(Number);
|
|
939
|
+
const below = have[0] !== want[0] ? have[0] < want[0] : have[1] !== want[1] ? have[1] < want[1] : have[2] < want[2];
|
|
940
|
+
if (!below) return null;
|
|
941
|
+
return {
|
|
942
|
+
code: "E129",
|
|
943
|
+
message:
|
|
944
|
+
`@CustomFields is used, but package.json pins @suppa/sdk to '${range}' — below the ${floorText} floor. ` +
|
|
945
|
+
"\"Older SDKs have no way to describe custom fields from an application\": the decorator does not exist " +
|
|
946
|
+
"there, so this file fails at import. Upgrade the SDK (pnpm add @suppa/sdk@latest) or declare the " +
|
|
947
|
+
"fields on the tenant with suppa_add_custom_field / suppa_apply_custom_fields instead.",
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/** Every property of the nested class is one custom field. */
|
|
952
|
+
function checkCustomFieldColumns(ts, info, cls, findings) {
|
|
953
|
+
const ownerFields = new Set();
|
|
954
|
+
for (const [propName, prop] of info.properties) {
|
|
955
|
+
ownerFields.add(propName);
|
|
956
|
+
const colName = stringValue(ts, prop.nameNode);
|
|
957
|
+
if (colName) ownerFields.add(colName);
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
for (const member of cls.members ?? []) {
|
|
961
|
+
if (!member.name) continue;
|
|
962
|
+
const propName = ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)
|
|
963
|
+
? member.name.text : member.name.getText(info.sf);
|
|
964
|
+
const decs = decoratorsOf(ts, member).map((d) => decoratorCall(ts, d, info.sf)).filter(Boolean);
|
|
965
|
+
if (!decs.length) continue;
|
|
966
|
+
|
|
967
|
+
// "`primary`, `@OneToMany()` and `@ManyToManyBackRef()` are rejected" —
|
|
968
|
+
// the same extension-mode restrictions as any table this app does not own.
|
|
969
|
+
let reverse = false;
|
|
970
|
+
for (const d of decs) {
|
|
971
|
+
if (d.name === "OneToMany" || d.name === "ManyToManyBackRef") {
|
|
972
|
+
reverse = true;
|
|
973
|
+
findings.push(finding(ts, info.sf, member, "E126",
|
|
974
|
+
`'${propName}' uses @${d.name}(), which the platform REJECTS on a custom-field class — a ` +
|
|
975
|
+
`reverse relation creates a field on the other entity, and the generated extension table ` +
|
|
976
|
+
`is not this application's to reshape. Declare the relation on the other side.`));
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// A reverse relation is not a column at all: reporting it again as a
|
|
981
|
+
// column with no set would say two things about one mistake.
|
|
982
|
+
if (reverse) continue;
|
|
983
|
+
const colDec = decs.find((d) => d.name === "Column") ??
|
|
984
|
+
decs.find((d) => d.name in RELATION_KIND_BY_DECORATOR);
|
|
985
|
+
if (!colDec) continue;
|
|
986
|
+
const opts = colDec.name === "Column"
|
|
987
|
+
? objectMap(ts, colDec.args[0])
|
|
988
|
+
: objectMap(ts, [...colDec.args].reverse().find((a) => ts.isObjectLiteralExpression(a)));
|
|
989
|
+
|
|
990
|
+
if (opts.get("primary")) {
|
|
991
|
+
findings.push(finding(ts, info.sf, opts.get("primary"), "E126",
|
|
992
|
+
`'${propName}' declares primary, which the platform REJECTS on a custom-field class: the ` +
|
|
993
|
+
`generated table's key is the owner relation, not yours to redefine.`));
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
const nullable = opts.get("nullable");
|
|
997
|
+
const nullableIsFalse = nullable && nullable.kind === ts.SyntaxKind.FalseKeyword;
|
|
998
|
+
if (nullableIsFalse && !opts.get("default")) {
|
|
999
|
+
findings.push(finding(ts, info.sf, nullable, "E127",
|
|
1000
|
+
`'${propName}' is nullable: false with no default. On a custom-field class "nullable: false ` +
|
|
1001
|
+
`needs a default" — the values row may already exist for records that have no value for this ` +
|
|
1002
|
+
`column yet. Give it a default (a SQL expression STRING), or leave it nullable.`));
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// "A field with no set never shows up."
|
|
1006
|
+
const inner = objectMap(ts, opts.get("options"));
|
|
1007
|
+
const setsNode = inner.get("customFieldSets");
|
|
1008
|
+
if (!setsNode) {
|
|
1009
|
+
findings.push(finding(ts, info.sf, member, "W621",
|
|
1010
|
+
`'${propName}' declares no options.customFieldSets, so no record will ever show it: a custom ` +
|
|
1011
|
+
`field "exists in the metadata (and in GET /core/schema/${info.entityName} with an empty ` +
|
|
1012
|
+
`setIds) but no record shows it". Declare where it applies — ` +
|
|
1013
|
+
`options: { customFieldSets: [{ contextField: '<owner field>', contextValue: '<value>' }] } — ` +
|
|
1014
|
+
`or, if it belongs on every record, it is an ordinary column of '${info.className}'.`));
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
if (!ts.isArrayLiteralExpression(setsNode)) {
|
|
1018
|
+
findings.push(finding(ts, info.sf, setsNode, "W624",
|
|
1019
|
+
`'${propName}' hands customFieldSets over by reference, so where it applies cannot be read ` +
|
|
1020
|
+
`here and its contexts went unchecked. Write the array literally.`));
|
|
1021
|
+
continue;
|
|
1022
|
+
}
|
|
1023
|
+
for (const entry of setsNode.elements) {
|
|
1024
|
+
if (!ts.isObjectLiteralExpression(entry)) continue;
|
|
1025
|
+
const set = objectMap(ts, entry);
|
|
1026
|
+
const cfNode = set.get("contextField");
|
|
1027
|
+
const cvNode = set.get("contextValue");
|
|
1028
|
+
if (!cfNode || !cvNode) {
|
|
1029
|
+
findings.push(finding(ts, info.sf, entry, "E128",
|
|
1030
|
+
`'${propName}' has a customFieldSets entry without ` +
|
|
1031
|
+
`${!cfNode ? "contextField" : "contextValue"} — a set binds the owner to ONE context value, ` +
|
|
1032
|
+
`and both halves are required.`));
|
|
1033
|
+
continue;
|
|
1034
|
+
}
|
|
1035
|
+
const cfName = stringValue(ts, cfNode);
|
|
1036
|
+
// Resolution table: for an @Enum/@MultiEnum context field "what
|
|
1037
|
+
// contextValue may say" is "the stored enum value ('Refrigeration
|
|
1038
|
+
// equipment')", resolved to the id of that Enums row. A NUMBER there is
|
|
1039
|
+
// almost always that id written by hand — and ids differ per workspace,
|
|
1040
|
+
// which is the very thing the by-value declaration exists to avoid.
|
|
1041
|
+
const ownerProp = cfName ? info.properties.get(cfName) : null;
|
|
1042
|
+
const cvExpr = unwrapExpr(ts, cvNode);
|
|
1043
|
+
const cvIsNumber =
|
|
1044
|
+
ts.isNumericLiteral(cvExpr) ||
|
|
1045
|
+
(ts.isPrefixUnaryExpression(cvExpr) && ts.isNumericLiteral(cvExpr.operand));
|
|
1046
|
+
if (ownerProp && (ownerProp.kind === "enum" || ownerProp.kind === "multi-enum") && cvIsNumber) {
|
|
1047
|
+
findings.push(finding(ts, info.sf, cvNode, "W625",
|
|
1048
|
+
`'${propName}' keys its context on the enum '${cfName}' with a NUMBER (${cvExpr.getText(info.sf)}) — ` +
|
|
1049
|
+
`for an @Enum context field contextValue is the STORED VALUE ('design'), which the platform ` +
|
|
1050
|
+
`resolves to the Enums row id per workspace. An id written here is only right on the one ` +
|
|
1051
|
+
`tenant it was copied from.`));
|
|
1052
|
+
}
|
|
1053
|
+
// "contextField — Name of the field ON THE OWNER whose value decides the
|
|
1054
|
+
// context. It must exist on the owner."
|
|
1055
|
+
if (cfName && ownerFields.size > 0 && !ownerFields.has(cfName)) {
|
|
1056
|
+
findings.push(finding(ts, info.sf, cfNode, "W622",
|
|
1057
|
+
`'${propName}' keys its context on '${cfName}', which '${info.className}' does not declare — ` +
|
|
1058
|
+
`contextField must name a field ON THE OWNER. The migration resolves the context inside the ` +
|
|
1059
|
+
`write transaction, so an unresolvable one fails the whole start, not just this field.`));
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
|
|
760
1065
|
// ── rules: tabular parts ──
|
|
761
1066
|
/**
|
|
762
1067
|
* Doc: "Three things make an entity a tabular part. All three are required,
|
|
@@ -2778,6 +3083,7 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
|
|
|
2778
3083
|
if (info.outOfScope) continue;
|
|
2779
3084
|
checkEntity(ts, info, sdk, model, findings);
|
|
2780
3085
|
}
|
|
3086
|
+
checkCustomFieldsClasses(ts, model, findings, rootDir);
|
|
2781
3087
|
for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
|
|
2782
3088
|
checkRegistration(ts, model, findings, rootDir, parsedByCanonical);
|
|
2783
3089
|
checkTsconfig(ts, rootDir, model, findings);
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TEMPLATE — custom fields declared in code (@suppa/sdk 1.38.0 or newer).
|
|
3
|
+
*
|
|
4
|
+
* Copy into the OWNER's entity file, or beside it. Replace `Tasks`/`category`
|
|
5
|
+
* and the columns; keep the shape. Every line that departs from the shape is a
|
|
6
|
+
* rule the gate blocks on — the code is in the comment.
|
|
7
|
+
*
|
|
8
|
+
* Doc: migrations.html#custom-fields, transcribed in references/custom-fields.md.
|
|
9
|
+
*/
|
|
10
|
+
import {
|
|
11
|
+
Column,
|
|
12
|
+
CustomFields,
|
|
13
|
+
Entity,
|
|
14
|
+
FieldTypeEnum,
|
|
15
|
+
SystemBaseEntity,
|
|
16
|
+
} from '@suppa/sdk';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The nested class: a PLAIN class of columns.
|
|
20
|
+
*
|
|
21
|
+
* - no @Entity(), does not extend SystemBaseEntity, NEVER passed to
|
|
22
|
+
* EntityModule.forFeature() (E124 — registering it makes the platform build
|
|
23
|
+
* a plain table where the generated extension table belongs, breaking every
|
|
24
|
+
* custom-field read and write)
|
|
25
|
+
* - named after the owner by convention only: the TABLE is always
|
|
26
|
+
* `{Owner}CustomFields`, whatever this class is called
|
|
27
|
+
* - one class serves one owner (E130)
|
|
28
|
+
*
|
|
29
|
+
* Inside it the extension-mode restrictions apply: no `primary`, no
|
|
30
|
+
* @OneToMany()/@ManyToManyBackRef() (E126); `nullable: false` needs a `default`
|
|
31
|
+
* (E127). Every other house rule still binds — relation typing, no option at
|
|
32
|
+
* its default, local enums unnamed, stubs for existing targets.
|
|
33
|
+
*/
|
|
34
|
+
export class TasksCustomFields {
|
|
35
|
+
/**
|
|
36
|
+
* One property = one custom field. EVERY column needs options.customFieldSets,
|
|
37
|
+
* or it exists in the metadata and shows on no record (W621). A set binds the
|
|
38
|
+
* owner to ONE context value; several entries = several contexts.
|
|
39
|
+
*
|
|
40
|
+
* contextField — a field ON THE OWNER (W622)
|
|
41
|
+
* contextValue — a business key, never an id (W625): the value itself for a
|
|
42
|
+
* text/number/boolean field, the STORED enum value for an
|
|
43
|
+
* @Enum, an import key or representative value for a relation
|
|
44
|
+
* required — default false; readOnly / defaultValue — default null
|
|
45
|
+
* (defer to the field)
|
|
46
|
+
*/
|
|
47
|
+
@Column({
|
|
48
|
+
type: FieldTypeEnum.Numeric,
|
|
49
|
+
nullable: true,
|
|
50
|
+
title: { en: 'Budget', uk: 'Бюджет' },
|
|
51
|
+
options: {
|
|
52
|
+
customFieldSets: [
|
|
53
|
+
{ contextField: 'category', contextValue: 'design', required: true },
|
|
54
|
+
{ contextField: 'category', contextValue: 'support' },
|
|
55
|
+
],
|
|
56
|
+
},
|
|
57
|
+
})
|
|
58
|
+
cfBudget?: number;
|
|
59
|
+
|
|
60
|
+
@Column({
|
|
61
|
+
type: FieldTypeEnum.Text,
|
|
62
|
+
nullable: true,
|
|
63
|
+
title: { en: 'Client reference' },
|
|
64
|
+
options: {
|
|
65
|
+
customFieldSets: [{ contextField: 'category', contextValue: 'support' }],
|
|
66
|
+
},
|
|
67
|
+
})
|
|
68
|
+
cfClientRef?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
@Entity({ name: 'Tasks', key: 'Tasks', importKeyFields: ['shortUID'] })
|
|
72
|
+
export class Tasks extends SystemBaseEntity {
|
|
73
|
+
@Column({ name: 'shortUID', type: FieldTypeEnum.Text, nullable: false })
|
|
74
|
+
shortUID: string;
|
|
75
|
+
|
|
76
|
+
@Column({ name: 'title', type: FieldTypeEnum.Text, nullable: false })
|
|
77
|
+
title: string;
|
|
78
|
+
|
|
79
|
+
/** The context field the sets above key on. */
|
|
80
|
+
@Column({ name: 'category', type: FieldTypeEnum.Text })
|
|
81
|
+
category?: string;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The property MUST be named `customFields` (E125). The decorator implies
|
|
85
|
+
* `options: { customFields: true }` — do not write the option beside it (W623).
|
|
86
|
+
* On an entity you do NOT own, the columns still come from this file, but the
|
|
87
|
+
* option has to be switched on once: suppa_update_entity_options(entity_name,
|
|
88
|
+
* '{"customFields": true}').
|
|
89
|
+
*/
|
|
90
|
+
@CustomFields(() => TasksCustomFields)
|
|
91
|
+
customFields?: TasksCustomFields;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Register ONLY the owner:
|
|
95
|
+
// EntityModule.forFeature([Tasks], { seeds: [] })
|