suppa-mcp-2 1.2.3 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -604,6 +604,10 @@ async function _planFields(props, entName, v2EntName, targetResolver, entIndex,
604
604
  title: ftitle,
605
605
  type: cls.v2Type,
606
606
  required,
607
+ // The v1 default must travel with the planned field: _requiredOpts reads
608
+ // `default_value` off the PLAN, so a plan that omits it downgrades every
609
+ // required field to nullable and the notNull path is never taken.
610
+ default_value: p.default_value ?? null,
607
611
  relation_entity: v2Target ?? (target ? normalizeEntityName(target) : null),
608
612
  target_in_set: inSet,
609
613
  };
@@ -630,6 +634,7 @@ async function _planFields(props, entName, v2EntName, targetResolver, entIndex,
630
634
  title: ftitle,
631
635
  type: cls.v2Type,
632
636
  required,
637
+ default_value: p.default_value ?? null,
633
638
  enum_name: _enumNameFor(v2EntName, v2Fname),
634
639
  values,
635
640
  });
@@ -642,6 +647,7 @@ async function _planFields(props, entName, v2EntName, targetResolver, entIndex,
642
647
  title: ftitle,
643
648
  type: cls.v2Type,
644
649
  required,
650
+ default_value: p.default_value ?? null,
645
651
  sub_type: cls.v2SubType,
646
652
  max_length: cls.v2Type === "text" ? maxLength : null,
647
653
  decimal_places: cls.v2Type === "numeric" ? decimalPlaces : null,
@@ -988,6 +994,62 @@ async function _runWrite(action, fn) {
988
994
  }
989
995
  return { action, status: "created", result: parsed };
990
996
  }
997
+ // Types the 2.0 builder marks notNull WITHOUT a defaultValue: the doc's
998
+ // "Relation types" group, whose values live in a join/side table
999
+ // (docs/superpowers/specs/captures/api-entity-builder-builder.txt:43 —
1000
+ // "defaultValue ... Not applicable to relations, enums, or unique fields";
1001
+ // :63 lists the group). Mirrors NO_DEFAULT_VALUE_FIELD_TYPES in tools/entity.ts,
1002
+ // kept local so the migrator decides before the write instead of learning from a
1003
+ // failed one — entity.js is module-mocked in the migrator's tests.
1004
+ const _NO_DEFAULT_VALUE_TYPES = new Set([
1005
+ "many-to-one",
1006
+ "one-to-many",
1007
+ "many-to-many",
1008
+ "many-to-many-backref",
1009
+ "enum",
1010
+ "multi-enum",
1011
+ "file",
1012
+ "multi-file",
1013
+ ]);
1014
+ const _DOWNGRADE_NOTE = "Some fields that are required in Suppa 1.0 were created NULLABLE here: the 2.0 " +
1015
+ "builder refuses NOT NULL without a defaultValue, and this migrator will not " +
1016
+ "invent one — the value empty rows should carry is a data decision, not a " +
1017
+ "migration detail. See required_downgrades. To restore the constraint: add " +
1018
+ '"default_value" to those fields in the plan (a SQL expression or literal, e.g. ' +
1019
+ "\"0\", \"'draft'\", \"now()\") and re-run in gap-fill mode after dropping the " +
1020
+ "field, or set NOT NULL in the builder UI once the column is backfilled.";
1021
+ /**
1022
+ * Resolve the required/defaultValue options for one planned field.
1023
+ *
1024
+ * A v1 field that is required but has no default cannot be created NOT NULL, and
1025
+ * that must NOT abort the migration: the field is created nullable and the
1026
+ * downgrade is recorded so the user can restore the constraint deliberately.
1027
+ */
1028
+ function _requiredOpts(entity, f, downgrades) {
1029
+ if (!(f.required ?? false)) {
1030
+ return { required: false };
1031
+ }
1032
+ if (_NO_DEFAULT_VALUE_TYPES.has(String(f.type ?? ""))) {
1033
+ return { required: true }; // defaultValue does not apply — notNull needs none
1034
+ }
1035
+ // `default_value` is put on every planned field by _planFields (from the v1
1036
+ // property); a plan built elsewhere that omits it downgrades, it never guesses.
1037
+ const raw = f.default_value;
1038
+ const defaultValue = raw === null || raw === undefined ? "" : String(raw).trim();
1039
+ if (defaultValue !== "") {
1040
+ return { required: true, defaultValue };
1041
+ }
1042
+ downgrades.push({
1043
+ entity,
1044
+ field: f.name,
1045
+ type: f.type ?? null,
1046
+ v1_required: true,
1047
+ created_as: "nullable",
1048
+ reason: "required in v1 but the plan carries no default_value; the 2.0 builder refuses " +
1049
+ "NOT NULL without one and no default is invented here",
1050
+ });
1051
+ return { required: false };
1052
+ }
991
1053
  /**
992
1054
  * Apply the plan to the active Suppa 2.0 tenant, idempotently. Two-pass for relations.
993
1055
  *
@@ -998,6 +1060,7 @@ async function _runWrite(action, fn) {
998
1060
  */
999
1061
  export async function _execute(plan, mode = "create") {
1000
1062
  const details = [];
1063
+ const requiredDowngrades = [];
1001
1064
  const existingEntities = await _liveEntityNames();
1002
1065
  // Pass 1: entities + scalar + enum fields.
1003
1066
  for (const ent of plan.entities) {
@@ -1030,7 +1093,7 @@ export async function _execute(plan, mode = "create") {
1030
1093
  continue;
1031
1094
  }
1032
1095
  const step = await _runWrite(`add_field:${f.name}`, () => entityTools.addField(name, f.name, f.type, f.title, {
1033
- required: f.required ?? false,
1096
+ ..._requiredOpts(name, f, requiredDowngrades),
1034
1097
  subType: f.sub_type ?? null,
1035
1098
  maxLength: f.max_length ?? null,
1036
1099
  decimalPlaces: f.decimal_places ?? null,
@@ -1057,7 +1120,7 @@ export async function _execute(plan, mode = "create") {
1057
1120
  }
1058
1121
  }
1059
1122
  const step = await _runWrite(`add_enum_field:${f.name}`, () => entityTools.addField(name, f.name, f.type ?? "enum", f.title, {
1060
- required: f.required ?? false,
1123
+ ..._requiredOpts(name, { ...f, type: f.type ?? "enum" }, requiredDowngrades),
1061
1124
  enumName: f.enum_name,
1062
1125
  }));
1063
1126
  step.entity = name;
@@ -1081,7 +1144,7 @@ export async function _execute(plan, mode = "create") {
1081
1144
  continue;
1082
1145
  }
1083
1146
  const step = await _runWrite(`add_field:${f.name}`, () => entityTools.addField(tpName, f.name, f.type, f.title, {
1084
- required: f.required ?? false,
1147
+ ..._requiredOpts(tpName, f, requiredDowngrades),
1085
1148
  subType: f.sub_type ?? null,
1086
1149
  maxLength: f.max_length ?? null,
1087
1150
  decimalPlaces: f.decimal_places ?? null,
@@ -1103,7 +1166,7 @@ export async function _execute(plan, mode = "create") {
1103
1166
  }
1104
1167
  }
1105
1168
  const step = await _runWrite(`add_enum_field:${f.name}`, () => entityTools.addField(tpName, f.name, f.type ?? "enum", f.title, {
1106
- required: f.required ?? false,
1169
+ ..._requiredOpts(tpName, { ...f, type: f.type ?? "enum" }, requiredDowngrades),
1107
1170
  enumName: f.enum_name,
1108
1171
  }));
1109
1172
  step.entity = tpName;
@@ -1147,7 +1210,7 @@ export async function _execute(plan, mode = "create") {
1147
1210
  continue;
1148
1211
  }
1149
1212
  const step = await _runWrite(`add_relation:${f.name}`, () => entityTools.addField(name, f.name, f.type, f.title, {
1150
- required: f.required ?? false,
1213
+ ..._requiredOpts(name, f, requiredDowngrades),
1151
1214
  relationEntity: f.relation_entity,
1152
1215
  }));
1153
1216
  step.entity = name;
@@ -1185,7 +1248,7 @@ export async function _execute(plan, mode = "create") {
1185
1248
  continue;
1186
1249
  }
1187
1250
  const step = await _runWrite(`add_relation:${f.name}`, () => entityTools.addField(tp.name, f.name, f.type, f.title, {
1188
- required: f.required ?? false,
1251
+ ..._requiredOpts(tp.name, f, requiredDowngrades),
1189
1252
  relationEntity: f.relation_entity,
1190
1253
  }));
1191
1254
  step.entity = tp.name;
@@ -1221,6 +1284,8 @@ export async function _execute(plan, mode = "create") {
1221
1284
  executed: true,
1222
1285
  mode,
1223
1286
  summary: _summarize(details),
1287
+ required_downgrades: requiredDowngrades,
1288
+ notes: requiredDowngrades.length > 0 ? [_DOWNGRADE_NOTE] : [],
1224
1289
  verify,
1225
1290
  details,
1226
1291
  };
@@ -202,7 +202,13 @@ export async function createTask(title, description = "", assignedToId = null, p
202
202
  const result = await insertEntity("Tasks", [fields]);
203
203
  return jsonResponse(result.length ? result[0] : null);
204
204
  }
205
- /** Update fields on an existing task. */
205
+ /**
206
+ * Update fields on an existing task.
207
+ *
208
+ * Every field written here is a scalar or a single {id} reference, so there is
209
+ * no merge path: a list-valued field would be REPLACED wholesale. Adding to /
210
+ * removing from a task's list field goes through updateRecord's merge/unmerge.
211
+ */
206
212
  export async function updateTask(taskId, title = null, description = null, assignedToId = null, projectId = null, workflowId = null, stageId = null, typeId = null, priorityId = null, deadline = null) {
207
213
  const fields = {};
208
214
  if (title !== null) {
@@ -243,7 +249,11 @@ export async function updateTask(taskId, title = null, description = null, assig
243
249
  const result = await updateEntity("Tasks", taskId, fields);
244
250
  return jsonResponse(result);
245
251
  }
246
- /** Soft-delete a task by ID. */
252
+ /**
253
+ * Soft-delete a task by ID: /remove sets deletedAt and keeps the row, so this is
254
+ * reversible (restore is UI-only until 1.3.0) — nothing is purged. The task does
255
+ * stop appearing in normal reads.
256
+ */
247
257
  export async function deleteTask(taskId) {
248
258
  const result = await removeEntity("Tasks", [makeFilter("id", taskId)]);
249
259
  return jsonResponse(result);
package/dist/utils.js CHANGED
@@ -128,6 +128,78 @@ function matchesExpectation(value, expect) {
128
128
  // "any" -> object or array (Python default expect=(dict, list))
129
129
  return isArray || isPlainObject;
130
130
  }
131
+ // ---------------------------------------------------------------------------
132
+ // merge / unmerge pre-flight
133
+ // ---------------------------------------------------------------------------
134
+ /**
135
+ * NO client-side cap on list length lives here, deliberately. The platform's
136
+ * documented 500 is a bound on RECORDS MATCHED, not on items sent:
137
+ * docs/superpowers/specs/captures/api-entity-builder-data.txt:396 — "The platform
138
+ * reads the current values before writing, so the operation is bounded: matching
139
+ * more than 500 records fails with Cannot perform 'merge'/'unmerge': update query
140
+ * returned maximum allowed records; limit is 500." That depends on the update's
141
+ * conditions, which this pure check never sees (and suppa_update_record targets a
142
+ * single record by id, so it cannot hit it). Refusing a long list here would have
143
+ * been this server inventing a rule the platform does not have.
144
+ */
145
+ /**
146
+ * Check the `merge` / `unmerge` lists of an update against the fields being
147
+ * sent, BEFORE any request goes out.
148
+ *
149
+ * An update REPLACES a list-valued field; `merge` (add the listed items) and
150
+ * `unmerge` (remove them) opt out of that per field name. A name the platform
151
+ * cannot line up with a list in `fields` is not an error there — it is silently
152
+ * ignored, i.e. the list gets replaced anyway and the caller is told the update
153
+ * succeeded. That is exactly the data loss this guard exists to prevent, so we
154
+ * refuse instead.
155
+ *
156
+ * Pure. Returns one message per problem; an empty array means "safe to send".
157
+ */
158
+ export function mergeListProblems(fields, merge = [], unmerge = []) {
159
+ const problems = [];
160
+ const both = merge.filter((n) => unmerge.includes(n));
161
+ for (const name of [...new Set(both)]) {
162
+ problems.push(`'${name}' appears in both merge and unmerge — one update cannot add and ` +
163
+ "remove the same field. Send two updates, or drop it from one list.");
164
+ }
165
+ const seen = new Set();
166
+ for (const [list, label] of [
167
+ [merge, "merge"],
168
+ [unmerge, "unmerge"],
169
+ ]) {
170
+ for (const name of list) {
171
+ const key = `${label}:${name}`;
172
+ if (seen.has(key) || both.includes(name)) {
173
+ continue; // already reported
174
+ }
175
+ seen.add(key);
176
+ if (!Object.prototype.hasOwnProperty.call(fields, name)) {
177
+ problems.push(`'${name}' is listed in ${label} but is not in the fields being sent — ` +
178
+ `${label} only applies to a field you also write. Add "${name}": ` +
179
+ `[{"id": N}, ...] to fields_json, or drop '${name}' from ${label}.`);
180
+ continue;
181
+ }
182
+ // data.txt:394 — "Every field named in merge / unmerge must hold an array in
183
+ // fields, otherwise the request fails with Field <name> is not an array."
184
+ const value = fields[name];
185
+ if (!Array.isArray(value)) {
186
+ problems.push(`'${name}' is listed in ${label} but its value is not an array (got ` +
187
+ `${typeName(value)}) — ${label} only applies to list-valued fields. ` +
188
+ `Send "${name}": [{"id": N}, ...], or drop '${name}' from ${label}.`);
189
+ }
190
+ // Length is NOT checked: see the note above mergeListProblems — the
191
+ // platform's 500 bounds MATCHED RECORDS, not items in the list.
192
+ }
193
+ }
194
+ return problems;
195
+ }
196
+ /** mergeListProblems as a guard: throws one combined, actionable Error. */
197
+ export function assertMergeLists(fields, merge = [], unmerge = []) {
198
+ const problems = mergeListProblems(fields, merge, unmerge);
199
+ if (problems.length > 0) {
200
+ throw new Error(`Refused before writing: ${problems.join(" ")}`);
201
+ }
202
+ }
131
203
  /** Python-ish type name for error messages. */
132
204
  function typeName(value) {
133
205
  if (value === null) {
@@ -373,8 +445,15 @@ export function buildFileUpload(meta, filePath) {
373
445
  /**
374
446
  * Approval-gate response returned by a mutating tool called without confirm=true.
375
447
  * The operation is NOT performed.
448
+ *
449
+ * For a delete the message states the real semantics: the platform's /remove is
450
+ * a SOFT delete (it sets deletedAt), so the row survives and the delete is
451
+ * reversible. Describing it as permanent would be a lie that pushes agents into
452
+ * refusing routine cleanups — the gate is here because the record vanishes from
453
+ * every normal read, not because the data is destroyed.
376
454
  */
377
455
  export function confirmRequired(action, target, proposedChanges) {
456
+ const isDelete = action.trim().toLowerCase().startsWith("delete");
378
457
  const body = {
379
458
  status: "confirmation_required",
380
459
  action,
@@ -382,8 +461,17 @@ export function confirmRequired(action, target, proposedChanges) {
382
461
  message: `⚠️ APPROVAL REQUIRED before this ${action} — it was NOT performed. ` +
383
462
  "Do not proceed on your own: show the target to the user (read the record " +
384
463
  "first if it may be important), get explicit approval, then re-call this tool " +
385
- "with confirm=true.",
464
+ "with confirm=true." +
465
+ (isDelete
466
+ ? " Semantics: this is a SOFT delete — it sets deletedAt, the row remains " +
467
+ "in the database and the delete is reversible (restore in the Suppa UI; " +
468
+ "this server has no restore tool yet). It is NOT a permanent purge, but " +
469
+ "the record does disappear from every normal read."
470
+ : ""),
386
471
  };
472
+ if (isDelete) {
473
+ body.delete_semantics = "soft — sets deletedAt, row remains, reversible";
474
+ }
387
475
  if (proposedChanges !== undefined) {
388
476
  body.proposed_changes = proposedChanges;
389
477
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.2.3",
3
+ "version": "1.2.4",
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" },
@@ -50,7 +50,9 @@ Confirm all 5 before writing anything:
50
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
51
  10. Autoload paths (`entitiesPath`/`seedsPath`) point at `dist/`, never `src/` — autoloading reads compiled output.
52
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
+ 12. `subType` refines `type` and means three unrelated things depending on the base type — `Timestamp` → `'date' | 'time' | 'timestamp'`, `Text` → `'encrypted'`, `Enum`/`MultiEnum` → the enum's global name. Never pass `subType` by hand on an `@Enum`/`@MultiEnum` field: the decorator fills it from its first argument (or derives `<ClassName>.<propertyName>`), and a hand-written one either duplicates that or silently disagrees with the value that resolves `{ value: 'active' }` on insert. Any other `(type, subType)` pair does not exist.
54
+ 13. `subType` is **immutable after creation**, with one exception: toggling `'encrypted'` on or off. The Builder API answers `Field subType cannot be changed.` to anything else — so choosing `Timestamp` where you needed `subType: 'date'` is not a conversion you can ship later, it is a NEW field plus a removal of the old one (see `references/registration.md` for what removal leaves behind). Get date-vs-timestamp right the first time. To CLEAR a subtype you must write `subType: null` explicitly — deleting the line does nothing, because an omitted key is dropped from the sync payload and the stored subtype survives.
55
+ 14. 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.
54
56
 
55
57
  ## Decorator decision table
56
58
 
@@ -58,6 +60,10 @@ Confirm all 5 before writing anything:
58
60
  |---|---|
59
61
  | 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` |
60
62
  | Scalar column (text/numeric/integer/boolean/timestamp/json/uuid/multi-language/bytea/tsvector/multi-type/icon) | `@Column({ type: FieldTypeEnum.<Member> })` |
63
+ | Date-only column (no time part) | `@Column({ type: FieldTypeEnum.Timestamp, subType: 'date' })` — there is **no** `FieldTypeEnum.Date` |
64
+ | Time-only column | `@Column({ type: FieldTypeEnum.Timestamp, subType: 'time' })` — there is **no** `FieldTypeEnum.Time` |
65
+ | Date **and** time | `@Column({ type: FieldTypeEnum.Timestamp })` — omitted `subType` already means `timestamp` |
66
+ | Text encrypted at rest | `@Column({ type: FieldTypeEnum.Text, subType: 'encrypted' })` — Text only; see rule 13 for what it costs |
61
67
  | Fixed single-select value set | `@Enum('<Entity>.<field>', <Field>Enum, <Field>Titles?, options?)` |
62
68
  | Fixed multi-select value set | `@MultiEnum(...)` — same signature as `@Enum` |
63
69
  | Foreign key on this entity | `@ManyToOne(() => Target, options?)` — **no inverse** |
@@ -69,6 +75,8 @@ Confirm all 5 before writing anything:
69
75
 
70
76
  `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.
71
77
 
78
+ **What `subType: 'encrypted'` costs.** The platform forces the column's `unique`, `searchable`, `canFilter`, `canSort` and `canGroup` to `false` and clears `maxLength`, `minLength` and `mask`, whatever you declared — the ciphertext envelope can't satisfy a plaintext constraint or be read by an index. So an encrypted column cannot be searched, filtered, sorted or grouped: if users need any of that, split the field and keep the searchable part in a separate plaintext column. It is also rejected inside a `MultiType` field and on any non-Text type.
79
+
72
80
  ## Naming conventions
73
81
 
74
82
  | Thing | Convention | Example |
@@ -165,6 +173,11 @@ The validator parses with the TypeScript compiler API, read from the app repo yo
165
173
  | A renamed entity or field appears as a new one | No `key` option was set | W602 |
166
174
  | `default` value is rejected | A JavaScript value was passed instead of a SQL expression string | E103 |
167
175
  | 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, { … })` |
176
+ | Migration rejects the column, or a date field ships as a full `timestamp` | The `(type, subType)` pair isn't one the doc allows — `Timestamp` takes `'date'`/`'time'`/`'timestamp'`, `Text` takes `'encrypted'`, nothing else | E112 |
177
+ | `Encrypted subtype is only allowed on text fields` | `subType: 'encrypted'` on a non-Text column | E112 |
178
+ | An enum field resolves to the wrong enum, or its values fail to insert | `subType` was written by hand on `@Enum`/`@MultiEnum` instead of being left to the decorator | E113 |
179
+ | `Field subType cannot be changed.` | A subtype change other than the `'encrypted'` toggle — add a NEW field instead of converting | rule 13, not statically checkable |
180
+ | A removed `subType` line is still in effect | An omitted key is dropped from the sync payload — clear it with `subType: null` | rule 13, not statically checkable |
168
181
  | `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 |
169
182
  | 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 |
170
183
  | 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 |
@@ -174,5 +187,5 @@ The validator parses with the TypeScript compiler API, read from the app repo yo
174
187
  | Duplicate tabular-part rows across different parents | `owner` is missing from `importKeyFields`, so the key is matched globally instead of per-parent | E110 |
175
188
  | 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 |
176
189
  | A tabular part's business key isn't scoped to its parent | `owner` is present in `importKeyFields` but not first | W607 |
177
- | 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 |
190
+ | Validator warns W606 | Content delivered via spread or reference — options, `default`, `subType`, `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 |
178
191
  | 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 |
@@ -1,6 +1,6 @@
1
1
  # Entity declaration — verbatim rules
2
2
 
3
- Transcribed from docs.modern-expo.com/backend/application-developing/migrations.html (captured 2026-08-03). If an option is not in these tables, it does not exist — stop and ask.
3
+ Transcribed from docs.modern-expo.com/backend/application-developing/migrations.html (captured 2026-08-04). If an option is not in these tables, it does not exist — stop and ask.
4
4
 
5
5
  ## A Minimal Entity
6
6
 
@@ -113,6 +113,7 @@ deadline: string;
113
113
  | Option | Type | Description |
114
114
  |---|---|---|
115
115
  | type | FieldTypeEnum | Column type. Take the value from FieldTypeEnum (see below). |
116
+ | subType | string \| null | Refines type — see subType. |
116
117
  | name | string | Column name. Defaults to the property name. |
117
118
  | nullable | boolean | Allow NULL. |
118
119
  | primary | boolean | Mark as primary key. |
@@ -161,6 +162,91 @@ import { FieldTypeEnum } from '@suppa/sdk';
161
162
  > **TIP**
162
163
  > FieldTypeEnum covers scalar columns only. Relations, enums and files are declared with their own decorators — @ManyToOne, @ManyToMany, @OneToMany, @Enum, @MultiEnum, @File, @MultiFile — and never with @Column({ type: ... }). The SDK also exports RelationTypeEnum with those relation kinds, but you do not pass it manually; each decorator sets it for you.
163
164
 
165
+ ## `subType` — Refining a Column Type
166
+
167
+ `subType` is a second, narrower classification on top of `type`. It is a plain string, and the thing to understand before using it is that **it means three unrelated things depending on the base type**:
168
+
169
+ | Base type | `subType` | Effect |
170
+ |---|---|---|
171
+ | `Timestamp` | `'date'`, `'time'`, `'timestamp'` | Chooses the physical column type. Omitted means `timestamp`. |
172
+ | `Text` | `'encrypted'` | The value is encrypted at rest. |
173
+ | `Enum`, `MultiEnum` | The global enum name | Identifies which enum the field draws from. Set by the decorator — never by hand. |
174
+
175
+ There is no enum for these values in the SDK. Write the string.
176
+
177
+ ### Dates and Times
178
+
179
+ `FieldTypeEnum` has no `Date` or `Time` member. A date-only or time-only column is `Timestamp` plus a `subType`:
180
+
181
+ ```ts
182
+ @Column({ name: 'deadline', type: FieldTypeEnum.Timestamp })
183
+ deadline: string; // timestamp
184
+
185
+ @Column({ name: 'birthday', type: FieldTypeEnum.Timestamp, subType: 'date' })
186
+ birthday: string; // date
187
+
188
+ @Column({ name: 'opensAt', type: FieldTypeEnum.Timestamp, subType: 'time' })
189
+ opensAt: string; // time
190
+ ```
191
+
192
+ The subtype becomes the column type verbatim, so `subType: 'date'` produces a real Postgres `date` column — not a `timestamp` that the UI renders without a time part.
193
+
194
+ ### Encrypted Text
195
+
196
+ `subType: 'encrypted'` on a text field stores the value as an AES-GCM envelope (`v1:iv:tag:ct`) instead of plaintext:
197
+
198
+ ```ts
199
+ @Column({
200
+ name: 'payload',
201
+ type: FieldTypeEnum.Text,
202
+ subType: 'encrypted',
203
+ nullable: false,
204
+ })
205
+ payload: string;
206
+ ```
207
+
208
+ The platform rejects the combinations that cannot work:
209
+
210
+ | Rule | Error |
211
+ |---|---|
212
+ | Only on a `text` field. | `Encrypted subtype is only allowed on text fields` |
213
+ | Not inside a multi-type field, and not as one of its sub-fields. | `Encrypted subtype is not allowed inside a multi-type field` |
214
+
215
+ It also forces off everything that would need to read the plaintext, whatever you declared:
216
+
217
+ - `unique` becomes `false`;
218
+ - the `searchable`, `canFilter`, `canSort` and `canGroup` options become `false`;
219
+ - `maxLength`, `minLength` and `mask` are cleared — the envelope never matches a plaintext length or mask constraint, so those `CHECK`s are dropped.
220
+
221
+ Turning encryption on for an existing field encrypts the rows already in the table; turning it off decrypts them. A row that fails to decrypt aborts the backfill rather than overwriting ciphertext with a marker.
222
+
223
+ > **TIP**
224
+ > Plan for the lost capabilities before encrypting a field. An encrypted column cannot be searched, filtered, sorted, or grouped — if users need any of that, keep the searchable part in a separate plaintext field.
225
+
226
+ ### Enums Set It For You
227
+
228
+ For an enum field, `subType` holds the enum's **global name** — the value that lets the platform resolve `{ value: 'active' }` to the right enum record on insert. `@Enum()` and `@MultiEnum()` fill it from their first argument:
229
+
230
+ ```ts
231
+ @Enum('StageWorkflows.status', StageStatusEnum, StageStatus, { nullable: false })
232
+ status: StageStatusEnum; // subType = 'StageWorkflows.status'
233
+ ```
234
+
235
+ Called without an explicit global name, the SDK derives `<ClassName>.<propertyName>`. Either way, do not pass `subType` yourself on an enum field.
236
+
237
+ ### Changing a Subtype
238
+
239
+ Through the Builder API a subtype change is rejected outright:
240
+
241
+ ```txt
242
+ Field subType cannot be changed.
243
+ ```
244
+
245
+ The one permitted transition is the encryption toggle — setting `'encrypted'`, or clearing it. Treat the date/time choice as **fixed at creation**: if a field was created as `timestamp` and should have been `date`, add a new field rather than trying to convert it, since the physical column type would have to change under existing data. See Removing and Re-Adding a Field for what happens to the old one.
246
+
247
+ > **WARNING**
248
+ > To clear a subtype, write `subType: null` explicitly. Deleting the line does nothing — an omitted key is dropped from the sync payload, so the stored subtype stays as it was.
249
+
164
250
  ## Relations
165
251
 
166
252
  Relation decorators take a thunk returning the target class — `() => Workflows` — which keeps circular imports working:
@@ -10,7 +10,7 @@ The API migration path and this code path share one authority: `classifyV1Field(
10
10
  | `numeric` | `@Column({ type: FieldTypeEnum.Numeric })` |
11
11
  | `integer` | `@Column({ type: FieldTypeEnum.Integer })` |
12
12
  | `boolean` | `@Column({ type: FieldTypeEnum.Boolean })` |
13
- | `timestamp` | `@Column({ type: FieldTypeEnum.Timestamp })` |
13
+ | `timestamp` | `@Column({ type: FieldTypeEnum.Timestamp })` — plus `subType: 'date'` when `classifyV1Field` returns `v2SubType: 'date'` (see below) |
14
14
  | `json` | `@Column({ type: FieldTypeEnum.JSON })` |
15
15
  | `uuid` | `@Column({ type: FieldTypeEnum.UUID })` |
16
16
  | `multi-language` | `@Column({ type: FieldTypeEnum.MultiLang })` |
@@ -30,9 +30,19 @@ The API migration path and this code path share one authority: `classifyV1Field(
30
30
 
31
31
  If `classifyV1Field` returns `kind = 'skip'` — a system/structural field, an unsupported relation sub_type, or an unrecognized v1 type — the field must still appear in the generated class as a `// SKIPPED: <field> — <reason>` comment, using the classifier's own note as `<reason>`. Omitting it is not an option: the generated code must account for every v1 field, migrated or not.
32
32
 
33
+ ## `v2SubType` — date-only v1 fields
34
+
35
+ `classifyV1Field` returns `v2SubType: 'date'` for a v1 date-only field. That maps to a documented option: `FieldTypeEnum.Timestamp` + `subType: 'date'`, which the platform turns into a real Postgres `date` column.
36
+
37
+ ```ts
38
+ @Column({ name: 'birthday', type: FieldTypeEnum.Timestamp, subType: 'date' })
39
+ birthday: string;
40
+ ```
41
+
42
+ Get it right the first time: `subType` is immutable after creation except for the `'encrypted'` toggle, so a field created as plain `timestamp` cannot later be converted to `date` — it has to be replaced by a new field. Never emit `subType` on an `@Enum`/`@MultiEnum` field; the decorator writes it.
43
+
33
44
  ## Documented open edges
34
45
 
35
- - `v2SubType: 'date'` (date-only v1 fields): `@Column()` has no documented `subType` option — emit `FieldTypeEnum.Timestamp` plus `// TODO: date-only in v1 — @Column has no documented date subtype; confirm rendering`.
36
46
  - Icon duality: default scalar `FieldTypeEnum.Icon`; relation form only if v1 reports `type: relation` targeting icons.
37
47
  - Lossy mappings carry the classifier's note as a trailing comment, e.g. `// v1 html_text → text (2.0 has no rich-text type)`.
38
48
 
@@ -19,7 +19,18 @@ import { pathToFileURL } from "node:url";
19
19
  export const SYSTEM_COLUMNS = ["id", "createdAt", "updatedAt", "deletedAt", "createdBy", "removedBy"];
20
20
  export const ACCESS_METADATA_KEYS = ["$readAccess", "$updateAccess", "$instanceAccess"];
21
21
  export const DOC_ENTITY_OPTIONS = ["name", "title", "comment", "representativeFieldName", "importKeyFields", "key", "icon", "type", "relationEntityName", "options"];
22
- export const DOC_COLUMN_OPTIONS = ["type", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask"];
22
+ export const DOC_COLUMN_OPTIONS = ["type", "subType", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask"];
23
+ /**
24
+ * The doc's subType matrix — "it means three unrelated things depending on the
25
+ * base type". Keyed by the CANONICAL FieldTypeEnum value, so E112 can be decided
26
+ * from whatever `checkColumn` resolved `type` to. The Enum/MultiEnum row of that
27
+ * matrix is deliberately absent: `subType` there is the enum's global name, set
28
+ * by @Enum()/@MultiEnum() and never written by hand — that is E113, not E112.
29
+ */
30
+ export const DOC_SUBTYPES_BY_TYPE = {
31
+ timestamp: ["date", "time", "timestamp"],
32
+ text: ["encrypted"],
33
+ };
23
34
  export const DOC_FIELD_TYPES = {
24
35
  Text: "text", Numeric: "numeric", Integer: "integer", Serial: "serial",
25
36
  Boolean: "boolean", Timestamp: "timestamp", JSON: "json", UUID: "uuid",
@@ -293,10 +304,20 @@ function analyzeEntities(ts, sf, model) {
293
304
  nameNode: columnOptions.get("name") ?? null,
294
305
  });
295
306
  } else if (ENUM_DECORATORS.has(d.name)) {
307
+ // (globalName?, Enum, titles?, options?) — the options object is
308
+ // the LAST argument when that is an object literal. An inline
309
+ // titles map occupies the same slot when options are omitted, so
310
+ // this node is only ever read for keys options own (E113's
311
+ // `subType`); a titles map never carries one.
312
+ const last = d.args[d.args.length - 1];
313
+ const enumOptionsNode =
314
+ d.args.length >= 2 && last && ts.isObjectLiteralExpression(last) ? last : null;
296
315
  info.properties.set(propName, {
297
316
  kind: d.name === "Enum" ? "enum" : "multi-enum",
298
317
  node: member, decorator: d,
299
318
  enumGlobalName: stringValue(ts, d.args[0]),
319
+ optionsNode: enumOptionsNode,
320
+ enumOptions: objectMap(ts, enumOptionsNode),
300
321
  });
301
322
  } else if (FILE_DECORATORS.has(d.name)) {
302
323
  info.properties.set(propName, {
@@ -479,7 +500,10 @@ function checkEntity(ts, info, sdk, model, findings) {
479
500
  findings.push(finding(ts, sf, prop.nameNode, "E102",
480
501
  `column name '${colName}' on property '${propName}' collides with the system column of the same name provided by SystemBaseEntity — "you never declare them yourself"`));
481
502
  }
482
- if (prop.kind === "column") checkColumn(ts, sf, prop, sdk, findings);
503
+ if (prop.kind === "column") checkColumn(ts, sf, propName, prop, sdk, findings);
504
+ if (prop.kind === "enum" || prop.kind === "multi-enum") {
505
+ checkEnumSubType(ts, sf, propName, prop, findings);
506
+ }
483
507
  if (RELATION_KINDS.has(prop.kind)) {
484
508
  if (prop.targetClass === null) {
485
509
  findings.push(finding(ts, sf, prop.node, "E105",
@@ -526,7 +550,21 @@ function checkInverseSelector(ts, sf, propName, prop, model, findings) {
526
550
  `inverse selector on '${propName}' (@${prop.decorator.name}) targets '${target.entityName}.${accessed}', but ${reason} — an inverse selector must select the RELATION property on the target that holds the OTHER SIDE of this relation, e.g. (task) => task.project`));
527
551
  }
528
552
 
529
- function checkColumn(ts, sf, prop, sdk, findings) {
553
+ /**
554
+ * E113 — "@Enum() and @MultiEnum() fill it from their first argument […] do not
555
+ * pass subType yourself on an enum field". Passing one by hand either duplicates
556
+ * what the decorator already writes or silently disagrees with it, and the value
557
+ * it disagrees with is the one that resolves { value: 'active' } to an enum
558
+ * record on insert.
559
+ */
560
+ function checkEnumSubType(ts, sf, propName, prop, findings) {
561
+ const subTypeNode = prop.enumOptions?.get("subType");
562
+ if (!subTypeNode) return;
563
+ findings.push(finding(ts, sf, subTypeNode, "E113",
564
+ `'${propName}' (@${prop.decorator.name}) passes 'subType' by hand — on an enum field subType holds the enum's global name and is "Set by the decorator — never by hand"; @Enum()/@MultiEnum() fill it from their first argument (or derive <ClassName>.<propertyName>). Remove the option.`));
565
+ }
566
+
567
+ function checkColumn(ts, sf, propName, prop, sdk, findings) {
530
568
  const opts = prop.columnOptions;
531
569
  for (const [opt, valNode] of opts) {
532
570
  if (!sdk.columnOptions.includes(opt)) {
@@ -584,6 +622,8 @@ function checkColumn(ts, sf, prop, sdk, findings) {
584
622
  `cannot statically verify that 'default' is a SQL expression string — it is delivered by reference or by an expression this checker cannot evaluate, so the check is skipped; inline a literal SQL string to restore checking`));
585
623
  }
586
624
  }
625
+ checkSubType(ts, sf, propName, prop, typeValue, findings);
626
+
587
627
  if (opts.has("length") && typeValue !== null && typeValue !== "text") {
588
628
  findings.push(finding(ts, sf, opts.get("length"), "W603",
589
629
  `'length' caps Text columns; this column is '${typeValue}'`));
@@ -594,6 +634,36 @@ function checkColumn(ts, sf, prop, sdk, findings) {
594
634
  }
595
635
  }
596
636
 
637
+ /**
638
+ * E112 — a subType string that the doc's matrix does not pair with this base
639
+ * type. Only two rows of that matrix belong to @Column(): Timestamp takes
640
+ * 'date' | 'time' | 'timestamp' ("Chooses the physical column type"), Text takes
641
+ * 'encrypted'. Anything else is rejected by the platform, not by tsc — `subType`
642
+ * is typed as a plain string, so a wrong pairing compiles.
643
+ *
644
+ * `subType: null` is the DOCUMENTED way to clear a subtype ("write subType: null
645
+ * explicitly") and is always clean. A value this AST-only checker cannot read
646
+ * takes the usual W606 unverifiable path — never E112. An unresolved `type`
647
+ * leaves nothing to judge the pairing against, so the check is skipped.
648
+ */
649
+ function checkSubType(ts, sf, propName, prop, typeValue, findings) {
650
+ const node = prop.columnOptions.get("subType");
651
+ if (!node) return;
652
+ const val = unwrapExpr(ts, node);
653
+ if (val.kind === ts.SyntaxKind.NullKeyword) return; // the documented "clear it"
654
+ const raw = stringValue(ts, val);
655
+ if (raw === null) {
656
+ findings.push(finding(ts, sf, node, "W606",
657
+ `cannot statically verify 'subType' of '${propName}' — it is delivered by reference or by an expression this checker cannot evaluate, so the base-type pairing check (E112) is skipped; inline the string literal to restore checking`));
658
+ return;
659
+ }
660
+ if (typeValue === null) return; // no readable `type` to pair it against
661
+ const allowed = DOC_SUBTYPES_BY_TYPE[typeValue];
662
+ if (allowed && allowed.includes(raw)) return;
663
+ findings.push(finding(ts, sf, node, "E112",
664
+ `subType '${raw}' is not valid on a '${typeValue}' column ('${propName}') — the doc's matrix pairs subType with exactly two @Column base types: Timestamp takes 'date', 'time' or 'timestamp', and Text takes 'encrypted'. No other (type, subType) combination exists.`));
665
+ }
666
+
597
667
  // ── extraction: string enums (createSeed(EnumName.Member) resolution) ──
598
668
  function analyzeEnums(ts, sf, model) {
599
669
  sf.forEachChild(function walk(node) {
@@ -55,6 +55,19 @@ export class __EntityName__ extends SystemBaseEntity {
55
55
  @Column({ name: 'amount', type: FieldTypeEnum.Numeric, decimalPlaces: 2 })
56
56
  amount: number;
57
57
 
58
+ // Date-only column — there is no FieldTypeEnum.Date; it is Timestamp + subType.
59
+ // CAVEAT: subType is fixed at creation — getting 'date' vs plain timestamp
60
+ // wrong later means a NEW field, not a conversion.
61
+ // @Column({ name: 'birthday', type: FieldTypeEnum.Timestamp, subType: 'date' })
62
+ // birthday: string;
63
+
64
+ // Encrypted at rest — Text only.
65
+ // CAVEAT: the platform forces unique/searchable/canFilter/canSort/canGroup to
66
+ // false and clears maxLength/minLength/mask — keep anything users must search
67
+ // in a separate plaintext column.
68
+ // @Column({ name: 'payload', type: FieldTypeEnum.Text, subType: 'encrypted' })
69
+ // payload: string;
70
+
58
71
  // Relation — ALWAYS a thunk (() => Target), never the class itself.
59
72
  // No inverse passed — it's optional on @ManyToOne and omitted by default.
60
73
  @ManyToOne(() => __TargetEntity__, { nullable: false })