@ismou-workspace/calendar-contracts 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,16 @@
1
- # Temporary Holding Version
1
+ # @ismou-workspace/calendar-contracts
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `calendar.*` entity types of Ismou's Calendar app (calendars, events and their occurrences, birthdays), and the DTOs of its API.
4
+
5
+ Published by the [calendar](https://github.com/ismou-workspace/calendar) app for the apps that use its entities: apps never know each other, the entities come through the core, and these types describe them.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add @ismou-workspace/calendar-contracts
11
+ ```
12
+
13
+ ## Documentation
14
+
15
+ - [The platform's documentation](https://github.com/ismou-workspace/sdk/tree/main/docs): architecture, conventions, design system.
16
+ - [Source](https://github.com/ismou-workspace/calendar/tree/main/contracts)
@@ -0,0 +1,17 @@
1
+ import type { InstantRange, OccurrenceTime } from './occurrences.ts';
2
+ /** What a birthday is read from: a contact's data has it. */
3
+ export interface WithBirthday {
4
+ /** `YYYY-MM-DD`; the year may be a guess, the month and day are what count. */
5
+ birthday: string | null;
6
+ }
7
+ /** One year's birthday of someone, as a whole day of the viewer's time zone. */
8
+ export interface BirthdayOccurrence<Person extends WithBirthday> extends OccurrenceTime {
9
+ person: Person;
10
+ year: number;
11
+ }
12
+ /**
13
+ * The birthdays of `people` overlapping `[from, to)`, each a whole day of `timeZone` (the
14
+ * viewer's: a birthday is the same date everywhere), by start. February 29th falls on the
15
+ * 28th in other years.
16
+ */
17
+ export declare function birthdaysInRange<Person extends WithBirthday>(people: readonly Person[], { from, to }: InstantRange, timeZone: string): BirthdayOccurrence<Person>[];
@@ -0,0 +1,25 @@
1
+ import { TZDate } from '@date-fns/tz';
2
+ /**
3
+ * The birthdays of `people` overlapping `[from, to)`, each a whole day of `timeZone` (the
4
+ * viewer's: a birthday is the same date everywhere), by start. February 29th falls on the
5
+ * 28th in other years.
6
+ */
7
+ export function birthdaysInRange(people, { from, to }, timeZone) {
8
+ const firstYear = new TZDate(from.getTime(), timeZone).getFullYear();
9
+ const lastYear = new TZDate(to.getTime(), timeZone).getFullYear();
10
+ const occurrences = [];
11
+ for (const person of people) {
12
+ const [, month, day] = person.birthday?.split('-').map(Number) ?? [];
13
+ if (!month || !day)
14
+ continue;
15
+ for (let year = firstYear; year <= lastYear; year++) {
16
+ const leap = new Date(Date.UTC(year, 1, 29)).getUTCMonth() === 1;
17
+ const date = month === 2 && day === 29 && !leap ? 28 : day;
18
+ const start = new Date(new TZDate(year, month - 1, date, timeZone).getTime());
19
+ const end = new Date(new TZDate(year, month - 1, date + 1, timeZone).getTime());
20
+ if (start < to && end > from)
21
+ occurrences.push({ person, year, start, end });
22
+ }
23
+ }
24
+ return occurrences.sort((left, right) => left.start.getTime() - right.start.getTime());
25
+ }
@@ -0,0 +1,68 @@
1
+ import { z } from 'zod';
2
+ export declare const CALENDAR_TYPE_ID = "calendar.calendar";
3
+ /** The colours a calendar can take: the palette of the design system. */
4
+ export declare const CALENDAR_COLORS: readonly ['blue', 'cyan', 'green', 'violet', 'yellow', 'orange', 'red'];
5
+ export declare const CalendarColorSchema: z.ZodEnum<{
6
+ blue: "blue";
7
+ cyan: "cyan";
8
+ green: "green";
9
+ orange: "orange";
10
+ red: "red";
11
+ violet: "violet";
12
+ yellow: "yellow";
13
+ }>;
14
+ export type CalendarColor = z.infer<typeof CalendarColorSchema>;
15
+ /** A calendar's data (its id, owner and dates are the envelope's). */
16
+ export declare const CalendarSchema: z.ZodObject<{
17
+ name: z.ZodString;
18
+ color: z.ZodEnum<{
19
+ blue: "blue";
20
+ cyan: "cyan";
21
+ green: "green";
22
+ orange: "orange";
23
+ red: "red";
24
+ violet: "violet";
25
+ yellow: "yellow";
26
+ }>;
27
+ }, z.core.$strip>;
28
+ export type Calendar = z.infer<typeof CalendarSchema>;
29
+ /** Creating or changing a calendar (the body of `create` and `update`). */
30
+ export declare const CalendarInputSchema: z.ZodObject<{
31
+ name: z.ZodString;
32
+ color: z.ZodEnum<{
33
+ blue: "blue";
34
+ cyan: "cyan";
35
+ green: "green";
36
+ orange: "orange";
37
+ red: "red";
38
+ violet: "violet";
39
+ yellow: "yellow";
40
+ }>;
41
+ }, z.core.$strip>;
42
+ export type CalendarInput = z.input<typeof CalendarInputSchema>;
43
+ export type CalendarFields = z.output<typeof CalendarInputSchema>;
44
+ export declare const calendarType: {
45
+ id: string;
46
+ version: number;
47
+ parent: string | null;
48
+ titleFields: string[];
49
+ schema: Record<string, z.JSONType>;
50
+ permissions: Record<string, string | null>;
51
+ operations: Record<string, string>;
52
+ kinds: string[];
53
+ actions: Record<string, {
54
+ permission: string;
55
+ target: "page" | "server";
56
+ }>;
57
+ messages: Partial<Record<"en" | "fr", {
58
+ name: string;
59
+ plural: string;
60
+ permissions: Record<string, {
61
+ label: string;
62
+ description: string;
63
+ }>;
64
+ operations: Record<string, string>;
65
+ kinds: Record<string, string>;
66
+ actions: Record<string, string>;
67
+ }>>;
68
+ };
@@ -0,0 +1,81 @@
1
+ import { defineEntityType } from '@ismou-workspace/contracts';
2
+ import { z } from 'zod';
3
+ /*
4
+ * `calendar.calendar`: a calendar, whoever provides it (the calendar app, a Google bridge). Its
5
+ * events are `calendar.event`s whose parent it is: sharing a calendar shares its events, the
6
+ * permissions inheriting by name.
7
+ */
8
+ export const CALENDAR_TYPE_ID = 'calendar.calendar';
9
+ /** The colours a calendar can take: the palette of the design system. */
10
+ export const CALENDAR_COLORS = [
11
+ 'blue',
12
+ 'cyan',
13
+ 'green',
14
+ 'violet',
15
+ 'yellow',
16
+ 'orange',
17
+ 'red',
18
+ ];
19
+ export const CalendarColorSchema = z.enum(CALENDAR_COLORS);
20
+ /** A calendar's data (its id, owner and dates are the envelope's). */
21
+ export const CalendarSchema = z.object({
22
+ name: z.string(),
23
+ color: CalendarColorSchema,
24
+ });
25
+ /** Creating or changing a calendar (the body of `create` and `update`). */
26
+ export const CalendarInputSchema = z.object({
27
+ name: z.string().trim().min(1).max(80),
28
+ color: CalendarColorSchema,
29
+ });
30
+ export const calendarType = defineEntityType({
31
+ id: CALENDAR_TYPE_ID,
32
+ version: 1,
33
+ parent: null,
34
+ titleFields: ['name'],
35
+ data: CalendarSchema,
36
+ permissions: { read: null, write: 'read', share: 'read' },
37
+ operations: { list: 'read', read: 'read', create: 'write', update: 'write', delete: 'write' },
38
+ messages: {
39
+ en: {
40
+ name: 'Calendar',
41
+ plural: 'Calendars',
42
+ permissions: {
43
+ read: { label: 'View calendars', description: 'See calendars and their events.' },
44
+ write: {
45
+ label: 'Edit calendars',
46
+ description: 'Create, rename and delete calendars, and their events.',
47
+ },
48
+ share: { label: 'Share calendars', description: 'Share calendars with other people.' },
49
+ },
50
+ operations: {
51
+ list: 'List calendars',
52
+ read: 'View a calendar',
53
+ create: 'Create calendars',
54
+ update: 'Rename calendars',
55
+ delete: 'Delete calendars',
56
+ },
57
+ },
58
+ fr: {
59
+ name: 'Agenda',
60
+ plural: 'Agendas',
61
+ permissions: {
62
+ read: { label: 'Voir les agendas', description: 'Voir les agendas et leurs événements.' },
63
+ write: {
64
+ label: 'Modifier les agendas',
65
+ description: 'Créer, renommer et supprimer des agendas, et leurs événements.',
66
+ },
67
+ share: {
68
+ label: 'Partager les agendas',
69
+ description: "Partager des agendas avec d'autres personnes.",
70
+ },
71
+ },
72
+ operations: {
73
+ list: 'Lister les agendas',
74
+ read: 'Voir un agenda',
75
+ create: 'Créer des agendas',
76
+ update: 'Renommer des agendas',
77
+ delete: 'Supprimer des agendas',
78
+ },
79
+ },
80
+ },
81
+ });
@@ -0,0 +1,202 @@
1
+ import { z } from 'zod';
2
+ export declare const EVENT_TYPE_ID = "calendar.event";
3
+ export declare const RECURRENCE_FREQUENCIES: readonly ['daily', 'weekly', 'monthly', 'yearly'];
4
+ export declare const RecurrenceFrequencySchema: z.ZodEnum<{
5
+ daily: "daily";
6
+ monthly: "monthly";
7
+ weekly: "weekly";
8
+ yearly: "yearly";
9
+ }>;
10
+ export type RecurrenceFrequency = z.infer<typeof RecurrenceFrequencySchema>;
11
+ /** Days of the week, as RFC 5545 names them, Monday first. */
12
+ export declare const WEEKDAYS: readonly ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'];
13
+ export declare const WeekdaySchema: z.ZodEnum<{
14
+ FR: "FR";
15
+ MO: "MO";
16
+ SA: "SA";
17
+ SU: "SU";
18
+ TH: "TH";
19
+ TU: "TU";
20
+ WE: "WE";
21
+ }>;
22
+ export type Weekday = z.infer<typeof WeekdaySchema>;
23
+ /** When a series stops: never, after a date, or after a number of occurrences. */
24
+ export declare const RecurrenceEndSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
25
+ kind: z.ZodLiteral<"never">;
26
+ }, z.core.$strip>, z.ZodObject<{
27
+ kind: z.ZodLiteral<"until">;
28
+ date: z.ZodISODate;
29
+ }, z.core.$strip>, z.ZodObject<{
30
+ kind: z.ZodLiteral<"count">;
31
+ count: z.ZodInt;
32
+ }, z.core.$strip>], "kind">;
33
+ export type RecurrenceEnd = z.infer<typeof RecurrenceEndSchema>;
34
+ /** How an event repeats (a subset of RFC 5545 rules the interface can edit). */
35
+ export declare const RecurrenceSchema: z.ZodObject<{
36
+ frequency: z.ZodEnum<{
37
+ daily: "daily";
38
+ monthly: "monthly";
39
+ weekly: "weekly";
40
+ yearly: "yearly";
41
+ }>;
42
+ interval: z.ZodDefault<z.ZodInt>;
43
+ weekdays: z.ZodDefault<z.ZodArray<z.ZodEnum<{
44
+ FR: "FR";
45
+ MO: "MO";
46
+ SA: "SA";
47
+ SU: "SU";
48
+ TH: "TH";
49
+ TU: "TU";
50
+ WE: "WE";
51
+ }>>>;
52
+ end: z.ZodDefault<z.ZodDiscriminatedUnion<[z.ZodObject<{
53
+ kind: z.ZodLiteral<"never">;
54
+ }, z.core.$strip>, z.ZodObject<{
55
+ kind: z.ZodLiteral<"until">;
56
+ date: z.ZodISODate;
57
+ }, z.core.$strip>, z.ZodObject<{
58
+ kind: z.ZodLiteral<"count">;
59
+ count: z.ZodInt;
60
+ }, z.core.$strip>], "kind">>;
61
+ }, z.core.$strip>;
62
+ export type Recurrence = z.output<typeof RecurrenceSchema>;
63
+ export type RecurrenceInput = z.input<typeof RecurrenceSchema>;
64
+ /** An IANA time zone the runtime knows (`Europe/Paris`). */
65
+ export declare const TimeZoneSchema: z.ZodString;
66
+ /** Who created an event, and through which app. */
67
+ export declare const EventProvenanceSchema: z.ZodObject<{
68
+ accountId: z.ZodString;
69
+ appId: z.ZodString;
70
+ }, z.core.$strip>;
71
+ /** An event's data (its id, calendar, owner and dates are the envelope's). */
72
+ export declare const CalendarEventSchema: z.ZodObject<{
73
+ title: z.ZodString;
74
+ description: z.ZodNullable<z.ZodString>;
75
+ location: z.ZodNullable<z.ZodString>;
76
+ allDay: z.ZodBoolean;
77
+ start: z.ZodISODateTime;
78
+ end: z.ZodISODateTime;
79
+ timeZone: z.ZodString;
80
+ recurrence: z.ZodNullable<z.ZodObject<{
81
+ frequency: z.ZodEnum<{
82
+ daily: "daily";
83
+ monthly: "monthly";
84
+ weekly: "weekly";
85
+ yearly: "yearly";
86
+ }>;
87
+ interval: z.ZodDefault<z.ZodInt>;
88
+ weekdays: z.ZodDefault<z.ZodArray<z.ZodEnum<{
89
+ FR: "FR";
90
+ MO: "MO";
91
+ SA: "SA";
92
+ SU: "SU";
93
+ TH: "TH";
94
+ TU: "TU";
95
+ WE: "WE";
96
+ }>>>;
97
+ end: z.ZodDefault<z.ZodDiscriminatedUnion<[z.ZodObject<{
98
+ kind: z.ZodLiteral<"never">;
99
+ }, z.core.$strip>, z.ZodObject<{
100
+ kind: z.ZodLiteral<"until">;
101
+ date: z.ZodISODate;
102
+ }, z.core.$strip>, z.ZodObject<{
103
+ kind: z.ZodLiteral<"count">;
104
+ count: z.ZodInt;
105
+ }, z.core.$strip>], "kind">>;
106
+ }, z.core.$strip>>;
107
+ exceptions: z.ZodArray<z.ZodISODateTime>;
108
+ createdBy: z.ZodObject<{
109
+ accountId: z.ZodString;
110
+ appId: z.ZodString;
111
+ }, z.core.$strip>;
112
+ }, z.core.$strip>;
113
+ export type CalendarEvent = z.infer<typeof CalendarEventSchema>;
114
+ /**
115
+ * Creating or changing an event (the body of `create` and `update`): every field, the series
116
+ * included. Its calendar is the envelope's parent (`?parent=` on the core).
117
+ */
118
+ export declare const CalendarEventInputSchema: z.ZodObject<{
119
+ title: z.ZodString;
120
+ description: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
121
+ location: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
122
+ allDay: z.ZodDefault<z.ZodBoolean>;
123
+ start: z.ZodISODateTime;
124
+ end: z.ZodISODateTime;
125
+ timeZone: z.ZodString;
126
+ recurrence: z.ZodDefault<z.ZodNullable<z.ZodObject<{
127
+ frequency: z.ZodEnum<{
128
+ daily: "daily";
129
+ monthly: "monthly";
130
+ weekly: "weekly";
131
+ yearly: "yearly";
132
+ }>;
133
+ interval: z.ZodDefault<z.ZodInt>;
134
+ weekdays: z.ZodDefault<z.ZodArray<z.ZodEnum<{
135
+ FR: "FR";
136
+ MO: "MO";
137
+ SA: "SA";
138
+ SU: "SU";
139
+ TH: "TH";
140
+ TU: "TU";
141
+ WE: "WE";
142
+ }>>>;
143
+ end: z.ZodDefault<z.ZodDiscriminatedUnion<[z.ZodObject<{
144
+ kind: z.ZodLiteral<"never">;
145
+ }, z.core.$strip>, z.ZodObject<{
146
+ kind: z.ZodLiteral<"until">;
147
+ date: z.ZodISODate;
148
+ }, z.core.$strip>, z.ZodObject<{
149
+ kind: z.ZodLiteral<"count">;
150
+ count: z.ZodInt;
151
+ }, z.core.$strip>], "kind">>;
152
+ }, z.core.$strip>>>;
153
+ }, z.core.$strip>;
154
+ export type CalendarEventInput = z.input<typeof CalendarEventInputSchema>;
155
+ export type CalendarEventFields = z.output<typeof CalendarEventInputSchema>;
156
+ /** An event's fields, as the input that recreates it elsewhere (moving it to another provider). */
157
+ export declare function eventInputOf(event: CalendarEvent): CalendarEventInput;
158
+ /**
159
+ * What a list of events takes: the events overlapping `[from, to)`, series included whole (the
160
+ * client expands them). Within a shared calendar, its events only.
161
+ */
162
+ export declare const EventListParamsSchema: z.ZodObject<{
163
+ from: z.ZodISODateTime;
164
+ to: z.ZodISODateTime;
165
+ }, z.core.$strip>;
166
+ export type EventListParams = z.infer<typeof EventListParamsSchema>;
167
+ /** The longest range one list asks: a month view and its edges, with room to spare. */
168
+ export declare const MAX_EVENT_RANGE_DAYS = 100;
169
+ /** The event's own operations, and what they take and answer. */
170
+ export declare const EVENT_OPERATIONS: {
171
+ /** POST `OccurrenceDeletion`: removes one occurrence of a series → 204. */
172
+ readonly deleteOccurrence: 'delete-occurrence';
173
+ };
174
+ export declare const OccurrenceDeletionSchema: z.ZodObject<{
175
+ start: z.ZodISODateTime;
176
+ }, z.core.$strip>;
177
+ export type OccurrenceDeletion = z.infer<typeof OccurrenceDeletionSchema>;
178
+ export declare const eventType: {
179
+ id: string;
180
+ version: number;
181
+ parent: string | null;
182
+ titleFields: string[];
183
+ schema: Record<string, z.JSONType>;
184
+ permissions: Record<string, string | null>;
185
+ operations: Record<string, string>;
186
+ kinds: string[];
187
+ actions: Record<string, {
188
+ permission: string;
189
+ target: "page" | "server";
190
+ }>;
191
+ messages: Partial<Record<"en" | "fr", {
192
+ name: string;
193
+ plural: string;
194
+ permissions: Record<string, {
195
+ label: string;
196
+ description: string;
197
+ }>;
198
+ operations: Record<string, string>;
199
+ kinds: Record<string, string>;
200
+ actions: Record<string, string>;
201
+ }>>;
202
+ };
@@ -0,0 +1,194 @@
1
+ import { defineEntityType } from '@ismou-workspace/contracts';
2
+ import { z } from 'zod';
3
+ import { CALENDAR_TYPE_ID } from './calendar.type.js';
4
+ /*
5
+ * `calendar.event`: an event in a calendar (its parent), whoever provides it. A repeating event
6
+ * is one entity with its rule; lists return series whole and clients expand them
7
+ * (`expandOccurrences`).
8
+ */
9
+ export const EVENT_TYPE_ID = 'calendar.event';
10
+ export const RECURRENCE_FREQUENCIES = ['daily', 'weekly', 'monthly', 'yearly'];
11
+ export const RecurrenceFrequencySchema = z.enum(RECURRENCE_FREQUENCIES);
12
+ /** Days of the week, as RFC 5545 names them, Monday first. */
13
+ export const WEEKDAYS = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'];
14
+ export const WeekdaySchema = z.enum(WEEKDAYS);
15
+ /** When a series stops: never, after a date, or after a number of occurrences. */
16
+ export const RecurrenceEndSchema = z.discriminatedUnion('kind', [
17
+ z.object({ kind: z.literal('never') }),
18
+ /** The last day an occurrence may start on (`YYYY-MM-DD`, in the event's time zone). */
19
+ z.object({ kind: z.literal('until'), date: z.iso.date() }),
20
+ z.object({ kind: z.literal('count'), count: z.int().min(1).max(999) }),
21
+ ]);
22
+ /** How an event repeats (a subset of RFC 5545 rules the interface can edit). */
23
+ export const RecurrenceSchema = z.object({
24
+ frequency: RecurrenceFrequencySchema,
25
+ /** Every `interval` days, weeks, months or years. */
26
+ interval: z.int().min(1).max(99).default(1),
27
+ /** Weekly only: the days it happens on; the start's day when empty. */
28
+ weekdays: z.array(WeekdaySchema).max(7).default([]),
29
+ end: RecurrenceEndSchema.default({ kind: 'never' }),
30
+ });
31
+ /** An IANA time zone the runtime knows (`Europe/Paris`). */
32
+ export const TimeZoneSchema = z.string().refine((zone) => {
33
+ try {
34
+ new Intl.DateTimeFormat('en', { timeZone: zone });
35
+ return true;
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ }, { message: 'Unknown time zone.' });
41
+ /** Who created an event, and through which app. */
42
+ export const EventProvenanceSchema = z.object({
43
+ accountId: z.string(),
44
+ appId: z.string().min(1),
45
+ });
46
+ /** An event's data (its id, calendar, owner and dates are the envelope's). */
47
+ export const CalendarEventSchema = z.object({
48
+ title: z.string(),
49
+ description: z.string().nullable(),
50
+ location: z.string().nullable(),
51
+ /** All-day events cover whole days of `timeZone`: `start` and `end` are midnights there. */
52
+ allDay: z.boolean(),
53
+ /** The first occurrence's start and end; `end` is exclusive. */
54
+ start: z.iso.datetime({ offset: true }),
55
+ end: z.iso.datetime({ offset: true }),
56
+ /** Where its times are meant: a series keeps its wall-clock time across daylight saving. */
57
+ timeZone: z.string(),
58
+ recurrence: RecurrenceSchema.nullable(),
59
+ /** Starts of the occurrences removed from the series. */
60
+ exceptions: z.array(z.iso.datetime({ offset: true })),
61
+ createdBy: EventProvenanceSchema,
62
+ });
63
+ const optionalText = (maxLength) => z
64
+ .string()
65
+ .trim()
66
+ .max(maxLength)
67
+ .nullish()
68
+ .transform((value) => (value ? value : null));
69
+ /** Events start from 1900: a series is computed from its start, which keeps that bounded. */
70
+ const EARLIEST_START = Date.UTC(1900, 0, 1);
71
+ /** A series lasts a century at most: its last occurrence is computed when it is saved. */
72
+ const LONGEST_SERIES_MS = 100 * 365.25 * 86_400_000;
73
+ /**
74
+ * Creating or changing an event (the body of `create` and `update`): every field, the series
75
+ * included. Its calendar is the envelope's parent (`?parent=` on the core).
76
+ */
77
+ export const CalendarEventInputSchema = z
78
+ .object({
79
+ title: z.string().trim().min(1).max(200),
80
+ description: optionalText(4000),
81
+ location: optionalText(200),
82
+ allDay: z.boolean().default(false),
83
+ start: z.iso.datetime({ offset: true }),
84
+ end: z.iso.datetime({ offset: true }),
85
+ timeZone: TimeZoneSchema,
86
+ recurrence: RecurrenceSchema.nullable().default(null),
87
+ })
88
+ .refine((event) => Date.parse(event.end) > Date.parse(event.start), {
89
+ message: 'An event ends after it starts.',
90
+ path: ['end'],
91
+ })
92
+ .refine((event) => Date.parse(event.start) >= EARLIEST_START, {
93
+ message: 'An event starts in 1900 or later.',
94
+ path: ['start'],
95
+ })
96
+ .refine(({ start, recurrence }) => recurrence?.end.kind !== 'until' ||
97
+ Date.parse(recurrence.end.date) - Date.parse(start) <= LONGEST_SERIES_MS, { message: 'A series ends within a hundred years.', path: ['recurrence'] });
98
+ /** An event's fields, as the input that recreates it elsewhere (moving it to another provider). */
99
+ export function eventInputOf(event) {
100
+ return {
101
+ title: event.title,
102
+ description: event.description,
103
+ location: event.location,
104
+ allDay: event.allDay,
105
+ start: event.start,
106
+ end: event.end,
107
+ timeZone: event.timeZone,
108
+ recurrence: event.recurrence,
109
+ };
110
+ }
111
+ /**
112
+ * What a list of events takes: the events overlapping `[from, to)`, series included whole (the
113
+ * client expands them). Within a shared calendar, its events only.
114
+ */
115
+ export const EventListParamsSchema = z
116
+ .object({
117
+ from: z.iso.datetime({ offset: true }),
118
+ to: z.iso.datetime({ offset: true }),
119
+ })
120
+ .refine(({ from, to }) => Date.parse(to) > Date.parse(from), {
121
+ message: 'The range ends after it starts.',
122
+ });
123
+ /** The longest range one list asks: a month view and its edges, with room to spare. */
124
+ export const MAX_EVENT_RANGE_DAYS = 100;
125
+ /** The event's own operations, and what they take and answer. */
126
+ export const EVENT_OPERATIONS = {
127
+ /** POST `OccurrenceDeletion`: removes one occurrence of a series → 204. */
128
+ deleteOccurrence: 'delete-occurrence',
129
+ };
130
+ export const OccurrenceDeletionSchema = z.object({
131
+ /** The start of the occurrence to remove, as expanded. */
132
+ start: z.iso.datetime({ offset: true }),
133
+ });
134
+ export const eventType = defineEntityType({
135
+ id: EVENT_TYPE_ID,
136
+ version: 1,
137
+ parent: CALENDAR_TYPE_ID,
138
+ titleFields: ['title'],
139
+ data: CalendarEventSchema,
140
+ permissions: { read: null, write: 'read', share: 'read' },
141
+ operations: {
142
+ list: 'read',
143
+ read: 'read',
144
+ create: 'write',
145
+ update: 'write',
146
+ delete: 'write',
147
+ [EVENT_OPERATIONS.deleteOccurrence]: 'write',
148
+ },
149
+ messages: {
150
+ en: {
151
+ name: 'Event',
152
+ plural: 'Events',
153
+ permissions: {
154
+ read: { label: 'View events', description: 'See events and their details.' },
155
+ write: { label: 'Edit events', description: 'Create, change and delete events.' },
156
+ share: { label: 'Share events', description: 'Share events with other people.' },
157
+ },
158
+ operations: {
159
+ list: 'List events',
160
+ read: 'View an event',
161
+ create: 'Create events',
162
+ update: 'Edit events',
163
+ delete: 'Delete events',
164
+ [EVENT_OPERATIONS.deleteOccurrence]: 'Delete one occurrence',
165
+ },
166
+ },
167
+ fr: {
168
+ name: 'Événement',
169
+ plural: 'Événements',
170
+ permissions: {
171
+ read: {
172
+ label: 'Voir les événements',
173
+ description: 'Voir les événements et leurs détails.',
174
+ },
175
+ write: {
176
+ label: 'Modifier les événements',
177
+ description: 'Créer, modifier et supprimer des événements.',
178
+ },
179
+ share: {
180
+ label: 'Partager les événements',
181
+ description: "Partager des événements avec d'autres personnes.",
182
+ },
183
+ },
184
+ operations: {
185
+ list: 'Lister les événements',
186
+ read: 'Voir un événement',
187
+ create: 'Créer des événements',
188
+ update: 'Modifier des événements',
189
+ delete: 'Supprimer des événements',
190
+ [EVENT_OPERATIONS.deleteOccurrence]: 'Supprimer une occurrence',
191
+ },
192
+ },
193
+ },
194
+ });
@@ -0,0 +1,4 @@
1
+ export { type BirthdayOccurrence, birthdaysInRange, type WithBirthday, } from './birthdays.ts';
2
+ export { CALENDAR_COLORS, CALENDAR_TYPE_ID, type Calendar, type CalendarColor, CalendarColorSchema, type CalendarFields, type CalendarInput, CalendarInputSchema, CalendarSchema, calendarType, } from './calendar.type.ts';
3
+ export { type CalendarEvent, type CalendarEventFields, type CalendarEventInput, CalendarEventInputSchema, CalendarEventSchema, EVENT_OPERATIONS, EVENT_TYPE_ID, type EventListParams, EventListParamsSchema, EventProvenanceSchema, eventInputOf, eventType, MAX_EVENT_RANGE_DAYS, type OccurrenceDeletion, OccurrenceDeletionSchema, RECURRENCE_FREQUENCIES, type Recurrence, type RecurrenceEnd, RecurrenceEndSchema, type RecurrenceFrequency, RecurrenceFrequencySchema, type RecurrenceInput, RecurrenceSchema, TimeZoneSchema, WEEKDAYS, type Weekday, WeekdaySchema, } from './event.type.ts';
4
+ export { type EventTiming, expandOccurrences, type InstantRange, isOccurrenceStart, lastEndOf, type OccurrenceTime, } from './occurrences.ts';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ /* The `calendar.calendar` and `calendar.event` entity types (docs/architecture/entities/). */
2
+ export { birthdaysInRange, } from './birthdays.js';
3
+ export { CALENDAR_COLORS, CALENDAR_TYPE_ID, CalendarColorSchema, CalendarInputSchema, CalendarSchema, calendarType, } from './calendar.type.js';
4
+ export { CalendarEventInputSchema, CalendarEventSchema, EVENT_OPERATIONS, EVENT_TYPE_ID, EventListParamsSchema, EventProvenanceSchema, eventInputOf, eventType, MAX_EVENT_RANGE_DAYS, OccurrenceDeletionSchema, RECURRENCE_FREQUENCIES, RecurrenceEndSchema, RecurrenceFrequencySchema, RecurrenceSchema, TimeZoneSchema, WEEKDAYS, WeekdaySchema, } from './event.type.js';
5
+ export { expandOccurrences, isOccurrenceStart, lastEndOf, } from './occurrences.js';
@@ -0,0 +1,25 @@
1
+ import type { CalendarEvent } from './event.type.ts';
2
+ /** When an event happens: what its occurrences are computed from. */
3
+ export interface EventTiming extends Pick<CalendarEvent, 'start' | 'end' | 'allDay' | 'timeZone' | 'recurrence'> {
4
+ /** Starts of the occurrences removed from the series; none by default. */
5
+ exceptions?: readonly string[];
6
+ }
7
+ /** One occurrence, as real instants (`end` exclusive). */
8
+ export interface OccurrenceTime {
9
+ start: Date;
10
+ end: Date;
11
+ }
12
+ /** A range of instants: `from` inclusive, `to` exclusive. */
13
+ export interface InstantRange {
14
+ from: Date;
15
+ to: Date;
16
+ }
17
+ /**
18
+ * The occurrences of an event overlapping `[from, to)`, in order, without the removed ones. A
19
+ * single event is its own occurrence.
20
+ */
21
+ export declare function expandOccurrences(timing: EventTiming, { from, to }: InstantRange): OccurrenceTime[];
22
+ /** When the last occurrence ends; `null` for a series without end. */
23
+ export declare function lastEndOf(timing: EventTiming): Date | null;
24
+ /** Whether `start` is the start of one of the series' occurrences (not removed). */
25
+ export declare function isOccurrenceStart(timing: EventTiming, start: Date): boolean;
@@ -0,0 +1,124 @@
1
+ import { TZDate } from '@date-fns/tz';
2
+ import * as rruleExports from 'rrule';
3
+ /*
4
+ * A repeating event is one entity with its rule: lists return series whole, and whoever shows
5
+ * them (a client, a provider checking an occurrence) expands them here.
6
+ */
7
+ /*
8
+ * rrule gives bundlers ES modules but Node its UMD build, whose exports Node only sees on the
9
+ * default export. `Reflect.get` keeps bundlers from resolving `default` statically.
10
+ */
11
+ const rrule = 'RRule' in rruleExports && rruleExports.RRule
12
+ ? rruleExports
13
+ : Reflect.get(rruleExports, 'default');
14
+ const { RRule, RRuleSet } = rrule;
15
+ const DAY_MS = 86_400_000;
16
+ const FREQUENCIES = {
17
+ daily: RRule.DAILY,
18
+ weekly: RRule.WEEKLY,
19
+ monthly: RRule.MONTHLY,
20
+ yearly: RRule.YEARLY,
21
+ };
22
+ const RRULE_WEEKDAYS = {
23
+ MO: RRule.MO,
24
+ TU: RRule.TU,
25
+ WE: RRule.WE,
26
+ TH: RRule.TH,
27
+ FR: RRule.FR,
28
+ SA: RRule.SA,
29
+ SU: RRule.SU,
30
+ };
31
+ /*
32
+ * rrule computes in UTC. A series is meant in wall-clock time of its time zone (9:00 stays 9:00
33
+ * across daylight saving), so it runs on "floating" dates: the wall-clock time written as if it
34
+ * were UTC, converted back to real instants in the event's zone afterwards.
35
+ */
36
+ function toFloating(instant, timeZone) {
37
+ const zoned = new TZDate(instant.getTime(), timeZone);
38
+ return new Date(Date.UTC(zoned.getFullYear(), zoned.getMonth(), zoned.getDate(), zoned.getHours(), zoned.getMinutes(), zoned.getSeconds()));
39
+ }
40
+ function fromFloating(floating, timeZone) {
41
+ return new Date(new TZDate(floating.getUTCFullYear(), floating.getUTCMonth(), floating.getUTCDate(), floating.getUTCHours(), floating.getUTCMinutes(), floating.getUTCSeconds(), timeZone).getTime());
42
+ }
43
+ /**
44
+ * The series' floating starts. The event's own start is always its first occurrence, counted in
45
+ * its `count`, as Google and RFC 5545 readers take a rule: a weekly series started on a Monday
46
+ * and repeating on Tuesdays still happens that Monday. rrule alone would skip it.
47
+ */
48
+ function seriesOf(timing, recurrence) {
49
+ const { end } = recurrence;
50
+ const dtstart = toFloating(new Date(timing.start), timing.timeZone);
51
+ const options = {
52
+ freq: FREQUENCIES[recurrence.frequency],
53
+ interval: recurrence.interval,
54
+ byweekday: recurrence.frequency === 'weekly' && recurrence.weekdays.length > 0
55
+ ? recurrence.weekdays.map((day) => RRULE_WEEKDAYS[day])
56
+ : null,
57
+ dtstart,
58
+ until: end.kind === 'until' ? new Date(`${end.date}T23:59:59.000Z`) : null,
59
+ };
60
+ const count = end.kind === 'count' ? end.count : null;
61
+ const startsOnRule = new RRule(options).after(dtstart, true)?.getTime() === dtstart.getTime();
62
+ if (startsOnRule)
63
+ return new RRule({ ...options, count });
64
+ const series = new RRuleSet();
65
+ series.rdate(dtstart);
66
+ // The event itself is one of `count`: the rule adds the others, if any.
67
+ if (count !== 1)
68
+ series.rrule(new RRule({ ...options, count: count && count - 1 }));
69
+ return series;
70
+ }
71
+ /** The occurrence starting at `floatingStart`, as real instants. */
72
+ function occurrenceAt(timing, floatingStart) {
73
+ const first = { start: new Date(timing.start), end: new Date(timing.end) };
74
+ const start = fromFloating(floatingStart, timing.timeZone);
75
+ if (!timing.allDay) {
76
+ return {
77
+ start,
78
+ end: new Date(start.getTime() + first.end.getTime() - first.start.getTime()),
79
+ };
80
+ }
81
+ // Whole days of the zone: as many days as the first occurrence, whatever the offsets.
82
+ const days = Math.round((toFloating(first.end, timing.timeZone).getTime() -
83
+ toFloating(first.start, timing.timeZone).getTime()) /
84
+ DAY_MS);
85
+ return {
86
+ start,
87
+ end: fromFloating(new Date(floatingStart.getTime() + days * DAY_MS), timing.timeZone),
88
+ };
89
+ }
90
+ /**
91
+ * The occurrences of an event overlapping `[from, to)`, in order, without the removed ones. A
92
+ * single event is its own occurrence.
93
+ */
94
+ export function expandOccurrences(timing, { from, to }) {
95
+ const overlaps = ({ start, end }) => start < to && end > from;
96
+ const { recurrence } = timing;
97
+ if (!recurrence) {
98
+ const single = { start: new Date(timing.start), end: new Date(timing.end) };
99
+ return overlaps(single) ? [single] : [];
100
+ }
101
+ const duration = Date.parse(timing.end) - Date.parse(timing.start);
102
+ // Occurrences starting before `from` may still overlap it; a day of margin covers the offsets.
103
+ const floatingFrom = new Date(toFloating(from, timing.timeZone).getTime() - duration - DAY_MS);
104
+ const floatingTo = new Date(toFloating(to, timing.timeZone).getTime() + DAY_MS);
105
+ const removed = new Set((timing.exceptions ?? []).map((start) => Date.parse(start)));
106
+ return seriesOf(timing, recurrence)
107
+ .between(floatingFrom, floatingTo, true)
108
+ .map((floatingStart) => occurrenceAt(timing, floatingStart))
109
+ .filter((occurrence) => overlaps(occurrence) && !removed.has(occurrence.start.getTime()));
110
+ }
111
+ /** When the last occurrence ends; `null` for a series without end. */
112
+ export function lastEndOf(timing) {
113
+ const { recurrence } = timing;
114
+ if (!recurrence)
115
+ return new Date(timing.end);
116
+ if (recurrence.end.kind === 'never')
117
+ return null;
118
+ const last = seriesOf(timing, recurrence).all().at(-1);
119
+ return last ? occurrenceAt(timing, last).end : new Date(timing.end);
120
+ }
121
+ /** Whether `start` is the start of one of the series' occurrences (not removed). */
122
+ export function isOccurrenceStart(timing, start) {
123
+ return expandOccurrences(timing, { from: start, to: new Date(start.getTime() + 1) }).some((occurrence) => occurrence.start.getTime() === start.getTime());
124
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@ismou-workspace/calendar-contracts",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.2",
4
+ "description": "The calendar.* entity types of Ismou's Calendar app (calendars, events and their occurrences, birthdays), and the DTOs of its API.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "dependencies": {
14
+ "@ismou-workspace/contracts": "^0.1.0",
15
+ "@date-fns/tz": "1.5.0",
16
+ "rrule": "2.8.1",
17
+ "zod": "4.6.7"
18
+ },
19
+ "devDependencies": {
20
+ "@ismou-workspace/tsconfig": "^0.1.0",
21
+ "typescript": "7.0.2",
22
+ "vitest": "5.1.2"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/ismou-workspace/calendar.git",
27
+ "directory": "contracts"
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "scripts": {
36
+ "build": "tsc --project tsconfig.build.json",
37
+ "typecheck": "tsc --project tsconfig.json",
38
+ "test": "vitest run"
39
+ }
6
40
  }