@openpeepshq/core 0.1.31 → 0.1.32

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 (69) hide show
  1. package/dist/analytics/clicks.d.ts +20 -0
  2. package/dist/analytics/clicks.js +194 -0
  3. package/dist/analytics/index.d.ts +1 -0
  4. package/dist/analytics/index.js +1 -0
  5. package/dist/analytics/metrics.d.ts +1 -0
  6. package/dist/analytics/metrics.js +5 -0
  7. package/dist/analytics/pdfReport.js +2 -1
  8. package/dist/analytics/read.js +51 -6
  9. package/dist/analytics/report.d.ts +31 -0
  10. package/dist/backups/index.js +7 -2
  11. package/dist/config/defaults/core.js +1 -0
  12. package/dist/config/index.d.ts +10 -0
  13. package/dist/db/pg/queries/derived.d.ts +5 -0
  14. package/dist/db/pg/queries/derived.js +21 -0
  15. package/dist/db/pg/schema/analytics.d.ts +76 -0
  16. package/dist/db/pg/schema/analytics.js +11 -1
  17. package/dist/db/pg/schema/edges.js +1 -1
  18. package/dist/db/pg/schema/index.d.ts +75 -0
  19. package/dist/db/pg/sql/0005_open_power_man.sql +9 -0
  20. package/dist/db/pg/sql/0006_fine_trish_tilby.sql +8 -0
  21. package/dist/db/pg/sql/meta/0004_snapshot.json +1 -1
  22. package/dist/db/pg/sql/meta/0005_snapshot.json +4179 -0
  23. package/dist/db/pg/sql/meta/0006_snapshot.json +4200 -0
  24. package/dist/db/pg/sql/meta/_journal.json +14 -0
  25. package/dist/db/replaceOrigin.d.ts +11 -0
  26. package/dist/db/replaceOrigin.js +110 -0
  27. package/dist/jams/helpers.d.ts +4 -4
  28. package/dist/jams/index.js +5 -1
  29. package/dist/jams/waitingRoom.d.ts +2 -0
  30. package/dist/jams/waitingRoom.js +13 -5
  31. package/dist/notifications/jobs.js +13 -2
  32. package/dist/plugins/helpers.d.ts +5 -2
  33. package/dist/plugins/helpers.js +21 -2
  34. package/dist/plugins/index.d.ts +1 -1
  35. package/dist/plugins/index.js +14 -10
  36. package/dist/posts/contextClosure.d.ts +2 -1
  37. package/dist/posts/contextClosure.js +6 -1
  38. package/dist/posts/conversationQueries.d.ts +23 -0
  39. package/dist/posts/conversationQueries.js +135 -0
  40. package/dist/posts/finders.d.ts +7 -5
  41. package/dist/posts/finders.js +24 -21
  42. package/dist/posts/helpers/index.d.ts +18 -18
  43. package/dist/posts/helpers/index.js +2 -2
  44. package/dist/posts/index.d.ts +1 -0
  45. package/dist/posts/index.js +1 -0
  46. package/dist/posts/mapping.d.ts +179 -0
  47. package/dist/posts/mapping.js +6 -6
  48. package/dist/posts/mutations.d.ts +3 -1
  49. package/dist/posts/mutations.js +27 -5
  50. package/dist/posts/unseenCounts.d.ts +10 -0
  51. package/dist/posts/unseenCounts.js +81 -0
  52. package/dist/profiles/cache.d.ts +2 -0
  53. package/dist/profiles/cache.js +19 -1
  54. package/dist/profiles/index.d.ts +1 -0
  55. package/dist/profiles/index.js +1 -0
  56. package/dist/profiles/mapping.d.ts +41 -0
  57. package/dist/profiles/mapping.js +24 -0
  58. package/dist/reports/helpers.js +2 -1
  59. package/dist/reports/mapping.js +6 -2
  60. package/dist/roles/mutations.d.ts +3 -3
  61. package/dist/roles/mutations.js +5 -3
  62. package/dist/server/index.d.ts +8 -0
  63. package/dist/session/index.d.ts +28 -0
  64. package/dist/session/index.js +79 -0
  65. package/dist/stats/finders.d.ts +220 -220
  66. package/dist/stats/mapping.d.ts +5 -5
  67. package/package.json +6 -6
  68. package/dist/db/replaceHostname.d.ts +0 -1
  69. package/dist/db/replaceHostname.js +0 -88
@@ -36,6 +36,20 @@
36
36
  "when": 1785770303150,
37
37
  "tag": "0004_analytics",
38
38
  "breakpoints": true
39
+ },
40
+ {
41
+ "idx": 5,
42
+ "version": "7",
43
+ "when": 1786638408097,
44
+ "tag": "0005_open_power_man",
45
+ "breakpoints": true
46
+ },
47
+ {
48
+ "idx": 6,
49
+ "version": "7",
50
+ "when": 1787042540973,
51
+ "tag": "0006_fine_trish_tilby",
52
+ "breakpoints": true
39
53
  }
40
54
  ]
41
55
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Recursively rewrite every absolute http(s) URL under `value` whose hostname
3
+ * matches `oldHostname` so it points at `newOrigin`. Pure — exported for tests.
4
+ */
5
+ export declare const replaceOriginInValue: (value: unknown, oldHostname: string, newOrigin: string) => unknown;
6
+ /**
7
+ * After a restore, repoint stored absolute URLs from the backup's origin to the
8
+ * current server. `oldHostname` comes from the backup metadata; `newOrigin` is
9
+ * this server's `serverRootUrl()` (scheme + host + port).
10
+ */
11
+ export declare const replaceOrigin: (oldHostname?: string, newOrigin?: string) => Promise<void>;
@@ -0,0 +1,110 @@
1
+ import { eq } from 'drizzle-orm';
2
+ import { logger } from '../log/index.js';
3
+ import { pgDb } from './pg/client.js';
4
+ import { asTable, getTableForCollection } from './pg/map/registry.js';
5
+ const log = logger('db:replaceOrigin');
6
+ const hostnameCollections = [
7
+ 'configs',
8
+ 'entries',
9
+ 'jamEvents',
10
+ 'mediaAttachments',
11
+ 'profiles',
12
+ ];
13
+ const absoluteHttpUrlPattern = /https?:\/\/[^\s"'<>`]+/g;
14
+ /**
15
+ * Rewrite the origin (scheme + host + port) of a single URL when its hostname
16
+ * matches the backup's origin. Matching by hostname — rather than the full
17
+ * origin — lets a backup taken on `https://community.example` restore onto a
18
+ * `http://localhost:5174` dev server: the old scheme/port are dropped and the
19
+ * current server's origin takes their place. Path, query, hash, and any
20
+ * userinfo are preserved verbatim (no URL normalization).
21
+ */
22
+ const replaceOriginInUrl = (urlValue, oldHostname, newOrigin) => {
23
+ try {
24
+ const url = new URL(urlValue);
25
+ if (!['http:', 'https:'].includes(url.protocol) ||
26
+ url.hostname !== oldHostname) {
27
+ return urlValue;
28
+ }
29
+ const authorityStart = urlValue.indexOf('://') + 3;
30
+ const afterAuthority = urlValue.slice(authorityStart).search(/[/?#]/);
31
+ const authorityEnd = afterAuthority === -1 ? urlValue.length : authorityStart + afterAuthority;
32
+ const authority = urlValue.slice(authorityStart, authorityEnd);
33
+ const userinfo = authority.slice(0, authority.lastIndexOf('@') + 1);
34
+ const rest = urlValue.slice(authorityEnd);
35
+ const newOriginTrimmed = newOrigin.replace(/\/+$/, '');
36
+ if (userinfo) {
37
+ const newAuthorityStart = newOriginTrimmed.indexOf('://') + 3;
38
+ return (newOriginTrimmed.slice(0, newAuthorityStart) +
39
+ userinfo +
40
+ newOriginTrimmed.slice(newAuthorityStart) +
41
+ rest);
42
+ }
43
+ return newOriginTrimmed + rest;
44
+ }
45
+ catch (_a) {
46
+ return urlValue;
47
+ }
48
+ };
49
+ const replaceOriginInString = (value, oldHostname, newOrigin) => value.replace(absoluteHttpUrlPattern, (urlValue) => replaceOriginInUrl(urlValue, oldHostname, newOrigin));
50
+ /**
51
+ * Recursively rewrite every absolute http(s) URL under `value` whose hostname
52
+ * matches `oldHostname` so it points at `newOrigin`. Pure — exported for tests.
53
+ */
54
+ export const replaceOriginInValue = (value, oldHostname, newOrigin) => {
55
+ if (typeof value === 'string') {
56
+ return replaceOriginInString(value, oldHostname, newOrigin);
57
+ }
58
+ if (Array.isArray(value)) {
59
+ return value.map((item) => replaceOriginInValue(item, oldHostname, newOrigin));
60
+ }
61
+ if (value && typeof value === 'object') {
62
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
63
+ key,
64
+ replaceOriginInValue(item, oldHostname, newOrigin),
65
+ ]));
66
+ }
67
+ return value;
68
+ };
69
+ /**
70
+ * After a restore, repoint stored absolute URLs from the backup's origin to the
71
+ * current server. `oldHostname` comes from the backup metadata; `newOrigin` is
72
+ * this server's `serverRootUrl()` (scheme + host + port).
73
+ */
74
+ export const replaceOrigin = async (oldHostname, newOrigin) => {
75
+ if (!oldHostname || !newOrigin) {
76
+ log.info('No origin to replace');
77
+ return;
78
+ }
79
+ log.info(`Repointing restored URLs from ${oldHostname} to ${newOrigin}`);
80
+ const db = pgDb();
81
+ for (const collectionName of hostnameCollections) {
82
+ const table = getTableForCollection(collectionName);
83
+ const rows = await db.select().from(table);
84
+ let replacedCount = 0;
85
+ for (const row of rows) {
86
+ const current = row;
87
+ const updated = replaceOriginInValue(current, oldHostname, newOrigin);
88
+ if (JSON.stringify(current) === JSON.stringify(updated)) {
89
+ continue;
90
+ }
91
+ const t = asTable(table);
92
+ if (collectionName === 'configs') {
93
+ await db
94
+ .update(table)
95
+ .set(updated)
96
+ .where(eq(t.key, current.key));
97
+ }
98
+ else {
99
+ await db
100
+ .update(table)
101
+ .set(updated)
102
+ .where(eq(t.id, current.id));
103
+ }
104
+ replacedCount += 1;
105
+ }
106
+ if (replacedCount > 0) {
107
+ log.info(`Repointed URLs in ${replacedCount} ${collectionName} row(s)`);
108
+ }
109
+ }
110
+ };
@@ -1,6 +1,6 @@
1
1
  import { JamRecording, JamRecordingWithMeta, PostWithMeta, ProfileWithMeta } from '@openpeepshq/common/types';
2
2
  export declare const connectRecording: (db: import("../db").PgDb, from: ProfileWithMeta, to: PostWithMeta, data?: {
3
- status: "active" | "completed" | "failed" | "requested";
3
+ status: "completed" | "failed" | "active" | "requested";
4
4
  egressId?: string | undefined;
5
5
  attachment?: {
6
6
  type: string;
@@ -22,7 +22,7 @@ export declare const connectRecording: (db: import("../db").PgDb, from: ProfileW
22
22
  updatedAt: string;
23
23
  description?: string | undefined;
24
24
  blurhash?: string | undefined;
25
- status?: "ready" | "failed" | "processing" | undefined;
25
+ status?: "failed" | "processing" | "ready" | undefined;
26
26
  error?: string | undefined;
27
27
  deletedAt?: string | null | undefined;
28
28
  } | undefined;
@@ -30,7 +30,7 @@ export declare const connectRecording: (db: import("../db").PgDb, from: ProfileW
30
30
  } & {
31
31
  id?: string;
32
32
  }) => Promise<import("../db/pg/map").WithId<{
33
- status: "active" | "completed" | "failed" | "requested";
33
+ status: "completed" | "failed" | "active" | "requested";
34
34
  egressId?: string | undefined;
35
35
  attachment?: {
36
36
  type: string;
@@ -52,7 +52,7 @@ export declare const connectRecording: (db: import("../db").PgDb, from: ProfileW
52
52
  updatedAt: string;
53
53
  description?: string | undefined;
54
54
  blurhash?: string | undefined;
55
- status?: "ready" | "failed" | "processing" | undefined;
55
+ status?: "failed" | "processing" | "ready" | undefined;
56
56
  error?: string | undefined;
57
57
  deletedAt?: string | null | undefined;
58
58
  } | undefined;
@@ -3,6 +3,7 @@ import { jamStateCache, LIVE_JAMS_CACHE_KEY, liveJamPostsCache } from './cache.j
3
3
  import { localInstanceDomain, parseRoomInstanceDomain } from './helpers.js';
4
4
  import { findPost } from '../posts/index.js';
5
5
  import { createJamEvent } from './mutations.js';
6
+ import { clearJamAdmittance } from './waitingRoom.js';
6
7
  import { uuidv7 } from 'uuidv7';
7
8
  import { canReadPost } from '../posts/helpers/index.js';
8
9
  import { capabilitiesConfig } from '../config/index.js';
@@ -86,7 +87,10 @@ export const closeJam = async (profile, jamEvent) => {
86
87
  }
87
88
  await stopRecording(jamEvent);
88
89
  return rs.deleteRoom(jamEvent.id).then(async () => {
89
- await invalidateJamCaches(jamEvent.id);
90
+ await Promise.all([
91
+ invalidateJamCaches(jamEvent.id),
92
+ clearJamAdmittance(jamEvent).catch(() => undefined),
93
+ ]);
90
94
  return createJamEvent({
91
95
  id: uuidv7(),
92
96
  jamId: jamEvent.id,
@@ -1,4 +1,6 @@
1
1
  import { type PublicProfile, type PostWithMeta } from '@openpeepshq/common/types';
2
+ export declare const isAdmittedToJam: (event: PostWithMeta, profileId: string) => Promise<boolean>;
3
+ export declare const clearJamAdmittance: (event: PostWithMeta) => Promise<void>;
2
4
  export declare const currentWaitingRoomWatch: (jamEvent: PostWithMeta, onChange: (waitingRoom: Record<string, PublicProfile>) => void | Promise<void>) => Promise<() => Promise<void>>;
3
5
  export declare const admittanceWatch: (jamEvent: PostWithMeta, profileId: string, onToken: (token: string) => Promise<void> | void) => Promise<() => Promise<void>>;
4
6
  export declare const joinWaitingRoom: (event: PostWithMeta, profile: PublicProfile) => Promise<void>;
@@ -3,6 +3,8 @@ import { assertJamRsvpAllowed, createJamToken } from './token.js';
3
3
  import { disconnect, getConnection, getSharedConnection, } from '../redis/connection.js';
4
4
  const waitingRoomKey = (event) => `jams:waiting-room:${event.id}`;
5
5
  const admittanceKey = (event) => `jams:admitted:${event.id}`;
6
+ /** Keep admissions around for the length of a long jam / mobile backgrounding. */
7
+ const ADMITTANCE_TTL_SEC = 12 * 60 * 60;
6
8
  const currentWaitingRoom = (event) => getSharedConnection()
7
9
  .then((conn) => conn.hGetAll(waitingRoomKey(event)))
8
10
  .then((wrRaw) => Object.entries(wrRaw))
@@ -13,6 +15,13 @@ const currentWaitingRoom = (event) => getSharedConnection()
13
15
  ]))
14
16
  .then((entries) => Object.fromEntries(entries));
15
17
  const currentAdmittance = (event) => getSharedConnection().then((conn) => conn.hGetAll(admittanceKey(event)));
18
+ export const isAdmittedToJam = async (event, profileId) => {
19
+ const conn = await getSharedConnection();
20
+ return Boolean(await conn.hExists(admittanceKey(event), profileId));
21
+ };
22
+ export const clearJamAdmittance = async (event) => {
23
+ await getSharedConnection().then((conn) => conn.del(admittanceKey(event)));
24
+ };
16
25
  export const currentWaitingRoomWatch = (jamEvent, onChange) => currentWaitingRoom(jamEvent)
17
26
  .then(onChange)
18
27
  .then(() => getConnection())
@@ -47,12 +56,10 @@ export const admittanceWatch = (jamEvent, profileId, onToken) => currentAdmittan
47
56
  export const joinWaitingRoom = async (event, profile) => {
48
57
  assertJamRsvpAllowed(event, profile);
49
58
  const conn = await getSharedConnection();
50
- const multi = conn.multi();
51
59
  const wrKey = waitingRoomKey(event);
52
- const aKey = admittanceKey(event);
53
- multi.hDel(aKey, profile.id);
54
- multi.hSet(wrKey, { [profile.id]: JSON.stringify(profile) });
55
- await multi.exec();
60
+ // Do not clear admittance here — once admitted, the guest may reconnect
61
+ // (mobile idle / tab freeze) without a second moderator approval.
62
+ await conn.hSet(wrKey, { [profile.id]: JSON.stringify(profile) });
56
63
  };
57
64
  export const acceptFromWaitingRoom = async (event, profileId) => {
58
65
  const conn = await getSharedConnection();
@@ -68,4 +75,5 @@ export const acceptFromWaitingRoom = async (event, profileId) => {
68
75
  await conn.hSet(aKey, {
69
76
  [profile.id]: await createJamToken(event, profile),
70
77
  });
78
+ await conn.expire(aKey, ADMITTANCE_TTL_SEC);
71
79
  };
@@ -9,6 +9,7 @@ import { updateNotification } from './mutations.js';
9
9
  import { getNotificationStats } from './finders.js';
10
10
  import { findProfileSettings } from '../profileSettings/index.js';
11
11
  import { logger } from '../log/index.js';
12
+ import { publishSessionEvent } from '../session/index.js';
12
13
  const log = logger('core:notifications:worker');
13
14
  const [notificationQueue, notificationWorker] = queueAndWorker('process-notification', async (job) => {
14
15
  var _a, _b;
@@ -33,6 +34,7 @@ const [notificationQueue, notificationWorker] = queueAndWorker('process-notifica
33
34
  const notificationStats = await getNotificationStats(profile);
34
35
  await logStep(jobLog, log, `Resolved ${accounts.length} account(s) for profile ${profile.id}; ` +
35
36
  `delivery channels: email=${email} push=${push}`);
37
+ let sessionPublished = false;
36
38
  for (const account of accounts) {
37
39
  if (email) {
38
40
  await logStep(jobLog, log, `Queueing email notification to ${account.email}`);
@@ -50,8 +52,17 @@ const [notificationQueue, notificationWorker] = queueAndWorker('process-notifica
50
52
  }
51
53
  if (push) {
52
54
  try {
53
- await doPush(await ((_b = notificationHandlers
54
- .get(notification.type)) === null || _b === void 0 ? void 0 : _b.pushRenderer(notification)), notificationStats, account, jobLog);
55
+ const pushNotification = await ((_b = notificationHandlers
56
+ .get(notification.type)) === null || _b === void 0 ? void 0 : _b.pushRenderer(notification));
57
+ if (pushNotification && !sessionPublished) {
58
+ sessionPublished = true;
59
+ await publishSessionEvent(profile.id, {
60
+ type: 'invalidate',
61
+ notification: pushNotification,
62
+ notificationStats,
63
+ }).catch((error) => logFailure(jobLog, log, `session SSE publish for profile ${profile.id} failed`, error));
64
+ }
65
+ await doPush(pushNotification, notificationStats, account, jobLog);
55
66
  }
56
67
  catch (error) {
57
68
  await logFailure(jobLog, log, `push delivery to account ${account.id} (${account.email}) threw`, error);
@@ -1,3 +1,6 @@
1
1
  import { PackageJson } from 'type-fest';
2
- export declare const sortByDependencies: (pluginInfos: [string, PackageJson][]) => [string, PackageJson][];
3
- export declare const enumeratePluginInfos: (pluginsPath: string) => Promise<[string, PackageJson][]>;
2
+ type PluginInfo = [string, PackageJson, string];
3
+ export declare const sortByDependencies: (pluginInfos: PluginInfo[]) => PluginInfo[];
4
+ export declare const enumeratePluginInfos: (pluginsPath: string) => Promise<PluginInfo[]>;
5
+ export declare const enumerateReferencedPluginInfos: (rootPackageJsonPath: string) => PluginInfo[];
6
+ export {};
@@ -46,8 +46,9 @@ const enumeratePluginsForNamespace = (pluginsPath, namespace) => {
46
46
  .filter((pluginName) => fs.lstatSync(path.join(pluginsPath, namespace, pluginName)).isDirectory())
47
47
  .map((name) => {
48
48
  const key = path.join(namespace, name);
49
- const info = JSON.parse(fs.readFileSync(path.join(path.join(pluginsPath, key), 'package.json'), 'utf-8'));
50
- return [key, info];
49
+ const pluginPath = path.join(pluginsPath, key);
50
+ const info = JSON.parse(fs.readFileSync(path.join(pluginPath, 'package.json'), 'utf-8'));
51
+ return [key, info, pluginPath];
51
52
  })
52
53
  .filter(([key, info]) => {
53
54
  if (isPluginEnabled(info)) {
@@ -70,3 +71,21 @@ export const enumeratePluginInfos = async (pluginsPath) => {
70
71
  return [];
71
72
  }
72
73
  };
74
+ // Plugins outside `plugins/<namespace>/<name>/` (e.g. `examples/*`) are not
75
+ // scanned automatically. They only load when explicitly referenced from the
76
+ // root `package.json`'s `openpeeps.plugins` array (paths relative to the repo
77
+ // root), keeping example/demo plugins opt-in.
78
+ export const enumerateReferencedPluginInfos = (rootPackageJsonPath) => {
79
+ var _a, _b;
80
+ if (!fs.existsSync(rootPackageJsonPath)) {
81
+ return [];
82
+ }
83
+ const rootPackageJson = JSON.parse(fs.readFileSync(rootPackageJsonPath, 'utf-8'));
84
+ const repoRoot = path.dirname(rootPackageJsonPath);
85
+ return ((_b = (_a = rootPackageJson.openpeeps) === null || _a === void 0 ? void 0 : _a.plugins) !== null && _b !== void 0 ? _b : []).map((relativePath) => {
86
+ const pluginPath = path.join(repoRoot, relativePath);
87
+ const key = path.join('examples', path.basename(pluginPath));
88
+ const info = JSON.parse(fs.readFileSync(path.join(pluginPath, 'package.json'), 'utf-8'));
89
+ return [key, info, pluginPath];
90
+ });
91
+ };
@@ -7,4 +7,4 @@ export declare const getPluginManifests: () => Record<string, PluginManifest>;
7
7
  export declare const initializePlugins: () => Promise<{
8
8
  [k: string]: Plugin;
9
9
  } | undefined>;
10
- export declare const sortedPluginInfos: () => Promise<[string, PackageJson][]>;
10
+ export declare const sortedPluginInfos: () => Promise<[string, PackageJson, string][]>;
@@ -1,8 +1,7 @@
1
- import path from 'node:path';
2
1
  import { hub, VALID_EVENT_KEYS } from '../events/index.js';
3
2
  import { defaultConfig, registerConfigSchema } from '../config/index.js';
4
3
  import { pluginManifestSchema } from '@openpeepshq/common';
5
- import { enumeratePluginInfos, sortByDependencies } from './helpers.js';
4
+ import { enumeratePluginInfos, enumerateReferencedPluginInfos, sortByDependencies, } from './helpers.js';
6
5
  import { logger } from '../log/index.js';
7
6
  export * from './pluginAuth.js';
8
7
  const log = logger('core:plugins');
@@ -17,11 +16,10 @@ export const initializePlugins = async () => {
17
16
  if (initialized) {
18
17
  return;
19
18
  }
20
- const { plugins: { path: pluginsPath }, } = await defaultConfig;
21
- const loadPlugin = async (pluginsPath, key, info) => {
19
+ const { plugins: { path: pluginsPath, rootPackageJsonPath }, } = await defaultConfig;
20
+ const loadPlugin = async (key, info, pluginPath) => {
22
21
  var _a;
23
22
  const [namespace, name] = key.split('/');
24
- const pluginPath = path.join(pluginsPath, key);
25
23
  const displayName = typeof ((_a = info === null || info === void 0 ? void 0 : info.config) === null || _a === void 0 ? void 0 : _a.displayName) === 'string'
26
24
  ? info.config.displayName
27
25
  : key;
@@ -71,14 +69,20 @@ export const initializePlugins = async () => {
71
69
  }
72
70
  loadedPlugins.set(key, plugin);
73
71
  };
74
- const sortedInfos = sortByDependencies(await enumeratePluginInfos(pluginsPath));
75
- for (const [key, info] of sortedInfos) {
76
- await loadPlugin(pluginsPath, key, info);
72
+ const sortedInfos = sortByDependencies([
73
+ ...(await enumeratePluginInfos(pluginsPath)),
74
+ ...enumerateReferencedPluginInfos(rootPackageJsonPath),
75
+ ]);
76
+ for (const [key, info, pluginPath] of sortedInfos) {
77
+ await loadPlugin(key, info, pluginPath);
77
78
  }
78
79
  initialized = true;
79
80
  return Object.fromEntries(loadedPlugins.entries());
80
81
  };
81
82
  export const sortedPluginInfos = async () => {
82
- const { plugins: { path: pluginsPath }, } = defaultConfig;
83
- return sortByDependencies(await enumeratePluginInfos(pluginsPath));
83
+ const { plugins: { path: pluginsPath, rootPackageJsonPath }, } = defaultConfig;
84
+ return sortByDependencies([
85
+ ...(await enumeratePluginInfos(pluginsPath)),
86
+ ...enumerateReferencedPluginInfos(rootPackageJsonPath),
87
+ ]);
84
88
  };
@@ -4,9 +4,10 @@ import type { Mapping } from '../db/pg/map';
4
4
  export declare const CONTEXT_NODE_CAP = 100;
5
5
  type ClosureDirection = 'ancestors' | 'descendents';
6
6
  /** Collect reply-graph ids via one recursive CTE (capped). */
7
- export declare const collectReplyClosureIds: (db: PgDb, startId: string, direction: ClosureDirection, { maxDepth, limit, }?: {
7
+ export declare const collectReplyClosureIds: (db: PgDb, startId: string, direction: ClosureDirection, { maxDepth, limit, newestFirst, }?: {
8
8
  maxDepth?: number;
9
9
  limit?: number;
10
+ newestFirst?: boolean;
10
11
  }) => Promise<string[]>;
11
12
  /** Load and hydrate posts in a reply closure, then ACL-filter + transform. */
12
13
  export declare const loadReplyContextPosts: (authData: AuthorizationData, startId: string, direction: ClosureDirection, mapping: Mapping<DbPost>, { maxDepth, limit, }?: {
@@ -6,9 +6,12 @@ import { capabilitiesConfig } from '../config/index.js';
6
6
  import { canReadPost, transformPost } from './helpers/index.js';
7
7
  export const CONTEXT_NODE_CAP = 100;
8
8
  /** Collect reply-graph ids via one recursive CTE (capped). */
9
- export const collectReplyClosureIds = async (db, startId, direction, { maxDepth = 9999, limit = CONTEXT_NODE_CAP, } = {}) => {
9
+ export const collectReplyClosureIds = async (db, startId, direction, { maxDepth = 9999, limit = CONTEXT_NODE_CAP,
10
+ /** Newest-first by uuidv7 id (useful for long DM threads). */
11
+ newestFirst = false, } = {}) => {
10
12
  if (!startId || limit <= 0)
11
13
  return [];
14
+ const orderClause = newestFirst ? sql `ORDER BY id DESC` : sql ``;
12
15
  const query = direction === 'ancestors'
13
16
  ? sql `
14
17
  WITH RECURSIVE t AS (
@@ -22,6 +25,7 @@ export const collectReplyClosureIds = async (db, startId, direction, { maxDepth
22
25
  WHERE t.depth < ${maxDepth}
23
26
  )
24
27
  SELECT id FROM t
28
+ ${orderClause}
25
29
  LIMIT ${limit}
26
30
  `
27
31
  : sql `
@@ -36,6 +40,7 @@ export const collectReplyClosureIds = async (db, startId, direction, { maxDepth
36
40
  WHERE t.depth < ${maxDepth}
37
41
  )
38
42
  SELECT id FROM t
43
+ ${orderClause}
39
44
  LIMIT ${limit}
40
45
  `;
41
46
  const result = (await db.execute(query));
@@ -0,0 +1,23 @@
1
+ import type { AuthorizationData, PostWithMeta } from '@openpeepshq/common/types';
2
+ import type { PgDb } from '../db/pg/client';
3
+ type RootLeafPair = {
4
+ rootId: string;
5
+ leafId: string;
6
+ };
7
+ /** Root + newest leaf per DM thread the profile is in (ids only). */
8
+ export declare const listConversationRootLeafPairs: (db: PgDb, profileId: string) => Promise<RootLeafPair[]>;
9
+ /** Newest post id in a reply thread (root included); uuidv7-ordered. */
10
+ export declare const findLatestThreadPostId: (rootId: string) => Promise<string>;
11
+ /**
12
+ * Inbox list: one preview per conversation as [root, leaf] (or [root] when
13
+ * they are the same). Avoids walking full ancestor chains.
14
+ */
15
+ export declare const listConversationPreviews: (authData: AuthorizationData) => Promise<PostWithMeta[][]>;
16
+ /**
17
+ * Conversation detail: root plus newest capped descendants (lean mapping +
18
+ * seenBatch). Prefer newest messages so long DMs stay usable.
19
+ */
20
+ export declare const getConversationThread: (root: PostWithMeta, authData: AuthorizationData, { limit }?: {
21
+ limit?: number;
22
+ }) => Promise<PostWithMeta[]>;
23
+ export {};
@@ -0,0 +1,135 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { getUniqueBy } from '@openpeepshq/common/lib';
3
+ import { allpeepDb } from '../db/index.js';
4
+ import { fetchRowsByIds, hydrateMapData } from '../db/pg/map/relations.js';
5
+ import { capabilitiesConfig } from '../config/index.js';
6
+ import { canReadPost, transformPost } from './helpers/index.js';
7
+ import { CONTEXT_NODE_CAP, collectReplyClosureIds } from './contextClosure.js';
8
+ import { postContextMappingForProfile } from './mapping.js';
9
+ /** Root + newest leaf per DM thread the profile is in (ids only). */
10
+ export const listConversationRootLeafPairs = async (db, profileId) => {
11
+ const result = (await db.execute(sql `
12
+ WITH RECURSIVE leaves AS (
13
+ SELECT p.id::text AS leaf_id
14
+ FROM audience a
15
+ INNER JOIN posts p
16
+ ON p.id::text = a.from_id
17
+ AND p.deleted_at IS NULL
18
+ WHERE a.to_id = ${profileId}
19
+ AND p.visibility = 'direct'
20
+ AND (
21
+ SELECT count(*)::int
22
+ FROM reply_to rt
23
+ INNER JOIN posts rp
24
+ ON rp.id::text = rt.from_id
25
+ AND rp.deleted_at IS NULL
26
+ WHERE rt.to_id = p.id::text
27
+ ) = 0
28
+ ),
29
+ walk AS (
30
+ SELECT l.leaf_id, l.leaf_id AS node_id, 0 AS depth
31
+ FROM leaves l
32
+ UNION ALL
33
+ SELECT walk.leaf_id, rt.to_id, walk.depth + 1
34
+ FROM reply_to rt
35
+ INNER JOIN walk ON rt.from_id = walk.node_id
36
+ ),
37
+ roots AS (
38
+ SELECT DISTINCT ON (leaf_id) leaf_id, node_id AS root_id
39
+ FROM walk
40
+ ORDER BY leaf_id, depth DESC
41
+ ),
42
+ best AS (
43
+ SELECT DISTINCT ON (root_id) root_id, leaf_id
44
+ FROM roots
45
+ ORDER BY root_id, leaf_id DESC
46
+ )
47
+ SELECT root_id, leaf_id
48
+ FROM best
49
+ ORDER BY leaf_id DESC
50
+ `));
51
+ return result.rows.map((row) => ({
52
+ rootId: row.root_id,
53
+ leafId: row.leaf_id,
54
+ }));
55
+ };
56
+ /** Newest post id in a reply thread (root included); uuidv7-ordered. */
57
+ export const findLatestThreadPostId = async (rootId) => {
58
+ var _a, _b;
59
+ const { db } = await allpeepDb();
60
+ const result = (await db.execute(sql `
61
+ WITH RECURSIVE t AS (
62
+ SELECT ${rootId}::text AS id
63
+ UNION ALL
64
+ SELECT rt.from_id
65
+ FROM reply_to rt
66
+ INNER JOIN t ON rt.to_id = t.id
67
+ INNER JOIN posts p
68
+ ON p.id::text = rt.from_id
69
+ AND p.deleted_at IS NULL
70
+ )
71
+ SELECT id
72
+ FROM t
73
+ ORDER BY id DESC
74
+ LIMIT 1
75
+ `));
76
+ return (_b = (_a = result.rows[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : rootId;
77
+ };
78
+ const hydrateLeanPostsByIds = async (authData, ids) => {
79
+ if (!ids.length)
80
+ return new Map();
81
+ const { db } = await allpeepDb();
82
+ const mapData = postContextMappingForProfile(authData.profile).data();
83
+ const rows = await fetchRowsByIds(db, mapData.collection, ids, mapData.softDelete);
84
+ const hydrated = (await hydrateMapData(db, mapData, rows));
85
+ const config = await capabilitiesConfig();
86
+ const readable = canReadPost(config, authData);
87
+ const byId = new Map();
88
+ for (const post of hydrated) {
89
+ const transformed = await transformPost(post, authData.profile);
90
+ if (readable(transformed))
91
+ byId.set(transformed.id, transformed);
92
+ }
93
+ return byId;
94
+ };
95
+ /**
96
+ * Inbox list: one preview per conversation as [root, leaf] (or [root] when
97
+ * they are the same). Avoids walking full ancestor chains.
98
+ */
99
+ export const listConversationPreviews = async (authData) => {
100
+ const profile = authData.profile;
101
+ if (!profile) {
102
+ throw new Error('AuthorizationData.profile is required for this finder');
103
+ }
104
+ const { db } = await allpeepDb();
105
+ const pairs = await listConversationRootLeafPairs(db, profile.id);
106
+ const ids = [...new Set(pairs.flatMap((pair) => [pair.rootId, pair.leafId]))];
107
+ const byId = await hydrateLeanPostsByIds(authData, ids);
108
+ return getUniqueBy(pairs
109
+ .map(({ rootId, leafId }) => {
110
+ const root = byId.get(rootId);
111
+ const leaf = byId.get(leafId);
112
+ if (!root || !leaf)
113
+ return null;
114
+ return rootId === leafId ? [root] : [root, leaf];
115
+ })
116
+ .filter((conversation) => !!conversation), (conversation) => conversation[0].id);
117
+ };
118
+ /**
119
+ * Conversation detail: root plus newest capped descendants (lean mapping +
120
+ * seenBatch). Prefer newest messages so long DMs stay usable.
121
+ */
122
+ export const getConversationThread = async (root, authData, { limit = CONTEXT_NODE_CAP } = {}) => {
123
+ const { db } = await allpeepDb();
124
+ const newestIds = await collectReplyClosureIds(db, root.id, 'descendents', {
125
+ maxDepth: 9999,
126
+ limit,
127
+ newestFirst: true,
128
+ });
129
+ const byId = await hydrateLeanPostsByIds(authData, newestIds);
130
+ const ordered = newestIds
131
+ .map((id) => byId.get(id))
132
+ .filter((post) => !!post)
133
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
134
+ return [root, ...ordered.filter((post) => post.id !== root.id)];
135
+ };
@@ -2,6 +2,8 @@ import { AuthorizationData, PostWithMeta, Post, PostType, Profile, DbPost, DbBas
2
2
  import { ProfileWithMeta } from '@openpeepshq/common/types';
3
3
  import type { Mapping, ObjectSort, PgFilter } from '../db/pg/map';
4
4
  export declare const findPost: (id: string, authData?: AuthorizationData) => Promise<PostWithMeta | undefined>;
5
+ /** Lean post load for capability checks (no nested reply/repost). */
6
+ export declare const findPostsForAuth: (ids: string[], authData?: AuthorizationData) => Promise<PostWithMeta[]>;
5
7
  export declare const postContext: (authData: AuthorizationData, id: string, depth: number, direction: "ancestors" | "descendents", contextMapping?: Mapping<DbPost>) => Promise<PostWithMeta[]>;
6
8
  export declare const descendents: (authData: AuthorizationData, post: PostWithMeta, depth: number, contextMapping?: Mapping<DbPost>) => Promise<PostWithMeta[]>;
7
9
  export declare const ancestors: (authData: AuthorizationData, post: PostWithMeta, depth: number, contextMapping?: Mapping<DbPost>) => Promise<PostWithMeta[]>;
@@ -17,7 +19,7 @@ export declare const baseFeed: ({ start, sort, profile, }: {
17
19
  }) => Mapping<DbPost>;
18
20
  export declare const baseEventsFeed: (profile?: ProfileWithMeta) => Mapping<{
19
21
  type: "note" | "question" | "event" | "article";
20
- visibility: "direct" | "group" | "local" | "report" | "public" | "unlisted" | "private";
22
+ visibility: "local" | "group" | "report" | "public" | "unlisted" | "private" | "direct";
21
23
  creatorId: string;
22
24
  capabilitiesNeeded?: string[] | undefined;
23
25
  data?: {
@@ -42,7 +44,7 @@ export declare const baseEventsFeed: (profile?: ProfileWithMeta) => Mapping<{
42
44
  };
43
45
  description?: string | undefined;
44
46
  blurhash?: string | undefined;
45
- status?: "ready" | "failed" | "processing" | undefined;
47
+ status?: "failed" | "processing" | "ready" | undefined;
46
48
  error?: string | undefined;
47
49
  }[] | undefined;
48
50
  customEmojis?: {
@@ -79,7 +81,7 @@ export declare const baseEventsFeed: (profile?: ProfileWithMeta) => Mapping<{
79
81
  };
80
82
  description?: string | undefined;
81
83
  blurhash?: string | undefined;
82
- status?: "ready" | "failed" | "processing" | undefined;
84
+ status?: "failed" | "processing" | "ready" | undefined;
83
85
  error?: string | undefined;
84
86
  }[] | undefined;
85
87
  customEmojis?: {
@@ -117,7 +119,7 @@ export declare const baseEventsFeed: (profile?: ProfileWithMeta) => Mapping<{
117
119
  };
118
120
  description?: string | undefined;
119
121
  blurhash?: string | undefined;
120
- status?: "ready" | "failed" | "processing" | undefined;
122
+ status?: "failed" | "processing" | "ready" | undefined;
121
123
  error?: string | undefined;
122
124
  }[] | undefined;
123
125
  customEmojis?: {
@@ -178,7 +180,7 @@ export declare const baseEventsFeed: (profile?: ProfileWithMeta) => Mapping<{
178
180
  };
179
181
  description?: string | undefined;
180
182
  blurhash?: string | undefined;
181
- status?: "ready" | "failed" | "processing" | undefined;
183
+ status?: "failed" | "processing" | "ready" | undefined;
182
184
  error?: string | undefined;
183
185
  }[] | undefined;
184
186
  customEmojis?: {