@openpeepshq/core 0.1.33 → 0.1.34

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 (213) hide show
  1. package/dist/accounts/mutations.js +33 -35
  2. package/dist/analytics/compile.js +16 -10
  3. package/dist/analytics/read.js +52 -9
  4. package/dist/analytics/report.d.ts +20 -0
  5. package/dist/backups/index.js +75 -15
  6. package/dist/backups/metadata.d.ts +2 -3
  7. package/dist/backups/metadata.js +6 -2
  8. package/dist/config/defaults/capabilities.js +13 -2
  9. package/dist/config/defaults/community.js +7 -3
  10. package/dist/config/defaults/core.d.ts +1 -1
  11. package/dist/config/defaults/core.js +3 -0
  12. package/dist/config/index.d.ts +21 -0
  13. package/dist/config/index.js +7 -1
  14. package/dist/db/helpers.d.ts +1 -0
  15. package/dist/db/helpers.js +11 -3
  16. package/dist/db/index.d.ts +1 -1
  17. package/dist/db/index.js +1 -0
  18. package/dist/db/init.js +2 -3
  19. package/dist/db/migration/importCollections.d.ts +14 -9
  20. package/dist/db/migration/importCollections.js +114 -164
  21. package/dist/db/migration/shared.d.ts +2 -33
  22. package/dist/db/migration/shared.js +2 -52
  23. package/dist/db/pg/collections.d.ts +2 -2
  24. package/dist/db/pg/collections.js +2 -2
  25. package/dist/db/pg/filters/posts.d.ts +10 -0
  26. package/dist/db/pg/filters/posts.js +28 -4
  27. package/dist/db/pg/filters/profiles.d.ts +1 -0
  28. package/dist/db/pg/filters/profiles.js +2 -1
  29. package/dist/db/pg/map/filters.js +32 -2
  30. package/dist/db/pg/map/mutations.js +13 -8
  31. package/dist/db/pg/map/registry.d.ts +5 -0
  32. package/dist/db/pg/map/registry.js +64 -24
  33. package/dist/db/pg/map/relations.js +9 -5
  34. package/dist/db/pg/migrate.d.ts +1 -2
  35. package/dist/db/pg/migrate.js +6 -6
  36. package/dist/db/pg/queries/activity.js +3 -3
  37. package/dist/db/pg/queries/sorts.d.ts +1 -0
  38. package/dist/db/pg/queries/sorts.js +4 -0
  39. package/dist/db/pg/schema/documents.d.ts +279 -41
  40. package/dist/db/pg/schema/documents.js +21 -8
  41. package/dist/db/pg/schema/edges.d.ts +116 -7
  42. package/dist/db/pg/schema/edges.js +2 -1
  43. package/dist/db/pg/schema/index.d.ts +362 -15
  44. package/dist/db/pg/sql/0010_user_group_membership_roles.sql +16 -0
  45. package/dist/db/pg/sql/0011_drop_data_migrations.sql +1 -0
  46. package/dist/db/pg/sql/0012_posts_last_activity_at.sql +5 -0
  47. package/dist/db/pg/sql/0013_add_blocks_edge.sql +12 -0
  48. package/dist/db/pg/sql/0014_federation_datamodel.sql +59 -0
  49. package/dist/db/pg/sql/0015_profile_hashtags.sql +12 -0
  50. package/dist/db/pg/sql/meta/{0009_snapshot.json → 0015_snapshot.json} +291 -36
  51. package/dist/db/pg/sql/meta/_journal.json +43 -1
  52. package/dist/email/render.js +11 -3
  53. package/dist/events/index.d.ts +4 -0
  54. package/dist/events/index.js +1 -0
  55. package/dist/federation/activities.d.ts +17 -0
  56. package/dist/federation/activities.js +26 -0
  57. package/dist/federation/identity.d.ts +16 -0
  58. package/dist/federation/identity.js +52 -0
  59. package/dist/federation/index.d.ts +4 -0
  60. package/dist/federation/index.js +3 -0
  61. package/dist/federation/profiles.d.ts +3 -0
  62. package/dist/federation/profiles.js +14 -0
  63. package/dist/groups/finders.d.ts +2 -1
  64. package/dist/groups/helpers.d.ts +18 -0
  65. package/dist/groups/mapping.d.ts +4 -2
  66. package/dist/hashtags/finders.d.ts +6 -3
  67. package/dist/hashtags/finders.js +2 -0
  68. package/dist/hashtags/helpers.d.ts +8 -0
  69. package/dist/hashtags/helpers.js +4 -0
  70. package/dist/hashtags/index.d.ts +2 -0
  71. package/dist/hashtags/index.js +2 -0
  72. package/dist/hashtags/mutations.d.ts +3 -0
  73. package/dist/hashtags/mutations.js +13 -1
  74. package/dist/i18n/index.d.ts +1 -1
  75. package/dist/i18n/index.js +3 -1
  76. package/dist/i18n/pluginLocales.d.ts +6 -0
  77. package/dist/i18n/pluginLocales.js +15 -0
  78. package/dist/jams/export.d.ts +19 -0
  79. package/dist/jams/export.js +60 -0
  80. package/dist/jams/health.d.ts +8 -0
  81. package/dist/jams/health.js +46 -0
  82. package/dist/jams/helpers.d.ts +2 -2
  83. package/dist/jams/index.d.ts +2 -0
  84. package/dist/jams/index.js +23 -16
  85. package/dist/jams/jobs.js +1 -1
  86. package/dist/jams/livekit.d.ts +49 -4
  87. package/dist/jams/livekit.js +56 -39
  88. package/dist/jams/mapping.d.ts +3 -3
  89. package/dist/jams/mutations.d.ts +1 -1
  90. package/dist/jams/recording.d.ts +10 -0
  91. package/dist/jams/recording.js +32 -0
  92. package/dist/jams/token.d.ts +13 -1
  93. package/dist/jams/token.js +18 -7
  94. package/dist/jams/waitingRoom.js +1 -1
  95. package/dist/jobs/index.d.ts +1 -0
  96. package/dist/jobs/index.js +6 -1
  97. package/dist/jobs/jobDetail.js +1 -6
  98. package/dist/media/index.d.ts +1 -1
  99. package/dist/media/index.js +23 -8
  100. package/dist/media/processing.js +18 -7
  101. package/dist/notifications/defaultNotifications/follow/index.js +2 -2
  102. package/dist/notifications/defaultNotifications/index.js +4 -0
  103. package/dist/notifications/defaultNotifications/newGroupPost/index.js +12 -6
  104. package/dist/notifications/defaultNotifications/pollEnded/index.d.ts +19 -0
  105. package/dist/notifications/defaultNotifications/pollEnded/index.js +39 -0
  106. package/dist/notifications/defaultNotifications/pollEnded/recipients.d.ts +3 -0
  107. package/dist/notifications/defaultNotifications/pollEnded/recipients.js +18 -0
  108. package/dist/notifications/defaultNotifications/rsvp/index.d.ts +6 -1
  109. package/dist/notifications/defaultNotifications/rsvp/index.js +7 -0
  110. package/dist/notifications/defaultNotifications/rsvpCanceled/index.d.ts +24 -0
  111. package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +75 -0
  112. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.d.ts +4 -0
  113. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.js +11 -0
  114. package/dist/notifications/jobs.js +3 -1
  115. package/dist/notifications/mutations.js +4 -0
  116. package/dist/plugins/index.js +37 -1
  117. package/dist/plugins/install.d.ts +28 -9
  118. package/dist/plugins/install.js +281 -49
  119. package/dist/plugins/pluginAuth.d.ts +1 -1
  120. package/dist/plugins/pluginAuth.js +10 -6
  121. package/dist/posts/activity.d.ts +9 -0
  122. package/dist/posts/activity.js +35 -0
  123. package/dist/posts/contextClosure.d.ts +1 -9
  124. package/dist/posts/contextClosure.js +15 -44
  125. package/dist/posts/conversationQueries.d.ts +7 -0
  126. package/dist/posts/conversationQueries.js +76 -2
  127. package/dist/posts/eventAgenda.d.ts +1 -0
  128. package/dist/posts/eventAgenda.js +10 -4
  129. package/dist/posts/eventOccurrenceJobs.js +7 -2
  130. package/dist/posts/eventOccurrences.d.ts +6 -0
  131. package/dist/posts/eventOccurrences.js +21 -0
  132. package/dist/posts/finders.d.ts +15 -8
  133. package/dist/posts/finders.js +67 -18
  134. package/dist/posts/helpers/filters.js +13 -8
  135. package/dist/posts/helpers/index.d.ts +27 -14
  136. package/dist/posts/helpers/index.js +34 -14
  137. package/dist/posts/index.d.ts +5 -2
  138. package/dist/posts/index.js +5 -2
  139. package/dist/posts/mapping.d.ts +216 -13
  140. package/dist/posts/mapping.js +14 -13
  141. package/dist/posts/mutations.d.ts +440 -3
  142. package/dist/posts/mutations.js +155 -32
  143. package/dist/posts/pollEnd.d.ts +3 -0
  144. package/dist/posts/pollEnd.js +7 -0
  145. package/dist/posts/pollEndJobs.d.ts +8 -0
  146. package/dist/posts/pollEndJobs.js +49 -0
  147. package/dist/posts/replyClosure.d.ts +10 -0
  148. package/dist/posts/replyClosure.js +43 -0
  149. package/dist/posts/rsvpConfirmationEmail.js +14 -16
  150. package/dist/posts/threadPreview.d.ts +8 -0
  151. package/dist/posts/threadPreview.js +44 -0
  152. package/dist/posts/unseenCounts.js +4 -1
  153. package/dist/profileSettings/cache.js +22 -5
  154. package/dist/profileSettings/mapping.d.ts +2 -0
  155. package/dist/profiles/activityQueries.d.ts +5 -0
  156. package/dist/profiles/activityQueries.js +85 -0
  157. package/dist/profiles/activitySummary.d.ts +3 -0
  158. package/dist/profiles/activitySummary.js +87 -0
  159. package/dist/profiles/blocks.d.ts +12 -0
  160. package/dist/profiles/blocks.js +73 -0
  161. package/dist/profiles/cache.d.ts +1 -0
  162. package/dist/profiles/cache.js +19 -6
  163. package/dist/profiles/finders.d.ts +2 -1
  164. package/dist/profiles/finders.js +8 -3
  165. package/dist/profiles/helpers.d.ts +2 -0
  166. package/dist/profiles/index.d.ts +2 -0
  167. package/dist/profiles/index.js +2 -0
  168. package/dist/profiles/mapping.d.ts +10 -5
  169. package/dist/profiles/mapping.js +13 -1
  170. package/dist/profiles/mutations.d.ts +8 -4
  171. package/dist/profiles/mutations.js +31 -2
  172. package/dist/redis/connection.d.ts +2 -0
  173. package/dist/redis/connection.js +25 -6
  174. package/dist/roles/index.d.ts +1 -1
  175. package/dist/roles/index.js +1 -1
  176. package/dist/roles/mapping.d.ts +1 -0
  177. package/dist/roles/mutations.js +86 -3
  178. package/dist/search/mapping.d.ts +1 -1
  179. package/dist/search/mapping.js +6 -2
  180. package/dist/server/index.d.ts +18 -0
  181. package/dist/server/index.js +24 -12
  182. package/dist/server/stablePublicServerInfo.d.ts +17 -0
  183. package/dist/server/stablePublicServerInfo.js +37 -0
  184. package/dist/server/status.d.ts +25 -0
  185. package/dist/server/status.js +98 -0
  186. package/dist/stats/finders.d.ts +1 -17681
  187. package/dist/stats/finders.js +9 -5
  188. package/dist/stats/mapping.d.ts +0 -1
  189. package/dist/stats/mapping.js +0 -3
  190. package/package.json +4 -5
  191. package/dist/db/migration/detect.d.ts +0 -3
  192. package/dist/db/migration/detect.js +0 -33
  193. package/dist/db/migration/importPostgres.d.ts +0 -3
  194. package/dist/db/migration/importPostgres.js +0 -18
  195. package/dist/db/migration/transform.d.ts +0 -20
  196. package/dist/db/migration/transform.js +0 -232
  197. package/dist/db/migration/validate.d.ts +0 -18
  198. package/dist/db/migration/validate.js +0 -69
  199. package/dist/db/pg/sql/meta/0000_snapshot.json +0 -3380
  200. package/dist/db/pg/sql/meta/0004_snapshot.json +0 -4114
  201. package/dist/db/pg/sql/meta/0005_snapshot.json +0 -4179
  202. package/dist/db/pg/sql/meta/0006_snapshot.json +0 -4200
  203. package/dist/db/pg/sql/meta/0007_snapshot.json +0 -4179
  204. package/dist/mastodon/index.d.ts +0 -4
  205. package/dist/mastodon/index.js +0 -51
  206. package/dist/mastodon/types.d.ts +0 -7579
  207. package/dist/mastodon/types.js +0 -523
  208. package/dist/mastodon/typescript.d.ts +0 -1578
  209. package/dist/mastodon/typescript.js +0 -1
  210. package/dist/migration/index.d.ts +0 -4
  211. package/dist/migration/index.js +0 -4
  212. package/dist/roles/defaults.d.ts +0 -2
  213. package/dist/roles/defaults.js +0 -95
@@ -1,14 +1,15 @@
1
1
  import { publicProfileWithActivityScoreSchema, publicPostWithActivityScoreSchema, } from '@openpeepshq/common/types';
2
2
  import { sub } from 'date-fns';
3
+ import { hostResources } from '../server/status.js';
3
4
  import { baseProfilesMapping } from '../profiles/index.js';
4
5
  import { allpeepDb } from '../db/index.js';
5
6
  import { postsMapping, postsWithReplyCountMapping, postsWithReplyToCountMapping, transformPost, } from '../posts/index.js';
6
- import { entriesMapping, followsMapping, postsWithActivityScoreMapping, profileWithActivityScoreMapping, reactionsMapping, repostsMapping, } from './mapping.js';
7
+ import { entriesMapping, followsMapping, postsWithActivityScoreMapping, profileWithActivityScoreMapping, repostsMapping, } from './mapping.js';
7
8
  import { compileStatsWithAll, createdAtFilter } from './helpers.js';
8
9
  import { jamParticipantsMapping, jamSessionStartsMapping, } from '../jams/mapping.js';
9
10
  import { edgeFilters, postFilters, profileFilters } from '../db/pg/filters/index.js';
10
11
  import { sorts } from '../db/pg/queries/index.js';
11
- import { entries, follows, reactions, repost } from '../db/pg/schema/edges.js';
12
+ import { entries, follows, repost } from '../db/pg/schema/edges.js';
12
13
  import { jamEvents, posts, profiles } from '../db/pg/schema/documents.js';
13
14
  export const activeProfilesCount = (db, start, end) => profileWithActivityScoreMapping(start, end)
14
15
  .filter(profileFilters.activityScorePositive(start, end))
@@ -37,7 +38,10 @@ export const postsRepliesCount = (db, start, end) => postsWithReplyToCountMappin
37
38
  .filter({ matches: { replyToCount: 1 } })
38
39
  .count(db);
39
40
  export const postsRepliesStats = () => compileStatsWithAll(postsRepliesCount);
40
- const reactionCount = (db, start, end) => reactionsMapping.filter(createdAtFilter(reactions, start, end)).count(db);
41
+ const reactionCount = (db, start, end) => entriesMapping
42
+ .filter(createdAtFilter(entries, start, end))
43
+ .filter(edgeFilters.entryType('reaction'))
44
+ .count(db);
41
45
  const rsvpCount = (db, start, end) => entriesMapping
42
46
  .filter(createdAtFilter(entries, start, end))
43
47
  .filter(edgeFilters.entryType('rsvp'))
@@ -45,8 +49,7 @@ const rsvpCount = (db, start, end) => entriesMapping
45
49
  const followCount = (db, start, end) => followsMapping.filter(createdAtFilter(follows, start, end)).count(db);
46
50
  const entryCount = (db, start, end) => entriesMapping.filter(createdAtFilter(entries, start, end)).count(db);
47
51
  const repostCount = (db, start, end) => repostsMapping.filter(createdAtFilter(repost, start, end)).count(db);
48
- const interactionsCount = async (db, start, end) => (await reactionCount(db, start, end)) +
49
- (await followCount(db, start, end)) +
52
+ const interactionsCount = async (db, start, end) => (await followCount(db, start, end)) +
50
53
  (await entryCount(db, start, end)) +
51
54
  (await repostCount(db, start, end));
52
55
  export const interactionsStats = () => compileStatsWithAll(interactionsCount);
@@ -164,4 +167,5 @@ export const serverStats = async () => ({
164
167
  fourMonths: await signupsTimeline('P120D'),
165
168
  },
166
169
  },
170
+ host: await hostResources(),
167
171
  });
@@ -203,7 +203,6 @@ export declare const postsWithActivityScoreMapping: import("../db/pg/map").Mappi
203
203
  }, DbPost & {
204
204
  activityScore: number;
205
205
  }>;
206
- export declare const reactionsMapping: import("../db/pg/map").Mapping<object, import("../db/pg/map").WithId<object>, import("../db/pg/map").WithId<object>>;
207
206
  export declare const followsMapping: import("../db/pg/map").Mapping<object, import("../db/pg/map").WithId<object>, import("../db/pg/map").WithId<object>>;
208
207
  export declare const entriesMapping: import("../db/pg/map").Mapping<object, import("../db/pg/map").WithId<object>, import("../db/pg/map").WithId<object>>;
209
208
  export declare const repostsMapping: import("../db/pg/map").Mapping<object, import("../db/pg/map").WithId<object>, import("../db/pg/map").WithId<object>>;
@@ -5,9 +5,6 @@ import { map } from '../db/pg/map/index.js';
5
5
  import { computedFields } from '../db/pg/queries/index.js';
6
6
  export const profileWithActivityScoreMapping = (start, end) => map(Object.assign(Object.assign({}, baseProfilesMapping.data()), { activityWindow: { start, end }, computedFields: [computedFields.profileActivityScore({ start, end })] }));
7
7
  export const postsWithActivityScoreMapping = map(Object.assign(Object.assign({}, postsMapping.data()), { computedFields: [computedFields.postActivityScore()] }));
8
- export const reactionsMapping = map({
9
- collection: collectionInfos.reactionsCollection.name,
10
- });
11
8
  export const followsMapping = map({
12
9
  collection: collectionInfos.followsCollection.name,
13
10
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/core",
3
- "version": "0.1.33",
3
+ "version": "0.1.34",
4
4
  "type": "module",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "dependencies": {
@@ -38,10 +38,10 @@
38
38
  "uuidv7": "^1.0.2",
39
39
  "web-push": "^3.6.7",
40
40
  "zod": "^4.4.3",
41
+ "@openpeepshq/common": "0.1.46",
42
+ "@openpeepshq/i18n": "^0.1.10",
41
43
  "@openpeepshq/geocoder": "^0.1.2",
42
- "@openpeepshq/fetch-client": "^0.1.7",
43
- "@openpeepshq/common": "0.1.45",
44
- "@openpeepshq/i18n": "^0.1.9"
44
+ "@openpeepshq/fetch-client": "^0.1.7"
45
45
  },
46
46
  "main": "dist/index.js",
47
47
  "types": "dist/index.d.ts",
@@ -86,7 +86,6 @@
86
86
  "build": "tsc && tsc-alias && rm -rf dist/db/pg/sql && cp -r src/db/pg/sql dist/db/pg/sql",
87
87
  "build:watch": "tsc && tsc-alias && (concurrently \"tsc -w\" \"tsc-alias -w\")",
88
88
  "uuidv7": "node -e 'import(\"uuidv7\").then(u => console.log(u.uuidv7()))'",
89
- "create-migration": "node create-migration.js",
90
89
  "db:generate": "drizzle-kit generate",
91
90
  "db:migrate": "drizzle-kit migrate",
92
91
  "db:studio": "drizzle-kit studio"
@@ -1,3 +0,0 @@
1
- declare const isUndefinedTableError: (err: unknown) => boolean;
2
- export declare const tableCount: (collection: string) => Promise<number>;
3
- export { isUndefinedTableError };
@@ -1,33 +0,0 @@
1
- import { getTableName, sql } from 'drizzle-orm';
2
- import { pgDb } from '../pg/client.js';
3
- import { getTableForCollection } from '../pg/map/registry.js';
4
- const isUndefinedTableError = (err) => {
5
- const candidates = [
6
- err,
7
- err && typeof err === 'object' && 'cause' in err
8
- ? err.cause
9
- : undefined,
10
- ];
11
- return candidates.some((candidate) => candidate &&
12
- typeof candidate === 'object' &&
13
- 'code' in candidate &&
14
- candidate.code === '42P01');
15
- };
16
- export const tableCount = async (collection) => {
17
- var _a, _b;
18
- const table = getTableForCollection(collection);
19
- const tableName = getTableName(table);
20
- const db = pgDb();
21
- try {
22
- const result = await db.execute(sql.raw(`SELECT COUNT(*)::text AS count FROM "${tableName}"`));
23
- return Number((_b = (_a = result.rows[0]) === null || _a === void 0 ? void 0 : _a.count) !== null && _b !== void 0 ? _b : 0);
24
- }
25
- catch (err) {
26
- // Missing table ⇒ treat as empty so callers can remigrate / auto-import.
27
- if (isUndefinedTableError(err)) {
28
- return 0;
29
- }
30
- throw err;
31
- }
32
- };
33
- export { isUndefinedTableError };
@@ -1,3 +0,0 @@
1
- export declare const importPostgres: (exportDir?: string, options?: {
2
- closeConnection?: boolean;
3
- }) => Promise<Record<string, number>>;
@@ -1,18 +0,0 @@
1
- import { logger } from '../../log/index.js';
2
- import { closePostgres } from '../pg/client.js';
3
- import { assertExportDir, collectionsDir, exportDirFromEnv, readManifest, writeImportStats, } from './shared.js';
4
- import { importAllArangoCollections } from './importCollections.js';
5
- const log = logger('core:migration:import');
6
- export const importPostgres = async (exportDir = exportDirFromEnv(), options = {}) => {
7
- var _a;
8
- const closeConnection = (_a = options.closeConnection) !== null && _a !== void 0 ? _a : true;
9
- await assertExportDir(exportDir);
10
- const manifest = await readManifest(exportDir);
11
- log.info('Importing export from %s (exported %s)', exportDir, manifest.exportedAt);
12
- const { imported } = await importAllArangoCollections(collectionsDir(exportDir));
13
- await writeImportStats(exportDir, imported);
14
- if (closeConnection) {
15
- await closePostgres();
16
- }
17
- return imported;
18
- };
@@ -1,20 +0,0 @@
1
- /** Postgres uuid compares case-insensitively; normalize so dedupe matches. */
2
- export declare const normalizeImportId: (value: unknown) => string | undefined;
3
- export declare const arangoDocToModel: (doc: Record<string, unknown>) => Record<string, unknown>;
4
- export type ImportContext = {
5
- postCreatorIdByPostId?: Map<string, string>;
6
- /** Empty-name / duplicate-name hashtags: old id → kept id, or '' if dropped. */
7
- hashtagIdRemap?: Map<string, string>;
8
- };
9
- /** Pre-scan entries edges so legacy posts without creatorId can be imported. */
10
- export declare const buildPostCreatorIdByPostId: (collectionsDir: string) => Promise<Map<string, string>>;
11
- /**
12
- * Legacy Arango groups used discoverable/locked flags; capabilities were added
13
- * later via an Arango-only data migration that never runs on Postgres restores.
14
- */
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>;
18
- export declare const arangoDocToDocumentRow: (collection: string, doc: Record<string, unknown>, context?: ImportContext) => Record<string, unknown>;
19
- export declare const arangoDocToEdgeRow: (collection: string, doc: Record<string, unknown>) => Record<string, unknown>;
20
- export declare const isEdgeCollection: (collection: string) => boolean;
@@ -1,232 +0,0 @@
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
- import { access } from 'node:fs/promises';
13
- import { constants } from 'node:fs';
14
- import { join } from 'node:path';
15
- import { groupCapabilityTemplates } from '@openpeepshq/common/lib';
16
- import { defaultGroupAdminCapabilityAdds } from '@openpeepshq/common/types';
17
- import { documentRegistry, edgeRegistry, parseDocRef, } from '../pg/map/registry.js';
18
- import { nowIso } from '../pg/mappers.js';
19
- import { uuidv7 } from 'uuidv7';
20
- import { readJsonl } from './shared.js';
21
- const ARANGO_META = ['_id', '_key', '_rev', '_from', '_to'];
22
- const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23
- /** Postgres uuid compares case-insensitively; normalize so dedupe matches. */
24
- export const normalizeImportId = (value) => {
25
- if (typeof value !== 'string') {
26
- return undefined;
27
- }
28
- const trimmed = value.trim();
29
- if (!trimmed) {
30
- return undefined;
31
- }
32
- return UUID_REGEX.test(trimmed) ? trimmed.toLowerCase() : trimmed;
33
- };
34
- export const arangoDocToModel = (doc) => {
35
- var _a;
36
- const id = ((_a = doc._key) !== null && _a !== void 0 ? _a : doc.id);
37
- const model = Object.assign(Object.assign({}, doc), { id });
38
- for (const key of ARANGO_META) {
39
- delete model[key];
40
- }
41
- return model;
42
- };
43
- const isNonEmptyTimestamp = (value) => typeof value === 'string' && value.trim() !== '';
44
- const resolveDocumentId = (doc) => {
45
- const candidates = [doc.id, doc._key]
46
- .map((value) => normalizeImportId(value))
47
- .filter((value) => Boolean(value));
48
- const uuid = candidates.find((value) => UUID_REGEX.test(value));
49
- return uuid !== null && uuid !== void 0 ? uuid : uuidv7();
50
- };
51
- const timestampsFromModel = (model) => {
52
- const ts = nowIso();
53
- return {
54
- createdAt: isNonEmptyTimestamp(model.createdAt) ? model.createdAt : ts,
55
- updatedAt: isNonEmptyTimestamp(model.updatedAt) ? model.updatedAt : ts,
56
- deletedAt: isNonEmptyTimestamp(model.deletedAt) ? model.deletedAt : null,
57
- };
58
- };
59
- const entryTypeFromDoc = (doc) => {
60
- if (typeof doc.type === 'string') {
61
- return doc.type;
62
- }
63
- const body = doc.body;
64
- if (body && typeof body === 'object' && 'type' in body) {
65
- return body.type;
66
- }
67
- return undefined;
68
- };
69
- /** Pre-scan entries edges so legacy posts without creatorId can be imported. */
70
- export const buildPostCreatorIdByPostId = async (collectionsDir) => {
71
- var _a, _b;
72
- const map = new Map();
73
- const filePath = join(collectionsDir, 'entries.jsonl');
74
- try {
75
- await access(filePath, constants.F_OK);
76
- }
77
- catch (_e) {
78
- return map;
79
- }
80
- const docs = await readJsonl(filePath);
81
- for (const doc of docs) {
82
- const fromRef = parseDocRef(doc._from);
83
- const toRef = parseDocRef(doc._to);
84
- if (!fromRef || !toRef || toRef.collection !== 'posts') {
85
- continue;
86
- }
87
- const entryType = entryTypeFromDoc(doc);
88
- const postId = (_a = normalizeImportId(toRef.id)) !== null && _a !== void 0 ? _a : toRef.id;
89
- const creatorId = (_b = normalizeImportId(fromRef.id)) !== null && _b !== void 0 ? _b : fromRef.id;
90
- if (entryType === 'create' || !map.has(postId)) {
91
- map.set(postId, creatorId);
92
- }
93
- }
94
- return map;
95
- };
96
- /**
97
- * Legacy Arango groups used discoverable/locked flags; capabilities were added
98
- * later via an Arango-only data migration that never runs on Postgres restores.
99
- */
100
- export const capabilitiesFromLegacyGroupFlags = (data) => {
101
- if (data.capabilities && typeof data.capabilities === 'object') {
102
- return undefined;
103
- }
104
- const discoverable = Boolean(data.discoverable);
105
- const locked = Boolean(data.locked);
106
- const { publicGroup, privateGroup, lockedGroup } = groupCapabilityTemplates;
107
- const template = discoverable
108
- ? locked
109
- ? lockedGroup
110
- : publicGroup
111
- : privateGroup;
112
- return template.capabilities;
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
- };
130
- export const arangoDocToDocumentRow = (collection, doc, context) => {
131
- var _a, _b, _e, _f, _g, _h, _j, _k, _m, _o, _p, _q, _r, _s;
132
- const model = arangoDocToModel(doc);
133
- const { createdAt, updatedAt, deletedAt } = timestampsFromModel(model);
134
- if (collection === 'configs') {
135
- const { createdAt: _c, updatedAt: _u, deletedAt: _d, id: _id } = model, body = __rest(model, ["createdAt", "updatedAt", "deletedAt", "id"]);
136
- const rawKey = String((_b = (_a = doc._key) !== null && _a !== void 0 ? _a : doc.id) !== null && _b !== void 0 ? _b : '');
137
- // Legacy Arango backups used allpeep-* keys; runtime loaders use openpeeps-*.
138
- const key = rawKey.startsWith('allpeep-')
139
- ? `openpeeps-${rawKey.slice('allpeep-'.length)}`
140
- : rawKey;
141
- return { key, body, createdAt, updatedAt, deletedAt };
142
- }
143
- if (collection === 'dataMigrations') {
144
- const appliedAtRaw = (_e = doc.appliedAt) !== null && _e !== void 0 ? _e : model.createdAt;
145
- return {
146
- id: (_f = doc._key) !== null && _f !== void 0 ? _f : doc.id,
147
- appliedAt: isNonEmptyTimestamp(appliedAtRaw) ? appliedAtRaw : nowIso(),
148
- };
149
- }
150
- if (collection === 'i18n') {
151
- const id = resolveDocumentId(doc);
152
- const locale = ((_h = (_g = doc.locale) !== null && _g !== void 0 ? _g : doc._key) !== null && _h !== void 0 ? _h : id);
153
- const namespace = ((_j = doc.namespace) !== null && _j !== void 0 ? _j : 'translation');
154
- const body = (_m = (_k = doc.body) !== null && _k !== void 0 ? _k : doc.translations) !== null && _m !== void 0 ? _m : (() => {
155
- const { createdAt: _c, updatedAt: _u, deletedAt: _d, id: _id, locale: _l, namespace: _n, translations: _t } = model, rest = __rest(model, ["createdAt", "updatedAt", "deletedAt", "id", "locale", "namespace", "translations"]);
156
- return rest;
157
- })();
158
- return {
159
- id,
160
- locale,
161
- namespace,
162
- body,
163
- createdAt,
164
- updatedAt,
165
- deletedAt,
166
- };
167
- }
168
- const config = documentRegistry[collection];
169
- if (!config) {
170
- throw new Error(`Unknown document collection: ${collection}`);
171
- }
172
- const id = (_p = normalizeImportId((_o = doc._key) !== null && _o !== void 0 ? _o : doc.id)) !== null && _p !== void 0 ? _p : String((_r = (_q = doc._key) !== null && _q !== void 0 ? _q : doc.id) !== null && _r !== void 0 ? _r : '');
173
- const { createdAt: _c, updatedAt: _u, deletedAt: _d, id: _id } = model, data = __rest(model, ["createdAt", "updatedAt", "deletedAt", "id"]);
174
- const { scalars, body } = config.splitPatch(data);
175
- if (collection === 'posts' &&
176
- scalars.creatorId === undefined &&
177
- (context === null || context === void 0 ? void 0 : context.postCreatorIdByPostId)) {
178
- const creatorId = context.postCreatorIdByPostId.get(id);
179
- if (creatorId) {
180
- scalars.creatorId = creatorId;
181
- }
182
- }
183
- if (collection === 'profileSettings' && scalars.profileId === undefined) {
184
- scalars.profileId = id;
185
- }
186
- if (collection === 'notifications' && scalars.profileId === undefined) {
187
- const actorId = (_s = model.actorId) !== null && _s !== void 0 ? _s : model.profileId;
188
- if (typeof actorId === 'string') {
189
- scalars.profileId = actorId;
190
- }
191
- }
192
- if (collection === 'groups') {
193
- const capabilities = capabilitiesFromLegacyGroupFlags(data);
194
- if (capabilities) {
195
- body.capabilities = capabilities;
196
- }
197
- else if (body.capabilities && typeof body.capabilities === 'object') {
198
- body.capabilities = normalizeGroupCapabilityMap(body.capabilities);
199
- }
200
- }
201
- return Object.assign(Object.assign({ id }, scalars), { body,
202
- createdAt,
203
- updatedAt,
204
- deletedAt });
205
- };
206
- export const arangoDocToEdgeRow = (collection, doc) => {
207
- var _a, _b, _e, _f, _g;
208
- const config = edgeRegistry[collection];
209
- if (!config) {
210
- throw new Error(`Unknown edge collection: ${collection}`);
211
- }
212
- const fromRef = parseDocRef(doc._from);
213
- const toRef = parseDocRef(doc._to);
214
- if (!fromRef || !toRef) {
215
- throw new Error(`Invalid edge refs in ${collection}/${String(doc._key)}: ${String(doc._from)} -> ${String(doc._to)}`);
216
- }
217
- const model = arangoDocToModel(doc);
218
- const { createdAt, updatedAt } = timestampsFromModel(model);
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
- }
223
- return {
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),
225
- fromId: (_f = normalizeImportId(fromRef.id)) !== null && _f !== void 0 ? _f : fromRef.id,
226
- toId: (_g = normalizeImportId(toRef.id)) !== null && _g !== void 0 ? _g : toRef.id,
227
- body,
228
- createdAt,
229
- updatedAt,
230
- };
231
- };
232
- export const isEdgeCollection = (collection) => collection in edgeRegistry;
@@ -1,18 +0,0 @@
1
- import { type CollectionCounts } from './shared';
2
- type ValidationIssue = {
3
- collection: string;
4
- kind: 'count' | 'checksum';
5
- expected: string | number;
6
- actual: string | number;
7
- };
8
- export declare const validateMigration: (exportDir?: string, options?: {
9
- closeConnection?: boolean;
10
- importedCounts?: CollectionCounts;
11
- }) => Promise<{
12
- ok: true;
13
- issues: ValidationIssue[];
14
- } | {
15
- ok: false;
16
- issues: ValidationIssue[];
17
- }>;
18
- export {};
@@ -1,69 +0,0 @@
1
- import { sql } from 'drizzle-orm';
2
- import { logger } from '../../log/index.js';
3
- import { closePostgres, pgDb } from '../pg/client.js';
4
- import { documentRegistry, edgeRegistry } from '../pg/map/registry.js';
5
- import { tableCount } from './detect.js';
6
- import { assertExportDir, expectedCollectionCount, exportDirFromEnv, readImportStats, readManifest, sortedChecksum, } from './shared.js';
7
- const log = logger('core:migration:validate');
8
- const accountEmailChecksum = async () => {
9
- const db = pgDb();
10
- const rows = await db.execute(sql `SELECT email FROM accounts ORDER BY email`);
11
- return sortedChecksum(rows.rows.map((row) => row.email));
12
- };
13
- const postIdChecksum = async () => {
14
- const db = pgDb();
15
- const rows = await db.execute(sql `SELECT id FROM posts ORDER BY id`);
16
- return sortedChecksum(rows.rows.map((row) => row.id));
17
- };
18
- export const validateMigration = async (exportDir = exportDirFromEnv(), options = {}) => {
19
- var _a, _b, _c;
20
- const closeConnection = (_a = options.closeConnection) !== null && _a !== void 0 ? _a : true;
21
- await assertExportDir(exportDir);
22
- const manifest = await readManifest(exportDir);
23
- const importStats = await readImportStats(exportDir);
24
- const importedCounts = (_c = (_b = options.importedCounts) !== null && _b !== void 0 ? _b : importStats === null || importStats === void 0 ? void 0 : importStats.collections) !== null && _c !== void 0 ? _c : null;
25
- if (importedCounts) {
26
- log.info('Validating Postgres counts against import stats (intentional Arango skips/remaps allowed)');
27
- }
28
- const issues = [];
29
- const collections = [
30
- ...Object.keys(documentRegistry),
31
- ...Object.keys(edgeRegistry),
32
- ];
33
- for (const collection of collections) {
34
- const expected = expectedCollectionCount(collection, manifest.collections, importedCounts);
35
- const actual = await tableCount(collection);
36
- if (expected !== actual) {
37
- issues.push({ collection, kind: 'count', expected, actual });
38
- }
39
- }
40
- const emailChecksum = await accountEmailChecksum();
41
- if (emailChecksum !== manifest.checksums.accountEmails) {
42
- issues.push({
43
- collection: 'accounts',
44
- kind: 'checksum',
45
- expected: manifest.checksums.accountEmails,
46
- actual: emailChecksum,
47
- });
48
- }
49
- const postsChecksum = await postIdChecksum();
50
- if (postsChecksum !== manifest.checksums.postIds) {
51
- issues.push({
52
- collection: 'posts',
53
- kind: 'checksum',
54
- expected: manifest.checksums.postIds,
55
- actual: postsChecksum,
56
- });
57
- }
58
- if (closeConnection) {
59
- await closePostgres();
60
- }
61
- if (issues.length === 0) {
62
- log.info('Validation passed for export %s', exportDir);
63
- return { ok: true, issues };
64
- }
65
- for (const issue of issues) {
66
- log.error('Validation failed for %s (%s): expected %s, got %s', issue.collection, issue.kind, issue.expected, issue.actual);
67
- }
68
- return { ok: false, issues };
69
- };