@headless-lms/adapter-db 0.4.0 → 0.6.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 (94) hide show
  1. package/dist/client.d.ts +8 -2
  2. package/dist/client.js +10 -2
  3. package/dist/client.js.map +1 -1
  4. package/dist/index.d.ts +5 -4
  5. package/dist/index.js +4 -3
  6. package/dist/repositories/admin.d.ts +12 -4
  7. package/dist/repositories/admin.js +164 -22
  8. package/dist/repositories/admin.js.map +1 -1
  9. package/dist/repositories/assets.d.ts +2 -1
  10. package/dist/repositories/assets.js +12 -1
  11. package/dist/repositories/assets.js.map +1 -1
  12. package/dist/repositories/automations.js +1 -1
  13. package/dist/repositories/chats.d.ts +13 -4
  14. package/dist/repositories/chats.js +164 -70
  15. package/dist/repositories/chats.js.map +1 -1
  16. package/dist/repositories/content.d.ts +22 -5
  17. package/dist/repositories/content.js +201 -40
  18. package/dist/repositories/content.js.map +1 -1
  19. package/dist/repositories/credentials.js +1 -1
  20. package/dist/repositories/devices.js +1 -1
  21. package/dist/repositories/digest-runs.js +1 -1
  22. package/dist/repositories/discussion.d.ts +1 -1
  23. package/dist/repositories/discussion.js +9 -3
  24. package/dist/repositories/discussion.js.map +1 -1
  25. package/dist/repositories/entitlements.d.ts +10 -10
  26. package/dist/repositories/entitlements.js +47 -56
  27. package/dist/repositories/entitlements.js.map +1 -1
  28. package/dist/repositories/event-reports.d.ts +16 -0
  29. package/dist/repositories/event-reports.js +199 -0
  30. package/dist/repositories/event-reports.js.map +1 -0
  31. package/dist/repositories/grant-covers.d.ts +4 -3
  32. package/dist/repositories/grant-covers.js +7 -4
  33. package/dist/repositories/grant-covers.js.map +1 -1
  34. package/dist/repositories/identity.js +1 -1
  35. package/dist/repositories/integrations.js +1 -1
  36. package/dist/repositories/member.d.ts +12 -4
  37. package/dist/repositories/member.js +19 -7
  38. package/dist/repositories/member.js.map +1 -1
  39. package/dist/repositories/members.d.ts +2 -5
  40. package/dist/repositories/members.js +39 -94
  41. package/dist/repositories/members.js.map +1 -1
  42. package/dist/repositories/mentions.js +1 -1
  43. package/dist/repositories/notification-settings.js +1 -1
  44. package/dist/repositories/notifications.js +2 -2
  45. package/dist/repositories/notifications.js.map +1 -1
  46. package/dist/repositories/org-user-profile.d.ts +0 -17
  47. package/dist/repositories/org-user-profile.js +0 -1
  48. package/dist/repositories/org-user-profile.js.map +1 -1
  49. package/dist/repositories/organizations.d.ts +4 -4
  50. package/dist/repositories/organizations.js +26 -46
  51. package/dist/repositories/organizations.js.map +1 -1
  52. package/dist/repositories/outbox.d.ts +5 -1
  53. package/dist/repositories/outbox.js +12 -3
  54. package/dist/repositories/outbox.js.map +1 -1
  55. package/dist/repositories/posts.js +1 -1
  56. package/dist/repositories/progress.js +1 -1
  57. package/dist/repositories/roles.d.ts +35 -0
  58. package/dist/repositories/roles.js +244 -0
  59. package/dist/repositories/roles.js.map +1 -0
  60. package/dist/repositories/settings.js +1 -1
  61. package/dist/repositories/subscriptions.js +1 -1
  62. package/dist/schema/assets.d.ts +17 -0
  63. package/dist/schema/assets.js +1 -0
  64. package/dist/schema/assets.js.map +1 -1
  65. package/dist/schema/automations.d.ts +3 -3
  66. package/dist/schema/automations.js +1 -1
  67. package/dist/schema/automations.js.map +1 -1
  68. package/dist/schema/content.d.ts +488 -3
  69. package/dist/schema/content.js +89 -4
  70. package/dist/schema/content.js.map +1 -1
  71. package/dist/schema/discussion.d.ts +17 -0
  72. package/dist/schema/discussion.js +4 -2
  73. package/dist/schema/discussion.js.map +1 -1
  74. package/dist/schema/index.d.ts +4 -3
  75. package/dist/schema/index.js +7 -2
  76. package/dist/schema/index.js.map +1 -1
  77. package/dist/schema/organizations.d.ts +24 -22
  78. package/dist/schema/organizations.js +3 -14
  79. package/dist/schema/organizations.js.map +1 -1
  80. package/dist/schema/roles.d.ts +369 -0
  81. package/dist/schema/roles.js +71 -0
  82. package/dist/schema/roles.js.map +1 -0
  83. package/drizzle/0017_configurable_roles.sql +38 -0
  84. package/drizzle/0018_messages_client_id.sql +2 -0
  85. package/drizzle/0019_events.sql +44 -0
  86. package/drizzle/0020_space_images.sql +9 -0
  87. package/drizzle/0021_org_metadata.sql +1 -0
  88. package/drizzle/meta/0017_snapshot.json +9518 -0
  89. package/drizzle/meta/0018_snapshot.json +9557 -0
  90. package/drizzle/meta/0019_snapshot.json +9919 -0
  91. package/drizzle/meta/0020_snapshot.json +10045 -0
  92. package/drizzle/meta/0021_snapshot.json +10052 -0
  93. package/drizzle/meta/_journal.json +35 -0
  94. package/package.json +2 -2
@@ -0,0 +1,35 @@
1
+ import { NodePgDatabase } from "drizzle-orm/node-postgres";
2
+ import { ActorFacts, AssignmentRow, CallerFacts, RolesRepository, StoredOrgRole } from "@headless-lms/core/organizations";
3
+ import { ContentType, RoleAssignment } from "@headless-lms/core/types";
4
+ //#region src/repositories/roles.d.ts
5
+ declare class DrizzleRolesRepository implements RolesRepository {
6
+ private readonly db;
7
+ constructor(db: NodePgDatabase);
8
+ actorFacts(orgId: string, orgUserId: string): Promise<ActorFacts | null>;
9
+ callerFacts(authOrgId: string, authUserId: string): Promise<CallerFacts | null>;
10
+ storedRoles(orgId: string): Promise<StoredOrgRole[]>;
11
+ saveStoredRole(orgId: string, role: StoredOrgRole): Promise<void>;
12
+ deleteStoredRole(orgId: string, key: string): Promise<boolean>;
13
+ assignmentsOf(orgId: string, orgUserId: string): Promise<RoleAssignment[]>;
14
+ assignmentsOfMany(orgId: string, orgUserIds: string[]): Promise<Map<string, AssignmentRow[]>>;
15
+ assignmentsOn(orgId: string, contentId: string): Promise<RoleAssignment[]>;
16
+ holdersOf(orgId: string, roleKeys: string[], contentId?: string): Promise<string[]>;
17
+ setOrgRole(orgId: string, orgUserId: string, roleKey: string | null, assignedBy: string): Promise<void>;
18
+ setItemRole(orgId: string, orgUserId: string, contentId: string, contentType: ContentType, roleKey: string, assignedBy: string): Promise<void>;
19
+ removeItemRole(orgId: string, orgUserId: string, contentId: string): Promise<RoleAssignment | null>;
20
+ countHolders(orgId: string, roleKey: string, contentType?: ContentType | "org"): Promise<number>;
21
+ holderCounts(orgId: string): Promise<Record<string, number>>;
22
+ contentTypeOf(orgId: string, contentId: string): Promise<ContentType | null>;
23
+ ownerOrgUserId(orgId: string): Promise<string | null>;
24
+ roleKeyUsage(): Promise<{
25
+ orgId: string;
26
+ roleKey: string;
27
+ level: string;
28
+ count: number;
29
+ stored: boolean;
30
+ }[]>;
31
+ lock(keys: string[]): Promise<void>;
32
+ }
33
+ //#endregion
34
+ export { DrizzleRolesRepository };
35
+ //# sourceMappingURL=roles.d.ts.map
@@ -0,0 +1,244 @@
1
+ import { contentItems } from "../schema/content.js";
2
+ import { orgUsers } from "../schema/organizations.js";
3
+ import { orgRoles, roleAssignments } from "../schema/roles.js";
4
+ import { translateDbErrors } from "./pg-errors.js";
5
+ import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";
6
+ import { OWNER_ROLE_KEY } from "@headless-lms/core/organizations";
7
+ //#region src/repositories/roles.ts
8
+ function toStored(row) {
9
+ return {
10
+ key: row.key,
11
+ name: row.name,
12
+ description: row.description,
13
+ base: row.base,
14
+ levels: row.levels ?? null,
15
+ permissions: row.permissions,
16
+ team: row.team
17
+ };
18
+ }
19
+ function toAssignment(row) {
20
+ return {
21
+ id: row.id,
22
+ orgId: row.orgId,
23
+ orgUserId: row.orgUserId,
24
+ roleKey: row.roleKey,
25
+ contentId: row.contentId,
26
+ contentType: row.contentType,
27
+ assignedBy: row.assignedBy,
28
+ createdAt: row.createdAt
29
+ };
30
+ }
31
+ function toRow(row) {
32
+ return {
33
+ roleKey: row.roleKey,
34
+ contentId: row.contentId,
35
+ contentType: row.contentType
36
+ };
37
+ }
38
+ function toStoredJson(role) {
39
+ return {
40
+ key: role.key,
41
+ name: role.name,
42
+ description: role.description,
43
+ base: role.base,
44
+ levels: role.levels ?? null,
45
+ permissions: role.permissions,
46
+ team: role.team
47
+ };
48
+ }
49
+ function assignmentsOf(orgId, orgUserId) {
50
+ return sql`coalesce(
51
+ (select json_agg(json_build_object(
52
+ 'roleKey', ra.role_key,
53
+ 'contentId', ra.content_id,
54
+ 'contentType', ra.content_type))
55
+ from role_assignments ra
56
+ where ra.org_id = ${orgId} and ra.org_user_id = ${orgUserId}),
57
+ '[]'::json
58
+ )`;
59
+ }
60
+ function rolesOf(orgId) {
61
+ return sql`coalesce(
62
+ (select json_agg(json_build_object(
63
+ 'key', r.key,
64
+ 'name', r.name,
65
+ 'description', r.description,
66
+ 'base', r.base,
67
+ 'levels', r.levels,
68
+ 'permissions', r.permissions,
69
+ 'team', r.team))
70
+ from org_roles r
71
+ where r.org_id = ${orgId}),
72
+ '[]'::json
73
+ )`;
74
+ }
75
+ var DrizzleRolesRepository = class {
76
+ db;
77
+ constructor(db) {
78
+ this.db = db;
79
+ }
80
+ async actorFacts(orgId, orgUserId) {
81
+ const row = (await this.db.execute(sql`
82
+ select ou.id as org_user_id, ou.status,
83
+ ${assignmentsOf(sql`ou.org_id`, sql`ou.id`)} as assignments,
84
+ ${rolesOf(sql`ou.org_id`)} as roles
85
+ from org_users ou
86
+ where ou.org_id = ${orgId} and ou.id = ${orgUserId}
87
+ `)).rows[0];
88
+ if (!row?.org_user_id || !row.status) return null;
89
+ return {
90
+ orgUserId: row.org_user_id,
91
+ status: row.status,
92
+ assignments: row.assignments.map(toRow),
93
+ storedRoles: row.roles.map(toStoredJson)
94
+ };
95
+ }
96
+ async callerFacts(authOrgId, authUserId) {
97
+ const row = (await this.db.execute(sql`
98
+ select o.id as org_id, u.id as user_id, ou.id as org_user_id, ou.status,
99
+ ${assignmentsOf(sql`o.id`, sql`ou.id`)} as assignments,
100
+ ${rolesOf(sql`o.id`)} as roles
101
+ from organizations o
102
+ left join users u on u.external_id = ${authUserId}
103
+ left join org_users ou on ou.org_id = o.id and ou.user_id = u.id
104
+ where o.external_id = ${authOrgId}
105
+ limit 1
106
+ `)).rows[0];
107
+ if (!row) return null;
108
+ return {
109
+ orgId: row.org_id,
110
+ userId: row.user_id,
111
+ orgUser: row.org_user_id && row.status ? {
112
+ orgUserId: row.org_user_id,
113
+ status: row.status,
114
+ assignments: row.assignments.map(toRow),
115
+ storedRoles: row.roles.map(toStoredJson)
116
+ } : null
117
+ };
118
+ }
119
+ async storedRoles(orgId) {
120
+ return (await this.db.select().from(orgRoles).where(eq(orgRoles.orgId, orgId))).map(toStored);
121
+ }
122
+ async saveStoredRole(orgId, role) {
123
+ const values = {
124
+ name: role.name,
125
+ description: role.description,
126
+ base: role.base,
127
+ levels: role.levels,
128
+ permissions: role.permissions,
129
+ team: role.team
130
+ };
131
+ await this.db.insert(orgRoles).values({
132
+ orgId,
133
+ key: role.key,
134
+ ...values
135
+ }).onConflictDoUpdate({
136
+ target: [orgRoles.orgId, orgRoles.key],
137
+ set: values
138
+ });
139
+ }
140
+ async deleteStoredRole(orgId, key) {
141
+ return (await this.db.delete(orgRoles).where(and(eq(orgRoles.orgId, orgId), eq(orgRoles.key, key))).returning({ key: orgRoles.key })).length > 0;
142
+ }
143
+ async assignmentsOf(orgId, orgUserId) {
144
+ return (await this.db.select().from(roleAssignments).where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.orgUserId, orgUserId)))).map(toAssignment);
145
+ }
146
+ async assignmentsOfMany(orgId, orgUserIds) {
147
+ const out = /* @__PURE__ */ new Map();
148
+ if (orgUserIds.length === 0) return out;
149
+ const rows = await this.db.select().from(roleAssignments).where(and(eq(roleAssignments.orgId, orgId), inArray(roleAssignments.orgUserId, orgUserIds)));
150
+ for (const row of rows) {
151
+ const list = out.get(row.orgUserId) ?? [];
152
+ list.push(toRow(row));
153
+ out.set(row.orgUserId, list);
154
+ }
155
+ return out;
156
+ }
157
+ async assignmentsOn(orgId, contentId) {
158
+ return (await this.db.select().from(roleAssignments).where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.contentId, contentId)))).map(toAssignment);
159
+ }
160
+ async holdersOf(orgId, roleKeys, contentId) {
161
+ if (roleKeys.length === 0) return [];
162
+ const scope = contentId === void 0 ? isNull(roleAssignments.contentId) : or(isNull(roleAssignments.contentId), eq(roleAssignments.contentId, contentId));
163
+ return (await this.db.selectDistinct({ id: roleAssignments.orgUserId }).from(roleAssignments).innerJoin(orgUsers, and(eq(orgUsers.orgId, roleAssignments.orgId), eq(orgUsers.id, roleAssignments.orgUserId))).where(and(eq(roleAssignments.orgId, orgId), inArray(roleAssignments.roleKey, roleKeys), eq(orgUsers.status, "active"), scope))).map((row) => row.id);
164
+ }
165
+ async setOrgRole(orgId, orgUserId, roleKey, assignedBy) {
166
+ await this.db.delete(roleAssignments).where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.orgUserId, orgUserId), isNull(roleAssignments.contentId)));
167
+ if (roleKey !== null) await this.db.insert(roleAssignments).values({
168
+ orgId,
169
+ orgUserId,
170
+ roleKey,
171
+ contentId: null,
172
+ contentType: null,
173
+ assignedBy
174
+ });
175
+ }
176
+ async setItemRole(orgId, orgUserId, contentId, contentType, roleKey, assignedBy) {
177
+ await this.db.insert(roleAssignments).values({
178
+ orgId,
179
+ orgUserId,
180
+ roleKey,
181
+ contentId,
182
+ contentType,
183
+ assignedBy
184
+ }).onConflictDoUpdate({
185
+ target: [
186
+ roleAssignments.orgId,
187
+ roleAssignments.orgUserId,
188
+ roleAssignments.contentId
189
+ ],
190
+ set: {
191
+ roleKey,
192
+ assignedBy,
193
+ createdAt: /* @__PURE__ */ new Date()
194
+ }
195
+ });
196
+ }
197
+ async removeItemRole(orgId, orgUserId, contentId) {
198
+ const [row] = await this.db.delete(roleAssignments).where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.orgUserId, orgUserId), eq(roleAssignments.contentId, contentId))).returning();
199
+ return row ? toAssignment(row) : null;
200
+ }
201
+ async countHolders(orgId, roleKey, contentType) {
202
+ const level = contentType === void 0 ? void 0 : contentType === "org" ? isNull(roleAssignments.contentId) : eq(roleAssignments.contentType, contentType);
203
+ const [row] = await this.db.select({ n: sql`count(*)::int` }).from(roleAssignments).where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.roleKey, roleKey), level));
204
+ return row?.n ?? 0;
205
+ }
206
+ async holderCounts(orgId) {
207
+ const rows = await this.db.select({
208
+ roleKey: roleAssignments.roleKey,
209
+ n: sql`count(distinct ${roleAssignments.orgUserId})::int`
210
+ }).from(roleAssignments).where(eq(roleAssignments.orgId, orgId)).groupBy(roleAssignments.roleKey);
211
+ return Object.fromEntries(rows.map((row) => [row.roleKey, row.n]));
212
+ }
213
+ async contentTypeOf(orgId, contentId) {
214
+ const [row] = await this.db.select({ type: contentItems.type }).from(contentItems).where(and(eq(contentItems.orgId, orgId), eq(contentItems.id, contentId))).limit(1);
215
+ return row?.type ?? null;
216
+ }
217
+ async ownerOrgUserId(orgId) {
218
+ const [row] = await this.db.select({ id: roleAssignments.orgUserId }).from(roleAssignments).where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.roleKey, OWNER_ROLE_KEY))).limit(1);
219
+ return row?.id ?? null;
220
+ }
221
+ async roleKeyUsage() {
222
+ return (await this.db.execute(sql`
223
+ select ra.org_id, ra.role_key, coalesce(ra.content_type, 'org') as level,
224
+ count(*)::int as count,
225
+ exists (select 1 from org_roles r where r.org_id = ra.org_id and r.key = ra.role_key) as stored
226
+ from role_assignments ra
227
+ group by ra.org_id, ra.role_key, coalesce(ra.content_type, 'org')
228
+ `)).rows.map((row) => ({
229
+ orgId: row.org_id,
230
+ roleKey: row.role_key,
231
+ level: row.level,
232
+ count: row.count,
233
+ stored: row.stored
234
+ }));
235
+ }
236
+ async lock(keys) {
237
+ for (const key of [...new Set(keys)].sort()) await this.db.execute(sql`select pg_advisory_xact_lock(hashtext(${key}))`);
238
+ }
239
+ };
240
+ translateDbErrors(DrizzleRolesRepository);
241
+ //#endregion
242
+ export { DrizzleRolesRepository };
243
+
244
+ //# sourceMappingURL=roles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roles.js","names":[],"sources":["../../src/repositories/roles.ts"],"sourcesContent":["import { and, eq, inArray, isNull, or, sql, type SQL } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport {\n OWNER_ROLE_KEY,\n type ActorFacts,\n type AssignmentRow,\n type CallerFacts,\n type RolesRepository,\n type StoredOrgRole,\n} from \"@headless-lms/core/organizations\";\nimport type { ContentType, Level, Permission, RoleAssignment } from \"@headless-lms/core/types\";\nimport { contentItems } from \"../schema/content.js\";\nimport { orgUsers } from \"../schema/organizations.js\";\nimport { orgRoles, roleAssignments } from \"../schema/roles.js\";\nimport { translateDbErrors } from \"./pg-errors.js\";\n\ntype RoleRow = typeof orgRoles.$inferSelect;\ntype AssignmentRecordRow = typeof roleAssignments.$inferSelect;\n\nfunction toStored(row: RoleRow): StoredOrgRole {\n return {\n key: row.key,\n name: row.name,\n description: row.description,\n base: row.base,\n levels: (row.levels as Level[] | null) ?? null,\n permissions: row.permissions as Partial<Record<Permission, boolean>>,\n team: row.team,\n };\n}\n\nfunction toAssignment(row: AssignmentRecordRow): RoleAssignment {\n return {\n id: row.id,\n orgId: row.orgId,\n orgUserId: row.orgUserId,\n roleKey: row.roleKey,\n contentId: row.contentId,\n contentType: row.contentType,\n assignedBy: row.assignedBy,\n createdAt: row.createdAt,\n };\n}\n\nfunction toRow(row: {\n roleKey: string;\n contentId: string | null;\n contentType: string | null;\n}): AssignmentRow {\n return {\n roleKey: row.roleKey,\n contentId: row.contentId,\n contentType: row.contentType as ContentType | null,\n };\n}\n\ntype StoredRoleJson = {\n key: string;\n name: string | null;\n description: string | null;\n base: string;\n levels: string[] | null;\n permissions: Record<string, boolean>;\n team: boolean | null;\n};\n\ntype FactsRow = {\n org_user_id: string | null;\n status: \"invited\" | \"active\" | null;\n assignments: { roleKey: string; contentId: string | null; contentType: string | null }[];\n roles: StoredRoleJson[];\n};\n\nfunction toStoredJson(role: StoredRoleJson): StoredOrgRole {\n return {\n key: role.key,\n name: role.name,\n description: role.description,\n base: role.base,\n levels: (role.levels as Level[] | null) ?? null,\n permissions: role.permissions as Partial<Record<Permission, boolean>>,\n team: role.team,\n };\n}\n\nfunction assignmentsOf(orgId: SQL, orgUserId: SQL): SQL {\n return sql`coalesce(\n (select json_agg(json_build_object(\n 'roleKey', ra.role_key,\n 'contentId', ra.content_id,\n 'contentType', ra.content_type))\n from role_assignments ra\n where ra.org_id = ${orgId} and ra.org_user_id = ${orgUserId}),\n '[]'::json\n )`;\n}\n\nfunction rolesOf(orgId: SQL): SQL {\n return sql`coalesce(\n (select json_agg(json_build_object(\n 'key', r.key,\n 'name', r.name,\n 'description', r.description,\n 'base', r.base,\n 'levels', r.levels,\n 'permissions', r.permissions,\n 'team', r.team))\n from org_roles r\n where r.org_id = ${orgId}),\n '[]'::json\n )`;\n}\n\nexport class DrizzleRolesRepository implements RolesRepository {\n constructor(private readonly db: NodePgDatabase) {}\n\n async actorFacts(orgId: string, orgUserId: string): Promise<ActorFacts | null> {\n const result = await this.db.execute<FactsRow>(sql`\n select ou.id as org_user_id, ou.status,\n ${assignmentsOf(sql`ou.org_id`, sql`ou.id`)} as assignments,\n ${rolesOf(sql`ou.org_id`)} as roles\n from org_users ou\n where ou.org_id = ${orgId} and ou.id = ${orgUserId}\n `);\n const row = result.rows[0];\n if (!row?.org_user_id || !row.status) {\n return null;\n }\n return {\n orgUserId: row.org_user_id,\n status: row.status,\n assignments: row.assignments.map(toRow),\n storedRoles: row.roles.map(toStoredJson),\n };\n }\n\n async callerFacts(authOrgId: string, authUserId: string): Promise<CallerFacts | null> {\n const result = await this.db.execute<FactsRow & { org_id: string; user_id: string | null }>(sql`\n select o.id as org_id, u.id as user_id, ou.id as org_user_id, ou.status,\n ${assignmentsOf(sql`o.id`, sql`ou.id`)} as assignments,\n ${rolesOf(sql`o.id`)} as roles\n from organizations o\n left join users u on u.external_id = ${authUserId}\n left join org_users ou on ou.org_id = o.id and ou.user_id = u.id\n where o.external_id = ${authOrgId}\n limit 1\n `);\n const row = result.rows[0];\n if (!row) {\n return null;\n }\n return {\n orgId: row.org_id,\n userId: row.user_id,\n orgUser:\n row.org_user_id && row.status\n ? {\n orgUserId: row.org_user_id,\n status: row.status,\n assignments: row.assignments.map(toRow),\n storedRoles: row.roles.map(toStoredJson),\n }\n : null,\n };\n }\n\n async storedRoles(orgId: string): Promise<StoredOrgRole[]> {\n const rows = await this.db.select().from(orgRoles).where(eq(orgRoles.orgId, orgId));\n return rows.map(toStored);\n }\n\n async saveStoredRole(orgId: string, role: StoredOrgRole): Promise<void> {\n const values = {\n name: role.name,\n description: role.description,\n base: role.base,\n levels: role.levels,\n permissions: role.permissions as Record<string, boolean>,\n team: role.team,\n };\n await this.db\n .insert(orgRoles)\n .values({ orgId, key: role.key, ...values })\n .onConflictDoUpdate({ target: [orgRoles.orgId, orgRoles.key], set: values });\n }\n\n async deleteStoredRole(orgId: string, key: string): Promise<boolean> {\n const rows = await this.db\n .delete(orgRoles)\n .where(and(eq(orgRoles.orgId, orgId), eq(orgRoles.key, key)))\n .returning({ key: orgRoles.key });\n return rows.length > 0;\n }\n\n async assignmentsOf(orgId: string, orgUserId: string): Promise<RoleAssignment[]> {\n const rows = await this.db\n .select()\n .from(roleAssignments)\n .where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.orgUserId, orgUserId)));\n return rows.map(toAssignment);\n }\n\n async assignmentsOfMany(\n orgId: string,\n orgUserIds: string[],\n ): Promise<Map<string, AssignmentRow[]>> {\n const out = new Map<string, AssignmentRow[]>();\n if (orgUserIds.length === 0) {\n return out;\n }\n const rows = await this.db\n .select()\n .from(roleAssignments)\n .where(and(eq(roleAssignments.orgId, orgId), inArray(roleAssignments.orgUserId, orgUserIds)));\n for (const row of rows) {\n const list = out.get(row.orgUserId) ?? [];\n list.push(toRow(row));\n out.set(row.orgUserId, list);\n }\n return out;\n }\n\n async assignmentsOn(orgId: string, contentId: string): Promise<RoleAssignment[]> {\n const rows = await this.db\n .select()\n .from(roleAssignments)\n .where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.contentId, contentId)));\n return rows.map(toAssignment);\n }\n\n async holdersOf(orgId: string, roleKeys: string[], contentId?: string): Promise<string[]> {\n if (roleKeys.length === 0) {\n return [];\n }\n const scope =\n contentId === undefined\n ? isNull(roleAssignments.contentId)\n : or(isNull(roleAssignments.contentId), eq(roleAssignments.contentId, contentId));\n const rows = await this.db\n .selectDistinct({ id: roleAssignments.orgUserId })\n .from(roleAssignments)\n .innerJoin(\n orgUsers,\n and(eq(orgUsers.orgId, roleAssignments.orgId), eq(orgUsers.id, roleAssignments.orgUserId)),\n )\n .where(\n and(\n eq(roleAssignments.orgId, orgId),\n inArray(roleAssignments.roleKey, roleKeys),\n eq(orgUsers.status, \"active\"),\n scope,\n ),\n );\n return rows.map((row) => row.id);\n }\n\n async setOrgRole(\n orgId: string,\n orgUserId: string,\n roleKey: string | null,\n assignedBy: string,\n ): Promise<void> {\n await this.db\n .delete(roleAssignments)\n .where(\n and(\n eq(roleAssignments.orgId, orgId),\n eq(roleAssignments.orgUserId, orgUserId),\n isNull(roleAssignments.contentId),\n ),\n );\n if (roleKey !== null) {\n await this.db\n .insert(roleAssignments)\n .values({ orgId, orgUserId, roleKey, contentId: null, contentType: null, assignedBy });\n }\n }\n\n async setItemRole(\n orgId: string,\n orgUserId: string,\n contentId: string,\n contentType: ContentType,\n roleKey: string,\n assignedBy: string,\n ): Promise<void> {\n await this.db\n .insert(roleAssignments)\n .values({ orgId, orgUserId, roleKey, contentId, contentType, assignedBy })\n .onConflictDoUpdate({\n target: [roleAssignments.orgId, roleAssignments.orgUserId, roleAssignments.contentId],\n set: { roleKey, assignedBy, createdAt: new Date() },\n });\n }\n\n async removeItemRole(\n orgId: string,\n orgUserId: string,\n contentId: string,\n ): Promise<RoleAssignment | null> {\n const [row] = await this.db\n .delete(roleAssignments)\n .where(\n and(\n eq(roleAssignments.orgId, orgId),\n eq(roleAssignments.orgUserId, orgUserId),\n eq(roleAssignments.contentId, contentId),\n ),\n )\n .returning();\n return row ? toAssignment(row) : null;\n }\n\n async countHolders(\n orgId: string,\n roleKey: string,\n contentType?: ContentType | \"org\",\n ): Promise<number> {\n const level =\n contentType === undefined\n ? undefined\n : contentType === \"org\"\n ? isNull(roleAssignments.contentId)\n : eq(roleAssignments.contentType, contentType);\n const [row] = await this.db\n .select({ n: sql<number>`count(*)::int` })\n .from(roleAssignments)\n .where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.roleKey, roleKey), level));\n return row?.n ?? 0;\n }\n\n async holderCounts(orgId: string): Promise<Record<string, number>> {\n const rows = await this.db\n .select({\n roleKey: roleAssignments.roleKey,\n n: sql<number>`count(distinct ${roleAssignments.orgUserId})::int`,\n })\n .from(roleAssignments)\n .where(eq(roleAssignments.orgId, orgId))\n .groupBy(roleAssignments.roleKey);\n return Object.fromEntries(rows.map((row) => [row.roleKey, row.n]));\n }\n\n async contentTypeOf(orgId: string, contentId: string): Promise<ContentType | null> {\n const [row] = await this.db\n .select({ type: contentItems.type })\n .from(contentItems)\n .where(and(eq(contentItems.orgId, orgId), eq(contentItems.id, contentId)))\n .limit(1);\n return (row?.type as ContentType | undefined) ?? null;\n }\n\n async ownerOrgUserId(orgId: string): Promise<string | null> {\n const [row] = await this.db\n .select({ id: roleAssignments.orgUserId })\n .from(roleAssignments)\n .where(and(eq(roleAssignments.orgId, orgId), eq(roleAssignments.roleKey, OWNER_ROLE_KEY)))\n .limit(1);\n return row?.id ?? null;\n }\n\n async roleKeyUsage(): Promise<\n { orgId: string; roleKey: string; level: string; count: number; stored: boolean }[]\n > {\n const result = await this.db.execute<{\n org_id: string;\n role_key: string;\n level: string;\n count: number;\n stored: boolean;\n }>(sql`\n select ra.org_id, ra.role_key, coalesce(ra.content_type, 'org') as level,\n count(*)::int as count,\n exists (select 1 from org_roles r where r.org_id = ra.org_id and r.key = ra.role_key) as stored\n from role_assignments ra\n group by ra.org_id, ra.role_key, coalesce(ra.content_type, 'org')\n `);\n return result.rows.map((row) => ({\n orgId: row.org_id,\n roleKey: row.role_key,\n level: row.level,\n count: row.count,\n stored: row.stored,\n }));\n }\n\n async lock(keys: string[]): Promise<void> {\n for (const key of [...new Set(keys)].sort()) {\n await this.db.execute(sql`select pg_advisory_xact_lock(hashtext(${key}))`);\n }\n }\n}\ntranslateDbErrors(DrizzleRolesRepository);\n"],"mappings":";;;;;;;AAmBA,SAAS,SAAS,KAA6B;CAC7C,OAAO;EACL,KAAK,IAAI;EACT,MAAM,IAAI;EACV,aAAa,IAAI;EACjB,MAAM,IAAI;EACV,QAAS,IAAI,UAA6B;EAC1C,aAAa,IAAI;EACjB,MAAM,IAAI;CACZ;AACF;AAEA,SAAS,aAAa,KAA0C;CAC9D,OAAO;EACL,IAAI,IAAI;EACR,OAAO,IAAI;EACX,WAAW,IAAI;EACf,SAAS,IAAI;EACb,WAAW,IAAI;EACf,aAAa,IAAI;EACjB,YAAY,IAAI;EAChB,WAAW,IAAI;CACjB;AACF;AAEA,SAAS,MAAM,KAIG;CAChB,OAAO;EACL,SAAS,IAAI;EACb,WAAW,IAAI;EACf,aAAa,IAAI;CACnB;AACF;AAmBA,SAAS,aAAa,MAAqC;CACzD,OAAO;EACL,KAAK,KAAK;EACV,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,MAAM,KAAK;EACX,QAAS,KAAK,UAA6B;EAC3C,aAAa,KAAK;EAClB,MAAM,KAAK;CACb;AACF;AAEA,SAAS,cAAc,OAAY,WAAqB;CACtD,OAAO,GAAG;;;;;;yBAMa,MAAM,wBAAwB,UAAU;;;AAGjE;AAEA,SAAS,QAAQ,OAAiB;CAChC,OAAO,GAAG;;;;;;;;;;wBAUY,MAAM;;;AAG9B;AAEA,IAAa,yBAAb,MAA+D;CAChC;CAA7B,YAAY,IAAqC;EAApB,KAAA,KAAA;CAAqB;CAElD,MAAM,WAAW,OAAe,WAA+C;EAQ7E,MAAM,OAAM,MAPS,KAAK,GAAG,QAAkB,GAAG;;UAE5C,cAAc,GAAG,aAAa,GAAG,OAAO,EAAE;UAC1C,QAAQ,GAAG,W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,UAAU,CAAC,CAAC,CACzC,KAAK,eAAe,CAAC,CACrB,MAAM,IAAI,GAAG,gBAAgB,OAAO,KAAK,GAAG,GAAG,gBAAgB,SAAS,cAAc,CAAC,CAAC,CAAC,CACzF,MAAM,CAAC;EACV,OAAO,KAAK,MAAM;CACpB;CAEA,MAAM,eAEJ;EAcA,QAAO,MAbc,KAAK,GAAG,QAM1B,GAAG;;;;;;KAML,EAAA,CACa,KAAK,KAAK,SAAS;GAC/B,OAAO,IAAI;GACX,SAAS,IAAI;GACb,OAAO,IAAI;GACX,OAAO,IAAI;GACX,QAAQ,IAAI;EACd,EAAE;CACJ;CAEA,MAAM,KAAK,MAA+B;EACxC,KAAK,MAAM,OAAO,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,GACxC,MAAM,KAAK,GAAG,QAAQ,GAAG,yCAAyC,IAAI,GAAG;CAE7E;AACF;AACA,kBAAkB,sBAAsB"}
@@ -1,7 +1,7 @@
1
1
  import { settings } from "../schema/settings.js";
2
2
  import { translateDbErrors } from "./pg-errors.js";
3
- import { and, eq } from "drizzle-orm";
4
3
  import { noopLogger } from "@headless-lms/core/shared/logger";
4
+ import { and, eq } from "drizzle-orm";
5
5
  //#region src/repositories/settings.ts
6
6
  function toRecord(row) {
7
7
  return {
@@ -1,7 +1,7 @@
1
1
  import { subscriptions } from "../schema/discussion.js";
2
2
  import "../schema/index.js";
3
- import { and, eq, gt, inArray, isNull, or } from "drizzle-orm";
4
3
  import { noopLogger } from "@headless-lms/core/shared/logger";
4
+ import { and, eq, gt, inArray, isNull, or } from "drizzle-orm";
5
5
  //#region src/repositories/subscriptions.ts
6
6
  function toSubscription(row) {
7
7
  return {
@@ -173,6 +173,23 @@ declare const assets: import("drizzle-orm/pg-core").PgTableWithColumns<{
173
173
  identity: undefined;
174
174
  generated: undefined;
175
175
  }, {}, {}>;
176
+ contentId: import("drizzle-orm/pg-core").PgColumn<{
177
+ name: "content_id";
178
+ tableName: "assets";
179
+ dataType: "string";
180
+ columnType: "PgText";
181
+ data: string;
182
+ driverParam: string;
183
+ notNull: false;
184
+ hasDefault: false;
185
+ isPrimaryKey: false;
186
+ isAutoincrement: false;
187
+ hasRuntimeDefault: false;
188
+ enumValues: [string, ...string[]];
189
+ baseColumn: never;
190
+ identity: undefined;
191
+ generated: undefined;
192
+ }, {}, {}>;
176
193
  createdAt: import("drizzle-orm/pg-core").PgColumn<{
177
194
  name: "created_at";
178
195
  tableName: "assets";
@@ -19,6 +19,7 @@ const assets = pgTable("assets", {
19
19
  size: bigint("size", { mode: "number" }).notNull().default(0),
20
20
  status: text("status", { enum: ["pending", "ready"] }).notNull().default("pending"),
21
21
  uploadedBy: text("uploaded_by").notNull(),
22
+ contentId: text("content_id"),
22
23
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
23
24
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
24
25
  }, (t) => ({
@@ -1 +1 @@
1
- {"version":3,"file":"assets.js","names":[],"sources":["../../src/schema/assets.ts"],"sourcesContent":["import { sql } from \"drizzle-orm\";\nimport { pgTable, text, bigint, timestamp, primaryKey, index } from \"drizzle-orm/pg-core\";\nimport type { Asset } from \"@headless-lms/core/schemas\";\nimport { genId } from \"@headless-lms/core/shared/id\";\nimport { organizations } from \"./organizations.js\";\nimport type { Expect, NoDrift } from \"./drift.js\";\n\nexport const assets = pgTable(\n \"assets\",\n {\n orgId: text(\"org_id\")\n .notNull()\n .references(() => organizations.id),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"asset\")),\n key: text(\"key\").notNull(),\n kind: text(\"kind\", { enum: [\"image\", \"video\", \"audio\", \"document\"] }).notNull(),\n source: text(\"source\", { enum: [\"library\", \"member\"] })\n .notNull()\n .default(\"library\"),\n filename: text(\"filename\").notNull(),\n contentType: text(\"content_type\").notNull(),\n size: bigint(\"size\", { mode: \"number\" }).notNull().default(0),\n status: text(\"status\", { enum: [\"pending\", \"ready\"] })\n .notNull()\n .default(\"pending\"),\n uploadedBy: text(\"uploaded_by\").notNull(),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp(\"updated_at\", { withTimezone: true })\n .notNull()\n .defaultNow()\n .$onUpdate(() => new Date()),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n memberUploadsIdx: index(\"assets_member_uploads_idx\")\n .on(t.orgId, t.createdAt)\n .where(sql`${t.source} = 'member'`),\n }),\n);\n\ntype _AssetsDrift = Expect<NoDrift<typeof assets.$inferSelect, Asset>>;\n"],"mappings":";;;;;AAOA,MAAa,SAAS,QACpB,UACA;CACE,OAAO,KAAK,QAAQ,CAAC,CAClB,QAAQ,CAAC,CACT,iBAAiB,cAAc,EAAE;CACpC,IAAI,KAAK,IAAI,CAAC,CACX,QAAQ,CAAC,CACT,iBAAiB,MAAM,OAAO,CAAC;CAClC,KAAK,KAAK,KAAK,CAAC,CAAC,QAAQ;CACzB,MAAM,KAAK,QAAQ,EAAE,MAAM;EAAC;EAAS;EAAS;EAAS;CAAU,EAAE,CAAC,CAAC,CAAC,QAAQ;CAC9E,QAAQ,KAAK,UAAU,EAAE,MAAM,CAAC,WAAW,QAAQ,EAAE,CAAC,CAAC,CACpD,QAAQ,CAAC,CACT,QAAQ,SAAS;CACpB,UAAU,KAAK,UAAU,CAAC,CAAC,QAAQ;CACnC,aAAa,KAAK,cAAc,CAAC,CAAC,QAAQ;CAC1C,MAAM,OAAO,QAAQ,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC;CAC5D,QAAQ,KAAK,UAAU,EAAE,MAAM,CAAC,WAAW,OAAO,EAAE,CAAC,CAAC,CACnD,QAAQ,CAAC,CACT,QAAQ,SAAS;CACpB,YAAY,KAAK,aAAa,CAAC,CAAC,QAAQ;CACxC,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,WAAW;CAChF,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,CAAC,CACvD,QAAQ,CAAC,CACT,WAAW,CAAC,CACZ,gCAAgB,IAAI,KAAK,CAAC;AAC/B,IACC,OAAO;CACN,IAAI,WAAW,EAAE,SAAS,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;CAC3C,kBAAkB,MAAM,2BAA2B,CAAC,CACjD,GAAG,EAAE,OAAO,EAAE,SAAS,CAAC,CACxB,MAAM,GAAG,GAAG,EAAE,OAAO,YAAY;AACtC,EACF"}
1
+ {"version":3,"file":"assets.js","names":[],"sources":["../../src/schema/assets.ts"],"sourcesContent":["import { sql } from \"drizzle-orm\";\nimport { pgTable, text, bigint, timestamp, primaryKey, index } from \"drizzle-orm/pg-core\";\nimport type { Asset } from \"@headless-lms/core/schemas\";\nimport { genId } from \"@headless-lms/core/shared/id\";\nimport { organizations } from \"./organizations.js\";\nimport type { Expect, NoDrift } from \"./drift.js\";\n\nexport const assets = pgTable(\n \"assets\",\n {\n orgId: text(\"org_id\")\n .notNull()\n .references(() => organizations.id),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"asset\")),\n key: text(\"key\").notNull(),\n kind: text(\"kind\", { enum: [\"image\", \"video\", \"audio\", \"document\"] }).notNull(),\n source: text(\"source\", { enum: [\"library\", \"member\"] })\n .notNull()\n .default(\"library\"),\n filename: text(\"filename\").notNull(),\n contentType: text(\"content_type\").notNull(),\n size: bigint(\"size\", { mode: \"number\" }).notNull().default(0),\n status: text(\"status\", { enum: [\"pending\", \"ready\"] })\n .notNull()\n .default(\"pending\"),\n uploadedBy: text(\"uploaded_by\").notNull(),\n contentId: text(\"content_id\"),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp(\"updated_at\", { withTimezone: true })\n .notNull()\n .defaultNow()\n .$onUpdate(() => new Date()),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n memberUploadsIdx: index(\"assets_member_uploads_idx\")\n .on(t.orgId, t.createdAt)\n .where(sql`${t.source} = 'member'`),\n }),\n);\n\ntype _AssetsDrift = Expect<NoDrift<typeof assets.$inferSelect, Asset>>;\n"],"mappings":";;;;;AAOA,MAAa,SAAS,QACpB,UACA;CACE,OAAO,KAAK,QAAQ,CAAC,CAClB,QAAQ,CAAC,CACT,iBAAiB,cAAc,EAAE;CACpC,IAAI,KAAK,IAAI,CAAC,CACX,QAAQ,CAAC,CACT,iBAAiB,MAAM,OAAO,CAAC;CAClC,KAAK,KAAK,KAAK,CAAC,CAAC,QAAQ;CACzB,MAAM,KAAK,QAAQ,EAAE,MAAM;EAAC;EAAS;EAAS;EAAS;CAAU,EAAE,CAAC,CAAC,CAAC,QAAQ;CAC9E,QAAQ,KAAK,UAAU,EAAE,MAAM,CAAC,WAAW,QAAQ,EAAE,CAAC,CAAC,CACpD,QAAQ,CAAC,CACT,QAAQ,SAAS;CACpB,UAAU,KAAK,UAAU,CAAC,CAAC,QAAQ;CACnC,aAAa,KAAK,cAAc,CAAC,CAAC,QAAQ;CAC1C,MAAM,OAAO,QAAQ,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC;CAC5D,QAAQ,KAAK,UAAU,EAAE,MAAM,CAAC,WAAW,OAAO,EAAE,CAAC,CAAC,CACnD,QAAQ,CAAC,CACT,QAAQ,SAAS;CACpB,YAAY,KAAK,aAAa,CAAC,CAAC,QAAQ;CACxC,WAAW,KAAK,YAAY;CAC5B,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,WAAW;CAChF,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,CAAC,CACvD,QAAQ,CAAC,CACT,WAAW,CAAC,CACZ,gCAAgB,IAAI,KAAK,CAAC;AAC/B,IACC,OAAO;CACN,IAAI,WAAW,EAAE,SAAS,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;CAC3C,kBAAkB,MAAM,2BAA2B,CAAC,CACjD,GAAG,EAAE,OAAO,EAAE,SAAS,CAAC,CACxB,MAAM,GAAG,GAAG,EAAE,OAAO,YAAY;AACtC,EACF"}
@@ -597,7 +597,6 @@ declare const notifications: import("drizzle-orm/pg-core").PgTableWithColumns<{
597
597
  identity: undefined;
598
598
  generated: undefined;
599
599
  }, {}, {
600
- $type: Reason[];
601
600
  size: undefined;
602
601
  baseBuilder: import("drizzle-orm/pg-core").PgColumnBuilder<{
603
602
  name: "reasons";
@@ -607,6 +606,7 @@ declare const notifications: import("drizzle-orm/pg-core").PgTableWithColumns<{
607
606
  enumValues: [string, ...string[]];
608
607
  driverParam: string;
609
608
  }, {}, {}, import("drizzle-orm").ColumnBuilderExtraConfig>;
609
+ $type: Reason[];
610
610
  }>;
611
611
  matchedReason: import("drizzle-orm/pg-core").PgColumn<{
612
612
  name: "matched_reason";
@@ -678,8 +678,8 @@ declare const notifications: import("drizzle-orm/pg-core").PgTableWithColumns<{
678
678
  identity: undefined;
679
679
  generated: undefined;
680
680
  }, {}, {}>;
681
- actorOrgUserId: import("drizzle-orm/pg-core").PgColumn<{
682
- name: "actor_org_user_id";
681
+ actorId: import("drizzle-orm/pg-core").PgColumn<{
682
+ name: "actor_id";
683
683
  tableName: "notifications";
684
684
  dataType: "string";
685
685
  columnType: "PgText";
@@ -59,7 +59,7 @@ const notifications = pgTable("notifications", {
59
59
  category: text("category").notNull(),
60
60
  communityId: text("community_id"),
61
61
  spaceId: text("space_id"),
62
- actorOrgUserId: text("actor_org_user_id"),
62
+ actorId: text("actor_id"),
63
63
  subjectType: text("subject_type"),
64
64
  subjectId: text("subject_id"),
65
65
  parentType: text("parent_type"),
@@ -1 +1 @@
1
- {"version":3,"file":"automations.js","names":[],"sources":["../../src/schema/automations.ts"],"sourcesContent":["// automations tables — org-scoped automation definitions and their run\n// history. `automations.actions` and `automation_runs.action_results` are\n// ordered jsonb blobs (contract types owned by @headless-lms/core/types); a run's\n// `event` is the triggering DomainEvent snapshot, stored verbatim.\nimport {\n pgTable,\n text,\n boolean,\n jsonb,\n timestamp,\n primaryKey,\n foreignKey,\n index,\n uniqueIndex,\n} from \"drizzle-orm/pg-core\";\nimport { desc, sql } from \"drizzle-orm\";\nimport { genId } from \"@headless-lms/core/shared/id\";\nimport { organizations, orgUsers } from \"./organizations.js\";\nimport { communities, spaces } from \"./content.js\";\nimport type {\n Automation,\n AutomationAction,\n AutomationActionResult,\n AutomationRun,\n} from \"@headless-lms/core/schemas\";\nimport type { DomainEvent, JsonValue } from \"@headless-lms/core/shared/ports\";\nimport type { Reason } from \"@headless-lms/core/types\";\nimport type { Expect, NoDrift } from \"./drift.js\";\n\nexport const automations = pgTable(\n \"automations\",\n {\n orgId: text(\"org_id\")\n .notNull()\n .references(() => organizations.id),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"automation\")),\n name: text(\"name\").notNull(),\n kind: text(\"kind\", { enum: [\"workflow\", \"webhook\"] })\n .notNull()\n .default(\"workflow\"),\n description: text(\"description\"),\n triggers: text(\"triggers\").array().notNull(),\n actions: jsonb(\"actions\").$type<AutomationAction[]>().notNull(),\n enabled: boolean(\"enabled\").notNull().default(true),\n filter: jsonb(\"filter\").$type<Automation[\"filter\"]>(),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp(\"updated_at\", { withTimezone: true })\n .notNull()\n .defaultNow()\n .$onUpdate(() => new Date()),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n triggersIdx: index(\"automations_triggers_idx\").using(\"gin\", t.triggers),\n }),\n);\n\nexport const automationRuns = pgTable(\n \"automation_runs\",\n {\n orgId: text(\"org_id\")\n .notNull()\n .references(() => organizations.id),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"automationRun\")),\n automationId: text(\"automation_id\").notNull(),\n trigger: text(\"trigger\").notNull(),\n // At-least-once dedupe key for the triggering event; DB-internal, not part of the domain `AutomationRun` type.\n eventId: text(\"event_id\").notNull(),\n event: jsonb(\"event\").$type<DomainEvent>().notNull(),\n status: text(\"status\", { enum: [\"running\", \"completed\", \"failed\"] }).notNull(),\n actionResults: jsonb(\"action_results\").$type<AutomationActionResult[]>().notNull().default([]),\n startedAt: timestamp(\"started_at\", { withTimezone: true }).notNull(),\n finishedAt: timestamp(\"finished_at\", { withTimezone: true }),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp(\"updated_at\", { withTimezone: true })\n .notNull()\n .defaultNow()\n .$onUpdate(() => new Date()),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n automationIdx: index(\"automation_runs_org_automation_idx\").on(t.orgId, t.automationId),\n eventDedupeIdx: uniqueIndex(\"automation_runs_org_automation_event_idx\").on(\n t.orgId,\n t.automationId,\n t.eventId,\n ),\n }),\n);\n\nexport const notifications = pgTable(\n \"notifications\",\n {\n orgId: text(\"org_id\").notNull(),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"notification\")),\n userId: text(\"user_id\").notNull(),\n sourceEventId: text(\"source_event_id\"),\n type: text(\"type\").notNull(),\n scope: text(\"scope\", { enum: [\"org\", \"community\", \"space\", \"chat\"] }).notNull(),\n reasons: text(\"reasons\").array().$type<Reason[]>().notNull(),\n matchedReason: text(\"matched_reason\").$type<Reason>().notNull(),\n category: text(\"category\").notNull(),\n communityId: text(\"community_id\"),\n spaceId: text(\"space_id\"),\n actorOrgUserId: text(\"actor_org_user_id\"),\n subjectType: text(\"subject_type\"),\n subjectId: text(\"subject_id\"),\n parentType: text(\"parent_type\"),\n parentId: text(\"parent_id\"),\n display: jsonb(\"display\").$type<Record<string, JsonValue>>().notNull(),\n inApp: boolean(\"in_app\").notNull(),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n readAt: timestamp(\"read_at\", { withTimezone: true }),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n userFk: foreignKey({\n columns: [t.orgId, t.userId],\n foreignColumns: [orgUsers.orgId, orgUsers.userId],\n }).onDelete(\"cascade\"),\n communityFk: foreignKey({\n columns: [t.orgId, t.communityId],\n foreignColumns: [communities.orgId, communities.id],\n }).onDelete(\"cascade\"),\n spaceFk: foreignKey({\n columns: [t.orgId, t.spaceId],\n foreignColumns: [spaces.orgId, spaces.id],\n }).onDelete(\"cascade\"),\n sourceIdx: uniqueIndex(\"notifications_source_event_idx\")\n .on(t.orgId, t.sourceEventId, t.userId, sql`coalesce(${t.communityId}, '')`)\n .where(sql`${t.sourceEventId} is not null`),\n listIdx: index(\"notifications_list_idx\")\n .on(t.orgId, t.userId, desc(t.createdAt), desc(t.id))\n .where(sql`${t.inApp}`),\n communityIdx: index(\"notifications_community_idx\").on(t.orgId, t.userId, t.communityId),\n categoryIdx: index(\"notifications_category_idx\").on(t.orgId, t.userId, t.category),\n reasonsIdx: index(\"notifications_reasons_idx\").using(\"gin\", t.reasons),\n }),\n);\n\nexport const notificationDeliveries = pgTable(\n \"notification_deliveries\",\n {\n orgId: text(\"org_id\").notNull(),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"notificationDelivery\")),\n notificationId: text(\"notification_id\").notNull(),\n channel: text(\"channel\").notNull(),\n status: text(\"status\", { enum: [\"pending\", \"sent\", \"failed\"] })\n .notNull()\n .default(\"pending\"),\n lastError: text(\"last_error\"),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n sentAt: timestamp(\"sent_at\", { withTimezone: true }),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n notificationFk: foreignKey({\n columns: [t.orgId, t.notificationId],\n foreignColumns: [notifications.orgId, notifications.id],\n }).onDelete(\"cascade\"),\n channelIdx: uniqueIndex(\"notification_deliveries_channel_idx\").on(\n t.orgId,\n t.notificationId,\n t.channel,\n ),\n }),\n);\n\ntype _AutomationsDrift = Expect<NoDrift<typeof automations.$inferSelect, Automation>>;\ntype _AutomationRunsDrift = Expect<NoDrift<typeof automationRuns.$inferSelect, AutomationRun>>;\n"],"mappings":";;;;;;AA6BA,MAAa,cAAc,QACzB,eACA;CACE,OAAO,KAAK,QAAQ,CAAC,CAClB,QAAQ,CAAC,CACT,iBAAiB,cAAc,EAAE;CACpC,IAAI,KAAK,IAAI,CAAC,CACX,QAAQ,CAAC,CACT,iBAAiB,MAAM,YAAY,CAAC;CACvC,MAAM,KAAK,MAAM,CAAC,CAAC,QAAQ;CAC3B,MAAM,KAAK,QAAQ,EAAE,MAAM,CAAC,YAAY,SAAS,EAAE,CAAC,CAAC,CAClD,QAAQ,CAAC,CACT,QAAQ,UAAU;CACrB,aAAa,KAAK,aAAa;CAC/B,UAAU,KAAK,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ;CAC3C,SAAS,MAAM,SAAS,CAAC,CAAC,MAA0B,CAAC,CAAC,QAAQ;CAC9D,SAAS,QAAQ,SAAS,CAAC,CAAC,QAAQ,CAAC,CAAC,QAAQ,IAAI;CAClD,QAAQ,MAAM,QAAQ,CAAC,CAAC,MAA4B;CACpD,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,WAAW;CAChF,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,CAAC,CACvD,QAAQ,CAAC,CACT,WAAW,CAAC,CACZ,gCAAgB,IAAI,KAAK,CAAC;AAC/B,IACC,OAAO;CACN,IAAI,WAAW,EAAE,SAAS,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;CAC3C,aAAa,MAAM,0BAA0B,CAAC,CAAC,MAAM,OAAO,EAAE,QAAQ;AACxE,EACF;AAEA,MAAa,iBAAiB,QAC5B,mBACA;CACE,OAAO,KAAK,QAAQ,CAAC,CAClB,QAAQ,CAAC,CACT,iBAAiB,cAAc,EAAE;CACp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,EAAE,EAAE,CAAC;CAC3C,gBAAgB,WAAW;EACzB,SAAS,CAAC,EAAE,OAAO,EAAE,cAAc;EACnC,gBAAgB,CAAC,cAAc,OAAO,cAAc,EAAE;CACxD,CAAC,CAAC,CAAC,SAAS,SAAS;CACrB,YAAY,YAAY,qCAAqC,CAAC,CAAC,GAC7D,EAAE,OACF,EAAE,gBACF,EAAE,OACJ;AACF,EACF"}
1
+ {"version":3,"file":"automations.js","names":[],"sources":["../../src/schema/automations.ts"],"sourcesContent":["// automations tables — org-scoped automation definitions and their run\n// history. `automations.actions` and `automation_runs.action_results` are\n// ordered jsonb blobs (contract types owned by @headless-lms/core/types); a run's\n// `event` is the triggering DomainEvent snapshot, stored verbatim.\nimport {\n pgTable,\n text,\n boolean,\n jsonb,\n timestamp,\n primaryKey,\n foreignKey,\n index,\n uniqueIndex,\n} from \"drizzle-orm/pg-core\";\nimport { desc, sql } from \"drizzle-orm\";\nimport { genId } from \"@headless-lms/core/shared/id\";\nimport { organizations, orgUsers } from \"./organizations.js\";\nimport { communities, spaces } from \"./content.js\";\nimport type {\n Automation,\n AutomationAction,\n AutomationActionResult,\n AutomationRun,\n} from \"@headless-lms/core/schemas\";\nimport type { DomainEvent, JsonValue } from \"@headless-lms/core/shared/ports\";\nimport type { Reason } from \"@headless-lms/core/types\";\nimport type { Expect, NoDrift } from \"./drift.js\";\n\nexport const automations = pgTable(\n \"automations\",\n {\n orgId: text(\"org_id\")\n .notNull()\n .references(() => organizations.id),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"automation\")),\n name: text(\"name\").notNull(),\n kind: text(\"kind\", { enum: [\"workflow\", \"webhook\"] })\n .notNull()\n .default(\"workflow\"),\n description: text(\"description\"),\n triggers: text(\"triggers\").array().notNull(),\n actions: jsonb(\"actions\").$type<AutomationAction[]>().notNull(),\n enabled: boolean(\"enabled\").notNull().default(true),\n filter: jsonb(\"filter\").$type<Automation[\"filter\"]>(),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp(\"updated_at\", { withTimezone: true })\n .notNull()\n .defaultNow()\n .$onUpdate(() => new Date()),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n triggersIdx: index(\"automations_triggers_idx\").using(\"gin\", t.triggers),\n }),\n);\n\nexport const automationRuns = pgTable(\n \"automation_runs\",\n {\n orgId: text(\"org_id\")\n .notNull()\n .references(() => organizations.id),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"automationRun\")),\n automationId: text(\"automation_id\").notNull(),\n trigger: text(\"trigger\").notNull(),\n // At-least-once dedupe key for the triggering event; DB-internal, not part of the domain `AutomationRun` type.\n eventId: text(\"event_id\").notNull(),\n event: jsonb(\"event\").$type<DomainEvent>().notNull(),\n status: text(\"status\", { enum: [\"running\", \"completed\", \"failed\"] }).notNull(),\n actionResults: jsonb(\"action_results\").$type<AutomationActionResult[]>().notNull().default([]),\n startedAt: timestamp(\"started_at\", { withTimezone: true }).notNull(),\n finishedAt: timestamp(\"finished_at\", { withTimezone: true }),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp(\"updated_at\", { withTimezone: true })\n .notNull()\n .defaultNow()\n .$onUpdate(() => new Date()),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n automationIdx: index(\"automation_runs_org_automation_idx\").on(t.orgId, t.automationId),\n eventDedupeIdx: uniqueIndex(\"automation_runs_org_automation_event_idx\").on(\n t.orgId,\n t.automationId,\n t.eventId,\n ),\n }),\n);\n\nexport const notifications = pgTable(\n \"notifications\",\n {\n orgId: text(\"org_id\").notNull(),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"notification\")),\n userId: text(\"user_id\").notNull(),\n sourceEventId: text(\"source_event_id\"),\n type: text(\"type\").notNull(),\n scope: text(\"scope\", { enum: [\"org\", \"community\", \"space\", \"chat\"] }).notNull(),\n reasons: text(\"reasons\").array().$type<Reason[]>().notNull(),\n matchedReason: text(\"matched_reason\").$type<Reason>().notNull(),\n category: text(\"category\").notNull(),\n communityId: text(\"community_id\"),\n spaceId: text(\"space_id\"),\n actorId: text(\"actor_id\"),\n subjectType: text(\"subject_type\"),\n subjectId: text(\"subject_id\"),\n parentType: text(\"parent_type\"),\n parentId: text(\"parent_id\"),\n display: jsonb(\"display\").$type<Record<string, JsonValue>>().notNull(),\n inApp: boolean(\"in_app\").notNull(),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n readAt: timestamp(\"read_at\", { withTimezone: true }),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n userFk: foreignKey({\n columns: [t.orgId, t.userId],\n foreignColumns: [orgUsers.orgId, orgUsers.userId],\n }).onDelete(\"cascade\"),\n communityFk: foreignKey({\n columns: [t.orgId, t.communityId],\n foreignColumns: [communities.orgId, communities.id],\n }).onDelete(\"cascade\"),\n spaceFk: foreignKey({\n columns: [t.orgId, t.spaceId],\n foreignColumns: [spaces.orgId, spaces.id],\n }).onDelete(\"cascade\"),\n sourceIdx: uniqueIndex(\"notifications_source_event_idx\")\n .on(t.orgId, t.sourceEventId, t.userId, sql`coalesce(${t.communityId}, '')`)\n .where(sql`${t.sourceEventId} is not null`),\n listIdx: index(\"notifications_list_idx\")\n .on(t.orgId, t.userId, desc(t.createdAt), desc(t.id))\n .where(sql`${t.inApp}`),\n communityIdx: index(\"notifications_community_idx\").on(t.orgId, t.userId, t.communityId),\n categoryIdx: index(\"notifications_category_idx\").on(t.orgId, t.userId, t.category),\n reasonsIdx: index(\"notifications_reasons_idx\").using(\"gin\", t.reasons),\n }),\n);\n\nexport const notificationDeliveries = pgTable(\n \"notification_deliveries\",\n {\n orgId: text(\"org_id\").notNull(),\n id: text(\"id\")\n .notNull()\n .$defaultFn(() => genId(\"notificationDelivery\")),\n notificationId: text(\"notification_id\").notNull(),\n channel: text(\"channel\").notNull(),\n status: text(\"status\", { enum: [\"pending\", \"sent\", \"failed\"] })\n .notNull()\n .default(\"pending\"),\n lastError: text(\"last_error\"),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).notNull().defaultNow(),\n sentAt: timestamp(\"sent_at\", { withTimezone: true }),\n },\n (t) => ({\n pk: primaryKey({ columns: [t.orgId, t.id] }),\n notificationFk: foreignKey({\n columns: [t.orgId, t.notificationId],\n foreignColumns: [notifications.orgId, notifications.id],\n }).onDelete(\"cascade\"),\n channelIdx: uniqueIndex(\"notification_deliveries_channel_idx\").on(\n t.orgId,\n t.notificationId,\n t.channel,\n ),\n }),\n);\n\ntype _AutomationsDrift = Expect<NoDrift<typeof automations.$inferSelect, Automation>>;\ntype _AutomationRunsDrift = Expect<NoDrift<typeof automationRuns.$inferSelect, AutomationRun>>;\n"],"mappings":";;;;;;AA6BA,MAAa,cAAc,QACzB,eACA;CACE,OAAO,KAAK,QAAQ,CAAC,CAClB,QAAQ,CAAC,CACT,iBAAiB,cAAc,EAAE;CACpC,IAAI,KAAK,IAAI,CAAC,CACX,QAAQ,CAAC,CACT,iBAAiB,MAAM,YAAY,CAAC;CACvC,MAAM,KAAK,MAAM,CAAC,CAAC,QAAQ;CAC3B,MAAM,KAAK,QAAQ,EAAE,MAAM,CAAC,YAAY,SAAS,EAAE,CAAC,CAAC,CAClD,QAAQ,CAAC,CACT,QAAQ,UAAU;CACrB,aAAa,KAAK,aAAa;CAC/B,UAAU,KAAK,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ;CAC3C,SAAS,MAAM,SAAS,CAAC,CAAC,MAA0B,CAAC,CAAC,QAAQ;CAC9D,SAAS,QAAQ,SAAS,CAAC,CAAC,QAAQ,CAAC,CAAC,QAAQ,IAAI;CAClD,QAAQ,MAAM,QAAQ,CAAC,CAAC,MAA4B;CACpD,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,WAAW;CAChF,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,C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