suppa-mcp-2 1.2.3 → 1.3.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.
@@ -15,8 +15,8 @@ import { existsSync, statSync } from "node:fs";
15
15
  import { basename } from "node:path";
16
16
  import { config } from "../config.js";
17
17
  import * as tenants from "../tenants.js";
18
- import { makeRequest, makeRequestRawBytes, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
19
- import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam } from "../utils.js";
18
+ import { makeRequest, makeRequestRawBytes, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, restoreEntity, copyEntity, validateSelect, DELETED_SCOPES, DEFAULT_DELETED_SCOPE, DEFAULT_INCLUDE_DELETED_RELATIONS, } from "../httpClient.js";
19
+ import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam, mergeListProblems, normalizeConditionNodes, } from "../utils.js";
20
20
  // Builder field types that accept file uploads.
21
21
  export const FILE_FIELD_TYPES = ["file", "multi-file"];
22
22
  export const RELATION_FIELD_TYPES = [
@@ -27,6 +27,14 @@ export const RELATION_FIELD_TYPES = [
27
27
  ];
28
28
  // Every type the 2.0 builder accepts — used to reject typos client-side with a
29
29
  // clear message instead of an opaque server 400.
30
+ // The scalar list is builder.txt:62 verbatim
31
+ // (docs/superpowers/specs/captures/api-entity-builder-builder.txt:62 — "Scalar
32
+ // types: text, numeric, integer, serial, boolean, timestamp, json, uuid,
33
+ // multi-language, bytea, tsvector, multi-type, icon."); the relation list is
34
+ // builder.txt:63. bytea / tsvector / multi-type were missing here, so this server
35
+ // REFUSED three types the platform accepts and the bundled suppa-entity-code
36
+ // skill documents (skills/suppa-entity-code/references/entities.md:157-159) —
37
+ // MCP and skill disagreed and the agent was told the type did not exist.
30
38
  export const VALID_FIELD_TYPES = [
31
39
  "text",
32
40
  "numeric",
@@ -37,6 +45,9 @@ export const VALID_FIELD_TYPES = [
37
45
  "json",
38
46
  "uuid",
39
47
  "multi-language",
48
+ "bytea", // builder.txt:62
49
+ "tsvector", // builder.txt:62
50
+ "multi-type", // builder.txt:62
40
51
  "icon",
41
52
  "enum",
42
53
  "multi-enum",
@@ -44,6 +55,290 @@ export const VALID_FIELD_TYPES = [
44
55
  "multi-file",
45
56
  ...RELATION_FIELD_TYPES,
46
57
  ];
58
+ // Field types the builder groups as "Relation types" — their values live in a
59
+ // join/side table, not in a column of this table.
60
+ // (docs/superpowers/specs/captures/api-entity-builder-builder.txt:63 —
61
+ // "Relation types: many-to-one, one-to-many, many-to-many, many-to-many-backref,
62
+ // enum, multi-enum, file, multi-file.")
63
+ export const RELATION_LIKE_FIELD_TYPES = [
64
+ ...RELATION_FIELD_TYPES,
65
+ "enum",
66
+ "multi-enum",
67
+ "file",
68
+ "multi-file",
69
+ ];
70
+ // Where `defaultValue` does NOT apply. builder.txt:43 — "defaultValue | string |
71
+ // false | Default value. Not applicable to relations, enums, or unique fields."
72
+ // So: every relation-like type above, plus ANY type when unique is set.
73
+ // (`notNull` has its own, narrower exclusion — builder.txt:41: "Not applicable to
74
+ // many-to-many / multi-enum" — and is still sent for the rest.)
75
+ export const NO_DEFAULT_VALUE_FIELD_TYPES = RELATION_LIKE_FIELD_TYPES;
76
+ /**
77
+ * True when `defaultValue` is applicable to this field — and therefore when
78
+ * `notNull` on it also demands one. Recorded evidence for that demand, on the
79
+ * types where the default DOES apply: the builder answers HTTP 400
80
+ * "`defaultValue` is required when creating a field with `notNull: true`" (an
81
+ * empty string is rejected too). Where the default does not apply the builder
82
+ * takes `notNull` alone, so no default is required — and none is sent.
83
+ */
84
+ export function defaultValueApplies(fieldType, unique = false) {
85
+ return !unique && !RELATION_LIKE_FIELD_TYPES.includes(fieldType);
86
+ }
87
+ // ---------------------------------------------------------------------------
88
+ // Field options (the `options` object of a field body)
89
+ // ---------------------------------------------------------------------------
90
+ //
91
+ // builder.txt:60 — "options | object | false | Field options configuration."
92
+ // Its keys are builder.txt:66-73. A field created without them is invisible in
93
+ // table views and unsearchable until a human fixes it in the UI: the free-text
94
+ // search of suppa_search_records only covers fields carrying `searchable`
95
+ // (data.txt:218 — "Only fields with the searchable option participate.").
96
+ /** Boolean members of the Field Options object. */
97
+ export const FIELD_OPTION_BOOLEAN_KEYS = [
98
+ "searchable", // builder.txt:66 — "Available for search."
99
+ "readOnly", // builder.txt:68 — "Field is read-only (UI level)."
100
+ "canGroup", // builder.txt:69 — "Allow grouping by field."
101
+ "canSort", // builder.txt:70 — "Allow sorting by field."
102
+ "showInTable", // builder.txt:71 — "Show field in table view."
103
+ "editFromTable", // builder.txt:72 — "Allow editing from table view."
104
+ "canFilter", // builder.txt:73 — "Allow filtering by field."
105
+ ];
106
+ // builder.txt:67 — "searchPriority | number | false | Search priority, 1–4
107
+ // (higher = stronger weight)." The only non-boolean option.
108
+ export const FIELD_OPTION_SEARCH_PRIORITY = "searchPriority";
109
+ export const FIELD_OPTION_KEYS = [
110
+ ...FIELD_OPTION_BOOLEAN_KEYS,
111
+ FIELD_OPTION_SEARCH_PRIORITY,
112
+ ];
113
+ /**
114
+ * Validate an `options_json` parameter into the builder's Field Options object.
115
+ *
116
+ * Strict on purpose: the builder drops an unknown key without complaint, so a
117
+ * typo ("searchible", "sortable") would be reported as applied and silently do
118
+ * nothing — the same failure mode that made every field this server created come
119
+ * out nullable. Throws with the valid key list instead; returns null when there
120
+ * is nothing to send (so no empty `options: {}` is emitted).
121
+ */
122
+ export function normalizeFieldOptions(raw, param = "options_json") {
123
+ if (raw === null || raw === undefined || raw === "") {
124
+ return null;
125
+ }
126
+ const parsed = parseJsonParam(raw, param, "object");
127
+ const unknownKeys = Object.keys(parsed).filter((k) => !FIELD_OPTION_KEYS.includes(k));
128
+ if (unknownKeys.length > 0) {
129
+ throw new Error(`Parameter '${param}' has unknown option(s): ${unknownKeys.join(", ")}. The builder ` +
130
+ `accepts only ${FIELD_OPTION_KEYS.join(", ")} (builder.txt:66-73) and drops anything ` +
131
+ "else without complaint — which would look like success and change nothing.");
132
+ }
133
+ const out = {};
134
+ for (const [key, value] of Object.entries(parsed)) {
135
+ if (key === FIELD_OPTION_SEARCH_PRIORITY) {
136
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 4) {
137
+ throw new Error(`Parameter '${param}': searchPriority must be an integer 1-4 (builder.txt:67 — ` +
138
+ `"Search priority, 1–4 (higher = stronger weight)"), got ${JSON.stringify(value)}.`);
139
+ }
140
+ }
141
+ else if (typeof value !== "boolean") {
142
+ throw new Error(`Parameter '${param}': '${key}' must be true or false (builder.txt:66-73 type it as ` +
143
+ `boolean), got ${JSON.stringify(value)}.`);
144
+ }
145
+ out[key] = value;
146
+ }
147
+ return Object.keys(out).length > 0 ? out : null;
148
+ }
149
+ // ---------------------------------------------------------------------------
150
+ // Entity options (the `options` object of an entity body)
151
+ // ---------------------------------------------------------------------------
152
+ //
153
+ // builder.txt:74-90 — the platform's 15 per-entity features. Sent on
154
+ // create-entity (builder.txt:113 — "options | object | false | See Entity
155
+ // Options.") and edited on their own through /update-options (builder.txt:267).
156
+ //
157
+ // builder.txt:91-92 (TIP): "Enabling an option creates the side table that backs
158
+ // it. Turning on recurrence, reminders, notificationMutes, timeTracking or pinned
159
+ // also refreshes the cache of the corresponding system entity." A toggle here is
160
+ // therefore a schema change, not a preference.
161
+ /** Options typed `boolean` by builder.txt:76-90. */
162
+ export const ENTITY_OPTION_BOOLEAN_KEYS = [
163
+ "comments", // builder.txt:76 — "Enable comments."
164
+ "reactions", // builder.txt:77 — "Enable reactions."
165
+ "trackChangeHistory", // builder.txt:80 — "Enable change tracking."
166
+ "globalSearch", // builder.txt:82 — "Enable global search."
167
+ "timeTracking", // builder.txt:83 — "Enable time tracking."
168
+ "favorites", // builder.txt:84 — "Enable favorites."
169
+ "pinned", // builder.txt:85 — "Enable pinned instances."
170
+ "approvals", // builder.txt:86 — "Enable approvals."
171
+ "checklists", // builder.txt:87 — "Enable checklists."
172
+ "recurrence", // builder.txt:88 — "Enable recurrence."
173
+ "reminders", // builder.txt:89 — "Enable reminders."
174
+ "notificationMutes", // builder.txt:90 — "Enable notification mutes."
175
+ ];
176
+ /** The two mode options, both `"single" | "multi"`. */
177
+ export const ENTITY_OPTION_MODE_KEYS = [
178
+ "hierarchy", // builder.txt:78 — "Hierarchy mode."
179
+ "folders", // builder.txt:79 — "Folders mode."
180
+ ];
181
+ /** builder.txt:78-79 — the closed value set of hierarchy / folders. */
182
+ export const ENTITY_OPTION_MODES = ["single", "multi"];
183
+ // builder.txt:81 — "browsingHistory | boolean | number | false | Enable browsing
184
+ // history." The one option that takes either.
185
+ export const ENTITY_OPTION_BROWSING_HISTORY = "browsingHistory";
186
+ /** All 15, in the order builder.txt:76-90 lists them. */
187
+ export const ENTITY_OPTION_KEYS = [
188
+ "comments",
189
+ "reactions",
190
+ "hierarchy",
191
+ "folders",
192
+ "trackChangeHistory",
193
+ "browsingHistory",
194
+ "globalSearch",
195
+ "timeTracking",
196
+ "favorites",
197
+ "pinned",
198
+ "approvals",
199
+ "checklists",
200
+ "recurrence",
201
+ "reminders",
202
+ "notificationMutes",
203
+ ];
204
+ /**
205
+ * builder.txt:251-256 — on an entity created by the system (initiator = system)
206
+ * the ONLY option key accepted is globalSearch; everything else is dropped, and a
207
+ * body carrying none of the accepted keys fails with
208
+ * `Cannot update system entity: <name>`.
209
+ */
210
+ export const SYSTEM_ENTITY_OPTION_KEYS = ["globalSearch"];
211
+ /**
212
+ * builder.txt:258-264 — on a system-GENERATED entity (reserved suffixes) enabling
213
+ * any of these fails with `Modifying options of system-generated entity "<name>"
214
+ * is forbidden.` The doc does not list the reserved suffixes, so this server
215
+ * cannot tell which names are system-generated: it warns instead of guessing.
216
+ */
217
+ export const SYSTEM_GENERATED_FORBIDDEN_OPTIONS = [
218
+ "comments", // builder.txt:259
219
+ "timeTracking", // builder.txt:260
220
+ "pinned", // builder.txt:261
221
+ "favorites", // builder.txt:262
222
+ "approvals", // builder.txt:263
223
+ "checklists", // builder.txt:264
224
+ ];
225
+ /** builder.txt:91-92 — what a toggle actually costs, quoted back to the caller. */
226
+ export const ENTITY_OPTION_SIDE_EFFECT_NOTE = "Enabling an option creates the side table that backs it; recurrence, reminders, " +
227
+ "notificationMutes, timeTracking and pinned also refresh the cache of the corresponding " +
228
+ "system entity (builder.txt:91-92). This is a schema change, not a preference.";
229
+ /**
230
+ * Validate an options parameter into the builder's Entity Options object.
231
+ *
232
+ * Strict for the same reason as normalizeFieldOptions: the builder drops an
233
+ * unknown key without complaint, so a typo ("comment", "folder") would be
234
+ * reported as applied and change nothing. Each key is checked against the type
235
+ * builder.txt:76-90 gives it — hierarchy/folders are the "single" | "multi"
236
+ * enums, browsingHistory is boolean-or-number, the other twelve are booleans.
237
+ * Returns null when there is nothing to send (so no empty `options: {}`).
238
+ */
239
+ export function normalizeEntityOptions(raw, param = "options_json") {
240
+ if (raw === null || raw === undefined || raw === "") {
241
+ return null;
242
+ }
243
+ const parsed = parseJsonParam(raw, param, "object");
244
+ const unknownKeys = Object.keys(parsed).filter((k) => !ENTITY_OPTION_KEYS.includes(k));
245
+ if (unknownKeys.length > 0) {
246
+ throw new Error(`Parameter '${param}' has unknown option(s): ${unknownKeys.join(", ")}. The builder ` +
247
+ `accepts only ${ENTITY_OPTION_KEYS.join(", ")} (builder.txt:76-90) and drops anything ` +
248
+ "else without complaint — which would look like success and change nothing.");
249
+ }
250
+ const out = {};
251
+ for (const [key, value] of Object.entries(parsed)) {
252
+ if (ENTITY_OPTION_MODE_KEYS.includes(key)) {
253
+ if (typeof value !== "string" || !ENTITY_OPTION_MODES.includes(value)) {
254
+ throw new Error(`Parameter '${param}': '${key}' must be "single" or "multi" (builder.txt:78-79 types ` +
255
+ `it as '"single" | "multi"', not a boolean), got ${JSON.stringify(value)}.`);
256
+ }
257
+ }
258
+ else if (key === ENTITY_OPTION_BROWSING_HISTORY) {
259
+ const ok = typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value));
260
+ if (!ok) {
261
+ throw new Error(`Parameter '${param}': 'browsingHistory' must be a boolean or a number ` +
262
+ `(builder.txt:81 — "boolean | number"), got ${JSON.stringify(value)}.`);
263
+ }
264
+ }
265
+ else if (typeof value !== "boolean") {
266
+ throw new Error(`Parameter '${param}': '${key}' must be true or false (builder.txt:76-90 type it as ` +
267
+ `boolean), got ${JSON.stringify(value)}.`);
268
+ }
269
+ out[key] = value;
270
+ }
271
+ return Object.keys(out).length > 0 ? out : null;
272
+ }
273
+ // ---------------------------------------------------------------------------
274
+ // subType matrix
275
+ // ---------------------------------------------------------------------------
276
+ //
277
+ // migrations.txt:211-216 (docs/superpowers/specs/captures/migrations.txt) —
278
+ // "subType is a second, narrower classification on top of type ... it means three
279
+ // unrelated things depending on the base type": Timestamp → 'date' | 'time' |
280
+ // 'timestamp'; Text → 'encrypted'; Enum / MultiEnum → the enum's global name,
281
+ // "Set by the decorator — never by hand". Everything else takes none.
282
+ /** The documented matrix, echoed in refusals so the caller sees the rule itself. */
283
+ export const SUB_TYPE_MATRIX = {
284
+ timestamp: "'date' | 'time' | 'timestamp' — chooses the physical column type; omitted = timestamp (migrations.txt:213)",
285
+ text: "'encrypted' — value stored as an AES-GCM envelope (migrations.txt:214)",
286
+ "enum / multi-enum": "the enum's global name — set by the platform, NEVER by hand (migrations.txt:215, :256)",
287
+ "every other type": "no sub_type is documented (migrations.txt:212-216)",
288
+ };
289
+ /** sub_type values each base type accepts. migrations.txt:213-214. */
290
+ export const SUB_TYPES_BY_FIELD_TYPE = {
291
+ timestamp: ["date", "time", "timestamp"], // migrations.txt:213
292
+ text: ["encrypted"], // migrations.txt:214
293
+ };
294
+ /**
295
+ * Why this (type, sub_type) pair is refused — or null when the matrix allows it.
296
+ *
297
+ * Pure and request-free: the point is to refuse BEFORE anything is sent.
298
+ * 'encrypted' used to be forwarded raw on a numeric field, where the platform
299
+ * answers "Encrypted subtype is only allowed on text fields" (migrations.txt:241).
300
+ */
301
+ export function subTypeProblem(fieldType, subType) {
302
+ if (subType === null || subType === undefined) {
303
+ return null;
304
+ }
305
+ if (typeof subType !== "string") {
306
+ return `Refused: sub_type must be a string, got ${JSON.stringify(subType)}.`;
307
+ }
308
+ const st = subType.trim();
309
+ if (st === "") {
310
+ return null;
311
+ }
312
+ if (fieldType === "enum" || fieldType === "multi-enum") {
313
+ return (`Refused: sub_type is not yours to set on a '${fieldType}' field. There it holds the ` +
314
+ "ENUM'S GLOBAL NAME and the platform fills it in (migrations.txt:215 \"Enum, MultiEnum | " +
315
+ "The global enum name | Identifies which enum the field draws from. Set by the decorator " +
316
+ "— never by hand\"; :256 \"do not pass subType yourself on an enum field\"). Pass enum_name " +
317
+ "instead and leave sub_type unset.");
318
+ }
319
+ const allowed = SUB_TYPES_BY_FIELD_TYPE[fieldType];
320
+ if (!allowed) {
321
+ let extra = "";
322
+ if (st === "encrypted") {
323
+ extra =
324
+ ' The platform\'s own rule: "Encrypted subtype is only allowed on text fields" ' +
325
+ "(migrations.txt:241)";
326
+ extra +=
327
+ fieldType === "multi-type"
328
+ ? ', and "Encrypted subtype is not allowed inside a multi-type field" (migrations.txt:242).'
329
+ : ".";
330
+ }
331
+ return (`Refused: field type '${fieldType}' takes no sub_type. The subType matrix ` +
332
+ `(migrations.txt:212-216) documents exactly two combinations — timestamp → 'date' | ` +
333
+ `'time' | 'timestamp', text → 'encrypted' — plus enum / multi-enum, where the platform ` +
334
+ `sets it itself.${extra}`);
335
+ }
336
+ if (!allowed.includes(st)) {
337
+ return (`Refused: sub_type '${st}' is not valid on a '${fieldType}' field. The subType matrix ` +
338
+ `(migrations.txt:212-216) allows ${allowed.map((v) => `'${v}'`).join(" | ")} there.`);
339
+ }
340
+ return null;
341
+ }
47
342
  // ---------------------------------------------------------------------------
48
343
  // Multi-language titles
49
344
  // ---------------------------------------------------------------------------
@@ -193,16 +488,40 @@ export async function describeEntity(entityName) {
193
488
  const result = await makeRequest("GET", `/api/core/schema/${entityName}`);
194
489
  return jsonResponse(result);
195
490
  }
491
+ /**
492
+ * Normalise a deleted_scope argument. Returns the scope, or an error string for
493
+ * anything the platform would reject — the enum is closed (data.txt:76).
494
+ */
495
+ function _parseDeletedScope(raw) {
496
+ const value = (raw ?? DEFAULT_DELETED_SCOPE).trim().toLowerCase();
497
+ if (!DELETED_SCOPES.includes(value)) {
498
+ return {
499
+ scope: DEFAULT_DELETED_SCOPE,
500
+ error: jsonResponse({
501
+ error: `deleted_scope must be one of ${DELETED_SCOPES.join(", ")} — got '${raw}'. ` +
502
+ "'active' hides soft-deleted rows (the platform default), 'deleted' returns " +
503
+ "ONLY the soft-deleted ones (use it to find a record to restore), 'all' returns both.",
504
+ }),
505
+ };
506
+ }
507
+ return { scope: value };
508
+ }
196
509
  /**
197
510
  * Search records of any entity with filters.
198
511
  * filters_json: JSON array of filter objects [{field, value, comparator}].
199
512
  * fields_json: JSON object specifying which fields to return.
200
513
  * order_by: 'field:direction' (e.g. 'createdAt:desc').
201
514
  * match_any: when True, filters are combined with OR instead of AND.
515
+ * deleted_scope: 'active' | 'deleted' | 'all' (data.txt:76).
516
+ * include_deleted_relations: keep soft-deleted RELATED records (data.txt:75).
202
517
  *
203
518
  * Returns {"records": [...], "returned": N, "has_more": bool, "next_offset": int|null}.
204
519
  */
205
- export async function searchRecords(entityName, filtersJson = "[]", fieldsJson = '{"id": true}', limit = 20, offset = 0, search = "", orderBy = "createdAt:desc", matchAny = false) {
520
+ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson = '{"id": true}', limit = 20, offset = 0, search = "", orderBy = "createdAt:desc", matchAny = false, deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
521
+ const scope = _parseDeletedScope(deletedScope);
522
+ if (scope.error) {
523
+ return scope.error;
524
+ }
206
525
  let filters;
207
526
  let fields;
208
527
  try {
@@ -214,8 +533,14 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
214
533
  }
215
534
  // Tolerate common near-miss shapes instead of erroring:
216
535
  // a single filter object -> one-element list; a list of field names -> projection.
217
- if (filters !== null && typeof filters === "object" && !Array.isArray(filters)) {
218
- filters = [filters];
536
+ // Nested condition GROUPS are accepted here too — normalizeConditionNodes
537
+ // validates both leaf filters and {"operator": "and"|"or", "filters": [...]}
538
+ // groups (data.txt:33-42), so (a AND b) OR c is one call.
539
+ try {
540
+ filters = normalizeConditionNodes(filters, "filters_json");
541
+ }
542
+ catch (e) {
543
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
219
544
  }
220
545
  if (Array.isArray(fields)) {
221
546
  const proj = {};
@@ -237,17 +562,162 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
237
562
  // Fetch one extra row so the agent learns whether another page exists.
238
563
  // Cap at 500/page: larger responses blow the model's context — page instead.
239
564
  limit = Math.max(1, Math.min(limit, 500));
240
- const rows = await searchEntity(entityName, filters, fields, limit + 1, offset, order, search, matchAny ? "or" : "and");
565
+ const conditions = {
566
+ operator: matchAny ? "or" : "and",
567
+ filters: filters,
568
+ };
569
+ let rows;
570
+ try {
571
+ rows = await searchEntity(entityName, filters, fields, limit + 1, offset, order, search, matchAny ? "or" : "and", scope.scope, includeDeletedRelations);
572
+ }
573
+ catch (e) {
574
+ // A 400 is the platform refusing the payload. Ask select/validate WHY
575
+ // instead of handing the caller back an opaque status line.
576
+ const msg = e instanceof Error ? e.message : String(e);
577
+ if (!/HTTP 400/.test(msg)) {
578
+ throw e;
579
+ }
580
+ const diag = await _selectDiagnostic(entityName, {
581
+ fields: fields,
582
+ conditions,
583
+ orderBy: order,
584
+ });
585
+ if (!diag) {
586
+ throw e;
587
+ }
588
+ return jsonResponse({ error: msg, ...diag, records: [], returned: 0 });
589
+ }
241
590
  const hasMore = rows.length > limit;
242
- return jsonResponse({
591
+ const out = {
243
592
  records: rows.slice(0, limit),
244
593
  returned: Math.min(rows.length, limit),
245
594
  has_more: hasMore,
246
595
  next_offset: hasMore ? offset + limit : null,
596
+ deleted_scope: scope.scope,
597
+ };
598
+ // Zero rows is ambiguous: no matches, or a typo'd field that the platform
599
+ // resolved to nothing. ONE extra call — only on the empty result, never after
600
+ // a successful non-empty read — turns that into a real answer.
601
+ if (rows.length === 0) {
602
+ const diag = await _selectDiagnostic(entityName, {
603
+ fields: fields,
604
+ conditions,
605
+ orderBy: order,
606
+ });
607
+ if (diag) {
608
+ Object.assign(out, diag);
609
+ }
610
+ }
611
+ return jsonResponse(out);
612
+ }
613
+ /**
614
+ * Ask POST /core/data/:entityName/select/validate why a select produced nothing
615
+ * (data.txt:126-129 — "Use it to tell a malformed query from an empty result").
616
+ *
617
+ * Returns null when the payload validates (nothing useful to add) or when the
618
+ * check itself fails — a diagnostic must never turn a legitimate empty result
619
+ * into an error.
620
+ */
621
+ async function _selectDiagnostic(entityName, payload) {
622
+ let result;
623
+ try {
624
+ result = await validateSelect(entityName, payload);
625
+ }
626
+ catch {
627
+ return null;
628
+ }
629
+ if (!result || result.valid !== false) {
630
+ return null;
631
+ }
632
+ const invalid = Array.isArray(result.invalidFields) ? result.invalidFields : [];
633
+ // data.txt:145-148 — path / location / kind / reason.
634
+ const reasons = invalid
635
+ .map((f) => f?.reason || (f?.path ? `Unresolved reference '${f.path}'.` : ""))
636
+ .filter(Boolean);
637
+ return {
638
+ validation: {
639
+ valid: false,
640
+ invalidFields: invalid,
641
+ message: reasons.join(" ") ||
642
+ `The platform rejected this query against '${entityName}'.`,
643
+ },
644
+ hint: "This result is EMPTY because the query is malformed, not because nothing " +
645
+ "matched: the references above do not resolve on this entity. Check the " +
646
+ "names with suppa_describe_entity and re-run.",
647
+ };
648
+ }
649
+ /**
650
+ * Standalone query check: validate a select payload WITHOUT running it
651
+ * (POST /core/data/:entityName/select/validate, data.txt:126).
652
+ *
653
+ * Use it before an expensive read, or to explain an empty one: a typo'd field
654
+ * name silently returns no records, while this returns
655
+ * {"valid": false, "invalidFields": [{path, location, kind, reason}]}.
656
+ */
657
+ export async function validateSelectQuery(entityName, filtersJson = "[]", fieldsJson = '{"id": true}', orderBy = "", matchAny = false) {
658
+ let filters;
659
+ let fields;
660
+ try {
661
+ fields = parseJsonParam(fieldsJson, "fields_json");
662
+ filters = normalizeConditionNodes(parseJsonParam(filtersJson, "filters_json"), "filters_json");
663
+ }
664
+ catch (e) {
665
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
666
+ }
667
+ if (Array.isArray(fields)) {
668
+ const proj = {};
669
+ for (const f of fields) {
670
+ proj[String(f)] = true;
671
+ }
672
+ fields = proj;
673
+ }
674
+ let order = null;
675
+ if (orderBy.trim()) {
676
+ const idx = orderBy.indexOf(":");
677
+ const field = (idx === -1 ? orderBy : orderBy.slice(0, idx)).trim();
678
+ const direction = (idx === -1 ? "desc" : orderBy.slice(idx + 1)).trim().toLowerCase() || "desc";
679
+ order = [{ field, order: direction }];
680
+ }
681
+ let result;
682
+ try {
683
+ result = await validateSelect(entityName, {
684
+ fields: fields,
685
+ conditions: { operator: matchAny ? "or" : "and", filters },
686
+ orderBy: order,
687
+ });
688
+ }
689
+ catch (e) {
690
+ return jsonResponse({
691
+ error: e instanceof Error ? e.message : String(e),
692
+ entity: entityName,
693
+ });
694
+ }
695
+ const invalid = Array.isArray(result?.invalidFields) ? result.invalidFields : [];
696
+ const valid = result?.valid !== false;
697
+ return jsonResponse({
698
+ entity: entityName,
699
+ valid, // data.txt:143
700
+ invalidFields: invalid, // data.txt:144-148
701
+ message: valid
702
+ ? "Every referenced field, comparator and operator resolves on this entity — " +
703
+ "an empty result from this query means nothing matched."
704
+ : invalid
705
+ .map((f) => f?.reason || `Unresolved reference '${f?.path}'.`)
706
+ .filter(Boolean)
707
+ .join(" ") || "The platform rejected this payload.",
247
708
  });
248
709
  }
249
- /** Get a single record of any entity by its numeric id. */
250
- export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}') {
710
+ /**
711
+ * Get a single record of any entity by its numeric id.
712
+ *
713
+ * deleted_scope='deleted' (or 'all') reads a soft-deleted record — the only way
714
+ * to inspect one before restoring it with restoreRecord.
715
+ */
716
+ export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}', deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
717
+ const scope = _parseDeletedScope(deletedScope);
718
+ if (scope.error) {
719
+ return scope.error;
720
+ }
251
721
  let fields;
252
722
  try {
253
723
  fields = parseJsonParam(fieldsJson, "fields_json", "object");
@@ -255,10 +725,14 @@ export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}
255
725
  catch (e) {
256
726
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
257
727
  }
258
- const result = await selectEntity(entityName, [makeFilter("id", recordId)], fields);
728
+ const result = await selectEntity(entityName, [makeFilter("id", recordId)], fields, scope.scope, includeDeletedRelations);
259
729
  if (result === null) {
260
730
  return jsonResponse({
261
- error: `No record ${recordId} in '${entityName}' (wrong id, deleted, or no access).`,
731
+ error: `No record ${recordId} in '${entityName}' (wrong id, deleted, or no access).` +
732
+ (scope.scope === "active"
733
+ ? " If it was deleted, re-read it with deleted_scope='deleted' — a soft delete " +
734
+ "is reversible with suppa_restore_record."
735
+ : ""),
262
736
  });
263
737
  }
264
738
  return jsonResponse(result);
@@ -271,8 +745,24 @@ export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}
271
745
  * and the entity's titleFieldName resolves to a real field. Pass
272
746
  * auto_title_field=False when the caller adds its own fields (e.g. migration),
273
747
  * to avoid a type clash with a field of the same name added later.
748
+ *
749
+ * `options` carries the Entity Options object (builder.txt:113 — "options |
750
+ * object | false | See Entity Options."). Setting them at creation is the cheap
751
+ * moment: each one enabled later still creates its side table (builder.txt:91-92).
274
752
  */
275
- export async function createEntity(name, title, titleFieldName = "title", autoTitleField = true, titleFieldType = "multi-language") {
753
+ export async function createEntity(name, title, titleFieldName = "title", autoTitleField = true, titleFieldType = "multi-language", options) {
754
+ let entityOptions;
755
+ try {
756
+ entityOptions = normalizeEntityOptions(options, "options_json");
757
+ }
758
+ catch (e) {
759
+ // Refused BEFORE the request: a bad options object must not create the
760
+ // entity with the rest of the body silently applied.
761
+ return jsonResponse({
762
+ error: e instanceof Error ? e.message : String(e),
763
+ valid_option_keys: [...ENTITY_OPTION_KEYS],
764
+ });
765
+ }
276
766
  const titleObj = await _expandTitle(title, name);
277
767
  const body = {
278
768
  name,
@@ -280,17 +770,26 @@ export async function createEntity(name, title, titleFieldName = "title", autoTi
280
770
  titleFieldName,
281
771
  fields: [],
282
772
  };
773
+ if (entityOptions) {
774
+ body.options = entityOptions; // builder.txt:113
775
+ }
283
776
  const result = await makeRequest("POST", "/api/core/builder/create-entity", body);
284
777
  let titleFieldResult = null;
778
+ let representative = null;
285
779
  if (autoTitleField && titleFieldName) {
286
780
  titleFieldResult = _parseMaybe(await addField(name, titleFieldName, titleFieldType, titleObj));
781
+ // Make the freshly-created title field the entity's representative, so
782
+ // records show a label instead of an id everywhere in the UI. 5 tries, the
783
+ // same as set_title_field: the field was created a moment ago and the schema
784
+ // read is eventually consistent, so a single try reports a false "not found"
785
+ // and — worse — never sends the /update at all.
786
+ representative = _representativeResult(await _setRepresentative(name, titleFieldName, 5));
287
787
  }
288
- // NOTE: we deliberately do NOT auto-set the representative field here. The only
289
- // builder endpoint that accepts it (POST /builder/{entity}/update with
290
- // {representativeField:{id}}) proved unreliable in live testing (worked on some
291
- // entities, returned HTTP 500 on others) — too risky to run on every create.
292
- // Use suppa_set_title_field explicitly, or set the representative in the UI.
293
- return jsonResponse({ entity: result, title_field: titleFieldResult });
788
+ return jsonResponse({
789
+ entity: result,
790
+ title_field: titleFieldResult,
791
+ representative_field: representative,
792
+ });
294
793
  }
295
794
  /**
296
795
  * Create a tabular part (ТЧ / "таблична частина") — an owned child sub-table
@@ -333,14 +832,19 @@ export async function createTabularPart(parentEntity, name, title, titleFieldNam
333
832
  };
334
833
  const result = await makeRequest("POST", "/api/core/builder/create-entity", body);
335
834
  let titleFieldResult = null;
835
+ let representative = null;
336
836
  if (autoTitleField && titleFieldName) {
337
837
  titleFieldResult = _parseMaybe(await addField(entityName, titleFieldName, titleFieldType, titleObj));
838
+ // 5 tries — see create_entity: the field is brand new and the schema read
839
+ // that resolves its id is eventually consistent.
840
+ representative = _representativeResult(await _setRepresentative(entityName, titleFieldName, 5));
338
841
  }
339
842
  return jsonResponse({
340
843
  tabular_part: result,
341
844
  entity_name: entityName,
342
845
  parent_entity: parentEntity,
343
846
  title_field: titleFieldResult,
847
+ representative_field: representative,
344
848
  });
345
849
  }
346
850
  /**
@@ -365,36 +869,67 @@ function _parseMaybe(result) {
365
869
  return result;
366
870
  }
367
871
  }
368
- /** Return the numeric id of a field on an entity, or None if absent. */
369
- async function _fieldId(entityName, fieldName) {
370
- const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
371
- for (const f of _extractFields(schema)) {
372
- if (f.name === fieldName) {
373
- return f.id;
872
+ /**
873
+ * Return the numeric id of a field on an entity, or null if absent.
874
+ *
875
+ * Retries on the SAME schedule as the representative confirmation below: the
876
+ * schema read is eventually consistent, so a field created moments ago can be
877
+ * missing from the first read. Without the retry the create path would skip the
878
+ * /update POST entirely and report "field not found" for a field that exists —
879
+ * a false negative, not a real failure.
880
+ */
881
+ async function _fieldId(entityName, fieldName, tries = 1) {
882
+ const attempts = Math.max(1, tries);
883
+ for (let i = 0; i < attempts; i++) {
884
+ const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
885
+ for (const f of _extractFields(schema)) {
886
+ if (f.name === fieldName) {
887
+ return f.id;
888
+ }
889
+ }
890
+ if (i + 1 < attempts) {
891
+ await sleep(_schemaRetryMs);
374
892
  }
375
893
  }
376
894
  return null;
377
895
  }
896
+ /** Delay between eventually-consistent schema re-reads (field id + representative). */
897
+ let _schemaRetryMs = 2000;
898
+ /** Test hook: shrink the re-read delay so offline suites do not sleep for real. */
899
+ export function _setSchemaRetryMs(ms) {
900
+ _schemaRetryMs = ms;
901
+ }
378
902
  /**
379
903
  * Make `field_name` the entity's representative (display-title) field.
380
904
  *
381
- * Uses ``POST /api/core/builder/{entity}/update`` with
382
- * ``{"representativeField": {"id": <fieldId>}}``. CAVEAT: in live testing this
383
- * endpoint was unreliable — it set the representative on some entities but
384
- * returned HTTP 500 on others — so the error is surfaced (not swallowed) and
385
- * callers must treat it as best-effort. The schema read is eventually-
386
- * consistent, so confirmation polls up to ``verify_tries`` times. Returns
387
- * ``[confirmed, representative_value, error_or_None]``.
905
+ * WIRE FORMAT: ``POST /api/core/builder/{entity}/update`` with
906
+ * ``{"representativeFieldId": <fieldId>}`` — a NUMBER, per
907
+ * docs/superpowers/specs/captures/api-entity-builder-builder.txt:218
908
+ * ("representativeFieldId | number | false | Representative field ID."). Note the
909
+ * asymmetry with the read: the REQUEST takes the id, the schema RESPONSE returns
910
+ * ``representativeField`` as an object. This server used to send that response
911
+ * shape (``{"representativeField": {"id": …}}``), an unknown key.
912
+ *
913
+ * STILL UNEXPLAINED — recorded, not deleted: in live testing this endpoint set
914
+ * the representative on some entities and answered HTTP 500 on others. A wrong
915
+ * key cannot produce a 500, so the wire-format fix above does NOT account for
916
+ * that observation and it may still be there. Hence the error is REPORTED rather
917
+ * than thrown — the entity and its field exist either way — and the caller can
918
+ * retry. The schema read is eventually consistent, so both the field-id lookup
919
+ * and the confirmation poll up to ``verify_tries`` times.
920
+ * Returns ``[confirmed, representative_value, error_or_None]``.
388
921
  */
389
922
  async function _setRepresentative(entityName, fieldName, verifyTries = 1) {
390
- const fid = await _fieldId(entityName, fieldName);
923
+ const fid = await _fieldId(entityName, fieldName, verifyTries);
391
924
  if (fid === null || fid === undefined) {
392
925
  return [false, null, `field '${fieldName}' not found on '${entityName}'`];
393
926
  }
394
927
  let error = null;
395
928
  try {
396
929
  await makeRequest("POST", `/api/core/builder/${entityName}/update`, {
397
- representativeField: { id: fid },
930
+ // builder.txt:218 — the request key is representativeFieldId (number);
931
+ // representativeField (object) is the RESPONSE shape and is dropped here.
932
+ representativeFieldId: fid,
398
933
  });
399
934
  }
400
935
  catch (ex) {
@@ -419,7 +954,7 @@ async function _setRepresentative(entityName, fieldName, verifyTries = 1) {
419
954
  return [true, rep, null];
420
955
  }
421
956
  if (i + 1 < tries) {
422
- await sleep(2000);
957
+ await sleep(_schemaRetryMs);
423
958
  }
424
959
  }
425
960
  return [false, rep, error];
@@ -427,15 +962,36 @@ async function _setRepresentative(entityName, fieldName, verifyTries = 1) {
427
962
  function sleep(ms) {
428
963
  return new Promise((resolve) => setTimeout(resolve, ms));
429
964
  }
965
+ /**
966
+ * What an unconfirmed representative means, in the caller's words. One text,
967
+ * used by both create_* (via `_representativeResult`) and `set_title_field`, so
968
+ * the two paths never explain the same state differently.
969
+ */
970
+ function _representativeNote(confirmed, error) {
971
+ if (confirmed) {
972
+ return null;
973
+ }
974
+ return ("Representative not confirmed by the schema read (it is eventually " +
975
+ "consistent). The field exists; re-check the entity in a moment, or set " +
976
+ "the display field in the UI. " +
977
+ (error ? `(error: ${error})` : ""));
978
+ }
979
+ /**
980
+ * Shape `_setRepresentative`'s tuple for a create-* response. Reported, never
981
+ * thrown: the entity and its title field exist either way, and the confirming
982
+ * schema read is eventually consistent — which is exactly what `note` says when
983
+ * the confirmation did not land.
984
+ */
985
+ function _representativeResult([confirmed, value, error]) {
986
+ return { set: confirmed, value, error, note: _representativeNote(confirmed, error) };
987
+ }
430
988
  /**
431
989
  * Make `field_name` the entity's display-title (representative) field.
432
990
  *
433
- * Creates the field (multi-language) if it is missing, then makes a BEST-EFFORT
434
- * attempt to set it as the entity's representative via the builder update
435
- * endpoint. That endpoint proved unreliable in live testing (HTTP 500 on some
436
- * entities), so a failure here does not raise — it is reported in the result,
437
- * and the field is still created. Set the representative in the UI if the API
438
- * attempt fails.
991
+ * Creates the field (multi-language) if it is missing, then sets it as the
992
+ * entity's representative via the builder update endpoint. A failure does not
993
+ * raise — it is reported in the result and the field is still created — because
994
+ * the schema read used for confirmation is eventually consistent.
439
995
  */
440
996
  export async function setTitleField(entityName, fieldName) {
441
997
  const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
@@ -445,14 +1001,7 @@ export async function setTitleField(entityName, fieldName) {
445
1001
  created = _parseMaybe(await addField(entityName, fieldName, "multi-language", fieldName));
446
1002
  }
447
1003
  const [confirmed, rep, error] = await _setRepresentative(entityName, fieldName, 5);
448
- let note = null;
449
- if (!confirmed) {
450
- note =
451
- "Representative not confirmed via API — the builder update endpoint " +
452
- "is unreliable (often HTTP 500). The field exists; set it as the " +
453
- "display field in the UI. " +
454
- (error ? `(error: ${error})` : "");
455
- }
1004
+ const note = _representativeNote(confirmed, error);
456
1005
  return jsonResponse({
457
1006
  entity: entityName,
458
1007
  title_field: fieldName,
@@ -463,6 +1012,105 @@ export async function setTitleField(entityName, fieldName) {
463
1012
  note,
464
1013
  });
465
1014
  }
1015
+ /**
1016
+ * Edit ONLY an entity's options: POST /api/core/builder/{entity}/update-options
1017
+ * (builder.txt:267 — "A narrower alternative to Edit Entity that touches only
1018
+ * options. The same Restrictions apply."). The body IS the Entity Options object
1019
+ * (builder.txt:275 — "Same shape as Entity Options."), not `{options: {...}}`.
1020
+ *
1021
+ * The Restrictions it points at (builder.txt:250-264) are enforced here, before
1022
+ * the request, as far as they are checkable:
1023
+ * - an entity created by the system (initiator = "system") accepts only
1024
+ * options.globalSearch; everything else is dropped and a body with none of the
1025
+ * accepted keys fails with "Cannot update system entity: <name>" (:251-256).
1026
+ * The live entity metadata is read once to check this; a failed read SKIPS the
1027
+ * check rather than blocking a legitimate edit (same rule as updateField).
1028
+ * - a system-GENERATED entity (reserved suffixes) refuses comments, timeTracking,
1029
+ * pinned, favorites, approvals, checklists (:258-264). The doc never lists the
1030
+ * reserved suffixes, so which names those are is unknowable client-side: the
1031
+ * result carries the warning instead of a guess that would block real entities.
1032
+ *
1033
+ * The response is "the applied entity options — which may be a subset of the
1034
+ * request when the entity is a system one" (:282), so what came back is compared
1035
+ * against what was sent and the difference is reported.
1036
+ */
1037
+ export async function updateEntityOptions(entityName, options) {
1038
+ let body;
1039
+ try {
1040
+ body = normalizeEntityOptions(options, "options_json");
1041
+ }
1042
+ catch (e) {
1043
+ return jsonResponse({
1044
+ error: e instanceof Error ? e.message : String(e),
1045
+ valid_option_keys: [...ENTITY_OPTION_KEYS],
1046
+ });
1047
+ }
1048
+ if (!body) {
1049
+ return jsonResponse({
1050
+ error: `Refused: no options to apply to '${entityName}' — no request was sent. Pass an ` +
1051
+ `options object with at least one of: ${ENTITY_OPTION_KEYS.join(", ")} ` +
1052
+ "(builder.txt:76-90).",
1053
+ });
1054
+ }
1055
+ // --- Restriction: a system entity accepts options.globalSearch only. ------
1056
+ let meta = null;
1057
+ try {
1058
+ const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
1059
+ if (isPlainObject(schema)) {
1060
+ meta = schema;
1061
+ }
1062
+ }
1063
+ catch {
1064
+ // Can't verify → proceed rather than block on a transient read.
1065
+ }
1066
+ if (meta && (meta.initiator === "system" || meta.system === true)) {
1067
+ const rejected = Object.keys(body).filter((k) => !SYSTEM_ENTITY_OPTION_KEYS.includes(k));
1068
+ if (rejected.length > 0) {
1069
+ return jsonResponse({
1070
+ error: `Refused: '${entityName}' is a SYSTEM entity (initiator="system"). On one of those the ` +
1071
+ "builder accepts only representativeFieldId, representativeTemplate, title, " +
1072
+ "importKeyFields and options.globalSearch — anything else is DROPPED without " +
1073
+ `complaint, and a body carrying none of them fails with "Cannot update system entity: ` +
1074
+ `${entityName}" (builder.txt:251-256). Nothing was sent, so nothing was reported as ` +
1075
+ "applied that the platform would have thrown away.",
1076
+ rejected_keys: rejected.map((k) => `options.${k}`),
1077
+ accepted_on_system_entities: SYSTEM_ENTITY_OPTION_KEYS.map((k) => `options.${k}`),
1078
+ });
1079
+ }
1080
+ }
1081
+ const result = await makeRequest("POST", `/api/core/builder/${entityName}/update-options`, // builder.txt:267
1082
+ body);
1083
+ const out = {
1084
+ entity: entityName,
1085
+ sent: body,
1086
+ applied: result,
1087
+ note: ENTITY_OPTION_SIDE_EFFECT_NOTE,
1088
+ };
1089
+ // builder.txt:282 — the response "may be a subset of the request when the
1090
+ // entity is a system one". Say so instead of implying everything landed.
1091
+ if (isPlainObject(result)) {
1092
+ const applied = result;
1093
+ const notApplied = Object.keys(body).filter((k) => !Object.prototype.hasOwnProperty.call(applied, k));
1094
+ if (notApplied.length > 0) {
1095
+ out.not_applied = notApplied;
1096
+ out.not_applied_note =
1097
+ "The platform returns the APPLIED options and may drop keys it does not accept on this " +
1098
+ `entity (builder.txt:282). These were sent but are missing from the response: ` +
1099
+ `${notApplied.join(", ")}. Read the entity back with suppa_describe_entity before ` +
1100
+ "assuming they took effect.";
1101
+ }
1102
+ }
1103
+ const forbiddenEnabled = Object.keys(body).filter((k) => body[k] !== false &&
1104
+ SYSTEM_GENERATED_FORBIDDEN_OPTIONS.includes(k));
1105
+ if (forbiddenEnabled.length > 0) {
1106
+ out.system_generated_warning =
1107
+ `If '${entityName}' is a system-GENERATED entity (reserved suffix), enabling ` +
1108
+ `${forbiddenEnabled.join(", ")} fails with 'Modifying options of system-generated entity ` +
1109
+ `"${entityName}" is forbidden.' (builder.txt:258-264). The doc does not list the reserved ` +
1110
+ "suffixes, so this cannot be checked before the call.";
1111
+ }
1112
+ return jsonResponse(out);
1113
+ }
466
1114
  /**
467
1115
  * Pre-flight a relation field against the LIVE schema so we never create a
468
1116
  * broken or duplicate relation — either of which corrupts the entity:
@@ -539,8 +1187,9 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
539
1187
  * Add a field to an existing entity.
540
1188
  *
541
1189
  * field_type: a real Suppa 2.0 type — text, numeric, integer, serial, boolean,
542
- * timestamp, json, uuid, multi-language, icon, enum, multi-enum, file, multi-file,
543
- * many-to-one, many-to-many, many-to-many-backref.
1190
+ * timestamp, json, uuid, multi-language, bytea, tsvector, multi-type, icon, enum,
1191
+ * multi-enum, file, multi-file, many-to-one, many-to-many, many-to-many-backref
1192
+ * (builder.txt:62-63).
544
1193
  * There is NO date/datetime/richtext/email/url/phone/string type:
545
1194
  * - date-only → field_type='timestamp' with sub_type='date'
546
1195
  * - localized → field_type='multi-language'
@@ -551,9 +1200,24 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
551
1200
  * For relation fields, provide relation_entity. For enum fields, provide enum_name.
552
1201
  * Constraints: max_length/min_length (text), decimal_places (numeric),
553
1202
  * min_value/max_value/only_positive (numeric).
1203
+ * required=true makes the column NOT NULL and REQUIRES default_value (a SQL
1204
+ * expression or literal, e.g. '0', 'false', "'draft'", 'now()') — the builder
1205
+ * refuses notNull without one. Exempt, because defaultValue does not apply to
1206
+ * them at all: relation types (many-to-one / many-to-many / many-to-many-backref),
1207
+ * enum and multi-enum, file and multi-file, and any unique field. The call is
1208
+ * refused before any request if an applicable default is missing; no default is
1209
+ * ever invented.
1210
+ * options: the builder's Field Options object (builder.txt:60, keys :66-73) —
1211
+ * searchable / searchPriority / readOnly / canGroup / canSort / showInTable /
1212
+ * editFromTable / canFilter. Omitting it leaves the field out of table views and
1213
+ * out of free-text search (data.txt:218).
1214
+ * sub_type is checked against the documented matrix (migrations.txt:212-216)
1215
+ * before the request: timestamp takes 'date' | 'time' | 'timestamp', text takes
1216
+ * 'encrypted', enum/multi-enum have it set by the platform, and no other type
1217
+ * takes one.
554
1218
  */
555
1219
  export async function addField(entityName, fieldName, fieldType, title, opts = {}) {
556
- const { required = false, unique = false, relationEntity = null, enumName = null, subType = null, maxLength = null, minLength = null, decimalPlaces = null, minValue = null, maxValue = null, onlyPositive = false, } = opts;
1220
+ const { required = false, defaultValue = null, unique = false, relationEntity = null, enumName = null, subType = null, maxLength = null, minLength = null, decimalPlaces = null, minValue = null, maxValue = null, onlyPositive = false, options = null, } = opts;
557
1221
  // The platform has no relation type literally called "relation"; a foreign
558
1222
  // key is "many-to-one" with the target entity in `relationTarget`.
559
1223
  let resolvedType = fieldType === "relation" ? "many-to-one" : fieldType;
@@ -601,6 +1265,54 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
601
1265
  "with suppa_add_enum_values.",
602
1266
  });
603
1267
  }
1268
+ // sub_type pre-flight: refuse a combination the matrix does not document,
1269
+ // BEFORE any request. 'encrypted' on a numeric field used to be forwarded raw.
1270
+ const subProblem = subTypeProblem(resolvedType, subType);
1271
+ if (subProblem) {
1272
+ return jsonResponse({ error: subProblem, sub_type_matrix: SUB_TYPE_MATRIX });
1273
+ }
1274
+ // Field options (builder.txt:60 / :66-73) — validated before anything is sent;
1275
+ // an unknown key here would be dropped by the builder and reported as applied.
1276
+ let fieldOptions;
1277
+ try {
1278
+ fieldOptions = normalizeFieldOptions(options, "options_json");
1279
+ }
1280
+ catch (e) {
1281
+ return jsonResponse({
1282
+ error: e instanceof Error ? e.message : String(e),
1283
+ valid_option_keys: [...FIELD_OPTION_KEYS],
1284
+ });
1285
+ }
1286
+ // NOT NULL needs a default — but ONLY where a default is applicable at all.
1287
+ // builder.txt:43 (docs/superpowers/specs/captures/api-entity-builder-builder.txt)
1288
+ // rules defaultValue out for relations, enums and unique fields; on everything
1289
+ // else the builder rejects `notNull: true` on its own (HTTP 400 "`defaultValue`
1290
+ // is required when creating a field with `notNull: true`") and rejects an
1291
+ // empty-string default as well. There we refuse BEFORE the request instead of
1292
+ // inventing a value: what an empty row should hold is a data-semantics decision
1293
+ // that belongs to the caller, and guessing it would silently write a value
1294
+ // nobody chose.
1295
+ const defaultText = defaultValue === null || defaultValue === undefined ? "" : String(defaultValue);
1296
+ const typeNeedsDefault = defaultValueApplies(resolvedType, unique);
1297
+ if (required && typeNeedsDefault && defaultText.trim() === "") {
1298
+ return jsonResponse({
1299
+ error: `Refused: required=true needs default_value. The builder rejects a notNull field ` +
1300
+ "without one (HTTP 400: \"`defaultValue` is required when creating a field with " +
1301
+ `\`notNull: true\`\"), and an empty string does not count. Pass default_value — the ` +
1302
+ "value every row without an explicit one gets — as a SQL expression or literal, or " +
1303
+ "leave required=false and add the constraint later once the column is populated. " +
1304
+ "This server will not pick a default for you: that would silently decide your data semantics.",
1305
+ examples: [
1306
+ `suppa_add_field(entity_name="${entityName}", field_name="${fieldName}", ` +
1307
+ `field_type="${resolvedType}", required=true, default_value="0") # literal`,
1308
+ `suppa_add_field(entity_name="${entityName}", field_name="${fieldName}", ` +
1309
+ `field_type="${resolvedType}", required=true, default_value="now()") # SQL expression ` +
1310
+ "(quote text literals inside the string: \"'draft'\")",
1311
+ ],
1312
+ no_default_needed_for: [...NO_DEFAULT_VALUE_FIELD_TYPES],
1313
+ no_default_needed_when: "unique=true (defaultValue does not apply to a unique field)",
1314
+ });
1315
+ }
604
1316
  // Relation pre-flight: verify the target exists and the field is new, so we
605
1317
  // never leave a dangling or duplicate relation on the entity. May correct a
606
1318
  // case-only target-name mismatch.
@@ -612,13 +1324,26 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
612
1324
  }
613
1325
  relTarget = pf.relationEntity;
614
1326
  }
1327
+ // The builder reads `notNull`, NOT `required` — an unknown key is dropped
1328
+ // without complaint, which is why every field this server used to create came
1329
+ // out nullable while the tool reported success. The TOOL parameter stays
1330
+ // `required`; only the wire key changed.
1331
+ // Wire keys per docs/superpowers/specs/captures/api-entity-builder-builder.txt:
1332
+ // notNull :41, unique :42, defaultValue :43, subType :40, relationTarget :44,
1333
+ // maxLength :49, minLength :50, maxValue :51, minValue :52, isOnlyPositive :53,
1334
+ // decimalPlaces :55, title :56.
615
1335
  const fieldDef = {
616
1336
  name: fieldName,
617
1337
  type: resolvedType,
618
1338
  title: await _expandTitle(title, fieldName),
619
- required,
1339
+ notNull: required,
620
1340
  unique,
621
1341
  };
1342
+ // builder.txt:43 — "Not applicable to relations, enums, or unique fields":
1343
+ // sending it there is at best ignored, so it is never emitted.
1344
+ if (defaultText.trim() !== "" && typeNeedsDefault) {
1345
+ fieldDef.defaultValue = defaultText;
1346
+ }
622
1347
  if (subType) {
623
1348
  fieldDef.subType = subType;
624
1349
  }
@@ -647,6 +1372,11 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
647
1372
  if (enumName) {
648
1373
  fieldDef.enumName = enumName;
649
1374
  }
1375
+ // builder.txt:60 — "options | object | false | Field options configuration."
1376
+ // (example body: builder.txt:127-132).
1377
+ if (fieldOptions) {
1378
+ fieldDef.options = fieldOptions;
1379
+ }
650
1380
  // Correct endpoint is /builder/{Entity}/add-fields and the body is the bare
651
1381
  // array of field defs (the old /builder/add-fields with an {entityName,fields}
652
1382
  // wrapper 404s).
@@ -655,6 +1385,217 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
655
1385
  ]);
656
1386
  return jsonResponse(result);
657
1387
  }
1388
+ // builder.txt:391-398 — on a field created by the system (initiator = system)
1389
+ // these are the only accepted keys. Note searchPriority is NOT among them.
1390
+ const _SYSTEM_FIELD_TOP_KEYS = ["title", "options"];
1391
+ const _SYSTEM_FIELD_OPTION_KEYS = [
1392
+ "canGroup", // builder.txt:392
1393
+ "canSort", // builder.txt:393
1394
+ "showInTable", // builder.txt:394
1395
+ "editFromTable", // builder.txt:395
1396
+ "canFilter", // builder.txt:396
1397
+ "readOnly", // builder.txt:397
1398
+ "searchable", // builder.txt:398
1399
+ ];
1400
+ /**
1401
+ * Edit an existing field: POST /api/core/builder/{entity}/{field}/update-field
1402
+ * (builder.txt:344). Every body key is optional — only what changes is sent.
1403
+ *
1404
+ * This replaces the old "field edits are UI-only" policy of this server, which
1405
+ * predated the endpoint. What the endpoint itself refuses is enforced HERE,
1406
+ * before the request (builder.txt:388-398, migrations.txt:257-263):
1407
+ * - `type` is never changeable — "Field type cannot be changed." (:389). No
1408
+ * type key is ever sent, and a caller asking for one is told why.
1409
+ * - `subType` is not changeable either — "Field subType cannot be changed."
1410
+ * (:390) — EXCEPT toggling 'encrypted' on or off (migrations.txt:261). A
1411
+ * date↔timestamp change is a physical column-type change under existing data:
1412
+ * add a new field instead.
1413
+ * - 'encrypted' only on a text field (migrations.txt:241), and never together
1414
+ * with searchable/canFilter/canSort/canGroup, which encryption forces off
1415
+ * (migrations.txt:245).
1416
+ * - a system field (initiator = "system") accepts only title + seven options
1417
+ * keys (:391-398).
1418
+ * The field's live metadata is read once to check those; a failed read SKIPS the
1419
+ * checks rather than blocking a legitimate edit (same rule as _relationPreflight).
1420
+ */
1421
+ export async function updateField(entityName, fieldName, opts = {}) {
1422
+ // --- Restriction: type is never changeable (builder.txt:389). -------------
1423
+ if (opts.type !== undefined && opts.type !== null && String(opts.type).trim() !== "") {
1424
+ return jsonResponse({
1425
+ error: 'Refused: "Field type cannot be changed." (builder.txt:389). The builder rejects a ' +
1426
+ `type change on an existing field, so '${fieldName}' keeps the type it was created ` +
1427
+ "with. To store a different type, add a NEW field with suppa_add_field and move the " +
1428
+ "data across; the old column would otherwise have to be rewritten under existing rows.",
1429
+ });
1430
+ }
1431
+ // --- Restriction: subType only toggles 'encrypted' (builder.txt:390). -----
1432
+ const wantsEncryptToggle = opts.encrypt !== undefined && opts.encrypt !== null;
1433
+ const wantsRawSubType = Object.prototype.hasOwnProperty.call(opts, "subType");
1434
+ let subTypeValue;
1435
+ if (wantsEncryptToggle) {
1436
+ subTypeValue = opts.encrypt ? "encrypted" : null;
1437
+ }
1438
+ if (wantsRawSubType) {
1439
+ const raw = opts.subType === undefined || opts.subType === null ? null : String(opts.subType).trim();
1440
+ const normalized = raw === "" ? null : raw;
1441
+ if (wantsEncryptToggle && normalized !== subTypeValue) {
1442
+ return jsonResponse({
1443
+ error: `Refused: encrypt=${opts.encrypt} and sub_type=${JSON.stringify(opts.subType)} ask for ` +
1444
+ "different subtypes. Pass one of them.",
1445
+ });
1446
+ }
1447
+ subTypeValue = normalized;
1448
+ }
1449
+ const changesSubType = wantsEncryptToggle || wantsRawSubType;
1450
+ if (changesSubType && subTypeValue !== null && subTypeValue !== "encrypted") {
1451
+ return jsonResponse({
1452
+ error: `Refused: "Field subType cannot be changed." (builder.txt:390; migrations.txt:258-259). ` +
1453
+ "The one permitted transition is the encryption toggle — setting 'encrypted' or clearing " +
1454
+ `it (migrations.txt:261) — not '${subTypeValue}'. A date/time choice is fixed at creation: ` +
1455
+ "the physical column type would have to change under existing data, so add a new field " +
1456
+ "with suppa_add_field instead of converting this one.",
1457
+ sub_type_matrix: SUB_TYPE_MATRIX,
1458
+ });
1459
+ }
1460
+ // --- Field options (builder.txt:364 — same shape as Field Options). -------
1461
+ let fieldOptions;
1462
+ try {
1463
+ fieldOptions = normalizeFieldOptions(opts.options, "options_json");
1464
+ }
1465
+ catch (e) {
1466
+ return jsonResponse({
1467
+ error: e instanceof Error ? e.message : String(e),
1468
+ valid_option_keys: [...FIELD_OPTION_KEYS],
1469
+ });
1470
+ }
1471
+ // Encryption forces the read-the-plaintext capabilities off whatever was
1472
+ // declared (migrations.txt:245), so asking for both in one call would report an
1473
+ // option the platform immediately discards.
1474
+ if (subTypeValue === "encrypted" && fieldOptions) {
1475
+ const clash = ["searchable", "canFilter", "canSort", "canGroup"].filter((k) => fieldOptions[k] === true);
1476
+ if (clash.length > 0) {
1477
+ return jsonResponse({
1478
+ error: `Refused: encrypting '${fieldName}' turns ${clash.join(", ")} off by itself — ` +
1479
+ '"the searchable, canFilter, canSort and canGroup options become false" ' +
1480
+ "(migrations.txt:245), because an encrypted column cannot be read as plaintext. " +
1481
+ "Asking for both in one call would report options the platform discards. Keep the " +
1482
+ "searchable part in a separate plaintext field (migrations.txt:249).",
1483
+ });
1484
+ }
1485
+ }
1486
+ // --- Build the body. Keys and their doc lines: builder.txt:352-364. -------
1487
+ const body = {};
1488
+ if (opts.newName !== undefined && opts.newName !== null && String(opts.newName).trim() !== "") {
1489
+ body.name = String(opts.newName).trim(); // builder.txt:353
1490
+ }
1491
+ if (changesSubType) {
1492
+ body.subType = subTypeValue; // builder.txt:355 (explicit null clears it — migrations.txt:263)
1493
+ }
1494
+ if (opts.required !== undefined && opts.required !== null) {
1495
+ body.notNull = opts.required; // builder.txt:356
1496
+ }
1497
+ if (opts.unique !== undefined && opts.unique !== null) {
1498
+ body.unique = opts.unique; // builder.txt:357
1499
+ }
1500
+ if (opts.defaultValue !== undefined && opts.defaultValue !== null) {
1501
+ body.defaultValue = String(opts.defaultValue); // builder.txt:358
1502
+ }
1503
+ if (opts.relationEntity !== undefined && opts.relationEntity !== null && String(opts.relationEntity).trim() !== "") {
1504
+ body.relationTarget = String(opts.relationEntity).trim(); // builder.txt:359
1505
+ }
1506
+ if (opts.backReference !== undefined && opts.backReference !== null && String(opts.backReference).trim() !== "") {
1507
+ body.backReference = String(opts.backReference).trim(); // builder.txt:360
1508
+ }
1509
+ if (opts.isPrimary !== undefined && opts.isPrimary !== null) {
1510
+ body.isPrimary = opts.isPrimary; // builder.txt:361
1511
+ }
1512
+ if (opts.isArray !== undefined && opts.isArray !== null) {
1513
+ body.isArray = opts.isArray; // builder.txt:362
1514
+ }
1515
+ if (fieldOptions) {
1516
+ body.options = fieldOptions; // builder.txt:364
1517
+ }
1518
+ const wantsTitle = opts.title !== undefined && opts.title !== null && (isPlainObject(opts.title) || String(opts.title).trim() !== "");
1519
+ if (Object.keys(body).length === 0 && !wantsTitle) {
1520
+ return jsonResponse({
1521
+ error: `Refused: nothing to update on '${entityName}.${fieldName}' — no request was sent. Pass ` +
1522
+ "at least one change: new_name, title, required, unique, default_value, relation_entity, " +
1523
+ "back_reference, is_primary, is_array, encrypt, or options_json. (type is never " +
1524
+ "changeable — builder.txt:389.)",
1525
+ });
1526
+ }
1527
+ // --- Live metadata, for the checks that need to know the field. -----------
1528
+ let meta = null;
1529
+ let metaRead = false;
1530
+ try {
1531
+ const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
1532
+ const fields = _extractFields(schema);
1533
+ if (fields.length > 0) {
1534
+ metaRead = true;
1535
+ meta = fields.find((f) => f.name === fieldName) ?? null;
1536
+ }
1537
+ }
1538
+ catch {
1539
+ // Can't verify → proceed rather than block on a transient read.
1540
+ }
1541
+ if (metaRead && !meta) {
1542
+ return jsonResponse({
1543
+ error: `Refused: field '${fieldName}' does not exist on '${entityName}' — nothing was sent. ` +
1544
+ "Check the name with suppa_describe_entity (field names are case-sensitive); if you " +
1545
+ "just created it, retry in a moment — the schema read is eventually consistent.",
1546
+ });
1547
+ }
1548
+ if (subTypeValue === "encrypted" && meta) {
1549
+ const liveType = String(meta.type ?? "");
1550
+ if (liveType !== "text") {
1551
+ return jsonResponse({
1552
+ error: `Refused: "Encrypted subtype is only allowed on text fields" (migrations.txt:241) — ` +
1553
+ `'${fieldName}' is '${liveType}'.` +
1554
+ (liveType === "multi-type"
1555
+ ? ' Also: "Encrypted subtype is not allowed inside a multi-type field" (migrations.txt:242).'
1556
+ : ""),
1557
+ });
1558
+ }
1559
+ }
1560
+ if (wantsTitle) {
1561
+ body.title = await _expandTitle(opts.title, String(body.name ?? fieldName)); // builder.txt:363
1562
+ }
1563
+ // System fields accept a much narrower body (builder.txt:391-398).
1564
+ if (meta && (meta.initiator === "system" || meta.system === true)) {
1565
+ const badTop = Object.keys(body).filter((k) => !_SYSTEM_FIELD_TOP_KEYS.includes(k));
1566
+ const badOptions = Object.keys(fieldOptions ?? {}).filter((k) => !_SYSTEM_FIELD_OPTION_KEYS.includes(k));
1567
+ if (badTop.length > 0 || badOptions.length > 0) {
1568
+ return jsonResponse({
1569
+ error: `Refused: '${fieldName}' is a SYSTEM field (initiator="system"). The builder accepts ` +
1570
+ "only title and options.{canGroup, canSort, showInTable, editFromTable, canFilter, " +
1571
+ "readOnly, searchable} on one (builder.txt:391-398) — note searchPriority is not in " +
1572
+ `that list — and a body carrying none of them fails with "Cannot update system field: ` +
1573
+ `${fieldName}". Nothing was sent.`,
1574
+ rejected_keys: [...badTop, ...badOptions.map((k) => `options.${k}`)],
1575
+ accepted_on_system_fields: [
1576
+ "title",
1577
+ ..._SYSTEM_FIELD_OPTION_KEYS.map((k) => `options.${k}`),
1578
+ ],
1579
+ });
1580
+ }
1581
+ }
1582
+ const result = await makeRequest("POST", `/api/core/builder/${entityName}/${fieldName}/update-field`, body);
1583
+ const out = {
1584
+ entity: entityName,
1585
+ field: fieldName,
1586
+ sent: body,
1587
+ result,
1588
+ };
1589
+ if (subTypeValue === "encrypted") {
1590
+ // migrations.txt:244-247 — what the platform does to the field and its rows.
1591
+ out.encryption_note =
1592
+ "Encrypting this field forces unique=false and searchable/canFilter/canSort/canGroup to " +
1593
+ "false, and clears maxLength/minLength/mask (migrations.txt:244-246). The rows already in " +
1594
+ "the table are encrypted in place; a row that fails to decrypt on the way back aborts the " +
1595
+ "backfill rather than overwriting ciphertext (migrations.txt:247).";
1596
+ }
1597
+ return jsonResponse(out);
1598
+ }
658
1599
  /**
659
1600
  * Add values to an enum (lookup table). values: comma-separated list of values to add.
660
1601
  *
@@ -704,10 +1645,21 @@ export async function listFieldTypes() {
704
1645
  },
705
1646
  { type: "serial", description: "Auto-incrementing integer" },
706
1647
  { type: "boolean", description: "True/false" },
707
- { type: "timestamp", description: "Date+time; for date-only set sub_type='date'" },
1648
+ {
1649
+ type: "timestamp",
1650
+ description: "Date+time; sub_type='date' for date-only, 'time' for time-only (migrations.txt:213)",
1651
+ },
708
1652
  { type: "multi-language", description: "Localized text object ({en, uk, ...})" },
709
1653
  { type: "json", description: "JSON object/array" },
710
1654
  { type: "uuid", description: "UUID value" },
1655
+ // builder.txt:62 — scalar types this server used to refuse client-side.
1656
+ { type: "bytea", description: "Raw binary (builder.txt:62); prefer 'file' for attachments" },
1657
+ { type: "tsvector", description: "Full-text search vector column (builder.txt:62)" },
1658
+ {
1659
+ type: "multi-type",
1660
+ description: "Composite field built from sub-fields (builder.txt:62). This tool creates the parent " +
1661
+ "field only — its subFields / multiTypeName wiring (builder.txt:58-59) is not exposed here.",
1662
+ },
711
1663
  { type: "icon", description: "Icon reference" },
712
1664
  { type: "enum", description: "Single lookup value (requires enum_name)" },
713
1665
  { type: "multi-enum", description: "Multiple lookup values" },
@@ -772,7 +1724,9 @@ function _shapeProblemsFromDefs(defs, fields) {
772
1724
  else if (_MULTI_REF_TYPES.includes(ftype) &&
773
1725
  !(isRef(val) || (Array.isArray(val) && val.every((x) => isRef(x))))) {
774
1726
  problems.push(`'${key}' is a ${ftype} field — write it as [{"id": N}, ...] ` +
775
- `(got ${_truncJson(val)}).`);
1727
+ `(got ${_truncJson(val)}). The list you send REPLACES the stored one: ` +
1728
+ "to ADD items pass the field name in merge_json, to REMOVE only the " +
1729
+ "listed items pass it in unmerge_json (suppa_update_record).");
776
1730
  }
777
1731
  }
778
1732
  return problems;
@@ -844,6 +1798,15 @@ async function _resolveEntity(name) {
844
1798
  * (possibly case-corrected) entity name and an error string when refused.
845
1799
  */
846
1800
  async function _validateRecordWrite(entityName, fields) {
1801
+ return _validateRecordWrites(entityName, [fields]);
1802
+ }
1803
+ /**
1804
+ * The batch form of `_validateRecordWrite`: validates EVERY record in one
1805
+ * insert against a SINGLE schema read, so a batch costs the same one GET a
1806
+ * single record does. With one record the refusals are byte-identical to the
1807
+ * single-record path; with several, each problem carries its record index.
1808
+ */
1809
+ async function _validateRecordWrites(entityName, records) {
847
1810
  const ent = await _resolveEntity(entityName);
848
1811
  if (ent.error) {
849
1812
  return { entityName, error: ent.error };
@@ -858,80 +1821,219 @@ async function _validateRecordWrite(entityName, fields) {
858
1821
  defs = null; // unreadable → can't validate fields; proceed
859
1822
  }
860
1823
  if (defs && defs.length > 0) {
1824
+ const many = records.length > 1;
861
1825
  const fieldNames = new Set(defs.map((f) => f.name).filter((n) => Boolean(n)));
862
- const unknown = Object.keys(fields).filter((k) => !fieldNames.has(k));
1826
+ const unknown = [
1827
+ ...new Set(records.flatMap((r) => Object.keys(r).filter((k) => !fieldNames.has(k)))),
1828
+ ];
863
1829
  if (unknown.length > 0) {
864
- return {
865
- entityName,
866
- error: jsonResponse({
867
- error: `Refused: field(s) [${unknown.join(", ")}] do not exist on '${entityName}'. ` +
868
- "The platform silently drops unknown keys, so this would create a record missing " +
869
- "that data (a 'broken' entity). Use only real fields (see valid_fields), or add " +
870
- "the field first with suppa_add_field.",
871
- unknown_fields: unknown,
872
- valid_fields: [...fieldNames].sort(),
873
- }),
1830
+ const body = {
1831
+ error: `Refused: field(s) [${unknown.join(", ")}] do not exist on '${entityName}'. ` +
1832
+ "The platform silently drops unknown keys, so this would create a record missing " +
1833
+ "that data (a 'broken' entity). Use only real fields (see valid_fields), or add " +
1834
+ "the field first with suppa_add_field.",
1835
+ unknown_fields: unknown,
1836
+ valid_fields: [...fieldNames].sort(),
874
1837
  };
1838
+ if (many) {
1839
+ body.offending_records = records
1840
+ .map((r, i) => (Object.keys(r).some((k) => !fieldNames.has(k)) ? i : -1))
1841
+ .filter((i) => i >= 0);
1842
+ body.note = "NOTHING was inserted — the whole batch is refused as one unit.";
1843
+ }
1844
+ return { entityName, error: jsonResponse(body) };
875
1845
  }
876
- const problems = _shapeProblemsFromDefs(defs, fields);
1846
+ const problems = records.flatMap((r, i) => _shapeProblemsFromDefs(defs, r).map((p) => many ? `record[${i}]: ${p}` : p));
877
1847
  if (problems.length > 0) {
878
- return {
879
- entityName,
880
- error: jsonResponse({
881
- error: "Refused: these values would be SILENTLY stored as NULL by the platform.",
882
- problems,
883
- hint: "Look up ids via suppa_search_records (Enums for enum values; the " +
884
- 'target entity for relations), then re-send as {"id": N}.',
885
- }),
1848
+ const body = {
1849
+ error: "Refused: these values would be SILENTLY stored as NULL by the platform.",
1850
+ problems,
1851
+ hint: "Look up ids via suppa_search_records (Enums for enum values; the " +
1852
+ 'target entity for relations), then re-send as {"id": N}.',
886
1853
  };
1854
+ if (many) {
1855
+ body.note = "NOTHING was inserted — the whole batch is refused as one unit.";
1856
+ }
1857
+ return { entityName, error: jsonResponse(body) };
1858
+ }
1859
+ }
1860
+ // The defs travel back so the caller does not re-read the schema to decide
1861
+ // which written fields are actually list-valued (see `_replacedListNames`).
1862
+ return { entityName, defs: defs && defs.length > 0 ? defs : null };
1863
+ }
1864
+ // The only field types whose stored value IS a list, so the only ones an update
1865
+ // can replace wholesale and the only ones merge/unmerge applies to. Types from
1866
+ // the builder's relation group (api-entity-builder-builder.txt:63). A `json`
1867
+ // column may perfectly well hold a JSON array — that is ONE value being
1868
+ // overwritten, not a list of links being wiped, and warning about it is noise.
1869
+ const LIST_VALUED_FIELD_TYPES = new Set([
1870
+ "many-to-many",
1871
+ "many-to-many-backref",
1872
+ "one-to-many",
1873
+ "multi-enum",
1874
+ "multi-file",
1875
+ ]);
1876
+ /**
1877
+ * Names of the fields this write REPLACES wholesale: list-valued per the schema,
1878
+ * written with an array, and not opted out via merge/unmerge.
1879
+ *
1880
+ * `defs === null` means the schema could not be read — then the array shape is
1881
+ * all we have, so we still warn. A spurious warning is noise; a missing one can
1882
+ * mean a silently wiped list.
1883
+ */
1884
+ function _replacedListNames(defs, fields, merge, unmerge) {
1885
+ const typeByName = new Map();
1886
+ for (const d of defs ?? []) {
1887
+ if (typeof d.name === "string") {
1888
+ typeByName.set(d.name, String(d.type ?? ""));
887
1889
  }
888
1890
  }
889
- return { entityName };
1891
+ return Object.entries(fields)
1892
+ .filter(([k, val]) => {
1893
+ if (!Array.isArray(val) || merge.includes(k) || unmerge.includes(k)) {
1894
+ return false;
1895
+ }
1896
+ const type = typeByName.get(k);
1897
+ return type === undefined ? defs === null : LIST_VALUED_FIELD_TYPES.has(type);
1898
+ })
1899
+ .map(([k]) => k);
1900
+ }
1901
+ /**
1902
+ * Same answer as `_replacedListNames`, for a caller that has no field defs — the
1903
+ * confirm-gate preview, which must name the lists a write would wipe BEFORE the
1904
+ * user approves it. Reads the schema best-effort; a failure degrades to the
1905
+ * value-shape heuristic rather than dropping the warning.
1906
+ */
1907
+ export async function previewReplacedLists(entityName, fields, merge = [], unmerge = []) {
1908
+ let defs = null;
1909
+ try {
1910
+ const found = _extractFields(await makeRequest("GET", `/api/core/schema/${entityName}`));
1911
+ defs = found.length > 0 ? found : null;
1912
+ }
1913
+ catch {
1914
+ defs = null;
1915
+ }
1916
+ return _replacedListNames(defs, fields, merge, unmerge);
890
1917
  }
891
1918
  /**
892
- * Create a new record in any entity. fields_json: JSON object of field values.
1919
+ * Create one record — or a whole BATCH — in any entity.
1920
+ *
1921
+ * fields_json is either a JSON object (one record; response and refusals are
1922
+ * unchanged) or a JSON ARRAY of such objects. The array is the platform's own
1923
+ * batch shape: POST /core/data/:entityName/insert takes "fields | object[] |
1924
+ * true | Array of records to insert" (data.txt:323), so N records are ONE
1925
+ * request — and one schema read validates them all, instead of N of each.
893
1926
  *
894
1927
  * Relation/enum values are shape-checked against the schema first — a bare
895
1928
  * number/string for those fields is refused with guidance, because the
896
- * platform would return 201 and silently store NULL.
1929
+ * platform would return 201 and silently store NULL. A batch is refused as a
1930
+ * unit: if any record is malformed, nothing is inserted.
897
1931
  */
898
1932
  export async function createRecord(entityName, fieldsJson) {
899
- let fields;
1933
+ // Which shape the caller MEANT is decided before parsing, so a single record
1934
+ // is still refused with the exact wording it has always used.
1935
+ const raw = fieldsJson;
1936
+ const looksBatch = typeof raw === "string" ? raw.trimStart().startsWith("[") : Array.isArray(raw);
1937
+ let parsed;
900
1938
  try {
901
- fields = parseJsonParam(fieldsJson, "fields_json", "object");
1939
+ parsed = parseJsonParam(fieldsJson, "fields_json", looksBatch ? "array" : "object");
902
1940
  }
903
1941
  catch (e) {
904
1942
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
905
1943
  }
906
- const v = await _validateRecordWrite(entityName, fields);
1944
+ const many = Array.isArray(parsed);
1945
+ const records = (many ? parsed : [parsed]);
1946
+ if (many && records.length === 0) {
1947
+ return jsonResponse({
1948
+ error: "fields_json is an empty array — nothing to create. Pass one record object, " +
1949
+ 'or an array of them: [{"title": "A"}, {"title": "B"}].',
1950
+ });
1951
+ }
1952
+ const badIndex = records.findIndex((r) => r === null || typeof r !== "object" || Array.isArray(r));
1953
+ if (badIndex !== -1) {
1954
+ return jsonResponse({
1955
+ error: `fields_json[${badIndex}] must be a JSON object of field values — got ` +
1956
+ `${JSON.stringify(records[badIndex] ?? null)}. A batch is an array of record objects.`,
1957
+ });
1958
+ }
1959
+ const rows = records;
1960
+ const v = await _validateRecordWrites(entityName, rows);
907
1961
  if (v.error) {
908
1962
  return v.error;
909
1963
  }
910
- const result = await insertEntity(v.entityName, [fields]);
911
- return jsonResponse(result && result.length ? result[0] : null);
1964
+ // One request for the whole batch (data.txt:323 — `fields` is the array).
1965
+ const result = await insertEntity(v.entityName, rows);
1966
+ if (!many) {
1967
+ return jsonResponse(result && result.length ? result[0] : null);
1968
+ }
1969
+ return jsonResponse({
1970
+ created: result.length,
1971
+ requested: rows.length,
1972
+ entity: v.entityName,
1973
+ records: result,
1974
+ });
1975
+ }
1976
+ /** Parse a merge_json/unmerge_json parameter into a list of field names. */
1977
+ function _parseNameList(raw, param) {
1978
+ if (raw === null || raw === undefined || raw === "") {
1979
+ return [];
1980
+ }
1981
+ const parsed = parseJsonParam(raw, param, "array");
1982
+ const bad = parsed.filter((n) => typeof n !== "string" || !n.trim());
1983
+ if (bad.length > 0) {
1984
+ throw new Error(`Parameter '${param}' must be a JSON array of field NAMES, e.g. ["watchers"] ` +
1985
+ `— got ${jsonResponse(parsed).slice(0, 60)}.`);
1986
+ }
1987
+ return parsed.map((n) => n.trim());
912
1988
  }
913
1989
  /**
914
1990
  * Update a record in any entity. fields_json: JSON object of field values to update.
915
1991
  *
916
1992
  * Relation/enum values are shape-checked against the schema first (see
917
1993
  * create_record) — malformed shapes are refused instead of silently nulled.
918
- * Returns an explicit status: {updated:true, id, entity, changedFields} on
919
- * success, or {updated:false, reason} when the platform reports no change.
1994
+ *
1995
+ * A list-valued field is REPLACED by what you send. merge_json / unmerge_json
1996
+ * (arrays of field names, each of which must also be in fields_json with an
1997
+ * array value) switch those fields to add / remove instead; the pairing is
1998
+ * checked before the request, because a name the platform cannot line up is
1999
+ * ignored there — the list would be replaced and the call would still report
2000
+ * success. A list written without merge/unmerge comes back with an explicit
2001
+ * warning, so "added a watcher" can never read as clean when it wiped the rest.
2002
+ *
2003
+ * Returns {updated:true, id, entity, changedFields[, mergedFields, unmergedFields,
2004
+ * warning]} on success, or {updated:false, reason} when the platform reports no
2005
+ * change.
920
2006
  */
921
- export async function updateRecord(entityName, recordId, fieldsJson) {
2007
+ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson = null, unmergeJson = null) {
922
2008
  let fields;
2009
+ let merge;
2010
+ let unmerge;
923
2011
  try {
924
2012
  fields = parseJsonParam(fieldsJson, "fields_json", "object");
2013
+ merge = _parseNameList(mergeJson, "merge_json");
2014
+ unmerge = _parseNameList(unmergeJson, "unmerge_json");
925
2015
  }
926
2016
  catch (e) {
927
2017
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
928
2018
  }
2019
+ const mergeProblems = mergeListProblems(fields, merge, unmerge);
2020
+ if (mergeProblems.length > 0) {
2021
+ return jsonResponse({
2022
+ error: "Refused: the merge/unmerge lists do not line up with fields_json. Nothing " +
2023
+ "was written — sending this would have REPLACED the list instead of " +
2024
+ "adding to it, and reported success.",
2025
+ problems: mergeProblems,
2026
+ hint: 'merge_json/unmerge_json take field NAMES (e.g. ["watchers"]); each name ' +
2027
+ 'must also appear in fields_json with an array value (e.g. {"watchers": ' +
2028
+ '[{"id": 15}]}), and no name may be in both lists.',
2029
+ });
2030
+ }
929
2031
  const v = await _validateRecordWrite(entityName, fields);
930
2032
  if (v.error) {
931
2033
  return v.error;
932
2034
  }
933
2035
  entityName = v.entityName;
934
- const result = await updateEntity(entityName, recordId, fields);
2036
+ const result = await updateEntity(entityName, recordId, fields, merge, unmerge);
935
2037
  if (!result || (Array.isArray(result) && result.length === 0)) {
936
2038
  return jsonResponse({
937
2039
  updated: false,
@@ -941,13 +2043,28 @@ export async function updateRecord(entityName, recordId, fieldsJson) {
941
2043
  "deleted, or the values matched the stored ones (no-op).",
942
2044
  });
943
2045
  }
944
- return jsonResponse({
2046
+ const out = {
945
2047
  updated: true,
946
2048
  id: recordId,
947
2049
  entity: entityName,
948
2050
  changedFields: Object.keys(fields),
949
- result: Array.isArray(result) && result.length ? result[0] : result,
950
- });
2051
+ };
2052
+ if (merge.length > 0) {
2053
+ out.mergedFields = merge;
2054
+ }
2055
+ if (unmerge.length > 0) {
2056
+ out.unmergedFields = unmerge;
2057
+ }
2058
+ const replacedLists = _replacedListNames(v.defs ?? null, fields, merge, unmerge);
2059
+ if (replacedLists.length > 0) {
2060
+ out.warning =
2061
+ `The ENTIRE list in [${replacedLists.join(", ")}] was REPLACED by the values ` +
2062
+ "sent — items that were stored before and not repeated here are now gone. " +
2063
+ "To add items instead, re-send with merge_json; to remove only the listed " +
2064
+ "items, use unmerge_json.";
2065
+ }
2066
+ out.result = Array.isArray(result) && result.length ? result[0] : result;
2067
+ return jsonResponse(out);
951
2068
  }
952
2069
  /**
953
2070
  * Pull the field list out of an entity schema, tolerant of response shape.
@@ -1109,12 +2226,19 @@ export async function attachFileToRecord(entityName, recordId, filePath, fieldNa
1109
2226
  }
1110
2227
  }
1111
2228
  /**
1112
- * Delete a record (instance) from any entity.
2229
+ * SOFT-delete a record (instance) from any entity: the platform sets deletedAt
2230
+ * and keeps the row, so this is reversible with restoreRecord — it is not a
2231
+ * permanent purge. The record does vanish from normal reads.
2232
+ *
2233
+ * The platform's PERMANENT delete (/core/data/:entityName/delete, data.txt:507
2234
+ * — "the rows leave the table and cannot be restored") is deliberately not
2235
+ * wired up here; there is no undo for it. Do not add one.
1113
2236
  *
1114
- * Removes a single instance, NOT the entity/schema. By design this module is
1115
- * add-only at the schema level (create_entity / add_field / add_enum_values) —
1116
- * there is no update-entity or remove-field operation, so fields can only be
1117
- * removed manually via the Suppa UI. Do not add one here.
2237
+ * Removes a single instance, NOT the entity/schema. At the schema level this
2238
+ * module creates (create_entity / add_field / add_enum_values) and edits fields
2239
+ * (update_field — builder.txt:344, within the endpoint's own restrictions), but
2240
+ * REMOVES nothing: there is no remove-fields or remove-entity call here, so a
2241
+ * field can only be dropped via the Suppa UI. Do not add one.
1118
2242
  */
1119
2243
  export async function deleteRecord(entityName, recordId) {
1120
2244
  // Verify the entity exists (best-effort) so a typo'd name gives a clear error
@@ -1126,6 +2250,63 @@ export async function deleteRecord(entityName, recordId) {
1126
2250
  const result = await removeEntity(ent.name, [makeFilter("id", recordId)]);
1127
2251
  return jsonResponse(result);
1128
2252
  }
2253
+ /**
2254
+ * UNDO a soft delete: clears deletedAt on one record so it returns to every
2255
+ * normal read. The counterpart of deleteRecord (/remove).
2256
+ *
2257
+ * The platform scopes the operation to soft-deleted rows itself (it adds
2258
+ * `deletedAt IS NOT NULL` to the conditions, data.txt:538), so restoring a
2259
+ * record that was never removed is a no-op rather than a mutation — an empty
2260
+ * result therefore means "nothing was deleted under that id", not a failure.
2261
+ */
2262
+ export async function restoreRecord(entityName, recordId) {
2263
+ const ent = await _resolveEntity(entityName);
2264
+ if (ent.error) {
2265
+ return ent.error;
2266
+ }
2267
+ const result = await restoreEntity(ent.name, [makeFilter("id", recordId)]);
2268
+ const rows = Array.isArray(result) ? result : result ? [result] : [];
2269
+ const out = {
2270
+ restored: rows.length > 0,
2271
+ entity: ent.name,
2272
+ record_id: Math.trunc(recordId),
2273
+ records: rows,
2274
+ };
2275
+ if (rows.length === 0) {
2276
+ out.note =
2277
+ `Nothing to restore: no SOFT-DELETED record ${Math.trunc(recordId)} in ` +
2278
+ `'${ent.name}'. Restore only touches rows with deletedAt set, so either the ` +
2279
+ "record is already active, it never existed, or it was purged. Check with " +
2280
+ "suppa_search_records(deleted_scope='deleted').";
2281
+ }
2282
+ return jsonResponse(out);
2283
+ }
2284
+ /**
2285
+ * Duplicate a record server-side, optionally with its attachments.
2286
+ *
2287
+ * fields_json overrides values on the copy (data.txt:454 — "fields is applied on
2288
+ * top of the copied values"), and is schema-validated exactly like createRecord
2289
+ * so an override the platform would silently drop is refused first.
2290
+ *
2291
+ * copy_files is the only way this server can duplicate a record's attachments:
2292
+ * attachFileToRecord uploads from a LOCAL path, which an agent holding only the
2293
+ * platform copy does not have.
2294
+ */
2295
+ export async function copyRecord(entityName, recordId, fieldsJson = "{}", copyFiles = false, copyRelatedEntities = false) {
2296
+ let fields;
2297
+ try {
2298
+ fields = parseJsonParam(fieldsJson, "fields_json", "object");
2299
+ }
2300
+ catch (e) {
2301
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
2302
+ }
2303
+ const v = await _validateRecordWrite(entityName, fields);
2304
+ if (v.error) {
2305
+ return v.error;
2306
+ }
2307
+ const result = await copyEntity(v.entityName, Math.trunc(recordId), fields, copyFiles, copyRelatedEntities);
2308
+ return jsonResponse(result);
2309
+ }
1129
2310
  // ---------------------------------------------------------------------------
1130
2311
  // helpers
1131
2312
  // ---------------------------------------------------------------------------