@vermeulen.solutions/eventual 0.0.0-stage → 0.18.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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +139 -2
  3. package/astro/EventList.astro +57 -0
  4. package/astro/admin.d.mts +3 -0
  5. package/astro/admin.mjs +158 -0
  6. package/astro/blueprint.d.mts +51 -0
  7. package/astro/blueprint.mjs +236 -0
  8. package/astro/cache.ts +82 -0
  9. package/astro/descriptor.mjs +7 -0
  10. package/astro/editor-compat.mjs +197 -0
  11. package/astro/editor-i18n.d.mts +8 -0
  12. package/astro/editor-i18n.mjs +157 -0
  13. package/astro/event-details.ts +29 -0
  14. package/astro/event-list.ts +56 -0
  15. package/astro/feed.ts +201 -0
  16. package/astro/install.d.mts +9 -0
  17. package/astro/install.mjs +66 -0
  18. package/astro/schema.ts +88 -0
  19. package/dist/index.d.mts +5 -0
  20. package/dist/index.mjs +1585 -0
  21. package/dist/plugin.d.mts +6 -0
  22. package/dist/plugin.mjs +13 -0
  23. package/docs/collection-setup.md +46 -0
  24. package/docs/history.md +16 -0
  25. package/docs/native-modernization.md +99 -0
  26. package/docs/public-feed-caching.md +259 -0
  27. package/docs/registry-installation.md +13 -0
  28. package/docs/release-notes-0.14.0.md +27 -0
  29. package/docs/release-notes-0.14.1.md +40 -0
  30. package/docs/release-notes-0.15.0.md +18 -0
  31. package/docs/release-notes-0.16.0.md +7 -0
  32. package/docs/release-notes-0.17.0.md +7 -0
  33. package/docs/release-notes-0.18.0.md +8 -0
  34. package/docs/release-notes-0.18.1.md +7 -0
  35. package/docs/release-notes-0.18.2.md +6 -0
  36. package/docs/upgrade-0.13.0.md +21 -0
  37. package/docs/user-guide.md +40 -0
  38. package/emdash-plugin.jsonc +77 -0
  39. package/package.json +143 -4
  40. package/scripts/check-editor-installation.mjs +32 -0
  41. package/scripts/export-native-schema.mjs +28 -0
  42. package/scripts/upgrade-native-editor.mjs +296 -0
  43. package/src/domain/calendar-links.ts +80 -0
  44. package/src/domain/category.ts +32 -0
  45. package/src/domain/collections.ts +101 -0
  46. package/src/domain/date-time.ts +220 -0
  47. package/src/domain/description.ts +108 -0
  48. package/src/domain/event-data.ts +217 -0
  49. package/src/domain/event-expansion.ts +305 -0
  50. package/src/domain/event.ts +195 -0
  51. package/src/domain/icalendar.ts +165 -0
  52. package/src/domain/image.ts +18 -0
  53. package/src/domain/invocation-budget.ts +56 -0
  54. package/src/domain/messages.ts +8 -0
  55. package/src/domain/migration.ts +666 -0
  56. package/src/domain/native-calendar.ts +256 -0
  57. package/src/domain/native-references.ts +41 -0
  58. package/src/domain/native-source.ts +261 -0
  59. package/src/domain/native-validation.ts +366 -0
  60. package/src/domain/occurrences.ts +54 -0
  61. package/src/domain/portable-text.ts +180 -0
  62. package/src/domain/public-cache.ts +24 -0
  63. package/src/domain/recurrence-rule.ts +34 -0
  64. package/src/domain/recurrence.ts +350 -0
  65. package/src/domain/request-memo.ts +8 -0
  66. package/src/domain/schedule-history.ts +14 -0
  67. package/src/domain/text.ts +2 -0
  68. package/src/domain/time-entry.ts +23 -0
  69. package/src/domain/venue-adapter.ts +101 -0
  70. package/src/domain/venue.ts +42 -0
  71. package/src/public-event.ts +88 -0
  72. package/src/schema/blueprint.ts +315 -0
  73. package/src/storage.ts +257 -0
  74. package/transfer/index.d.mts +13 -0
  75. package/transfer/index.mjs +155 -0
@@ -0,0 +1,305 @@
1
+ import { text } from "./text";
2
+ import { reject } from './messages';
3
+ import { expandEventsInDateRange, scheduledOccurrence } from "./recurrence";
4
+ import type { EventRecord, EventException } from "./event";
5
+ import { portableTextToPlainText } from "./portable-text";
6
+ import {
7
+ normalizeVenueRecord,
8
+ localizedVenue,
9
+ type NormalizedVenue,
10
+ } from "./venue-adapter";
11
+ import { normalizeNativeSchedule, parseJson } from "./native-validation";
12
+ import { formatPublicEvent } from "../public-event";
13
+ import { categoryKey, readCategories } from "./category";
14
+ import type { PublicEvent } from "../../astro/feed";
15
+
16
+ export interface ExpandOccurrencesOptions {
17
+ from: string;
18
+ through: string;
19
+ category?: string;
20
+ venues?: unknown[] | Map<string, unknown>;
21
+ siteUrl?: string;
22
+ }
23
+ const timestamp = (value: unknown) =>
24
+ value instanceof Date ? value.toISOString() : text(value);
25
+ export function nativeEntryToEventRecord(entry: unknown): EventRecord | null {
26
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return null;
27
+ const outer = entry as Record<string, unknown>;
28
+ const nested =
29
+ !!outer.data &&
30
+ typeof outer.data === "object" &&
31
+ !Array.isArray(outer.data);
32
+ const data = (nested ? outer.data : outer) as Record<string, unknown>;
33
+ // LiveCollection entry IDs are slugs; the loader keeps the CMS ID in data.id.
34
+ const id = text(nested && outer.type ? outer.id : (data.id ?? outer.id));
35
+ if (!id) return null;
36
+ try {
37
+ const parsedExceptions = (parseJson(data.exceptions) ??
38
+ []) as EventException[];
39
+ if (!Array.isArray(parsedExceptions)) return null;
40
+ const native =
41
+ Object.hasOwn(data, "all_day") ||
42
+ (nested &&
43
+ (typeof outer.type === "string" || !Object.hasOwn(data, "published")));
44
+ const sharedExceptions = native
45
+ ? parsedExceptions
46
+ : parsedExceptions
47
+ .map((ex) => ({
48
+ ...ex,
49
+ overrides: ex.overrides
50
+ ? Object.fromEntries(
51
+ Object.entries(ex.overrides).filter(
52
+ ([key]) =>
53
+ ![
54
+ "title",
55
+ "description",
56
+ "location",
57
+ "organizer",
58
+ "locale",
59
+ ].includes(key),
60
+ ),
61
+ )
62
+ : undefined,
63
+ }))
64
+ .filter(
65
+ (ex) =>
66
+ ex.status === "cancelled" ||
67
+ Object.keys(ex.overrides ?? {}).length,
68
+ );
69
+ const normalized = normalizeNativeSchedule(
70
+ {
71
+ ...data,
72
+ all_day: data.all_day ?? data.allDay,
73
+ exceptions: sharedExceptions,
74
+ },
75
+ { allowStaleOccurrenceCopy: true },
76
+ );
77
+ const allDay = normalized.all_day as boolean;
78
+ const start = text(allDay ? normalized.start_date : normalized.start);
79
+ const end = text(allDay ? normalized.end_date : normalized.end);
80
+ const recurrence = parseJson(data.recurrence) as EventRecord["recurrence"];
81
+ const exceptions = parsedExceptions.map((ex) => ({
82
+ ...ex,
83
+ overrides: ex.overrides ? { ...ex.overrides } : undefined,
84
+ }));
85
+ const editorial = (parseJson(data.occurrence_content) ?? []) as Array<{
86
+ recurrenceId: string;
87
+ overrides: Record<string, unknown>;
88
+ }>;
89
+ for (const copy of editorial) {
90
+ if (
91
+ !recurrence ||
92
+ !scheduledOccurrence(
93
+ {
94
+ id,
95
+ start,
96
+ end,
97
+ allDay,
98
+ timezone: text(normalized.timezone),
99
+ recurrence,
100
+ } as EventRecord,
101
+ copy.recurrenceId,
102
+ )
103
+ )
104
+ continue;
105
+ const existing = exceptions.find(
106
+ (item) => item.recurrenceId === copy.recurrenceId,
107
+ );
108
+ if (existing?.status === "cancelled") continue;
109
+ if (existing)
110
+ existing.overrides = { ...existing.overrides, ...copy.overrides };
111
+ else
112
+ exceptions.push({
113
+ recurrenceId: copy.recurrenceId,
114
+ status: "modified",
115
+ overrides: copy.overrides,
116
+ });
117
+ }
118
+ const coreStatus = native
119
+ ? nested && typeof outer.status === "string"
120
+ ? outer.status
121
+ : data.status
122
+ : undefined;
123
+ const published = coreStatus
124
+ ? coreStatus === "published"
125
+ : data.published === true;
126
+ const status = (data.event_status ??
127
+ (["cancelled", "postponed", "rescheduled"].includes(text(data.status))
128
+ ? data.status
129
+ : published
130
+ ? "published"
131
+ : "draft")) as EventRecord["status"];
132
+ const image = (typeof data.featured_image === "string" ? parseJson(data.featured_image) : data.featured_image) as Record<string, unknown> | undefined;
133
+ const venue = Object.hasOwn(data, "venue_id")
134
+ ? data.venue_id
135
+ : (data.venue ?? data.venueId);
136
+ const reference =
137
+ typeof venue === "string"
138
+ ? venue
139
+ : venue && typeof venue === "object"
140
+ ? text((venue as Record<string, unknown>).id)
141
+ : "";
142
+ const categories = readCategories(data.categories);
143
+ const mediaId = text(image?.id ?? data.featuredMediaId ?? data.featured_media_id ?? data.imageMediaId);
144
+ const metaKey = (image?.meta as Record<string, unknown> | undefined)?.storageKey;
145
+ const mediaSrc = text(image?.src || image?.url) || (metaKey ? "/_emdash/api/media/file/" + encodeURIComponent(String(metaKey)) : "");
146
+ const posNum = (v: unknown) => typeof v === "number" && v > 0 ? v : undefined;
147
+ const imageMedia = mediaSrc ? { src: mediaSrc, width: posNum(image?.width), height: posNum(image?.height), alt: text(image?.alt) || undefined } : undefined;
148
+ return {
149
+ id,
150
+ title: text(data.title).trim(),
151
+ description:
152
+ typeof data.description === "string"
153
+ ? data.description
154
+ : JSON.stringify(data.description ?? []),
155
+ descriptionBlocks: Array.isArray(data.description)
156
+ ? data.description
157
+ : undefined,
158
+ start,
159
+ end,
160
+ allDay,
161
+ timezone: text(normalized.timezone),
162
+ published,
163
+ status,
164
+ recurrence,
165
+ exceptions,
166
+ location: text(data.location),
167
+ locationType: (data.location_type ??
168
+ data.locationType ??
169
+ "physical") as EventRecord["locationType"],
170
+ virtualUrl: text(data.virtual_url ?? data.virtualUrl),
171
+ externalUrl: text(data.external_url ?? data.externalUrl),
172
+ organizer: text(data.organizer),
173
+ organizerId: text(
174
+ Object.hasOwn(data, "organizer_id")
175
+ ? data.organizer_id
176
+ : typeof data.organizer_ref === "object"
177
+ ? (data.organizer_ref as Record<string, unknown> | null)?.id
178
+ : (data.organizer_ref ?? data.organizerId),
179
+ ),
180
+ organizerDetails: parseJson(
181
+ data.organizer_details,
182
+ ) as EventRecord["organizerDetails"],
183
+ venueId: reference,
184
+ imageUrl: mediaId ? "" : text(data.image_url ?? data.imageUrl ?? image?.src ?? image?.url),
185
+ imageMediaId: mediaId,
186
+ featuredMediaId: mediaId || undefined,
187
+ imageMedia,
188
+ categories,
189
+ createdAt:
190
+ timestamp(outer.createdAt ?? data.created_at ?? data.createdAt) ||
191
+ "1970-01-01T00:00:00.000Z",
192
+ updatedAt:
193
+ timestamp(outer.updatedAt ?? data.updated_at ?? data.updatedAt) ||
194
+ "1970-01-01T00:00:00.000Z",
195
+ locale: text(outer.locale ?? data.locale) || undefined,
196
+ translationGroup:
197
+ text(
198
+ outer.translationGroup ??
199
+ data.translation_group ??
200
+ data.translationGroup ??
201
+ outer.translation_group,
202
+ ) || undefined,
203
+ calendarUid: text(data.calendar_uid ?? data.calendarUid) || undefined,
204
+ calendarSequence:
205
+ typeof data.calendarSequence === "number"
206
+ ? data.calendarSequence
207
+ : undefined,
208
+ previousStartDate:
209
+ text(data.previous_start_date ?? data.previousStartDate) || undefined,
210
+ scheduleHistory: parseJson(
211
+ data.schedule_history ?? data.scheduleHistory,
212
+ ) as EventRecord["scheduleHistory"],
213
+ slug: text(outer.slug ?? data.slug) || undefined,
214
+ publicUrl:
215
+ text(outer.publicUrl ?? outer.url ?? data.publicUrl ?? data.url) ||
216
+ undefined,
217
+ };
218
+ } catch {
219
+ return null;
220
+ }
221
+ }
222
+ export function eventRecordToPublicEvent(
223
+ record: EventRecord,
224
+ venueMap?: Map<string, NormalizedVenue>,
225
+ siteUrl?: string,
226
+ pluginId = "eventual",
227
+ ): PublicEvent {
228
+ const venue = localizedVenue(venueMap, record);
229
+ const normalized = venue
230
+ ? {
231
+ ...venue,
232
+ street: venue.street ?? "",
233
+ street2: venue.street2 ?? "",
234
+ locality: venue.locality ?? "",
235
+ region: venue.region ?? "",
236
+ postalCode: venue.postalCode ?? "",
237
+ country: venue.country ?? "",
238
+ createdAt: "",
239
+ updatedAt: "",
240
+ }
241
+ : undefined;
242
+ const formatted = formatPublicEvent(record, normalized, pluginId);
243
+ let imageUrl = formatted.imageUrl || record.imageUrl;
244
+ if (siteUrl && imageUrl) {
245
+ try {
246
+ imageUrl = new URL(imageUrl, siteUrl).href;
247
+ } catch {
248
+ imageUrl = "";
249
+ }
250
+ }
251
+ const m = record.imageMedia;
252
+ const imageMedia = m ? { ...m, src: siteUrl && m.src.startsWith("/") ? new URL(m.src, siteUrl).href : m.src } : undefined;
253
+ return {
254
+ ...formatted,
255
+ description: portableTextToPlainText(record.description),
256
+ ...(record.descriptionBlocks
257
+ ? { descriptionBlocks: record.descriptionBlocks }
258
+ : {}),
259
+ imageUrl,
260
+ ...(imageMedia ? { imageMedia } : {}),
261
+ organizerDetails: record.organizerDetails,
262
+ previousStartDate: record.previousStartDate,
263
+ locale: record.locale,
264
+ translationGroup: record.translationGroup,
265
+ slug: record.slug,
266
+ publicUrl: record.publicUrl,
267
+ };
268
+ }
269
+ export function expandEventOccurrences(
270
+ entries: unknown[],
271
+ options: ExpandOccurrencesOptions,
272
+ ): PublicEvent[] {
273
+ if (!Array.isArray(entries) || !options?.from || !options.through) return [];
274
+ const records = entries
275
+ .map(nativeEntryToEventRecord)
276
+ .filter((record): record is EventRecord => !!record && record.published);
277
+ const venues = new Map<string, NormalizedVenue>();
278
+ if (options.venues instanceof Map) {
279
+ for (const [key, value] of options.venues) {
280
+ const venue = normalizeVenueRecord(value);
281
+ if (venue) venues.set(key, venue);
282
+ }
283
+ } else if (Array.isArray(options.venues)) {
284
+ for (const value of options.venues) {
285
+ const venue = normalizeVenueRecord(value);
286
+ if (venue) venues.set(venue.id, venue);
287
+ }
288
+ }
289
+ const expanded = expandEventsInDateRange(
290
+ records,
291
+ options.from,
292
+ options.through,
293
+ );
294
+ if (expanded.length > 10000)
295
+ reject("Too many expanded occurrences; narrow the date range.");
296
+ const category = options.category ? categoryKey(options.category) : "";
297
+ const visible = category
298
+ ? expanded.filter((record) =>
299
+ record.categories.some((value) => categoryKey(value) === category),
300
+ )
301
+ : expanded;
302
+ return visible.map((record) =>
303
+ eventRecordToPublicEvent(record, venues, options.siteUrl),
304
+ );
305
+ }
@@ -0,0 +1,195 @@
1
+ export type WeekdayName =
2
+ | "sunday"
3
+ | "monday"
4
+ | "tuesday"
5
+ | "wednesday"
6
+ | "thursday"
7
+ | "friday"
8
+ | "saturday";
9
+
10
+ export type MonthlyPosition = 1 | 2 | 3 | 4 | 5 | "last";
11
+
12
+ export type EventRecurrence = (
13
+ | { frequency: "daily"; until: string }
14
+ | { frequency: "weekly"; until: string; weekdays?: WeekdayName[] }
15
+ | {
16
+ frequency: "monthly";
17
+ until: string;
18
+ pattern:
19
+ | {
20
+ type: "dayOfMonth";
21
+ dayOfMonth: number;
22
+ missingDayBehavior: "skip" | "lastDay";
23
+ }
24
+ | {
25
+ type: "weekdayOfMonth";
26
+ weekday: WeekdayName;
27
+ position: MonthlyPosition;
28
+ };
29
+ }) & { interval?: number };
30
+
31
+ export type EventLocationType = "physical" | "virtual" | "hybrid";
32
+ export type EventStatus = "draft" | "published" | "cancelled" | "postponed" | "rescheduled";
33
+
34
+ export interface EventFields {
35
+ title: string;
36
+ description: string;
37
+ /** Date-only for all-day events; an ISO instant for timed events. */
38
+ start: string;
39
+ /** Inclusive date-only end for all-day events; an ISO instant otherwise. */
40
+ end: string;
41
+ allDay: boolean;
42
+ timezone: string;
43
+ location: string;
44
+ locationType?: EventLocationType;
45
+ virtualUrl?: string;
46
+ status?: EventStatus;
47
+ organizer: string;
48
+ organizerId?: string;
49
+ externalUrl: string;
50
+ imageUrl: string;
51
+ imageMediaId?: string;
52
+ featuredMediaId?: string;
53
+ imageMedia?: { src: string; width?: number; height?: number; alt?: string };
54
+ categories: string[];
55
+ venueId?: string;
56
+ published: boolean;
57
+ locale?: string;
58
+ }
59
+
60
+ export type EventOverride = Partial<
61
+ Pick<
62
+ EventFields,
63
+ | "title"
64
+ | "description"
65
+ | "start"
66
+ | "end"
67
+ | "allDay"
68
+ | "timezone"
69
+ | "location"
70
+ | "locationType"
71
+ | "virtualUrl"
72
+ | "status"
73
+ | "organizer"
74
+ | "externalUrl"
75
+ | "imageUrl"
76
+ | "imageMediaId"
77
+ | "featuredMediaId"
78
+ | "imageMedia"
79
+ | "categories"
80
+ | "locale"
81
+ >
82
+ >;
83
+
84
+ export interface EventException {
85
+ /** Original local wall time (`YYYY-MM-DDTHH:mm`) or all-day date. */
86
+ recurrenceId: string;
87
+ status: "cancelled" | "modified";
88
+ overrides?: EventOverride;
89
+ }
90
+
91
+ export interface EventRecord extends EventFields {
92
+ /** Built-in manual translations in standalone mode; schedule stays on this one record. */
93
+ translations?: Record<string, { title: string; description: string; location: string; organizer: string }>;
94
+ id: string;
95
+ recurrence?: EventRecurrence;
96
+ exceptions: EventException[];
97
+ createdAt: string;
98
+ updatedAt: string;
99
+ /** Up to ten previous series schedules, newest first; never copied to duplicates. */
100
+ scheduleHistory?: Array<{ start: string; end: string; allDay: boolean; timezone: string; changedAt: string }>;
101
+ previousStartDate?: string;
102
+ translationGroup?: string;
103
+ calendarUid?: string;
104
+ calendarSequence?: number;
105
+ slug?: string;
106
+ publicUrl?: string;
107
+ organizerDetails?: { id: string; name: string; website: string; contactUrl: string };
108
+ descriptionBlocks?: unknown[];
109
+ }
110
+
111
+ export interface EventDraft {
112
+ title: string;
113
+ description: string;
114
+ start: string;
115
+ end: string;
116
+ allDay: boolean;
117
+ timezone: string;
118
+ location: string;
119
+ locationType?: EventLocationType;
120
+ virtualUrl?: string;
121
+ status?: EventStatus;
122
+ organizer: string;
123
+ organizerId?: string;
124
+ externalUrl: string;
125
+ imageUrl: string;
126
+ imageMediaId: string;
127
+ featuredMediaId?: string;
128
+ categories: string;
129
+ venueId: string;
130
+ published: boolean;
131
+ repeatFrequency: "none" | "daily" | "weekly" | "monthly";
132
+ recurrenceUntil: string;
133
+ recurrenceInterval?: number;
134
+ weeklyWeekdays?: WeekdayName[];
135
+ monthlyDayOfMonth?: number;
136
+ monthlyPattern: "dayOfMonth" | "weekdayOfMonth";
137
+ missingDayBehavior: "skip" | "lastDay";
138
+ monthlyWeekday: WeekdayName;
139
+ monthlyPosition: MonthlyPosition;
140
+ exceptions: EventException[];
141
+ }
142
+
143
+ export interface VenueFields {
144
+ name: string;
145
+ street: string;
146
+ street2: string;
147
+ locality: string;
148
+ region: string;
149
+ postalCode: string;
150
+ country: string;
151
+ }
152
+
153
+ export interface VenueRecord extends VenueFields {
154
+ id: string;
155
+ createdAt: string;
156
+ updatedAt: string;
157
+ }
158
+
159
+ export interface OrganizerRecord {
160
+ id: string;
161
+ name: string;
162
+ website: string;
163
+ /** Public contact URL; do not store private addresses here. */
164
+ contactUrl: string;
165
+ createdAt: string;
166
+ updatedAt: string;
167
+ }
168
+
169
+ export const EMPTY_EVENT_DRAFT: EventDraft = {
170
+ title: "",
171
+ description: "",
172
+ start: "",
173
+ end: "",
174
+ allDay: false,
175
+ timezone: "UTC",
176
+ location: "",
177
+ locationType: "physical",
178
+ virtualUrl: "",
179
+ status: "draft",
180
+ organizer: "",
181
+ externalUrl: "",
182
+ imageUrl: "",
183
+ imageMediaId: "",
184
+ categories: "",
185
+ venueId: "",
186
+ published: false,
187
+ repeatFrequency: "none",
188
+ recurrenceUntil: "",
189
+ recurrenceInterval: 1,
190
+ monthlyPattern: "dayOfMonth",
191
+ missingDayBehavior: "skip",
192
+ monthlyWeekday: "monday",
193
+ monthlyPosition: 1,
194
+ exceptions: [],
195
+ };
@@ -0,0 +1,165 @@
1
+ import { reject } from './messages';
2
+ import { calendarLocation, calendarStatus, calendarEventUrl } from "../../astro/event-details";
3
+ import type { EventRecord } from "./event";
4
+ import type { CalendarCancellation } from "../storage";
5
+ import { portableTextToPlainText } from "./portable-text";
6
+
7
+ export function formatCalendarFeed(
8
+ events: EventRecord[],
9
+ cancellations: CalendarCancellation[],
10
+ host: string,
11
+ generatedAt = new Date(),
12
+ calendarName?: string,
13
+ ): string {
14
+ const activeUids = new Set(events.map((event) => eventUid(event, host)));
15
+ const uniqueCancellations = new Map<string,CalendarCancellation>();
16
+ for (const item of cancellations) {
17
+ const uid=eventUid(item,host); const old=uniqueCancellations.get(uid);
18
+ if (!activeUids.has(uid) && (!old || item.cancelledAt>old.cancelledAt)) uniqueCancellations.set(uid,item);
19
+ }
20
+ const lines = [
21
+ "BEGIN:VCALENDAR",
22
+ "VERSION:2.0",
23
+ "PRODID:-//Vermeulen Solutions//Eventual RSVP//EN",
24
+ "CALSCALE:GREGORIAN",
25
+ "METHOD:PUBLISH",
26
+ `X-WR-CALNAME:${escapeText(calendarName || "Eventual RSVP")}`,
27
+ ...events.flatMap((event) => eventLines(event, host, generatedAt)),
28
+ ...[...uniqueCancellations.values()].flatMap((item) => cancellationLines(item, host, generatedAt)),
29
+ "END:VCALENDAR",
30
+ ];
31
+ const result = `${lines.flatMap(foldLine).join("\r\n")}\r\n`;
32
+ if (utf8Encoder.encode(result).length > 4*1024*1024) reject('Calendar output exceeds 4 MiB; narrow the subscription.');
33
+ return result;
34
+ }
35
+
36
+ const utf8Encoder = new TextEncoder();
37
+
38
+ function eventLines(event: EventRecord, host: string, generatedAt: Date): string[] {
39
+ const modifiedAt = parseDate(event.updatedAt) ?? generatedAt;
40
+ const statusLine = `STATUS:${calendarStatus(event)}`;
41
+ const locationText = calendarLocation(event);
42
+ const eventUrl = calendarEventUrl({...event,externalUrl:event.publicUrl || event.externalUrl});
43
+ const description = portableTextToPlainText(event.description);
44
+ return [
45
+ "BEGIN:VEVENT",
46
+ `UID:${escapeText(eventUid(event, host))}`,
47
+ `DTSTAMP:${formatUtc(generatedAt)}`,
48
+ `LAST-MODIFIED:${formatUtc(modifiedAt)}`,
49
+ `SEQUENCE:${sequence(event.calendarSequence, modifiedAt)}`,
50
+ statusLine,
51
+ `SUMMARY:${escapeText(event.title)}`,
52
+ ...(description ? [`DESCRIPTION:${escapeText(description)}`] : []),
53
+ ...(locationText ? [`LOCATION:${escapeText(locationText)}`] : []),
54
+ ...(eventUrl ? [`URL:${eventUrl}`] : []),
55
+ ...(event.categories.length ? [`CATEGORIES:${event.categories.map(escapeText).join(",")}`] : []),
56
+ `X-EVENTUAL-TIMEZONE:${escapeText(event.timezone)}`,
57
+ ...dateLines(event.start, event.end, event.allDay),
58
+ "END:VEVENT",
59
+ ];
60
+ }
61
+
62
+ function cancellationLines(item: CalendarCancellation, host: string, generatedAt: Date): string[] {
63
+ const modifiedAt = parseDate(item.cancelledAt) ?? generatedAt;
64
+ return [
65
+ "BEGIN:VEVENT",
66
+ `UID:${escapeText(eventUid(item, host))}`,
67
+ `DTSTAMP:${formatUtc(generatedAt)}`,
68
+ `LAST-MODIFIED:${formatUtc(modifiedAt)}`,
69
+ `SEQUENCE:${sequence(item.calendarSequence, modifiedAt)}`,
70
+ "STATUS:CANCELLED",
71
+ "SUMMARY:Cancelled event",
72
+ `X-EVENTUAL-TIMEZONE:${escapeText(item.timezone)}`,
73
+ ...dateLines(item.start, item.end, item.allDay),
74
+ "END:VEVENT",
75
+ ];
76
+ }
77
+
78
+ function dateLines(start: string, end: string, allDay: boolean): string[] {
79
+ if (allDay) {
80
+ const exclusiveEnd = addDay(end.slice(0, 10));
81
+ return [
82
+ `DTSTART;VALUE=DATE:${start.slice(0, 10).replaceAll("-", "")}`,
83
+ `DTEND;VALUE=DATE:${exclusiveEnd.replaceAll("-", "")}`,
84
+ ];
85
+ }
86
+ const startDate = parseDate(start);
87
+ const endDate = parseDate(end);
88
+ return startDate && endDate
89
+ ? [`DTSTART:${formatUtc(startDate)}`, ...(endDate>startDate ? [`DTEND:${formatUtc(endDate)}`] : [])]
90
+ : [];
91
+ }
92
+
93
+ export function eventUid(
94
+ item: string | { id: string; translationGroup?: string; eventId?: string; calendarUid?: string },
95
+ host: string,
96
+ ): string {
97
+ let id = typeof item === "string" ? item : item.id;
98
+ if (typeof item !== "string" && item.id.startsWith("cancellation_") && item.eventId) {
99
+ id = item.eventId;
100
+ }
101
+ const translationGroup = typeof item === "string" ? undefined : item.translationGroup;
102
+
103
+ let stableId = id;
104
+ if (translationGroup) {
105
+ const hashIndex = id.indexOf("#");
106
+ const recurrencePart = hashIndex >= 0 ? id.slice(hashIndex) : "";
107
+ stableId = `eventual-${translationGroup}${recurrencePart}`;
108
+ }
109
+ const safeHost = host.trim().replace(/[^a-zA-Z0-9.-]/g, "-").toLowerCase() || "eventual.invalid";
110
+ if (typeof item !== 'string' && item.calendarUid) {
111
+ const split = item.calendarUid.lastIndexOf('@');
112
+ if (split < 1 || /[\r\n\u0000-\u0020]/.test(item.calendarUid)) reject('Invalid stored calendar UID.');
113
+ const recurrencePart = id.includes('#') ? encodeURIComponent(id.slice(id.indexOf('#'))) : '';
114
+ return item.calendarUid.slice(0,split) + recurrencePart + item.calendarUid.slice(split);
115
+ }
116
+ return `${encodeURIComponent(stableId)}@${safeHost}`;
117
+ }
118
+
119
+ function sequence(value: number | undefined, date: Date): number {
120
+ const result = value ?? Math.floor(date.getTime()/1000);
121
+ return Math.min(2147483647, Math.max(0, Math.floor(result)));
122
+ }
123
+
124
+ function escapeText(value: string): string {
125
+ return value
126
+ .replace(/\\/g, "\\\\")
127
+ .replace(/\r\n|\r|\n/g, "\\n")
128
+ .replace(/,/g, "\\,")
129
+ .replace(/;/g, "\\;")
130
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "");
131
+ }
132
+
133
+ function parseDate(value: string): Date | undefined {
134
+ const milliseconds = Date.parse(value);
135
+ return Number.isFinite(milliseconds) ? new Date(milliseconds) : undefined;
136
+ }
137
+
138
+ function formatUtc(date: Date): string {
139
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
140
+ }
141
+
142
+ function addDay(value: string): string {
143
+ const date = new Date(`${value}T00:00:00Z`);
144
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(date.getTime())) return value;
145
+ date.setUTCDate(date.getUTCDate() + 1);
146
+ return date.toISOString().slice(0, 10);
147
+ }
148
+
149
+ function foldLine(line: string): string[] {
150
+ const result: string[] = [];
151
+ let current = "";
152
+ let bytes = 0;
153
+ for (const character of line) {
154
+ const size = utf8Encoder.encode(character).length;
155
+ if (bytes + size > 75) {
156
+ result.push(current);
157
+ current = " ";
158
+ bytes = 1;
159
+ }
160
+ current += character;
161
+ bytes += size;
162
+ }
163
+ result.push(current);
164
+ return result;
165
+ }
@@ -0,0 +1,18 @@
1
+ const PUBLIC_EVENT_IMAGE_TYPES = new Set([
2
+ "image/avif",
3
+ "image/gif",
4
+ "image/jpeg",
5
+ "image/png",
6
+ "image/webp",
7
+ ]);
8
+
9
+ export const MAX_PUBLIC_EVENT_IMAGE_BYTES = 8 * 1024 * 1024;
10
+
11
+ export function isPublicEventImageType(mimeType: string): boolean {
12
+ return PUBLIC_EVENT_IMAGE_TYPES.has(mimeType.toLowerCase());
13
+ }
14
+
15
+ export function publicEventImageUrl(pluginId: string, eventId: string): string {
16
+ const query = new URLSearchParams({ eventId });
17
+ return `/_emdash/api/plugins/${encodeURIComponent(pluginId)}/publicEventImage?${query}`;
18
+ }