@openpeepshq/core 0.1.31 → 0.1.33

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 (167) hide show
  1. package/dist/accessTokens/helpers.d.ts +2 -2
  2. package/dist/accessTokens/tokens.js +14 -7
  3. package/dist/accounts/mutations.d.ts +2 -2
  4. package/dist/analytics/cache.js +12 -7
  5. package/dist/analytics/clicks.d.ts +20 -0
  6. package/dist/analytics/clicks.js +194 -0
  7. package/dist/analytics/index.d.ts +1 -0
  8. package/dist/analytics/index.js +1 -0
  9. package/dist/analytics/metrics.d.ts +1 -0
  10. package/dist/analytics/metrics.js +5 -0
  11. package/dist/analytics/pdfReport.d.ts +1 -0
  12. package/dist/analytics/pdfReport.js +7 -5
  13. package/dist/analytics/privacy.d.ts +18 -0
  14. package/dist/analytics/privacy.js +10 -0
  15. package/dist/analytics/read.js +74 -16
  16. package/dist/analytics/report.d.ts +32 -1
  17. package/dist/analytics/report.js +9 -2
  18. package/dist/backups/index.js +13 -5
  19. package/dist/backups/metadata.d.ts +7 -0
  20. package/dist/config/defaults/community.js +0 -6
  21. package/dist/config/defaults/core.js +1 -0
  22. package/dist/config/defaults/db.d.ts +0 -2
  23. package/dist/config/defaults/db.js +0 -2
  24. package/dist/config/index.d.ts +20 -9
  25. package/dist/db/helpers.d.ts +6 -28
  26. package/dist/db/helpers.js +19 -149
  27. package/dist/db/index.d.ts +2 -0
  28. package/dist/db/index.js +4 -0
  29. package/dist/db/init.js +3 -2
  30. package/dist/db/migration/detect.d.ts +0 -3
  31. package/dist/db/migration/detect.js +0 -54
  32. package/dist/db/migration/importCollections.d.ts +1 -1
  33. package/dist/db/migration/importCollections.js +22 -6
  34. package/dist/db/migration/shared.d.ts +0 -4
  35. package/dist/db/migration/shared.js +0 -7
  36. package/dist/db/migration/transform.d.ts +2 -0
  37. package/dist/db/migration/transform.js +23 -0
  38. package/dist/db/pg/client.js +4 -0
  39. package/dist/db/pg/filters/edges.d.ts +1 -1
  40. package/dist/db/pg/filters/edges.js +1 -1
  41. package/dist/db/pg/filters/posts.d.ts +1 -0
  42. package/dist/db/pg/filters/posts.js +11 -1
  43. package/dist/db/pg/map/filters.js +5 -0
  44. package/dist/db/pg/map/relations.d.ts +1 -1
  45. package/dist/db/pg/map/relations.js +89 -41
  46. package/dist/db/pg/migrate.d.ts +23 -0
  47. package/dist/db/pg/migrate.js +87 -1
  48. package/dist/db/pg/queries/derived.d.ts +5 -0
  49. package/dist/db/pg/queries/derived.js +21 -0
  50. package/dist/db/pg/schema/analytics.d.ts +76 -0
  51. package/dist/db/pg/schema/analytics.js +11 -1
  52. package/dist/db/pg/schema/documents.d.ts +143 -0
  53. package/dist/db/pg/schema/documents.js +22 -1
  54. package/dist/db/pg/schema/edges.d.ts +1 -0
  55. package/dist/db/pg/schema/edges.js +1 -0
  56. package/dist/db/pg/schema/index.d.ts +218 -0
  57. package/dist/db/pg/sql/0005_open_power_man.sql +9 -0
  58. package/dist/db/pg/sql/0006_fine_trish_tilby.sql +8 -0
  59. package/dist/db/pg/sql/0007_shallow_oracle.sql +3 -0
  60. package/dist/db/pg/sql/0008_group_owner_roles.sql +31 -0
  61. package/dist/db/pg/sql/0009_event_occurrences.sql +26 -0
  62. package/dist/db/pg/sql/meta/0004_snapshot.json +1 -1
  63. package/dist/db/pg/sql/meta/0005_snapshot.json +4179 -0
  64. package/dist/db/pg/sql/meta/0006_snapshot.json +4200 -0
  65. package/dist/db/pg/sql/meta/0007_snapshot.json +4179 -0
  66. package/dist/db/pg/sql/meta/0009_snapshot.json +4299 -0
  67. package/dist/db/pg/sql/meta/_journal.json +35 -0
  68. package/dist/db/replaceOrigin.d.ts +11 -0
  69. package/dist/db/replaceOrigin.js +116 -0
  70. package/dist/db/types.d.ts +0 -4
  71. package/dist/events/index.d.ts +2 -1
  72. package/dist/events/index.js +54 -33
  73. package/dist/groups/finders.d.ts +2 -2
  74. package/dist/groups/helpers.d.ts +6 -6
  75. package/dist/groups/mapping.d.ts +4 -4
  76. package/dist/groups/mapping.js +2 -2
  77. package/dist/groups/mutations.js +1 -1
  78. package/dist/inviteLinks/helpers.d.ts +4 -4
  79. package/dist/jams/cache.d.ts +1 -1
  80. package/dist/jams/cache.js +2 -1
  81. package/dist/jams/finders.d.ts +2 -1
  82. package/dist/jams/finders.js +18 -7
  83. package/dist/jams/helpers.d.ts +8 -4
  84. package/dist/jams/index.d.ts +4 -3
  85. package/dist/jams/index.js +23 -12
  86. package/dist/jams/livekit.d.ts +46 -8
  87. package/dist/jams/livekit.js +103 -21
  88. package/dist/jams/mapping.d.ts +14 -4
  89. package/dist/jams/mutations.d.ts +2 -0
  90. package/dist/jams/rtmp.d.ts +5 -0
  91. package/dist/jams/rtmp.js +8 -0
  92. package/dist/jams/token.d.ts +3 -3
  93. package/dist/jams/token.js +15 -12
  94. package/dist/jams/waitingRoom.d.ts +6 -4
  95. package/dist/jams/waitingRoom.js +33 -24
  96. package/dist/migration/index.d.ts +4 -0
  97. package/dist/migration/index.js +4 -0
  98. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +3 -1
  99. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +3 -1
  100. package/dist/notifications/helpers.js +6 -2
  101. package/dist/notifications/jobs.js +13 -2
  102. package/dist/notifications/push.js +11 -4
  103. package/dist/plugins/helpers.d.ts +6 -2
  104. package/dist/plugins/helpers.js +22 -10
  105. package/dist/plugins/index.d.ts +6 -1
  106. package/dist/plugins/index.js +54 -13
  107. package/dist/plugins/install.d.ts +20 -0
  108. package/dist/plugins/install.js +223 -0
  109. package/dist/plugins/state.d.ts +4 -0
  110. package/dist/plugins/state.js +29 -0
  111. package/dist/posts/contextClosure.d.ts +2 -1
  112. package/dist/posts/contextClosure.js +6 -1
  113. package/dist/posts/conversationQueries.d.ts +23 -0
  114. package/dist/posts/conversationQueries.js +135 -0
  115. package/dist/posts/eventAgenda.d.ts +165 -0
  116. package/dist/posts/eventAgenda.js +120 -0
  117. package/dist/posts/eventOccurrenceJobs.d.ts +4 -0
  118. package/dist/posts/eventOccurrenceJobs.js +23 -0
  119. package/dist/posts/eventOccurrences.d.ts +4 -0
  120. package/dist/posts/eventOccurrences.js +40 -0
  121. package/dist/posts/finders.d.ts +39 -13
  122. package/dist/posts/finders.js +51 -66
  123. package/dist/posts/helpers/filters.js +1 -1
  124. package/dist/posts/helpers/index.d.ts +120 -34
  125. package/dist/posts/helpers/index.js +34 -21
  126. package/dist/posts/index.d.ts +4 -0
  127. package/dist/posts/index.js +4 -0
  128. package/dist/posts/mapping.d.ts +454 -0
  129. package/dist/posts/mapping.js +43 -9
  130. package/dist/posts/mutations.d.ts +4 -2
  131. package/dist/posts/mutations.js +49 -16
  132. package/dist/posts/rsvpConfirmationEmail.js +2 -1
  133. package/dist/posts/unseenCounts.d.ts +12 -0
  134. package/dist/posts/unseenCounts.js +98 -0
  135. package/dist/profiles/cache.d.ts +5 -1
  136. package/dist/profiles/cache.js +27 -1
  137. package/dist/profiles/helpers.d.ts +5 -5
  138. package/dist/profiles/index.d.ts +1 -0
  139. package/dist/profiles/index.js +1 -0
  140. package/dist/profiles/mapping.d.ts +45 -4
  141. package/dist/profiles/mapping.js +24 -0
  142. package/dist/profiles/mutations.js +12 -14
  143. package/dist/pushSubscriptions/helpers.d.ts +2 -2
  144. package/dist/pushSubscriptions/mutations.js +13 -1
  145. package/dist/reports/helpers.d.ts +6 -6
  146. package/dist/reports/helpers.js +2 -1
  147. package/dist/reports/mapping.js +6 -2
  148. package/dist/roles/defaults.js +1 -0
  149. package/dist/roles/mutations.d.ts +3 -3
  150. package/dist/roles/mutations.js +5 -3
  151. package/dist/server/index.d.ts +15 -7
  152. package/dist/server/index.js +15 -8
  153. package/dist/session/index.d.ts +28 -0
  154. package/dist/session/index.js +79 -0
  155. package/dist/stats/finders.d.ts +1912 -362
  156. package/dist/stats/mapping.d.ts +26 -5
  157. package/package.json +7 -12
  158. package/dist/db/arango.d.ts +0 -2
  159. package/dist/db/arango.js +0 -110
  160. package/dist/db/migration/autoMigrate.d.ts +0 -2
  161. package/dist/db/migration/autoMigrate.js +0 -111
  162. package/dist/db/migration/cli.d.ts +0 -1
  163. package/dist/db/migration/cli.js +0 -56
  164. package/dist/db/migration/exportArango.d.ts +0 -4
  165. package/dist/db/migration/exportArango.js +0 -80
  166. package/dist/db/replaceHostname.d.ts +0 -1
  167. package/dist/db/replaceHostname.js +0 -88
@@ -1,12 +1,6 @@
1
- import { aql, Database } from 'arangojs';
2
1
  import { getTableName, sql } from 'drizzle-orm';
3
- import { logger } from '../../log/index.js';
4
2
  import { pgDb } from '../pg/client.js';
5
3
  import { getTableForCollection } from '../pg/map/registry.js';
6
- import { connectArango } from './exportArango.js';
7
- import { arangoConfig, DOCUMENT_IMPORT_ORDER, EDGE_IMPORT_ORDER, } from './shared.js';
8
- const log = logger('core:migration:detect');
9
- const ARANGO_SOURCE_COLLECTIONS = ['accounts', 'profiles', 'posts'];
10
4
  const isUndefinedTableError = (err) => {
11
5
  const candidates = [
12
6
  err,
@@ -36,52 +30,4 @@ export const tableCount = async (collection) => {
36
30
  throw err;
37
31
  }
38
32
  };
39
- export const isPostgresEmpty = async () => {
40
- for (const collection of [
41
- ...DOCUMENT_IMPORT_ORDER,
42
- ...EDGE_IMPORT_ORDER,
43
- ]) {
44
- if ((await tableCount(collection)) > 0) {
45
- return false;
46
- }
47
- }
48
- return true;
49
- };
50
33
  export { isUndefinedTableError };
51
- export const isArangoAvailable = async () => {
52
- const config = arangoConfig();
53
- const systemDb = new Database({ url: config.url, databaseName: '_system' });
54
- try {
55
- return Boolean(await systemDb.availability());
56
- }
57
- catch (_a) {
58
- return false;
59
- }
60
- };
61
- export const arangoHasSourceData = async () => {
62
- if (!(await isArangoAvailable())) {
63
- return false;
64
- }
65
- const config = arangoConfig();
66
- if (config.databaseName) {
67
- const systemDb = new Database(Object.assign(Object.assign({}, config), { databaseName: '_system' }));
68
- if (!(await systemDb.database(config.databaseName).exists())) {
69
- log.info('Arango database %s does not exist; skipping auto migration', config.databaseName);
70
- return false;
71
- }
72
- }
73
- const db = connectArango();
74
- for (const collectionName of ARANGO_SOURCE_COLLECTIONS) {
75
- if (!(await db.collection(collectionName).exists())) {
76
- continue;
77
- }
78
- const cursor = await db.query(aql `
79
- RETURN LENGTH(FOR doc IN ${db.collection(collectionName)} LIMIT 1 RETURN 1)
80
- `);
81
- const hasDocuments = (await cursor.next()) === 1;
82
- if (hasDocuments) {
83
- return true;
84
- }
85
- }
86
- return false;
87
- };
@@ -12,7 +12,7 @@ export declare const importAllArangoCollections: (collectionsDir: string) => Pro
12
12
  imported: Record<string, number>;
13
13
  total: number;
14
14
  }>;
15
- export declare const importAllPostgresCollections: (collectionsDir: string) => Promise<{
15
+ export declare const importAllPostgresCollections: (collectionsDir: string, schemaVersionFromBackup?: string) => Promise<{
16
16
  imported: Record<string, number>;
17
17
  total: number;
18
18
  }>;
@@ -5,7 +5,7 @@ import { join } from 'node:path';
5
5
  import { getTableName, sql } from 'drizzle-orm';
6
6
  import { logger } from '../../log/index.js';
7
7
  import { pgDb } from '../pg/client.js';
8
- import { runMigrations } from '../pg/migrate.js';
8
+ import { resetAndMigrateToSchemaVersion, resolveRestoreSchemaVersion, runMigrations, } from '../pg/migrate.js';
9
9
  import { documentRegistry, edgeRegistry, getTableForCollection, } from '../pg/map/registry.js';
10
10
  import { arangoDocToDocumentRow, arangoDocToEdgeRow, buildPostCreatorIdByPostId, isEdgeCollection, normalizeImportId, } from './transform.js';
11
11
  import { BATCH_SIZE, DOCUMENT_IMPORT_ORDER, EDGE_IMPORT_ORDER, readJsonl, } from './shared.js';
@@ -230,27 +230,41 @@ export const importPostgresRowCollection = async (collection, collectionsDir) =>
230
230
  return imported;
231
231
  };
232
232
  const sumImported = (imported) => Object.values(imported).reduce((sum, count) => sum + count, 0);
233
- export const importAllArangoCollections = async (collectionsDir) => {
234
- await runMigrations();
233
+ const prepareSchemaForRestore = async (databaseType, schemaVersionFromBackup) => {
234
+ const schemaVersion = resolveRestoreSchemaVersion(databaseType, schemaVersionFromBackup);
235
+ log.info('Preparing %s restore at schema %s', databaseType, schemaVersion);
236
+ await resetAndMigrateToSchemaVersion(schemaVersion);
237
+ // 0006 added a unique (from_id, to_id) on post_seen; that was wrong for
238
+ // impressions. Drop it before import so pre-0007 backups with duplicate
239
+ // view rows can restore. 0007 (and later) drop it permanently.
240
+ await pgDb().execute(sql.raw('DROP INDEX IF EXISTS "post_seen_from_to_unique"'));
235
241
  await truncateAllTables();
242
+ };
243
+ export const importAllArangoCollections = async (collectionsDir) => {
244
+ await prepareSchemaForRestore('arango');
236
245
  const imported = {};
237
246
  const context = {
238
247
  postCreatorIdByPostId: await buildPostCreatorIdByPostId(collectionsDir),
239
248
  hashtagIdRemap: new Map(),
240
249
  };
250
+ // Skip dataMigrations — Arango-era migration ledger is unused on Postgres.
241
251
  for (const collection of DOCUMENT_IMPORT_ORDER) {
252
+ if (collection === 'dataMigrations') {
253
+ continue;
254
+ }
242
255
  imported[collection] = await importArangoCollection(collection, collectionsDir, context);
243
256
  }
244
257
  for (const collection of EDGE_IMPORT_ORDER) {
245
258
  imported[collection] = await importArangoCollection(collection, collectionsDir, context);
246
259
  }
260
+ log.info('Arango rows loaded; migrating schema forward to latest');
261
+ await runMigrations();
247
262
  const total = sumImported(imported);
248
263
  log.info('Arango JSONL import complete: %d rows across %d collections', total, Object.keys(imported).filter((key) => imported[key] > 0).length);
249
264
  return { imported, total };
250
265
  };
251
- export const importAllPostgresCollections = async (collectionsDir) => {
252
- await runMigrations();
253
- await truncateAllTables();
266
+ export const importAllPostgresCollections = async (collectionsDir, schemaVersionFromBackup) => {
267
+ await prepareSchemaForRestore('postgres', schemaVersionFromBackup);
254
268
  const imported = {};
255
269
  for (const collection of DOCUMENT_IMPORT_ORDER) {
256
270
  imported[collection] = await importPostgresRowCollection(collection, collectionsDir);
@@ -258,6 +272,8 @@ export const importAllPostgresCollections = async (collectionsDir) => {
258
272
  for (const collection of EDGE_IMPORT_ORDER) {
259
273
  imported[collection] = await importPostgresRowCollection(collection, collectionsDir);
260
274
  }
275
+ log.info('Postgres rows loaded; ensuring schema is at latest');
276
+ await runMigrations();
261
277
  const total = sumImported(imported);
262
278
  log.info('Postgres JSONL import complete: %d rows across %d collections', total, Object.keys(imported).filter((key) => imported[key] > 0).length);
263
279
  return { imported, total };
@@ -22,10 +22,6 @@ export type MigrationManifest = {
22
22
  postIds: string;
23
23
  };
24
24
  };
25
- export declare const arangoConfig: () => {
26
- url: string;
27
- databaseName: string | undefined;
28
- };
29
25
  export declare const sha256: (value: string) => string;
30
26
  export declare const sortedChecksum: (values: string[]) => string;
31
27
  export declare const readJsonl: (filePath: string) => Promise<Record<string, unknown>[]>;
@@ -67,13 +67,6 @@ export const EDGE_IMPORT_ORDER = [
67
67
  'inviteLinkRedeemers',
68
68
  'jamRecordings',
69
69
  ];
70
- export const arangoConfig = () => {
71
- var _a;
72
- return ({
73
- url: (_a = process.env.DB_URL) !== null && _a !== void 0 ? _a : 'http://localhost:8529',
74
- databaseName: process.env.DB_NAME,
75
- });
76
- };
77
70
  export const sha256 = (value) => createHash('sha256').update(value).digest('hex');
78
71
  export const sortedChecksum = (values) => sha256(values.filter(Boolean).sort().join('\n'));
79
72
  export const readJsonl = async (filePath) => {
@@ -13,6 +13,8 @@ export declare const buildPostCreatorIdByPostId: (collectionsDir: string) => Pro
13
13
  * later via an Arango-only data migration that never runs on Postgres restores.
14
14
  */
15
15
  export declare const capabilitiesFromLegacyGroupFlags: (data: Record<string, unknown>) => Record<string, unknown> | undefined;
16
+ export declare const normalizeGroupMembershipRoles: (roles: unknown) => unknown;
17
+ export declare const normalizeGroupCapabilityMap: (capabilities: Record<string, unknown>) => Record<string, unknown>;
16
18
  export declare const arangoDocToDocumentRow: (collection: string, doc: Record<string, unknown>, context?: ImportContext) => Record<string, unknown>;
17
19
  export declare const arangoDocToEdgeRow: (collection: string, doc: Record<string, unknown>) => Record<string, unknown>;
18
20
  export declare const isEdgeCollection: (collection: string) => boolean;
@@ -13,6 +13,7 @@ import { access } from 'node:fs/promises';
13
13
  import { constants } from 'node:fs';
14
14
  import { join } from 'node:path';
15
15
  import { groupCapabilityTemplates } from '@openpeepshq/common/lib';
16
+ import { defaultGroupAdminCapabilityAdds } from '@openpeepshq/common/types';
16
17
  import { documentRegistry, edgeRegistry, parseDocRef, } from '../pg/map/registry.js';
17
18
  import { nowIso } from '../pg/mappers.js';
18
19
  import { uuidv7 } from 'uuidv7';
@@ -110,6 +111,22 @@ export const capabilitiesFromLegacyGroupFlags = (data) => {
110
111
  : privateGroup;
111
112
  return template.capabilities;
112
113
  };
114
+ export const normalizeGroupMembershipRoles = (roles) => {
115
+ if (!Array.isArray(roles))
116
+ return roles;
117
+ return [...new Set(roles.map((role) => (role === 'admin' ? 'owner' : role)))];
118
+ };
119
+ export const normalizeGroupCapabilityMap = (capabilities) => {
120
+ const next = Object.assign({}, capabilities);
121
+ if (next.admin && !next.owner) {
122
+ next.owner = next.admin;
123
+ delete next.admin;
124
+ }
125
+ if (!next.admin) {
126
+ next.admin = { add: [...defaultGroupAdminCapabilityAdds] };
127
+ }
128
+ return next;
129
+ };
113
130
  export const arangoDocToDocumentRow = (collection, doc, context) => {
114
131
  var _a, _b, _e, _f, _g, _h, _j, _k, _m, _o, _p, _q, _r, _s;
115
132
  const model = arangoDocToModel(doc);
@@ -177,6 +194,9 @@ export const arangoDocToDocumentRow = (collection, doc, context) => {
177
194
  if (capabilities) {
178
195
  body.capabilities = capabilities;
179
196
  }
197
+ else if (body.capabilities && typeof body.capabilities === 'object') {
198
+ body.capabilities = normalizeGroupCapabilityMap(body.capabilities);
199
+ }
180
200
  }
181
201
  return Object.assign(Object.assign({ id }, scalars), { body,
182
202
  createdAt,
@@ -197,6 +217,9 @@ export const arangoDocToEdgeRow = (collection, doc) => {
197
217
  const model = arangoDocToModel(doc);
198
218
  const { createdAt, updatedAt } = timestampsFromModel(model);
199
219
  const { createdAt: _c, updatedAt: _u, id: _id } = model, body = __rest(model, ["createdAt", "updatedAt", "id"]);
220
+ if (collection === 'userGroups' && 'roles' in body) {
221
+ body.roles = normalizeGroupMembershipRoles(body.roles);
222
+ }
200
223
  return {
201
224
  id: (_b = normalizeImportId((_a = doc._key) !== null && _a !== void 0 ? _a : doc.id)) !== null && _b !== void 0 ? _b : String((_e = doc._key) !== null && _e !== void 0 ? _e : doc.id),
202
225
  fromId: (_f = normalizeImportId(fromRef.id)) !== null && _f !== void 0 ? _f : fromRef.id,
@@ -95,6 +95,10 @@ export const closePostgres = async () => {
95
95
  await (pool === null || pool === void 0 ? void 0 : pool.end());
96
96
  pool = undefined;
97
97
  dbInstance = undefined;
98
+ // DROP SCHEMA / pool.end leaves allpeepDb() holding a dead Pool; next caller
99
+ // must re-run initDb() (e.g. setDefaultRoles after backup restore).
100
+ const { resetAllpeepDb } = await import('../index.js');
101
+ resetAllpeepDb();
98
102
  };
99
103
  /**
100
104
  * Drop and recreate app schemas. Drizzle stores its migration journal in
@@ -5,5 +5,5 @@ export declare const edgeFilters: {
5
5
  bodyFieldEq: (table: {
6
6
  body: unknown;
7
7
  }, field: string, value: string) => SqlFilter;
8
- groupAdminRole: () => SqlFilter;
8
+ groupOwnerRole: () => SqlFilter;
9
9
  };
@@ -6,5 +6,5 @@ export const edgeFilters = {
6
6
  entryType: (type) => pgSql(eq(sql `${entries.body}->>'type'`, type)),
7
7
  entryCreated: (start, end) => createdAtBetween(entries, start, end),
8
8
  bodyFieldEq: (table, field, value) => pgSql(eq(sql `${table.body}->>${field}`, value)),
9
- groupAdminRole: () => pgSql(sql `${userGroups.body}->'roles' ? 'admin'`),
9
+ groupOwnerRole: () => pgSql(sql `${userGroups.body}->'roles' ? 'owner'`),
10
10
  };
@@ -4,6 +4,7 @@ export declare const postFilters: {
4
4
  isDirect: () => SqlFilter;
5
5
  hasJam: () => SqlFilter;
6
6
  creatorId: (id: string) => SqlFilter;
7
+ myFeed: (profileId: string, followedProfileIds: string[], groupIds: string[]) => SqlFilter;
7
8
  type: (type: string) => SqlFilter;
8
9
  replyCount: (op: "==" | "!=" | ">" | ">=" | "<" | "<=", count: number) => SqlFilter;
9
10
  replyCountZero: () => SqlFilter;
@@ -1,5 +1,6 @@
1
- import { and, eq, isNotNull, ne, or, sql } from 'drizzle-orm';
1
+ import { and, eq, inArray, isNotNull, ne, or, sql } from 'drizzle-orm';
2
2
  import { posts } from '../schema/documents.js';
3
+ import { postGroups } from '../schema/edges.js';
3
4
  import { postHasYesOrMaybeRsvpExpr, postReplyCountExpr, } from '../queries/activity.js';
4
5
  import { compareCount } from './common.js';
5
6
  import { pgSql } from './types.js';
@@ -11,6 +12,15 @@ export const postFilters = {
11
12
  isDirect: () => pgSql(eq(posts.visibility, 'direct')),
12
13
  hasJam: () => pgSql(isNotNull(sql `${posts.body}->'jam'`)),
13
14
  creatorId: (id) => pgSql(eq(posts.creatorId, id)),
15
+ myFeed: (profileId, followedProfileIds, groupIds) => {
16
+ const followed = followedProfileIds.length
17
+ ? inArray(posts.creatorId, followedProfileIds)
18
+ : sql `false`;
19
+ const groupMemberPost = groupIds.length
20
+ ? and(eq(posts.visibility, 'group'), sql `EXISTS (SELECT 1 FROM ${postGroups} WHERE ${postGroups.fromId} = ${posts.id}::text AND ${inArray(postGroups.toId, groupIds)})`)
21
+ : sql `false`;
22
+ return pgSql(or(eq(posts.creatorId, profileId), followed, groupMemberPost));
23
+ },
14
24
  type: (type) => pgSql(eq(posts.type, type)),
15
25
  replyCount: (op, count) => pgSql(compareCount(postsReplyCountExpr, op, count)),
16
26
  replyCountZero: () => postFilters.replyCount('==', 0),
@@ -438,6 +438,11 @@ export const filterToSql = (collection, table, filter) => {
438
438
  const matches = Array.isArray(filter.matches)
439
439
  ? filter.matches
440
440
  : [filter.matches];
441
+ // An empty match list is a valid predicate that can never match. Keeping
442
+ // it in SQL prevents an empty OR branch from demoting the whole filter to
443
+ // post-hydration evaluation.
444
+ if (!matches.length)
445
+ return sql `false`;
441
446
  const parts = matches
442
447
  .map((match) => matchToSql(collection, table, match))
443
448
  .filter(Boolean);
@@ -18,7 +18,7 @@ export declare const executeCount: (db: PgDb, mapData: MapData<object, object>)
18
18
  export declare const executeFirst: (db: PgDb, mapData: MapData<object, object>) => Promise<Doc | undefined>;
19
19
  export declare const relationsFrom: (db: PgDb, start: {
20
20
  id: string;
21
- }, parentCollection: string, relation: Relation & {
21
+ }, _parentCollection: string, relation: Relation & {
22
22
  mapping: MapData<object, object>;
23
23
  }) => Promise<Doc[]>;
24
24
  export declare const evaluateDerived: (db: PgDb, doc: Doc, derived: DerivedProperty) => Promise<unknown>;
@@ -130,8 +130,8 @@ const attachForeignKeyRelation = async (db, docs, fkr) => Promise.all(docs.map(a
130
130
  const loaded = (await Promise.all(ids.map((id) => executeFind(db, fkr.mapping.collection, fkr.mapping, id)))).filter(Boolean);
131
131
  return Object.assign(Object.assign({}, doc), { [fkr.alias]: fkr.cardinality === 'many' ? loaded : ((_b = loaded[0]) !== null && _b !== void 0 ? _b : undefined) });
132
132
  }));
133
- const attachRelation = async (db, parentCollection, docs, relation) => {
134
- var _a;
133
+ const attachRelation = async (db, _parentCollection, docs, relation) => {
134
+ var _a, _b;
135
135
  if (relation.maxDepth && relation.maxDepth > 1) {
136
136
  return Promise.all(docs.map(async (doc) => (Object.assign(Object.assign({}, doc), { [relation.alias]: await traverseRelation(db, doc.id, relation) }))));
137
137
  }
@@ -160,51 +160,96 @@ const attachRelation = async (db, parentCollection, docs, relation) => {
160
160
  list.push(edge);
161
161
  grouped.set(parentId, list);
162
162
  }
163
- return Promise.all(docs.map(async (doc) => {
164
- var _a, _b;
165
- const edgesForDoc = (_a = grouped.get(doc.id)) !== null && _a !== void 0 ? _a : [];
166
- if (relation.count) {
167
- let count = edgesForDoc.length;
168
- if ((_b = relation.mapping) === null || _b === void 0 ? void 0 : _b.collection) {
169
- const vertexCol = vertexEdgeColumn(relation);
170
- const vertexIds = edgesForDoc.map((e) => e[vertexCol]);
171
- const vertices = await fetchRowsByIds(db, relation.mapping.collection, vertexIds, relation.mapping.softDelete);
172
- const filtered = applyPostFilters(vertices, relation.mapping.filters, relation.mapping.defaultFilter);
173
- count = filtered.length;
174
- }
175
- return Object.assign(Object.assign({}, doc), { [relation.alias]: count });
163
+ const vertexCol = vertexEdgeColumn(relation);
164
+ const edgesFor = (doc) => { var _a; return (_a = grouped.get(doc.id)) !== null && _a !== void 0 ? _a : []; };
165
+ const edgeVertexIdsFor = (doc) => edgesFor(doc).map((edge) => edge[vertexCol]);
166
+ // Vertices are fetched and hydrated once for the whole batch. Doing it per
167
+ // parent row cost a query per row per relation, so one feed page ran
168
+ // hundreds of round trips.
169
+ const batchIdsFrom = (idsFor) => [
170
+ ...new Set(docs.flatMap(idsFor)),
171
+ ];
172
+ if (relation.count) {
173
+ if (!((_b = relation.mapping) === null || _b === void 0 ? void 0 : _b.collection)) {
174
+ return docs.map((doc) => (Object.assign(Object.assign({}, doc), { [relation.alias]: edgesFor(doc).length })));
176
175
  }
177
- const value = await resolveRelationValue(db, edgesForDoc, relation, parentCollection);
178
- return Object.assign(Object.assign({}, doc), { [relation.alias]: value });
179
- }));
176
+ const rows = await fetchRowsByIds(db, relation.mapping.collection, batchIdsFrom(edgeVertexIdsFor), relation.mapping.softDelete);
177
+ const counted = new Set(applyPostFilters(rows, relation.mapping.filters, relation.mapping.defaultFilter).map((row) => row.id));
178
+ return docs.map((doc) => (Object.assign(Object.assign({}, doc), { [relation.alias]: [...new Set(edgeVertexIdsFor(doc))].filter((id) => counted.has(id)).length })));
179
+ }
180
+ const vertexIdsFor = (doc) => capVertexIds(edgeVertexIdsFor(doc), relation);
181
+ const vertexCollection = vertexCollectionFor(relation);
182
+ const lookup = vertexCollection
183
+ ? await fetchVertexLookup(db, vertexCollection, batchIdsFrom(vertexIdsFor), relation)
184
+ : emptyVertexLookup;
185
+ return docs.map((doc) => (Object.assign(Object.assign({}, doc), { [relation.alias]: relationValueFrom(edgesFor(doc), relation, vertexIdsFor(doc), lookup) })));
180
186
  };
181
- const resolveRelationValue = async (db, edgeRows, relation, _parentCollection) => {
187
+ const nodeCapFromLimit = (limit) => {
188
+ if (limit == null)
189
+ return undefined;
190
+ return typeof limit === 'number' ? limit : limit[1];
191
+ };
192
+ /**
193
+ * Cap before fetch when mapping.limit is set so hot inbound lists (e.g.
194
+ * embedded reposters) do not hydrate every vertex. uuidv7 ids are
195
+ * time-ordered, so newest-first approximates `createdAt DESC` before we have
196
+ * row data to sort on.
197
+ */
198
+ const capVertexIds = (vertexIds, relation) => {
182
199
  var _a;
183
- const vertexCollection = vertexCollectionFor(relation);
184
- const vertexCol = vertexEdgeColumn(relation);
185
- const vertexIds = edgeRows.map((e) => e[vertexCol]);
186
- if (!vertexCollection) {
187
- const items = edgeRows.map((edge) => {
188
- var _a;
189
- return rowToDocument(edgeCollectionName(relation.edgeCollection), edge, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.keepMetadata);
190
- });
191
- return relation.cardinality === 'one' ? items[0] : items;
200
+ const nodeCap = nodeCapFromLimit((_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.limit);
201
+ if (nodeCap === undefined || relation.cardinality !== 'many') {
202
+ return vertexIds;
192
203
  }
193
- let vertices = await fetchRowsByIds(db, vertexCollection, vertexIds, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.softDelete);
194
- if (relation.mapping) {
195
- vertices = await hydrateMapData(db, relation.mapping, vertices);
204
+ return [...new Set(vertexIds)]
205
+ .sort((a, b) => (a < b ? 1 : a > b ? -1 : 0))
206
+ .slice(0, nodeCap);
207
+ };
208
+ const emptyVertexLookup = {
209
+ get: () => undefined,
210
+ rank: () => 0,
211
+ };
212
+ const fetchVertexLookup = async (db, vertexCollection, vertexIds, relation) => {
213
+ var _a;
214
+ const rows = await fetchRowsByIds(db, vertexCollection, vertexIds, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.softDelete);
215
+ const vertices = relation.mapping
216
+ ? await hydrateMapData(db, relation.mapping, rows)
217
+ : rows;
218
+ const byId = new Map(vertices.map((vertex) => [vertex.id, vertex]));
219
+ const ranks = new Map(vertices.map((vertex, index) => [vertex.id, index]));
220
+ return {
221
+ get: (id) => byId.get(id),
222
+ rank: (id) => { var _a; return (_a = ranks.get(id)) !== null && _a !== void 0 ? _a : Number.MAX_SAFE_INTEGER; },
223
+ };
224
+ };
225
+ const relationValueFrom = (edgeRows, relation, vertexIds, lookup) => {
226
+ var _a, _b;
227
+ const toEdgeDoc = (edge) => {
228
+ var _a;
229
+ return rowToDocument(edgeCollectionName(relation.edgeCollection), edge, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.keepMetadata);
230
+ };
231
+ if (!vertexCollectionFor(relation)) {
232
+ const items = edgeRows.map(toEdgeDoc);
233
+ return relation.cardinality === 'one' ? items[0] : items;
196
234
  }
197
235
  if (relation.skipEdge) {
198
- return relation.cardinality === 'one' ? vertices[0] : vertices;
236
+ const vertices = [...new Set(vertexIds)]
237
+ .sort((a, b) => lookup.rank(a) - lookup.rank(b))
238
+ .map((id) => lookup.get(id))
239
+ .filter((vertex) => !!vertex);
240
+ if (relation.cardinality === 'one')
241
+ return vertices[0];
242
+ return applyLimit(applySort(vertices, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.sort), (_b = relation.mapping) === null || _b === void 0 ? void 0 : _b.limit);
199
243
  }
244
+ const vertexCol = vertexEdgeColumn(relation);
245
+ const capped = new Set(vertexIds);
200
246
  const items = edgeRows
201
247
  .map((edge) => {
202
- var _a;
203
248
  const vertexId = edge[vertexCol];
204
- const vertex = vertices.find((v) => v.id === vertexId);
249
+ const vertex = capped.has(vertexId) ? lookup.get(vertexId) : undefined;
205
250
  if (!vertex)
206
251
  return undefined;
207
- const edgeDoc = rowToDocument(edgeCollectionName(relation.edgeCollection), edge, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.keepMetadata);
252
+ const edgeDoc = toEdgeDoc(edge);
208
253
  if (relation.vertexAlias) {
209
254
  return Object.assign(Object.assign({}, edgeDoc), { [relation.vertexAlias]: vertex });
210
255
  }
@@ -213,10 +258,13 @@ const resolveRelationValue = async (db, edgeRows, relation, _parentCollection) =
213
258
  .filter(Boolean);
214
259
  return relation.cardinality === 'one' ? items[0] : items;
215
260
  };
216
- const nodeCapFromLimit = (limit) => {
217
- if (limit == null)
218
- return undefined;
219
- return typeof limit === 'number' ? limit : limit[1];
261
+ const resolveRelationValue = async (db, edgeRows, relation) => {
262
+ const vertexCollection = vertexCollectionFor(relation);
263
+ const vertexIds = capVertexIds(edgeRows.map((edge) => edge[vertexEdgeColumn(relation)]), relation);
264
+ const lookup = vertexCollection
265
+ ? await fetchVertexLookup(db, vertexCollection, vertexIds, relation)
266
+ : emptyVertexLookup;
267
+ return relationValueFrom(edgeRows, relation, vertexIds, lookup);
220
268
  };
221
269
  const traverseRelation = async (db, startId, relation) => {
222
270
  var _a, _b, _c, _d, _e;
@@ -338,7 +386,7 @@ export const executeFirst = async (db, mapData) => {
338
386
  const limited = applyLimit(await executeAll(db, mapData), [0, 1]);
339
387
  return limited[0];
340
388
  };
341
- export const relationsFrom = async (db, start, parentCollection, relation) => {
389
+ export const relationsFrom = async (db, start, _parentCollection, relation) => {
342
390
  var _a;
343
391
  // Match attachRelation: honor maxDepth via BFS traversal. Without this,
344
392
  // callers like getConversationByStart only see direct (depth-1) replies.
@@ -367,7 +415,7 @@ export const relationsFrom = async (db, start, parentCollection, relation) => {
367
415
  }
368
416
  // Keep edge fields (e.g. roles) and attach the related vertex under
369
417
  // vertexAlias — same shape as hydrateDocuments/attachRelation.
370
- const value = await resolveRelationValue(db, edgeRows, relation, parentCollection);
418
+ const value = await resolveRelationValue(db, edgeRows, relation);
371
419
  if (relation.cardinality === 'one') {
372
420
  return value ? [value] : [];
373
421
  }
@@ -1,3 +1,26 @@
1
+ /** Drizzle journal tags in apply order (e.g. `0000_bizarre_chat`). */
2
+ export declare const listSchemaVersions: () => string[];
3
+ export declare const getFirstSchemaVersion: () => string;
4
+ export declare const getLatestSchemaVersion: () => string;
5
+ /**
6
+ * Postgres backups created before `schemaVersion` was stamped assumed this
7
+ * journal tag (see `sql/meta/0007_snapshot.json`).
8
+ */
9
+ export declare const LEGACY_POSTGRES_BACKUP_SCHEMA_VERSION = "0007_shallow_oracle";
10
+ /**
11
+ * Schema to apply before JSONL import on restore.
12
+ * - Arango → first journal tag so later SQL data migrations see restored rows.
13
+ * - Postgres with `schemaVersion` → that tag (must still exist in this binary).
14
+ * - Postgres without → `0007_shallow_oracle` (pre-stamping baseline).
15
+ */
16
+ export declare const resolveRestoreSchemaVersion: (databaseType: "arango" | "postgres", schemaVersion?: string) => string;
17
+ /** Apply Drizzle migrations only through `tag` (inclusive). */
18
+ export declare const migrateToSchemaVersion: (tag: string) => Promise<void>;
19
+ /**
20
+ * Wipe public + drizzle schemas, then migrate through `tag`.
21
+ * Used by backup restore so import lands on a known schema version.
22
+ */
23
+ export declare const resetAndMigrateToSchemaVersion: (tag: string) => Promise<void>;
1
24
  /** Fail if app tables are missing (used when RUN_DB_MIGRATE_ON_BOOT=false). */
2
25
  export declare const assertSchemaReady: () => Promise<void>;
3
26
  /**
@@ -1,4 +1,6 @@
1
- import { existsSync } from 'node:fs';
1
+ import { copyFileSync, existsSync, readFileSync } from 'node:fs';
2
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
2
4
  import { join, dirname } from 'node:path';
3
5
  import { fileURLToPath } from 'node:url';
4
6
  import { getTableName, sql } from 'drizzle-orm';
@@ -17,6 +19,90 @@ const resolveMigrationsFolder = () => {
17
19
  return join(moduleDir, '..', '..', '..', 'src', 'db', 'pg', 'sql');
18
20
  };
19
21
  const migrationsFolder = resolveMigrationsFolder();
22
+ const readMigrationJournal = () => {
23
+ const journalPath = join(migrationsFolder, 'meta', '_journal.json');
24
+ return JSON.parse(readFileSync(journalPath, 'utf8'));
25
+ };
26
+ /** Drizzle journal tags in apply order (e.g. `0000_bizarre_chat`). */
27
+ export const listSchemaVersions = () => readMigrationJournal().entries.map((entry) => entry.tag);
28
+ export const getFirstSchemaVersion = () => {
29
+ const tags = listSchemaVersions();
30
+ const first = tags[0];
31
+ if (!first) {
32
+ throw new Error('No Postgres schema migrations found');
33
+ }
34
+ return first;
35
+ };
36
+ export const getLatestSchemaVersion = () => {
37
+ const tags = listSchemaVersions();
38
+ const latest = tags[tags.length - 1];
39
+ if (!latest) {
40
+ throw new Error('No Postgres schema migrations found');
41
+ }
42
+ return latest;
43
+ };
44
+ /**
45
+ * Postgres backups created before `schemaVersion` was stamped assumed this
46
+ * journal tag (see `sql/meta/0007_snapshot.json`).
47
+ */
48
+ export const LEGACY_POSTGRES_BACKUP_SCHEMA_VERSION = '0007_shallow_oracle';
49
+ const assertKnownSchemaVersion = (tag) => {
50
+ if (!listSchemaVersions().includes(tag)) {
51
+ throw new Error(`Unknown Postgres schema version "${tag}"; known: ${listSchemaVersions().join(', ')}`);
52
+ }
53
+ return tag;
54
+ };
55
+ /**
56
+ * Schema to apply before JSONL import on restore.
57
+ * - Arango → first journal tag so later SQL data migrations see restored rows.
58
+ * - Postgres with `schemaVersion` → that tag (must still exist in this binary).
59
+ * - Postgres without → `0007_shallow_oracle` (pre-stamping baseline).
60
+ */
61
+ export const resolveRestoreSchemaVersion = (databaseType, schemaVersion) => {
62
+ if (databaseType === 'arango') {
63
+ return getFirstSchemaVersion();
64
+ }
65
+ if (schemaVersion) {
66
+ return assertKnownSchemaVersion(schemaVersion);
67
+ }
68
+ return assertKnownSchemaVersion(LEGACY_POSTGRES_BACKUP_SCHEMA_VERSION);
69
+ };
70
+ const buildMigrationsFolderUpTo = async (tag) => {
71
+ const journal = readMigrationJournal();
72
+ const endIdx = journal.entries.findIndex((entry) => entry.tag === tag);
73
+ if (endIdx < 0) {
74
+ throw new Error(`Unknown Postgres schema version: ${tag}`);
75
+ }
76
+ const entries = journal.entries.slice(0, endIdx + 1);
77
+ const folder = await mkdtemp(join(tmpdir(), 'op-migrate-'));
78
+ await mkdir(join(folder, 'meta'), { recursive: true });
79
+ await writeFile(join(folder, 'meta', '_journal.json'), `${JSON.stringify(Object.assign(Object.assign({}, journal), { entries }), null, 2)}\n`);
80
+ for (const entry of entries) {
81
+ copyFileSync(join(migrationsFolder, `${entry.tag}.sql`), join(folder, `${entry.tag}.sql`));
82
+ }
83
+ return folder;
84
+ };
85
+ /** Apply Drizzle migrations only through `tag` (inclusive). */
86
+ export const migrateToSchemaVersion = async (tag) => {
87
+ const folder = await buildMigrationsFolderUpTo(tag);
88
+ try {
89
+ await ensurePublicSchema();
90
+ await migrate(pgDb(), { migrationsFolder: folder });
91
+ }
92
+ finally {
93
+ await rm(folder, { recursive: true, force: true });
94
+ }
95
+ };
96
+ /**
97
+ * Wipe public + drizzle schemas, then migrate through `tag`.
98
+ * Used by backup restore so import lands on a known schema version.
99
+ */
100
+ export const resetAndMigrateToSchemaVersion = async (tag) => {
101
+ log.info('Resetting Postgres schemas and migrating to %s', tag);
102
+ await resetPostgresSchemas();
103
+ await migrateToSchemaVersion(tag);
104
+ log.info('Postgres schema ready at %s', tag);
105
+ };
20
106
  const APP_TABLE_NAMES = [
21
107
  ...DOCUMENT_IMPORT_ORDER.map((collection) => getTableName(getTableForCollection(collection))),
22
108
  ...EDGE_IMPORT_ORDER.map((collection) => getTableName(getTableForCollection(collection))),
@@ -8,6 +8,11 @@ export declare const profileDerived: {
8
8
  followersCount: number;
9
9
  followingCount: number;
10
10
  };
11
+ /** Counts without loading follower/following trees. */
12
+ profileStatsCounts: (db: PgDb, doc: Doc) => Promise<{
13
+ followersCount: number;
14
+ followingCount: number;
15
+ }>;
11
16
  };
12
17
  export declare const postDerived: {
13
18
  seen: (profileId?: string) => (db: PgDb, doc: Doc) => Promise<boolean>;