suppa-mcp-2 1.2.4 → 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, mergeListProblems, } 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",
@@ -74,6 +85,261 @@ export function defaultValueApplies(fieldType, unique = false) {
74
85
  return !unique && !RELATION_LIKE_FIELD_TYPES.includes(fieldType);
75
86
  }
76
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
+ }
342
+ // ---------------------------------------------------------------------------
77
343
  // Multi-language titles
78
344
  // ---------------------------------------------------------------------------
79
345
  //
@@ -222,16 +488,40 @@ export async function describeEntity(entityName) {
222
488
  const result = await makeRequest("GET", `/api/core/schema/${entityName}`);
223
489
  return jsonResponse(result);
224
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
+ }
225
509
  /**
226
510
  * Search records of any entity with filters.
227
511
  * filters_json: JSON array of filter objects [{field, value, comparator}].
228
512
  * fields_json: JSON object specifying which fields to return.
229
513
  * order_by: 'field:direction' (e.g. 'createdAt:desc').
230
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).
231
517
  *
232
518
  * Returns {"records": [...], "returned": N, "has_more": bool, "next_offset": int|null}.
233
519
  */
234
- 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
+ }
235
525
  let filters;
236
526
  let fields;
237
527
  try {
@@ -243,8 +533,14 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
243
533
  }
244
534
  // Tolerate common near-miss shapes instead of erroring:
245
535
  // a single filter object -> one-element list; a list of field names -> projection.
246
- if (filters !== null && typeof filters === "object" && !Array.isArray(filters)) {
247
- 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) });
248
544
  }
249
545
  if (Array.isArray(fields)) {
250
546
  const proj = {};
@@ -266,17 +562,162 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
266
562
  // Fetch one extra row so the agent learns whether another page exists.
267
563
  // Cap at 500/page: larger responses blow the model's context — page instead.
268
564
  limit = Math.max(1, Math.min(limit, 500));
269
- 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
+ }
270
590
  const hasMore = rows.length > limit;
271
- return jsonResponse({
591
+ const out = {
272
592
  records: rows.slice(0, limit),
273
593
  returned: Math.min(rows.length, limit),
274
594
  has_more: hasMore,
275
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.",
276
708
  });
277
709
  }
278
- /** Get a single record of any entity by its numeric id. */
279
- 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
+ }
280
721
  let fields;
281
722
  try {
282
723
  fields = parseJsonParam(fieldsJson, "fields_json", "object");
@@ -284,10 +725,14 @@ export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}
284
725
  catch (e) {
285
726
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
286
727
  }
287
- const result = await selectEntity(entityName, [makeFilter("id", recordId)], fields);
728
+ const result = await selectEntity(entityName, [makeFilter("id", recordId)], fields, scope.scope, includeDeletedRelations);
288
729
  if (result === null) {
289
730
  return jsonResponse({
290
- 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
+ : ""),
291
736
  });
292
737
  }
293
738
  return jsonResponse(result);
@@ -300,8 +745,24 @@ export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}
300
745
  * and the entity's titleFieldName resolves to a real field. Pass
301
746
  * auto_title_field=False when the caller adds its own fields (e.g. migration),
302
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).
303
752
  */
304
- 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
+ }
305
766
  const titleObj = await _expandTitle(title, name);
306
767
  const body = {
307
768
  name,
@@ -309,6 +770,9 @@ export async function createEntity(name, title, titleFieldName = "title", autoTi
309
770
  titleFieldName,
310
771
  fields: [],
311
772
  };
773
+ if (entityOptions) {
774
+ body.options = entityOptions; // builder.txt:113
775
+ }
312
776
  const result = await makeRequest("POST", "/api/core/builder/create-entity", body);
313
777
  let titleFieldResult = null;
314
778
  let representative = null;
@@ -548,6 +1012,105 @@ export async function setTitleField(entityName, fieldName) {
548
1012
  note,
549
1013
  });
550
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
+ }
551
1114
  /**
552
1115
  * Pre-flight a relation field against the LIVE schema so we never create a
553
1116
  * broken or duplicate relation — either of which corrupts the entity:
@@ -624,8 +1187,9 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
624
1187
  * Add a field to an existing entity.
625
1188
  *
626
1189
  * field_type: a real Suppa 2.0 type — text, numeric, integer, serial, boolean,
627
- * timestamp, json, uuid, multi-language, icon, enum, multi-enum, file, multi-file,
628
- * 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).
629
1193
  * There is NO date/datetime/richtext/email/url/phone/string type:
630
1194
  * - date-only → field_type='timestamp' with sub_type='date'
631
1195
  * - localized → field_type='multi-language'
@@ -643,9 +1207,17 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
643
1207
  * enum and multi-enum, file and multi-file, and any unique field. The call is
644
1208
  * refused before any request if an applicable default is missing; no default is
645
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.
646
1218
  */
647
1219
  export async function addField(entityName, fieldName, fieldType, title, opts = {}) {
648
- 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, } = 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;
649
1221
  // The platform has no relation type literally called "relation"; a foreign
650
1222
  // key is "many-to-one" with the target entity in `relationTarget`.
651
1223
  let resolvedType = fieldType === "relation" ? "many-to-one" : fieldType;
@@ -693,6 +1265,24 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
693
1265
  "with suppa_add_enum_values.",
694
1266
  });
695
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
+ }
696
1286
  // NOT NULL needs a default — but ONLY where a default is applicable at all.
697
1287
  // builder.txt:43 (docs/superpowers/specs/captures/api-entity-builder-builder.txt)
698
1288
  // rules defaultValue out for relations, enums and unique fields; on everything
@@ -782,6 +1372,11 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
782
1372
  if (enumName) {
783
1373
  fieldDef.enumName = enumName;
784
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
+ }
785
1380
  // Correct endpoint is /builder/{Entity}/add-fields and the body is the bare
786
1381
  // array of field defs (the old /builder/add-fields with an {entityName,fields}
787
1382
  // wrapper 404s).
@@ -790,6 +1385,217 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
790
1385
  ]);
791
1386
  return jsonResponse(result);
792
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
+ }
793
1599
  /**
794
1600
  * Add values to an enum (lookup table). values: comma-separated list of values to add.
795
1601
  *
@@ -839,10 +1645,21 @@ export async function listFieldTypes() {
839
1645
  },
840
1646
  { type: "serial", description: "Auto-incrementing integer" },
841
1647
  { type: "boolean", description: "True/false" },
842
- { 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
+ },
843
1652
  { type: "multi-language", description: "Localized text object ({en, uk, ...})" },
844
1653
  { type: "json", description: "JSON object/array" },
845
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
+ },
846
1663
  { type: "icon", description: "Icon reference" },
847
1664
  { type: "enum", description: "Single lookup value (requires enum_name)" },
848
1665
  { type: "multi-enum", description: "Multiple lookup values" },
@@ -981,6 +1798,15 @@ async function _resolveEntity(name) {
981
1798
  * (possibly case-corrected) entity name and an error string when refused.
982
1799
  */
983
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) {
984
1810
  const ent = await _resolveEntity(entityName);
985
1811
  if (ent.error) {
986
1812
  return { entityName, error: ent.error };
@@ -995,32 +1821,40 @@ async function _validateRecordWrite(entityName, fields) {
995
1821
  defs = null; // unreadable → can't validate fields; proceed
996
1822
  }
997
1823
  if (defs && defs.length > 0) {
1824
+ const many = records.length > 1;
998
1825
  const fieldNames = new Set(defs.map((f) => f.name).filter((n) => Boolean(n)));
999
- 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
+ ];
1000
1829
  if (unknown.length > 0) {
1001
- return {
1002
- entityName,
1003
- error: jsonResponse({
1004
- error: `Refused: field(s) [${unknown.join(", ")}] do not exist on '${entityName}'. ` +
1005
- "The platform silently drops unknown keys, so this would create a record missing " +
1006
- "that data (a 'broken' entity). Use only real fields (see valid_fields), or add " +
1007
- "the field first with suppa_add_field.",
1008
- unknown_fields: unknown,
1009
- valid_fields: [...fieldNames].sort(),
1010
- }),
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(),
1011
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) };
1012
1845
  }
1013
- const problems = _shapeProblemsFromDefs(defs, fields);
1846
+ const problems = records.flatMap((r, i) => _shapeProblemsFromDefs(defs, r).map((p) => many ? `record[${i}]: ${p}` : p));
1014
1847
  if (problems.length > 0) {
1015
- return {
1016
- entityName,
1017
- error: jsonResponse({
1018
- error: "Refused: these values would be SILENTLY stored as NULL by the platform.",
1019
- problems,
1020
- hint: "Look up ids via suppa_search_records (Enums for enum values; the " +
1021
- 'target entity for relations), then re-send as {"id": N}.',
1022
- }),
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}.',
1023
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) };
1024
1858
  }
1025
1859
  }
1026
1860
  // The defs travel back so the caller does not re-read the schema to decide
@@ -1082,26 +1916,62 @@ export async function previewReplacedLists(entityName, fields, merge = [], unmer
1082
1916
  return _replacedListNames(defs, fields, merge, unmerge);
1083
1917
  }
1084
1918
  /**
1085
- * 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.
1086
1926
  *
1087
1927
  * Relation/enum values are shape-checked against the schema first — a bare
1088
1928
  * number/string for those fields is refused with guidance, because the
1089
- * 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.
1090
1931
  */
1091
1932
  export async function createRecord(entityName, fieldsJson) {
1092
- 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;
1093
1938
  try {
1094
- fields = parseJsonParam(fieldsJson, "fields_json", "object");
1939
+ parsed = parseJsonParam(fieldsJson, "fields_json", looksBatch ? "array" : "object");
1095
1940
  }
1096
1941
  catch (e) {
1097
1942
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
1098
1943
  }
1099
- 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);
1100
1961
  if (v.error) {
1101
1962
  return v.error;
1102
1963
  }
1103
- const result = await insertEntity(v.entityName, [fields]);
1104
- 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
+ });
1105
1975
  }
1106
1976
  /** Parse a merge_json/unmerge_json parameter into a list of field names. */
1107
1977
  function _parseNameList(raw, param) {
@@ -1357,13 +2227,18 @@ export async function attachFileToRecord(entityName, recordId, filePath, fieldNa
1357
2227
  }
1358
2228
  /**
1359
2229
  * SOFT-delete a record (instance) from any entity: the platform sets deletedAt
1360
- * and keeps the row, so this is reversible (restore is UI-only until 1.3.0) —
1361
- * it is not a permanent purge. The record does vanish from normal reads.
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.
1362
2236
  *
1363
- * Removes a single instance, NOT the entity/schema. By design this module is
1364
- * add-only at the schema level (create_entity / add_field / add_enum_values) —
1365
- * there is no update-entity or remove-field operation, so fields can only be
1366
- * 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.
1367
2242
  */
1368
2243
  export async function deleteRecord(entityName, recordId) {
1369
2244
  // Verify the entity exists (best-effort) so a typo'd name gives a clear error
@@ -1375,6 +2250,63 @@ export async function deleteRecord(entityName, recordId) {
1375
2250
  const result = await removeEntity(ent.name, [makeFilter("id", recordId)]);
1376
2251
  return jsonResponse(result);
1377
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
+ }
1378
2310
  // ---------------------------------------------------------------------------
1379
2311
  // helpers
1380
2312
  // ---------------------------------------------------------------------------