@revenexx/app-sdk 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -219,7 +219,47 @@ mountCrud(app, db.locales, {
219
219
  ```
220
220
 
221
221
  Options: `only: ['list', 'get']` restricts the mounted routes; `defaultLimit` /
222
- `maxLimit` tune pagination bounds (defaults 50 / 200).
222
+ `maxLimit` tune pagination bounds (defaults 50 / 200); `readOnly` names columns the
223
+ App keeps itself (see below).
224
+
225
+ **A record read and sent back is an edit.** An edit form reads a record, changes a
226
+ field and sends the whole row back with `PUT`. The row carries fields no write may
227
+ set — the key, `tenant_id`, `created_at`, `updated_at`, stored generated columns,
228
+ the trash columns — and the data plane refused them (`id` / `tenant_id` have no
229
+ UPDATE grant and answered `401`; Postgres refuses any value for a generated
230
+ column). `PUT` now compares them with the row it has just read:
231
+
232
+ | field in the body | says what the record says | says something else |
233
+ |---|---|---|
234
+ | the primary key | dropped (also `null` / `''`) | `400 store_owned_field` |
235
+ | `tenant_id` | dropped (also `null` / `''`) | `400 store_owned_field` |
236
+ | `updated_at` | dropped — Baseline stamps it | dropped; written only when it is the only field (a touch) |
237
+ | `created_at` | dropped (same instant, any offset) | written, as before (a correction) |
238
+ | a `generated` column | dropped | dropped — Postgres computes it |
239
+ | a column in `readOnly` | dropped | `400 read_only_field` |
240
+ | a trash column (`trash: true`), `purge_at` | `null` dropped while the record holds `null` | a value, or `null` on a record in the trash: `400 read_only_field` (`purge_at` is written) |
241
+
242
+ A `readOnly` column compares by its declared type: a numeric column by number,
243
+ exactly (`"5.000"` is `5`, a big integer is never rounded), any other as text
244
+ (`"007"` is not `"7"`), a document regardless of key order (`{}` is `[]`).
245
+
246
+ A refusal names the field in `details.field` (and `details.fields`). When nothing is
247
+ left, the answer is `200` with the record as it stands — nothing is written and no
248
+ update event fires. A body sent as `{}` is still `400 empty_update`. Under a parent,
249
+ the parent column in the body is not a change of its own.
250
+
251
+ ```js
252
+ mountCrud(app, db.orders, {
253
+ path: '/orders',
254
+ columns: ENTITIES.orders.columns,
255
+ readOnly: ['status', 'number'], // the App's own: a PUT may repeat them, never change them
256
+ });
257
+ ```
258
+
259
+ `POST` refuses a value for a key the store assigns (a `serial` key, or one with
260
+ `default: gen_random_uuid()`) and a `tenant_id` naming another tenant than the
261
+ request's, both with `400 store_owned_field`; the request's tenant and `null` are
262
+ dropped. A key the caller assigns (a text key without default) is written as before.
223
263
 
224
264
  **List query keys are checked.** A list accepts the columns in `columns`, the
225
265
  reserved keys `limit`, `offset`, `order` (exported as `RESERVED_LIST_QUERY_KEYS`)
@@ -253,9 +293,11 @@ flag is only ever added; `trash: false` does not switch off what the client says
253
293
  key you claim in `queryParams` stays yours and is not a filter.
254
294
 
255
295
  On a `trash: true` entity, `POST` / `PUT` refuse a body that sets a trash column
256
- (`deleted_at`, `deleted_by`, `deleted_by_id`, `trash_batch`, `purge_blocked_reason`,
257
- `null` included) with `400 read_only_field`, naming them in `details.fields`. Only the
258
- trash routes (`mountTrash`) write them. `external_id` is written like any column.
296
+ (`deleted_at`, `deleted_by`, `deleted_by_id`, `trash_batch`, `purge_blocked_reason`)
297
+ to a value with `400 read_only_field`, naming them in `details.fields`. Sent as `null`
298
+ they are dropped when the record holds `null` too — what a live record reads (from
299
+ 2.2); `null` to a record in the trash would restore it, and is still refused. Only the trash routes
300
+ (`mountTrash`) write them. `external_id` is written like any column.
259
301
 
260
302
  Without `columns`, only the reserved and declared keys and the columns the flags
261
303
  add are accepted. A list
@@ -367,6 +409,24 @@ The empty-patch rule lives in the data client, not in `mountCrud`, so it holds
367
409
  for hand-written route handlers too. It is enforced before the request leaves
368
410
  the App — an empty patch costs no round trip.
369
411
 
412
+ ### An update of a record sent back writes the change it makes
413
+
414
+ `update` and `updateIf` apply the round-trip rules of `PUT` (see *CRUD in one
415
+ line*) to every patch, so a hand-written handler that writes `db.x.update(id,
416
+ c.body)` gets them too: a key or tenant that repeats the record is dropped, another
417
+ one is `400 store_owned_field`; `updated_at` is dropped unless it is the only field
418
+ (`update(id, { updated_at: now() })` is a touch, and still writes; a key or tenant
419
+ that repeats the record does not count); `created_at` is
420
+ dropped when it names the stored instant and written otherwise; a `generated`
421
+ column is always dropped. The stored record is read once, and only when a rule
422
+ needs it. When nothing is left nothing is written: `update` answers the record,
423
+ `updateIf` the record while its condition holds, else `null`. The trash columns are
424
+ written as given — the trash routes write them through the client.
425
+
426
+ The `mock` adapter refuses an update naming the key or `tenant_id` — which only a
427
+ write past the client can still carry — with the `401` production answers for it
428
+ (SQLSTATE 42501), so a test cannot pass on a write the grants refuse.
429
+
370
430
  ### A write names only the columns the App declares
371
431
 
372
432
  `create`, `update` and `updateIf` check every key of the row against the
@@ -391,7 +451,8 @@ columns it was generated against.
391
451
  - Only the top level is checked; a `jsonb` column takes any document.
392
452
  - `tenant_id` is on every table without being declared and is accepted.
393
453
  - The system columns the App declares in `schema.json` (`id`, `created_at`,
394
- `updated_at`, …) are columns like any other.
454
+ `updated_at`, …) are columns like any other; an update leaves out the ones
455
+ that repeat the record (see above).
395
456
  - The columns a schema flag adds count as declared, whether or not the App
396
457
  declares them as well: `trash: true` adds `deleted_at`, `deleted_by`,
397
458
  `deleted_by_id`, `trash_batch` and `purge_blocked_reason`, `external_id: true`
@@ -441,7 +502,8 @@ on the wording:
441
502
  | `undefined_condition` | 400 | a `where` entry left `undefined`, on any read or `updateIf` |
442
503
  | `unknown_filter`, `unsupported_filter_operator`, `invalid_value` | 400 | a mounted list's querystring |
443
504
  | `missing_parameter` | 400 | a `mountCrud` route without its path parameter |
444
- | `read_only_field` | 400 | `POST` / `PUT` on a mounted `trash: true` entity setting a trash column |
505
+ | `read_only_field` | 400 | `POST` / `PUT` on a mounted `trash: true` entity setting a trash column; `PUT` changing a `readOnly` column |
506
+ | `store_owned_field` | 400 | an update naming another key or tenant than the record's; `POST` naming a key the store assigns or another tenant |
445
507
  | `trash_blocked`, `delete_blocked`, `already_in_trash`, `not_in_trash`, `parent_in_trash` | 409 | `mountTrash` routes |
446
508
  | `not_permitted` | 403 | `mountTrash`'s final delete when `canDeleteForGood` refuses |
447
509
  | `no_route` / `method_not_allowed` | 404 / 405 | the router |
@@ -494,6 +494,165 @@ function assertKnownFields(entity, data) {
494
494
  { code: "unknown_field" }
495
495
  );
496
496
  }
497
+ var STORE_OWNED_FIELD = "store_owned_field";
498
+ var READ_ONLY_FIELD = "read_only_field";
499
+ var STORE_STAMPED_COLUMNS = ["updated_at"];
500
+ var CREATION_STAMP_COLUMNS = ["created_at"];
501
+ var TRASH_ROUND_TRIP_COLUMNS = [...TRASH_FLAG_COLUMNS, "purge_at"];
502
+ var RecordGone = class extends Error {
503
+ constructor() {
504
+ super("the record is not there");
505
+ this.name = "RecordGone";
506
+ }
507
+ };
508
+ var noValue = (v) => v === null || v === void 0 || v === "";
509
+ var has = (row, key) => Object.prototype.hasOwnProperty.call(row, key) && row[key] !== void 0;
510
+ var nullish = (v) => v === null || v === void 0;
511
+ var DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?$/;
512
+ var NUMERIC_TYPE = /^(?:(?:small|big)?int(?:eger)?|int[248]|(?:big|small)?serial|serial[248]|numeric|decimal|real|double|float[48]?)\b/i;
513
+ var INSTANT = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
514
+ function sameInstant(a, b) {
515
+ if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);
516
+ if (String(a) === String(b)) return true;
517
+ if (typeof a !== "string" || typeof b !== "string" || !INSTANT.test(a) || !INSTANT.test(b)) return false;
518
+ const x = Date.parse(a);
519
+ const y = Date.parse(b);
520
+ return Number.isFinite(x) && Number.isFinite(y) && x === y;
521
+ }
522
+ function decimal(v) {
523
+ const text = typeof v === "number" ? Number.isFinite(v) ? String(v) : "" : typeof v === "string" ? v.trim() : "";
524
+ const m = DECIMAL.exec(text);
525
+ if (!m || m[2] === "" && (m[3] ?? "") === "") return null;
526
+ const whole = m[2].replace(/^0+(?=\d)/, "") || "0";
527
+ const fraction = (m[3] ?? "").replace(/0+$/, "");
528
+ const digits = fraction ? `${whole}.${fraction}` : whole;
529
+ return digits === "0" ? "0" : `${m[1] === "-" ? "-" : ""}${digits}`;
530
+ }
531
+ function isNumericType(type) {
532
+ return NUMERIC_TYPE.test(String(type ?? "").trim());
533
+ }
534
+ function sameValue(a, b, type) {
535
+ if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);
536
+ if (typeof a === "object" || typeof b === "object") return canonical(a) === canonical(b);
537
+ if (String(a) === String(b)) return true;
538
+ if (isNumericType(type)) {
539
+ const x = decimal(a);
540
+ const y = decimal(b);
541
+ if (x !== null && y !== null) return x === y;
542
+ const fx = Number(a);
543
+ const fy = Number(b);
544
+ return Number.isFinite(fx) && Number.isFinite(fy) && fx === fy;
545
+ }
546
+ return sameInstant(a, b);
547
+ }
548
+ function canonical(v) {
549
+ return JSON.stringify(v, (_k, value) => {
550
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
551
+ const keys = Object.keys(value);
552
+ return keys.length === 0 ? [] : Object.fromEntries(keys.sort().map((k) => [k, value[k]]));
553
+ });
554
+ }
555
+ function pkOf(entity) {
556
+ return entity?.pk || "id";
557
+ }
558
+ function declares(entity, column) {
559
+ const columns = entity.columns;
560
+ return !columns || Object.keys(columns).length === 0 || Object.prototype.hasOwnProperty.call(columns, column);
561
+ }
562
+ function generatedColumns(entity) {
563
+ return Object.entries(entity?.columns ?? {}).filter(([, def]) => !!def && typeof def === "object" && !!def.generated).map(([name]) => name).sort();
564
+ }
565
+ function storeAssignsKey(entity) {
566
+ const def = entity?.columns?.[pkOf(entity)];
567
+ if (!def || typeof def !== "object") return false;
568
+ if (/^(big)?serial\b/i.test(String(def.type ?? ""))) return true;
569
+ return /gen_random_uuid/i.test(String(def.default ?? ""));
570
+ }
571
+ var storeOwned = (field, message) => badRequest(message, { field, fields: [field] }, { code: STORE_OWNED_FIELD });
572
+ var readOnly = (field, what) => badRequest(
573
+ `'${field}' is ${what} and cannot be changed by a write \u2014 send it as read, or leave it out`,
574
+ { field, fields: [field] },
575
+ { code: READ_ONLY_FIELD }
576
+ );
577
+ var TENANT_CHANGED = "'tenant_id' cannot be changed: a record stays in the tenant it was written under";
578
+ async function roundTripped(entity, id, patch, options) {
579
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) return patch;
580
+ const out = { ...patch };
581
+ let loaded = false;
582
+ let current = null;
583
+ const stored = async () => {
584
+ if (!loaded) {
585
+ current = await options.stored();
586
+ loaded = true;
587
+ }
588
+ if (!current) throw new RecordGone();
589
+ return current;
590
+ };
591
+ const pk = pkOf(entity);
592
+ if (has(out, pk)) {
593
+ if (!noValue(out[pk]) && String(out[pk]) !== String(id)) {
594
+ throw storeOwned(pk, `'${pk}' cannot be changed: the record is '${String(id)}'`);
595
+ }
596
+ delete out[pk];
597
+ }
598
+ if (has(out, "tenant_id")) {
599
+ if (!noValue(out.tenant_id)) {
600
+ const tenant = (await stored()).tenant_id;
601
+ if (!noValue(tenant) && String(out.tenant_id) !== String(tenant)) throw storeOwned("tenant_id", TENANT_CHANGED);
602
+ }
603
+ delete out.tenant_id;
604
+ }
605
+ const left = updateFields(out);
606
+ const touch = left.length === 1 && STORE_STAMPED_COLUMNS.includes(left[0]);
607
+ for (const field of STORE_STAMPED_COLUMNS) {
608
+ if (!touch && has(out, field) && declares(entity, field)) delete out[field];
609
+ }
610
+ for (const field of CREATION_STAMP_COLUMNS) {
611
+ if (!has(out, field) || !declares(entity, field)) continue;
612
+ if (sameInstant(out[field], (await stored())[field])) delete out[field];
613
+ }
614
+ const generated = generatedColumns(entity);
615
+ for (const field of generated) delete out[field];
616
+ for (const field of [...new Set(options.readOnly ?? [])].sort()) {
617
+ if (!has(out, field) || generated.includes(field)) continue;
618
+ const type = entity.columns?.[field]?.type;
619
+ if (!sameValue(out[field], (await stored())[field], type)) throw readOnly(field, "kept by the app");
620
+ delete out[field];
621
+ }
622
+ return out;
623
+ }
624
+ function createdFields(entity, body, tenant) {
625
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
626
+ const out = { ...body };
627
+ const pk = pkOf(entity);
628
+ if (has(out, pk) && storeAssignsKey(entity)) {
629
+ if (!noValue(out[pk])) throw storeOwned(pk, `'${pk}' is assigned by the store and cannot be sent on a create`);
630
+ delete out[pk];
631
+ }
632
+ if (has(out, "tenant_id")) {
633
+ if (!noValue(out.tenant_id) && !noValue(tenant) && String(out.tenant_id) !== String(tenant)) {
634
+ throw storeOwned("tenant_id", "'tenant_id' is the tenant of the request and cannot name another");
635
+ }
636
+ delete out.tenant_id;
637
+ }
638
+ return out;
639
+ }
640
+ function withoutNullTrash(body) {
641
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
642
+ const row = body;
643
+ if (!TRASH_ROUND_TRIP_COLUMNS.some((k) => Object.prototype.hasOwnProperty.call(row, k) && row[k] === null)) return body;
644
+ const out = { ...row };
645
+ for (const k of TRASH_ROUND_TRIP_COLUMNS) if (out[k] === null) delete out[k];
646
+ return out;
647
+ }
648
+ function trashRoundTripped(body, stored) {
649
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
650
+ const out = { ...body };
651
+ for (const k of TRASH_ROUND_TRIP_COLUMNS) {
652
+ if (Object.prototype.hasOwnProperty.call(out, k) && out[k] === null && nullish(stored[k])) delete out[k];
653
+ }
654
+ return out;
655
+ }
497
656
 
498
657
  // src/backdating.ts
499
658
  var MAX_MONTHS_BACK = 24;
@@ -649,6 +808,12 @@ export {
649
808
  bulkRecords,
650
809
  oneRecordRefusal,
651
810
  assertKnownFields,
811
+ RecordGone,
812
+ pkOf,
813
+ roundTripped,
814
+ createdFields,
815
+ withoutNullTrash,
816
+ trashRoundTripped,
652
817
  DEFAULT_GATEWAY_ENDPOINT,
653
818
  DEFAULT_SETTINGS_TTL_MS,
654
819
  DEFAULT_SETTINGS_ERROR_TTL_MS,
@@ -668,4 +833,4 @@ export {
668
833
  backdatingFields,
669
834
  backdatingDb
670
835
  };
671
- //# sourceMappingURL=chunk-TLWWVUJ4.js.map
836
+ //# sourceMappingURL=chunk-ZTTYOJYU.js.map