@vermeulen.solutions/eventual 0.18.7 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Query-string state of the events page and the date range of a detail page.
3
+ * Moved from the Astro showcase (browser-state.ts, event-range.ts).
4
+ */
5
+ import { addMonths, isMonthKey } from "./grid";
6
+
7
+ export const EVENT_VIEWS = ["list", "timeline", "cards", "schedule", "dates", "month", "locations"] as const;
8
+
9
+ export type EventView = typeof EVENT_VIEWS[number];
10
+
11
+ export interface EventBrowserState {
12
+ month: string;
13
+ view: EventView;
14
+ category: string;
15
+ }
16
+
17
+ export interface EventBrowserStateOptions {
18
+ /** Views the site offers, in this order (default: all seven). */
19
+ views?: readonly EventView[];
20
+ /** View when the address names none, or one the site does not offer (default: the first offered). */
21
+ defaultView?: EventView;
22
+ /** Fixed values instead of the query string. */
23
+ view?: EventView;
24
+ month?: string;
25
+ category?: string;
26
+ }
27
+
28
+ export function offeredViews(options: Pick<EventBrowserStateOptions, "views"> = {}): EventView[] {
29
+ const chosen = (options.views ?? EVENT_VIEWS).filter((view, index, all) => EVENT_VIEWS.includes(view) && all.indexOf(view) === index);
30
+ return chosen.length ? chosen : [...EVENT_VIEWS];
31
+ }
32
+
33
+ export function eventBrowserState(params: URLSearchParams, currentMonth: string, options: EventBrowserStateOptions = {}): EventBrowserState {
34
+ const views = offeredViews(options);
35
+ const fallback = options.defaultView && views.includes(options.defaultView) ? options.defaultView : views[0]!;
36
+ const requestedView = (options.view ?? params.get("view")) as EventView | null;
37
+ const requestedMonth = options.month ?? params.get("month");
38
+ return {
39
+ month: isMonthKey(requestedMonth) ? requestedMonth : currentMonth,
40
+ view: requestedView && views.includes(requestedView) ? requestedView : fallback,
41
+ category: (options.category ?? params.get("category") ?? "").trim().slice(0, 100),
42
+ };
43
+ }
44
+
45
+ /** Same-page address for another view, month or category ("?month=…&view=…"). */
46
+ export function eventBrowserHref(state: EventBrowserState, change: Partial<EventBrowserState> = {}): string {
47
+ const next = { ...state, ...change };
48
+ const params = new URLSearchParams({ month: next.month, view: next.view });
49
+ if (next.category) params.set("category", next.category);
50
+ return `?${params.toString()}`;
51
+ }
52
+
53
+ export function adjacentMonth(state: EventBrowserState, offset: -1 | 1): string {
54
+ return addMonths(state.month, offset);
55
+ }
56
+
57
+ export interface EventRange {
58
+ from: string;
59
+ through: string;
60
+ }
61
+
62
+ /** The detail page's `from`/`through` (default: today and the year after); null when invalid. */
63
+ export function eventRange(searchParams: URLSearchParams, now = new Date()): EventRange | null {
64
+ const from = searchParams.get("from") ?? now.toISOString().slice(0, 10);
65
+ const through = searchParams.get("through") ?? addDays(from, 365);
66
+ if (!isDateOnly(from) || !isDateOnly(through) || from > through) return null;
67
+ const span = (Date.parse(`${through}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86_400_000;
68
+ return Number.isInteger(span) && span < 366 ? { from, through } : null;
69
+ }
70
+
71
+ export function isDateOnly(value: string): boolean {
72
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
73
+ const date = new Date(`${value}T00:00:00Z`);
74
+ return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
75
+ }
76
+
77
+ function addDays(value: string, amount: number): string {
78
+ const date = new Date(`${value}T00:00:00Z`);
79
+ if (!isDateOnly(value)) return "";
80
+ date.setUTCDate(date.getUTCDate() + amount);
81
+ return date.toISOString().slice(0, 10);
82
+ }
package/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  /** @type {import("emdash").PluginDescriptor} */
8
8
  const descriptor = Object.freeze({
9
9
  "id": "eventual",
10
- "version": "0.18.7",
10
+ "version": "0.19.0",
11
11
  "format": "standard",
12
12
  "entrypoint": "@vermeulen.solutions/eventual/sandbox",
13
13
  "capabilities": [
package/dist/plugin.mjs CHANGED
@@ -9,5 +9,5 @@ function e(e={}){let t=[];return new Headers(e.headers).forEach((e,n)=>t.push([n
9
9
  `)){if(/^\s*\x60\x60\x60/.test(t)){i(),a=!a,r(t);continue}if(a){r(t);continue}if(!t.trim()){i();continue}let e=/^(#{1,6})\s+(.+)$/.exec(t),o=/^(\s*)(?:([-*+])|\d+\.)\s+(.+)$/.exec(t),s=/^>\s?(.*)$/.exec(t);e?(i(),r(e[2],`h`+e[1].length)):o?(i(),r(o[3],`normal`,o[2]?`bullet`:`number`,Math.floor(o[1].length/2)+1)):s?(i(),r(s[1],`blockquote`)):n.push(Te(t))}return i(),t}function De(e,t){return t.venueId?e?.get(t.venueId+`|`+(t.locale??``).toLowerCase())??e?.get(t.venueId):void 0}function Oe(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=t.data&&typeof t.data==`object`?t.data:t,r=a(t.type?t.id:n.id??t.id??t._id??``);if(!r)return null;let i=a(n.name??n.title??t.name??t.title??``).trim(),o=a(n.street??n.address??n.streetAddress??t.street??t.address??t.streetAddress??``).trim(),s=a(n.street2??t.street2??``).trim(),c=a(n.locality??n.city??t.locality??t.city??``).trim(),l=a(n.region??n.state??t.region??t.state??``).trim(),u=a(n.postal_code??n.postalCode??n.zip??t.postal_code??t.postalCode??t.zip??``).trim(),d=a(n.country??t.country??``).trim(),f=M(n.directions??t.directions)||void 0,p=[[o,s].filter(Boolean).join(` `),[u,c].filter(Boolean).join(` `),l,d].filter(Boolean).join(`, `);return{id:r,name:i||p||`Event Venue`,address:p,street:o||void 0,street2:s||void 0,locality:c||void 0,region:l||void 0,postalCode:u||void 0,country:d||void 0,directions:f}}function ke(e,t=``,n=`eventual`){let r=e.title||`Event`,i=T(e.virtualUrl??``),a=[M(e.description??``),i].filter(Boolean).join(`
10
10
 
11
11
  `),o=e.location||``;e.locationType===`virtual`?o=i||o:e.locationType===`hybrid`&&i&&o&&(o=`${o} · ${i}`);let s,c,l,u=``;if(e.allDay){let t=e.start.slice(0,10).replace(/-/g,``),n=new Date(e.end.slice(0,10)+`T00:00:00Z`);n.setUTCDate(n.getUTCDate()+1),s=`${t}/${n.toISOString().slice(0,10).replace(/-/g,``)}`,c=e.start.slice(0,10),l=n.toISOString().slice(0,10),u=`&allday=true`}else{let t=new Date(e.start).toISOString(),n=new Date(e.end).toISOString();s=`${t.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}/${n.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}`,c=t,l=n}let d=encodeURIComponent,f=`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${d(r)}&dates=${s}&details=${d(a)}&location=${d(o)}`,p=`path=/calendar/action/compose&rru=addevent&subject=${d(r)}&body=${d(a)}&location=${d(o)}&startdt=${d(c)}&enddt=${d(l)}${u}`,m=`https://outlook.live.com/calendar/0/deeplink/compose?${p}`,h=`https://outlook.office.com/calendar/0/deeplink/compose?${p}`,g=e.id.split(`#`)[0],_=`/_emdash/api/plugins/${d(n)}/calendar?eventId=${d(g)}`;return{google:f,outlook:m,office365:h,ics:t?new URL(_,t).href:_}}function Ae(e,t){if(typeof e!=`string`||!e.trim())return``;try{let n=t?new URL(e,t):new URL(e);return n.protocol===`http:`||n.protocol===`https:`?n.href:``}catch{return``}}function je(e){let t=Ae(e.virtualUrl??``);return e.locationType===`virtual`?t||e.location:e.locationType===`hybrid`?[e.location,t].filter(Boolean).join(` · `):e.location}function Me(e){return Ae(e.externalUrl)||(e.locationType===`virtual`||e.locationType===`hybrid`?Ae(e.virtualUrl??``):``)}function Ne(e){return e.status===`cancelled`?`CANCELLED`:e.status===`postponed`?`TENTATIVE`:`CONFIRMED`}function Pe(e){if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return!1;let t=e.slice(11,19).split(`:`);return p(e.slice(0,10))&&Number.isFinite(Date.parse(e))&&Number(t[0])<=23&&Number(t[1])<=59&&(!t[2]||Number(t[2])<=59)}function N(e){if(typeof e!=`string`)return e??void 0;if(e.trim())try{return JSON.parse(e)}catch{i(`Invalid JSON.`)}}const Fe=[`start`,`end`,`start_date`,`end_date`,`all_day`,`timezone`,`recurrence`,`exceptions`,`occurrence_content`,`venue`,`venue_id`,`organizer_ref`,`organizer_id`,`location_type`,`event_status`,`calendar_uid`,`legacy_id`,`categories`,`virtual_url`,`external_url`,`image_url`,`organizer_details`,`previous_start_date`,`schedule_history`];function Ie(e,t={}){let n={...e},r=e.all_day??e.allDay??!1,a=r===0?!1:r===1?!0:r;typeof a!=`boolean`&&i(`all_day must be a boolean.`);let o=e.timezone??`Europe/Zurich`;(typeof o!=`string`||!h(o))&&i(`Invalid IANA timezone.`);let s=a?e.start_date??e.start:e.start,c=a?e.end_date??e.end:e.end;(typeof s!=`string`||typeof c!=`string`||!s||!c)&&i(`Start and end are required.`);let l=s,u=c;if(a)(e.start_date!=null&&!p(l)||e.end_date!=null&&!p(u))&&i(`All-day date fields must use YYYY-MM-DD.`),[l,u].some(e=>!p(e)&&!Pe(e))&&i(`Invalid all-day date representation.`),l=l.slice(0,10),u=u.slice(0,10),(!p(l)||!p(u)||u<l)&&i(`Invalid inclusive all-day dates.`),n.start_date=l,n.end_date=u,delete n.start,delete n.end;else{let e=e=>{if(Pe(e))return new Date(e).toISOString()},t=e(l),r=e(u);if(t&&r)l=t,u=r;else{let e=y({start:l,end:u,allDay:!1,timezone:o});e.dates||i(`Invalid local datetime or timezone.`),{start:l,end:u}=e.dates}Date.parse(u)<Date.parse(l)&&i(`End must be at or after start.`),n.start=l,n.end=u,delete n.start_date,delete n.end_date}let d=N(e.recurrence);if(d!=null&&!D(d)&&i(`Invalid recurrence rule.`),d&&D(d)){let e=a?l:_(l,o)?.slice(0,10);(!e||d.until<e)&&i(`Recurrence until precedes start.`),!a&&(new Date(l).getUTCSeconds()||new Date(l).getUTCMilliseconds())&&i(`Recurring starts require minute precision.`)}let f=N(e.exceptions)??[];(!Array.isArray(f)||f.length>500)&&i(`Exceptions must be an array of at most 500 items.`);let m=new Set([`start`,`end`,`allDay`,`timezone`,`locationType`,`virtualUrl`,`status`,`externalUrl`,`imageUrl`,`imageMediaId`,`categories`]),g={id:`validation`,start:l,end:u,allDay:a,timezone:o,recurrence:d,exceptions:f,published:!0};for(let e of f)if((!e||typeof e!=`object`||typeof e.recurrenceId!=`string`||![`cancelled`,`modified`].includes(e.status))&&i(`Invalid exception.`),e.status===`modified`){(!e.overrides||typeof e.overrides!=`object`||Array.isArray(e.overrides)||!Object.keys(e.overrides).length)&&i(`Modified exceptions require overrides.`),Object.keys(e.overrides).some(e=>!m.has(e))&&i(`Editorial exception overrides belong in occurrence_content.`);let t=A(g,e.recurrenceId);t||i(`Exception is not a scheduled occurrence.`);let n={...t,...e.overrides};(typeof n.allDay!=`boolean`||!h(n.timezone))&&i(`Invalid exception timezone or allDay.`),(n.allDay?!p(n.start)||!p(n.end)||n.end<n.start:!Number.isFinite(Date.parse(n.start))||!Number.isFinite(Date.parse(n.end))||Date.parse(n.end)<Date.parse(n.start))&&i(`Invalid exception schedule.`),!n.allDay&&[n.start,n.end].some(e=>!Pe(e))&&i(`Timed exceptions require ISO instants.`);for(let t of[`locationType`,`virtualUrl`,`status`,`externalUrl`,`imageUrl`,`imageMediaId`])t in e.overrides&&typeof e.overrides[t]!=`string`&&i(`Exception field must be text: `+t);e.overrides.locationType!==void 0&&![`physical`,`virtual`,`hybrid`].includes(e.overrides.locationType)&&i(`Invalid exception location type.`),e.overrides.status!==void 0&&![`published`,`cancelled`,`postponed`,`rescheduled`].includes(e.overrides.status)&&i(`Invalid exception status.`);for(let t of[`virtualUrl`,`externalUrl`,`imageUrl`])e.overrides[t]&&!Ae(e.overrides[t])&&i(`Exception URLs must use HTTP(S).`);e.overrides.categories!==void 0&&(!Array.isArray(e.overrides.categories)||e.overrides.categories.some(e=>typeof e!=`string`))&&i(`Exception categories must be an array of strings.`)}f.length&&(!d||!we(g))&&i(`Duplicate or invalid exception recurrence IDs.`);let v=N(e.occurrence_content)??[];(!Array.isArray(v)||v.length>500||v.some(e=>!e||typeof e.recurrenceId!=`string`||!e.overrides||Object.keys(e.overrides).some(e=>![`title`,`description`,`location`,`organizer`].includes(e))))&&i(`Invalid occurrence_content.`),(new Set(v.map(e=>e.recurrenceId)).size!==v.length||!t.allowStaleOccurrenceCopy&&v.some(e=>!d||!A(g,e.recurrenceId)))&&i(`Invalid editorial recurrence IDs.`);for(let e of v)for(let[t,n]of Object.entries(e.overrides))(t===`description`?typeof n!=`string`&&!Array.isArray(n):typeof n!=`string`)&&i(`Invalid occurrence copy field: `+t);e.location_type!=null&&![`physical`,`virtual`,`hybrid`].includes(String(e.location_type))&&i(`Invalid location type.`),e.event_status!=null&&![`published`,`cancelled`,`postponed`,`rescheduled`].includes(String(e.event_status))&&i(`Invalid event status.`);for(let t of[`virtual_url`,`external_url`,`image_url`])e[t]&&(typeof e[t]!=`string`||!Ae(e[t]))&&i(`Public URLs must use HTTP(S): `+t);let b=N(e.organizer_details);b!=null&&(typeof b!=`object`||Array.isArray(b)||[`id`,`name`,`website`,`contactUrl`].some(e=>typeof b[e]!=`string`)||[`website`,`contactUrl`].some(e=>{let t=b[e];return t&&!Ae(t)}))&&i(`Invalid organizer details.`),e.previous_start_date&&!p(e.previous_start_date)&&!Pe(e.previous_start_date)&&i(`Invalid previous start date.`);let x=N(e.schedule_history);return x!=null&&(!Array.isArray(x)||x.length>10||x.some(e=>!e||!Pe(e.changedAt)||!h(e.timezone)||typeof e.allDay!=`boolean`||(e.allDay?!p(e.start)||!p(e.end)||e.end<e.start:!Pe(e.start)||!Pe(e.end)||Date.parse(e.end)<Date.parse(e.start))))&&i(`Invalid schedule history.`),n.all_day=a,n.timezone=o,ee(e.categories),e.calendar_uid!=null&&(typeof e.calendar_uid!=`string`||!/^[A-Za-z0-9.!~*'()%_-]+@[A-Za-z0-9.-]+$/.test(e.calendar_uid))&&i(`Invalid calendar UID.`),n}const Le=new Set([`image/avif`,`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),Re=8*1024*1024;function ze(e){return Le.has(e.toLowerCase())}function Be(e,t){let n=new URLSearchParams({eventId:t});return`/_emdash/api/plugins/${encodeURIComponent(e)}/publicEventImage?${n}`}function Ve(e,t,n=`eventual`,r){let i=C(t,e.location);return{...e.locale?{locale:e.locale}:{},...e.translationGroup?{translationGroup:e.translationGroup}:{},id:e.id,updatedAt:e.updatedAt,title:e.title,description:e.description,...e.descriptionBlocks?{descriptionBlocks:e.descriptionBlocks}:{},start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,location:i,locationType:e.locationType??`physical`,...T(e.virtualUrl??``)?{virtualUrl:T(e.virtualUrl??``)}:{},status:le(e.published,e.status),organizer:r?.name??(e.organizer||e.organizerDetails?.name||``),...r?{organizerDetails:{id:r.id,name:r.name,website:T(r.website),contactUrl:T(r.contactUrl)}}:e.organizerDetails?{organizerDetails:e.organizerDetails}:{},...e.status===`rescheduled`&&e.previousStartDate?{previousStartDate:e.previousStartDate}:{},externalUrl:e.externalUrl,imageUrl:e.featuredMediaId||e.imageMediaId?e.imageUrl?.includes(`publicEventImage`)?e.imageUrl:Be(n,e.id):e.imageUrl||``,...e.imageMedia?{imageMedia:e.imageMedia}:{},categories:b(e.categories),venue:t?{id:t.id,name:t.name,address:S(t),addressParts:{street:t.street,street2:t.street2,locality:t.locality,region:t.region,postalCode:t.postalCode,country:t.country}}:null,directionsUrl:w(i),calendarLinks:ke({id:e.id,title:e.title,description:e.description,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,location:i,locationType:e.locationType,virtualUrl:e.virtualUrl},``,n)}}const He=e=>e instanceof Date?e.toISOString():a(e);function Ue(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=!!t.data&&typeof t.data==`object`&&!Array.isArray(t.data),r=n?t.data:t,i=a(n&&t.type?t.id:r.id??t.id);if(!i)return null;try{let e=N(r.exceptions)??[];if(!Array.isArray(e))return null;let o=Object.hasOwn(r,`all_day`)||n&&(typeof t.type==`string`||!Object.hasOwn(r,`published`)),s=o?e:e.map(e=>({...e,overrides:e.overrides?Object.fromEntries(Object.entries(e.overrides).filter(([e])=>![`title`,`description`,`location`,`organizer`,`locale`].includes(e))):void 0})).filter(e=>e.status===`cancelled`||Object.keys(e.overrides??{}).length),c=Ie({...r,all_day:r.all_day??r.allDay,exceptions:s},{allowStaleOccurrenceCopy:!0}),l=c.all_day,u=a(l?c.start_date:c.start),d=a(l?c.end_date:c.end),f=N(r.recurrence),p=e.map(e=>({...e,overrides:e.overrides?{...e.overrides}:void 0})),m=N(r.occurrence_content)??[];for(let e of m){if(!f||!A({id:i,start:u,end:d,allDay:l,timezone:a(c.timezone),recurrence:f},e.recurrenceId))continue;let t=p.find(t=>t.recurrenceId===e.recurrenceId);t?.status!==`cancelled`&&(t?t.overrides={...t.overrides,...e.overrides}:p.push({recurrenceId:e.recurrenceId,status:`modified`,overrides:e.overrides}))}let h=o?n&&typeof t.status==`string`?t.status:r.status:void 0,g=h?h===`published`:r.published===!0,_=r.event_status??([`cancelled`,`postponed`,`rescheduled`].includes(a(r.status))?r.status:g?`published`:`draft`),v=typeof r.featured_image==`string`?N(r.featured_image):r.featured_image,y=Object.hasOwn(r,`venue_id`)?r.venue_id:r.venue??r.venueId,b=typeof y==`string`?y:y&&typeof y==`object`?a(y.id):``,x=ee(r.categories),S=a(v?.id??r.featuredMediaId??r.featured_media_id??r.imageMediaId),C=v?.meta?.storageKey,w=a(v?.src||v?.url)||(C?`/_emdash/api/media/file/`+encodeURIComponent(String(C)):``),T=e=>typeof e==`number`&&e>0?e:void 0,E=w?{src:w,width:T(v?.width),height:T(v?.height),alt:a(v?.alt)||void 0}:void 0;return{id:i,title:a(r.title).trim(),description:typeof r.description==`string`?r.description:JSON.stringify(r.description??[]),descriptionBlocks:Array.isArray(r.description)?r.description:void 0,start:u,end:d,allDay:l,timezone:a(c.timezone),published:g,status:_,recurrence:f,exceptions:p,location:a(r.location),locationType:r.location_type??r.locationType??`physical`,virtualUrl:a(r.virtual_url??r.virtualUrl),externalUrl:a(r.external_url??r.externalUrl),organizer:a(r.organizer),organizerId:a(Object.hasOwn(r,`organizer_id`)?r.organizer_id:typeof r.organizer_ref==`object`?r.organizer_ref?.id:r.organizer_ref??r.organizerId),organizerDetails:N(r.organizer_details),venueId:b,imageUrl:S?``:a(r.image_url??r.imageUrl??v?.src??v?.url),imageMediaId:S,featuredMediaId:S||void 0,imageMedia:E,categories:x,createdAt:He(t.createdAt??r.created_at??r.createdAt)||`1970-01-01T00:00:00.000Z`,updatedAt:He(t.updatedAt??r.updated_at??r.updatedAt)||`1970-01-01T00:00:00.000Z`,locale:a(t.locale??r.locale)||void 0,translationGroup:a(t.translationGroup??r.translation_group??r.translationGroup??t.translation_group)||void 0,calendarUid:a(r.calendar_uid??r.calendarUid)||void 0,calendarSequence:typeof r.calendarSequence==`number`?r.calendarSequence:void 0,previousStartDate:a(r.previous_start_date??r.previousStartDate)||void 0,scheduleHistory:N(r.schedule_history??r.scheduleHistory),slug:a(t.slug??r.slug)||void 0,publicUrl:a(t.publicUrl??t.url??r.publicUrl??r.url)||void 0}}catch{return null}}function We(e,t,n,r=`eventual`){let i=De(t,e),a=Ve(e,i?{...i,street:i.street??``,street2:i.street2??``,locality:i.locality??``,region:i.region??``,postalCode:i.postalCode??``,country:i.country??``,createdAt:``,updatedAt:``}:void 0,r),o=a.imageUrl||e.imageUrl;if(n&&o)try{o=new URL(o,n).href}catch{o=``}let s=e.imageMedia,c=s?{...s,src:n&&s.src.startsWith(`/`)?new URL(s.src,n).href:s.src}:void 0;return{...a,description:M(e.description),...e.descriptionBlocks?{descriptionBlocks:e.descriptionBlocks}:{},imageUrl:o,...c?{imageMedia:c}:{},organizerDetails:e.organizerDetails,previousStartDate:e.previousStartDate,locale:e.locale,translationGroup:e.translationGroup,slug:e.slug,publicUrl:e.publicUrl}}const Ge=new WeakMap;function Ke(e,t,n){let r=Ge.get(e);return r||Ge.set(e,r=Object.create(null)),r[t]??=Promise.resolve().then(n)}function qe(e,t){let n=Ge.get(e);n&&delete n[t]}const Je=`collections`,Ye=`legacyReads`,Xe=/^[a-z][a-z0-9_]{0,62}$/;async function Ze(e){return(await Qe(e))?.events??`events`}function Qe(e){return Ke(e,`collection-settings`,async()=>await e.settings?.get(Je)??void 0)}function $e(e){return Ke(e,`legacy-reads`,async()=>await e.settings?.get(Ye)===!0)}async function et(e,t){await e.settings.set(Ye,t),qe(e,`legacy-reads`)}function P(e){return Ke(e,`schemas`,async()=>await e.schema?.listCollections()??[])}function tt(e){return Ke(e,`bindings`,()=>nt(e))}async function nt(e){let[t,n]=await Promise.all([Qe(e),P(e)]);t&&(!t.events||Object.values(t).some(e=>typeof e!=`string`||e!==``&&!Xe.test(e)))&&i(`Invalid collections. Choose them again in Event settings.`);let r=t?.events??`events`,a=n.find(e=>e.slug===r);t&&!a&&i(`The selected event collection is missing.`);let o=(e,t)=>{let n=a?.fields?.find(t=>t.slug===e);return String(n?.validation?.targetCollection??n?.options?.collection??t)},s={events:r,venues:t?.venues??o(`venue`,`venues`),organizers:t?.organizers??o(`organizer_ref`,`organizers`)};if(t)for(let e of[s.venues,s.organizers])e&&!n.some(t=>t.slug===e)&&i(`Selected directory missing. Review Event settings.`);return{...s,schema:a,schemas:n,configured:!!t}}async function rt(e,t){(!t.events||Object.values(t).some(e=>typeof e!=`string`||e!==``&&!Xe.test(e)))&&i(`Choose valid collection names.`);let n=await P(e),r=n.find(e=>e.slug===t.events);r||i(`Choose an existing event collection.`);for(let[e,t]of Object.entries({title:`string`,description:`portableText`,start:`datetime`,end:`datetime`,start_date:`string`,end_date:`string`,all_day:`boolean`,timezone:`string`,recurrence:`json`,exceptions:`json`,occurrence_content:`json`})){let n=r.fields.find(t=>t.slug===e);(!n||n.type!==t)&&i(`Event collection needs `+e+` (`+t+`). Apply the event blueprint first.`);let a=[`title`,`description`,`occurrence_content`].includes(e);n.translatable!==a&&i(`Set `+e+` translatable to `+a+` before selecting this collection.`)}for(let[e,a]of[[`venues`,`venue`],[`organizers`,`organizer_ref`]]){let o=t[e],s=n.find(e=>e.slug===o);o&&(!s||!s.fields.some(e=>[`name`,`title`].includes(e.slug)&&e.type===`string`))&&i(`Choose a `+e+` collection with a name or title field.`);let c=r.fields.find(e=>e.slug===a),l=r.fields.find(t=>t.slug===(c?.validation?.relation?e===`venues`?`venue_id`:`organizer_id`:a)),u=l?.validation?.targetCollection??l?.options?.collection;o&&(l?.type!==`reference`||u!==o)&&i(`Set the event `+a+` reference target to `+o+` first.`),!o&&l&&i(`This event schema has a `+a+` reference. Select its target collection.`),l?.translatable!==void 0&&l.translatable!==!1&&i(`Event references must be shared across languages.`)}await e.settings.set(Je,t),qe(e,`collection-settings`),qe(e,`bindings`)}function it(e){if(typeof e==`string`)return e.trim()||void 0;if(e&&typeof e==`object`&&!Array.isArray(e))return it(e.id)}function F(e,t){let n=e?.fields.find(e=>e.slug===t),r=n?.validation?.targetCollection??n?.options?.collection;return typeof r==`string`&&r?r:t===`venue`?`venues`:`organizers`}function at(e,t){return(e?.fields.find(e=>e.slug===t))?.validation?.relation?t===`venue`?`venue_id`:`organizer_id`:t}async function I(e){return(await tt(e)).schema}var ot=class extends Error{constructor(){super(`The sandbox RPC budget is exceeded.`),this.name=`SandboxBudgetError`}};const st=Symbol(`eventual invocation budget`),ct=new WeakMap;function L(e,t=10){if(e[st])return e;let n=ct.get(e);if(n)return n;let r={used:0,reserved:0,limit:t},i={...e,[st]:r},a=e=>new Proxy(e,{get(e,t){let n=Reflect.get(e,t,e);return typeof n==`function`?(...t)=>{if(r.used+r.reserved>=r.limit)throw new ot;return r.used++,Reflect.apply(n,e,t)}:n}});for(let[t,n]of Object.entries(e))![`site`,`plugin`,`storage`].includes(t)&&n&&typeof n==`object`&&(i[t]=a(n));return e.storage&&(i.storage=new Proxy(e.storage,{get(e,t){let n=Reflect.get(e,t,e);return n&&typeof n==`object`?a(n):n}})),ct.set(e,i),i}function lt(e,t){let n=e[st];if(!n)return()=>{};if(n.used+n.reserved+t>n.limit)throw new ot;n.reserved+=t;let r=!1;return()=>{r||=(n.reserved-=t,!0)}}function ut(e){let t=e[st];return t?t.limit-t.used-t.reserved:10}function dt(e,t){if(!e)return{...t,calendarSequence:t.calendarSequence??Math.floor(Date.now()/1e3)};let n=Math.max(e.calendarSequence??(Math.floor(Date.parse(e.updatedAt)/1e3)||0),t.calendarSequence??0)+1;n>2147483647&&i(`Calendar sequence exhausted.`);let r=e.start!==t.start||e.end!==t.end||e.allDay!==t.allDay||e.timezone!==t.timezone,a=r?[{start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,changedAt:t.updatedAt},...e.scheduleHistory??[]].slice(0,10):e.scheduleHistory;return{...t,calendarSequence:n,...a?{scheduleHistory:a}:{},...r?{previousStartDate:e.start}:e.previousStartDate?{previousStartDate:e.previousStartDate}:{}}}const ft=1e4;var pt=class extends Error{constructor(e){super(`More than ${e} events matched the request. Narrow the query or contact the site administrator.`),this.limit=e,this.name=`EventScanLimitError`}};function mt(e){return e.storage.events}function ht(e){return e.storage.venues}function gt(e){return e.storage.calendar_cancellations}function R(e,t){return mt(e).get(t)}function _t(e,t){return yt(e,t)}function vt(e){return new Date(Math.max(Date.now(),Date.parse(e??``)+1||0)).toISOString()}async function yt(e,t){let n=await mt(e).get(t.id);t=dt(n,t);let r=await xt(e,n,t);await mt(e).put(t.id,t);for(let t=0;t<r.length;t+=100)await gt(e).deleteMany(r.slice(t,t+100));return t}async function bt(e,t){return await xt(e,await mt(e).get(t),null),mt(e).delete(t)}async function xt(e,t,n){let r=new Date().toISOString().slice(0,10),i=new Date(`${r}T00:00:00Z`);i.setUTCDate(i.getUTCDate()+365);let a=i.toISOString().slice(0,10),o=t?.published?j([t],r,a):[],s=n?.published?j([n],r,a):[],c=new Set(s.map(e=>e.id)),l=(e,t)=>`locale:`+e.toLowerCase()+`:`+t,u=[...c,...s.flatMap(e=>Object.keys(n?.translations??{}).map(t=>l(t,e.id)))],d=o.filter(e=>!c.has(e.id)),f=Object.keys(t?.translations??{}).filter(e=>!Object.hasOwn(n?.translations??{},e)),p=n?o.flatMap(e=>f.map(t=>({item:e,locale:t}))):[],m=new Date().toISOString(),h=p.map(({item:e,locale:r})=>({id:l(r,e.id),data:{id:e.id,eventId:t.id,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,cancelledAt:m,locale:r.toLowerCase(),categories:e.categories,calendarUid:t.calendarUid,translationGroup:t.translationGroup,calendarSequence:n?.calendarSequence}}));return d.length&&h.push(...d.map(e=>({id:e.id,data:{id:e.id,eventId:t.id,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,cancelledAt:m,translationGroup:e.translationGroup??t.translationGroup,calendarUid:t.calendarUid,calendarSequence:n?.calendarSequence??(t.calendarSequence??Math.floor(Date.parse(t.updatedAt)/1e3))+1,categories:e.categories,locales:e.locale?[e.locale.toLowerCase(),...Object.keys(t.translations??{}).map(e=>e.toLowerCase())]:void 0}}))),h.length&&await gt(e).putMany(h),u}async function St(e){let t=[],n;do{let r=await gt(e).query({limit:100,cursor:n});if(t.push(...r.items.map(e=>e.data)),r.hasMore&&(!r.cursor||r.cursor===n)&&i(`Incomplete cancellation cursor.`),t.length>ft)throw new pt(ft);n=r.hasMore?r.cursor:void 0}while(n);return t}function Ct(e,t){return ht(e).get(t)}function wt(e,t){return ht(e).put(t.id,t)}function Tt(e,t){return ht(e).delete(t)}async function Et(e,t){return await mt(e).count({venueId:t})>0}async function Dt(e,t={}){let n=[],r=t.maxItems??ft;if(!Number.isInteger(r)||r<1||r>ft)throw RangeError(`maxItems must be between 1 and ${ft}`);let a,o=t.through?new Date(Date.parse(`${t.through}T00:00:00Z`)+2*864e5).toISOString().slice(0,10):void 0,s=new Set;do{let c=await mt(e).query({where:{...t.published===void 0?{}:{published:t.published},...o?{start:{lt:o}}:{}},orderBy:{start:t.order??`asc`},limit:Math.min(100,r-n.length),cursor:a});if(n.push(...c.items.map(e=>e.data)),c.hasMore&&!c.cursor&&i(`Event storage returned an incomplete page without a cursor.`),c.hasMore&&s.has(c.cursor)&&i(`Event storage returned a repeated cursor.`),c.cursor&&s.add(c.cursor),a=c.hasMore?c.cursor:void 0,a&&n.length>=r)throw new pt(r)}while(a);return n}async function Ot(e){let t=[],n;do{let r=await ht(e).query({orderBy:{name:`asc`},limit:100,cursor:n});if(t.push(...r.items.map(e=>e.data)),r.hasMore&&(!r.cursor||r.cursor===n)&&i(`Incomplete venue cursor.`),t.length>5e3)throw new pt(5e3);n=r.hasMore?r.cursor:void 0}while(n);return t}async function kt(e,t){return t.length?ht(e).getMany([...new Set(t)]):new Map}function At(e){return e.storage.organizers}async function jt(e){let t=[],n;do{let r=await At(e).query({orderBy:{name:`asc`},limit:100,cursor:n});t.push(...r.items.map(e=>e.data)),r.hasMore&&(!r.cursor||t.length>=5e3)&&i(`Organizer list exceeds the supported scan limit or has an incomplete page.`),n=r.hasMore?r.cursor:void 0}while(n);return t}function Mt(e,t){return t.length?At(e).getMany([...new Set(t)]):Promise.resolve(new Map)}async function z(e){if(!e.schema||!e.content)return;let t=await I(e);return t&&!t.fields?.some(e=>e.slug===`start`)&&i(`Not an event schema.`),t}async function B(e,t,n=!1){let r=[],a,o=new Set;do{let s=await e.content.list(t,{limit:100,cursor:a,...n?{where:{status:`published`}}:{}});if(r.push(...s.items),r.length>ft)throw new pt(ft);if(!s.hasMore)break;(!s.cursor||o.has(s.cursor))&&i(`Invalid cursor.`),o.add(s.cursor),a=s.cursor}while(!0);return r}async function Nt(e,t){let n=await z(e);if(!n)return await $e(e)||i(`Events are not connected to a content type. Turn on "Show old events saved inside the plugin".`),{native:!1,events:(await Dt(e,{published:!0,...t?{through:t}:{}})).map(t=>t.locale?t:{...t,locale:e.site?.locale??`en`}),schema:n};let r=await B(e,n.slug,!0),a=[];for(let e of r){let t=Ue(e);t||i(`Invalid event: `+e.id),t.published&&a.push(t)}return{native:!0,events:a,schema:n}}async function Pt(e,t,n){let r=new Map,i=[...new Set(t.flatMap(e=>e.venueId?[e.venueId]:[]))],a=n?await Ft(e,F(n,`venue`),t,e=>e.venueId):await kt(e,i);for(let[e,t]of a){let n=Oe(t);n&&r.set(e,n)}return r}async function Ft(e,t,n,r){let i=new Map;for(let e of n){let t=r(e);if(!t)continue;let n=i.get(t)??new Set;n.add((e.locale??``).toLowerCase()),i.set(t,n)}let a=new Map;if(!i.size||!e.content)return a;let o=await Ke(e,`directory:`+t,()=>B(e,t,!0)),s=new Map,c=new Map;for(let e of o){if(e.status!==`published`)continue;s.set(e.id,e);let t=e.translationGroup||e.id,n=(e.locale??``).toLowerCase();c.set(`${t}|${n}`,e)}for(let[e,t]of i){let n=s.get(e);if(n){a.set(e,n);for(let r of t){if(!r||r===(n.locale??``).toLowerCase())continue;let t=n.translationGroup||n.id,i=c.get(`${t}|${r}`);i&&a.set(`${e}|${r}`,i)}}}return a}function It(e,t,n=!1){let r=e=>Intl.getCanonicalLocales(e)[0].toLowerCase(),i=t?r(t):void 0,a=new Map;for(let t of e){let e=t.translationGroup??t.id,n=a.get(e)??[];n.push(t);for(let[e,r]of Object.entries(t.translations??{}))n.push({...t,...r,locale:e,descriptionBlocks:void 0,exceptions:t.exceptions.map(e=>({...e,overrides:e.overrides?Object.fromEntries(Object.entries(e.overrides).filter(([e])=>![`title`,`description`,`location`,`organizer`,`locale`].includes(e))):void 0}))});a.set(e,n)}let o=[];for(let t of a.values()){t.sort((e,t)=>(e.locale??``).localeCompare(t.locale??``)||e.id.localeCompare(t.id));let a=i?t.find(e=>e.locale&&r(e.locale)===i):t.find(t=>!t.translations||e.includes(t))??t[0];if(a)o.push(a);else if(!n){let n=t.find(t=>e.includes(t))??t[0],r=n.locale?`[`+n.locale.toUpperCase()+`] `:``;o.push({...n,title:r+n.title,exceptions:(n.exceptions??[]).map(e=>e.overrides?.title===void 0?e:{...e,overrides:{...e.overrides,title:r+e.overrides.title}})})}}return o}async function Lt(e,t,n=!0){let r=new Map,i=await I(e);if(t.some(e=>e.organizerId)){let n=F(i,`organizer_ref`);for(let[i,a]of await Ft(e,n,t,e=>e.organizerId))r.set(i,{id:a.id,name:String(a.data.name??a.data.title??``),website:T(String(a.data.website??``)),contactUrl:T(String(a.data.contact_url??a.data.contactUrl??``))})}let a=e.plugin?.id??`eventual`,o=new Map,s={};if(n&&i&&e.content?.getPublicUrl)for(let n of t){let t=n.id.split(`#`)[0],r=s[n.locale];if(!n.published||!n.slug||o.has(t))continue;let a=(i.urlPattern??`/`+i.slug+`/{slug}`).replace(`{slug}`,encodeURIComponent(n.slug)).replace(`{id}`,t).replace(/(.)\/$/,`$1`);if(r){o.set(t,r[0]+a+r[1]);continue}if(ut(e)<3)continue;let c=await Ke(e,`url:`+i.slug+`:`+t,()=>e.content.getPublicUrl(i.slug,t)),l=c?.replace(/\/$/,``);o.set(t,c),l?.endsWith(a)&&!a.includes(`{`)&&(s[n.locale]=[l.slice(0,-a.length),c.slice(l.length)])}return Promise.all(t.map(async e=>{let t=r.get((e.organizerId??``)+`|`+(e.locale??``).toLowerCase())??r.get(e.organizerId??``),n=o.get(e.id.split(`#`)[0])??e.publicUrl;return{...e,organizer:e.organizer||t?.name||e.organizerDetails?.name||``,organizerDetails:t??e.organizerDetails,publicUrl:n,imageUrl:e.featuredMediaId||e.imageMediaId?Be(a,e.id):e.imageUrl||``}}))}function Rt(e){let t=e=>({rule:null,error:e}),n=String(e.frequency||``).trim().toLowerCase();if(!n||n===`none`)return{rule:null};let r=String(e.until||``).trim();if(!p(r))return t(`Repeat until must be a valid YYYY-MM-DD date.`);let i=e.interval===void 0||String(e.interval).trim()===``?1:Number(e.interval);if(!Number.isInteger(i)||i<1||i>52)return t(`Interval must be an integer between 1 and 52.`);let a={frequency:n,until:r,...i>1?{interval:i}:{}};if(n===`weekly`&&e.weekdays){let n=Array.isArray(e.weekdays)?e.weekdays:String(e.weekdays).split(`,`).map(e=>e.trim());if(n.some(e=>!E.includes(e)))return t(`Choose valid weekdays.`);n.length&&(a.weekdays=ne(n))}else if(n===`monthly`){let n=e.monthlyPatternType??`dayOfMonth`;if(n===`dayOfMonth`){let r=Number(e.dayOfMonth??1);if(!Number.isInteger(r)||r<1||r>31)return t(`Day of month must be between 1 and 31.`);a.pattern={type:n,dayOfMonth:r,missingDayBehavior:e.missingDayBehavior===`lastDay`?`lastDay`:`skip`}}else if(n===`weekdayOfMonth`){let r=String(e.weekday||`monday`).toLowerCase();if(!E.includes(r))return t(`Choose a valid weekday.`);let i=e.position===`last`?`last`:Number(e.position??1);if(i!==`last`&&(!Number.isInteger(i)||i<1||i>5))return t(`Choose first, second, third, fourth, fifth or last.`);a.pattern={type:n,weekday:r,position:i}}else return t(`Choose a monthly pattern.`)}return[`daily`,`weekly`,`monthly`].includes(n)?D(a)?{rule:a}:t(`Invalid `+n+` recurrence.`):t(`Unsupported recurrence frequency: `+n)}function zt(e){if(e=N(e),!D(e))return{frequency:`none`,interval:1};let t={frequency:e.frequency,interval:e.interval??1,until:e.until};return e.frequency===`weekly`&&e.weekdays&&(t.weekdays=[...e.weekdays]),e.frequency===`monthly`&&e.pattern&&(e.pattern.type===`dayOfMonth`?(t.monthlyPatternType=`dayOfMonth`,t.dayOfMonth=e.pattern.dayOfMonth,t.missingDayBehavior=e.pattern.missingDayBehavior):(t.monthlyPatternType=`weekdayOfMonth`,t.weekday=e.pattern.weekday,t.position=e.pattern.position)),t}function Bt(e){if(e=N(e),!D(e))return`Does not repeat`;let t=te(e);if(e.frequency===`monthly`){let n=e.pattern;t+=n.type===`dayOfMonth`?` on day ${n.dayOfMonth} (${n.missingDayBehavior===`skip`?`skip missing months`:`use last day if missing`})`:` on ${n.position===`last`?`last`:[`first`,`second`,`third`,`fourth`,`fifth`][n.position-1]} ${n.weekday[0].toUpperCase()}${n.weekday.slice(1)}`}return`${t} through ${e.until}`}function Vt(e){let t=new Set([`title`,`description`,`excerpt`,`featured_image`,`image_url`,`start`,`end`,`start_date`,`end_date`,`all_day`,`timezone`,`location_type`,`venue`,`venue_id`,`location`,`virtual_url`,`external_url`,`organizer`,`organizer_ref`,`organizer_id`,`organizer_details`,`categories`,`recurrence`]),n=structuredClone(Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e))));return n.event_status=`published`,n}function Ht(e,t,n){return{version:1,dependencies:[...new Set([e.slug,F(e,`venue`),F(e,`organizer_ref`),`emdash:settings`])],generatedAt:new Date(t).toISOString(),expiresAt:new Date(Math.min(t+15e3,n?(Math.floor(t/864e5)+1)*864e5:1/0)).toISOString()}}function Ut(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Wt(e,t){try{return await Gt(e,L(t,30))}catch(e){if(e instanceof ot)return{ok:!1,error:`SANDBOX_BUDGET_EXCEEDED`,details:e.message,events:void 0};throw e}}async function Gt(e,t){let n={ok:!1,error:`INVALID_QUERY`};if(!Ut(e)||[`from`,`through`,`category`,`locale`,`eventId`].some(t=>e[t]!==void 0&&typeof e[t]!=`string`)||[e.strict,e.publicUrls].some(e=>![void 0,!0,!1,`true`,`false`].includes(e)))return n;try{e.locale&&Intl.getCanonicalLocales(e.locale)}catch{return n}let r=typeof e.eventId==`string`&&e.eventId.trim()?e.eventId.trim():void 0,i=Date.now(),a=new Date(i).toISOString().slice(0,10),o=e.from??a,s=e.through??m(o,180);if(!p(o)||!p(s)||o>s)return{ok:!1,error:`INVALID_DATE_RANGE`};if((Date.parse(`${s}T00:00:00Z`)-Date.parse(`${o}T00:00:00Z`))/864e5+1>366)return{ok:!1,error:`DATE_RANGE_TOO_LARGE`,maxDays:366};let c,l;try{if(l=await Nt(t,s),c=It(l.events,e.locale,[!0,`true`].includes(e.strict)),r){let e=r.split(`#`)[0];c=c.filter(t=>t.id===e)}}catch(e){if(e instanceof pt)return{ok:!1,error:`EVENT_LIMIT_EXCEEDED`,maxEvents:e.limit};throw e}let u=j(c,o,s),d=e.category?x(e.category):``,f=d?u.filter(e=>e.categories.some(e=>x(e)===d)):u;if(r&&r.includes(`#`)&&(f=f.filter(e=>e.id===r)),f.length>1e4)return{ok:!1,error:`OCCURRENCE_LIMIT_EXCEEDED`};if(l.native){let[n,r]=await Promise.all([Pt(t,f,l.schema),Lt(t,f,[void 0,!0,`true`].includes(e.publicUrls))]);return{ok:!0,from:o,through:s,cache:Ht(l.schema,i,e.from===void 0),events:r.map(e=>We(e,n,t.site.url,t.plugin.id))}}let[h,g]=await Promise.all([kt(t,f.flatMap(e=>e.venueId?[e.venueId]:[])),Mt(t,f.flatMap(e=>e.organizerId?[e.organizerId]:[]))]);return{ok:!0,from:o,through:s,events:f.map(e=>Ve(e,e.venueId?h.get(e.venueId):void 0,t.plugin.id,e.organizerId?g.get(e.organizerId):void 0))}}async function Kt(e,t,n){let r=e,a=await z(t);if(!a)return{blocks:[{type:`context`,text:`Choose an event collection in Event settings.`}]};let o=(e,n)=>({type:`link`,label:n,target:{kind:`external`,url:new URL(e,t.site.url).href}}),s=(e,t)=>({type:`link`,label:t,target:{kind:`content`,collection:a.slug,id:e}}),c=`/_emdash/admin/content/`+encodeURIComponent(a.slug),l=`/_emdash/api/plugins/`+encodeURIComponent(t.plugin?.id||`eventual`)+`/`;if(r.page===`widget:upcoming-events`)return{blocks:[{type:`header`,text:`Upcoming events`},...((await Wt({},t)).events??[]).slice(0,5).map(e=>({type:`section`,block_id:`eventual-verbatim`,text:e.title+` · `+e.start}))]};let u=[{type:`header`,text:`Events`},{type:`context`,text:`Create and edit announcements in EmDash. Save first, then open the Dates, venue & repeat panel.`}];if(r.action_id===`duplicate-event`){(!n||typeof r.value!=`string`)&&i(`Sign in before creating a copy.`);let e=await t.content.get(a.slug,r.value);e||i(`This event no longer exists.`);let o=Vt((e.draftRevisionId?await t.content.getRevision?.(a.slug,e.id,e.draftRevisionId):void 0)?.data??e.data),c=new Set(a.fields.filter(e=>!e.validation?.relation).map(e=>e.slug)),l=await t.content.create(a.slug,Object.fromEntries(Object.entries({...o,title:String(o.title??`Event`)+` (copy)`}).filter(([e])=>c.has(e))),{locale:e.locale??void 0});u.push({type:`context`,text:`Draft copy created.`},{type:`actions`,elements:[s(l.id,`Edit the copy`)]})}else r.action_id&&!String(r.action_id).startsWith(`page-native-events`)&&i(`Reload the workspace before trying this action.`);let d=await P(t);u.push({type:`actions`,elements:[s(`new`,`Create event`),o(c,`All events`),...[`venue`,`organizer_ref`].flatMap(e=>{let t=F(a,e);return d.some(e=>e.slug===t)?[o(`/_emdash/admin/content/`+encodeURIComponent(t),e===`venue`?`Manage venues`:`Manage organizers`)]:[]})]});let f=String(r.action_id).startsWith(`page-native-events`)?String(r.value||``):void 0,p=await t.content.list(a.slug,{limit:20,cursor:f});u.push({type:`table`,page_action_id:`page-native-events`,columns:[{key:`title`,label:`Event`},{key:`locale`,label:`Language`},{key:`status`,label:`Publication`,format:`badge`},{key:`edit`,label:`Edit`,format:`element`},...n?[{key:`copy`,label:`Copy`,format:`element`}]:[]],rows:p.items.map(e=>({title:String(e.data.title||e.slug),locale:e.locale??``,status:e.status,edit:s(e.id,`Edit`),...n?{copy:{type:`button`,action_id:`duplicate-event`,label:`Duplicate`,value:e.id}}:{}})),empty_text:`No events yet.`}),p.hasMore&&(!p.cursor||p.cursor===f)&&i(`Incomplete event page. Reload the workspace.`);let m=[...f?[{type:`button`,action_id:`page-native-events-first`,label:`First page`,value:``}]:[],...p.hasMore?[{type:`button`,action_id:`page-native-events-next`,label:`Next events`,value:p.cursor}]:[]];return m.length&&u.push({type:`actions`,elements:m}),u.push({type:`header`,text:`Subscribe`},{type:`actions`,elements:[o(l+`calendar`,`Calendar subscription (.ics)`),o(l+`publicEvents`,`Published events (JSON)`)]}),{blocks:u}}const qt=e=>({type:`context`,text:e}),Jt=()=>({type:`actions`,elements:[[`/events`,`Events`],[`/settings`,`Settings`]].map(([e,t])=>({type:`button`,action_id:`open-page:`+e,label:t,value:e}))});async function Yt(e,t){let n=await Qe(e),r=await $e(e),i=await P(e),a=i.find(e=>e.slug===`events`),o=(e,t)=>String(a?.fields.find(t=>t.slug===e)?.options?.collection??t),s=(e,t)=>t.slug===n?.[e]||t.fields.some(t=>e===`events`?t.slug===`start`:[`name`,`title`].includes(t.slug)&&t.type===`string`),c=(e,t)=>({type:`select`,action_id:e,label:t,options:[{value:``,label:e===`events`?`Choose a collection`:`No collection`},...i.filter(t=>s(e,t)).map(e=>({value:e.slug,label:(e.label||e.slug)+` (`+e.slug+`)`}))],initial_value:n?.[e]??(e===`events`?a?.slug??``:i.some(t=>t.slug===o(e===`venues`?`venue`:`organizer_ref`,e))?o(e===`venues`?`venue`:`organizer_ref`,e):``)});return{blocks:[Jt(),{type:`header`,text:`Settings`},qt(i.some(e=>s(`events`,e))?`Choose content types.`:`Event collection needs start (datetime). Apply the event blueprint first.`),...t?[{type:`banner`,title:`Settings not saved`,description:t,variant:`error`}]:[],{type:`form`,block_id:`collection-settings:`+Object.values(n??{}).join(`:`),fields:[c(`events`,`Event collection`),c(`venues`,`Venue collection`),c(`organizers`,`Organizer collection`)],submit:{action_id:`save-settings`,label:`Save settings`}},{type:`form`,block_id:`legacy-reads:`+r,fields:[{type:`toggle`,action_id:`legacyReads`,label:`Show old events saved inside the plugin`,description:`Enable to serve old plugin events.`,initial_value:r}],submit:{action_id:`save-legacy-reads`,label:`Save switch`}},{type:`actions`,elements:[{type:`link`,label:`Setup guide`,target:{kind:`external`,url:`https://github.com/Vermeulen-Solutions/eventual-rsvp-core`}}]}]}}async function Xt(e,t,n){t=L(t);let r=e&&typeof e==`object`&&!Array.isArray(e)?{...e}:{};if(r.type===`form_submit`&&(!r.values||typeof r.values!=`object`||Array.isArray(r.values)))return{blocks:[{type:`banner`,title:`Invalid admin request`,variant:`error`}]};if(String(r.action_id??``).startsWith(`open-page:`)&&(r.type=`page_load`,r.page=r.value,delete r.action_id),r.page===`/settings`||r.action_id===`save-settings`||r.action_id===`save-legacy-reads`){if(!n||n.role<50)return{blocks:[Jt(),qt(`Only an administrator can change these settings.`)]};if(r.action_id===`save-legacy-reads`)try{let e=r.values?.legacyReads;e===!0||e===!1||e===`true`||e===`false`||i(`The legacy read setting must be on or off.`),await et(t,e===!0||e===`true`)}catch(e){return Yt(t,e instanceof Error?e.message:`Check the legacy read setting.`)}if(r.action_id===`save-settings`)try{let e=r.values;(!e||e.defaultTimezone!==void 0&&!h(String(e.defaultTimezone)))&&i(`Choose a valid IANA time zone.`),await rt(t,{events:String(e.events??``),venues:String(e.venues??``),organizers:String(e.organizers??``)}),e.defaultTimezone!==void 0&&await t.settings.set(`defaultTimezone`,String(e.defaultTimezone))}catch(e){return Yt(t,e instanceof Error?e.message:`Check the collection settings.`)}return Yt(t)}try{if(!(await tt(t)).schema){let e=await $e(t);return{blocks:[Jt(),{type:`header`,text:`Connect events to a content type`},qt(`Choose an event content type.`),qt(e?`Public calendars show old plugin events.`:`Turn on "Show old events saved inside the plugin" in settings if needed.`),qt(`You can copy the old events into a content type. See the setup guide.`)]}}return{blocks:[Jt(),...(await Kt(r,t,n)).blocks]}}catch(e){return{blocks:[Jt(),{type:`banner`,title:`Review collection settings`,description:e instanceof Error?e.message:`Collections could not be loaded.`,variant:`error`}]}}}const Zt=new Set([`label`,`text`,`title`,`description`,`placeholder`,`empty_text`,`confirm`,`deny`,`message`]),Qt=new Set([`venueId`,`organizerId`,`venue`,`organizer_ref`,`imageMediaId`,`timezone`,`eventIds`,`events`,`venues`,`organizers`]);function $t(e,t){let n=e=>{if(Array.isArray(e))return e.map(n);if(!e||typeof e!=`object`)return e;let r=e;return String(r.block_id).startsWith(`eventual-verbatim`)?r:Object.fromEntries(Object.entries(r).map(([e,i])=>[`value`,`initial_value`,`target`,`condition`,`patch`].includes(e)?[e,i]:e===`options`&&Qt.has(String(r.action_id))?[e,i.map(e=>e.value===``?{...e,label:t(e.label)}:e)]:e===`rows`?[e,i.map(e=>Object.fromEntries(Object.entries(e).map(([e,i])=>{if(typeof i!=`string`)return[e,n(i)];let a=i[0]?.toUpperCase()+i.slice(1),o=r.columns.some(t=>t.key==e&&t.format==`badge`)?t(a):e==`effective`?t(i):i;return[e,o==a?i:o]})))]:e===`label`&&r.action_id===`edit-organizer`?[e,i]:[e,Zt.has(e)&&typeof i==`string`?t(i):n(i)]))};return n(e)}const en=new Map;function tn(e){let t=0,n=(n,r)=>{let a=[],o=``,s=()=>{o&&a.push(o),o=``};for(;t<e.length;){let c=e[t];if(c===`{`)s(),t++,a.push(i(n));else if(c===`}`&&r)break;else c===`#`&&n?(s(),a.push(0),t++):(o+=c,t++)}return s(),a},r=()=>{for(;e[t]===` `;)t++;let n=t;for(;t<e.length&&!/[\s,{}]/.test(e[t]);)t++;let r=e.slice(n,t);for(;e[t]===` `||e[t]===`
12
- `;)t++;return r},i=i=>{let a=r();if(e[t]===`}`)return t++,{a};t++;let o=r();if(o!==`plural`&&o!==`select`){let n=e[t]===`,`?(t++,r()):``;for(;t<e.length&&e[t]!==`}`;)t++;return t++,{a,t:o,s:n}}t++;let s={};for(;;){let a=r();if(!a||e[t]!==`{`)break;t++,s[a]=n(o===`plural`||i,!0),t++}for(;t<e.length&&e[t]!==`}`;)t++;return t++,{a,p:o===`plural`,o:s}};return n(!1,!1)}function nn(e,t,n,r){let i=``;for(let a of e)if(typeof a==`string`)i+=a;else if(a===0)i+=r===void 0?`#`:new Intl.NumberFormat(n).format(r);else if(a.t)i+=rn(a,t[a.a],n);else if(!a.o)i+=a.a in t?String(t[a.a]):`{${a.a}}`;else{let e=t[a.a],o;if(a.p){let r=Number(e),s=`other`;try{s=new Intl.PluralRules(n).select(r)}catch{}o=a.o[`=`+r]??a.o[s]??a.o.other,i+=nn(o??[],t,n,r)}else o=a.o[String(e)]??a.o.other,i+=nn(o??[],t,n,r)}return i}function rn(e,t,n){if(t==null||t===``)return``;try{if(e.t===`number`)return new Intl.NumberFormat(n).format(Number(t));if(e.t===`date`){let r=String(t),i=new Date(/^\d{4}-\d{2}-\d{2}$/.test(r)?r+`T00:00:00Z`:r);return Number.isNaN(i.getTime())?r:new Intl.DateTimeFormat(n,{dateStyle:e.s||`medium`,...r.length===10?{timeZone:`UTC`}:{}}).format(i)}}catch{}return String(t)}function an(e,t={},n=`en`){if(!e.includes(`{`))return e;let r=en.get(e);return r||(r=tn(e),en.size>4e3&&en.clear(),en.set(e,r)),nn(r,t,n)}const on=[`fr`,`de`,`nl`,`es`,`it`,`pt`,`pt-BR`,`pl`,`cs`,`sv`,`da`,`nb`,`fi`,`ja`,`zh-CN`,`ko`,`tr`,`uk`,`ar`,`he`],sn={no:`nb`,nn:`nb`,iw:`he`,"zh-Hans":`zh-CN`,"zh-SG":`zh-CN`,"zh-MY":`zh-CN`};function cn(e,t=on){let n;try{n=Intl.getCanonicalLocales(String(e||``).trim().replace(/_/g,`-`))[0]}catch{}if(!n)return`en`;let[r,...i]=n.split(`-`),a=i.find(e=>e.length===4),o=i.find(e=>e.length===2||/^\d{3}$/.test(e)),s=[];if(r===`zh`){if(a===`Hant`||!a&&[`TW`,`HK`,`MO`].includes(o))return`en`;s.push(`zh-CN`)}o&&s.push(`${r}-${o}`,sn[`${r}-${o}`]),a&&s.push(sn[`${r}-${a}`]),s.push(r,sn[r]);for(let e of s)if(e===`en`||t.includes(e))return e;return`en`}const ln=new WeakMap;function un(e,t=`en`){if(!e)return e=>e;let n=ln.get(e);if(!n){n=[];for(let t of Object.keys(e)){if(!/\{\w+\}/.test(t))continue;let e=[],r=t.split(/(\{\w+\})/).map(t=>{let n=/^\{(\w+)\}$/.exec(t)?.[1];return n?(e.push(n),`([\\s\\S]+?)`):t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}).join(``);n.push([RegExp(`^${r}$`),e,t])}ln.set(e,n)}let r=(r,o)=>{if(typeof r!=`string`||!r)return r;let s=e[r];if(s)return s.includes(`{`)?an(s,{},t):s;let c=null;for(let[t,i,a]of n){let n=e[a]&&t.exec(r);n&&(!c||n[n.length-1].length<c[0][c[0].length-1].length)&&(c=[n,i,a])}if(c){let[n,r,s]=c,l={};r.forEach((e,t)=>{let r=n[t+1],o=a(r);o===r&&r.includes(`, `)&&(o=i(r.split(`, `).map(a))),l[e]=o});let u=an(e[s],l,t);return o?u:u.charAt(0).toLocaleUpperCase(t)+u.slice(1)}return r},i=e=>{try{return new Intl.ListFormat(t).format(e)}catch{return e.join(`, `)}},a=t=>{let n=t&&t[0].toLowerCase()+t.slice(1);return n!==t&&e[n]?e[n]:r(t,!0)};return e=>r(e,!1)}const dn=new Map;function fn(e,t){return`https://cdn.jsdelivr.net/npm/${e.package}@${e.version}/catalogs/${e.namespace}/${t}.json`}const pn=(e,t)=>`i18n:${e.namespace}:${e.version}:${t}`;async function mn(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t,0,16))).slice(0,22)}async function hn(e,t,n){let r=await e.http.fetch(fn(t,n));if(!r.ok)return null;let i=await r.text();if(await mn(i)!==t.hashes[n])return null;let a=JSON.parse(i);return!a||typeof a!=`object`?null:(await e.kv.set(pn(t,n),a),dn.set(pn(t,n),{messages:a}),a)}async function gn(e,t,n,r){let i=cn(n,Object.keys(t.hashes));if(i===`en`)return null;let a=pn(t,i),o=dn.get(a);if(o&&(o.messages||Date.now()<o.retry))return o.messages;let s=null;try{if(r&&r()<1)return null;if(s=await e.kv?.get(a)??null,!s){if(!e.http||!e.kv||r&&r()<2)return null;s=await hn(e,t,i)}}catch{s=null}return s&&typeof s!=`object`&&(s=null),dn.set(a,s?{messages:s}:{messages:null,retry:Date.now()+3e5}),s}var _n={package:`@vermeulen.solutions/eventual-locales`,version:`0.1.10`,namespace:`core`,hashes:{ar:`Jr+SsiJppqn2rr/WpJigRw`,cs:`BbmJhujNUiL8fDBw/+wCSw`,da:`Ij9IaV5B7gd+am4YKMcedw`,de:`ADmFQCy+Pv3q6PQSBk7xKQ`,es:`cr3OI43MX3EWALXbjnsy8w`,fi:`OLwpZx/szCaR5fcj8oeMaA`,fr:`FeirW6Y9C44xXOyGFL92hA`,he:`tKYZPpsv0f3z/Ms4/Tm7Lw`,it:`0NiDiE62pLdaGfmXKRcxGA`,ja:`rQsLMNECmEpjxZjz7Wrrww`,ko:`Wx1hBxDHnVUVZ/0hdbvJjA`,nb:`EirSx4KtSzX4NeN+TbK1aw`,nl:`XvvsZpZE2RpqMAPV8bENeg`,pl:`AK0ph74u6zSkAiTlsQX8bg`,"pt-BR":`D2Gp1nCw+85dT6fYcnQK4A`,pt:`c4JysqbI2mVcHXwlQn//XA`,sv:`fTU5PPBSLJJfkW20fY6Nlg`,tr:`uH3GpUPNIN9znD3hNVxTFw`,uk:`jnSPOMPPXXq2RvcLB9c6LQ`,"zh-CN":`ltuv2/7aXv+T0FZFFWIyAQ`}};async function vn(e,t){let n=L(e),r=await gn(n,_n,t,()=>ut(n));return r?un(r,t):null}async function yn(e){await gn(e,_n,e.site?.locale)}function bn(e,t){return p(e)&&p(t)&&e<=t&&Date.parse(`${t}T00:00:00Z`)-Date.parse(`${e}T00:00:00Z`)<366*864e5}function xn(e,t){return t.allDay?e:_(e,t.timezone)}function Sn(e,t,n,r=100,a=0){(!bn(t,n)||!Number.isInteger(r)||r<1||r>100||!Number.isInteger(a)||a<0)&&i(`Invalid occurrence range or limit.`);let o=j([{...e,exceptions:e.exceptions.filter(e=>e.status!==`cancelled`)}],t,n),s=o.slice(a,a+r).map(t=>{let n=e.recurrence?t.id.slice(e.id.length+1):null,r=n?A(e,n):e,i=e.exceptions.find(e=>e.recurrenceId===n);return{id:t.id,recurrenceId:n,scheduledStart:r.start,scheduledEnd:r.end,scheduledLocalStart:xn(r.start,r),scheduledLocalEnd:xn(r.end,r),scheduledTimezone:r.timezone,start:t.start,end:t.end,localStart:xn(t.start,t),localEnd:xn(t.end,t),timezone:t.timezone,allDay:t.allDay,status:i?.status??`scheduled`}});return{from:t,through:n,occurrences:s,total:o.length,truncated:a+s.length<o.length}}function Cn(e,t,n,r=10,a=0){bn(t,n)||i(`Invalid occurrence date range. Must be <= 366 days.`);let o=N(e.recurrence);if(!o||typeof o!=`object`)return{from:t,through:n,occurrences:[],total:0,offset:a,limit:r,hasMore:!1};let s=!!e.all_day,c=String(e.timezone||`Europe/Zurich`),l=s?String(e.start_date||``):String(e.start||``),u=s?String(e.end_date||l):String(e.end||l),d=N(e.exceptions),f=Array.isArray(d)?d:[],p=new Map;for(let e of f)e&&typeof e.recurrenceId==`string`&&p.set(e.recurrenceId,e);let m=N(e.occurrence_content),h=new Map((Array.isArray(m)?m:[]).map(e=>[e.recurrenceId,e.overrides])),g={id:`series`,title:String(e.title||``),description:``,start:l,end:u,allDay:s,timezone:c,location:``,organizer:``,externalUrl:``,imageUrl:``,categories:[],published:!0,recurrence:o,exceptions:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},v=Ce(g,t,n).map(e=>{let t=e.id.slice(7),n=A(g,t)??e,r=p.get(t),i=r?.status===`cancelled`,a=r?.status===`modified`,o=i?`cancelled`:a?`modified`:`scheduled`,l=a&&r?.overrides?{...e,...r.overrides}:e,u=(e,t,n)=>t?e:_(e,n);return{id:t,recurrenceId:t,scheduledStart:n.start,scheduledEnd:n.end,scheduledLocalStart:u(n.start,s,c),scheduledLocalEnd:u(n.end,s,c),effectiveStart:i?n.start:l.start,effectiveEnd:i?n.end:l.end,effectiveLocalStart:u(i?n.start:l.start,l.allDay,l.timezone||c),effectiveLocalEnd:u(i?n.end:l.end,l.allDay,l.timezone||c),timezone:l.timezone||c,allDay:l.allDay,status:o,hasLocalizedCopy:h.has(t),localizedCopy:h.get(t)}});return{from:t,through:n,occurrences:v.slice(a,a+r),total:v.length,offset:a,limit:r,hasMore:a+r<v.length}}function wn(e=[],t){let n=e.filter(e=>e.recurrenceId!==t);return n.push({recurrenceId:t,status:`cancelled`}),n}function Tn(e=[],t,n){let r=e.filter(e=>e.recurrenceId!==t);return r.push({recurrenceId:t,status:`modified`,overrides:n}),r}function En(e=[],t){return e.filter(e=>e.recurrenceId!==t)}function Dn(e=[],t,n){return[...e.filter(e=>e.recurrenceId!==t),{recurrenceId:t,overrides:{...e.find(e=>e.recurrenceId===t)?.overrides,...n}}]}function On(e=[],t){return e.filter(e=>e.recurrenceId!==t)}function kn(e,t,n,r=``,i=!1,a=80){let o=new Map;for(let t of e){let e=t.translationGroup||t.id;o.has(e)||o.set(e,[]),o.get(e).push(t)}let s=[...o.values()].map(e=>{let r=[...e].sort((e,t)=>Number(t.status===`published`)-Number(e.status===`published`)||e.id.localeCompare(t.id)),a=r.find(e=>e.id===n)??r[0],o=r.find(e=>e.status===`published`&&e.locale?.toLowerCase()===t.toLowerCase())??r.find(e=>e.status===`published`)??r.find(e=>e.locale?.toLowerCase()===t.toLowerCase())??r[0],s=i?Oe(o):void 0,c=String(o.data.name??o.data.title??o.id),l=s?.address??``;return{value:a.id,editId:o.id,label:c+(l?` — `+l:``)+` [`+(o.locale||`default`).toUpperCase()+`]`+(a.status===`published`?``:` (publish before the event)`),name:c,address:l,published:a.status===`published`}}).sort((e,t)=>e.label.localeCompare(t.label)),c=r.trim().normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase(),l=s.filter(e=>!c||e.label.normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase().includes(c)),u=l.slice(0,a),d=s.find(e=>e.value===n);return d&&!u.includes(d)&&u.push(d),{choices:u,current:d,matches:l.length}}const An=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{};[...E.slice(1),E[0]].map(e=>({value:e,label:e[0].toUpperCase()+e.slice(1)}));const jn=(e,t,n)=>({type:`date_input`,action_id:e,label:t,initial_value:a(n)||void 0}),Mn=(e,t,n,r=!1)=>({type:`text_input`,action_id:e,label:t,initial_value:a(n),multiline:r}),Nn=(e,t,n,r)=>({type:`combobox`,action_id:e,label:t,options:n,initial_value:a(r)}),Pn=(e,t,n)=>({type:`form`,block_id:e,fields:n,submit:{action_id:e,label:t}}),Fn=e=>N(e.exceptions)??[],In=e=>N(e.occurrence_content)??[],V=e=>({type:`editor-draft-patch`,operations:e}),H=(e,t)=>({op:`set`,field:e,value:t}),Ln=e=>({op:`clear`,field:e});function Rn(e,t,n){let r=a(e);try{return t?r:r&&Number.isFinite(Date.parse(r))?_(r,n):r}catch{return r}}function zn(e){let t=!!e.all_day,n=a(e.timezone)||`Europe/Zurich`;return{allDay:t,timezone:n,start:Rn(t?e.start_date:e.start,t,n),end:Rn(t?e.end_date:e.end,t,n)}}function Bn(e,t=``,n){let r=zn(e);return[{type:`toggle`,action_id:t+`all_day`,label:`All-day event`,initial_value:r.allDay},jn(t+`start_date`,`Start date`,r.start.slice(0,10)),{...Mn(t+`start_time`,`Start time`,r.start.slice(11,16)),placeholder:`18:30`,condition:{field:t+`all_day`,eq:!1}},jn(t+`end_date`,`End date (last day for all-day events)`,r.end.slice(0,10)),{...Mn(t+`end_time`,`End time`,r.end.slice(11,16)),placeholder:`20:00`,condition:{field:t+`all_day`,eq:!1}},Nn(t+`timezone`,`Time zone`,[...new Set([r.timezone,`UTC`,`Europe/Zurich`,`Europe/Paris`,`Europe/London`,`America/New_York`])].map(e=>({value:e,label:e.replaceAll(`_`,` `)})).concat({value:`custom`,label:`Other time zone…`}),r.timezone),{...Mn(t+`custom_timezone`,`Other IANA time zone`),placeholder:`Pacific/Auckland`,condition:{field:t+`timezone`,eq:`custom`}}].map(e=>n&&Object.hasOwn(n,e.action_id)?{...e,initial_value:n[e.action_id]}:e)}function Vn(e,t=``){let n=e[t+`all_day`]===!0,r=a(e[t+`timezone`]===`custom`?e[t+`custom_timezone`]:e[t+`timezone`]).trim(),o=a(e[t+`start_date`]),s=a(e[t+`end_date`])||o;if((!p(o)||!p(s))&&i(`Choose a valid start and end date.`),n)return{all_day:!0,timezone:r,start_date:o,end_date:s};let c=g(o+`T`+a(e[t+`start_time`]),r),l=g(s+`T`+a(e[t+`end_time`]),r);return(!c.value||!l.value)&&i(c.error||l.error||`Enter times as HH:MM.`),{all_day:!1,timezone:r,start:c.value,end:l.value}}async function Hn(e,t){let n=e.ui?.entry;if(!n||n.collection!==(await I(t))?.slug&&n.collection!==`events`)return{blocks:[{type:`banner`,variant:`error`,title:`Open this panel from an event editor.`}]};let r=An(e.input),o=An(An(r.draft).fields);if(!r.draft){let e=await t.content?.get(n.collection,n.id);if(o=e?.data??{},e?.draftRevisionId){let r=await t.content?.getRevision?.(n.collection,n.id,e.draftRevisionId);r&&(o=r.data)}}try{o={...o,recurrence:N(o.recurrence),exceptions:N(o.exceptions),occurrence_content:N(o.occurrence_content)}}catch{return{blocks:[{type:`banner`,variant:`error`,title:`Stored event data needs repair`,description:`The recurrence or date overrides could not be read.`}]}}let s=An(r.values),c,l,u=a(r.value)||a(s.recurrence_id),d=0,f;try{r.type!==`panel_load`&&!r.draft&&i(`Reload the editor before changing this event.`);let e=a(r.action_id);if(e===`apply-recurrence`){let e=a(s.frequency),t=Rt(e.startsWith(`monthly-`)?{...s,frequency:`monthly`,monthlyPatternType:e===`monthly-weekday`?`weekdayOfMonth`:`dayOfMonth`,interval:Number((e===`monthly-weekday`?s.interval_months_weekday:s.interval_months)??s.interval??1)}:{...s,interval:Number(s[`interval_`+(e===`daily`?`days`:`weeks`)]??s.interval??1)});t.error&&i(t.error),c=V(t.rule?[H(`recurrence`,t.rule)]:[Ln(`recurrence`)])}else if(e===`apply-schedule`){let e=Vn(s);c=V([...Object.entries(e).map(([e,t])=>H(e,t)),...e.all_day?[Ln(`start`),Ln(`end`)]:[Ln(`start_date`),Ln(`end_date`)]])}else if(e===`apply-details`){let e=await I(t);for(let n of[`venue`,`organizer_ref`].filter(e=>Object.hasOwn(s,e))){e&&!e.fields.some(t=>t.slug===at(e,n))&&i(`Upgrade event reference schema first.`);let r=a(s[n]);r&&!await t.content?.get(F(e,n),r)&&i(`Selected entry no longer exists.`)}c=V([...[`venue`,`organizer_ref`].filter(e=>Object.hasOwn(s,e)).map(t=>H(at(e,t),a(s[t])))])}else if(e!==`search-directories`)if(e===`page-occurrences`){let e=An(JSON.parse(a(r.value)||`{}`));d=Math.max(0,Math.min(500,Number(e.offset)||0)),f=a(e.from)}else if(e===`inspect-window`)f=a(s.from),u=``;else if([`cancel-occurrence`,`restore-occurrence`,`reschedule-occurrence`,`set-occurrence-copy`,`clear-occurrence-copy`,`edit-occurrence`].includes(e)){let t=Ie(o,{allowStaleOccurrenceCopy:!0}),r=A({id:n.id,start:t.all_day?t.start_date:t.start,end:t.all_day?t.end_date:t.end,allDay:t.all_day,timezone:t.timezone,recurrence:N(o.recurrence)},u);if(r||i(`Date no longer belongs to repeat schedule.`),f=Rn(r.start,r.allDay,r.timezone).slice(0,10),e===`cancel-occurrence`&&(c=V([H(`exceptions`,wn(Fn(o),u))])),e===`restore-occurrence`&&(c=V([H(`exceptions`,En(Fn(o),u))])),e===`clear-occurrence-copy`&&(c=V([H(`occurrence_content`,On(In(o),u))])),e===`reschedule-occurrence`){let e=Vn(s,`override_`);c=V([H(`exceptions`,Tn(Fn(o),u,{start:a(e.all_day?e.start_date:e.start),end:a(e.all_day?e.end_date:e.end),allDay:e.all_day,timezone:e.timezone}))])}if(e===`set-occurrence-copy`){let e={};for(let t of[`title`,`location`,`organizer`])s[`use_`+t]===!0&&(e[t]=a(s[`copy_`+t]));if(s.use_description===!0){let t=In(o).find(e=>e.recurrenceId===u)?.overrides.description;e.description=t!==void 0&&M(t)===a(s.copy_description)?t:Ee(a(s.copy_description))}let t=In(o).filter(e=>e.recurrenceId!==u);c=V([H(`occurrence_content`,Object.keys(e).length?Dn(t,u,e):t)])}}else e&&i(`Unknown action. Reload the panel.`);if(c){let t={...o};for(let e of c.operations)t[e.field]=e.op===`clear`?null:e.value;(e!==`apply-details`||[`start`,`end`,`start_date`,`end_date`].some(e=>t[e]))&&Ie(t,{allowStaleOccurrenceCopy:!0}),c.operations=c.operations.filter(e=>{let t=o[e.field];if(e.op===`clear`)return t!=null&&t!==``;let n=t;if(typeof t==`string`&&(Array.isArray(e.value)||typeof e.value==`object`))try{n=JSON.parse(t)}catch{}return JSON.stringify(n??``)!==JSON.stringify(e.value)}),o=t,c.operations.length||(c=void 0)}}catch(e){l=e instanceof Error?e.message:`Changes could not be applied.`,c=void 0}return{fields:o,effect:c,state:{selectedId:u,offset:d,windowStart:f,search:a(s.directory_search),values:l?s:void 0,locale:n.locale??``,uiLocale:e.ui?.locale||`en`,error:l,action:a(r.action_id),origin:t.site?.url||new URL(e.request.url).origin}}}const Un=(e,t,n=``,r=!1)=>({type:`text_input`,action_id:e,label:t,initial_value:String(n??``),multiline:r}),Wn=(e,t,n,r)=>({type:`select`,action_id:e,label:t,options:n,initial_value:String(r??``)}),Gn=(e,t,n)=>({type:`date_input`,action_id:e,label:t,initial_value:String(n??``)}),U=(e,t,n)=>({type:`button`,action_id:e,label:t,value:n}),Kn=(e,t,n=!1)=>({type:`accordion`,label:e,blocks:t,default_open:n});async function qn(e,t,n){let r=[];n.error&&r.push({type:`banner`,title:`Check these details`,description:n.error,variant:`error`}),r.push(Kn(`When`,[Pn(`apply-schedule`,`Save dates to draft`,Bn(e,``,n.values))],!0));let i=zt(e.recurrence),a={...i,...n.values},o=i.frequency===`monthly`?i.monthlyPatternType===`weekdayOfMonth`?`monthly-weekday`:`monthly-day`:i.frequency,s=[...E.slice(1),E[0]].map(e=>({value:e,label:e[0].toUpperCase()+e.slice(1)})),c=[Wn(`frequency`,`Repeat`,[{value:`none`,label:`Does not repeat`},{value:`daily`,label:`Daily`},{value:`weekly`,label:`Weekly`},{value:`monthly-day`,label:`Monthly — day of month`},{value:`monthly-weekday`,label:`Monthly — weekday position`}],a.frequency===`monthly`?o:a.frequency)];for(let[e,t,n]of[[`daily`,`days`,`Every … days`],[`weekly`,`weeks`,`Every … weeks`],[`monthly-day`,`months`,`Every … months`],[`monthly-weekday`,`months_weekday`,`Every … months`]])c.push({type:`number_input`,action_id:`interval_`+t,label:n,initial_value:Number(a[`interval_`+t]??a.interval??1),min:1,max:52,condition:{field:`frequency`,eq:e}});c.push({...Gn(`until`,`Last repeat date`,a.until),condition:{field:`frequency`,neq:`none`}},{type:`checkbox`,action_id:`weekdays`,label:`Days of the week`,options:s,initial_value:Array.isArray(a.weekdays)?a.weekdays:[],condition:{field:`frequency`,eq:`weekly`}},{type:`number_input`,action_id:`dayOfMonth`,label:`Day of month`,initial_value:Number(a.dayOfMonth??(String(e.start_date??e.start??``).slice(8,10)||1)),min:1,max:31,condition:{field:`frequency`,eq:`monthly-day`}},{...Wn(`missingDayBehavior`,`When this day does not exist`,[{value:`skip`,label:`Skip that month`},{value:`lastDay`,label:`Use the month’s last day`}],a.missingDayBehavior??`skip`),condition:{field:`frequency`,eq:`monthly-day`}},{...Wn(`weekday`,`Weekday`,s,a.weekday??`monday`),condition:{field:`frequency`,eq:`monthly-weekday`}},{...Wn(`position`,`Weekday position`,[1,2,3,4,5,`last`].map((e,t)=>({value:String(e),label:[`First`,`Second`,`Third`,`Fourth`,`Fifth`,`Last`][t]})),a.position??1),condition:{field:`frequency`,eq:`monthly-weekday`}}),r.push(Kn(`Repeat`,[{type:`context`,text:Bt(e.recurrence)},Pn(`apply-recurrence`,`Save repeat settings`,c)],n.action===`apply-recurrence`));let l=await I(t),u=[];for(let[r,i]of[[`venue`,`Saved venue`],[`organizer_ref`,`Saved organizer`]]){let a=at(l,r);if(!l?.fields.some(e=>e.slug===a))continue;let o=F(l,r),s=it(e[a]),c=kn((await P(t)).some(e=>e.slug===o)?await B(t,o):[],n.locale,s,void 0,r===`venue`,998).choices;u.push({type:`combobox`,action_id:r,label:i,options:[{value:``,label:r===`venue`?`No saved venue`:`No saved organizer`},...c],initial_value:s??``})}r.push(Kn(`Where`,[Pn(`apply-details`,`Save venue and organizer`,u)],n.action===`apply-details`));try{Ie(e,{allowStaleOccurrenceCopy:!0});let t=new Date().toISOString().slice(0,10),i=String(e.start_date??e.start??``).slice(0,10),a=n.windowStart??(i>t?i:t),o=k(a,89),s=Cn(e,a,o,20,n.offset),c=[Pn(`inspect-window`,`Show dates`,[Gn(`from`,`Show dates from`,a)]),{type:`context`,text:a+` — `+o}];for(let e of s.occurrences)c.push({type:`section`,block_id:`eventual-verbatim:`+e.recurrenceId,text:e.scheduledLocalStart+` → `+e.scheduledLocalEnd+` · `+e.status},{type:`actions`,elements:[U(`edit-occurrence`,`Change date`,e.recurrenceId),...e.status===`cancelled`?[U(`restore-occurrence`,`Restore date`,e.recurrenceId)]:[U(`cancel-occurrence`,`Cancel date`,e.recurrenceId)],...e.status===`modified`?[U(`restore-occurrence`,`Restore date`,e.recurrenceId)]:[]]});let l=[];n.offset&&l.push(U(`page-occurrences-prev`,`Previous dates`,JSON.stringify({from:a,offset:Math.max(0,n.offset-20)}))),s.hasMore&&l.push(U(`page-occurrences-next`,`Next dates`,JSON.stringify({from:a,offset:n.offset+20}))),l.length&&c.push({type:`actions`,elements:l}),c.push({type:`actions`,elements:[U(`window-prev`,`Previous 90 days`,k(a,-90)),U(`window-next`,`Next 90 days`,k(a,90))]});let u=s.occurrences.find(e=>e.recurrenceId===n.selectedId);if(u){let t=Wn(`recurrence_id`,`Occurrence`,[{value:u.recurrenceId,label:u.scheduledLocalStart}],u.recurrenceId),r={...e,all_day:u.allDay,timezone:u.timezone,...u.allDay?{start_date:u.effectiveStart,end_date:u.effectiveEnd}:{start:u.effectiveStart,end:u.effectiveEnd}};c.push(Pn(`reschedule-occurrence`,`Save changed date`,[t,...Bn(r,`override_`,n.values)]));let i=u.localizedCopy??{};c.push(Pn(`set-occurrence-copy`,`Save announcement for this date`,[t,...[`title`,`description`,`location`,`organizer`].flatMap(e=>[{type:`toggle`,action_id:`use_`+e,label:`Use a different `+e,initial_value:i[e]!==void 0},{...Un(`copy_`+e,e[0].toUpperCase()+e.slice(1),e===`description`?M(i[e]):i[e],e===`description`),condition:{field:`use_`+e,eq:!0}}])]),{type:`actions`,elements:[U(`clear-occurrence-copy`,`Use the series announcement`,u.recurrenceId)]})}r.push(Kn(`Individual dates`,c,!!n.selectedId))}catch(e){r.push(Kn(`Individual dates`,[{type:`context`,text:e instanceof Error?e.message:`Check the event schedule.`}]))}return{blocks:r}}const Jn=e=>JSON.stringify([e.updatedAt,e.draftRevisionId??``,e.status]),Yn=e=>({blocks:[{type:`banner`,title:e,variant:`error`}]});async function Xn(e,t){t=L(t);let n=await I(t),r=e.ui?.entry;if(!n||r?.collection!==n.slug)return{blocks:[{type:`context`,text:`Eventual RSVP manages the collection chosen in Event settings.`}]};let i=await t.content?.get(n.slug,r.id);if(!i)return Yn(`This event no longer exists.`);let a=(i.draftRevisionId?await t.content?.getRevision?.(n.slug,i.id,i.draftRevisionId):void 0)?.data??i.data,o=e.input&&typeof e.input==`object`?e.input:{},[s,c]=String(o.action_id??``).split(`|`);if(o.type!==`panel_load`&&c!==encodeURIComponent(Jn(i)))return Yn(`This event changed. Close and reopen the panel before trying again.`);s?.startsWith(`page-occurrences-`)&&(s=`page-occurrences`),s?.startsWith(`window-`)&&(s=`inspect-window`,o.values={from:o.value});let l=await Hn({...e,input:{...o,action_id:s,draft:{fields:a}}},t);if(`blocks`in l)return l;let u=l.effect?.operations;if(u?.length){let e=await t.content.get(n.slug,i.id);if(!e||Jn(e)!==Jn(i))return Yn(`This event changed. Close and reopen the panel before trying again.`);let r=new Set(n.fields.filter(e=>!e.validation?.relation).map(e=>e.slug)),a={};for(let e of u){if(!r.has(e.field)||[`title`,`description`,`excerpt`].includes(e.field))return Yn(`The event schema needs an administrator to review this field.`);a[e.field]=e.op===`clear`?null:e.value}return await t.content.update(n.slug,i.id,a),{blocks:[{type:`context`,text:`Schedule saved as an EmDash draft. Publish in the content editor when ready.`}],refresh:!0,toast:{message:`Schedule draft saved.`,type:`success`}}}let d=encodeURIComponent(Jn(i)),f=e=>{if(Array.isArray(e))return e.map(f);if(!e||typeof e!=`object`)return e;let t=e;return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,e===`action_id`&&(t.type===`button`||!t.type&&`label`in t)?String(n)+`|`+d:f(n)]))},p=await qn(l.fields,t,l.state);return p.blocks=f(p.blocks),p.blocks.unshift({type:`context`,text:`Save announcement edits first. This panel updates the saved draft. Publish in core. Dates and venue are shared across languages.`}),p}const Zn=(t,n,r={})=>e({status:t,headers:{"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,...r},body:{kind:`text`,value:n}}),Qn=()=>Zn(404,`Not found`);async function $n(t,n){if(n=L(n),typeof t!=`object`||!t||Array.isArray(t))return Qn();let r=t.eventId;if(typeof r!=`string`||r.length<1||r.length>128)return Qn();let[i,a]=r.split(`#`),o=await z(n),s=o?await n.content.get(o.slug,i):void 0;if(o&&!s&&o.fields.some(e=>e.slug===`legacy_id`&&e.indexed)){let e=await n.content.list(o.slug,{limit:2,where:{status:`published`,fieldFilters:{legacy_id:i}}});if(e.hasMore||e.items.length>1)return Qn();s=e.items[0]}let c=!o&&await $e(n),l=o?Ue(s):c?await R(n,r)??await R(n,i):void 0;if(l&&a){let e=l.exceptions?.find(e=>e.recurrenceId===a),t=e?.overrides?.featuredMediaId||e?.overrides?.imageMediaId;t&&(l={...l,featuredMediaId:t,imageMediaId:t})}let u=l?.featuredMediaId||l?.imageMediaId;if(!l?.published||!u||!n.media?.readBytes)return Qn();let d=await n.media.get(u);if(!d||!ze(d.mimeType))return Qn();if(d.size!==null&&d.size>Re)return Zn(413,`Event image is too large`);try{let t=await n.media.readBytes(u,{maxBytes:Re});return!ze(t.mimeType)||t.mimeType!==d.mimeType?Qn():e({status:200,headers:{"content-type":t.mimeType,"cache-control":`public, max-age=3600, must-revalidate`},body:{kind:`bytes`,value:t.bytes}})}catch{return Qn()}}function er(e,t,n,r=new Date,a){let o=new Set(e.map(e=>W(e,n))),s=new Map;for(let e of t){let t=W(e,n),r=s.get(t);!o.has(t)&&(!r||e.cancelledAt>r.cancelledAt)&&s.set(t,e)}let c=`${[`BEGIN:VCALENDAR`,`VERSION:2.0`,`PRODID:-//Vermeulen Solutions//Eventual RSVP//EN`,`CALSCALE:GREGORIAN`,`METHOD:PUBLISH`,`X-WR-CALNAME:${G(a||`Eventual RSVP`)}`,...e.flatMap(e=>nr(e,n,r)),...[...s.values()].flatMap(e=>rr(e,n,r)),`END:VCALENDAR`].flatMap(lr).join(`\r
12
+ `;)t++;return r},i=i=>{let a=r();if(e[t]===`}`)return t++,{a};t++;let o=r();if(o!==`plural`&&o!==`select`){let n=e[t]===`,`?(t++,r()):``;for(;t<e.length&&e[t]!==`}`;)t++;return t++,{a,t:o,s:n}}t++;let s={};for(;;){let a=r();if(!a||e[t]!==`{`)break;t++,s[a]=n(o===`plural`||i,!0),t++}for(;t<e.length&&e[t]!==`}`;)t++;return t++,{a,p:o===`plural`,o:s}};return n(!1,!1)}function nn(e,t,n,r){let i=``;for(let a of e)if(typeof a==`string`)i+=a;else if(a===0)i+=r===void 0?`#`:new Intl.NumberFormat(n).format(r);else if(a.t)i+=rn(a,t[a.a],n);else if(!a.o)i+=a.a in t?String(t[a.a]):`{${a.a}}`;else{let e=t[a.a],o;if(a.p){let r=Number(e),s=`other`;try{s=new Intl.PluralRules(n).select(r)}catch{}o=a.o[`=`+r]??a.o[s]??a.o.other,i+=nn(o??[],t,n,r)}else o=a.o[String(e)]??a.o.other,i+=nn(o??[],t,n,r)}return i}function rn(e,t,n){if(t==null||t===``)return``;try{if(e.t===`number`)return new Intl.NumberFormat(n).format(Number(t));if(e.t===`date`){let r=String(t),i=new Date(/^\d{4}-\d{2}-\d{2}$/.test(r)?r+`T00:00:00Z`:r);return Number.isNaN(i.getTime())?r:new Intl.DateTimeFormat(n,{dateStyle:e.s||`medium`,...r.length===10?{timeZone:`UTC`}:{}}).format(i)}}catch{}return String(t)}function an(e,t={},n=`en`){if(!e.includes(`{`))return e;let r=en.get(e);return r||(r=tn(e),en.size>4e3&&en.clear(),en.set(e,r)),nn(r,t,n)}const on=[`fr`,`de`,`nl`,`es`,`it`,`pt`,`pt-BR`,`pl`,`cs`,`sv`,`da`,`nb`,`fi`,`ja`,`zh-CN`,`ko`,`tr`,`uk`,`ar`,`he`],sn={no:`nb`,nn:`nb`,iw:`he`,"zh-Hans":`zh-CN`,"zh-SG":`zh-CN`,"zh-MY":`zh-CN`};function cn(e,t=on){let n;try{n=Intl.getCanonicalLocales(String(e||``).trim().replace(/_/g,`-`))[0]}catch{}if(!n)return`en`;let[r,...i]=n.split(`-`),a=i.find(e=>e.length===4),o=i.find(e=>e.length===2||/^\d{3}$/.test(e)),s=[];if(r===`zh`){if(a===`Hant`||!a&&[`TW`,`HK`,`MO`].includes(o))return`en`;s.push(`zh-CN`)}o&&s.push(`${r}-${o}`,sn[`${r}-${o}`]),a&&s.push(sn[`${r}-${a}`]),s.push(r,sn[r]);for(let e of s)if(e===`en`||t.includes(e))return e;return`en`}const ln=new WeakMap;function un(e,t=`en`){if(!e)return e=>e;let n=ln.get(e);if(!n){n=[];for(let t of Object.keys(e)){if(!/\{\w+\}/.test(t))continue;let e=[],r=t.split(/(\{\w+\})/).map(t=>{let n=/^\{(\w+)\}$/.exec(t)?.[1];return n?(e.push(n),`([\\s\\S]+?)`):t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}).join(``);n.push([RegExp(`^${r}$`),e,t])}ln.set(e,n)}let r=(r,o)=>{if(typeof r!=`string`||!r)return r;let s=e[r];if(s)return s.includes(`{`)?an(s,{},t):s;let c=null;for(let[t,i,a]of n){let n=e[a]&&t.exec(r);n&&(!c||n[n.length-1].length<c[0][c[0].length-1].length)&&(c=[n,i,a])}if(c){let[n,r,s]=c,l={};r.forEach((e,t)=>{let r=n[t+1],o=a(r);o===r&&r.includes(`, `)&&(o=i(r.split(`, `).map(a))),l[e]=o});let u=an(e[s],l,t);return o?u:u.charAt(0).toLocaleUpperCase(t)+u.slice(1)}return r},i=e=>{try{return new Intl.ListFormat(t).format(e)}catch{return e.join(`, `)}},a=t=>{let n=t&&t[0].toLowerCase()+t.slice(1);return n!==t&&e[n]?e[n]:r(t,!0)};return e=>r(e,!1)}const dn=new Map;function fn(e,t){return`https://cdn.jsdelivr.net/npm/${e.package}@${e.version}/catalogs/${e.namespace}/${t}.json`}const pn=(e,t)=>`i18n:${e.namespace}:${e.version}:${t}`;async function mn(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t,0,16))).slice(0,22)}async function hn(e,t,n){let r=await e.http.fetch(fn(t,n));if(!r.ok)return null;let i=await r.text();if(await mn(i)!==t.hashes[n])return null;let a=JSON.parse(i);return!a||typeof a!=`object`?null:(await e.kv.set(pn(t,n),a),dn.set(pn(t,n),{messages:a}),a)}async function gn(e,t,n,r){let i=cn(n,Object.keys(t.hashes));if(i===`en`)return null;let a=pn(t,i),o=dn.get(a);if(o&&(o.messages||Date.now()<o.retry))return o.messages;let s=null;try{if(r&&r()<1)return null;if(s=await e.kv?.get(a)??null,!s){if(!e.http||!e.kv||r&&r()<2)return null;s=await hn(e,t,i)}}catch{s=null}return s&&typeof s!=`object`&&(s=null),dn.set(a,s?{messages:s}:{messages:null,retry:Date.now()+3e5}),s}var _n={package:`@vermeulen.solutions/eventual-locales`,version:`0.1.12`,namespace:`core`,hashes:{ar:`Jr+SsiJppqn2rr/WpJigRw`,cs:`BbmJhujNUiL8fDBw/+wCSw`,da:`Ij9IaV5B7gd+am4YKMcedw`,de:`ADmFQCy+Pv3q6PQSBk7xKQ`,es:`cr3OI43MX3EWALXbjnsy8w`,fi:`OLwpZx/szCaR5fcj8oeMaA`,fr:`FeirW6Y9C44xXOyGFL92hA`,he:`tKYZPpsv0f3z/Ms4/Tm7Lw`,it:`0NiDiE62pLdaGfmXKRcxGA`,ja:`rQsLMNECmEpjxZjz7Wrrww`,ko:`Wx1hBxDHnVUVZ/0hdbvJjA`,nb:`EirSx4KtSzX4NeN+TbK1aw`,nl:`XvvsZpZE2RpqMAPV8bENeg`,pl:`AK0ph74u6zSkAiTlsQX8bg`,"pt-BR":`D2Gp1nCw+85dT6fYcnQK4A`,pt:`c4JysqbI2mVcHXwlQn//XA`,sv:`fTU5PPBSLJJfkW20fY6Nlg`,tr:`uH3GpUPNIN9znD3hNVxTFw`,uk:`jnSPOMPPXXq2RvcLB9c6LQ`,"zh-CN":`ltuv2/7aXv+T0FZFFWIyAQ`}};async function vn(e,t){let n=L(e),r=await gn(n,_n,t,()=>ut(n));return r?un(r,t):null}async function yn(e){await gn(e,_n,e.site?.locale)}function bn(e,t){return p(e)&&p(t)&&e<=t&&Date.parse(`${t}T00:00:00Z`)-Date.parse(`${e}T00:00:00Z`)<366*864e5}function xn(e,t){return t.allDay?e:_(e,t.timezone)}function Sn(e,t,n,r=100,a=0){(!bn(t,n)||!Number.isInteger(r)||r<1||r>100||!Number.isInteger(a)||a<0)&&i(`Invalid occurrence range or limit.`);let o=j([{...e,exceptions:e.exceptions.filter(e=>e.status!==`cancelled`)}],t,n),s=o.slice(a,a+r).map(t=>{let n=e.recurrence?t.id.slice(e.id.length+1):null,r=n?A(e,n):e,i=e.exceptions.find(e=>e.recurrenceId===n);return{id:t.id,recurrenceId:n,scheduledStart:r.start,scheduledEnd:r.end,scheduledLocalStart:xn(r.start,r),scheduledLocalEnd:xn(r.end,r),scheduledTimezone:r.timezone,start:t.start,end:t.end,localStart:xn(t.start,t),localEnd:xn(t.end,t),timezone:t.timezone,allDay:t.allDay,status:i?.status??`scheduled`}});return{from:t,through:n,occurrences:s,total:o.length,truncated:a+s.length<o.length}}function Cn(e,t,n,r=10,a=0){bn(t,n)||i(`Invalid occurrence date range. Must be <= 366 days.`);let o=N(e.recurrence);if(!o||typeof o!=`object`)return{from:t,through:n,occurrences:[],total:0,offset:a,limit:r,hasMore:!1};let s=!!e.all_day,c=String(e.timezone||`Europe/Zurich`),l=s?String(e.start_date||``):String(e.start||``),u=s?String(e.end_date||l):String(e.end||l),d=N(e.exceptions),f=Array.isArray(d)?d:[],p=new Map;for(let e of f)e&&typeof e.recurrenceId==`string`&&p.set(e.recurrenceId,e);let m=N(e.occurrence_content),h=new Map((Array.isArray(m)?m:[]).map(e=>[e.recurrenceId,e.overrides])),g={id:`series`,title:String(e.title||``),description:``,start:l,end:u,allDay:s,timezone:c,location:``,organizer:``,externalUrl:``,imageUrl:``,categories:[],published:!0,recurrence:o,exceptions:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},v=Ce(g,t,n).map(e=>{let t=e.id.slice(7),n=A(g,t)??e,r=p.get(t),i=r?.status===`cancelled`,a=r?.status===`modified`,o=i?`cancelled`:a?`modified`:`scheduled`,l=a&&r?.overrides?{...e,...r.overrides}:e,u=(e,t,n)=>t?e:_(e,n);return{id:t,recurrenceId:t,scheduledStart:n.start,scheduledEnd:n.end,scheduledLocalStart:u(n.start,s,c),scheduledLocalEnd:u(n.end,s,c),effectiveStart:i?n.start:l.start,effectiveEnd:i?n.end:l.end,effectiveLocalStart:u(i?n.start:l.start,l.allDay,l.timezone||c),effectiveLocalEnd:u(i?n.end:l.end,l.allDay,l.timezone||c),timezone:l.timezone||c,allDay:l.allDay,status:o,hasLocalizedCopy:h.has(t),localizedCopy:h.get(t)}});return{from:t,through:n,occurrences:v.slice(a,a+r),total:v.length,offset:a,limit:r,hasMore:a+r<v.length}}function wn(e=[],t){let n=e.filter(e=>e.recurrenceId!==t);return n.push({recurrenceId:t,status:`cancelled`}),n}function Tn(e=[],t,n){let r=e.filter(e=>e.recurrenceId!==t);return r.push({recurrenceId:t,status:`modified`,overrides:n}),r}function En(e=[],t){return e.filter(e=>e.recurrenceId!==t)}function Dn(e=[],t,n){return[...e.filter(e=>e.recurrenceId!==t),{recurrenceId:t,overrides:{...e.find(e=>e.recurrenceId===t)?.overrides,...n}}]}function On(e=[],t){return e.filter(e=>e.recurrenceId!==t)}function kn(e,t,n,r=``,i=!1,a=80){let o=new Map;for(let t of e){let e=t.translationGroup||t.id;o.has(e)||o.set(e,[]),o.get(e).push(t)}let s=[...o.values()].map(e=>{let r=[...e].sort((e,t)=>Number(t.status===`published`)-Number(e.status===`published`)||e.id.localeCompare(t.id)),a=r.find(e=>e.id===n)??r[0],o=r.find(e=>e.status===`published`&&e.locale?.toLowerCase()===t.toLowerCase())??r.find(e=>e.status===`published`)??r.find(e=>e.locale?.toLowerCase()===t.toLowerCase())??r[0],s=i?Oe(o):void 0,c=String(o.data.name??o.data.title??o.id),l=s?.address??``;return{value:a.id,editId:o.id,label:c+(l?` — `+l:``)+` [`+(o.locale||`default`).toUpperCase()+`]`+(a.status===`published`?``:` (publish before the event)`),name:c,address:l,published:a.status===`published`}}).sort((e,t)=>e.label.localeCompare(t.label)),c=r.trim().normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase(),l=s.filter(e=>!c||e.label.normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase().includes(c)),u=l.slice(0,a),d=s.find(e=>e.value===n);return d&&!u.includes(d)&&u.push(d),{choices:u,current:d,matches:l.length}}const An=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{};[...E.slice(1),E[0]].map(e=>({value:e,label:e[0].toUpperCase()+e.slice(1)}));const jn=(e,t,n)=>({type:`date_input`,action_id:e,label:t,initial_value:a(n)||void 0}),Mn=(e,t,n,r=!1)=>({type:`text_input`,action_id:e,label:t,initial_value:a(n),multiline:r}),Nn=(e,t,n,r)=>({type:`combobox`,action_id:e,label:t,options:n,initial_value:a(r)}),Pn=(e,t,n)=>({type:`form`,block_id:e,fields:n,submit:{action_id:e,label:t}}),Fn=e=>N(e.exceptions)??[],In=e=>N(e.occurrence_content)??[],V=e=>({type:`editor-draft-patch`,operations:e}),H=(e,t)=>({op:`set`,field:e,value:t}),Ln=e=>({op:`clear`,field:e});function Rn(e,t,n){let r=a(e);try{return t?r:r&&Number.isFinite(Date.parse(r))?_(r,n):r}catch{return r}}function zn(e){let t=!!e.all_day,n=a(e.timezone)||`Europe/Zurich`;return{allDay:t,timezone:n,start:Rn(t?e.start_date:e.start,t,n),end:Rn(t?e.end_date:e.end,t,n)}}function Bn(e,t=``,n){let r=zn(e);return[{type:`toggle`,action_id:t+`all_day`,label:`All-day event`,initial_value:r.allDay},jn(t+`start_date`,`Start date`,r.start.slice(0,10)),{...Mn(t+`start_time`,`Start time`,r.start.slice(11,16)),placeholder:`18:30`,condition:{field:t+`all_day`,eq:!1}},jn(t+`end_date`,`End date (last day for all-day events)`,r.end.slice(0,10)),{...Mn(t+`end_time`,`End time`,r.end.slice(11,16)),placeholder:`20:00`,condition:{field:t+`all_day`,eq:!1}},Nn(t+`timezone`,`Time zone`,[...new Set([r.timezone,`UTC`,`Europe/Zurich`,`Europe/Paris`,`Europe/London`,`America/New_York`])].map(e=>({value:e,label:e.replaceAll(`_`,` `)})).concat({value:`custom`,label:`Other time zone…`}),r.timezone),{...Mn(t+`custom_timezone`,`Other IANA time zone`),placeholder:`Pacific/Auckland`,condition:{field:t+`timezone`,eq:`custom`}}].map(e=>n&&Object.hasOwn(n,e.action_id)?{...e,initial_value:n[e.action_id]}:e)}function Vn(e,t=``){let n=e[t+`all_day`]===!0,r=a(e[t+`timezone`]===`custom`?e[t+`custom_timezone`]:e[t+`timezone`]).trim(),o=a(e[t+`start_date`]),s=a(e[t+`end_date`])||o;if((!p(o)||!p(s))&&i(`Choose a valid start and end date.`),n)return{all_day:!0,timezone:r,start_date:o,end_date:s};let c=g(o+`T`+a(e[t+`start_time`]),r),l=g(s+`T`+a(e[t+`end_time`]),r);return(!c.value||!l.value)&&i(c.error||l.error||`Enter times as HH:MM.`),{all_day:!1,timezone:r,start:c.value,end:l.value}}async function Hn(e,t){let n=e.ui?.entry;if(!n||n.collection!==(await I(t))?.slug&&n.collection!==`events`)return{blocks:[{type:`banner`,variant:`error`,title:`Open this panel from an event editor.`}]};let r=An(e.input),o=An(An(r.draft).fields);if(!r.draft){let e=await t.content?.get(n.collection,n.id);if(o=e?.data??{},e?.draftRevisionId){let r=await t.content?.getRevision?.(n.collection,n.id,e.draftRevisionId);r&&(o=r.data)}}try{o={...o,recurrence:N(o.recurrence),exceptions:N(o.exceptions),occurrence_content:N(o.occurrence_content)}}catch{return{blocks:[{type:`banner`,variant:`error`,title:`Stored event data needs repair`,description:`The recurrence or date overrides could not be read.`}]}}let s=An(r.values),c,l,u=a(r.value)||a(s.recurrence_id),d=0,f;try{r.type!==`panel_load`&&!r.draft&&i(`Reload the editor before changing this event.`);let e=a(r.action_id);if(e===`apply-recurrence`){let e=a(s.frequency),t=Rt(e.startsWith(`monthly-`)?{...s,frequency:`monthly`,monthlyPatternType:e===`monthly-weekday`?`weekdayOfMonth`:`dayOfMonth`,interval:Number((e===`monthly-weekday`?s.interval_months_weekday:s.interval_months)??s.interval??1)}:{...s,interval:Number(s[`interval_`+(e===`daily`?`days`:`weeks`)]??s.interval??1)});t.error&&i(t.error),c=V(t.rule?[H(`recurrence`,t.rule)]:[Ln(`recurrence`)])}else if(e===`apply-schedule`){let e=Vn(s);c=V([...Object.entries(e).map(([e,t])=>H(e,t)),...e.all_day?[Ln(`start`),Ln(`end`)]:[Ln(`start_date`),Ln(`end_date`)]])}else if(e===`apply-details`){let e=await I(t);for(let n of[`venue`,`organizer_ref`].filter(e=>Object.hasOwn(s,e))){e&&!e.fields.some(t=>t.slug===at(e,n))&&i(`Upgrade event reference schema first.`);let r=a(s[n]);r&&!await t.content?.get(F(e,n),r)&&i(`Selected entry no longer exists.`)}c=V([...[`venue`,`organizer_ref`].filter(e=>Object.hasOwn(s,e)).map(t=>H(at(e,t),a(s[t])))])}else if(e!==`search-directories`)if(e===`page-occurrences`){let e=An(JSON.parse(a(r.value)||`{}`));d=Math.max(0,Math.min(500,Number(e.offset)||0)),f=a(e.from)}else if(e===`inspect-window`)f=a(s.from),u=``;else if([`cancel-occurrence`,`restore-occurrence`,`reschedule-occurrence`,`set-occurrence-copy`,`clear-occurrence-copy`,`edit-occurrence`].includes(e)){let t=Ie(o,{allowStaleOccurrenceCopy:!0}),r=A({id:n.id,start:t.all_day?t.start_date:t.start,end:t.all_day?t.end_date:t.end,allDay:t.all_day,timezone:t.timezone,recurrence:N(o.recurrence)},u);if(r||i(`Date no longer belongs to repeat schedule.`),f=Rn(r.start,r.allDay,r.timezone).slice(0,10),e===`cancel-occurrence`&&(c=V([H(`exceptions`,wn(Fn(o),u))])),e===`restore-occurrence`&&(c=V([H(`exceptions`,En(Fn(o),u))])),e===`clear-occurrence-copy`&&(c=V([H(`occurrence_content`,On(In(o),u))])),e===`reschedule-occurrence`){let e=Vn(s,`override_`);c=V([H(`exceptions`,Tn(Fn(o),u,{start:a(e.all_day?e.start_date:e.start),end:a(e.all_day?e.end_date:e.end),allDay:e.all_day,timezone:e.timezone}))])}if(e===`set-occurrence-copy`){let e={};for(let t of[`title`,`location`,`organizer`])s[`use_`+t]===!0&&(e[t]=a(s[`copy_`+t]));if(s.use_description===!0){let t=In(o).find(e=>e.recurrenceId===u)?.overrides.description;e.description=t!==void 0&&M(t)===a(s.copy_description)?t:Ee(a(s.copy_description))}let t=In(o).filter(e=>e.recurrenceId!==u);c=V([H(`occurrence_content`,Object.keys(e).length?Dn(t,u,e):t)])}}else e&&i(`Unknown action. Reload the panel.`);if(c){let t={...o};for(let e of c.operations)t[e.field]=e.op===`clear`?null:e.value;(e!==`apply-details`||[`start`,`end`,`start_date`,`end_date`].some(e=>t[e]))&&Ie(t,{allowStaleOccurrenceCopy:!0}),c.operations=c.operations.filter(e=>{let t=o[e.field];if(e.op===`clear`)return t!=null&&t!==``;let n=t;if(typeof t==`string`&&(Array.isArray(e.value)||typeof e.value==`object`))try{n=JSON.parse(t)}catch{}return JSON.stringify(n??``)!==JSON.stringify(e.value)}),o=t,c.operations.length||(c=void 0)}}catch(e){l=e instanceof Error?e.message:`Changes could not be applied.`,c=void 0}return{fields:o,effect:c,state:{selectedId:u,offset:d,windowStart:f,search:a(s.directory_search),values:l?s:void 0,locale:n.locale??``,uiLocale:e.ui?.locale||`en`,error:l,action:a(r.action_id),origin:t.site?.url||new URL(e.request.url).origin}}}const Un=(e,t,n=``,r=!1)=>({type:`text_input`,action_id:e,label:t,initial_value:String(n??``),multiline:r}),Wn=(e,t,n,r)=>({type:`select`,action_id:e,label:t,options:n,initial_value:String(r??``)}),Gn=(e,t,n)=>({type:`date_input`,action_id:e,label:t,initial_value:String(n??``)}),U=(e,t,n)=>({type:`button`,action_id:e,label:t,value:n}),Kn=(e,t,n=!1)=>({type:`accordion`,label:e,blocks:t,default_open:n});async function qn(e,t,n){let r=[];n.error&&r.push({type:`banner`,title:`Check these details`,description:n.error,variant:`error`}),r.push(Kn(`When`,[Pn(`apply-schedule`,`Save dates to draft`,Bn(e,``,n.values))],!0));let i=zt(e.recurrence),a={...i,...n.values},o=i.frequency===`monthly`?i.monthlyPatternType===`weekdayOfMonth`?`monthly-weekday`:`monthly-day`:i.frequency,s=[...E.slice(1),E[0]].map(e=>({value:e,label:e[0].toUpperCase()+e.slice(1)})),c=[Wn(`frequency`,`Repeat`,[{value:`none`,label:`Does not repeat`},{value:`daily`,label:`Daily`},{value:`weekly`,label:`Weekly`},{value:`monthly-day`,label:`Monthly — day of month`},{value:`monthly-weekday`,label:`Monthly — weekday position`}],a.frequency===`monthly`?o:a.frequency)];for(let[e,t,n]of[[`daily`,`days`,`Every … days`],[`weekly`,`weeks`,`Every … weeks`],[`monthly-day`,`months`,`Every … months`],[`monthly-weekday`,`months_weekday`,`Every … months`]])c.push({type:`number_input`,action_id:`interval_`+t,label:n,initial_value:Number(a[`interval_`+t]??a.interval??1),min:1,max:52,condition:{field:`frequency`,eq:e}});c.push({...Gn(`until`,`Last repeat date`,a.until),condition:{field:`frequency`,neq:`none`}},{type:`checkbox`,action_id:`weekdays`,label:`Days of the week`,options:s,initial_value:Array.isArray(a.weekdays)?a.weekdays:[],condition:{field:`frequency`,eq:`weekly`}},{type:`number_input`,action_id:`dayOfMonth`,label:`Day of month`,initial_value:Number(a.dayOfMonth??(String(e.start_date??e.start??``).slice(8,10)||1)),min:1,max:31,condition:{field:`frequency`,eq:`monthly-day`}},{...Wn(`missingDayBehavior`,`When this day does not exist`,[{value:`skip`,label:`Skip that month`},{value:`lastDay`,label:`Use the month’s last day`}],a.missingDayBehavior??`skip`),condition:{field:`frequency`,eq:`monthly-day`}},{...Wn(`weekday`,`Weekday`,s,a.weekday??`monday`),condition:{field:`frequency`,eq:`monthly-weekday`}},{...Wn(`position`,`Weekday position`,[1,2,3,4,5,`last`].map((e,t)=>({value:String(e),label:[`First`,`Second`,`Third`,`Fourth`,`Fifth`,`Last`][t]})),a.position??1),condition:{field:`frequency`,eq:`monthly-weekday`}}),r.push(Kn(`Repeat`,[{type:`context`,text:Bt(e.recurrence)},Pn(`apply-recurrence`,`Save repeat settings`,c)],n.action===`apply-recurrence`));let l=await I(t),u=[];for(let[r,i]of[[`venue`,`Saved venue`],[`organizer_ref`,`Saved organizer`]]){let a=at(l,r);if(!l?.fields.some(e=>e.slug===a))continue;let o=F(l,r),s=it(e[a]),c=kn((await P(t)).some(e=>e.slug===o)?await B(t,o):[],n.locale,s,void 0,r===`venue`,998).choices;u.push({type:`combobox`,action_id:r,label:i,options:[{value:``,label:r===`venue`?`No saved venue`:`No saved organizer`},...c],initial_value:s??``})}r.push(Kn(`Where`,[Pn(`apply-details`,`Save venue and organizer`,u)],n.action===`apply-details`));try{Ie(e,{allowStaleOccurrenceCopy:!0});let t=new Date().toISOString().slice(0,10),i=String(e.start_date??e.start??``).slice(0,10),a=n.windowStart??(i>t?i:t),o=k(a,89),s=Cn(e,a,o,20,n.offset),c=[Pn(`inspect-window`,`Show dates`,[Gn(`from`,`Show dates from`,a)]),{type:`context`,text:a+` — `+o}];for(let e of s.occurrences)c.push({type:`section`,block_id:`eventual-verbatim:`+e.recurrenceId,text:e.scheduledLocalStart+` → `+e.scheduledLocalEnd+` · `+e.status},{type:`actions`,elements:[U(`edit-occurrence`,`Change date`,e.recurrenceId),...e.status===`cancelled`?[U(`restore-occurrence`,`Restore date`,e.recurrenceId)]:[U(`cancel-occurrence`,`Cancel date`,e.recurrenceId)],...e.status===`modified`?[U(`restore-occurrence`,`Restore date`,e.recurrenceId)]:[]]});let l=[];n.offset&&l.push(U(`page-occurrences-prev`,`Previous dates`,JSON.stringify({from:a,offset:Math.max(0,n.offset-20)}))),s.hasMore&&l.push(U(`page-occurrences-next`,`Next dates`,JSON.stringify({from:a,offset:n.offset+20}))),l.length&&c.push({type:`actions`,elements:l}),c.push({type:`actions`,elements:[U(`window-prev`,`Previous 90 days`,k(a,-90)),U(`window-next`,`Next 90 days`,k(a,90))]});let u=s.occurrences.find(e=>e.recurrenceId===n.selectedId);if(u){let t=Wn(`recurrence_id`,`Occurrence`,[{value:u.recurrenceId,label:u.scheduledLocalStart}],u.recurrenceId),r={...e,all_day:u.allDay,timezone:u.timezone,...u.allDay?{start_date:u.effectiveStart,end_date:u.effectiveEnd}:{start:u.effectiveStart,end:u.effectiveEnd}};c.push(Pn(`reschedule-occurrence`,`Save changed date`,[t,...Bn(r,`override_`,n.values)]));let i=u.localizedCopy??{};c.push(Pn(`set-occurrence-copy`,`Save announcement for this date`,[t,...[`title`,`description`,`location`,`organizer`].flatMap(e=>[{type:`toggle`,action_id:`use_`+e,label:`Use a different `+e,initial_value:i[e]!==void 0},{...Un(`copy_`+e,e[0].toUpperCase()+e.slice(1),e===`description`?M(i[e]):i[e],e===`description`),condition:{field:`use_`+e,eq:!0}}])]),{type:`actions`,elements:[U(`clear-occurrence-copy`,`Use the series announcement`,u.recurrenceId)]})}r.push(Kn(`Individual dates`,c,!!n.selectedId))}catch(e){r.push(Kn(`Individual dates`,[{type:`context`,text:e instanceof Error?e.message:`Check the event schedule.`}]))}return{blocks:r}}const Jn=e=>JSON.stringify([e.updatedAt,e.draftRevisionId??``,e.status]),Yn=e=>({blocks:[{type:`banner`,title:e,variant:`error`}]});async function Xn(e,t){t=L(t);let n=await I(t),r=e.ui?.entry;if(!n||r?.collection!==n.slug)return{blocks:[{type:`context`,text:`Eventual RSVP manages the collection chosen in Event settings.`}]};let i=await t.content?.get(n.slug,r.id);if(!i)return Yn(`This event no longer exists.`);let a=(i.draftRevisionId?await t.content?.getRevision?.(n.slug,i.id,i.draftRevisionId):void 0)?.data??i.data,o=e.input&&typeof e.input==`object`?e.input:{},[s,c]=String(o.action_id??``).split(`|`);if(o.type!==`panel_load`&&c!==encodeURIComponent(Jn(i)))return Yn(`This event changed. Close and reopen the panel before trying again.`);s?.startsWith(`page-occurrences-`)&&(s=`page-occurrences`),s?.startsWith(`window-`)&&(s=`inspect-window`,o.values={from:o.value});let l=await Hn({...e,input:{...o,action_id:s,draft:{fields:a}}},t);if(`blocks`in l)return l;let u=l.effect?.operations;if(u?.length){let e=await t.content.get(n.slug,i.id);if(!e||Jn(e)!==Jn(i))return Yn(`This event changed. Close and reopen the panel before trying again.`);let r=new Set(n.fields.filter(e=>!e.validation?.relation).map(e=>e.slug)),a={};for(let e of u){if(!r.has(e.field)||[`title`,`description`,`excerpt`].includes(e.field))return Yn(`The event schema needs an administrator to review this field.`);a[e.field]=e.op===`clear`?null:e.value}return await t.content.update(n.slug,i.id,a),{blocks:[{type:`context`,text:`Schedule saved as an EmDash draft. Publish in the content editor when ready.`}],refresh:!0,toast:{message:`Schedule draft saved.`,type:`success`}}}let d=encodeURIComponent(Jn(i)),f=e=>{if(Array.isArray(e))return e.map(f);if(!e||typeof e!=`object`)return e;let t=e;return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,e===`action_id`&&(t.type===`button`||!t.type&&`label`in t)?String(n)+`|`+d:f(n)]))},p=await qn(l.fields,t,l.state);return p.blocks=f(p.blocks),p.blocks.unshift({type:`context`,text:`Save announcement edits first. This panel updates the saved draft. Publish in core. Dates and venue are shared across languages.`}),p}const Zn=(t,n,r={})=>e({status:t,headers:{"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,...r},body:{kind:`text`,value:n}}),Qn=()=>Zn(404,`Not found`);async function $n(t,n){if(n=L(n),typeof t!=`object`||!t||Array.isArray(t))return Qn();let r=t.eventId;if(typeof r!=`string`||r.length<1||r.length>128)return Qn();let[i,a]=r.split(`#`),o=await z(n),s=o?await n.content.get(o.slug,i):void 0;if(o&&!s&&o.fields.some(e=>e.slug===`legacy_id`&&e.indexed)){let e=await n.content.list(o.slug,{limit:2,where:{status:`published`,fieldFilters:{legacy_id:i}}});if(e.hasMore||e.items.length>1)return Qn();s=e.items[0]}let c=!o&&await $e(n),l=o?Ue(s):c?await R(n,r)??await R(n,i):void 0;if(l&&a){let e=l.exceptions?.find(e=>e.recurrenceId===a),t=e?.overrides?.featuredMediaId||e?.overrides?.imageMediaId;t&&(l={...l,featuredMediaId:t,imageMediaId:t})}let u=l?.featuredMediaId||l?.imageMediaId;if(!l?.published||!u||!n.media?.readBytes)return Qn();let d=await n.media.get(u);if(!d||!ze(d.mimeType))return Qn();if(d.size!==null&&d.size>Re)return Zn(413,`Event image is too large`);try{let t=await n.media.readBytes(u,{maxBytes:Re});return!ze(t.mimeType)||t.mimeType!==d.mimeType?Qn():e({status:200,headers:{"content-type":t.mimeType,"cache-control":`public, max-age=3600, must-revalidate`},body:{kind:`bytes`,value:t.bytes}})}catch{return Qn()}}function er(e,t,n,r=new Date,a){let o=new Set(e.map(e=>W(e,n))),s=new Map;for(let e of t){let t=W(e,n),r=s.get(t);!o.has(t)&&(!r||e.cancelledAt>r.cancelledAt)&&s.set(t,e)}let c=`${[`BEGIN:VCALENDAR`,`VERSION:2.0`,`PRODID:-//Vermeulen Solutions//Eventual RSVP//EN`,`CALSCALE:GREGORIAN`,`METHOD:PUBLISH`,`X-WR-CALNAME:${G(a||`Eventual RSVP`)}`,...e.flatMap(e=>nr(e,n,r)),...[...s.values()].flatMap(e=>rr(e,n,r)),`END:VCALENDAR`].flatMap(lr).join(`\r
13
13
  `)}\r\n`;return tr.encode(c).length>4*1024*1024&&i(`Calendar output exceeds 4 MiB; narrow the subscription.`),c}const tr=new TextEncoder;function nr(e,t,n){let r=or(e.updatedAt)??n,i=`STATUS:${Ne(e)}`,a=je(e),o=Me({...e,externalUrl:e.publicUrl||e.externalUrl}),s=M(e.description);return[`BEGIN:VEVENT`,`UID:${G(W(e,t))}`,`DTSTAMP:${sr(n)}`,`LAST-MODIFIED:${sr(r)}`,`SEQUENCE:${ar(e.calendarSequence,r)}`,i,`SUMMARY:${G(e.title)}`,...s?[`DESCRIPTION:${G(s)}`]:[],...a?[`LOCATION:${G(a)}`]:[],...o?[`URL:${o}`]:[],...e.categories.length?[`CATEGORIES:${e.categories.map(G).join(`,`)}`]:[],`X-EVENTUAL-TIMEZONE:${G(e.timezone)}`,...ir(e.start,e.end,e.allDay),`END:VEVENT`]}function rr(e,t,n){let r=or(e.cancelledAt)??n;return[`BEGIN:VEVENT`,`UID:${G(W(e,t))}`,`DTSTAMP:${sr(n)}`,`LAST-MODIFIED:${sr(r)}`,`SEQUENCE:${ar(e.calendarSequence,r)}`,`STATUS:CANCELLED`,`SUMMARY:Cancelled event`,`X-EVENTUAL-TIMEZONE:${G(e.timezone)}`,...ir(e.start,e.end,e.allDay),`END:VEVENT`]}function ir(e,t,n){if(n){let n=cr(t.slice(0,10));return[`DTSTART;VALUE=DATE:${e.slice(0,10).replaceAll(`-`,``)}`,`DTEND;VALUE=DATE:${n.replaceAll(`-`,``)}`]}let r=or(e),i=or(t);return r&&i?[`DTSTART:${sr(r)}`,...i>r?[`DTEND:${sr(i)}`]:[]]:[]}function W(e,t){let n=typeof e==`string`?e:e.id;typeof e!=`string`&&e.id.startsWith(`cancellation_`)&&e.eventId&&(n=e.eventId);let r=typeof e==`string`?void 0:e.translationGroup,a=n;if(r){let e=n.indexOf(`#`);a=`eventual-${r}${e>=0?n.slice(e):``}`}let o=t.trim().replace(/[^a-zA-Z0-9.-]/g,`-`).toLowerCase()||`eventual.invalid`;if(typeof e!=`string`&&e.calendarUid){let t=e.calendarUid.lastIndexOf(`@`);(t<1||/[\r\n\u0000-\u0020]/.test(e.calendarUid))&&i(`Invalid stored calendar UID.`);let r=n.includes(`#`)?encodeURIComponent(n.slice(n.indexOf(`#`))):``;return e.calendarUid.slice(0,t)+r+e.calendarUid.slice(t)}return`${encodeURIComponent(a)}@${o}`}function ar(e,t){let n=e??Math.floor(t.getTime()/1e3);return Math.min(2147483647,Math.max(0,Math.floor(n)))}function G(e){return e.replace(/\\/g,`\\\\`).replace(/\r\n|\r|\n/g,`\\n`).replace(/,/g,`\\,`).replace(/;/g,`\\;`).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,``)}function or(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t):void 0}function sr(e){return e.toISOString().replace(/[-:]/g,``).replace(/\.\d{3}Z$/,`Z`)}function cr(e){let t=new Date(`${e}T00:00:00Z`);return!/^\d{4}-\d{2}-\d{2}$/.test(e)||!Number.isFinite(t.getTime())?e:(t.setUTCDate(t.getUTCDate()+1),t.toISOString().slice(0,10))}function lr(e){let t=[],n=``,r=0;for(let i of e){let e=tr.encode(i).length;r+e>75&&(t.push(n),n=` `,r=1),n+=i,r+=e}return t.push(n),t}const ur=async e=>Array.from(new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))),e=>e.toString(16).padStart(2,`0`)).join(``),dr=`state:eventual-calendar-snapshot`,fr=new WeakMap;function pr(e,t=`eventual.invalid`){try{return new URL(e.site.url).host}catch{return t}}function mr(e,t=`eventual.invalid`){let n=fr.get(e);if(n)return n;let r=hr(e,t);return fr.set(e,r),r}async function hr(e,t){let n=await e.kv.get(dr);if(n?.version===1&&n.host)return n.host;let r=await e.kv.get(`state:eventual-calendar-host`);if(r)return r;let i=pr(e,t);return(await e.kv.compareAndSet(`state:eventual-calendar-host`,null,i)).applied?i:await e.kv.get(`state:eventual-calendar-host`)}async function gr(e){let t=new Date,n=t.toISOString().slice(0,10),r=new Date(t);r.setUTCDate(r.getUTCDate()+365);let a=r.toISOString().slice(0,10),o=await e.kv.getVersioned(dr);o&&o.value.version!==1&&i(`Unsupported calendar snapshot.`);let s=o?[]:await e.kv.list(`state:eventual-calendar`),c=s.find(e=>e.key===`state:eventual-calendar-lock`)?.value;c&&c.until>Date.now()&&i(`Calendar busy; retry.`);let l=o?.value.host??s.find(e=>e.key===`state:eventual-calendar-host`)?.value;l||=pr(e),fr.set(e,Promise.resolve(l));let u=new Map(o?Object.entries(o.value.groups):s.filter(e=>e.key.startsWith(`state:eventual-calendar:`)).map(e=>[decodeURIComponent(e.key.slice(24)),e.value]));u.size>1e4&&i(`Calendar state limit exceeded.`);let d=new Map(u),f=!o,p=lt(e,1);try{let r=await Nt(e);if(!r.native)return{events:r.events,cancellations:[]};r.events=await Lt(e,r.events,!1);let s=await Pt(e,r.events,r.schema),c=new Map;for(let e of r.events){let t=e.translationGroup??e.id,n=c.get(t)??[];n.push(e),c.set(t,n)}let m=new Set([...c.keys(),...u.keys()]),h=[],g=[],_=0;for(let o of m){let p=(c.get(o)??[]).sort((e,t)=>e.id.localeCompare(t.id)),m=JSON.stringify([e.site,r.schema?.urlPattern,r.schema?.routable,p.map(e=>({...e,calendarSequence:void 0,venue:De(s,e)}))]),v=await ur(m),y=u.get(o),b=y?.fingerprint===v||y?.fingerprint===m;if(b&&y.from===n){y.fingerprint!==v&&(d.set(o,{...y,fingerprint:v}),f=!0),_+=y.occurrences.length,_>1e4&&i(`Calendar occurrence limit exceeded.`),g.push(...p.map(e=>({...e,calendarSequence:y.sequence}))),h.push(...y.cancellations),h.length>1e4&&i(`Calendar cancellation limit exceeded.`);continue}let ee=!b,S=y?y.sequence+(ee?1:0):p.some(e=>e.calendarUid)?Math.floor(t.getTime()/1e3):0;S>2147483647&&i(`Calendar sequence exhausted.`);let C=j(p.slice(0,1),n,a);C.length>1e3&&i(`Calendar occurrence limit exceeded.`),_+=C.length,_>1e4&&i(`Calendar occurrence limit exceeded.`);let w=new Set(C.map(e=>W(e,l))),T=new Map(C.map(e=>[W(e,l),e.categories.map(x)])),E=[...new Set(p.flatMap(e=>e.locale?[e.locale.toLowerCase()]:[]))],D=(y?.cancellations??[]).filter(e=>Date.parse(e.cancelledAt)>t.getTime()-366*864e5&&(e.feedCategory?!T.get(W(e,l))?.includes(e.feedCategory):e.locale?!E.includes(e.locale):!w.has(W(e,l))));for(let e of y?.occurrences??[])if(!w.has(W(e,l))&&e.end.slice(0,10)>=n&&D.push({...e,cancelledAt:t.toISOString(),calendarSequence:S}),w.has(W(e,l)))for(let n of e.categories??[])T.get(W(e,l))?.includes(x(n))||D.push({...e,feedCategory:x(n),cancelledAt:t.toISOString(),calendarSequence:S});for(let e of y?.locales??[])if(!E.includes(e))for(let n of y?.occurrences??[])w.has(W(n,l))&&D.push({...n,locale:e,cancelledAt:t.toISOString(),calendarSequence:S});let te=[...new Map(D.map(e=>[W(e,l)+`:`+(e.locale??``)+`:`+(e.feedCategory??``),e])).values()];te.length>1e3&&i(`Cancellation history limit exceeded for this series.`);let ne={from:n,locales:E,fingerprint:v,sequence:S,occurrences:C.map(e=>({id:e.id,eventId:e.id,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,translationGroup:e.translationGroup,calendarUid:e.calendarUid,calendarSequence:S,cancelledAt:t.toISOString(),categories:e.categories,locales:E})),cancellations:te};d.set(o,ne),f=!0,g.push(...p.map(e=>({...e,calendarSequence:S}))),h.push(...te),h.length>1e4&&i(`Calendar cancellation limit exceeded.`)}let v={version:1,host:l,groups:Object.fromEntries(d)};return new TextEncoder().encode(JSON.stringify(v)).length>1024*1024&&i(`Calendar snapshot exceeds 1 MiB.`),p(),f&&((await e.kv.compareAndSet(dr,o?.revision??null,v)).applied||i(`Calendar state conflict; retry.`)),{events:g,cancellations:h,venues:s,host:l}}finally{p()}}async function _r(e,t,n){e=L(e,30);let r=new Date().toISOString().slice(0,10),a=new Date(r+`T00:00:00Z`);a.setUTCDate(a.getUTCDate()+365);let o=a.toISOString().slice(0,10),s=await z(e),c=s?{native:!0,schema:s,events:[]}:await Nt(e,o),l=c.native?await gr(e):{events:c.events,cancellations:[]},u=n?.eventId,d=u?.split(`#`)[0],f=j(It(d?l.events.filter(e=>e.id===d):l.events,n?.locale,n?.strict),r,o),p=u?.includes(`#`)?f.filter(e=>e.id===u):f;p.length>1e4&&i(`Too many calendar occurrences.`);let m=n?.category?x(n.category):``,h=m?p.filter(e=>e.categories.some(e=>x(e)===m)):p;if(u&&!h.length)return``;let g=`venues`in l&&l.venues||await Pt(e,h,c.schema),_=(c.native?await Lt(e,h):h).map(e=>({...e,location:We(e,g).location})),v=!u&&e.storage?.calendar_cancellations?await St(e):[];return er(_,u?[]:[...l.cancellations,...v].filter(e=>Date.parse(e.cancelledAt)>Date.now()-366*864e5&&(!m||e.categories?.some(e=>x(e)===m))&&(!e.feedCategory||e.feedCategory===m)&&(e.locale?n?.strict&&n.locale?.toLowerCase()===e.locale:!n?.strict||!n.locale||!e.locales||e.locales.includes(n.locale.toLowerCase()))),`host`in l&&l.host||await mr(e,t),void 0,n?.calendarName)}const K=(e,t)=>({type:`object`,properties:e,...t&&t.length>0?{required:t}:{},additionalProperties:!1}),q=(e=0,t=12e3)=>({type:`string`,...e>0?{minLength:e}:{},maxLength:t}),J={type:`string`},Y=(e,t)=>({type:`integer`,...e===void 0?{}:{minimum:e},...t===void 0?{}:{maximum:t}}),vr={type:`boolean`},X=e=>({type:`string`,enum:e}),yr=(e,t,n)=>({type:`array`,items:e,...t===void 0?{}:{maxItems:t},...n===void 0?{}:{minItems:n}}),br=X([`sunday`,`monday`,`tuesday`,`wednesday`,`thursday`,`friday`,`saturday`]),xr={oneOf:[K({frequency:{type:`string`,const:`daily`},until:J,interval:Y(1,52)},[`frequency`,`until`]),K({frequency:{type:`string`,const:`weekly`},until:J,interval:Y(1,52),weekdays:yr(br,7,1)},[`frequency`,`until`]),K({frequency:{type:`string`,const:`monthly`},until:J,interval:Y(1,52),pattern:{oneOf:[K({type:{type:`string`,const:`dayOfMonth`},dayOfMonth:Y(1,31),missingDayBehavior:X([`skip`,`lastDay`])},[`type`,`dayOfMonth`,`missingDayBehavior`]),K({type:{type:`string`,const:`weekdayOfMonth`},weekday:br,position:{anyOf:[{type:`number`,const:1},{type:`number`,const:2},{type:`number`,const:3},{type:`number`,const:4},{type:`number`,const:5},{type:`string`,const:`last`}]}},[`type`,`weekday`,`position`])]}},[`frequency`,`until`,`pattern`])]},Sr=X([`physical`,`virtual`,`hybrid`]),Cr=X([`draft`,`published`,`cancelled`,`postponed`,`rescheduled`]),wr=yr(q(0,100),30),Tr={title:q(1,200),description:q(0,12e3),start:q(1,32),end:q(1,32),allDay:vr,timezone:q(1,100),location:q(0,500),locationType:Sr,virtualUrl:q(0,2048),status:Cr,organizer:q(0,300),organizerId:q(0,200),externalUrl:q(0,2048),imageUrl:q(0,2048),imageMediaId:q(0,200),categories:wr,venueId:q(0,200),recurrence:xr},Er=K({id:q(1,200)},[`id`]),Dr=K(Tr,[`title`,`start`,`end`,`allDay`]),Or=K({...Tr,recurrence:{anyOf:[xr,{type:`null`}]}}),kr={name:q(1,200),street:q(0,300),street2:q(0,300),locality:q(0,150),region:q(0,150),postalCode:q(0,40),country:q(0,100)},Ar=K(kr,[`name`]),jr=K({id:q(1,200)},[`id`]),Mr=K(kr),Nr=K({id:q(1,200),patch:Or},[`id`,`patch`]),Pr=K({id:q(1,200),patch:Mr},[`id`,`patch`]),Fr=K({locationType:Sr,virtualUrl:q(0,2048),status:Cr,title:q(1,200),description:q(0,12e3),start:q(1,32),end:q(1,32),allDay:vr,timezone:q(1,100),location:q(0,500),organizer:q(0,300),externalUrl:q(0,2048),imageUrl:q(0,2048),categories:wr}),Ir=K({eventId:q(1,200),recurrenceId:q(0,16),status:X([`cancelled`,`modified`]),overrides:Fr},[`eventId`,`recurrenceId`,`status`]),Lr=K({eventId:q(1,200),recurrenceId:q(0,16)},[`eventId`,`recurrenceId`]),Rr=K({}),zr=K({from:J,through:J,includeDrafts:vr,limit:Y(1,100)}),Br=K({id:q(1,200),from:J,through:J,limit:Y(1,100)},[`id`]),Vr=K({defaultTimezone:q(1,100),collections:K({events:q(1,63),venues:q(0,63),organizers:q(0,63)},[`events`,`venues`,`organizers`]),legacyReads:vr},[`defaultTimezone`]),Hr={name:q(1,200),website:q(0,2048),contactUrl:q(0,2048)},Ur=K(Hr,[`name`]),Wr=K({id:q(1,200),expectedUpdatedAt:q(1,32),patch:K(Hr)},[`id`,`expectedUpdatedAt`,`patch`]),Gr={id:q(1,200),createdAt:q(1,32),updatedAt:q(1,32)},Kr=K({start:q(1,32),end:q(1,32),allDay:vr,timezone:q(1,100),changedAt:q(1,32)},[`start`,`end`,`allDay`,`timezone`,`changedAt`]),qr=K({recurrenceId:q(1,16),status:X([`cancelled`,`modified`]),overrides:K({...Fr.properties,imageMediaId:q(0,200)})},[`recurrenceId`,`status`]),Jr={events:K({...Tr,...Gr,calendarSequence:Y(0,2147483647),calendarUid:q(1,500),locale:q(1,40),translations:{type:`object`,maxProperties:20,additionalProperties:K({title:q(1,500),description:q(0,1e4),location:q(0,500),organizer:q(0,500)},[`title`,`description`,`location`,`organizer`])},published:vr,exceptions:yr(qr,500),scheduleHistory:yr(Kr,10),previousStartDate:q(1,32)},[`id`,`title`,`description`,`start`,`end`,`allDay`,`timezone`,`location`,`organizer`,`externalUrl`,`imageUrl`,`categories`,`published`,`exceptions`,`createdAt`,`updatedAt`]),venues:K({...kr,...Gr},Object.keys({...kr,...Gr})),organizers:K({...Hr,...Gr},Object.keys({...Hr,...Gr}))},Yr=K({collection:X([`events`,`venues`,`organizers`]),source:q(1,200),mode:X([`copy`,`restore`]),records:yr(K({sourceId:q(1,200),data:{type:`object`,additionalProperties:!0}},[`sourceId`,`data`]),10,1)},[`collection`,`source`,`records`]),Xr={listEvents:zr,getEvent:Er,listOccurrences:Br,createEvent:Dr,updateEvent:Nr,publishEvent:Er,unpublishEvent:Er,deleteEvent:Er,setOccurrenceException:Ir,removeOccurrenceException:Lr,listVenues:Rr,createVenue:Ar,updateVenue:Pr,deleteVenue:jr,getSettings:Rr,updateSettings:Vr,listOrganizers:Rr,createOrganizer:Ur,updateOrganizer:Wr,previewImport:Yr,importRecords:Yr,exportRecords:K({collection:X([`events`,`venues`,`organizers`]),cursor:q(1,2e3),limit:Y(1,10)},[`collection`]),migrateToNative:K({locale:q(1,20),venueCollection:q(1,100),dryRun:vr,cursor:q(1,4e3),limit:Y(1,100),venueMapping:{type:`object`,additionalProperties:q(1,200),maxProperties:1e3}})};function Zr(e,t){if(e.anyOf)return e.anyOf.some(e=>Zr(e,t));if(e.oneOf)return e.oneOf.filter(e=>Zr(e,t)).length===1;if(`const`in e&&t!==e.const||e.enum&&!e.enum.some(e=>e===t))return!1;switch(e.type){case`null`:return t===null;case`boolean`:return typeof t==`boolean`;case`number`:case`integer`:return typeof t==`number`&&Number.isFinite(t)&&(e.type!==`integer`||Number.isInteger(t))&&(e.minimum===void 0||t>=Number(e.minimum))&&(e.maximum===void 0||t<=Number(e.maximum));case`string`:return typeof t==`string`&&t.length>=Number(e.minLength??0)&&t.length<=Number(e.maxLength??1/0);case`array`:return Array.isArray(t)&&t.length>=Number(e.minItems??0)&&t.length<=Number(e.maxItems??1/0)&&t.every(t=>!!e.items&&Zr(e.items,t));case`object`:{if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t;if(e.maxProperties!==void 0&&Object.keys(n).length>e.maxProperties)return!1;let r=e.properties;return r?(e.required??[]).every(e=>Object.hasOwn(n,e)&&n[e]!==void 0)&&Object.keys(n).every(e=>Object.hasOwn(r,e)&&(n[e]===void 0||Zr(r[e],n[e]))):e.additionalProperties===!0||typeof e.additionalProperties==`object`&&Object.values(n).every(t=>Zr(e.additionalProperties,t))}default:return!1}}function Qr(e,t){if(!Zr(Xr[e],t))return!1;let n=t;if([`listEvents`,`listOccurrences`].includes(e)&&[n.from,n.through].some(e=>e!==void 0&&!p(e)))return!1;let r=e===`createEvent`?n:e===`updateEvent`?n.patch:void 0;return!(r?.recurrence!=null&&!D(r.recurrence))}function $r(e,t){if(!Zr(Jr[e],t))return!1;if(e===`events`){let e=t;try{let t=Object.keys(e.translations??{});return(!e.locale||Intl.getCanonicalLocales(e.locale)[0]===e.locale)&&t.every(t=>Intl.getCanonicalLocales(t)[0]===t&&t.toLowerCase()!==e.locale?.toLowerCase())}catch{return!1}}return!0}const ei={title:``,description:``,start:``,end:``,allDay:!1,timezone:`UTC`,location:``,locationType:`physical`,virtualUrl:``,status:`draft`,organizer:``,externalUrl:``,imageUrl:``,imageMediaId:``,categories:``,venueId:``,published:!1,repeatFrequency:`none`,recurrenceUntil:``,recurrenceInterval:1,monthlyPattern:`dayOfMonth`,missingDayBehavior:`skip`,monthlyWeekday:`monday`,monthlyPosition:1,exceptions:[]};async function ti(e,t){let n=await e.media?.get(t);if(!n||!ze(n.mimeType))return!1;if(n.size!==null)return n.size<=Re;if(!e.media?.readBytes)return!1;try{let r=await e.media.readBytes(t,{maxBytes:Re});return r.mimeType===n.mimeType&&ze(r.mimeType)&&r.bytes.byteLength<=Re}catch{return!1}}async function ni(e,t,n,r){let i={name:t.name.trim(),website:t.website?.trim()??``,contactUrl:t.contactUrl?.trim()??``};if(!i.name||i.name.length>200||[i.website,i.contactUrl].some(e=>e.length>2048||e&&!T(e)))return{ok:!1,error:`Use a name and valid public HTTP(S) URLs.`};let a=At(e),o=n?await a.getVersioned(n):null;if(n&&(!o||o.value.updatedAt!==r))return{ok:!1,error:`This organizer changed. Reload before saving.`};let s=vt(o?.value.updatedAt),c={...i,website:T(i.website),contactUrl:T(i.contactUrl),id:n??crypto.randomUUID(),createdAt:o?.value.createdAt??s,updatedAt:s};return(await a.compareAndSet(c.id,o?.revision??null,c)).applied?{ok:!0,organizer:c}:{ok:!1,error:`This organizer changed. Reload before saving.`}}const Z=()=>({ok:!1,error:`NOT_FOUND`});function Q(e,t,n=!1){return{permission:`plugins:manage`,handler:async(r,i)=>(n&&(i=L(i)),Qr(e,r.input)?!n&&await z(i)?{ok:!1,error:`NATIVE_COLLECTIONS_ACTIVE`,details:`Use EmDash content tools.`}:t(r.input,i):{ok:!1,error:`VALIDATION_ERROR`})}}function ri(e,t){let n=t?de(t):ei,r=e.recurrence===null?void 0:e.recurrence??t?.recurrence;return{...n,title:e.title??n.title,description:e.description??n.description,start:e.start??n.start,end:e.end??n.end,allDay:e.allDay??n.allDay,timezone:e.timezone??n.timezone,location:e.location??n.location,locationType:e.locationType??n.locationType??`physical`,virtualUrl:e.virtualUrl??n.virtualUrl??``,status:e.status??n.status??(n.published?`published`:`draft`),organizer:e.organizer??n.organizer,organizerId:e.organizerId??n.organizerId,externalUrl:e.externalUrl??n.externalUrl,imageUrl:e.imageUrl??n.imageUrl,categories:e.categories?e.categories.join(`, `):n.categories,venueId:e.venueId??n.venueId,imageMediaId:e.imageMediaId??n.imageMediaId,repeatFrequency:r?.frequency??`none`,recurrenceUntil:r?.until??``,recurrenceInterval:r?.interval??1,weeklyWeekdays:r?.frequency===`weekly`?r.weekdays:void 0,monthlyDayOfMonth:r?.frequency===`monthly`&&r.pattern.type===`dayOfMonth`?r.pattern.dayOfMonth:void 0,monthlyPattern:r?.frequency===`monthly`?r.pattern.type:`dayOfMonth`,missingDayBehavior:r?.frequency===`monthly`&&r.pattern.type===`dayOfMonth`?r.pattern.missingDayBehavior:`skip`,monthlyWeekday:r?.frequency===`monthly`&&r.pattern.type===`weekdayOfMonth`?r.pattern.weekday:`monday`,monthlyPosition:r?.frequency===`monthly`&&r.pattern.type===`weekdayOfMonth`?r.pattern.position:1}}function $(e){return{ok:!1,error:`INVALID_EVENT`,details:[e]}}async function ii(e,t,n){let i=ri(t,n),a=ue(i);if(!a.data)return $(a.error??`Check the event fields.`);if(a.data.externalUrl&&!T(a.data.externalUrl))return $(r);if(i.imageMediaId&&!await ti(e,i.imageMediaId))return $(`Choose a ready JPEG, PNG, GIF, WebP, or AVIF media image under 8 MiB.`);if(i.venueId&&!await Ct(e,i.venueId))return $(`The selected saved venue does not exist.`);if(i.organizerId&&!await At(e).get(i.organizerId))return $(`The selected saved organizer does not exist.`);let o=new Date().toISOString(),s={...n,...a.data,recurrence:a.data.recurrence,venueId:a.data.venueId,organizerId:a.data.organizerId,imageMediaId:a.data.imageMediaId,virtualUrl:a.data.virtualUrl,locale:n?.locale??e.site.locale??`en`,id:n?.id??crypto.randomUUID(),exceptions:n?.exceptions??[],createdAt:n?.createdAt??o,updatedAt:o};for(let e of[`recurrence`,`venueId`,`organizerId`,`imageMediaId`,`virtualUrl`])s[e]===void 0&&delete s[e];return we(s)?{ok:!0,event:await _t(e,s)}:$(`Changing this schedule would invalidate occurrence exceptions. Remove or update those exceptions first.`)}function ai(e,t){let n=new Date().toISOString();return{name:e.name.trim(),street:e.street?.trim()??``,street2:e.street2?.trim()??``,locality:e.locality?.trim()??``,region:e.region?.trim()??``,postalCode:e.postalCode?.trim()??``,country:e.country?.trim()??``,id:t?.id??crypto.randomUUID(),createdAt:t?.createdAt??n,updatedAt:n}}const oi={"mcp/organizers/list":Q(`listOrganizers`,async(e,t)=>{let n=await z(t);if(n){let e=F(n,`organizer_ref`);return(await P(t)).some(t=>t.slug===e)?{ok:!0,organizers:(await B(t,e)).map(e=>({id:e.id,name:String(e.data.name??e.data.title??e.id),website:String(e.data.website??``),contactUrl:String(e.data.contact_url??``),locale:e.locale,status:e.status}))}:{ok:!0,organizers:[]}}return{ok:!0,organizers:await jt(t)}},!0),"mcp/organizers/create":Q(`createOrganizer`,async(e,t)=>ni(t,e)),"mcp/organizers/update":Q(`updateOrganizer`,async(e,t)=>{let n=await At(t).get(e.id);return n?ni(t,{...n,...e.patch},e.id,e.expectedUpdatedAt):Z()}),"mcp/events/list":Q(`listEvents`,async(e,t)=>{let n=new Date().toISOString().slice(0,10),r=e.from??n,i=e.through??m(r,180);if(r>i||Date.parse(`${i}T00:00:00Z`)-Date.parse(`${r}T00:00:00Z`)>365*864e5)return{ok:!1,error:`INVALID_DATE_RANGE`};let a=await z(t);if(a){let n=(await B(t,a.slug)).map(Ue).filter(e=>e!==null);return{ok:!0,from:r,through:i,events:j(e.includeDrafts?n:n.filter(e=>e.published),r,i).slice(0,e.limit??50)}}let o;try{o=await Dt(t,{published:e.includeDrafts?void 0:!0})}catch(e){if(e instanceof pt)return{ok:!1,error:`EVENT_LIMIT_EXCEEDED`,maxEvents:e.limit};throw e}let s=j(o,r,i).slice(0,e.limit??50),c=await kt(t,s.flatMap(e=>e.venueId?[e.venueId]:[]));return{ok:!0,from:r,through:i,events:s.map(e=>({...e,venue:e.venueId?c.get(e.venueId)??null:null}))}},!0),"mcp/events/get":Q(`getEvent`,async({id:e},t)=>{let n=await z(t);if(n){let r=await t.content?.get(n.slug,e);if(!r)return Z();let i=Ue(r);if(!i)return Z();let a=await z(t),o=await Pt(t,[i],a);return{ok:!0,event:(await Lt(t,[i]))[0],venue:De(o,i)??null}}let r=await R(t,e);return r?{ok:!0,event:r,venue:r.venueId?await Ct(t,r.venueId):null}:Z()},!0),"mcp/events/occurrences":Q(`listOccurrences`,async(e,t)=>{let n=e.from??new Date().toISOString().slice(0,10),r=e.through??m(n,89);if(!bn(n,r))return{ok:!1,error:`INVALID_DATE_RANGE`};let i=await z(t);if(i){let a=await t.content?.get(i.slug,e.id);if(!a)return Z();let o=Ue(a);return o?{ok:!0,eventId:o.id,published:o.published,...Sn(o,n,r,e.limit??50)}:Z()}let a=await R(t,e.id);return a?{ok:!0,eventId:a.id,published:a.published,...Sn(a,n,r,e.limit??50)}:Z()},!0),"mcp/events/create":Q(`createEvent`,async(e,t)=>ii(t,e)),"mcp/events/update":Q(`updateEvent`,async({id:e,patch:t},n)=>{if(!Object.keys(t).length)return{ok:!1,error:`EMPTY_PATCH`};let r=await R(n,e);if(!r)return Z();let i=de(r),a=t.recurrence===void 0?r.recurrence:t.recurrence;return ii(n,{title:t.title??i.title,description:t.description??i.description,start:t.start??i.start,end:t.end??i.end,allDay:t.allDay??i.allDay,timezone:t.timezone??i.timezone,location:t.location??i.location,locationType:t.locationType??i.locationType,virtualUrl:t.virtualUrl??i.virtualUrl,status:t.status??i.status,organizer:t.organizer??i.organizer,organizerId:t.organizerId??i.organizerId,externalUrl:t.externalUrl??i.externalUrl,imageUrl:t.imageUrl??i.imageUrl,imageMediaId:t.imageMediaId??i.imageMediaId,categories:t.categories??b(i.categories),venueId:t.venueId??i.venueId,recurrence:a},r)}),"mcp/events/publish":Q(`getEvent`,async({id:e},t)=>{let n=await R(t,e);if(!n)return Z();let r={...n,published:!0,status:le(!0,n.status),updatedAt:new Date().toISOString()};return await _t(t,r),{ok:!0,event:r}}),"mcp/events/unpublish":Q(`getEvent`,async({id:e},t)=>{let n=await R(t,e);if(!n)return Z();let r={...n,published:!1,status:le(!1,n.status),updatedAt:new Date().toISOString()};return await _t(t,r),{ok:!0,event:r}}),"mcp/events/delete":Q(`getEvent`,async({id:e},t)=>({ok:!0,deleted:await bt(t,e)})),"mcp/events/exception/set":Q(`setOccurrenceException`,async(e,t)=>{let n=await R(t,e.eventId);if(!n)return Z();if(!n.recurrence)return{ok:!1,error:`NOT_RECURRING`};let i=e.recurrenceId.slice(0,10);if(!p(i)||(n.allDay?e.recurrenceId!==i:!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(e.recurrenceId)))return{ok:!1,error:`INVALID_RECURRENCE_ID`};if(!A(n,e.recurrenceId))return{ok:!1,error:`OCCURRENCE_NOT_FOUND`};let a;if(e.status===`cancelled`)a={recurrenceId:e.recurrenceId,status:`cancelled`};else{if(!e.overrides||!Object.keys(e.overrides).length)return{ok:!1,error:`OVERRIDES_REQUIRED`};let t=e.overrides,i=t.allDay??n.allDay,o=t.timezone??n.timezone,s=t.start,c=t.end;if(s===void 0!=(c===void 0))return{ok:!1,error:`START_AND_END_REQUIRED`};if(i!==n.allDay&&s===void 0)return{ok:!1,error:`REPLACEMENT_SCHEDULE_REQUIRED`};let l={...t};if(s&&c){let e=y({start:s,end:c,allDay:i,timezone:o});if(!e.dates)return $(e.errors.start??e.errors.end??e.errors.timezone??`Check the replacement schedule.`);l.start=e.dates.start,l.end=e.dates.end}if(t.virtualUrl!==void 0&&t.virtualUrl&&!T(t.virtualUrl))return $(`Virtual URL must use HTTP or HTTPS.`);if(t.virtualUrl!==void 0&&(l.virtualUrl=T(t.virtualUrl)),t.status!==void 0&&(l.status=le(n.published,t.status)),t.externalUrl!==void 0&&t.externalUrl&&!T(t.externalUrl))return $(r);if(t.imageUrl!==void 0&&t.imageUrl&&!T(t.imageUrl))return $(`Image URL must use HTTP or HTTPS.`);if(!h(o))return $(`Choose a valid IANA timezone.`);t.categories&&(l.categories=b(t.categories)),a={recurrenceId:e.recurrenceId,status:`modified`,overrides:l}}let o=[...n.exceptions.filter(t=>t.recurrenceId!==e.recurrenceId),a].sort((e,t)=>e.recurrenceId.localeCompare(t.recurrenceId));if(o.length>500)return{ok:!1,error:`TOO_MANY_EXCEPTIONS`};let s={...n,exceptions:o,updatedAt:new Date().toISOString()};return await _t(t,s),{ok:!0,event:s}}),"mcp/events/exception/remove":Q(`removeOccurrenceException`,async({eventId:e,recurrenceId:t},n)=>{let r=await R(n,e);if(!r)return Z();let i=r.exceptions.filter(e=>e.recurrenceId!==t);if(i.length===r.exceptions.length)return{ok:!1,error:`EXCEPTION_NOT_FOUND`};let a={...r,exceptions:i,updatedAt:new Date().toISOString()};return await _t(n,a),{ok:!0,event:a}}),"mcp/venues/list":Q(`getSettings`,async(e,t)=>{let n=await z(t);return n?{ok:!0,venues:(await B(t,F(n,`venue`))).map(Oe).filter(Boolean)}:{ok:!0,venues:await Ot(t)}},!0),"mcp/venues/create":Q(`createVenue`,async(e,t)=>{let n=ai(e);return await wt(t,n),{ok:!0,venue:n}}),"mcp/venues/update":Q(`updateVenue`,async({id:e,patch:t},n)=>{if(!Object.keys(t).length)return{ok:!1,error:`EMPTY_PATCH`};let r=await Ct(n,e);if(!r)return Z();let i=ai({...r,...t},r);return await wt(n,i),{ok:!0,venue:i}}),"mcp/venues/delete":Q(`getEvent`,async({id:e},t)=>await Ct(t,e)?await Et(t,e)?{ok:!1,error:`VENUE_IN_USE`}:{ok:!0,deleted:await Tt(t,e)}:Z()),"mcp/settings/get":Q(`getSettings`,async(e,t)=>({ok:!0,defaultTimezone:await t.settings.get(`defaultTimezone`)??`UTC`,collections:await Qe(t)??null,legacyReads:await $e(t)}),!0),"mcp/settings/update":Q(`updateSettings`,async({defaultTimezone:e,collections:t,legacyReads:n},r)=>{if(!h(e))return{ok:!1,error:`INVALID_TIMEZONE`};if(t)try{await rt(r,t)}catch(e){return{ok:!1,error:`INVALID_COLLECTIONS`,details:e instanceof Error?e.message:`Review the collection schemas.`}}return n!==void 0&&await et(r,n),await r.settings.set(`defaultTimezone`,e),{ok:!0,defaultTimezone:e,legacyReads:await $e(r)}},!0)},si=(e,t)=>`state:eventual-migration:`+e+`:`+encodeURIComponent(t);function ci(e,t){let n=new Set(e.fields.map(e=>e.slug)),r=Object.fromEntries(Object.entries(t).filter(([e,t])=>n.has(e)&&t!=null));for(let t of e.fields)t.required&&!(t.slug in r)&&t.default===void 0&&i(`Missing required target field `+t.slug);return r}async function li(e,t={}){let n=t.locale??`fr`,r=t.dryRun===!0,o={ok:!1,dryRun:r,locale:n,venueCollection:t.venueCollection??`venues`,venues:[],events:[],summary:{totalVenues:0,migratedVenues:0,totalEvents:0,migratedEvents:0,errors:0}},s=null,c=`state:eventual-migration-lock`;try{Intl.getCanonicalLocales(n)[0]!==n&&i(`Use a canonical BCP 47 locale.`),r&&(o.warnings=[`Execution assigns native IDs and checks site locales and other plugins' content policies.`]),(!e.schema||!e.content?.create||!e.content.publish||!e.content.getVersioned)&&i(`Native schema, write and publish APIs are required.`);let l=await P(e),u=await I(e);u||i(`Apply the event blueprint before migrating.`);let d=F(u,`venue`),f=at(u,`venue`);u.fields.some(e=>e.slug===f)||i(`Upgrade the bound venue reference schema before migration.`),o.venueCollection=t.venueCollection??(typeof d==`string`?d:l.some(e=>e.slug===`locations`)?`locations`:`venues`),d!==o.venueCollection&&i(`venueCollection must match the events.venue reference target.`);let p=l.find(e=>e.slug===o.venueCollection);p||i(`Target venue collection is missing.`);for(let e of[u,p]){let t=e.fields.find(e=>e.slug===`legacy_id`);(!t?.unique||!t.indexed)&&i(e.slug+` requires unique indexed legacy_id field.`),e.fields.some(e=>e.slug===`legacy_metadata`&&e.type===`json`)||i(e.slug+` requires legacy_metadata JSON.`)}for(let e of[`start_date`,`end_date`,`all_day`,`timezone`,`description`,`event_status`,`calendar_uid`,`exceptions`,`occurrence_content`,`legacy_metadata`,`image_url`,`organizer_details`,`categories`,`location`])u.fields.some(t=>t.slug===e)||i(`Update the events blueprint: missing `+e);if(!r){let t=await e.kv.getVersioned(c);t&&t.value.until>Date.now()&&i(`Migration is already running.`),(await e.kv.compareAndSet(c,t?.revision??null,{until:Date.now()+3e5})).applied||i(`Migration lock conflict; retry.`),s=await e.kv.getVersioned(c)}let m=await B(e,o.venueCollection),h=await B(e,u.slug),g=new Map([[o.venueCollection,new Map(m.filter(e=>typeof e.data.legacy_id==`string`).map(e=>[e.data.legacy_id,e]))],[u.slug,new Map(h.filter(e=>typeof e.data.legacy_id==`string`).map(e=>[e.data.legacy_id,e]))]]),_=new Map;for(let[n,a]of Object.entries(t.venueMapping??{}))(typeof a!=`string`||!a)&&i(`venueMapping values must be non-empty native IDs.`),await e.content.get(o.venueCollection,a)||i(`Mapped venue does not exist: `+a),_.set(n,a),r||await e.kv.set(si(o.venueCollection,n),{id:a,published:!0,status:`complete`});for(let t of m)if(typeof t.data.legacy_id==`string`&&!_.has(t.data.legacy_id)){let n=await e.kv.get(si(o.venueCollection,t.data.legacy_id));(!n||n.status===`complete`||t.status===`published`)&&_.set(t.data.legacy_id,t.id)}let v=(e,t)=>ci(p,{name:a(e.name).trim(),title:a(e.name).trim(),street:a(e.street),street2:a(e.street2),address:a(e.street),streetAddress:a(e.street),locality:a(e.locality),city:a(e.locality),region:a(e.region),state:a(e.region),postal_code:a(e.postalCode),postalCode:a(e.postalCode),zip:a(e.postalCode),country:a(e.country),legacy_id:t,legacy_metadata:JSON.stringify(e)}),y=`venues`,b;if(t.cursor){let e=JSON.parse(t.cursor);(![`venues`,`events`].includes(e.phase)||e.locale!==n||e.collection!==o.venueCollection||e.cursor!==void 0&&typeof e.cursor!=`string`)&&i(`Invalid migration cursor.`),y=e.phase,b=e.cursor}let x=t.limit??25;(!Number.isInteger(x)||x<1||x>100)&&i(`limit must be between 1 and 100.`);let ee=r?pr(e):await mr(e),S=await e.kv.get(`state:eventual-calendar-host`),C=async()=>{r||!s||((await e.kv.compareAndSet(c,s.revision,{until:Date.now()+3e5})).applied||i(`Migration lease expired or changed; retry the batch.`),s=await e.kv.getVersioned(c))},w=async(t,a,o,s,c)=>{await C();let l=si(t,o),d=await e.kv.get(l),f=g.get(t)?.get(o);if(d?.id){let n=await e.content.get(t,d.id);n||i(`Native item removed; restore it explicitly.`),f=n}if(f){t===u.slug&&f.locale&&f.locale!==n&&i(`Migration identity belongs to locale `+f.locale+`; use its original locale.`);let a=typeof f.data.legacy_metadata==`string`?JSON.parse(f.data.legacy_metadata):f.data.legacy_metadata,o=d&&d.status!==`complete`&&d.token&&a?.migrationToken===d.token,s=o&&c&&f.status!==`published`?`resume_publication`:`none`;if(!r&&o&&c&&f.status!==`published`){let n=await e.content.getVersioned(t,f.id);n||i(`Created item disappeared.`),await e.content.publish(t,f.id,{_rev:n._rev})}return!r&&(!d||o)&&await e.kv.set(l,{id:f.id,published:c,status:`complete`,token:d?.token}),{id:f.id,existed:!0,action:s}}if(r)return{id:``,existed:!1,action:`create`};let p=crypto.randomUUID(),m=typeof s.legacy_metadata==`string`?JSON.parse(s.legacy_metadata):s.legacy_metadata??{};await e.kv.set(l,{id:``,published:c,status:`creating`,token:p});let h=await e.content.create(t,ci(a,{...s,legacy_metadata:JSON.stringify({...m,migrationToken:p})}),{locale:n});if(g.get(t).set(o,h),await C(),await e.kv.set(l,{id:h.id,published:c,status:`created`,token:p}),c&&h.status!==`published`){let n=await e.content.getVersioned(t,h.id);n||i(`Created item disappeared.`),await e.content.publish(t,h.id,{_rev:n._rev})}return await C(),await e.kv.set(l,{id:h.id,published:c,status:`complete`,token:p}),{id:h.id,existed:!1,action:`create`}};for(;x>0;){let t=await e.storage[y].query({limit:x,cursor:b});t.hasMore&&(!t.cursor||t.cursor===b)&&i(`Incomplete legacy storage cursor.`);for(let n of t.items){x--;let t=n.id,s=n.data,c=a(y===`venues`?s.name:s.title).trim(),l=y===`venues`?o.venues:o.events;try{if(y===`venues`&&_.has(t)){l.push({legacyId:t,nativeId:_.get(t),titleOrName:c||t,status:`already_exists`});continue}c||i(`Missing title or venue name.`);let n,d=!1,m,h;if(y===`venues`)m=p,h=o.venueCollection,n=v(s,t),d=!0;else{h=u.slug,m=u;let l=s;Object.keys(l.translations??{}).length&&i(`Manual translations need explicit native locale rows. Migration skipped; source retained.`);let p=l.venueId?_.get(l.venueId)??(await e.kv.get(si(o.venueCollection,l.venueId)))?.id:void 0;if(r&&l.venueId&&!p){let t=await e.storage.venues.get(l.venueId);a(t?.name).trim()&&v(t,l.venueId)&&(p=`planned:`+l.venueId)}l.venueId&&!p&&i(`Unmapped venue `+l.venueId);let g=p&&!p.startsWith(`planned:`)?await e.content.get(o.venueCollection,p):void 0;p&&!p.startsWith(`planned:`)&&!g&&i(`Mapped venue was removed.`),l.published&&p&&!p.startsWith(`planned:`)&&g?.status!==`published`&&i(`Publish the mapped venue before migrating a published event.`),l.imageMediaId&&!await e.media?.get(l.imageMediaId)&&i(`Legacy media item is unavailable.`);let y=new Set([`title`,`description`,`location`,`organizer`]),b=(l.exceptions??[]).map(e=>({...e,overrides:e.overrides?Object.fromEntries(Object.entries(e.overrides).filter(([e])=>!y.has(e)&&e!==`locale`)):void 0})),x=(l.exceptions??[]).flatMap(e=>{let t=Object.fromEntries(Object.entries(e.overrides??{}).filter(([e])=>y.has(e)));return Object.keys(t).length?[{recurrenceId:e.recurrenceId,overrides:t}]:[]}),C=b.filter(e=>e.status===`cancelled`||Object.keys(e.overrides??{}).length),w=l.organizerId?await e.storage.organizers?.get(l.organizerId):void 0,T=Ie({start:l.start,end:l.end,all_day:l.allDay,timezone:l.timezone,recurrence:l.recurrence,exceptions:C,occurrence_content:x});n=ci(m,{title:c,description:Ee(a(l.description)),excerpt:M(l.description).slice(0,160),...T,location_type:l.locationType??`physical`,location:a(l.location),[f]:p,virtual_url:l.virtualUrl||void 0,external_url:l.externalUrl||void 0,organizer:a(l.organizer),organizer_details:w?JSON.stringify(w):void 0,categories:JSON.stringify(l.categories??[]),featured_image:l.imageMediaId?{id:l.imageMediaId,...l.imageUrl?{src:l.imageUrl}:{}}:void 0,image_url:l.imageMediaId?void 0:l.imageUrl||void 0,event_status:[`cancelled`,`postponed`,`rescheduled`].includes(l.status??``)?l.status:`published`,recurrence:l.recurrence?JSON.stringify(l.recurrence):void 0,exceptions:JSON.stringify(C),occurrence_content:JSON.stringify(x),previous_start_date:l.previousStartDate,schedule_history:l.scheduleHistory?JSON.stringify(l.scheduleHistory):void 0,legacy_id:t,calendar_uid:W(t,S??ee),legacy_metadata:JSON.stringify({createdAt:l.createdAt,updatedAt:l.updatedAt,organizerId:l.organizerId,locale:l.locale,description:l.description,exceptions:l.exceptions})}),Ue({id:t,status:`published`,type:`events`,data:n})||i(`Invalid migrated event payload.`),d=l.published===!0}let g=await w(h,m,t,n,d);y===`venues`&&_.set(t,g.id||`planned:`+t),l.push({legacyId:t,nativeId:g.id,action:g.action,titleOrName:c,status:g.existed?`already_exists`:r?`planned`:`migrated`,...r?{payload:n}:{}})}catch(e){l.push({legacyId:t,nativeId:``,titleOrName:c,status:`error`,error:e instanceof Error?e.message:String(e)})}}if(t.hasMore){o.nextCursor=JSON.stringify({phase:y,cursor:t.cursor,locale:n,collection:o.venueCollection});break}if(y===`events`)break;y=`events`,b=void 0,x||(o.nextCursor=JSON.stringify({phase:y,locale:n,collection:o.venueCollection}))}r||await gr(e),o.ok=!o.venues.concat(o.events).some(e=>e.status===`error`)}catch(e){o.error=e instanceof Error?e.message:String(e)}finally{s&&await e.kv.compareAndDelete(c,s.revision)}return o.summary={totalVenues:o.venues.length,migratedVenues:o.venues.filter(e=>e.status===`migrated`).length,totalEvents:o.events.length,migratedEvents:o.events.filter(e=>e.status===`migrated`).length,errors:o.venues.concat(o.events).filter(e=>e.status===`error`).length+(o.error?1:0)},o}async function ui(e,t,n){return`import-${await ur(JSON.stringify([e,t,n]))}`}function di(e){return!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(e)||!Number.isFinite(Date.parse(e))?!1:new Date(e).toISOString().replace(`.000Z`,`Z`)===e.replace(`.000Z`,`Z`)}function fi(e){return h(e.timezone)?e.allDay?p(e.start)&&p(e.end)&&e.end>=e.start:di(e.start)&&di(e.end)&&Date.parse(e.end)>=Date.parse(e.start):!1}async function pi(e,t,n,r,a,o){[n.createdAt,n.updatedAt].every(di)||i(`Invalid record timestamp.`);let s=new Date().toISOString();if(t.collection!==`events`){let e=n;return e.name.trim()||i(`Name is required.`),t.collection===`organizers`&&[n.website,n.contactUrl].some(e=>e&&!T(e))&&i(`Public URLs must use HTTP(S).`),{...n,name:e.name.trim(),id:r,updatedAt:s}}let c=n;(!fi(c)||c.recurrence&&!D(c.recurrence))&&i(`Invalid schedule or recurrence.`);let l=ue(de({...c,published:!1,status:`draft`}),{start:c.start,end:c.end});l.data||i(l.error);let u={...c,...l.data,id:r,createdAt:c.createdAt,updatedAt:s};if(t.mode!==`restore`)for(let e of[`calendarUid`,`translationGroup`,`calendarSequence`,`scheduleHistory`,`previousStartDate`,`publicUrl`])delete u[e];for(let n of[`venueId`,`organizerId`]){let r=c[n];if(!r)continue;let s=n===`venueId`?`venues`:`organizers`,l=t.mode===`restore`?r:await ui(t.source,s,r);if(!e.has(s+`:`+l)){let e=`Missing ${s} reference: ${r}. Import referenced records first.`;a&&i(e),o.push(e)}u[n]=l}c.imageMediaId&&i(`Media is not restored by this tool.`);for(let e of u.exceptions){let t=A(u,e.recurrenceId);if(t||i(`Invalid exception recurrenceId.`),e.status===`modified`){let n=e.overrides;(!n||!Object.keys(n).length)&&i(`Modified exceptions require overrides.`),n.imageMediaId&&i(`Exception media IDs require a host media restore.`),[`virtualUrl`,`externalUrl`,`imageUrl`].some(e=>{let t=n[e];return t&&!T(t)})&&i(`Exception URLs must use HTTP(S).`),(n.start===void 0!=(n.end===void 0)||n.allDay!==void 0&&n.allDay!==t.allDay&&n.start===void 0)&&i(`Replacement schedule requires start and end.`),fi({...t,...n})||i(`Invalid exception schedule.`),n.status=`draft`}}return(new Set(u.exceptions.map(e=>e.recurrenceId)).size!==u.exceptions.length||!we(u))&&i(`Duplicate or invalid exception IDs.`),c.scheduleHistory?.some(e=>!fi(e)||!di(e.changedAt))&&i(`Invalid schedule history.`),c.previousStartDate&&!p(c.previousStartDate)&&!di(c.previousStartDate)&&i(`Invalid previous start.`),c.scheduleHistory&&(u.scheduleHistory=c.scheduleHistory),c.previousStartDate&&(u.previousStartDate=c.previousStartDate),u}async function mi(e,t,n){if(e=L(e),await z(e))return{ok:!1,preview:!n,error:`NATIVE_COLLECTIONS_ACTIVE`,details:`Legacy imports are disabled when native collections are active.`,rows:[]};if(!Qr(n?`importRecords`:`previewImport`,t)||new TextEncoder().encode(JSON.stringify(t)).length>65536)return{ok:!1,error:`VALIDATION_ERROR`,maxBytes:65536};let r=[],a=new Set,o=await Promise.all(t.records.map(e=>t.mode===`restore`?e.sourceId:ui(t.source,t.collection,e.sourceId))),s=e.storage[t.collection],c=await s.getMany([...new Set(o)]),l=new Set;if(t.collection===`events`)for(let[n,r]of[[`venueId`,`venues`],[`organizerId`,`organizers`]]){let i=[...new Set(t.records.flatMap(e=>$r(`events`,e.data)&&e.data[n]?[e.data[n]]:[]))],a=await Promise.all(i.map(e=>t.mode===`restore`?e:ui(t.source,r,e)));if(a.length)for(let t of(await e.storage[r].getMany(a)).keys())l.add(r+`:`+t)}for(let[u,d]of t.records.entries()){let f=o[u];try{$r(t.collection,d.data)||i(`Record does not match its collection schema.`),d.sourceId!==d.data.id&&i(`sourceId must match the record ID.`),a.has(f)&&i(`Duplicate source ID in this batch.`),a.add(f);let o=[],p=await pi(l,t,structuredClone(d.data),f,n,o),m=c.has(f)?`skipped`:n?ut(e)===0?`pending`:(await s.compareAndSet(f,null,p)).applied?`imported`:`skipped`:`ready`;r.push({row:u+1,sourceId:d.sourceId,id:f,status:m,...o.length?{warnings:o}:{}})}catch(e){r.push({row:u+1,sourceId:d.sourceId,id:f,status:`error`,error:e instanceof Error?e.message:`Import failed.`})}}return{ok:r.every(e=>e.status!==`error`&&e.status!==`pending`),preview:!n,...r.some(e=>e.status===`pending`)?{error:`SANDBOX_BUDGET_EXCEEDED`,details:`Retry pending rows; existing IDs are skipped.`}:{},rows:r}}const hi={"mcp/transfer/preview":{permission:`plugins:manage`,handler:(e,t)=>mi(t,e.input,!1)},"mcp/transfer/import":{permission:`plugins:manage`,handler:(e,t)=>mi(t,e.input,!0)},"mcp/transfer/export":{permission:`plugins:manage`,handler:async(e,t)=>{if(!Qr(`exportRecords`,e.input))return{ok:!1,error:`VALIDATION_ERROR`};let n=e.input,r=await z(t);if(r){let e=n.collection===`venues`?F(r,`venue`):n.collection===`organizers`?F(r,`organizer_ref`):r.slug,i=await t.content.list(e,{limit:n.limit??5,cursor:n.cursor});if(i.hasMore&&(!i.cursor||i.cursor===n.cursor))return{ok:!1,error:`INCOMPLETE_PAGE`};let a=i.items.map(e=>({sourceId:e.id,data:e.data,metadata:{slug:e.slug,locale:e.locale,status:e.status,translationGroup:e.translationGroup,createdAt:e.createdAt,updatedAt:e.updatedAt,publishedAt:e.publishedAt,scheduledAt:e.scheduledAt,draftRevisionId:e.draftRevisionId,liveRevisionId:e.liveRevisionId}}));return new TextEncoder().encode(JSON.stringify(a)).length>65536?{ok:!1,error:`EXPORT_PAGE_TOO_LARGE`,details:`Retry with limit 1.`}:{ok:!0,format:`native-content-v1`,collection:e,records:a,...i.hasMore?{nextCursor:i.cursor}:{}}}let i=await t.storage[n.collection].query({limit:n.limit??5,cursor:n.cursor});if(i.hasMore&&!i.cursor)return{ok:!1,error:`INCOMPLETE_PAGE`};let a=i.items.map(e=>({sourceId:e.id,data:e.data}));return new TextEncoder().encode(JSON.stringify(a)).length>65536?{ok:!1,error:`EXPORT_PAGE_TOO_LARGE`,details:`Retry with limit 1.`}:{ok:!0,collection:n.collection,records:a,...i.hasMore?{nextCursor:i.cursor}:{}}}},"mcp/transfer/migrateToNative":{permission:`plugins:manage`,handler:async(e,t)=>{let n=e.input??{};return Qr(`migrateToNative`,n)?li(t,n):{ok:!1,error:`VALIDATION_ERROR`}}}};async function gi(e,t){if(t=L(t),e.collection===await Ze(t)){if(!Fe.some(t=>Object.hasOwn(e.content,t))||e.isNew&&![`start`,`end`,`start_date`,`end_date`].some(t=>e.content[t]!=null&&e.content[t]!==``))return e.content;try{let n={},r;if(e.id&&(r=await t.content?.get(e.collection,e.id),r&&(n=r.data),r?.draftRevisionId&&t.content?.getRevision)){let i=await t.content.getRevision(e.collection,e.id,r.draftRevisionId);i&&(n=i.data)}for(let t of[`calendar_uid`,`legacy_id`])e.id&&Object.hasOwn(e.content,t)&&e.content[t]!==n[t]&&i(t+` cannot be changed after creation.`);if(r?.status===`draft`&&![`start`,`end`,`start_date`,`end_date`].some(t=>({...n,...e.content})[t]))return e.content;let a=Ie({...n,...e.content},{allowStaleOccurrenceCopy:!Object.hasOwn(e.content,`occurrence_content`)||JSON.stringify(N(e.content.occurrence_content)??[])===JSON.stringify(N(n.occurrence_content)??[])}),o={...e.content};for(let e of[`start`,`end`,`start_date`,`end_date`,`all_day`,`timezone`])e in a&&(o[e]=a[e]);if(e.id&&Object.hasOwn(e.content,`all_day`))for(let e of a.all_day?[`start`,`end`]:[`start_date`,`end_date`])o[e]=null;if(r?.status===`published`){let n=e=>({start:String(e[e.all_day?`start_date`:`start`]||``),end:String(e[e.all_day?`end_date`:`end`]||``),allDay:!!e.all_day,timezone:String(e.timezone||`UTC`)}),i=n(r.data),s=n(a),c=e=>e&&Object.entries(i).every(([t,n])=>e[t]===n);if(i.start&&i.end&&!c(s)){let n=(await P(t)).find(t=>t.slug===e.collection),a=e=>n?.fields.some(t=>t.slug===e),s=N(r.data.schedule_history??o.schedule_history),l=Array.isArray(s)?s:[];a(`schedule_history`)&&!c(l[0])&&(o.schedule_history=JSON.stringify([{...i,changedAt:new Date().toISOString()},...l].slice(0,10))),a(`previous_start_date`)&&(o.previous_start_date=i.start),r.data.event_status!==`cancelled`&&(!Object.hasOwn(e.content,`event_status`)||e.content.event_status===r.data.event_status)&&(o.event_status=`rescheduled`)}}return o}catch(e){return{__emdashSandboxHookResult:!0,version:1,error:{code:`SAVE_REJECTED`,reason:e instanceof Error?e.message:String(e)}}}}}async function _i(e,t){if(t&&=L(t),e.collection===(t?await Ze(t):`events`))try{let n=e.content.data&&typeof e.content.data==`object`?e.content.data:e.content;if(Ie(n,{allowStaleOccurrenceCopy:!0}),t&&(n.venue_id??n.venue)){let e=F(await I(t),`venue`),r=it(n.venue_id??n.venue);(typeof e!=`string`||typeof r!=`string`||(await t.content?.get(e,r))?.status!==`published`)&&i(`Publish a valid referenced venue before publishing or scheduling this event.`)}if(t&&(n.organizer_id??n.organizer_ref??n.organizerId)){let e=it(n.organizer_id??n.organizer_ref??n.organizerId);if(e){let n=F(await I(t),`organizer_ref`),r=await t.content?.get(n,e);(!r||r.status!==`published`)&&i(`Publish the referenced organizer before publishing or scheduling this event.`)}else i(`Choose a valid saved organizer.`)}}catch(e){return{cancel:!0,reason:e instanceof Error?e.message:String(e)}}}async function vi(e,t,n){let r=await Qe(n);if(r&&![r.venues,r.organizers].includes(e))return;let a=await I(n);if(!a)return;let o=F(a,`venue`),s=F(a,`organizer_ref`);if(e!==o&&e!==s)return;(typeof t!=`string`||!t)&&i(`Cannot verify this dependency. Reload the entry.`);let c=await n.content?.get(e,t),l=new Set([t]);if(c&&n.content?.getTranslations){let r=await n.content.getTranslations(e,t);for(let e of r.translations)l.add(e.id)}for(let t of await B(n,a.slug)){if(t.status!==`published`&&t.status!==`scheduled`)continue;let r=[t.data];if((t.status===`scheduled`||t.scheduledAt)&&t.draftRevisionId&&n.content?.getRevision){let e=await n.content.getRevision(a.slug,t.id,t.draftRevisionId);e||i(`Scheduled event revision could not be verified. Retry before changing this dependency.`),r.push(e.data)}if((t.status===`scheduled`||t.scheduledAt)&&t.draftRevisionId&&!n.content?.getRevision&&i(`Scheduled event revision access is required to verify this dependency.`),r.some(t=>e===o&&l.has(it(t.venue_id??t.venue)??``)||e===s&&l.has(it(t.organizer_id??t.organizer_ref)??``)))return`This `+(e===o?`venue`:`organizer`)+` is used by published or scheduled event "`+String(t.data.title??t.id)+`". Reassign or unpublish the event first.`}}async function yi(e,t){if(t){t=L(t);try{let n=e.content.data&&typeof e.content.data==`object`?e.content.data:{},r=await vi(e.collection,e.content.id??n.id,t);if(r)return{cancel:!0,reason:r}}catch(e){return{cancel:!0,reason:e instanceof Error?e.message:`Dependencies could not be verified. Retry before unpublishing.`}}}}async function bi(e,t){if(t=L(t),e.collection===await Ze(t)){await gr(t);return}if(await vi(e.collection,e.id,t))return!1}const xi=(e,t)=>{let n=new URL(t).origin;try{return e&&new URL(e).host===new URL(n).host?e:n}catch{return n}},Si=e=>Zn(503,e.message,{"retry-after":`60`});async function Ci(e,t,n){let r=L(e),i=await n(r),a=await vn(r,t);return a?$t(i,a):i}const wi={hooks:{"plugin:activate":async(e,t)=>{await yn(t)},"content:beforeSave":gi,"content:beforeDelete":bi,"content:beforePublish":_i,"content:beforeSchedule":_i,"content:beforeUnpublish":yi},routes:{...oi,...hi,admin:{permission:`content:edit_any`,handler:async(e,t)=>Ci(t,e.ui?.locale,t=>Xt(e.input,{...t,site:{...t.site,url:xi(t.site.url,e.request.url)}},e.user))},"admin/editor/schedule":{permission:`content:edit_any`,handler:async(e,t)=>Ci(t,e.ui?.locale,t=>Xn(e,t))},publicEvents:t({public:!0,methods:[`GET`],request:{body:`none`},cacheControl:`public, max-age=60`,handler:async(e,t)=>{let n=await Wt(e.input,t);if(n.error===`SANDBOX_BUDGET_EXCEEDED`)throw new ot;return n}}),publicEventImage:t({public:!0,methods:[`GET`],request:{body:`none`},response:`raw`,cacheControl:`no-store`,handler:async(e,t)=>{try{return await $n(e.input,t)}catch(e){if(e instanceof ot)return Si(e);throw e}}}),calendar:t({public:!0,methods:[`GET`],request:{body:`none`},response:`raw`,cacheControl:`public, max-age=300`,handler:async(t,n)=>{try{let r=new URL(t.request.url,`http://localhost`),i=r.searchParams.get(`locale`)||void 0;try{i&&Intl.getCanonicalLocales(i)}catch{return Zn(400,`Invalid locale.`)}let a=r.searchParams.get(`strict`)===`true`,o=r.searchParams.get(`category`)||void 0,s=r.searchParams.get(`eventId`)?.trim()||void 0,c=await _r(n,r.host||`localhost`,{locale:i,strict:a,category:o,eventId:s});return c?e({status:200,headers:{"content-type":`text/calendar; charset=utf-8`},body:{kind:`text`,value:c}}):Zn(404,`This event has ended or is no longer published.`)}catch(e){return Si(e instanceof pt||e instanceof ot?e:Error(`Calendar feed unavailable; retry later.`))}}})}};export{wi as default};
@@ -8,7 +8,7 @@ Eventual RSVP – Core requires EmDash **>=1.2.0 <2.0.0**; it is tested on **1.2
8
8
  2. Open **Event settings**, select the event and venue/organizer collections, and choose **Save settings**. Selection connects collections; it does not create them or move entries.
9
9
  3. Create a draft, save it, set its schedule in **Dates, venue & repeat**, and publish it. Check it on your site's calendar.
10
10
 
11
- A **content type/collection** is simply the place under **Content** where entries are listed and edited. If compatible collections are missing, ask your site builder to create them with the blueprint below. Your builder adds visitor pages using Eventual's feeds; the [Astro showcase](../examples/astro-events/README.md) is an optional website design.
11
+ A **content type/collection** is simply the place under **Content** where entries are listed and edited. If compatible collections are missing, ask your site builder to create them with the blueprint below. Your builder adds the visitor pages with the package's [event page components](./developer-guide.md#event-pages).
12
12
 
13
13
  ## Agent tools (optional)
14
14
 
@@ -128,7 +128,81 @@ if (!result.success) throw new Error(result.error?.message ?? 'Event feed unavai
128
128
 
129
129
  Each feed event carries `calendarLinks` (Google, Outlook, Office 365 and `.ics`), already built with the installed ID. The `.ics` link downloads that event only (`calendar?eventId=…`); before 0.18.5 it returned the whole calendar. `buildCalendarLinks(event, siteUrl, pluginId)` builds the same links on your side and takes the ID as its third argument.
130
130
 
131
- `@vermeulen.solutions/eventual/astro/EventList.astro` is an optional plain list (title, status, date, venue and, with `showCalendarLinks`, calendar buttons). Since 0.18.7 it has light default styles in the `eventual` cascade layer, so your own CSS always wins: neutral colours follow the surrounding text colour, and the link and status colours follow the page's `color-scheme` (set `color-scheme: dark` where it sits on a dark surface). Adjust them with `--eventual-list-accent`, `--eventual-list-muted`, `--eventual-list-border`, `--eventual-list-radius`, `--eventual-list-cancelled` and `--eventual-list-rescheduled`. JSON-LD helpers are eventToJsonLd and serializeJsonLd; use the safe serializer. The [showcase](../examples/astro-events/README.md) supplies seven complete visitor layouts.
131
+ `@vermeulen.solutions/eventual/astro/EventList.astro` is an optional plain list (title, status, date, venue and, with `showCalendarLinks`, calendar buttons). Since 0.18.7 it has light default styles in the `eventual` cascade layer, so your own CSS always wins: neutral colours follow the surrounding text colour, and the link and status colours follow the page's `color-scheme` (set `color-scheme: dark` where it sits on a dark surface). Adjust them with `--eventual-list-accent`, `--eventual-list-muted`, `--eventual-list-border`, `--eventual-list-radius`, `--eventual-list-cancelled` and `--eventual-list-rescheduled`. JSON-LD helpers are eventToJsonLd and serializeJsonLd; use the safe serializer. For full events pages, use the components below.
132
+
133
+ ## Event pages
134
+
135
+ Since 0.19.0 the package has two complete page bodies: `EventBrowser` (the events page, with seven views) and `EventDetail` (one event). A loader fetches the feed and returns everything a page needs, including the HTTP status; you render the component inside your own layout. They are site code: nothing here counts towards the plugin's sandbox size.
136
+
137
+ `src/pages/events.astro`:
138
+
139
+ ```astro
140
+ ---
141
+ import EventBrowser from "@vermeulen.solutions/eventual/astro/EventBrowser.astro";
142
+ import { loadEventBrowser } from "@vermeulen.solutions/eventual/astro/events";
143
+ import Layout from "../layouts/Layout.astro";
144
+
145
+ export const prerender = false;
146
+ const data = await loadEventBrowser(Astro.url, { pluginId: "eventual", locale: "fr-CH", timeZone: "Europe/Zurich" });
147
+ Astro.response.status = data.status;
148
+ ---
149
+ <Layout title={data.pageTitle}><EventBrowser data={data} /></Layout>
150
+ ```
151
+
152
+ `src/pages/events/[id].astro`:
153
+
154
+ ```astro
155
+ ---
156
+ import EventDetail from "@vermeulen.solutions/eventual/astro/EventDetail.astro";
157
+ import { eventContentId, loadEventDetail, occurrenceStart } from "@vermeulen.solutions/eventual/astro/events";
158
+ import RsvpForm from "@vermeulen.solutions/eventual-attendance/astro/RsvpForm.astro";
159
+ import Layout from "../../layouts/Layout.astro";
160
+
161
+ export const prerender = false;
162
+ const data = await loadEventDetail(Astro.url, Astro.params.id, { pluginId: "eventual", locale: "fr-CH" });
163
+ Astro.response.status = data.status;
164
+ ---
165
+ <Layout title={data.pageTitle}>
166
+ <EventDetail data={data}>
167
+ {data.event && <RsvpForm eventId={eventContentId(data.event)} occurrenceStart={occurrenceStart(data.event)} />}
168
+ </EventDetail>
169
+ </Layout>
170
+ ```
171
+
172
+ Anything inside `EventDetail` (Registrations' `RsvpForm`, Tickets' `TicketCheckout`) appears after the description. On a static site keep `prerender = false` on both pages, since they read the month and the view from the address.
173
+
174
+ **Loader options** (both loaders):
175
+
176
+ | Option | Default | What it does |
177
+ |---|---|---|
178
+ | `pluginId` | `eventual` | The installed ID; `r_…` for a Registry install ([how to find it](#installation-and-plugin-id)). |
179
+ | `origin` | the page's own | The EmDash site that serves the feed, when the pages run elsewhere. |
180
+ | `locale` | `en` | Page texts (21 languages), date formats, first day of the week, and the content language asked from the feed. Arabic and Hebrew pages are right to left. |
181
+ | `contentLocale`, `strict` | language of `locale`, `false` | The feed's content language, and whether to leave out events not translated into it. |
182
+ | `timeZone` | `UTC` | The zone for "this month" and "today". Each event keeps its own zone. |
183
+ | `basePath` | `/events` | The events page's address; detail links are `<basePath>/<slug>`. |
184
+ | `linkTo` | `detail` | `cms` links to the entry's own public page when it has one. |
185
+ | `views`, `defaultView` | all seven, `list` | The views offered, in order: `list`, `timeline`, `cards`, `schedule`, `dates`, `month`, `locations`. |
186
+ | `view`, `month`, `category` | from the address | Fix a value instead of reading `?view=`, `?month=` or `?category=`. |
187
+
188
+ **Component props:** `EventBrowser` takes `headingLevel` (1, or 2 inside another page), `title`, `intro` (`false` for none), `id`, `showFilter`, `showViewSwitch` and `scheme`. `EventDetail` takes `headingLevel`, `backHref` (`false` for none), `showSubscribe`, `jsonLd` (Event structured data, on by default) and `scheme`.
189
+
190
+ **Look and theming.** The styles are in the `eventual` cascade layer, so any CSS of your own wins. Neutral colours follow the surrounding text colour, so the pages suit any background; the accent and status colours follow the page's `color-scheme` (set `color-scheme: light dark` on your page, or pass `scheme="dark"` where a block sits on a dark surface). Override these properties on the component or any ancestor; Registrations and Tickets read the same names:
191
+
192
+ | Property | Default |
193
+ |---|---|
194
+ | `--eventual-primary`, `--eventual-on-primary` | blue (`light-dark(#075985, #7dd3fc)`) and the text on it |
195
+ | `--eventual-text-muted`, `--eventual-border`, `--eventual-surface` | the text colour at 72%, 14% and 3% |
196
+ | `--eventual-cancelled`, `--eventual-changed`, `--eventual-error` | red, amber, red |
197
+ | `--eventual-radius`, `--eventual-control-radius`, `--eventual-focus`, `--eventual-gap` | `0.875rem`, `0.5rem`, the primary colour, `1rem` |
198
+
199
+ Layouts adapt to the width of the component, not the window (container queries): the month grid becomes a day list below about 700 pixels, and images drop out of narrow rows. All classes start with `eventual-`.
200
+
201
+ **Accessibility.** Status (cancelled, postponed, rescheduled) shows in every view, each event's content language is marked, the month grid reads full day names and dates, today is marked, and links that open a new tab say so. Checked with axe (WCAG 2.2 AA) in all views in light and dark, and on a 375-pixel screen at 200% text size.
202
+
203
+ **Lower level.** `buildEventBrowserData(events, url, options)` and `buildEventDetailData(events, id, url, options)` do the same without fetching, for example when you call the SSR dispatcher yourself. `eventPageText(locale)` gives the translated texts. The texts live in the `core-site` namespace of `@vermeulen.solutions/eventual-locales`.
204
+
205
+ The [example site](../examples/astro-events/README.md) uses both pages with a green accent.
132
206
 
133
207
  ## Settings, tools and transfer
134
208
 
@@ -1,8 +1,8 @@
1
- # Eventual RSVP – Core 0.18.7
1
+ # Eventual RSVP – Core 0.19.0
2
2
 
3
3
  Requires EmDash **>=1.2.0 <2.0.0**; tested on 1.2.0, 1.4.0, 1.5.0 and 1.6.0. **1.4.0 or newer is recommended** for nested forms and Cloudflare plugin mutations, and required for the optional cache integration.
4
4
 
5
- In **Plugins → Registry**, find **Eventual RSVP – Core** by **vermeulen.solutions**, review permissions and install or update. 0.18.7 needs no new permissions; since 0.18.0 Core uses `network:request` to `cdn.jsdelivr.net` for the admin's language packs. Agent tools stay off until you expand the plugin under **Plugins** and switch on **Agent access**.
5
+ In **Plugins → Registry**, find **Eventual RSVP – Core** by **vermeulen.solutions**, review permissions and install or update. 0.19.0 needs no new permissions; since 0.18.0 Core uses `network:request` to `cdn.jsdelivr.net` for the admin's language packs. Agent tools stay off until you expand the plugin under **Plugins** and switch on **Agent access**.
6
6
 
7
7
  Open **Event settings**, select compatible event, venue and organizer collections, then **Save settings**. Installation does not create schemas or migrate content. Site builders: [collection setup](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/main/docs/collection-setup.md).
8
8
 
@@ -0,0 +1,12 @@
1
+ # Eventual RSVP – Core 0.19.0 — event pages in the package
2
+
3
+ Visitor pages no longer have to be built by your developer. The package now has a complete events page and an event page, ready to put in an Astro site.
4
+
5
+ - **Events page (`EventBrowser`):** seven views (list, timeline, cards, schedule, date strip, month and locations), month navigation, a category filter and a calendar subscription link. Cancelled, postponed and rescheduled events are marked in every view.
6
+ - **Event page (`EventDetail`):** date, time, place with directions, organizer, website, the description, an "Add to calendar" menu (Google, Outlook, Office 365, iCal file), a subscription link and Event structured data for search engines. Registrations' or Tickets' form goes inside it.
7
+ - **Two short pages:** a loader fetches the feed and gives the page its texts, data and HTTP status (502 when the feed cannot be reached, 404 for an unknown event). See [Event pages](developer-guide.md#event-pages).
8
+ - **21 languages:** English, French, German, Dutch, Spanish, Italian, Portuguese (Portugal and Brazil), Polish, Czech, Swedish, Danish, Norwegian, Finnish, Japanese, Chinese, Korean, Turkish, Ukrainian, Arabic and Hebrew, with right-to-left layout for Arabic and Hebrew. The texts come with `@vermeulen.solutions/eventual-locales` 0.1.12.
9
+ - **Light and dark:** a neutral look with a blue accent that follows the page's text colour and colour scheme. Your own CSS always wins, and `--eventual-*` properties (shared with Registrations and Tickets) change the colours, corners and spacing.
10
+ - **Accessible and responsive:** no axe (WCAG 2.2 AA) violations in any view in light or dark; nothing runs off a 375-pixel screen at 200% text size. Layouts follow the space the component has, so the month grid becomes a day list in narrow columns.
11
+ - **The Astro example site** in `examples/astro-events` now uses these components; its own copies of the code are gone.
12
+ - **The plugin itself is unchanged:** same permissions, schema and MCP tools as 0.18.7. The Registry bundle only fetches its admin language packs from locales 0.1.12 (the same texts). EmDash `>=1.2.0 <2.0.0`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vermeulen.solutions/eventual",
3
- "version": "0.18.7",
3
+ "version": "0.19.0",
4
4
  "license": "MIT",
5
5
  "homepage": "https://eventual.rsvp/",
6
6
  "type": "module",
@@ -22,6 +22,9 @@
22
22
  "./astro": "./astro/feed.ts",
23
23
  "./astro/schema": "./astro/schema.ts",
24
24
  "./astro/EventList.astro": "./astro/EventList.astro",
25
+ "./astro/events": "./astro/events/index.ts",
26
+ "./astro/EventBrowser.astro": "./astro/events/EventBrowser.astro",
27
+ "./astro/EventDetail.astro": "./astro/events/EventDetail.astro",
25
28
  "./transfer": {
26
29
  "types": "./transfer/index.d.mts",
27
30
  "import": "./transfer/index.mjs"
@@ -69,7 +72,8 @@
69
72
  "docs/release-notes-0.18.4.md",
70
73
  "docs/release-notes-0.18.5.md",
71
74
  "docs/release-notes-0.18.6.md",
72
- "docs/release-notes-0.18.7.md"
75
+ "docs/release-notes-0.18.7.md",
76
+ "docs/release-notes-0.19.0.md"
73
77
  ],
74
78
  "scripts": {
75
79
  "validate": "emdash-plugin validate",
@@ -117,7 +121,7 @@
117
121
  "dependencies": {
118
122
  "@lingui/core": "5.9.5",
119
123
  "zod": "4.5.4",
120
- "@vermeulen.solutions/eventual-locales": "0.1.10"
124
+ "@vermeulen.solutions/eventual-locales": "0.1.12"
121
125
  },
122
126
  "allowScripts": {
123
127
  "esbuild": true,
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
  /** Emit a schema-only seed. Never connect to a database or overwrite a file. */
3
3
  import { writeFileSync } from 'node:fs';
4
4
  import {createEventsCollectionBlueprint,createVenuesCollectionBlueprint,createOrganizersCollectionBlueprint} from '../astro/blueprint.mjs';