@openpeepshq/common 0.2.0 → 0.3.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/common",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
package/src/lib/index.ts CHANGED
@@ -12,6 +12,7 @@ export * from './groupTemplateHelpers';
12
12
  export * from './colors';
13
13
  export * from './markdownHelpers';
14
14
  export * from './attachmentHelpers';
15
+ export * from './resources';
15
16
  export * from './eventIcs';
16
17
  export * from './eventTime';
17
18
  export * from './timeZone';
@@ -1,5 +1,13 @@
1
1
  import { mentionHandleRegexBase } from '../types';
2
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
+
3
11
  const escapeRegExp = (value: string) =>
4
12
  value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5
13
 
@@ -51,6 +59,14 @@ export const linkProfileMentions = (
51
59
  );
52
60
  };
53
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
+
54
70
  export const matchMentionHandles = (text?: string | null): string[] => {
55
71
  if (!text) return [];
56
72
  const handles = new Set<string>();
@@ -101,6 +117,48 @@ export const firstNWords = (markdown: string | undefined, n: number) => {
101
117
  return firstTwelveWords.join(' ');
102
118
  };
103
119
 
120
+ /**
121
+ * Truncates markdown to at most `maxBlocks` block-level regions, then to
122
+ * `maxChars` characters at a word boundary. Preserves punctuation and inline
123
+ * markdown formatting (links, bold, etc.). An ellipsis is appended only when
124
+ * the content was actually shortened.
125
+ */
126
+ export const truncateMarkdown = (
127
+ markdown: string | undefined,
128
+ maxBlocks: number,
129
+ maxChars: number,
130
+ ): string => {
131
+ if (!markdown) return '';
132
+
133
+ const blocks = markdown
134
+ .replace(/\r\n/g, '\n')
135
+ .split(/\n{2,}/)
136
+ .map((block) => block.trim())
137
+ .filter(Boolean);
138
+
139
+ if (blocks.length === 0) return '';
140
+
141
+ const hadMoreBlocks = blocks.length > maxBlocks;
142
+ const content = blocks.slice(0, maxBlocks).join('\n\n');
143
+
144
+ if (content.length <= maxChars) {
145
+ return hadMoreBlocks ? `${content}…` : content;
146
+ }
147
+
148
+ const candidate = content.slice(0, maxChars);
149
+ const lastBreak = Math.max(
150
+ candidate.lastIndexOf(' '),
151
+ candidate.lastIndexOf('\n'),
152
+ candidate.lastIndexOf('\t'),
153
+ );
154
+
155
+ if (lastBreak > 0) {
156
+ return `${content.slice(0, lastBreak).trimEnd()}…`;
157
+ }
158
+
159
+ return `${candidate}…`;
160
+ };
161
+
104
162
  /** Average adult reading speed (words per minute). */
105
163
  const DEFAULT_WORDS_PER_MINUTE = 210;
106
164
 
@@ -120,3 +178,155 @@ export const minutesToRead = (
120
178
  ? 0
121
179
  : Math.max(1, Math.ceil(wordCount / wordsPerMinute));
122
180
  };
181
+
182
+ /* ------------------------------------------------------------------ */
183
+ /* Shared link utilities */
184
+ /* ------------------------------------------------------------------ */
185
+
186
+ /**
187
+ * True when `href` points to a different origin than `origin`.
188
+ * Same logic as the web `linkTargets.isExternalLink`.
189
+ */
190
+ export const isExternalLink = (href: string, origin?: string): boolean => {
191
+ if (!href || /^(mailto:|tel:|#)/.test(href)) {
192
+ return false;
193
+ }
194
+ if (href.startsWith('/') && !href.startsWith('//')) {
195
+ return false;
196
+ }
197
+ if (!origin) {
198
+ return !href.startsWith('/');
199
+ }
200
+ try {
201
+ return new URL(href, origin).origin !== origin;
202
+ } catch {
203
+ return !href.startsWith('/');
204
+ }
205
+ };
206
+
207
+ /** Convert a same-origin path or URL to a `goto:` deep-link for RN navigation. */
208
+ export const toGotoUrl = (url: string, origin: string): string => {
209
+ if (url.includes('goto:/')) {
210
+ return url;
211
+ }
212
+ if (url.startsWith('/') && !url.startsWith('//')) {
213
+ return `goto:${url}`;
214
+ }
215
+ try {
216
+ const urlObj = new URL(url);
217
+ if (urlObj.origin === origin) {
218
+ return `goto:${urlObj.pathname}${urlObj.search}${urlObj.hash}`;
219
+ }
220
+ } catch {
221
+ // fall through
222
+ }
223
+ return url;
224
+ };
225
+
226
+ /* ------------------------------------------------------------------ */
227
+ /* HTML sanitization helpers (shared allowlist + iframe safety) */
228
+ /* ------------------------------------------------------------------ */
229
+
230
+ /**
231
+ * Tags, attrs and forbits shared by both the web (DOMPurify config) and
232
+ * RN (custom HTML token renderers) so both platforms apply the same policy.
233
+ */
234
+ export const MARKDOWN_HTML_ALLOWED_TAGS = [
235
+ 'b',
236
+ 'i',
237
+ 'em',
238
+ 'strong',
239
+ 'a',
240
+ 'p',
241
+ 'br',
242
+ 'ul',
243
+ 'ol',
244
+ 'li',
245
+ 'blockquote',
246
+ 'code',
247
+ 'pre',
248
+ 'h1',
249
+ 'h2',
250
+ 'h3',
251
+ 'h4',
252
+ 'h5',
253
+ 'h6',
254
+ 'hr',
255
+ 'img',
256
+ 'iframe',
257
+ 'video',
258
+ 'source',
259
+ 'picture',
260
+ 'figcaption',
261
+ ] as const;
262
+
263
+ export const MARKDOWN_HTML_ALLOWED_ATTRS = [
264
+ 'href',
265
+ 'src',
266
+ 'title',
267
+ 'alt',
268
+ 'target',
269
+ 'rel',
270
+ 'width',
271
+ 'height',
272
+ 'loading',
273
+ 'sandbox',
274
+ 'frameborder',
275
+ 'allowfullscreen',
276
+ 'referrerpolicy',
277
+ 'style',
278
+ ] as const;
279
+
280
+ export const MARKDOWN_HTML_FORBIDDEN_TAGS = [
281
+ 'script',
282
+ 'style',
283
+ 'form',
284
+ 'object',
285
+ 'embed',
286
+ ] as const;
287
+
288
+ export const MARKDOWN_HTML_FORBIDDEN_ATTRS = [
289
+ 'onload',
290
+ 'onerror',
291
+ 'onclick',
292
+ 'onmouseover',
293
+ ] as const;
294
+
295
+ /** Simple `<iframe>` tag detector for extracting embed URLs from raw HTML. */
296
+ const IFRAME_SRC_RE =
297
+ /<iframe\b[^>]*?\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)')[^>]*>/gi;
298
+
299
+ /** Extract all iframe `src` URLs found in an HTML string. */
300
+ export const extractIframeSrcs = (html: string): string[] => {
301
+ const srcs: string[] = [];
302
+ let match: RegExpExecArray | null;
303
+ while ((match = IFRAME_SRC_RE.exec(html)) !== null) {
304
+ srcs.push(match[1] ?? match[2] ?? '');
305
+ }
306
+ return srcs;
307
+ };
308
+
309
+ /**
310
+ * Inject safety attributes onto `<iframe>` tags so they can't break out of
311
+ * their container or execute script navigation. Runs after sanitization
312
+ * (so attackers can't smuggle attributes through), before DOM injection.
313
+ */
314
+ export const injectIframeSafetyAttrs = (html: string): string => {
315
+ return html.replace(/<iframe([^>]*?)>/gi, (match, attrs: string) => {
316
+ let safeAttrs = attrs;
317
+ if (!/loading\s*=/.test(safeAttrs)) {
318
+ safeAttrs += ' loading="lazy"';
319
+ }
320
+ if (!/sandbox\s*=/.test(safeAttrs)) {
321
+ safeAttrs +=
322
+ ' sandbox="allow-scripts allow-same-origin allow-popups allow-presentation"';
323
+ }
324
+ if (!/referrerpolicy\s*=/.test(safeAttrs)) {
325
+ safeAttrs += ' referrerpolicy="no-referrer"';
326
+ }
327
+ if (!/style\s*=/.test(safeAttrs)) {
328
+ safeAttrs += ' style="max-width:100%;width:100%;border:0;display:block;"';
329
+ }
330
+ return `<iframe${safeAttrs}>`;
331
+ });
332
+ };
@@ -0,0 +1,88 @@
1
+ import type { MediaAttachmentData, ResourceKind } from '../types/models';
2
+
3
+ export const RESOURCE_KINDS = [
4
+ 'video',
5
+ 'file',
6
+ 'gallery',
7
+ 'audio',
8
+ 'link',
9
+ ] as const satisfies readonly ResourceKind[];
10
+
11
+ export const attachmentMediaKind = (
12
+ att: Pick<MediaAttachmentData, 'type' | 'meta'>,
13
+ ): 'image' | 'video' | 'audio' | 'file' => {
14
+ const mime = att.meta?.mimetype ?? '';
15
+ const type = att.type ?? '';
16
+ if (type === 'image' || mime.startsWith('image/')) return 'image';
17
+ if (type === 'video' || mime.startsWith('video/')) return 'video';
18
+ if (type === 'audio' || mime.startsWith('audio/')) return 'audio';
19
+ return 'file';
20
+ };
21
+
22
+ export const resourceHasRequiredMedia = (resource: {
23
+ resourceKind: ResourceKind;
24
+ url?: string;
25
+ attachments?: MediaAttachmentData[];
26
+ }): boolean => {
27
+ if (resource.resourceKind === 'link') return Boolean(resource.url);
28
+ const need =
29
+ resource.resourceKind === 'gallery'
30
+ ? 'image'
31
+ : resource.resourceKind === 'video'
32
+ ? 'video'
33
+ : resource.resourceKind === 'audio'
34
+ ? 'audio'
35
+ : 'file';
36
+ return (resource.attachments ?? []).some(
37
+ (att) => attachmentMediaKind(att) === need,
38
+ );
39
+ };
40
+
41
+ export type CategoryNode = {
42
+ name: string;
43
+ path: string[];
44
+ children: CategoryNode[];
45
+ };
46
+
47
+ export const categoryTreeFromPaths = (
48
+ paths: readonly (readonly string[])[],
49
+ ): CategoryNode[] => {
50
+ const root: CategoryNode[] = [];
51
+ for (const path of paths) {
52
+ let level = root;
53
+ const acc: string[] = [];
54
+ for (const name of path) {
55
+ const segment = name.trim();
56
+ if (!segment) continue;
57
+ acc.push(segment);
58
+ let node = level.find((entry) => entry.name === segment);
59
+ if (!node) {
60
+ node = { name: segment, path: [...acc], children: [] };
61
+ level.push(node);
62
+ }
63
+ level = node.children;
64
+ }
65
+ }
66
+ return root;
67
+ };
68
+
69
+ export const pathStartsWith = (
70
+ path: readonly string[],
71
+ prefix: readonly string[],
72
+ ): boolean =>
73
+ prefix.length <= path.length &&
74
+ prefix.every((segment, index) => path[index] === segment);
75
+
76
+ export const normalizeResourceTags = (
77
+ tags: readonly string[] | undefined,
78
+ ): string[] => {
79
+ const seen = new Set<string>();
80
+ const out: string[] = [];
81
+ for (const raw of tags ?? []) {
82
+ const tag = raw.replace(/^#/, '').trim().toLowerCase();
83
+ if (!tag || seen.has(tag)) continue;
84
+ seen.add(tag);
85
+ out.push(tag);
86
+ }
87
+ return out;
88
+ };
@@ -117,6 +117,7 @@ export const analyticsPostTypeKeySchema = z.enum([
117
117
  'note',
118
118
  'poll',
119
119
  'event',
120
+ 'resource',
120
121
  ]);
121
122
  export type AnalyticsPostTypeKey = z.infer<typeof analyticsPostTypeKeySchema>;
122
123
 
@@ -136,6 +137,7 @@ export const analyticsStackedPointSchema = z.object({
136
137
  note: z.number(),
137
138
  poll: z.number(),
138
139
  event: z.number(),
140
+ resource: z.number(),
139
141
  });
140
142
  export type AnalyticsStackedPoint = z.infer<typeof analyticsStackedPointSchema>;
141
143
 
package/src/types/api.ts CHANGED
@@ -745,6 +745,9 @@ export const chronologicalInfiniteQueryParamsSchema = z.object({
745
745
  start: z.string().optional(),
746
746
  limit: z.coerce.number().optional(),
747
747
  format: z.enum(['threaded', 'linear']).optional(),
748
+ groupId: z.string().optional(),
749
+ /** Query-string flag; fetch params only allow string | number. */
750
+ ungrouped: z.literal('true').optional(),
748
751
  });
749
752
  export type ChronologicalInfiniteQueryParams =
750
753
  | z.infer<typeof chronologicalInfiniteQueryParamsSchema>
@@ -83,6 +83,7 @@ export const groupCapabilities = [
83
83
  'core-posts-create-event',
84
84
  'core-posts-create-poll',
85
85
  'core-posts-create-article',
86
+ 'core-posts-create-resource',
86
87
  ] as const;
87
88
 
88
89
  /** Caps an owner can toggle per relationship in the group editor. */
@@ -185,6 +186,10 @@ export const roleCapabilities = [
185
186
  'core-posts-create-article-public',
186
187
  'core-posts-create-article-direct',
187
188
  'core-posts-create-article-private',
189
+ 'core-posts-create-resource-local',
190
+ 'core-posts-create-resource-public',
191
+ 'core-posts-create-resource-direct',
192
+ 'core-posts-create-resource-private',
188
193
  'core-posts-read-local',
189
194
  'core-posts-announce',
190
195
  'core-posts-delete',
@@ -404,9 +404,24 @@ export const visibilityTypeSchema = z.enum(visibilityTypeValues);
404
404
 
405
405
  export type VisibilityType = z.infer<typeof visibilityTypeSchema>;
406
406
 
407
- export const postTypeSchema = z.enum(['note', 'question', 'event', 'article']);
407
+ export const postTypeSchema = z.enum([
408
+ 'note',
409
+ 'question',
410
+ 'event',
411
+ 'article',
412
+ 'resource',
413
+ ]);
408
414
  export type PostType = z.infer<typeof postTypeSchema>;
409
415
 
416
+ export const resourceKindSchema = z.enum([
417
+ 'video',
418
+ 'file',
419
+ 'gallery',
420
+ 'audio',
421
+ 'link',
422
+ ]);
423
+ export type ResourceKind = z.infer<typeof resourceKindSchema>;
424
+
410
425
  export const mediaAttachmentStatusSchema = z.enum([
411
426
  'processing',
412
427
  'ready',
@@ -508,6 +523,18 @@ export const articleSchema = noteSchema
508
523
 
509
524
  export type Article = z.infer<typeof articleSchema>;
510
525
 
526
+ export const resourcePostSchema = noteSchema
527
+ .extend({
528
+ type: z.literal('resource'),
529
+ title: z.string(),
530
+ tags: z.array(z.string().min(1)).optional(),
531
+ categoryPath: z.array(z.string().min(1)).optional(),
532
+ resourceKind: resourceKindSchema,
533
+ url: z.url().optional(),
534
+ })
535
+ .openapi('ResourcePost');
536
+ export type ResourcePost = z.infer<typeof resourcePostSchema>;
537
+
511
538
  export const eventIsoDatetimeSchema = z.iso.datetime({
512
539
  offset: true,
513
540
  precision: 3,
@@ -583,6 +610,7 @@ export const postDataUnionSchema = z.discriminatedUnion('type', [
583
610
  questionSchema,
584
611
  eventSchema,
585
612
  articleSchema,
613
+ resourcePostSchema,
586
614
  ]);
587
615
 
588
616
  export type PostDataUnion = z.infer<typeof postDataUnionSchema>;