@openpeepshq/core 0.1.32 → 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 (136) 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/pdfReport.d.ts +1 -0
  6. package/dist/analytics/pdfReport.js +5 -4
  7. package/dist/analytics/privacy.d.ts +18 -0
  8. package/dist/analytics/privacy.js +10 -0
  9. package/dist/analytics/read.js +24 -11
  10. package/dist/analytics/report.d.ts +1 -1
  11. package/dist/analytics/report.js +9 -2
  12. package/dist/backups/index.js +6 -3
  13. package/dist/backups/metadata.d.ts +7 -0
  14. package/dist/config/defaults/community.js +0 -6
  15. package/dist/config/defaults/db.d.ts +0 -2
  16. package/dist/config/defaults/db.js +0 -2
  17. package/dist/config/index.d.ts +10 -9
  18. package/dist/db/helpers.d.ts +6 -28
  19. package/dist/db/helpers.js +19 -149
  20. package/dist/db/index.d.ts +2 -0
  21. package/dist/db/index.js +4 -0
  22. package/dist/db/init.js +3 -2
  23. package/dist/db/migration/detect.d.ts +0 -3
  24. package/dist/db/migration/detect.js +0 -54
  25. package/dist/db/migration/importCollections.d.ts +1 -1
  26. package/dist/db/migration/importCollections.js +22 -6
  27. package/dist/db/migration/shared.d.ts +0 -4
  28. package/dist/db/migration/shared.js +0 -7
  29. package/dist/db/migration/transform.d.ts +2 -0
  30. package/dist/db/migration/transform.js +23 -0
  31. package/dist/db/pg/client.js +4 -0
  32. package/dist/db/pg/filters/edges.d.ts +1 -1
  33. package/dist/db/pg/filters/edges.js +1 -1
  34. package/dist/db/pg/filters/posts.d.ts +1 -0
  35. package/dist/db/pg/filters/posts.js +11 -1
  36. package/dist/db/pg/map/filters.js +5 -0
  37. package/dist/db/pg/map/relations.d.ts +1 -1
  38. package/dist/db/pg/map/relations.js +89 -41
  39. package/dist/db/pg/migrate.d.ts +23 -0
  40. package/dist/db/pg/migrate.js +87 -1
  41. package/dist/db/pg/schema/documents.d.ts +143 -0
  42. package/dist/db/pg/schema/documents.js +22 -1
  43. package/dist/db/pg/schema/edges.d.ts +1 -0
  44. package/dist/db/pg/schema/edges.js +2 -1
  45. package/dist/db/pg/schema/index.d.ts +143 -0
  46. package/dist/db/pg/sql/0007_shallow_oracle.sql +3 -0
  47. package/dist/db/pg/sql/0008_group_owner_roles.sql +31 -0
  48. package/dist/db/pg/sql/0009_event_occurrences.sql +26 -0
  49. package/dist/db/pg/sql/meta/0007_snapshot.json +4179 -0
  50. package/dist/db/pg/sql/meta/0009_snapshot.json +4299 -0
  51. package/dist/db/pg/sql/meta/_journal.json +21 -0
  52. package/dist/db/replaceOrigin.js +6 -0
  53. package/dist/db/types.d.ts +0 -4
  54. package/dist/events/index.d.ts +2 -1
  55. package/dist/events/index.js +54 -33
  56. package/dist/groups/finders.d.ts +2 -2
  57. package/dist/groups/helpers.d.ts +6 -6
  58. package/dist/groups/mapping.d.ts +4 -4
  59. package/dist/groups/mapping.js +2 -2
  60. package/dist/groups/mutations.js +1 -1
  61. package/dist/inviteLinks/helpers.d.ts +4 -4
  62. package/dist/jams/cache.d.ts +1 -1
  63. package/dist/jams/cache.js +2 -1
  64. package/dist/jams/finders.d.ts +2 -1
  65. package/dist/jams/finders.js +18 -7
  66. package/dist/jams/helpers.d.ts +4 -0
  67. package/dist/jams/index.d.ts +4 -3
  68. package/dist/jams/index.js +20 -13
  69. package/dist/jams/livekit.d.ts +46 -8
  70. package/dist/jams/livekit.js +103 -21
  71. package/dist/jams/mapping.d.ts +14 -4
  72. package/dist/jams/mutations.d.ts +2 -0
  73. package/dist/jams/rtmp.d.ts +5 -0
  74. package/dist/jams/rtmp.js +8 -0
  75. package/dist/jams/token.d.ts +3 -3
  76. package/dist/jams/token.js +15 -12
  77. package/dist/jams/waitingRoom.d.ts +6 -6
  78. package/dist/jams/waitingRoom.js +24 -23
  79. package/dist/migration/index.d.ts +4 -0
  80. package/dist/migration/index.js +4 -0
  81. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +3 -1
  82. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +3 -1
  83. package/dist/notifications/helpers.js +6 -2
  84. package/dist/notifications/push.js +11 -4
  85. package/dist/plugins/helpers.d.ts +1 -0
  86. package/dist/plugins/helpers.js +1 -8
  87. package/dist/plugins/index.d.ts +5 -0
  88. package/dist/plugins/index.js +41 -4
  89. package/dist/plugins/install.d.ts +20 -0
  90. package/dist/plugins/install.js +223 -0
  91. package/dist/plugins/state.d.ts +4 -0
  92. package/dist/plugins/state.js +29 -0
  93. package/dist/posts/eventAgenda.d.ts +165 -0
  94. package/dist/posts/eventAgenda.js +120 -0
  95. package/dist/posts/eventOccurrenceJobs.d.ts +4 -0
  96. package/dist/posts/eventOccurrenceJobs.js +23 -0
  97. package/dist/posts/eventOccurrences.d.ts +4 -0
  98. package/dist/posts/eventOccurrences.js +40 -0
  99. package/dist/posts/finders.d.ts +32 -8
  100. package/dist/posts/finders.js +27 -45
  101. package/dist/posts/helpers/filters.js +1 -1
  102. package/dist/posts/helpers/index.d.ts +102 -16
  103. package/dist/posts/helpers/index.js +33 -20
  104. package/dist/posts/index.d.ts +3 -0
  105. package/dist/posts/index.js +3 -0
  106. package/dist/posts/mapping.d.ts +275 -0
  107. package/dist/posts/mapping.js +37 -3
  108. package/dist/posts/mutations.d.ts +1 -1
  109. package/dist/posts/mutations.js +29 -18
  110. package/dist/posts/rsvpConfirmationEmail.js +2 -1
  111. package/dist/posts/unseenCounts.d.ts +2 -0
  112. package/dist/posts/unseenCounts.js +25 -8
  113. package/dist/profiles/cache.d.ts +3 -1
  114. package/dist/profiles/cache.js +9 -1
  115. package/dist/profiles/helpers.d.ts +5 -5
  116. package/dist/profiles/index.d.ts +1 -1
  117. package/dist/profiles/index.js +1 -1
  118. package/dist/profiles/mapping.d.ts +5 -5
  119. package/dist/profiles/mutations.js +12 -14
  120. package/dist/pushSubscriptions/helpers.d.ts +2 -2
  121. package/dist/pushSubscriptions/mutations.js +13 -1
  122. package/dist/reports/helpers.d.ts +6 -6
  123. package/dist/roles/defaults.js +1 -0
  124. package/dist/server/index.d.ts +7 -7
  125. package/dist/server/index.js +15 -8
  126. package/dist/stats/finders.d.ts +1692 -142
  127. package/dist/stats/mapping.d.ts +21 -0
  128. package/package.json +4 -9
  129. package/dist/db/arango.d.ts +0 -2
  130. package/dist/db/arango.js +0 -110
  131. package/dist/db/migration/autoMigrate.d.ts +0 -2
  132. package/dist/db/migration/autoMigrate.js +0 -111
  133. package/dist/db/migration/cli.d.ts +0 -1
  134. package/dist/db/migration/cli.js +0 -56
  135. package/dist/db/migration/exportArango.d.ts +0 -4
  136. package/dist/db/migration/exportArango.js +0 -80
@@ -130,8 +130,8 @@ const attachForeignKeyRelation = async (db, docs, fkr) => Promise.all(docs.map(a
130
130
  const loaded = (await Promise.all(ids.map((id) => executeFind(db, fkr.mapping.collection, fkr.mapping, id)))).filter(Boolean);
131
131
  return Object.assign(Object.assign({}, doc), { [fkr.alias]: fkr.cardinality === 'many' ? loaded : ((_b = loaded[0]) !== null && _b !== void 0 ? _b : undefined) });
132
132
  }));
133
- const attachRelation = async (db, parentCollection, docs, relation) => {
134
- var _a;
133
+ const attachRelation = async (db, _parentCollection, docs, relation) => {
134
+ var _a, _b;
135
135
  if (relation.maxDepth && relation.maxDepth > 1) {
136
136
  return Promise.all(docs.map(async (doc) => (Object.assign(Object.assign({}, doc), { [relation.alias]: await traverseRelation(db, doc.id, relation) }))));
137
137
  }
@@ -160,51 +160,96 @@ const attachRelation = async (db, parentCollection, docs, relation) => {
160
160
  list.push(edge);
161
161
  grouped.set(parentId, list);
162
162
  }
163
- return Promise.all(docs.map(async (doc) => {
164
- var _a, _b;
165
- const edgesForDoc = (_a = grouped.get(doc.id)) !== null && _a !== void 0 ? _a : [];
166
- if (relation.count) {
167
- let count = edgesForDoc.length;
168
- if ((_b = relation.mapping) === null || _b === void 0 ? void 0 : _b.collection) {
169
- const vertexCol = vertexEdgeColumn(relation);
170
- const vertexIds = edgesForDoc.map((e) => e[vertexCol]);
171
- const vertices = await fetchRowsByIds(db, relation.mapping.collection, vertexIds, relation.mapping.softDelete);
172
- const filtered = applyPostFilters(vertices, relation.mapping.filters, relation.mapping.defaultFilter);
173
- count = filtered.length;
174
- }
175
- return Object.assign(Object.assign({}, doc), { [relation.alias]: count });
163
+ const vertexCol = vertexEdgeColumn(relation);
164
+ const edgesFor = (doc) => { var _a; return (_a = grouped.get(doc.id)) !== null && _a !== void 0 ? _a : []; };
165
+ const edgeVertexIdsFor = (doc) => edgesFor(doc).map((edge) => edge[vertexCol]);
166
+ // Vertices are fetched and hydrated once for the whole batch. Doing it per
167
+ // parent row cost a query per row per relation, so one feed page ran
168
+ // hundreds of round trips.
169
+ const batchIdsFrom = (idsFor) => [
170
+ ...new Set(docs.flatMap(idsFor)),
171
+ ];
172
+ if (relation.count) {
173
+ if (!((_b = relation.mapping) === null || _b === void 0 ? void 0 : _b.collection)) {
174
+ return docs.map((doc) => (Object.assign(Object.assign({}, doc), { [relation.alias]: edgesFor(doc).length })));
176
175
  }
177
- const value = await resolveRelationValue(db, edgesForDoc, relation, parentCollection);
178
- return Object.assign(Object.assign({}, doc), { [relation.alias]: value });
179
- }));
176
+ const rows = await fetchRowsByIds(db, relation.mapping.collection, batchIdsFrom(edgeVertexIdsFor), relation.mapping.softDelete);
177
+ const counted = new Set(applyPostFilters(rows, relation.mapping.filters, relation.mapping.defaultFilter).map((row) => row.id));
178
+ return docs.map((doc) => (Object.assign(Object.assign({}, doc), { [relation.alias]: [...new Set(edgeVertexIdsFor(doc))].filter((id) => counted.has(id)).length })));
179
+ }
180
+ const vertexIdsFor = (doc) => capVertexIds(edgeVertexIdsFor(doc), relation);
181
+ const vertexCollection = vertexCollectionFor(relation);
182
+ const lookup = vertexCollection
183
+ ? await fetchVertexLookup(db, vertexCollection, batchIdsFrom(vertexIdsFor), relation)
184
+ : emptyVertexLookup;
185
+ return docs.map((doc) => (Object.assign(Object.assign({}, doc), { [relation.alias]: relationValueFrom(edgesFor(doc), relation, vertexIdsFor(doc), lookup) })));
180
186
  };
181
- const resolveRelationValue = async (db, edgeRows, relation, _parentCollection) => {
187
+ const nodeCapFromLimit = (limit) => {
188
+ if (limit == null)
189
+ return undefined;
190
+ return typeof limit === 'number' ? limit : limit[1];
191
+ };
192
+ /**
193
+ * Cap before fetch when mapping.limit is set so hot inbound lists (e.g.
194
+ * embedded reposters) do not hydrate every vertex. uuidv7 ids are
195
+ * time-ordered, so newest-first approximates `createdAt DESC` before we have
196
+ * row data to sort on.
197
+ */
198
+ const capVertexIds = (vertexIds, relation) => {
182
199
  var _a;
183
- const vertexCollection = vertexCollectionFor(relation);
184
- const vertexCol = vertexEdgeColumn(relation);
185
- const vertexIds = edgeRows.map((e) => e[vertexCol]);
186
- if (!vertexCollection) {
187
- const items = edgeRows.map((edge) => {
188
- var _a;
189
- return rowToDocument(edgeCollectionName(relation.edgeCollection), edge, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.keepMetadata);
190
- });
191
- return relation.cardinality === 'one' ? items[0] : items;
200
+ const nodeCap = nodeCapFromLimit((_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.limit);
201
+ if (nodeCap === undefined || relation.cardinality !== 'many') {
202
+ return vertexIds;
192
203
  }
193
- let vertices = await fetchRowsByIds(db, vertexCollection, vertexIds, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.softDelete);
194
- if (relation.mapping) {
195
- vertices = await hydrateMapData(db, relation.mapping, vertices);
204
+ return [...new Set(vertexIds)]
205
+ .sort((a, b) => (a < b ? 1 : a > b ? -1 : 0))
206
+ .slice(0, nodeCap);
207
+ };
208
+ const emptyVertexLookup = {
209
+ get: () => undefined,
210
+ rank: () => 0,
211
+ };
212
+ const fetchVertexLookup = async (db, vertexCollection, vertexIds, relation) => {
213
+ var _a;
214
+ const rows = await fetchRowsByIds(db, vertexCollection, vertexIds, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.softDelete);
215
+ const vertices = relation.mapping
216
+ ? await hydrateMapData(db, relation.mapping, rows)
217
+ : rows;
218
+ const byId = new Map(vertices.map((vertex) => [vertex.id, vertex]));
219
+ const ranks = new Map(vertices.map((vertex, index) => [vertex.id, index]));
220
+ return {
221
+ get: (id) => byId.get(id),
222
+ rank: (id) => { var _a; return (_a = ranks.get(id)) !== null && _a !== void 0 ? _a : Number.MAX_SAFE_INTEGER; },
223
+ };
224
+ };
225
+ const relationValueFrom = (edgeRows, relation, vertexIds, lookup) => {
226
+ var _a, _b;
227
+ const toEdgeDoc = (edge) => {
228
+ var _a;
229
+ return rowToDocument(edgeCollectionName(relation.edgeCollection), edge, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.keepMetadata);
230
+ };
231
+ if (!vertexCollectionFor(relation)) {
232
+ const items = edgeRows.map(toEdgeDoc);
233
+ return relation.cardinality === 'one' ? items[0] : items;
196
234
  }
197
235
  if (relation.skipEdge) {
198
- return relation.cardinality === 'one' ? vertices[0] : vertices;
236
+ const vertices = [...new Set(vertexIds)]
237
+ .sort((a, b) => lookup.rank(a) - lookup.rank(b))
238
+ .map((id) => lookup.get(id))
239
+ .filter((vertex) => !!vertex);
240
+ if (relation.cardinality === 'one')
241
+ return vertices[0];
242
+ return applyLimit(applySort(vertices, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.sort), (_b = relation.mapping) === null || _b === void 0 ? void 0 : _b.limit);
199
243
  }
244
+ const vertexCol = vertexEdgeColumn(relation);
245
+ const capped = new Set(vertexIds);
200
246
  const items = edgeRows
201
247
  .map((edge) => {
202
- var _a;
203
248
  const vertexId = edge[vertexCol];
204
- const vertex = vertices.find((v) => v.id === vertexId);
249
+ const vertex = capped.has(vertexId) ? lookup.get(vertexId) : undefined;
205
250
  if (!vertex)
206
251
  return undefined;
207
- const edgeDoc = rowToDocument(edgeCollectionName(relation.edgeCollection), edge, (_a = relation.mapping) === null || _a === void 0 ? void 0 : _a.keepMetadata);
252
+ const edgeDoc = toEdgeDoc(edge);
208
253
  if (relation.vertexAlias) {
209
254
  return Object.assign(Object.assign({}, edgeDoc), { [relation.vertexAlias]: vertex });
210
255
  }
@@ -213,10 +258,13 @@ const resolveRelationValue = async (db, edgeRows, relation, _parentCollection) =
213
258
  .filter(Boolean);
214
259
  return relation.cardinality === 'one' ? items[0] : items;
215
260
  };
216
- const nodeCapFromLimit = (limit) => {
217
- if (limit == null)
218
- return undefined;
219
- return typeof limit === 'number' ? limit : limit[1];
261
+ const resolveRelationValue = async (db, edgeRows, relation) => {
262
+ const vertexCollection = vertexCollectionFor(relation);
263
+ const vertexIds = capVertexIds(edgeRows.map((edge) => edge[vertexEdgeColumn(relation)]), relation);
264
+ const lookup = vertexCollection
265
+ ? await fetchVertexLookup(db, vertexCollection, vertexIds, relation)
266
+ : emptyVertexLookup;
267
+ return relationValueFrom(edgeRows, relation, vertexIds, lookup);
220
268
  };
221
269
  const traverseRelation = async (db, startId, relation) => {
222
270
  var _a, _b, _c, _d, _e;
@@ -338,7 +386,7 @@ export const executeFirst = async (db, mapData) => {
338
386
  const limited = applyLimit(await executeAll(db, mapData), [0, 1]);
339
387
  return limited[0];
340
388
  };
341
- export const relationsFrom = async (db, start, parentCollection, relation) => {
389
+ export const relationsFrom = async (db, start, _parentCollection, relation) => {
342
390
  var _a;
343
391
  // Match attachRelation: honor maxDepth via BFS traversal. Without this,
344
392
  // callers like getConversationByStart only see direct (depth-1) replies.
@@ -367,7 +415,7 @@ export const relationsFrom = async (db, start, parentCollection, relation) => {
367
415
  }
368
416
  // Keep edge fields (e.g. roles) and attach the related vertex under
369
417
  // vertexAlias — same shape as hydrateDocuments/attachRelation.
370
- const value = await resolveRelationValue(db, edgeRows, relation, parentCollection);
418
+ const value = await resolveRelationValue(db, edgeRows, relation);
371
419
  if (relation.cardinality === 'one') {
372
420
  return value ? [value] : [];
373
421
  }
@@ -1,3 +1,26 @@
1
+ /** Drizzle journal tags in apply order (e.g. `0000_bizarre_chat`). */
2
+ export declare const listSchemaVersions: () => string[];
3
+ export declare const getFirstSchemaVersion: () => string;
4
+ export declare const getLatestSchemaVersion: () => string;
5
+ /**
6
+ * Postgres backups created before `schemaVersion` was stamped assumed this
7
+ * journal tag (see `sql/meta/0007_snapshot.json`).
8
+ */
9
+ export declare const LEGACY_POSTGRES_BACKUP_SCHEMA_VERSION = "0007_shallow_oracle";
10
+ /**
11
+ * Schema to apply before JSONL import on restore.
12
+ * - Arango → first journal tag so later SQL data migrations see restored rows.
13
+ * - Postgres with `schemaVersion` → that tag (must still exist in this binary).
14
+ * - Postgres without → `0007_shallow_oracle` (pre-stamping baseline).
15
+ */
16
+ export declare const resolveRestoreSchemaVersion: (databaseType: "arango" | "postgres", schemaVersion?: string) => string;
17
+ /** Apply Drizzle migrations only through `tag` (inclusive). */
18
+ export declare const migrateToSchemaVersion: (tag: string) => Promise<void>;
19
+ /**
20
+ * Wipe public + drizzle schemas, then migrate through `tag`.
21
+ * Used by backup restore so import lands on a known schema version.
22
+ */
23
+ export declare const resetAndMigrateToSchemaVersion: (tag: string) => Promise<void>;
1
24
  /** Fail if app tables are missing (used when RUN_DB_MIGRATE_ON_BOOT=false). */
2
25
  export declare const assertSchemaReady: () => Promise<void>;
3
26
  /**
@@ -1,4 +1,6 @@
1
- import { existsSync } from 'node:fs';
1
+ import { copyFileSync, existsSync, readFileSync } from 'node:fs';
2
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
2
4
  import { join, dirname } from 'node:path';
3
5
  import { fileURLToPath } from 'node:url';
4
6
  import { getTableName, sql } from 'drizzle-orm';
@@ -17,6 +19,90 @@ const resolveMigrationsFolder = () => {
17
19
  return join(moduleDir, '..', '..', '..', 'src', 'db', 'pg', 'sql');
18
20
  };
19
21
  const migrationsFolder = resolveMigrationsFolder();
22
+ const readMigrationJournal = () => {
23
+ const journalPath = join(migrationsFolder, 'meta', '_journal.json');
24
+ return JSON.parse(readFileSync(journalPath, 'utf8'));
25
+ };
26
+ /** Drizzle journal tags in apply order (e.g. `0000_bizarre_chat`). */
27
+ export const listSchemaVersions = () => readMigrationJournal().entries.map((entry) => entry.tag);
28
+ export const getFirstSchemaVersion = () => {
29
+ const tags = listSchemaVersions();
30
+ const first = tags[0];
31
+ if (!first) {
32
+ throw new Error('No Postgres schema migrations found');
33
+ }
34
+ return first;
35
+ };
36
+ export const getLatestSchemaVersion = () => {
37
+ const tags = listSchemaVersions();
38
+ const latest = tags[tags.length - 1];
39
+ if (!latest) {
40
+ throw new Error('No Postgres schema migrations found');
41
+ }
42
+ return latest;
43
+ };
44
+ /**
45
+ * Postgres backups created before `schemaVersion` was stamped assumed this
46
+ * journal tag (see `sql/meta/0007_snapshot.json`).
47
+ */
48
+ export const LEGACY_POSTGRES_BACKUP_SCHEMA_VERSION = '0007_shallow_oracle';
49
+ const assertKnownSchemaVersion = (tag) => {
50
+ if (!listSchemaVersions().includes(tag)) {
51
+ throw new Error(`Unknown Postgres schema version "${tag}"; known: ${listSchemaVersions().join(', ')}`);
52
+ }
53
+ return tag;
54
+ };
55
+ /**
56
+ * Schema to apply before JSONL import on restore.
57
+ * - Arango → first journal tag so later SQL data migrations see restored rows.
58
+ * - Postgres with `schemaVersion` → that tag (must still exist in this binary).
59
+ * - Postgres without → `0007_shallow_oracle` (pre-stamping baseline).
60
+ */
61
+ export const resolveRestoreSchemaVersion = (databaseType, schemaVersion) => {
62
+ if (databaseType === 'arango') {
63
+ return getFirstSchemaVersion();
64
+ }
65
+ if (schemaVersion) {
66
+ return assertKnownSchemaVersion(schemaVersion);
67
+ }
68
+ return assertKnownSchemaVersion(LEGACY_POSTGRES_BACKUP_SCHEMA_VERSION);
69
+ };
70
+ const buildMigrationsFolderUpTo = async (tag) => {
71
+ const journal = readMigrationJournal();
72
+ const endIdx = journal.entries.findIndex((entry) => entry.tag === tag);
73
+ if (endIdx < 0) {
74
+ throw new Error(`Unknown Postgres schema version: ${tag}`);
75
+ }
76
+ const entries = journal.entries.slice(0, endIdx + 1);
77
+ const folder = await mkdtemp(join(tmpdir(), 'op-migrate-'));
78
+ await mkdir(join(folder, 'meta'), { recursive: true });
79
+ await writeFile(join(folder, 'meta', '_journal.json'), `${JSON.stringify(Object.assign(Object.assign({}, journal), { entries }), null, 2)}\n`);
80
+ for (const entry of entries) {
81
+ copyFileSync(join(migrationsFolder, `${entry.tag}.sql`), join(folder, `${entry.tag}.sql`));
82
+ }
83
+ return folder;
84
+ };
85
+ /** Apply Drizzle migrations only through `tag` (inclusive). */
86
+ export const migrateToSchemaVersion = async (tag) => {
87
+ const folder = await buildMigrationsFolderUpTo(tag);
88
+ try {
89
+ await ensurePublicSchema();
90
+ await migrate(pgDb(), { migrationsFolder: folder });
91
+ }
92
+ finally {
93
+ await rm(folder, { recursive: true, force: true });
94
+ }
95
+ };
96
+ /**
97
+ * Wipe public + drizzle schemas, then migrate through `tag`.
98
+ * Used by backup restore so import lands on a known schema version.
99
+ */
100
+ export const resetAndMigrateToSchemaVersion = async (tag) => {
101
+ log.info('Resetting Postgres schemas and migrating to %s', tag);
102
+ await resetPostgresSchemas();
103
+ await migrateToSchemaVersion(tag);
104
+ log.info('Postgres schema ready at %s', tag);
105
+ };
20
106
  const APP_TABLE_NAMES = [
21
107
  ...DOCUMENT_IMPORT_ORDER.map((collection) => getTableName(getTableForCollection(collection))),
22
108
  ...EDGE_IMPORT_ORDER.map((collection) => getTableName(getTableForCollection(collection))),
@@ -2000,3 +2000,146 @@ export declare const profileSettings: import("drizzle-orm/pg-core").PgTableWithC
2000
2000
  };
2001
2001
  dialect: "pg";
2002
2002
  }>;
2003
+ export declare const eventOccurrences: import("drizzle-orm/pg-core").PgTableWithColumns<{
2004
+ name: "event_occurrences";
2005
+ schema: undefined;
2006
+ columns: {
2007
+ id: import("drizzle-orm/pg-core").PgColumn<{
2008
+ name: "id";
2009
+ tableName: "event_occurrences";
2010
+ dataType: "string";
2011
+ columnType: "PgUUID";
2012
+ data: string;
2013
+ driverParam: string;
2014
+ notNull: true;
2015
+ hasDefault: false;
2016
+ isPrimaryKey: true;
2017
+ isAutoincrement: false;
2018
+ hasRuntimeDefault: false;
2019
+ enumValues: undefined;
2020
+ baseColumn: never;
2021
+ identity: undefined;
2022
+ generated: undefined;
2023
+ }, {}, {}>;
2024
+ postId: import("drizzle-orm/pg-core").PgColumn<{
2025
+ name: "post_id";
2026
+ tableName: "event_occurrences";
2027
+ dataType: "string";
2028
+ columnType: "PgUUID";
2029
+ data: string;
2030
+ driverParam: string;
2031
+ notNull: true;
2032
+ hasDefault: false;
2033
+ isPrimaryKey: false;
2034
+ isAutoincrement: false;
2035
+ hasRuntimeDefault: false;
2036
+ enumValues: undefined;
2037
+ baseColumn: never;
2038
+ identity: undefined;
2039
+ generated: undefined;
2040
+ }, {}, {}>;
2041
+ recurrenceId: import("drizzle-orm/pg-core").PgColumn<{
2042
+ name: "recurrence_id";
2043
+ tableName: "event_occurrences";
2044
+ dataType: "string";
2045
+ columnType: "PgTimestampString";
2046
+ data: string;
2047
+ driverParam: string;
2048
+ notNull: true;
2049
+ hasDefault: false;
2050
+ isPrimaryKey: false;
2051
+ isAutoincrement: false;
2052
+ hasRuntimeDefault: false;
2053
+ enumValues: undefined;
2054
+ baseColumn: never;
2055
+ identity: undefined;
2056
+ generated: undefined;
2057
+ }, {}, {}>;
2058
+ start: import("drizzle-orm/pg-core").PgColumn<{
2059
+ name: "start";
2060
+ tableName: "event_occurrences";
2061
+ dataType: "string";
2062
+ columnType: "PgTimestampString";
2063
+ data: string;
2064
+ driverParam: string;
2065
+ notNull: true;
2066
+ hasDefault: false;
2067
+ isPrimaryKey: false;
2068
+ isAutoincrement: false;
2069
+ hasRuntimeDefault: false;
2070
+ enumValues: undefined;
2071
+ baseColumn: never;
2072
+ identity: undefined;
2073
+ generated: undefined;
2074
+ }, {}, {}>;
2075
+ end: import("drizzle-orm/pg-core").PgColumn<{
2076
+ name: "end";
2077
+ tableName: "event_occurrences";
2078
+ dataType: "string";
2079
+ columnType: "PgTimestampString";
2080
+ data: string;
2081
+ driverParam: string;
2082
+ notNull: false;
2083
+ hasDefault: false;
2084
+ isPrimaryKey: false;
2085
+ isAutoincrement: false;
2086
+ hasRuntimeDefault: false;
2087
+ enumValues: undefined;
2088
+ baseColumn: never;
2089
+ identity: undefined;
2090
+ generated: undefined;
2091
+ }, {}, {}>;
2092
+ cancelled: import("drizzle-orm/pg-core").PgColumn<{
2093
+ name: "cancelled";
2094
+ tableName: "event_occurrences";
2095
+ dataType: "boolean";
2096
+ columnType: "PgBoolean";
2097
+ data: boolean;
2098
+ driverParam: boolean;
2099
+ notNull: true;
2100
+ hasDefault: true;
2101
+ isPrimaryKey: false;
2102
+ isAutoincrement: false;
2103
+ hasRuntimeDefault: false;
2104
+ enumValues: undefined;
2105
+ baseColumn: never;
2106
+ identity: undefined;
2107
+ generated: undefined;
2108
+ }, {}, {}>;
2109
+ createdAt: import("drizzle-orm/pg-core").PgColumn<{
2110
+ name: "created_at";
2111
+ tableName: "event_occurrences";
2112
+ dataType: "string";
2113
+ columnType: "PgTimestampString";
2114
+ data: string;
2115
+ driverParam: string;
2116
+ notNull: true;
2117
+ hasDefault: true;
2118
+ isPrimaryKey: false;
2119
+ isAutoincrement: false;
2120
+ hasRuntimeDefault: false;
2121
+ enumValues: undefined;
2122
+ baseColumn: never;
2123
+ identity: undefined;
2124
+ generated: undefined;
2125
+ }, {}, {}>;
2126
+ updatedAt: import("drizzle-orm/pg-core").PgColumn<{
2127
+ name: "updated_at";
2128
+ tableName: "event_occurrences";
2129
+ dataType: "string";
2130
+ columnType: "PgTimestampString";
2131
+ data: string;
2132
+ driverParam: string;
2133
+ notNull: true;
2134
+ hasDefault: true;
2135
+ isPrimaryKey: false;
2136
+ isAutoincrement: false;
2137
+ hasRuntimeDefault: false;
2138
+ enumValues: undefined;
2139
+ baseColumn: never;
2140
+ identity: undefined;
2141
+ generated: undefined;
2142
+ }, {}, {}>;
2143
+ };
2144
+ dialect: "pg";
2145
+ }>;
@@ -1,4 +1,4 @@
1
- import { boolean, index, jsonb, pgTable, text, timestamp, uniqueIndex, } from 'drizzle-orm/pg-core';
1
+ import { boolean, index, jsonb, pgTable, text, timestamp, uniqueIndex, uuid, } from 'drizzle-orm/pg-core';
2
2
  import { sql } from 'drizzle-orm';
3
3
  import { idColumn, modelTimestamps, tsvector } from './base.js';
4
4
  export const dataMigrations = pgTable('data_migrations', {
@@ -38,3 +38,24 @@ export const processingStats = pgTable('processing_stats', Object.assign({ id: i
38
38
  index('processing_stats_filetype_size_idx').on(t.filetype, t.filesize),
39
39
  ]);
40
40
  export const profileSettings = pgTable('profile_settings', Object.assign({ id: idColumn(), profileId: text('profile_id').notNull(), body: jsonb('body').notNull().default({}) }, modelTimestamps), (t) => [uniqueIndex('profile_settings_profile_unique').on(t.profileId)]);
41
+ export const eventOccurrences = pgTable('event_occurrences', {
42
+ id: idColumn(),
43
+ postId: uuid('post_id').notNull(),
44
+ recurrenceId: timestamp('recurrence_id', {
45
+ withTimezone: true,
46
+ mode: 'string',
47
+ }).notNull(),
48
+ start: timestamp('start', { withTimezone: true, mode: 'string' }).notNull(),
49
+ end: timestamp('end', { withTimezone: true, mode: 'string' }),
50
+ cancelled: boolean('cancelled').notNull().default(false),
51
+ createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' })
52
+ .notNull()
53
+ .default(sql `now()`),
54
+ updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'string' })
55
+ .notNull()
56
+ .default(sql `now()`),
57
+ }, (t) => [
58
+ uniqueIndex('event_occurrences_post_recurrence').on(t.postId, t.recurrenceId),
59
+ index('event_occurrences_start_idx').on(t.start),
60
+ index('event_occurrences_post_idx').on(t.postId),
61
+ ]);
@@ -1197,6 +1197,7 @@ export declare const bookmarks: import("drizzle-orm/pg-core").PgTableWithColumns
1197
1197
  };
1198
1198
  dialect: "pg";
1199
1199
  }>;
1200
+ /** Not unique: each view is an impression; unread uses EXISTS on any row. */
1200
1201
  export declare const postSeen: import("drizzle-orm/pg-core").PgTableWithColumns<{
1201
1202
  name: string;
1202
1203
  schema: undefined;
@@ -18,7 +18,8 @@ export const reactions = edgeTable('reactions', true);
18
18
  export const replyTo = edgeTable('reply_to', true);
19
19
  export const repost = edgeTable('repost', true);
20
20
  export const bookmarks = edgeTable('bookmarks');
21
- export const postSeen = edgeTable('post_seen', true);
21
+ /** Not unique: each view is an impression; unread uses EXISTS on any row. */
22
+ export const postSeen = edgeTable('post_seen');
22
23
  export const hasSeen = edgeTable('has_seen');
23
24
  export const hasRead = edgeTable('has_read');
24
25
  export const userGroups = edgeTable('user_groups');
@@ -5795,5 +5795,148 @@ export declare const schema: {
5795
5795
  };
5796
5796
  dialect: "pg";
5797
5797
  }>;
5798
+ eventOccurrences: import("drizzle-orm/pg-core").PgTableWithColumns<{
5799
+ name: "event_occurrences";
5800
+ schema: undefined;
5801
+ columns: {
5802
+ id: import("drizzle-orm/pg-core").PgColumn<{
5803
+ name: "id";
5804
+ tableName: "event_occurrences";
5805
+ dataType: "string";
5806
+ columnType: "PgUUID";
5807
+ data: string;
5808
+ driverParam: string;
5809
+ notNull: true;
5810
+ hasDefault: false;
5811
+ isPrimaryKey: true;
5812
+ isAutoincrement: false;
5813
+ hasRuntimeDefault: false;
5814
+ enumValues: undefined;
5815
+ baseColumn: never;
5816
+ identity: undefined;
5817
+ generated: undefined;
5818
+ }, {}, {}>;
5819
+ postId: import("drizzle-orm/pg-core").PgColumn<{
5820
+ name: "post_id";
5821
+ tableName: "event_occurrences";
5822
+ dataType: "string";
5823
+ columnType: "PgUUID";
5824
+ data: string;
5825
+ driverParam: string;
5826
+ notNull: true;
5827
+ hasDefault: false;
5828
+ isPrimaryKey: false;
5829
+ isAutoincrement: false;
5830
+ hasRuntimeDefault: false;
5831
+ enumValues: undefined;
5832
+ baseColumn: never;
5833
+ identity: undefined;
5834
+ generated: undefined;
5835
+ }, {}, {}>;
5836
+ recurrenceId: import("drizzle-orm/pg-core").PgColumn<{
5837
+ name: "recurrence_id";
5838
+ tableName: "event_occurrences";
5839
+ dataType: "string";
5840
+ columnType: "PgTimestampString";
5841
+ data: string;
5842
+ driverParam: string;
5843
+ notNull: true;
5844
+ hasDefault: false;
5845
+ isPrimaryKey: false;
5846
+ isAutoincrement: false;
5847
+ hasRuntimeDefault: false;
5848
+ enumValues: undefined;
5849
+ baseColumn: never;
5850
+ identity: undefined;
5851
+ generated: undefined;
5852
+ }, {}, {}>;
5853
+ start: import("drizzle-orm/pg-core").PgColumn<{
5854
+ name: "start";
5855
+ tableName: "event_occurrences";
5856
+ dataType: "string";
5857
+ columnType: "PgTimestampString";
5858
+ data: string;
5859
+ driverParam: string;
5860
+ notNull: true;
5861
+ hasDefault: false;
5862
+ isPrimaryKey: false;
5863
+ isAutoincrement: false;
5864
+ hasRuntimeDefault: false;
5865
+ enumValues: undefined;
5866
+ baseColumn: never;
5867
+ identity: undefined;
5868
+ generated: undefined;
5869
+ }, {}, {}>;
5870
+ end: import("drizzle-orm/pg-core").PgColumn<{
5871
+ name: "end";
5872
+ tableName: "event_occurrences";
5873
+ dataType: "string";
5874
+ columnType: "PgTimestampString";
5875
+ data: string;
5876
+ driverParam: string;
5877
+ notNull: false;
5878
+ hasDefault: false;
5879
+ isPrimaryKey: false;
5880
+ isAutoincrement: false;
5881
+ hasRuntimeDefault: false;
5882
+ enumValues: undefined;
5883
+ baseColumn: never;
5884
+ identity: undefined;
5885
+ generated: undefined;
5886
+ }, {}, {}>;
5887
+ cancelled: import("drizzle-orm/pg-core").PgColumn<{
5888
+ name: "cancelled";
5889
+ tableName: "event_occurrences";
5890
+ dataType: "boolean";
5891
+ columnType: "PgBoolean";
5892
+ data: boolean;
5893
+ driverParam: boolean;
5894
+ notNull: true;
5895
+ hasDefault: true;
5896
+ isPrimaryKey: false;
5897
+ isAutoincrement: false;
5898
+ hasRuntimeDefault: false;
5899
+ enumValues: undefined;
5900
+ baseColumn: never;
5901
+ identity: undefined;
5902
+ generated: undefined;
5903
+ }, {}, {}>;
5904
+ createdAt: import("drizzle-orm/pg-core").PgColumn<{
5905
+ name: "created_at";
5906
+ tableName: "event_occurrences";
5907
+ dataType: "string";
5908
+ columnType: "PgTimestampString";
5909
+ data: string;
5910
+ driverParam: string;
5911
+ notNull: true;
5912
+ hasDefault: true;
5913
+ isPrimaryKey: false;
5914
+ isAutoincrement: false;
5915
+ hasRuntimeDefault: false;
5916
+ enumValues: undefined;
5917
+ baseColumn: never;
5918
+ identity: undefined;
5919
+ generated: undefined;
5920
+ }, {}, {}>;
5921
+ updatedAt: import("drizzle-orm/pg-core").PgColumn<{
5922
+ name: "updated_at";
5923
+ tableName: "event_occurrences";
5924
+ dataType: "string";
5925
+ columnType: "PgTimestampString";
5926
+ data: string;
5927
+ driverParam: string;
5928
+ notNull: true;
5929
+ hasDefault: true;
5930
+ isPrimaryKey: false;
5931
+ isAutoincrement: false;
5932
+ hasRuntimeDefault: false;
5933
+ enumValues: undefined;
5934
+ baseColumn: never;
5935
+ identity: undefined;
5936
+ generated: undefined;
5937
+ }, {}, {}>;
5938
+ };
5939
+ dialect: "pg";
5940
+ }>;
5798
5941
  };
5799
5942
  export type Schema = typeof schema;
@@ -0,0 +1,3 @@
1
+ -- post_seen rows are impression events; uniqueness blocked repeats (0006).
2
+ -- Unread still uses EXISTS / NOT EXISTS on any matching row.
3
+ DROP INDEX IF EXISTS "post_seen_from_to_unique";