@anievo-id/rbac-evolution-drizzle 1.0.0 → 1.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.
Files changed (40) hide show
  1. package/dist/{chunk-7DROVIVH.js → chunk-3AH2K6KS.js} +129 -17
  2. package/dist/chunk-3AH2K6KS.js.map +1 -0
  3. package/dist/{chunk-VQYJULOM.js → chunk-CK2CKZPC.js} +49 -6
  4. package/dist/chunk-CK2CKZPC.js.map +1 -0
  5. package/dist/{chunk-I4GXEURO.js → chunk-CQBJTVGQ.js} +48 -5
  6. package/dist/chunk-CQBJTVGQ.js.map +1 -0
  7. package/dist/{chunk-5GEP46FS.js → chunk-SPNXRYKH.js} +48 -5
  8. package/dist/chunk-SPNXRYKH.js.map +1 -0
  9. package/dist/index.cjs +261 -20
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +6 -108
  12. package/dist/index.d.ts +6 -108
  13. package/dist/index.js +4 -4
  14. package/dist/mysql.cjs +171 -16
  15. package/dist/mysql.cjs.map +1 -1
  16. package/dist/mysql.d.cts +447 -5
  17. package/dist/mysql.d.ts +447 -5
  18. package/dist/mysql.js +2 -2
  19. package/dist/names-DD-kYSFO.d.cts +146 -0
  20. package/dist/names-DD-kYSFO.d.ts +146 -0
  21. package/dist/pg.cjs +171 -16
  22. package/dist/pg.cjs.map +1 -1
  23. package/dist/pg.d.cts +447 -5
  24. package/dist/pg.d.ts +447 -5
  25. package/dist/pg.js +2 -2
  26. package/dist/sqlite.cjs +171 -16
  27. package/dist/sqlite.cjs.map +1 -1
  28. package/dist/sqlite.d.cts +469 -5
  29. package/dist/sqlite.d.ts +469 -5
  30. package/dist/sqlite.js +2 -2
  31. package/package.json +5 -2
  32. package/sql/mysql-expiry.sql +9 -0
  33. package/sql/pg-expiry.sql +8 -0
  34. package/sql/sqlite-expiry.sql +10 -0
  35. package/dist/chunk-5GEP46FS.js.map +0 -1
  36. package/dist/chunk-7DROVIVH.js.map +0 -1
  37. package/dist/chunk-I4GXEURO.js.map +0 -1
  38. package/dist/chunk-VQYJULOM.js.map +0 -1
  39. package/dist/names-BVofJeMN.d.cts +0 -13
  40. package/dist/names-BVofJeMN.d.ts +0 -13
@@ -0,0 +1,146 @@
1
+ import { RbacAdapter, Permission, FindPermissionsQuery, Id, TeamId, Role, FindRolesQuery, RolePermissionLink, Subject, AttachLinkOptions, ActiveLinkOptions, SubjectRoleLink, SubjectPermissionLink, DeletedLinkCounts, SubjectLinks } from '@anievo-id/rbac-evolution';
2
+ import { Table, AnyColumn } from 'drizzle-orm';
3
+
4
+ /** Structural shape shared by the PostgreSQL, SQLite and MySQL schemas. */
5
+ interface RbacTables {
6
+ permissions: Table & {
7
+ id: AnyColumn;
8
+ name: AnyColumn;
9
+ guardName: AnyColumn;
10
+ };
11
+ roles: Table & {
12
+ id: AnyColumn;
13
+ name: AnyColumn;
14
+ guardName: AnyColumn;
15
+ teamId: AnyColumn;
16
+ };
17
+ roleHasPermissions: Table & {
18
+ roleId: AnyColumn;
19
+ permissionId: AnyColumn;
20
+ };
21
+ /** `expiresAt` only in a schema built with `{ expiry: true }`. */
22
+ modelHasRoles: Table & {
23
+ roleId: AnyColumn;
24
+ subjectType: AnyColumn;
25
+ subjectId: AnyColumn;
26
+ teamId: AnyColumn;
27
+ expiresAt?: AnyColumn;
28
+ };
29
+ modelHasPermissions: Table & {
30
+ permissionId: AnyColumn;
31
+ subjectType: AnyColumn;
32
+ subjectId: AnyColumn;
33
+ teamId: AnyColumn;
34
+ expiresAt?: AnyColumn;
35
+ };
36
+ }
37
+ /** Options of `drizzlePgAdapter()`, `drizzleSqliteAdapter()` and `drizzleMysqlAdapter()`. */
38
+ interface DrizzleAdapterOptions {
39
+ /**
40
+ * Store an expiry per role assignment and direct permission (`assignRole(role, { expiresAt })`). Needs the
41
+ * schema built with `{ expiry: true }` and the `expires_at` column in the database (`sql/<dialect>-expiry.sql`).
42
+ * Default: `false`: the adapter never reads or writes that column, so 1.1 tables keep working unchanged.
43
+ */
44
+ expiry?: boolean | undefined;
45
+ }
46
+ /**
47
+ * The PostgreSQL, SQLite and MySQL query builders expose the same chainable API
48
+ * (`select/insert/delete`, `selectDistinct`) but have incompatible static types. The public factories
49
+ * (`drizzlePgAdapter`, `drizzleSqliteAdapter`, `drizzleMysqlAdapter`) are strictly typed; internally the
50
+ * builder is used untyped and every row is mapped explicitly.
51
+ */
52
+ type UntypedDb = any;
53
+ /**
54
+ * SQL dialect of the Drizzle database. It only changes how inserts are written:
55
+ * - `'pg'` / `'sqlite'`: `INSERT ... RETURNING` and `ON CONFLICT DO NOTHING`
56
+ * - `'mysql'`: `$returningId()` (no `RETURNING` in MySQL) and a no-op `ON DUPLICATE KEY UPDATE`
57
+ */
58
+ type DrizzleDialect = 'pg' | 'sqlite' | 'mysql';
59
+ /**
60
+ * Dialect-agnostic Drizzle implementation of `RbacAdapter`.
61
+ * Use `drizzlePgAdapter()`, `drizzleSqliteAdapter()` or `drizzleMysqlAdapter()` to construct it.
62
+ */
63
+ declare class DrizzleRbacAdapter implements RbacAdapter {
64
+ private readonly db;
65
+ private readonly t;
66
+ private readonly dialect;
67
+ /** `true` with `{ expiry: true }`: the engine may then pass `expiresAt`. */
68
+ readonly supportsExpiry: boolean;
69
+ constructor(db: UntypedDb, t: RbacTables, dialect?: DrizzleDialect, options?: DrizzleAdapterOptions);
70
+ /**
71
+ * Runs `fn` in a transaction (a savepoint when `db` is already a transaction). SQLite runs without one:
72
+ * better-sqlite3 and bun:sqlite only accept synchronous transaction callbacks, and libsql `:memory:` would
73
+ * open a separate, empty database.
74
+ */
75
+ private atomically;
76
+ createPermission(data: {
77
+ name: string;
78
+ guardName: string;
79
+ }): Promise<Permission>;
80
+ findPermissions(query?: FindPermissionsQuery): Promise<Permission[]>;
81
+ deletePermission(id: Id): Promise<void>;
82
+ createRole(data: {
83
+ name: string;
84
+ guardName: string;
85
+ teamId: TeamId;
86
+ }): Promise<Role>;
87
+ findRoles(query?: FindRolesQuery): Promise<Role[]>;
88
+ deleteRole(id: Id): Promise<void>;
89
+ getRolePermissionLinks(roleIds: readonly Id[]): Promise<RolePermissionLink[]>;
90
+ attachRolePermissions(roleId: Id, permissionIds: readonly Id[]): Promise<void>;
91
+ detachRolePermissions(roleId: Id, permissionIds?: readonly Id[]): Promise<void>;
92
+ getSubjectRoleIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
93
+ attachSubjectRoles(subject: Subject, roleIds: readonly Id[], teamId: TeamId, options?: AttachLinkOptions): Promise<void>;
94
+ detachSubjectRoles(subject: Subject, roleIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
95
+ getSubjectPermissionIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
96
+ attachSubjectPermissions(subject: Subject, permissionIds: readonly Id[], teamId: TeamId, options?: AttachLinkOptions): Promise<void>;
97
+ detachSubjectPermissions(subject: Subject, permissionIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
98
+ getSubjectIdsWithRoles(subjectType: string, roleIds: readonly Id[], teamId: TeamId, options?: ActiveLinkOptions): Promise<Id[]>;
99
+ getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId, options?: ActiveLinkOptions): Promise<Id[]>;
100
+ getSubjectRoleLinks(subject: Subject, teamId: TeamId): Promise<SubjectRoleLink[]>;
101
+ getSubjectPermissionLinks(subject: Subject, teamId: TeamId): Promise<SubjectPermissionLink[]>;
102
+ deleteExpiredLinks(now: Date): Promise<DeletedLinkCounts>;
103
+ getSubjectLinks(subject: Subject): Promise<SubjectLinks>;
104
+ getTeamLinks(teamId: Id): Promise<SubjectLinks>;
105
+ detachTeamLinks(teamId: Id): Promise<void>;
106
+ /** Link rows matching `where` (subject and/or team), compared exactly (see `sameLink`). */
107
+ private exactRows;
108
+ private static toSubjectLinks;
109
+ /** The columns of a link row; `expiresAt` only with `{ expiry: true }` (1.1 tables don't have it). */
110
+ private linkColumns;
111
+ private static first;
112
+ /** MySQL has no `INSERT ... RETURNING`: insert, then read the generated auto-increment id. */
113
+ private insertReturningId;
114
+ /**
115
+ * Idempotent multi-row insert into a link table (every column is part of the primary key).
116
+ * PostgreSQL / SQLite: `ON CONFLICT DO NOTHING`. MySQL: `ON DUPLICATE KEY UPDATE col = col`, a no-op
117
+ * update that — unlike `INSERT IGNORE` — still reports foreign-key and other errors.
118
+ */
119
+ private insertIgnoringDuplicates;
120
+ private static subjectWhere;
121
+ /** The subject's link rows, compared exactly (see `sameLink`). */
122
+ private linkRows;
123
+ private getLinks;
124
+ private attach;
125
+ private detach;
126
+ private reverse;
127
+ }
128
+
129
+ interface RbacSchemaOptions {
130
+ /** Prepended to every table name, e.g. `'rbac_'` → `rbac_permissions`. Default: `''`. */
131
+ prefix?: string | undefined;
132
+ /**
133
+ * Add the nullable `expires_at` column to `model_has_roles` and `model_has_permissions` (1.2), for an adapter
134
+ * created with `{ expiry: true }`. Default: `false` (the 1.1 tables).
135
+ */
136
+ expiry?: boolean | undefined;
137
+ }
138
+ interface RbacTableNames {
139
+ permissions: string;
140
+ roles: string;
141
+ roleHasPermissions: string;
142
+ modelHasRoles: string;
143
+ modelHasPermissions: string;
144
+ }
145
+
146
+ export { type DrizzleAdapterOptions as D, type RbacSchemaOptions as R, type DrizzleDialect as a, DrizzleRbacAdapter as b, type RbacTableNames as c, type RbacTables as d };
package/dist/pg.cjs CHANGED
@@ -32,16 +32,37 @@ var toRole = (row) => ({
32
32
  guardName: row.guardName,
33
33
  teamId: teamFromKey(row.teamId)
34
34
  });
35
+ var expiryOf = (row) => row.expiresAt === void 0 ? {} : { expiresAt: row.expiresAt ?? null };
36
+ var toRoleLink = (row) => ({
37
+ subject: { type: row.subjectType, id: row.subjectId },
38
+ roleId: Number(row.id),
39
+ teamId: teamFromKey(row.teamId),
40
+ ...expiryOf(row)
41
+ });
42
+ var toPermissionLink = (row) => ({
43
+ subject: { type: row.subjectType, id: row.subjectId },
44
+ permissionId: Number(row.id),
45
+ teamId: teamFromKey(row.teamId),
46
+ ...expiryOf(row)
47
+ });
35
48
  var sameLink = (row, subjectType, subjectId, team) => row.subjectType === subjectType && (subjectId === void 0 || row.subjectId === subjectId) && row.teamId === team;
36
49
  var DrizzleRbacAdapter = class _DrizzleRbacAdapter {
37
- constructor(db, t, dialect = "pg") {
50
+ constructor(db, t, dialect = "pg", options = {}) {
38
51
  this.db = db;
39
52
  this.t = t;
40
53
  this.dialect = dialect;
54
+ this.supportsExpiry = options.expiry === true;
55
+ if (this.supportsExpiry && (t.modelHasRoles.expiresAt === void 0 || t.modelHasPermissions.expiresAt === void 0)) {
56
+ throw new TypeError(
57
+ "rbac-evolution-drizzle: `{ expiry: true }` needs the tables with the `expiresAt` column: build them with `{ expiry: true }`."
58
+ );
59
+ }
41
60
  }
42
61
  db;
43
62
  t;
44
63
  dialect;
64
+ /** `true` with `{ expiry: true }`: the engine may then pass `expiresAt`. */
65
+ supportsExpiry;
45
66
  /**
46
67
  * Runs `fn` in a transaction (a savepoint when `db` is already a transaction). SQLite runs without one:
47
68
  * better-sqlite3 and bun:sqlite only accept synchronous transaction callbacks, and libsql `:memory:` would
@@ -166,8 +187,8 @@ var DrizzleRbacAdapter = class _DrizzleRbacAdapter {
166
187
  getSubjectRoleIds(subject, teamId) {
167
188
  return this.getLinks(this.t.modelHasRoles, this.t.modelHasRoles.roleId, subject, teamId);
168
189
  }
169
- attachSubjectRoles(subject, roleIds, teamId) {
170
- return this.attach(this.t.modelHasRoles, "roleId", subject, roleIds, teamId);
190
+ attachSubjectRoles(subject, roleIds, teamId, options) {
191
+ return this.attach(this.t.modelHasRoles, "roleId", this.t.modelHasRoles.roleId, subject, roleIds, teamId, options);
171
192
  }
172
193
  detachSubjectRoles(subject, roleIds, teamId) {
173
194
  return this.detach(this.t.modelHasRoles, this.t.modelHasRoles.roleId, subject, roleIds, teamId);
@@ -175,8 +196,9 @@ var DrizzleRbacAdapter = class _DrizzleRbacAdapter {
175
196
  getSubjectPermissionIds(subject, teamId) {
176
197
  return this.getLinks(this.t.modelHasPermissions, this.t.modelHasPermissions.permissionId, subject, teamId);
177
198
  }
178
- attachSubjectPermissions(subject, permissionIds, teamId) {
179
- return this.attach(this.t.modelHasPermissions, "permissionId", subject, permissionIds, teamId);
199
+ attachSubjectPermissions(subject, permissionIds, teamId, options) {
200
+ const { modelHasPermissions: table } = this.t;
201
+ return this.attach(table, "permissionId", table.permissionId, subject, permissionIds, teamId, options);
180
202
  }
181
203
  detachSubjectPermissions(subject, permissionIds, teamId) {
182
204
  return this.detach(
@@ -187,18 +209,100 @@ var DrizzleRbacAdapter = class _DrizzleRbacAdapter {
187
209
  teamId
188
210
  );
189
211
  }
190
- getSubjectIdsWithRoles(subjectType, roleIds, teamId) {
191
- return this.reverse(this.t.modelHasRoles, this.t.modelHasRoles.roleId, subjectType, roleIds, teamId);
212
+ getSubjectIdsWithRoles(subjectType, roleIds, teamId, options) {
213
+ return this.reverse(this.t.modelHasRoles, this.t.modelHasRoles.roleId, subjectType, roleIds, teamId, options);
192
214
  }
193
- getSubjectIdsWithPermissions(subjectType, permissionIds, teamId) {
215
+ getSubjectIdsWithPermissions(subjectType, permissionIds, teamId, options) {
194
216
  return this.reverse(
195
217
  this.t.modelHasPermissions,
196
218
  this.t.modelHasPermissions.permissionId,
197
219
  subjectType,
198
220
  permissionIds,
199
- teamId
221
+ teamId,
222
+ options
200
223
  );
201
224
  }
225
+ // ----------------------------------------------------------- expiry (optional)
226
+ async getSubjectRoleLinks(subject, teamId) {
227
+ return (await this.linkRows(this.t.modelHasRoles, this.t.modelHasRoles.roleId, subject, teamId)).map(toRoleLink);
228
+ }
229
+ async getSubjectPermissionLinks(subject, teamId) {
230
+ const { modelHasPermissions: table } = this.t;
231
+ return (await this.linkRows(table, table.permissionId, subject, teamId)).map(toPermissionLink);
232
+ }
233
+ async deleteExpiredLinks(now) {
234
+ if (!this.supportsExpiry) return { roles: 0, permissions: 0 };
235
+ const remove = async (table, target) => {
236
+ const query = this.db.delete(table).where(drizzleOrm.lte(table.expiresAt, now));
237
+ if (this.dialect !== "mysql") return (await query.returning({ id: target })).length;
238
+ const result = await query;
239
+ const header = Array.isArray(result) ? result[0] : result;
240
+ return Number(header?.affectedRows ?? header?.rowsAffected ?? 0);
241
+ };
242
+ return {
243
+ roles: await remove(this.t.modelHasRoles, this.t.modelHasRoles.roleId),
244
+ permissions: await remove(this.t.modelHasPermissions, this.t.modelHasPermissions.permissionId)
245
+ };
246
+ }
247
+ // ------------------------------------------------------------- bulk (optional)
248
+ async getSubjectLinks(subject) {
249
+ const where = { subjectType: subject.type, subjectId: String(subject.id) };
250
+ return _DrizzleRbacAdapter.toSubjectLinks(
251
+ await this.exactRows(this.db, this.t.modelHasRoles, this.t.modelHasRoles.roleId, where),
252
+ await this.exactRows(this.db, this.t.modelHasPermissions, this.t.modelHasPermissions.permissionId, where)
253
+ );
254
+ }
255
+ async getTeamLinks(teamId) {
256
+ const team = teamKey(teamId);
257
+ if (team === GLOBAL_TEAM) return { roles: [], permissions: [] };
258
+ return _DrizzleRbacAdapter.toSubjectLinks(
259
+ await this.exactRows(this.db, this.t.modelHasRoles, this.t.modelHasRoles.roleId, { teamId: team }),
260
+ await this.exactRows(this.db, this.t.modelHasPermissions, this.t.modelHasPermissions.permissionId, {
261
+ teamId: team
262
+ })
263
+ );
264
+ }
265
+ async detachTeamLinks(teamId) {
266
+ const team = teamKey(teamId);
267
+ if (team === GLOBAL_TEAM) return;
268
+ const tables = [
269
+ [this.t.modelHasRoles, this.t.modelHasRoles.roleId],
270
+ [this.t.modelHasPermissions, this.t.modelHasPermissions.permissionId]
271
+ ];
272
+ await this.atomically(async (db) => {
273
+ for (const [table, target] of tables) {
274
+ const bySubject = /* @__PURE__ */ new Map();
275
+ for (const row of await this.exactRows(db, table, target, { teamId: team })) {
276
+ const k = JSON.stringify([row.subjectType, row.subjectId]);
277
+ const entry = bySubject.get(k) ?? { subject: { type: row.subjectType, id: row.subjectId }, ids: [] };
278
+ entry.ids.push(Number(row.id));
279
+ bySubject.set(k, entry);
280
+ }
281
+ for (const { subject, ids } of bySubject.values()) {
282
+ await db.delete(table).where(drizzleOrm.and(..._DrizzleRbacAdapter.subjectWhere(table, subject, teamId), drizzleOrm.inArray(target, ids)));
283
+ }
284
+ }
285
+ });
286
+ }
287
+ /** Link rows matching `where` (subject and/or team), compared exactly (see `sameLink`). */
288
+ async exactRows(db, table, target, where) {
289
+ const filters = [];
290
+ if (where.subjectType !== void 0) filters.push(drizzleOrm.eq(table.subjectType, where.subjectType));
291
+ if (where.subjectId !== void 0) filters.push(drizzleOrm.eq(table.subjectId, where.subjectId));
292
+ if (where.teamId !== void 0) filters.push(drizzleOrm.eq(table.teamId, where.teamId));
293
+ const rows = await db.select(this.linkColumns(table, target)).from(table).where(drizzleOrm.and(...filters));
294
+ return rows.filter(
295
+ (row) => (where.subjectType === void 0 || row.subjectType === where.subjectType) && (where.subjectId === void 0 || row.subjectId === where.subjectId) && (where.teamId === void 0 || row.teamId === where.teamId)
296
+ );
297
+ }
298
+ static toSubjectLinks(roles, permissions) {
299
+ return { roles: roles.map(toRoleLink), permissions: permissions.map(toPermissionLink) };
300
+ }
301
+ /** The columns of a link row; `expiresAt` only with `{ expiry: true }` (1.1 tables don't have it). */
302
+ linkColumns(table, target) {
303
+ const columns = { id: target, subjectType: table.subjectType, subjectId: table.subjectId, teamId: table.teamId };
304
+ return this.supportsExpiry ? { ...columns, expiresAt: table.expiresAt } : columns;
305
+ }
202
306
  // -------------------------------------------------------------------- helpers
203
307
  static first(rows) {
204
308
  const row = rows[0];
@@ -232,22 +336,28 @@ var DrizzleRbacAdapter = class _DrizzleRbacAdapter {
232
336
  }
233
337
  /** The subject's link rows, compared exactly (see `sameLink`). */
234
338
  async linkRows(table, target, subject, teamId) {
235
- const rows = await this.db.select({ id: target, subjectType: table.subjectType, subjectId: table.subjectId, teamId: table.teamId }).from(table).where(drizzleOrm.and(..._DrizzleRbacAdapter.subjectWhere(table, subject, teamId)));
339
+ const rows = await this.db.select(this.linkColumns(table, target)).from(table).where(drizzleOrm.and(..._DrizzleRbacAdapter.subjectWhere(table, subject, teamId)));
236
340
  return rows.filter((row) => sameLink(row, subject.type, String(subject.id), teamKey(teamId)));
237
341
  }
238
342
  async getLinks(table, target, subject, teamId) {
239
343
  return (await this.linkRows(table, target, subject, teamId)).map((row) => Number(row.id));
240
344
  }
241
- async attach(table, targetKey, subject, targetIds, teamId) {
345
+ async attach(table, targetKey, target, subject, targetIds, teamId, options) {
242
346
  const ids = toIntIds(targetIds);
243
347
  if (ids.length === 0) return;
244
348
  const base = { subjectType: subject.type, subjectId: String(subject.id), teamId: teamKey(teamId) };
349
+ const expiry = this.supportsExpiry ? { expiresAt: options?.expiresAt ?? null } : {};
245
350
  await this.insertIgnoringDuplicates(
246
351
  table,
247
- ids.map((id) => ({ ...base, [targetKey]: id })),
352
+ ids.map((id) => ({ ...base, [targetKey]: id, ...expiry })),
248
353
  "subjectType",
249
354
  table.subjectType
250
355
  );
356
+ if (expiry.expiresAt === void 0) return;
357
+ const wanted = new Set(ids);
358
+ const held = (await this.linkRows(table, target, subject, teamId)).map((row) => Number(row.id)).filter((id) => wanted.has(id));
359
+ if (held.length === 0) return;
360
+ await this.db.update(table).set({ expiresAt: expiry.expiresAt }).where(drizzleOrm.and(..._DrizzleRbacAdapter.subjectWhere(table, subject, teamId), drizzleOrm.inArray(target, held)));
251
361
  }
252
362
  async detach(table, target, subject, targetIds, teamId) {
253
363
  const wanted = targetIds === void 0 ? void 0 : new Set(toIntIds(targetIds));
@@ -256,11 +366,13 @@ var DrizzleRbacAdapter = class _DrizzleRbacAdapter {
256
366
  if (ids.length === 0) return;
257
367
  await this.db.delete(table).where(drizzleOrm.and(..._DrizzleRbacAdapter.subjectWhere(table, subject, teamId), drizzleOrm.inArray(target, ids)));
258
368
  }
259
- async reverse(table, target, subjectType, targetIds, teamId) {
369
+ async reverse(table, target, subjectType, targetIds, teamId, options) {
260
370
  const ids = toIntIds(targetIds);
261
371
  if (ids.length === 0) return [];
262
372
  const team = teamKey(teamId);
263
- const rows = await this.db.selectDistinct({ subjectType: table.subjectType, subjectId: table.subjectId, teamId: table.teamId }).from(table).where(drizzleOrm.and(drizzleOrm.eq(table.subjectType, subjectType), drizzleOrm.eq(table.teamId, team), drizzleOrm.inArray(target, ids)));
373
+ const where = [drizzleOrm.eq(table.subjectType, subjectType), drizzleOrm.eq(table.teamId, team), drizzleOrm.inArray(target, ids)];
374
+ if (this.supportsExpiry && options) where.push(drizzleOrm.or(drizzleOrm.isNull(table.expiresAt), drizzleOrm.gt(table.expiresAt, options.now)));
375
+ const rows = await this.db.selectDistinct({ subjectType: table.subjectType, subjectId: table.subjectId, teamId: table.teamId }).from(table).where(drizzleOrm.and(...where));
264
376
  const exact = rows.filter((row) => sameLink(row, subjectType, void 0, team));
265
377
  return [...new Set(exact.map((row) => row.subjectId))];
266
378
  }
@@ -284,6 +396,9 @@ var timestamps = () => ({
284
396
  updatedAt: pgCore.timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
285
397
  });
286
398
  function pgRbacSchema(options = {}) {
399
+ return options.expiry === true ? buildPgExpiry(options) : buildPg(options);
400
+ }
401
+ function buildPg(options) {
287
402
  const n = tableNames(options);
288
403
  const permissions = pgCore.pgTable(
289
404
  n.permissions,
@@ -351,10 +466,50 @@ function pgRbacSchema(options = {}) {
351
466
  );
352
467
  return { permissions, roles, roleHasPermissions, modelHasRoles, modelHasPermissions };
353
468
  }
469
+ function buildPgExpiry(options) {
470
+ const n = tableNames(options);
471
+ const { permissions, roles, roleHasPermissions } = buildPg(options);
472
+ const modelHasRoles = pgCore.pgTable(
473
+ n.modelHasRoles,
474
+ {
475
+ roleId: pgCore.integer("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
476
+ subjectType: pgCore.text("subject_type").notNull(),
477
+ subjectId: pgCore.text("subject_id").notNull(),
478
+ /** `''` = global (no team). */
479
+ teamId: pgCore.text("team_id").notNull().default(""),
480
+ /** When the link ends (`NULL` = never). Only used by an adapter created with `{ expiry: true }`. */
481
+ expiresAt: pgCore.timestamp("expires_at", { withTimezone: true, mode: "date" })
482
+ },
483
+ (t) => [
484
+ pgCore.primaryKey({ name: `${n.modelHasRoles}_pkey`, columns: [t.subjectType, t.subjectId, t.teamId, t.roleId] }),
485
+ pgCore.index(`${n.modelHasRoles}_role_id_index`).on(t.roleId)
486
+ ]
487
+ );
488
+ const modelHasPermissions = pgCore.pgTable(
489
+ n.modelHasPermissions,
490
+ {
491
+ permissionId: pgCore.integer("permission_id").notNull().references(() => permissions.id, { onDelete: "cascade" }),
492
+ subjectType: pgCore.text("subject_type").notNull(),
493
+ subjectId: pgCore.text("subject_id").notNull(),
494
+ /** `''` = global (no team). */
495
+ teamId: pgCore.text("team_id").notNull().default(""),
496
+ /** When the link ends (`NULL` = never). Only used by an adapter created with `{ expiry: true }`. */
497
+ expiresAt: pgCore.timestamp("expires_at", { withTimezone: true, mode: "date" })
498
+ },
499
+ (t) => [
500
+ pgCore.primaryKey({
501
+ name: `${n.modelHasPermissions}_pkey`,
502
+ columns: [t.subjectType, t.subjectId, t.teamId, t.permissionId]
503
+ }),
504
+ pgCore.index(`${n.modelHasPermissions}_permission_id_index`).on(t.permissionId)
505
+ ]
506
+ );
507
+ return { permissions, roles, roleHasPermissions, modelHasRoles, modelHasPermissions };
508
+ }
354
509
 
355
510
  // src/pg.ts
356
- function drizzlePgAdapter(db, schema = pgRbacSchema()) {
357
- return new DrizzleRbacAdapter(db, schema, "pg");
511
+ function drizzlePgAdapter(db, schema = pgRbacSchema(), options = {}) {
512
+ return new DrizzleRbacAdapter(db, schema, "pg", options);
358
513
  }
359
514
 
360
515
  exports.drizzlePgAdapter = drizzlePgAdapter;