@openpeepshq/common 0.1.46 → 0.2.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 (82) 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.js +2 -3
  12. package/dist/lib/postHelpers.js +70 -97
  13. package/dist/lib/profileHelpers.js +17 -24
  14. package/dist/lib/pushHelpers.js +3 -4
  15. package/dist/lib/scopeHelpers.js +6 -9
  16. package/dist/lib/ssoLoginUrl.js +4 -6
  17. package/dist/lib/ssoProviders.js +35 -39
  18. package/dist/lib/tokenHelpers.js +5 -5
  19. package/dist/lib/utils.js +6 -7
  20. package/dist/types/admin-db.js +1 -1
  21. package/dist/types/api.d.ts +1 -0
  22. package/dist/types/api.js +1 -1
  23. package/dist/types/config.d.ts +3 -0
  24. package/dist/types/config.js +3 -0
  25. package/dist/types/models.js +1 -1
  26. package/dist/types/plugins.js +2 -2
  27. package/dist/zod.d.ts +1 -0
  28. package/dist/zod.js +1 -0
  29. package/package.json +36 -6
  30. package/src/index.ts +4 -0
  31. package/src/lib/adminSections.ts +84 -0
  32. package/src/lib/attachmentHelpers.ts +14 -0
  33. package/src/lib/capabilitiesHelpers.ts +532 -0
  34. package/src/lib/colors.ts +20 -0
  35. package/src/lib/csvHelpers.ts +31 -0
  36. package/src/lib/eventIcs.ts +265 -0
  37. package/src/lib/eventRecurrence.ts +495 -0
  38. package/src/lib/eventTime.ts +206 -0
  39. package/src/lib/federationHosts.ts +22 -0
  40. package/src/lib/feedCursor.ts +27 -0
  41. package/src/lib/feedFormat.ts +24 -0
  42. package/src/lib/groupHelpers.ts +421 -0
  43. package/src/lib/groupTemplateHelpers.ts +83 -0
  44. package/src/lib/index.ts +29 -0
  45. package/src/lib/jamHelpers.ts +164 -0
  46. package/src/lib/legacyThemeRoot.ts +14 -0
  47. package/src/lib/markdownHelpers.ts +122 -0
  48. package/src/lib/mediaDimensions.ts +21 -0
  49. package/src/lib/postHelpers.ts +783 -0
  50. package/src/lib/profileHelpers.ts +220 -0
  51. package/src/lib/pushHelpers.ts +34 -0
  52. package/src/lib/reactions.ts +52 -0
  53. package/src/lib/reportHelpers.ts +7 -0
  54. package/src/lib/scopeHelpers.ts +176 -0
  55. package/src/lib/ssoLoginUrl.ts +93 -0
  56. package/src/lib/ssoProviders.ts +472 -0
  57. package/src/lib/text.ts +26 -0
  58. package/src/lib/timeZone.ts +52 -0
  59. package/src/lib/tokenHelpers.ts +119 -0
  60. package/src/lib/utils.ts +322 -0
  61. package/src/types/admin-db.ts +74 -0
  62. package/src/types/admin-email.ts +55 -0
  63. package/src/types/admin-jobs.ts +17 -0
  64. package/src/types/admin-performance.ts +20 -0
  65. package/src/types/analytics.ts +318 -0
  66. package/src/types/api.ts +871 -0
  67. package/src/types/apple-app-site-association.ts +54 -0
  68. package/src/types/auth.ts +22 -0
  69. package/src/types/capabilities.ts +280 -0
  70. package/src/types/config.ts +546 -0
  71. package/src/types/db.ts +138 -0
  72. package/src/types/export.ts +10 -0
  73. package/src/types/index.ts +20 -0
  74. package/src/types/internal.ts +338 -0
  75. package/src/types/models.ts +939 -0
  76. package/src/types/notifications.ts +92 -0
  77. package/src/types/plugins.ts +150 -0
  78. package/src/types/roleDefaults.ts +132 -0
  79. package/src/types/stats.ts +195 -0
  80. package/src/types/stripe.ts +45 -0
  81. package/src/types/utils.ts +100 -0
  82. package/src/zod.ts +1 -0
@@ -0,0 +1,322 @@
1
+ import {
2
+ AudienceSetting,
3
+ CommunityConfig,
4
+ GroupData,
5
+ GroupWithMeta,
6
+ ProfileSettings,
7
+ PublicProfile,
8
+ } from '../types';
9
+ export const pick = <T, K extends keyof T>(
10
+ obj: T,
11
+ ...keys: K[]
12
+ ): Pick<T, K> => {
13
+ const ret = {} as Pick<T, K>;
14
+ keys.forEach((key) => {
15
+ ret[key] = obj[key];
16
+ });
17
+ return ret;
18
+ };
19
+
20
+ export const transformKeys = (
21
+ object: Record<string, unknown>,
22
+ transform: (name: string) => string,
23
+ ) =>
24
+ Object.fromEntries(
25
+ [...Object.entries(object)].map((entry) => [transform(entry[0]), entry[1]]),
26
+ );
27
+
28
+ export const transformValues = <T, V>(
29
+ object: Record<string | number | symbol, T>,
30
+ transform: (value: T) => V,
31
+ ): Record<string | number | symbol, V> =>
32
+ Object.fromEntries(
33
+ [...Object.entries(object)].map((entry) => [entry[0], transform(entry[1])]),
34
+ );
35
+
36
+ const toPaddedBase64 = (value: string) => {
37
+ const normalized = value
38
+ .replace(/-/g, '+')
39
+ .replace(/_/g, '/')
40
+ .replace(/\s+/g, '');
41
+ return normalized.padEnd(
42
+ normalized.length + ((4 - (normalized.length % 4)) % 4),
43
+ '=',
44
+ );
45
+ };
46
+
47
+ export const decodeBase64ToUint8Array = (value: string): Uint8Array =>
48
+ Uint8Array.from(Buffer.from(toPaddedBase64(value), 'base64'));
49
+
50
+ export const decodeBase64UrlToUint8Array = (value: string): Uint8Array =>
51
+ decodeBase64ToUint8Array(value);
52
+
53
+ export const lowerCaseFirst = (input: string) => {
54
+ return input.charAt(0).toLowerCase() + input.substring(1);
55
+ };
56
+
57
+ export const asyncFilter = async <T>(
58
+ arr: T[],
59
+ predicate: (e: T) => Promise<boolean>,
60
+ ) =>
61
+ Promise.all(arr.map(predicate)).then((results) =>
62
+ arr.filter((_v, index) => results[index]),
63
+ );
64
+
65
+ export const passThroughUndefined =
66
+ <Input, Output>(func: (input: Input) => Output) =>
67
+ (input: Input | undefined) =>
68
+ input && func(input);
69
+
70
+ export const countBy = <T, V extends string | number | symbol>(
71
+ arr: T[],
72
+ fn: (val: T) => V,
73
+ ): Record<V, number> =>
74
+ arr.map(fn).reduce(
75
+ (acc: Record<V, number>, val) => {
76
+ acc[val] = (acc[val] || 0) + 1;
77
+ return acc;
78
+ },
79
+ {} as Record<V, number>,
80
+ );
81
+
82
+ export const groupBy = <T, V extends string | number | symbol>(
83
+ arr: T[],
84
+ fn: (val: T) => V,
85
+ ): Record<V, T[]> =>
86
+ arr.reduce(
87
+ (acc: Record<V, T[]>, val) => {
88
+ acc[fn(val)] = [...(acc[fn(val)] || []), val];
89
+ return acc;
90
+ },
91
+ {} as Record<V, T[]>,
92
+ );
93
+
94
+ export const dateSorter =
95
+ <T extends { createdAt: string }>(): ((v0: T, v1: T) => number) =>
96
+ (v0: T, v1: T) =>
97
+ Date.parse(v0.createdAt) - Date.parse(v1.createdAt);
98
+
99
+ export const getUniqueBy = <T, V = string>(
100
+ arr: T[],
101
+ predicate: (o: T) => V,
102
+ ) => {
103
+ const set = new Set<V>();
104
+ return arr.filter((o) => !set.has(predicate(o)) && set.add(predicate(o)));
105
+ };
106
+
107
+ export const interpolate = (
108
+ text: string | undefined,
109
+ params: Record<string, string> = {},
110
+ ) => {
111
+ try {
112
+ if (!text) return text;
113
+
114
+ const names = Object.keys(params);
115
+ const vals = Object.values(params);
116
+ return new Function(...names, `return \`${text}\`;`)(...vals);
117
+ } catch {
118
+ throw new Error(
119
+ `Failed to interpolate "${text}" with ${JSON.stringify(params)}, error`,
120
+ );
121
+ }
122
+ };
123
+
124
+ export const sleep = async (seconds: number) => {
125
+ await new Promise((resolve) => {
126
+ setTimeout(resolve, seconds * 1000);
127
+ });
128
+ };
129
+
130
+ export const deepSet = <T>(
131
+ obj: T,
132
+ path: string | (string | number)[],
133
+ val: unknown,
134
+ ): T => {
135
+ const keys = Array.isArray(path)
136
+ ? path
137
+ : path
138
+ .replace(/(\w)\[/g, '$1.[')
139
+ .split('.')
140
+ .map((k) =>
141
+ k.includes('[') ? parseInt(k.substring(1, k.length - 1)) : k,
142
+ );
143
+
144
+ let subObject: unknown = obj;
145
+ for (let i = 0; i < keys.length; i++) {
146
+ const currentKey = keys[i];
147
+ const nextKey = keys[i + 1];
148
+
149
+ if (typeof nextKey !== 'undefined') {
150
+ // @ts-expect-error deepset is not really typeable
151
+ subObject[currentKey] = subObject[currentKey]
152
+ ? // @ts-expect-error deepset is not really typeable
153
+ subObject[currentKey]
154
+ : // @ts-expect-error deepset is not really typeable
155
+ isNaN(nextKey)
156
+ ? {}
157
+ : [];
158
+ } else {
159
+ // @ts-expect-error deepset is not really typeable
160
+ subObject[currentKey] = val;
161
+ }
162
+
163
+ // @ts-expect-error deepset is not really typeable
164
+ subObject = subObject[currentKey];
165
+ }
166
+ return obj;
167
+ };
168
+
169
+ export const deepGet = (obj: unknown, path: (string | number)[]) =>
170
+ // @ts-expect-error deepget is not typeable
171
+ path.reduce((o, i) => o[i], obj);
172
+
173
+ /**
174
+ * Checks if a value is valid => not (null, undefined, empty, etc.)
175
+ * Special case: treats 0 as a valid value unlike standard JS truthiness
176
+ */
177
+ export const hasValue = (v: unknown): boolean => v === 0 || !!v;
178
+
179
+ export const kebabToCamelCase = (str: string) => {
180
+ return str.replace(/-([a-z])/g, function (_match, letter) {
181
+ return letter.toUpperCase();
182
+ });
183
+ };
184
+
185
+ export const formatTimeStamp = (
186
+ timestamp: number | null,
187
+ startDate?: number | null,
188
+ ) => {
189
+ if (!timestamp) {
190
+ if (startDate) {
191
+ const startDateObj = new Date(startDate * 1000);
192
+ const nextMonth = new Date(startDateObj);
193
+ nextMonth.setMonth(nextMonth.getMonth() + 1);
194
+
195
+ if (nextMonth.getDate() !== startDateObj.getDate()) {
196
+ nextMonth.setDate(0);
197
+ }
198
+
199
+ return nextMonth.toLocaleDateString();
200
+ }
201
+ return 'N/A';
202
+ }
203
+ return new Date(timestamp * 1000).toLocaleDateString();
204
+ };
205
+
206
+ const getMode = (config: CommunityConfig, profileSettings: ProfileSettings | undefined, systemTheme: 'dark' | 'light'): 'dark' | 'light' => {
207
+ if (profileSettings) {
208
+ if (profileSettings.theme === "system") {
209
+ return systemTheme;
210
+ } else if (profileSettings?.theme === "dark") {
211
+ return "dark";
212
+ } else if (profileSettings?.theme === "light") {
213
+ return "light";
214
+ }
215
+ }
216
+ return config.theme.base === 'OpenpeepsDark' ? 'dark' : 'light';
217
+ }
218
+
219
+ export const getTheme = (
220
+ config: CommunityConfig,
221
+ profileSettings?: ProfileSettings,
222
+ systemTheme: 'dark' | 'light' = getSystemTheme()
223
+ ) =>
224
+ getMode(config, profileSettings, systemTheme) === 'dark' ?
225
+ { ...config.theme.dark, dark: true } :
226
+ { ...config.theme.light, dark: false };
227
+
228
+ export const getSystemTheme = () => {
229
+ if (typeof window !== "undefined" && window.matchMedia) {
230
+ const systemIsDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
231
+ return systemIsDark ? "dark" : "light"
232
+ }
233
+ return 'light';
234
+ }
235
+
236
+ export const getProfileAvatar = (
237
+ profile: PublicProfile | undefined | null,
238
+ config: CommunityConfig,
239
+ ) => {
240
+ return profile?.avatar
241
+ ? profile.avatar
242
+ : (getTheme(config).defaultProfileAvatar as string);
243
+ };
244
+
245
+ export const getGroupAvatar = (
246
+ group: GroupWithMeta | GroupData | undefined | null,
247
+ config: CommunityConfig,
248
+ ) => {
249
+ return group?.avatar
250
+ ? group.avatar
251
+ : (getTheme(config).defaultGroupAvatar as string);
252
+ };
253
+
254
+ export const extractDateFromUUIDv7 = (uuidV7: string): string => {
255
+ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
256
+ if (!UUID_REGEX.test(uuidV7)) {
257
+ throw new Error('Invalid UUID format');
258
+ }
259
+
260
+ const versionChar = uuidV7[14];
261
+ if ((parseInt(versionChar, 16) & 0xf) !== 0x7) {
262
+ throw new Error('Not a UUIDv7 - version bits are not 7');
263
+ }
264
+
265
+ const hex = uuidV7.replace(/-/g, '');
266
+
267
+ const timestampHex = hex.slice(0, 12);
268
+ const timestampMs = parseInt(timestampHex, 16);
269
+
270
+ const date = new Date(timestampMs);
271
+
272
+ const pad = (num: number, size: number): string => {
273
+ let s = String(num);
274
+ while (s.length < size) { s = '0' + s; }
275
+ return s;
276
+ };
277
+
278
+ return (
279
+ date.getUTCFullYear().toString() +
280
+ pad(date.getUTCMonth() + 1, 2) + // months are zero‑based
281
+ pad(date.getUTCDate(), 2) +
282
+ pad(date.getUTCHours(), 2) +
283
+ pad(date.getUTCMinutes(), 2)
284
+ );
285
+ };
286
+
287
+ export const formatSize = (bytes: number) => {
288
+ if (bytes < 1024) return bytes + ' B';
289
+ if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' kB';
290
+ return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
291
+ };
292
+
293
+ export const hasVisibilityChanged = (
294
+ previousAudienceSetting: AudienceSetting,
295
+ newAudienceSetting: AudienceSetting
296
+ ): boolean => {
297
+ if (previousAudienceSetting.visibility !== newAudienceSetting.visibility) {
298
+ return true;
299
+ }
300
+
301
+ if (previousAudienceSetting.groupId !== newAudienceSetting.groupId) {
302
+ return true;
303
+ }
304
+
305
+ const prevAudience = previousAudienceSetting.audience ?? [];
306
+ const newAudience = newAudienceSetting.audience ?? [];
307
+
308
+ if (prevAudience.length !== newAudience.length) {
309
+ return true;
310
+ }
311
+
312
+ const prevIds = prevAudience.map((p) => p.id).sort();
313
+ const newIds = newAudience.map((p) => p.id).sort();
314
+
315
+ for (let i = 0; i < prevIds.length; i++) {
316
+ if (prevIds[i] !== newIds[i]) {
317
+ return true;
318
+ }
319
+ }
320
+
321
+ return false;
322
+ };
@@ -0,0 +1,74 @@
1
+ import { z } from 'zod';
2
+ import { jsonSchema, type Json } from './utils';
3
+
4
+ export const explorerColumnSchema = z.object({
5
+ name: z.string(),
6
+ dataType: z.string(),
7
+ primaryKey: z.boolean(),
8
+ notNull: z.boolean(),
9
+ });
10
+
11
+ export type ExplorerColumn = z.infer<typeof explorerColumnSchema>;
12
+
13
+ export const explorerTableSchema = z.object({
14
+ name: z.string(),
15
+ columns: z.array(explorerColumnSchema),
16
+ });
17
+
18
+ export type ExplorerTable = z.infer<typeof explorerTableSchema>;
19
+
20
+ export const explorerTablesResponseSchema = z.object({
21
+ tables: z.array(explorerTableSchema),
22
+ });
23
+
24
+ export type ExplorerTablesResponse = z.infer<
25
+ typeof explorerTablesResponseSchema
26
+ >;
27
+
28
+ export const explorerRowsResponseSchema = z.object({
29
+ columns: z.array(z.string()),
30
+ // Use jsonSchema (not z.unknown / z.lazy) so OpenAPI generation stays safe.
31
+ rows: z.array(z.record(z.string(), jsonSchema)),
32
+ total: z.number(),
33
+ limit: z.number(),
34
+ offset: z.number(),
35
+ });
36
+
37
+ export type ExplorerRowsResponse = z.infer<typeof explorerRowsResponseSchema>;
38
+
39
+ /** JSON-compatible values for request bodies (matches fetch-client Serializable). */
40
+ export type ExplorerJson = Json;
41
+
42
+ export const explorerUpdateRowInputSchema = z.object({
43
+ primaryKey: z.record(z.string(), jsonSchema),
44
+ patch: z.record(z.string(), jsonSchema),
45
+ });
46
+
47
+ export type ExplorerUpdateRowInput = z.infer<
48
+ typeof explorerUpdateRowInputSchema
49
+ >;
50
+
51
+ export const explorerUpdateRowResponseSchema = z.object({
52
+ row: z.record(z.string(), jsonSchema),
53
+ });
54
+
55
+ export type ExplorerUpdateRowResponse = z.infer<
56
+ typeof explorerUpdateRowResponseSchema
57
+ >;
58
+
59
+ export const explorerSqlInputSchema = z.object({
60
+ statement: z.string().min(1),
61
+ /** Max rows to return (capped server-side). Omit for the default cap. */
62
+ limit: z.number().int().positive().max(10_000).optional(),
63
+ });
64
+
65
+ export type ExplorerSqlInput = z.infer<typeof explorerSqlInputSchema>;
66
+
67
+ export const explorerSqlResponseSchema = z.object({
68
+ columns: z.array(z.string()),
69
+ rows: z.array(z.record(z.string(), jsonSchema)),
70
+ rowCount: z.number(),
71
+ command: z.string(),
72
+ });
73
+
74
+ export type ExplorerSqlResponse = z.infer<typeof explorerSqlResponseSchema>;
@@ -0,0 +1,55 @@
1
+ import { z } from 'zod';
2
+
3
+ const transportOverrideSchema = z.object({
4
+ host: z.string().optional(),
5
+ port: z.number().optional(),
6
+ secure: z.boolean().optional(),
7
+ auth: z
8
+ .object({
9
+ user: z.string().optional(),
10
+ pass: z.string().optional(),
11
+ })
12
+ .optional(),
13
+ });
14
+
15
+ export const adminEmailTestInputSchema = z.object({
16
+ to: z.string().email(),
17
+ email: z
18
+ .object({
19
+ defaultFrom: z.string().optional(),
20
+ transportConfig: transportOverrideSchema.optional(),
21
+ })
22
+ .optional(),
23
+ });
24
+
25
+ export type AdminEmailTestInput = z.infer<typeof adminEmailTestInputSchema>;
26
+
27
+ export const adminEmailQueueTestInputSchema = z.object({
28
+ to: z.string().email(),
29
+ });
30
+
31
+ export type AdminEmailQueueTestInput = z.infer<
32
+ typeof adminEmailQueueTestInputSchema
33
+ >;
34
+
35
+ export const adminEmailQueueStatsSchema = z.object({
36
+ counts: z.object({
37
+ waiting: z.number(),
38
+ active: z.number(),
39
+ completed: z.number(),
40
+ failed: z.number(),
41
+ delayed: z.number(),
42
+ prioritized: z.number(),
43
+ }),
44
+ recentFailures: z.array(
45
+ z.object({
46
+ queue: z.string(),
47
+ id: z.string().nullable(),
48
+ name: z.string(),
49
+ failedReason: z.string(),
50
+ finishedOn: z.number().nullable(),
51
+ }),
52
+ ),
53
+ });
54
+
55
+ export type AdminEmailQueueStats = z.infer<typeof adminEmailQueueStatsSchema>;
@@ -0,0 +1,17 @@
1
+ import { z } from 'zod';
2
+
3
+ export const adminJobDetailSchema = z.object({
4
+ queue: z.string(),
5
+ id: z.string(),
6
+ name: z.string(),
7
+ state: z.string(),
8
+ failedReason: z.string().nullable(),
9
+ finishedOn: z.number().nullable(),
10
+ processedOn: z.number().nullable(),
11
+ timestamp: z.number().nullable(),
12
+ data: z.unknown().nullable(),
13
+ logs: z.array(z.string()),
14
+ logCount: z.number(),
15
+ });
16
+
17
+ export type AdminJobDetail = z.infer<typeof adminJobDetailSchema>;
@@ -0,0 +1,20 @@
1
+ import { z } from 'zod';
2
+
3
+ export const slowRequestRecordSchema = z.object({
4
+ method: z.string(),
5
+ path: z.string(),
6
+ status: z.number(),
7
+ durationMs: z.number(),
8
+ at: z.string(),
9
+ hostname: z.string().optional(),
10
+ });
11
+
12
+ export type SlowRequestRecord = z.infer<typeof slowRequestRecordSchema>;
13
+
14
+ export const adminPerformanceStatsSchema = z.object({
15
+ slowRequestMs: z.number(),
16
+ dbTimingEnabled: z.boolean(),
17
+ slowRequests: z.array(slowRequestRecordSchema),
18
+ });
19
+
20
+ export type AdminPerformanceStats = z.infer<typeof adminPerformanceStatsSchema>;