@openpeepshq/common 0.1.46 → 0.3.0

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 (83) hide show
  1. package/dist/lib/adminSections.js +1 -1
  2. package/dist/lib/capabilitiesHelpers.js +30 -40
  3. package/dist/lib/csvHelpers.js +1 -1
  4. package/dist/lib/eventIcs.js +26 -32
  5. package/dist/lib/eventRecurrence.d.ts +17 -0
  6. package/dist/lib/eventRecurrence.js +75 -18
  7. package/dist/lib/eventTime.js +9 -11
  8. package/dist/lib/groupHelpers.js +13 -34
  9. package/dist/lib/groupTemplateHelpers.js +6 -10
  10. package/dist/lib/jamHelpers.js +6 -9
  11. package/dist/lib/markdownHelpers.d.ts +37 -0
  12. package/dist/lib/markdownHelpers.js +151 -3
  13. package/dist/lib/postHelpers.js +70 -97
  14. package/dist/lib/profileHelpers.js +17 -24
  15. package/dist/lib/pushHelpers.js +3 -4
  16. package/dist/lib/scopeHelpers.js +6 -9
  17. package/dist/lib/ssoLoginUrl.js +4 -6
  18. package/dist/lib/ssoProviders.js +35 -39
  19. package/dist/lib/tokenHelpers.js +5 -5
  20. package/dist/lib/utils.js +6 -7
  21. package/dist/types/admin-db.js +1 -1
  22. package/dist/types/api.d.ts +1 -0
  23. package/dist/types/api.js +1 -1
  24. package/dist/types/config.d.ts +3 -0
  25. package/dist/types/config.js +3 -0
  26. package/dist/types/models.js +1 -1
  27. package/dist/types/plugins.js +2 -2
  28. package/dist/zod.d.ts +1 -0
  29. package/dist/zod.js +1 -0
  30. package/package.json +36 -6
  31. package/src/index.ts +4 -0
  32. package/src/lib/adminSections.ts +84 -0
  33. package/src/lib/attachmentHelpers.ts +14 -0
  34. package/src/lib/capabilitiesHelpers.ts +532 -0
  35. package/src/lib/colors.ts +20 -0
  36. package/src/lib/csvHelpers.ts +31 -0
  37. package/src/lib/eventIcs.ts +265 -0
  38. package/src/lib/eventRecurrence.ts +495 -0
  39. package/src/lib/eventTime.ts +206 -0
  40. package/src/lib/federationHosts.ts +22 -0
  41. package/src/lib/feedCursor.ts +27 -0
  42. package/src/lib/feedFormat.ts +24 -0
  43. package/src/lib/groupHelpers.ts +421 -0
  44. package/src/lib/groupTemplateHelpers.ts +83 -0
  45. package/src/lib/index.ts +29 -0
  46. package/src/lib/jamHelpers.ts +164 -0
  47. package/src/lib/legacyThemeRoot.ts +14 -0
  48. package/src/lib/markdownHelpers.ts +290 -0
  49. package/src/lib/mediaDimensions.ts +21 -0
  50. package/src/lib/postHelpers.ts +783 -0
  51. package/src/lib/profileHelpers.ts +220 -0
  52. package/src/lib/pushHelpers.ts +34 -0
  53. package/src/lib/reactions.ts +52 -0
  54. package/src/lib/reportHelpers.ts +7 -0
  55. package/src/lib/scopeHelpers.ts +176 -0
  56. package/src/lib/ssoLoginUrl.ts +93 -0
  57. package/src/lib/ssoProviders.ts +472 -0
  58. package/src/lib/text.ts +26 -0
  59. package/src/lib/timeZone.ts +52 -0
  60. package/src/lib/tokenHelpers.ts +119 -0
  61. package/src/lib/utils.ts +322 -0
  62. package/src/types/admin-db.ts +74 -0
  63. package/src/types/admin-email.ts +55 -0
  64. package/src/types/admin-jobs.ts +17 -0
  65. package/src/types/admin-performance.ts +20 -0
  66. package/src/types/analytics.ts +318 -0
  67. package/src/types/api.ts +871 -0
  68. package/src/types/apple-app-site-association.ts +54 -0
  69. package/src/types/auth.ts +22 -0
  70. package/src/types/capabilities.ts +280 -0
  71. package/src/types/config.ts +546 -0
  72. package/src/types/db.ts +138 -0
  73. package/src/types/export.ts +10 -0
  74. package/src/types/index.ts +20 -0
  75. package/src/types/internal.ts +338 -0
  76. package/src/types/models.ts +939 -0
  77. package/src/types/notifications.ts +92 -0
  78. package/src/types/plugins.ts +150 -0
  79. package/src/types/roleDefaults.ts +132 -0
  80. package/src/types/stats.ts +195 -0
  81. package/src/types/stripe.ts +45 -0
  82. package/src/types/utils.ts +100 -0
  83. package/src/zod.ts +1 -0
@@ -0,0 +1,164 @@
1
+ import { Jam, JamRecording, PublicPost, PublicProfile } from '../types';
2
+ import { normalizeRecurrenceId } from './eventRecurrence';
3
+
4
+ export const jamRoomName = (postId: string, _recurrenceId?: string) => postId;
5
+
6
+ const UUID_PREFIX =
7
+ /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_.*)?$/i;
8
+
9
+ export const postIdFromJamRoomName = (roomName: string): string => {
10
+ const match = roomName.match(UUID_PREFIX);
11
+ return match?.[1] ?? roomName;
12
+ };
13
+
14
+ /** Recurring jams use one LiveKit room per event; leftover occurrence rooms still collapse. */
15
+ export const uniquePostsById = <T extends { id: string }>(
16
+ posts: (T | undefined)[],
17
+ ): T[] => {
18
+ const seen = new Set<string>();
19
+ const unique: T[] = [];
20
+ for (const post of posts) {
21
+ if (!post || seen.has(post.id)) continue;
22
+ seen.add(post.id);
23
+ unique.push(post);
24
+ }
25
+ return unique;
26
+ };
27
+
28
+ export const getJamUrl = (
29
+ id: string,
30
+ origin: string | undefined,
31
+ occurrence?: string,
32
+ ) => {
33
+ if (!id) {
34
+ return '';
35
+ }
36
+ const query = occurrence
37
+ ? `?occurrence=${encodeURIComponent(normalizeRecurrenceId(occurrence))}`
38
+ : '';
39
+ if (!origin) return `/events/${id}/jam${query}`;
40
+ return `${origin}/events/${id}/jam${query}`;
41
+ };
42
+
43
+ export const jamFromEvent = (event: PublicPost): Jam | undefined => {
44
+ if (event.data?.type === 'event' && event.data?.jam) {
45
+ return event.data.jam;
46
+ }
47
+ return undefined;
48
+ };
49
+
50
+ export const canModerateJam = (
51
+ profile: Pick<PublicProfile, 'id'> | undefined,
52
+ post: PublicPost,
53
+ ) => !!(profile && jamFromEvent(post)?.moderators?.includes(profile.id));
54
+
55
+ /** Host or jam moderator — same gate as the event Attendees tab. */
56
+ export const canViewJamAttendees = (
57
+ profile: Pick<PublicProfile, 'id'> | undefined,
58
+ post: PublicPost,
59
+ ) =>
60
+ !!(
61
+ profile &&
62
+ (post.profile.id === profile.id || canModerateJam(profile, post))
63
+ );
64
+
65
+ export const canAccessJamRecordings = (
66
+ profile: Pick<PublicProfile, 'id'> | undefined,
67
+ post: PublicPost,
68
+ ) => {
69
+ if (!profile) {
70
+ return false;
71
+ }
72
+ if (post.profile.id === profile.id) {
73
+ return true;
74
+ }
75
+ if (post.data?.type !== 'event') {
76
+ return false;
77
+ }
78
+ const event = post.data;
79
+ if (event.moderators?.includes(profile.id)) {
80
+ return true;
81
+ }
82
+ return !!event.jam?.moderators?.includes(profile.id);
83
+ };
84
+
85
+ export const jamRecordingAcceptsUpload = (status: string | undefined) =>
86
+ status === 'requested' || status === 'active' || status === 'finalizing';
87
+
88
+ export const isRtmpJamRecording = (recording: { kind?: string | null }) =>
89
+ recording.kind === 'rtmp';
90
+
91
+ export const isFileJamRecording = (recording: { kind?: string | null }) =>
92
+ !isRtmpJamRecording(recording);
93
+
94
+ export const pickActiveFileRecording = <T extends { kind?: string | null }>(
95
+ recordings: T[],
96
+ ) => recordings.find(isFileJamRecording);
97
+
98
+ export const pickActiveRtmpStream = <T extends { kind?: string | null }>(
99
+ recordings: T[],
100
+ ) => recordings.find(isRtmpJamRecording);
101
+
102
+ export const assembleRtmpUrl = (
103
+ url: string,
104
+ streamKey: string,
105
+ ): string | undefined => {
106
+ const base = url.trim().replace(/\/+$/, '');
107
+ const key = streamKey.trim().replace(/^\/+/, '');
108
+ if (!base || !key) {
109
+ return undefined;
110
+ }
111
+ if (!/^rtmps?:\/\//i.test(base)) {
112
+ return undefined;
113
+ }
114
+ return `${base}/${key}`;
115
+ };
116
+
117
+ export const rtmpDestinationHost = (rtmpUrl: string): string | undefined => {
118
+ try {
119
+ return new URL(rtmpUrl).hostname || undefined;
120
+ } catch {
121
+ return undefined;
122
+ }
123
+ };
124
+
125
+ export const toRtmpStreamResponse = (recording: JamRecording) => ({
126
+ id: recording.id,
127
+ status: recording.status,
128
+ destinationHost: recording.destinationHost,
129
+ egressId: recording.egressId,
130
+ });
131
+
132
+ /** Epoch ms from participant metadata when their hand is up. */
133
+ const raisedHandTimestamp = (metadata?: string): number | undefined => {
134
+ if (!metadata) return undefined;
135
+ try {
136
+ const handRaised = (JSON.parse(metadata) as { handRaised?: unknown })
137
+ .handRaised;
138
+ if (typeof handRaised !== 'string' || handRaised.length === 0) {
139
+ return undefined;
140
+ }
141
+ const timestamp = Date.parse(handRaised);
142
+ return Number.isNaN(timestamp) ? undefined : timestamp;
143
+ } catch {
144
+ return undefined;
145
+ }
146
+ };
147
+
148
+ /**
149
+ * Raised hands first, most recent raise first, so the person who just raised
150
+ * moves to the top of the people list and the top-left of the video grid.
151
+ * Everyone else keeps their relative order.
152
+ */
153
+ export const sortByRaisedHand = <T>(
154
+ items: readonly T[],
155
+ metadataOf: (item: T) => string | undefined,
156
+ ): T[] =>
157
+ [...items].sort((a, b) => {
158
+ const aRaised = raisedHandTimestamp(metadataOf(a));
159
+ const bRaised = raisedHandTimestamp(metadataOf(b));
160
+ if (aRaised === undefined && bRaised === undefined) return 0;
161
+ if (aRaised === undefined) return 1;
162
+ if (bRaised === undefined) return -1;
163
+ return bRaised - aRaised;
164
+ });
@@ -0,0 +1,14 @@
1
+ import type { CommunityConfig } from '../types';
2
+
3
+ /** Copy light-mode fields onto theme root for pre-0.1.45 clients. */
4
+ export const withLegacyThemeRoot = (
5
+ theme: CommunityConfig['theme'],
6
+ ): CommunityConfig['theme'] => ({
7
+ primaryHex: theme.light.primaryHex,
8
+ logoSmall: theme.light.logoSmall,
9
+ defaultProfileAvatar: theme.light.defaultProfileAvatar,
10
+ defaultGroupAvatar: theme.light.defaultGroupAvatar,
11
+ backgroundAuth: theme.light.backgroundAuth,
12
+ background: theme.light.background,
13
+ ...theme,
14
+ });
@@ -0,0 +1,290 @@
1
+ import { mentionHandleRegexBase } from '../types';
2
+
3
+ export interface MarkdownRenderProps {
4
+ source?: string;
5
+ mentions?: MentionProfileRef[];
6
+ linkPreviewMode?: 'prepend' | 'append' | 'inline' | 'none';
7
+ /** When true, all links open in a new tab (web) / system browser (RN). */
8
+ newTab?: boolean | ((link: string) => boolean);
9
+ }
10
+
11
+ const escapeRegExp = (value: string) =>
12
+ value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
13
+
14
+ export type MentionProfileRef = {
15
+ profile: { handle?: string | null; displayName?: string | null };
16
+ };
17
+
18
+ const mentionPrefix = '(^|[\\s(>])';
19
+ const mentionSuffix = '(?=\\s|$|[.,!?;:])';
20
+
21
+ /**
22
+ * Turn `@handle` / known `@displayName` into markdown profile links.
23
+ * Display names are matched exactly (longest first) so apostrophes and other
24
+ * non-letter characters still count when that profile is in `mentions`.
25
+ * Bare `@handle` tokens use the allowed handle charset (letters, digits, `_`, `-`).
26
+ */
27
+ export const linkProfileMentions = (
28
+ source: string,
29
+ mentions: MentionProfileRef[] = [],
30
+ ): string => {
31
+ const aliases = mentions.flatMap(({ profile }) => {
32
+ const handle = profile.handle?.trim();
33
+ if (!handle) return [];
34
+ const names = new Set<string>([handle]);
35
+ const displayName = profile.displayName?.trim();
36
+ if (displayName) names.add(displayName);
37
+ return [...names].map((name) => ({ name, handle }));
38
+ });
39
+
40
+ aliases.sort((a, b) => b.name.length - a.name.length);
41
+
42
+ let text = source;
43
+ for (const { name, handle } of aliases) {
44
+ const pattern = new RegExp(
45
+ `${mentionPrefix}@(${escapeRegExp(name)})${mentionSuffix}`,
46
+ 'gi',
47
+ );
48
+ text = text.replace(
49
+ pattern,
50
+ (_full, prefix: string, mentioned: string) =>
51
+ `${prefix}[@${mentioned}](/@${handle})`,
52
+ );
53
+ }
54
+
55
+ return text.replace(
56
+ new RegExp(mentionHandleRegexBase, 'g'),
57
+ (_full, prefix: string, handle: string) =>
58
+ `${prefix}[@${handle}](/@${handle})`,
59
+ );
60
+ };
61
+
62
+ /**
63
+ * Pre-process markdown source: convert `@handle` mentions into markdown
64
+ * profile links. Hashtag conversion is handled per-platform (web regex vs.
65
+ * markdown-it plugin) because the resulting URL schemes differ.
66
+ * Shared by web and RN renderers so both start from the same text.
67
+ */
68
+ export const preprocessMarkdownSource = linkProfileMentions;
69
+
70
+ export const matchMentionHandles = (text?: string | null): string[] => {
71
+ if (!text) return [];
72
+ const handles = new Set<string>();
73
+ for (const match of text.matchAll(new RegExp(mentionHandleRegexBase, 'g'))) {
74
+ const handle = match[2];
75
+ if (handle) handles.add(handle);
76
+ }
77
+ return [...handles];
78
+ };
79
+
80
+ /** Readable text for a shortened preview. Drops markdown marks, keeps words. */
81
+ export const markdownPlainText = (markdown?: string | null): string => {
82
+ if (!markdown) return '';
83
+ return markdown
84
+ .replace(/```[\s\S]*?```/g, ' ')
85
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
86
+ .replace(/[#>*_~`]+/g, '')
87
+ .replace(/\s+/g, ' ')
88
+ .trim();
89
+ };
90
+
91
+ export const firstNWords = (markdown: string | undefined, n: number) => {
92
+ if (!markdown) return '';
93
+ // Regular expression to match words and markdown links.
94
+ const regex = /\[.*?\]\(.*?\)|(\w+)/g;
95
+
96
+ let wordCount = 0;
97
+ const firstTwelveWords = [];
98
+ let match;
99
+
100
+ while ((match = regex.exec(markdown)) !== null) {
101
+ // Check if the match is a link or a regular word.
102
+ if (match[1]) {
103
+ // It's a regular word
104
+ firstTwelveWords.push(match[1]);
105
+ wordCount++;
106
+ } else {
107
+ // It's a markdown link - treat it as one word
108
+ firstTwelveWords.push(match[0]); // Add the entire link string
109
+ wordCount++;
110
+ }
111
+
112
+ if (wordCount >= n) {
113
+ break;
114
+ }
115
+ }
116
+
117
+ return firstTwelveWords.join(' ');
118
+ };
119
+
120
+ /** Average adult reading speed (words per minute). */
121
+ const DEFAULT_WORDS_PER_MINUTE = 210;
122
+
123
+ /**
124
+ * Estimate reading time for a markdown article. Strips markdown syntax
125
+ * before counting words, then divides by the words-per-minute rate.
126
+ * Always returns at least 1 for non-empty content.
127
+ */
128
+ export const minutesToRead = (
129
+ markdown: string | undefined,
130
+ wordsPerMinute = DEFAULT_WORDS_PER_MINUTE,
131
+ ): number => {
132
+ if (!markdown) return 0;
133
+ const plainText = markdownPlainText(markdown);
134
+ const wordCount = plainText.split(/\s+/).filter(Boolean).length;
135
+ return wordCount === 0
136
+ ? 0
137
+ : Math.max(1, Math.ceil(wordCount / wordsPerMinute));
138
+ };
139
+
140
+ /* ------------------------------------------------------------------ */
141
+ /* Shared link utilities */
142
+ /* ------------------------------------------------------------------ */
143
+
144
+ /**
145
+ * True when `href` points to a different origin than `origin`.
146
+ * Same logic as the web `linkTargets.isExternalLink`.
147
+ */
148
+ export const isExternalLink = (href: string, origin?: string): boolean => {
149
+ if (!href || /^(mailto:|tel:|#)/.test(href)) {
150
+ return false;
151
+ }
152
+ if (href.startsWith('/') && !href.startsWith('//')) {
153
+ return false;
154
+ }
155
+ if (!origin) {
156
+ return !href.startsWith('/');
157
+ }
158
+ try {
159
+ return new URL(href, origin).origin !== origin;
160
+ } catch {
161
+ return !href.startsWith('/');
162
+ }
163
+ };
164
+
165
+ /** Convert a same-origin path or URL to a `goto:` deep-link for RN navigation. */
166
+ export const toGotoUrl = (url: string, origin: string): string => {
167
+ if (url.includes('goto:/')) {
168
+ return url;
169
+ }
170
+ if (url.startsWith('/') && !url.startsWith('//')) {
171
+ return `goto:${url}`;
172
+ }
173
+ try {
174
+ const urlObj = new URL(url);
175
+ if (urlObj.origin === origin) {
176
+ return `goto:${urlObj.pathname}${urlObj.search}${urlObj.hash}`;
177
+ }
178
+ } catch {
179
+ // fall through
180
+ }
181
+ return url;
182
+ };
183
+
184
+ /* ------------------------------------------------------------------ */
185
+ /* HTML sanitization helpers (shared allowlist + iframe safety) */
186
+ /* ------------------------------------------------------------------ */
187
+
188
+ /**
189
+ * Tags, attrs and forbits shared by both the web (DOMPurify config) and
190
+ * RN (custom HTML token renderers) so both platforms apply the same policy.
191
+ */
192
+ export const MARKDOWN_HTML_ALLOWED_TAGS = [
193
+ 'b',
194
+ 'i',
195
+ 'em',
196
+ 'strong',
197
+ 'a',
198
+ 'p',
199
+ 'br',
200
+ 'ul',
201
+ 'ol',
202
+ 'li',
203
+ 'blockquote',
204
+ 'code',
205
+ 'pre',
206
+ 'h1',
207
+ 'h2',
208
+ 'h3',
209
+ 'h4',
210
+ 'h5',
211
+ 'h6',
212
+ 'hr',
213
+ 'img',
214
+ 'iframe',
215
+ 'video',
216
+ 'source',
217
+ 'picture',
218
+ 'figcaption',
219
+ ] as const;
220
+
221
+ export const MARKDOWN_HTML_ALLOWED_ATTRS = [
222
+ 'href',
223
+ 'src',
224
+ 'title',
225
+ 'alt',
226
+ 'target',
227
+ 'rel',
228
+ 'width',
229
+ 'height',
230
+ 'loading',
231
+ 'sandbox',
232
+ 'frameborder',
233
+ 'allowfullscreen',
234
+ 'referrerpolicy',
235
+ 'style',
236
+ ] as const;
237
+
238
+ export const MARKDOWN_HTML_FORBIDDEN_TAGS = [
239
+ 'script',
240
+ 'style',
241
+ 'form',
242
+ 'object',
243
+ 'embed',
244
+ ] as const;
245
+
246
+ export const MARKDOWN_HTML_FORBIDDEN_ATTRS = [
247
+ 'onload',
248
+ 'onerror',
249
+ 'onclick',
250
+ 'onmouseover',
251
+ ] as const;
252
+
253
+ /** Simple `<iframe>` tag detector for extracting embed URLs from raw HTML. */
254
+ const IFRAME_SRC_RE =
255
+ /<iframe\b[^>]*?\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)')[^>]*>/gi;
256
+
257
+ /** Extract all iframe `src` URLs found in an HTML string. */
258
+ export const extractIframeSrcs = (html: string): string[] => {
259
+ const srcs: string[] = [];
260
+ let match: RegExpExecArray | null;
261
+ while ((match = IFRAME_SRC_RE.exec(html)) !== null) {
262
+ srcs.push(match[1] ?? match[2] ?? '');
263
+ }
264
+ return srcs;
265
+ };
266
+
267
+ /**
268
+ * Inject safety attributes onto `<iframe>` tags so they can't break out of
269
+ * their container or execute script navigation. Runs after sanitization
270
+ * (so attackers can't smuggle attributes through), before DOM injection.
271
+ */
272
+ export const injectIframeSafetyAttrs = (html: string): string => {
273
+ return html.replace(/<iframe([^>]*?)>/gi, (match, attrs: string) => {
274
+ let safeAttrs = attrs;
275
+ if (!/loading\s*=/.test(safeAttrs)) {
276
+ safeAttrs += ' loading="lazy"';
277
+ }
278
+ if (!/sandbox\s*=/.test(safeAttrs)) {
279
+ safeAttrs +=
280
+ ' sandbox="allow-scripts allow-same-origin allow-popups allow-presentation"';
281
+ }
282
+ if (!/referrerpolicy\s*=/.test(safeAttrs)) {
283
+ safeAttrs += ' referrerpolicy="no-referrer"';
284
+ }
285
+ if (!/style\s*=/.test(safeAttrs)) {
286
+ safeAttrs += ' style="max-width:100%;width:100%;border:0;display:block;"';
287
+ }
288
+ return `<iframe${safeAttrs}>`;
289
+ });
290
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Maximum width (px) we store header/banner images at.
3
+ *
4
+ * Intentionally larger than the web center column (~669px) to leave headroom
5
+ * for other clients and future layout changes. Header uploads are cropped to
6
+ * their aspect ratio and then scaled down to this width if necessary (never
7
+ * upscaled), which keeps banners sharp without bloating storage.
8
+ */
9
+ export const HEADER_IMAGE_MAX_WIDTH = 800;
10
+
11
+ /** Aspect ratio used for event/article header banners. */
12
+ export const EVENT_HEADER_ASPECT_RATIO = '16:9';
13
+
14
+ /**
15
+ * Aspect ratio for profile/group cover banners. Uploads are cropped to this
16
+ * ratio; display containers use the same ratio. Banners that arrive with a
17
+ * different ratio (federation or older uploads) are shown with `object-cover`
18
+ * so they fill the 3:1 banner (center-cropped) rather than being letterboxed
19
+ * with grey gaps.
20
+ */
21
+ export const PROFILE_GROUP_HEADER_ASPECT_RATIO = '3:1';