@headless-lms/core 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 (249) hide show
  1. package/dist/assets/events.d.ts +15 -9
  2. package/dist/assets/file-urls.d.ts +14 -7
  3. package/dist/assets/file-urls.js +15 -4
  4. package/dist/assets/file-urls.js.map +1 -1
  5. package/dist/assets/index.d.ts +4 -4
  6. package/dist/assets/index.js +3 -3
  7. package/dist/assets/ports.d.ts +34 -15
  8. package/dist/assets/service.d.ts +30 -14
  9. package/dist/assets/service.js +233 -54
  10. package/dist/assets/service.js.map +1 -1
  11. package/dist/automations/actions.js.map +1 -1
  12. package/dist/automations/catalog.js +68 -3
  13. package/dist/automations/catalog.js.map +1 -1
  14. package/dist/automations/community-derivations.js +16 -16
  15. package/dist/automations/community-derivations.js.map +1 -1
  16. package/dist/automations/community-mail.d.ts +34 -4
  17. package/dist/automations/community-mail.js +32 -4
  18. package/dist/automations/community-mail.js.map +1 -1
  19. package/dist/automations/event-permissions.d.ts +12 -0
  20. package/dist/automations/event-permissions.js +38 -0
  21. package/dist/automations/event-permissions.js.map +1 -0
  22. package/dist/automations/index.d.ts +2 -1
  23. package/dist/automations/index.js +2 -1
  24. package/dist/automations/notifications/applicable.d.ts +8 -0
  25. package/dist/automations/notifications/applicable.js +12 -0
  26. package/dist/automations/notifications/applicable.js.map +1 -0
  27. package/dist/automations/notifications/debounce.js +1 -1
  28. package/dist/automations/notifications/debounce.js.map +1 -1
  29. package/dist/automations/notifications/defaults.js +33 -3
  30. package/dist/automations/notifications/defaults.js.map +1 -1
  31. package/dist/automations/notifications/processor.js +1 -1
  32. package/dist/automations/notifications/processor.js.map +1 -1
  33. package/dist/automations/notifications/rules/content.js +60 -3
  34. package/dist/automations/notifications/rules/content.js.map +1 -1
  35. package/dist/automations/notifications/rules/discussion.js +29 -29
  36. package/dist/automations/notifications/rules/discussion.js.map +1 -1
  37. package/dist/automations/notifications/rules/entitlements.js +36 -9
  38. package/dist/automations/notifications/rules/entitlements.js.map +1 -1
  39. package/dist/automations/notifications/rules/events.d.ts +9 -0
  40. package/dist/automations/notifications/rules/events.js +27 -0
  41. package/dist/automations/notifications/rules/events.js.map +1 -0
  42. package/dist/automations/notifications/rules/organizations.js +17 -10
  43. package/dist/automations/notifications/rules/organizations.js.map +1 -1
  44. package/dist/automations/notifications/rules/recipients.js +0 -1
  45. package/dist/automations/notifications/rules/recipients.js.map +1 -1
  46. package/dist/automations/notifications/service.d.ts +8 -6
  47. package/dist/automations/notifications/service.js +12 -12
  48. package/dist/automations/notifications/service.js.map +1 -1
  49. package/dist/automations/notifications/types.js +94 -7
  50. package/dist/automations/notifications/types.js.map +1 -1
  51. package/dist/automations/ports.d.ts +30 -31
  52. package/dist/automations/service.d.ts +20 -17
  53. package/dist/automations/service.js +90 -61
  54. package/dist/automations/service.js.map +1 -1
  55. package/dist/content/event-sight.d.ts +11 -0
  56. package/dist/content/event-sight.js +11 -0
  57. package/dist/content/event-sight.js.map +1 -0
  58. package/dist/content/events.d.ts +465 -88
  59. package/dist/content/events.js +34 -1
  60. package/dist/content/events.js.map +1 -1
  61. package/dist/content/index.d.ts +6 -4
  62. package/dist/content/index.js +3 -1
  63. package/dist/content/jobs.d.ts +16 -0
  64. package/dist/content/jobs.js +37 -0
  65. package/dist/content/jobs.js.map +1 -0
  66. package/dist/content/model.d.ts +2 -2
  67. package/dist/content/notification-categories.d.ts +5 -4
  68. package/dist/content/notification-categories.js +15 -6
  69. package/dist/content/notification-categories.js.map +1 -1
  70. package/dist/content/ports.d.ts +113 -68
  71. package/dist/content/service.d.ts +103 -67
  72. package/dist/content/service.js +739 -152
  73. package/dist/content/service.js.map +1 -1
  74. package/dist/content/titles.d.ts +6 -3
  75. package/dist/content/titles.js +37 -24
  76. package/dist/content/titles.js.map +1 -1
  77. package/dist/content/types.d.ts +2 -2
  78. package/dist/discussion/authors.d.ts +4 -2
  79. package/dist/discussion/authors.js +9 -5
  80. package/dist/discussion/authors.js.map +1 -1
  81. package/dist/discussion/chats.d.ts +56 -37
  82. package/dist/discussion/chats.js +392 -160
  83. package/dist/discussion/chats.js.map +1 -1
  84. package/dist/discussion/events.d.ts +85 -47
  85. package/dist/discussion/events.js +41 -3
  86. package/dist/discussion/events.js.map +1 -1
  87. package/dist/discussion/index.d.ts +8 -5
  88. package/dist/discussion/index.js +5 -3
  89. package/dist/discussion/live.d.ts +106 -0
  90. package/dist/discussion/live.js +642 -0
  91. package/dist/discussion/live.js.map +1 -0
  92. package/dist/discussion/mentions.js +2 -2
  93. package/dist/discussion/mentions.js.map +1 -1
  94. package/dist/discussion/ports.d.ts +182 -100
  95. package/dist/discussion/ports.js.map +1 -1
  96. package/dist/discussion/posts.d.ts +45 -39
  97. package/dist/discussion/posts.js +266 -152
  98. package/dist/discussion/posts.js.map +1 -1
  99. package/dist/discussion/rules.d.ts +18 -0
  100. package/dist/discussion/rules.js +22 -0
  101. package/dist/discussion/rules.js.map +1 -0
  102. package/dist/discussion/service.d.ts +37 -31
  103. package/dist/discussion/service.js +250 -186
  104. package/dist/discussion/service.js.map +1 -1
  105. package/dist/discussion/subscriptions.d.ts +8 -8
  106. package/dist/discussion/subscriptions.js +28 -12
  107. package/dist/discussion/subscriptions.js.map +1 -1
  108. package/dist/discussion/titles.d.ts +4 -2
  109. package/dist/discussion/titles.js +27 -13
  110. package/dist/discussion/titles.js.map +1 -1
  111. package/dist/entitlements/events.d.ts +58 -58
  112. package/dist/entitlements/index.d.ts +4 -4
  113. package/dist/entitlements/index.js +2 -2
  114. package/dist/entitlements/model.d.ts +2 -2
  115. package/dist/entitlements/ports.d.ts +65 -39
  116. package/dist/entitlements/rules.d.ts +3 -6
  117. package/dist/entitlements/rules.js +5 -10
  118. package/dist/entitlements/rules.js.map +1 -1
  119. package/dist/entitlements/service.d.ts +40 -28
  120. package/dist/entitlements/service.js +369 -162
  121. package/dist/entitlements/service.js.map +1 -1
  122. package/dist/identity/devices.d.ts +3 -3
  123. package/dist/identity/devices.js +6 -4
  124. package/dist/identity/devices.js.map +1 -1
  125. package/dist/identity/index.d.ts +2 -2
  126. package/dist/identity/index.js +2 -2
  127. package/dist/identity/notification-settings.d.ts +1 -1
  128. package/dist/identity/notification-settings.js +2 -1
  129. package/dist/identity/notification-settings.js.map +1 -1
  130. package/dist/identity/ports.d.ts +7 -7
  131. package/dist/identity/service.d.ts +8 -7
  132. package/dist/identity/service.js +16 -12
  133. package/dist/identity/service.js.map +1 -1
  134. package/dist/integrations/events.d.ts +3 -3
  135. package/dist/integrations/ports.d.ts +9 -8
  136. package/dist/integrations/service.d.ts +9 -8
  137. package/dist/integrations/service.js +31 -14
  138. package/dist/integrations/service.js.map +1 -1
  139. package/dist/organizations/default-roles.d.ts +22 -0
  140. package/dist/organizations/default-roles.js +89 -0
  141. package/dist/organizations/default-roles.js.map +1 -0
  142. package/dist/organizations/effective-permissions.d.ts +47 -0
  143. package/dist/organizations/effective-permissions.js +118 -0
  144. package/dist/organizations/effective-permissions.js.map +1 -0
  145. package/dist/organizations/events.d.ts +326 -181
  146. package/dist/organizations/events.js +90 -18
  147. package/dist/organizations/events.js.map +1 -1
  148. package/dist/organizations/index.d.ts +14 -10
  149. package/dist/organizations/index.js +7 -3
  150. package/dist/organizations/members.d.ts +66 -8
  151. package/dist/organizations/members.js.map +1 -1
  152. package/dist/organizations/model.d.ts +2 -2
  153. package/dist/organizations/notification-catalog.d.ts +31 -0
  154. package/dist/organizations/notification-catalog.js +32 -0
  155. package/dist/organizations/notification-catalog.js.map +1 -0
  156. package/dist/organizations/notification-categories.d.ts +6 -4
  157. package/dist/organizations/notification-categories.js +25 -10
  158. package/dist/organizations/notification-categories.js.map +1 -1
  159. package/dist/organizations/org-roles.d.ts +33 -0
  160. package/dist/organizations/org-roles.js +49 -0
  161. package/dist/organizations/org-roles.js.map +1 -0
  162. package/dist/organizations/permissions.d.ts +311 -0
  163. package/dist/organizations/permissions.js +327 -0
  164. package/dist/organizations/permissions.js.map +1 -0
  165. package/dist/organizations/ports.d.ts +187 -65
  166. package/dist/organizations/service.d.ts +102 -35
  167. package/dist/organizations/service.js +1254 -327
  168. package/dist/organizations/service.js.map +1 -1
  169. package/dist/organizations/testing.d.ts +18 -0
  170. package/dist/organizations/testing.js +37 -0
  171. package/dist/organizations/testing.js.map +1 -0
  172. package/dist/organizations/types.d.ts +5 -16
  173. package/dist/progress/events.d.ts +14 -14
  174. package/dist/progress/index.d.ts +2 -2
  175. package/dist/progress/ports.d.ts +11 -3
  176. package/dist/progress/service.d.ts +6 -5
  177. package/dist/progress/service.js +21 -6
  178. package/dist/progress/service.js.map +1 -1
  179. package/dist/reporting/admin/index.d.ts +6 -4
  180. package/dist/reporting/admin/model.d.ts +36 -3
  181. package/dist/reporting/admin/ports.d.ts +39 -14
  182. package/dist/reporting/admin/service.d.ts +32 -11
  183. package/dist/reporting/admin/service.js +102 -18
  184. package/dist/reporting/admin/service.js.map +1 -1
  185. package/dist/reporting/events/index.d.ts +27 -0
  186. package/dist/reporting/events/index.js +20 -0
  187. package/dist/reporting/events/index.js.map +1 -0
  188. package/dist/reporting/member/calendar.d.ts +11 -0
  189. package/dist/reporting/member/calendar.js +75 -0
  190. package/dist/reporting/member/calendar.js.map +1 -0
  191. package/dist/reporting/member/index.d.ts +3 -2
  192. package/dist/reporting/member/model.d.ts +29 -5
  193. package/dist/reporting/member/ports.d.ts +49 -29
  194. package/dist/reporting/member/service.d.ts +57 -29
  195. package/dist/reporting/member/service.js +345 -114
  196. package/dist/reporting/member/service.js.map +1 -1
  197. package/dist/shared/actor.d.ts +23 -3
  198. package/dist/shared/errors.d.ts +2 -1
  199. package/dist/shared/errors.js +3 -1
  200. package/dist/shared/errors.js.map +1 -1
  201. package/dist/shared/id.d.ts +4 -0
  202. package/dist/shared/id.js +4 -0
  203. package/dist/shared/id.js.map +1 -1
  204. package/dist/shared/logger.d.ts +2 -1
  205. package/dist/shared/logger.js +10 -1
  206. package/dist/shared/logger.js.map +1 -1
  207. package/dist/shared/ports.d.ts +25 -5
  208. package/dist/types/content.d.ts +2 -2
  209. package/dist/types/discussion.d.ts +4 -5
  210. package/dist/types/email-templates.d.ts +22 -3
  211. package/dist/types/entitlements.d.ts +2 -2
  212. package/dist/types/identity.d.ts +13 -16
  213. package/dist/types/index.d.ts +9 -9
  214. package/dist/types/index.js +2 -1
  215. package/dist/types/notifications.d.ts +4 -4
  216. package/dist/types/organizations.d.ts +3 -2
  217. package/dist/types/ports.d.ts +8 -1
  218. package/dist/types/ports.js +7 -1
  219. package/dist/types/ports.js.map +1 -0
  220. package/dist/types/schemas/assets.d.ts +5 -5
  221. package/dist/types/schemas/assets.js +4 -3
  222. package/dist/types/schemas/assets.js.map +1 -1
  223. package/dist/types/schemas/content.d.ts +599 -13
  224. package/dist/types/schemas/content.js +219 -8
  225. package/dist/types/schemas/content.js.map +1 -1
  226. package/dist/types/schemas/discussion.d.ts +280 -57
  227. package/dist/types/schemas/discussion.js +77 -3
  228. package/dist/types/schemas/discussion.js.map +1 -1
  229. package/dist/types/schemas/entitlements.d.ts +21 -8
  230. package/dist/types/schemas/entitlements.js +11 -4
  231. package/dist/types/schemas/entitlements.js.map +1 -1
  232. package/dist/types/schemas/index.d.ts +5 -5
  233. package/dist/types/schemas/index.js +5 -5
  234. package/dist/types/schemas/notifications.d.ts +11 -10
  235. package/dist/types/schemas/notifications.js +3 -2
  236. package/dist/types/schemas/notifications.js.map +1 -1
  237. package/dist/types/schemas/organizations.d.ts +99 -60
  238. package/dist/types/schemas/organizations.js +80 -27
  239. package/dist/types/schemas/organizations.js.map +1 -1
  240. package/dist/types/schemas/progress.d.ts +3 -4
  241. package/dist/types/schemas/progress.js +0 -1
  242. package/dist/types/schemas/progress.js.map +1 -1
  243. package/package.json +1 -1
  244. package/dist/organizations/access-scopes.d.ts +0 -19
  245. package/dist/organizations/access-scopes.js +0 -89
  246. package/dist/organizations/access-scopes.js.map +0 -1
  247. package/dist/organizations/roles.d.ts +0 -19
  248. package/dist/organizations/roles.js +0 -82
  249. package/dist/organizations/roles.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","names":[],"sources":["../../../src/reporting/member/service.ts"],"sourcesContent":["import { type ContentServicePort, type SpaceDetail } from '../../content/index.js';\nimport { seesSpace, type EntitlementsService, type SpaceMember } from '../../entitlements/index.js';\nimport type { ProgressService } from '../../progress/index.js';\nimport type { AssetFiles, FileUrls } from '../../assets/index.js';\nimport { isStaffRole } from '../../organizations/index.js';\nimport type {\n ItemTitles as DiscussionItemTitles,\n SubscriptionService,\n} from '../../discussion/index.js';\nimport type { ItemTitles as ContentItemTitles } from '../../content/index.js';\nimport type { NotificationSettingsService } from '../../identity/index.js';\nimport type { ListedNotification, NotificationsService } from '../../automations/index.js';\nimport type { ChannelRegistry, NotificationCategoryService } from '../../shared/ports.js';\nimport { resolveChannels } from '../../shared/notification-settings.js';\nimport { channelOrder } from '../../shared/notification-categories.js';\nimport type {\n NotificationCategory,\n NotificationFilter,\n StoredSetting,\n SubjectRef,\n} from '../../types/index.js';\nimport type { Actor } from '../../shared/actor.js';\nimport type { Page } from '../../types/index.js';\nimport type {\n ActivityView,\n CommunityHome,\n CommunityHomeLink,\n CommunityHomeSpace,\n CourseProgressView,\n CourseView,\n DirectoryEntry,\n DirectoryQuery,\n DownloadFile,\n DownloadView,\n Module,\n NotificationItemView,\n NotificationView,\n NotificationsView,\n NotificationUnreadCounts,\n CommunityNotificationSettingsView,\n NotificationSettingsCategoryView,\n OrgNotificationSettingsView,\n SettingsChannelView,\n} from './model.js';\nimport type { MemberReportRepository, MemberReportService } from './ports.js';\n\nfunction refKey(ref: SubjectRef): string {\n return `${ref.type}:${ref.id}`;\n}\n\nfunction itemView(\n ref: SubjectRef | null,\n titles: Record<string, { title: string; excerpt?: string }>,\n): NotificationItemView | null {\n const found = ref ? titles[refKey(ref)] : undefined;\n if (!ref || !found) {\n return null;\n }\n return found.excerpt !== undefined\n ? { type: ref.type, id: ref.id, excerpt: found.excerpt }\n : { type: ref.type, id: ref.id, title: found.title };\n}\n\nfunction isActivityPublished(settings: unknown): boolean {\n return (settings as { published?: boolean } | null)?.published !== false;\n}\n\ntype MemberAccess = Pick<\n EntitlementsService,\n | 'isCommunityMember'\n | 'openSpaceIds'\n | 'spaceStandings'\n | 'hasAccess'\n | 'listAccessibleContent'\n | 'openCommunityIds'\n>;\n\nexport type MemberReportServiceParams = {\n repo: MemberReportRepository;\n content: ContentServicePort;\n progress: ProgressService;\n files: Pick<AssetFiles, 'signFile'>;\n fileUrls: FileUrls;\n access: MemberAccess;\n notifications: Pick<NotificationsService, 'list' | 'get' | 'unreadCounts'>;\n titles: { discussion: DiscussionItemTitles; content: ContentItemTitles };\n subscriptions: Pick<SubscriptionService, 'viewerSubscriptions'>;\n notificationCategories: {\n community: Pick<NotificationCategoryService, 'get'>;\n org: Pick<NotificationCategoryService, 'get'>;\n };\n notificationSettings: Pick<NotificationSettingsService, 'get'>;\n channels: Pick<ChannelRegistry, 'list'>;\n};\n\nexport class MemberReportServiceImpl implements MemberReportService {\n private readonly repo: MemberReportRepository;\n private readonly content: ContentServicePort;\n private readonly progress: ProgressService;\n private readonly files: Pick<AssetFiles, 'signFile'>;\n private readonly fileUrls: FileUrls;\n private readonly access: MemberAccess;\n private readonly notificationList: Pick<NotificationsService, 'list' | 'get' | 'unreadCounts'>;\n private readonly titles: MemberReportServiceParams['titles'];\n private readonly subscriptions: Pick<SubscriptionService, 'viewerSubscriptions'>;\n private readonly notificationCategories: MemberReportServiceParams['notificationCategories'];\n private readonly notificationSettings: Pick<NotificationSettingsService, 'get'>;\n private readonly channels: Pick<ChannelRegistry, 'list'>;\n\n constructor(params: MemberReportServiceParams) {\n this.repo = params.repo;\n this.content = params.content;\n this.progress = params.progress;\n this.files = params.files;\n this.fileUrls = params.fileUrls;\n this.access = params.access;\n this.notificationList = params.notifications;\n this.titles = params.titles;\n this.subscriptions = params.subscriptions;\n this.notificationCategories = params.notificationCategories;\n this.notificationSettings = params.notificationSettings;\n this.channels = params.channels;\n }\n\n async communityNotificationSettings(\n orgId: string,\n actor: Actor,\n userId: string,\n communityId: string,\n ): Promise<CommunityNotificationSettingsView | null> {\n if (!(await this.access.isCommunityMember(orgId, actor, communityId))) {\n return null;\n }\n const [list, settings, spaceIds, spaces, community] = await Promise.all([\n this.notificationCategories.community.get(orgId, communityId),\n this.notificationSettings.get(orgId, userId, { communityId }),\n this.access.openSpaceIds(orgId, actor, communityId),\n this.content.listSpaces(orgId, communityId),\n this.content.getCommunity(orgId, communityId),\n ]);\n const open = new Set(spaceIds);\n return {\n communityId,\n digest: community?.settings.digest ?? null,\n categories: this.settingsView(\n list.categories,\n settings,\n spaces\n .filter((space) => open.has(space.id))\n .map((space) => ({ spaceId: space.id, name: space.name })),\n ),\n };\n }\n\n async orgNotificationSettings(\n orgId: string,\n userId: string,\n ): Promise<OrgNotificationSettingsView> {\n const [list, settings] = await Promise.all([\n this.notificationCategories.org.get(orgId, orgId),\n this.notificationSettings.get(orgId, userId, 'org'),\n ]);\n return { categories: this.settingsView(list.categories, settings, []) };\n }\n\n private settingsView(\n categories: NotificationCategory[],\n settings: StoredSetting[],\n spaces: { spaceId: string; name: string }[],\n ): NotificationSettingsCategoryView[] {\n const configured = channelOrder(this.channels.list());\n const channelsAt = (\n category: NotificationCategory,\n spaceId: string | null,\n ): SettingsChannelView[] => {\n const withoutLevel = settings.filter(\n (setting) => setting.category !== category.key || setting.spaceId !== spaceId,\n );\n const fallback = new Map(\n resolveChannels(category, withoutLevel, spaceId, configured).map((resolved) => [\n resolved.channel,\n resolved.enabled,\n ]),\n );\n return resolveChannels(category, settings, spaceId, configured).map((resolved) => ({\n ...resolved,\n default: fallback.get(resolved.channel) ?? resolved.enabled,\n }));\n };\n return categories.map((category) => {\n const perSpace = category.perSpace === true;\n const view: NotificationSettingsCategoryView = {\n key: category.key,\n perSpace,\n channels: channelsAt(category, null),\n };\n if (perSpace) {\n view.spaces = spaces.map(({ spaceId, name }) => ({\n spaceId,\n name,\n channels: channelsAt(category, spaceId),\n }));\n }\n return view;\n });\n }\n\n async notifications(\n orgId: string,\n actor: Actor,\n userId: string,\n filter: NotificationFilter,\n page: { page: number; pageSize: number },\n ): Promise<NotificationsView> {\n const listed = await this.notificationList.list(orgId, userId, filter, page);\n return {\n rows: await this.describeNotifications(orgId, actor, listed.items),\n total: listed.total,\n page: page.page,\n pageSize: page.pageSize,\n unreadCount: listed.unreadCount,\n };\n }\n\n async notification(\n orgId: string,\n actor: Actor,\n userId: string,\n notificationId: string,\n ): Promise<NotificationView | null> {\n const found = await this.notificationList.get(orgId, userId, notificationId);\n if (!found) {\n return null;\n }\n const [view] = await this.describeNotifications(orgId, actor, [found]);\n return view ?? null;\n }\n\n async notificationUnreadCounts(\n orgId: string,\n actor: Actor,\n userId: string,\n ): Promise<NotificationUnreadCounts> {\n const communityIds = await this.access.openCommunityIds(orgId, actor);\n return this.notificationList.unreadCounts(orgId, userId, communityIds);\n }\n\n private async describeNotifications(\n orgId: string,\n actor: Actor,\n rows: ListedNotification[],\n ): Promise<NotificationView[]> {\n const refs = rows.flatMap((row) => [\n ...(row.subject ? [row.subject] : []),\n ...(row.parent ? [row.parent] : []),\n ...(row.communityId ? [{ type: 'community' as const, id: row.communityId }] : []),\n ...(row.spaceId ? [{ type: 'space' as const, id: row.spaceId }] : []),\n ]);\n const actorIds = [...new Set(rows.flatMap((row) => row.actorOrgUserId ?? []))];\n const [people, discussionTitles, contentTitles] = await Promise.all([\n this.repo.people(orgId, actorIds),\n this.titles.discussion.titlesFor(orgId, actor, refs),\n this.titles.content.titlesFor(orgId, actor, refs),\n ]);\n const titles = { ...contentTitles, ...discussionTitles };\n const personById = new Map(people.map((person) => [person.orgUserId, person]));\n return rows.map((row) => {\n const person = row.actorOrgUserId ? personById.get(row.actorOrgUserId) : undefined;\n const community = row.communityId ? titles[`community:${row.communityId}`] : undefined;\n const space = row.spaceId ? titles[`space:${row.spaceId}`] : undefined;\n return {\n id: row.id,\n type: row.type,\n scope: row.scope,\n reasons: row.reasons,\n matchedReason: row.matchedReason,\n category: row.category,\n display: row.display,\n community:\n row.communityId && community ? { id: row.communityId, title: community.title } : null,\n space: row.spaceId && space ? { id: row.spaceId, name: space.title } : null,\n actor: person\n ? {\n orgUserId: person.orgUserId,\n name: person.displayName,\n imageUrl: person.imageAssetId ? this.fileUrls.personImage(person.orgUserId) : null,\n }\n : null,\n subject: itemView(row.subject, titles),\n parent: itemView(row.parent, titles),\n createdAt: row.createdAt,\n readAt: row.readAt,\n };\n });\n }\n\n async listCourses(orgId: string, orgUserId: string): Promise<CourseView[]> {\n const ids = await this.access.listAccessibleContent(orgId, orgUserId, 'course');\n const courses = await Promise.all(ids.map((id) => this.content.getCourse(orgId, id)));\n return courses.filter((c): c is CourseView => c !== null && c.status === 'published');\n }\n\n async getCourse(orgId: string, orgUserId: string, courseId: string): Promise<CourseView | null> {\n if (!(await this.access.hasAccess(orgId, orgUserId, courseId))) {\n return null;\n }\n const course = await this.content.getCourse(orgId, courseId);\n return course && course.status === 'published' ? course : null;\n }\n\n async listModules(orgId: string, orgUserId: string, courseId: string): Promise<Module[] | null> {\n if (!(await this.getCourse(orgId, orgUserId, courseId))) {\n return null;\n }\n return this.content.listCourseModules(orgId, courseId);\n }\n\n async listActivities(\n orgId: string,\n orgUserId: string,\n courseId: string,\n ): Promise<ActivityView[] | null> {\n if (!(await this.getCourse(orgId, orgUserId, courseId))) {\n return null;\n }\n const activities = await this.content.listCourseActivityViews(orgId, courseId);\n return activities.filter((a) => isActivityPublished(a.settings));\n }\n\n async courseProgress(\n orgId: string,\n orgUserId: string,\n courseId: string,\n ): Promise<CourseProgressView | null> {\n if (!(await this.getCourse(orgId, orgUserId, courseId))) {\n return null;\n }\n const courseActivities = await this.content.listCourseActivities(orgId, courseId);\n const ids = courseActivities.filter((a) => isActivityPublished(a.settings)).map((a) => a.id);\n const records = await this.progress.listByTargets(orgId, orgUserId, ids);\n const activities: CourseProgressView['activities'] = {};\n const positions: CourseProgressView['positions'] = {};\n let done = 0;\n for (const r of records) {\n if (r.targetType !== 'activity') {\n continue;\n }\n activities[r.targetId] = r.completedAt ? 'completed' : 'in-progress';\n if (r.completedAt) {\n done += 1;\n }\n if (r.position != null) {\n positions[r.targetId] = r.position;\n }\n }\n const courseRecord = await this.progress.get(orgId, {\n orgUserId,\n targetType: 'course',\n targetId: courseId,\n });\n return {\n activities,\n percent: ids.length > 0 ? Math.round((done / ids.length) * 100) : 0,\n completed: courseRecord?.completedAt != null,\n positions,\n };\n }\n\n async listDownloads(orgId: string, orgUserId: string): Promise<DownloadView[]> {\n const ids = await this.access.listAccessibleContent(orgId, orgUserId, 'download');\n const rows = await Promise.all(ids.map((id) => this.content.getDownload(orgId, id)));\n return rows.filter((d): d is DownloadView => d !== null && d.status === 'published');\n }\n\n async getDownload(\n orgId: string,\n orgUserId: string,\n downloadId: string,\n ): Promise<{ download: DownloadView; assets: DownloadFile[] } | null> {\n if (!(await this.access.hasAccess(orgId, orgUserId, downloadId))) {\n return null;\n }\n const download = await this.content.getDownload(orgId, downloadId);\n if (!download || download.status !== 'published') {\n return null;\n }\n const assets = await this.content.listDownloadAssets(orgId, downloadId);\n return { download, assets };\n }\n\n async thumbnailFile(\n orgId: string,\n actor: Actor,\n owner: 'course' | 'download' | 'community',\n id: string,\n ): Promise<string | null> {\n const item =\n owner === 'course'\n ? await this.content.getCourse(orgId, id)\n : owner === 'download'\n ? await this.content.getDownload(orgId, id)\n : await this.content.getCommunity(orgId, id);\n if (!item?.thumbnailAssetId || (item.status !== 'published' && !isStaffRole(actor.role))) {\n return null;\n }\n return this.files.signFile(orgId, item.thumbnailAssetId);\n }\n\n async activityFile(\n orgId: string,\n actor: Actor,\n activityId: string,\n assetId: string,\n ): Promise<string | null> {\n const activity = await this.content.getActivity(orgId, activityId);\n if (!activity) {\n return null;\n }\n if (!isStaffRole(actor.role)) {\n if (\n !isActivityPublished(activity.settings) ||\n !(await this.getCourse(orgId, actor.id, activity.courseId))\n ) {\n return null;\n }\n }\n const links = await this.content.listCourseActivityAssets(orgId, activity.courseId);\n if (!links.some((link) => link.activityId === activityId && link.assetId === assetId)) {\n return null;\n }\n return this.files.signFile(orgId, assetId);\n }\n\n async downloadFile(\n orgId: string,\n actor: Actor,\n downloadId: string,\n assetId: string,\n ): Promise<string | null> {\n if (!isStaffRole(actor.role) && !(await this.getDownload(orgId, actor.id, downloadId))) {\n return null;\n }\n const files = await this.content.listDownloadAssets(orgId, downloadId);\n const file = files.find((f) => f.assetId === assetId);\n if (!file) {\n return null;\n }\n return this.files.signFile(orgId, assetId, { saveAs: file.displayName ?? file.filename });\n }\n\n async personImage(orgId: string, orgUserId: string): Promise<string | null> {\n const [person] = await this.repo.people(orgId, [orgUserId]);\n if (!person?.imageAssetId) {\n return null;\n }\n return this.files.signFile(orgId, person.imageAssetId);\n }\n\n async directory(\n orgId: string,\n actor: Actor,\n communityId: string,\n query: DirectoryQuery,\n ): Promise<Page<DirectoryEntry> | null> {\n if (!(await this.access.isCommunityMember(orgId, actor, communityId))) {\n return null;\n }\n const community = await this.content.getCommunity(orgId, communityId);\n if (!community) {\n return null;\n }\n const page = await this.repo.directory(orgId, communityId, query);\n return {\n ...page,\n rows: page.rows.map((row) => ({\n ...row,\n imageUrl: row.imageAssetId ? this.fileUrls.personImage(row.orgUserId) : null,\n })),\n };\n }\n\n async communityHome(\n orgId: string,\n actor: Actor,\n communityId: string,\n ): Promise<CommunityHome | null> {\n if (!(await this.access.isCommunityMember(orgId, actor, communityId))) {\n return null;\n }\n const community = await this.content.getCommunity(orgId, communityId);\n if (!community) {\n return null;\n }\n const spaces = await this.content.listSpaces(orgId, communityId);\n return {\n communityId,\n title: community.title,\n description: community.description,\n thumbnailUrl: community.thumbnailUrl,\n dm: community.settings.dm,\n spaces: await this.homeSpaces(orgId, actor, communityId, spaces),\n };\n }\n\n async communitySpace(\n orgId: string,\n actor: Actor,\n communityId: string,\n spaceId: string,\n ): Promise<CommunityHomeSpace | null> {\n if (!(await this.access.isCommunityMember(orgId, actor, communityId))) {\n return null;\n }\n const space = await this.content.getSpace(orgId, spaceId);\n if (!space || space.communityId !== communityId) {\n return null;\n }\n const [view] = await this.homeSpaces(orgId, actor, communityId, [space]);\n return view ?? null;\n }\n\n private async homeSpaces(\n orgId: string,\n actor: Actor,\n communityId: string,\n spaces: SpaceDetail[],\n ): Promise<CommunityHomeSpace[]> {\n const [openIds, counts, standings, subscribed] = await Promise.all([\n this.access.openSpaceIds(orgId, actor, communityId),\n this.repo.spaceMemberCounts(orgId, communityId),\n this.access.spaceStandings(orgId, actor, communityId),\n this.subscriptions.viewerSubscriptions(\n orgId,\n actor.id,\n 'space',\n spaces.map((space) => space.id),\n new Date(),\n ),\n ]);\n const open = new Set(openIds);\n const seen = spaces.filter((space) =>\n seesSpace(actor.role, space.accessRule, standings[space.id]),\n );\n return Promise.all(\n seen.map(async (space): Promise<CommunityHomeSpace> => {\n const memberCount = counts[space.id] ?? 0;\n const base = {\n id: space.id,\n name: space.name,\n memberCount,\n accessRule: space.accessRule,\n standing: standingOf(space, open.has(space.id), memberCount, standings[space.id]),\n };\n if (!open.has(space.id)) {\n return { ...base, locked: true };\n }\n return {\n ...base,\n locked: false,\n description: space.description,\n capacity: space.capacity,\n settings: space.settings,\n topics: space.topics.map((topic) => ({ id: topic.id, name: topic.name })),\n links: await this.linkViews(orgId, actor, space.links),\n subscription: subscribed[space.id] ?? null,\n };\n }),\n );\n }\n\n private async linkViews(\n orgId: string,\n actor: Actor,\n links: SpaceDetail['links'],\n ): Promise<CommunityHomeLink[]> {\n const shown = (status: string) => status === 'published' || isStaffRole(actor.role);\n const views = await Promise.all(\n links.map(async (link): Promise<CommunityHomeLink | null> => {\n const course = await this.content.getCourse(orgId, link.contentId);\n if (course) {\n return shown(course.status)\n ? { id: link.id, contentId: link.contentId, type: 'course', title: course.title }\n : null;\n }\n const download = await this.content.getDownload(orgId, link.contentId);\n if (download) {\n return shown(download.status)\n ? { id: link.id, contentId: link.contentId, type: 'download', title: download.title }\n : null;\n }\n const community = await this.content.getCommunity(orgId, link.contentId);\n if (community) {\n return shown(community.status)\n ? { id: link.id, contentId: link.contentId, type: 'community', title: community.title }\n : null;\n }\n return null;\n }),\n );\n return views.filter((view): view is CommunityHomeLink => view !== null);\n }\n}\n\nfunction standingOf(\n space: SpaceDetail,\n open: boolean,\n memberCount: number,\n status: SpaceMember['status'] | undefined,\n): CommunityHomeSpace['standing'] {\n if (space.accessRule === 'all_members' || (open && status !== 'active')) {\n return 'open';\n }\n if (status === 'active') {\n return 'member';\n }\n if (status === 'requested' || status === 'invited') {\n return status;\n }\n if (space.capacity !== null && memberCount >= space.capacity) {\n return 'full';\n }\n return 'none';\n}\n"],"mappings":";;;;;AA8CA,SAAS,OAAO,KAAyB;CACvC,OAAO,GAAG,IAAI,KAAK,GAAG,IAAI;AAC5B;AAEA,SAAS,SACP,KACA,QAC6B;CAC7B,MAAM,QAAQ,MAAM,OAAO,OAAO,GAAG,KAAK,KAAA;CAC1C,IAAI,CAAC,OAAO,CAAC,OACX,OAAO;CAET,OAAO,MAAM,YAAY,KAAA,IACrB;EAAE,MAAM,IAAI;EAAM,IAAI,IAAI;EAAI,SAAS,MAAM;CAAQ,IACrD;EAAE,MAAM,IAAI;EAAM,IAAI,IAAI;EAAI,OAAO,MAAM;CAAM;AACvD;AAEA,SAAS,oBAAoB,UAA4B;CACvD,OAAQ,UAA6C,cAAc;AACrE;AA8BA,IAAa,0BAAb,MAAoE;CAClE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,QAAmC;EAC7C,KAAK,OAAO,OAAO;EACnB,KAAK,UAAU,OAAO;EACtB,KAAK,WAAW,OAAO;EACvB,KAAK,QAAQ,OAAO;EACpB,KAAK,WAAW,OAAO;EACvB,KAAK,SAAS,OAAO;EACrB,KAAK,mBAAmB,OAAO;EAC/B,KAAK,SAAS,OAAO;EACrB,KAAK,gBAAgB,OAAO;EAC5B,KAAK,yBAAyB,OAAO;EACrC,KAA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MAAM,KAAK,QAAQ,UAAU,OAAO,KAAK,SAAS;GACjE,IAAI,QACF,OAAO,MAAM,OAAO,MAAM,IACtB;IAAE,IAAI,KAAK;IAAI,WAAW,KAAK;IAAW,MAAM;IAAU,OAAO,OAAO;GAAM,IAC9E;GAEN,MAAM,WAAW,MAAM,KAAK,QAAQ,YAAY,OAAO,KAAK,SAAS;GACrE,IAAI,UACF,OAAO,MAAM,SAAS,MAAM,IACxB;IAAE,IAAI,KAAK;IAAI,WAAW,KAAK;IAAW,MAAM;IAAY,OAAO,SAAS;GAAM,IAClF;GAEN,MAAM,YAAY,MAAM,KAAK,QAAQ,aAAa,OAAO,KAAK,SAAS;GACvE,IAAI,WACF,OAAO,MAAM,UAAU,MAAM,IACzB;IAAE,IAAI,KAAK;IAAI,WAAW,KAAK;IAAW,MAAM;IAAa,OAAO,UAAU;GAAM,IACpF;GAEN,OAAO;EACT,CAAC,CACH,EAAA,CACa,QAAQ,SAAoC,SAAS,IAAI;CACxE;AACF;AAEA,SAAS,WACP,OACA,MACA,aACA,QACgC;CAChC,IAAI,MAAM,eAAe,iBAAkB,QAAQ,WAAW,UAC5D,OAAO;CAET,IAAI,WAAW,UACb,OAAO;CAET,IAAI,WAAW,eAAe,WAAW,WACvC,OAAO;CAET,IAAI,MAAM,aAAa,QAAQ,eAAe,MAAM,UAClD,OAAO;CAET,OAAO;AACT"}
1
+ {"version":3,"file":"service.js","names":[],"sources":["../../../src/reporting/member/service.ts"],"sourcesContent":["import {\n eventSight,\n type ContentServicePort,\n type EventSight,\n type EventView,\n type SpaceDetail,\n type SpaceImage,\n type SpaceView,\n} from '../../content/index.js';\nimport { NotFoundError } from '../../shared/errors.js';\nimport { seesSpace, type EntitlementsService, type SpaceMember } from '../../entitlements/index.js';\nimport type { ProgressService } from '../../progress/index.js';\nimport type { AssetFiles, FileUrls } from '../../assets/index.js';\nimport type { OrganizationService } from '../../organizations/index.js';\nimport { PERMISSION_KEYS } from '../../types/schemas/organizations.js';\nimport type {\n ItemTitles as DiscussionItemTitles,\n SubscriptionService,\n} from '../../discussion/index.js';\nimport type { ItemTitles as ContentItemTitles } from '../../content/index.js';\nimport type { MemberActor, NotificationSettingsService } from '../../identity/index.js';\nimport {\n applicableCategories,\n type ListedNotification,\n type NotificationsService,\n} from '../../automations/index.js';\nimport type { ChannelRegistry, NotificationCategoryService } from '../../shared/ports.js';\nimport { resolveChannels } from '../../shared/notification-settings.js';\nimport { channelOrder } from '../../shared/notification-categories.js';\nimport type {\n NotificationCategory,\n NotificationFilter,\n StoredSetting,\n SubjectRef,\n} from '../../types/index.js';\nimport type { Actor } from '../../shared/actor.js';\nimport type { EventFile, Page, Permission } from '../../types/index.js';\nimport type {\n ActivityView,\n CommunityHome,\n CommunityHomeLink,\n CommunityHomeSpace,\n CourseProgressView,\n CourseView,\n DirectoryEntry,\n DirectoryQuery,\n DownloadFile,\n DownloadView,\n EventAttendee,\n MemberEvent,\n MemberEventSummary,\n MemberEventsQuery,\n MemberViewer,\n Module,\n NotificationItemView,\n NotificationView,\n NotificationsView,\n NotificationUnreadCounts,\n CommunityNotificationSettingsView,\n NotificationSettingsCategoryView,\n OrgNotificationSettingsView,\n SettingsChannelView,\n} from './model.js';\nimport type { MemberReportRepository, MemberReportService } from './ports.js';\nimport { eventCalendar } from './calendar.js';\nimport { attendeeFace, attendeeView, type EventFaces } from '../events/index.js';\n\nfunction refKey(ref: SubjectRef): string {\n return `${ref.type}:${ref.id}`;\n}\n\nfunction itemView(\n ref: SubjectRef | null,\n titles: Record<string, { title: string; excerpt?: string }>,\n): NotificationItemView | null {\n const found = ref ? titles[refKey(ref)] : undefined;\n if (!ref || !found) {\n return null;\n }\n return found.excerpt !== undefined\n ? { type: ref.type, id: ref.id, excerpt: found.excerpt }\n : { type: ref.type, id: ref.id, title: found.title };\n}\n\nfunction isActivityPublished(settings: unknown): boolean {\n return (settings as { published?: boolean } | null)?.published !== false;\n}\n\ntype MemberAccess = Pick<\n EntitlementsService,\n | 'isCommunityMember'\n | 'openSpaceIds'\n | 'spaceStandings'\n | 'hasAccess'\n | 'listAccessibleContent'\n | 'openCommunityIds'\n | 'opensEverySpace'\n | 'everySpaceOpeners'\n>;\n\ntype MemberContent = Pick<\n ContentServicePort,\n | 'findCourse'\n | 'listCourseModules'\n | 'listCourseActivityViews'\n | 'listCourseActivities'\n | 'listCourseActivityAssets'\n | 'getActivity'\n | 'findDownload'\n | 'listDownloadAssets'\n | 'findCommunity'\n | 'listSpaces'\n | 'getSpace'\n | 'findEvent'\n | 'findEvents'\n | 'eventFilesFor'\n>;\n\ntype MemberPeople = Pick<OrganizationService, 'systemActor' | 'permissionsOfMany' | 'holders'>;\n\ntype Owner = 'course' | 'download' | 'community' | 'event';\n\nconst READ_OF = {\n course: 'courses:read',\n download: 'downloads:read',\n community: 'communities:read',\n event: 'events:read',\n} as const satisfies Record<Owner, Permission>;\n\nconst THUMBNAIL_OF = {\n course: 'Course thumbnail',\n download: 'Download thumbnail',\n community: 'Community thumbnail',\n event: 'Event thumbnail',\n} as const satisfies Record<Owner, string>;\n\nconst SPACE_IMAGE_ASSET = {\n cover: (space) => space.coverAssetId,\n background: (space) => space.backgroundAssetId,\n icon: (space) => space.iconAssetId,\n} as const satisfies Record<SpaceImage, (space: SpaceView) => string | null>;\n\nconst EVENT_FACES = 10;\n\ninterface SeenEvent {\n event: EventView;\n sight: EventSight;\n attending: boolean;\n}\n\nexport type MemberReportServiceParams = {\n repo: MemberReportRepository;\n content: MemberContent;\n progress: Pick<ProgressService, 'get' | 'listByTargets'>;\n files: Pick<AssetFiles, 'signFile'>;\n fileUrls: FileUrls;\n access: MemberAccess;\n people: MemberPeople;\n notifications: Pick<NotificationsService, 'list' | 'get' | 'unreadCounts'>;\n titles: { discussion: DiscussionItemTitles; content: ContentItemTitles };\n subscriptions: Pick<SubscriptionService, 'viewerSubscriptions'>;\n notificationCategories: {\n community: Pick<NotificationCategoryService, 'get'>;\n org: Pick<NotificationCategoryService, 'get'>;\n };\n notificationSettings: Pick<NotificationSettingsService, 'get'>;\n channels: Pick<ChannelRegistry, 'list'>;\n studentPortalUrl: string;\n now?: () => Date;\n};\n\nexport class MemberReportServiceImpl implements MemberReportService {\n private readonly repo: MemberReportRepository;\n private readonly content: MemberContent;\n private readonly progress: Pick<ProgressService, 'get' | 'listByTargets'>;\n private readonly files: Pick<AssetFiles, 'signFile'>;\n private readonly fileUrls: FileUrls;\n private readonly access: MemberAccess;\n private readonly people: MemberPeople;\n private readonly notificationList: Pick<NotificationsService, 'list' | 'get' | 'unreadCounts'>;\n private readonly titles: MemberReportServiceParams['titles'];\n private readonly subscriptions: Pick<SubscriptionService, 'viewerSubscriptions'>;\n private readonly notificationCategories: MemberReportServiceParams['notificationCategories'];\n private readonly notificationSettings: Pick<NotificationSettingsService, 'get'>;\n private readonly channels: Pick<ChannelRegistry, 'list'>;\n private readonly studentPortalUrl: string;\n private readonly now: () => Date;\n\n constructor(params: MemberReportServiceParams) {\n this.repo = params.repo;\n this.content = params.content;\n this.progress = params.progress;\n this.files = params.files;\n this.fileUrls = params.fileUrls;\n this.access = params.access;\n this.people = params.people;\n this.notificationList = params.notifications;\n this.titles = params.titles;\n this.subscriptions = params.subscriptions;\n this.notificationCategories = params.notificationCategories;\n this.notificationSettings = params.notificationSettings;\n this.channels = params.channels;\n this.studentPortalUrl = params.studentPortalUrl.replace(/\\/+$/, '');\n this.now = params.now ?? (() => new Date());\n }\n\n private system(actor: Actor): Actor {\n return this.people.systemActor(actor.orgId);\n }\n\n viewer(actor: Actor): MemberViewer {\n const role = actor.permissions.roleOn();\n return {\n orgUserId: actor.id,\n orgRole: { key: role.key, name: role.name },\n permissions: PERMISSION_KEYS.filter((p) => actor.permissions.anywhere(p)),\n orgPermissions: PERMISSION_KEYS.filter((p) => actor.permissions.has(p)),\n };\n }\n\n async communityNotificationSettings(\n communityId: string,\n actor: MemberActor,\n ): Promise<CommunityNotificationSettingsView> {\n if (!(await this.access.isCommunityMember(communityId, actor))) {\n throw new NotFoundError('Community', communityId);\n }\n const orgId = actor.orgId;\n const system = this.system(actor);\n const [list, settings, spaceIds, spaces, community] = await Promise.all([\n this.notificationCategories.community.get(communityId, system),\n this.notificationSettings.get(orgId, actor.userId, { communityId }),\n this.access.openSpaceIds(communityId, actor),\n this.content.listSpaces(communityId, system),\n this.content.findCommunity(communityId, system),\n ]);\n const open = new Set(spaceIds);\n return {\n communityId,\n digest: community?.settings.digest ?? null,\n categories: this.settingsView(\n applicableCategories(list.categories, actor.permissions, { communityId }),\n settings,\n spaces\n .filter((space) => open.has(space.id))\n .map((space) => ({ spaceId: space.id, name: space.name })),\n ),\n };\n }\n\n async orgNotificationSettings(actor: MemberActor): Promise<OrgNotificationSettingsView> {\n const orgId = actor.orgId;\n const [list, settings] = await Promise.all([\n this.notificationCategories.org.get(orgId, this.system(actor)),\n this.notificationSettings.get(orgId, actor.userId, 'org'),\n ]);\n return {\n categories: this.settingsView(\n applicableCategories(list.categories, actor.permissions, 'org'),\n settings,\n [],\n ),\n };\n }\n\n private settingsView(\n categories: NotificationCategory[],\n settings: StoredSetting[],\n spaces: { spaceId: string; name: string }[],\n ): NotificationSettingsCategoryView[] {\n const configured = channelOrder(this.channels.list());\n const channelsAt = (\n category: NotificationCategory,\n spaceId: string | null,\n ): SettingsChannelView[] => {\n const withoutLevel = settings.filter(\n (setting) => setting.category !== category.key || setting.spaceId !== spaceId,\n );\n const fallback = new Map(\n resolveChannels(category, withoutLevel, spaceId, configured).map((resolved) => [\n resolved.channel,\n resolved.enabled,\n ]),\n );\n return resolveChannels(category, settings, spaceId, configured).map((resolved) => ({\n ...resolved,\n default: fallback.get(resolved.channel) ?? resolved.enabled,\n }));\n };\n return categories.map((category) => {\n const perSpace = category.perSpace === true;\n const view: NotificationSettingsCategoryView = {\n key: category.key,\n perSpace,\n channels: channelsAt(category, null),\n };\n if (perSpace) {\n view.spaces = spaces.map(({ spaceId, name }) => ({\n spaceId,\n name,\n channels: channelsAt(category, spaceId),\n }));\n }\n return view;\n });\n }\n\n async notifications(\n filter: NotificationFilter,\n page: { page: number; pageSize: number },\n actor: MemberActor,\n ): Promise<NotificationsView> {\n const listed = await this.notificationList.list(filter, page, actor);\n return {\n rows: await this.describeNotifications(actor, listed.items),\n total: listed.total,\n page: page.page,\n pageSize: page.pageSize,\n unreadCount: listed.unreadCount,\n };\n }\n\n async notification(notificationId: string, actor: MemberActor): Promise<NotificationView> {\n const found = await this.notificationList.get(notificationId, actor);\n const [view] = found ? await this.describeNotifications(actor, [found]) : [];\n if (!view) {\n throw new NotFoundError('Notification', notificationId);\n }\n return view;\n }\n\n async notificationUnreadCounts(actor: MemberActor): Promise<NotificationUnreadCounts> {\n const communityIds = await this.access.openCommunityIds(actor);\n return this.notificationList.unreadCounts(communityIds, actor);\n }\n\n private async describeNotifications(\n actor: Actor,\n rows: ListedNotification[],\n ): Promise<NotificationView[]> {\n const orgId = actor.orgId;\n const refs = rows.flatMap((row) => [\n ...(row.subject ? [row.subject] : []),\n ...(row.parent ? [row.parent] : []),\n ...(row.communityId ? [{ type: 'community' as const, id: row.communityId }] : []),\n ...(row.spaceId ? [{ type: 'space' as const, id: row.spaceId }] : []),\n ]);\n const actorIds = [...new Set(rows.flatMap((row) => row.actorId ?? []))];\n const [people, discussionTitles, contentTitles] = await Promise.all([\n this.repo.people(orgId, actorIds),\n this.titles.discussion.titlesFor(refs, actor),\n this.titles.content.titlesFor(refs, actor),\n ]);\n const titles = { ...contentTitles, ...discussionTitles };\n const personById = new Map(people.map((person) => [person.orgUserId, person]));\n return rows.map((row) => {\n const person = row.actorId ? personById.get(row.actorId) : undefined;\n const community = row.communityId ? titles[`community:${row.communityId}`] : undefined;\n const space = row.spaceId ? titles[`space:${row.spaceId}`] : undefined;\n return {\n id: row.id,\n type: row.type,\n scope: row.scope,\n reasons: row.reasons,\n matchedReason: row.matchedReason,\n category: row.category,\n display: row.display,\n community:\n row.communityId && community ? { id: row.communityId, title: community.title } : null,\n space: row.spaceId && space ? { id: row.spaceId, name: space.title } : null,\n actor: person\n ? {\n orgUserId: person.orgUserId,\n name: person.displayName,\n imageUrl: person.imageAssetId\n ? this.fileUrls.publicImage(orgId, person.orgUserId, person.imageAssetId)\n : null,\n }\n : null,\n subject: itemView(row.subject, titles),\n parent: itemView(row.parent, titles),\n createdAt: row.createdAt,\n readAt: row.readAt,\n };\n });\n }\n\n private async opensCourse(courseId: string, actor: Actor): Promise<CourseView | null> {\n const reads = actor.permissions.has('courses:read', courseId);\n if (!reads && !(await this.access.hasAccess(actor.orgId, actor.id, courseId))) {\n return null;\n }\n const course = await this.content.findCourse(courseId, this.system(actor));\n return course && (reads || course.status === 'published') ? course : null;\n }\n\n private async opensDownload(downloadId: string, actor: Actor): Promise<DownloadView | null> {\n const reads = actor.permissions.has('downloads:read', downloadId);\n if (!reads && !(await this.access.hasAccess(actor.orgId, actor.id, downloadId))) {\n return null;\n }\n const download = await this.content.findDownload(downloadId, this.system(actor));\n return download && (reads || download.status === 'published') ? download : null;\n }\n\n async listCourses(actor: Actor): Promise<CourseView[]> {\n const ids = await this.access.listAccessibleContent(actor.orgId, actor.id, 'course');\n const system = this.system(actor);\n const courses = await Promise.all(ids.map((id) => this.content.findCourse(id, system)));\n return courses.filter((c): c is CourseView => c !== null && c.status === 'published');\n }\n\n private async requireCourse(courseId: string, actor: Actor): Promise<CourseView> {\n const course = await this.opensCourse(courseId, actor);\n if (!course) {\n throw new NotFoundError('Course', courseId);\n }\n return course;\n }\n\n getCourse(courseId: string, actor: Actor): Promise<CourseView> {\n return this.requireCourse(courseId, actor);\n }\n\n async listModules(courseId: string, actor: Actor): Promise<Module[]> {\n await this.requireCourse(courseId, actor);\n return this.content.listCourseModules(courseId, this.system(actor));\n }\n\n async listActivities(courseId: string, actor: Actor): Promise<ActivityView[]> {\n await this.requireCourse(courseId, actor);\n const activities = await this.content.listCourseActivityViews(courseId, this.system(actor));\n return activities.filter((a) => isActivityPublished(a.settings));\n }\n\n async courseProgress(courseId: string, actor: Actor): Promise<CourseProgressView> {\n await this.requireCourse(courseId, actor);\n const orgId = actor.orgId;\n const courseActivities = await this.content.listCourseActivities(courseId, this.system(actor));\n const ids = courseActivities.filter((a) => isActivityPublished(a.settings)).map((a) => a.id);\n const records = await this.progress.listByTargets(orgId, actor.id, ids);\n const activities: CourseProgressView['activities'] = {};\n const positions: CourseProgressView['positions'] = {};\n let done = 0;\n for (const r of records) {\n if (r.targetType !== 'activity') {\n continue;\n }\n activities[r.targetId] = r.completedAt ? 'completed' : 'in-progress';\n if (r.completedAt) {\n done += 1;\n }\n if (r.position != null) {\n positions[r.targetId] = r.position;\n }\n }\n const courseRecord = await this.progress.get(orgId, {\n orgUserId: actor.id,\n targetType: 'course',\n targetId: courseId,\n });\n return {\n activities,\n percent: ids.length > 0 ? Math.round((done / ids.length) * 100) : 0,\n completed: courseRecord?.completedAt != null,\n positions,\n };\n }\n\n async listDownloads(actor: Actor): Promise<DownloadView[]> {\n const ids = await this.access.listAccessibleContent(actor.orgId, actor.id, 'download');\n const system = this.system(actor);\n const rows = await Promise.all(ids.map((id) => this.content.findDownload(id, system)));\n return rows.filter((d): d is DownloadView => d !== null && d.status === 'published');\n }\n\n async getDownload(\n downloadId: string,\n actor: Actor,\n ): Promise<{ download: DownloadView; assets: DownloadFile[] }> {\n const download = await this.opensDownload(downloadId, actor);\n if (!download) {\n throw new NotFoundError('Download', downloadId);\n }\n const assets = await this.content.listDownloadAssets(downloadId, this.system(actor));\n return { download, assets };\n }\n\n async thumbnailFile(owner: Owner, id: string, actor: Actor): Promise<string> {\n const system = this.system(actor);\n const item =\n owner === 'event'\n ? (await this.seeEvents([id], actor))[0]?.event\n : owner === 'course'\n ? await this.content.findCourse(id, system)\n : owner === 'download'\n ? await this.content.findDownload(id, system)\n : await this.content.findCommunity(id, system);\n if (\n !item?.thumbnailAssetId ||\n (owner !== 'event' &&\n item.status !== 'published' &&\n !actor.permissions.has(READ_OF[owner], id))\n ) {\n throw new NotFoundError(THUMBNAIL_OF[owner], id);\n }\n return signed(\n await this.files.signFile(actor.orgId, item.thumbnailAssetId),\n THUMBNAIL_OF[owner],\n id,\n );\n }\n\n async spaceImageFile(spaceId: string, image: SpaceImage, actor: Actor): Promise<string> {\n const system = this.system(actor);\n const space = await this.content.getSpace(spaceId, system);\n const assetId = space ? SPACE_IMAGE_ASSET[image](space) : null;\n const community = space ? await this.content.findCommunity(space.communityId, system) : null;\n if (\n !space ||\n !assetId ||\n !community ||\n (community.status !== 'published' &&\n !actor.permissions.has('communities:read', space.communityId))\n ) {\n throw new NotFoundError('Space image', spaceId);\n }\n return signed(await this.files.signFile(actor.orgId, assetId), 'Space image', spaceId);\n }\n\n async activityFile(activityId: string, assetId: string, actor: Actor): Promise<string> {\n const system = this.system(actor);\n const activity = await this.content.getActivity(activityId, system);\n if (!activity) {\n throw new NotFoundError('Lesson file', assetId);\n }\n if (!actor.permissions.has('courses:read', activity.courseId)) {\n if (\n !isActivityPublished(activity.settings) ||\n !(await this.opensCourse(activity.courseId, actor))\n ) {\n throw new NotFoundError('Lesson file', assetId);\n }\n }\n const links = await this.content.listCourseActivityAssets(activity.courseId, system);\n if (!links.some((link) => link.activityId === activityId && link.assetId === assetId)) {\n throw new NotFoundError('Lesson file', assetId);\n }\n return signed(await this.files.signFile(actor.orgId, assetId), 'Lesson file', assetId);\n }\n\n async downloadFile(downloadId: string, assetId: string, actor: Actor): Promise<string> {\n if (!(await this.opensDownload(downloadId, actor))) {\n throw new NotFoundError('Download file', assetId);\n }\n const files = await this.content.listDownloadAssets(downloadId, this.system(actor));\n const file = files.find((f) => f.assetId === assetId);\n if (!file) {\n throw new NotFoundError('Download file', assetId);\n }\n return signed(\n await this.files.signFile(actor.orgId, assetId, {\n saveAs: file.displayName ?? file.filename,\n }),\n 'Download file',\n assetId,\n );\n }\n\n private async seeEvents(ids: string[], actor: Actor): Promise<SeenEvent[]> {\n if (ids.length === 0) {\n return [];\n }\n const system = this.system(actor);\n const [events, attended] = await Promise.all([\n this.content.findEvents(ids, system),\n ids.length === 1\n ? this.access\n .hasAccess(actor.orgId, actor.id, ids[0]!)\n .then((attending) => (attending ? [ids[0]!] : []))\n : this.access.listAccessibleContent(actor.orgId, actor.id, 'event'),\n ]);\n const attending = new Set(attended);\n const byId = new Map(events.map((event) => [event.id, event]));\n return ids.flatMap((id) => {\n const event = byId.get(id);\n if (!event) {\n return [];\n }\n const sight = eventSight(event, {\n canRead: actor.permissions.has('events:read', id),\n attending: attending.has(id),\n });\n return sight ? [{ event, sight, attending: attending.has(id) }] : [];\n });\n }\n\n private async requireEvent(eventId: string, actor: Actor): Promise<SeenEvent> {\n const [seen] = await this.seeEvents([eventId], actor);\n if (!seen) {\n throw new NotFoundError('Event', eventId);\n }\n return seen;\n }\n\n private async eventSummaries(\n seen: SeenEvent[],\n actor: Actor,\n now: Date,\n ): Promise<MemberEventSummary[]> {\n const ids = seen.map((item) => item.event.id);\n const attended = seen.filter((item) => item.attending).map((item) => item.event.id);\n const [faces, direct] = await Promise.all([\n this.repo.eventFaces(actor.orgId, ids, EVENT_FACES),\n attended.length > 0\n ? this.repo.directEventGrants(actor.orgId, actor.id, attended)\n : Promise.resolve([]),\n ]);\n const leaves = new Set(direct);\n return seen.map((item) =>\n this.eventSummary(\n item,\n faces[item.event.id] ?? { total: 0, rows: [] },\n leaves.has(item.event.id),\n actor,\n now,\n ),\n );\n }\n\n private eventSummary(\n seen: SeenEvent,\n faces: EventFaces,\n canLeave: boolean,\n actor: Actor,\n now: Date,\n ): MemberEventSummary {\n const { event, sight, attending } = seen;\n const id = event.id;\n const canOpen = sight !== 'public';\n const capacity = event.settings.capacity;\n const attendeeCount = faces.total;\n const ended = event.endsAt.getTime() <= now.getTime();\n const recording =\n sight === 'read' || (sight === 'attendee' && ended && event.settings.replay)\n ? event.recording\n : null;\n const writes = actor.permissions.has('events:write', id);\n const canManageAttendees = actor.permissions.has('access:write') || writes;\n return {\n orgId: event.orgId,\n id,\n type: event.type,\n title: event.title,\n thumbnailAssetId: event.thumbnailAssetId,\n thumbnailUrl: event.thumbnailUrl,\n status: event.status,\n startsAt: event.startsAt,\n endsAt: event.endsAt,\n timeZone: event.timeZone,\n location: canOpen ? event.location : null,\n recording,\n settings: {\n type: event.settings.type,\n capacity,\n replay: event.settings.replay,\n },\n attendeeCount,\n attendees: faces.rows.map((row) => attendeeFace(actor.orgId, row, this.fileUrls)),\n placesLeft: capacity === null ? null : Math.max(capacity - attendeeCount, 0),\n viewer: {\n attending,\n canRegister:\n event.status === 'published' &&\n !attending &&\n event.settings.type === 'public' &&\n event.startsAt.getTime() > now.getTime() &&\n (capacity === null || attendeeCount < capacity),\n canOpen,\n canLeave,\n canManageAttendees,\n canAddAttendees: canManageAttendees && event.status === 'published' && !ended,\n canEdit: writes,\n canCancel: writes,\n canDelete: actor.permissions.has('events:delete', id),\n },\n };\n }\n\n async getEvent(eventId: string, actor: Actor): Promise<MemberEvent> {\n const seen = await this.requireEvent(eventId, actor);\n const now = this.now();\n const [[summary], files] = await Promise.all([\n this.eventSummaries([seen], actor, now),\n seen.sight === 'public'\n ? Promise.resolve({} as Record<string, EventFile[]>)\n : this.content.eventFilesFor([eventId], this.system(actor)),\n ]);\n return { ...summary!, description: seen.event.description, files: files[eventId] ?? [] };\n }\n\n async listEvents(query: MemberEventsQuery, actor: Actor): Promise<Page<MemberEventSummary>> {\n const now = this.now();\n const reads = actor.permissions.where('events:read');\n const page = await this.repo.events(\n actor.orgId,\n query,\n { orgUserId: actor.id, readAll: reads.org, readIds: reads.content },\n now,\n );\n const rows = await this.eventSummaries(await this.seeEvents(page.rows, actor), actor, now);\n return { ...page, rows };\n }\n\n async eventCalendar(eventId: string, actor: Actor): Promise<string> {\n const { event, sight } = await this.requireEvent(eventId, actor);\n return eventCalendar(event, {\n pageUrl: `${this.studentPortalUrl}/events/${encodeURIComponent(event.id)}`,\n withLocation: sight !== 'public',\n now: this.now(),\n });\n }\n\n async eventAttendees(\n eventId: string,\n query: { page: number; pageSize: number },\n actor: Actor,\n ): Promise<Page<EventAttendee>> {\n actor.permissions.require('events:read', eventId);\n if (!(await this.content.findEvent(eventId, this.system(actor)))) {\n throw new NotFoundError('Event', eventId);\n }\n const page = await this.repo.eventAttendees(actor.orgId, eventId, query);\n return {\n ...page,\n rows: page.rows.map((row) => attendeeView(actor.orgId, row, this.fileUrls)),\n };\n }\n\n async eventFile(eventId: string, assetId: string, actor: Actor): Promise<string> {\n const [seen] = await this.seeEvents([eventId], actor);\n if (!seen || seen.sight === 'public') {\n throw new NotFoundError('Event file', assetId);\n }\n const files = await this.content.eventFilesFor([eventId], this.system(actor));\n const file = files[eventId]?.find((f) => f.assetId === assetId);\n if (!file) {\n throw new NotFoundError('Event file', assetId);\n }\n return signed(\n await this.files.signFile(actor.orgId, assetId, {\n saveAs: file.displayName ?? file.filename,\n }),\n 'Event file',\n assetId,\n );\n }\n\n async directory(\n communityId: string,\n query: DirectoryQuery,\n actor: Actor,\n ): Promise<Page<DirectoryEntry>> {\n if (!(await this.access.isCommunityMember(communityId, actor))) {\n throw new NotFoundError('Community', communityId);\n }\n const orgId = actor.orgId;\n const community = await this.content.findCommunity(communityId, this.system(actor));\n if (!community) {\n throw new NotFoundError('Community', communityId);\n }\n const readers = await this.people.holders(orgId, 'communities:read', communityId);\n const page = await this.repo.directory(orgId, communityId, query, readers);\n const permissions = await this.people.permissionsOfMany(\n orgId,\n page.rows.map((row) => row.orgUserId),\n );\n return {\n ...page,\n rows: page.rows.map((row) => {\n const held = permissions.get(row.orgUserId);\n const item = held?.roleOn(communityId);\n const org = held?.roleOn();\n return {\n ...row,\n imageUrl: row.imageAssetId\n ? this.fileUrls.publicImage(orgId, row.orgUserId, row.imageAssetId)\n : null,\n team: (item?.team ?? false) || (org?.team ?? false),\n roleName: item?.team ? item.name : org?.team ? org.name : null,\n opensEverySpace:\n (held?.has('communities:read', communityId) ||\n held?.has('communities:moderate', communityId)) ??\n false,\n };\n }),\n };\n }\n\n async communityHome(communityId: string, actor: Actor): Promise<CommunityHome> {\n if (!(await this.access.isCommunityMember(communityId, actor))) {\n throw new NotFoundError('Community', communityId);\n }\n const system = this.system(actor);\n const community = await this.content.findCommunity(communityId, system);\n if (!community) {\n throw new NotFoundError('Community', communityId);\n }\n const [spaces, everySpace] = await Promise.all([\n this.content.listSpaces(communityId, system),\n this.access.opensEverySpace(actor, communityId),\n ]);\n const itemRole = actor.permissions.roleOn(communityId);\n const orgRole = actor.permissions.roleOn();\n const role = itemRole.team || !orgRole.team ? itemRole : orgRole;\n return {\n communityId,\n title: community.title,\n description: community.description,\n thumbnailUrl: community.thumbnailUrl,\n dm: community.settings.dm,\n spaces: await this.homeSpaces(actor, communityId, spaces, everySpace),\n viewer: {\n permissions: PERMISSION_KEYS.filter((p) => actor.permissions.has(p, communityId)),\n opensEverySpace: everySpace,\n team: itemRole.team || orgRole.team,\n roleName: role.name,\n canCreateEvents: actor.permissions.has('events:write'),\n },\n };\n }\n\n async communitySpace(\n communityId: string,\n spaceId: string,\n actor: Actor,\n ): Promise<CommunityHomeSpace> {\n if (!(await this.access.isCommunityMember(communityId, actor))) {\n throw new NotFoundError('Space', spaceId);\n }\n const space = await this.content.getSpace(spaceId, this.system(actor));\n if (!space || space.communityId !== communityId) {\n throw new NotFoundError('Space', spaceId);\n }\n const everySpace = await this.access.opensEverySpace(actor, communityId);\n const [view] = await this.homeSpaces(actor, communityId, [space], everySpace);\n if (!view) {\n throw new NotFoundError('Space', spaceId);\n }\n return view;\n }\n\n private async homeSpaces(\n actor: Actor,\n communityId: string,\n spaces: SpaceView[],\n everySpace: boolean,\n ): Promise<CommunityHomeSpace[]> {\n const orgId = actor.orgId;\n const excluding = await this.access.everySpaceOpeners(orgId, communityId);\n const [openIds, counts, standings, subscribed] = await Promise.all([\n this.access.openSpaceIds(communityId, actor),\n this.repo.spaceMemberCounts(orgId, communityId, excluding),\n this.access.spaceStandings(communityId, actor),\n this.subscriptions.viewerSubscriptions(\n orgId,\n actor.id,\n 'space',\n spaces.map((space) => space.id),\n new Date(),\n ),\n ]);\n const open = new Set(openIds);\n const seen = spaces.filter((space) =>\n seesSpace(everySpace, space.accessRule, standings[space.id]),\n );\n return Promise.all(\n seen.map(async (space): Promise<CommunityHomeSpace> => {\n const memberCount = counts[space.id] ?? 0;\n const base = {\n id: space.id,\n name: space.name,\n memberCount,\n accessRule: space.accessRule,\n standing: standingOf(space, open.has(space.id), memberCount, standings[space.id]),\n coverUrl: space.coverUrl,\n backgroundUrl: space.backgroundUrl,\n iconUrl: space.iconUrl,\n };\n if (!open.has(space.id)) {\n return { ...base, locked: true };\n }\n return {\n ...base,\n locked: false,\n description: space.description,\n capacity: space.capacity,\n settings: space.settings,\n topics: space.topics.map((topic) => ({ id: topic.id, name: topic.name })),\n links: await this.linkViews(actor, space.links),\n subscription: subscribed[space.id] ?? null,\n };\n }),\n );\n }\n\n private async linkViews(actor: Actor, links: SpaceDetail['links']): Promise<CommunityHomeLink[]> {\n const system = this.system(actor);\n const shown = (type: keyof typeof READ_OF, id: string, status: string) =>\n status === 'published' || actor.permissions.has(READ_OF[type], id);\n const views = await Promise.all(\n links.map(async (link): Promise<CommunityHomeLink | null> => {\n const course = await this.content.findCourse(link.contentId, system);\n if (course) {\n return shown('course', link.contentId, course.status)\n ? { id: link.id, contentId: link.contentId, type: 'course', title: course.title }\n : null;\n }\n const download = await this.content.findDownload(link.contentId, system);\n if (download) {\n return shown('download', link.contentId, download.status)\n ? { id: link.id, contentId: link.contentId, type: 'download', title: download.title }\n : null;\n }\n const community = await this.content.findCommunity(link.contentId, system);\n if (community) {\n return shown('community', link.contentId, community.status)\n ? { id: link.id, contentId: link.contentId, type: 'community', title: community.title }\n : null;\n }\n return null;\n }),\n );\n return views.filter((view): view is CommunityHomeLink => view !== null);\n }\n}\n\nfunction signed(url: string | null, what: string, id: string): string {\n if (!url) {\n throw new NotFoundError(what, id);\n }\n return url;\n}\n\nfunction standingOf(\n space: SpaceDetail,\n open: boolean,\n memberCount: number,\n status: SpaceMember['status'] | undefined,\n): CommunityHomeSpace['standing'] {\n if (space.accessRule === 'all_members' || (open && status !== 'active')) {\n return 'open';\n }\n if (status === 'active') {\n return 'member';\n }\n if (status === 'requested' || status === 'invited') {\n return status;\n }\n if (space.capacity !== null && memberCount >= space.capacity) {\n return 'full';\n }\n return 'none';\n}\n"],"mappings":";;;;;;;;;;AAmEA,SAAS,OAAO,KAAyB;CACvC,OAAO,GAAG,IAAI,KAAK,GAAG,IAAI;AAC5B;AAEA,SAAS,SACP,KACA,QAC6B;CAC7B,MAAM,QAAQ,MAAM,OAAO,OAAO,GAAG,KAAK,KAAA;CAC1C,IAAI,CAAC,OAAO,CAAC,OACX,OAAO;CAET,OAAO,MAAM,YAAY,KAAA,IACrB;EAAE,MAAM,IAAI;EAAM,IAAI,IAAI;EAAI,SAAS,MAAM;CAAQ,IACrD;EAAE,MAAM,IAAI;EAAM,IAAI,IAAI;EAAI,OAAO,MAAM;CAAM;AACvD;AAEA,SAAS,oBAAoB,UAA4B;CACvD,OAAQ,UAA6C,cAAc;AACrE;AAoCA,MAAM,UAAU;CACd,QAAQ;CACR,UAAU;CACV,WAAW;CACX,OAAO;AACT;AAEA,MAAM,eAAe;CACnB,QAAQ;CACR,UAAU;CACV,WAAW;CACX,OAAO;AACT;AAEA,MAAM,oBAAoB;CACxB,QAAQ,UAAU,MAAM;CACxB,aAAa,UAAU,MAAM;CAC7B,OAAO,UAAU,MAAM;AACzB;AAEA,MAAM,cAAc;AA6BpB,IAAa,0BAAb,MAAoE;CAClE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,QAAmC;EAC7C,KAAK,OAAO,OAAO;EACnB,KAAK,UAAU,OAAO;EACtB,KAAK,WAAW,OAAO;EACvB,KAAK,QAAQ,OAAO;EACpB,KAAK,WAAW,OAAO;EACvB,KAAK,SAAS,OAAO;EACrB,KAAK,SAAS,OAAO;EACrB,KAAK,mBAAmB,OAAO;EAC/B,KAAK,SAAS,OAAO;EACrB,KAAK,gBAAgB,OAAO;EAC5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WACF,OAAO,MAAM,aAAa,KAAK,WAAW,UAAU,MAAM,IACtD;IAAE,IAAI,KAAK;IAAI,WAAW,KAAK;IAAW,MAAM;IAAa,OAAO,UAAU;GAAM,IACpF;GAEN,OAAO;EACT,CAAC,CACH,EAAA,CACa,QAAQ,SAAoC,SAAS,IAAI;CACxE;AACF;AAEA,SAAS,OAAO,KAAoB,MAAc,IAAoB;CACpE,IAAI,CAAC,KACH,MAAM,IAAI,cAAc,MAAM,EAAE;CAElC,OAAO;AACT;AAEA,SAAS,WACP,OACA,MACA,aACA,QACgC;CAChC,IAAI,MAAM,eAAe,iBAAkB,QAAQ,WAAW,UAC5D,OAAO;CAET,IAAI,WAAW,UACb,OAAO;CAET,IAAI,WAAW,eAAe,WAAW,WACvC,OAAO;CAET,IAAI,MAAM,aAAa,QAAQ,eAAe,MAAM,UAClD,OAAO;CAET,OAAO;AACT"}
@@ -1,9 +1,29 @@
1
- import { Role } from "../types/schemas/organizations.js";
1
+ import { Permission } from "../types/schemas/organizations.js";
2
+ import { ContentId } from "../types/organizations.js";
3
+ import "../types/index.js";
2
4
  //#region src/shared/actor.d.ts
5
+ interface RoleRef {
6
+ key: string;
7
+ name: string;
8
+ team: boolean;
9
+ }
10
+ interface EffectivePermissions {
11
+ has(permission: Permission, on?: ContentId): boolean;
12
+ require(permission: Permission, on?: ContentId): void;
13
+ anywhere(permission: Permission): boolean;
14
+ where(permission: Permission): {
15
+ org: boolean;
16
+ content: ContentId[];
17
+ };
18
+ roleOn(on?: ContentId): RoleRef;
19
+ isOwner(): boolean;
20
+ isToken(): boolean;
21
+ }
3
22
  interface Actor {
4
23
  id: string;
5
- role: Role;
24
+ orgId: string;
25
+ permissions: EffectivePermissions;
6
26
  }
7
27
  //#endregion
8
- export { Actor };
28
+ export { Actor, EffectivePermissions, RoleRef };
9
29
  //# sourceMappingURL=actor.d.ts.map
@@ -10,7 +10,8 @@ declare class NotFoundError extends Error {
10
10
  /** A command conflicts with existing state (duplicate email, already linked,
11
11
  * …). The HTTP layer maps this to 409. */
12
12
  declare class ConflictError extends Error {
13
- constructor(message: string);
13
+ readonly code?: string | undefined;
14
+ constructor(message: string, code?: string | undefined);
14
15
  }
15
16
  /** The caller is authenticated but not permitted to perform this command.
16
17
  * The HTTP layer maps this to 403. */
@@ -15,8 +15,10 @@ var NotFoundError = class extends Error {
15
15
  /** A command conflicts with existing state (duplicate email, already linked,
16
16
  * …). The HTTP layer maps this to 409. */
17
17
  var ConflictError = class extends Error {
18
- constructor(message) {
18
+ code;
19
+ constructor(message, code) {
19
20
  super(message);
21
+ this.code = code;
20
22
  this.name = "ConflictError";
21
23
  }
22
24
  };
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../../src/shared/errors.ts"],"sourcesContent":["// Cross-cutting domain errors. Like `../shared/ports.js`, this file is\n// importable from any context; the central HTTP error handler maps these to\n// status codes so routes never hand-roll error replies.\n\n/** A command's target does not exist in this org. Queries return null for the\n * same situation — a missing row is a normal answer to a question, but a\n * failed precondition for a command. */\nexport class NotFoundError extends Error {\n constructor(\n readonly resource: string,\n readonly id: string,\n ) {\n super(`${resource} not found`);\n this.name = 'NotFoundError';\n }\n}\n\n/** A command conflicts with existing state (duplicate email, already linked,\n * …). The HTTP layer maps this to 409. */\nexport class ConflictError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConflictError';\n }\n}\n\n/** The caller is authenticated but not permitted to perform this command.\n * The HTTP layer maps this to 403. */\nexport class ForbiddenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ForbiddenError';\n }\n}\n\n/** The caller's own input breaks a rule, independent of existing state\n * (wrong file type, too large, talking to yourself, …). The HTTP layer maps\n * this to 400. */\nexport class InvalidInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidInputError';\n }\n}\n\nexport class UnavailableError extends Error {\n constructor(\n message: string,\n readonly details?: Record<string, string>,\n ) {\n super(message);\n this.name = 'UnavailableError';\n }\n}\n\nexport type ValidationProblem = { path?: string; message: string };\n\nexport class ValidationError extends Error {\n readonly problems: ValidationProblem[];\n\n constructor(problems: string | ValidationProblem[]) {\n const list = typeof problems === 'string' ? [{ message: problems }] : problems;\n super(\n list\n .map((problem) => (problem.path ? `${problem.path}: ${problem.message}` : problem.message))\n .join('; '),\n );\n this.problems = list;\n this.name = 'ValidationError';\n }\n}\n"],"mappings":";;;;AAOA,IAAa,gBAAb,cAAmC,MAAM;CAE5B;CACA;CAFX,YACE,UACA,IACA;EACA,MAAM,GAAG,SAAS,WAAW;EAHpB,KAAA,WAAA;EACA,KAAA,KAAA;EAGT,KAAK,OAAO;CACd;AACF;;;AAIA,IAAa,gBAAb,cAAmC,MAAM;CACvC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;AAIA,IAAa,iBAAb,cAAoC,MAAM;CACxC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,IAAa,mBAAb,cAAsC,MAAM;CAG/B;CAFX,YACE,SACA,SACA;EACA,MAAM,OAAO;EAFJ,KAAA,UAAA;EAGT,KAAK,OAAO;CACd;AACF;AAIA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CAEA,YAAY,UAAwC;EAClD,MAAM,OAAO,OAAO,aAAa,WAAW,CAAC,EAAE,SAAS,SAAS,CAAC,IAAI;EACtE,MACE,KACG,KAAK,YAAa,QAAQ,OAAO,GAAG,QAAQ,KAAK,IAAI,QAAQ,YAAY,QAAQ,OAAQ,CAAC,CAC1F,KAAK,IAAI,CACd;EACA,KAAK,WAAW;EAChB,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../src/shared/errors.ts"],"sourcesContent":["// Cross-cutting domain errors. Like `../shared/ports.js`, this file is\n// importable from any context; the central HTTP error handler maps these to\n// status codes so routes never hand-roll error replies.\n\n/** A command's target does not exist in this org. Queries return null for the\n * same situation — a missing row is a normal answer to a question, but a\n * failed precondition for a command. */\nexport class NotFoundError extends Error {\n constructor(\n readonly resource: string,\n readonly id: string,\n ) {\n super(`${resource} not found`);\n this.name = 'NotFoundError';\n }\n}\n\n/** A command conflicts with existing state (duplicate email, already linked,\n * …). The HTTP layer maps this to 409. */\nexport class ConflictError extends Error {\n constructor(\n message: string,\n readonly code?: string,\n ) {\n super(message);\n this.name = 'ConflictError';\n }\n}\n\n/** The caller is authenticated but not permitted to perform this command.\n * The HTTP layer maps this to 403. */\nexport class ForbiddenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ForbiddenError';\n }\n}\n\n/** The caller's own input breaks a rule, independent of existing state\n * (wrong file type, too large, talking to yourself, …). The HTTP layer maps\n * this to 400. */\nexport class InvalidInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidInputError';\n }\n}\n\nexport class UnavailableError extends Error {\n constructor(\n message: string,\n readonly details?: Record<string, string>,\n ) {\n super(message);\n this.name = 'UnavailableError';\n }\n}\n\nexport type ValidationProblem = { path?: string; message: string };\n\nexport class ValidationError extends Error {\n readonly problems: ValidationProblem[];\n\n constructor(problems: string | ValidationProblem[]) {\n const list = typeof problems === 'string' ? [{ message: problems }] : problems;\n super(\n list\n .map((problem) => (problem.path ? `${problem.path}: ${problem.message}` : problem.message))\n .join('; '),\n );\n this.problems = list;\n this.name = 'ValidationError';\n }\n}\n"],"mappings":";;;;AAOA,IAAa,gBAAb,cAAmC,MAAM;CAE5B;CACA;CAFX,YACE,UACA,IACA;EACA,MAAM,GAAG,SAAS,WAAW;EAHpB,KAAA,WAAA;EACA,KAAA,KAAA;EAGT,KAAK,OAAO;CACd;AACF;;;AAIA,IAAa,gBAAb,cAAmC,MAAM;CAG5B;CAFX,YACE,SACA,MACA;EACA,MAAM,OAAO;EAFJ,KAAA,OAAA;EAGT,KAAK,OAAO;CACd;AACF;;;AAIA,IAAa,iBAAb,cAAoC,MAAM;CACxC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,IAAa,mBAAb,cAAsC,MAAM;CAG/B;CAFX,YACE,SACA,SACA;EACA,MAAM,OAAO;EAFJ,KAAA,UAAA;EAGT,KAAK,OAAO;CACd;AACF;AAIA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CAEA,YAAY,UAAwC;EAClD,MAAM,OAAO,OAAO,aAAa,WAAW,CAAC,EAAE,SAAS,SAAS,CAAC,IAAI;EACtE,MACE,KACG,KAAK,YAAa,QAAQ,OAAO,GAAG,QAAQ,KAAK,IAAI,QAAQ,YAAY,QAAQ,OAAQ,CAAC,CAC1F,KAAK,IAAI,CACd;EACA,KAAK,WAAW;EAChB,KAAK,OAAO;CACd;AACF"}
@@ -12,6 +12,8 @@ declare const ID_PREFIXES: {
12
12
  readonly user: "usr";
13
13
  readonly student: "stu";
14
14
  readonly orgUser: "orm";
15
+ readonly orgRole: "orl";
16
+ readonly roleAssignment: "ras";
15
17
  readonly invite: "ivt";
16
18
  readonly bundle: "bun";
17
19
  readonly course: "crs";
@@ -20,6 +22,8 @@ declare const ID_PREFIXES: {
20
22
  readonly activityAsset: "aca";
21
23
  readonly download: "dwn";
22
24
  readonly downloadAsset: "dla";
25
+ readonly contentEvent: "evn";
26
+ readonly eventAsset: "eva";
23
27
  readonly asset: "ast";
24
28
  readonly entitlement: "ent";
25
29
  readonly progress: "prg";
package/dist/shared/id.js CHANGED
@@ -13,6 +13,8 @@ const ID_PREFIXES = {
13
13
  user: "usr",
14
14
  student: "stu",
15
15
  orgUser: "orm",
16
+ orgRole: "orl",
17
+ roleAssignment: "ras",
16
18
  invite: "ivt",
17
19
  bundle: "bun",
18
20
  course: "crs",
@@ -21,6 +23,8 @@ const ID_PREFIXES = {
21
23
  activityAsset: "aca",
22
24
  download: "dwn",
23
25
  downloadAsset: "dla",
26
+ contentEvent: "evn",
27
+ eventAsset: "eva",
24
28
  asset: "ast",
25
29
  entitlement: "ent",
26
30
  progress: "prg",
@@ -1 +1 @@
1
- {"version":3,"file":"id.js","names":[],"sources":["../../src/shared/id.ts"],"sourcesContent":["import KSUID from 'ksuid';\n\n/**\n * Prefixed, KSUID-bodied string ids — `${prefix}_${ksuid}`, e.g. `org_2QZ4mK...`.\n *\n * The body is a real KSUID (27-char base62, 4-byte timestamp + 16 random bytes),\n * so ids are lexicographically time-sortable. The prefix marks the entity type at\n * a glance. A core utility (one implementation, nothing to swap), called directly\n * by core services and used as the Drizzle `.$defaultFn` for every domain id column.\n */\nexport const ID_PREFIXES = {\n organization: 'org',\n user: 'usr',\n student: 'stu',\n orgUser: 'orm',\n invite: 'ivt',\n bundle: 'bun',\n course: 'crs',\n module: 'mod',\n activity: 'act',\n activityAsset: 'aca',\n download: 'dwn',\n downloadAsset: 'dla',\n asset: 'ast',\n entitlement: 'ent',\n progress: 'prg',\n credential: 'crd',\n connection: 'con',\n event: 'evt',\n automation: 'atm',\n automationRun: 'run',\n comment: 'cmt',\n commentReport: 'crp',\n community: 'cmy',\n space: 'spc',\n topic: 'top',\n spaceLink: 'slk',\n spaceMember: 'spm',\n post: 'pst',\n postFlag: 'pfl',\n chat: 'cht',\n message: 'msg',\n messageFlag: 'mfl',\n notification: 'ntf',\n notificationSetting: 'nst',\n notificationDelivery: 'ndl',\n device: 'dev',\n} as const;\n\nexport type IdType = keyof typeof ID_PREFIXES;\n\n/** A bare KSUID body (27-char base62, time-sortable), no prefix. */\nexport function ksuid(): string {\n return KSUID.randomSync().string;\n}\n\n/** Attach an arbitrary prefix to a fresh KSUID — `${prefix}_${ksuid}`. */\nexport function prefixId(prefix: string): string {\n return `${prefix}_${ksuid()}`;\n}\n\n/** Generate a prefixed, time-sortable id for the given domain entity type. */\nexport function genId(type: IdType): string {\n return prefixId(ID_PREFIXES[type]);\n}\n\n/** True when `value` carries the prefix for `type` (shape check only, not existence). */\nexport function isId(type: IdType, value: string): boolean {\n return value.startsWith(`${ID_PREFIXES[type]}_`);\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,cAAc;CACzB,cAAc;CACd,MAAM;CACN,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,eAAe;CACf,UAAU;CACV,eAAe;CACf,OAAO;CACP,aAAa;CACb,UAAU;CACV,YAAY;CACZ,YAAY;CACZ,OAAO;CACP,YAAY;CACZ,eAAe;CACf,SAAS;CACT,eAAe;CACf,WAAW;CACX,OAAO;CACP,OAAO;CACP,WAAW;CACX,aAAa;CACb,MAAM;CACN,UAAU;CACV,MAAM;CACN,SAAS;CACT,aAAa;CACb,cAAc;CACd,qBAAqB;CACrB,sBAAsB;CACtB,QAAQ;AACV;;AAKA,SAAgB,QAAgB;CAC9B,OAAO,MAAM,WAAW,CAAC,CAAC;AAC5B;;AAGA,SAAgB,SAAS,QAAwB;CAC/C,OAAO,GAAG,OAAO,GAAG,MAAM;AAC5B;;AAGA,SAAgB,MAAM,MAAsB;CAC1C,OAAO,SAAS,YAAY,KAAK;AACnC;;AAGA,SAAgB,KAAK,MAAc,OAAwB;CACzD,OAAO,MAAM,WAAW,GAAG,YAAY,MAAM,EAAE;AACjD"}
1
+ {"version":3,"file":"id.js","names":[],"sources":["../../src/shared/id.ts"],"sourcesContent":["import KSUID from 'ksuid';\n\n/**\n * Prefixed, KSUID-bodied string ids — `${prefix}_${ksuid}`, e.g. `org_2QZ4mK...`.\n *\n * The body is a real KSUID (27-char base62, 4-byte timestamp + 16 random bytes),\n * so ids are lexicographically time-sortable. The prefix marks the entity type at\n * a glance. A core utility (one implementation, nothing to swap), called directly\n * by core services and used as the Drizzle `.$defaultFn` for every domain id column.\n */\nexport const ID_PREFIXES = {\n organization: 'org',\n user: 'usr',\n student: 'stu',\n orgUser: 'orm',\n orgRole: 'orl',\n roleAssignment: 'ras',\n invite: 'ivt',\n bundle: 'bun',\n course: 'crs',\n module: 'mod',\n activity: 'act',\n activityAsset: 'aca',\n download: 'dwn',\n downloadAsset: 'dla',\n contentEvent: 'evn',\n eventAsset: 'eva',\n asset: 'ast',\n entitlement: 'ent',\n progress: 'prg',\n credential: 'crd',\n connection: 'con',\n event: 'evt',\n automation: 'atm',\n automationRun: 'run',\n comment: 'cmt',\n commentReport: 'crp',\n community: 'cmy',\n space: 'spc',\n topic: 'top',\n spaceLink: 'slk',\n spaceMember: 'spm',\n post: 'pst',\n postFlag: 'pfl',\n chat: 'cht',\n message: 'msg',\n messageFlag: 'mfl',\n notification: 'ntf',\n notificationSetting: 'nst',\n notificationDelivery: 'ndl',\n device: 'dev',\n} as const;\n\nexport type IdType = keyof typeof ID_PREFIXES;\n\n/** A bare KSUID body (27-char base62, time-sortable), no prefix. */\nexport function ksuid(): string {\n return KSUID.randomSync().string;\n}\n\n/** Attach an arbitrary prefix to a fresh KSUID — `${prefix}_${ksuid}`. */\nexport function prefixId(prefix: string): string {\n return `${prefix}_${ksuid()}`;\n}\n\n/** Generate a prefixed, time-sortable id for the given domain entity type. */\nexport function genId(type: IdType): string {\n return prefixId(ID_PREFIXES[type]);\n}\n\n/** True when `value` carries the prefix for `type` (shape check only, not existence). */\nexport function isId(type: IdType, value: string): boolean {\n return value.startsWith(`${ID_PREFIXES[type]}_`);\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,cAAc;CACzB,cAAc;CACd,MAAM;CACN,SAAS;CACT,SAAS;CACT,SAAS;CACT,gBAAgB;CAChB,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,eAAe;CACf,UAAU;CACV,eAAe;CACf,cAAc;CACd,YAAY;CACZ,OAAO;CACP,aAAa;CACb,UAAU;CACV,YAAY;CACZ,YAAY;CACZ,OAAO;CACP,YAAY;CACZ,eAAe;CACf,SAAS;CACT,eAAe;CACf,WAAW;CACX,OAAO;CACP,OAAO;CACP,WAAW;CACX,aAAa;CACb,MAAM;CACN,UAAU;CACV,MAAM;CACN,SAAS;CACT,aAAa;CACb,cAAc;CACd,qBAAqB;CACrB,sBAAsB;CACtB,QAAQ;AACV;;AAKA,SAAgB,QAAgB;CAC9B,OAAO,MAAM,WAAW,CAAC,CAAC;AAC5B;;AAGA,SAAgB,SAAS,QAAwB;CAC/C,OAAO,GAAG,OAAO,GAAG,MAAM;AAC5B;;AAGA,SAAgB,MAAM,MAAsB;CAC1C,OAAO,SAAS,YAAY,KAAK;AACnC;;AAGA,SAAgB,KAAK,MAAc,OAAwB;CACzD,OAAO,MAAM,WAAW,GAAG,YAAY,MAAM,EAAE;AACjD"}
@@ -14,6 +14,7 @@ declare function createCapturingLogger(): {
14
14
  logger: Logger;
15
15
  entries: CapturedLog[];
16
16
  };
17
+ declare function describeError(err: unknown): string;
17
18
  //#endregion
18
- export { CapturedLog, createCapturingLogger, noopLogger };
19
+ export { CapturedLog, createCapturingLogger, describeError, noopLogger };
19
20
  //# sourceMappingURL=logger.d.ts.map
@@ -38,7 +38,16 @@ function createCapturingLogger() {
38
38
  entries
39
39
  };
40
40
  }
41
+ function describeError(err) {
42
+ if (err instanceof AggregateError && err.errors.length > 0) return [...new Set(err.errors.map(describeError))].join("; ");
43
+ if (err instanceof Error) {
44
+ const code = err.code;
45
+ const text = err.message || err.name;
46
+ return typeof code === "string" && !text.includes(code) ? `${code}: ${text}` : text;
47
+ }
48
+ return String(err);
49
+ }
41
50
  //#endregion
42
- export { createCapturingLogger, noopLogger };
51
+ export { createCapturingLogger, describeError, noopLogger };
43
52
 
44
53
  //# sourceMappingURL=logger.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","names":[],"sources":["../../src/shared/logger.ts"],"sourcesContent":["// Test/default implementations of the Logger port. The real pino-backed\n// implementation lives in adapters/logging; these exist so constructors can\n// default to a silent logger and tests can assert on emitted entries.\nimport type { Logger } from './ports.js';\n\n/** Discards everything. The default for constructors the container overrides. */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => noopLogger,\n};\n\nexport interface CapturedLog {\n level: 'debug' | 'info' | 'warn' | 'error';\n msg: string;\n meta: Record<string, unknown>;\n}\n\n/** In-memory logger for tests: every entry (from the root or any child) lands\n * in `entries`, with child bindings merged into meta. */\nexport function createCapturingLogger(): { logger: Logger; entries: CapturedLog[] } {\n const entries: CapturedLog[] = [];\n const make = (bindings: Record<string, unknown>): Logger => {\n const record =\n (level: CapturedLog['level']) => (msg: string, meta?: Record<string, unknown>) => {\n entries.push({ level, msg, meta: { ...bindings, ...meta } });\n };\n return {\n debug: record('debug'),\n info: record('info'),\n warn: record('warn'),\n error: record('error'),\n child: (more) => make({ ...bindings, ...more }),\n };\n };\n return { logger: make({}), entries };\n}\n"],"mappings":";;AAMA,MAAa,aAAqB;CAChC,aAAa,CAAC;CACd,YAAY,CAAC;CACb,YAAY,CAAC;CACb,aAAa,CAAC;CACd,aAAa;AACf;;;AAUA,SAAgB,wBAAoE;CAClF,MAAM,UAAyB,CAAC;CAChC,MAAM,QAAQ,aAA8C;EAC1D,MAAM,UACH,WAAiC,KAAa,SAAmC;GAChF,QAAQ,KAAK;IAAE;IAAO;IAAK,MAAM;KAAE,GAAG;KAAU,GAAG;IAAK;GAAE,CAAC;EAC7D;EACF,OAAO;GACL,OAAO,OAAO,OAAO;GACrB,MAAM,OAAO,MAAM;GACnB,MAAM,OAAO,MAAM;GACnB,OAAO,OAAO,OAAO;GACrB,QAAQ,SAAS,KAAK;IAAE,GAAG;IAAU,GAAG;GAAK,CAAC;EAChD;CACF;CACA,OAAO;EAAE,QAAQ,KAAK,CAAC,CAAC;EAAG;CAAQ;AACrC"}
1
+ {"version":3,"file":"logger.js","names":[],"sources":["../../src/shared/logger.ts"],"sourcesContent":["// Test/default implementations of the Logger port. The real pino-backed\n// implementation lives in adapters/logging; these exist so constructors can\n// default to a silent logger and tests can assert on emitted entries.\nimport type { Logger } from './ports.js';\n\n/** Discards everything. The default for constructors the container overrides. */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => noopLogger,\n};\n\nexport interface CapturedLog {\n level: 'debug' | 'info' | 'warn' | 'error';\n msg: string;\n meta: Record<string, unknown>;\n}\n\n/** In-memory logger for tests: every entry (from the root or any child) lands\n * in `entries`, with child bindings merged into meta. */\nexport function createCapturingLogger(): { logger: Logger; entries: CapturedLog[] } {\n const entries: CapturedLog[] = [];\n const make = (bindings: Record<string, unknown>): Logger => {\n const record =\n (level: CapturedLog['level']) => (msg: string, meta?: Record<string, unknown>) => {\n entries.push({ level, msg, meta: { ...bindings, ...meta } });\n };\n return {\n debug: record('debug'),\n info: record('info'),\n warn: record('warn'),\n error: record('error'),\n child: (more) => make({ ...bindings, ...more }),\n };\n };\n return { logger: make({}), entries };\n}\n\nexport function describeError(err: unknown): string {\n if (err instanceof AggregateError && err.errors.length > 0) {\n return [...new Set(err.errors.map(describeError))].join('; ');\n }\n if (err instanceof Error) {\n const code = (err as { code?: unknown }).code;\n const text = err.message || err.name;\n return typeof code === 'string' && !text.includes(code) ? `${code}: ${text}` : text;\n }\n return String(err);\n}\n"],"mappings":";;AAMA,MAAa,aAAqB;CAChC,aAAa,CAAC;CACd,YAAY,CAAC;CACb,YAAY,CAAC;CACb,aAAa,CAAC;CACd,aAAa;AACf;;;AAUA,SAAgB,wBAAoE;CAClF,MAAM,UAAyB,CAAC;CAChC,MAAM,QAAQ,aAA8C;EAC1D,MAAM,UACH,WAAiC,KAAa,SAAmC;GAChF,QAAQ,KAAK;IAAE;IAAO;IAAK,MAAM;KAAE,GAAG;KAAU,GAAG;IAAK;GAAE,CAAC;EAC7D;EACF,OAAO;GACL,OAAO,OAAO,OAAO;GACrB,MAAM,OAAO,MAAM;GACnB,MAAM,OAAO,MAAM;GACnB,OAAO,OAAO,OAAO;GACrB,QAAQ,SAAS,KAAK;IAAE,GAAG;IAAU,GAAG;GAAK,CAAC;EAChD;CACF;CACA,OAAO;EAAE,QAAQ,KAAK,CAAC,CAAC;EAAG;CAAQ;AACrC;AAEA,SAAgB,cAAc,KAAsB;CAClD,IAAI,eAAe,kBAAkB,IAAI,OAAO,SAAS,GACvD,OAAO,CAAC,GAAG,IAAI,IAAI,IAAI,OAAO,IAAI,aAAa,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI;CAE9D,IAAI,eAAe,OAAO;EACxB,MAAM,OAAQ,IAA2B;EACzC,MAAM,OAAO,IAAI,WAAW,IAAI;EAChC,OAAO,OAAO,SAAS,YAAY,CAAC,KAAK,SAAS,IAAI,IAAI,GAAG,KAAK,IAAI,SAAS;CACjF;CACA,OAAO,OAAO,GAAG;AACnB"}
@@ -5,6 +5,7 @@ import { EmailContent, EmailTemplateId, EmailTemplateParams, TemplateContext, Te
5
5
  import { ChannelRecipient, DeliveryResult, NotificationCategory, NotificationTypeDeclaration, PushDevice, PushMessage, StoredNotification } from "../types/notifications.js";
6
6
  import "../types/index.js";
7
7
  import { EventOf, EventOfValues, InvalidDomainEventError, RuntimeEventDefinition, defineEvent, eventIdSchema, eventJsonValueSchema, eventMetadataSchema } from "./events.js";
8
+ import { Actor } from "./actor.js";
8
9
  //#region src/shared/ports.d.ts
9
10
  interface Clock {
10
11
  now(): Date;
@@ -15,6 +16,17 @@ interface EventBus {
15
16
  subscribe(type: string, handler: (event: DomainEvent) => Promise<void>): void;
16
17
  subscribeAll(handler: (event: DomainEvent) => Promise<void>): void;
17
18
  }
19
+ /** Messages published on any instance, delivered to every subscriber on every
20
+ * instance, the publisher's included. Best effort: a subscriber can miss
21
+ * messages while its instance is disconnected; `onReset` fires after every
22
+ * reconnect. No ordering is promised. `start` never fails on connectivity:
23
+ * it keeps reconnecting and fires `onReset` once connected. */
24
+ interface PubSub {
25
+ publish(channel: string, message: JsonValue): Promise<void>;
26
+ subscribe(channel: string, handler: (message: JsonValue) => void, onReset: () => void): () => void;
27
+ start(): Promise<void>;
28
+ stop(): Promise<void>;
29
+ }
18
30
  /** Appends domain events to the transactional outbox. A tx-bound member of a
19
31
  * UnitOfWork scope, so the append shares that transaction — the event
20
32
  * becomes visible to the relay only when the surrounding write commits. */
@@ -73,16 +85,24 @@ interface ChannelRegistry {
73
85
  get(key: string): NotificationChannel | undefined;
74
86
  }
75
87
  interface NotificationCategoryService {
76
- get(orgId: string, scopeId: string): Promise<{
88
+ get(scopeId: string, actor: Actor): Promise<{
77
89
  categories: NotificationCategory[];
78
90
  source: 'default' | 'stored';
79
91
  }>;
80
- replace(orgId: string, scopeId: string, categories: NotificationCategory[]): Promise<{
92
+ replace(scopeId: string, categories: NotificationCategory[], actor: Actor): Promise<{
81
93
  categories: NotificationCategory[];
82
94
  source: 'stored';
83
95
  }>;
84
- reset(orgId: string, scopeId: string): Promise<void>;
85
- defaults(): NotificationCategory[];
96
+ reset(scopeId: string, actor: Actor): Promise<void>;
97
+ defaults(actor: Actor): NotificationCategory[];
98
+ }
99
+ interface ParsedBody {
100
+ text: string;
101
+ mentions: string[];
102
+ assetIds: string[];
103
+ }
104
+ interface BodyParser {
105
+ parse(body: string): ParsedBody;
86
106
  }
87
107
  interface PushSender {
88
108
  send(devices: PushDevice[], message: PushMessage): Promise<DeliveryResult>;
@@ -104,5 +124,5 @@ interface Scheduler {
104
124
  cancel(job: string, key: string): Promise<void>;
105
125
  }
106
126
  //#endregion
107
- export { type ChannelRecipient, ChannelRegistry, Clock, CredentialStore, type DeliveryResult, type DomainEvent, type EmailContent, type EmailMessage, type EmailSender, type EmailTemplateId, type EmailTemplateParams, EventBus, type EventDefinition, type EventOf, type EventOfValues, InvalidDomainEventError, type JsonValue, type Logger, type NewDomainEvent, type NotificationCategory, NotificationCategoryService, NotificationChannel, type NotificationTypeDeclaration, NotificationTypeRegistry, type ObjectStorage, OutboxAppender, OutboxMessage, OutboxRelay, OutboxStore, type PresignDownloadInput, type PresignedUpload, type PushDevice, type PushMessage, PushSender, RecurringJob, type RuntimeEventDefinition, ScheduledJob, Scheduler, type StoredNotification, type StoredObjectInfo, type TemplateContext, type TemplateRenderer, UnitOfWork, defineEvent, eventIdSchema, eventJsonValueSchema, eventMetadataSchema };
127
+ export { BodyParser, type ChannelRecipient, ChannelRegistry, Clock, CredentialStore, type DeliveryResult, type DomainEvent, type EmailContent, type EmailMessage, type EmailSender, type EmailTemplateId, type EmailTemplateParams, EventBus, type EventDefinition, type EventOf, type EventOfValues, InvalidDomainEventError, type JsonValue, type Logger, type NewDomainEvent, type NotificationCategory, NotificationCategoryService, NotificationChannel, type NotificationTypeDeclaration, NotificationTypeRegistry, type ObjectStorage, OutboxAppender, OutboxMessage, OutboxRelay, OutboxStore, ParsedBody, type PresignDownloadInput, type PresignedUpload, PubSub, type PushDevice, type PushMessage, PushSender, RecurringJob, type RuntimeEventDefinition, ScheduledJob, Scheduler, type StoredNotification, type StoredObjectInfo, type TemplateContext, type TemplateRenderer, UnitOfWork, defineEvent, eventIdSchema, eventJsonValueSchema, eventMetadataSchema };
108
128
  //# sourceMappingURL=ports.d.ts.map
@@ -1,2 +1,2 @@
1
- import { Activity, ActivityAsset, ActivitySettings, ActivityView, AddDownloadAssetInput, AddSpaceLinkInput, Bundle, BundleItem, Community, CommunitySettings, CommunityStatus, CommunityView, ContentItem, ContentType, Course, CourseSettings, CourseStatus, CourseView, CreateBundleInput, CreateCommunityInput, CreateCourseInput, CreateDownloadInput, CreateSpaceInput, DigestCadence, DigestSchedule, DmSettings, Download, DownloadAsset, DownloadFile, DownloadStatus, DownloadView, ListBundlesQuery, ListCommunitiesQuery, ListCoursesQuery, ListDownloadsQuery, Module, PatchCommunitySettingsInput, PatchDmSettingsInput, ReorderDownloadAssetsInput, SaveActivityInput, SetSpaceTopicsInput, Space, SpaceAccessRule, SpaceDetail, SpaceLink, SpaceSettings, SpaceTopic, UpdateBundleInput, UpdateCommunityInput, UpdateCourseInput, UpdateDownloadInput, UpdateSpaceInput } from "./schemas/content.js";
2
- export type { Activity, ActivityAsset, ActivitySettings, ActivityView, AddDownloadAssetInput, AddSpaceLinkInput, Bundle, BundleItem, Community, CommunitySettings, CommunityStatus, CommunityView, ContentItem, ContentType, Course, CourseSettings, CourseStatus, CourseView, CreateBundleInput, CreateCommunityInput, CreateCourseInput, CreateDownloadInput, CreateSpaceInput, DigestCadence, DigestSchedule, DmSettings, Download, DownloadAsset, DownloadFile, DownloadStatus, DownloadView, ListBundlesQuery, ListCommunitiesQuery, ListCoursesQuery, ListDownloadsQuery, Module, PatchCommunitySettingsInput, PatchDmSettingsInput, ReorderDownloadAssetsInput, SaveActivityInput, SetSpaceTopicsInput, Space, SpaceAccessRule, SpaceDetail, SpaceLink, SpaceSettings, SpaceTopic, UpdateBundleInput, UpdateCommunityInput, UpdateCourseInput, UpdateDownloadInput, UpdateSpaceInput };
1
+ import { Activity, ActivityAsset, ActivitySettings, ActivityView, AddDownloadAssetInput, AddEventAssetInput, AddSpaceLinkInput, Bundle, BundleItem, Community, CommunitySettings, CommunityStatus, CommunityView, ContentItem, ContentType, Course, CourseSettings, CourseStatus, CourseView, CreateBundleInput, CreateCommunityInput, CreateCourseInput, CreateDownloadInput, CreateEventInput, CreateSpaceInput, DigestCadence, DigestSchedule, DmSettings, Download, DownloadAsset, DownloadFile, DownloadStatus, DownloadView, Event, EventAddress, EventAnalytics, EventAsset, EventAttendee, EventAttendeeFace, EventAttendeeSource, EventFile, EventLead, EventLocation, EventOnline, EventRecording, EventSettings, EventSort, EventStatus, EventType, EventVenue, EventView, ListBundlesQuery, ListCommunitiesQuery, ListCoursesQuery, ListDownloadsQuery, ListEventsQuery, MemberEvent, MemberEventSummary, MemberEventViewer, MemberEventsQuery, Module, PatchCommunitySettingsInput, PatchDmSettingsInput, ReorderDownloadAssetsInput, ReorderEventAssetsInput, SaveActivityInput, SetSpaceTopicsInput, Space, SpaceAccessRule, SpaceDetail, SpaceImage, SpaceLink, SpaceSettings, SpaceTopic, SpaceView, UpdateBundleInput, UpdateCommunityInput, UpdateCourseInput, UpdateDownloadInput, UpdateEventInput, UpdateSpaceInput } from "./schemas/content.js";
2
+ export type { Activity, ActivityAsset, ActivitySettings, ActivityView, AddDownloadAssetInput, AddEventAssetInput, AddSpaceLinkInput, Bundle, BundleItem, Community, CommunitySettings, CommunityStatus, CommunityView, ContentItem, ContentType, Course, CourseSettings, CourseStatus, CourseView, CreateBundleInput, CreateCommunityInput, CreateCourseInput, CreateDownloadInput, CreateEventInput, CreateSpaceInput, DigestCadence, DigestSchedule, DmSettings, Download, DownloadAsset, DownloadFile, DownloadStatus, DownloadView, Event, EventAddress, EventAnalytics, EventAsset, EventAttendee, EventAttendeeFace, EventAttendeeSource, EventFile, EventLead, EventLocation, EventOnline, EventRecording, EventSettings, EventSort, EventStatus, EventType, EventVenue, EventView, ListBundlesQuery, ListCommunitiesQuery, ListCoursesQuery, ListDownloadsQuery, ListEventsQuery, MemberEvent, MemberEventSummary, MemberEventViewer, MemberEventsQuery, Module, PatchCommunitySettingsInput, PatchDmSettingsInput, ReorderDownloadAssetsInput, ReorderEventAssetsInput, SaveActivityInput, SetSpaceTopicsInput, Space, SpaceAccessRule, SpaceDetail, SpaceImage, SpaceLink, SpaceSettings, SpaceTopic, SpaceView, UpdateBundleInput, UpdateCommunityInput, UpdateCourseInput, UpdateDownloadInput, UpdateEventInput, UpdateSpaceInput };
@@ -1,7 +1,5 @@
1
1
  import { Page } from "./shared.js";
2
- import { Role } from "./schemas/organizations.js";
3
- import "./organizations.js";
4
- import { ActivityCommentsRule, BlockedUser, Chat, ChatKind, ChatLastMessage, ChatStatus, ChatUser, CommentFlagResolution, CommentListItem, CommentReaction, CommentReportSummary, CommentSettings, CommentStatus, CommentView, CommentsConfig, DigestRun, FlaggedComment, ListCommentsQuery, Mention, MentionItemType, MentionView, Message, MessageAttachment, MessageFile, MessageFlag, MessageFlagResolution, MessageReaction, MessageView, Post, PostBookmark, PostFlag, PostFlagResolution, PostReaction, PostStatus, PostView, ReactionCounts, ReactionEmoji, Subscription, SubscriptionItemType, SubscriptionState, SubscriptionView } from "./schemas/discussion.js";
2
+ import { ActivityCommentsRule, BlockedUser, Chat, ChatKind, ChatLastMessage, ChatLiveEvent, ChatStatus, ChatUnreadSummary, ChatUser, CommentFlagResolution, CommentListItem, CommentReaction, CommentReportSummary, CommentSettings, CommentStatus, CommentView, CommentsConfig, DigestRun, FlaggedComment, FlaggedCommentView, ListCommentsQuery, LiveMessage, Mention, MentionItemType, MentionView, Message, MessageAttachment, MessageFile, MessageFlag, MessageFlagResolution, MessageReaction, MessageView, Post, PostBookmark, PostFlag, PostFlagResolution, PostReaction, PostStatus, PostView, ReactionCounts, ReactionEmoji, Subscription, SubscriptionItemType, SubscriptionState, SubscriptionView } from "./schemas/discussion.js";
5
3
  //#region src/types/discussion.d.ts
6
4
  interface Comment {
7
5
  readonly id: string;
@@ -26,7 +24,8 @@ interface CommentAuthor {
26
24
  image: string | null;
27
25
  imageAssetId: string | null;
28
26
  imageUrl: string | null;
29
- role: Role;
27
+ team: boolean;
28
+ roleName: string | null;
30
29
  }
31
30
  interface CommentReport {
32
31
  readonly id: string;
@@ -41,5 +40,5 @@ interface CommentReport {
41
40
  updatedAt: Date;
42
41
  }
43
42
  //#endregion
44
- export { type ActivityCommentsRule, type BlockedUser, type Chat, type ChatKind, type ChatLastMessage, type ChatStatus, type ChatUser, Comment, CommentAuthor, type CommentFlagResolution, type CommentListItem, type CommentReaction, CommentReport, type CommentReportSummary, type CommentSettings, type CommentStatus, type CommentView, type CommentsConfig, type DigestRun, type FlaggedComment, type ListCommentsQuery, type Mention, type MentionItemType, type MentionView, type Message, type MessageAttachment, type MessageFile, type MessageFlag, type MessageFlagResolution, type MessageReaction, type MessageView, type Page, type Post, type PostBookmark, type PostFlag, type PostFlagResolution, type PostReaction, type PostStatus, type PostView, type ReactionCounts, type ReactionEmoji, type Subscription, type SubscriptionItemType, type SubscriptionState, type SubscriptionView };
43
+ export { type ActivityCommentsRule, type BlockedUser, type Chat, type ChatKind, type ChatLastMessage, type ChatLiveEvent, type ChatStatus, type ChatUnreadSummary, type ChatUser, Comment, CommentAuthor, type CommentFlagResolution, type CommentListItem, type CommentReaction, CommentReport, type CommentReportSummary, type CommentSettings, type CommentStatus, type CommentView, type CommentsConfig, type DigestRun, type FlaggedComment, type FlaggedCommentView, type ListCommentsQuery, type LiveMessage, type Mention, type MentionItemType, type MentionView, type Message, type MessageAttachment, type MessageFile, type MessageFlag, type MessageFlagResolution, type MessageReaction, type MessageView, type Page, type Post, type PostBookmark, type PostFlag, type PostFlagResolution, type PostReaction, type PostStatus, type PostView, type ReactionCounts, type ReactionEmoji, type Subscription, type SubscriptionItemType, type SubscriptionState, type SubscriptionView };
45
44
  //# sourceMappingURL=discussion.d.ts.map
@@ -15,6 +15,13 @@ interface EmailContent {
15
15
  html: string;
16
16
  text: string;
17
17
  }
18
+ interface EventEmailParams {
19
+ eventId: string;
20
+ eventTitle: string;
21
+ startsAt: string;
22
+ endsAt: string;
23
+ timeZone: string;
24
+ }
18
25
  /** Template id → params. Adding an email = adding a row here. */
19
26
  interface EmailTemplateParams {
20
27
  magicLink: {
@@ -138,8 +145,11 @@ interface EmailTemplateParams {
138
145
  chatId: string;
139
146
  communityId: string;
140
147
  };
141
- youAreNowAModerator: {
142
- communityTitles: string[];
148
+ roleAssigned: {
149
+ roleName: string;
150
+ place: string;
151
+ contentId: string | null;
152
+ contentType: ContentType | null;
143
153
  };
144
154
  digest: {
145
155
  communityTitle: string;
@@ -262,6 +272,15 @@ interface EmailTemplateParams {
262
272
  courseId: string;
263
273
  activityId: string;
264
274
  };
275
+ eventGranted: EventEmailParams;
276
+ eventStartingSoon: EventEmailParams & {
277
+ leadText: string;
278
+ };
279
+ eventChanged: EventEmailParams & {
280
+ changed: 'time' | 'location' | 'time_and_location';
281
+ };
282
+ eventCanceled: EventEmailParams;
283
+ eventRevoked: EventEmailParams;
265
284
  }
266
285
  type EmailTemplateId = keyof EmailTemplateParams;
267
286
  /** Resolves a template + data to rendered content. Deployment-swappable;
@@ -270,5 +289,5 @@ interface TemplateRenderer {
270
289
  render<K extends EmailTemplateId>(id: K, ctx: TemplateContext, params: EmailTemplateParams[K]): Promise<EmailContent>;
271
290
  }
272
291
  //#endregion
273
- export { EmailContent, EmailTemplateId, EmailTemplateParams, TemplateContext, TemplateRenderer };
292
+ export { EmailContent, EmailTemplateId, EmailTemplateParams, EventEmailParams, TemplateContext, TemplateRenderer };
274
293
  //# sourceMappingURL=email-templates.d.ts.map
@@ -1,3 +1,3 @@
1
1
  import { Page } from "./shared.js";
2
- import { Entitlement, EntitlementStatus, EntitlementsQuery, GrantEntitlementInput, SpaceMember, SpaceMemberSource, SpaceMemberStatus } from "./schemas/entitlements.js";
3
- export type { Entitlement, EntitlementStatus, EntitlementsQuery, GrantEntitlementInput, Page, SpaceMember, SpaceMemberSource, SpaceMemberStatus };
2
+ import { Entitlement, EntitlementStatus, EntitlementsQuery, GrantEntitlementInput, GrantSource, SpaceMember, SpaceMemberSource, SpaceMemberStatus } from "./schemas/entitlements.js";
3
+ export type { Entitlement, EntitlementStatus, EntitlementsQuery, GrantEntitlementInput, GrantSource, Page, SpaceMember, SpaceMemberSource, SpaceMemberStatus };
@@ -33,11 +33,16 @@ interface AccountProvisioner {
33
33
  }
34
34
  type UserId = string;
35
35
  type HeaderBag = Record<string, string | string[] | undefined>;
36
+ type CredentialLimit = {
37
+ scopes: string[];
38
+ } | {
39
+ roleKey: string;
40
+ };
36
41
  type AccessGrant = {
37
42
  userId: string;
38
43
  orgId: string;
39
- scopes: string[];
40
44
  clientId: string;
45
+ limit: CredentialLimit;
41
46
  };
42
47
  type AccessRequest = {
43
48
  method: string;
@@ -46,6 +51,7 @@ type AccessRequest = {
46
51
  };
47
52
  interface AccessTokenVerifier {
48
53
  verifyAccess(request: AccessRequest): Promise<AccessGrant | null>;
54
+ verifyApiKey(headers: HeaderBag): Promise<AccessGrant | null>;
49
55
  }
50
56
  type ConnectedApp = {
51
57
  clientId: string;
@@ -58,26 +64,17 @@ type ApiKeySummary = {
58
64
  id: string;
59
65
  name: string | null;
60
66
  start: string | null;
61
- scopes: string[];
67
+ role: {
68
+ key: string;
69
+ name: string | null;
70
+ } | null;
62
71
  createdAt: Date;
63
72
  lastUsedAt: Date | null;
73
+ expiresAt: Date | null;
64
74
  };
65
75
  type CreatedApiKey = ApiKeySummary & {
66
76
  key: string;
67
77
  };
68
- type NewApiKey = {
69
- authUserId: string;
70
- orgId: string;
71
- name: string;
72
- scopes: string[];
73
- };
74
- interface AppAccessAdmin {
75
- listConnectedApps(headers: HeaderBag, orgId: string): Promise<ConnectedApp[]>;
76
- revokeConnectedApp(headers: HeaderBag, orgId: string, clientId: string): Promise<void>;
77
- listApiKeys(headers: HeaderBag, orgId: string): Promise<ApiKeySummary[]>;
78
- createApiKey(input: NewApiKey): Promise<CreatedApiKey>;
79
- deleteApiKey(headers: HeaderBag, orgId: string, keyId: string): Promise<void>;
80
- }
81
78
  //#endregion
82
- export { AccessGrant, AccessRequest, AccessTokenVerifier, AccountProvisioner, ActiveSession, ApiKeySummary, AppAccessAdmin, ConnectedApp, type CreateUserInput, CreatedApiKey, HeaderBag, NewApiKey, type ProvisionUserInput, SessionVerifier, type UpdateUserInput, User, UserId, type UserProfile, type UserProfileView };
79
+ export { AccessGrant, AccessRequest, AccessTokenVerifier, AccountProvisioner, ActiveSession, ApiKeySummary, ConnectedApp, type CreateUserInput, CreatedApiKey, CredentialLimit, HeaderBag, type ProvisionUserInput, SessionVerifier, type UpdateUserInput, User, UserId, type UserProfile, type UserProfileView };
83
80
  //# sourceMappingURL=identity.d.ts.map