@openpeepshq/common 0.1.44 → 0.1.45

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 (47) hide show
  1. package/dist/lib/adminSections.d.ts +4 -0
  2. package/dist/lib/adminSections.js +5 -0
  3. package/dist/lib/capabilitiesHelpers.d.ts +7 -7
  4. package/dist/lib/capabilitiesHelpers.js +4 -11
  5. package/dist/lib/eventIcs.js +56 -2
  6. package/dist/lib/eventRecurrence.d.ts +30 -0
  7. package/dist/lib/eventRecurrence.js +279 -0
  8. package/dist/lib/eventTime.d.ts +22 -0
  9. package/dist/lib/eventTime.js +127 -0
  10. package/dist/lib/groupHelpers.d.ts +63 -41
  11. package/dist/lib/groupHelpers.js +155 -45
  12. package/dist/lib/groupTemplateHelpers.d.ts +16 -0
  13. package/dist/lib/groupTemplateHelpers.js +51 -0
  14. package/dist/lib/index.d.ts +4 -0
  15. package/dist/lib/index.js +4 -0
  16. package/dist/lib/jamHelpers.d.ts +28 -2
  17. package/dist/lib/jamHelpers.js +56 -8
  18. package/dist/lib/markdownHelpers.d.ts +14 -0
  19. package/dist/lib/markdownHelpers.js +41 -0
  20. package/dist/lib/postHelpers.d.ts +22 -6
  21. package/dist/lib/postHelpers.js +49 -10
  22. package/dist/lib/pushHelpers.d.ts +3 -1
  23. package/dist/lib/pushHelpers.js +13 -0
  24. package/dist/lib/ssoLoginUrl.d.ts +24 -0
  25. package/dist/lib/ssoLoginUrl.js +75 -0
  26. package/dist/lib/text.d.ts +2 -0
  27. package/dist/lib/text.js +2 -0
  28. package/dist/lib/tokenHelpers.d.ts +5 -0
  29. package/dist/lib/tokenHelpers.js +19 -0
  30. package/dist/types/api.d.ts +2384 -350
  31. package/dist/types/api.js +43 -13
  32. package/dist/types/auth.d.ts +2 -7
  33. package/dist/types/capabilities.d.ts +11 -4
  34. package/dist/types/capabilities.js +44 -1
  35. package/dist/types/config.d.ts +15 -24
  36. package/dist/types/config.js +10 -8
  37. package/dist/types/db.d.ts +738 -66
  38. package/dist/types/db.js +3 -3
  39. package/dist/types/internal.d.ts +6189 -2604
  40. package/dist/types/internal.js +10 -1
  41. package/dist/types/models.d.ts +280 -9
  42. package/dist/types/models.js +59 -5
  43. package/dist/types/notifications.d.ts +1 -0
  44. package/dist/types/plugins.d.ts +21 -1
  45. package/dist/types/plugins.js +9 -1
  46. package/dist/types/stats.d.ts +1284 -184
  47. package/package.json +1 -1
@@ -32,6 +32,10 @@ export declare const adminSections: readonly [{
32
32
  readonly key: "apiKeys";
33
33
  readonly path: "/admin/api-keys";
34
34
  readonly capabilities: readonly ["core-serviceTokens-read"];
35
+ }, {
36
+ readonly key: "plugins";
37
+ readonly path: "/admin/plugins";
38
+ readonly capabilities: readonly ["core-plugins-manage"];
35
39
  }, {
36
40
  readonly key: "configuration";
37
41
  readonly path: "/admin/configuration";
@@ -40,6 +40,11 @@ export const adminSections = [
40
40
  path: '/admin/api-keys',
41
41
  capabilities: ['core-serviceTokens-read'],
42
42
  },
43
+ {
44
+ key: 'plugins',
45
+ path: '/admin/plugins',
46
+ capabilities: ['core-plugins-manage'],
47
+ },
43
48
  {
44
49
  key: 'configuration',
45
50
  path: '/admin/configuration',
@@ -37,7 +37,7 @@ export declare const checkGroupCapabilities: (authData: AuthorizationData, neede
37
37
  missingCapabilities: string[];
38
38
  missingScope: {
39
39
  resource: {
40
- type: "self" | "db" | "jams" | "profiles" | "*" | "jam" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
40
+ type: "self" | "db" | "jams" | "profiles" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
41
41
  id?: string | undefined;
42
42
  };
43
43
  scopeLevel?: "admin" | "write" | "read" | undefined;
@@ -48,7 +48,7 @@ export declare const checkPostCapabilities: (authData: AuthorizationData, needed
48
48
  missingCapabilities: string[];
49
49
  missingScope: {
50
50
  resource: {
51
- type: "self" | "db" | "jams" | "profiles" | "*" | "jam" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
51
+ type: "self" | "db" | "jams" | "profiles" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
52
52
  id?: string | undefined;
53
53
  };
54
54
  scopeLevel?: "admin" | "write" | "read" | undefined;
@@ -59,7 +59,7 @@ export declare const checkProfileCapabilities: (authData: AuthorizationData, nee
59
59
  missingCapabilities: string[];
60
60
  missingScope: {
61
61
  resource: {
62
- type: "self" | "db" | "jams" | "profiles" | "*" | "jam" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
62
+ type: "self" | "db" | "jams" | "profiles" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
63
63
  id?: string | undefined;
64
64
  };
65
65
  scopeLevel?: "admin" | "write" | "read" | undefined;
@@ -70,7 +70,7 @@ export declare const checkReportCapabilities: (authData: AuthorizationData, need
70
70
  missingCapabilities: string[];
71
71
  missingScope: {
72
72
  resource: {
73
- type: "self" | "db" | "jams" | "profiles" | "*" | "jam" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
73
+ type: "self" | "db" | "jams" | "profiles" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
74
74
  id?: string | undefined;
75
75
  };
76
76
  scopeLevel?: "admin" | "write" | "read" | undefined;
@@ -81,7 +81,7 @@ export declare const checkAccessTokenCapabilities: (authData: AuthorizationData,
81
81
  missingCapabilities: string[];
82
82
  missingScope: {
83
83
  resource: {
84
- type: "self" | "db" | "jams" | "profiles" | "*" | "jam" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
84
+ type: "self" | "db" | "jams" | "profiles" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
85
85
  id?: string | undefined;
86
86
  };
87
87
  scopeLevel?: "admin" | "write" | "read" | undefined;
@@ -92,7 +92,7 @@ export declare const checkAccountCapabilities: (authData: AuthorizationData, nee
92
92
  missingCapabilities: string[];
93
93
  missingScope: {
94
94
  resource: {
95
- type: "self" | "db" | "jams" | "profiles" | "*" | "jam" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
95
+ type: "self" | "db" | "jams" | "profiles" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
96
96
  id?: string | undefined;
97
97
  };
98
98
  scopeLevel?: "admin" | "write" | "read" | undefined;
@@ -110,7 +110,7 @@ export declare const checkAccountCreateAuthorization: (authData: AuthorizationDa
110
110
  missingCapabilities: string[];
111
111
  missingScope: {
112
112
  resource: {
113
- type: "self" | "db" | "jams" | "profiles" | "*" | "jam" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
113
+ type: "self" | "db" | "jams" | "profiles" | "*" | "notifications" | "posts" | "groups" | "reports" | "webhooks" | "analytics" | "render";
114
114
  id?: string | undefined;
115
115
  };
116
116
  scopeLevel?: "admin" | "write" | "read" | undefined;
@@ -53,17 +53,10 @@ export const localOrNone = (authData) => {
53
53
  return ['none'];
54
54
  };
55
55
  export const getGroupRelationships = (authData, group) => {
56
- var _a, _b;
57
- const { profile } = authData;
58
- if (profile) {
59
- return [
60
- 'local',
61
- 'none',
62
- ...((_b = (_a = profile.memberships.find((m) => m.group.id === group.id)) === null || _a === void 0 ? void 0 : _a.roles) !== null && _b !== void 0 ? _b : []),
63
- ];
64
- }
65
- if (authData.service) {
66
- return ['local', 'none'];
56
+ var _a, _b, _c;
57
+ const membershipRoles = (_c = (_b = (_a = authData.profile) === null || _a === void 0 ? void 0 : _a.memberships.find((m) => m.group.id === group.id)) === null || _b === void 0 ? void 0 : _b.roles) !== null && _c !== void 0 ? _c : [];
58
+ if (authData.profile || authData.service) {
59
+ return [...localOrNone(authData), ...membershipRoles];
67
60
  }
68
61
  return ['none'];
69
62
  };
@@ -1,4 +1,4 @@
1
- import ical, { ICalCalendarMethod } from 'ical-generator';
1
+ import ical, { ICalCalendarMethod, ICalEventRepeatingFreq, ICalWeekday, } from 'ical-generator';
2
2
  import { getJamUrl } from './jamHelpers.js';
3
3
  const utcDateFromYmd = (yyyyMmDd) => {
4
4
  const [y, m, d] = yyyyMmDd.split('-').map(Number);
@@ -35,8 +35,41 @@ const eventLocation = (post, event, postUrl) => {
35
35
  }
36
36
  return ((_c = event.url) === null || _c === void 0 ? void 0 : _c.trim()) || undefined;
37
37
  };
38
+ const repeatingFreq = {
39
+ DAILY: ICalEventRepeatingFreq.DAILY,
40
+ WEEKLY: ICalEventRepeatingFreq.WEEKLY,
41
+ MONTHLY: ICalEventRepeatingFreq.MONTHLY,
42
+ };
43
+ const repeatingWeekday = {
44
+ MO: ICalWeekday.MO,
45
+ TU: ICalWeekday.TU,
46
+ WE: ICalWeekday.WE,
47
+ TH: ICalWeekday.TH,
48
+ FR: ICalWeekday.FR,
49
+ SA: ICalWeekday.SA,
50
+ SU: ICalWeekday.SU,
51
+ };
52
+ const repeatingOptions = (event) => {
53
+ var _a, _b, _c;
54
+ const recurrence = event.recurrence;
55
+ if (!recurrence)
56
+ return undefined;
57
+ const exclude = ((_a = event.exceptions) !== null && _a !== void 0 ? _a : [])
58
+ .filter((exception) => exception.cancelled)
59
+ .map((exception) => new Date(exception.recurrenceId));
60
+ return {
61
+ freq: repeatingFreq[recurrence.freq],
62
+ interval: (_b = recurrence.interval) !== null && _b !== void 0 ? _b : 1,
63
+ ...(((_c = recurrence.byDay) === null || _c === void 0 ? void 0 : _c.length)
64
+ ? { byDay: recurrence.byDay.map((day) => repeatingWeekday[day]) }
65
+ : {}),
66
+ ...(recurrence.until ? { until: new Date(recurrence.until) } : {}),
67
+ ...(recurrence.count ? { count: recurrence.count } : {}),
68
+ ...(exclude.length ? { exclude } : {}),
69
+ };
70
+ };
38
71
  export const buildEventIcs = (post, options) => {
39
- var _a, _b, _c, _d, _e, _f;
72
+ var _a, _b, _c, _d, _e, _f, _g;
40
73
  if (post.type !== 'event' || ((_a = post.data) === null || _a === void 0 ? void 0 : _a.type) !== 'event') {
41
74
  return null;
42
75
  }
@@ -50,6 +83,7 @@ export const buildEventIcs = (post, options) => {
50
83
  const summary = ((_c = event.name) === null || _c === void 0 ? void 0 : _c.trim()) || 'Event';
51
84
  const description = (_d = event.content) === null || _d === void 0 ? void 0 : _d.trim();
52
85
  const location = eventLocation(post, event, options === null || options === void 0 ? void 0 : options.postUrl);
86
+ const repeating = repeatingOptions(event);
53
87
  if (event.wholeDay) {
54
88
  const startYmd = event.start.slice(0, 10);
55
89
  const lastInclusiveYmd = (_f = (_e = event.end) === null || _e === void 0 ? void 0 : _e.slice(0, 10)) !== null && _f !== void 0 ? _f : startYmd;
@@ -62,6 +96,7 @@ export const buildEventIcs = (post, options) => {
62
96
  ...(description ? { description } : {}),
63
97
  ...(location ? { location } : {}),
64
98
  ...(link ? { url: link } : {}),
99
+ ...(repeating ? { repeating } : {}),
65
100
  });
66
101
  }
67
102
  else {
@@ -77,6 +112,25 @@ export const buildEventIcs = (post, options) => {
77
112
  ...(description ? { description } : {}),
78
113
  ...(location ? { location } : {}),
79
114
  ...(link ? { url: link } : {}),
115
+ ...(repeating ? { repeating } : {}),
116
+ });
117
+ }
118
+ for (const exception of (_g = event.exceptions) !== null && _g !== void 0 ? _g : []) {
119
+ if (exception.cancelled || !exception.start)
120
+ continue;
121
+ const start = new Date(exception.start);
122
+ const end = exception.end
123
+ ? new Date(exception.end)
124
+ : new Date(start.getTime() + 60 * 60 * 1000);
125
+ calendar.createEvent({
126
+ id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
127
+ start,
128
+ end,
129
+ summary,
130
+ ...(description ? { description } : {}),
131
+ ...(location ? { location } : {}),
132
+ ...(link ? { url: link } : {}),
133
+ recurrenceId: new Date(exception.recurrenceId),
80
134
  });
81
135
  }
82
136
  return calendar.toString() + '\r\n';
@@ -0,0 +1,30 @@
1
+ import type { Event, EventOccurrenceException, EventRecurrence, RecurrenceWeekday } from '../types';
2
+ export type EventRecurrenceTranslate = (key: string, options?: {
3
+ defaultValue?: string;
4
+ [key: string]: string | number | undefined;
5
+ }) => string;
6
+ export declare const OCCURRENCE_HORIZON_MS: number;
7
+ export type ExpandedOccurrence = {
8
+ recurrenceId: string;
9
+ start: string;
10
+ end?: string;
11
+ cancelled: boolean;
12
+ };
13
+ export declare const normalizeRecurrenceId: (value: string) => string;
14
+ export declare const sameRecurrenceId: (a?: string, b?: string) => boolean;
15
+ export declare const isRecurringEvent: (event: Event) => boolean;
16
+ export declare const eventDurationMs: (event: Event) => number | undefined;
17
+ export declare const weekdayFromDate: (date: Date) => RecurrenceWeekday;
18
+ export declare const parseOccurrenceQuery: (value?: string | null) => string | undefined;
19
+ export declare const expandEventOccurrences: (event: Event, window: {
20
+ from: Date;
21
+ to: Date;
22
+ }) => ExpandedOccurrence[];
23
+ export declare const occurrencesForIndex: (event: Event, now?: Date) => ExpandedOccurrence[];
24
+ export declare const previewUpcomingOccurrences: (event: Event, count?: number, now?: Date) => ExpandedOccurrence[];
25
+ export declare const effectiveEventTimes: (event: Event, recurrenceId?: string) => {
26
+ start: string;
27
+ end?: string;
28
+ };
29
+ export declare const upsertEventException: (event: Event, exception: EventOccurrenceException) => Event;
30
+ export declare const formatEventRecurrence: (recurrence: EventRecurrence | undefined, t: EventRecurrenceTranslate, start?: string) => string;
@@ -0,0 +1,279 @@
1
+ import { addDays, addMonths, addWeeks, differenceInCalendarWeeks, getDay, } from 'date-fns';
2
+ const WEEKDAY_ORDER = [
3
+ 'MO',
4
+ 'TU',
5
+ 'WE',
6
+ 'TH',
7
+ 'FR',
8
+ 'SA',
9
+ 'SU',
10
+ ];
11
+ export const OCCURRENCE_HORIZON_MS = 365 * 24 * 60 * 60 * 1000;
12
+ const WEEKDAY_INDEX = {
13
+ SU: 0,
14
+ MO: 1,
15
+ TU: 2,
16
+ WE: 3,
17
+ TH: 4,
18
+ FR: 5,
19
+ SA: 6,
20
+ };
21
+ const INDEX_WEEKDAY = [
22
+ 'SU',
23
+ 'MO',
24
+ 'TU',
25
+ 'WE',
26
+ 'TH',
27
+ 'FR',
28
+ 'SA',
29
+ ];
30
+ export const normalizeRecurrenceId = (value) => {
31
+ const date = new Date(value);
32
+ if (Number.isNaN(date.getTime())) {
33
+ return value;
34
+ }
35
+ return date.toISOString();
36
+ };
37
+ export const sameRecurrenceId = (a, b) => {
38
+ if (!a || !b)
39
+ return false;
40
+ return normalizeRecurrenceId(a) === normalizeRecurrenceId(b);
41
+ };
42
+ export const isRecurringEvent = (event) => !!event.recurrence;
43
+ export const eventDurationMs = (event) => {
44
+ if (!event.end)
45
+ return undefined;
46
+ const ms = new Date(event.end).getTime() - new Date(event.start).getTime();
47
+ return Number.isFinite(ms) && ms >= 0 ? ms : undefined;
48
+ };
49
+ const toIso = (date) => date.toISOString();
50
+ const applyDuration = (start, durationMs) => {
51
+ if (durationMs == null)
52
+ return undefined;
53
+ return toIso(new Date(start.getTime() + durationMs));
54
+ };
55
+ const exceptionById = (event) => {
56
+ var _a;
57
+ const map = new Map();
58
+ for (const exception of (_a = event.exceptions) !== null && _a !== void 0 ? _a : []) {
59
+ map.set(normalizeRecurrenceId(exception.recurrenceId), exception);
60
+ }
61
+ return map;
62
+ };
63
+ export const weekdayFromDate = (date) => INDEX_WEEKDAY[getDay(date)];
64
+ export const parseOccurrenceQuery = (value) => {
65
+ if (!value)
66
+ return undefined;
67
+ const date = new Date(value);
68
+ if (Number.isNaN(date.getTime()))
69
+ return undefined;
70
+ return date.toISOString();
71
+ };
72
+ const nextByFreq = (date, freq, interval) => {
73
+ if (freq === 'DAILY')
74
+ return addDays(date, interval);
75
+ if (freq === 'WEEKLY')
76
+ return addWeeks(date, interval);
77
+ return addMonths(date, interval);
78
+ };
79
+ const generateRawStarts = (event, untilBound) => {
80
+ var _a, _b, _c;
81
+ const recurrence = event.recurrence;
82
+ const dtstart = new Date(event.start);
83
+ if (!recurrence) {
84
+ return [dtstart];
85
+ }
86
+ const interval = (_a = recurrence.interval) !== null && _a !== void 0 ? _a : 1;
87
+ const until = recurrence.until ? new Date(recurrence.until) : undefined;
88
+ const hardStop = until && until < untilBound ? until : untilBound;
89
+ const starts = [];
90
+ const pushIfValid = (date) => {
91
+ if (date.getTime() < dtstart.getTime())
92
+ return;
93
+ if (date.getTime() > hardStop.getTime())
94
+ return;
95
+ starts.push(date);
96
+ };
97
+ if (recurrence.freq === 'WEEKLY' && ((_c = (_b = recurrence.byDay) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) > 0) {
98
+ const byDays = new Set(recurrence.byDay);
99
+ let cursor = dtstart;
100
+ while (cursor.getTime() <= hardStop.getTime()) {
101
+ if (byDays.has(weekdayFromDate(cursor)) &&
102
+ differenceInCalendarWeeks(cursor, dtstart) % interval === 0) {
103
+ pushIfValid(cursor);
104
+ }
105
+ if (recurrence.count && starts.length >= recurrence.count)
106
+ break;
107
+ cursor = addDays(cursor, 1);
108
+ }
109
+ }
110
+ else {
111
+ let cursor = dtstart;
112
+ while (cursor.getTime() <= hardStop.getTime()) {
113
+ pushIfValid(cursor);
114
+ if (recurrence.count && starts.length >= recurrence.count)
115
+ break;
116
+ cursor = nextByFreq(cursor, recurrence.freq, interval);
117
+ }
118
+ }
119
+ const unique = [
120
+ ...new Map(starts.map((date) => [date.getTime(), date])).values(),
121
+ ].sort((a, b) => a.getTime() - b.getTime());
122
+ return recurrence.count ? unique.slice(0, recurrence.count) : unique;
123
+ };
124
+ const decorateOccurrence = (originalStart, event, exceptions, durationMs) => {
125
+ var _a, _b, _c;
126
+ const recurrenceId = toIso(originalStart);
127
+ const exception = exceptions.get(recurrenceId);
128
+ if (exception === null || exception === void 0 ? void 0 : exception.cancelled) {
129
+ return {
130
+ recurrenceId,
131
+ start: (_a = exception.start) !== null && _a !== void 0 ? _a : recurrenceId,
132
+ end: (_b = exception.end) !== null && _b !== void 0 ? _b : applyDuration(originalStart, durationMs),
133
+ cancelled: true,
134
+ };
135
+ }
136
+ if (exception === null || exception === void 0 ? void 0 : exception.start) {
137
+ const start = new Date(exception.start);
138
+ return {
139
+ recurrenceId,
140
+ start: toIso(start),
141
+ end: (_c = exception.end) !== null && _c !== void 0 ? _c : applyDuration(start, durationMs),
142
+ cancelled: false,
143
+ };
144
+ }
145
+ return {
146
+ recurrenceId,
147
+ start: recurrenceId,
148
+ end: applyDuration(originalStart, durationMs),
149
+ cancelled: false,
150
+ };
151
+ };
152
+ export const expandEventOccurrences = (event, window) => {
153
+ const durationMs = eventDurationMs(event);
154
+ const exceptions = exceptionById(event);
155
+ const rawStarts = generateRawStarts(event, window.to);
156
+ return rawStarts
157
+ .map((start) => decorateOccurrence(start, event, exceptions, durationMs))
158
+ .filter((occurrence) => {
159
+ const start = new Date(occurrence.start);
160
+ const end = occurrence.end ? new Date(occurrence.end) : start;
161
+ return end >= window.from && start <= window.to;
162
+ });
163
+ };
164
+ export const occurrencesForIndex = (event, now = new Date()) => {
165
+ if (!event.recurrence) {
166
+ return [
167
+ {
168
+ recurrenceId: normalizeRecurrenceId(event.start),
169
+ start: normalizeRecurrenceId(event.start),
170
+ end: event.end ? normalizeRecurrenceId(event.end) : undefined,
171
+ cancelled: false,
172
+ },
173
+ ];
174
+ }
175
+ return expandEventOccurrences(event, {
176
+ from: new Date(now.getTime() - OCCURRENCE_HORIZON_MS),
177
+ to: new Date(now.getTime() + OCCURRENCE_HORIZON_MS),
178
+ });
179
+ };
180
+ export const previewUpcomingOccurrences = (event, count = 3, now = new Date()) => expandEventOccurrences(event, {
181
+ from: now,
182
+ to: new Date(now.getTime() + OCCURRENCE_HORIZON_MS),
183
+ })
184
+ .filter((occurrence) => !occurrence.cancelled)
185
+ .slice(0, count);
186
+ export const effectiveEventTimes = (event, recurrenceId) => {
187
+ if (!recurrenceId) {
188
+ return { start: event.start, end: event.end };
189
+ }
190
+ const window = {
191
+ from: new Date(new Date(recurrenceId).getTime() - OCCURRENCE_HORIZON_MS),
192
+ to: new Date(new Date(recurrenceId).getTime() + OCCURRENCE_HORIZON_MS),
193
+ };
194
+ const match = expandEventOccurrences(event, window).find((occurrence) => sameRecurrenceId(occurrence.recurrenceId, recurrenceId));
195
+ if (!match || match.cancelled) {
196
+ return { start: event.start, end: event.end };
197
+ }
198
+ return { start: match.start, end: match.end };
199
+ };
200
+ export const upsertEventException = (event, exception) => {
201
+ var _a;
202
+ const recurrenceId = normalizeRecurrenceId(exception.recurrenceId);
203
+ const rest = ((_a = event.exceptions) !== null && _a !== void 0 ? _a : []).filter((existing) => !sameRecurrenceId(existing.recurrenceId, recurrenceId));
204
+ return {
205
+ ...event,
206
+ exceptions: [...rest, { ...exception, recurrenceId }],
207
+ };
208
+ };
209
+ const sortWeekdays = (days) => [...days].sort((a, b) => WEEKDAY_ORDER.indexOf(a) - WEEKDAY_ORDER.indexOf(b));
210
+ const formatUntilDate = (until) => new Date(until).toLocaleDateString(undefined, {
211
+ month: 'short',
212
+ day: 'numeric',
213
+ year: 'numeric',
214
+ });
215
+ const formatWeekdayLabels = (days, t) => sortWeekdays(days)
216
+ .map((day) => t(`events.form.repeat.day.${day}`, { defaultValue: day }))
217
+ .join(', ');
218
+ const formatRecurrencePattern = (recurrence, t, start) => {
219
+ var _a, _b;
220
+ const interval = (_a = recurrence.interval) !== null && _a !== void 0 ? _a : 1;
221
+ if (recurrence.freq === 'DAILY') {
222
+ return interval === 1
223
+ ? t('events.repeat.daily', { defaultValue: 'Daily' })
224
+ : t('events.repeat.everyNDays', {
225
+ defaultValue: 'Every {{count}} days',
226
+ count: interval,
227
+ });
228
+ }
229
+ if (recurrence.freq === 'MONTHLY') {
230
+ return interval === 1
231
+ ? t('events.repeat.monthly', { defaultValue: 'Monthly' })
232
+ : t('events.repeat.everyNMonths', {
233
+ defaultValue: 'Every {{count}} months',
234
+ count: interval,
235
+ });
236
+ }
237
+ const days = ((_b = recurrence.byDay) === null || _b === void 0 ? void 0 : _b.length) && recurrence.byDay.length > 0
238
+ ? recurrence.byDay
239
+ : start
240
+ ? [weekdayFromDate(new Date(start))]
241
+ : [];
242
+ const dayLabels = formatWeekdayLabels(days, t);
243
+ if (dayLabels) {
244
+ return interval === 1
245
+ ? t('events.repeat.weeklyOn', {
246
+ defaultValue: 'Weekly on {{days}}',
247
+ days: dayLabels,
248
+ })
249
+ : t('events.repeat.everyNWeeksOn', {
250
+ defaultValue: 'Every {{count}} weeks on {{days}}',
251
+ count: interval,
252
+ days: dayLabels,
253
+ });
254
+ }
255
+ return interval === 1
256
+ ? t('events.repeat.weekly', { defaultValue: 'Weekly' })
257
+ : t('events.repeat.everyNWeeks', {
258
+ defaultValue: 'Every {{count}} weeks',
259
+ count: interval,
260
+ });
261
+ };
262
+ export const formatEventRecurrence = (recurrence, t, start) => {
263
+ if (!recurrence)
264
+ return '';
265
+ const pattern = formatRecurrencePattern(recurrence, t, start);
266
+ if (recurrence.until) {
267
+ return `${pattern} ${t('events.repeat.until', {
268
+ defaultValue: 'until {{date}}',
269
+ date: formatUntilDate(recurrence.until),
270
+ })}`;
271
+ }
272
+ if (recurrence.count) {
273
+ return `${pattern}, ${t('events.repeat.times', {
274
+ defaultValue: '{{count}} times',
275
+ count: recurrence.count,
276
+ })}`;
277
+ }
278
+ return pattern;
279
+ };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Interpret a datetime-local wall clock (`YYYY-MM-DDTHH:mm`) in `timeZone`
3
+ * and return a UTC ISO string.
4
+ */
5
+ export declare const zonedDateTimeToUtcIso: (local: string, timeZone: string) => string | undefined;
6
+ /** Format a UTC ISO instant as a datetime-local string in `timeZone`. */
7
+ export declare const utcIsoToZonedDateTime: (iso: string, timeZone: string) => string;
8
+ /**
9
+ * Keep the wall-clock time of `iso` (as seen in `fromTimeZone`) and express
10
+ * that same clock time in `toTimeZone`.
11
+ */
12
+ export declare const reinterpretIsoInTimeZone: (iso: string | undefined, fromTimeZone: string, toTimeZone: string) => string | undefined;
13
+ /** Build a Date whose local components match `iso` as seen in `timeZone`. */
14
+ export declare const utcIsoToWallClockDate: (iso: string, timeZone: string) => Date;
15
+ /** Treat `date`'s local components as wall time in `timeZone`. */
16
+ export declare const wallClockDateToUtcIso: (date: Date, timeZone: string) => string;
17
+ export declare const formatEventWhen: (start: string, options?: {
18
+ end?: string | null;
19
+ timeZone?: string | null;
20
+ allDay?: boolean;
21
+ locale?: string;
22
+ }) => string;
@@ -0,0 +1,127 @@
1
+ const DATETIME_LOCAL_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/;
2
+ const partNumber = (parts, type) => { var _a; return Number((_a = parts.find((part) => part.type === type)) === null || _a === void 0 ? void 0 : _a.value); };
3
+ /** Milliseconds to add to UTC to get wall time in `timeZone` at `utcMs`. */
4
+ const tzOffsetMs = (utcMs, timeZone) => {
5
+ const parts = new Intl.DateTimeFormat('en-US', {
6
+ timeZone,
7
+ year: 'numeric',
8
+ month: '2-digit',
9
+ day: '2-digit',
10
+ hour: '2-digit',
11
+ minute: '2-digit',
12
+ second: '2-digit',
13
+ hourCycle: 'h23',
14
+ }).formatToParts(new Date(utcMs));
15
+ const hour = partNumber(parts, 'hour');
16
+ const asUtc = Date.UTC(partNumber(parts, 'year'), partNumber(parts, 'month') - 1, partNumber(parts, 'day'), hour === 24 ? 0 : hour, partNumber(parts, 'minute'), partNumber(parts, 'second'));
17
+ return asUtc - utcMs;
18
+ };
19
+ const pad2 = (value) => String(value).padStart(2, '0');
20
+ /**
21
+ * Interpret a datetime-local wall clock (`YYYY-MM-DDTHH:mm`) in `timeZone`
22
+ * and return a UTC ISO string.
23
+ */
24
+ export const zonedDateTimeToUtcIso = (local, timeZone) => {
25
+ var _a;
26
+ if (!local)
27
+ return undefined;
28
+ const match = DATETIME_LOCAL_RE.exec(local);
29
+ if (!match) {
30
+ const parsed = new Date(local);
31
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString();
32
+ }
33
+ const utcGuess = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), Number((_a = match[6]) !== null && _a !== void 0 ? _a : 0));
34
+ try {
35
+ const offset = tzOffsetMs(utcGuess, timeZone);
36
+ const utcWithOffset = utcGuess - offset;
37
+ const offsetAtResult = tzOffsetMs(utcWithOffset, timeZone);
38
+ const utc = offsetAtResult === offset ? utcWithOffset : utcGuess - offsetAtResult;
39
+ return new Date(utc).toISOString();
40
+ }
41
+ catch {
42
+ return new Date(utcGuess).toISOString();
43
+ }
44
+ };
45
+ /** Format a UTC ISO instant as a datetime-local string in `timeZone`. */
46
+ export const utcIsoToZonedDateTime = (iso, timeZone) => {
47
+ const date = new Date(iso);
48
+ if (Number.isNaN(date.getTime()))
49
+ return '';
50
+ try {
51
+ const parts = new Intl.DateTimeFormat('en-US', {
52
+ timeZone,
53
+ year: 'numeric',
54
+ month: '2-digit',
55
+ day: '2-digit',
56
+ hour: '2-digit',
57
+ minute: '2-digit',
58
+ hourCycle: 'h23',
59
+ }).formatToParts(date);
60
+ const hour = partNumber(parts, 'hour');
61
+ const y = partNumber(parts, 'year');
62
+ const month = pad2(partNumber(parts, 'month'));
63
+ const day = pad2(partNumber(parts, 'day'));
64
+ const hh = pad2(hour === 24 ? 0 : hour);
65
+ const mm = pad2(partNumber(parts, 'minute'));
66
+ return `${y}-${month}-${day}T${hh}:${mm}`;
67
+ }
68
+ catch {
69
+ return '';
70
+ }
71
+ };
72
+ /**
73
+ * Keep the wall-clock time of `iso` (as seen in `fromTimeZone`) and express
74
+ * that same clock time in `toTimeZone`.
75
+ */
76
+ export const reinterpretIsoInTimeZone = (iso, fromTimeZone, toTimeZone) => {
77
+ if (!iso)
78
+ return undefined;
79
+ if (fromTimeZone === toTimeZone)
80
+ return iso;
81
+ const wall = utcIsoToZonedDateTime(iso, fromTimeZone);
82
+ return wall ? zonedDateTimeToUtcIso(wall, toTimeZone) : iso;
83
+ };
84
+ /** Build a Date whose local components match `iso` as seen in `timeZone`. */
85
+ export const utcIsoToWallClockDate = (iso, timeZone) => {
86
+ const local = utcIsoToZonedDateTime(iso, timeZone);
87
+ if (!local)
88
+ return new Date(iso);
89
+ const [datePart, timePart] = local.split('T');
90
+ const [year, month, day] = datePart.split('-').map(Number);
91
+ const [hour, minute] = timePart.split(':').map(Number);
92
+ return new Date(year, month - 1, day, hour, minute);
93
+ };
94
+ /** Treat `date`'s local components as wall time in `timeZone`. */
95
+ export const wallClockDateToUtcIso = (date, timeZone) => {
96
+ var _a;
97
+ const local = `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}T${pad2(date.getHours())}:${pad2(date.getMinutes())}`;
98
+ return (_a = zonedDateTimeToUtcIso(local, timeZone)) !== null && _a !== void 0 ? _a : date.toISOString();
99
+ };
100
+ export const formatEventWhen = (start, options) => {
101
+ const timeZone = (options === null || options === void 0 ? void 0 : options.timeZone) || undefined;
102
+ const dateOptions = {
103
+ weekday: 'long',
104
+ year: 'numeric',
105
+ month: 'long',
106
+ day: 'numeric',
107
+ ...(timeZone ? { timeZone } : {}),
108
+ };
109
+ if (options === null || options === void 0 ? void 0 : options.allDay) {
110
+ const startLabel = new Date(start).toLocaleDateString(options.locale, dateOptions);
111
+ if (!options.end)
112
+ return startLabel;
113
+ const endLabel = new Date(options.end).toLocaleDateString(options.locale, dateOptions);
114
+ return `${startLabel} – ${endLabel}`;
115
+ }
116
+ const dateTimeOptions = {
117
+ ...dateOptions,
118
+ hour: '2-digit',
119
+ minute: '2-digit',
120
+ ...(timeZone ? { timeZoneName: 'short' } : {}),
121
+ };
122
+ const startLabel = new Date(start).toLocaleString(options === null || options === void 0 ? void 0 : options.locale, dateTimeOptions);
123
+ if (!(options === null || options === void 0 ? void 0 : options.end))
124
+ return startLabel;
125
+ const endLabel = new Date(options.end).toLocaleString(options.locale, dateTimeOptions);
126
+ return `${startLabel} – ${endLabel}`;
127
+ };