@openpeepshq/common 0.11.0 → 0.13.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/common",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -10,6 +10,12 @@ import { effectiveEventTimes } from './eventRecurrence';
10
10
  import { getJamUrl } from './jamHelpers';
11
11
  import { isIanaTimeZone } from './timeZone';
12
12
 
13
+ /**
14
+ * Feed cache TTL in seconds. Single source of truth for the HTTP `max-age`
15
+ * and the ICS `REFRESH-INTERVAL`/`X-PUBLISHED-TTL` so they cannot drift.
16
+ */
17
+ export const EVENTS_ICS_FEED_TTL_SECONDS = 3600;
18
+
13
19
  const utcDateFromYmd = (yyyyMmDd: string): Date => {
14
20
  const [y, m, d] = yyyyMmDd.split('-').map(Number);
15
21
  return new Date(Date.UTC(y, m - 1, d));
@@ -60,6 +66,30 @@ const withVtimezone = (calendarText: string, timeZone: string): string => {
60
66
  );
61
67
  };
62
68
 
69
+ /**
70
+ * ical-generator writes an all-day `recurrenceId` as a UTC instant
71
+ * (`RECURRENCE-ID:20260713T000000Z`), but RFC 5545 §3.8.4.4 requires the
72
+ * RECURRENCE-ID value type to match the series DTSTART — DATE for all-day
73
+ * events. Rewrite each RECURRENCE-ID line to DATE form.
74
+ */
75
+ const withDateRecurrenceId = (calendarText: string): string =>
76
+ // Split on any line ending so a trailing `\r` is never carried into the
77
+ // re-joined CRLF text (splitting on `\n` alone would leave `\r\r\n`).
78
+ calendarText
79
+ .split(/\r\n|\r|\n/)
80
+ .map((line) => {
81
+ if (!line.startsWith('RECURRENCE-ID')) return line;
82
+ if (line.includes(';VALUE=DATE')) return line;
83
+ const colonIdx = line.indexOf(':');
84
+ if (colonIdx === -1) return line;
85
+ const ymd = line
86
+ .slice(colonIdx + 1)
87
+ .replace(/[^0-9]/g, '')
88
+ .slice(0, 8);
89
+ return `RECURRENCE-ID;VALUE=DATE:${ymd}`;
90
+ })
91
+ .join('\r\n');
92
+
63
93
  const originFromUrl = (url?: string): string | undefined => {
64
94
  if (!url) {
65
95
  return undefined;
@@ -73,7 +103,7 @@ const originFromUrl = (url?: string): string | undefined => {
73
103
 
74
104
  /** Prefer a joinable place: physical address, jam URL, then external event URL. */
75
105
  const eventLocation = (
76
- post: PublicPost,
106
+ post: IcsEventPost,
77
107
  event: Event,
78
108
  postUrl?: string,
79
109
  ): string | undefined => {
@@ -127,9 +157,20 @@ const repeatingOptions = (event: Event, timeZone?: string) => {
127
157
  };
128
158
  };
129
159
 
160
+ /**
161
+ * Minimal structural shape of an event post that the feed builder reads.
162
+ * `PostWithMeta` satisfies it, so callers can pass rich post objects
163
+ * without a cast.
164
+ */
165
+ export type IcsEventPost = {
166
+ id: string;
167
+ type: string;
168
+ data?: { type?: string } & Record<string, unknown>;
169
+ updatedAt: string;
170
+ };
130
171
  export const buildEventIcs = (
131
- post: PublicPost,
132
- options?: { postUrl?: string },
172
+ post: IcsEventPost,
173
+ options?: { postUrl?: string; lastModified?: string; sequence?: number },
133
174
  ): string | null => {
134
175
  if (post.type !== 'event' || post.data?.type !== 'event') {
135
176
  return null;
@@ -142,6 +183,15 @@ export const buildEventIcs = (
142
183
  scale: 'GREGORIAN',
143
184
  });
144
185
 
186
+ // Optional per-post edit stamp (used by the feed so clients update an
187
+ // existing UID instead of re-adding); omitted for single-event exports.
188
+ const stamp = options?.lastModified
189
+ ? {
190
+ lastModified: new Date(options.lastModified),
191
+ sequence: options.sequence ?? 0,
192
+ }
193
+ : {};
194
+
145
195
  const link = event.url ?? options?.postUrl;
146
196
  const summary = event.name?.trim() || 'Event';
147
197
  const description = event.content?.trim();
@@ -163,6 +213,7 @@ export const buildEventIcs = (
163
213
  ...(description ? { description } : {}),
164
214
  ...(location ? { location } : {}),
165
215
  ...(link ? { url: link } : {}),
216
+ ...stamp,
166
217
  ...(repeating ? { repeating } : {}),
167
218
  });
168
219
  } else {
@@ -179,33 +230,58 @@ export const buildEventIcs = (
179
230
  ...(description ? { description } : {}),
180
231
  ...(location ? { location } : {}),
181
232
  ...(link ? { url: link } : {}),
233
+ ...stamp,
182
234
  ...(repeating ? { repeating } : {}),
183
235
  });
184
236
  }
185
237
 
186
238
  for (const exception of event.exceptions ?? []) {
187
239
  if (exception.cancelled || !exception.start) continue;
188
- const start = instantInZone(exception.start, timeZone);
189
- const end = exception.end
190
- ? instantInZone(exception.end, timeZone)
191
- : defaultEnd(start, timeZone);
192
- calendar.createEvent({
193
- id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
194
- start,
195
- end,
196
- ...(timeZone ? { timezone: timeZone } : {}),
197
- summary,
198
- ...(description ? { description } : {}),
199
- ...(location ? { location } : {}),
200
- ...(link ? { url: link } : {}),
201
- recurrenceId: instantInZone(exception.recurrenceId, timeZone),
202
- });
240
+ if (event.wholeDay) {
241
+ // Rescheduled all-day occurrence: an all-day override whose day range
242
+ // is the exception's new start day through its end day (inclusive).
243
+ // RECURRENCE-ID identifies the *original* occurrence (RFC 5545 3.8.4.4),
244
+ // while DTSTART/DTEND stay on the new days. The DATE-form RECURRENCE-ID
245
+ // is normalized after serialization.
246
+ const excStartYmd = exception.start.slice(0, 10);
247
+ const excLastInclusiveYmd = exception.end?.slice(0, 10) ?? excStartYmd;
248
+ calendar.createEvent({
249
+ id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
250
+ allDay: true,
251
+ start: utcDateFromYmd(excStartYmd),
252
+ end: exclusiveEndAfterInclusiveDay(excLastInclusiveYmd),
253
+ summary,
254
+ ...(description ? { description } : {}),
255
+ ...(location ? { location } : {}),
256
+ ...(link ? { url: link } : {}),
257
+ ...stamp,
258
+ recurrenceId: utcDateFromYmd(exception.recurrenceId.slice(0, 10)),
259
+ });
260
+ } else {
261
+ const start = instantInZone(exception.start, timeZone);
262
+ const end = exception.end
263
+ ? instantInZone(exception.end, timeZone)
264
+ : defaultEnd(start, timeZone);
265
+ calendar.createEvent({
266
+ id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
267
+ start,
268
+ end,
269
+ ...(timeZone ? { timezone: timeZone } : {}),
270
+ summary,
271
+ ...(description ? { description } : {}),
272
+ ...(location ? { location } : {}),
273
+ ...(link ? { url: link } : {}),
274
+ ...stamp,
275
+ recurrenceId: instantInZone(exception.recurrenceId, timeZone),
276
+ });
277
+ }
203
278
  }
204
279
 
205
280
  const calendarText = calendar.toString();
206
- return (
207
- (timeZone ? withVtimezone(calendarText, timeZone) : calendarText) + '\r\n'
208
- );
281
+ const processed = event.wholeDay
282
+ ? withDateRecurrenceId(calendarText)
283
+ : calendarText;
284
+ return (timeZone ? withVtimezone(processed, timeZone) : processed) + '\r\n';
209
285
  };
210
286
 
211
287
  const addOccurrenceEvent = (
@@ -319,3 +395,98 @@ export const rsvpConfirmationContent = (
319
395
  occurrenceCount: occurrenceIds.length,
320
396
  };
321
397
  };
398
+
399
+ /** Collect the VEVENT blocks from a full ICS document. */
400
+ const extractVevents = (ics: string): string[] => {
401
+ const blocks: string[] = [];
402
+ let depth = 0;
403
+ let current: string[] = [];
404
+ for (const line of ics.split(/\r?\n/)) {
405
+ if (line.startsWith('BEGIN:VEVENT')) {
406
+ depth += 1;
407
+ current = [line];
408
+ } else if (line.startsWith('END:VEVENT')) {
409
+ depth -= 1;
410
+ current.push(line);
411
+ if (depth === 0) blocks.push(current.join('\r\n'));
412
+ } else if (depth > 0) {
413
+ current.push(line);
414
+ }
415
+ }
416
+ return blocks;
417
+ };
418
+
419
+ /**
420
+ * The zone list referenced by a set of VEVENTs, in first-seen order. Each
421
+ * per-post export splices in the VTIMEZONEs its events use; a feed of several
422
+ * zone-aware events must keep one block per zone (ical-generator emits
423
+ * `TZID=` references without any VTIMEZONE of its own).
424
+ */
425
+ const referencedZones = (vevents: string[]): string[] => {
426
+ const zones: string[] = [];
427
+ for (const vevent of vevents) {
428
+ for (const line of vevent.split('\r\n')) {
429
+ const match = line.match(/;TZID=([^:;]+)/);
430
+ if (match && !zones.includes(match[1])) {
431
+ zones.push(match[1]);
432
+ }
433
+ }
434
+ }
435
+ return zones;
436
+ };
437
+
438
+ /**
439
+ * Build a multi-event ICS feed string. Composes the single-event exports so
440
+ * the feed stays byte-identical to what the per-event download produces, and
441
+ * carries one deduped VTIMEZONE block per zone so zone-aware events survive.
442
+ *
443
+ * `postUrl` is the community base (origin); each event's joinable-URL fallback
444
+ * is derived as `${postUrl}/posts/{id}`, mirroring the single-event export.
445
+ * Passing a bare origin (never the request URL) keeps the feed's `?token=`
446
+ * secret out of the ICS body.
447
+ *
448
+ * With no events the feed is still a valid calendar (PRODID, `X-WR-CALNAME`,
449
+ * `REFRESH-INTERVAL`, `X-PUBLISHED-TTL`, no VEVENTs) — the same shape the
450
+ * feed endpoint's 401 `emptyCalendar` fallback mirrors. An empty feed is 200,
451
+ * not 404: calendar clients expect a parseable document they can re-poll.
452
+ */
453
+ export const buildEventsFeedIcs = (
454
+ posts: IcsEventPost[],
455
+ options: { postUrl?: string; name: string; ttl?: number },
456
+ ): string => {
457
+ const { name, ttl = EVENTS_ICS_FEED_TTL_SECONDS } = options;
458
+ const calendar = ical({
459
+ prodId: '//OpenPeeps//Feed//EN',
460
+ method: ICalCalendarMethod.PUBLISH,
461
+ scale: 'GREGORIAN',
462
+ name,
463
+ ttl,
464
+ });
465
+
466
+ const base = options.postUrl?.replace(/\/+$/, '');
467
+ const vevents: string[] = [];
468
+ for (const post of posts) {
469
+ if (post.type !== 'event' || post.data?.type !== 'event') continue;
470
+ const single = buildEventIcs(post, {
471
+ postUrl: base ? `${base}/posts/${post.id}` : undefined,
472
+ lastModified: post.updatedAt,
473
+ // Minutes since epoch: stable across processes, grows only on edits.
474
+ sequence: Math.floor(new Date(post.updatedAt).getTime() / 60000),
475
+ });
476
+ if (single) vevents.push(...extractVevents(single));
477
+ }
478
+
479
+ const zoneBlocks = referencedZones(vevents)
480
+ .map((zone) => {
481
+ const [block] = tzlib_get_ical_block(zone) as [string, string];
482
+ return block.replace(/\r?\n/g, '\r\n').trim();
483
+ })
484
+ .join('\r\n');
485
+
486
+ const body =
487
+ (zoneBlocks ? zoneBlocks + '\r\n' : '') +
488
+ (vevents.length ? vevents.join('\r\n') + '\r\n' : '');
489
+ return calendar
490
+ .toString()
491
+ .replace(/END:VCALENDAR\r?\n?$/, body + 'END:VCALENDAR\r\n');
492
+ };
@@ -13,12 +13,17 @@ import {
13
13
  PublicProfile,
14
14
  PublicRsvp,
15
15
  Question,
16
+ Role,
16
17
  RSVP,
17
18
  Thread,
18
19
  VisibilityType,
19
20
  visibilityTypeValues,
20
21
  } from '../types';
21
22
  import { canModerateJam } from './jamHelpers';
23
+ import {
24
+ canAnnouncePosts,
25
+ isCommunityWideVisibility,
26
+ } from './capabilitiesHelpers';
22
27
  import {
23
28
  defaultRsvpRecurrenceId,
24
29
  effectiveEventTimes,
@@ -563,6 +568,35 @@ export const withoutEventMaxAttendees = <T extends Event>(event: T): T => {
563
568
  return rest as T;
564
569
  };
565
570
 
571
+ /** A community-wide jam only broadcasts when the creator opted in. */
572
+ export const withoutJamNotifyEveryone = <T extends Event>(event: T): T => {
573
+ if (!event.jam?.notifyEveryone) return event;
574
+ return { ...event, jam: { ...event.jam, notifyEveryone: undefined } } as T;
575
+ };
576
+
577
+ /**
578
+ * Broadcast requires community-wide visibility AND the announce capability
579
+ * (same rule as `POST /admin/posts/:postId/announce`); other visibilities or
580
+ * roles drop the flag. The capability check matters because the save path is
581
+ * reachable without the UI toggle: a plain member's role wildcard-matches
582
+ * `core-posts-create-*`, so a crafted API payload could otherwise plant the
583
+ * flag and blast the whole instance.
584
+ *
585
+ * Exported (rather than kept module-local) because `@openpeepshq/core`'s
586
+ * `createPost`/`updatePost` mutations apply it on the server-side save path;
587
+ * it is not a general-purpose utility — unlike `withoutJamNotifyEveryone` and
588
+ * `withoutEventMaxAttendees`, it takes the creator's roles in addition to the
589
+ * event.
590
+ */
591
+ export const withoutCommunityJamNotifyEveryone = <T extends Event>(
592
+ event: T,
593
+ visibility: string | undefined,
594
+ roles?: Role[],
595
+ ): T =>
596
+ isCommunityWideVisibility(visibility) && canAnnouncePosts(roles)
597
+ ? event
598
+ : withoutJamNotifyEveryone(event);
599
+
566
600
  export const normalizeEventDataForSave = <T extends Event>(event: T): T => {
567
601
  const { maxAttendees } = event;
568
602
  if (
package/src/types/api.ts CHANGED
@@ -580,6 +580,16 @@ export const jamTokenResponseSchema = tokenResponseSchema.extend({
580
580
  });
581
581
  export type JamTokenResponse = z.infer<typeof jamTokenResponseSchema>;
582
582
 
583
+ // The calendar-feed mint returns no `checkoutUrl`; a dedicated shape keeps
584
+ // the endpoint's contract exact.
585
+ export const calendarFeedTokenResponseSchema = z.object({
586
+ success: z.literal(true),
587
+ token: z.string(),
588
+ });
589
+ export type CalendarFeedTokenResponse = z.infer<
590
+ typeof calendarFeedTokenResponseSchema
591
+ >;
592
+
583
593
  /**
584
594
  * Waiting-room entry as stored in Redis and streamed to moderators: the
585
595
  * profile's `displayName` (or `handle` when absent) keyed by `profile.id`.
@@ -380,6 +380,8 @@ export const jamDataSchema = z
380
380
  maxPresenters: z.number().int().positive().optional(),
381
381
  maxAudience: z.number().int().positive().optional(),
382
382
  waitingRoom: z.boolean().optional(),
383
+ /** Opt-in broadcast to the whole community when the jam starts. */
384
+ notifyEveryone: z.boolean().optional(),
383
385
  })
384
386
  .openapi('Jam');
385
387