@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/dist/index.cjs CHANGED
@@ -253,6 +253,41 @@ function isList(data) {
253
253
  return keys.length > 0 && keys.every((k) => INDEX.test(k) && Number(k) < keys.length);
254
254
  }
255
255
  var ENTITY_DESCRIPTOR = /* @__PURE__ */ Symbol.for("revenexx.app-sdk.entity");
256
+ var MANY_RECORDS_MESSAGE = "createMany takes a list of records";
257
+ function bulkRecords(entity, data) {
258
+ if (Array.isArray(data) && data.length === 0) throw badRequest(EMPTY_CREATE_MESSAGE, void 0, { code: "empty_create" });
259
+ if (!isList(data)) throw badRequest(MANY_RECORDS_MESSAGE, void 0, { code: "bad_request" });
260
+ const records = Array.isArray(data) ? data : Object.keys(data).sort((a, b) => Number(a) - Number(b)).map((k) => data[k]);
261
+ let shape2;
262
+ records.forEach((record, index) => {
263
+ if (!record || typeof record !== "object" || isList(record)) {
264
+ throw badRequest(`record ${index} of a bulk create is not an object \u2014 each element is one record`, { index }, { code: "bad_request" });
265
+ }
266
+ const fields = updateFields(record);
267
+ if (fields.length === 0) {
268
+ throw badRequest(`record ${index} of a bulk create has no field \u2014 ${EMPTY_CREATE_MESSAGE}`, { index }, { code: "empty_create" });
269
+ }
270
+ const unknown = unknownFields(entity, record);
271
+ if (unknown.length > 0) {
272
+ const quoted = unknown.map((k) => `'${k}'`).join(", ");
273
+ throw badRequest(
274
+ `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.`,
275
+ { index, unknown, allowed: writableColumns(entity) },
276
+ { code: "unknown_field" }
277
+ );
278
+ }
279
+ const key = [...fields].sort().join("\0");
280
+ if (shape2 === void 0) shape2 = key;
281
+ else if (key !== shape2) {
282
+ throw badRequest(
283
+ `record ${index} of a bulk create names other fields than record 0 \u2014 every record of a bulk create names the same fields`,
284
+ { index },
285
+ { code: "bad_request" }
286
+ );
287
+ }
288
+ });
289
+ return records;
290
+ }
256
291
  function oneRecordRefusal() {
257
292
  return badRequest(ONE_RECORD_MESSAGE, void 0, { code: "bad_request" });
258
293
  }
@@ -267,6 +302,127 @@ function assertKnownFields(entity, data) {
267
302
  { code: "unknown_field" }
268
303
  );
269
304
  }
305
+ var STORE_OWNED_FIELD = "store_owned_field";
306
+ var READ_ONLY_FIELD = "read_only_field";
307
+ var STORE_STAMPED_COLUMNS = ["updated_at"];
308
+ var CREATION_STAMP_COLUMNS = ["created_at"];
309
+ var TRASH_ROUND_TRIP_COLUMNS = [...TRASH_FLAG_COLUMNS, "purge_at"];
310
+ var RecordGone = class extends Error {
311
+ constructor() {
312
+ super("the record is not there");
313
+ this.name = "RecordGone";
314
+ }
315
+ };
316
+ var noValue = (v) => v === null || v === void 0 || v === "";
317
+ var has = (row, key) => Object.prototype.hasOwnProperty.call(row, key) && row[key] !== void 0;
318
+ var nullish = (v) => v === null || v === void 0;
319
+ var DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?$/;
320
+ var NUMERIC_TYPE = /^(?:(?:small|big)?int(?:eger)?|int[248]|(?:big|small)?serial|serial[248]|numeric|decimal|real|double|float[48]?)\b/i;
321
+ var INSTANT = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
322
+ function sameInstant(a, b) {
323
+ if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);
324
+ if (String(a) === String(b)) return true;
325
+ if (typeof a !== "string" || typeof b !== "string" || !INSTANT.test(a) || !INSTANT.test(b)) return false;
326
+ const x = Date.parse(a);
327
+ const y = Date.parse(b);
328
+ return Number.isFinite(x) && Number.isFinite(y) && x === y;
329
+ }
330
+ function decimal(v) {
331
+ const text = typeof v === "number" ? Number.isFinite(v) ? String(v) : "" : typeof v === "string" ? v.trim() : "";
332
+ const m = DECIMAL.exec(text);
333
+ if (!m || m[2] === "" && (m[3] ?? "") === "") return null;
334
+ const whole = m[2].replace(/^0+(?=\d)/, "") || "0";
335
+ const fraction = (m[3] ?? "").replace(/0+$/, "");
336
+ const digits = fraction ? `${whole}.${fraction}` : whole;
337
+ return digits === "0" ? "0" : `${m[1] === "-" ? "-" : ""}${digits}`;
338
+ }
339
+ function isNumericType(type) {
340
+ return NUMERIC_TYPE.test(String(type ?? "").trim());
341
+ }
342
+ function sameValue(a, b, type) {
343
+ if (nullish(a) || nullish(b)) return nullish(a) && nullish(b);
344
+ if (typeof a === "object" || typeof b === "object") return canonical(a) === canonical(b);
345
+ if (String(a) === String(b)) return true;
346
+ if (isNumericType(type)) {
347
+ const x = decimal(a);
348
+ const y = decimal(b);
349
+ if (x !== null && y !== null) return x === y;
350
+ const fx = Number(a);
351
+ const fy = Number(b);
352
+ return Number.isFinite(fx) && Number.isFinite(fy) && fx === fy;
353
+ }
354
+ return sameInstant(a, b);
355
+ }
356
+ function canonical(v) {
357
+ return JSON.stringify(v, (_k, value) => {
358
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
359
+ const keys = Object.keys(value);
360
+ return keys.length === 0 ? [] : Object.fromEntries(keys.sort().map((k) => [k, value[k]]));
361
+ });
362
+ }
363
+ function pkOf(entity) {
364
+ return entity?.pk || "id";
365
+ }
366
+ function declares(entity, column) {
367
+ const columns = entity.columns;
368
+ return !columns || Object.keys(columns).length === 0 || Object.prototype.hasOwnProperty.call(columns, column);
369
+ }
370
+ function generatedColumns(entity) {
371
+ return Object.entries(entity?.columns ?? {}).filter(([, def]) => !!def && typeof def === "object" && !!def.generated).map(([name]) => name).sort();
372
+ }
373
+ var storeOwned = (field, message) => badRequest(message, { field, fields: [field] }, { code: STORE_OWNED_FIELD });
374
+ var readOnly = (field, what) => badRequest(
375
+ `'${field}' is ${what} and cannot be changed by a write \u2014 send it as read, or leave it out`,
376
+ { field, fields: [field] },
377
+ { code: READ_ONLY_FIELD }
378
+ );
379
+ var TENANT_CHANGED = "'tenant_id' cannot be changed: a record stays in the tenant it was written under";
380
+ async function roundTripped(entity, id, patch, options) {
381
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) return patch;
382
+ const out = { ...patch };
383
+ let loaded = false;
384
+ let current = null;
385
+ const stored = async () => {
386
+ if (!loaded) {
387
+ current = await options.stored();
388
+ loaded = true;
389
+ }
390
+ if (!current) throw new RecordGone();
391
+ return current;
392
+ };
393
+ const pk = pkOf(entity);
394
+ if (has(out, pk)) {
395
+ if (!noValue(out[pk]) && String(out[pk]) !== String(id)) {
396
+ throw storeOwned(pk, `'${pk}' cannot be changed: the record is '${String(id)}'`);
397
+ }
398
+ delete out[pk];
399
+ }
400
+ if (has(out, "tenant_id")) {
401
+ if (!noValue(out.tenant_id)) {
402
+ const tenant = (await stored()).tenant_id;
403
+ if (!noValue(tenant) && String(out.tenant_id) !== String(tenant)) throw storeOwned("tenant_id", TENANT_CHANGED);
404
+ }
405
+ delete out.tenant_id;
406
+ }
407
+ const left = updateFields(out);
408
+ const touch = left.length === 1 && STORE_STAMPED_COLUMNS.includes(left[0]);
409
+ for (const field of STORE_STAMPED_COLUMNS) {
410
+ if (!touch && has(out, field) && declares(entity, field)) delete out[field];
411
+ }
412
+ for (const field of CREATION_STAMP_COLUMNS) {
413
+ if (!has(out, field) || !declares(entity, field)) continue;
414
+ if (sameInstant(out[field], (await stored())[field])) delete out[field];
415
+ }
416
+ const generated = generatedColumns(entity);
417
+ for (const field of generated) delete out[field];
418
+ for (const field of [...new Set(options.readOnly ?? [])].sort()) {
419
+ if (!has(out, field) || generated.includes(field)) continue;
420
+ const type = entity.columns?.[field]?.type;
421
+ if (!sameValue(out[field], (await stored())[field], type)) throw readOnly(field, "kept by the app");
422
+ delete out[field];
423
+ }
424
+ return out;
425
+ }
270
426
 
271
427
  // src/adapters/mock.ts
272
428
  function shape(rows, query) {
@@ -299,6 +455,17 @@ function assertWhereColumns(entity, where) {
299
455
  serverDetail: { source: "mock", entity: entity.name, unknownColumns: unknown }
300
456
  });
301
457
  }
458
+ function assertUpdatableColumns(entity, patch) {
459
+ if (!patch || typeof patch !== "object") return;
460
+ const refused = [.../* @__PURE__ */ new Set([entity.pk || "id", "tenant_id"])].filter(
461
+ (k) => Object.prototype.hasOwnProperty.call(patch, k) && patch[k] !== void 0
462
+ );
463
+ if (refused.length === 0) return;
464
+ throw new HttpError(401, "unauthenticated", void 0, {
465
+ code: "bad_request",
466
+ serverDetail: { source: "mock", entity: entity.name, sqlstate: "42501", columns: refused.sort() }
467
+ });
468
+ }
302
469
  function applyDefaults(entity, data) {
303
470
  const row = { ...data };
304
471
  for (const [col, def] of Object.entries(entity.columns ?? {})) {
@@ -328,7 +495,8 @@ function createMockAdapter(seed = {}) {
328
495
  };
329
496
  const write = (entity, id, cur, patch) => {
330
497
  const row = { ...cur, ...patch };
331
- if (entity.columns?.updated_at) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
498
+ const changed = Object.keys(patch).some((k) => patch[k] !== void 0 && JSON.stringify(patch[k]) !== JSON.stringify(cur[k]));
499
+ if (entity.columns?.updated_at && changed) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
332
500
  tbl(entity).set(id, row);
333
501
  return { ...row };
334
502
  };
@@ -359,8 +527,33 @@ function createMockAdapter(seed = {}) {
359
527
  tbl(entity).set(row[entity.pk], row);
360
528
  return { ...row };
361
529
  },
530
+ // One statement in Postgres: a primary key twice in the batch, or one the
531
+ // table already holds, is the 409 the remote adapter maps from 23505, and
532
+ // nothing is stored.
533
+ async createMany(entity, data) {
534
+ const rows = bulkRecords(entity, data).map((record) => {
535
+ const row = applyDefaults(entity, record);
536
+ if (row[entity.pk] === void 0) row[entity.pk] = (0, import_node_crypto.randomUUID)();
537
+ return row;
538
+ });
539
+ const table = tbl(entity);
540
+ const seen = /* @__PURE__ */ new Set();
541
+ for (const row of rows) {
542
+ const id = row[entity.pk];
543
+ if (seen.has(id) || table.has(id)) {
544
+ throw new HttpError(409, "a record with this value already exists", void 0, {
545
+ code: "unique_violation",
546
+ serverDetail: { source: "mock", entity: entity.name, duplicate: id }
547
+ });
548
+ }
549
+ seen.add(id);
550
+ }
551
+ for (const row of rows) table.set(row[entity.pk], row);
552
+ return rows.map((row) => ({ ...row }));
553
+ },
362
554
  async update(entity, id, patch) {
363
555
  assertKnownFields(entity, patch);
556
+ assertUpdatableColumns(entity, patch);
364
557
  const cur = tbl(entity).get(id);
365
558
  if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);
366
559
  return write(entity, id, cur, patch);
@@ -373,6 +566,7 @@ function createMockAdapter(seed = {}) {
373
566
  async updateIf(entity, id, where, patch) {
374
567
  assertWhereColumns(entity, where);
375
568
  assertKnownFields(entity, patch);
569
+ assertUpdatableColumns(entity, patch);
376
570
  const cur = tbl(entity).get(id);
377
571
  if (!cur || !matches(cur, where)) return null;
378
572
  return write(entity, id, cur, patch);
@@ -573,6 +767,23 @@ function createRemoteAdapter(config) {
573
767
  })
574
768
  );
575
769
  },
770
+ // One POST of the whole list: PostgREST inserts it in one statement and
771
+ // answers every row, in order. Checked here as well as in the client.
772
+ async createMany(entity, data) {
773
+ const records = bulkRecords(entity, data);
774
+ const rows = await req("POST", `/${entity.table}`, {
775
+ body: records,
776
+ prefer: "return=representation",
777
+ table: entity.table
778
+ });
779
+ if (!Array.isArray(rows) || rows.length < records.length) {
780
+ throw new HttpError(500, "the records were created but could not be read back", void 0, {
781
+ code: "empty_representation",
782
+ serverDetail: { source: "postgrest", method: "POST", table: entity.table, sent: records.length }
783
+ });
784
+ }
785
+ return rows;
786
+ },
576
787
  async update(entity, id, patch) {
577
788
  assertKnownFields(entity, patch);
578
789
  const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
@@ -725,6 +936,18 @@ function opsFromAccess(access = []) {
725
936
  for (const a of access) (ACCESS_TO_OPS[a] ?? []).forEach((o) => ops.add(o));
726
937
  return ops;
727
938
  }
939
+ function storedOnce(adapter, entity, id) {
940
+ let read;
941
+ return () => read ??= adapter.get(entity, id);
942
+ }
943
+ async function roundTrip(stored, entity, id, patch) {
944
+ try {
945
+ return await roundTripped(entity, id, patch, { stored });
946
+ } catch (err) {
947
+ if (err instanceof RecordGone) return null;
948
+ throw err;
949
+ }
950
+ }
728
951
  function entityClient(adapter, entity) {
729
952
  const ops = entity.ops instanceof Set ? entity.ops : new Set(entity.ops ?? ["list", "get", "create", "update", "delete"]);
730
953
  const guard = (op, fn, method = op) => ops.has(op) ? fn : (() => {
@@ -758,6 +981,15 @@ function entityClient(adapter, entity) {
758
981
  assertCreatable(data);
759
982
  return adapter.create(entity, data);
760
983
  }),
984
+ // A bulk create is its own call: checked whole before the one request
985
+ // (./patch.ts `bulkRecords`), never emulated as one create per record.
986
+ createMany: guard("create", async (rows) => {
987
+ const records = bulkRecords(entity, rows);
988
+ if (!adapter.createMany) {
989
+ throw new Error(`${entity.name}.createMany() is not supported by the '${adapter.kind}' adapter`);
990
+ }
991
+ return adapter.createMany(entity, records);
992
+ }, "createMany"),
761
993
  // A patch with no fields is a malformed request, not a write: PostgREST
762
994
  // performs no update and returns no row, which used to leave the App
763
995
  // serialising `undefined` and answering 500 (see ./patch.ts). Rejected here
@@ -771,7 +1003,15 @@ function entityClient(adapter, entity) {
771
1003
  assertOneRecord(entity, patch);
772
1004
  assertUpdatable(patch);
773
1005
  assertKnownFields(entity, patch);
774
- return adapter.update(entity, id, patch);
1006
+ const stored = storedOnce(adapter, entity, id);
1007
+ const write = await roundTrip(stored, entity, id, patch);
1008
+ if (write === null) throw notFound();
1009
+ if (updateFields(write).length === 0) {
1010
+ const row = await stored();
1011
+ if (!row) throw notFound();
1012
+ return row;
1013
+ }
1014
+ return adapter.update(entity, id, write);
775
1015
  }),
776
1016
  // Validated in the same order and at the same layer as `update`, so every
777
1017
  // adapter refuses a missing condition identically, before any request.
@@ -783,7 +1023,13 @@ function entityClient(adapter, entity) {
783
1023
  if (!adapter.updateIf) {
784
1024
  throw new Error(`${entity.name}.updateIf() is not supported by the '${adapter.kind}' adapter`);
785
1025
  }
786
- return adapter.updateIf(entity, id, where, patch);
1026
+ const write = await roundTrip(storedOnce(adapter, entity, id), entity, id, patch);
1027
+ if (write === null) return null;
1028
+ if (updateFields(write).length === 0) {
1029
+ const [row] = await adapter.list(entity, { where: { ...where, [pkOf(entity)]: id }, limit: 1 });
1030
+ return row ?? null;
1031
+ }
1032
+ return adapter.updateIf(entity, id, where, write);
787
1033
  }, "updateIf"),
788
1034
  delete: guard("delete", (id) => adapter.remove(entity, id))
789
1035
  };
@@ -1094,17 +1340,23 @@ function backdatingDb(db, entities) {
1094
1340
  new Proxy(repo, {
1095
1341
  get(r, key, rr) {
1096
1342
  const member = Reflect.get(r, key, rr);
1097
- if (key !== "create" || typeof member !== "function") return member;
1098
- return (data, ...rest) => {
1099
- if (!backdated() || !data || typeof data !== "object" || Array.isArray(data) || isList(data)) {
1100
- return member.call(r, data, ...rest);
1101
- }
1102
- const at = now();
1343
+ if (key !== "create" && key !== "createMany" || typeof member !== "function") return member;
1344
+ const call = (data, rest) => member.call(r, data, ...rest);
1345
+ const stamp = (data, at) => {
1346
+ if (!data || typeof data !== "object" || Array.isArray(data) || isList(data)) return data;
1103
1347
  const row = { ...data };
1104
1348
  if (row.created_at === void 0) row.created_at = at;
1105
1349
  if ("updated_at" in columns && row.updated_at === void 0) row.updated_at = at;
1106
- return member.call(r, row, ...rest);
1350
+ return row;
1107
1351
  };
1352
+ if (key === "createMany") {
1353
+ return (data, ...rest) => {
1354
+ if (!backdated() || !Array.isArray(data)) return call(data, rest);
1355
+ const at = now();
1356
+ return call(data.map((record) => stamp(record, at)), rest);
1357
+ };
1358
+ }
1359
+ return (data, ...rest) => backdated() ? call(stamp(data, now()), rest) : call(data, rest);
1108
1360
  }
1109
1361
  })
1110
1362
  );