@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
@@ -74,7 +74,7 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
74
74
  event: number;
75
75
  }[];
76
76
  postTypes: {
77
- type: "jam" | "poll" | "note" | "event" | "article";
77
+ type: "poll" | "note" | "event" | "article" | "jam";
78
78
  count: number;
79
79
  }[];
80
80
  activeUsersSeries: {
@@ -157,6 +157,36 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
157
157
  value: number;
158
158
  }[] | undefined;
159
159
  };
160
+ dau: {
161
+ key: string;
162
+ value: number;
163
+ previousValue: number;
164
+ deltaPct: number | null;
165
+ series?: {
166
+ day: string;
167
+ value: number;
168
+ }[] | undefined;
169
+ };
170
+ mau: {
171
+ key: string;
172
+ value: number;
173
+ previousValue: number;
174
+ deltaPct: number | null;
175
+ series?: {
176
+ day: string;
177
+ value: number;
178
+ }[] | undefined;
179
+ };
180
+ dauMau: {
181
+ key: string;
182
+ value: number;
183
+ previousValue: number;
184
+ deltaPct: number | null;
185
+ series?: {
186
+ day: string;
187
+ value: number;
188
+ }[] | undefined;
189
+ };
160
190
  };
161
191
  signupsByDay: {
162
192
  day: string;
@@ -258,6 +288,7 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
258
288
  comments: number;
259
289
  reposts: number;
260
290
  bookmarks: number;
291
+ dms: number;
261
292
  }[];
262
293
  impressionsByPeriod: {
263
294
  day: string;
@@ -1,6 +1,7 @@
1
1
  import { endOfMonth, formatISO, startOfMonth, subMonths } from 'date-fns';
2
2
  import { eq } from 'drizzle-orm';
3
3
  import { uuidv7 } from 'uuidv7';
4
+ import { communityConfig } from '../config/index.js';
4
5
  import { sendEmailQueue } from '../email/index.js';
5
6
  import { database } from '../db/index.js';
6
7
  import { analyticsReportDeliveries } from '../db/pg/schema/analytics.js';
@@ -25,10 +26,11 @@ const narrativeSentence = (label, value, deltaPct) => {
25
26
  };
26
27
  /** Board-ready report: plain-text email body + visual multi-page PDF. */
27
28
  export const buildAnalyticsBoardReport = async (query = {}) => {
28
- const [overview, growth, engagement] = await Promise.all([
29
+ const [overview, growth, engagement, community] = await Promise.all([
29
30
  getAnalyticsOverview(query),
30
31
  getAnalyticsGrowth(query),
31
32
  getAnalyticsEngagement(query),
33
+ communityConfig(),
32
34
  ]);
33
35
  const from = overview.range.from;
34
36
  const to = overview.range.to;
@@ -51,7 +53,12 @@ export const buildAnalyticsBoardReport = async (query = {}) => {
51
53
  '',
52
54
  ...summary,
53
55
  ].join('\n');
54
- const pdf = await buildAnalyticsPdf({ overview, growth, engagement });
56
+ const pdf = await buildAnalyticsPdf({
57
+ communityName: community.info.name,
58
+ overview,
59
+ growth,
60
+ engagement,
61
+ });
55
62
  return { text, pdf, overview, growth, engagement };
56
63
  };
57
64
  /** @deprecated Prefer buildAnalyticsBoardReport().pdf — kept for tests. */
@@ -9,9 +9,11 @@ import extract from 'extract-zip';
9
9
  import { collectionInfos } from '../db/index.js';
10
10
  import { communityConfig, config } from '../config/index.js';
11
11
  import { exportAllPostgresCollections, importAllArangoCollections, importAllPostgresCollections, } from '../db/migration/importCollections.js';
12
- import { replaceHostname } from '../db/replaceHostname.js';
12
+ import { getLatestSchemaVersion } from '../db/pg/migrate.js';
13
+ import { replaceOrigin } from '../db/replaceOrigin.js';
13
14
  import { logger } from '../log/index.js';
14
15
  import { setDefaultRoles } from '../roles/index.js';
16
+ import { serverRootUrl } from '../server/index.js';
15
17
  import { resolveBackupDatabaseType, } from './metadata.js';
16
18
  export { resolveBackupDatabaseType } from './metadata.js';
17
19
  const log = logger('core:backups');
@@ -152,10 +154,10 @@ const assertBackupExtracted = async (tempDir) => {
152
154
  }
153
155
  log.info(`Found ${jsonlFiles.length} collection backup files in archive`);
154
156
  };
155
- const restoreDatabaseFromBackup = async (collectionsDir, databaseType) => {
157
+ const restoreDatabaseFromBackup = async (collectionsDir, databaseType, schemaVersion) => {
156
158
  log.info('Restoring %s database from JSONL collections', databaseType);
157
159
  const { total } = databaseType === 'postgres'
158
- ? await importAllPostgresCollections(collectionsDir)
160
+ ? await importAllPostgresCollections(collectionsDir, schemaVersion)
159
161
  : await importAllArangoCollections(collectionsDir);
160
162
  if (total === 0) {
161
163
  throw new Error('Backup restore completed with zero rows; archive may be empty or corrupt');
@@ -188,6 +190,8 @@ export const createBackup = async () => {
188
190
  await writeFile(join(metaDir, 'collectionInfos.json'), JSON.stringify(collectionInfos, null, 2));
189
191
  await writeFile(join(backupDir, 'metadata.json'), JSON.stringify({
190
192
  databaseType: 'postgres',
193
+ createdAt: new Date().toISOString(),
194
+ schemaVersion: getLatestSchemaVersion(),
191
195
  config: {
192
196
  hostname: hostnameFromServerHost(coreConfig.server.host),
193
197
  },
@@ -253,8 +257,12 @@ export const restoreBackups = async (zipFilePath) => {
253
257
  await cp(join(tempDir, 'logs'), coreConfig.logs.local.path, {
254
258
  recursive: true,
255
259
  });
256
- await restoreDatabaseFromBackup(collectionsDir, databaseType);
257
- await replaceHostname((_a = backupMetadata === null || backupMetadata === void 0 ? void 0 : backupMetadata.config) === null || _a === void 0 ? void 0 : _a.hostname, hostnameFromServerHost(coreConfig.server.host));
260
+ await restoreDatabaseFromBackup(collectionsDir, databaseType, backupMetadata === null || backupMetadata === void 0 ? void 0 : backupMetadata.schemaVersion);
261
+ // Repoint the backup's absolute URLs at this server's full origin (scheme +
262
+ // host + port). Matching by the backup hostname means a prod backup on
263
+ // `https://host` restores cleanly onto `http://localhost:5174` without
264
+ // stranding the old scheme/port.
265
+ await replaceOrigin((_a = backupMetadata === null || backupMetadata === void 0 ? void 0 : backupMetadata.config) === null || _a === void 0 ? void 0 : _a.hostname, await serverRootUrl());
258
266
  log.info(`Restored ${databaseType} backup (hostname was ${(_c = (_b = backupMetadata === null || backupMetadata === void 0 ? void 0 : backupMetadata.config) === null || _b === void 0 ? void 0 : _b.hostname) !== null && _c !== void 0 ? _c : 'unknown'})`);
259
267
  await setDefaultRoles();
260
268
  };
@@ -1,6 +1,13 @@
1
1
  export type BackupDatabaseType = 'arango' | 'postgres';
2
2
  export type BackupMetadata = {
3
3
  databaseType?: BackupDatabaseType;
4
+ /** When this backup archive was created (ISO-8601). */
5
+ createdAt?: string;
6
+ /**
7
+ * Drizzle journal tag the database was on when the backup was created
8
+ * (e.g. `0007_shallow_oracle`). Omitted on legacy Arango archives.
9
+ */
10
+ schemaVersion?: string;
4
11
  config?: {
5
12
  hostname?: string;
6
13
  };
@@ -3,12 +3,6 @@ dotenv.config();
3
3
  export const defaultCommunityConfig = {
4
4
  theme: {
5
5
  base: 'OpenpeepsLight',
6
- primaryHex: '#15678a',
7
- logoFull: '/img/logo-full.png',
8
- logoSmall: '/img/logo-small.png',
9
- defaultProfileAvatar: '/img/default-avatar.png',
10
- defaultGroupAvatar: '/img/default-group-avatar.svg',
11
- backgroundAuth: '/img/background-auth.png',
12
6
  icon: '/img/icon.svg',
13
7
  light: {
14
8
  primaryHex: '#15678a',
@@ -45,6 +45,7 @@ export const defaultConfig = {
45
45
  },
46
46
  plugins: {
47
47
  path: path.resolve(process.env.PLUGINS_PATH || '../plugins'),
48
+ rootPackageJsonPath: path.resolve(process.env.ROOT_PACKAGE_JSON_PATH || '../package.json'),
48
49
  },
49
50
  secrets: {
50
51
  jwt: resolveJwtSecret(),
@@ -1,6 +1,4 @@
1
1
  declare const _default: {
2
- url: string;
3
- databaseName: string | undefined;
4
2
  databaseUrl: string;
5
3
  };
6
4
  export default _default;
@@ -1,8 +1,6 @@
1
1
  import dotenv from 'dotenv';
2
2
  dotenv.config();
3
3
  export default {
4
- url: process.env.DB_URL || 'http://localhost:8529',
5
- databaseName: process.env.DB_NAME || undefined,
6
4
  databaseUrl: process.env.DATABASE_URL ||
7
5
  'postgresql://openpeeps:openpeeps@localhost:5432/openpeeps',
8
6
  };
@@ -24,8 +24,8 @@ export declare const config: <T = {
24
24
  maxProfiles?: number | undefined;
25
25
  };
26
26
  db: {
27
- url: string;
28
27
  databaseUrl: string;
28
+ url?: string | undefined;
29
29
  databaseName?: string | undefined;
30
30
  };
31
31
  redis: {
@@ -65,6 +65,7 @@ export declare const config: <T = {
65
65
  };
66
66
  plugins: {
67
67
  path: string;
68
+ rootPackageJsonPath: string;
68
69
  };
69
70
  secrets: {
70
71
  jwt: string;
@@ -94,6 +95,8 @@ export declare const config: <T = {
94
95
  };
95
96
  sso: {
96
97
  generic: {
98
+ id: string;
99
+ name: string;
97
100
  userProfileRequest: {
98
101
  url: string;
99
102
  authHeader?: string | undefined;
@@ -104,6 +107,7 @@ export declare const config: <T = {
104
107
  avatar?: string | undefined;
105
108
  displayName?: string | undefined;
106
109
  };
110
+ loginLink?: string | undefined;
107
111
  createAccounts?: boolean | undefined;
108
112
  createProfiles?: boolean | undefined;
109
113
  }[];
@@ -125,6 +129,7 @@ export declare const config: <T = {
125
129
  } | undefined;
126
130
  approvalRequired?: boolean | undefined;
127
131
  }[];
132
+ onlySSO?: boolean | undefined;
128
133
  };
129
134
  services: {
130
135
  sentry: {
@@ -170,9 +175,12 @@ export declare const config: <T = {
170
175
  export declare const communityConfig: () => Promise<{
171
176
  theme: {
172
177
  base: string;
173
- primaryHex: string;
174
178
  light: {
175
179
  primaryHex: string;
180
+ secondaryHex?: string | undefined;
181
+ fontFamily?: string | undefined;
182
+ buttonRadius?: string | undefined;
183
+ radius?: string | undefined;
176
184
  logoSmall?: string | undefined;
177
185
  defaultProfileAvatar?: string | undefined;
178
186
  defaultGroupAvatar?: string | undefined;
@@ -181,6 +189,10 @@ export declare const communityConfig: () => Promise<{
181
189
  };
182
190
  dark: {
183
191
  primaryHex: string;
192
+ secondaryHex?: string | undefined;
193
+ fontFamily?: string | undefined;
194
+ buttonRadius?: string | undefined;
195
+ radius?: string | undefined;
184
196
  logoSmall?: string | undefined;
185
197
  defaultProfileAvatar?: string | undefined;
186
198
  defaultGroupAvatar?: string | undefined;
@@ -189,12 +201,6 @@ export declare const communityConfig: () => Promise<{
189
201
  };
190
202
  icon?: string | undefined;
191
203
  mobileIcon?: string | undefined;
192
- logoFull?: string | undefined;
193
- logoSmall?: string | undefined;
194
- defaultProfileAvatar?: string | undefined;
195
- defaultGroupAvatar?: string | undefined;
196
- backgroundAuth?: string | undefined;
197
- background?: string | undefined;
198
204
  };
199
205
  info: {
200
206
  name: string;
@@ -244,8 +250,8 @@ export declare const sanitizedConfigWithDefaults: <T = {
244
250
  maxProfiles?: number | undefined;
245
251
  };
246
252
  db: {
247
- url: string;
248
253
  databaseUrl: string;
254
+ url?: string | undefined;
249
255
  databaseName?: string | undefined;
250
256
  };
251
257
  redis: {
@@ -285,6 +291,7 @@ export declare const sanitizedConfigWithDefaults: <T = {
285
291
  };
286
292
  plugins: {
287
293
  path: string;
294
+ rootPackageJsonPath: string;
288
295
  };
289
296
  secrets: {
290
297
  jwt: string;
@@ -314,6 +321,8 @@ export declare const sanitizedConfigWithDefaults: <T = {
314
321
  };
315
322
  sso: {
316
323
  generic: {
324
+ id: string;
325
+ name: string;
317
326
  userProfileRequest: {
318
327
  url: string;
319
328
  authHeader?: string | undefined;
@@ -324,6 +333,7 @@ export declare const sanitizedConfigWithDefaults: <T = {
324
333
  avatar?: string | undefined;
325
334
  displayName?: string | undefined;
326
335
  };
336
+ loginLink?: string | undefined;
327
337
  createAccounts?: boolean | undefined;
328
338
  createProfiles?: boolean | undefined;
329
339
  }[];
@@ -345,6 +355,7 @@ export declare const sanitizedConfigWithDefaults: <T = {
345
355
  } | undefined;
346
356
  approvalRequired?: boolean | undefined;
347
357
  }[];
358
+ onlySSO?: boolean | undefined;
348
359
  };
349
360
  services: {
350
361
  sentry: {
@@ -1,35 +1,13 @@
1
- import { Database } from 'arangojs';
2
- import { DocumentCollection, EdgeCollection } from 'arangojs/collections';
3
- import { Document, DocumentMetadata, Edge, EdgeMetadata, Patch } from 'arangojs/documents';
4
- import type { Base } from '@openpeepshq/common/types';
5
- import { type Filter } from '@openpeepshq/arango-querybuilder';
6
- import type { CollectionInfo, ViewInfo } from './pg/map/queryTypes';
1
+ import type { FilterAndTransformOptions, ObjectFilter } from './types';
2
+ import type { CollectionInfo } from './pg/map/queryTypes';
7
3
  import type { Mapping, ObjectSort, WithId } from './pg/map';
8
4
  import type { PgQueryResult } from './pg/map/types';
9
5
  import type { PgDb } from './pg/client';
10
- import { EdgeDefinitionOptions } from 'arangojs/graphs';
11
- import { EnsureIndexOptions } from 'arangojs/indexes';
12
- import { FilterAndTransformOptions, ObjectFilter, UserFunctionDefinition } from './types';
13
- export declare const addModificationDates: (collection: DocumentCollection) => Promise<void>;
14
- export declare const addIndices: (collection: DocumentCollection | EdgeCollection, indices: EnsureIndexOptions[]) => Promise<void>;
15
- export declare const ensureIndexedCollection: <T extends Record<string, unknown>>(db: Database, collectionInfo: CollectionInfo) => Promise<DocumentCollection<Base<T>, T>>;
16
- export declare const ensureView: (db: Database, viewInfo: ViewInfo) => Promise<import("arangojs/views").View | undefined>;
17
- export declare const ensureGraph: (db: Database, name: string, edgeDefinitions: EdgeDefinitionOptions[]) => Promise<import("arangojs/graphs").Graph>;
18
- export declare const ensureFunction: (db: Database, { name, dbFunction }: UserFunctionDefinition) => Promise<void>;
19
- export declare const createEdge: <T extends object | {} = {}>(collection: EdgeCollection<Base<T>, T>, document: T & EdgeMetadata & {
20
- id?: string;
21
- }) => Promise<WithId<Base<T>>>;
22
- export declare const updateEdge: <T extends Record<string, unknown> & EdgeMetadata>(collection: EdgeCollection<Base<T>>, documentKey: string, document: Patch<Document<Base<T>>>) => Promise<Document<Base<T>> | undefined>;
23
- export declare const deleteEdge: <T extends Record<string, unknown> & Base<EdgeMetadata>>(collection: EdgeCollection<Base<T>>, documentKey: string) => Promise<DocumentMetadata & {
24
- old?: Edge<Base<T>> | undefined;
25
- }>;
26
- export declare const findOneBy: <O extends object>(db: Database, collectionInfo: CollectionInfo) => (filter: Filter) => Promise<O | undefined>;
27
- export declare const edgeCollections: (database: Database) => Promise<(DocumentCollection<any, any> & EdgeCollection<any, any>)[]>;
28
6
  export declare const connector: <F extends {
29
7
  id: string;
30
8
  }, T extends {
31
9
  id: string;
32
- }, E extends object | {} = {}>(fromCollectionInfo: CollectionInfo, toCollectionInfo: CollectionInfo, edgeCollectionInfo: CollectionInfo) => (db: PgDb, from: F, to: T, data?: E & {
10
+ }, E extends object = object>(fromCollectionInfo: CollectionInfo, toCollectionInfo: CollectionInfo, edgeCollectionInfo: CollectionInfo) => (db: PgDb, from: F, to: T, data?: E & {
33
11
  id?: string;
34
12
  }) => Promise<WithId<E & {
35
13
  _from: string;
@@ -39,17 +17,17 @@ export declare const disconnector: <F extends {
39
17
  id: string;
40
18
  }, T extends {
41
19
  id: string;
42
- }>(fromCollectionInfo: CollectionInfo, toCollectionInfo: CollectionInfo, edgeCollectionInfo: CollectionInfo) => (db: PgDb, from: F, to: T) => Promise<void>;
20
+ }>(_fromCollectionInfo: CollectionInfo, _toCollectionInfo: CollectionInfo, edgeCollectionInfo: CollectionInfo) => (db: PgDb, from: F, to: T) => Promise<void>;
43
21
  export declare const connectionUpdater: <F extends {
44
22
  id: string;
45
23
  }, T extends {
46
24
  id: string;
47
- }, C extends Record<string, unknown> | undefined = {}>(fromCollectionInfo: CollectionInfo, toCollectionInfo: CollectionInfo, edgeCollectionInfo: CollectionInfo) => (db: PgDb, from: F, to: T, data?: C) => Promise<void>;
25
+ }, C extends Record<string, unknown> | undefined = Record<string, unknown>>(_fromCollectionInfo: CollectionInfo, _toCollectionInfo: CollectionInfo, edgeCollectionInfo: CollectionInfo) => (db: PgDb, from: F, to: T, data?: C) => Promise<void>;
48
26
  export declare const connectionFinder: <F extends {
49
27
  id: string;
50
28
  }, T extends {
51
29
  id: string;
52
- }, C extends Record<string, unknown> = {}>(_fromCollectionInfo: CollectionInfo, _toCollectionInfo: CollectionInfo, edgeCollectionInfo: CollectionInfo) => (db: PgDb, from: F, to: T) => Promise<C | undefined>;
30
+ }, C extends Record<string, unknown> = Record<string, unknown>>(_fromCollectionInfo: CollectionInfo, _toCollectionInfo: CollectionInfo, edgeCollectionInfo: CollectionInfo) => (db: PgDb, from: F, to: T) => Promise<C | undefined>;
53
31
  export declare const filterBefore: <T extends object>(mapping: Mapping<T>, id?: string) => Mapping<T>;
54
32
  export declare const filterAfter: <T extends object>(mapping: Mapping<T>, id?: string) => Mapping<T>;
55
33
  export declare const addQuerySort: <T extends object>(mapping: Mapping<T>, sort?: ObjectSort) => Mapping<T>;
@@ -1,152 +1,9 @@
1
- import { CollectionType, } from 'arangojs/collections';
2
- import { uuidv7 } from 'uuidv7';
3
- import { collectionElement, query, literal, } from '@openpeepshq/arango-querybuilder';
4
1
  import { deleteEdge as deletePgEdge, insertEdge } from './pg/helpers.js';
5
2
  import { asTable, edgeRegistry } from './pg/map/registry.js';
6
3
  import { nowIso } from './pg/mappers.js';
7
4
  import { and, eq } from 'drizzle-orm';
8
5
  import { documentKeyAfter, documentKeyBefore } from './pg/filters/index.js';
9
6
  import { sorts } from './pg/queries/index.js';
10
- import { asyncFilter } from '@openpeepshq/common/lib';
11
- import { logger } from '../log/index.js';
12
- const log = logger('openpeeps:db');
13
- const collectionName = (collectionOrName) => typeof collectionOrName === 'string'
14
- ? collectionOrName
15
- : collectionOrName.name;
16
- export const addModificationDates = async (collection) => {
17
- await collection.properties({
18
- computedValues: [
19
- {
20
- name: 'createdAt',
21
- expression: 'RETURN DATE_ISO8601(DATE_NOW())',
22
- computeOn: ['insert'],
23
- overwrite: false,
24
- failOnWarning: false,
25
- keepNull: true,
26
- },
27
- {
28
- name: 'updatedAt',
29
- expression: 'RETURN DATE_ISO8601(DATE_NOW())',
30
- computeOn: ['update', 'replace', 'insert'],
31
- overwrite: false,
32
- failOnWarning: false,
33
- keepNull: true,
34
- },
35
- ],
36
- });
37
- };
38
- export const addIndices = async (collection, indices) => {
39
- for (const index of indices) {
40
- if (!index.name) {
41
- return;
42
- }
43
- try {
44
- log.info('ensuring index', index.name);
45
- await collection.ensureIndex(index);
46
- }
47
- catch (error) {
48
- const message = error.message;
49
- if (message.includes('duplicate value')) {
50
- log.info('index already exists', index.name);
51
- log.info('dropping and recreating...');
52
- await collection.dropIndex(index.name);
53
- await collection.ensureIndex(index);
54
- log.info('index recreated');
55
- }
56
- else {
57
- log.error('error ensuring index', index.name, message);
58
- }
59
- }
60
- }
61
- };
62
- export const ensureIndexedCollection = async (db, collectionInfo) => {
63
- var _a;
64
- const maybeCollection = db.collection(collectionInfo.name);
65
- const collection = (await maybeCollection.exists())
66
- ? maybeCollection
67
- : collectionInfo.edge
68
- ? await db.createEdgeCollection(collectionInfo.name)
69
- : await db.createCollection(collectionInfo.name);
70
- await addModificationDates(collection);
71
- await addIndices(collection, ((_a = collectionInfo.indices) !== null && _a !== void 0 ? _a : []));
72
- return collection;
73
- };
74
- const isEqualView = (viewInfo1, viewInfo2) => viewInfo1.indexes.length === viewInfo2.indexes.length &&
75
- viewInfo1.indexes.every((index1) => viewInfo2.indexes.find((index2) => index1.collection === index2.collection &&
76
- index1.index === index2.index)) &&
77
- viewInfo2.indexes.every((index2) => viewInfo1.indexes.find((index1) => index1.collection === index2.collection &&
78
- index1.index === index2.index));
79
- export const ensureView = async (db, viewInfo) => {
80
- const view = db.view(viewInfo.name);
81
- if (await view.exists()) {
82
- const viewData = await view.properties();
83
- if (viewData.type === 'search-alias' && isEqualView(viewData, viewInfo)) {
84
- return view;
85
- }
86
- else {
87
- await view.drop();
88
- }
89
- }
90
- await view.create(viewInfo);
91
- };
92
- const replaceEdgeDefinition = (db) => (edgeDefinition) => db
93
- .listGraphs()
94
- .then((graphInfos) => graphInfos.map((gi) => gi.edgeDefinitions).flat())
95
- .then((edgeDefinitions) => edgeDefinitions.find((ed) => ed.collection === edgeDefinition.collection) || edgeDefinition);
96
- export const ensureGraph = async (db, name, edgeDefinitions) => {
97
- const replacedEdgeDefinitions = await Promise.all(edgeDefinitions.map(replaceEdgeDefinition(db)));
98
- const graph = db.graph(name);
99
- if (await graph.exists()) {
100
- const edgeDefinitionsToAdd = await asyncFilter(replacedEdgeDefinitions, (ed) => graph
101
- .listEdgeCollections()
102
- .then((ecs) => !ecs.includes(collectionName(ed.collection))));
103
- const edgeDefinitionsToRemove = await graph
104
- .listEdgeCollections()
105
- .then((ecs) => ecs.filter((ec) => !replacedEdgeDefinitions
106
- .map((ed) => collectionName(ed.collection))
107
- .includes(ec)));
108
- for (const edgeDefinition of edgeDefinitionsToAdd) {
109
- await graph.addEdgeDefinition(edgeDefinition);
110
- }
111
- for (const edgeDefinitionCollectionName of edgeDefinitionsToRemove) {
112
- await graph.removeEdgeDefinition(edgeDefinitionCollectionName);
113
- }
114
- }
115
- else {
116
- return await db.createGraph(name, replacedEdgeDefinitions);
117
- }
118
- return graph;
119
- };
120
- export const ensureFunction = async (db, { name, dbFunction }) => {
121
- console.log('--------------------------------');
122
- console.log('ensureFunction', name);
123
- console.log('--------------------------------');
124
- console.log(dbFunction.toString());
125
- console.log('--------------------------------');
126
- db.createUserFunction(`ALLPEEP::${name}`, dbFunction.toString(), true);
127
- };
128
- const setId = (document) => (Object.assign(Object.assign({}, document), { id: document._key }));
129
- export const createEdge = async (collection, document) => {
130
- var _a;
131
- const data = Object.assign(Object.assign({}, document), { _key: (_a = document.id) !== null && _a !== void 0 ? _a : uuidv7() });
132
- const createdEdge = (await collection.save(data, { returnNew: true })).new;
133
- if (createdEdge) {
134
- return setId(createdEdge);
135
- }
136
- else {
137
- throw Error(`Edge in collection ${collection.name} could not be created.`);
138
- }
139
- };
140
- export const updateEdge = async (collection, documentKey, document) => (await collection.update(documentKey, document, { returnNew: true })).new;
141
- export const deleteEdge = async (collection, documentKey) => await collection.remove(documentKey);
142
- export const findOneBy = (db, collectionInfo) => (filter) => query().collection(collectionInfo.name).filter(filter).first(db);
143
- export const edgeCollections = async (database) => database
144
- .collections()
145
- .then((collections) => asyncFilter(collections, async (c) => c.properties().then((p) => p.type === CollectionType.EDGE_COLLECTION)));
146
- const getEdge = async (db, collection, from, to) => findOneBy(db, collection)({
147
- name: literal(collectionElement(collection)),
148
- matches: { _from: from, _to: to },
149
- });
150
7
  const getPgEdge = async (db, edgeCollectionName, fromId, toId) => {
151
8
  const edgeConfig = edgeRegistry[edgeCollectionName];
152
9
  if (!edgeConfig) {
@@ -171,14 +28,14 @@ export const connector = (fromCollectionInfo, toCollectionInfo, edgeCollectionIn
171
28
  const id = await insertEdge(db, edgeConfig.table, from.id, to.id, data);
172
29
  return Object.assign(Object.assign({}, data), { id, _from: `${fromCollectionInfo.name}/${from.id}`, _to: `${toCollectionInfo.name}/${to.id}` });
173
30
  };
174
- export const disconnector = (fromCollectionInfo, toCollectionInfo, edgeCollectionInfo) => async (db, from, to) => {
31
+ export const disconnector = (_fromCollectionInfo, _toCollectionInfo, edgeCollectionInfo) => async (db, from, to) => {
175
32
  const edgeConfig = edgeRegistry[edgeCollectionInfo.name];
176
33
  if (!edgeConfig) {
177
34
  throw new Error(`Unknown edge collection: ${edgeCollectionInfo.name}`);
178
35
  }
179
36
  await deletePgEdge(db, edgeConfig.table, from.id, to.id);
180
37
  };
181
- export const connectionUpdater = (fromCollectionInfo, toCollectionInfo, edgeCollectionInfo) => async (db, from, to, data) => {
38
+ export const connectionUpdater = (_fromCollectionInfo, _toCollectionInfo, edgeCollectionInfo) => async (db, from, to, data) => {
182
39
  const edgeConfig = edgeRegistry[edgeCollectionInfo.name];
183
40
  if (!edgeConfig) {
184
41
  throw new Error(`Unknown edge collection: ${edgeCollectionInfo.name}`);
@@ -205,17 +62,30 @@ export const sortOldestFirst = (mapping) => mapping.sort(sorts.idAsc);
205
62
  export const addStartLimit = (mapping, start, limit = 100) => filterBefore(sortNewestFirst(mapping.limit(limit)), start);
206
63
  export const addStart = (mapping, start) => filterBefore(sortNewestFirst(mapping), start);
207
64
  const buildLimit = (limit, offset) => limit && offset ? [offset, limit] : limit;
65
+ /**
66
+ * Ceiling on base rows read for one page, as a multiple of the page size. A
67
+ * post-filter that rejects everything would otherwise walk (and hydrate) the
68
+ * whole collection before returning an empty page.
69
+ */
70
+ const MAX_SCAN_FACTOR = 10;
208
71
  export const filterAndTransform = async (queryResult, db, options) => {
209
- const { filter = (_) => true, transform = async (i) => i, limit = 100, offset = 0, } = options;
72
+ const { filter = () => true, transform = async (i) => i, limit = 100, offset = 0, } = options;
210
73
  const result = [];
74
+ const maxScan = limit * MAX_SCAN_FACTOR;
75
+ let scanned = 0;
211
76
  let pageOffset = 0;
212
- while (result.length < limit) {
213
- const nextPageLength = (limit - result.length) * 2;
77
+ while (result.length < limit && scanned < maxScan) {
78
+ const shortfall = limit - result.length;
79
+ // Transform is the expensive part, so read only what the page still needs
80
+ // until a page proves the filter is dropping rows; then over-fetch to
81
+ // converge without a round trip per remaining row.
82
+ const nextPageLength = Math.min(pageOffset === 0 ? shortfall : shortfall * 2, maxScan - scanned);
214
83
  const list = await queryResult
215
84
  .limit(buildLimit(nextPageLength, offset + pageOffset))
216
85
  .all(db);
217
86
  const filteredList = await Promise.all(list.map(transform)).then((items) => items.filter(filter));
218
- result.push(...filteredList.slice(0, limit - result.length));
87
+ result.push(...filteredList.slice(0, shortfall));
88
+ scanned += list.length;
219
89
  if (list.length < nextPageLength) {
220
90
  break;
221
91
  }
@@ -10,4 +10,6 @@ export type { PgFilter, SqlFilter } from './pg/map/queryTypes';
10
10
  export { combine, createdAtBetween, documentKeyAfter, documentKeyBefore, edgeFilters, eventTimeFilters, groupFilters, isSqlFilter, notificationFilters, pgSql, postFilters, profileFilters, } from './pg/filters';
11
11
  export { computedFields, sorts } from './pg/queries';
12
12
  export declare const allpeepDb: () => Promise<OpenpeepsDatabase>;
13
+ /** Clear the cached DB after `closePostgres()` so the next call re-inits. */
14
+ export declare const resetAllpeepDb: () => void;
13
15
  export declare const database: () => Promise<PgDb>;
package/dist/db/index.js CHANGED
@@ -12,4 +12,8 @@ export const allpeepDb = () => {
12
12
  }
13
13
  return dbPromise;
14
14
  };
15
+ /** Clear the cached DB after `closePostgres()` so the next call re-inits. */
16
+ export const resetAllpeepDb = () => {
17
+ dbPromise = undefined;
18
+ };
15
19
  export const database = () => allpeepDb().then(({ db }) => db);
package/dist/db/init.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { logger } from '../log/index.js';
2
- import { maybeAutoMigrateFromArango } from './migration/autoMigrate.js';
3
2
  import { initPostgres } from './pg/client.js';
4
3
  const log = logger('openpeeps:db');
5
4
  export const initDb = async () => {
6
5
  log.info('Initializing Postgres');
6
+ if (process.env.AUTO_MIGRATE_FROM_ARANGO === 'true') {
7
+ log.warn('AUTO_MIGRATE_FROM_ARANGO is ignored at runtime. Use @openpeepshq/arango-migrate (archive/arango-migrate) for Arango cutover.');
8
+ }
7
9
  const db = await initPostgres();
8
- await maybeAutoMigrateFromArango();
9
10
  return { db };
10
11
  };
@@ -1,6 +1,3 @@
1
1
  declare const isUndefinedTableError: (err: unknown) => boolean;
2
2
  export declare const tableCount: (collection: string) => Promise<number>;
3
- export declare const isPostgresEmpty: () => Promise<boolean>;
4
3
  export { isUndefinedTableError };
5
- export declare const isArangoAvailable: () => Promise<boolean>;
6
- export declare const arangoHasSourceData: () => Promise<boolean>;