@openpeepshq/common 0.11.0 → 0.12.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.
@@ -1,6 +1,26 @@
1
1
  import type { PublicPost } from '../types';
2
- export declare const buildEventIcs: (post: PublicPost, options?: {
2
+ /**
3
+ * Feed cache TTL in seconds. Single source of truth for the HTTP `max-age`
4
+ * and the ICS `REFRESH-INTERVAL`/`X-PUBLISHED-TTL` so they cannot drift.
5
+ */
6
+ export declare const EVENTS_ICS_FEED_TTL_SECONDS = 3600;
7
+ /**
8
+ * Minimal structural shape of an event post that the feed builder reads.
9
+ * `PostWithMeta` satisfies it, so callers can pass rich post objects
10
+ * without a cast.
11
+ */
12
+ export type IcsEventPost = {
13
+ id: string;
14
+ type: string;
15
+ data?: {
16
+ type?: string;
17
+ } & Record<string, unknown>;
18
+ updatedAt: string;
19
+ };
20
+ export declare const buildEventIcs: (post: IcsEventPost, options?: {
3
21
  postUrl?: string;
22
+ lastModified?: string;
23
+ sequence?: number;
4
24
  }) => string | null;
5
25
  /** Attendance ICS: discrete booked dates, or the series definition when none. */
6
26
  export declare const buildRsvpIcs: (post: PublicPost, options?: {
@@ -19,3 +39,23 @@ export declare const rsvpConfirmationContent: (post: PublicPost, options: {
19
39
  allDay: boolean;
20
40
  occurrenceCount: number;
21
41
  } | null;
42
+ /**
43
+ * Build a multi-event ICS feed string. Composes the single-event exports so
44
+ * the feed stays byte-identical to what the per-event download produces, and
45
+ * carries one deduped VTIMEZONE block per zone so zone-aware events survive.
46
+ *
47
+ * `postUrl` is the community base (origin); each event's joinable-URL fallback
48
+ * is derived as `${postUrl}/posts/{id}`, mirroring the single-event export.
49
+ * Passing a bare origin (never the request URL) keeps the feed's `?token=`
50
+ * secret out of the ICS body.
51
+ *
52
+ * With no events the feed is still a valid calendar (PRODID, `X-WR-CALNAME`,
53
+ * `REFRESH-INTERVAL`, `X-PUBLISHED-TTL`, no VEVENTs) — the same shape the
54
+ * feed endpoint's 401 `emptyCalendar` fallback mirrors. An empty feed is 200,
55
+ * not 404: calendar clients expect a parseable document they can re-poll.
56
+ */
57
+ export declare const buildEventsFeedIcs: (posts: IcsEventPost[], options: {
58
+ postUrl?: string;
59
+ name: string;
60
+ ttl?: number;
61
+ }) => string;
@@ -4,6 +4,11 @@ import { tzlib_get_ical_block } from 'timezones-ical-library';
4
4
  import { effectiveEventTimes } from './eventRecurrence.js';
5
5
  import { getJamUrl } from './jamHelpers.js';
6
6
  import { isIanaTimeZone } from './timeZone.js';
7
+ /**
8
+ * Feed cache TTL in seconds. Single source of truth for the HTTP `max-age`
9
+ * and the ICS `REFRESH-INTERVAL`/`X-PUBLISHED-TTL` so they cannot drift.
10
+ */
11
+ export const EVENTS_ICS_FEED_TTL_SECONDS = 3600;
7
12
  const utcDateFromYmd = (yyyyMmDd) => {
8
13
  const [y, m, d] = yyyyMmDd.split('-').map(Number);
9
14
  return new Date(Date.UTC(y, m - 1, d));
@@ -43,6 +48,32 @@ const withVtimezone = (calendarText, timeZone) => {
43
48
  normalized +
44
49
  calendarText.slice(veventIndex));
45
50
  };
51
+ /**
52
+ * ical-generator writes an all-day `recurrenceId` as a UTC instant
53
+ * (`RECURRENCE-ID:20260713T000000Z`), but RFC 5545 §3.8.4.4 requires the
54
+ * RECURRENCE-ID value type to match the series DTSTART — DATE for all-day
55
+ * events. Rewrite each RECURRENCE-ID line to DATE form.
56
+ */
57
+ const withDateRecurrenceId = (calendarText) =>
58
+ // Split on any line ending so a trailing `\r` is never carried into the
59
+ // re-joined CRLF text (splitting on `\n` alone would leave `\r\r\n`).
60
+ calendarText
61
+ .split(/\r\n|\r|\n/)
62
+ .map((line) => {
63
+ if (!line.startsWith('RECURRENCE-ID'))
64
+ return line;
65
+ if (line.includes(';VALUE=DATE'))
66
+ return line;
67
+ const colonIdx = line.indexOf(':');
68
+ if (colonIdx === -1)
69
+ return line;
70
+ const ymd = line
71
+ .slice(colonIdx + 1)
72
+ .replace(/[^0-9]/g, '')
73
+ .slice(0, 8);
74
+ return `RECURRENCE-ID;VALUE=DATE:${ymd}`;
75
+ })
76
+ .join('\r\n');
46
77
  const originFromUrl = (url) => {
47
78
  if (!url) {
48
79
  return undefined;
@@ -110,6 +141,14 @@ export const buildEventIcs = (post, options) => {
110
141
  method: ICalCalendarMethod.PUBLISH,
111
142
  scale: 'GREGORIAN',
112
143
  });
144
+ // Optional per-post edit stamp (used by the feed so clients update an
145
+ // existing UID instead of re-adding); omitted for single-event exports.
146
+ const stamp = options?.lastModified
147
+ ? {
148
+ lastModified: new Date(options.lastModified),
149
+ sequence: options.sequence ?? 0,
150
+ }
151
+ : {};
113
152
  const link = event.url ?? options?.postUrl;
114
153
  const summary = event.name?.trim() || 'Event';
115
154
  const description = event.content?.trim();
@@ -130,6 +169,7 @@ export const buildEventIcs = (post, options) => {
130
169
  ...(description ? { description } : {}),
131
170
  ...(location ? { location } : {}),
132
171
  ...(link ? { url: link } : {}),
172
+ ...stamp,
133
173
  ...(repeating ? { repeating } : {}),
134
174
  });
135
175
  }
@@ -147,30 +187,58 @@ export const buildEventIcs = (post, options) => {
147
187
  ...(description ? { description } : {}),
148
188
  ...(location ? { location } : {}),
149
189
  ...(link ? { url: link } : {}),
190
+ ...stamp,
150
191
  ...(repeating ? { repeating } : {}),
151
192
  });
152
193
  }
153
194
  for (const exception of event.exceptions ?? []) {
154
195
  if (exception.cancelled || !exception.start)
155
196
  continue;
156
- const start = instantInZone(exception.start, timeZone);
157
- const end = exception.end
158
- ? instantInZone(exception.end, timeZone)
159
- : defaultEnd(start, timeZone);
160
- calendar.createEvent({
161
- id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
162
- start,
163
- end,
164
- ...(timeZone ? { timezone: timeZone } : {}),
165
- summary,
166
- ...(description ? { description } : {}),
167
- ...(location ? { location } : {}),
168
- ...(link ? { url: link } : {}),
169
- recurrenceId: instantInZone(exception.recurrenceId, timeZone),
170
- });
197
+ if (event.wholeDay) {
198
+ // Rescheduled all-day occurrence: an all-day override whose day range
199
+ // is the exception's new start day through its end day (inclusive).
200
+ // RECURRENCE-ID identifies the *original* occurrence (RFC 5545 3.8.4.4),
201
+ // while DTSTART/DTEND stay on the new days. The DATE-form RECURRENCE-ID
202
+ // is normalized after serialization.
203
+ const excStartYmd = exception.start.slice(0, 10);
204
+ const excLastInclusiveYmd = exception.end?.slice(0, 10) ?? excStartYmd;
205
+ calendar.createEvent({
206
+ id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
207
+ allDay: true,
208
+ start: utcDateFromYmd(excStartYmd),
209
+ end: exclusiveEndAfterInclusiveDay(excLastInclusiveYmd),
210
+ summary,
211
+ ...(description ? { description } : {}),
212
+ ...(location ? { location } : {}),
213
+ ...(link ? { url: link } : {}),
214
+ ...stamp,
215
+ recurrenceId: utcDateFromYmd(exception.recurrenceId.slice(0, 10)),
216
+ });
217
+ }
218
+ else {
219
+ const start = instantInZone(exception.start, timeZone);
220
+ const end = exception.end
221
+ ? instantInZone(exception.end, timeZone)
222
+ : defaultEnd(start, timeZone);
223
+ calendar.createEvent({
224
+ id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
225
+ start,
226
+ end,
227
+ ...(timeZone ? { timezone: timeZone } : {}),
228
+ summary,
229
+ ...(description ? { description } : {}),
230
+ ...(location ? { location } : {}),
231
+ ...(link ? { url: link } : {}),
232
+ ...stamp,
233
+ recurrenceId: instantInZone(exception.recurrenceId, timeZone),
234
+ });
235
+ }
171
236
  }
172
237
  const calendarText = calendar.toString();
173
- return ((timeZone ? withVtimezone(calendarText, timeZone) : calendarText) + '\r\n');
238
+ const processed = event.wholeDay
239
+ ? withDateRecurrenceId(calendarText)
240
+ : calendarText;
241
+ return (timeZone ? withVtimezone(processed, timeZone) : processed) + '\r\n';
174
242
  };
175
243
  const addOccurrenceEvent = (calendar, post, event, recurrenceId, options) => {
176
244
  const link = event.url ?? options?.postUrl;
@@ -254,3 +322,93 @@ export const rsvpConfirmationContent = (post, options) => {
254
322
  occurrenceCount: occurrenceIds.length,
255
323
  };
256
324
  };
325
+ /** Collect the VEVENT blocks from a full ICS document. */
326
+ const extractVevents = (ics) => {
327
+ const blocks = [];
328
+ let depth = 0;
329
+ let current = [];
330
+ for (const line of ics.split(/\r?\n/)) {
331
+ if (line.startsWith('BEGIN:VEVENT')) {
332
+ depth += 1;
333
+ current = [line];
334
+ }
335
+ else if (line.startsWith('END:VEVENT')) {
336
+ depth -= 1;
337
+ current.push(line);
338
+ if (depth === 0)
339
+ blocks.push(current.join('\r\n'));
340
+ }
341
+ else if (depth > 0) {
342
+ current.push(line);
343
+ }
344
+ }
345
+ return blocks;
346
+ };
347
+ /**
348
+ * The zone list referenced by a set of VEVENTs, in first-seen order. Each
349
+ * per-post export splices in the VTIMEZONEs its events use; a feed of several
350
+ * zone-aware events must keep one block per zone (ical-generator emits
351
+ * `TZID=` references without any VTIMEZONE of its own).
352
+ */
353
+ const referencedZones = (vevents) => {
354
+ const zones = [];
355
+ for (const vevent of vevents) {
356
+ for (const line of vevent.split('\r\n')) {
357
+ const match = line.match(/;TZID=([^:;]+)/);
358
+ if (match && !zones.includes(match[1])) {
359
+ zones.push(match[1]);
360
+ }
361
+ }
362
+ }
363
+ return zones;
364
+ };
365
+ /**
366
+ * Build a multi-event ICS feed string. Composes the single-event exports so
367
+ * the feed stays byte-identical to what the per-event download produces, and
368
+ * carries one deduped VTIMEZONE block per zone so zone-aware events survive.
369
+ *
370
+ * `postUrl` is the community base (origin); each event's joinable-URL fallback
371
+ * is derived as `${postUrl}/posts/{id}`, mirroring the single-event export.
372
+ * Passing a bare origin (never the request URL) keeps the feed's `?token=`
373
+ * secret out of the ICS body.
374
+ *
375
+ * With no events the feed is still a valid calendar (PRODID, `X-WR-CALNAME`,
376
+ * `REFRESH-INTERVAL`, `X-PUBLISHED-TTL`, no VEVENTs) — the same shape the
377
+ * feed endpoint's 401 `emptyCalendar` fallback mirrors. An empty feed is 200,
378
+ * not 404: calendar clients expect a parseable document they can re-poll.
379
+ */
380
+ export const buildEventsFeedIcs = (posts, options) => {
381
+ const { name, ttl = EVENTS_ICS_FEED_TTL_SECONDS } = options;
382
+ const calendar = ical({
383
+ prodId: '//OpenPeeps//Feed//EN',
384
+ method: ICalCalendarMethod.PUBLISH,
385
+ scale: 'GREGORIAN',
386
+ name,
387
+ ttl,
388
+ });
389
+ const base = options.postUrl?.replace(/\/+$/, '');
390
+ const vevents = [];
391
+ for (const post of posts) {
392
+ if (post.type !== 'event' || post.data?.type !== 'event')
393
+ continue;
394
+ const single = buildEventIcs(post, {
395
+ postUrl: base ? `${base}/posts/${post.id}` : undefined,
396
+ lastModified: post.updatedAt,
397
+ // Minutes since epoch: stable across processes, grows only on edits.
398
+ sequence: Math.floor(new Date(post.updatedAt).getTime() / 60000),
399
+ });
400
+ if (single)
401
+ vevents.push(...extractVevents(single));
402
+ }
403
+ const zoneBlocks = referencedZones(vevents)
404
+ .map((zone) => {
405
+ const [block] = tzlib_get_ical_block(zone);
406
+ return block.replace(/\r?\n/g, '\r\n').trim();
407
+ })
408
+ .join('\r\n');
409
+ const body = (zoneBlocks ? zoneBlocks + '\r\n' : '') +
410
+ (vevents.length ? vevents.join('\r\n') + '\r\n' : '');
411
+ return calendar
412
+ .toString()
413
+ .replace(/END:VCALENDAR\r?\n?$/, body + 'END:VCALENDAR\r\n');
414
+ };
@@ -38964,6 +38964,11 @@ export declare const jamTokenResponseSchema: z.ZodObject<{
38964
38964
  livekitUrl: z.ZodString;
38965
38965
  }, z.core.$strip>;
38966
38966
  export type JamTokenResponse = z.infer<typeof jamTokenResponseSchema>;
38967
+ export declare const calendarFeedTokenResponseSchema: z.ZodObject<{
38968
+ success: z.ZodLiteral<true>;
38969
+ token: z.ZodString;
38970
+ }, z.core.$strip>;
38971
+ export type CalendarFeedTokenResponse = z.infer<typeof calendarFeedTokenResponseSchema>;
38967
38972
  /**
38968
38973
  * Waiting-room entry as stored in Redis and streamed to moderators: the
38969
38974
  * profile's `displayName` (or `handle` when absent) keyed by `profile.id`.
package/dist/types/api.js CHANGED
@@ -379,6 +379,12 @@ export const tokenResponseSchema = z.object({
379
379
  export const jamTokenResponseSchema = tokenResponseSchema.extend({
380
380
  livekitUrl: z.string(),
381
381
  });
382
+ // The calendar-feed mint returns no `checkoutUrl`; a dedicated shape keeps
383
+ // the endpoint's contract exact.
384
+ export const calendarFeedTokenResponseSchema = z.object({
385
+ success: z.literal(true),
386
+ token: z.string(),
387
+ });
382
388
  /**
383
389
  * Waiting-room entry as stored in Redis and streamed to moderators: the
384
390
  * profile's `displayName` (or `handle` when absent) keyed by `profile.id`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/common",
3
- "version": "0.11.0",
3
+ "version": "0.12.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
+ };
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`.