@moltenship/ics 0.0.0-stage → 1.0.0-rc.1

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/dist/index.mjs ADDED
@@ -0,0 +1,2339 @@
1
+ //#region src/model/event-end.ts
2
+ function wallTimeOf(value) {
3
+ switch (value.kind) {
4
+ case "date": return value.date.toPlainDateTime();
5
+ case "utc": return value.instant.toZonedDateTimeISO("UTC").toPlainDateTime();
6
+ case "zoned": return value.zoned.toPlainDateTime();
7
+ default: return value.wallTime;
8
+ }
9
+ }
10
+ function instantOf(value) {
11
+ if (value.kind === "utc") return value.instant;
12
+ return value.kind === "zoned" ? value.zoned.toInstant() : void 0;
13
+ }
14
+ function inKindOf(start, value) {
15
+ const sameZone = value.kind !== "zoned" || start.kind === "zoned" && value.zoned.timeZoneId === start.zoned.timeZoneId;
16
+ if (value.kind === start.kind && sameZone) return value;
17
+ const instant = instantOf(value);
18
+ switch (start.kind) {
19
+ case "date": return {
20
+ date: wallTimeOf(value).toPlainDate(),
21
+ kind: "date"
22
+ };
23
+ case "utc": return {
24
+ instant: instant ?? wallTimeOf(value).toZonedDateTime("UTC").toInstant(),
25
+ kind: "utc"
26
+ };
27
+ case "zoned": {
28
+ const timeZone = start.zoned.timeZoneId;
29
+ if (instant !== void 0) {
30
+ const zoned = instant.toZonedDateTimeISO(timeZone);
31
+ return {
32
+ kind: "zoned",
33
+ tzid: start.tzid,
34
+ wallTime: zoned.toPlainDateTime(),
35
+ zoned
36
+ };
37
+ }
38
+ const wallTime = wallTimeOf(value);
39
+ return {
40
+ kind: "zoned",
41
+ tzid: start.tzid,
42
+ wallTime,
43
+ zoned: wallTime.toZonedDateTime(timeZone)
44
+ };
45
+ }
46
+ default: return {
47
+ ...start,
48
+ wallTime: wallTimeOf(value)
49
+ };
50
+ }
51
+ }
52
+ function addDuration(start, duration) {
53
+ switch (start.kind) {
54
+ case "date": {
55
+ const days = duration.round({
56
+ largestUnit: "day",
57
+ relativeTo: start.date,
58
+ roundingMode: "expand",
59
+ smallestUnit: "day"
60
+ });
61
+ return {
62
+ date: start.date.add(days),
63
+ kind: "date"
64
+ };
65
+ }
66
+ case "utc": return {
67
+ instant: start.instant.toZonedDateTimeISO("UTC").add(duration).toInstant(),
68
+ kind: "utc"
69
+ };
70
+ case "zoned": {
71
+ const zoned = start.zoned.add(duration);
72
+ return {
73
+ kind: "zoned",
74
+ tzid: start.tzid,
75
+ wallTime: zoned.toPlainDateTime(),
76
+ zoned
77
+ };
78
+ }
79
+ default: return {
80
+ ...start,
81
+ wallTime: start.wallTime.add(duration)
82
+ };
83
+ }
84
+ }
85
+ /**
86
+ * The event's effective end: DTEND, else DTSTART + DURATION, else RFC 5545's default (the next day
87
+ * for a date, the start itself for a date-time). Always the same kind as the start: a DTEND of
88
+ * another kind is converted, keeping its instant where both have one, else its wall time.
89
+ *
90
+ * DURATION on a zoned start adds days as calendar days and hours as exact time (RFC 5545 §3.3.6).
91
+ * On a date start it adds whole days: a time part, which RFC 5545 doesn't allow there, rounds up
92
+ * to whole days, so the end covers it (`PT1H` ends the next day).
93
+ */
94
+ function getEventEnd(event) {
95
+ const { duration, end, start } = event;
96
+ if (end !== void 0) return inKindOf(start, end);
97
+ if (duration !== void 0) return addDuration(start, duration);
98
+ return start.kind === "date" ? {
99
+ date: start.date.add({ days: 1 }),
100
+ kind: "date"
101
+ } : start;
102
+ }
103
+ //#endregion
104
+ //#region src/values/result.ts
105
+ function success(value, warnings = []) {
106
+ return warnings.length === 0 ? {
107
+ ok: true,
108
+ value
109
+ } : {
110
+ ok: true,
111
+ value,
112
+ warnings
113
+ };
114
+ }
115
+ function failure(message) {
116
+ return {
117
+ ok: false,
118
+ message
119
+ };
120
+ }
121
+ /** A value that breaks RFC 5545 and was read anyway. */
122
+ function invalid(message) {
123
+ return {
124
+ code: "invalid-value",
125
+ message
126
+ };
127
+ }
128
+ /** A part's warnings, such as an UNTIL's inside a RECUR, each prefixed with the part. */
129
+ function nested(prefix, result) {
130
+ return (result.warnings ?? []).map(({ code, message }) => ({
131
+ code,
132
+ message: `${prefix}: ${message}`
133
+ }));
134
+ }
135
+ /** The value for a message, cut short so a huge value doesn't end up in every issue. */
136
+ function quote(raw) {
137
+ return JSON.stringify(raw.length > 48 ? `${raw.slice(0, 45)}...` : raw);
138
+ }
139
+ //#endregion
140
+ //#region src/values/date-time.ts
141
+ const DATE = /^(\d{4})(\d{2})(\d{2})$/;
142
+ const DATE_TIME = /^(\d{4})(\d{2})(\d{2})([Tt])(\d{2})(\d{2})(\d{2})?([Zz])?$/;
143
+ const TIME = /^(\d{2})(\d{2})(\d{2})?([Zz])?$/;
144
+ const MAX_CACHED_TIME_ZONES = 512;
145
+ const temporalTimeZones = /* @__PURE__ */ new Map();
146
+ /** The id Temporal uses for `id`, or `undefined` when it isn't a time zone Temporal knows. */
147
+ function temporalTimeZoneId(id) {
148
+ if (temporalTimeZones.has(id)) return temporalTimeZones.get(id);
149
+ let resolved;
150
+ try {
151
+ resolved = new Temporal.ZonedDateTime(0n, id).timeZoneId;
152
+ } catch {
153
+ resolved = void 0;
154
+ }
155
+ if (temporalTimeZones.size >= MAX_CACHED_TIME_ZONES) temporalTimeZones.clear();
156
+ temporalTimeZones.set(id, resolved);
157
+ return resolved;
158
+ }
159
+ function resolveTimeZone(tzid, context) {
160
+ const id = context.resolveTimeZone ? context.resolveTimeZone(tzid) : tzid;
161
+ return id === void 0 ? void 0 : temporalTimeZoneId(id);
162
+ }
163
+ function lenientSecond(second, lowercase) {
164
+ const warnings = [];
165
+ if (lowercase) warnings.push(invalid("lowercase T or Z; read as uppercase"));
166
+ if (second === void 0) warnings.push(invalid("no seconds; read as :00"));
167
+ else if (second === "60") warnings.push(invalid("second 60 (a leap second); read as 59"));
168
+ return {
169
+ second: second === void 0 ? 0 : Math.min(Number(second), 59),
170
+ warnings
171
+ };
172
+ }
173
+ function decodeDate(raw) {
174
+ const match = DATE.exec(raw);
175
+ if (!match) return failure(`${quote(raw)} isn't a DATE (YYYYMMDD)`);
176
+ try {
177
+ const [, year, month, day] = match.map(Number);
178
+ return success({
179
+ date: Temporal.PlainDate.from({
180
+ day,
181
+ month,
182
+ year
183
+ }, { overflow: "reject" }),
184
+ kind: "date"
185
+ });
186
+ } catch {
187
+ return failure(`${quote(raw)} isn't a real date`);
188
+ }
189
+ }
190
+ function decodeDateTime(raw, context) {
191
+ const match = DATE_TIME.exec(raw);
192
+ if (!match) return failure(`${quote(raw)} isn't a DATE-TIME (YYYYMMDDTHHMMSS, optionally ending in Z)`);
193
+ const [, year, month, day, t, hour, minute, second, z] = match;
194
+ const { second: seconds, warnings } = lenientSecond(second, t === "t" || z === "z");
195
+ let wallTime;
196
+ try {
197
+ wallTime = Temporal.PlainDateTime.from({
198
+ day: Number(day),
199
+ hour: Number(hour),
200
+ minute: Number(minute),
201
+ month: Number(month),
202
+ second: seconds,
203
+ year: Number(year)
204
+ }, { overflow: "reject" });
205
+ } catch {
206
+ return failure(`${quote(raw)} isn't a real date and time`);
207
+ }
208
+ let { tzid } = context;
209
+ if (tzid === "") {
210
+ warnings.push(invalid("an empty TZID; ignored"));
211
+ tzid = void 0;
212
+ }
213
+ if (z !== void 0) {
214
+ if (tzid !== void 0) warnings.push(invalid(`UTC time with TZID ${quote(tzid)}; the Z wins`));
215
+ return success({
216
+ instant: wallTime.toZonedDateTime("UTC").toInstant(),
217
+ kind: "utc"
218
+ }, warnings);
219
+ }
220
+ if (tzid === void 0) return success({
221
+ kind: "floating",
222
+ wallTime
223
+ }, warnings);
224
+ const timeZone = resolveTimeZone(tzid, context);
225
+ return success(timeZone === void 0 ? {
226
+ kind: "unresolved",
227
+ tzid,
228
+ wallTime
229
+ } : {
230
+ kind: "zoned",
231
+ tzid,
232
+ wallTime,
233
+ zoned: wallTime.toZonedDateTime(timeZone, { disambiguation: "compatible" })
234
+ }, warnings);
235
+ }
236
+ /** Decodes a DATE or DATE-TIME by its shape, warning when it isn't the declared type. */
237
+ function decodeDateValue(raw, declared, context) {
238
+ const actual = DATE.test(raw) ? "DATE" : DATE_TIME.test(raw) ? "DATE-TIME" : declared;
239
+ const result = actual === "DATE" ? decodeDate(raw) : decodeDateTime(raw, context);
240
+ if (!result.ok || declared === void 0 || actual === declared) return result;
241
+ return success(result.value, [invalid(`a ${actual} where ${declared} is declared; read as ${actual}`), ...result.warnings ?? []]);
242
+ }
243
+ function decodeTime(raw) {
244
+ const match = TIME.exec(raw);
245
+ if (!match) return failure(`${quote(raw)} isn't a TIME (HHMMSS, optionally ending in Z)`);
246
+ const [, hour, minute, second, z] = match;
247
+ const { second: seconds, warnings } = lenientSecond(second, z === "z");
248
+ try {
249
+ return success({
250
+ time: Temporal.PlainTime.from({
251
+ hour: Number(hour),
252
+ minute: Number(minute),
253
+ second: seconds
254
+ }, { overflow: "reject" }),
255
+ utc: z !== void 0
256
+ }, warnings);
257
+ } catch {
258
+ return failure(`${quote(raw)} isn't a real time`);
259
+ }
260
+ }
261
+ function pad(value, length = 2) {
262
+ return String(value).padStart(length, "0");
263
+ }
264
+ function encodeDate(date) {
265
+ if (date.year < 0 || date.year > 9999) throw new RangeError(`iCalendar can't write the year ${date.year}`);
266
+ return `${pad(date.year, 4)}${pad(date.month)}${pad(date.day)}`;
267
+ }
268
+ function encodeTime(time) {
269
+ return `${pad(time.hour)}${pad(time.minute)}${pad(time.second)}`;
270
+ }
271
+ function encodeWallTime(wallTime) {
272
+ return `${encodeDate(wallTime.toPlainDate())}T${encodeTime(wallTime)}`;
273
+ }
274
+ function encodeInstant(instant) {
275
+ return `${encodeWallTime(instant.toZonedDateTimeISO("UTC").toPlainDateTime())}Z`;
276
+ }
277
+ /** Writes a DATE or DATE-TIME by its kind. Sub-second parts are dropped: iCalendar has none. */
278
+ function encodeDateValue(value) {
279
+ switch (value.kind) {
280
+ case "date": return encodeDate(value.date);
281
+ case "utc": return encodeInstant(value.instant);
282
+ default: return encodeWallTime(value.wallTime);
283
+ }
284
+ }
285
+ //#endregion
286
+ //#region src/values/duration.ts
287
+ const DURATION = /^([+-])?P(?:(\d+)W)?(?:(\d+)D)?(?:(T)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
288
+ /** Keeps the units as written: `P1D` and `PT24H` differ across a DST change. */
289
+ function decodeDuration(raw) {
290
+ const upper = raw.toUpperCase();
291
+ const [, sign, weeks, days, t, hours, minutes, seconds] = DURATION.exec(upper) ?? [];
292
+ const time = [
293
+ hours,
294
+ minutes,
295
+ seconds
296
+ ];
297
+ if ([
298
+ weeks,
299
+ days,
300
+ ...time
301
+ ].every((unit) => unit === void 0) || t !== void 0 && time.every((unit) => unit === void 0)) return failure(`${quote(raw)} isn't a DURATION (such as P1D, PT1H30M or -P2W)`);
302
+ const warnings = [];
303
+ if (upper !== raw) warnings.push("lowercase DURATION; read as uppercase");
304
+ if (weeks !== void 0 && (days ?? t) !== void 0) warnings.push("weeks with other units, which RFC 5545 doesn't allow; kept both");
305
+ if (hours !== void 0 && minutes === void 0 && seconds !== void 0) warnings.push("hours and seconds without minutes, which RFC 5545 doesn't allow");
306
+ try {
307
+ const duration = Temporal.Duration.from({
308
+ days: Number(days ?? 0),
309
+ hours: Number(hours ?? 0),
310
+ minutes: Number(minutes ?? 0),
311
+ seconds: Number(seconds ?? 0),
312
+ weeks: Number(weeks ?? 0)
313
+ });
314
+ return success(sign === "-" ? duration.negated() : duration, warnings.map(invalid));
315
+ } catch {
316
+ return failure(`${quote(raw)} is longer than a Temporal.Duration can hold`);
317
+ }
318
+ }
319
+ /** Sub-second parts are dropped: iCalendar has none. Years and months have no iCalendar form. */
320
+ function encodeDuration(duration) {
321
+ if (duration.years !== 0 || duration.months !== 0) throw new RangeError(`iCalendar can't write a DURATION in years or months: ${duration.toString()}`);
322
+ const { days, hours, minutes, seconds, weeks } = duration.abs();
323
+ const time = [
324
+ [hours, "H"],
325
+ [minutes, "M"],
326
+ [seconds, "S"]
327
+ ];
328
+ const first = time.findIndex(([value]) => value !== 0);
329
+ const last = time.findLastIndex(([value]) => value !== 0);
330
+ const date = `${weeks === 0 ? "" : `${weeks}W`}${days === 0 ? "" : `${days}D`}`;
331
+ const clock = first === -1 ? "" : `T${time.slice(first, last + 1).map(([value, unit]) => `${value}${unit}`).join("")}`;
332
+ if (date === "" && clock === "") return "PT0S";
333
+ return `${duration.sign < 0 ? "-" : ""}P${date}${clock}`;
334
+ }
335
+ //#endregion
336
+ //#region src/values/period.ts
337
+ function decodePeriod(raw, context) {
338
+ const slash = raw.indexOf("/");
339
+ if (slash === -1) return failure(`${quote(raw)} isn't a PERIOD (start/end or start/duration)`);
340
+ const start = decodeDateTime(raw.slice(0, slash), context);
341
+ if (!start.ok) return failure(`PERIOD start: ${start.message}`);
342
+ const endText = raw.slice(slash + 1);
343
+ const warnings = nested("PERIOD start", start);
344
+ if (/^[+-]?P/i.test(endText)) {
345
+ const duration = decodeDuration(endText);
346
+ if (!duration.ok) return failure(`PERIOD duration: ${duration.message}`);
347
+ warnings.push(...nested("PERIOD duration", duration));
348
+ if (duration.value.sign < 0) warnings.push(invalid("a PERIOD with a negative duration, which RFC 5545 doesn't allow"));
349
+ return success({
350
+ duration: duration.value,
351
+ start: start.value
352
+ }, warnings);
353
+ }
354
+ const end = decodeDateTime(endText, context);
355
+ if (!end.ok) return failure(`PERIOD end: ${end.message}`);
356
+ warnings.push(...nested("PERIOD end", end));
357
+ return success({
358
+ end: end.value,
359
+ start: start.value
360
+ }, warnings);
361
+ }
362
+ function encodePeriod(period) {
363
+ const end = "duration" in period ? encodeDuration(period.duration) : encodeDateValue(period.end);
364
+ return `${encodeDateValue(period.start)}/${end}`;
365
+ }
366
+ //#endregion
367
+ //#region src/values/recur.ts
368
+ const NUMBER_LIST_PARTS = /* @__PURE__ */ new Map([
369
+ ["BYSECOND", {
370
+ field: "bySecond",
371
+ max: 60,
372
+ min: 0
373
+ }],
374
+ ["BYMINUTE", {
375
+ field: "byMinute",
376
+ max: 59,
377
+ min: 0
378
+ }],
379
+ ["BYHOUR", {
380
+ field: "byHour",
381
+ max: 23,
382
+ min: 0
383
+ }],
384
+ ["BYMONTHDAY", {
385
+ field: "byMonthDay",
386
+ max: 31,
387
+ min: -31
388
+ }],
389
+ ["BYYEARDAY", {
390
+ field: "byYearDay",
391
+ max: 366,
392
+ min: -366
393
+ }],
394
+ ["BYWEEKNO", {
395
+ field: "byWeekNumber",
396
+ max: 53,
397
+ min: -53
398
+ }],
399
+ ["BYMONTH", {
400
+ field: "byMonth",
401
+ max: 12,
402
+ min: 1
403
+ }],
404
+ ["BYSETPOS", {
405
+ field: "bySetPosition",
406
+ max: 366,
407
+ min: -366
408
+ }]
409
+ ]);
410
+ const FREQUENCIES = /* @__PURE__ */ new Set([
411
+ "DAILY",
412
+ "HOURLY",
413
+ "MINUTELY",
414
+ "MONTHLY",
415
+ "SECONDLY",
416
+ "WEEKLY",
417
+ "YEARLY"
418
+ ]);
419
+ const WEEKDAYS = /* @__PURE__ */ new Set([
420
+ "FR",
421
+ "MO",
422
+ "SA",
423
+ "SU",
424
+ "TH",
425
+ "TU",
426
+ "WE"
427
+ ]);
428
+ const WEEKDAY_NUMBER = /^([+-]?\d{1,2})?([A-Z]{2})$/;
429
+ const INTEGER$1 = /^[+-]?\d{1,9}$/;
430
+ function integer(text) {
431
+ return INTEGER$1.test(text) ? Number(text) : void 0;
432
+ }
433
+ function numberList(text, { max, min }) {
434
+ const values = text.split(",").map(integer);
435
+ return values.every((value) => value !== void 0 && value >= min && value <= max && (min >= 0 || value !== 0)) ? values : void 0;
436
+ }
437
+ function weekdayList(text) {
438
+ const days = [];
439
+ for (const item of text.split(",")) {
440
+ const [, ordinal, weekday] = WEEKDAY_NUMBER.exec(item) ?? [];
441
+ const number = ordinal === void 0 ? void 0 : Number(ordinal);
442
+ if (weekday === void 0 || !WEEKDAYS.has(weekday) || number === 0 || Math.abs(number ?? 0) > 53) return;
443
+ days.push(number === void 0 ? { weekday } : {
444
+ ordinal: number,
445
+ weekday
446
+ });
447
+ }
448
+ return days;
449
+ }
450
+ /** Parses every rule part, in any order and any case. Invalid parts are dropped with a warning. */
451
+ function decodeRecur(raw) {
452
+ const rule = {};
453
+ const seen = /* @__PURE__ */ new Set();
454
+ const warnings = [];
455
+ const unsupported = [];
456
+ const drop = (part, why) => warnings.push(invalid(`dropped ${quote(part)}: ${why}`));
457
+ for (const part of raw.split(";")) {
458
+ if (part === "") continue;
459
+ const equals = part.indexOf("=");
460
+ if (equals === -1) {
461
+ drop(part, "not NAME=VALUE");
462
+ continue;
463
+ }
464
+ const name = part.slice(0, equals).toUpperCase();
465
+ const value = part.slice(equals + 1).toUpperCase();
466
+ if (seen.has(name)) {
467
+ drop(part, `${name} already appeared; the first one wins`);
468
+ continue;
469
+ }
470
+ seen.add(name);
471
+ const numbers = NUMBER_LIST_PARTS.get(name);
472
+ if (numbers !== void 0) {
473
+ const list = numberList(value, numbers);
474
+ if (list === void 0) drop(part, `${name} takes integers from ${numbers.min} to ${numbers.max}`);
475
+ else rule[numbers.field] = list;
476
+ continue;
477
+ }
478
+ switch (name) {
479
+ case "FREQ":
480
+ if (!FREQUENCIES.has(value)) return failure(`${quote(value)} isn't a recurrence frequency`);
481
+ rule.frequency = value;
482
+ break;
483
+ case "UNTIL": {
484
+ const until = decodeDateValue(value, void 0, {});
485
+ if (until.ok) {
486
+ rule.until = until.value;
487
+ warnings.push(...nested("UNTIL", until));
488
+ } else drop(part, until.message);
489
+ break;
490
+ }
491
+ case "COUNT":
492
+ case "INTERVAL": {
493
+ const number = integer(value);
494
+ if (number === void 0 || number < 1) drop(part, `${name} takes a positive integer`);
495
+ else rule[name === "COUNT" ? "count" : "interval"] = number;
496
+ break;
497
+ }
498
+ case "BYDAY": {
499
+ const days = weekdayList(value);
500
+ if (days === void 0) drop(part, "BYDAY takes weekdays such as MO, 1MO or -1FR");
501
+ else rule.byDay = days;
502
+ break;
503
+ }
504
+ case "WKST":
505
+ if (WEEKDAYS.has(value)) rule.weekStart = value;
506
+ else drop(part, "WKST takes a weekday");
507
+ break;
508
+ default: unsupported.push(name);
509
+ }
510
+ }
511
+ const { frequency } = rule;
512
+ if (frequency === void 0) return failure(`${quote(raw)} has no FREQ, which a recurrence rule requires`);
513
+ if (rule.count !== void 0 && rule.until !== void 0) warnings.push({
514
+ code: "conflicting-properties",
515
+ message: "COUNT with UNTIL, which RFC 5545 doesn't allow; kept both"
516
+ });
517
+ if (unsupported.length > 0) warnings.push({
518
+ code: "unsupported",
519
+ message: `unsupported rule parts ignored: ${unsupported.join(", ")}`
520
+ });
521
+ return success({
522
+ ...rule,
523
+ frequency
524
+ }, warnings);
525
+ }
526
+ function encodeUntil(until) {
527
+ return until.kind === "zoned" ? encodeInstant(until.zoned.toInstant()) : encodeDateValue(until);
528
+ }
529
+ /** Writes the parts in RFC 5545's grammar order, FREQ first; empty lists are left out. */
530
+ function encodeRecur(rule) {
531
+ return [
532
+ ["FREQ", rule.frequency],
533
+ ["UNTIL", rule.until && encodeUntil(rule.until)],
534
+ ["COUNT", rule.count],
535
+ ["INTERVAL", rule.interval],
536
+ ["BYSECOND", rule.bySecond?.join(",")],
537
+ ["BYMINUTE", rule.byMinute?.join(",")],
538
+ ["BYHOUR", rule.byHour?.join(",")],
539
+ ["BYDAY", rule.byDay?.map(({ ordinal, weekday }) => `${ordinal ?? ""}${weekday}`).join(",")],
540
+ ["BYMONTHDAY", rule.byMonthDay?.join(",")],
541
+ ["BYYEARDAY", rule.byYearDay?.join(",")],
542
+ ["BYWEEKNO", rule.byWeekNumber?.join(",")],
543
+ ["BYMONTH", rule.byMonth?.join(",")],
544
+ ["BYSETPOS", rule.bySetPosition?.join(",")],
545
+ ["WKST", rule.weekStart]
546
+ ].filter(([, value]) => value !== void 0 && value !== "").map(([name, value]) => `${name}=${value}`).join(";");
547
+ }
548
+ //#endregion
549
+ //#region src/values/scalars.ts
550
+ const INTEGER = /^[+-]?\d+$/;
551
+ const FLOAT = /^[+-]?\d+(?:\.\d+)?$/;
552
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
553
+ const EXPONENT = /^(-?)(\d+)(?:\.(\d+))?e([+-]\d+)$/;
554
+ function decodeInteger(raw) {
555
+ const value = Number(raw);
556
+ return INTEGER.test(raw) && Number.isSafeInteger(value) ? success(value) : failure(`${quote(raw)} isn't an INTEGER`);
557
+ }
558
+ function decodeFloat(raw) {
559
+ const value = Number(raw);
560
+ return FLOAT.test(raw) && Number.isFinite(value) ? success(value) : failure(`${quote(raw)} isn't a FLOAT`);
561
+ }
562
+ function decodeBoolean(raw) {
563
+ const upper = raw.toUpperCase();
564
+ return upper === "TRUE" || upper === "FALSE" ? success(upper === "TRUE") : failure(`${quote(raw)} isn't a BOOLEAN (TRUE or FALSE)`);
565
+ }
566
+ /** Checks the alphabet only; the data stays as written. */
567
+ function decodeBinary(raw) {
568
+ return BASE64.test(raw) ? success(raw) : failure(`${quote(raw)} isn't base64`);
569
+ }
570
+ function encodeInteger(value) {
571
+ if (!Number.isSafeInteger(value)) throw new RangeError(`Not an integer: ${value}`);
572
+ return String(value);
573
+ }
574
+ function encodeFloat(value) {
575
+ if (!Number.isFinite(value)) throw new RangeError(`iCalendar can't write the FLOAT ${value}`);
576
+ const text = Object.is(value, -0) ? "-0" : String(value);
577
+ const [, sign, whole, fraction = "", exponent] = EXPONENT.exec(text) ?? [];
578
+ if (whole === void 0) return text;
579
+ const digits = `${whole}${fraction}`;
580
+ const point = whole.length + Number(exponent);
581
+ if (point <= 0) return `${sign}0.${"0".repeat(-point)}${digits}`;
582
+ return point >= digits.length ? `${sign}${digits}${"0".repeat(point - digits.length)}` : `${sign}${digits.slice(0, point)}.${digits.slice(point)}`;
583
+ }
584
+ //#endregion
585
+ //#region src/values/text.ts
586
+ const ESCAPES = /* @__PURE__ */ new Map([
587
+ [",", ","],
588
+ [";", ";"],
589
+ ["N", "\n"],
590
+ ["\\", "\\"],
591
+ ["n", "\n"]
592
+ ]);
593
+ function decodeText(raw) {
594
+ if (!raw.includes("\\")) return success(raw);
595
+ const unknown = /* @__PURE__ */ new Set();
596
+ const warnings = [];
597
+ const text = raw.replaceAll(/\\(.?)/gsu, (escape, next) => {
598
+ if (next === "") {
599
+ warnings.push("TEXT ends in a lone backslash; kept it");
600
+ return escape;
601
+ }
602
+ const unescaped = ESCAPES.get(next);
603
+ if (unescaped === void 0) unknown.add(escape);
604
+ return unescaped ?? next;
605
+ });
606
+ if (unknown.size > 0) warnings.unshift(`TEXT has escapes RFC 5545 doesn't define (${[...unknown].join(" ")}); dropped their backslashes`);
607
+ return success(text, warnings.map(invalid));
608
+ }
609
+ function encodeText(text) {
610
+ return text.replaceAll(/\r\n|[\r\n\\;,]/g, (char) => char === "\\" || char === ";" || char === "," ? `\\${char}` : "\\n");
611
+ }
612
+ /**
613
+ * Splits a list value on its separating commas. Only TEXT escapes commas, and `\\,` there is an
614
+ * escaped backslash before a separator. RECUR uses commas inside its parts, so it never splits.
615
+ */
616
+ function splitList(type, raw) {
617
+ if (type === "RECUR") return [raw];
618
+ if (type !== "TEXT" || !raw.includes("\\")) return raw.split(",");
619
+ const items = [];
620
+ let start = 0;
621
+ for (let index = 0; index < raw.length; index += 1) if (raw[index] === "\\") index += 1;
622
+ else if (raw[index] === ",") {
623
+ items.push(raw.slice(start, index));
624
+ start = index + 1;
625
+ }
626
+ items.push(raw.slice(start));
627
+ return items;
628
+ }
629
+ //#endregion
630
+ //#region src/values/utc-offset.ts
631
+ const UTC_OFFSET$1 = /^([+-])?(\d{2}):?(\d{2})(?::?(\d{2}))?$/;
632
+ const OFFSET_STRING = /^([+-])(\d{2}):(\d{2})(?::(\d{2}))?$/;
633
+ function decodeUtcOffset(raw) {
634
+ const match = UTC_OFFSET$1.exec(raw);
635
+ if (!match) return failure(`${quote(raw)} isn't a UTC-OFFSET (±HHMM or ±HHMMSS)`);
636
+ const [, sign, hours, minutes, seconds] = match;
637
+ if (Number(hours) > 23 || Number(minutes) > 59 || Number(seconds ?? 0) > 59) return failure(`${quote(raw)} is out of range for a UTC-OFFSET`);
638
+ const warnings = [];
639
+ if (sign === void 0) warnings.push("a UTC-OFFSET without a sign; read as +");
640
+ if (raw.includes(":")) warnings.push("a UTC-OFFSET with colons; read without");
641
+ const zero = Number(hours) + Number(minutes) + Number(seconds ?? 0) === 0;
642
+ if (zero && sign === "-") warnings.push("-0000 isn't a valid UTC-OFFSET; read as +0000");
643
+ return success(`${sign !== "-" || zero ? "+" : "-"}${hours}:${minutes}${seconds === void 0 ? "" : `:${seconds}`}`, warnings.map(invalid));
644
+ }
645
+ function encodeUtcOffset(offset) {
646
+ const match = OFFSET_STRING.exec(offset);
647
+ if (!match) throw new RangeError(`Not a ±HH:MM[:SS] offset: ${offset}`);
648
+ const [, sign, hours, minutes, seconds = ""] = match;
649
+ return `${/^0+$/.test(`${hours}${minutes}${seconds}`) ? "+" : sign}${hours}${minutes}${seconds}`;
650
+ }
651
+ //#endregion
652
+ //#region src/values/registry.ts
653
+ const VALUE_TYPES = /* @__PURE__ */ new Set([
654
+ "BINARY",
655
+ "BOOLEAN",
656
+ "CAL-ADDRESS",
657
+ "DATE",
658
+ "DATE-TIME",
659
+ "DURATION",
660
+ "FLOAT",
661
+ "INTEGER",
662
+ "PERIOD",
663
+ "RECUR",
664
+ "TEXT",
665
+ "TIME",
666
+ "URI",
667
+ "UTC-OFFSET"
668
+ ]);
669
+ const DEFAULT_VALUE_TYPES = {
670
+ ACKNOWLEDGED: "DATE-TIME",
671
+ ATTACH: "URI",
672
+ ATTENDEE: "CAL-ADDRESS",
673
+ COMPLETED: "DATE-TIME",
674
+ CONFERENCE: "URI",
675
+ CREATED: "DATE-TIME",
676
+ DTEND: "DATE-TIME",
677
+ DTSTAMP: "DATE-TIME",
678
+ DTSTART: "DATE-TIME",
679
+ DUE: "DATE-TIME",
680
+ DURATION: "DURATION",
681
+ EXDATE: "DATE-TIME",
682
+ EXRULE: "RECUR",
683
+ FREEBUSY: "PERIOD",
684
+ GEO: "FLOAT",
685
+ IMAGE: "URI",
686
+ "LAST-MODIFIED": "DATE-TIME",
687
+ ORGANIZER: "CAL-ADDRESS",
688
+ "PERCENT-COMPLETE": "INTEGER",
689
+ PRIORITY: "INTEGER",
690
+ RDATE: "DATE-TIME",
691
+ "RECURRENCE-ID": "DATE-TIME",
692
+ "REFRESH-INTERVAL": "DURATION",
693
+ REPEAT: "INTEGER",
694
+ RRULE: "RECUR",
695
+ SEQUENCE: "INTEGER",
696
+ SOURCE: "URI",
697
+ TRIGGER: "DURATION",
698
+ TZOFFSETFROM: "UTC-OFFSET",
699
+ TZOFFSETTO: "UTC-OFFSET",
700
+ TZURL: "URI",
701
+ URL: "URI",
702
+ "X-PUBLISHED-TTL": "DURATION"
703
+ };
704
+ /** The property's value type: its VALUE parameter, else its registered default, else TEXT. */
705
+ function icsValueTypeOf(property) {
706
+ const declared = property.parameters["VALUE"]?.[0];
707
+ if (declared !== void 0) {
708
+ const type = declared.toUpperCase();
709
+ return VALUE_TYPES.has(type) ? type : "TEXT";
710
+ }
711
+ const name = property.name.toUpperCase();
712
+ return Object.hasOwn(DEFAULT_VALUE_TYPES, name) ? DEFAULT_VALUE_TYPES[name] : "TEXT";
713
+ }
714
+ //#endregion
715
+ //#region src/values/index.ts
716
+ const asWritten = (raw) => success(raw);
717
+ const identity = (value) => value;
718
+ const DECODERS = {
719
+ BINARY: decodeBinary,
720
+ BOOLEAN: decodeBoolean,
721
+ "CAL-ADDRESS": asWritten,
722
+ DATE: decodeDate,
723
+ "DATE-TIME": decodeDateTime,
724
+ DURATION: decodeDuration,
725
+ FLOAT: decodeFloat,
726
+ INTEGER: decodeInteger,
727
+ PERIOD: decodePeriod,
728
+ RECUR: decodeRecur,
729
+ TEXT: decodeText,
730
+ TIME: decodeTime,
731
+ URI: asWritten,
732
+ "UTC-OFFSET": decodeUtcOffset
733
+ };
734
+ const ENCODERS = {
735
+ BINARY: identity,
736
+ BOOLEAN: (value) => value ? "TRUE" : "FALSE",
737
+ "CAL-ADDRESS": identity,
738
+ DATE: encodeDateValue,
739
+ "DATE-TIME": encodeDateValue,
740
+ DURATION: encodeDuration,
741
+ FLOAT: encodeFloat,
742
+ INTEGER: encodeInteger,
743
+ PERIOD: encodePeriod,
744
+ RECUR: encodeRecur,
745
+ TEXT: encodeText,
746
+ TIME: ({ time, utc }) => `${encodeTime(time)}${utc ? "Z" : ""}`,
747
+ URI: identity,
748
+ "UTC-OFFSET": encodeUtcOffset
749
+ };
750
+ /**
751
+ * Decodes one raw value as `type`. It doesn't split lists: use `decodeIcsValues` for a property
752
+ * such as CATEGORIES or EXDATE. Never throws: a value that doesn't parse is `{ ok: false }`, and
753
+ * one read leniently carries `warnings`.
754
+ */
755
+ function decodeIcsValue(type, raw, context = {}) {
756
+ return Object.hasOwn(DECODERS, type) ? DECODERS[type](raw, context) : failure(`Unknown value type ${JSON.stringify(type)}`);
757
+ }
758
+ /**
759
+ * The items of a list value, such as CATEGORIES or EXDATE, as raw text: split on separating
760
+ * commas, TEXT escapes left in place, so `a\,b,c` gives `a\,b` and `c`. RECUR, whose parts hold
761
+ * commas, is never split.
762
+ */
763
+ function splitIcsValues(type, raw) {
764
+ return splitList(type, raw);
765
+ }
766
+ /**
767
+ * Splits a list value on its separating commas and decodes each item as `type`: one result per
768
+ * item, in order, so one bad item doesn't lose the others.
769
+ */
770
+ function decodeIcsValues(type, raw, context = {}) {
771
+ return splitList(type, raw).map((item) => decodeIcsValue(type, item, context));
772
+ }
773
+ /**
774
+ * Decodes a DATE or DATE-TIME by its shape, so a date written without `VALUE=DATE` still decodes
775
+ * (with a warning). `declared` is the property's value type, as `icsValueTypeOf` gives it. Use it
776
+ * for DTSTART, DTEND, DUE, RECURRENCE-ID and each item of EXDATE or RDATE.
777
+ */
778
+ function decodeIcsDateValue(raw, declared, context = {}) {
779
+ return decodeDateValue(raw, declared, context);
780
+ }
781
+ /**
782
+ * Encodes one value as raw property text. Zoned and unresolved DATE-TIMEs are written as their wall
783
+ * time; writing the TZID parameter is the caller's job.
784
+ */
785
+ function encodeIcsValue(type, value) {
786
+ if (!Object.hasOwn(ENCODERS, type)) throw new TypeError(`Unknown value type ${JSON.stringify(type)}`);
787
+ return ENCODERS[type](value);
788
+ }
789
+ //#endregion
790
+ //#region src/model/extensions.ts
791
+ /** Declares a typed extension property, such as `X-RESOURCE-ID`, for `IcsParseOptions.extensions`. */
792
+ function icsExtension(name, options) {
793
+ return {
794
+ multiple: Boolean(options?.multiple),
795
+ name: name.toUpperCase(),
796
+ schema: options?.schema,
797
+ type: options?.type ?? "TEXT"
798
+ };
799
+ }
800
+ function extensionEntries(map) {
801
+ return map === void 0 ? [] : Object.entries(map);
802
+ }
803
+ function isPromise(value) {
804
+ return typeof value?.then === "function";
805
+ }
806
+ function extensionValue(read, property, raw, { schema, type }, at, dropAt) {
807
+ const context = read.context(property);
808
+ const result = type === "DATE" || type === "DATE-TIME" ? decodeIcsDateValue(raw, type, context) : decodeIcsValue(type, raw, context);
809
+ const value = read.decode(property, result, at, dropAt);
810
+ if (value === void 0) return void 0;
811
+ if (schema === void 0) return { value };
812
+ const outcome = schema["~standard"].validate(value);
813
+ if (isPromise(outcome)) {
814
+ Promise.resolve(outcome).catch(() => void 0);
815
+ const message = `${property.name}: asynchronous schemas aren't supported; dropped`;
816
+ read.report("error", "schema", message, property, dropAt);
817
+ return;
818
+ }
819
+ if (outcome.issues) {
820
+ const messages = outcome.issues.map((issue) => issue.message).join("; ");
821
+ read.report("error", "schema", `${property.name}: ${messages}`, property, dropAt);
822
+ return;
823
+ }
824
+ return { value: outcome.value };
825
+ }
826
+ function readExtensions(read, entries) {
827
+ const values = {};
828
+ for (const [field, extension] of entries) {
829
+ const at = ["extensions", field];
830
+ if (!extension.multiple) {
831
+ const property = read.one(extension.name, at);
832
+ values[field] = property && extensionValue(read, property, property.value, extension, at, at)?.value;
833
+ continue;
834
+ }
835
+ const items = [];
836
+ for (const property of read.all(extension.name)) for (const raw of splitIcsValues(extension.type, property.value)) {
837
+ if (raw === "") continue;
838
+ const item = extensionValue(read, property, raw, extension, [...at, items.length], at);
839
+ if (item !== void 0) items.push(item.value);
840
+ }
841
+ values[field] = items;
842
+ }
843
+ return values;
844
+ }
845
+ //#endregion
846
+ //#region src/issues.ts
847
+ /** Thrown by a strict parser when it finds error-severity issues. */
848
+ var IcsParseError = class extends Error {
849
+ issues;
850
+ constructor(issues) {
851
+ const [first] = issues;
852
+ const more = issues.length > 1 ? ` (and ${issues.length - 1} more)` : "";
853
+ super(first ? `${first.message}${more}` : "Invalid iCalendar data");
854
+ this.name = "IcsParseError";
855
+ this.issues = issues;
856
+ }
857
+ };
858
+ //#endregion
859
+ //#region src/syntax/parameters.ts
860
+ /** Decodes RFC 6868 caret escapes. Any other caret sequence stays as written, as §3.2 asks. */
861
+ function decodeParameterValue(raw) {
862
+ let caret = raw.indexOf("^");
863
+ if (caret === -1) return raw;
864
+ let decoded = "";
865
+ let from = 0;
866
+ while (caret !== -1 && caret < raw.length - 1) {
867
+ const next = raw[caret + 1];
868
+ const replacement = next === "n" ? "\n" : next === "^" ? "^" : next === "'" ? "\"" : void 0;
869
+ if (replacement === void 0) caret = raw.indexOf("^", caret + 1);
870
+ else {
871
+ decoded += raw.slice(from, caret) + replacement;
872
+ from = caret + 2;
873
+ caret = raw.indexOf("^", from);
874
+ }
875
+ }
876
+ return decoded + raw.slice(from);
877
+ }
878
+ /**
879
+ * RFC 6868-encodes a parameter value and quotes it when it holds `:`, `;` or `,`. Any line break,
880
+ * CRLF included, becomes `^n`, since a raw one would end the content line.
881
+ */
882
+ function encodeParameterValue(value) {
883
+ const encoded = /[\n\r"^]/.test(value) ? value.replace(/\r\n|[\n\r"^]/g, (match) => match === "^" ? "^^" : match === "\"" ? "^'" : "^n") : value;
884
+ return /[,:;]/.test(encoded) ? `"${encoded}"` : encoded;
885
+ }
886
+ //#endregion
887
+ //#region src/syntax/content-line.ts
888
+ const COLON = 58;
889
+ const COMMA = 44;
890
+ const EQUALS = 61;
891
+ const QUOTE = 34;
892
+ const SEMICOLON = 59;
893
+ /**
894
+ * Splits `name *(";" param) ":" value`, or returns `undefined` when the line isn't one: no name,
895
+ * no colon outside quotes, or a parameter name with characters a name can't have. Tolerated, and
896
+ * listed in `problems`: a parameter without `=` (kept with no values), an unterminated quote or a
897
+ * stray one (kept as a literal character), and text after a closing quote (appended to the value).
898
+ */
899
+ function parseContentLine(text) {
900
+ const length = text.length;
901
+ let position = scanName(text, 0);
902
+ if (position === 0) return void 0;
903
+ const name = text.slice(0, position).toUpperCase();
904
+ const parameters = Object.create(null);
905
+ let problems;
906
+ while (position < length) {
907
+ const code = text.charCodeAt(position);
908
+ if (code === COLON) return {
909
+ name,
910
+ parameters,
911
+ problems,
912
+ value: text.slice(position + 1)
913
+ };
914
+ if (code !== SEMICOLON) return void 0;
915
+ const nameStart = position + 1;
916
+ position = scanName(text, nameStart);
917
+ if (position === nameStart) return void 0;
918
+ const parameterName = text.slice(nameStart, position).toUpperCase();
919
+ const values = parameters[parameterName] ??= [];
920
+ const separator = text.charCodeAt(position);
921
+ if (separator === SEMICOLON || separator === COLON) {
922
+ (problems ??= []).push(`Parameter ${parameterName} has no "="; kept without a value`);
923
+ continue;
924
+ }
925
+ if (separator !== EQUALS) return void 0;
926
+ position += 1;
927
+ for (;;) {
928
+ let raw;
929
+ const close = text.charCodeAt(position) === QUOTE ? text.indexOf("\"", position + 1) : -1;
930
+ if (close !== -1) {
931
+ raw = text.slice(position + 1, close);
932
+ position = close + 1;
933
+ if (position >= length) return void 0;
934
+ if (!isValueEnd(text.charCodeAt(position))) {
935
+ const end = scanParameterText(text, position);
936
+ raw += text.slice(position, end);
937
+ position = end;
938
+ (problems ??= []).push(`Parameter ${parameterName} has text after its closing quote`);
939
+ }
940
+ } else {
941
+ const end = scanParameterText(text, position);
942
+ raw = text.slice(position, end);
943
+ position = end;
944
+ if (raw.includes("\"")) (problems ??= []).push(`Parameter ${parameterName} has a stray double quote`);
945
+ }
946
+ values.push(decodeParameterValue(raw));
947
+ if (text.charCodeAt(position) !== COMMA) break;
948
+ position += 1;
949
+ }
950
+ }
951
+ }
952
+ function scanName(text, start) {
953
+ let position = start;
954
+ while (position < text.length && isNameCode(text.charCodeAt(position))) position += 1;
955
+ return position;
956
+ }
957
+ function scanParameterText(text, start) {
958
+ let position = start;
959
+ while (position < text.length && !isValueEnd(text.charCodeAt(position))) position += 1;
960
+ return position;
961
+ }
962
+ function isValueEnd(code) {
963
+ return code === COMMA || code === SEMICOLON || code === COLON;
964
+ }
965
+ function isNameCode(code) {
966
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45;
967
+ }
968
+ //#endregion
969
+ //#region src/syntax/lines.ts
970
+ const SPACE = 32;
971
+ const TAB = 9;
972
+ const BOM = 65279;
973
+ /**
974
+ * Calls `onLine` with each unfolded line and the 1-based physical line it starts on. Accepts CRLF,
975
+ * LF and lone CR. Blank physical lines are skipped without ending a folded line, so files whose
976
+ * line ends got doubled (`\r\r\n`) still unfold; whitespace-only logical lines are skipped too.
977
+ * Each doubled end counts as two physical lines, a lone CR and then a CRLF, so line numbers in
978
+ * such files come out about twice what the producer meant.
979
+ */
980
+ function forEachUnfoldedLine(text, onLine) {
981
+ const length = text.length;
982
+ let position = text.charCodeAt(0) === BOM ? 1 : 0;
983
+ let physical = 0;
984
+ let nextLf = -2;
985
+ let nextCr = -2;
986
+ let parts = [];
987
+ let partsLine = 0;
988
+ const flush = () => {
989
+ if (parts.length === 0) return;
990
+ const content = parts.length === 1 ? parts[0] : parts.join("");
991
+ parts = [];
992
+ if (!isBlank(content)) onLine(content, partsLine);
993
+ };
994
+ while (position < length) {
995
+ physical += 1;
996
+ if (nextLf !== -1 && nextLf < position) nextLf = text.indexOf("\n", position);
997
+ if (nextCr !== -1 && nextCr < position) nextCr = text.indexOf("\r", position);
998
+ let end = length;
999
+ let next = length;
1000
+ if (nextCr !== -1 && (nextLf === -1 || nextCr < nextLf)) {
1001
+ end = nextCr;
1002
+ next = nextLf === nextCr + 1 ? nextCr + 2 : nextCr + 1;
1003
+ } else if (nextLf !== -1) {
1004
+ end = nextLf;
1005
+ next = nextLf + 1;
1006
+ }
1007
+ if (end > position) {
1008
+ const first = text.charCodeAt(position);
1009
+ if ((first === SPACE || first === TAB) && parts.length > 0) parts.push(text.slice(position + 1, end));
1010
+ else {
1011
+ flush();
1012
+ parts.push(text.slice(position, end));
1013
+ partsLine = physical;
1014
+ }
1015
+ }
1016
+ position = next;
1017
+ }
1018
+ flush();
1019
+ }
1020
+ function isBlank(content) {
1021
+ const first = content.charCodeAt(0);
1022
+ if (first !== SPACE && first !== TAB) return false;
1023
+ return content.trim() === "";
1024
+ }
1025
+ //#endregion
1026
+ //#region src/syntax/parse.ts
1027
+ function parseComponents(text) {
1028
+ const roots = [];
1029
+ const stack = [];
1030
+ const openCounts = /* @__PURE__ */ new Map();
1031
+ const issues = [];
1032
+ let hasContent = false;
1033
+ let lastProperty;
1034
+ const report = (severity, code, message, line, component, property) => {
1035
+ const issue = {
1036
+ code,
1037
+ line,
1038
+ message,
1039
+ path: [],
1040
+ severity
1041
+ };
1042
+ if (component !== void 0) issue.component = component;
1043
+ if (property !== void 0) issue.property = property;
1044
+ issues.push(issue);
1045
+ };
1046
+ const close = (component) => {
1047
+ const count = openCounts.get(component.name);
1048
+ if (count === 1) openCounts.delete(component.name);
1049
+ else openCounts.set(component.name, count - 1);
1050
+ };
1051
+ forEachUnfoldedLine(text, (content, line) => {
1052
+ hasContent = true;
1053
+ const current = stack.at(-1);
1054
+ const parsed = parseContentLine(content);
1055
+ if (parsed === void 0) {
1056
+ if (lastProperty !== void 0) {
1057
+ lastProperty.value += `\\n${content}`;
1058
+ report("warning", "invalid-content-line", `Line is not a content line; appended to ${lastProperty.name} as a line break`, line, current?.name, lastProperty.name);
1059
+ } else report("warning", "invalid-content-line", current === void 0 ? "Line outside any component is not a content line; dropped" : "Line is not a content line and follows no property; dropped", line, current?.name);
1060
+ return;
1061
+ }
1062
+ if (parsed.name === "BEGIN" || parsed.name === "END") {
1063
+ lastProperty = void 0;
1064
+ const name = parsed.value.trim().toUpperCase();
1065
+ if (name === "") {
1066
+ report("warning", "invalid-structure", `${parsed.name} without a component name; ignored`, line, current?.name);
1067
+ return;
1068
+ }
1069
+ if (parsed.name === "BEGIN") {
1070
+ const component = {
1071
+ components: [],
1072
+ line,
1073
+ name,
1074
+ properties: []
1075
+ };
1076
+ (current === void 0 ? roots : current.components).push(component);
1077
+ stack.push(component);
1078
+ openCounts.set(name, (openCounts.get(name) ?? 0) + 1);
1079
+ return;
1080
+ }
1081
+ if (!openCounts.has(name)) {
1082
+ report("warning", "invalid-structure", `END:${name} has no matching BEGIN; ignored`, line, name);
1083
+ return;
1084
+ }
1085
+ for (;;) {
1086
+ const component = stack.pop();
1087
+ close(component);
1088
+ if (component.name === name) break;
1089
+ report("warning", "invalid-structure", `${component.name} from line ${component.line} is closed by END:${name}`, line, component.name);
1090
+ }
1091
+ return;
1092
+ }
1093
+ for (const problem of parsed.problems ?? []) report("warning", "invalid-content-line", problem, line, current?.name, parsed.name);
1094
+ if (current === void 0) {
1095
+ lastProperty = void 0;
1096
+ report("warning", "invalid-structure", `${parsed.name} is outside any component; dropped`, line, void 0, parsed.name);
1097
+ return;
1098
+ }
1099
+ lastProperty = {
1100
+ line,
1101
+ name: parsed.name,
1102
+ parameters: parsed.parameters,
1103
+ value: parsed.value
1104
+ };
1105
+ current.properties.push(lastProperty);
1106
+ });
1107
+ for (let index = stack.length - 1; index >= 0; index -= 1) {
1108
+ const component = stack[index];
1109
+ report("warning", "invalid-structure", `${component.name} is never closed; closed at the end of the text`, component.line, component.name);
1110
+ }
1111
+ if (roots.length === 0 && hasContent) return {
1112
+ components: [],
1113
+ issues: [{
1114
+ code: "invalid-structure",
1115
+ message: "The text contains no iCalendar component",
1116
+ path: [],
1117
+ severity: "error"
1118
+ }]
1119
+ };
1120
+ return {
1121
+ components: roots,
1122
+ issues
1123
+ };
1124
+ }
1125
+ //#endregion
1126
+ //#region src/syntax/stringify.ts
1127
+ const MAX_OCTETS = 75;
1128
+ function stringifyComponents(components) {
1129
+ const lines = [];
1130
+ const pending = [...components].reverse();
1131
+ while (pending.length > 0) {
1132
+ const item = pending.pop();
1133
+ if (typeof item === "string") {
1134
+ lines.push(foldLine(`END:${item}`));
1135
+ continue;
1136
+ }
1137
+ assertNoLineBreak(item.name, () => `Component name ${JSON.stringify(item.name)}`);
1138
+ lines.push(foldLine(`BEGIN:${item.name}`));
1139
+ for (const property of item.properties) lines.push(foldLine(formatProperty(property)));
1140
+ pending.push(item.name);
1141
+ for (let index = item.components.length - 1; index >= 0; index -= 1) pending.push(item.components[index]);
1142
+ }
1143
+ return lines.join("");
1144
+ }
1145
+ function formatProperty(property) {
1146
+ const { name } = property;
1147
+ assertNoLineBreak(name, () => `Property name ${JSON.stringify(name)}`);
1148
+ let line = name;
1149
+ for (const parameter in property.parameters) {
1150
+ const values = property.parameters[parameter];
1151
+ if (values === void 0) continue;
1152
+ assertNoLineBreak(parameter, () => `Parameter name ${JSON.stringify(parameter)} of ${name}`);
1153
+ line += values.length === 0 ? `;${parameter}` : `;${parameter}=${values.map(encodeParameterValue).join(",")}`;
1154
+ }
1155
+ assertNoLineBreak(property.value, () => `Value of ${name}`);
1156
+ return `${line}:${property.value}`;
1157
+ }
1158
+ function assertNoLineBreak(text, subject) {
1159
+ if (text.includes("\n") || text.includes("\r")) throw new RangeError(`${subject()} contains a line break, which iCalendar text can't hold`);
1160
+ }
1161
+ /**
1162
+ * Folds a line into physical lines of at most 75 UTF-8 octets, each ending in CRLF. Continuation
1163
+ * lines start with a space that counts toward their 75. Breaks fall between code points only.
1164
+ */
1165
+ function foldLine(line) {
1166
+ if (line.length * 3 <= MAX_OCTETS) return `${line}\r\n`;
1167
+ let folded = "";
1168
+ let start = 0;
1169
+ let octets = 0;
1170
+ let index = 0;
1171
+ while (index < line.length) {
1172
+ const code = line.charCodeAt(index);
1173
+ let units = 1;
1174
+ let size;
1175
+ if (code < 128) size = 1;
1176
+ else if (code < 2048) size = 2;
1177
+ else if (code >= 55296 && code <= 56319 && isLowSurrogate(line.charCodeAt(index + 1))) {
1178
+ size = 4;
1179
+ units = 2;
1180
+ } else size = 3;
1181
+ if (octets + size > MAX_OCTETS) {
1182
+ folded += `${line.slice(start, index)}\r\n `;
1183
+ start = index;
1184
+ octets = 1;
1185
+ }
1186
+ octets += size;
1187
+ index += units;
1188
+ }
1189
+ return `${folded}${line.slice(start)}\r\n`;
1190
+ }
1191
+ function isLowSurrogate(code) {
1192
+ return code >= 56320 && code <= 57343;
1193
+ }
1194
+ //#endregion
1195
+ //#region src/syntax/index.ts
1196
+ /** Splits iCalendar text into a lossless component tree, collecting syntax issues. */
1197
+ function parseIcsComponents(text) {
1198
+ return parseComponents(text);
1199
+ }
1200
+ /**
1201
+ * Writes components back as iCalendar text: CRLF line ends, folded at 75 octets. Parameter values
1202
+ * are RFC 6868-encoded, so they may hold line breaks; values are written as they are.
1203
+ *
1204
+ * @throws {RangeError} When a component name, property name, parameter name or property value
1205
+ * contains CR or LF, which would end the content line. The message names the property. Escape
1206
+ * line breaks in TEXT values as `\n` first.
1207
+ */
1208
+ function stringifyIcsComponents(components) {
1209
+ return stringifyComponents(isComponentList(components) ? components : [components]);
1210
+ }
1211
+ function isComponentList(components) {
1212
+ return Array.isArray(components);
1213
+ }
1214
+ //#endregion
1215
+ //#region src/time-zones/canonical.ts
1216
+ const CACHE_LIMIT = 1024;
1217
+ const cache = /* @__PURE__ */ new Map();
1218
+ /** The canonical id Temporal uses for `id`, or `undefined` when Temporal doesn't know it. */
1219
+ function canonicalTimeZoneId(id) {
1220
+ if (cache.has(id)) return cache.get(id);
1221
+ let canonical;
1222
+ try {
1223
+ canonical = new Temporal.ZonedDateTime(0n, id).timeZoneId;
1224
+ } catch (error) {
1225
+ if (!(error instanceof RangeError)) throw error;
1226
+ }
1227
+ if (cache.size >= CACHE_LIMIT) cache.clear();
1228
+ cache.set(id, canonical);
1229
+ return canonical;
1230
+ }
1231
+ function offsetTimeZoneId(sign, hours, minutes, seconds = 0) {
1232
+ if (minutes > 59 || seconds !== 0) return void 0;
1233
+ const pad = (value) => String(value).padStart(2, "0");
1234
+ return canonicalTimeZoneId(`${sign === "-" ? "-" : "+"}${pad(hours)}:${pad(minutes)}`);
1235
+ }
1236
+ //#endregion
1237
+ //#region src/time-zones/definition.ts
1238
+ const UTC_OFFSET = /^([+-])(\d{2}):?(\d{2})(?::?(\d{2}))?$/;
1239
+ function propertyValue(component, name) {
1240
+ return component.properties.find((property) => property.name === name)?.value.trim();
1241
+ }
1242
+ function offsetTo(observance) {
1243
+ const match = UTC_OFFSET.exec(propertyValue(observance, "TZOFFSETTO") ?? "");
1244
+ if (!match) return void 0;
1245
+ const [, sign = "+", hours = "", minutes = "", seconds = "0"] = match;
1246
+ return offsetTimeZoneId(sign, Number(hours), Number(minutes), Number(seconds));
1247
+ }
1248
+ function observances(definition) {
1249
+ return definition.components.filter((component) => component.name === "STANDARD" || component.name === "DAYLIGHT");
1250
+ }
1251
+ function definitionOffsets(definition) {
1252
+ const offsets = /* @__PURE__ */ new Set();
1253
+ for (const observance of observances(definition)) {
1254
+ const match = UTC_OFFSET.exec(propertyValue(observance, "TZOFFSETTO") ?? "");
1255
+ if (!match) continue;
1256
+ const [, sign, hours = "", minutes = "", seconds = "0"] = match;
1257
+ offsets.add((sign === "-" ? -1 : 1) * (Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds)));
1258
+ }
1259
+ return offsets;
1260
+ }
1261
+ function definitionTimeZone(definition) {
1262
+ const location = propertyValue(definition, "X-LIC-LOCATION");
1263
+ const named = location === void 0 ? void 0 : canonicalTimeZoneId(location);
1264
+ if (named !== void 0) return named;
1265
+ const [first, ...rest] = observances(definition).map(offsetTo);
1266
+ return first !== void 0 && rest.every((offset) => offset === first) ? first : void 0;
1267
+ }
1268
+ //#endregion
1269
+ //#region src/time-zones/history.ts
1270
+ const EARLIEST = -8640000000000000000000n;
1271
+ const LAST_SAMPLED_YEAR = 2040;
1272
+ const samples = /* @__PURE__ */ new Map();
1273
+ function fitsDefinitionOffsets(timeZone, offsets) {
1274
+ if (new Temporal.ZonedDateTime(0n, timeZone).getTimeZoneTransition("next") !== null) return true;
1275
+ const seen = /* @__PURE__ */ new Set();
1276
+ let zoned = new Temporal.ZonedDateTime(EARLIEST, timeZone);
1277
+ while (zoned !== null) {
1278
+ seen.add(zoned.offsetNanoseconds / 1e9);
1279
+ zoned = zoned.getTimeZoneTransition("next");
1280
+ }
1281
+ for (const offset of offsets) if (!seen.has(offset)) return false;
1282
+ return true;
1283
+ }
1284
+ function hadOffset(timeZone, offset, from) {
1285
+ const key = `${timeZone} ${from}`;
1286
+ let offsets = samples.get(key);
1287
+ if (offsets === void 0) {
1288
+ const sampled = /* @__PURE__ */ new Set();
1289
+ for (let year = from; year <= LAST_SAMPLED_YEAR; year += 1) for (const month of [1, 7]) sampled.add(Temporal.ZonedDateTime.from({
1290
+ day: 1,
1291
+ month,
1292
+ timeZone,
1293
+ year
1294
+ }).offset);
1295
+ offsets = sampled;
1296
+ samples.set(key, offsets);
1297
+ }
1298
+ return offsets.has(offset);
1299
+ }
1300
+ //#endregion
1301
+ //#region src/time-zones/windows-zones.ts
1302
+ /*!
1303
+ * UNICODE LICENSE V3
1304
+ *
1305
+ * COPYRIGHT AND PERMISSION NOTICE
1306
+ *
1307
+ * Copyright © 2004-2026 Unicode, Inc.
1308
+ *
1309
+ * NOTICE TO USER: Carefully read the following legal agreement. BY
1310
+ * DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
1311
+ * SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
1312
+ * TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
1313
+ * DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
1314
+ *
1315
+ * Permission is hereby granted, free of charge, to any person obtaining a
1316
+ * copy of data files and any associated documentation (the "Data Files") or
1317
+ * software and any associated documentation (the "Software") to deal in the
1318
+ * Data Files or Software without restriction, including without limitation
1319
+ * the rights to use, copy, modify, merge, publish, distribute, and/or sell
1320
+ * copies of the Data Files or Software, and to permit persons to whom the
1321
+ * Data Files or Software are furnished to do so, provided that either (a)
1322
+ * this copyright and permission notice appear with all copies of the Data
1323
+ * Files or Software, or (b) this copyright and permission notice appear in
1324
+ * associated Documentation.
1325
+ *
1326
+ * THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
1327
+ * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1328
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
1329
+ * THIRD PARTY RIGHTS.
1330
+ *
1331
+ * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
1332
+ * BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
1333
+ * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
1334
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
1335
+ * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
1336
+ * FILES OR SOFTWARE.
1337
+ *
1338
+ * Except as contained in this notice, the name of a copyright holder shall
1339
+ * not be used in advertising or otherwise to promote the sale, use or other
1340
+ * dealings in these Data Files or Software without prior written
1341
+ * authorization of the copyright holder.
1342
+ *
1343
+ * SPDX-License-Identifier: Unicode-3.0
1344
+ */
1345
+ const WINDOWS_ZONES = `Dateline|Etc/GMT+12|-1200|international date line west
1346
+ UTC-11|Etc/GMT+11|-1100|coordinated universal time-11
1347
+ Aleutian|America/Adak|-1000|aleutian islands
1348
+ Hawaiian|Pacific/Honolulu|-1000|hawaii
1349
+ Marquesas|Pacific/Marquesas|-0930|marquesas islands
1350
+ Alaskan|America/Anchorage|-0900|alaska
1351
+ UTC-09|Etc/GMT+9|-0900|coordinated universal time-09
1352
+ Pacific Standard Time (Mexico)|America/Tijuana|-0800|baja california
1353
+ UTC-08|Etc/GMT+8|-0800|coordinated universal time-08
1354
+ Pacific|America/Los_Angeles|-0800|pacific time (us & canada)
1355
+ US Mountain|America/Phoenix|-0700|arizona
1356
+ Mountain Standard Time (Mexico)|America/Mazatlan|-0700|chihuahua
1357
+ Mountain|America/Denver|-0700|mountain time (us & canada)
1358
+ Yukon|America/Whitehorse|-0700|yukon
1359
+ Central America|America/Guatemala|-0600|central america
1360
+ Central|America/Chicago|-0600|central time (us & canada)
1361
+ Easter Island|Pacific/Easter|-0600|easter island
1362
+ Central Standard Time (Mexico)|America/Mexico_City|-0600|guadalajara
1363
+ Canada Central|America/Regina|-0600|saskatchewan
1364
+ SA Pacific|America/Bogota|-0500|bogota
1365
+ Eastern Standard Time (Mexico)|America/Cancun|-0500|chetumal
1366
+ Eastern|America/New_York|-0500|eastern time (us & canada)
1367
+ Haiti|America/Port-au-Prince|-0500|haiti
1368
+ Cuba|America/Havana|-0500|havana
1369
+ US Eastern|America/Indiana/Indianapolis|-0500|indiana (east)
1370
+ Turks And Caicos|America/Grand_Turk|-0500|turks and caicos
1371
+ Paraguay|America/Asuncion|-0400|asuncion
1372
+ Atlantic|America/Halifax|-0400|atlantic time (canada)
1373
+ Venezuela|America/Caracas|-0400|caracas
1374
+ Central Brazilian|America/Cuiaba|-0400|cuiaba
1375
+ SA Western|America/La_Paz|-0400|georgetown
1376
+ Pacific SA|America/Santiago|-0400|santiago
1377
+ Newfoundland|America/St_Johns|-0330|newfoundland
1378
+ Tocantins|America/Araguaina|-0300|araguaina
1379
+ E. South America|America/Sao_Paulo|-0300|brasilia
1380
+ SA Eastern|America/Cayenne|-0300|cayenne
1381
+ Argentina|America/Argentina/Buenos_Aires|-0300|city of buenos aires
1382
+ Greenland|America/Nuuk|-0300|greenland
1383
+ Montevideo|America/Montevideo|-0300|montevideo
1384
+ Magallanes|America/Punta_Arenas|-0300|punta arenas
1385
+ Saint Pierre|America/Miquelon|-0300|saint pierre and miquelon
1386
+ Bahia|America/Bahia|-0300|salvador
1387
+ UTC-02|Etc/GMT+2|-0200|coordinated universal time-02
1388
+ Azores|Atlantic/Azores|-0100|azores
1389
+ Cape Verde|Atlantic/Cape_Verde|-0100|cabo verde is.
1390
+ UTC|Etc/UTC|+0000|coordinated universal time
1391
+ GMT|Europe/London|+0000|dublin
1392
+ Greenwich|Atlantic/Reykjavik|+0000|monrovia
1393
+ Sao Tome|Africa/Sao_Tome|+0000|sao tome
1394
+ Morocco|Africa/Casablanca|+0100|casablanca
1395
+ W. Europe|Europe/Berlin|+0100|amsterdam
1396
+ Central Europe|Europe/Budapest|+0100|belgrade
1397
+ Romance|Europe/Paris|+0100|brussels
1398
+ Central European|Europe/Warsaw|+0100|sarajevo
1399
+ W. Central Africa|Africa/Lagos|+0100|west central africa
1400
+ Jordan|Asia/Amman|+0200|amman
1401
+ GTB|Europe/Bucharest|+0200|athens
1402
+ Middle East|Asia/Beirut|+0200|beirut
1403
+ Egypt|Africa/Cairo|+0200|cairo
1404
+ E. Europe|Europe/Chisinau|+0200|chisinau
1405
+ Syria|Asia/Damascus|+0200|damascus
1406
+ West Bank|Asia/Hebron|+0200|gaza
1407
+ South Africa|Africa/Johannesburg|+0200|harare
1408
+ FLE|Europe/Kyiv|+0200|helsinki
1409
+ Israel|Asia/Jerusalem|+0200|jerusalem
1410
+ South Sudan|Africa/Juba|+0200|juba
1411
+ Kaliningrad|Europe/Kaliningrad|+0200|kaliningrad
1412
+ Sudan|Africa/Khartoum|+0200|khartoum
1413
+ Libya|Africa/Tripoli|+0200|tripoli
1414
+ Namibia|Africa/Windhoek|+0200|windhoek
1415
+ Arabic|Asia/Baghdad|+0300|baghdad
1416
+ Turkey|Europe/Istanbul|+0300|istanbul
1417
+ Arab|Asia/Riyadh|+0300|kuwait
1418
+ Belarus|Europe/Minsk|+0300|minsk
1419
+ Russian|Europe/Moscow|+0300|moscow
1420
+ E. Africa|Africa/Nairobi|+0300|nairobi
1421
+ Iran|Asia/Tehran|+0330|tehran
1422
+ Arabian|Asia/Dubai|+0400|abu dhabi
1423
+ Astrakhan|Europe/Astrakhan|+0400|astrakhan
1424
+ Azerbaijan|Asia/Baku|+0400|baku
1425
+ Russia Time Zone 3|Europe/Samara|+0400|izhevsk
1426
+ Mauritius|Indian/Mauritius|+0400|port louis
1427
+ Saratov|Europe/Saratov|+0400|saratov
1428
+ Georgian|Asia/Tbilisi|+0400|tbilisi
1429
+ Volgograd|Europe/Volgograd|+0400|volgograd
1430
+ Caucasus|Asia/Yerevan|+0400|yerevan
1431
+ Afghanistan|Asia/Kabul|+0430|kabul
1432
+ West Asia|Asia/Tashkent|+0500|ashgabat
1433
+ Ekaterinburg|Asia/Yekaterinburg|+0500|ekaterinburg
1434
+ Pakistan|Asia/Karachi|+0500|islamabad
1435
+ Qyzylorda|Asia/Qyzylorda|+0500|qyzylorda
1436
+ India|Asia/Kolkata|+0530|chennai
1437
+ Sri Lanka|Asia/Colombo|+0530|sri jayawardenepura
1438
+ Nepal|Asia/Kathmandu|+0545|kathmandu
1439
+ Central Asia|Asia/Bishkek|+0600|astana
1440
+ Bangladesh|Asia/Dhaka|+0600|dhaka
1441
+ Omsk|Asia/Omsk|+0600|omsk
1442
+ Myanmar|Asia/Yangon|+0630|yangon (rangoon)
1443
+ SE Asia|Asia/Bangkok|+0700|bangkok
1444
+ Altai|Asia/Barnaul|+0700|barnaul
1445
+ W. Mongolia|Asia/Hovd|+0700|hovd
1446
+ North Asia|Asia/Krasnoyarsk|+0700|krasnoyarsk
1447
+ N. Central Asia|Asia/Novosibirsk|+0700|novosibirsk
1448
+ Tomsk|Asia/Tomsk|+0700|tomsk
1449
+ China|Asia/Shanghai|+0800|beijing
1450
+ North Asia East|Asia/Irkutsk|+0800|irkutsk
1451
+ Singapore|Asia/Singapore|+0800|kuala lumpur
1452
+ W. Australia|Australia/Perth|+0800|perth
1453
+ Taipei|Asia/Taipei|+0800|taipei
1454
+ Ulaanbaatar|Asia/Ulaanbaatar|+0800|ulaanbaatar
1455
+ Aus Central W.|Australia/Eucla|+0845|eucla
1456
+ Transbaikal|Asia/Chita|+0900|chita
1457
+ Tokyo|Asia/Tokyo|+0900|osaka
1458
+ North Korea|Asia/Pyongyang|+0900|pyongyang
1459
+ Korea|Asia/Seoul|+0900|seoul
1460
+ Yakutsk|Asia/Yakutsk|+0900|yakutsk
1461
+ Cen. Australia|Australia/Adelaide|+0930|adelaide
1462
+ AUS Central|Australia/Darwin|+0930|darwin
1463
+ E. Australia|Australia/Brisbane|+1000|brisbane
1464
+ AUS Eastern|Australia/Sydney|+1000|canberra
1465
+ West Pacific|Pacific/Port_Moresby|+1000|guam
1466
+ Tasmania|Australia/Hobart|+1000|hobart
1467
+ Vladivostok|Asia/Vladivostok|+1000|vladivostok
1468
+ Lord Howe|Australia/Lord_Howe|+1030|lord howe island
1469
+ Bougainville|Pacific/Bougainville|+1100|bougainville island
1470
+ Russia Time Zone 10|Asia/Srednekolymsk|+1100|chokurdakh
1471
+ Magadan|Asia/Magadan|+1100|magadan
1472
+ Norfolk|Pacific/Norfolk|+1100|norfolk island
1473
+ Sakhalin|Asia/Sakhalin|+1100|sakhalin
1474
+ Central Pacific|Pacific/Guadalcanal|+1100|solomon is.
1475
+ Russia Time Zone 11|Asia/Kamchatka|+1200|anadyr
1476
+ New Zealand|Pacific/Auckland|+1200|auckland
1477
+ UTC+12|Etc/GMT-12|+1200|coordinated universal time+12
1478
+ Fiji|Pacific/Fiji|+1200|fiji
1479
+ Chatham Islands|Pacific/Chatham|+1245|chatham islands
1480
+ UTC+13|Etc/GMT-13|+1300|coordinated universal time+13
1481
+ Tonga|Pacific/Tongatapu|+1300|nuku'alofa
1482
+ Samoa|Pacific/Apia|+1300|samoa
1483
+ Line Islands|Pacific/Kiritimati|+1400|kiritimati island`;
1484
+ //#endregion
1485
+ //#region src/time-zones/windows.ts
1486
+ const DISPLAY_NAME = /^\( ?(UTC|GMT)(?: ?([+\-−]) ?(\d{1,2})(?:[:.]?(\d{2}))?)? ?\) ?(.+)$/i;
1487
+ const DISPLAY_NAME_SEPARATOR = / ?[,;/:] ?| \. /;
1488
+ const UTC_NAMES_SINCE = 2009;
1489
+ const GMT_NAMES_SINCE = 1970;
1490
+ let index;
1491
+ function windowsIndex() {
1492
+ if (index) return index;
1493
+ const places = /* @__PURE__ */ new Map();
1494
+ const windowsIds = /* @__PURE__ */ new Map();
1495
+ for (const line of WINDOWS_ZONES.split("\n")) {
1496
+ const [windowsId = "", timeZone = "", offset = "", place = ""] = line.split("|");
1497
+ windowsIds.set(normalize(windowsId), timeZone);
1498
+ places.set(normalize(place), {
1499
+ offset,
1500
+ timeZone
1501
+ });
1502
+ }
1503
+ index = {
1504
+ places,
1505
+ windowsIds
1506
+ };
1507
+ return index;
1508
+ }
1509
+ function normalize(name) {
1510
+ return name.trim().replace(/\s+/g, " ").toLowerCase();
1511
+ }
1512
+ function windowsTimeZone(tzid) {
1513
+ const key = normalize(tzid).replace(/ (?:daylight|standard) time$/, "");
1514
+ const timeZone = windowsIndex().windowsIds.get(key);
1515
+ return timeZone === void 0 ? void 0 : canonicalTimeZoneId(timeZone);
1516
+ }
1517
+ function displayNameTimeZone(tzid) {
1518
+ const match = DISPLAY_NAME.exec(normalize(tzid));
1519
+ if (!match) return void 0;
1520
+ const [, prefix = "", sign = "+", hours = "0", minutes = "00", rest = ""] = match;
1521
+ const hh = hours.padStart(2, "0");
1522
+ const signed = sign === "+" || Number(hours) + Number(minutes) === 0 ? "+" : "-";
1523
+ const offset = `${signed}${hh}${minutes}`;
1524
+ const { places } = windowsIndex();
1525
+ const [first = "", ...others] = rest.split(DISPLAY_NAME_SEPARATOR);
1526
+ const firstZone = places.get(first);
1527
+ if (firstZone !== void 0) {
1528
+ const since = prefix === "utc" ? UTC_NAMES_SINCE : GMT_NAMES_SINCE;
1529
+ return firstZone.offset === offset || hadOffset(firstZone.timeZone, `${signed}${hh}:${minutes}`, since) ? canonicalTimeZoneId(firstZone.timeZone) : void 0;
1530
+ }
1531
+ const zone = others.map((place) => places.get(place)).find((candidate) => candidate?.offset === offset);
1532
+ return zone === void 0 ? void 0 : canonicalTimeZoneId(zone.timeZone);
1533
+ }
1534
+ //#endregion
1535
+ //#region src/time-zones/index.ts
1536
+ const MAX_NAME_LENGTH = 256;
1537
+ const OFFSET_NAME = /^(?:UTC|GMT|Z)$|^(?:UTC|GMT)?\s*([+\-−])\s*(\d{1,2})(?:[:.]?(\d{2}))?$/i;
1538
+ function unquote(tzid) {
1539
+ const trimmed = tzid.trim();
1540
+ return trimmed.length > 1 && trimmed.startsWith("\"") && trimmed.endsWith("\"") ? trimmed.slice(1, -1).trim() : trimmed;
1541
+ }
1542
+ function definitionsByTzid(definitions = /* @__PURE__ */ new Map()) {
1543
+ const byTzid = new Map(definitions);
1544
+ for (const [tzid, definition] of definitions) {
1545
+ const name = unquote(tzid.replace(/\\([\\,;])/g, "$1"));
1546
+ if (!byTzid.has(name)) byTzid.set(name, definition);
1547
+ }
1548
+ return byTzid;
1549
+ }
1550
+ function pathTimeZone(tzid) {
1551
+ if (!tzid.includes("/") || /\s/.test(tzid)) return void 0;
1552
+ const segments = tzid.split("/").filter(Boolean);
1553
+ for (let count = Math.min(3, segments.length); count > 0; count--) {
1554
+ const timeZone = canonicalTimeZoneId(segments.slice(-count).join("/"));
1555
+ if (timeZone !== void 0) return timeZone;
1556
+ }
1557
+ }
1558
+ function offsetNameTimeZone(tzid) {
1559
+ const match = OFFSET_NAME.exec(tzid);
1560
+ if (!match) return void 0;
1561
+ const [, sign, hours, minutes = "0"] = match;
1562
+ return sign === void 0 || hours === void 0 ? "UTC" : offsetTimeZoneId(sign === "+" ? "+" : "-", Number(hours), Number(minutes));
1563
+ }
1564
+ /** Builds a TZID resolver for one calendar. Results are cached per resolver. */
1565
+ function createTimeZoneResolver(options = {}) {
1566
+ const { custom } = options;
1567
+ const definitions = definitionsByTzid(options.definitions);
1568
+ const cache = /* @__PURE__ */ new Map();
1569
+ function resolve(tzid) {
1570
+ const name = unquote(tzid);
1571
+ const definition = definitions.get(tzid) ?? definitions.get(name);
1572
+ const fromCustom = custom?.(tzid, definition);
1573
+ const chosen = fromCustom === void 0 ? void 0 : canonicalTimeZoneId(fromCustom);
1574
+ if (chosen !== void 0) return chosen;
1575
+ if (name.length > MAX_NAME_LENGTH) return definition === void 0 ? void 0 : definitionTimeZone(definition);
1576
+ const offsets = definition === void 0 ? void 0 : definitionOffsets(definition);
1577
+ const fits = (timeZone) => timeZone === void 0 || offsets === void 0 || offsets.size < 2 || fitsDefinitionOffsets(timeZone, offsets) ? timeZone : void 0;
1578
+ return fits(canonicalTimeZoneId(name)) ?? fits(pathTimeZone(name)) ?? fits(windowsTimeZone(name)) ?? fits(displayNameTimeZone(name)) ?? (definition === void 0 ? void 0 : definitionTimeZone(definition)) ?? fits(offsetNameTimeZone(name));
1579
+ }
1580
+ return (tzid) => {
1581
+ if (cache.has(tzid)) return cache.get(tzid);
1582
+ const timeZone = resolve(tzid);
1583
+ cache.set(tzid, timeZone);
1584
+ return timeZone;
1585
+ };
1586
+ }
1587
+ //#endregion
1588
+ //#region src/model/reader.ts
1589
+ const NO_PROPERTIES = [];
1590
+ function defined(fields) {
1591
+ const result = {};
1592
+ for (const key in fields) if (fields[key] !== void 0) result[key] = fields[key];
1593
+ return result;
1594
+ }
1595
+ function upper(value) {
1596
+ return value?.toUpperCase();
1597
+ }
1598
+ function parameter(property, name) {
1599
+ return property.parameters[name]?.join(",");
1600
+ }
1601
+ function isUnresolved(value) {
1602
+ if (typeof value !== "object" || value === null) return false;
1603
+ if ("kind" in value) return value.kind === "unresolved";
1604
+ return "start" in value && isUnresolved(value.start) || "end" in value && isUnresolved(value.end);
1605
+ }
1606
+ function declaredDateType(property) {
1607
+ return icsValueTypeOf(property) === "DATE" ? "DATE" : "DATE-TIME";
1608
+ }
1609
+ var ComponentReader = class ComponentReader {
1610
+ #byName = /* @__PURE__ */ new Map();
1611
+ #claimed = /* @__PURE__ */ new Set();
1612
+ collection;
1613
+ component;
1614
+ path;
1615
+ scope;
1616
+ constructor(component, scope, path, collection) {
1617
+ this.collection = collection;
1618
+ this.component = component;
1619
+ this.path = path;
1620
+ this.scope = scope;
1621
+ for (const property of component.properties) {
1622
+ const same = this.#byName.get(property.name);
1623
+ if (same === void 0) this.#byName.set(property.name, [property]);
1624
+ else same.push(property);
1625
+ }
1626
+ }
1627
+ child(component, field, index) {
1628
+ return new ComponentReader(component, this.scope, [
1629
+ ...this.path,
1630
+ field,
1631
+ index
1632
+ ], [...this.path, field]);
1633
+ }
1634
+ report(severity, code, message, property, at) {
1635
+ this.scope.issues.push(defined({
1636
+ code,
1637
+ component: this.component.name,
1638
+ line: property?.line ?? this.component.line,
1639
+ message,
1640
+ path: [...this.path, ...typeof at === "string" ? [at] : at],
1641
+ property: property?.name,
1642
+ severity
1643
+ }));
1644
+ }
1645
+ skip(code, message, property, line = this.component.line) {
1646
+ this.scope.issues.push(defined({
1647
+ code,
1648
+ component: this.component.name,
1649
+ line,
1650
+ message,
1651
+ path: this.collection,
1652
+ property,
1653
+ severity: "error"
1654
+ }));
1655
+ }
1656
+ require(...names) {
1657
+ let complete = true;
1658
+ for (const name of names) {
1659
+ const value = this.#byName.get(name)?.[0]?.value;
1660
+ if (value !== void 0 && value.trim() !== "") continue;
1661
+ complete = false;
1662
+ const what = value === void 0 ? "no" : "an empty";
1663
+ this.skip("missing-property", `${this.component.name} has ${what} ${name}; skipped`, name);
1664
+ }
1665
+ return complete;
1666
+ }
1667
+ all(name) {
1668
+ const properties = this.#byName.get(name) ?? NO_PROPERTIES;
1669
+ for (const property of properties) this.#claimed.add(property);
1670
+ return properties;
1671
+ }
1672
+ one(name, at, repeatable = false) {
1673
+ const properties = this.#byName.get(name);
1674
+ if (properties === void 0) return void 0;
1675
+ const [first] = properties;
1676
+ this.#claimed.add(first);
1677
+ for (let index = 1; !repeatable && index < properties.length; index += 1) {
1678
+ const duplicate = properties[index];
1679
+ this.#claimed.add(duplicate);
1680
+ const message = `${name} occurs more than once; the first one wins`;
1681
+ this.report("warning", "duplicate-property", message, duplicate, at);
1682
+ }
1683
+ return first;
1684
+ }
1685
+ others() {
1686
+ const others = [];
1687
+ for (const property of this.component.properties) {
1688
+ if (this.#claimed.has(property)) continue;
1689
+ if (property.name === "EXRULE") this.report("warning", "unsupported", "EXRULE was removed in RFC 5545 and isn't applied; kept as written", property, ["otherProperties", others.length]);
1690
+ others.push(property);
1691
+ }
1692
+ return others;
1693
+ }
1694
+ context(property) {
1695
+ return {
1696
+ resolveTimeZone: this.scope.resolveTimeZone,
1697
+ tzid: parameter(property, "TZID")
1698
+ };
1699
+ }
1700
+ decode(property, result, at, dropAt = at) {
1701
+ if (!result.ok) {
1702
+ this.report("error", "invalid-value", `${property.name}: ${result.message}`, property, dropAt);
1703
+ return;
1704
+ }
1705
+ for (const { code, message } of result.warnings ?? []) this.report("warning", code, `${property.name}: ${message}`, property, at);
1706
+ const tzid = parameter(property, "TZID");
1707
+ if (tzid !== void 0 && isUnresolved(result.value)) this.unknownTimeZone(tzid, property, at);
1708
+ return result.value;
1709
+ }
1710
+ required(property, result, at) {
1711
+ if (result.ok) return this.decode(property, result, at);
1712
+ const message = `${property.name}: ${result.message}; the ${this.component.name} is skipped`;
1713
+ this.skip("invalid-value", message, property.name, property.line);
1714
+ }
1715
+ unknownTimeZone(tzid, property, at) {
1716
+ const { issues, unknownTimeZones } = this.scope;
1717
+ const reported = unknownTimeZones.get(tzid);
1718
+ const line = property.line ?? this.component.line ?? 0;
1719
+ if (reported !== void 0 && (issues[reported]?.line ?? 0) <= line) return;
1720
+ const message = property.name === "X-WR-TIMEZONE" ? `X-WR-TIMEZONE ${quote(tzid)} resolves to no time zone; the calendar has no timeZone` : `TZID ${quote(tzid)} resolves to no time zone; its times stay unresolved`;
1721
+ this.report("warning", "unknown-time-zone", message, property, at);
1722
+ if (reported === void 0) unknownTimeZones.set(tzid, issues.length - 1);
1723
+ else issues[reported] = issues.pop();
1724
+ }
1725
+ value(name, at, type, repeatable = false) {
1726
+ const property = this.one(name, at, repeatable);
1727
+ if (property === void 0) return void 0;
1728
+ return this.decode(property, decodeIcsValue(type, property.value, this.context(property)), at);
1729
+ }
1730
+ text(name, at, repeatable = false) {
1731
+ return this.value(name, at, "TEXT", repeatable);
1732
+ }
1733
+ enumerated(name, at) {
1734
+ return upper(this.text(name, at));
1735
+ }
1736
+ dateResult(property, raw) {
1737
+ return decodeIcsDateValue(raw, declaredDateType(property), this.context(property));
1738
+ }
1739
+ date(name, at) {
1740
+ const property = this.one(name, at);
1741
+ return property && this.decode(property, this.dateResult(property, property.value), at);
1742
+ }
1743
+ instant(property, at, required = false) {
1744
+ const result = decodeIcsValue("DATE-TIME", property.value, this.context(property));
1745
+ if (!result.ok && decodeIcsValue("DATE", property.value).ok) return "date";
1746
+ const value = required ? this.required(property, result, at) : this.decode(property, result, at);
1747
+ if (value === void 0) return void 0;
1748
+ if (value.kind === "utc") return value.instant;
1749
+ if (value.kind === "zoned") return value.zoned.toInstant();
1750
+ const message = `${property.name} should be in UTC; read the ${value.kind} time as UTC`;
1751
+ this.report("warning", "invalid-value", message, property, at);
1752
+ return value.wallTime.toZonedDateTime("UTC").toInstant();
1753
+ }
1754
+ timestamp(name, at) {
1755
+ const property = this.one(name, at);
1756
+ if (property === void 0) return void 0;
1757
+ const instant = this.instant(property, at);
1758
+ if (instant !== "date") return instant;
1759
+ const message = `${name} is a DATE where a UTC DATE-TIME belongs; dropped`;
1760
+ this.report("warning", "invalid-value", message, property, at);
1761
+ }
1762
+ list(name, field, map) {
1763
+ const items = [];
1764
+ for (const property of this.all(name)) {
1765
+ const item = map(property, [field, items.length], field);
1766
+ if (item !== void 0) items.push(item);
1767
+ }
1768
+ return items;
1769
+ }
1770
+ items(name, field, decode) {
1771
+ const items = [];
1772
+ for (const property of this.all(name)) {
1773
+ const type = icsValueTypeOf(property);
1774
+ for (const raw of splitIcsValues(type, property.value)) {
1775
+ if (raw === "") continue;
1776
+ const item = this.decode(property, decode(property, raw, type), [field, items.length], field);
1777
+ if (item !== void 0) items.push(item);
1778
+ }
1779
+ }
1780
+ return items;
1781
+ }
1782
+ };
1783
+ //#endregion
1784
+ //#region src/model/fields.ts
1785
+ const USER_PARAMETERS = [
1786
+ "CN",
1787
+ "DIR",
1788
+ "EMAIL",
1789
+ "LANGUAGE",
1790
+ "SENT-BY"
1791
+ ];
1792
+ const ATTENDEE_PARAMETERS = [
1793
+ ...USER_PARAMETERS,
1794
+ "CUTYPE",
1795
+ "DELEGATED-FROM",
1796
+ "DELEGATED-TO",
1797
+ "MEMBER",
1798
+ "PARTSTAT",
1799
+ "ROLE",
1800
+ "RSVP"
1801
+ ];
1802
+ const MAILTO = /^mailto:/i;
1803
+ function otherParameters(property, mapped) {
1804
+ const others = Object.create(null);
1805
+ for (const [name, values] of Object.entries(property.parameters)) if (!mapped.includes(name)) others[name] = values;
1806
+ return others;
1807
+ }
1808
+ function calendarUserFields(property, mapped) {
1809
+ const address = property.value;
1810
+ return {
1811
+ address,
1812
+ directory: parameter(property, "DIR"),
1813
+ email: parameter(property, "EMAIL") ?? (MAILTO.test(address) ? address.slice(7) : void 0),
1814
+ language: parameter(property, "LANGUAGE"),
1815
+ name: parameter(property, "CN"),
1816
+ otherParameters: otherParameters(property, mapped),
1817
+ sentBy: parameter(property, "SENT-BY")
1818
+ };
1819
+ }
1820
+ function organizer(read) {
1821
+ const property = read.one("ORGANIZER", "organizer");
1822
+ return property && defined(calendarUserFields(property, USER_PARAMETERS));
1823
+ }
1824
+ function attendee(read, property, at) {
1825
+ const rsvp = parameter(property, "RSVP");
1826
+ const answer = upper(rsvp);
1827
+ if (rsvp !== void 0 && answer !== "TRUE" && answer !== "FALSE") {
1828
+ const message = `ATTENDEE: RSVP=${quote(rsvp)} isn't TRUE or FALSE; dropped`;
1829
+ read.report("error", "invalid-value", message, property, [...at, "rsvp"]);
1830
+ }
1831
+ return defined({
1832
+ ...calendarUserFields(property, ATTENDEE_PARAMETERS),
1833
+ calendarUserType: upper(parameter(property, "CUTYPE")),
1834
+ delegatedFrom: property.parameters["DELEGATED-FROM"] ?? [],
1835
+ delegatedTo: property.parameters["DELEGATED-TO"] ?? [],
1836
+ memberOf: property.parameters["MEMBER"] ?? [],
1837
+ participationStatus: upper(parameter(property, "PARTSTAT")),
1838
+ role: upper(parameter(property, "ROLE")),
1839
+ rsvp: answer === "TRUE" ? true : answer === "FALSE" ? false : void 0
1840
+ });
1841
+ }
1842
+ function attendees(read) {
1843
+ return read.list("ATTENDEE", "attendees", (property, at) => attendee(read, property, at));
1844
+ }
1845
+ function attachments(read) {
1846
+ return read.list("ATTACH", "attachments", (property, at, field) => {
1847
+ const formatType = parameter(property, "FMTTYPE");
1848
+ if (!(upper(parameter(property, "VALUE")) === "BINARY" || upper(parameter(property, "ENCODING")) === "BASE64")) return defined({
1849
+ formatType,
1850
+ kind: "uri",
1851
+ uri: property.value
1852
+ });
1853
+ const data = read.decode(property, decodeIcsValue("BINARY", property.value), at, field);
1854
+ return data === void 0 ? void 0 : defined({
1855
+ data,
1856
+ formatType,
1857
+ kind: "binary"
1858
+ });
1859
+ });
1860
+ }
1861
+ function conferences(read) {
1862
+ return read.list("CONFERENCE", "conferences", (property) => defined({
1863
+ features: (property.parameters["FEATURE"] ?? []).map((feature) => feature.toUpperCase()),
1864
+ label: parameter(property, "LABEL"),
1865
+ uri: property.value
1866
+ }));
1867
+ }
1868
+ function relations(read) {
1869
+ return read.list("RELATED-TO", "relatedTo", (property, at) => {
1870
+ const uid = read.decode(property, decodeIcsValue("TEXT", property.value), at);
1871
+ return uid === void 0 ? void 0 : defined({
1872
+ relationship: upper(parameter(property, "RELTYPE")),
1873
+ uid
1874
+ });
1875
+ });
1876
+ }
1877
+ function texts(read, name, field) {
1878
+ return read.list(name, field, (property, at) => read.decode(property, decodeIcsValue("TEXT", property.value), at));
1879
+ }
1880
+ function textItems(read, name, field) {
1881
+ return read.items(name, field, (_, raw) => decodeIcsValue("TEXT", raw));
1882
+ }
1883
+ function exceptionDates(read) {
1884
+ return read.items("EXDATE", "exceptionDates", (property, raw) => read.dateResult(property, raw));
1885
+ }
1886
+ function recurrenceDates(read) {
1887
+ return read.items("RDATE", "recurrenceDates", (property, raw, type) => type === "PERIOD" ? decodeIcsValue("PERIOD", raw, read.context(property)) : read.dateResult(property, raw));
1888
+ }
1889
+ function geo(read) {
1890
+ const property = read.one("GEO", "geo");
1891
+ if (property === void 0) return void 0;
1892
+ const parts = property.value.split(";");
1893
+ if (parts.length !== 2) {
1894
+ const message = `GEO: ${quote(property.value)} isn't latitude;longitude`;
1895
+ read.report("error", "invalid-value", message, property, "geo");
1896
+ return;
1897
+ }
1898
+ const [latitude, longitude] = parts.map((part) => read.decode(property, decodeIcsValue("FLOAT", part), "geo"));
1899
+ return latitude === void 0 || longitude === void 0 ? void 0 : {
1900
+ latitude,
1901
+ longitude
1902
+ };
1903
+ }
1904
+ //#endregion
1905
+ //#region src/model/components.ts
1906
+ const DATE_TIME_SHAPE = /^\d{8}T/i;
1907
+ function schedulingFields(read, uid) {
1908
+ const recurrenceIdProperty = read.one("RECURRENCE-ID", "recurrenceId");
1909
+ return {
1910
+ attachments: attachments(read),
1911
+ attendees: attendees(read),
1912
+ categories: textItems(read, "CATEGORIES", "categories"),
1913
+ classification: read.enumerated("CLASS", "classification"),
1914
+ color: read.text("COLOR", "color"),
1915
+ comments: texts(read, "COMMENT", "comments"),
1916
+ contacts: texts(read, "CONTACT", "contacts"),
1917
+ created: read.timestamp("CREATED", "created"),
1918
+ description: read.text("DESCRIPTION", "description", read.component.name === "VJOURNAL"),
1919
+ exceptionDates: exceptionDates(read),
1920
+ lastModified: read.timestamp("LAST-MODIFIED", "lastModified"),
1921
+ organizer: organizer(read),
1922
+ recurrenceDates: recurrenceDates(read),
1923
+ recurrenceId: recurrenceIdProperty && read.decode(recurrenceIdProperty, read.dateResult(recurrenceIdProperty, recurrenceIdProperty.value), "recurrenceId"),
1924
+ recurrenceRange: recurrenceIdProperty && recurrenceRange(read, recurrenceIdProperty),
1925
+ recurrenceRule: read.value("RRULE", "recurrenceRule", "RECUR"),
1926
+ relatedTo: relations(read),
1927
+ sequence: read.value("SEQUENCE", "sequence", "INTEGER"),
1928
+ stamp: read.timestamp("DTSTAMP", "stamp"),
1929
+ summary: read.text("SUMMARY", "summary"),
1930
+ uid,
1931
+ url: read.value("URL", "url", "URI")
1932
+ };
1933
+ }
1934
+ function recurrenceRange(read, property) {
1935
+ const range = parameter(property, "RANGE");
1936
+ switch (upper(range)) {
1937
+ case void 0: return;
1938
+ case "THISANDFUTURE": return "THISANDFUTURE";
1939
+ case "THISANDPRIOR":
1940
+ read.report("warning", "unsupported", "RECURRENCE-ID: RANGE=THISANDPRIOR was removed in RFC 5545; ignored", property, "recurrenceRange");
1941
+ return;
1942
+ default:
1943
+ read.report("error", "invalid-value", `RECURRENCE-ID: RANGE=${range} isn't THISANDFUTURE; dropped`, property, "recurrenceRange");
1944
+ return;
1945
+ }
1946
+ }
1947
+ function compare(left, right) {
1948
+ if (left.kind === "date" || right.kind === "date") return left.kind === "date" && right.kind === "date" ? Temporal.PlainDate.compare(left.date, right.date) : void 0;
1949
+ const instant = (value) => value.kind === "utc" ? value.instant : value.kind === "zoned" ? value.zoned.toInstant() : void 0;
1950
+ const leftInstant = instant(left);
1951
+ const rightInstant = instant(right);
1952
+ if (leftInstant && rightInstant) return Temporal.Instant.compare(leftInstant, rightInstant);
1953
+ if (left.kind === "floating" && right.kind === "floating" || left.kind === "unresolved" && right.kind === "unresolved" && left.tzid === right.tzid) return Temporal.PlainDateTime.compare(left.wallTime, right.wallTime);
1954
+ }
1955
+ function endAndDuration(read, start, name, field) {
1956
+ const endProperty = read.one(name, field);
1957
+ const end = endProperty && read.decode(endProperty, read.dateResult(endProperty, endProperty.value), field);
1958
+ const durationProperty = read.one("DURATION", "duration");
1959
+ if (endProperty !== void 0 && end !== void 0 && start !== void 0) {
1960
+ const typeOf = (value) => value.kind === "date" ? "a DATE" : "a DATE-TIME";
1961
+ if (typeOf(start) !== typeOf(end)) {
1962
+ const message = `${name} is ${typeOf(end)} but DTSTART is ${typeOf(start)}`;
1963
+ read.report("warning", "invalid-value", message, endProperty, field);
1964
+ } else if ((compare(end, start) ?? 0) < 0) read.report("warning", "invalid-value", `${name} is before DTSTART`, endProperty, field);
1965
+ }
1966
+ if (durationProperty === void 0) return { end };
1967
+ if (end !== void 0) {
1968
+ const message = `${name} and DURATION exclude each other; DURATION is dropped`;
1969
+ read.report("warning", "conflicting-properties", message, durationProperty, "duration");
1970
+ return { end };
1971
+ }
1972
+ const duration = read.decode(durationProperty, decodeIcsValue("DURATION", durationProperty.value), "duration");
1973
+ if (duration !== void 0 && duration.sign < 0) read.report("warning", "invalid-value", "DURATION is negative, which RFC 5545 doesn't allow", durationProperty, "duration");
1974
+ return {
1975
+ duration,
1976
+ end
1977
+ };
1978
+ }
1979
+ function alarmsAndOthers(read) {
1980
+ const alarms = [];
1981
+ const otherComponents = [];
1982
+ for (const child of read.component.components) {
1983
+ if (child.name !== "VALARM") {
1984
+ otherComponents.push(child);
1985
+ continue;
1986
+ }
1987
+ const alarm = readAlarm(read.child(child, "alarms", alarms.length));
1988
+ if (alarm !== void 0) alarms.push(alarm);
1989
+ }
1990
+ return {
1991
+ alarms,
1992
+ otherComponents
1993
+ };
1994
+ }
1995
+ function readEvent(read, extensions) {
1996
+ if (!read.require("UID", "DTSTART")) return void 0;
1997
+ const startProperty = read.one("DTSTART", "start");
1998
+ const start = read.required(startProperty, read.dateResult(startProperty, startProperty.value), "start");
1999
+ if (start === void 0) return void 0;
2000
+ return defined({
2001
+ ...schedulingFields(read, read.text("UID", "uid")),
2002
+ ...alarmsAndOthers(read),
2003
+ ...endAndDuration(read, start, "DTEND", "end"),
2004
+ conferences: conferences(read),
2005
+ extensions: readExtensions(read, extensions),
2006
+ geo: geo(read),
2007
+ location: read.text("LOCATION", "location"),
2008
+ priority: read.value("PRIORITY", "priority", "INTEGER"),
2009
+ resources: textItems(read, "RESOURCES", "resources"),
2010
+ start,
2011
+ status: read.enumerated("STATUS", "status"),
2012
+ transparency: read.enumerated("TRANSP", "transparency"),
2013
+ otherProperties: read.others()
2014
+ });
2015
+ }
2016
+ function readTodo(read, extensions) {
2017
+ if (!read.require("UID")) return void 0;
2018
+ const start = read.date("DTSTART", "start");
2019
+ const { duration, end: due } = endAndDuration(read, start, "DUE", "due");
2020
+ return defined({
2021
+ ...schedulingFields(read, read.text("UID", "uid")),
2022
+ ...alarmsAndOthers(read),
2023
+ completed: read.timestamp("COMPLETED", "completed"),
2024
+ conferences: conferences(read),
2025
+ due,
2026
+ duration,
2027
+ extensions: readExtensions(read, extensions),
2028
+ geo: geo(read),
2029
+ location: read.text("LOCATION", "location"),
2030
+ percentComplete: read.value("PERCENT-COMPLETE", "percentComplete", "INTEGER"),
2031
+ priority: read.value("PRIORITY", "priority", "INTEGER"),
2032
+ resources: textItems(read, "RESOURCES", "resources"),
2033
+ start,
2034
+ status: read.enumerated("STATUS", "status"),
2035
+ otherProperties: read.others()
2036
+ });
2037
+ }
2038
+ function readJournal(read, extensions) {
2039
+ if (!read.require("UID")) return void 0;
2040
+ return defined({
2041
+ ...schedulingFields(read, read.text("UID", "uid")),
2042
+ extensions: readExtensions(read, extensions),
2043
+ otherComponents: read.component.components,
2044
+ start: read.date("DTSTART", "start"),
2045
+ status: read.enumerated("STATUS", "status"),
2046
+ otherProperties: read.others()
2047
+ });
2048
+ }
2049
+ function readFreeBusy(read) {
2050
+ if (!read.require("UID")) return void 0;
2051
+ return defined({
2052
+ attendees: attendees(read),
2053
+ comments: texts(read, "COMMENT", "comments"),
2054
+ contact: read.text("CONTACT", "contact"),
2055
+ end: read.date("DTEND", "end"),
2056
+ freeBusy: read.list("FREEBUSY", "freeBusy", (property, at) => {
2057
+ const periods = [];
2058
+ for (const raw of splitIcsValues("PERIOD", property.value)) {
2059
+ if (raw === "") continue;
2060
+ const result = decodeIcsValue("PERIOD", raw, read.context(property));
2061
+ const period = read.decode(property, result, [
2062
+ ...at,
2063
+ "periods",
2064
+ periods.length
2065
+ ], [...at, "periods"]);
2066
+ if (period !== void 0) periods.push(period);
2067
+ }
2068
+ return {
2069
+ periods,
2070
+ type: upper(parameter(property, "FBTYPE")) ?? "BUSY"
2071
+ };
2072
+ }),
2073
+ organizer: organizer(read),
2074
+ otherComponents: read.component.components,
2075
+ stamp: read.timestamp("DTSTAMP", "stamp"),
2076
+ start: read.date("DTSTART", "start"),
2077
+ uid: read.text("UID", "uid"),
2078
+ url: read.value("URL", "url", "URI"),
2079
+ otherProperties: read.others()
2080
+ });
2081
+ }
2082
+ function readTrigger(read) {
2083
+ const property = read.one("TRIGGER", "trigger");
2084
+ const declared = upper(parameter(property, "VALUE"));
2085
+ if (declared === "DATE-TIME" || declared === void 0 && DATE_TIME_SHAPE.test(property.value)) {
2086
+ if (declared === void 0) read.report("warning", "invalid-value", "TRIGGER: a DATE-TIME without VALUE=DATE-TIME; read as DATE-TIME", property, "trigger");
2087
+ const instant = read.instant(property, "trigger", true);
2088
+ if (instant === "date") {
2089
+ read.skip("invalid-value", "TRIGGER: a DATE isn't a time to alarm at; the VALARM is skipped", property.name, property.line);
2090
+ return;
2091
+ }
2092
+ return instant && {
2093
+ instant,
2094
+ kind: "absolute"
2095
+ };
2096
+ }
2097
+ const offset = read.required(property, decodeIcsValue("DURATION", property.value), "trigger");
2098
+ if (offset === void 0) return void 0;
2099
+ const related = parameter(property, "RELATED");
2100
+ const relatedTo = upper(related);
2101
+ if (related !== void 0 && relatedTo !== "START" && relatedTo !== "END") {
2102
+ const message = `TRIGGER: RELATED=${related} isn't START or END; read as START`;
2103
+ read.report("warning", "invalid-value", message, property, ["trigger", "relatedTo"]);
2104
+ }
2105
+ return {
2106
+ kind: "relative",
2107
+ offset,
2108
+ relatedTo: relatedTo === "END" ? "END" : "START"
2109
+ };
2110
+ }
2111
+ function readAlarm(read) {
2112
+ if (!read.require("ACTION", "TRIGGER")) return void 0;
2113
+ const trigger = readTrigger(read);
2114
+ if (trigger === void 0) return void 0;
2115
+ return defined({
2116
+ action: read.enumerated("ACTION", "action"),
2117
+ attachments: attachments(read),
2118
+ attendees: attendees(read),
2119
+ description: read.text("DESCRIPTION", "description"),
2120
+ duration: read.value("DURATION", "duration", "DURATION"),
2121
+ otherComponents: read.component.components,
2122
+ repeat: read.value("REPEAT", "repeat", "INTEGER"),
2123
+ summary: read.text("SUMMARY", "summary"),
2124
+ trigger,
2125
+ uid: read.text("UID", "uid"),
2126
+ otherProperties: read.others()
2127
+ });
2128
+ }
2129
+ function readObservance(read) {
2130
+ if (!read.require("DTSTART", "TZOFFSETFROM", "TZOFFSETTO")) return void 0;
2131
+ const required = (property, field, type) => read.required(property, decodeIcsValue(type, property.value), field);
2132
+ const startProperty = read.one("DTSTART", "start");
2133
+ const start = required(startProperty, "start", "DATE-TIME");
2134
+ const offsetFrom = required(read.one("TZOFFSETFROM", "offsetFrom"), "offsetFrom", "UTC-OFFSET");
2135
+ const offsetTo = required(read.one("TZOFFSETTO", "offsetTo"), "offsetTo", "UTC-OFFSET");
2136
+ if (start === void 0 || offsetFrom === void 0 || offsetTo === void 0) return void 0;
2137
+ let wallTime;
2138
+ if (start.kind === "utc") {
2139
+ read.report("warning", "invalid-value", "DTSTART of an observance is a local time; read without its Z", startProperty, "start");
2140
+ wallTime = start.instant.toZonedDateTimeISO("UTC").toPlainDateTime();
2141
+ } else wallTime = start.wallTime;
2142
+ return defined({
2143
+ comments: texts(read, "COMMENT", "comments"),
2144
+ kind: read.component.name === "DAYLIGHT" ? "daylight" : "standard",
2145
+ names: texts(read, "TZNAME", "names"),
2146
+ offsetFrom,
2147
+ offsetTo,
2148
+ recurrenceDates: recurrenceDates(read),
2149
+ recurrenceRule: read.value("RRULE", "recurrenceRule", "RECUR"),
2150
+ start: wallTime,
2151
+ otherProperties: read.others()
2152
+ });
2153
+ }
2154
+ function readTimeZone(read) {
2155
+ if (!read.require("TZID")) return void 0;
2156
+ const tzid = read.text("TZID", "tzid");
2157
+ const observances = [];
2158
+ const otherComponents = [];
2159
+ for (const child of read.component.components) {
2160
+ if (child.name !== "STANDARD" && child.name !== "DAYLIGHT") {
2161
+ otherComponents.push(child);
2162
+ continue;
2163
+ }
2164
+ const observance = readObservance(read.child(child, "observances", observances.length));
2165
+ if (observance !== void 0) observances.push(observance);
2166
+ }
2167
+ return defined({
2168
+ lastModified: read.timestamp("LAST-MODIFIED", "lastModified"),
2169
+ observances,
2170
+ otherComponents,
2171
+ timeZone: read.scope.resolveTimeZone(tzid),
2172
+ tzid,
2173
+ url: read.value("TZURL", "url", "URI"),
2174
+ otherProperties: read.others()
2175
+ });
2176
+ }
2177
+ //#endregion
2178
+ //#region src/model/calendar.ts
2179
+ function push(items, item) {
2180
+ if (item !== void 0) items.push(item);
2181
+ }
2182
+ function calendarTimeZone(read) {
2183
+ const property = read.one("X-WR-TIMEZONE", "timeZone");
2184
+ if (property === void 0) return void 0;
2185
+ const tzid = read.decode(property, decodeIcsValue("TEXT", property.value), "timeZone");
2186
+ const timeZone = tzid && read.scope.resolveTimeZone(tzid);
2187
+ if (tzid !== void 0 && timeZone === void 0) read.unknownTimeZone(tzid, property, "timeZone");
2188
+ return timeZone;
2189
+ }
2190
+ function readCalendar(component, index, issues, config) {
2191
+ const definitions = /* @__PURE__ */ new Map();
2192
+ for (const child of component.components) {
2193
+ if (child.name !== "VTIMEZONE") continue;
2194
+ const tzid = child.properties.find((property) => property.name === "TZID")?.value;
2195
+ if (tzid !== void 0 && !definitions.has(tzid)) definitions.set(tzid, child);
2196
+ }
2197
+ const read = new ComponentReader(component, {
2198
+ issues,
2199
+ resolveTimeZone: createTimeZoneResolver({
2200
+ custom: config.resolveTimeZone,
2201
+ definitions
2202
+ }),
2203
+ unknownTimeZones: /* @__PURE__ */ new Map()
2204
+ }, ["calendars", index], ["calendars"]);
2205
+ const name = read.text("NAME", "name", true);
2206
+ const wrName = read.text("X-WR-CALNAME", "name");
2207
+ const description = read.text("DESCRIPTION", "description", true);
2208
+ const wrDescription = read.text("X-WR-CALDESC", "description");
2209
+ const refreshInterval = read.value("REFRESH-INTERVAL", "refreshInterval", "DURATION");
2210
+ const publishedTtl = read.value("X-PUBLISHED-TTL", "refreshInterval", "DURATION");
2211
+ const properties = {
2212
+ calendarScale: read.text("CALSCALE", "calendarScale"),
2213
+ color: read.text("COLOR", "color"),
2214
+ description: description ?? wrDescription,
2215
+ extensions: readExtensions(read, config.extensions.calendar),
2216
+ lastModified: read.timestamp("LAST-MODIFIED", "lastModified"),
2217
+ method: read.enumerated("METHOD", "method"),
2218
+ name: name ?? wrName,
2219
+ productId: read.text("PRODID", "productId"),
2220
+ refreshInterval: refreshInterval ?? publishedTtl,
2221
+ source: read.value("SOURCE", "source", "URI"),
2222
+ timeZone: calendarTimeZone(read),
2223
+ uid: read.text("UID", "uid"),
2224
+ url: read.value("URL", "url", "URI"),
2225
+ version: read.text("VERSION", "version")
2226
+ };
2227
+ const events = [];
2228
+ const todos = [];
2229
+ const journals = [];
2230
+ const freeBusy = [];
2231
+ const timeZones = [];
2232
+ const otherComponents = [];
2233
+ const { event, journal, todo } = config.extensions;
2234
+ for (const child of component.components) switch (child.name) {
2235
+ case "VEVENT":
2236
+ push(events, readEvent(read.child(child, "events", events.length), event));
2237
+ break;
2238
+ case "VTODO":
2239
+ push(todos, readTodo(read.child(child, "todos", todos.length), todo));
2240
+ break;
2241
+ case "VJOURNAL":
2242
+ push(journals, readJournal(read.child(child, "journals", journals.length), journal));
2243
+ break;
2244
+ case "VFREEBUSY":
2245
+ push(freeBusy, readFreeBusy(read.child(child, "freeBusy", freeBusy.length)));
2246
+ break;
2247
+ case "VTIMEZONE":
2248
+ push(timeZones, readTimeZone(read.child(child, "timeZones", timeZones.length)));
2249
+ break;
2250
+ default: otherComponents.push(child);
2251
+ }
2252
+ return defined({
2253
+ ...properties,
2254
+ events,
2255
+ freeBusy,
2256
+ journals,
2257
+ otherComponents,
2258
+ otherProperties: read.others(),
2259
+ timeZones,
2260
+ todos
2261
+ });
2262
+ }
2263
+ function parseCalendars(text, config) {
2264
+ const parsed = parseIcsComponents(text);
2265
+ const issues = [...parsed.issues];
2266
+ const calendars = [];
2267
+ for (const component of parsed.components) {
2268
+ if (component.name === "VCALENDAR") {
2269
+ calendars.push(readCalendar(component, calendars.length, issues, config));
2270
+ continue;
2271
+ }
2272
+ issues.push(defined({
2273
+ code: "invalid-structure",
2274
+ component: component.name,
2275
+ line: component.line,
2276
+ message: `${component.name} outside a VCALENDAR; skipped`,
2277
+ path: [],
2278
+ severity: "warning"
2279
+ }));
2280
+ }
2281
+ if (calendars.length === 0 && !issues.some(({ severity }) => severity === "error")) issues.push({
2282
+ code: "invalid-structure",
2283
+ message: "No VCALENDAR found",
2284
+ path: [],
2285
+ severity: "error"
2286
+ });
2287
+ issues.sort((left, right) => (left.line ?? 0) - (right.line ?? 0));
2288
+ return {
2289
+ calendars,
2290
+ issues
2291
+ };
2292
+ }
2293
+ //#endregion
2294
+ //#region src/model/parser.ts
2295
+ function errorsOf(issues) {
2296
+ return issues.filter((issue) => issue.severity === "error");
2297
+ }
2298
+ /** Builds a reusable parser. The parser is also a Standard Schema for ICS text. */
2299
+ function createIcsParser(options = {}) {
2300
+ const { resolveTimeZone, strict = false } = options;
2301
+ const extensions = options.extensions ?? {};
2302
+ const config = {
2303
+ extensions: {
2304
+ calendar: extensionEntries(extensions.calendar),
2305
+ event: extensionEntries(extensions.event),
2306
+ journal: extensionEntries(extensions.journal),
2307
+ todo: extensionEntries(extensions.todo)
2308
+ },
2309
+ resolveTimeZone
2310
+ };
2311
+ const parse = (text) => parseCalendars(text, config);
2312
+ return {
2313
+ parse(text) {
2314
+ const result = parse(text);
2315
+ const errors = strict ? errorsOf(result.issues) : [];
2316
+ if (errors.length > 0) throw new IcsParseError(errors);
2317
+ return result;
2318
+ },
2319
+ "~standard": {
2320
+ validate(value) {
2321
+ if (typeof value !== "string") return { issues: [{ message: `Expected iCalendar text, a string; got ${typeof value}` }] };
2322
+ const result = parse(value);
2323
+ const errors = errorsOf(result.issues);
2324
+ return errors.length === 0 ? { value: result } : { issues: errors.map(({ message, path }) => ({
2325
+ message,
2326
+ path
2327
+ })) };
2328
+ },
2329
+ vendor: "@moltenship/ics",
2330
+ version: 1
2331
+ }
2332
+ };
2333
+ }
2334
+ /** Parses iCalendar text into typed calendars. */
2335
+ function parseIcs(text, options) {
2336
+ return createIcsParser(options).parse(text);
2337
+ }
2338
+ //#endregion
2339
+ export { IcsParseError, createIcsParser, decodeIcsDateValue, decodeIcsValue, decodeIcsValues, encodeIcsValue, getEventEnd, icsExtension, icsValueTypeOf, parseIcs, parseIcsComponents, splitIcsValues, stringifyIcsComponents };