@openpeepshq/core 0.1.33 → 0.1.35

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 (297) hide show
  1. package/dist/accessTokens/finders.js +5 -6
  2. package/dist/accessTokens/mutations.js +1 -1
  3. package/dist/accessTokens/tokens.js +8 -11
  4. package/dist/accounts/helpers.js +6 -2
  5. package/dist/accounts/mutations.js +36 -33
  6. package/dist/analytics/cache.js +3 -3
  7. package/dist/analytics/clicks.js +14 -22
  8. package/dist/analytics/compile.js +17 -12
  9. package/dist/analytics/dateRange.js +3 -5
  10. package/dist/analytics/jobs.js +3 -4
  11. package/dist/analytics/pdfReport.js +45 -61
  12. package/dist/analytics/privacy.js +1 -1
  13. package/dist/analytics/read.js +164 -140
  14. package/dist/analytics/report.d.ts +22 -1
  15. package/dist/analytics/report.js +2 -3
  16. package/dist/analytics/settings.js +3 -4
  17. package/dist/backups/index.js +82 -25
  18. package/dist/backups/metadata.d.ts +2 -3
  19. package/dist/backups/metadata.js +6 -2
  20. package/dist/config/db.js +2 -4
  21. package/dist/config/defaults/capabilities.js +13 -2
  22. package/dist/config/defaults/community.js +8 -3
  23. package/dist/config/defaults/core.d.ts +1 -1
  24. package/dist/config/defaults/core.js +16 -8
  25. package/dist/config/index.d.ts +22 -0
  26. package/dist/config/index.js +15 -11
  27. package/dist/db/explorer/query.js +9 -8
  28. package/dist/db/explorer/sql.js +8 -8
  29. package/dist/db/helpers.d.ts +1 -0
  30. package/dist/db/helpers.js +25 -7
  31. package/dist/db/index.d.ts +1 -1
  32. package/dist/db/index.js +1 -0
  33. package/dist/db/init.js +2 -3
  34. package/dist/db/migration/importCollections.d.ts +14 -9
  35. package/dist/db/migration/importCollections.js +121 -174
  36. package/dist/db/migration/shared.d.ts +2 -33
  37. package/dist/db/migration/shared.js +17 -87
  38. package/dist/db/pg/client.js +4 -7
  39. package/dist/db/pg/collections.d.ts +2 -2
  40. package/dist/db/pg/collections.js +2 -2
  41. package/dist/db/pg/filters/index.js +1 -1
  42. package/dist/db/pg/filters/posts.d.ts +12 -0
  43. package/dist/db/pg/filters/posts.js +30 -4
  44. package/dist/db/pg/filters/profiles.d.ts +1 -0
  45. package/dist/db/pg/filters/profiles.js +2 -1
  46. package/dist/db/pg/helpers.js +2 -14
  47. package/dist/db/pg/map/filters.js +40 -10
  48. package/dist/db/pg/map/helpers.js +5 -1
  49. package/dist/db/pg/map/index.js +46 -51
  50. package/dist/db/pg/map/mutations.js +65 -25
  51. package/dist/db/pg/map/registry.d.ts +5 -0
  52. package/dist/db/pg/map/registry.js +133 -56
  53. package/dist/db/pg/map/relations.js +76 -68
  54. package/dist/db/pg/map/search.js +15 -37
  55. package/dist/db/pg/mappers.js +13 -7
  56. package/dist/db/pg/migrate.d.ts +1 -2
  57. package/dist/db/pg/migrate.js +8 -9
  58. package/dist/db/pg/queries/activity.js +5 -5
  59. package/dist/db/pg/queries/derived.js +8 -12
  60. package/dist/db/pg/queries/sorts.d.ts +1 -0
  61. package/dist/db/pg/queries/sorts.js +4 -0
  62. package/dist/db/pg/schema/documents.d.ts +279 -41
  63. package/dist/db/pg/schema/documents.js +136 -22
  64. package/dist/db/pg/schema/edges.d.ts +116 -7
  65. package/dist/db/pg/schema/edges.js +9 -2
  66. package/dist/db/pg/schema/index.d.ts +362 -15
  67. package/dist/db/pg/schema/index.js +5 -1
  68. package/dist/db/pg/sql/0010_user_group_membership_roles.sql +16 -0
  69. package/dist/db/pg/sql/0011_drop_data_migrations.sql +1 -0
  70. package/dist/db/pg/sql/0012_posts_last_activity_at.sql +5 -0
  71. package/dist/db/pg/sql/0013_add_blocks_edge.sql +12 -0
  72. package/dist/db/pg/sql/0014_federation_datamodel.sql +59 -0
  73. package/dist/db/pg/sql/0015_profile_hashtags.sql +12 -0
  74. package/dist/db/pg/sql/0016_posts_search_vector_title_tags_path.sql +54 -0
  75. package/dist/db/pg/sql/meta/{0009_snapshot.json → 0015_snapshot.json} +291 -36
  76. package/dist/db/pg/sql/meta/_journal.json +49 -0
  77. package/dist/db/replaceOrigin.js +1 -1
  78. package/dist/email/queueStats.js +8 -11
  79. package/dist/email/render.js +14 -3
  80. package/dist/email/send.js +19 -17
  81. package/dist/email/smtpTest.js +10 -6
  82. package/dist/errors/index.js +1 -1
  83. package/dist/events/index.d.ts +4 -0
  84. package/dist/events/index.js +1 -0
  85. package/dist/events/once.js +2 -4
  86. package/dist/federation/activities.d.ts +17 -0
  87. package/dist/federation/activities.js +25 -0
  88. package/dist/federation/identity.d.ts +16 -0
  89. package/dist/federation/identity.js +52 -0
  90. package/dist/federation/index.d.ts +4 -0
  91. package/dist/federation/index.js +3 -0
  92. package/dist/federation/profiles.d.ts +3 -0
  93. package/dist/federation/profiles.js +14 -0
  94. package/dist/groups/finders.d.ts +2 -1
  95. package/dist/groups/helpers.d.ts +18 -0
  96. package/dist/groups/helpers.js +1 -2
  97. package/dist/groups/mapping.d.ts +4 -2
  98. package/dist/groups/mutations.js +1 -1
  99. package/dist/hashtags/finders.d.ts +6 -3
  100. package/dist/hashtags/finders.js +2 -0
  101. package/dist/hashtags/helpers.d.ts +8 -0
  102. package/dist/hashtags/helpers.js +4 -0
  103. package/dist/hashtags/index.d.ts +2 -0
  104. package/dist/hashtags/index.js +2 -0
  105. package/dist/hashtags/mutations.d.ts +3 -0
  106. package/dist/hashtags/mutations.js +13 -1
  107. package/dist/i18n/index.d.ts +1 -1
  108. package/dist/i18n/index.js +3 -1
  109. package/dist/i18n/pluginLocales.d.ts +6 -0
  110. package/dist/i18n/pluginLocales.js +15 -0
  111. package/dist/inviteLinks/mutations.js +2 -3
  112. package/dist/jams/export.d.ts +19 -0
  113. package/dist/jams/export.js +58 -0
  114. package/dist/jams/finders.js +4 -1
  115. package/dist/jams/health.d.ts +10 -0
  116. package/dist/jams/health.js +50 -0
  117. package/dist/jams/helpers.d.ts +2 -2
  118. package/dist/jams/helpers.js +6 -2
  119. package/dist/jams/index.d.ts +2 -0
  120. package/dist/jams/index.js +25 -18
  121. package/dist/jams/jobs.js +2 -3
  122. package/dist/jams/livekit.d.ts +49 -4
  123. package/dist/jams/livekit.js +62 -45
  124. package/dist/jams/mapping.d.ts +3 -3
  125. package/dist/jams/mutations.d.ts +1 -1
  126. package/dist/jams/recording.d.ts +10 -0
  127. package/dist/jams/recording.js +33 -1
  128. package/dist/jams/token.d.ts +13 -1
  129. package/dist/jams/token.js +25 -18
  130. package/dist/jams/waitingRoom.js +1 -1
  131. package/dist/jobs/index.d.ts +1 -0
  132. package/dist/jobs/index.js +9 -3
  133. package/dist/jobs/jobDetail.js +6 -12
  134. package/dist/jobs/jobLog.js +2 -3
  135. package/dist/lib/streams.js +4 -39
  136. package/dist/lib/zodDeepPartial.d.ts +1 -1
  137. package/dist/lib/zodDeepPartial.js +1 -1
  138. package/dist/log/index.js +13 -29
  139. package/dist/media/index.d.ts +1 -1
  140. package/dist/media/index.js +73 -12
  141. package/dist/media/jobs.js +1 -2
  142. package/dist/media/openpeeps/index.js +11 -46
  143. package/dist/media/processing.js +25 -11
  144. package/dist/media/streaming.js +5 -5
  145. package/dist/media/streamingCleanupJobs.js +1 -2
  146. package/dist/media/streamingJobs.js +3 -4
  147. package/dist/media/streamingPrewarm.js +7 -11
  148. package/dist/mediaAttachments/index.js +6 -2
  149. package/dist/notifications/defaultNotifications/announcement/index.js +15 -18
  150. package/dist/notifications/defaultNotifications/directMessage/index.js +9 -8
  151. package/dist/notifications/defaultNotifications/follow/index.js +15 -18
  152. package/dist/notifications/defaultNotifications/groupAdded/index.js +14 -17
  153. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +15 -18
  154. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +15 -18
  155. package/dist/notifications/defaultNotifications/index.js +4 -0
  156. package/dist/notifications/defaultNotifications/jamModerator/index.js +3 -5
  157. package/dist/notifications/defaultNotifications/jamSpeaker/index.js +14 -18
  158. package/dist/notifications/defaultNotifications/jamStarted/index.js +18 -22
  159. package/dist/notifications/defaultNotifications/mention/index.js +20 -24
  160. package/dist/notifications/defaultNotifications/newGroupPost/index.js +11 -6
  161. package/dist/notifications/defaultNotifications/newProfile/index.js +14 -17
  162. package/dist/notifications/defaultNotifications/pollEnded/index.d.ts +19 -0
  163. package/dist/notifications/defaultNotifications/pollEnded/index.js +39 -0
  164. package/dist/notifications/defaultNotifications/pollEnded/recipients.d.ts +3 -0
  165. package/dist/notifications/defaultNotifications/pollEnded/recipients.js +17 -0
  166. package/dist/notifications/defaultNotifications/pollVote/index.js +14 -17
  167. package/dist/notifications/defaultNotifications/reaction/index.js +18 -21
  168. package/dist/notifications/defaultNotifications/reply/index.js +21 -22
  169. package/dist/notifications/defaultNotifications/repost/index.js +16 -20
  170. package/dist/notifications/defaultNotifications/rsvp/index.d.ts +6 -1
  171. package/dist/notifications/defaultNotifications/rsvp/index.js +31 -18
  172. package/dist/notifications/defaultNotifications/rsvpCanceled/index.d.ts +24 -0
  173. package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +82 -0
  174. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.d.ts +4 -0
  175. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.js +11 -0
  176. package/dist/notifications/fcmCredential.js +1 -1
  177. package/dist/notifications/finders.js +1 -1
  178. package/dist/notifications/helpers.js +13 -10
  179. package/dist/notifications/jobs.js +10 -5
  180. package/dist/notifications/mutations.js +8 -1
  181. package/dist/notifications/push.js +11 -16
  182. package/dist/performance/index.js +3 -3
  183. package/dist/plugins/helpers.js +3 -6
  184. package/dist/plugins/index.js +39 -4
  185. package/dist/plugins/install.d.ts +28 -9
  186. package/dist/plugins/install.js +302 -56
  187. package/dist/plugins/pluginAuth.d.ts +1 -1
  188. package/dist/plugins/pluginAuth.js +13 -10
  189. package/dist/plugins/state.js +2 -3
  190. package/dist/posts/activity.d.ts +9 -0
  191. package/dist/posts/activity.js +34 -0
  192. package/dist/posts/contextClosure.d.ts +1 -9
  193. package/dist/posts/contextClosure.js +14 -44
  194. package/dist/posts/conversationQueries.d.ts +7 -0
  195. package/dist/posts/conversationQueries.js +76 -4
  196. package/dist/posts/eventAgenda.d.ts +1 -0
  197. package/dist/posts/eventAgenda.js +17 -8
  198. package/dist/posts/eventOccurrenceJobs.js +7 -2
  199. package/dist/posts/eventOccurrences.d.ts +6 -0
  200. package/dist/posts/eventOccurrences.js +22 -1
  201. package/dist/posts/finders.d.ts +56 -9
  202. package/dist/posts/finders.js +84 -23
  203. package/dist/posts/helpers/filters.js +13 -9
  204. package/dist/posts/helpers/index.d.ts +179 -14
  205. package/dist/posts/helpers/index.js +70 -34
  206. package/dist/posts/index.d.ts +5 -2
  207. package/dist/posts/index.js +5 -2
  208. package/dist/posts/mapping.d.ts +765 -30
  209. package/dist/posts/mapping.js +74 -31
  210. package/dist/posts/mutations.d.ts +516 -3
  211. package/dist/posts/mutations.js +179 -41
  212. package/dist/posts/pollEnd.d.ts +3 -0
  213. package/dist/posts/pollEnd.js +4 -0
  214. package/dist/posts/pollEndJobs.d.ts +8 -0
  215. package/dist/posts/pollEndJobs.js +49 -0
  216. package/dist/posts/replyClosure.d.ts +10 -0
  217. package/dist/posts/replyClosure.js +43 -0
  218. package/dist/posts/rsvpConfirmationEmail.js +23 -15
  219. package/dist/posts/threadPreview.d.ts +8 -0
  220. package/dist/posts/threadPreview.js +44 -0
  221. package/dist/posts/unseenCounts.js +4 -1
  222. package/dist/processingStats/queries.js +6 -7
  223. package/dist/profileSettings/cache.js +21 -5
  224. package/dist/profileSettings/mapping.d.ts +2 -0
  225. package/dist/profiles/activityQueries.d.ts +5 -0
  226. package/dist/profiles/activityQueries.js +85 -0
  227. package/dist/profiles/activitySummary.d.ts +3 -0
  228. package/dist/profiles/activitySummary.js +82 -0
  229. package/dist/profiles/blocks.d.ts +12 -0
  230. package/dist/profiles/blocks.js +73 -0
  231. package/dist/profiles/cache.d.ts +1 -0
  232. package/dist/profiles/cache.js +30 -10
  233. package/dist/profiles/export.js +30 -39
  234. package/dist/profiles/finders.d.ts +2 -1
  235. package/dist/profiles/finders.js +15 -8
  236. package/dist/profiles/helpers.d.ts +2 -0
  237. package/dist/profiles/index.d.ts +2 -0
  238. package/dist/profiles/index.js +2 -0
  239. package/dist/profiles/mapping.d.ts +10 -5
  240. package/dist/profiles/mapping.js +13 -1
  241. package/dist/profiles/mutations.d.ts +8 -4
  242. package/dist/profiles/mutations.js +31 -4
  243. package/dist/redis/connection.d.ts +2 -0
  244. package/dist/redis/connection.js +25 -6
  245. package/dist/reports/helpers.js +7 -3
  246. package/dist/roles/index.d.ts +1 -1
  247. package/dist/roles/index.js +1 -1
  248. package/dist/roles/mapping.d.ts +1 -0
  249. package/dist/roles/mutations.js +85 -3
  250. package/dist/search/finders.js +15 -3
  251. package/dist/search/helpers.js +1 -1
  252. package/dist/search/mapping.d.ts +1 -1
  253. package/dist/search/mapping.js +6 -2
  254. package/dist/sentry/index.js +9 -11
  255. package/dist/seo/index.d.ts +50 -0
  256. package/dist/seo/index.js +145 -0
  257. package/dist/seo/route.d.ts +18 -0
  258. package/dist/seo/route.js +19 -0
  259. package/dist/server/index.d.ts +19 -0
  260. package/dist/server/index.js +31 -14
  261. package/dist/server/stablePublicServerInfo.d.ts +17 -0
  262. package/dist/server/stablePublicServerInfo.js +37 -0
  263. package/dist/server/status.d.ts +25 -0
  264. package/dist/server/status.js +97 -0
  265. package/dist/session/index.js +2 -2
  266. package/dist/stats/finders.d.ts +1 -17681
  267. package/dist/stats/finders.js +22 -9
  268. package/dist/stats/helpers.js +4 -1
  269. package/dist/stats/mapping.d.ts +39 -2
  270. package/dist/stats/mapping.js +8 -4
  271. package/dist/stripe/cache.js +5 -6
  272. package/dist/stripe/connection.js +3 -4
  273. package/dist/stripe/helpers.js +15 -20
  274. package/package.json +5 -7
  275. package/dist/db/migration/detect.d.ts +0 -3
  276. package/dist/db/migration/detect.js +0 -33
  277. package/dist/db/migration/importPostgres.d.ts +0 -3
  278. package/dist/db/migration/importPostgres.js +0 -18
  279. package/dist/db/migration/transform.d.ts +0 -20
  280. package/dist/db/migration/transform.js +0 -232
  281. package/dist/db/migration/validate.d.ts +0 -18
  282. package/dist/db/migration/validate.js +0 -69
  283. package/dist/db/pg/sql/meta/0000_snapshot.json +0 -3380
  284. package/dist/db/pg/sql/meta/0004_snapshot.json +0 -4114
  285. package/dist/db/pg/sql/meta/0005_snapshot.json +0 -4179
  286. package/dist/db/pg/sql/meta/0006_snapshot.json +0 -4200
  287. package/dist/db/pg/sql/meta/0007_snapshot.json +0 -4179
  288. package/dist/mastodon/index.d.ts +0 -4
  289. package/dist/mastodon/index.js +0 -51
  290. package/dist/mastodon/types.d.ts +0 -7579
  291. package/dist/mastodon/types.js +0 -523
  292. package/dist/mastodon/typescript.d.ts +0 -1578
  293. package/dist/mastodon/typescript.js +0 -1
  294. package/dist/migration/index.d.ts +0 -4
  295. package/dist/migration/index.js +0 -4
  296. package/dist/roles/defaults.d.ts +0 -2
  297. package/dist/roles/defaults.js +0 -95
@@ -4,5 +4,15 @@ import type { JamRecording, JamRecordingWithMeta, MediaAttachment, PostWithMeta
4
4
  * notifies listeners (e.g. streaming pre-warm) via `jamRecordingCompleted`.
5
5
  */
6
6
  export declare const completeJamRecording: (recordingId: string, attachment: MediaAttachment) => Promise<JamRecordingWithMeta | undefined>;
7
+ /**
8
+ * Marks a stopped recording as still accepting its multipart complete. Used
9
+ * after egress stop so a later start does not fail the in-flight upload.
10
+ */
11
+ export declare const finalizeJamRecording: (recordingId: string) => Promise<void>;
12
+ /**
13
+ * Marks an in-progress or finalizing recording failed. Completed recordings
14
+ * are left unchanged. Multipart temp files are the S3 layer's responsibility.
15
+ */
16
+ export declare const failJamRecording: (recordingId: string) => Promise<void>;
7
17
  export declare const publishJamRecordingReply: (eventPost: PostWithMeta, recordingId: string) => Promise<JamRecording>;
8
18
  export declare const deleteJamRecording: (eventPost: PostWithMeta, recordingId: string) => Promise<void>;
@@ -1,8 +1,10 @@
1
1
  import { jamRecordingSchema } from '@openpeepshq/common/types';
2
+ import { jamRecordingAcceptsUpload } from '@openpeepshq/common/lib';
2
3
  import { hub } from '../events/index.js';
3
4
  import { createPost } from '../posts/index.js';
4
5
  import { allpeepDb } from '../db/index.js';
5
6
  import { findJamRecording } from './finders.js';
7
+ import { cancelRecordingAutoStop } from './jobs.js';
6
8
  import { jamRecordingsMapping } from './mapping.js';
7
9
  import { updateJamRecording } from './mutations.js';
8
10
  /**
@@ -20,6 +22,36 @@ export const completeJamRecording = async (recordingId, attachment) => {
20
22
  }
21
23
  return recording;
22
24
  };
25
+ /**
26
+ * Marks a stopped recording as still accepting its multipart complete. Used
27
+ * after egress stop so a later start does not fail the in-flight upload.
28
+ */
29
+ export const finalizeJamRecording = async (recordingId) => {
30
+ const recording = await findJamRecording(recordingId);
31
+ if (!recording) {
32
+ return;
33
+ }
34
+ if (recording.status !== 'requested' && recording.status !== 'active') {
35
+ return;
36
+ }
37
+ await cancelRecordingAutoStop(recordingId);
38
+ await updateJamRecording(recordingId, { status: 'finalizing' });
39
+ };
40
+ /**
41
+ * Marks an in-progress or finalizing recording failed. Completed recordings
42
+ * are left unchanged. Multipart temp files are the S3 layer's responsibility.
43
+ */
44
+ export const failJamRecording = async (recordingId) => {
45
+ const recording = await findJamRecording(recordingId);
46
+ if (!recording) {
47
+ return;
48
+ }
49
+ if (!jamRecordingAcceptsUpload(recording.status)) {
50
+ return;
51
+ }
52
+ await cancelRecordingAutoStop(recordingId);
53
+ await updateJamRecording(recordingId, { status: 'failed' });
54
+ };
23
55
  export const publishJamRecordingReply = async (eventPost, recordingId) => {
24
56
  const recording = await findJamRecording(recordingId);
25
57
  if (!recording) {
@@ -49,7 +81,7 @@ export const publishJamRecordingReply = async (eventPost, recordingId) => {
49
81
  audience: eventPost.audience,
50
82
  });
51
83
  await updateJamRecording(recordingId, { replyPostId: reply.id });
52
- return jamRecordingSchema.parse(Object.assign(Object.assign({}, recording), { replyPostId: reply.id }));
84
+ return jamRecordingSchema.parse({ ...recording, replyPostId: reply.id });
53
85
  };
54
86
  export const deleteJamRecording = async (eventPost, recordingId) => {
55
87
  const recording = await findJamRecording(recordingId);
@@ -1,4 +1,16 @@
1
1
  import { PostWithMeta, PublicProfile } from '@openpeepshq/common/types';
2
2
  export declare const assertJamRsvpAllowed: (event: PostWithMeta, profile: PublicProfile, recurrenceId?: string) => void;
3
3
  export declare const createJamEgressToken: (event: PostWithMeta, recurrenceId?: string) => Promise<string>;
4
- export declare const createJamToken: (event: PostWithMeta, profile: PublicProfile, external?: boolean, recurrenceId?: string) => Promise<string>;
4
+ export type CreateJamTokenOptions = {
5
+ /** Participant is joining from another instance. */
6
+ external?: boolean;
7
+ recurrenceId?: string;
8
+ /**
9
+ * Automatic re-join after a dropped connection, as opposed to a participant
10
+ * deliberately joining. A reconnect must never open the room: a moderator
11
+ * whose client re-tokens into an ended jam would put it back on the live
12
+ * list and notify the community all over again.
13
+ */
14
+ reconnect?: boolean;
15
+ };
16
+ export declare const createJamToken: (event: PostWithMeta, profile: PublicProfile, { external, recurrenceId, reconnect, }?: CreateJamTokenOptions) => Promise<string>;
@@ -1,5 +1,5 @@
1
1
  import { publicProfileSchema, } from '@openpeepshq/common/types';
2
- import { canModerateJam, countYesRsvps, getEffectiveRsvp, jamRoomName, } from '@openpeepshq/common/lib';
2
+ import { canModerateJam, countYesRsvps, getEffectiveRsvp, isBlockedPair, jamRoomName, } from '@openpeepshq/common/lib';
3
3
  import { authNeeded, forbidden, notFound } from '../errors/index.js';
4
4
  import { config } from '../config/index.js';
5
5
  import { AccessToken, TrackSource } from 'livekit-server-sdk';
@@ -8,27 +8,26 @@ import { JAM_ROOM_DEPARTURE_TIMEOUT_SEC, JAM_ROOM_EMPTY_TIMEOUT_SEC, roomService
8
8
  import { localInstanceDomain } from './helpers.js';
9
9
  import { createJamEvent } from './mutations.js';
10
10
  import { uuidv7 } from 'uuidv7';
11
+ import { findProfile } from '../profiles/index.js';
11
12
  const calculateSources = (jam, profile) => {
12
- var _a;
13
13
  const sources = [TrackSource.MICROPHONE];
14
14
  if (jam.videoEnabled) {
15
15
  sources.push(TrackSource.CAMERA, TrackSource.SCREEN_SHARE, TrackSource.SCREEN_SHARE_AUDIO);
16
16
  }
17
- if ((_a = jam.presenters) === null || _a === void 0 ? void 0 : _a.includes(profile.id)) {
17
+ if (jam.presenters?.includes(profile.id)) {
18
18
  sources.push(TrackSource.SCREEN_SHARE, TrackSource.SCREEN_SHARE_AUDIO);
19
19
  }
20
20
  return sources;
21
21
  };
22
22
  export const assertJamRsvpAllowed = (event, profile, recurrenceId) => {
23
- var _a, _b;
24
- const eventData = ((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) === 'event' ? event.data : undefined;
25
- if (!(eventData === null || eventData === void 0 ? void 0 : eventData.maxAttendees)) {
23
+ const eventData = event.data?.type === 'event' ? event.data : undefined;
24
+ if (!eventData?.maxAttendees) {
26
25
  return;
27
26
  }
28
27
  if (canModerateJam(profile, event)) {
29
28
  return;
30
29
  }
31
- if (((_b = getEffectiveRsvp(event, profile.id, recurrenceId)) === null || _b === void 0 ? void 0 : _b.response) === 'yes') {
30
+ if (getEffectiveRsvp(event, profile.id, recurrenceId)?.response === 'yes') {
32
31
  return;
33
32
  }
34
33
  if (countYesRsvps(event, recurrenceId) >= eventData.maxAttendees) {
@@ -37,10 +36,9 @@ export const assertJamRsvpAllowed = (event, profile, recurrenceId) => {
37
36
  throw forbidden({ errorKey: 'error.jamRsvpRequired' });
38
37
  };
39
38
  export const createJamEgressToken = async (event, recurrenceId) => {
40
- var _a, _b;
41
39
  const jamId = event.id;
42
40
  const roomName = jamRoomName(event.id, recurrenceId);
43
- const jam = ((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) === 'event' && ((_b = event.data) === null || _b === void 0 ? void 0 : _b.jam);
41
+ const jam = event.data?.type === 'event' && event.data?.jam;
44
42
  if (!jam) {
45
43
  throw notFound({ errorKey: 'error.jamNotFound', parameters: { jamId } });
46
44
  }
@@ -60,24 +58,33 @@ export const createJamEgressToken = async (event, recurrenceId) => {
60
58
  });
61
59
  return accessToken.toJwt();
62
60
  };
63
- export const createJamToken = async (event, profile, external = false, recurrenceId) => {
64
- var _a, _b, _c;
61
+ export const createJamToken = async (event, profile, { external = false, recurrenceId, reconnect = false, } = {}) => {
65
62
  if (!profile.id)
66
63
  throw authNeeded({ errorKey: 'error.profileRequired' });
67
64
  const jamId = event.id;
68
65
  const roomName = jamRoomName(event.id, recurrenceId);
69
- const jam = ((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) === 'event' && ((_b = event.data) === null || _b === void 0 ? void 0 : _b.jam);
66
+ const jam = event.data?.type === 'event' && event.data?.jam;
70
67
  if (!jam) {
71
68
  throw notFound({ errorKey: 'error.jamNotFound', parameters: { jamId } });
72
69
  }
70
+ const joiner = await findProfile(profile.id);
71
+ if (joiner && isBlockedPair(joiner, event.profile?.id)) {
72
+ throw notFound({ errorKey: 'error.jamNotFound', parameters: { jamId } });
73
+ }
73
74
  assertJamRsvpAllowed(event, profile, recurrenceId);
74
75
  const rs = await roomService();
75
76
  if (rs === undefined) {
76
77
  throw forbidden({ errorKey: 'error.jamsUnavailable' });
77
78
  }
78
- const rooms = await rs.listRooms([roomName]);
79
+ let rooms;
80
+ try {
81
+ rooms = await rs.listRooms([roomName]);
82
+ }
83
+ catch {
84
+ throw forbidden({ errorKey: 'error.jamsUnavailable' });
85
+ }
79
86
  const jamOpen = rooms.length === 1;
80
- if (!jamOpen && !(jam === null || jam === void 0 ? void 0 : jam.moderators.includes(profile.id))) {
87
+ if (!jamOpen && (reconnect || !jam?.moderators.includes(profile.id))) {
81
88
  throw forbidden({ errorKey: 'error.jamNotOpen' });
82
89
  }
83
90
  if (!jamOpen) {
@@ -92,7 +99,7 @@ export const createJamToken = async (event, profile, external = false, recurrenc
92
99
  departureTimeout: JAM_ROOM_DEPARTURE_TIMEOUT_SEC,
93
100
  });
94
101
  }
95
- catch (_d) {
102
+ catch {
96
103
  // Concurrent open may have created the room already.
97
104
  }
98
105
  }
@@ -117,9 +124,9 @@ export const createJamToken = async (event, profile, external = false, recurrenc
117
124
  accessToken.addGrant({
118
125
  room: roomName,
119
126
  roomJoin: true,
120
- roomAdmin: jam === null || jam === void 0 ? void 0 : jam.moderators.includes(profile.id),
121
- roomRecord: jam === null || jam === void 0 ? void 0 : jam.moderators.includes(profile.id),
122
- canPublish: (jam === null || jam === void 0 ? void 0 : jam.type) === 'video-call' || !!((_c = jam === null || jam === void 0 ? void 0 : jam.speakers) === null || _c === void 0 ? void 0 : _c.includes(profile.id)),
127
+ roomAdmin: jam?.moderators.includes(profile.id),
128
+ roomRecord: jam?.moderators.includes(profile.id),
129
+ canPublish: jam?.type === 'video-call' || !!jam?.speakers?.includes(profile.id),
123
130
  canPublishSources: calculateSources(jam, profile),
124
131
  canPublishData: true,
125
132
  canSubscribe: true,
@@ -74,7 +74,7 @@ export const acceptFromWaitingRoom = async (event, profileId, recurrenceId) => {
74
74
  }
75
75
  const aKey = admittanceKey(event, recurrenceId);
76
76
  await conn.hSet(aKey, {
77
- [profile.id]: await createJamToken(event, profile, false, recurrenceId),
77
+ [profile.id]: await createJamToken(event, profile, { recurrenceId }),
78
78
  });
79
79
  await conn.expire(aKey, ADMITTANCE_TTL_SEC);
80
80
  };
@@ -6,5 +6,6 @@ export declare const connection: {
6
6
  export declare const queues: Record<string, Queue>;
7
7
  export declare const closeQueues: () => Promise<void>;
8
8
  export declare const queueAndWorker: <Input, Output = undefined>(queueName: string, processor: Processor<Input, Output>, queueOptions?: Omit<QueueOptions, "connection">) => [() => Queue, () => Worker];
9
+ export declare const getOrCreateQueue: (queueName: string) => Queue;
9
10
  export { getJobDetail } from './jobDetail';
10
11
  export { jobLogger, logStep, logFailure, formatErrorDetail, type JobLog, } from './jobLog';
@@ -1,4 +1,4 @@
1
- import { Queue, Worker } from 'bullmq';
1
+ import { MetricsTime, Queue, Worker } from 'bullmq';
2
2
  export const connection = {
3
3
  host: process.env.REDIS_HOST || 'localhost',
4
4
  port: Number(process.env.REDIS_PORT) || 6379,
@@ -18,10 +18,13 @@ export const closeQueues = async () => {
18
18
  export const queueAndWorker = (queueName, processor, queueOptions) => [
19
19
  () => {
20
20
  if (!queues[queueName]) {
21
- const queue = new Queue(queueName, Object.assign({ connection }, queueOptions));
21
+ const queue = new Queue(queueName, {
22
+ connection,
23
+ ...queueOptions,
24
+ });
22
25
  queues[queueName] = queue;
23
26
  // Clean up existing jobs based on defaultJobOptions retention settings
24
- const defaultJobOptions = queueOptions === null || queueOptions === void 0 ? void 0 : queueOptions.defaultJobOptions;
27
+ const defaultJobOptions = queueOptions?.defaultJobOptions;
25
28
  if (defaultJobOptions) {
26
29
  void (async () => {
27
30
  try {
@@ -54,7 +57,10 @@ export const queueAndWorker = (queueName, processor, queueOptions) => [
54
57
  () => new Worker(queueName, processor, {
55
58
  connection,
56
59
  concurrency: 5,
60
+ metrics: { maxDataPoints: MetricsTime.ONE_WEEK },
57
61
  }),
58
62
  ];
63
+ export const getOrCreateQueue = (queueName) => queues[queueName] ??
64
+ (queues[queueName] = new Queue(queueName, { connection }));
59
65
  export { getJobDetail } from './jobDetail.js';
60
66
  export { jobLogger, logStep, logFailure, formatErrorDetail, } from './jobLog.js';
@@ -1,11 +1,5 @@
1
- import { Queue } from 'bullmq';
2
- import { connection, queues } from './index.js';
3
- const getOrCreateQueue = (queueName) => {
4
- var _a;
5
- return (_a = queues[queueName]) !== null && _a !== void 0 ? _a : (queues[queueName] = new Queue(queueName, { connection }));
6
- };
1
+ import { getOrCreateQueue } from './index.js';
7
2
  export const getJobDetail = async (queueName, jobId) => {
8
- var _a, _b, _c, _d, _e;
9
3
  const queue = getOrCreateQueue(queueName);
10
4
  const job = await queue.getJob(jobId);
11
5
  if (!job || job.id == null) {
@@ -20,11 +14,11 @@ export const getJobDetail = async (queueName, jobId) => {
20
14
  id: String(job.id),
21
15
  name: job.name,
22
16
  state,
23
- failedReason: (_a = job.failedReason) !== null && _a !== void 0 ? _a : null,
24
- finishedOn: (_b = job.finishedOn) !== null && _b !== void 0 ? _b : null,
25
- processedOn: (_c = job.processedOn) !== null && _c !== void 0 ? _c : null,
26
- timestamp: (_d = job.timestamp) !== null && _d !== void 0 ? _d : null,
27
- data: (_e = job.data) !== null && _e !== void 0 ? _e : null,
17
+ failedReason: job.failedReason ?? null,
18
+ finishedOn: job.finishedOn ?? null,
19
+ processedOn: job.processedOn ?? null,
20
+ timestamp: job.timestamp ?? null,
21
+ data: job.data ?? null,
28
22
  logs,
29
23
  logCount: count,
30
24
  };
@@ -6,7 +6,6 @@ export const jobLogger = (job) => (message) => job.log(message).then(() => undef
6
6
  * `code`) so failed deliveries are diagnosable from the job log alone.
7
7
  */
8
8
  export const formatErrorDetail = (error) => {
9
- var _a, _b;
10
9
  if (error instanceof Error) {
11
10
  const e = error;
12
11
  const parts = [e.message];
@@ -24,13 +23,13 @@ export const formatErrorDetail = (error) => {
24
23
  }
25
24
  if (error && typeof error === 'object') {
26
25
  const e = error;
27
- const reason = (_b = (_a = e.reason) !== null && _a !== void 0 ? _a : e.code) !== null && _b !== void 0 ? _b : e.message;
26
+ const reason = e.reason ?? e.code ?? e.message;
28
27
  if (reason != null)
29
28
  return String(reason);
30
29
  try {
31
30
  return JSON.stringify(error);
32
31
  }
33
- catch (_c) {
32
+ catch {
34
33
  return String(error);
35
34
  }
36
35
  }
@@ -1,42 +1,7 @@
1
- var __asyncValues = (this && this.__asyncValues) || function (o) {
2
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3
- var m = o[Symbol.asyncIterator], i;
4
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
5
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
6
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
7
- };
8
- var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
9
- var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
10
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
11
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
12
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
13
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
14
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
15
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
16
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
17
- function fulfill(value) { resume("next", value); }
18
- function reject(value) { resume("throw", value); }
19
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
20
- };
21
- function nodeStreamToIterator(stream) {
22
- return __asyncGenerator(this, arguments, function* nodeStreamToIterator_1() {
23
- var _a, e_1, _b, _c;
24
- try {
25
- for (var _d = true, stream_1 = __asyncValues(stream), stream_1_1; stream_1_1 = yield __await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) {
26
- _c = stream_1_1.value;
27
- _d = false;
28
- const chunk = _c;
29
- yield yield __await(chunk);
30
- }
31
- }
32
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
33
- finally {
34
- try {
35
- if (!_d && !_a && (_b = stream_1.return)) yield __await(_b.call(stream_1));
36
- }
37
- finally { if (e_1) throw e_1.error; }
38
- }
39
- });
1
+ async function* nodeStreamToIterator(stream) {
2
+ for await (const chunk of stream) {
3
+ yield chunk;
4
+ }
40
5
  }
41
6
  function iteratorToStream(iterator) {
42
7
  return new ReadableStream({
@@ -1,3 +1,3 @@
1
- import { type ZodTypeAny } from 'zod';
1
+ import { type ZodTypeAny } from '@openpeepshq/common/zod';
2
2
  /** Zod v4 removed `.deepPartial()`; this mirrors the v3 helper for config documents. */
3
3
  export declare const zodDeepPartialSchema: (schema: ZodTypeAny) => ZodTypeAny;
@@ -1,4 +1,4 @@
1
- import { z } from 'zod';
1
+ import { z } from '@openpeepshq/common/zod';
2
2
  const ZodObjectCtor = z.object({}).constructor;
3
3
  const ZodArrayCtor = z.array(z.string()).constructor;
4
4
  const ZodOptionalCtor = z.string().optional().constructor;
package/dist/log/index.js CHANGED
@@ -1,10 +1,3 @@
1
- var __asyncValues = (this && this.__asyncValues) || function (o) {
2
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3
- var m = o[Symbol.asyncIterator], i;
4
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
5
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
6
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
7
- };
8
1
  import { createReadStream, existsSync, mkdirSync } from 'node:fs';
9
2
  import { appendFile } from 'node:fs/promises';
10
3
  import { join } from 'node:path';
@@ -15,7 +8,6 @@ import { default as logsConfig } from '../config/defaults/logs.js';
15
8
  const createLogDirectory = () => mkdirSync(logsConfig.local.path, { recursive: true });
16
9
  const currentFile = (date) => join(logsConfig.local.path, formatDate(date, 'yyyyMMdd') + '.log');
17
10
  export const listLogs = async (date = new Date()) => {
18
- var _a, e_1, _b, _c;
19
11
  const filePath = currentFile(date);
20
12
  if (!existsSync(filePath)) {
21
13
  return [];
@@ -26,25 +18,13 @@ export const listLogs = async (date = new Date()) => {
26
18
  crlfDelay: Infinity,
27
19
  });
28
20
  const lines = [];
29
- try {
30
- for (var _d = true, iterator_1 = __asyncValues(iterator), iterator_1_1; iterator_1_1 = await iterator_1.next(), _a = iterator_1_1.done, !_a; _d = true) {
31
- _c = iterator_1_1.value;
32
- _d = false;
33
- const logLine = _c;
34
- try {
35
- lines.push(JSON.parse(logLine));
36
- }
37
- catch (_e) {
38
- // skip malformed lines
39
- }
40
- }
41
- }
42
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
43
- finally {
21
+ for await (const logLine of iterator) {
44
22
  try {
45
- if (!_d && !_a && (_b = iterator_1.return)) await _b.call(iterator_1);
23
+ lines.push(JSON.parse(logLine));
24
+ }
25
+ catch {
26
+ // skip malformed lines
46
27
  }
47
- finally { if (e_1) throw e_1.error; }
48
28
  }
49
29
  return lines.reverse();
50
30
  };
@@ -62,7 +42,12 @@ const namespaceLogLevels = {};
62
42
  /** Errors stringify to `{}` unless message/stack are copied onto enumerable keys. */
63
43
  const serializeLogArg = (arg) => {
64
44
  if (arg instanceof Error) {
65
- return safeJsonStringify(Object.assign({ name: arg.name, message: arg.message, stack: arg.stack }, arg));
45
+ return safeJsonStringify({
46
+ name: arg.name,
47
+ message: arg.message,
48
+ stack: arg.stack,
49
+ ...arg,
50
+ });
66
51
  }
67
52
  if (arg !== null && typeof arg === 'object') {
68
53
  return safeJsonStringify(arg);
@@ -72,12 +57,11 @@ const serializeLogArg = (arg) => {
72
57
  export const logger = (ns, meta) => {
73
58
  createLogDirectory();
74
59
  const log = (level, ...args) => {
75
- var _a;
76
- if (logLevels[level] < ((_a = namespaceLogLevels[ns]) !== null && _a !== void 0 ? _a : defaultLogLevel)) {
60
+ if (logLevels[level] < (namespaceLogLevels[ns] ?? defaultLogLevel)) {
77
61
  return;
78
62
  }
79
63
  const date = new Date();
80
- console.log(`${date.toISOString()} - ${ns} - ${level} | `, ...args, meta !== null && meta !== void 0 ? meta : '');
64
+ console.log(`${date.toISOString()} - ${ns} - ${level} | `, ...args, meta ?? '');
81
65
  appendFile(currentFile(date), JSON.stringify({
82
66
  level,
83
67
  message: args.map(serializeLogArg).join(' '),
@@ -12,7 +12,7 @@ export interface MediaFile {
12
12
  }
13
13
  /**
14
14
  * Stream a web `ReadableStream` to a temp file, preserving the original
15
- * extension so format-sniffing tools (audiowaveform, sharp) behave. Peak
15
+ * extension so format-sniffing tools (ffmpeg, sharp) behave. Peak
16
16
  * memory is bounded by the write stream's highWaterMark, not the file size.
17
17
  */
18
18
  export declare const writeStreamToTemp: (stream: ReadableStream, name: string) => Promise<string>;
@@ -9,7 +9,6 @@ import { createReadStream, createWriteStream } from 'node:fs';
9
9
  import { Readable } from 'node:stream';
10
10
  import { pipeline } from 'node:stream/promises';
11
11
  import { getTheme, randomString } from '@openpeepshq/common/lib';
12
- import { execSync } from 'node:child_process';
13
12
  import { logger } from '../log/index.js';
14
13
  import { hub } from '../events/index.js';
15
14
  let storagePromise = null;
@@ -33,7 +32,7 @@ export const mediaStorage = () => {
33
32
  const tempPathFor = (name) => join(tmpdir(), `media-${randomString(16)}${path.extname(name)}`);
34
33
  /**
35
34
  * Stream a web `ReadableStream` to a temp file, preserving the original
36
- * extension so format-sniffing tools (audiowaveform, sharp) behave. Peak
35
+ * extension so format-sniffing tools (ffmpeg, sharp) behave. Peak
37
36
  * memory is bounded by the write stream's highWaterMark, not the file size.
38
37
  */
39
38
  export const writeStreamToTemp = async (stream, name) => {
@@ -108,7 +107,7 @@ export const createPreview = async (inputPath, mimetype, originalName) => {
108
107
  if (originalName.endsWith('.mkv')) {
109
108
  return createVideoPreview(inputPath);
110
109
  }
111
- return { path: inputPath, mimetype };
110
+ return createFilePreview(inputPath, mimetype, originalName);
112
111
  }
113
112
  };
114
113
  const createImagePreview = async (inputPath, mimetype) => {
@@ -126,6 +125,52 @@ const createImagePreview = async (inputPath, mimetype) => {
126
125
  .toFile(outputPath);
127
126
  return { path: outputPath, mimetype: 'image/webp' };
128
127
  };
128
+ const escapeXml = (value) => value
129
+ .replace(/&/g, '&amp;')
130
+ .replace(/</g, '&lt;')
131
+ .replace(/>/g, '&gt;')
132
+ .replace(/"/g, '&quot;');
133
+ const createPdfPreview = (inputPath) => {
134
+ const outputPath = join(tmpdir(), `preview-${randomString(16)}.webp`);
135
+ return new Promise((resolve, reject) => {
136
+ ffmpeg(inputPath)
137
+ .frames(1)
138
+ .outputOptions(['-c:v libwebp', '-lossless 0', '-q:v 80'])
139
+ .output(outputPath)
140
+ .on('end', () => resolve({ path: outputPath, mimetype: 'image/webp' }))
141
+ .on('error', reject)
142
+ .run();
143
+ });
144
+ };
145
+ const createDocumentCardPreview = async (originalName) => {
146
+ const ext = (path.extname(originalName).replace('.', '') || 'FILE')
147
+ .slice(0, 8)
148
+ .toUpperCase();
149
+ const base = path.parse(originalName).name.slice(0, 28);
150
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="700" height="700">
151
+ <rect width="700" height="700" fill="#f4f4f5"/>
152
+ <rect x="160" y="80" width="380" height="480" rx="16" fill="#ffffff" stroke="#d4d4d8" stroke-width="4"/>
153
+ <rect x="210" y="140" width="180" height="72" rx="8" fill="#18181b"/>
154
+ <text x="300" y="188" text-anchor="middle" font-family="sans-serif" font-size="28" font-weight="700" fill="#ffffff">${escapeXml(ext)}</text>
155
+ <text x="350" y="420" text-anchor="middle" font-family="sans-serif" font-size="28" fill="#18181b">${escapeXml(base)}</text>
156
+ </svg>`;
157
+ const outputPath = join(tmpdir(), `preview-${randomString(16)}.webp`);
158
+ await sharp(Buffer.from(svg)).webp({ quality: 80 }).toFile(outputPath);
159
+ return { path: outputPath, mimetype: 'image/webp' };
160
+ };
161
+ const createFilePreview = async (inputPath, mimetype, originalName) => {
162
+ const isPdf = mimetype === 'application/pdf' ||
163
+ originalName.toLowerCase().endsWith('.pdf');
164
+ if (isPdf) {
165
+ try {
166
+ return await createPdfPreview(inputPath);
167
+ }
168
+ catch {
169
+ // Some ffmpeg builds cannot rasterize PDFs.
170
+ }
171
+ }
172
+ return createDocumentCardPreview(originalName);
173
+ };
129
174
  const getMediaDuration = (filePath) => new Promise((resolve, reject) => {
130
175
  ffmpeg.ffprobe(filePath, (err, metadata) => {
131
176
  if (err) {
@@ -145,29 +190,45 @@ const getMediaDuration = (filePath) => new Promise((resolve, reject) => {
145
190
  });
146
191
  const getVideoStreamInfo = (filePath) => new Promise((resolve, reject) => {
147
192
  ffmpeg.ffprobe(filePath, (err, metadata) => {
148
- var _a;
149
193
  if (err) {
150
194
  reject(err);
151
195
  return;
152
196
  }
153
197
  const stream = metadata.streams.find((s) => s.codec_type === 'video');
154
- const duration = (_a = metadata.format.duration) !== null && _a !== void 0 ? _a : ((stream === null || stream === void 0 ? void 0 : stream.duration) ? Number(stream.duration) : undefined);
155
- if (!(stream === null || stream === void 0 ? void 0 : stream.width) || !(stream === null || stream === void 0 ? void 0 : stream.height) || !duration) {
198
+ const duration = metadata.format.duration ??
199
+ (stream?.duration ? Number(stream.duration) : undefined);
200
+ if (!stream?.width || !stream?.height || !duration) {
156
201
  reject(new Error('Could not determine video stream info'));
157
202
  return;
158
203
  }
159
204
  resolve({ width: stream.width, height: stream.height, duration });
160
205
  });
161
206
  });
207
+ const waveformColor = (hex) => {
208
+ const bare = hex.replace('#', '');
209
+ return /^[0-9a-fA-F]{6}$/.test(bare) ? `0x${bare}` : '0x15678a';
210
+ };
211
+ /**
212
+ * Waveform still via ffmpeg. `audiowaveform` is not a project dependency and
213
+ * is often missing locally; ffmpeg already is, because video processing uses it.
214
+ */
215
+ const renderWaveform = (inputPath, outputPath, color) => new Promise((resolve, reject) => {
216
+ const size = `${previewMaxWidth}x${previewMaxWidth}`;
217
+ ffmpeg(inputPath)
218
+ .noVideo()
219
+ .outputOptions('-filter_complex', `aformat=channel_layouts=mono,showwavespic=s=${size}:colors=${color}`)
220
+ .outputOptions('-frames:v', '1')
221
+ .outputOptions('-update', '1')
222
+ .output(outputPath)
223
+ .on('end', () => resolve())
224
+ .on('error', (error) => reject(error))
225
+ .run();
226
+ });
162
227
  const createAudioPreview = async (inputPath) => {
163
228
  const outputPath = join(tmpdir(), `preview-${randomString(16)}.png`);
229
+ const color = waveformColor(getTheme(await communityConfig()).primaryHex);
164
230
  try {
165
- const duration = await getMediaDuration(inputPath);
166
- const pixelsPerSecond = Math.floor(700 / duration);
167
- execSync(`audiowaveform -i ${inputPath} -o ${outputPath} \
168
- --background-color ffffff88 --waveform-color ${getTheme(await communityConfig()).primaryHex.slice(1)} \
169
- -w ${previewMaxWidth} -h ${previewMaxWidth} --pixels-per-second ${pixelsPerSecond} \
170
- --no-axis-labels -q`);
231
+ await renderWaveform(inputPath, outputPath, color);
171
232
  return { path: outputPath, mimetype: 'image/png' };
172
233
  }
173
234
  catch (error) {
@@ -42,13 +42,12 @@ export const subscribeToMediaProgress = async (mediaAttachmentId, onMessage) =>
42
42
  return () => disconnect(conn);
43
43
  };
44
44
  const [mediaProcessingQueue, mediaProcessingWorker] = queueAndWorker('media-processing', async (job) => {
45
- var _a;
46
45
  const { mediaAttachmentId, fileStorageKey } = job.data;
47
46
  const attachment = await findMediaAttachment(mediaAttachmentId);
48
47
  if (!attachment) {
49
48
  throw new Error(`MediaAttachment ${mediaAttachmentId} not found in worker`);
50
49
  }
51
- const filesize = (_a = attachment.meta.size) !== null && _a !== void 0 ? _a : 0;
50
+ const filesize = attachment.meta.size ?? 0;
52
51
  const estimatedDurationMs = await estimateProcessingDuration({
53
52
  filetype: attachment.type,
54
53
  filesize,