@openpeepshq/core 0.1.31 → 0.1.32

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 (69) hide show
  1. package/dist/analytics/clicks.d.ts +20 -0
  2. package/dist/analytics/clicks.js +194 -0
  3. package/dist/analytics/index.d.ts +1 -0
  4. package/dist/analytics/index.js +1 -0
  5. package/dist/analytics/metrics.d.ts +1 -0
  6. package/dist/analytics/metrics.js +5 -0
  7. package/dist/analytics/pdfReport.js +2 -1
  8. package/dist/analytics/read.js +51 -6
  9. package/dist/analytics/report.d.ts +31 -0
  10. package/dist/backups/index.js +7 -2
  11. package/dist/config/defaults/core.js +1 -0
  12. package/dist/config/index.d.ts +10 -0
  13. package/dist/db/pg/queries/derived.d.ts +5 -0
  14. package/dist/db/pg/queries/derived.js +21 -0
  15. package/dist/db/pg/schema/analytics.d.ts +76 -0
  16. package/dist/db/pg/schema/analytics.js +11 -1
  17. package/dist/db/pg/schema/edges.js +1 -1
  18. package/dist/db/pg/schema/index.d.ts +75 -0
  19. package/dist/db/pg/sql/0005_open_power_man.sql +9 -0
  20. package/dist/db/pg/sql/0006_fine_trish_tilby.sql +8 -0
  21. package/dist/db/pg/sql/meta/0004_snapshot.json +1 -1
  22. package/dist/db/pg/sql/meta/0005_snapshot.json +4179 -0
  23. package/dist/db/pg/sql/meta/0006_snapshot.json +4200 -0
  24. package/dist/db/pg/sql/meta/_journal.json +14 -0
  25. package/dist/db/replaceOrigin.d.ts +11 -0
  26. package/dist/db/replaceOrigin.js +110 -0
  27. package/dist/jams/helpers.d.ts +4 -4
  28. package/dist/jams/index.js +5 -1
  29. package/dist/jams/waitingRoom.d.ts +2 -0
  30. package/dist/jams/waitingRoom.js +13 -5
  31. package/dist/notifications/jobs.js +13 -2
  32. package/dist/plugins/helpers.d.ts +5 -2
  33. package/dist/plugins/helpers.js +21 -2
  34. package/dist/plugins/index.d.ts +1 -1
  35. package/dist/plugins/index.js +14 -10
  36. package/dist/posts/contextClosure.d.ts +2 -1
  37. package/dist/posts/contextClosure.js +6 -1
  38. package/dist/posts/conversationQueries.d.ts +23 -0
  39. package/dist/posts/conversationQueries.js +135 -0
  40. package/dist/posts/finders.d.ts +7 -5
  41. package/dist/posts/finders.js +24 -21
  42. package/dist/posts/helpers/index.d.ts +18 -18
  43. package/dist/posts/helpers/index.js +2 -2
  44. package/dist/posts/index.d.ts +1 -0
  45. package/dist/posts/index.js +1 -0
  46. package/dist/posts/mapping.d.ts +179 -0
  47. package/dist/posts/mapping.js +6 -6
  48. package/dist/posts/mutations.d.ts +3 -1
  49. package/dist/posts/mutations.js +27 -5
  50. package/dist/posts/unseenCounts.d.ts +10 -0
  51. package/dist/posts/unseenCounts.js +81 -0
  52. package/dist/profiles/cache.d.ts +2 -0
  53. package/dist/profiles/cache.js +19 -1
  54. package/dist/profiles/index.d.ts +1 -0
  55. package/dist/profiles/index.js +1 -0
  56. package/dist/profiles/mapping.d.ts +41 -0
  57. package/dist/profiles/mapping.js +24 -0
  58. package/dist/reports/helpers.js +2 -1
  59. package/dist/reports/mapping.js +6 -2
  60. package/dist/roles/mutations.d.ts +3 -3
  61. package/dist/roles/mutations.js +5 -3
  62. package/dist/server/index.d.ts +8 -0
  63. package/dist/session/index.d.ts +28 -0
  64. package/dist/session/index.js +79 -0
  65. package/dist/stats/finders.d.ts +220 -220
  66. package/dist/stats/mapping.d.ts +5 -5
  67. package/package.json +6 -6
  68. package/dist/db/replaceHostname.d.ts +0 -1
  69. package/dist/db/replaceHostname.js +0 -88
@@ -0,0 +1,20 @@
1
+ import type { AnalyticsClickEvent, AnalyticsClickKind, AnalyticsClicks, AnalyticsDateQuery } from '@openpeepshq/common/types';
2
+ export declare const MAX_CLICK_TARGET_LENGTH = 512;
3
+ export declare const MAX_DISTINCT_CLICK_TARGETS_PER_DAY = 5000;
4
+ export declare const TOP_CLICKS_LIMIT = 25;
5
+ /** Pathname only; drop query/hash; skip admin/api/auth routes. */
6
+ export declare const normalizePageTarget: (raw: string) => string | null;
7
+ /** origin + pathname, lowercase host, no query/hash. http(s) only. */
8
+ export declare const normalizeLinkTarget: (raw: string) => string | null;
9
+ export declare const normalizeClickEvent: (event: AnalyticsClickEvent) => {
10
+ kind: AnalyticsClickKind;
11
+ target: string;
12
+ } | null;
13
+ export declare const tallyNormalizedClicks: (events: AnalyticsClickEvent[]) => Array<{
14
+ kind: AnalyticsClickKind;
15
+ target: string;
16
+ clicks: number;
17
+ }>;
18
+ /** Live increment. Does not accept or persist a profile id. */
19
+ export declare const recordClickEvents: (events: AnalyticsClickEvent[]) => Promise<void>;
20
+ export declare const getAnalyticsClicks: (query?: AnalyticsDateQuery) => Promise<AnalyticsClicks>;
@@ -0,0 +1,194 @@
1
+ import { and, count, desc, eq, gte, lte, sql, sum } from 'drizzle-orm';
2
+ import { formatISO, startOfDay } from 'date-fns';
3
+ import { logger } from '../log/index.js';
4
+ import { database } from '../db/index.js';
5
+ import { analyticsDailyClicks } from '../db/pg/schema/analytics.js';
6
+ import { resolveAnalyticsRange } from './dateRange.js';
7
+ const log = logger('app:analytics:clicks');
8
+ export const MAX_CLICK_TARGET_LENGTH = 512;
9
+ export const MAX_DISTINCT_CLICK_TARGETS_PER_DAY = 5000;
10
+ export const TOP_CLICKS_LIMIT = 25;
11
+ const SKIP_PAGE_PREFIXES = [
12
+ '/admin',
13
+ '/api',
14
+ '/login',
15
+ '/signup',
16
+ '/register',
17
+ '/auth',
18
+ '/oauth',
19
+ '/sso',
20
+ '/health',
21
+ '/_db',
22
+ ];
23
+ const todayString = () => formatISO(startOfDay(new Date()), { representation: 'date' });
24
+ const skipPagePath = (pathname) => SKIP_PAGE_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
25
+ const truncateCheck = (value) => value.length === 0 || value.length > MAX_CLICK_TARGET_LENGTH ? null : value;
26
+ /** Pathname only; drop query/hash; skip admin/api/auth routes. */
27
+ export const normalizePageTarget = (raw) => {
28
+ const trimmed = raw.trim();
29
+ if (!trimmed)
30
+ return null;
31
+ let pathname;
32
+ try {
33
+ if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed)) {
34
+ const url = new URL(trimmed);
35
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
36
+ return null;
37
+ }
38
+ pathname = url.pathname || '/';
39
+ }
40
+ else {
41
+ pathname = new URL(trimmed, 'https://openpeeps.invalid').pathname || '/';
42
+ }
43
+ }
44
+ catch (_a) {
45
+ return null;
46
+ }
47
+ if (!pathname.startsWith('/'))
48
+ return null;
49
+ if (skipPagePath(pathname))
50
+ return null;
51
+ return truncateCheck(pathname);
52
+ };
53
+ /** origin + pathname, lowercase host, no query/hash. http(s) only. */
54
+ export const normalizeLinkTarget = (raw) => {
55
+ const trimmed = raw.trim();
56
+ if (!trimmed)
57
+ return null;
58
+ if (/^(javascript|data|mailto|tel|blob):/i.test(trimmed))
59
+ return null;
60
+ try {
61
+ const url = new URL(trimmed);
62
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
63
+ return null;
64
+ }
65
+ const host = url.hostname.toLowerCase();
66
+ const port = url.port ? `:${url.port}` : '';
67
+ const path = url.pathname || '/';
68
+ return truncateCheck(`${url.protocol}//${host}${port}${path}`);
69
+ }
70
+ catch (_a) {
71
+ return null;
72
+ }
73
+ };
74
+ export const normalizeClickEvent = (event) => {
75
+ if (event.kind === 'page') {
76
+ const target = normalizePageTarget(event.target);
77
+ return target ? { kind: 'page', target } : null;
78
+ }
79
+ const target = normalizeLinkTarget(event.target);
80
+ return target ? { kind: 'link', target } : null;
81
+ };
82
+ export const tallyNormalizedClicks = (events) => {
83
+ var _a;
84
+ const counts = new Map();
85
+ const tallies = new Map();
86
+ for (const event of events) {
87
+ const normalized = normalizeClickEvent(event);
88
+ if (!normalized)
89
+ continue;
90
+ const key = `${normalized.kind}\0${normalized.target}`;
91
+ counts.set(key, normalized);
92
+ tallies.set(key, ((_a = tallies.get(key)) !== null && _a !== void 0 ? _a : 0) + 1);
93
+ }
94
+ return [...counts.entries()].map(([key, { kind, target }]) => {
95
+ var _a;
96
+ return ({
97
+ kind,
98
+ target,
99
+ clicks: (_a = tallies.get(key)) !== null && _a !== void 0 ? _a : 0,
100
+ });
101
+ });
102
+ };
103
+ const incrementExisting = async (day, kind, target, clicks) => {
104
+ const db = await database();
105
+ await db
106
+ .update(analyticsDailyClicks)
107
+ .set({
108
+ clicks: sql `${analyticsDailyClicks.clicks} + ${clicks}`,
109
+ })
110
+ .where(and(eq(analyticsDailyClicks.day, day), eq(analyticsDailyClicks.kind, kind), eq(analyticsDailyClicks.target, target)));
111
+ };
112
+ const upsertClick = async (day, kind, target, clicks) => {
113
+ const db = await database();
114
+ await db
115
+ .insert(analyticsDailyClicks)
116
+ .values({ day, kind, target, clicks })
117
+ .onConflictDoUpdate({
118
+ target: [
119
+ analyticsDailyClicks.day,
120
+ analyticsDailyClicks.kind,
121
+ analyticsDailyClicks.target,
122
+ ],
123
+ set: { clicks: sql `${analyticsDailyClicks.clicks} + ${clicks}` },
124
+ });
125
+ };
126
+ const distinctTargetCount = async (day) => {
127
+ var _a, _b;
128
+ const db = await database();
129
+ const rows = await db
130
+ .select({ n: count() })
131
+ .from(analyticsDailyClicks)
132
+ .where(eq(analyticsDailyClicks.day, day));
133
+ return Number((_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.n) !== null && _b !== void 0 ? _b : 0);
134
+ };
135
+ /** Live increment. Does not accept or persist a profile id. */
136
+ export const recordClickEvents = async (events) => {
137
+ const tallied = tallyNormalizedClicks(events);
138
+ if (tallied.length === 0)
139
+ return;
140
+ const day = todayString();
141
+ let distinct = await distinctTargetCount(day);
142
+ let loggedCap = false;
143
+ for (const row of tallied) {
144
+ if (distinct >= MAX_DISTINCT_CLICK_TARGETS_PER_DAY) {
145
+ if (!loggedCap) {
146
+ log.warn('Dropping new click targets; day %s already has %s distinct targets', day, distinct);
147
+ loggedCap = true;
148
+ }
149
+ await incrementExisting(day, row.kind, row.target, row.clicks);
150
+ continue;
151
+ }
152
+ await upsertClick(day, row.kind, row.target, row.clicks);
153
+ distinct += 1;
154
+ }
155
+ };
156
+ const topClicks = async (from, to, kind) => {
157
+ const db = await database();
158
+ const rows = await db
159
+ .select({
160
+ target: analyticsDailyClicks.target,
161
+ clicks: sum(analyticsDailyClicks.clicks),
162
+ })
163
+ .from(analyticsDailyClicks)
164
+ .where(and(gte(analyticsDailyClicks.day, from), lte(analyticsDailyClicks.day, to), eq(analyticsDailyClicks.kind, kind)))
165
+ .groupBy(analyticsDailyClicks.target)
166
+ .orderBy(desc(sum(analyticsDailyClicks.clicks)))
167
+ .limit(TOP_CLICKS_LIMIT);
168
+ return rows.map((row) => {
169
+ var _a;
170
+ return ({
171
+ target: row.target,
172
+ clicks: Number((_a = row.clicks) !== null && _a !== void 0 ? _a : 0),
173
+ });
174
+ });
175
+ };
176
+ export const getAnalyticsClicks = async (query = {}) => {
177
+ const range = resolveAnalyticsRange(query);
178
+ const [pages, links] = await Promise.all([
179
+ topClicks(range.from, range.to, 'page'),
180
+ topClicks(range.from, range.to, 'link'),
181
+ ]);
182
+ return {
183
+ range: {
184
+ from: range.from,
185
+ to: range.to,
186
+ previousFrom: range.previousFrom,
187
+ previousTo: range.previousTo,
188
+ preset: range.preset,
189
+ compiledAt: null,
190
+ },
191
+ pages,
192
+ links,
193
+ };
194
+ };
@@ -2,6 +2,7 @@ export { resolveAnalyticsRange, eachUtcDay, type ResolvedAnalyticsRange, } from
2
2
  export { analyticsCacheKey, getAnalyticsCache, setAnalyticsCache, invalidateAnalyticsCache, } from './cache';
3
3
  export { compileAnalyticsDay, compileRetentionCohorts, compileRecentAnalytics, backfillAnalytics, } from './compile';
4
4
  export { getAnalyticsOverview, getAnalyticsGrowth, getAnalyticsEngagement, getAnalyticsRetention, exportAnalyticsCsv, } from './read';
5
+ export { recordClickEvents, getAnalyticsClicks, normalizeClickEvent, } from './clicks';
5
6
  export { getAnalyticsReportSettings, setAnalyticsReportSettings, } from './settings';
6
7
  export { sendMonthlyAnalyticsReport, buildSimplePdf, buildAnalyticsBoardReport, } from './report';
7
8
  export { buildAnalyticsPdf, type AnalyticsPdfData } from './pdfReport';
@@ -2,6 +2,7 @@ export { resolveAnalyticsRange, eachUtcDay, } from './dateRange.js';
2
2
  export { analyticsCacheKey, getAnalyticsCache, setAnalyticsCache, invalidateAnalyticsCache, } from './cache.js';
3
3
  export { compileAnalyticsDay, compileRetentionCohorts, compileRecentAnalytics, backfillAnalytics, } from './compile.js';
4
4
  export { getAnalyticsOverview, getAnalyticsGrowth, getAnalyticsEngagement, getAnalyticsRetention, exportAnalyticsCsv, } from './read.js';
5
+ export { recordClickEvents, getAnalyticsClicks, normalizeClickEvent, } from './clicks.js';
5
6
  export { getAnalyticsReportSettings, setAnalyticsReportSettings, } from './settings.js';
6
7
  export { sendMonthlyAnalyticsReport, buildSimplePdf, buildAnalyticsBoardReport, } from './report.js';
7
8
  export { buildAnalyticsPdf } from './pdfReport.js';
@@ -2,3 +2,4 @@ import type { AnalyticsMetricCard, AnalyticsSeriesPoint } from '@openpeepshq/com
2
2
  export declare const deltaPct: (current: number, previous: number) => number | null;
3
3
  export declare const metricCard: (key: string, value: number, previousValue: number, series?: AnalyticsSeriesPoint[]) => AnalyticsMetricCard;
4
4
  export declare const sumSeries: (series: AnalyticsSeriesPoint[]) => number;
5
+ export declare const averageSeries: (series: AnalyticsSeriesPoint[]) => number;
@@ -11,3 +11,8 @@ export const metricCard = (key, value, previousValue, series) => ({
11
11
  series,
12
12
  });
13
13
  export const sumSeries = (series) => series.reduce((acc, p) => acc + p.value, 0);
14
+ export const averageSeries = (series) => {
15
+ if (series.length === 0)
16
+ return 0;
17
+ return Math.round((sumSeries(series) / series.length) * 10) / 10;
18
+ };
@@ -35,6 +35,7 @@ const ENGAGEMENT_SERIES = [
35
35
  { key: 'reposts', label: 'Shares', color: '#4b5563' },
36
36
  { key: 'bookmarks', label: 'Bookmarks', color: '#6b7280' },
37
37
  { key: 'comments', label: 'Replies', color: '#9ca3af' },
38
+ { key: 'dms', label: 'DMs', color: '#d97706' },
38
39
  ];
39
40
  /** Single-line text that must not trigger pdfkit auto page-breaks. */
40
41
  const writeText = (doc, text, x, y, options = {}) => {
@@ -368,7 +369,7 @@ const drawStackedAreaAsBars = (layout, points, height = 170) => {
368
369
  const pad = { t: 16, r: 12, b: 40, l: 36 };
369
370
  const plotW = frame.w - pad.l - pad.r;
370
371
  const plotH = frame.h - pad.t - pad.b;
371
- const totals = points.map((p) => p.likes + p.comments + p.reposts + p.bookmarks);
372
+ const totals = points.map((p) => p.likes + p.comments + p.reposts + p.bookmarks + p.dms);
372
373
  const max = Math.max(1, ...totals);
373
374
  const barGap = 3;
374
375
  const barW = points.length
@@ -1,14 +1,44 @@
1
1
  import { and, asc, desc, gte, lte, min, sql, sum } from 'drizzle-orm';
2
- import { formatISO, startOfDay } from 'date-fns';
2
+ import { formatISO, startOfDay, subDays, parseISO, addDays } from 'date-fns';
3
3
  import { database } from '../db/index.js';
4
4
  import { analyticsDailyByGroup, analyticsDailyTotals, analyticsPostViewsDaily, analyticsRetentionCohorts, } from '../db/pg/schema/analytics.js';
5
5
  import { groups, posts, profiles } from '../db/pg/schema/documents.js';
6
6
  import { analyticsCacheKey, getAnalyticsCache, setAnalyticsCache, } from './cache.js';
7
7
  import { aggregateSeriesIntoBuckets, eachUtcDay, resolveAnalyticsRange, selectChartBuckets, } from './dateRange.js';
8
- import { metricCard, sumSeries } from './metrics.js';
8
+ import { metricCard, sumSeries, averageSeries } from './metrics.js';
9
9
  const POST_TYPE_KEYS = ['jam', 'article', 'note', 'poll', 'event'];
10
10
  const todayString = () => formatISO(startOfDay(new Date()), { representation: 'date' });
11
11
  const includesToday = (to) => to >= todayString();
12
+ const utcDayStart = (day) => `${day}T00:00:00.000Z`;
13
+ const exclusiveEnd = (day) => `${formatISO(addDays(parseISO(utcDayStart(day)), 1), { representation: 'date' })}T00:00:00.000Z`;
14
+ const rollingMauFrom = (to) => formatISO(subDays(parseISO(utcDayStart(to)), 29), { representation: 'date' });
15
+ const countDistinctActives = async (from, to) => {
16
+ var _a, _b;
17
+ const db = await database();
18
+ const start = utcDayStart(from);
19
+ const end = exclusiveEnd(to);
20
+ const result = await db.execute(sql `
21
+ select count(*)::int as c from (
22
+ select creator_id as profile_id from posts
23
+ where deleted_at is null
24
+ and created_at >= ${start} and created_at < ${end}
25
+ union
26
+ select from_id from reactions
27
+ where created_at >= ${start} and created_at < ${end}
28
+ union
29
+ select from_id from repost
30
+ where created_at >= ${start} and created_at < ${end}
31
+ union
32
+ select from_id from reply_to
33
+ where created_at >= ${start} and created_at < ${end}
34
+ union
35
+ select from_id from bookmarks
36
+ where created_at >= ${start} and created_at < ${end}
37
+ ) active
38
+ `);
39
+ const rows = result.rows;
40
+ return Number((_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.c) !== null && _b !== void 0 ? _b : 0);
41
+ };
12
42
  /** Earliest day with compiled analytics — used to bound the `all` preset. */
13
43
  const earliestAnalyticsDay = async () => {
14
44
  var _a;
@@ -528,11 +558,17 @@ export const getAnalyticsOverview = async (query = {}) => {
528
558
  };
529
559
  export const getAnalyticsGrowth = async (query = {}) => {
530
560
  const range = await resolveQueryRange(query);
531
- return withCache('growth-v5', range.from, range.to, async () => {
561
+ return withCache('growth-v6', range.from, range.to, async () => {
532
562
  const db = await database();
533
- const [newMembersSeries, prevNew, compiledAt, recentRows] = await Promise.all([
563
+ const mauFrom = rollingMauFrom(range.to);
564
+ const prevMauFrom = rollingMauFrom(range.previousTo);
565
+ const [newMembersSeries, activeMembersSeries, prevNew, prevActiveSeries, mau, prevMau, compiledAt, recentRows,] = await Promise.all([
534
566
  loadTotalsSeries(range.from, range.to, 'newMembers'),
567
+ loadTotalsSeries(range.from, range.to, 'activeMembers'),
535
568
  sumColumn(range.previousFrom, range.previousTo, 'newMembers'),
569
+ loadTotalsSeries(range.previousFrom, range.previousTo, 'activeMembers'),
570
+ countDistinctActives(mauFrom, range.to),
571
+ countDistinctActives(prevMauFrom, range.previousTo),
536
572
  latestCompiledAt(range.from, range.to),
537
573
  db.execute(sql `
538
574
  select p.id, p.handle, p.body, p.created_at,
@@ -547,6 +583,10 @@ export const getAnalyticsGrowth = async (query = {}) => {
547
583
  `),
548
584
  ]);
549
585
  const newSignups = sumSeries(newMembersSeries);
586
+ const dau = averageSeries(activeMembersSeries);
587
+ const prevDau = averageSeries(prevActiveSeries);
588
+ const dauMau = mau === 0 ? 0 : Math.round((dau / mau) * 1000) / 10;
589
+ const prevDauMau = prevMau === 0 ? 0 : Math.round((prevDau / prevMau) * 1000) / 10;
550
590
  const byDay = new Map(newMembersSeries.map((p) => [p.day, p.value]));
551
591
  const signupsByDay = eachUtcDay(range.from, range.to).map((day) => {
552
592
  var _a;
@@ -569,6 +609,9 @@ export const getAnalyticsGrowth = async (query = {}) => {
569
609
  range: Object.assign(Object.assign({}, range), { compiledAt }),
570
610
  metrics: {
571
611
  newSignups: metricCard('newSignups', newSignups, prevNew, newMembersSeries),
612
+ dau: metricCard('dau', dau, prevDau, activeMembersSeries),
613
+ mau: metricCard('mau', mau, prevMau),
614
+ dauMau: metricCard('dauMau', dauMau, prevDauMau),
572
615
  },
573
616
  signupsByDay,
574
617
  recentSignups,
@@ -577,7 +620,7 @@ export const getAnalyticsGrowth = async (query = {}) => {
577
620
  };
578
621
  export const getAnalyticsEngagement = async (query = {}) => {
579
622
  const range = await resolveQueryRange(query);
580
- return withCache('engagement-v3', range.from, range.to, async () => {
623
+ return withCache('engagement-v4', range.from, range.to, async () => {
581
624
  const [likesSeries, commentsSeries, repostsSeries, bookmarksSeries, dmsSeries, viewersSeries, impressionsSeries, prevLikes, prevComments, prevReposts, prevBookmarks, prevDms, prevViewers, prevImpressions, groups, compiledAt,] = await Promise.all([
582
625
  loadTotalsSeries(range.from, range.to, 'likes'),
583
626
  loadTotalsSeries(range.from, range.to, 'comments'),
@@ -601,9 +644,10 @@ export const getAnalyticsEngagement = async (query = {}) => {
601
644
  const commentsByBucket = aggregateSeriesIntoBuckets(commentsSeries, buckets);
602
645
  const repostsByBucket = aggregateSeriesIntoBuckets(repostsSeries, buckets);
603
646
  const bookmarksByBucket = aggregateSeriesIntoBuckets(bookmarksSeries, buckets);
647
+ const dmsByBucket = aggregateSeriesIntoBuckets(dmsSeries, buckets);
604
648
  const impressionsByPeriod = aggregateSeriesIntoBuckets(impressionsSeries, buckets);
605
649
  const engagementOverTime = buckets.map((bucket, i) => {
606
- var _a, _b, _c, _d, _e, _f, _g, _h;
650
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
607
651
  return ({
608
652
  day: bucket.key,
609
653
  label: bucket.label,
@@ -611,6 +655,7 @@ export const getAnalyticsEngagement = async (query = {}) => {
611
655
  comments: (_d = (_c = commentsByBucket[i]) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : 0,
612
656
  reposts: (_f = (_e = repostsByBucket[i]) === null || _e === void 0 ? void 0 : _e.value) !== null && _f !== void 0 ? _f : 0,
613
657
  bookmarks: (_h = (_g = bookmarksByBucket[i]) === null || _g === void 0 ? void 0 : _g.value) !== null && _h !== void 0 ? _h : 0,
658
+ dms: (_k = (_j = dmsByBucket[i]) === null || _j === void 0 ? void 0 : _j.value) !== null && _k !== void 0 ? _k : 0,
614
659
  });
615
660
  });
616
661
  return {
@@ -157,6 +157,36 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
157
157
  value: number;
158
158
  }[] | undefined;
159
159
  };
160
+ dau: {
161
+ key: string;
162
+ value: number;
163
+ previousValue: number;
164
+ deltaPct: number | null;
165
+ series?: {
166
+ day: string;
167
+ value: number;
168
+ }[] | undefined;
169
+ };
170
+ mau: {
171
+ key: string;
172
+ value: number;
173
+ previousValue: number;
174
+ deltaPct: number | null;
175
+ series?: {
176
+ day: string;
177
+ value: number;
178
+ }[] | undefined;
179
+ };
180
+ dauMau: {
181
+ key: string;
182
+ value: number;
183
+ previousValue: number;
184
+ deltaPct: number | null;
185
+ series?: {
186
+ day: string;
187
+ value: number;
188
+ }[] | undefined;
189
+ };
160
190
  };
161
191
  signupsByDay: {
162
192
  day: string;
@@ -258,6 +288,7 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
258
288
  comments: number;
259
289
  reposts: number;
260
290
  bookmarks: number;
291
+ dms: number;
261
292
  }[];
262
293
  impressionsByPeriod: {
263
294
  day: string;
@@ -9,9 +9,10 @@ import extract from 'extract-zip';
9
9
  import { collectionInfos } from '../db/index.js';
10
10
  import { communityConfig, config } from '../config/index.js';
11
11
  import { exportAllPostgresCollections, importAllArangoCollections, importAllPostgresCollections, } from '../db/migration/importCollections.js';
12
- import { replaceHostname } from '../db/replaceHostname.js';
12
+ import { replaceOrigin } from '../db/replaceOrigin.js';
13
13
  import { logger } from '../log/index.js';
14
14
  import { setDefaultRoles } from '../roles/index.js';
15
+ import { serverRootUrl } from '../server/index.js';
15
16
  import { resolveBackupDatabaseType, } from './metadata.js';
16
17
  export { resolveBackupDatabaseType } from './metadata.js';
17
18
  const log = logger('core:backups');
@@ -254,7 +255,11 @@ export const restoreBackups = async (zipFilePath) => {
254
255
  recursive: true,
255
256
  });
256
257
  await restoreDatabaseFromBackup(collectionsDir, databaseType);
257
- await replaceHostname((_a = backupMetadata === null || backupMetadata === void 0 ? void 0 : backupMetadata.config) === null || _a === void 0 ? void 0 : _a.hostname, hostnameFromServerHost(coreConfig.server.host));
258
+ // Repoint the backup's absolute URLs at this server's full origin (scheme +
259
+ // host + port). Matching by the backup hostname means a prod backup on
260
+ // `https://host` restores cleanly onto `http://localhost:5174` without
261
+ // stranding the old scheme/port.
262
+ await replaceOrigin((_a = backupMetadata === null || backupMetadata === void 0 ? void 0 : backupMetadata.config) === null || _a === void 0 ? void 0 : _a.hostname, await serverRootUrl());
258
263
  log.info(`Restored ${databaseType} backup (hostname was ${(_c = (_b = backupMetadata === null || backupMetadata === void 0 ? void 0 : backupMetadata.config) === null || _b === void 0 ? void 0 : _b.hostname) !== null && _c !== void 0 ? _c : 'unknown'})`);
259
264
  await setDefaultRoles();
260
265
  };
@@ -45,6 +45,7 @@ export const defaultConfig = {
45
45
  },
46
46
  plugins: {
47
47
  path: path.resolve(process.env.PLUGINS_PATH || '../plugins'),
48
+ rootPackageJsonPath: path.resolve(process.env.ROOT_PACKAGE_JSON_PATH || '../package.json'),
48
49
  },
49
50
  secrets: {
50
51
  jwt: resolveJwtSecret(),
@@ -65,6 +65,7 @@ export declare const config: <T = {
65
65
  };
66
66
  plugins: {
67
67
  path: string;
68
+ rootPackageJsonPath: string;
68
69
  };
69
70
  secrets: {
70
71
  jwt: string;
@@ -173,6 +174,10 @@ export declare const communityConfig: () => Promise<{
173
174
  primaryHex: string;
174
175
  light: {
175
176
  primaryHex: string;
177
+ secondaryHex?: string | undefined;
178
+ fontFamily?: string | undefined;
179
+ buttonRadius?: string | undefined;
180
+ radius?: string | undefined;
176
181
  logoSmall?: string | undefined;
177
182
  defaultProfileAvatar?: string | undefined;
178
183
  defaultGroupAvatar?: string | undefined;
@@ -181,6 +186,10 @@ export declare const communityConfig: () => Promise<{
181
186
  };
182
187
  dark: {
183
188
  primaryHex: string;
189
+ secondaryHex?: string | undefined;
190
+ fontFamily?: string | undefined;
191
+ buttonRadius?: string | undefined;
192
+ radius?: string | undefined;
184
193
  logoSmall?: string | undefined;
185
194
  defaultProfileAvatar?: string | undefined;
186
195
  defaultGroupAvatar?: string | undefined;
@@ -285,6 +294,7 @@ export declare const sanitizedConfigWithDefaults: <T = {
285
294
  };
286
295
  plugins: {
287
296
  path: string;
297
+ rootPackageJsonPath: string;
288
298
  };
289
299
  secrets: {
290
300
  jwt: string;
@@ -8,6 +8,11 @@ export declare const profileDerived: {
8
8
  followersCount: number;
9
9
  followingCount: number;
10
10
  };
11
+ /** Counts without loading follower/following trees. */
12
+ profileStatsCounts: (db: PgDb, doc: Doc) => Promise<{
13
+ followersCount: number;
14
+ followingCount: number;
15
+ }>;
11
16
  };
12
17
  export declare const postDerived: {
13
18
  seen: (profileId?: string) => (db: PgDb, doc: Doc) => Promise<boolean>;
@@ -44,6 +44,27 @@ export const profileDerived = {
44
44
  followersCount: Array.isArray(doc.followers) ? doc.followers.length : 0,
45
45
  followingCount: Array.isArray(doc.following) ? doc.following.length : 0,
46
46
  }),
47
+ /** Counts without loading follower/following trees. */
48
+ profileStatsCounts: async (db, doc) => {
49
+ var _a, _b, _c, _d;
50
+ const edgeTableRef = getEdgeTable('follows');
51
+ const edgeTable = asTable(edgeTableRef);
52
+ const profileId = doc.id;
53
+ const [followersRows, followingRows] = await Promise.all([
54
+ db
55
+ .select({ count: sql `count(*)::int` })
56
+ .from(edgeTableRef)
57
+ .where(eq(edgeTable.toId, profileId)),
58
+ db
59
+ .select({ count: sql `count(*)::int` })
60
+ .from(edgeTableRef)
61
+ .where(eq(edgeTable.fromId, profileId)),
62
+ ]);
63
+ return {
64
+ followersCount: (_b = (_a = followersRows[0]) === null || _a === void 0 ? void 0 : _a.count) !== null && _b !== void 0 ? _b : 0,
65
+ followingCount: (_d = (_c = followingRows[0]) === null || _c === void 0 ? void 0 : _c.count) !== null && _d !== void 0 ? _d : 0,
66
+ };
67
+ },
47
68
  };
48
69
  export const postDerived = {
49
70
  seen: (profileId) => async (db, doc) => {
@@ -996,3 +996,79 @@ export declare const analyticsReportDeliveries: import("drizzle-orm/pg-core").Pg
996
996
  };
997
997
  dialect: "pg";
998
998
  }>;
999
+ /** Aggregate in-app page views and outbound link clicks. No identity columns. */
1000
+ export declare const analyticsDailyClicks: import("drizzle-orm/pg-core").PgTableWithColumns<{
1001
+ name: "analytics_daily_clicks";
1002
+ schema: undefined;
1003
+ columns: {
1004
+ day: import("drizzle-orm/pg-core").PgColumn<{
1005
+ name: "day";
1006
+ tableName: "analytics_daily_clicks";
1007
+ dataType: "string";
1008
+ columnType: "PgDateString";
1009
+ data: string;
1010
+ driverParam: string;
1011
+ notNull: true;
1012
+ hasDefault: false;
1013
+ isPrimaryKey: false;
1014
+ isAutoincrement: false;
1015
+ hasRuntimeDefault: false;
1016
+ enumValues: undefined;
1017
+ baseColumn: never;
1018
+ identity: undefined;
1019
+ generated: undefined;
1020
+ }, {}, {}>;
1021
+ kind: import("drizzle-orm/pg-core").PgColumn<{
1022
+ name: "kind";
1023
+ tableName: "analytics_daily_clicks";
1024
+ dataType: "string";
1025
+ columnType: "PgText";
1026
+ data: string;
1027
+ driverParam: string;
1028
+ notNull: true;
1029
+ hasDefault: false;
1030
+ isPrimaryKey: false;
1031
+ isAutoincrement: false;
1032
+ hasRuntimeDefault: false;
1033
+ enumValues: [string, ...string[]];
1034
+ baseColumn: never;
1035
+ identity: undefined;
1036
+ generated: undefined;
1037
+ }, {}, {}>;
1038
+ target: import("drizzle-orm/pg-core").PgColumn<{
1039
+ name: "target";
1040
+ tableName: "analytics_daily_clicks";
1041
+ dataType: "string";
1042
+ columnType: "PgText";
1043
+ data: string;
1044
+ driverParam: string;
1045
+ notNull: true;
1046
+ hasDefault: false;
1047
+ isPrimaryKey: false;
1048
+ isAutoincrement: false;
1049
+ hasRuntimeDefault: false;
1050
+ enumValues: [string, ...string[]];
1051
+ baseColumn: never;
1052
+ identity: undefined;
1053
+ generated: undefined;
1054
+ }, {}, {}>;
1055
+ clicks: import("drizzle-orm/pg-core").PgColumn<{
1056
+ name: "clicks";
1057
+ tableName: "analytics_daily_clicks";
1058
+ dataType: "number";
1059
+ columnType: "PgInteger";
1060
+ data: number;
1061
+ driverParam: string | number;
1062
+ notNull: true;
1063
+ hasDefault: true;
1064
+ isPrimaryKey: false;
1065
+ isAutoincrement: false;
1066
+ hasRuntimeDefault: false;
1067
+ enumValues: undefined;
1068
+ baseColumn: never;
1069
+ identity: undefined;
1070
+ generated: undefined;
1071
+ }, {}, {}>;
1072
+ };
1073
+ dialect: "pg";
1074
+ }>;
@@ -1,4 +1,4 @@
1
- import { date, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex, } from 'drizzle-orm/pg-core';
1
+ import { date, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, } from 'drizzle-orm/pg-core';
2
2
  import { sql } from 'drizzle-orm';
3
3
  import { idColumn } from './base.js';
4
4
  /** One row per UTC calendar day — community-wide counters. */
@@ -108,3 +108,13 @@ export const analyticsReportDeliveries = pgTable('analytics_report_deliveries',
108
108
  .notNull()
109
109
  .default(sql `now()`),
110
110
  }, (t) => [index('analytics_report_deliveries_period_idx').on(t.periodStart)]);
111
+ /** Aggregate in-app page views and outbound link clicks. No identity columns. */
112
+ export const analyticsDailyClicks = pgTable('analytics_daily_clicks', {
113
+ day: date('day', { mode: 'string' }).notNull(),
114
+ kind: text('kind').notNull(),
115
+ target: text('target').notNull(),
116
+ clicks: integer('clicks').notNull().default(0),
117
+ }, (t) => [
118
+ primaryKey({ columns: [t.day, t.kind, t.target] }),
119
+ index('analytics_daily_clicks_day_kind_idx').on(t.day, t.kind),
120
+ ]);
@@ -18,7 +18,7 @@ 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');
21
+ export const postSeen = edgeTable('post_seen', true);
22
22
  export const hasSeen = edgeTable('has_seen');
23
23
  export const hasRead = edgeTable('has_read');
24
24
  export const userGroups = edgeTable('user_groups');