@revenexx/app-sdk 2.0.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
@@ -67,6 +67,22 @@ await db.markets.list({
67
67
 
68
68
  Operators: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `like`, `ilike`, `in`, `is`.
69
69
 
70
+ ### Bulk create
71
+
72
+ `create` takes one record. `createMany` takes a list and inserts it in one request,
73
+ answering the created rows in order:
74
+
75
+ ```js
76
+ await db.segment_members.createMany(rows); // one POST, every row checked first
77
+ ```
78
+
79
+ Every record is checked like one create, and all records name the same fields
80
+ (PostgREST refuses an array whose objects differ); a refusal names the record in
81
+ `details.index`. An empty list is `400 empty_create`. On the mock, a primary key twice
82
+ in the list or one already stored is `409 unique_violation` and nothing is stored, as
83
+ in Postgres. `createMany` needs the `create` permission. Because it is its own call, a
84
+ handler that writes its request body with `create(c.body)` stays a one-record route.
85
+
70
86
  ### Conditional updates
71
87
 
72
88
  `update` writes by id, whatever state the row is in. A state transition that
@@ -127,7 +143,7 @@ catch permission gaps before deploy.
127
143
  ### Custom adapters
128
144
 
129
145
  The adapter is a small interface (`list/get/create/update/remove`, optional
130
- `page` and `updateIf`). Register a new backend before constructing the client:
146
+ `page`, `updateIf` and `createMany`). Register a new backend before constructing the client:
131
147
 
132
148
  ```js
133
149
  const { registerAdapter, createClient } = require('@revenexx/app-sdk');
@@ -203,7 +219,47 @@ mountCrud(app, db.locales, {
203
219
  ```
204
220
 
205
221
  Options: `only: ['list', 'get']` restricts the mounted routes; `defaultLimit` /
206
- `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.
207
263
 
208
264
  **List query keys are checked.** A list accepts the columns in `columns`, the
209
265
  reserved keys `limit`, `offset`, `order` (exported as `RESERVED_LIST_QUERY_KEYS`)
@@ -237,9 +293,11 @@ flag is only ever added; `trash: false` does not switch off what the client says
237
293
  key you claim in `queryParams` stays yours and is not a filter.
238
294
 
239
295
  On a `trash: true` entity, `POST` / `PUT` refuse a body that sets a trash column
240
- (`deleted_at`, `deleted_by`, `deleted_by_id`, `trash_batch`, `purge_blocked_reason`,
241
- `null` included) with `400 read_only_field`, naming them in `details.fields`. Only the
242
- 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.
243
301
 
244
302
  Without `columns`, only the reserved and declared keys and the columns the flags
245
303
  add are accepted. A list
@@ -351,6 +409,24 @@ The empty-patch rule lives in the data client, not in `mountCrud`, so it holds
351
409
  for hand-written route handlers too. It is enforced before the request leaves
352
410
  the App — an empty patch costs no round trip.
353
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
+
354
430
  ### A write names only the columns the App declares
355
431
 
356
432
  `create`, `update` and `updateIf` check every key of the row against the
@@ -375,7 +451,8 @@ columns it was generated against.
375
451
  - Only the top level is checked; a `jsonb` column takes any document.
376
452
  - `tenant_id` is on every table without being declared and is accepted.
377
453
  - The system columns the App declares in `schema.json` (`id`, `created_at`,
378
- `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).
379
456
  - The columns a schema flag adds count as declared, whether or not the App
380
457
  declares them as well: `trash: true` adds `deleted_at`, `deleted_by`,
381
458
  `deleted_by_id`, `trash_batch` and `purge_blocked_reason`, `external_id: true`
@@ -425,7 +502,8 @@ on the wording:
425
502
  | `undefined_condition` | 400 | a `where` entry left `undefined`, on any read or `updateIf` |
426
503
  | `unknown_filter`, `unsupported_filter_operator`, `invalid_value` | 400 | a mounted list's querystring |
427
504
  | `missing_parameter` | 400 | a `mountCrud` route without its path parameter |
428
- | `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 |
429
507
  | `trash_blocked`, `delete_blocked`, `already_in_trash`, `not_in_trash`, `parent_in_trash` | 409 | `mountTrash` routes |
430
508
  | `not_permitted` | 403 | `mountTrash`'s final delete when `canDeleteForGood` refuses |
431
509
  | `no_route` / `method_not_allowed` | 404 / 405 | the router |
@@ -445,6 +445,41 @@ function describedEntity(repo) {
445
445
  if (!repo || typeof repo !== "object") return void 0;
446
446
  return repo[ENTITY_DESCRIPTOR];
447
447
  }
448
+ var MANY_RECORDS_MESSAGE = "createMany takes a list of records";
449
+ function bulkRecords(entity, data) {
450
+ if (Array.isArray(data) && data.length === 0) throw badRequest(EMPTY_CREATE_MESSAGE, void 0, { code: "empty_create" });
451
+ if (!isList(data)) throw badRequest(MANY_RECORDS_MESSAGE, void 0, { code: "bad_request" });
452
+ const records = Array.isArray(data) ? data : Object.keys(data).sort((a, b) => Number(a) - Number(b)).map((k) => data[k]);
453
+ let shape;
454
+ records.forEach((record, index) => {
455
+ if (!record || typeof record !== "object" || isList(record)) {
456
+ throw badRequest(`record ${index} of a bulk create is not an object \u2014 each element is one record`, { index }, { code: "bad_request" });
457
+ }
458
+ const fields = updateFields(record);
459
+ if (fields.length === 0) {
460
+ throw badRequest(`record ${index} of a bulk create has no field \u2014 ${EMPTY_CREATE_MESSAGE}`, { index }, { code: "empty_create" });
461
+ }
462
+ const unknown = unknownFields(entity, record);
463
+ if (unknown.length > 0) {
464
+ const quoted = unknown.map((k) => `'${k}'`).join(", ");
465
+ throw badRequest(
466
+ `unknown field${unknown.length > 1 ? "s" : ""} ${quoted} in record ${index} \u2014 not a column of '${entity.name}'. A field that cannot be written is refused rather than dropped; see details.allowed.`,
467
+ { index, unknown, allowed: writableColumns(entity) },
468
+ { code: "unknown_field" }
469
+ );
470
+ }
471
+ const key = [...fields].sort().join("\0");
472
+ if (shape === void 0) shape = key;
473
+ else if (key !== shape) {
474
+ throw badRequest(
475
+ `record ${index} of a bulk create names other fields than record 0 \u2014 every record of a bulk create names the same fields`,
476
+ { index },
477
+ { code: "bad_request" }
478
+ );
479
+ }
480
+ });
481
+ return records;
482
+ }
448
483
  function oneRecordRefusal() {
449
484
  return badRequest(ONE_RECORD_MESSAGE, void 0, { code: "bad_request" });
450
485
  }
@@ -459,6 +494,165 @@ function assertKnownFields(entity, data) {
459
494
  { code: "unknown_field" }
460
495
  );
461
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
+ }
462
656
 
463
657
  // src/backdating.ts
464
658
  var MAX_MONTHS_BACK = 24;
@@ -559,17 +753,23 @@ function backdatingDb(db, entities) {
559
753
  new Proxy(repo, {
560
754
  get(r, key, rr) {
561
755
  const member = Reflect.get(r, key, rr);
562
- if (key !== "create" || typeof member !== "function") return member;
563
- return (data, ...rest) => {
564
- if (!backdated() || !data || typeof data !== "object" || Array.isArray(data) || isList(data)) {
565
- return member.call(r, data, ...rest);
566
- }
567
- const at = now();
756
+ if (key !== "create" && key !== "createMany" || typeof member !== "function") return member;
757
+ const call = (data, rest) => member.call(r, data, ...rest);
758
+ const stamp = (data, at) => {
759
+ if (!data || typeof data !== "object" || Array.isArray(data) || isList(data)) return data;
568
760
  const row = { ...data };
569
761
  if (row.created_at === void 0) row.created_at = at;
570
762
  if ("updated_at" in columns && row.updated_at === void 0) row.updated_at = at;
571
- return member.call(r, row, ...rest);
763
+ return row;
572
764
  };
765
+ if (key === "createMany") {
766
+ return (data, ...rest) => {
767
+ if (!backdated() || !Array.isArray(data)) return call(data, rest);
768
+ const at = now();
769
+ return call(data.map((record) => stamp(record, at)), rest);
770
+ };
771
+ }
772
+ return (data, ...rest) => backdated() ? call(stamp(data, now()), rest) : call(data, rest);
573
773
  }
574
774
  })
575
775
  );
@@ -605,8 +805,15 @@ export {
605
805
  ENTITY_DESCRIPTOR,
606
806
  guardsTrash,
607
807
  describedEntity,
808
+ bulkRecords,
608
809
  oneRecordRefusal,
609
810
  assertKnownFields,
811
+ RecordGone,
812
+ pkOf,
813
+ roundTripped,
814
+ createdFields,
815
+ withoutNullTrash,
816
+ trashRoundTripped,
610
817
  DEFAULT_GATEWAY_ENDPOINT,
611
818
  DEFAULT_SETTINGS_TTL_MS,
612
819
  DEFAULT_SETTINGS_ERROR_TTL_MS,
@@ -626,4 +833,4 @@ export {
626
833
  backdatingFields,
627
834
  backdatingDb
628
835
  };
629
- //# sourceMappingURL=chunk-AVWPY5D2.js.map
836
+ //# sourceMappingURL=chunk-ZTTYOJYU.js.map