@openpeepshq/core 0.2.0 → 0.2.2

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 (74) hide show
  1. package/LICENSE +674 -0
  2. package/dist/accounts/mutations.js +9 -0
  3. package/dist/analytics/cache.js +1 -1
  4. package/dist/config/index.d.ts +3 -336
  5. package/dist/db/explorer/index.d.ts +1 -1
  6. package/dist/db/explorer/index.js +1 -1
  7. package/dist/db/index.d.ts +1 -1
  8. package/dist/db/index.js +1 -1
  9. package/dist/db/pg/map/registry.js +3 -2
  10. package/dist/federation/actors.d.ts +32 -0
  11. package/dist/federation/actors.js +136 -0
  12. package/dist/federation/identity.d.ts +11 -0
  13. package/dist/federation/identity.js +11 -0
  14. package/dist/federation/index.d.ts +8 -1
  15. package/dist/federation/index.js +5 -1
  16. package/dist/federation/ingest.d.ts +9 -0
  17. package/dist/federation/ingest.js +60 -0
  18. package/dist/federation/notes.d.ts +8 -0
  19. package/dist/federation/notes.js +30 -0
  20. package/dist/federation/peers.d.ts +3 -0
  21. package/dist/federation/peers.js +24 -0
  22. package/dist/jams/export.d.ts +2 -0
  23. package/dist/jams/export.js +5 -0
  24. package/dist/jams/finders.d.ts +1 -0
  25. package/dist/jams/finders.js +1 -0
  26. package/dist/jams/health.d.ts +23 -0
  27. package/dist/jams/health.js +79 -7
  28. package/dist/jams/index.d.ts +1 -1
  29. package/dist/jams/index.js +10 -3
  30. package/dist/jams/token.js +6 -2
  31. package/dist/jams/waitingRoom.js +3 -1
  32. package/dist/media/garbageCollection.d.ts +109 -0
  33. package/dist/media/garbageCollection.js +603 -0
  34. package/dist/media/garbageCollectionJobs.d.ts +14 -0
  35. package/dist/media/garbageCollectionJobs.js +55 -0
  36. package/dist/media/index.d.ts +10 -0
  37. package/dist/media/index.js +39 -15
  38. package/dist/media/streaming.d.ts +2 -0
  39. package/dist/media/streaming.js +8 -0
  40. package/dist/notifications/defaultNotifications/index.js +2 -0
  41. package/dist/notifications/defaultNotifications/jamStarted/index.d.ts +1 -0
  42. package/dist/notifications/defaultNotifications/jamStarted/index.js +61 -13
  43. package/dist/notifications/defaultNotifications/waitlistOffer/index.d.ts +24 -0
  44. package/dist/notifications/defaultNotifications/waitlistOffer/index.js +40 -0
  45. package/dist/notifications/index.d.ts +1 -1
  46. package/dist/notifications/index.js +1 -1
  47. package/dist/plugins/pluginAuth.js +1 -0
  48. package/dist/posts/conversationQueries.d.ts +31 -0
  49. package/dist/posts/conversationQueries.js +150 -24
  50. package/dist/posts/finders.d.ts +9 -0
  51. package/dist/posts/finders.js +23 -3
  52. package/dist/posts/helpers/index.d.ts +10 -2
  53. package/dist/posts/helpers/index.js +6 -0
  54. package/dist/posts/index.d.ts +3 -1
  55. package/dist/posts/index.js +3 -1
  56. package/dist/posts/mapping.d.ts +14 -0
  57. package/dist/posts/mutations.d.ts +13 -6
  58. package/dist/posts/mutations.js +271 -72
  59. package/dist/posts/rsvpExport.d.ts +47 -0
  60. package/dist/posts/rsvpExport.js +178 -0
  61. package/dist/posts/unseenCounts.d.ts +6 -0
  62. package/dist/posts/unseenCounts.js +51 -1
  63. package/dist/posts/waitlist.d.ts +13 -0
  64. package/dist/posts/waitlist.js +75 -0
  65. package/dist/posts/waitlistOfferJobs.d.ts +10 -0
  66. package/dist/posts/waitlistOfferJobs.js +91 -0
  67. package/dist/profiles/index.js +6 -1
  68. package/dist/profiles/mutations.js +6 -3
  69. package/dist/reports/mapping.d.ts +1 -1
  70. package/dist/server/index.d.ts +1 -0
  71. package/dist/stats/mapping.d.ts +1 -0
  72. package/dist/stripe/connection.js +1 -1
  73. package/dist/stripe/helpers.js +7 -3
  74. package/package.json +11 -10
@@ -15,6 +15,17 @@ import { hub } from '../events/index.js';
15
15
  let storagePromise = null;
16
16
  const log = logger('app:media');
17
17
  const previewMaxWidth = 700;
18
+ /**
19
+ * Thrown when file content does not match its declared type (e.g. a text file
20
+ * renamed to `.jpg`). The upload handler maps this to HTTP 400 so the client
21
+ * gets a clear message instead of a 500.
22
+ */
23
+ export class MediaContentError extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = 'MediaContentError';
27
+ }
28
+ }
18
29
  const initStorage = async () => {
19
30
  const { media: { storage: { params }, }, } = await config();
20
31
  hub.on('configUpdated', (namespace, name) => {
@@ -99,7 +110,7 @@ export const transcodeIncomingMedia = async (type, inputPath, originalName, sour
99
110
  export const createPreview = async (inputPath, mimetype, originalName) => {
100
111
  switch (mimetype.split('/')[0]) {
101
112
  case 'image':
102
- return createImagePreview(inputPath, mimetype);
113
+ return createImagePreview(inputPath);
103
114
  case 'audio':
104
115
  return createAudioPreview(inputPath);
105
116
  case 'video':
@@ -111,19 +122,18 @@ export const createPreview = async (inputPath, mimetype, originalName) => {
111
122
  return createFilePreview(inputPath, mimetype, originalName);
112
123
  }
113
124
  };
114
- const createImagePreview = async (inputPath, mimetype) => {
115
- const width = await sharp(inputPath)
116
- .metadata()
117
- .then((m) => m.width || 0);
118
- if (width <= previewMaxWidth) {
119
- return { path: inputPath, mimetype };
120
- }
125
+ const createImagePreview = async (inputPath) => {
121
126
  const outputPath = join(tmpdir(), `preview-${randomString(16)}.webp`);
122
- await sharp(inputPath)
123
- .rotate()
124
- .resize(previewMaxWidth)
125
- .webp()
126
- .toFile(outputPath);
127
+ try {
128
+ await sharp(inputPath)
129
+ .rotate()
130
+ .resize(previewMaxWidth)
131
+ .webp({ quality: 80 })
132
+ .toFile(outputPath);
133
+ }
134
+ catch {
135
+ throw new MediaContentError("This file isn't a supported image.");
136
+ }
127
137
  return { path: outputPath, mimetype: 'image/webp' };
128
138
  };
129
139
  const escapeXml = (value) => value
@@ -142,6 +152,18 @@ const createPdfPreview = async (inputPath) => {
142
152
  .resize(previewMaxWidth)
143
153
  .webp({ quality: 80 })
144
154
  .toFile(outputPath);
155
+ // sharp/poppler may produce a blank or corrupt thumbnail without erroring
156
+ // when fonts are missing (text renders as tofu rectangles) or the PDF page is
157
+ // genuinely empty. Validate the output so callers fall back to the document
158
+ // card preview, which shows the filename instead of garbled content.
159
+ const { size } = await fs.stat(outputPath);
160
+ if (size < 100) {
161
+ throw new Error('PDF preview rendered to empty image');
162
+ }
163
+ const stats = await sharp(outputPath).stats();
164
+ if (stats.channels.every((c) => c.stdev < 2)) {
165
+ throw new Error('PDF preview rendered to blank image');
166
+ }
145
167
  return { path: outputPath, mimetype: 'image/webp' };
146
168
  };
147
169
  const OFFICE_DOC_EXTENSIONS = new Set([
@@ -248,7 +270,7 @@ const createFilePreview = async (inputPath, mimetype, originalName) => {
248
270
  }
249
271
  return createDocumentCardPreview(originalName);
250
272
  };
251
- const getMediaDuration = (filePath) => new Promise((resolve, reject) => {
273
+ const _getMediaDuration = (filePath) => new Promise((resolve, reject) => {
252
274
  ffmpeg.ffprobe(filePath, (err, metadata) => {
253
275
  if (err) {
254
276
  reject(err);
@@ -368,7 +390,7 @@ const createVideoPreview = async (inputPath) => {
368
390
  }
369
391
  catch (error) {
370
392
  await cleanup();
371
- reject(new Error(`Error handling output file: ${error.message}`));
393
+ reject(new Error(`Error handling output file: ${error instanceof Error ? error.message : String(error)}`));
372
394
  }
373
395
  })
374
396
  .on('error', async (error) => {
@@ -384,3 +406,5 @@ export * from './streaming.js';
384
406
  export * from './streamingJobs.js';
385
407
  export * from './streamingCleanupJobs.js';
386
408
  export * from './streamingPrewarm.js';
409
+ export * from './garbageCollection.js';
410
+ export * from './garbageCollectionJobs.js';
@@ -53,6 +53,8 @@ export declare const ensureStreamDir: (storageId: string) => Promise<string>;
53
53
  */
54
54
  export declare const recordStreamAccess: (storageId: string) => Promise<void>;
55
55
  export declare const getStreamLastAccess: (storageId: string) => Promise<number | null>;
56
+ /** Drop the playback record for a source file that no longer exists. */
57
+ export declare const forgetStreamAccess: (storageId: string) => Promise<void>;
56
58
  export interface CleanupResult {
57
59
  deleted: string[];
58
60
  kept: number;
@@ -188,6 +188,14 @@ export const getStreamLastAccess = async (storageId) => {
188
188
  const score = await conn.zScore(STREAM_ACCESS_KEY, storageId);
189
189
  return typeof score === 'number' ? score : null;
190
190
  };
191
+ /** Drop the playback record for a source file that no longer exists. */
192
+ export const forgetStreamAccess = async (storageId) => {
193
+ lastAccessWriteCache.delete(storageId);
194
+ if (!isValidStorageId(storageId))
195
+ return;
196
+ const conn = await getSharedConnection();
197
+ await conn.zRem(STREAM_ACCESS_KEY, storageId);
198
+ };
191
199
  /**
192
200
  * Deletes every stream directory whose Redis-recorded last-access time is
193
201
  * older than `maxAgeMs`, or which has no Redis entry at all. A missing entry
@@ -18,6 +18,7 @@ import { default as pollEnded } from './pollEnded/index.js';
18
18
  import { default as newGroupPost } from './newGroupPost/index.js';
19
19
  import { default as rsvp } from './rsvp/index.js';
20
20
  import { default as rsvpCanceled } from './rsvpCanceled/index.js';
21
+ import { default as waitlistOffer } from './waitlistOffer/index.js';
21
22
  const defaultNotificationsHandlers = [
22
23
  announcement,
23
24
  directMessage,
@@ -38,6 +39,7 @@ const defaultNotificationsHandlers = [
38
39
  newGroupPost,
39
40
  rsvp,
40
41
  rsvpCanceled,
42
+ waitlistOffer,
41
43
  ];
42
44
  export const defaultNotificationTypes = defaultNotificationsHandlers.map((handler) => pick(handler, 'type', 'requiredCapabilities', 'defaultSettings'));
43
45
  export const registerDefaultNotifications = async () => {
@@ -3,6 +3,7 @@ declare const _default: {
3
3
  event: string;
4
4
  type: string;
5
5
  eventHandler: (...args: unknown[]) => Promise<void>;
6
+ expander: (notification: ExpandedNotification) => Promise<ExpandedNotification>;
6
7
  pushRenderer: (notification: ExpandedNotification) => Promise<{
7
8
  title: string;
8
9
  options: {
@@ -1,21 +1,49 @@
1
1
  import { listProfiles, listGroupMembers, findProfile, } from '@openpeepshq/core/profiles';
2
2
  import { maybeCreateNotification } from '@openpeepshq/core/notifications';
3
- import { profileName } from '@openpeepshq/common/lib';
3
+ import { getJamUrl, occurrenceForJamStart, profileName, } from '@openpeepshq/common/lib';
4
+ import { listJamStarts } from '../../../jams/finders.js';
4
5
  import { PUSH_INVALIDATE } from '../../pushInvalidation.js';
6
+ // The start row is written in the same request, then the notification is
7
+ // queued. They are not linked by id, so match on time.
8
+ const START_MATCH_WINDOW_MS = 15 * 60 * 1000;
9
+ const storedRecurrenceId = (data) => {
10
+ if (!data || typeof data !== 'object' || !('recurrenceId' in data)) {
11
+ return undefined;
12
+ }
13
+ const recurrenceId = data.recurrenceId;
14
+ return typeof recurrenceId === 'string' ? recurrenceId : undefined;
15
+ };
16
+ const recurrenceIdFromStart = async (postId, at) => {
17
+ const target = at.getTime();
18
+ let closest;
19
+ for (const start of await listJamStarts(postId)) {
20
+ if (!start.recurrenceId)
21
+ continue;
22
+ const delta = Math.abs(new Date(start.createdAt).getTime() - target);
23
+ if (!closest || delta < closest.delta) {
24
+ closest = { recurrenceId: start.recurrenceId, delta };
25
+ }
26
+ }
27
+ if (!closest || closest.delta > START_MATCH_WINDOW_MS)
28
+ return undefined;
29
+ return closest.recurrenceId;
30
+ };
5
31
  const eventHandler = async (...args) => {
6
- const [profile, post] = args;
32
+ const [profile, post, recurrenceId] = args;
7
33
  const jam = post.data?.type === 'event' && post.data?.jam;
8
34
  if (!jam) {
9
35
  return;
10
36
  }
37
+ const notify = (recipientProfile) => maybeCreateNotification(recipientProfile, {
38
+ type: 'jamStarted',
39
+ fromProfileId: profile.id,
40
+ postId: post.id,
41
+ ...(recurrenceId ? { data: { recurrenceId } } : {}),
42
+ });
11
43
  if (['local', 'public'].includes(post.visibility)) {
12
44
  for (const recipientProfile of await listProfiles()) {
13
45
  if (profile.id !== recipientProfile?.id) {
14
- await maybeCreateNotification(recipientProfile, {
15
- type: 'jamStarted',
16
- fromProfileId: profile.id,
17
- postId: post.id,
18
- });
46
+ await notify(recipientProfile);
19
47
  }
20
48
  }
21
49
  return;
@@ -50,12 +78,31 @@ const eventHandler = async (...args) => {
50
78
  }
51
79
  }
52
80
  for (const recipientProfile of recipients) {
53
- await maybeCreateNotification(recipientProfile, {
54
- type: 'jamStarted',
55
- fromProfileId: profile.id,
56
- postId: post.id,
57
- });
81
+ await notify(recipientProfile);
82
+ }
83
+ };
84
+ const expander = async (notification) => {
85
+ const post = notification.post;
86
+ if (!post || post.data?.type !== 'event' || !post.data.recurrence) {
87
+ return notification;
58
88
  }
89
+ const at = new Date(notification.createdAt);
90
+ const occurrence = occurrenceForJamStart(post.data, {
91
+ recurrenceId: storedRecurrenceId(notification.data) ??
92
+ (await recurrenceIdFromStart(post.id, at)),
93
+ at,
94
+ });
95
+ if (!occurrence)
96
+ return notification;
97
+ return {
98
+ ...notification,
99
+ post: {
100
+ ...post,
101
+ occurrenceRecurrenceId: occurrence.recurrenceId,
102
+ occurrenceStart: occurrence.start,
103
+ ...(occurrence.end ? { occurrenceEnd: occurrence.end } : {}),
104
+ },
105
+ };
59
106
  };
60
107
  const pushRenderer = async (notification) => ({
61
108
  title: `${profileName(notification.senderProfile)} started a jam`,
@@ -63,7 +110,7 @@ const pushRenderer = async (notification) => ({
63
110
  body: notification.post?.data?.name,
64
111
  actions: [
65
112
  {
66
- action: `goto:/events/${notification.post?.id}/jam`,
113
+ action: `goto:${getJamUrl(notification.post?.id ?? '', undefined, notification.post?.occurrenceRecurrenceId)}`,
67
114
  title: 'Join Jam',
68
115
  },
69
116
  ],
@@ -74,5 +121,6 @@ export default {
74
121
  event: 'jamStarted',
75
122
  type: 'jamStarted',
76
123
  eventHandler,
124
+ expander,
77
125
  pushRenderer,
78
126
  };
@@ -0,0 +1,24 @@
1
+ import { type ExpandedNotification } from '@openpeepshq/common/types';
2
+ declare const _default: {
3
+ type: string;
4
+ event: string;
5
+ defaultSettings: {
6
+ readonly create: true;
7
+ readonly push: true;
8
+ readonly email: true;
9
+ };
10
+ eventHandler: () => Promise<void>;
11
+ pushRenderer: (notification: ExpandedNotification) => Promise<{
12
+ title: string;
13
+ options: {
14
+ body: string;
15
+ icon: string;
16
+ actions: {
17
+ action: string;
18
+ title: string;
19
+ }[];
20
+ };
21
+ invalidateQueries: string[][];
22
+ }>;
23
+ };
24
+ export default _default;
@@ -0,0 +1,40 @@
1
+ import { notificationAll, } from '@openpeepshq/common/types';
2
+ import { getProfileAvatar, isWaitlistOfferNotice, waitlistClaimPath, } from '@openpeepshq/common/lib';
3
+ import { communityConfig } from '../../../config/index.js';
4
+ import { PUSH_INVALIDATE } from '../../pushInvalidation.js';
5
+ const eventHandler = async () => { };
6
+ const pushRenderer = async (notification) => {
7
+ const notice = isWaitlistOfferNotice(notification.data)
8
+ ? notification.data
9
+ : undefined;
10
+ const eventName = notification.post?.data?.type === 'event'
11
+ ? notification.post.data.name?.trim()
12
+ : undefined;
13
+ const path = notification.post
14
+ ? waitlistClaimPath(notification.post.id, notice?.recurrenceId)
15
+ : '/notifications';
16
+ return {
17
+ title: 'A spot opened',
18
+ options: {
19
+ body: eventName
20
+ ? `Claim your spot at ${eventName}`
21
+ : 'Claim your spot before the offer expires',
22
+ icon: getProfileAvatar(notification.senderProfile ?? notification.post?.profile, await communityConfig()),
23
+ actions: [
24
+ {
25
+ action: `goto:${path}`,
26
+ title: 'Claim spot',
27
+ },
28
+ ],
29
+ },
30
+ invalidateQueries: [PUSH_INVALIDATE.posts],
31
+ };
32
+ };
33
+ export default {
34
+ type: 'waitlistOffer',
35
+ // Created directly when a seat is offered. The handler exists for push/email.
36
+ event: 'waitlistOffer',
37
+ defaultSettings: notificationAll,
38
+ eventHandler,
39
+ pushRenderer,
40
+ };
@@ -1,6 +1,6 @@
1
1
  export { maybeCreateNotification } from './mutations';
2
2
  export { registerDefaultNotifications, defaultNotificationTypes, } from './defaultNotifications';
3
- export { registerNotificationHandler, notificationHandlers, } from './handlers';
3
+ export { registerNotificationHandler, notificationHandlers } from './handlers';
4
4
  export { notificationSettings } from './helpers';
5
5
  export { sendTestPushNotification } from './push';
6
6
  export { notificationQueue, notificationWorker } from './jobs';
@@ -6,7 +6,7 @@ import { initializeFirebase } from './firebase.js';
6
6
  import { notificationQueue } from './jobs.js';
7
7
  export { maybeCreateNotification } from './mutations.js';
8
8
  export { registerDefaultNotifications, defaultNotificationTypes, } from './defaultNotifications/index.js';
9
- export { registerNotificationHandler, notificationHandlers, } from './handlers.js';
9
+ export { registerNotificationHandler, notificationHandlers } from './handlers.js';
10
10
  export { notificationSettings } from './helpers.js';
11
11
  export { sendTestPushNotification } from './push.js';
12
12
  export { notificationQueue, notificationWorker } from './jobs.js';
@@ -1,4 +1,5 @@
1
1
  import { jwtUtil } from '../jwt/index.js';
2
+ /* eslint-enable @typescript-eslint/no-namespace */
2
3
  /**
3
4
  * Express middleware that verifies the `Authorization: Bearer <token>` header
4
5
  * and attaches `{ pluginProfile }` to the request if valid.
@@ -13,6 +13,14 @@ export declare const findLatestThreadPostId: (rootId: string) => Promise<string>
13
13
  * they are the same). Avoids walking full ancestor chains.
14
14
  */
15
15
  export declare const listConversationPreviews: (authData: AuthorizationData) => Promise<PostWithMeta[][]>;
16
+ /**
17
+ * Collapse 1:1 previews sharing a participant pair into one entry
18
+ * [oldest root, newest leaf] so a conversation with several roots lists
19
+ * once. The oldest root (min uuidv7) is the pair's stable conversation id;
20
+ * it must match the key the unseen counts are merged under. Other
21
+ * conversations pass through. Result is ordered newest-leaf first.
22
+ */
23
+ export declare const mergeOneToOnePreviews: (conversations: PostWithMeta[][]) => PostWithMeta[][];
16
24
  /**
17
25
  * Archived conversations: threads the profile has left — detected by posts
18
26
  * they authored but are no longer in the audience of. Returns
@@ -27,4 +35,27 @@ export declare const listLeftConversations: (authData: AuthorizationData) => Pro
27
35
  export declare const getConversationThread: (root: PostWithMeta, authData: AuthorizationData, { limit }?: {
28
36
  limit?: number;
29
37
  }) => Promise<PostWithMeta[]>;
38
+ /**
39
+ * All post ids in the 1:1 conversation between two profiles, oldest first:
40
+ * every post of the pair, plus their reply descendants (e.g. system "left"
41
+ * posts, whose participants are only the remaining participant and which
42
+ * are reachable as descendants only). Ids are uuidv7, so ordering is
43
+ * chronological.
44
+ */
45
+ export declare const listOneToOneConversationPostIds: (db: PgDb, profileAId: string, profileBId: string) => Promise<string[]>;
46
+ /**
47
+ * Per root of a 1:1 conversation: the root id and that thread's newest post
48
+ * (leaf). Used to terminate every root's thread on leave.
49
+ */
50
+ export declare const listOneToOneConversationRootLeaves: (db: PgDb, profileAId: string, profileBId: string) => Promise<Array<{
51
+ rootId: string;
52
+ leafId: string;
53
+ }>>;
54
+ /**
55
+ * Merged 1:1 conversation: every message for the pair across all roots,
56
+ * oldest first. Any post of the conversation (typically the root in the URL)
57
+ * resolves to the same list. Capped like {@link getConversationThread}:
58
+ * the oldest message plus the newest CONTEXT_NODE_CAP others.
59
+ */
60
+ export declare const getOneToOneConversation: (post: PostWithMeta, authData: AuthorizationData) => Promise<PostWithMeta[]>;
30
61
  export {};
@@ -1,5 +1,5 @@
1
1
  import { sql } from 'drizzle-orm';
2
- import { blockedPairIds, getUniqueBy, isOneToOneWithBlocked, toHiddenPost, } from '@openpeepshq/common/lib';
2
+ import { blockedPairIds, isOneToOneDm, isOneToOneWithBlocked, participantIds, toHiddenPost, } from '@openpeepshq/common/lib';
3
3
  import { allpeepDb } from '../db/index.js';
4
4
  import { fetchRowsByIds, hydrateMapData } from '../db/pg/map/relations.js';
5
5
  import { capabilitiesConfig } from '../config/index.js';
@@ -113,17 +113,53 @@ export const listConversationPreviews = async (authData) => {
113
113
  const ids = [...new Set(pairs.flatMap((pair) => [pair.rootId, pair.leafId]))];
114
114
  const byId = await hydrateLeanPostsByIds(authData, ids);
115
115
  const blocked = new Set(blockedPairIds(profile));
116
- return getUniqueBy(pairs
117
- .map(({ rootId, leafId }) => {
118
- const root = byId.get(rootId);
119
- const leaf = byId.get(leafId);
120
- if (!root || !leaf)
121
- return null;
122
- if (isOneToOneWithBlocked(root, profile, blocked))
123
- return null;
124
- return rootId === leafId ? [root] : [root, leaf];
125
- })
126
- .filter((conversation) => !!conversation), (conversation) => conversation[0].id);
116
+ return mergeOneToOnePreviews(conversationPreviewsFromPairs(pairs, byId, profile, blocked));
117
+ };
118
+ const conversationPreviewsFromPairs = (pairs, byId, profile, blocked) => pairs
119
+ .map(({ rootId, leafId }) => {
120
+ const root = byId.get(rootId);
121
+ const leaf = byId.get(leafId);
122
+ if (!root || !leaf)
123
+ return null;
124
+ if (isOneToOneWithBlocked(root, profile, blocked))
125
+ return null;
126
+ return rootId === leafId ? [root] : [root, leaf];
127
+ })
128
+ .filter((conversation) => !!conversation);
129
+ const oneToOnePairKey = (post) => [...participantIds(post)].sort().join(',');
130
+ const byIdAsc = (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
131
+ /**
132
+ * Collapse 1:1 previews sharing a participant pair into one entry
133
+ * [oldest root, newest leaf] so a conversation with several roots lists
134
+ * once. The oldest root (min uuidv7) is the pair's stable conversation id;
135
+ * it must match the key the unseen counts are merged under. Other
136
+ * conversations pass through. Result is ordered newest-leaf first.
137
+ */
138
+ export const mergeOneToOnePreviews = (conversations) => {
139
+ const merged = [];
140
+ const byPair = new Map();
141
+ for (const conversation of conversations) {
142
+ const root = conversation[0];
143
+ if (!isOneToOneDm(root)) {
144
+ merged.push(conversation);
145
+ continue;
146
+ }
147
+ const pairKey = oneToOnePairKey(root);
148
+ const entries = byPair.get(pairKey) ?? [];
149
+ entries.push(conversation);
150
+ byPair.set(pairKey, entries);
151
+ }
152
+ for (const entries of byPair.values()) {
153
+ const root = entries
154
+ .map((conversation) => conversation[0])
155
+ .sort(byIdAsc)[0];
156
+ const leaf = entries
157
+ .map((conversation) => conversation[conversation.length - 1])
158
+ .sort(byIdAsc)
159
+ .at(-1);
160
+ merged.push(root.id === leaf.id ? [root] : [root, leaf]);
161
+ }
162
+ return merged.sort((a, b) => byIdAsc(b[b.length - 1], a[a.length - 1]));
127
163
  };
128
164
  /**
129
165
  * Archived conversations: threads the profile has left — detected by posts
@@ -175,17 +211,7 @@ export const listLeftConversations = async (authData) => {
175
211
  const ids = [...new Set(pairs.flatMap((pair) => [pair.rootId, pair.leafId]))];
176
212
  const byId = await hydrateLeanPostsByIds(authData, ids);
177
213
  const blocked = new Set(blockedPairIds(profile));
178
- return getUniqueBy(pairs
179
- .map(({ rootId, leafId }) => {
180
- const root = byId.get(rootId);
181
- const leaf = byId.get(leafId);
182
- if (!root || !leaf)
183
- return null;
184
- if (isOneToOneWithBlocked(root, profile, blocked))
185
- return null;
186
- return rootId === leafId ? [root] : [root, leaf];
187
- })
188
- .filter((conversation) => !!conversation), (conversation) => conversation[0].id);
214
+ return mergeOneToOnePreviews(conversationPreviewsFromPairs(pairs, byId, profile, blocked));
189
215
  };
190
216
  /**
191
217
  * Conversation detail: root plus newest capped descendants (lean mapping +
@@ -202,6 +228,106 @@ export const getConversationThread = async (root, authData, { limit = CONTEXT_NO
202
228
  const ordered = newestIds
203
229
  .map((id) => byId.get(id))
204
230
  .filter((post) => !!post)
205
- .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
231
+ .sort(byIdAsc);
206
232
  return [root, ...ordered.filter((post) => post.id !== root.id)];
207
233
  };
234
+ /**
235
+ * Non-deleted direct post whose participants (audience ∪ creator) are
236
+ * exactly the pair — tolerates legacy rows where the creator is not in the
237
+ * audience edge set.
238
+ */
239
+ const oneToOnePairPost = (profileAId, profileBId) => sql `
240
+ p.visibility = 'direct'
241
+ AND p.deleted_at IS NULL
242
+ AND NOT EXISTS (
243
+ SELECT 1 FROM audience a
244
+ WHERE a.from_id = p.id::text
245
+ AND a.to_id <> ${profileAId}
246
+ AND a.to_id <> ${profileBId}
247
+ )
248
+ AND (p.creator_id = ${profileAId} OR EXISTS (
249
+ SELECT 1 FROM audience a
250
+ WHERE a.from_id = p.id::text AND a.to_id = ${profileAId}
251
+ ))
252
+ AND (p.creator_id = ${profileBId} OR EXISTS (
253
+ SELECT 1 FROM audience a
254
+ WHERE a.from_id = p.id::text AND a.to_id = ${profileBId}
255
+ ))
256
+ `;
257
+ /**
258
+ * All post ids in the 1:1 conversation between two profiles, oldest first:
259
+ * every post of the pair, plus their reply descendants (e.g. system "left"
260
+ * posts, whose participants are only the remaining participant and which
261
+ * are reachable as descendants only). Ids are uuidv7, so ordering is
262
+ * chronological.
263
+ */
264
+ export const listOneToOneConversationPostIds = async (db, profileAId, profileBId) => {
265
+ const result = (await db.execute(sql `
266
+ WITH RECURSIVE start AS (
267
+ SELECT p.id::text AS id
268
+ FROM posts p
269
+ WHERE ${oneToOnePairPost(profileAId, profileBId)}
270
+ ),
271
+ walk AS (
272
+ SELECT id FROM start
273
+ UNION ALL
274
+ SELECT rt.from_id::text
275
+ FROM reply_to rt
276
+ INNER JOIN walk ON rt.to_id = walk.id
277
+ )
278
+ SELECT DISTINCT id FROM walk
279
+ ORDER BY id
280
+ `));
281
+ return result.rows.map((row) => row.id);
282
+ };
283
+ /**
284
+ * Per root of a 1:1 conversation: the root id and that thread's newest post
285
+ * (leaf). Used to terminate every root's thread on leave.
286
+ */
287
+ export const listOneToOneConversationRootLeaves = async (db, profileAId, profileBId) => {
288
+ const result = (await db.execute(sql `
289
+ WITH RECURSIVE start AS (
290
+ SELECT p.id::text AS root_id, p.id::text AS node_id
291
+ FROM posts p
292
+ WHERE ${oneToOnePairPost(profileAId, profileBId)}
293
+ AND NOT EXISTS (
294
+ SELECT 1 FROM reply_to rt
295
+ WHERE rt.from_id = p.id::text
296
+ )
297
+ ),
298
+ walk AS (
299
+ SELECT root_id, node_id FROM start
300
+ UNION ALL
301
+ SELECT walk.root_id, rt.from_id::text
302
+ FROM reply_to rt
303
+ INNER JOIN walk ON rt.to_id = walk.node_id
304
+ )
305
+ SELECT DISTINCT ON (root_id) root_id, node_id AS leaf_id
306
+ FROM walk
307
+ ORDER BY root_id, node_id DESC
308
+ `));
309
+ return result.rows.map((row) => ({
310
+ rootId: row.root_id,
311
+ leafId: row.leaf_id,
312
+ }));
313
+ };
314
+ /**
315
+ * Merged 1:1 conversation: every message for the pair across all roots,
316
+ * oldest first. Any post of the conversation (typically the root in the URL)
317
+ * resolves to the same list. Capped like {@link getConversationThread}:
318
+ * the oldest message plus the newest CONTEXT_NODE_CAP others.
319
+ */
320
+ export const getOneToOneConversation = async (post, authData) => {
321
+ const { db } = await allpeepDb();
322
+ const [profileAId, profileBId] = [...participantIds(post)];
323
+ const ids = await listOneToOneConversationPostIds(db, profileAId, profileBId);
324
+ if (ids.length === 0)
325
+ return [];
326
+ const capped = ids.length > CONTEXT_NODE_CAP + 1
327
+ ? [ids[0], ...ids.slice(-CONTEXT_NODE_CAP)]
328
+ : ids;
329
+ const byId = await hydrateLeanPostsByIds(authData, [...new Set(capped)]);
330
+ return capped
331
+ .map((id) => byId.get(id))
332
+ .filter((message) => !!message);
333
+ };
@@ -135,6 +135,7 @@ export declare const baseEventsFeed: (profile?: ProfileWithMeta) => Mapping<{
135
135
  image?: string | undefined;
136
136
  end?: string | undefined;
137
137
  maxAttendees?: number | undefined;
138
+ waitlistOfferMinutes?: number | undefined;
138
139
  attendeeListPublic?: boolean | undefined;
139
140
  moderators?: string[] | undefined;
140
141
  jam?: {
@@ -361,7 +362,15 @@ export declare const listPastGroupEventsFeed: (authData: AuthorizationData, grou
361
362
  }) => Promise<PostWithMeta[]>;
362
363
  export declare const reposts: (post: PostWithMeta, authData: AuthorizationData) => Promise<PostWithMeta[]>;
363
364
  export declare const getConversationByEnd: (post: PostWithMeta, authData: AuthorizationData) => Promise<PostWithMeta[]>;
365
+ /**
366
+ * 1:1 conversations can span several roots (new messages to the same person,
367
+ * federated posts): answer with the merged conversation across all roots so
368
+ * any root — or even the system "left" post — of the pair resolves to the
369
+ * same view. Group conversations stay per root.
370
+ */
364
371
  export declare const getConversationByStart: (post: PostWithMeta, authData: AuthorizationData) => Promise<PostWithMeta[]>;
372
+ /** Newest post across all roots of a 1:1 conversation (uuidv7-ordered). */
373
+ export declare const findLatestOneToOnePostId: (post: PostWithMeta) => Promise<string>;
365
374
  /** Full ancestor/descendant trees for post detail (CTE + lean mapping). */
366
375
  export declare const getPostContext: (post: PostWithMeta, authData: AuthorizationData) => Promise<{
367
376
  ancestors: PostWithMeta[];
@@ -1,5 +1,5 @@
1
1
  import { parseFeedFormat } from '@openpeepshq/common';
2
- import { blockedPairIds, isBlockedPair } from '@openpeepshq/common/lib';
2
+ import { blockedPairIds, isBlockedPair, isOneToOneDm, participantIds, } from '@openpeepshq/common/lib';
3
3
  import { allpeepDb, collectionInfos } from '../db/index.js';
4
4
  import { edgeFilters, postFilters } from '../db/pg/filters/index.js';
5
5
  import { contextRelation, conversationLeavesMappingForProfile, postContextMappingForProfile, postsAuthMapping, postsMappingForProfile, repostsOfPostRelationForProfile, postIdsMapping, } from './mapping.js';
@@ -13,7 +13,7 @@ import { profilesMapping } from '../profiles/mapping.js';
13
13
  import { CONTEXT_NODE_CAP, loadReplyContextPosts } from './contextClosure.js';
14
14
  import { withSpan } from '../performance/index.js';
15
15
  import { queryUnseenPostCounts } from './unseenCounts.js';
16
- import { getConversationThread } from './conversationQueries.js';
16
+ import { getConversationThread, getOneToOneConversation, listOneToOneConversationPostIds, } from './conversationQueries.js';
17
17
  import { fetchRowsByIds, hydrateMapData } from '../db/pg/map/relations.js';
18
18
  import { listEventAgenda } from './eventAgenda.js';
19
19
  /**
@@ -285,7 +285,27 @@ export const listPastGroupEventsFeed = async (authData, groupId, { offset, limit
285
285
  };
286
286
  export const reposts = async (post, authData) => toFilteredPostsList(postsMappingForProfile(authData.profile).relationsFrom(post, repostsOfPostRelationForProfile(authData.profile)), { authData });
287
287
  export const getConversationByEnd = async (post, authData) => ancestors(authData, post, 9999, sortOldestFirst(postsMappingForProfile(authData.profile))).then((conversation) => [...conversation, post]);
288
- export const getConversationByStart = async (post, authData) => getConversationThread(post, authData);
288
+ /**
289
+ * 1:1 conversations can span several roots (new messages to the same person,
290
+ * federated posts): answer with the merged conversation across all roots so
291
+ * any root — or even the system "left" post — of the pair resolves to the
292
+ * same view. Group conversations stay per root.
293
+ */
294
+ export const getConversationByStart = async (post, authData) => {
295
+ if (isOneToOneDm(post)) {
296
+ const conversation = await getOneToOneConversation(post, authData);
297
+ if (conversation.length > 0)
298
+ return conversation;
299
+ }
300
+ return getConversationThread(post, authData);
301
+ };
302
+ /** Newest post across all roots of a 1:1 conversation (uuidv7-ordered). */
303
+ export const findLatestOneToOnePostId = async (post) => {
304
+ const { db } = await allpeepDb();
305
+ const [profileAId, profileBId] = [...participantIds(post)];
306
+ const ids = await listOneToOneConversationPostIds(db, profileAId, profileBId);
307
+ return ids[ids.length - 1] ?? post.id;
308
+ };
289
309
  /** Full ancestor/descendant trees for post detail (CTE + lean mapping). */
290
310
  export const getPostContext = async (post, authData) => {
291
311
  const mapping = sortOldestFirst(postContextMappingForProfile(authData.profile));