@revenexx/app-sdk 1.6.0 → 2.0.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
@@ -183,6 +183,91 @@ function compare(a, op, b) {
183
183
  }
184
184
  }
185
185
 
186
+ // src/patch.ts
187
+ var EMPTY_UPDATE_MESSAGE = "request body must contain at least one field to update";
188
+ function updateFields(patch) {
189
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) return [];
190
+ return Object.keys(patch).filter(
191
+ (key) => patch[key] !== void 0
192
+ );
193
+ }
194
+ var EMPTY_CREATE_MESSAGE = "request body must contain at least one field to create";
195
+ function assertCreatable(data) {
196
+ if (updateFields(data).length === 0) throw badRequest(EMPTY_CREATE_MESSAGE, void 0, { code: "empty_create" });
197
+ }
198
+ function assertUpdatable(patch) {
199
+ if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE, void 0, { code: "empty_update" });
200
+ }
201
+ var EMPTY_CONDITION_MESSAGE = "a conditional update needs at least one condition in where";
202
+ function assertCondition(where) {
203
+ if (!where || typeof where !== "object" || Array.isArray(where) || Object.keys(where).length === 0) {
204
+ throw badRequest(EMPTY_CONDITION_MESSAGE, void 0, { code: "empty_condition" });
205
+ }
206
+ assertDefined(where);
207
+ }
208
+ function assertDefined(where) {
209
+ if (!where || typeof where !== "object") return;
210
+ for (const [col, cond] of Object.entries(where)) {
211
+ if (cond === void 0) {
212
+ throw badRequest(`where.${col} is undefined \u2014 a condition needs a value`, void 0, { code: "undefined_condition" });
213
+ }
214
+ }
215
+ }
216
+ var IMPLICIT_COLUMNS = ["tenant_id"];
217
+ var TRASH_FLAG_COLUMNS = [
218
+ "deleted_at",
219
+ "deleted_by",
220
+ "deleted_by_id",
221
+ "trash_batch",
222
+ "purge_blocked_reason"
223
+ ];
224
+ var EXTERNAL_ID_FLAG_COLUMNS = ["external_id"];
225
+ function flagColumns(entity) {
226
+ return [
227
+ ...entity.trash === true ? TRASH_FLAG_COLUMNS : [],
228
+ ...entity.external_id === true ? EXTERNAL_ID_FLAG_COLUMNS : []
229
+ ];
230
+ }
231
+ function writableColumns(entity) {
232
+ return [.../* @__PURE__ */ new Set([...Object.keys(entity.columns ?? {}), ...flagColumns(entity)])].sort();
233
+ }
234
+ function unknownFields(entity, data) {
235
+ if (!checksFields(entity)) return [];
236
+ if (!data || typeof data !== "object" || Array.isArray(data)) return [];
237
+ const row = data;
238
+ const writable = /* @__PURE__ */ new Set([...writableColumns(entity), ...IMPLICIT_COLUMNS]);
239
+ return Object.keys(row).filter((key) => row[key] !== void 0 && !writable.has(key)).sort();
240
+ }
241
+ function checksFields(entity) {
242
+ return !!entity.columns && Object.keys(entity.columns).length > 0;
243
+ }
244
+ var ONE_RECORD_MESSAGE = "a write takes one record, as a JSON object \u2014 not a list";
245
+ function assertOneRecord(entity, data) {
246
+ if (checksFields(entity) && isList(data)) throw oneRecordRefusal();
247
+ }
248
+ var INDEX = /^(?:0|[1-9]\d*)$/;
249
+ function isList(data) {
250
+ if (!data || typeof data !== "object") return false;
251
+ if (Array.isArray(data)) return data.length > 0;
252
+ const keys = Object.keys(data);
253
+ return keys.length > 0 && keys.every((k) => INDEX.test(k) && Number(k) < keys.length);
254
+ }
255
+ var ENTITY_DESCRIPTOR = /* @__PURE__ */ Symbol.for("revenexx.app-sdk.entity");
256
+ function oneRecordRefusal() {
257
+ return badRequest(ONE_RECORD_MESSAGE, void 0, { code: "bad_request" });
258
+ }
259
+ function assertKnownFields(entity, data) {
260
+ assertOneRecord(entity, data);
261
+ const unknown = unknownFields(entity, data);
262
+ if (unknown.length === 0) return;
263
+ const quoted = unknown.map((k) => `'${k}'`).join(", ");
264
+ throw badRequest(
265
+ `unknown field${unknown.length > 1 ? "s" : ""} ${quoted} \u2014 not a column of '${entity.name}'. A field that cannot be written is refused rather than dropped; see details.allowed.`,
266
+ { unknown, allowed: writableColumns(entity) },
267
+ { code: "unknown_field" }
268
+ );
269
+ }
270
+
186
271
  // src/adapters/mock.ts
187
272
  function shape(rows, query) {
188
273
  let out = rows;
@@ -200,12 +285,13 @@ function shape(rows, query) {
200
285
  }
201
286
  return out.map((r) => ({ ...r }));
202
287
  }
203
- var IMPLICIT_COLUMNS = /* @__PURE__ */ new Set(["tenant_id"]);
288
+ var IMPLICIT_COLUMNS2 = new Set(IMPLICIT_COLUMNS);
204
289
  function assertWhereColumns(entity, where) {
205
290
  const columns = entity.columns;
206
291
  if (!columns || Object.keys(columns).length === 0 || !where) return;
292
+ const flagged = new Set(flagColumns(entity));
207
293
  const unknown = Object.keys(where).filter(
208
- (k) => !Object.prototype.hasOwnProperty.call(columns, k) && !IMPLICIT_COLUMNS.has(k)
294
+ (k) => !Object.prototype.hasOwnProperty.call(columns, k) && !IMPLICIT_COLUMNS2.has(k) && !flagged.has(k)
209
295
  );
210
296
  if (unknown.length === 0) return;
211
297
  throw new HttpError(400, "the request could not be processed", void 0, {
@@ -262,13 +348,19 @@ function createMockAdapter(seed = {}) {
262
348
  const r = tbl(entity).get(id);
263
349
  return r ? { ...r } : null;
264
350
  },
351
+ // A key that is not a declared column is the same 400 `unknown_field` the
352
+ // remote adapter raises, so a test cannot pass on a write production
353
+ // refuses.
265
354
  async create(entity, data) {
355
+ assertKnownFields(entity, data);
356
+ assertCreatable(data);
266
357
  const row = applyDefaults(entity, data);
267
358
  if (row[entity.pk] === void 0) row[entity.pk] = (0, import_node_crypto.randomUUID)();
268
359
  tbl(entity).set(row[entity.pk], row);
269
360
  return { ...row };
270
361
  },
271
362
  async update(entity, id, patch) {
363
+ assertKnownFields(entity, patch);
272
364
  const cur = tbl(entity).get(id);
273
365
  if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);
274
366
  return write(entity, id, cur, patch);
@@ -280,6 +372,7 @@ function createMockAdapter(seed = {}) {
280
372
  // a lost race: answering `null` would read as "somebody else moved it".
281
373
  async updateIf(entity, id, where, patch) {
282
374
  assertWhereColumns(entity, where);
375
+ assertKnownFields(entity, patch);
283
376
  const cur = tbl(entity).get(id);
284
377
  if (!cur || !matches(cur, where)) return null;
285
378
  return write(entity, id, cur, patch);
@@ -461,7 +554,12 @@ function createRemoteAdapter(config) {
461
554
  });
462
555
  return rows?.[0] ?? null;
463
556
  },
557
+ // Every write is checked against the entity's declared columns here as
558
+ // well as in the client, so the adapter used on its own refuses the same
559
+ // keys (see ../patch.ts `unknownFields`).
464
560
  async create(entity, data) {
561
+ assertKnownFields(entity, data);
562
+ assertCreatable(data);
465
563
  const rows = await req("POST", `/${entity.table}`, {
466
564
  body: data,
467
565
  prefer: "return=representation",
@@ -476,6 +574,7 @@ function createRemoteAdapter(config) {
476
574
  );
477
575
  },
478
576
  async update(entity, id, patch) {
577
+ assertKnownFields(entity, patch);
479
578
  const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
480
579
  body: patch,
481
580
  prefer: "return=representation",
@@ -484,6 +583,7 @@ function createRemoteAdapter(config) {
484
583
  return oneRow(rows, () => notFound());
485
584
  },
486
585
  async updateIf(entity, id, where, patch) {
586
+ assertKnownFields(entity, patch);
487
587
  const cond = toParams({ where }).toString();
488
588
  const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}&${cond}`, {
489
589
  body: patch,
@@ -613,33 +713,6 @@ registerAdapter("mock", (c) => createMockAdapter(c.seed));
613
713
  registerAdapter("remote", (c) => createRemoteAdapter(c));
614
714
  registerAdapter("runtime", (c) => createRuntimeAdapter(c));
615
715
 
616
- // src/patch.ts
617
- var EMPTY_UPDATE_MESSAGE = "request body must contain at least one field to update";
618
- function updateFields(patch) {
619
- if (!patch || typeof patch !== "object" || Array.isArray(patch)) return [];
620
- return Object.keys(patch).filter(
621
- (key) => patch[key] !== void 0
622
- );
623
- }
624
- function assertUpdatable(patch) {
625
- if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE, void 0, { code: "empty_update" });
626
- }
627
- var EMPTY_CONDITION_MESSAGE = "a conditional update needs at least one condition in where";
628
- function assertCondition(where) {
629
- if (!where || typeof where !== "object" || Array.isArray(where) || Object.keys(where).length === 0) {
630
- throw badRequest(EMPTY_CONDITION_MESSAGE, void 0, { code: "empty_condition" });
631
- }
632
- assertDefined(where);
633
- }
634
- function assertDefined(where) {
635
- if (!where || typeof where !== "object") return;
636
- for (const [col, cond] of Object.entries(where)) {
637
- if (cond === void 0) {
638
- throw badRequest(`where.${col} is undefined \u2014 a condition needs a value`, void 0, { code: "undefined_condition" });
639
- }
640
- }
641
- }
642
-
643
716
  // src/client.ts
644
717
  var ACCESS_TO_OPS = {
645
718
  read: ["list", "get"],
@@ -662,7 +735,7 @@ function entityClient(adapter, entity) {
662
735
  { code: "not_permitted" }
663
736
  );
664
737
  });
665
- return {
738
+ const client = {
666
739
  list: guard("list", async (query) => {
667
740
  assertDefined(query?.where);
668
741
  return adapter.list(entity, query ?? {});
@@ -675,7 +748,16 @@ function entityClient(adapter, entity) {
675
748
  return adapter.page(entity, query ?? {});
676
749
  }),
677
750
  get: guard("get", (id) => adapter.get(entity, id)),
678
- create: guard("create", (data) => adapter.create(entity, data)),
751
+ // A key that is not a column this version declares is refused before the
752
+ // request (see ./patch.ts `unknownFields`): the database cannot tell an
753
+ // old version's stray key from a new version's column. `async` so the
754
+ // refusal is a rejection like every other write failure; the permission
755
+ // refusal above stays synchronous.
756
+ create: guard("create", async (data) => {
757
+ assertKnownFields(entity, data);
758
+ assertCreatable(data);
759
+ return adapter.create(entity, data);
760
+ }),
679
761
  // A patch with no fields is a malformed request, not a write: PostgREST
680
762
  // performs no update and returns no row, which used to leave the App
681
763
  // serialising `undefined` and answering 500 (see ./patch.ts). Rejected here
@@ -686,14 +768,18 @@ function entityClient(adapter, entity) {
686
768
  // patch is handled like any other data-plane failure (`await` / `.catch()`)
687
769
  // and the declared `Promise<T>` stays honest.
688
770
  update: guard("update", async (id, patch) => {
771
+ assertOneRecord(entity, patch);
689
772
  assertUpdatable(patch);
773
+ assertKnownFields(entity, patch);
690
774
  return adapter.update(entity, id, patch);
691
775
  }),
692
776
  // Validated in the same order and at the same layer as `update`, so every
693
777
  // adapter refuses a missing condition identically, before any request.
694
778
  updateIf: guard("update", async (id, where, patch) => {
695
779
  assertCondition(where);
780
+ assertOneRecord(entity, patch);
696
781
  assertUpdatable(patch);
782
+ assertKnownFields(entity, patch);
697
783
  if (!adapter.updateIf) {
698
784
  throw new Error(`${entity.name}.updateIf() is not supported by the '${adapter.kind}' adapter`);
699
785
  }
@@ -701,6 +787,8 @@ function entityClient(adapter, entity) {
701
787
  }, "updateIf"),
702
788
  delete: guard("delete", (id) => adapter.remove(entity, id))
703
789
  };
790
+ Object.defineProperty(client, ENTITY_DESCRIPTOR, { value: entity, enumerable: true });
791
+ return client;
704
792
  }
705
793
  function eventsClient(adapter, config) {
706
794
  const names = () => Object.keys(config.declared).sort().join(", ") || "(none)";
@@ -1008,7 +1096,7 @@ function backdatingDb(db, entities) {
1008
1096
  const member = Reflect.get(r, key, rr);
1009
1097
  if (key !== "create" || typeof member !== "function") return member;
1010
1098
  return (data, ...rest) => {
1011
- if (!backdated() || !data || typeof data !== "object" || Array.isArray(data)) {
1099
+ if (!backdated() || !data || typeof data !== "object" || Array.isArray(data) || isList(data)) {
1012
1100
  return member.call(r, data, ...rest);
1013
1101
  }
1014
1102
  const at = now();