@openpeepshq/common 0.3.0 → 0.3.2

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.
@@ -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';
package/dist/lib/index.js CHANGED
@@ -12,6 +12,7 @@ export * from './groupTemplateHelpers.js';
12
12
  export * from './colors.js';
13
13
  export * from './markdownHelpers.js';
14
14
  export * from './attachmentHelpers.js';
15
+ export * from './resources.js';
15
16
  export * from './eventIcs.js';
16
17
  export * from './eventTime.js';
17
18
  export * from './timeZone.js';
@@ -29,6 +29,13 @@ export declare const matchMentionHandles: (text?: string | null) => string[];
29
29
  /** Readable text for a shortened preview. Drops markdown marks, keeps words. */
30
30
  export declare const markdownPlainText: (markdown?: string | null) => string;
31
31
  export declare const firstNWords: (markdown: string | undefined, n: number) => string;
32
+ /**
33
+ * Truncates markdown to at most `maxBlocks` block-level regions, then to
34
+ * `maxChars` characters at a word boundary. Preserves punctuation and inline
35
+ * markdown formatting (links, bold, etc.). An ellipsis is appended only when
36
+ * the content was actually shortened.
37
+ */
38
+ export declare const truncateMarkdown: (markdown: string | undefined, maxBlocks: number, maxChars: number) => string;
32
39
  /**
33
40
  * Estimate reading time for a markdown article. Strips markdown syntax
34
41
  * before counting words, then divides by the words-per-minute rate.
@@ -43,11 +50,11 @@ export declare const isExternalLink: (href: string, origin?: string) => boolean;
43
50
  /** Convert a same-origin path or URL to a `goto:` deep-link for RN navigation. */
44
51
  export declare const toGotoUrl: (url: string, origin: string) => string;
45
52
  /**
46
- * Tags, attrs and forbits shared by both the web (DOMPurify config) and
53
+ * Tags, attrs and forits shared by both the web (DOMPurify config) and
47
54
  * RN (custom HTML token renderers) so both platforms apply the same policy.
48
55
  */
49
56
  export declare const MARKDOWN_HTML_ALLOWED_TAGS: readonly ["b", "i", "em", "strong", "a", "p", "br", "ul", "ol", "li", "blockquote", "code", "pre", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "img", "iframe", "video", "source", "picture", "figcaption"];
50
- export declare const MARKDOWN_HTML_ALLOWED_ATTRS: readonly ["href", "src", "title", "alt", "target", "rel", "width", "height", "loading", "sandbox", "frameborder", "allowfullscreen", "referrerpolicy", "style"];
57
+ export declare const MARKDOWN_HTML_ALLOWED_ATTRS: readonly ["href", "src", "title", "alt", "target", "rel", "width", "height", "loading", "sandbox", "frameborder", "allowfullscreen", "referrerpolicy", "allow", "style"];
51
58
  export declare const MARKDOWN_HTML_FORBIDDEN_TAGS: readonly ["script", "style", "form", "object", "embed"];
52
59
  export declare const MARKDOWN_HTML_FORBIDDEN_ATTRS: readonly ["onload", "onerror", "onclick", "onmouseover"];
53
60
  /** Extract all iframe `src` URLs found in an HTML string. */
@@ -56,5 +63,11 @@ export declare const extractIframeSrcs: (html: string) => string[];
56
63
  * Inject safety attributes onto `<iframe>` tags so they can't break out of
57
64
  * their container or execute script navigation. Runs after sanitization
58
65
  * (so attackers can't smuggle attributes through), before DOM injection.
66
+ *
67
+ * We grant a broad Permissions Policy (`allow`) covering autoplay, encrypted
68
+ * media, and picture-in-picture, plus `allow-popups-to-escape-sandbox` in the
69
+ * sandbox itself. Without these, embedded players (YouTube, Vimeo, etc.)
70
+ * report Error 153 (autoplay blocked) because the browser denies the
71
+ * Permissions Policy the player requests.
59
72
  */
60
73
  export declare const injectIframeSafetyAttrs: (html: string) => string;
@@ -82,6 +82,34 @@ export const firstNWords = (markdown, n) => {
82
82
  }
83
83
  return firstTwelveWords.join(' ');
84
84
  };
85
+ /**
86
+ * Truncates markdown to at most `maxBlocks` block-level regions, then to
87
+ * `maxChars` characters at a word boundary. Preserves punctuation and inline
88
+ * markdown formatting (links, bold, etc.). An ellipsis is appended only when
89
+ * the content was actually shortened.
90
+ */
91
+ export const truncateMarkdown = (markdown, maxBlocks, maxChars) => {
92
+ if (!markdown)
93
+ return '';
94
+ const blocks = markdown
95
+ .replace(/\r\n/g, '\n')
96
+ .split(/\n{2,}/)
97
+ .map((block) => block.trim())
98
+ .filter(Boolean);
99
+ if (blocks.length === 0)
100
+ return '';
101
+ const hadMoreBlocks = blocks.length > maxBlocks;
102
+ const content = blocks.slice(0, maxBlocks).join('\n\n');
103
+ if (content.length <= maxChars) {
104
+ return hadMoreBlocks ? `${content}…` : content;
105
+ }
106
+ const candidate = content.slice(0, maxChars);
107
+ const lastBreak = Math.max(candidate.lastIndexOf(' '), candidate.lastIndexOf('\n'), candidate.lastIndexOf('\t'));
108
+ if (lastBreak > 0) {
109
+ return `${content.slice(0, lastBreak).trimEnd()}…`;
110
+ }
111
+ return `${candidate}…`;
112
+ };
85
113
  /** Average adult reading speed (words per minute). */
86
114
  const DEFAULT_WORDS_PER_MINUTE = 210;
87
115
  /**
@@ -145,7 +173,7 @@ export const toGotoUrl = (url, origin) => {
145
173
  /* HTML sanitization helpers (shared allowlist + iframe safety) */
146
174
  /* ------------------------------------------------------------------ */
147
175
  /**
148
- * Tags, attrs and forbits shared by both the web (DOMPurify config) and
176
+ * Tags, attrs and forits shared by both the web (DOMPurify config) and
149
177
  * RN (custom HTML token renderers) so both platforms apply the same policy.
150
178
  */
151
179
  export const MARKDOWN_HTML_ALLOWED_TAGS = [
@@ -190,6 +218,7 @@ export const MARKDOWN_HTML_ALLOWED_ATTRS = [
190
218
  'frameborder',
191
219
  'allowfullscreen',
192
220
  'referrerpolicy',
221
+ 'allow',
193
222
  'style',
194
223
  ];
195
224
  export const MARKDOWN_HTML_FORBIDDEN_TAGS = [
@@ -220,6 +249,12 @@ export const extractIframeSrcs = (html) => {
220
249
  * Inject safety attributes onto `<iframe>` tags so they can't break out of
221
250
  * their container or execute script navigation. Runs after sanitization
222
251
  * (so attackers can't smuggle attributes through), before DOM injection.
252
+ *
253
+ * We grant a broad Permissions Policy (`allow`) covering autoplay, encrypted
254
+ * media, and picture-in-picture, plus `allow-popups-to-escape-sandbox` in the
255
+ * sandbox itself. Without these, embedded players (YouTube, Vimeo, etc.)
256
+ * report Error 153 (autoplay blocked) because the browser denies the
257
+ * Permissions Policy the player requests.
223
258
  */
224
259
  export const injectIframeSafetyAttrs = (html) => {
225
260
  return html.replace(/<iframe([^>]*?)>/gi, (match, attrs) => {
@@ -229,7 +264,7 @@ export const injectIframeSafetyAttrs = (html) => {
229
264
  }
230
265
  if (!/sandbox\s*=/.test(safeAttrs)) {
231
266
  safeAttrs +=
232
- ' sandbox="allow-scripts allow-same-origin allow-popups allow-presentation"';
267
+ ' sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox allow-presentation"';
233
268
  }
234
269
  if (!/referrerpolicy\s*=/.test(safeAttrs)) {
235
270
  safeAttrs += ' referrerpolicy="no-referrer"';
@@ -237,6 +272,9 @@ export const injectIframeSafetyAttrs = (html) => {
237
272
  if (!/style\s*=/.test(safeAttrs)) {
238
273
  safeAttrs += ' style="max-width:100%;width:100%;border:0;display:block;"';
239
274
  }
275
+ if (!/\ballow\s*=/.test(safeAttrs)) {
276
+ safeAttrs += ' allow="autoplay; encrypted-media; picture-in-picture"';
277
+ }
240
278
  return `<iframe${safeAttrs}>`;
241
279
  });
242
280
  };
@@ -0,0 +1,16 @@
1
+ import type { MediaAttachmentData, ResourceKind } from '../types/models';
2
+ export declare const RESOURCE_KINDS: readonly ["video", "file", "gallery", "audio", "link"];
3
+ export declare const attachmentMediaKind: (att: Pick<MediaAttachmentData, "type" | "meta">) => "image" | "video" | "audio" | "file";
4
+ export declare const resourceHasRequiredMedia: (resource: {
5
+ resourceKind: ResourceKind;
6
+ url?: string;
7
+ attachments?: MediaAttachmentData[];
8
+ }) => boolean;
9
+ export type CategoryNode = {
10
+ name: string;
11
+ path: string[];
12
+ children: CategoryNode[];
13
+ };
14
+ export declare const categoryTreeFromPaths: (paths: readonly (readonly string[])[]) => CategoryNode[];
15
+ export declare const pathStartsWith: (path: readonly string[], prefix: readonly string[]) => boolean;
16
+ export declare const normalizeResourceTags: (tags: readonly string[] | undefined) => string[];
@@ -0,0 +1,64 @@
1
+ export const RESOURCE_KINDS = [
2
+ 'video',
3
+ 'file',
4
+ 'gallery',
5
+ 'audio',
6
+ 'link',
7
+ ];
8
+ export const attachmentMediaKind = (att) => {
9
+ const mime = att.meta?.mimetype ?? '';
10
+ const type = att.type ?? '';
11
+ if (type === 'image' || mime.startsWith('image/'))
12
+ return 'image';
13
+ if (type === 'video' || mime.startsWith('video/'))
14
+ return 'video';
15
+ if (type === 'audio' || mime.startsWith('audio/'))
16
+ return 'audio';
17
+ return 'file';
18
+ };
19
+ export const resourceHasRequiredMedia = (resource) => {
20
+ if (resource.resourceKind === 'link')
21
+ return Boolean(resource.url);
22
+ const need = resource.resourceKind === 'gallery'
23
+ ? 'image'
24
+ : resource.resourceKind === 'video'
25
+ ? 'video'
26
+ : resource.resourceKind === 'audio'
27
+ ? 'audio'
28
+ : 'file';
29
+ return (resource.attachments ?? []).some((att) => attachmentMediaKind(att) === need);
30
+ };
31
+ export const categoryTreeFromPaths = (paths) => {
32
+ const root = [];
33
+ for (const path of paths) {
34
+ let level = root;
35
+ const acc = [];
36
+ for (const name of path) {
37
+ const segment = name.trim();
38
+ if (!segment)
39
+ continue;
40
+ acc.push(segment);
41
+ let node = level.find((entry) => entry.name === segment);
42
+ if (!node) {
43
+ node = { name: segment, path: [...acc], children: [] };
44
+ level.push(node);
45
+ }
46
+ level = node.children;
47
+ }
48
+ }
49
+ return root;
50
+ };
51
+ export const pathStartsWith = (path, prefix) => prefix.length <= path.length &&
52
+ prefix.every((segment, index) => path[index] === segment);
53
+ export const normalizeResourceTags = (tags) => {
54
+ const seen = new Set();
55
+ const out = [];
56
+ for (const raw of tags ?? []) {
57
+ const tag = raw.replace(/^#/, '').trim().toLowerCase();
58
+ if (!tag || seen.has(tag))
59
+ continue;
60
+ seen.add(tag);
61
+ out.push(tag);
62
+ }
63
+ return out;
64
+ };
@@ -105,6 +105,7 @@ export declare const analyticsMemberRowSchema: z.ZodObject<{
105
105
  export type AnalyticsMemberRow = z.infer<typeof analyticsMemberRowSchema>;
106
106
  export declare const analyticsPostTypeKeySchema: z.ZodEnum<{
107
107
  jam: "jam";
108
+ resource: "resource";
108
109
  note: "note";
109
110
  event: "event";
110
111
  article: "article";
@@ -114,6 +115,7 @@ export type AnalyticsPostTypeKey = z.infer<typeof analyticsPostTypeKeySchema>;
114
115
  export declare const analyticsPostTypeCountSchema: z.ZodObject<{
115
116
  type: z.ZodEnum<{
116
117
  jam: "jam";
118
+ resource: "resource";
117
119
  note: "note";
118
120
  event: "event";
119
121
  article: "article";
@@ -130,6 +132,7 @@ export declare const analyticsStackedPointSchema: z.ZodObject<{
130
132
  note: z.ZodNumber;
131
133
  poll: z.ZodNumber;
132
134
  event: z.ZodNumber;
135
+ resource: z.ZodNumber;
133
136
  }, z.core.$strip>;
134
137
  export type AnalyticsStackedPoint = z.infer<typeof analyticsStackedPointSchema>;
135
138
  export declare const analyticsBucketedPointSchema: z.ZodObject<{
@@ -264,10 +267,12 @@ export declare const analyticsOverviewSchema: z.ZodObject<{
264
267
  note: z.ZodNumber;
265
268
  poll: z.ZodNumber;
266
269
  event: z.ZodNumber;
270
+ resource: z.ZodNumber;
267
271
  }, z.core.$strip>>;
268
272
  postTypes: z.ZodArray<z.ZodObject<{
269
273
  type: z.ZodEnum<{
270
274
  jam: "jam";
275
+ resource: "resource";
271
276
  note: "note";
272
277
  event: "event";
273
278
  article: "article";
@@ -88,6 +88,7 @@ export const analyticsPostTypeKeySchema = z.enum([
88
88
  'note',
89
89
  'poll',
90
90
  'event',
91
+ 'resource',
91
92
  ]);
92
93
  export const analyticsPostTypeCountSchema = z.object({
93
94
  type: analyticsPostTypeKeySchema,
@@ -101,6 +102,7 @@ export const analyticsStackedPointSchema = z.object({
101
102
  note: z.number(),
102
103
  poll: z.number(),
103
104
  event: z.number(),
105
+ resource: z.number(),
104
106
  });
105
107
  export const analyticsBucketedPointSchema = z.object({
106
108
  day: z.string(),