@verikit/prisma 0.24.1 → 0.24.3

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
@@ -4,6 +4,23 @@ Prisma ORM adapter for VeriKit server resources.
4
4
 
5
5
  See the [VeriKit documentation](https://verikit.dev) for setup and usage.
6
6
 
7
+ ## Field and id mapping
8
+
9
+ Each resource field maps to the Prisma scalar with the same name, and the id to
10
+ a string `id` scalar, so a model that matches its resource needs neither
11
+ `fields` nor `id`. List only the fields whose scalar has a different name, and
12
+ pass `id` for a different scalar or a non-string key:
13
+
14
+ ```ts
15
+ createPrismaAdapter(resource, {
16
+ model: prisma.legacyPost,
17
+ fields: { title: "headline" }, // every other field: same-named scalar
18
+ id: { field: "postId" },
19
+ listTransaction: (operation) =>
20
+ prisma.$transaction((tx) => operation(tx.legacyPost)),
21
+ });
22
+ ```
23
+
7
24
  ## Consistent pagination
8
25
 
9
26
  `listTransaction` is required: `list()`'s records and count queries always run
@@ -15,11 +32,61 @@ transaction on its own pass one built from your `PrismaClient`:
15
32
  ```ts
16
33
  createPrismaAdapter(resource, {
17
34
  model: prisma.post,
18
- fields: { title: "title" },
19
- id: { field: "id" },
20
35
  listTransaction: (operation) =>
21
36
  prisma.$transaction(
22
37
  (tx) => operation(tx.post),
23
38
  { isolationLevel: "RepeatableRead" },
24
39
  ),
25
- });
40
+ });
41
+ ```
42
+
43
+ ## Conditional writes for protected resources
44
+
45
+ Update and delete on resources with permissions require an adapter implementing
46
+ `findForMutation`. The server authorizes its detached record snapshot and passes
47
+ its storage-authored `revision` to `update`/`delete` as `expectedRevision`. The
48
+ adapter must compare that revision **in the same database statement as the write**,
49
+ combine it with the ID and scope, and throw `ConflictError` (HTTP 409) when no row
50
+ matches. Missing/deleted rows and stale revisions produce the same conflict. There
51
+ is no automatic retry; retrying must repeat authorization and validation.
52
+
53
+ The in-memory adapter supports this automatically. Database adapters require a
54
+ migration adding a dedicated non-null integer revision column with default `0`,
55
+ excluded from the resource field map:
56
+
57
+ ```ts
58
+ // Drizzle: revision: integer("revision").notNull().default(0)
59
+ const adapter = createDrizzleAdapter(db, resource, {
60
+ versionColumn: table.revision,
61
+ });
62
+
63
+ // Prisma model: revision Int @default(0)
64
+ const adapter = createPrismaAdapter(resource, {
65
+ // ...existing model, fields, id, and listTransaction options
66
+ versionField: "revision",
67
+ });
68
+ ```
69
+
70
+ Configured adapters increment revisions on every update, including empty updates
71
+ and updates without an expected revision. Revisions never appear in API responses.
72
+ **All other writers must increment the same revision atomically**, including jobs,
73
+ custom actions, raw SQL, and other adapter instances. Do not reset revisions or
74
+ reuse a deleted record's ID. Provision the column before enabling the option; this
75
+ library does not run database migrations. Adapters without conditional-write
76
+ support return HTTP 501 for protected update/delete; explicitly `"open"` resources
77
+ retain unconditional writes.
78
+
79
+ When a revision column isn't possible, a protected resource can opt out with
80
+ `unsafeUnconditionalWrites: true` in its `createServer()` resource config.
81
+ Update and delete then check permissions against the record as read and write
82
+ without a revision, so a change made in between is not detected. This is only
83
+ safe when the update and delete rules don't depend on record fields that can
84
+ change, such as a rule that checks only the actor's role. Adapters that support
85
+ conditional writes keep using them.
86
+
87
+ Custom adapter wrappers must forward `expectedRevision` (fourth argument to
88
+ `update`, third to `delete`). `findForMutation` must capture record and revision
89
+ atomically and return a detached record. Revisions must be safe nonnegative
90
+ integers with room to increment. This protects rules based on the target record;
91
+ rules depending on other records or external services need application-level
92
+ transactional coordination as well.
@@ -51,18 +51,24 @@ export interface PrismaIdConfig<TId = unknown> {
51
51
  */
52
52
  export type PrismaSearchProvider = "postgresql" | "sqlite" | "mysql";
53
53
  export interface PrismaAdapterOptions<TFields extends FieldMap> {
54
+ /** Dedicated non-null Int revision scalar, excluded from resource fields. All external writers must increment it. */
55
+ versionField?: string;
54
56
  /** The generated Prisma model delegate this adapter reads/writes, e.g. `prisma.post`. */
55
57
  model: PrismaModelDelegate;
56
58
  /**
57
- * Maps every resource field to its Prisma scalar field.
58
- * All fields must be explicitly mapped; relations and Prisma `include`/`select`
59
- * values are not supported.
59
+ * Maps resource fields to Prisma scalar fields when the names differ. A field
60
+ * left out maps to the scalar with the same name, so a model whose scalars
61
+ * match the resource's field names needs no map. Relations and Prisma
62
+ * `include`/`select` values are not supported.
60
63
  */
61
- fields: {
62
- [K in keyof TFields & string]: string;
64
+ fields?: {
65
+ [K in keyof TFields & string]?: string;
63
66
  };
64
- /** Names the model's primary (or other unique) scalar and how to codec it. */
65
- id: PrismaIdConfig;
67
+ /**
68
+ * Names the model's primary (or other unique) scalar and how to codec it.
69
+ * Defaults to a string `id` scalar; numeric or composite IDs need `fromPath`.
70
+ */
71
+ id?: PrismaIdConfig;
66
72
  /** See `PrismaSearchProvider`. */
67
73
  provider?: PrismaSearchProvider;
68
74
  /**
@@ -89,10 +95,9 @@ export interface PrismaResourceRecord extends Record<string, unknown> {
89
95
  }
90
96
  /**
91
97
  * Creates a Prisma-backed `ResourceAdapter`.
92
- * Selects only configured fields plus `id`, never full model rows.
98
+ * Selects only the resource's fields plus `id`, never full model rows.
93
99
  *
94
- * @throws {Error} If a resource field is unmapped or a `.searchable()` field
95
- * is not text-like.
100
+ * @throws {Error} If a `.searchable()` field is not text-like.
96
101
  */
97
102
  export declare function createPrismaAdapter<TFields extends FieldMap, TRelationships extends RelationshipMap, TTable = unknown>(resource: Resource<string, TFields, TTable, TRelationships>, options: PrismaAdapterOptions<TFields>): ResourceAdapter<PrismaResourceRecord>;
98
103
  //# sourceMappingURL=create-prisma-adapter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-prisma-adapter.d.ts","sourceRoot":"","sources":["../src/create-prisma-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzE,OAAO,EAEL,KAAK,eAAe,EAErB,MAAM,iBAAiB,CAAC;AAYzB;;;GAGG;AAEH,MAAM,WAAW,mBAAmB;IAClC,QA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AC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,MAAM,CAAC;CACjC;AAED;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAAG,YAAY,GAAG,QAAQ,GAAG,OAAO,CAAC;AAErE,MAAM,WAAW,oBAAoB,CAAC,OAAO,SAAS,QAAQ;IAC5D,qHAAqH;IACrH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,yFAAyF;IACzF,KAAK,EAAE,mBAAmB,CAAC;IAC3B;;;;;OAKG;IACH,MAAM,CAAC,EAAE;SAAG,CAAC,IAAI,MAAM,OAAO,GAAG,MAAM,CAAC,CAAC,EAAE,MAAM;KAAE,CAAC;IACpD;;;OAGG;IACH,EAAE,CAAC,EAAE,cAAc,CAAC;IACpB,kCAAkC;IAClC,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAChC;;;;;;OAMG;IACH,2BAA2B,CAAC,EAAE,MAAM,CAAC;IACrC;;;;;;OAMG;IACH,eAAe,EAAE,qBAAqB,CAAC;CACxC;AAED,6DAA6D;AAC7D,MAAM,WAAW,oBAAqB,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACnE,mEAAmE;IACnE,EAAE,EAAE,MAAM,CAAC;CACZ;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,SAAS,QAAQ,EACxB,cAAc,SAAS,eAAe,EACtC,MAAM,GAAG,OAAO,EAEhB,QAAQ,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,cAAc,CAAC,EAC3D,OAAO,EAAE,oBAAoB,CAAC,OAAO,CAAC,GACrC,eAAe,CAAC,oBAAoB,CAAC,CAuavC"}
@@ -1,20 +1,39 @@
1
+ import { ConflictError } from "@verikit/core";
1
2
  import { UniqueConstraintError, } from "@verikit/server";
2
3
  import { buildSelect, isRecordNotFoundError, isUniqueConstraintError, mapFilterToPrisma, mapValuesToData, presentRow, uniqueConstraintFields, } from "./mapping.js";
3
4
  /**
4
5
  * Creates a Prisma-backed `ResourceAdapter`.
5
- * Selects only configured fields plus `id`, never full model rows.
6
+ * Selects only the resource's fields plus `id`, never full model rows.
6
7
  *
7
- * @throws {Error} If a resource field is unmapped or a `.searchable()` field
8
- * is not text-like.
8
+ * @throws {Error} If a `.searchable()` field is not text-like.
9
9
  */
10
10
  export function createPrismaAdapter(resource, options) {
11
- const { model, id } = options;
12
- const fields = options.fields;
11
+ const { model } = options;
12
+ const id = options.id ?? { field: "id" };
13
13
  const schema = resource.toSchema();
14
- const unmapped = Object.keys(schema.fields).filter((name) => !Object.hasOwn(fields, name));
15
- if (unmapped.length > 0) {
16
- throw new Error(`@verikit/prisma: resource "${resource.name}" has no Prisma field mapping for: ${unmapped.join(", ")}. Every declared field needs an entry in \`fields\`.`);
14
+ // Only declared fields are mapped, so a stray `fields` key can never widen
15
+ // the select.
16
+ const fields = Object.fromEntries(Object.keys(schema.fields).map((name) => [
17
+ name,
18
+ options.fields?.[name] ?? name,
19
+ ]));
20
+ const versionField = options.versionField;
21
+ if (versionField !== undefined &&
22
+ (!versionField ||
23
+ versionField === id.field ||
24
+ Object.values(fields).includes(versionField))) {
25
+ throw new Error("versionField must be a dedicated revision scalar, not an ID or resource field.");
17
26
  }
27
+ function revisionWhere(expectedRevision) {
28
+ if (!versionField ||
29
+ !Number.isSafeInteger(expectedRevision) ||
30
+ expectedRevision < 0 ||
31
+ expectedRevision >= Number.MAX_SAFE_INTEGER) {
32
+ throw new Error("Conditional writes require a configured versionField and a valid revision.");
33
+ }
34
+ return { [versionField]: expectedRevision };
35
+ }
36
+ const conflict = () => new ConflictError("Record changed since authorization. Retry the request.");
18
37
  const searchableScalars = Object.entries(schema.fields)
19
38
  .filter(([, field]) => field.searchable)
20
39
  .map(([name, field]) => {
@@ -101,6 +120,22 @@ export function createPrismaAdapter(resource, options) {
101
120
  return present(row);
102
121
  }
103
122
  return {
123
+ ...(versionField && {
124
+ async findForMutation(pathId, scope) {
125
+ const value = fromPath(pathId);
126
+ if (value === undefined)
127
+ return undefined;
128
+ // Prisma 6/7 extended unique filters retain the unique ID at the top level.
129
+ const row = await model.findUnique({
130
+ where: { [id.field]: value, AND: scopeWhere(scope) ?? {} },
131
+ select: { ...select, [versionField]: true },
132
+ });
133
+ if (!row)
134
+ return undefined;
135
+ revisionWhere(row[versionField]);
136
+ return { record: present(row), revision: row[versionField] };
137
+ },
138
+ }),
104
139
  async list(params) {
105
140
  // Search with no searchable fields can never match; return zero results.
106
141
  const permittedSearchScalars = params.searchFields
@@ -173,12 +208,37 @@ export function createPrismaAdapter(resource, options) {
173
208
  throw error;
174
209
  }
175
210
  },
176
- async update(pathId, values, scope) {
211
+ async update(pathId, values, scope, expectedRevision) {
177
212
  const value = fromPath(pathId);
178
213
  if (value === undefined) {
214
+ if (expectedRevision !== undefined)
215
+ throw conflict();
179
216
  return undefined;
180
217
  }
181
218
  const data = mapValuesToData(values, fields);
219
+ if (versionField)
220
+ data[versionField] = { increment: 1 };
221
+ if (expectedRevision !== undefined) {
222
+ const revision = revisionWhere(expectedRevision);
223
+ try {
224
+ const row = await model.update({
225
+ where: {
226
+ [id.field]: value,
227
+ AND: [scopeWhere(scope) ?? {}, revision],
228
+ },
229
+ data,
230
+ select,
231
+ });
232
+ return present(row);
233
+ }
234
+ catch (error) {
235
+ if (isRecordNotFoundError(error))
236
+ throw conflict();
237
+ if (isUniqueConstraintError(error))
238
+ throw new UniqueConstraintError(uniqueConstraintFields(error, fields));
239
+ throw error;
240
+ }
241
+ }
182
242
  // Prisma's update() only accepts a unique selector, so it cannot express
183
243
  // `{ id, organizationId }`. updateMany/updateManyAndReturn make the tenant
184
244
  // predicate atomic.
@@ -226,11 +286,30 @@ export function createPrismaAdapter(resource, options) {
226
286
  throw error;
227
287
  }
228
288
  },
229
- async delete(pathId, scope) {
289
+ async delete(pathId, scope, expectedRevision) {
230
290
  const value = fromPath(pathId);
231
291
  if (value === undefined) {
292
+ if (expectedRevision !== undefined)
293
+ throw conflict();
232
294
  return;
233
295
  }
296
+ if (expectedRevision !== undefined) {
297
+ const revision = revisionWhere(expectedRevision);
298
+ try {
299
+ await model.delete({
300
+ where: {
301
+ [id.field]: value,
302
+ AND: [scopeWhere(scope) ?? {}, revision],
303
+ },
304
+ });
305
+ return;
306
+ }
307
+ catch (error) {
308
+ if (isRecordNotFoundError(error))
309
+ throw conflict();
310
+ throw error;
311
+ }
312
+ }
234
313
  if (scope) {
235
314
  if (!model.deleteMany) {
236
315
  throw new Error("@verikit/prisma: scoped deletes require a Prisma delegate with deleteMany().");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verikit/prisma",
3
- "version": "0.24.1",
3
+ "version": "0.24.3",
4
4
  "description": "Prisma ORM storage adapter for @verikit/server resources.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -36,8 +36,8 @@
36
36
  "dist"
37
37
  ],
38
38
  "dependencies": {
39
- "@verikit/core": "0.24.1",
40
- "@verikit/server": "0.24.1"
39
+ "@verikit/core": "0.24.3",
40
+ "@verikit/server": "0.24.3"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@prisma/adapter-better-sqlite3": "^7.9.1",