@openpeepshq/core 0.1.34 → 0.1.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/accessTokens/finders.js +5 -6
  2. package/dist/accessTokens/mutations.js +1 -1
  3. package/dist/accessTokens/tokens.js +8 -11
  4. package/dist/accounts/helpers.js +6 -2
  5. package/dist/accounts/mutations.js +13 -8
  6. package/dist/analytics/cache.js +3 -3
  7. package/dist/analytics/clicks.js +14 -22
  8. package/dist/analytics/compile.js +1 -2
  9. package/dist/analytics/dateRange.js +3 -5
  10. package/dist/analytics/jobs.js +3 -4
  11. package/dist/analytics/pdfReport.js +45 -61
  12. package/dist/analytics/privacy.js +1 -1
  13. package/dist/analytics/read.js +116 -135
  14. package/dist/analytics/report.d.ts +2 -1
  15. package/dist/analytics/report.js +2 -3
  16. package/dist/analytics/settings.js +3 -4
  17. package/dist/backups/index.js +13 -16
  18. package/dist/backups/metadata.js +1 -1
  19. package/dist/config/db.js +2 -4
  20. package/dist/config/defaults/community.js +1 -0
  21. package/dist/config/defaults/core.js +13 -8
  22. package/dist/config/index.d.ts +1 -0
  23. package/dist/config/index.js +9 -11
  24. package/dist/db/explorer/query.js +9 -8
  25. package/dist/db/explorer/sql.js +8 -8
  26. package/dist/db/helpers.js +15 -5
  27. package/dist/db/migration/importCollections.js +15 -18
  28. package/dist/db/migration/shared.js +15 -35
  29. package/dist/db/pg/client.js +4 -7
  30. package/dist/db/pg/filters/index.js +1 -1
  31. package/dist/db/pg/filters/posts.d.ts +2 -0
  32. package/dist/db/pg/filters/posts.js +2 -0
  33. package/dist/db/pg/helpers.js +2 -14
  34. package/dist/db/pg/map/filters.js +8 -8
  35. package/dist/db/pg/map/helpers.js +5 -1
  36. package/dist/db/pg/map/index.js +46 -51
  37. package/dist/db/pg/map/mutations.js +56 -21
  38. package/dist/db/pg/map/registry.js +87 -50
  39. package/dist/db/pg/map/relations.js +67 -63
  40. package/dist/db/pg/map/search.js +15 -37
  41. package/dist/db/pg/mappers.js +13 -7
  42. package/dist/db/pg/migrate.js +2 -3
  43. package/dist/db/pg/queries/activity.js +2 -2
  44. package/dist/db/pg/queries/derived.js +8 -12
  45. package/dist/db/pg/schema/documents.js +119 -18
  46. package/dist/db/pg/schema/edges.js +7 -1
  47. package/dist/db/pg/schema/index.js +5 -1
  48. package/dist/db/pg/sql/0016_posts_search_vector_title_tags_path.sql +54 -0
  49. package/dist/db/pg/sql/meta/_journal.json +8 -1
  50. package/dist/db/replaceOrigin.js +1 -1
  51. package/dist/email/queueStats.js +8 -11
  52. package/dist/email/render.js +7 -4
  53. package/dist/email/send.js +19 -17
  54. package/dist/email/smtpTest.js +10 -6
  55. package/dist/errors/index.js +1 -1
  56. package/dist/events/once.js +2 -4
  57. package/dist/federation/activities.js +1 -2
  58. package/dist/groups/helpers.js +1 -2
  59. package/dist/groups/mutations.js +1 -1
  60. package/dist/hashtags/finders.js +2 -2
  61. package/dist/inviteLinks/mutations.js +2 -3
  62. package/dist/jams/export.js +5 -7
  63. package/dist/jams/finders.js +4 -1
  64. package/dist/jams/health.d.ts +6 -4
  65. package/dist/jams/health.js +15 -11
  66. package/dist/jams/helpers.js +6 -2
  67. package/dist/jams/index.js +2 -2
  68. package/dist/jams/jobs.js +1 -2
  69. package/dist/jams/livekit.js +8 -8
  70. package/dist/jams/recording.js +1 -1
  71. package/dist/jams/token.js +13 -17
  72. package/dist/jobs/index.js +7 -6
  73. package/dist/jobs/jobDetail.js +5 -6
  74. package/dist/jobs/jobLog.js +2 -3
  75. package/dist/lib/streams.js +4 -39
  76. package/dist/lib/zodDeepPartial.d.ts +1 -1
  77. package/dist/lib/zodDeepPartial.js +1 -1
  78. package/dist/log/index.js +13 -29
  79. package/dist/media/index.js +50 -4
  80. package/dist/media/jobs.js +1 -2
  81. package/dist/media/openpeeps/index.js +11 -46
  82. package/dist/media/processing.js +7 -4
  83. package/dist/media/streaming.js +5 -5
  84. package/dist/media/streamingCleanupJobs.js +1 -2
  85. package/dist/media/streamingJobs.js +3 -4
  86. package/dist/media/streamingPrewarm.js +7 -11
  87. package/dist/mediaAttachments/index.js +6 -2
  88. package/dist/notifications/defaultNotifications/announcement/index.js +15 -18
  89. package/dist/notifications/defaultNotifications/directMessage/index.js +9 -8
  90. package/dist/notifications/defaultNotifications/follow/index.js +14 -17
  91. package/dist/notifications/defaultNotifications/groupAdded/index.js +14 -17
  92. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +15 -18
  93. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +15 -18
  94. package/dist/notifications/defaultNotifications/jamModerator/index.js +3 -5
  95. package/dist/notifications/defaultNotifications/jamSpeaker/index.js +14 -18
  96. package/dist/notifications/defaultNotifications/jamStarted/index.js +18 -22
  97. package/dist/notifications/defaultNotifications/mention/index.js +20 -24
  98. package/dist/notifications/defaultNotifications/newGroupPost/index.js +6 -7
  99. package/dist/notifications/defaultNotifications/newProfile/index.js +14 -17
  100. package/dist/notifications/defaultNotifications/pollEnded/index.js +21 -21
  101. package/dist/notifications/defaultNotifications/pollEnded/recipients.js +2 -3
  102. package/dist/notifications/defaultNotifications/pollVote/index.js +14 -17
  103. package/dist/notifications/defaultNotifications/reaction/index.js +18 -21
  104. package/dist/notifications/defaultNotifications/reply/index.js +21 -22
  105. package/dist/notifications/defaultNotifications/repost/index.js +16 -20
  106. package/dist/notifications/defaultNotifications/rsvp/index.js +24 -18
  107. package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +20 -13
  108. package/dist/notifications/fcmCredential.js +1 -1
  109. package/dist/notifications/finders.js +1 -1
  110. package/dist/notifications/helpers.js +13 -10
  111. package/dist/notifications/jobs.js +10 -7
  112. package/dist/notifications/mutations.js +4 -1
  113. package/dist/notifications/push.js +11 -16
  114. package/dist/performance/index.js +3 -3
  115. package/dist/plugins/helpers.js +3 -6
  116. package/dist/plugins/index.js +2 -3
  117. package/dist/plugins/install.js +31 -17
  118. package/dist/plugins/pluginAuth.js +3 -4
  119. package/dist/plugins/state.js +2 -3
  120. package/dist/posts/activity.js +1 -2
  121. package/dist/posts/contextClosure.js +1 -2
  122. package/dist/posts/conversationQueries.js +2 -4
  123. package/dist/posts/eventAgenda.js +8 -5
  124. package/dist/posts/eventOccurrences.js +2 -2
  125. package/dist/posts/finders.d.ts +42 -2
  126. package/dist/posts/finders.js +21 -9
  127. package/dist/posts/helpers/filters.js +2 -3
  128. package/dist/posts/helpers/index.d.ts +152 -0
  129. package/dist/posts/helpers/index.js +43 -27
  130. package/dist/posts/mapping.d.ts +546 -14
  131. package/dist/posts/mapping.js +60 -18
  132. package/dist/posts/mutations.d.ts +76 -0
  133. package/dist/posts/mutations.js +46 -31
  134. package/dist/posts/pollEnd.js +3 -6
  135. package/dist/posts/rsvpConfirmationEmail.js +18 -8
  136. package/dist/posts/threadPreview.js +1 -1
  137. package/dist/processingStats/queries.js +6 -7
  138. package/dist/profileSettings/cache.js +1 -2
  139. package/dist/profiles/activitySummary.js +23 -28
  140. package/dist/profiles/cache.js +15 -8
  141. package/dist/profiles/export.js +30 -39
  142. package/dist/profiles/finders.js +7 -5
  143. package/dist/profiles/mutations.js +3 -5
  144. package/dist/redis/connection.js +1 -1
  145. package/dist/reports/helpers.js +7 -3
  146. package/dist/roles/mutations.js +20 -21
  147. package/dist/search/finders.js +15 -3
  148. package/dist/search/helpers.js +1 -1
  149. package/dist/sentry/index.js +9 -11
  150. package/dist/seo/index.d.ts +50 -0
  151. package/dist/seo/index.js +145 -0
  152. package/dist/seo/route.d.ts +18 -0
  153. package/dist/seo/route.js +19 -0
  154. package/dist/server/index.d.ts +1 -0
  155. package/dist/server/index.js +16 -11
  156. package/dist/server/status.js +6 -7
  157. package/dist/session/index.js +2 -2
  158. package/dist/stats/finders.js +13 -4
  159. package/dist/stats/helpers.js +4 -1
  160. package/dist/stats/mapping.d.ts +39 -1
  161. package/dist/stats/mapping.js +9 -2
  162. package/dist/stripe/cache.js +5 -6
  163. package/dist/stripe/connection.js +3 -4
  164. package/dist/stripe/helpers.js +15 -20
  165. package/package.json +5 -6
@@ -25,13 +25,12 @@ const pathExists = (p) => access(p)
25
25
  /** Safety net if extraction stalls (normal 1 GiB restore finishes in a few minutes). */
26
26
  const EXTRACT_TIMEOUT_MS = 30 * 60 * 1000;
27
27
  const extractWithUnzipCli = (zipPath, tempDir) => {
28
- var _a, _b;
29
28
  const proc = spawn('unzip', ['-qq', '-o', zipPath, '-d', tempDir], {
30
29
  stdio: ['ignore', 'ignore', 'pipe'],
31
30
  });
32
31
  let stderrTail = '';
33
- (_a = proc.stderr) === null || _a === void 0 ? void 0 : _a.setEncoding('utf8');
34
- (_b = proc.stderr) === null || _b === void 0 ? void 0 : _b.on('data', (chunk) => {
32
+ proc.stderr?.setEncoding('utf8');
33
+ proc.stderr?.on('data', (chunk) => {
35
34
  stderrTail = (stderrTail + chunk).slice(-4096);
36
35
  });
37
36
  const promise = new Promise((resolve, reject) => {
@@ -46,7 +45,7 @@ const extractWithUnzipCli = (zipPath, tempDir) => {
46
45
  return;
47
46
  }
48
47
  const detail = stderrTail.trim();
49
- reject(new Error(`unzip exited with code ${code !== null && code !== void 0 ? code : 'null'}${detail ? `: ${detail}` : ''}`));
48
+ reject(new Error(`unzip exited with code ${code ?? 'null'}${detail ? `: ${detail}` : ''}`));
50
49
  });
51
50
  });
52
51
  return {
@@ -84,7 +83,7 @@ const extractZipArchive = (zipPath, tempDir) => {
84
83
  promise,
85
84
  kill: () => {
86
85
  cli.kill();
87
- fallbackKill === null || fallbackKill === void 0 ? void 0 : fallbackKill();
86
+ fallbackKill?.();
88
87
  },
89
88
  };
90
89
  };
@@ -115,7 +114,6 @@ const zipDirectory = (sourceDir, zipPath) => new Promise((resolve, reject) => {
115
114
  * host tree so restored plugins resolve even after an image update.
116
115
  */
117
116
  const relinkRestoredPlugins = async (pluginsPath) => {
118
- var _a, _b;
119
117
  const namespaces = await readdir(pluginsPath).catch(() => []);
120
118
  for (const namespace of namespaces) {
121
119
  const namespaceDir = join(pluginsPath, namespace);
@@ -131,15 +129,15 @@ const relinkRestoredPlugins = async (pluginsPath) => {
131
129
  try {
132
130
  pkg = JSON.parse(await readFile(join(pluginDir, 'package.json'), 'utf8'));
133
131
  }
134
- catch (_c) {
132
+ catch {
135
133
  continue;
136
134
  }
137
- const peers = Object.keys((_a = pkg.peerDependencies) !== null && _a !== void 0 ? _a : {});
135
+ const peers = Object.keys(pkg.peerDependencies ?? {});
138
136
  if (peers.length === 0)
139
137
  continue;
140
138
  const linked = await linkHostPeerDependencies(pluginDir, peers);
141
139
  if (!linked.success) {
142
- log.warn(`Restored plugin ${(_b = pkg.name) !== null && _b !== void 0 ? _b : pluginDir} peer re-link failed: ${linked.error}`);
140
+ log.warn(`Restored plugin ${pkg.name ?? pluginDir} peer re-link failed: ${linked.error}`);
143
141
  }
144
142
  }
145
143
  }
@@ -150,7 +148,7 @@ const withTimeout = (promise, ms, message, onTimeout) => {
150
148
  promise,
151
149
  new Promise((_, reject) => {
152
150
  timeoutId = setTimeout(() => {
153
- onTimeout === null || onTimeout === void 0 ? void 0 : onTimeout();
151
+ onTimeout?.();
154
152
  reject(new Error(message));
155
153
  }, ms);
156
154
  }),
@@ -177,13 +175,13 @@ const assertBackupExtracted = async (tempDir) => {
177
175
  try {
178
176
  await access(metadataPath, constants.F_OK);
179
177
  }
180
- catch (_a) {
178
+ catch {
181
179
  throw new Error('Backup invalid: missing metadata.json (Postgres JSONL archives only)');
182
180
  }
183
181
  try {
184
182
  await access(collectionsPath, constants.F_OK);
185
183
  }
186
- catch (_b) {
184
+ catch {
187
185
  throw new Error('Backup invalid: missing collections/ directory after extract');
188
186
  }
189
187
  const files = await readdir(collectionsPath);
@@ -265,7 +263,6 @@ export const listAllBackups = async () => {
265
263
  .map((filename) => filename.replace('.zip', ''));
266
264
  };
267
265
  export const restoreBackups = async (zipFilePath) => {
268
- var _a, _b, _c;
269
266
  console.log('Restoring backup', zipFilePath);
270
267
  log.info(`Restoring backup ${zipFilePath}`);
271
268
  const coreConfig = await config();
@@ -317,12 +314,12 @@ export const restoreBackups = async (zipFilePath) => {
317
314
  else {
318
315
  log.info('Backup contains no plugins; leaving existing plugins in place.');
319
316
  }
320
- await restoreDatabaseFromBackup(collectionsDir, backupMetadata === null || backupMetadata === void 0 ? void 0 : backupMetadata.schemaVersion);
317
+ await restoreDatabaseFromBackup(collectionsDir, backupMetadata?.schemaVersion);
321
318
  // Repoint the backup's absolute URLs at this server's full origin (scheme +
322
319
  // host + port). Matching by the backup hostname means a prod backup on
323
320
  // `https://host` restores cleanly onto `http://localhost:5174` without
324
321
  // stranding the old scheme/port.
325
- await replaceOrigin((_a = backupMetadata === null || backupMetadata === void 0 ? void 0 : backupMetadata.config) === null || _a === void 0 ? void 0 : _a.hostname, await serverRootUrl());
326
- log.info(`Restored postgres 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'})`);
322
+ await replaceOrigin(backupMetadata?.config?.hostname, await serverRootUrl());
323
+ log.info(`Restored postgres backup (hostname was ${backupMetadata?.config?.hostname ?? 'unknown'})`);
327
324
  await setDefaultRoles();
328
325
  };
@@ -1,5 +1,5 @@
1
1
  export const resolveBackupDatabaseType = (metadata) => {
2
- if ((metadata === null || metadata === void 0 ? void 0 : metadata.databaseType) === 'postgres') {
2
+ if (metadata?.databaseType === 'postgres') {
3
3
  return 'postgres';
4
4
  }
5
5
  throw new Error('Backup is not a Postgres JSONL archive (missing metadata.json databaseType: "postgres")');
package/dist/config/db.js CHANGED
@@ -3,7 +3,6 @@ import { allpeepDb } from '../db/index.js';
3
3
  import { configs } from '../db/pg/schema/documents.js';
4
4
  import { nowIso } from '../db/pg/mappers.js';
5
5
  export const storeConfig = (key, config) => allpeepDb().then(async ({ db }) => {
6
- var _a;
7
6
  const ts = nowIso();
8
7
  const rows = await db
9
8
  .insert(configs)
@@ -13,14 +12,13 @@ export const storeConfig = (key, config) => allpeepDb().then(async ({ db }) => {
13
12
  set: { body: config, updatedAt: ts },
14
13
  })
15
14
  .returning();
16
- return (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.body;
15
+ return rows[0]?.body;
17
16
  });
18
17
  export const loadConfig = (key) => allpeepDb().then(async ({ db }) => {
19
- var _a;
20
18
  const rows = await db
21
19
  .select()
22
20
  .from(configs)
23
21
  .where(eq(configs.key, key))
24
22
  .limit(1);
25
- return (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.body;
23
+ return rows[0]?.body;
26
24
  });
@@ -30,6 +30,7 @@ export const defaultCommunityConfig = {
30
30
  },
31
31
  settings: {
32
32
  openRegistrations: process.env.COMMUNITY_SETTINGS_OPEN_REGISTRATIONS !== 'false',
33
+ indexProfiles: process.env.COMMUNITY_SETTINGS_INDEX_PROFILES === 'true',
33
34
  },
34
35
  content: {},
35
36
  roles: {
@@ -21,14 +21,19 @@ export const defaultConfig = {
21
21
  service: 'smtp',
22
22
  defaultTemplatePath: 'assets/email/templates',
23
23
  defaultFrom: process.env.EMAIL_DEFAULT_FROM,
24
- transportConfig: Object.assign({ host: process.env.EMAIL_CONFIG_HOST || 'localhost', port: readEnvInteger('EMAIL_CONFIG_PORT', 465), secure: process.env.EMAIL_CONFIG_SECURE !== 'false' }, (process.env.EMAIL_CONFIG_AUTH_USER
25
- ? {
26
- auth: {
27
- user: process.env.EMAIL_CONFIG_AUTH_USER,
28
- pass: process.env.EMAIL_CONFIG_AUTH_PASS,
29
- },
30
- }
31
- : {})),
24
+ transportConfig: {
25
+ host: process.env.EMAIL_CONFIG_HOST || 'localhost',
26
+ port: readEnvInteger('EMAIL_CONFIG_PORT', 465),
27
+ secure: process.env.EMAIL_CONFIG_SECURE !== 'false',
28
+ ...(process.env.EMAIL_CONFIG_AUTH_USER
29
+ ? {
30
+ auth: {
31
+ user: process.env.EMAIL_CONFIG_AUTH_USER,
32
+ pass: process.env.EMAIL_CONFIG_AUTH_PASS,
33
+ },
34
+ }
35
+ : {}),
36
+ },
32
37
  },
33
38
  logs,
34
39
  media: {
@@ -234,6 +234,7 @@ export declare const communityConfig: () => Promise<{
234
234
  defaultLanguage?: string | undefined;
235
235
  defaultTimeZone?: string | undefined;
236
236
  defaultFeedFormat?: "threaded" | "linear" | undefined;
237
+ indexProfiles?: boolean | undefined;
237
238
  };
238
239
  roles: {
239
240
  onRegistration: {
@@ -34,7 +34,7 @@ const initConfig = async (namespace, name) => {
34
34
  if (!factory) {
35
35
  throw new Error(`No config registered for ${key}`);
36
36
  }
37
- const customConfig = (customConfigDocument === null || customConfigDocument === void 0 ? void 0 : customConfigDocument.config) &&
37
+ const customConfig = customConfigDocument?.config &&
38
38
  zodDeepPartialSchema(factory()).parse(pruneEmptyConfigStrings(customConfigDocument.config));
39
39
  return (customConfig ? deepmerge(defaults, customConfig) : defaults);
40
40
  };
@@ -56,8 +56,7 @@ const replaceStoredConfig = (config, namespace = 'openpeeps', name = 'core') =>
56
56
  * admin UI forms and pin/unpin all send partial trees.
57
57
  */
58
58
  export const updateConfigValues = (configValues, namespace = 'openpeeps', name = 'core') => loadConfig(configKey(namespace, name)).then((configDocument) => {
59
- var _a;
60
- const stored = (_a = configDocument === null || configDocument === void 0 ? void 0 : configDocument.config) !== null && _a !== void 0 ? _a : {};
59
+ const stored = configDocument?.config ?? {};
61
60
  return replaceStoredConfig(deepmerge(stored, restorePasswordPlaceholders(configValues, stored)), namespace, name);
62
61
  });
63
62
  export const config = (namespace = 'openpeeps', name = 'core') => {
@@ -73,17 +72,16 @@ export const config = (namespace = 'openpeeps', name = 'core') => {
73
72
  return configPromises.get(key);
74
73
  };
75
74
  export const communityConfig = () => config('openpeeps', 'community');
76
- export const capabilitiesConfig = () => config('openpeeps', 'capabilities').then((loaded) => {
77
- var _a, _b;
78
- return (Object.assign(Object.assign({}, loaded), { accessToken: deepmerge((_a = defaultCapabilitiesConfig.accessToken) !== null && _a !== void 0 ? _a : {}, (_b = loaded.accessToken) !== null && _b !== void 0 ? _b : {}) }));
79
- });
75
+ export const capabilitiesConfig = () => config('openpeeps', 'capabilities').then((loaded) => ({
76
+ ...loaded,
77
+ accessToken: deepmerge(defaultCapabilitiesConfig.accessToken ?? {}, loaded.accessToken ?? {}),
78
+ }));
80
79
  export const sanitizedConfigWithDefaults = async (namespace = 'openpeeps', name = 'core') => {
81
- var _a;
82
80
  const key = configKey(namespace, name);
83
- const { defaults, factory } = (_a = configSchemaRegistry.get(key)) !== null && _a !== void 0 ? _a : {};
81
+ const { defaults, factory } = configSchemaRegistry.get(key) ?? {};
84
82
  const sanitizedSchema = factory && factory(true);
85
83
  return {
86
- config: sanitizedSchema === null || sanitizedSchema === void 0 ? void 0 : sanitizedSchema.parse(await config(namespace, name)),
87
- defaults: sanitizedSchema === null || sanitizedSchema === void 0 ? void 0 : sanitizedSchema.parse(defaults),
84
+ config: sanitizedSchema?.parse(await config(namespace, name)),
85
+ defaults: sanitizedSchema?.parse(defaults),
88
86
  };
89
87
  };
@@ -2,10 +2,10 @@ import { pgPool } from '../pg/client.js';
2
2
  import { assertKnownColumns, describeExplorerTable, getExplorerTable, primaryKeyColumns, quoteIdent, } from './tables.js';
3
3
  export const DEFAULT_ROW_LIMIT = 100;
4
4
  /** Hard cap for browse page sizes (50 / 200 / 1000 / All). */
5
- export const MAX_ROW_LIMIT = 10000;
6
- export const MAX_EXPORT_LIMIT = 10000;
5
+ export const MAX_ROW_LIMIT = 10_000;
6
+ export const MAX_EXPORT_LIMIT = 10_000;
7
7
  export const clampLimit = (limit, max) => {
8
- const n = limit !== null && limit !== void 0 ? limit : DEFAULT_ROW_LIMIT;
8
+ const n = limit ?? DEFAULT_ROW_LIMIT;
9
9
  if (!Number.isFinite(n) || n < 1)
10
10
  return DEFAULT_ROW_LIMIT;
11
11
  return Math.min(Math.floor(n), max);
@@ -21,13 +21,14 @@ export const buildFilterClause = (tableName, filters, params) => {
21
21
  return ` WHERE ${parts.join(' AND ')}`;
22
22
  };
23
23
  export const listExplorerRows = async (input, options) => {
24
- var _a, _b, _c, _d, _e, _f, _g, _h;
25
24
  const tableName = input.table;
26
25
  const meta = describeExplorerTable(getExplorerTable(tableName));
27
- const maxLimit = (_a = options === null || options === void 0 ? void 0 : options.maxLimit) !== null && _a !== void 0 ? _a : MAX_ROW_LIMIT;
26
+ const maxLimit = options?.maxLimit ?? MAX_ROW_LIMIT;
28
27
  const limit = clampLimit(input.limit, maxLimit);
29
- const offset = Math.max(0, Math.floor((_b = input.offset) !== null && _b !== void 0 ? _b : 0));
30
- const orderCol = (_e = (_c = input.orderBy) !== null && _c !== void 0 ? _c : (_d = primaryKeyColumns(tableName)[0]) === null || _d === void 0 ? void 0 : _d.name) !== null && _e !== void 0 ? _e : (_f = meta.columns[0]) === null || _f === void 0 ? void 0 : _f.name;
28
+ const offset = Math.max(0, Math.floor(input.offset ?? 0));
29
+ const orderCol = input.orderBy ??
30
+ primaryKeyColumns(tableName)[0]?.name ??
31
+ meta.columns[0]?.name;
31
32
  if (!orderCol) {
32
33
  throw new Error(`Table ${tableName} has no columns`);
33
34
  }
@@ -36,7 +37,7 @@ export const listExplorerRows = async (input, options) => {
36
37
  const where = buildFilterClause(tableName, input.filters, filterParams);
37
38
  const tableSql = quoteIdent(tableName);
38
39
  const countResult = await pgPool().query(`SELECT count(*)::text AS count FROM ${tableSql}${where}`, filterParams);
39
- const total = Number((_h = (_g = countResult.rows[0]) === null || _g === void 0 ? void 0 : _g.count) !== null && _h !== void 0 ? _h : 0);
40
+ const total = Number(countResult.rows[0]?.count ?? 0);
40
41
  const result = await pgPool().query(`SELECT * FROM ${tableSql}${where} ORDER BY ${quoteIdent(orderCol)} LIMIT $${filterParams.length + 1} OFFSET $${filterParams.length + 2}`, [...filterParams, limit, offset]);
41
42
  return {
42
43
  columns: meta.columns.map((c) => c.name),
@@ -1,18 +1,17 @@
1
1
  import { pgPool } from '../pg/client.js';
2
- export const SQL_STATEMENT_TIMEOUT_MS = 15000;
2
+ export const SQL_STATEMENT_TIMEOUT_MS = 15_000;
3
3
  /** Absolute cap for returned SQL rows (All). */
4
- export const SQL_HARD_MAX_ROWS = 100000;
4
+ export const SQL_HARD_MAX_ROWS = 100_000;
5
5
  /** Default cap when the client does not request a limit. */
6
- export const SQL_DEFAULT_MAX_ROWS = 1000;
6
+ export const SQL_DEFAULT_MAX_ROWS = 1_000;
7
7
  /** @deprecated Use SQL_HARD_MAX_ROWS */
8
8
  export const SQL_MAX_ROWS = SQL_HARD_MAX_ROWS;
9
9
  export const runExplorerSql = async (statement, options) => {
10
- var _a, _b, _c;
11
10
  const trimmed = statement.trim();
12
11
  if (!trimmed) {
13
12
  throw new Error('SQL statement is empty');
14
13
  }
15
- const requested = options === null || options === void 0 ? void 0 : options.limit;
14
+ const requested = options?.limit;
16
15
  const maxRows = requested != null && Number.isFinite(requested) && requested > 0
17
16
  ? Math.min(Math.floor(requested), SQL_HARD_MAX_ROWS)
18
17
  : SQL_DEFAULT_MAX_ROWS;
@@ -22,11 +21,12 @@ export const runExplorerSql = async (statement, options) => {
22
21
  const result = await client.query(trimmed);
23
22
  const allRows = result.rows;
24
23
  const rows = allRows.slice(0, maxRows);
25
- const columns = (_b = (_a = result.fields) === null || _a === void 0 ? void 0 : _a.map((f) => f.name)) !== null && _b !== void 0 ? _b : (rows[0] ? Object.keys(rows[0]) : []);
24
+ const columns = result.fields?.map((f) => f.name) ??
25
+ (rows[0] ? Object.keys(rows[0]) : []);
26
26
  return {
27
27
  columns,
28
28
  rows,
29
- rowCount: (_c = result.rowCount) !== null && _c !== void 0 ? _c : allRows.length,
29
+ rowCount: result.rowCount ?? allRows.length,
30
30
  command: result.command,
31
31
  };
32
32
  }
@@ -34,7 +34,7 @@ export const runExplorerSql = async (statement, options) => {
34
34
  try {
35
35
  await client.query('SET statement_timeout = 0');
36
36
  }
37
- catch (_d) {
37
+ catch {
38
38
  // ignore reset failures on a broken connection
39
39
  }
40
40
  client.release();
@@ -19,7 +19,12 @@ const getPgEdge = async (db, edgeCollectionName, fromId, toId) => {
19
19
  const row = rows[0];
20
20
  if (!row)
21
21
  return undefined;
22
- return Object.assign(Object.assign({}, row.body), { id: row.id, _from: `${edgeConfig.fromCollection}/${row.fromId}`, _to: `${edgeConfig.toCollection}/${row.toId}` });
22
+ return {
23
+ ...row.body,
24
+ id: row.id,
25
+ _from: `${edgeConfig.fromCollection}/${row.fromId}`,
26
+ _to: `${edgeConfig.toCollection}/${row.toId}`,
27
+ };
23
28
  };
24
29
  export const connector = (fromCollectionInfo, toCollectionInfo, edgeCollectionInfo) => async (db, from, to, data = {}) => {
25
30
  const edgeConfig = edgeRegistry[edgeCollectionInfo.name];
@@ -27,7 +32,12 @@ export const connector = (fromCollectionInfo, toCollectionInfo, edgeCollectionIn
27
32
  throw new Error(`Unknown edge collection: ${edgeCollectionInfo.name}`);
28
33
  }
29
34
  const id = await insertEdge(db, edgeConfig.table, from.id, to.id, data);
30
- return Object.assign(Object.assign({}, data), { id, _from: `${fromCollectionInfo.name}/${from.id}`, _to: `${toCollectionInfo.name}/${to.id}` });
35
+ return {
36
+ ...data,
37
+ id,
38
+ _from: `${fromCollectionInfo.name}/${from.id}`,
39
+ _to: `${toCollectionInfo.name}/${to.id}`,
40
+ };
31
41
  };
32
42
  export const disconnector = (_fromCollectionInfo, _toCollectionInfo, edgeCollectionInfo) => async (db, from, to) => {
33
43
  const edgeConfig = edgeRegistry[edgeCollectionInfo.name];
@@ -45,7 +55,7 @@ export const connectionUpdater = (_fromCollectionInfo, _toCollectionInfo, edgeCo
45
55
  await db
46
56
  .update(edgeConfig.table)
47
57
  .set({
48
- body: data !== null && data !== void 0 ? data : {},
58
+ body: data ?? {},
49
59
  updatedAt: nowIso(),
50
60
  })
51
61
  .where(and(eq(table.fromId, from.id), eq(table.toId, to.id)));
@@ -57,11 +67,11 @@ export const filterBefore = (mapping, id) => id
57
67
  export const filterAfter = (mapping, id) => id
58
68
  ? mapping.filter(documentKeyAfter(mapping.data().collection, id))
59
69
  : mapping;
60
- export const addQuerySort = (mapping, sort) => ((sort === null || sort === void 0 ? void 0 : sort.length) ? mapping.sort(sort) : mapping);
70
+ export const addQuerySort = (mapping, sort) => (sort?.length ? mapping.sort(sort) : mapping);
61
71
  export const sortNewestFirst = (mapping) => mapping.sort(sorts.idDesc);
62
72
  export const sortOldestFirst = (mapping) => mapping.sort(sorts.idAsc);
63
73
  export const addStartLimit = (mapping, start, limit = 100) => filterBefore(sortNewestFirst(mapping.limit(limit)), start);
64
- export const addStart = (mapping, start) => { var _a; return filterBefore(sortNewestFirst(mapping), (_a = parseFeedCursor(start)) === null || _a === void 0 ? void 0 : _a.id); };
74
+ export const addStart = (mapping, start) => filterBefore(sortNewestFirst(mapping), parseFeedCursor(start)?.id);
65
75
  export const addActivityStart = (mapping, start) => {
66
76
  const sorted = mapping.sort(sorts.lastActivityDesc);
67
77
  const cursor = parseFeedCursor(start);
@@ -20,7 +20,7 @@ const normalizeImportId = (value) => {
20
20
  }
21
21
  return UUID_RE.test(trimmed) ? trimmed.toLowerCase() : trimmed;
22
22
  };
23
- const rowDedupeKey = (row) => { var _a; return normalizeImportId((_a = row.id) !== null && _a !== void 0 ? _a : row.key); };
23
+ const rowDedupeKey = (row) => normalizeImportId(row.id ?? row.key);
24
24
  /** Keep the last row per id when a JSONL file repeats keys. */
25
25
  export const dedupeRowsById = (rows) => {
26
26
  const byKey = new Map();
@@ -28,7 +28,7 @@ export const dedupeRowsById = (rows) => {
28
28
  for (const row of rows) {
29
29
  const key = rowDedupeKey(row);
30
30
  if (key) {
31
- byKey.set(key, typeof row.id === 'string' ? Object.assign(Object.assign({}, row), { id: key }) : row);
31
+ byKey.set(key, typeof row.id === 'string' ? { ...row, id: key } : row);
32
32
  }
33
33
  else {
34
34
  withoutKey.push(row);
@@ -39,7 +39,6 @@ export const dedupeRowsById = (rows) => {
39
39
  export const collectionJsonlPath = (collectionsDir, collection) => join(collectionsDir, `${collection}.jsonl`);
40
40
  const isKnownCollection = (collection) => collection in documentRegistry || collection in edgeRegistry;
41
41
  export const truncateAllTables = async () => {
42
- var _a;
43
42
  const db = pgDb();
44
43
  const tableNames = [
45
44
  ...EDGE_IMPORT_ORDER.map((collection) => getTableName(edgeRegistry[collection].table)),
@@ -50,7 +49,7 @@ export const truncateAllTables = async () => {
50
49
  const existing = [];
51
50
  for (const name of tableNames) {
52
51
  const result = await db.execute(sql.raw(`SELECT to_regclass('public.${name}')::text AS regclass`));
53
- if (((_a = result.rows[0]) === null || _a === void 0 ? void 0 : _a.regclass) != null) {
52
+ if (result.rows[0]?.regclass != null) {
54
53
  existing.push(name);
55
54
  }
56
55
  }
@@ -61,15 +60,14 @@ export const truncateAllTables = async () => {
61
60
  };
62
61
  export const isUuid = (value) => typeof value === 'string' && UUID_RE.test(value);
63
62
  const ensureEdgeUuidId = (collection, row) => {
64
- var _a;
65
63
  if (!isEdgeCollection(collection)) {
66
64
  return row;
67
65
  }
68
66
  if (isUuid(row.id)) {
69
- const normalized = (_a = normalizeImportId(row.id)) !== null && _a !== void 0 ? _a : String(row.id);
70
- return normalized === row.id ? row : Object.assign(Object.assign({}, row), { id: normalized });
67
+ const normalized = normalizeImportId(row.id) ?? String(row.id);
68
+ return normalized === row.id ? row : { ...row, id: normalized };
71
69
  }
72
- const next = Object.assign(Object.assign({}, row), { id: randomUUID() });
70
+ const next = { ...row, id: randomUUID() };
73
71
  log.warn('Replaced non-UUID %s edge id %s with %s', collection, String(row.id), next.id);
74
72
  return next;
75
73
  };
@@ -81,7 +79,7 @@ export const importPostgresRowCollection = async (collection, collectionsDir) =>
81
79
  try {
82
80
  await access(filePath, constants.F_OK);
83
81
  }
84
- catch (_a) {
82
+ catch {
85
83
  return 0;
86
84
  }
87
85
  const mapped = await readJsonl(filePath);
@@ -106,9 +104,8 @@ export const importPostgresRowCollection = async (collection, collectionsDir) =>
106
104
  };
107
105
  /** Legacy reactions rows become append-only reaction entries. */
108
106
  export const wrapReactionEntryBody = (body) => {
109
- var _a;
110
- if ((body === null || body === void 0 ? void 0 : body.type) === 'reaction') {
111
- const reaction = typeof ((_a = body.data) === null || _a === void 0 ? void 0 : _a.reaction) ===
107
+ if (body?.type === 'reaction') {
108
+ const reaction = typeof body.data?.reaction ===
112
109
  'string'
113
110
  ? body.data.reaction
114
111
  : typeof body.reaction === 'string'
@@ -116,7 +113,7 @@ export const wrapReactionEntryBody = (body) => {
116
113
  : '👍';
117
114
  return { type: 'reaction', data: { reaction } };
118
115
  }
119
- const reaction = typeof (body === null || body === void 0 ? void 0 : body.reaction) === 'string' ? body.reaction : '👍';
116
+ const reaction = typeof body?.reaction === 'string' ? body.reaction : '👍';
120
117
  return { type: 'reaction', data: { reaction } };
121
118
  };
122
119
  const insertEntryRows = async (rows) => {
@@ -138,17 +135,17 @@ export const importLegacyReactionsAsEntries = async (collectionsDir) => {
138
135
  try {
139
136
  await access(filePath, constants.F_OK);
140
137
  }
141
- catch (_a) {
138
+ catch {
142
139
  return 0;
143
140
  }
144
141
  const docs = await readJsonl(filePath);
145
142
  if (docs.length === 0) {
146
143
  return 0;
147
144
  }
148
- const mapped = docs.map((doc) => {
149
- var _a;
150
- return ensureEdgeUuidId('entries', Object.assign(Object.assign({}, doc), { body: wrapReactionEntryBody((_a = doc.body) !== null && _a !== void 0 ? _a : doc) }));
151
- });
145
+ const mapped = docs.map((doc) => ensureEdgeUuidId('entries', {
146
+ ...doc,
147
+ body: wrapReactionEntryBody(doc.body ?? doc),
148
+ }));
152
149
  const rows = dedupeRowsById(mapped);
153
150
  const imported = await insertEntryRows(rows);
154
151
  log.info('Imported %d legacy reactions as entries', imported);
@@ -1,10 +1,3 @@
1
- var __asyncValues = (this && this.__asyncValues) || function (o) {
2
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3
- var m = o[Symbol.asyncIterator], i;
4
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
5
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
6
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
7
- };
8
1
  import { createReadStream } from 'node:fs';
9
2
  import { createInterface } from 'node:readline';
10
3
  export const DOCUMENT_IMPORT_ORDER = [
@@ -55,43 +48,30 @@ export const EDGE_IMPORT_ORDER = [
55
48
  'profileHashtags',
56
49
  ];
57
50
  export const readJsonl = async (filePath) => {
58
- var _a, e_1, _b, _c;
59
51
  const docs = [];
60
52
  let buffer = '';
61
53
  const lineReader = createInterface({
62
54
  input: createReadStream(filePath),
63
55
  crlfDelay: Infinity,
64
56
  });
65
- try {
66
- for (var _d = true, lineReader_1 = __asyncValues(lineReader), lineReader_1_1; lineReader_1_1 = await lineReader_1.next(), _a = lineReader_1_1.done, !_a; _d = true) {
67
- _c = lineReader_1_1.value;
68
- _d = false;
69
- const line = _c;
70
- if (!line.trim()) {
71
- continue;
72
- }
73
- buffer += line;
74
- try {
75
- docs.push(JSON.parse(buffer));
76
- buffer = '';
77
- }
78
- catch (err) {
79
- const message = err instanceof Error ? err.message : String(err);
80
- const partialJson = message.includes('Unexpected end of JSON input') ||
81
- message.includes('Unterminated string') ||
82
- message.includes('Unexpected token');
83
- if (!partialJson) {
84
- throw err;
85
- }
86
- }
57
+ for await (const line of lineReader) {
58
+ if (!line.trim()) {
59
+ continue;
87
60
  }
88
- }
89
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
90
- finally {
61
+ buffer += line;
91
62
  try {
92
- if (!_d && !_a && (_b = lineReader_1.return)) await _b.call(lineReader_1);
63
+ docs.push(JSON.parse(buffer));
64
+ buffer = '';
65
+ }
66
+ catch (err) {
67
+ const message = err instanceof Error ? err.message : String(err);
68
+ const partialJson = message.includes('Unexpected end of JSON input') ||
69
+ message.includes('Unterminated string') ||
70
+ message.includes('Unexpected token');
71
+ if (!partialJson) {
72
+ throw err;
73
+ }
93
74
  }
94
- finally { if (e_1) throw e_1.error; }
95
75
  }
96
76
  if (buffer.trim().length > 0) {
97
77
  throw new Error(`Unparsed JSON remaining in ${filePath}`);
@@ -10,10 +10,8 @@ const log = logger('openpeeps:pg');
10
10
  export const SCHEMA_MIGRATE_LOCK = { key1: 8742301, key2: 1 };
11
11
  let pool;
12
12
  let dbInstance;
13
- export const pgConnectionString = () => {
14
- var _a;
15
- return (_a = process.env.DATABASE_URL) !== null && _a !== void 0 ? _a : 'postgresql://openpeeps:openpeeps@localhost:5432/openpeeps';
16
- };
13
+ export const pgConnectionString = () => process.env.DATABASE_URL ??
14
+ 'postgresql://openpeeps:openpeeps@localhost:5432/openpeeps';
17
15
  const instrumentPoolQuery = (target) => {
18
16
  if (!dbTimingEnabled())
19
17
  return;
@@ -92,7 +90,7 @@ export const initPostgres = async () => {
92
90
  return pgDb();
93
91
  };
94
92
  export const closePostgres = async () => {
95
- await (pool === null || pool === void 0 ? void 0 : pool.end());
93
+ await pool?.end();
96
94
  pool = undefined;
97
95
  dbInstance = undefined;
98
96
  // DROP SCHEMA / pool.end leaves allpeepDb() holding a dead Pool; next caller
@@ -111,8 +109,7 @@ export const closePostgres = async () => {
111
109
  * advisory lock).
112
110
  */
113
111
  export const resetPostgresSchemas = async (options = {}) => {
114
- var _a;
115
- const closePool = (_a = options.closePool) !== null && _a !== void 0 ? _a : true;
112
+ const closePool = options.closePool ?? true;
116
113
  const db = pgDb();
117
114
  await db.execute(sql.raw('DROP SCHEMA IF EXISTS public CASCADE'));
118
115
  await db.execute(sql.raw('DROP SCHEMA IF EXISTS drizzle CASCADE'));
@@ -24,7 +24,7 @@ export const sqlConditions = (...filters) => {
24
24
  export const partitionPgFilters = (filters) => {
25
25
  const sqlFilters = [];
26
26
  const omFilters = [];
27
- for (const filter of filters !== null && filters !== void 0 ? filters : []) {
27
+ for (const filter of filters ?? []) {
28
28
  if (isSqlFilter(filter))
29
29
  sqlFilters.push(filter);
30
30
  else
@@ -15,6 +15,8 @@ export declare const postFilters: {
15
15
  notCreatorIn: (ids: string[]) => SqlFilter | undefined;
16
16
  myFeed: (profileId: string, followedProfileIds: string[], groupIds: string[]) => SqlFilter;
17
17
  type: (type: string) => SqlFilter;
18
+ inGroup: (groupId: string) => SqlFilter;
19
+ notInAnyGroup: () => SqlFilter;
18
20
  replyCount: (op: "==" | "!=" | ">" | ">=" | "<" | "<=", count: number) => SqlFilter;
19
21
  replyCountZero: () => SqlFilter;
20
22
  replyCountPositive: () => SqlFilter;
@@ -43,6 +43,8 @@ export const postFilters = {
43
43
  return pgSql(or(eq(posts.creatorId, profileId), followed, groupMemberPost));
44
44
  },
45
45
  type: (type) => pgSql(eq(posts.type, type)),
46
+ inGroup: (groupId) => pgSql(sql `EXISTS (SELECT 1 FROM ${postGroups} WHERE ${postGroups.fromId} = ${posts.id}::text AND ${postGroups.toId} = ${groupId})`),
47
+ notInAnyGroup: () => pgSql(sql `NOT EXISTS (SELECT 1 FROM ${postGroups} WHERE ${postGroups.fromId} = ${posts.id}::text)`),
46
48
  replyCount: (op, count) => pgSql(compareCount(postsReplyCountExpr, op, count)),
47
49
  replyCountZero: () => postFilters.replyCount('==', 0),
48
50
  replyCountPositive: () => postFilters.replyCount('>', 0),
@@ -1,14 +1,3 @@
1
- var __rest = (this && this.__rest) || function (s, e) {
2
- var t = {};
3
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
- t[p] = s[p];
5
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
- t[p[i]] = s[p[i]];
9
- }
10
- return t;
11
- };
12
1
  import { and, eq, isNull, sql } from 'drizzle-orm';
13
2
  import { nowIso } from './mappers.js';
14
3
  import { uuidv7 } from 'uuidv7';
@@ -37,7 +26,7 @@ export const softDeleteById = async (db, table, id) => {
37
26
  export const insertEdge = async (db, table, fromId, toId, body = {}) => {
38
27
  // Callers (e.g. jam recordings) pass a pre-generated id on the body; use it
39
28
  // as the row primary key and keep it out of jsonb so finds/updates match.
40
- const { id: providedId } = body, edgeBody = __rest(body, ["id"]);
29
+ const { id: providedId, ...edgeBody } = body;
41
30
  const id = typeof providedId === 'string' && providedId.length > 0
42
31
  ? providedId
43
32
  : uuidv7();
@@ -58,10 +47,9 @@ export const deleteEdge = async (db, table, fromId, toId) => {
58
47
  .where(and(eq(table.fromId, fromId), eq(table.toId, toId)));
59
48
  };
60
49
  export const countRows = async (db, table, where) => {
61
- var _a, _b;
62
50
  const query = db
63
51
  .select({ count: sql `count(*)::int` })
64
52
  .from(table);
65
53
  const result = (where ? await query.where(where) : await query);
66
- return (_b = (_a = result[0]) === null || _a === void 0 ? void 0 : _a.count) !== null && _b !== void 0 ? _b : 0;
54
+ return result[0]?.count ?? 0;
67
55
  };