From 5d497f32ec9cd6383aed105ef208be91bb7cd33e Mon Sep 17 00:00:00 2001 From: PhilflowIO Date: Fri, 14 Aug 2026 21:43:40 +0200 Subject: [PATCH 1/2] fix(caldav): honour fetch override in todo API The todo module was modelled on the calendar one but predates the fetch override, and never gained it. All six functions lacked `fetch?: typeof fetch`, and neither createDAVClient nor the DAVClient class forwarded an override to any of them -- the only remaining gap after makeAddressBook, and silent rather than red because client.ts never attempted to pass it. Each function now matches its calendar counterpart exactly: todoQuery and todoMultiGet mirror calendarQuery and calendarMultiGet, fetchTodos mirrors fetchCalendarObjects including threading the override through its internal query and multiget calls, and the write trio mirrors create/update/deleteCalendarObject. Consumers on a platform that needs a custom fetch -- KaiOS mozSystem, a Cloudflare Worker, any environment the default cross-fetch cannot serve -- can now read and write VTODOs at all. Before, every todo request bypassed their fetch, so the whole todo surface was unusable there while calendars and contacts worked. --- dist/client.d.ts | 6 +++ dist/index.d.ts | 12 ++++++ dist/package.json | 2 +- dist/todo.d.ts | 12 ++++++ dist/tsdav.cjs | 92 +++++++++++++++++++++++++++++++++++++--------- dist/tsdav.cjs.js | 92 +++++++++++++++++++++++++++++++++++++--------- dist/tsdav.d.ts | 30 +++++++++++++++ dist/tsdav.esm.js | 92 +++++++++++++++++++++++++++++++++++++--------- dist/tsdav.js | 92 +++++++++++++++++++++++++++++++++++++--------- dist/tsdav.min.cjs | 2 +- dist/tsdav.min.js | 2 +- dist/tsdav.min.mjs | 2 +- dist/tsdav.mjs | 92 +++++++++++++++++++++++++++++++++++++--------- package.json | 2 +- src/client.ts | 66 +++++++++++++++++++++++++++------ src/todo.ts | 49 ++++++++++++++++++++++-- 16 files changed, 535 insertions(+), 110 deletions(-) diff --git a/dist/client.d.ts b/dist/client.d.ts index dea591c7..fa155772 100644 --- a/dist/client.d.ts +++ b/dist/client.d.ts @@ -277,6 +277,7 @@ export declare const createDAVClient: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; todoMultiGet: (params: { url: string; @@ -288,6 +289,7 @@ export declare const createDAVClient: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; fetchTodos: (params: { calendar: DAVCalendar; @@ -303,6 +305,7 @@ export declare const createDAVClient: (params: { headersToExclude?: string[]; useMultiGet?: boolean; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; createTodo: (params: { calendar: DAVCalendar; @@ -311,18 +314,21 @@ export declare const createDAVClient: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; updateTodo: (params: { calendarObject: DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; deleteTodo: (params: { calendarObject: DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; }>; export declare class DAVClient { diff --git a/dist/index.d.ts b/dist/index.d.ts index 3fcac7e4..f95c9d17 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -53,6 +53,7 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; todoMultiGet: (params: { url: string; @@ -64,6 +65,7 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; fetchTodos: (params: { calendar: import("./types/models").DAVCalendar; @@ -79,6 +81,7 @@ declare const _default: { headersToExclude?: string[]; useMultiGet?: boolean; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; createTodo: (params: { calendar: import("./types/models").DAVCalendar; @@ -87,18 +90,21 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; updateTodo: (params: { calendarObject: import("./types/models").DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; deleteTodo: (params: { calendarObject: import("./types/models").DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; fetchCalendarUserAddresses: (params: { account: import("./types/models").DAVAccount; @@ -659,6 +665,7 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; todoMultiGet: (params: { url: string; @@ -670,6 +677,7 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; fetchTodos: (params: { calendar: import("./types/models").DAVCalendar; @@ -685,6 +693,7 @@ declare const _default: { headersToExclude?: string[]; useMultiGet?: boolean; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; createTodo: (params: { calendar: import("./types/models").DAVCalendar; @@ -693,18 +702,21 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; updateTodo: (params: { calendarObject: import("./types/models").DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; deleteTodo: (params: { calendarObject: import("./types/models").DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; }>; DAVClient: typeof client.DAVClient; diff --git a/dist/package.json b/dist/package.json index 06ef653f..8c867c3c 100644 --- a/dist/package.json +++ b/dist/package.json @@ -1,6 +1,6 @@ { "name": "tsdav", - "version": "2.3.2", + "version": "2.3.3", "description": "WebDAV, CALDAV, and CARDDAV client for Nodejs and the Browser", "keywords": [ "dav", diff --git a/dist/todo.d.ts b/dist/todo.d.ts index 72d82ddc..6a2d2c1f 100644 --- a/dist/todo.d.ts +++ b/dist/todo.d.ts @@ -12,6 +12,7 @@ import { DAVCalendar, DAVCalendarObject } from './types/models'; * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ export declare const todoQuery: (params: { @@ -23,6 +24,7 @@ export declare const todoQuery: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Fetch multiple todos by URL using CalDAV calendar-multiget @@ -36,6 +38,7 @@ export declare const todoQuery: (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ export declare const todoMultiGet: (params: { @@ -48,6 +51,7 @@ export declare const todoMultiGet: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Fetch VTODO objects from a CalDAV calendar with optional filtering @@ -62,6 +66,7 @@ export declare const todoMultiGet: (params: { * @param params.headersToExclude - Headers to exclude * @param params.useMultiGet - Whether to use multiget (default: true) * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of todo objects with url, etag, and iCalendar data * @throws Error if calendar URL is missing or timeRange format is invalid */ @@ -79,6 +84,7 @@ export declare const fetchTodos: (params: { headersToExclude?: string[]; useMultiGet?: boolean; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Create a new VTODO object in a CalDAV calendar @@ -89,6 +95,7 @@ export declare const fetchTodos: (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if iCalString does not contain a UID */ @@ -99,6 +106,7 @@ export declare const createTodo: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Update an existing VTODO object in a CalDAV calendar @@ -107,6 +115,7 @@ export declare const createTodo: (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if calendarObject does not have an etag */ @@ -115,6 +124,7 @@ export declare const updateTodo: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Delete a VTODO object from a CalDAV calendar @@ -123,6 +133,7 @@ export declare const updateTodo: (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server */ export declare const deleteTodo: (params: { @@ -130,4 +141,5 @@ export declare const deleteTodo: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; diff --git a/dist/tsdav.cjs b/dist/tsdav.cjs index adf6eb16..3eab1378 100644 --- a/dist/tsdav.cjs +++ b/dist/tsdav.cjs @@ -1512,10 +1512,11 @@ const buildExpandProp = (timeRange) => ({ * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -1535,6 +1536,7 @@ const todoQuery = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1549,10 +1551,11 @@ const todoQuery = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -1568,6 +1571,7 @@ const todoMultiGet = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1583,11 +1587,12 @@ const todoMultiGet = async (params) => { * @param params.headersToExclude - Headers to exclude * @param params.useMultiGet - Whether to use multiget (default: true) * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of todo objects with url, etag, and iCalendar data * @throws Error if calendar URL is missing or timeRange format is invalid */ const fetchTodos = async (params) => { - const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, } = params; + const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (timeRange) { validateISO8601TimeRange(timeRange.start, timeRange.end); } @@ -1644,6 +1649,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, })).map((res) => { var _a; return (_a = res.href) !== null && _a !== void 0 ? _a : ''; })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, calendar.url).href)) .filter(urlFilter) @@ -1663,6 +1669,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } else { @@ -1678,6 +1685,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } } @@ -1699,11 +1707,12 @@ const fetchTodos = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if iCalString does not contain a UID */ const createTodo = async (params) => { - const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!iCalString.includes('UID:')) { throw new Error('iCalString must contain a UID'); } @@ -1716,6 +1725,7 @@ const createTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1725,11 +1735,12 @@ const createTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if calendarObject does not have an etag */ const updateTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!calendarObject.etag) { throw new Error('calendarObject must have etag for update - fetch todo first'); } @@ -1742,6 +1753,7 @@ const updateTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1751,15 +1763,17 @@ const updateTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server */ const deleteTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return deleteObject({ url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; @@ -2077,12 +2091,30 @@ const createDAVClient = async (params) => { fetch: fetchOverride, }); // todo - const todoQuery$1 = defaultParam(todoQuery, { headers: authHeaders }); - const todoMultiGet$1 = defaultParam(todoMultiGet, { headers: authHeaders }); - const fetchTodos$1 = defaultParam(fetchTodos, { headers: authHeaders }); - const createTodo$1 = defaultParam(createTodo, { headers: authHeaders }); - const updateTodo$1 = defaultParam(updateTodo, { headers: authHeaders }); - const deleteTodo$1 = defaultParam(deleteTodo, { headers: authHeaders }); + const todoQuery$1 = defaultParam(todoQuery, { + headers: authHeaders, + fetch: fetchOverride, + }); + const todoMultiGet$1 = defaultParam(todoMultiGet, { + headers: authHeaders, + fetch: fetchOverride, + }); + const fetchTodos$1 = defaultParam(fetchTodos, { + headers: authHeaders, + fetch: fetchOverride, + }); + const createTodo$1 = defaultParam(createTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const updateTodo$1 = defaultParam(updateTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const deleteTodo$1 = defaultParam(deleteTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); return { davRequest: davRequest$1, propfind: propfind$1, @@ -2401,22 +2433,46 @@ class DAVClient { })(params[0]); } async todoQuery(...params) { - return defaultParam(todoQuery, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoQuery, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async todoMultiGet(...params) { - return defaultParam(todoMultiGet, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoMultiGet, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async fetchTodos(...params) { - return defaultParam(fetchTodos, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(fetchTodos, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async createTodo(...params) { - return defaultParam(createTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(createTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async updateTodo(...params) { - return defaultParam(updateTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(updateTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async deleteTodo(...params) { - return defaultParam(deleteTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(deleteTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } } diff --git a/dist/tsdav.cjs.js b/dist/tsdav.cjs.js index adf6eb16..3eab1378 100644 --- a/dist/tsdav.cjs.js +++ b/dist/tsdav.cjs.js @@ -1512,10 +1512,11 @@ const buildExpandProp = (timeRange) => ({ * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -1535,6 +1536,7 @@ const todoQuery = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1549,10 +1551,11 @@ const todoQuery = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -1568,6 +1571,7 @@ const todoMultiGet = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1583,11 +1587,12 @@ const todoMultiGet = async (params) => { * @param params.headersToExclude - Headers to exclude * @param params.useMultiGet - Whether to use multiget (default: true) * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of todo objects with url, etag, and iCalendar data * @throws Error if calendar URL is missing or timeRange format is invalid */ const fetchTodos = async (params) => { - const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, } = params; + const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (timeRange) { validateISO8601TimeRange(timeRange.start, timeRange.end); } @@ -1644,6 +1649,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, })).map((res) => { var _a; return (_a = res.href) !== null && _a !== void 0 ? _a : ''; })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, calendar.url).href)) .filter(urlFilter) @@ -1663,6 +1669,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } else { @@ -1678,6 +1685,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } } @@ -1699,11 +1707,12 @@ const fetchTodos = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if iCalString does not contain a UID */ const createTodo = async (params) => { - const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!iCalString.includes('UID:')) { throw new Error('iCalString must contain a UID'); } @@ -1716,6 +1725,7 @@ const createTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1725,11 +1735,12 @@ const createTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if calendarObject does not have an etag */ const updateTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!calendarObject.etag) { throw new Error('calendarObject must have etag for update - fetch todo first'); } @@ -1742,6 +1753,7 @@ const updateTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1751,15 +1763,17 @@ const updateTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server */ const deleteTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return deleteObject({ url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; @@ -2077,12 +2091,30 @@ const createDAVClient = async (params) => { fetch: fetchOverride, }); // todo - const todoQuery$1 = defaultParam(todoQuery, { headers: authHeaders }); - const todoMultiGet$1 = defaultParam(todoMultiGet, { headers: authHeaders }); - const fetchTodos$1 = defaultParam(fetchTodos, { headers: authHeaders }); - const createTodo$1 = defaultParam(createTodo, { headers: authHeaders }); - const updateTodo$1 = defaultParam(updateTodo, { headers: authHeaders }); - const deleteTodo$1 = defaultParam(deleteTodo, { headers: authHeaders }); + const todoQuery$1 = defaultParam(todoQuery, { + headers: authHeaders, + fetch: fetchOverride, + }); + const todoMultiGet$1 = defaultParam(todoMultiGet, { + headers: authHeaders, + fetch: fetchOverride, + }); + const fetchTodos$1 = defaultParam(fetchTodos, { + headers: authHeaders, + fetch: fetchOverride, + }); + const createTodo$1 = defaultParam(createTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const updateTodo$1 = defaultParam(updateTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const deleteTodo$1 = defaultParam(deleteTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); return { davRequest: davRequest$1, propfind: propfind$1, @@ -2401,22 +2433,46 @@ class DAVClient { })(params[0]); } async todoQuery(...params) { - return defaultParam(todoQuery, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoQuery, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async todoMultiGet(...params) { - return defaultParam(todoMultiGet, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoMultiGet, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async fetchTodos(...params) { - return defaultParam(fetchTodos, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(fetchTodos, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async createTodo(...params) { - return defaultParam(createTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(createTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async updateTodo(...params) { - return defaultParam(updateTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(updateTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async deleteTodo(...params) { - return defaultParam(deleteTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(deleteTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } } diff --git a/dist/tsdav.d.ts b/dist/tsdav.d.ts index 5dba3548..2ee33e3f 100644 --- a/dist/tsdav.d.ts +++ b/dist/tsdav.d.ts @@ -467,6 +467,7 @@ declare const deleteObject: (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ declare const todoQuery: (params: { @@ -478,6 +479,7 @@ declare const todoQuery: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Fetch multiple todos by URL using CalDAV calendar-multiget @@ -491,6 +493,7 @@ declare const todoQuery: (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ declare const todoMultiGet: (params: { @@ -503,6 +506,7 @@ declare const todoMultiGet: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Fetch VTODO objects from a CalDAV calendar with optional filtering @@ -517,6 +521,7 @@ declare const todoMultiGet: (params: { * @param params.headersToExclude - Headers to exclude * @param params.useMultiGet - Whether to use multiget (default: true) * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of todo objects with url, etag, and iCalendar data * @throws Error if calendar URL is missing or timeRange format is invalid */ @@ -534,6 +539,7 @@ declare const fetchTodos: (params: { headersToExclude?: string[]; useMultiGet?: boolean; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Create a new VTODO object in a CalDAV calendar @@ -544,6 +550,7 @@ declare const fetchTodos: (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if iCalString does not contain a UID */ @@ -554,6 +561,7 @@ declare const createTodo: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Update an existing VTODO object in a CalDAV calendar @@ -562,6 +570,7 @@ declare const createTodo: (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if calendarObject does not have an etag */ @@ -570,6 +579,7 @@ declare const updateTodo: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; /** * Delete a VTODO object from a CalDAV calendar @@ -578,6 +588,7 @@ declare const updateTodo: (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server */ declare const deleteTodo: (params: { @@ -585,6 +596,7 @@ declare const deleteTodo: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; declare const createDAVClient: (params: { @@ -857,6 +869,7 @@ declare const createDAVClient: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; todoMultiGet: (params: { url: string; @@ -868,6 +881,7 @@ declare const createDAVClient: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; fetchTodos: (params: { calendar: DAVCalendar; @@ -883,6 +897,7 @@ declare const createDAVClient: (params: { headersToExclude?: string[]; useMultiGet?: boolean; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; createTodo: (params: { calendar: DAVCalendar; @@ -891,18 +906,21 @@ declare const createDAVClient: (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; updateTodo: (params: { calendarObject: DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; deleteTodo: (params: { calendarObject: DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; }>; declare class DAVClient { @@ -1078,6 +1096,7 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; todoMultiGet: (params: { url: string; @@ -1089,6 +1108,7 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; fetchTodos: (params: { calendar: DAVCalendar; @@ -1104,6 +1124,7 @@ declare const _default: { headersToExclude?: string[]; useMultiGet?: boolean; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; createTodo: (params: { calendar: DAVCalendar; @@ -1112,18 +1133,21 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; updateTodo: (params: { calendarObject: DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; deleteTodo: (params: { calendarObject: DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; fetchCalendarUserAddresses: (params: { account: DAVAccount; @@ -1684,6 +1708,7 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; todoMultiGet: (params: { url: string; @@ -1695,6 +1720,7 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; fetchTodos: (params: { calendar: DAVCalendar; @@ -1710,6 +1736,7 @@ declare const _default: { headersToExclude?: string[]; useMultiGet?: boolean; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; createTodo: (params: { calendar: DAVCalendar; @@ -1718,18 +1745,21 @@ declare const _default: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; updateTodo: (params: { calendarObject: DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; deleteTodo: (params: { calendarObject: DAVCalendarObject; headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }) => Promise; }>; DAVClient: typeof DAVClient; diff --git a/dist/tsdav.esm.js b/dist/tsdav.esm.js index 60d7c359..fe4cb9e5 100644 --- a/dist/tsdav.esm.js +++ b/dist/tsdav.esm.js @@ -1508,10 +1508,11 @@ const buildExpandProp = (timeRange) => ({ * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -1531,6 +1532,7 @@ const todoQuery = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1545,10 +1547,11 @@ const todoQuery = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -1564,6 +1567,7 @@ const todoMultiGet = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1579,11 +1583,12 @@ const todoMultiGet = async (params) => { * @param params.headersToExclude - Headers to exclude * @param params.useMultiGet - Whether to use multiget (default: true) * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of todo objects with url, etag, and iCalendar data * @throws Error if calendar URL is missing or timeRange format is invalid */ const fetchTodos = async (params) => { - const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, } = params; + const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (timeRange) { validateISO8601TimeRange(timeRange.start, timeRange.end); } @@ -1640,6 +1645,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, })).map((res) => { var _a; return (_a = res.href) !== null && _a !== void 0 ? _a : ''; })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, calendar.url).href)) .filter(urlFilter) @@ -1659,6 +1665,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } else { @@ -1674,6 +1681,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } } @@ -1695,11 +1703,12 @@ const fetchTodos = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if iCalString does not contain a UID */ const createTodo = async (params) => { - const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!iCalString.includes('UID:')) { throw new Error('iCalString must contain a UID'); } @@ -1712,6 +1721,7 @@ const createTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1721,11 +1731,12 @@ const createTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if calendarObject does not have an etag */ const updateTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!calendarObject.etag) { throw new Error('calendarObject must have etag for update - fetch todo first'); } @@ -1738,6 +1749,7 @@ const updateTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1747,15 +1759,17 @@ const updateTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server */ const deleteTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return deleteObject({ url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; @@ -2073,12 +2087,30 @@ const createDAVClient = async (params) => { fetch: fetchOverride, }); // todo - const todoQuery$1 = defaultParam(todoQuery, { headers: authHeaders }); - const todoMultiGet$1 = defaultParam(todoMultiGet, { headers: authHeaders }); - const fetchTodos$1 = defaultParam(fetchTodos, { headers: authHeaders }); - const createTodo$1 = defaultParam(createTodo, { headers: authHeaders }); - const updateTodo$1 = defaultParam(updateTodo, { headers: authHeaders }); - const deleteTodo$1 = defaultParam(deleteTodo, { headers: authHeaders }); + const todoQuery$1 = defaultParam(todoQuery, { + headers: authHeaders, + fetch: fetchOverride, + }); + const todoMultiGet$1 = defaultParam(todoMultiGet, { + headers: authHeaders, + fetch: fetchOverride, + }); + const fetchTodos$1 = defaultParam(fetchTodos, { + headers: authHeaders, + fetch: fetchOverride, + }); + const createTodo$1 = defaultParam(createTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const updateTodo$1 = defaultParam(updateTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const deleteTodo$1 = defaultParam(deleteTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); return { davRequest: davRequest$1, propfind: propfind$1, @@ -2397,22 +2429,46 @@ class DAVClient { })(params[0]); } async todoQuery(...params) { - return defaultParam(todoQuery, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoQuery, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async todoMultiGet(...params) { - return defaultParam(todoMultiGet, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoMultiGet, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async fetchTodos(...params) { - return defaultParam(fetchTodos, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(fetchTodos, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async createTodo(...params) { - return defaultParam(createTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(createTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async updateTodo(...params) { - return defaultParam(updateTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(updateTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async deleteTodo(...params) { - return defaultParam(deleteTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(deleteTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } } diff --git a/dist/tsdav.js b/dist/tsdav.js index bf9a5c77..71331e30 100644 --- a/dist/tsdav.js +++ b/dist/tsdav.js @@ -10702,10 +10702,11 @@ const buildExpandProp = (timeRange) => ({ * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -10725,6 +10726,7 @@ const todoQuery = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -10739,10 +10741,11 @@ const todoQuery = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -10758,6 +10761,7 @@ const todoMultiGet = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -10773,11 +10777,12 @@ const todoMultiGet = async (params) => { * @param params.headersToExclude - Headers to exclude * @param params.useMultiGet - Whether to use multiget (default: true) * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of todo objects with url, etag, and iCalendar data * @throws Error if calendar URL is missing or timeRange format is invalid */ const fetchTodos = async (params) => { - const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, } = params; + const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (timeRange) { validateISO8601TimeRange(timeRange.start, timeRange.end); } @@ -10834,6 +10839,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, })).map((res) => { var _a; return (_a = res.href) !== null && _a !== void 0 ? _a : ''; })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, calendar.url).href)) .filter(urlFilter) @@ -10853,6 +10859,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } else { @@ -10868,6 +10875,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } } @@ -10889,11 +10897,12 @@ const fetchTodos = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if iCalString does not contain a UID */ const createTodo = async (params) => { - const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!iCalString.includes('UID:')) { throw new Error('iCalString must contain a UID'); } @@ -10906,6 +10915,7 @@ const createTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -10915,11 +10925,12 @@ const createTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if calendarObject does not have an etag */ const updateTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!calendarObject.etag) { throw new Error('calendarObject must have etag for update - fetch todo first'); } @@ -10932,6 +10943,7 @@ const updateTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -10941,15 +10953,17 @@ const updateTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server */ const deleteTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return deleteObject({ url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; @@ -11439,12 +11453,30 @@ const createDAVClient = async (params) => { fetch: fetchOverride, }); // todo - const todoQuery$1 = defaultParam(todoQuery, { headers: authHeaders }); - const todoMultiGet$1 = defaultParam(todoMultiGet, { headers: authHeaders }); - const fetchTodos$1 = defaultParam(fetchTodos, { headers: authHeaders }); - const createTodo$1 = defaultParam(createTodo, { headers: authHeaders }); - const updateTodo$1 = defaultParam(updateTodo, { headers: authHeaders }); - const deleteTodo$1 = defaultParam(deleteTodo, { headers: authHeaders }); + const todoQuery$1 = defaultParam(todoQuery, { + headers: authHeaders, + fetch: fetchOverride, + }); + const todoMultiGet$1 = defaultParam(todoMultiGet, { + headers: authHeaders, + fetch: fetchOverride, + }); + const fetchTodos$1 = defaultParam(fetchTodos, { + headers: authHeaders, + fetch: fetchOverride, + }); + const createTodo$1 = defaultParam(createTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const updateTodo$1 = defaultParam(updateTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const deleteTodo$1 = defaultParam(deleteTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); return { davRequest: davRequest$1, propfind: propfind$1, @@ -11763,22 +11795,46 @@ class DAVClient { })(params[0]); } async todoQuery(...params) { - return defaultParam(todoQuery, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoQuery, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async todoMultiGet(...params) { - return defaultParam(todoMultiGet, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoMultiGet, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async fetchTodos(...params) { - return defaultParam(fetchTodos, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(fetchTodos, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async createTodo(...params) { - return defaultParam(createTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(createTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async updateTodo(...params) { - return defaultParam(updateTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(updateTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async deleteTodo(...params) { - return defaultParam(deleteTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(deleteTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } } diff --git a/dist/tsdav.min.cjs b/dist/tsdav.min.cjs index c9643619..fc4999f7 100644 --- a/dist/tsdav.min.cjs +++ b/dist/tsdav.min.cjs @@ -1 +1 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("debug"),r=require("xml-js"),a=require("cross-fetch"),s=require("base-64");exports.DAVNamespace=void 0,(e=exports.DAVNamespace||(exports.DAVNamespace={})).CALENDAR_SERVER="http://calendarserver.org/ns/",e.CALDAV_APPLE="http://apple.com/ns/ical/",e.CALDAV="urn:ietf:params:xml:ns:caldav",e.CARDDAV="urn:ietf:params:xml:ns:carddav",e.DAV="DAV:";const o={[exports.DAVNamespace.CALDAV]:"xmlns:c",[exports.DAVNamespace.CARDDAV]:"xmlns:card",[exports.DAVNamespace.CALENDAR_SERVER]:"xmlns:cs",[exports.DAVNamespace.CALDAV_APPLE]:"xmlns:ca",[exports.DAVNamespace.DAV]:"xmlns:d"};var c,n;exports.DAVNamespaceShort=void 0,(c=exports.DAVNamespaceShort||(exports.DAVNamespaceShort={})).CALDAV="c",c.CARDDAV="card",c.CALENDAR_SERVER="cs",c.CALDAV_APPLE="ca",c.DAV="d",function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(n||(n={}));const d="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):a,i=e=>{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},h=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),a=t.trim();if(Math.abs(r.length-a.length)>1)return!1;const s="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===a.slice(-1)?a.slice(0,-1):a;return e.includes(o)||t.includes(s)},l=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),a=t.trim(),s="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===a.slice(-1)?a.slice(0,-1):a;return e.includes(o)||t.includes(s)},p=e=>e.reduce((e,t)=>({...e,[o[t]]:t}),{}),u=e=>Object.entries(e).reduce((e,[t,r])=>r?{...e,[t]:r}:e,{}),f=(e,t)=>t?{[e]:t}:{},A=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))):e:{},v=e=>Boolean(null==e?void 0:e.includes(".ics")),m=(e,t)=>{const r=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,a=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(r.test(e)&&r.test(t)||a.test(e)&&a.test(t)))throw new Error("invalid timeRange format, not in ISO8601")};var O=Object.freeze({__proto__:null,cleanupFalsy:u,conditionalParam:f,defaultIcsFilter:v,excludeHeaders:A,getDAVAttribute:p,urlContains:l,urlEquals:h,validateISO8601TimeRange:m});const D=t("tsdav:request"),y=async e=>{var t;const{url:a,init:s,convertIncoming:o=!0,parseOutgoing:c=!0,fetchOptions:n={},fetch:h}=e,l=null!=h?h:d,{headers:p={},body:f,namespace:A,method:v,attributes:m}=s,O=o?r.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...f,_attributes:m},{compact:!0,spaces:2,elementNameFn:e=>A&&!/^.+:.+/.test(e)?`${A}:${e}`:e}):f,y={...n};delete y.headers;const V=await l(a,{headers:{"Content-Type":"text/xml;charset=UTF-8",...u(p),...n.headers||{}},body:O,method:v,...y}),x=await V.text();if(!(V.ok&&(null===(t=V.headers.get("content-type"))||void 0===t?void 0:t.includes("xml"))&&c&&x))return[{href:V.url,ok:V.ok,status:V.status,statusText:V.statusText,raw:x}];const g=r.xml2js(x,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,a=Object.keys(r),s=a[a.length-1],o=r[s];if(o.length>0){o[o.length-1]=i(e)}else r[s]=i(e)}catch(e){D(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,e=>e[1].toUpperCase()),attributesFn:e=>{const t={...e};return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(g.multistatus.response)?g.multistatus.response:[g.multistatus.response]).map(e=>{var t,r;if(!e)return{status:V.status,statusText:V.statusText,ok:V.ok};const a=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:g,href:e.href,status:(null==a?void 0:a.groups)?Number.parseInt(null==a?void 0:a.groups.status,10):V.status,statusText:null!==(r=null===(t=null==a?void 0:a.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:V.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce((e,t)=>({...e,...null==t?void 0:t.prop}),{})}})},V=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return y({url:t,init:{method:"PROPFIND",headers:A(u({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:{propfind:{_attributes:p([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),prop:r}}},fetchOptions:c,fetch:n})},x=async e=>{const{url:t,data:r,headers:a,headersToExclude:s,fetchOptions:o={},fetch:c}=e;return(null!=c?c:d)(t,{method:"PUT",body:r,headers:A(a,s),...o})},g=async e=>{const{url:t,data:r,etag:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return(null!=n?n:d)(t,{method:"PUT",body:r,headers:A(u({"If-Match":a,...s}),o),...c})},C=async e=>{const{url:t,headers:r,etag:a,headersToExclude:s,fetchOptions:o={},fetch:c}=e;return(null!=c?c:d)(t,{method:"DELETE",headers:A(u({"If-Match":a,...r}),s),...o})};var b=Object.freeze({__proto__:null,createObject:x,davRequest:y,deleteObject:C,propfind:V,updateObject:g});function w(e,t){const r=e=>t.every(t=>e[t]);return Array.isArray(e)?e.every(e=>r(e)):r(e)}const N=(e,t)=>t.reduce((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`,""),S=t("tsdav:collection"),T=async e=>{const{url:t,body:r,depth:a,defaultNamespace:s=exports.DAVNamespaceShort.DAV,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e,i=await y({url:t,init:{method:"REPORT",headers:A(u({depth:a,...o}),c),namespace:s,body:r},fetchOptions:n,fetch:d}),h=i.find(e=>!e.ok||e.status&&e.status>=400);if(h)throw new Error(`Collection query failed: ${h.status} ${h.statusText}. ${h.raw?`Raw response: ${h.raw}`:""}`);return 1===i.length&&!i[0].raw&&i[0].status&&i[0].status<300?[]:i},$=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return y({url:t,init:{method:"MKCOL",headers:A(u({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:c,fetch:n})},E=async e=>{var t,r,a,s,o;const{collection:c,headers:n,headersToExclude:d,fetchOptions:i={},fetch:h}=e;return null!==(o=null===(s=null===(a=null===(r=null===(t=(await V({url:c.url,props:{[`${exports.DAVNamespaceShort.DAV}:supported-report-set`]:{}},depth:"0",headers:A(n,d),fetchOptions:i,fetch:h}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===a?void 0:a.supportedReport)||void 0===s?void 0:s.map(e=>Object.keys(e.report)[0]))&&void 0!==o?o:[]},k=async e=>{var t,r,a;const{collection:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e,i=(await V({url:s.url,props:{[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:A(o,c),fetchOptions:n,fetch:d})).filter(e=>l(s.url,e.href))[0];if(!i)throw new Error("Collection does not exist on server");return{isDirty:`${s.ctag}`!=`${null===(t=i.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(a=null===(r=i.props)||void 0===r?void 0:r.getctag)||void 0===a?void 0:a.toString()}},_=e=>{const{url:t,props:r,headers:a,syncLevel:s,syncToken:o,headersToExclude:c,fetchOptions:n,fetch:d}=e;return y({url:t,init:{method:"REPORT",namespace:exports.DAVNamespaceShort.DAV,headers:A({...a},c),body:{"sync-collection":{_attributes:p([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),"sync-level":s,"sync-token":o,[`${exports.DAVNamespaceShort.DAV}:prop`]:r}}},fetchOptions:n,fetch:d})},U=async e=>{var t,r,a,s,o,c,n,d,i,h,p,u;const{collection:f,method:v,headers:m,headersToExclude:O,account:D,detailedResult:y,fetchOptions:V={},fetch:x}=e,g=["accountType","homeUrl"];if(!D||!w(D,g)){if(!D)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${N(D,g)} before smartCollectionSync`)}const C=null!=v?v:(null===(t=f.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(S(`smart collection sync with type ${D.accountType} and method ${C}`),"webdav"===C){const e=await _({url:f.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${"caldav"===D.accountType?exports.DAVNamespaceShort.CALDAV:exports.DAVNamespaceShort.CARDDAV}:${"caldav"===D.accountType?"calendar-data":"address-data"}`]:{},[`${exports.DAVNamespaceShort.DAV}:displayname`]:{}},syncLevel:1,syncToken:f.syncToken,headers:A(m,O),fetchOptions:V,fetch:x}),t=e.filter(e=>{var t;const r="caldav"===D.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r}),i=t.filter(e=>404!==e.status).map(e=>e.href),h=t.filter(e=>404===e.status).map(e=>e.href),p=(i.length&&null!==(a=await(null===(r=null==f?void 0:f.objectMultiGet)||void 0===r?void 0:r.call(f,{url:f.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${"caldav"===D.accountType?exports.DAVNamespaceShort.CALDAV:exports.DAVNamespaceShort.CARDDAV}:${"caldav"===D.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:i,depth:"1",headers:A(m,O),fetchOptions:V,fetch:x})))&&void 0!==a?a:[]).map(e=>{var t,r,a,s,o,c,n,d,i,h;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==D?void 0:D.accountType)?null!==(o=null===(s=null===(a=e.props)||void 0===a?void 0:a.calendarData)||void 0===s?void 0:s._cdata)&&void 0!==o?o:null===(c=e.props)||void 0===c?void 0:c.calendarData:null!==(i=null===(d=null===(n=e.props)||void 0===n?void 0:n.addressData)||void 0===d?void 0:d._cdata)&&void 0!==i?i:null===(h=e.props)||void 0===h?void 0:h.addressData}}),u=null!==(s=f.objects)&&void 0!==s?s:[],v=p.filter(e=>u.every(t=>!l(t.url,e.url))),g=u.reduce((e,t)=>{const r=p.find(e=>l(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),C=h.map(e=>({url:e,etag:""})),b=u.filter(e=>p.some(t=>l(e.url,t.url)&&t.etag===e.etag));return{...f,objects:y?{created:v,updated:g,deleted:C}:[...b,...v,...g],syncToken:null!==(d=null===(n=null===(c=null===(o=e[0])||void 0===o?void 0:o.raw)||void 0===c?void 0:c.multistatus)||void 0===n?void 0:n.syncToken)&&void 0!==d?d:f.syncToken}}if("basic"===C){const{isDirty:e,newCtag:t}=await k({collection:f,headers:A(m,O),fetchOptions:V,fetch:x}),r=null!==(i=f.objects)&&void 0!==i?i:[],a=null!==(u=await(null===(p=(h=f).fetchObjects)||void 0===p?void 0:p.call(h,{collection:f,headers:A(m,O),fetchOptions:V,fetch:x})))&&void 0!==u?u:[],s=a.filter(e=>r.every(t=>!l(t.url,e.url))),o=r.reduce((e,t)=>{const r=a.find(e=>l(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),c=r.filter(e=>a.every(t=>!l(t.url,e.url))),n=r.filter(e=>a.some(t=>l(e.url,t.url)&&t.etag===e.etag));if(e)return{...f,objects:y?{created:s,updated:o,deleted:c}:[...n,...s,...o],ctag:t}}return y?{...f,objects:{created:[],updated:[],deleted:[]}}:f};var R=Object.freeze({__proto__:null,collectionQuery:T,isCollectionDirty:k,makeCollection:$,smartCollectionSync:U,supportedReportSet:E,syncCollection:_});const L=t("tsdav:addressBook"),j=async e=>{const{url:t,props:r,filters:a,depth:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e;return T({url:t,body:{"addressbook-query":u({_attributes:p([exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:null!=a?a:{"prop-filter":{_attributes:{name:"FN"}}}})},defaultNamespace:exports.DAVNamespaceShort.CARDDAV,depth:s,headers:A(o,c),fetchOptions:n,fetch:d})},H=async e=>{const{url:t,props:r,objectUrls:a,depth:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e;return T({url:t,body:{"addressbook-multiget":u({_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CARDDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:a})},defaultNamespace:exports.DAVNamespaceShort.CARDDAV,depth:s,headers:A(o,c),fetchOptions:n,fetch:d})},B=async e=>{const{account:t,headers:r,props:a,headersToExclude:s,fetchOptions:o={},fetch:c}=null!=e?e:{},n=["homeUrl","rootUrl"];if(!t||!w(t,n)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${N(t,n)} before fetchAddressBooks`)}const d=await V({url:t.homeUrl,props:null!=a?a:{[`${exports.DAVNamespaceShort.DAV}:displayname`]:{},[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{},[`${exports.DAVNamespaceShort.DAV}:resourcetype`]:{},[`${exports.DAVNamespaceShort.DAV}:sync-token`]:{}},depth:"1",headers:A(r,s),fetchOptions:o,fetch:c});return Promise.all(d.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")}).map(e=>{var r,a,s,o,c,n,d,i,h;const l=null!==(s=null===(a=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===a?void 0:a._cdata)&&void 0!==s?s:null===(o=e.props)||void 0===o?void 0:o.displayname;return L(`Found address book named ${"string"==typeof l?l:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(c=e.href)&&void 0!==c?c:"",null!==(n=t.rootUrl)&&void 0!==n?n:"").href,ctag:null===(d=e.props)||void 0===d?void 0:d.getctag,displayName:"string"==typeof l?l:"",resourcetype:Object.keys(null===(i=e.props)||void 0===i?void 0:i.resourcetype),syncToken:null===(h=e.props)||void 0===h?void 0:h.syncToken}}).map(async e=>({...e,reports:await E({collection:e,headers:A(r,s),fetchOptions:o,fetch:c})})))},P=async e=>{const{addressBook:t,headers:r,objectUrls:a,headersToExclude:s,urlFilter:o=e=>e,useMultiGet:c=!0,fetchOptions:n={},fetch:d}=e;L(`Fetching vcards from ${null==t?void 0:t.url}`);const i=["url"];if(!t||!w(t,i)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${N(t,i)} before fetchVCards`)}const l=(null!=a?a:(await j({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{}},depth:"1",headers:A(r,s),fetchOptions:n,fetch:d})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(e=>e&&!h(e,t.url)).filter(o).map(e=>new URL(e).pathname);let p=[];return l.length>0&&(p=c?await H({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},objectUrls:l,depth:"1",headers:A(r,s),fetchOptions:n,fetch:d}):await j({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},depth:"1",headers:A(r,s),fetchOptions:n,fetch:d})),p.map(e=>{var r,a,s,o,c,n;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(a=e.props)||void 0===a?void 0:a.getetag,data:null!==(c=null===(o=null===(s=e.props)||void 0===s?void 0:s.addressData)||void 0===o?void 0:o._cdata)&&void 0!==c?c:null===(n=e.props)||void 0===n?void 0:n.addressData}})},M=async e=>{const{addressBook:t,vCardString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return x({url:new URL(a,t.url).href,data:r,headers:A({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:c,fetch:n})},I=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return g({url:t.url,data:t.data,etag:t.etag,headers:A({"content-type":"text/vcard; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},F=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:A(r,a),fetchOptions:s,fetch:o})},z=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return y({url:t,init:{method:"MKCOL",headers:A(u({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:r?{mkcol:{_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CARDDAV]),set:{prop:r}}}:void 0},fetchOptions:c,fetch:n})};var Q=Object.freeze({__proto__:null,addressBookMultiGet:H,addressBookQuery:j,createVCard:M,deleteVCard:F,fetchAddressBooks:B,fetchVCards:P,makeAddressBook:z,updateVCard:I});const Z=t("tsdav:calendar"),q=async e=>{var t,r,a;const{account:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e,i=["principalUrl","rootUrl"];if(!w(s,i))throw new Error(`account must have ${N(s,i)} before fetchUserAddresses`);Z(`Fetch user addresses from ${s.principalUrl}`);const h=(await V({url:s.principalUrl,props:{[`${exports.DAVNamespaceShort.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:A(o,c),fetchOptions:n,fetch:d})).find(e=>l(s.principalUrl,e.href));if(!h||!h.ok)throw new Error("cannot find calendarUserAddresses");const p=(null===(a=null===(r=null===(t=null==h?void 0:h.props)||void 0===t?void 0:t.calendarUserAddressSet)||void 0===r?void 0:r.href)||void 0===a?void 0:a.filter(Boolean))||[];return Z(`Fetched calendar user addresses ${p}`),p},G=async e=>{const{url:t,props:r,filters:a,timezone:s,depth:o,headers:c,headersToExclude:n,fetchOptions:d={},fetch:i}=e;return T({url:t,body:{"calendar-query":u({_attributes:p([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:a,timezone:s})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:o,headers:A(c,n),fetchOptions:d,fetch:i})},J=async e=>{const{url:t,props:r,objectUrls:a,filters:s,timezone:o,depth:c,headers:n,headersToExclude:d,fetchOptions:i={},fetch:h}=e;return T({url:t,body:{"calendar-multiget":u({_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:a,filter:s,timezone:o})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:c,headers:A(n,d),fetchOptions:i,fetch:h})},W=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return y({url:t,init:{method:"MKCALENDAR",headers:A(u({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:{[`${exports.DAVNamespaceShort.CALDAV}:mkcalendar`]:{_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:c,fetch:n})},K=async e=>{const{headers:t,account:r,props:a,projectedProps:s,headersToExclude:o,fetchOptions:c={},fetch:d}=null!=e?e:{},i=["homeUrl","rootUrl"];if(!r||!w(r,i)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${N(r,i)} before fetchCalendars`)}const h=await V({url:r.homeUrl,props:null!=a?a:{[`${exports.DAVNamespaceShort.CALDAV}:calendar-description`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-timezone`]:{},[`${exports.DAVNamespaceShort.DAV}:displayname`]:{},[`${exports.DAVNamespaceShort.CALDAV_APPLE}:calendar-color`]:{},[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{},[`${exports.DAVNamespaceShort.DAV}:resourcetype`]:{},[`${exports.DAVNamespaceShort.CALDAV}:supported-calendar-component-set`]:{},[`${exports.DAVNamespaceShort.DAV}:sync-token`]:{}},depth:"1",headers:A(t,o),fetchOptions:c,fetch:d});return Promise.all(h.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")}).filter(e=>{var t,r,a,s,o,c;return(Array.isArray(null===(r=null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet)||void 0===r?void 0:r.comp)?null===(a=e.props)||void 0===a?void 0:a.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(c=null===(o=null===(s=e.props)||void 0===s?void 0:s.supportedCalendarComponentSet)||void 0===o?void 0:o.comp)||void 0===c?void 0:c._attributes.name]).some(e=>Object.values(n).includes(e))}).map(e=>{var t,a,o,c,n,d,i,h,l,p,u,A,v,m,O,D;const y=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,V=null===(a=e.props)||void 0===a?void 0:a.calendarTimezone;return{description:"string"==typeof y?y:"",timezone:"string"==typeof V?V:"",url:new URL(null!==(o=e.href)&&void 0!==o?o:"",null!==(c=r.rootUrl)&&void 0!==c?c:"").href,ctag:null===(n=e.props)||void 0===n?void 0:n.getctag,calendarColor:null===(d=e.props)||void 0===d?void 0:d.calendarColor,displayName:null!==(h=null===(i=e.props)||void 0===i?void 0:i.displayname._cdata)&&void 0!==h?h:null===(l=e.props)||void 0===l?void 0:l.displayname,components:Array.isArray(null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp)?null===(u=e.props)||void 0===u?void 0:u.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(v=null===(A=e.props)||void 0===A?void 0:A.supportedCalendarComponentSet.comp)||void 0===v?void 0:v._attributes.name],resourcetype:Object.keys(null===(m=e.props)||void 0===m?void 0:m.resourcetype),syncToken:null===(O=e.props)||void 0===O?void 0:O.syncToken,...f("projectedProps",Object.fromEntries(Object.entries(null!==(D=e.props)&&void 0!==D?D:{}).filter(([e])=>null==s?void 0:s[e])))}}).map(async e=>({...e,reports:await E({collection:e,headers:A(t,o),fetchOptions:c,fetch:d})})))},Y=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:c,urlFilter:n=v,useMultiGet:d=!0,headersToExclude:i,fetchOptions:h={},fetch:l}=e;s&&m(s.start,s.end),Z(`Fetching calendar objects from ${null==t?void 0:t.url}`);const p=["url"];if(!t||!w(t,p)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${N(t,p)} before fetchCalendarObjects`)}const u=null!=a?a:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VEVENT"},...s?{"time-range":{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}];let f=[];const O=(null!=r?r:(f=await G({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},...c&&s?{[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}}:{}},filters:u,depth:"1",headers:A(o,i),fetchOptions:h,fetch:l})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(n).map(e=>new URL(e).pathname);let D=[];return O.length>0&&(D=c&&!r?f.filter(e=>{var r,a;const s=(null!==(r=e.href)&&void 0!==r?r:"").startsWith("http")?e.href:new URL(null!==(a=e.href)&&void 0!==a?a:"",t.url).href;return n(null!=s?s:"")}):d?await J({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...c&&s?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},objectUrls:O,depth:"1",headers:A(o,i),fetchOptions:h,fetch:l}):await G({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...c&&s?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},filters:u,depth:"1",headers:A(o,i),fetchOptions:h,fetch:l})),D.map(e=>{var r,a,s,o,c,n;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(a=e.props)||void 0===a?void 0:a.getetag}`,data:null!==(c=null===(o=null===(s=e.props)||void 0===s?void 0:s.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==c?c:null===(n=e.props)||void 0===n?void 0:n.calendarData}})},X=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return x({url:new URL(a,t.url).href,data:r,headers:A({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:c,fetch:n})},ee=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return g({url:t.url,data:t.data,etag:t.etag,headers:A({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},te=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:A(r,a),fetchOptions:s,fetch:o})},re=async e=>{var t;const{oldCalendars:r,account:a,detailedResult:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e;if(!a)throw new Error("Must have account before syncCalendars");const i=null!==(t=null!=r?r:a.calendars)&&void 0!==t?t:[],h=await K({account:a,headers:A(o,c),fetchOptions:n,fetch:d}),p=h.filter(e=>i.every(t=>!l(t.url,e.url)));Z(`new calendars: ${p.map(e=>e.displayName)}`);const u=i.reduce((e,t)=>{const r=h.find(e=>l(e.url,t.url));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e},[]);Z(`updated calendars: ${u.map(e=>e.displayName)}`);const f=await Promise.all(u.map(async e=>await U({collection:{...e,objectMultiGet:J},method:"webdav",headers:A(o,c),account:a,fetchOptions:n,fetch:d}))),v=i.filter(e=>h.every(t=>!l(t.url,e.url)));Z(`deleted calendars: ${v.map(e=>e.displayName)}`);const m=i.filter(e=>h.some(t=>l(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)));return s?{created:p,updated:u,deleted:v}:[...m,...p,...f]},ae=async e=>{const{url:t,timeRange:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;if(!r)throw new Error("timeRange is required");m(r.start,r.end);return(await T({url:t,body:{"free-busy-query":u({_attributes:p([exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:a,headers:A(s,o),fetchOptions:c,fetch:n}))[0]};var se=Object.freeze({__proto__:null,calendarMultiGet:J,calendarQuery:G,createCalendarObject:X,deleteCalendarObject:te,fetchCalendarObjects:Y,fetchCalendarUserAddresses:q,fetchCalendars:K,freeBusyQuery:ae,makeCalendar:W,syncCalendars:re,updateCalendarObject:ee});const oe=t("tsdav:account"),ce=async e=>{var t,r;oe("Service discovery...");const{account:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e,i=null!=n?n:d,h=new URL(a.serverUrl),l=new URL(`/.well-known/${a.accountType}`,h);l.protocol=null!==(t=h.protocol)&&void 0!==t?t:"http";try{const e=await i(l.href,{headers:{...A(s,o),"Content-Type":"text/xml;charset=UTF-8"},method:"PROPFIND",body:'\n\n \n \n \n',redirect:"manual",...c});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){oe(`Service discovery redirected to ${t}`);const e=new URL(t,h);return e.hostname===l.hostname&&l.port&&!e.port&&(e.port=l.port),e.protocol=null!==(r=h.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){oe(`Service discovery failed: ${e.stack}`)}return h.href},ne=async e=>{var t,r,a,s,o;const{account:c,headers:n,headersToExclude:d,fetchOptions:i={},fetch:h}=e,l=["rootUrl"];if(!w(c,l))throw new Error(`account must have ${N(c,l)} before fetchPrincipalUrl`);oe(`Fetching principal url from path ${c.rootUrl}`);const[p]=await V({url:c.rootUrl,props:{[`${exports.DAVNamespaceShort.DAV}:current-user-principal`]:{}},depth:"0",headers:A(n,d),fetchOptions:i,fetch:h});if(!p.ok&&(oe(`Fetch principal url failed: ${p.statusText}`),401===p.status))throw new Error("Invalid credentials");return oe(`Fetched principal url ${null===(r=null===(t=p.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(o=null===(s=null===(a=p.props)||void 0===a?void 0:a.currentUserPrincipal)||void 0===s?void 0:s.href)&&void 0!==o?o:"",c.rootUrl).href},de=async e=>{var t,r;const{account:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e,d=["principalUrl","rootUrl"];if(!w(a,d))throw new Error(`account must have ${N(a,d)} before fetchHomeUrl`);oe(`Fetch home url from ${a.principalUrl}`);const i=await V({url:a.principalUrl,props:"caldav"===a.accountType?{[`${exports.DAVNamespaceShort.CALDAV}:calendar-home-set`]:{}}:{[`${exports.DAVNamespaceShort.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:A(s,o),fetchOptions:c,fetch:n}),h=i.find(e=>l(a.principalUrl,e.href));if(!h||!h.ok)throw oe(`Fetch home url failed with status ${null==h?void 0:h.statusText} and error ${JSON.stringify(i.map(e=>e.error))}`),new Error("cannot find homeUrl");const p=new URL("caldav"===a.accountType?null===(t=null==h?void 0:h.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==h?void 0:h.props)||void 0===r?void 0:r.addressbookHomeSet.href,a.rootUrl).href;return oe(`Fetched home url ${p}`),p},ie=async e=>{const{account:t,headers:r,loadCollections:a=!1,loadObjects:s=!1,headersToExclude:o,fetchOptions:c={},fetch:n}=e,d={...t};return d.rootUrl=await ce({account:t,headers:A(r,o),fetchOptions:c,fetch:n}),d.principalUrl=await ne({account:d,headers:A(r,o),fetchOptions:c,fetch:n}),d.homeUrl=await de({account:d,headers:A(r,o),fetchOptions:c,fetch:n}),(a||s)&&("caldav"===t.accountType?d.calendars=await K({headers:A(r,o),account:d,fetchOptions:c,fetch:n}):"carddav"===t.accountType&&(d.addressBooks=await B({headers:A(r,o),account:d,fetchOptions:c,fetch:n}))),s&&("caldav"===t.accountType&&d.calendars?d.calendars=await Promise.all(d.calendars.map(async e=>({...e,objects:await Y({calendar:e,headers:A(r,o),fetchOptions:c,fetch:n})}))):"carddav"===t.accountType&&d.addressBooks&&(d.addressBooks=await Promise.all(d.addressBooks.map(async e=>({...e,objects:await P({addressBook:e,headers:A(r,o),fetchOptions:c,fetch:n})}))))),d};var he=Object.freeze({__proto__:null,createAccount:ie,fetchHomeUrl:de,fetchPrincipalUrl:ne,serviceDiscovery:ce});const le=t("tsdav:todo"),pe=e=>({[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(e.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(e.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}),ue=async e=>{const{url:t,props:r,filters:a,timezone:s,depth:o,headers:c,headersToExclude:n,fetchOptions:d={}}=e;return T({url:t,body:{"calendar-query":u({_attributes:p([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:a,timezone:s})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:o,headers:A(c,n),fetchOptions:d})},fe=async e=>{const{url:t,props:r,objectUrls:a,filters:s,timezone:o,depth:c,headers:n,headersToExclude:d,fetchOptions:i={}}=e;return T({url:t,body:{"calendar-multiget":u({_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:a,filter:s,timezone:o})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:c,headers:A(n,d),fetchOptions:i})},Ae=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:c,urlFilter:n=v,useMultiGet:d=!0,headersToExclude:i,fetchOptions:h={}}=e;s&&m(s.start,s.end),le(`Fetching todo objects from ${null==t?void 0:t.url}`);const l=["url"];if(!t||!w(t,l)){if(!t)throw new Error("cannot fetchTodos for undefined calendar");throw new Error(`calendar must have ${N(t,l)} before fetchTodos`)}const p=null!=a?a:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VTODO"},...s?{"time-range":{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}],u=(null!=r?r:(await ue({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{...c&&s?pe(s):{}}},filters:p,depth:"1",headers:A(o,i),fetchOptions:h})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(n).map(e=>new URL(e).pathname);let f=[];return u.length>0&&(f=!d||c?await ue({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...c&&s?pe(s):{}}},filters:p,depth:"1",headers:A(o,i),fetchOptions:h}):await fe({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...c&&s?pe(s):{}}},objectUrls:u,depth:"1",headers:A(o,i),fetchOptions:h})),f.map(e=>{var r,a,s,o,c,n;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(a=e.props)||void 0===a?void 0:a.getetag}`,data:null!==(c=null===(o=null===(s=e.props)||void 0===s?void 0:s.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==c?c:null===(n=e.props)||void 0===n?void 0:n.calendarData}})},ve=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:c={}}=e;if(!r.includes("UID:"))throw new Error("iCalString must contain a UID");return x({url:new URL(a,t.url).href,data:r,headers:A({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:c})},me=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;if(!t.etag)throw new Error("calendarObject must have etag for update - fetch todo first");return g({url:t.url,data:t.data,etag:t.etag,headers:A({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s})},Oe=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return C({url:t.url,etag:t.etag,headers:A(r,a),fetchOptions:s})};var De=Object.freeze({__proto__:null,createTodo:ve,deleteTodo:Oe,fetchTodos:Ae,todoMultiGet:fe,todoQuery:ue,updateTodo:me});const ye=t("tsdav:authHelper"),Ve=(e,t)=>(...r)=>e({...t,...r[0]}),xe=e=>(ye(`Basic auth token generated: ${s.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${s.encode(`${e.username}:${e.password}`)}`}),ge=e=>({authorization:`Bearer ${e.accessToken}`}),Ce=async(e,t,r)=>{const a=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!w(e,a))throw new Error(`Oauth credentials missing: ${N(e,a)}`);const s=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ye(e.tokenUrl),ye(s.toString());const o=null!=r?r:d,c=await o(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"content-length":`${s.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(c.ok){return await c.json()}return ye(`Fetch Oauth tokens failed: ${await c.text()}`),{}},be=async(e,t,r)=>{const a=["refreshToken","clientId","clientSecret","tokenUrl"];if(!w(e,a))throw new Error(`Oauth credentials missing: ${N(e,a)}`);const s=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),o=null!=r?r:d,c=await o(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(c.ok){return await c.json()}return ye(`Refresh access token failed: ${await c.text()}`),{}},we=async(e,t,r)=>{var a;ye("Fetching oauth headers");let s={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(a=e.expiration)&&void 0!==a?a:0))&&(s=await be(e,t,r)):s=await Ce(e,t,r),ye(`Oauth tokens fetched: ${s.access_token}`),{tokens:s,headers:{authorization:`Bearer ${s.access_token}`}}};var Ne=Object.freeze({__proto__:null,defaultParam:Ve,fetchOauthTokens:Ce,getBasicAuthHeaders:xe,getBearerAuthHeaders:ge,getOauthHeaders:we,refreshAccessToken:be});const Se=async e=>{var t;const{serverUrl:r,credentials:a,authMethod:s,defaultAccountType:o,authFunction:c,fetch:n}=e;let d={};switch(s){case"Basic":d=xe(a);break;case"Bearer":d=ge(a);break;case"Oauth":d=(await we(a,void 0,n)).headers;break;case"Digest":d={Authorization:`Digest ${a.digestString}`};break;case"Custom":d=null!==(t=await(null==c?void 0:c(a)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const i=o?await ie({account:{serverUrl:r,credentials:a,accountType:o},headers:d,fetch:n}):void 0,h=Ve(x,{url:r,headers:d,fetch:n}),l=Ve(g,{headers:d,url:r,fetch:n}),p=Ve(C,{headers:d,url:r,fetch:n}),u=Ve(V,{headers:d,fetch:n}),f=Ve(T,{headers:d,fetch:n}),A=Ve($,{headers:d,fetch:n}),v=Ve(_,{headers:d,fetch:n}),m=Ve(E,{headers:d,fetch:n}),O=Ve(k,{headers:d,fetch:n}),D=Ve(U,{headers:d,account:i,fetch:n}),b=Ve(G,{headers:d,fetch:n}),w=Ve(J,{headers:d,fetch:n}),N=Ve(W,{headers:d,fetch:n}),S=Ve(K,{headers:d,account:i,fetch:n}),R=Ve(q,{headers:d,account:i,fetch:n}),L=Ve(Y,{headers:d,fetch:n}),Q=Ve(X,{headers:d,fetch:n}),Z=Ve(ee,{headers:d,fetch:n}),ae=Ve(te,{headers:d,fetch:n}),se=Ve(re,{account:i,headers:d,fetch:n}),oe=Ve(j,{headers:d,fetch:n}),ce=Ve(H,{headers:d,fetch:n}),ne=Ve(z,{headers:d,fetch:n});return{davRequest:async e=>{const{init:t,fetch:r,...a}=e,{headers:s,...o}=t;return y({...a,init:{...o,headers:{...d,...s}},fetch:null!=r?r:n})},propfind:u,createAccount:async e=>{const{account:t,headers:s,loadCollections:o,loadObjects:c,fetch:i}=e;return ie({account:{serverUrl:r,credentials:a,...t},headers:{...d,...s},loadCollections:o,loadObjects:c,fetch:null!=i?i:n})},createObject:h,updateObject:l,deleteObject:p,calendarQuery:b,addressBookQuery:oe,collectionQuery:f,makeCollection:A,calendarMultiGet:w,makeCalendar:N,syncCollection:v,supportedReportSet:m,isCollectionDirty:O,smartCollectionSync:D,fetchCalendars:S,fetchCalendarUserAddresses:R,fetchCalendarObjects:L,createCalendarObject:Q,updateCalendarObject:Z,deleteCalendarObject:ae,syncCalendars:se,fetchAddressBooks:Ve(B,{account:i,headers:d,fetch:n}),addressBookMultiGet:ce,makeAddressBook:ne,fetchVCards:Ve(P,{headers:d,fetch:n}),createVCard:Ve(M,{headers:d,fetch:n}),updateVCard:Ve(I,{headers:d,fetch:n}),deleteVCard:Ve(F,{headers:d,fetch:n}),todoQuery:Ve(ue,{headers:d}),todoMultiGet:Ve(fe,{headers:d}),fetchTodos:Ve(Ae,{headers:d}),createTodo:Ve(ve,{headers:d}),updateTodo:Ve(me,{headers:d}),deleteTodo:Ve(Oe,{headers:d})}};class Te{constructor(e){var t,r,a;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav",this.authFunction=e.authFunction,this.fetchOptions=null!==(a=e.fetchOptions)&&void 0!==a?a:{},this.fetchOverride=e.fetch}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=xe(this.credentials);break;case"Bearer":this.authHeaders=ge(this.credentials);break;case"Oauth":this.authHeaders=(await we(this.credentials,this.fetchOptions,this.fetchOverride)).headers;break;case"Digest":this.authHeaders={Authorization:`Digest ${this.credentials.digestString}`};break;case"Custom":this.authHeaders=await(null===(e=this.authFunction)||void 0===e?void 0:e.call(this,this.credentials));break;default:throw new Error("Invalid auth method")}this.account=this.accountType?await ie({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride}):void 0}async davRequest(e){const{init:t,fetch:r,...a}=e,{headers:s,...o}=t;return y({...a,init:{...o,headers:{...this.authHeaders,...s}},fetchOptions:this.fetchOptions,fetch:null!=r?r:this.fetchOverride})}async createObject(...e){return Ve(x,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateObject(...e){return Ve(g,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteObject(...e){return Ve(C,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async propfind(...e){return Ve(V,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:a,loadObjects:s,fetchOptions:o,fetch:c}=e;return ie({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:a,loadObjects:s,fetchOptions:null!=o?o:this.fetchOptions,fetch:null!=c?c:this.fetchOverride})}async collectionQuery(...e){return Ve(T,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCollection(...e){return Ve($,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCollection(...e){return Ve(_,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async supportedReportSet(...e){return Ve(E,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async isCollectionDirty(...e){return Ve(k,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async smartCollectionSync(...e){return Ve(U,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride,account:this.account})(e[0])}async calendarQuery(...e){return Ve(G,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCalendar(...e){return Ve(W,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async calendarMultiGet(...e){return Ve(J,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchCalendars(...e){return Ve(K,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return Ve(q,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return Ve(Y,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createCalendarObject(...e){return Ve(X,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateCalendarObject(...e){return Ve(ee,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteCalendarObject(...e){return Ve(te,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCalendars(...e){return Ve(re,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookQuery(...e){return Ve(j,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookMultiGet(...e){return Ve(H,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeAddressBook(...e){return Ve(z,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchAddressBooks(...e){return Ve(B,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchVCards(...e){return Ve(P,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createVCard(...e){return Ve(M,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateVCard(...e){return Ve(I,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteVCard(...e){return Ve(F,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async todoQuery(...e){return Ve(ue,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async todoMultiGet(...e){return Ve(fe,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchTodos(...e){return Ve(Ae,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createTodo(...e){return Ve(ve,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateTodo(...e){return Ve(me,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteTodo(...e){return Ve(Oe,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}}var $e=Object.freeze({__proto__:null,DAVClient:Te,createDAVClient:Se}),Ee={DAVNamespace:exports.DAVNamespace,DAVNamespaceShort:exports.DAVNamespaceShort,DAVAttributeMap:o,...$e,...b,...R,...he,...Q,...se,...De,...Ne,...O};exports.DAVAttributeMap=o,exports.DAVClient=Te,exports.addressBookMultiGet=H,exports.addressBookQuery=j,exports.calendarMultiGet=J,exports.calendarQuery=G,exports.cleanupFalsy=u,exports.collectionQuery=T,exports.createAccount=ie,exports.createCalendarObject=X,exports.createDAVClient=Se,exports.createObject=x,exports.createTodo=ve,exports.createVCard=M,exports.davRequest=y,exports.default=Ee,exports.deleteCalendarObject=te,exports.deleteObject=C,exports.deleteTodo=Oe,exports.deleteVCard=F,exports.fetchAddressBooks=B,exports.fetchCalendarObjects=Y,exports.fetchCalendarUserAddresses=q,exports.fetchCalendars=K,exports.fetchOauthTokens=Ce,exports.fetchTodos=Ae,exports.fetchVCards=P,exports.freeBusyQuery=ae,exports.getBasicAuthHeaders=xe,exports.getBearerAuthHeaders=ge,exports.getDAVAttribute=p,exports.getOauthHeaders=we,exports.isCollectionDirty=k,exports.makeAddressBook=z,exports.makeCalendar=W,exports.propfind=V,exports.refreshAccessToken=be,exports.smartCollectionSync=U,exports.supportedReportSet=E,exports.syncCalendars=re,exports.syncCollection=_,exports.todoMultiGet=fe,exports.todoQuery=ue,exports.updateCalendarObject=ee,exports.updateObject=g,exports.updateTodo=me,exports.updateVCard=I,exports.urlContains=l,exports.urlEquals=h; +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("debug"),r=require("xml-js"),a=require("cross-fetch"),s=require("base-64");exports.DAVNamespace=void 0,(e=exports.DAVNamespace||(exports.DAVNamespace={})).CALENDAR_SERVER="http://calendarserver.org/ns/",e.CALDAV_APPLE="http://apple.com/ns/ical/",e.CALDAV="urn:ietf:params:xml:ns:caldav",e.CARDDAV="urn:ietf:params:xml:ns:carddav",e.DAV="DAV:";const o={[exports.DAVNamespace.CALDAV]:"xmlns:c",[exports.DAVNamespace.CARDDAV]:"xmlns:card",[exports.DAVNamespace.CALENDAR_SERVER]:"xmlns:cs",[exports.DAVNamespace.CALDAV_APPLE]:"xmlns:ca",[exports.DAVNamespace.DAV]:"xmlns:d"};var c,n;exports.DAVNamespaceShort=void 0,(c=exports.DAVNamespaceShort||(exports.DAVNamespaceShort={})).CALDAV="c",c.CARDDAV="card",c.CALENDAR_SERVER="cs",c.CALDAV_APPLE="ca",c.DAV="d",function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(n||(n={}));const d="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):a,h=e=>{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},i=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),a=t.trim();if(Math.abs(r.length-a.length)>1)return!1;const s="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===a.slice(-1)?a.slice(0,-1):a;return e.includes(o)||t.includes(s)},l=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),a=t.trim(),s="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===a.slice(-1)?a.slice(0,-1):a;return e.includes(o)||t.includes(s)},p=e=>e.reduce((e,t)=>({...e,[o[t]]:t}),{}),u=e=>Object.entries(e).reduce((e,[t,r])=>r?{...e,[t]:r}:e,{}),f=(e,t)=>t?{[e]:t}:{},v=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))):e:{},A=e=>Boolean(null==e?void 0:e.includes(".ics")),m=(e,t)=>{const r=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,a=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(r.test(e)&&r.test(t)||a.test(e)&&a.test(t)))throw new Error("invalid timeRange format, not in ISO8601")};var O=Object.freeze({__proto__:null,cleanupFalsy:u,conditionalParam:f,defaultIcsFilter:A,excludeHeaders:v,getDAVAttribute:p,urlContains:l,urlEquals:i,validateISO8601TimeRange:m});const D=t("tsdav:request"),y=async e=>{var t;const{url:a,init:s,convertIncoming:o=!0,parseOutgoing:c=!0,fetchOptions:n={},fetch:i}=e,l=null!=i?i:d,{headers:p={},body:f,namespace:v,method:A,attributes:m}=s,O=o?r.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...f,_attributes:m},{compact:!0,spaces:2,elementNameFn:e=>v&&!/^.+:.+/.test(e)?`${v}:${e}`:e}):f,y={...n};delete y.headers;const V=await l(a,{headers:{"Content-Type":"text/xml;charset=UTF-8",...u(p),...n.headers||{}},body:O,method:A,...y}),x=await V.text();if(!(V.ok&&(null===(t=V.headers.get("content-type"))||void 0===t?void 0:t.includes("xml"))&&c&&x))return[{href:V.url,ok:V.ok,status:V.status,statusText:V.statusText,raw:x}];const g=r.xml2js(x,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,a=Object.keys(r),s=a[a.length-1],o=r[s];if(o.length>0){o[o.length-1]=h(e)}else r[s]=h(e)}catch(e){D(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,e=>e[1].toUpperCase()),attributesFn:e=>{const t={...e};return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(g.multistatus.response)?g.multistatus.response:[g.multistatus.response]).map(e=>{var t,r;if(!e)return{status:V.status,statusText:V.statusText,ok:V.ok};const a=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:g,href:e.href,status:(null==a?void 0:a.groups)?Number.parseInt(null==a?void 0:a.groups.status,10):V.status,statusText:null!==(r=null===(t=null==a?void 0:a.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:V.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce((e,t)=>({...e,...null==t?void 0:t.prop}),{})}})},V=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return y({url:t,init:{method:"PROPFIND",headers:v(u({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:{propfind:{_attributes:p([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),prop:r}}},fetchOptions:c,fetch:n})},x=async e=>{const{url:t,data:r,headers:a,headersToExclude:s,fetchOptions:o={},fetch:c}=e;return(null!=c?c:d)(t,{method:"PUT",body:r,headers:v(a,s),...o})},g=async e=>{const{url:t,data:r,etag:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return(null!=n?n:d)(t,{method:"PUT",body:r,headers:v(u({"If-Match":a,...s}),o),...c})},C=async e=>{const{url:t,headers:r,etag:a,headersToExclude:s,fetchOptions:o={},fetch:c}=e;return(null!=c?c:d)(t,{method:"DELETE",headers:v(u({"If-Match":a,...r}),s),...o})};var b=Object.freeze({__proto__:null,createObject:x,davRequest:y,deleteObject:C,propfind:V,updateObject:g});function w(e,t){const r=e=>t.every(t=>e[t]);return Array.isArray(e)?e.every(e=>r(e)):r(e)}const N=(e,t)=>t.reduce((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`,""),S=t("tsdav:collection"),T=async e=>{const{url:t,body:r,depth:a,defaultNamespace:s=exports.DAVNamespaceShort.DAV,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e,h=await y({url:t,init:{method:"REPORT",headers:v(u({depth:a,...o}),c),namespace:s,body:r},fetchOptions:n,fetch:d}),i=h.find(e=>!e.ok||e.status&&e.status>=400);if(i)throw new Error(`Collection query failed: ${i.status} ${i.statusText}. ${i.raw?`Raw response: ${i.raw}`:""}`);return 1===h.length&&!h[0].raw&&h[0].status&&h[0].status<300?[]:h},$=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return y({url:t,init:{method:"MKCOL",headers:v(u({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:c,fetch:n})},E=async e=>{var t,r,a,s,o;const{collection:c,headers:n,headersToExclude:d,fetchOptions:h={},fetch:i}=e;return null!==(o=null===(s=null===(a=null===(r=null===(t=(await V({url:c.url,props:{[`${exports.DAVNamespaceShort.DAV}:supported-report-set`]:{}},depth:"0",headers:v(n,d),fetchOptions:h,fetch:i}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===a?void 0:a.supportedReport)||void 0===s?void 0:s.map(e=>Object.keys(e.report)[0]))&&void 0!==o?o:[]},k=async e=>{var t,r,a;const{collection:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e,h=(await V({url:s.url,props:{[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:v(o,c),fetchOptions:n,fetch:d})).filter(e=>l(s.url,e.href))[0];if(!h)throw new Error("Collection does not exist on server");return{isDirty:`${s.ctag}`!=`${null===(t=h.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(a=null===(r=h.props)||void 0===r?void 0:r.getctag)||void 0===a?void 0:a.toString()}},_=e=>{const{url:t,props:r,headers:a,syncLevel:s,syncToken:o,headersToExclude:c,fetchOptions:n,fetch:d}=e;return y({url:t,init:{method:"REPORT",namespace:exports.DAVNamespaceShort.DAV,headers:v({...a},c),body:{"sync-collection":{_attributes:p([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),"sync-level":s,"sync-token":o,[`${exports.DAVNamespaceShort.DAV}:prop`]:r}}},fetchOptions:n,fetch:d})},U=async e=>{var t,r,a,s,o,c,n,d,h,i,p,u;const{collection:f,method:A,headers:m,headersToExclude:O,account:D,detailedResult:y,fetchOptions:V={},fetch:x}=e,g=["accountType","homeUrl"];if(!D||!w(D,g)){if(!D)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${N(D,g)} before smartCollectionSync`)}const C=null!=A?A:(null===(t=f.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(S(`smart collection sync with type ${D.accountType} and method ${C}`),"webdav"===C){const e=await _({url:f.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${"caldav"===D.accountType?exports.DAVNamespaceShort.CALDAV:exports.DAVNamespaceShort.CARDDAV}:${"caldav"===D.accountType?"calendar-data":"address-data"}`]:{},[`${exports.DAVNamespaceShort.DAV}:displayname`]:{}},syncLevel:1,syncToken:f.syncToken,headers:v(m,O),fetchOptions:V,fetch:x}),t=e.filter(e=>{var t;const r="caldav"===D.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r}),h=t.filter(e=>404!==e.status).map(e=>e.href),i=t.filter(e=>404===e.status).map(e=>e.href),p=(h.length&&null!==(a=await(null===(r=null==f?void 0:f.objectMultiGet)||void 0===r?void 0:r.call(f,{url:f.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${"caldav"===D.accountType?exports.DAVNamespaceShort.CALDAV:exports.DAVNamespaceShort.CARDDAV}:${"caldav"===D.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:h,depth:"1",headers:v(m,O),fetchOptions:V,fetch:x})))&&void 0!==a?a:[]).map(e=>{var t,r,a,s,o,c,n,d,h,i;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==D?void 0:D.accountType)?null!==(o=null===(s=null===(a=e.props)||void 0===a?void 0:a.calendarData)||void 0===s?void 0:s._cdata)&&void 0!==o?o:null===(c=e.props)||void 0===c?void 0:c.calendarData:null!==(h=null===(d=null===(n=e.props)||void 0===n?void 0:n.addressData)||void 0===d?void 0:d._cdata)&&void 0!==h?h:null===(i=e.props)||void 0===i?void 0:i.addressData}}),u=null!==(s=f.objects)&&void 0!==s?s:[],A=p.filter(e=>u.every(t=>!l(t.url,e.url))),g=u.reduce((e,t)=>{const r=p.find(e=>l(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),C=i.map(e=>({url:e,etag:""})),b=u.filter(e=>p.some(t=>l(e.url,t.url)&&t.etag===e.etag));return{...f,objects:y?{created:A,updated:g,deleted:C}:[...b,...A,...g],syncToken:null!==(d=null===(n=null===(c=null===(o=e[0])||void 0===o?void 0:o.raw)||void 0===c?void 0:c.multistatus)||void 0===n?void 0:n.syncToken)&&void 0!==d?d:f.syncToken}}if("basic"===C){const{isDirty:e,newCtag:t}=await k({collection:f,headers:v(m,O),fetchOptions:V,fetch:x}),r=null!==(h=f.objects)&&void 0!==h?h:[],a=null!==(u=await(null===(p=(i=f).fetchObjects)||void 0===p?void 0:p.call(i,{collection:f,headers:v(m,O),fetchOptions:V,fetch:x})))&&void 0!==u?u:[],s=a.filter(e=>r.every(t=>!l(t.url,e.url))),o=r.reduce((e,t)=>{const r=a.find(e=>l(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),c=r.filter(e=>a.every(t=>!l(t.url,e.url))),n=r.filter(e=>a.some(t=>l(e.url,t.url)&&t.etag===e.etag));if(e)return{...f,objects:y?{created:s,updated:o,deleted:c}:[...n,...s,...o],ctag:t}}return y?{...f,objects:{created:[],updated:[],deleted:[]}}:f};var R=Object.freeze({__proto__:null,collectionQuery:T,isCollectionDirty:k,makeCollection:$,smartCollectionSync:U,supportedReportSet:E,syncCollection:_});const L=t("tsdav:addressBook"),j=async e=>{const{url:t,props:r,filters:a,depth:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e;return T({url:t,body:{"addressbook-query":u({_attributes:p([exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:null!=a?a:{"prop-filter":{_attributes:{name:"FN"}}}})},defaultNamespace:exports.DAVNamespaceShort.CARDDAV,depth:s,headers:v(o,c),fetchOptions:n,fetch:d})},H=async e=>{const{url:t,props:r,objectUrls:a,depth:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e;return T({url:t,body:{"addressbook-multiget":u({_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CARDDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:a})},defaultNamespace:exports.DAVNamespaceShort.CARDDAV,depth:s,headers:v(o,c),fetchOptions:n,fetch:d})},B=async e=>{const{account:t,headers:r,props:a,headersToExclude:s,fetchOptions:o={},fetch:c}=null!=e?e:{},n=["homeUrl","rootUrl"];if(!t||!w(t,n)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${N(t,n)} before fetchAddressBooks`)}const d=await V({url:t.homeUrl,props:null!=a?a:{[`${exports.DAVNamespaceShort.DAV}:displayname`]:{},[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{},[`${exports.DAVNamespaceShort.DAV}:resourcetype`]:{},[`${exports.DAVNamespaceShort.DAV}:sync-token`]:{}},depth:"1",headers:v(r,s),fetchOptions:o,fetch:c});return Promise.all(d.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")}).map(e=>{var r,a,s,o,c,n,d,h,i;const l=null!==(s=null===(a=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===a?void 0:a._cdata)&&void 0!==s?s:null===(o=e.props)||void 0===o?void 0:o.displayname;return L(`Found address book named ${"string"==typeof l?l:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(c=e.href)&&void 0!==c?c:"",null!==(n=t.rootUrl)&&void 0!==n?n:"").href,ctag:null===(d=e.props)||void 0===d?void 0:d.getctag,displayName:"string"==typeof l?l:"",resourcetype:Object.keys(null===(h=e.props)||void 0===h?void 0:h.resourcetype),syncToken:null===(i=e.props)||void 0===i?void 0:i.syncToken}}).map(async e=>({...e,reports:await E({collection:e,headers:v(r,s),fetchOptions:o,fetch:c})})))},P=async e=>{const{addressBook:t,headers:r,objectUrls:a,headersToExclude:s,urlFilter:o=e=>e,useMultiGet:c=!0,fetchOptions:n={},fetch:d}=e;L(`Fetching vcards from ${null==t?void 0:t.url}`);const h=["url"];if(!t||!w(t,h)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${N(t,h)} before fetchVCards`)}const l=(null!=a?a:(await j({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{}},depth:"1",headers:v(r,s),fetchOptions:n,fetch:d})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(e=>e&&!i(e,t.url)).filter(o).map(e=>new URL(e).pathname);let p=[];return l.length>0&&(p=c?await H({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},objectUrls:l,depth:"1",headers:v(r,s),fetchOptions:n,fetch:d}):await j({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},depth:"1",headers:v(r,s),fetchOptions:n,fetch:d})),p.map(e=>{var r,a,s,o,c,n;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(a=e.props)||void 0===a?void 0:a.getetag,data:null!==(c=null===(o=null===(s=e.props)||void 0===s?void 0:s.addressData)||void 0===o?void 0:o._cdata)&&void 0!==c?c:null===(n=e.props)||void 0===n?void 0:n.addressData}})},M=async e=>{const{addressBook:t,vCardString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return x({url:new URL(a,t.url).href,data:r,headers:v({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:c,fetch:n})},I=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return g({url:t.url,data:t.data,etag:t.etag,headers:v({"content-type":"text/vcard; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},F=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:v(r,a),fetchOptions:s,fetch:o})},z=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return y({url:t,init:{method:"MKCOL",headers:v(u({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:r?{mkcol:{_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CARDDAV]),set:{prop:r}}}:void 0},fetchOptions:c,fetch:n})};var Q=Object.freeze({__proto__:null,addressBookMultiGet:H,addressBookQuery:j,createVCard:M,deleteVCard:F,fetchAddressBooks:B,fetchVCards:P,makeAddressBook:z,updateVCard:I});const Z=t("tsdav:calendar"),q=async e=>{var t,r,a;const{account:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e,h=["principalUrl","rootUrl"];if(!w(s,h))throw new Error(`account must have ${N(s,h)} before fetchUserAddresses`);Z(`Fetch user addresses from ${s.principalUrl}`);const i=(await V({url:s.principalUrl,props:{[`${exports.DAVNamespaceShort.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:v(o,c),fetchOptions:n,fetch:d})).find(e=>l(s.principalUrl,e.href));if(!i||!i.ok)throw new Error("cannot find calendarUserAddresses");const p=(null===(a=null===(r=null===(t=null==i?void 0:i.props)||void 0===t?void 0:t.calendarUserAddressSet)||void 0===r?void 0:r.href)||void 0===a?void 0:a.filter(Boolean))||[];return Z(`Fetched calendar user addresses ${p}`),p},G=async e=>{const{url:t,props:r,filters:a,timezone:s,depth:o,headers:c,headersToExclude:n,fetchOptions:d={},fetch:h}=e;return T({url:t,body:{"calendar-query":u({_attributes:p([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:a,timezone:s})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:o,headers:v(c,n),fetchOptions:d,fetch:h})},J=async e=>{const{url:t,props:r,objectUrls:a,filters:s,timezone:o,depth:c,headers:n,headersToExclude:d,fetchOptions:h={},fetch:i}=e;return T({url:t,body:{"calendar-multiget":u({_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:a,filter:s,timezone:o})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:c,headers:v(n,d),fetchOptions:h,fetch:i})},W=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return y({url:t,init:{method:"MKCALENDAR",headers:v(u({depth:a,...s}),o),namespace:exports.DAVNamespaceShort.DAV,body:{[`${exports.DAVNamespaceShort.CALDAV}:mkcalendar`]:{_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:c,fetch:n})},K=async e=>{const{headers:t,account:r,props:a,projectedProps:s,headersToExclude:o,fetchOptions:c={},fetch:d}=null!=e?e:{},h=["homeUrl","rootUrl"];if(!r||!w(r,h)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${N(r,h)} before fetchCalendars`)}const i=await V({url:r.homeUrl,props:null!=a?a:{[`${exports.DAVNamespaceShort.CALDAV}:calendar-description`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-timezone`]:{},[`${exports.DAVNamespaceShort.DAV}:displayname`]:{},[`${exports.DAVNamespaceShort.CALDAV_APPLE}:calendar-color`]:{},[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{},[`${exports.DAVNamespaceShort.DAV}:resourcetype`]:{},[`${exports.DAVNamespaceShort.CALDAV}:supported-calendar-component-set`]:{},[`${exports.DAVNamespaceShort.DAV}:sync-token`]:{}},depth:"1",headers:v(t,o),fetchOptions:c,fetch:d});return Promise.all(i.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")}).filter(e=>{var t,r,a,s,o,c;return(Array.isArray(null===(r=null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet)||void 0===r?void 0:r.comp)?null===(a=e.props)||void 0===a?void 0:a.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(c=null===(o=null===(s=e.props)||void 0===s?void 0:s.supportedCalendarComponentSet)||void 0===o?void 0:o.comp)||void 0===c?void 0:c._attributes.name]).some(e=>Object.values(n).includes(e))}).map(e=>{var t,a,o,c,n,d,h,i,l,p,u,v,A,m,O,D;const y=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,V=null===(a=e.props)||void 0===a?void 0:a.calendarTimezone;return{description:"string"==typeof y?y:"",timezone:"string"==typeof V?V:"",url:new URL(null!==(o=e.href)&&void 0!==o?o:"",null!==(c=r.rootUrl)&&void 0!==c?c:"").href,ctag:null===(n=e.props)||void 0===n?void 0:n.getctag,calendarColor:null===(d=e.props)||void 0===d?void 0:d.calendarColor,displayName:null!==(i=null===(h=e.props)||void 0===h?void 0:h.displayname._cdata)&&void 0!==i?i:null===(l=e.props)||void 0===l?void 0:l.displayname,components:Array.isArray(null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp)?null===(u=e.props)||void 0===u?void 0:u.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(A=null===(v=e.props)||void 0===v?void 0:v.supportedCalendarComponentSet.comp)||void 0===A?void 0:A._attributes.name],resourcetype:Object.keys(null===(m=e.props)||void 0===m?void 0:m.resourcetype),syncToken:null===(O=e.props)||void 0===O?void 0:O.syncToken,...f("projectedProps",Object.fromEntries(Object.entries(null!==(D=e.props)&&void 0!==D?D:{}).filter(([e])=>null==s?void 0:s[e])))}}).map(async e=>({...e,reports:await E({collection:e,headers:v(t,o),fetchOptions:c,fetch:d})})))},Y=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:c,urlFilter:n=A,useMultiGet:d=!0,headersToExclude:h,fetchOptions:i={},fetch:l}=e;s&&m(s.start,s.end),Z(`Fetching calendar objects from ${null==t?void 0:t.url}`);const p=["url"];if(!t||!w(t,p)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${N(t,p)} before fetchCalendarObjects`)}const u=null!=a?a:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VEVENT"},...s?{"time-range":{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}];let f=[];const O=(null!=r?r:(f=await G({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},...c&&s?{[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}}:{}},filters:u,depth:"1",headers:v(o,h),fetchOptions:i,fetch:l})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(n).map(e=>new URL(e).pathname);let D=[];return O.length>0&&(D=c&&!r?f.filter(e=>{var r,a;const s=(null!==(r=e.href)&&void 0!==r?r:"").startsWith("http")?e.href:new URL(null!==(a=e.href)&&void 0!==a?a:"",t.url).href;return n(null!=s?s:"")}):d?await J({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...c&&s?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},objectUrls:O,depth:"1",headers:v(o,h),fetchOptions:i,fetch:l}):await G({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...c&&s?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},filters:u,depth:"1",headers:v(o,h),fetchOptions:i,fetch:l})),D.map(e=>{var r,a,s,o,c,n;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(a=e.props)||void 0===a?void 0:a.getetag}`,data:null!==(c=null===(o=null===(s=e.props)||void 0===s?void 0:s.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==c?c:null===(n=e.props)||void 0===n?void 0:n.calendarData}})},X=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;return x({url:new URL(a,t.url).href,data:r,headers:v({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:c,fetch:n})},ee=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return g({url:t.url,data:t.data,etag:t.etag,headers:v({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},te=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:v(r,a),fetchOptions:s,fetch:o})},re=async e=>{var t;const{oldCalendars:r,account:a,detailedResult:s,headers:o,headersToExclude:c,fetchOptions:n={},fetch:d}=e;if(!a)throw new Error("Must have account before syncCalendars");const h=null!==(t=null!=r?r:a.calendars)&&void 0!==t?t:[],i=await K({account:a,headers:v(o,c),fetchOptions:n,fetch:d}),p=i.filter(e=>h.every(t=>!l(t.url,e.url)));Z(`new calendars: ${p.map(e=>e.displayName)}`);const u=h.reduce((e,t)=>{const r=i.find(e=>l(e.url,t.url));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e},[]);Z(`updated calendars: ${u.map(e=>e.displayName)}`);const f=await Promise.all(u.map(async e=>await U({collection:{...e,objectMultiGet:J},method:"webdav",headers:v(o,c),account:a,fetchOptions:n,fetch:d}))),A=h.filter(e=>i.every(t=>!l(t.url,e.url)));Z(`deleted calendars: ${A.map(e=>e.displayName)}`);const m=h.filter(e=>i.some(t=>l(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)));return s?{created:p,updated:u,deleted:A}:[...m,...p,...f]},ae=async e=>{const{url:t,timeRange:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;if(!r)throw new Error("timeRange is required");m(r.start,r.end);return(await T({url:t,body:{"free-busy-query":u({_attributes:p([exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:a,headers:v(s,o),fetchOptions:c,fetch:n}))[0]};var se=Object.freeze({__proto__:null,calendarMultiGet:J,calendarQuery:G,createCalendarObject:X,deleteCalendarObject:te,fetchCalendarObjects:Y,fetchCalendarUserAddresses:q,fetchCalendars:K,freeBusyQuery:ae,makeCalendar:W,syncCalendars:re,updateCalendarObject:ee});const oe=t("tsdav:account"),ce=async e=>{var t,r;oe("Service discovery...");const{account:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e,h=null!=n?n:d,i=new URL(a.serverUrl),l=new URL(`/.well-known/${a.accountType}`,i);l.protocol=null!==(t=i.protocol)&&void 0!==t?t:"http";try{const e=await h(l.href,{headers:{...v(s,o),"Content-Type":"text/xml;charset=UTF-8"},method:"PROPFIND",body:'\n\n \n \n \n',redirect:"manual",...c});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){oe(`Service discovery redirected to ${t}`);const e=new URL(t,i);return e.hostname===l.hostname&&l.port&&!e.port&&(e.port=l.port),e.protocol=null!==(r=i.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){oe(`Service discovery failed: ${e.stack}`)}return i.href},ne=async e=>{var t,r,a,s,o;const{account:c,headers:n,headersToExclude:d,fetchOptions:h={},fetch:i}=e,l=["rootUrl"];if(!w(c,l))throw new Error(`account must have ${N(c,l)} before fetchPrincipalUrl`);oe(`Fetching principal url from path ${c.rootUrl}`);const[p]=await V({url:c.rootUrl,props:{[`${exports.DAVNamespaceShort.DAV}:current-user-principal`]:{}},depth:"0",headers:v(n,d),fetchOptions:h,fetch:i});if(!p.ok&&(oe(`Fetch principal url failed: ${p.statusText}`),401===p.status))throw new Error("Invalid credentials");return oe(`Fetched principal url ${null===(r=null===(t=p.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(o=null===(s=null===(a=p.props)||void 0===a?void 0:a.currentUserPrincipal)||void 0===s?void 0:s.href)&&void 0!==o?o:"",c.rootUrl).href},de=async e=>{var t,r;const{account:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e,d=["principalUrl","rootUrl"];if(!w(a,d))throw new Error(`account must have ${N(a,d)} before fetchHomeUrl`);oe(`Fetch home url from ${a.principalUrl}`);const h=await V({url:a.principalUrl,props:"caldav"===a.accountType?{[`${exports.DAVNamespaceShort.CALDAV}:calendar-home-set`]:{}}:{[`${exports.DAVNamespaceShort.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:v(s,o),fetchOptions:c,fetch:n}),i=h.find(e=>l(a.principalUrl,e.href));if(!i||!i.ok)throw oe(`Fetch home url failed with status ${null==i?void 0:i.statusText} and error ${JSON.stringify(h.map(e=>e.error))}`),new Error("cannot find homeUrl");const p=new URL("caldav"===a.accountType?null===(t=null==i?void 0:i.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==i?void 0:i.props)||void 0===r?void 0:r.addressbookHomeSet.href,a.rootUrl).href;return oe(`Fetched home url ${p}`),p},he=async e=>{const{account:t,headers:r,loadCollections:a=!1,loadObjects:s=!1,headersToExclude:o,fetchOptions:c={},fetch:n}=e,d={...t};return d.rootUrl=await ce({account:t,headers:v(r,o),fetchOptions:c,fetch:n}),d.principalUrl=await ne({account:d,headers:v(r,o),fetchOptions:c,fetch:n}),d.homeUrl=await de({account:d,headers:v(r,o),fetchOptions:c,fetch:n}),(a||s)&&("caldav"===t.accountType?d.calendars=await K({headers:v(r,o),account:d,fetchOptions:c,fetch:n}):"carddav"===t.accountType&&(d.addressBooks=await B({headers:v(r,o),account:d,fetchOptions:c,fetch:n}))),s&&("caldav"===t.accountType&&d.calendars?d.calendars=await Promise.all(d.calendars.map(async e=>({...e,objects:await Y({calendar:e,headers:v(r,o),fetchOptions:c,fetch:n})}))):"carddav"===t.accountType&&d.addressBooks&&(d.addressBooks=await Promise.all(d.addressBooks.map(async e=>({...e,objects:await P({addressBook:e,headers:v(r,o),fetchOptions:c,fetch:n})}))))),d};var ie=Object.freeze({__proto__:null,createAccount:he,fetchHomeUrl:de,fetchPrincipalUrl:ne,serviceDiscovery:ce});const le=t("tsdav:todo"),pe=e=>({[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(e.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(e.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}),ue=async e=>{const{url:t,props:r,filters:a,timezone:s,depth:o,headers:c,headersToExclude:n,fetchOptions:d={},fetch:h}=e;return T({url:t,body:{"calendar-query":u({_attributes:p([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:a,timezone:s})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:o,headers:v(c,n),fetchOptions:d,fetch:h})},fe=async e=>{const{url:t,props:r,objectUrls:a,filters:s,timezone:o,depth:c,headers:n,headersToExclude:d,fetchOptions:h={},fetch:i}=e;return T({url:t,body:{"calendar-multiget":u({_attributes:p([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:a,filter:s,timezone:o})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:c,headers:v(n,d),fetchOptions:h,fetch:i})},ve=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:c,urlFilter:n=A,useMultiGet:d=!0,headersToExclude:h,fetchOptions:i={},fetch:l}=e;s&&m(s.start,s.end),le(`Fetching todo objects from ${null==t?void 0:t.url}`);const p=["url"];if(!t||!w(t,p)){if(!t)throw new Error("cannot fetchTodos for undefined calendar");throw new Error(`calendar must have ${N(t,p)} before fetchTodos`)}const u=null!=a?a:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VTODO"},...s?{"time-range":{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}],f=(null!=r?r:(await ue({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{...c&&s?pe(s):{}}},filters:u,depth:"1",headers:v(o,h),fetchOptions:i,fetch:l})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(n).map(e=>new URL(e).pathname);let O=[];return f.length>0&&(O=!d||c?await ue({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...c&&s?pe(s):{}}},filters:u,depth:"1",headers:v(o,h),fetchOptions:i,fetch:l}):await fe({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:{...c&&s?pe(s):{}}},objectUrls:f,depth:"1",headers:v(o,h),fetchOptions:i,fetch:l})),O.map(e=>{var r,a,s,o,c,n;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(a=e.props)||void 0===a?void 0:a.getetag}`,data:null!==(c=null===(o=null===(s=e.props)||void 0===s?void 0:s.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==c?c:null===(n=e.props)||void 0===n?void 0:n.calendarData}})},Ae=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:n}=e;if(!r.includes("UID:"))throw new Error("iCalString must contain a UID");return x({url:new URL(a,t.url).href,data:r,headers:v({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:c,fetch:n})},me=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;if(!t.etag)throw new Error("calendarObject must have etag for update - fetch todo first");return g({url:t.url,data:t.data,etag:t.etag,headers:v({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},Oe=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:v(r,a),fetchOptions:s,fetch:o})};var De=Object.freeze({__proto__:null,createTodo:Ae,deleteTodo:Oe,fetchTodos:ve,todoMultiGet:fe,todoQuery:ue,updateTodo:me});const ye=t("tsdav:authHelper"),Ve=(e,t)=>(...r)=>e({...t,...r[0]}),xe=e=>(ye(`Basic auth token generated: ${s.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${s.encode(`${e.username}:${e.password}`)}`}),ge=e=>({authorization:`Bearer ${e.accessToken}`}),Ce=async(e,t,r)=>{const a=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!w(e,a))throw new Error(`Oauth credentials missing: ${N(e,a)}`);const s=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ye(e.tokenUrl),ye(s.toString());const o=null!=r?r:d,c=await o(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"content-length":`${s.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(c.ok){return await c.json()}return ye(`Fetch Oauth tokens failed: ${await c.text()}`),{}},be=async(e,t,r)=>{const a=["refreshToken","clientId","clientSecret","tokenUrl"];if(!w(e,a))throw new Error(`Oauth credentials missing: ${N(e,a)}`);const s=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),o=null!=r?r:d,c=await o(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(c.ok){return await c.json()}return ye(`Refresh access token failed: ${await c.text()}`),{}},we=async(e,t,r)=>{var a;ye("Fetching oauth headers");let s={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(a=e.expiration)&&void 0!==a?a:0))&&(s=await be(e,t,r)):s=await Ce(e,t,r),ye(`Oauth tokens fetched: ${s.access_token}`),{tokens:s,headers:{authorization:`Bearer ${s.access_token}`}}};var Ne=Object.freeze({__proto__:null,defaultParam:Ve,fetchOauthTokens:Ce,getBasicAuthHeaders:xe,getBearerAuthHeaders:ge,getOauthHeaders:we,refreshAccessToken:be});const Se=async e=>{var t;const{serverUrl:r,credentials:a,authMethod:s,defaultAccountType:o,authFunction:c,fetch:n}=e;let d={};switch(s){case"Basic":d=xe(a);break;case"Bearer":d=ge(a);break;case"Oauth":d=(await we(a,void 0,n)).headers;break;case"Digest":d={Authorization:`Digest ${a.digestString}`};break;case"Custom":d=null!==(t=await(null==c?void 0:c(a)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const h=o?await he({account:{serverUrl:r,credentials:a,accountType:o},headers:d,fetch:n}):void 0,i=Ve(x,{url:r,headers:d,fetch:n}),l=Ve(g,{headers:d,url:r,fetch:n}),p=Ve(C,{headers:d,url:r,fetch:n}),u=Ve(V,{headers:d,fetch:n}),f=Ve(T,{headers:d,fetch:n}),v=Ve($,{headers:d,fetch:n}),A=Ve(_,{headers:d,fetch:n}),m=Ve(E,{headers:d,fetch:n}),O=Ve(k,{headers:d,fetch:n}),D=Ve(U,{headers:d,account:h,fetch:n}),b=Ve(G,{headers:d,fetch:n}),w=Ve(J,{headers:d,fetch:n}),N=Ve(W,{headers:d,fetch:n}),S=Ve(K,{headers:d,account:h,fetch:n}),R=Ve(q,{headers:d,account:h,fetch:n}),L=Ve(Y,{headers:d,fetch:n}),Q=Ve(X,{headers:d,fetch:n}),Z=Ve(ee,{headers:d,fetch:n}),ae=Ve(te,{headers:d,fetch:n}),se=Ve(re,{account:h,headers:d,fetch:n}),oe=Ve(j,{headers:d,fetch:n}),ce=Ve(H,{headers:d,fetch:n}),ne=Ve(z,{headers:d,fetch:n});return{davRequest:async e=>{const{init:t,fetch:r,...a}=e,{headers:s,...o}=t;return y({...a,init:{...o,headers:{...d,...s}},fetch:null!=r?r:n})},propfind:u,createAccount:async e=>{const{account:t,headers:s,loadCollections:o,loadObjects:c,fetch:h}=e;return he({account:{serverUrl:r,credentials:a,...t},headers:{...d,...s},loadCollections:o,loadObjects:c,fetch:null!=h?h:n})},createObject:i,updateObject:l,deleteObject:p,calendarQuery:b,addressBookQuery:oe,collectionQuery:f,makeCollection:v,calendarMultiGet:w,makeCalendar:N,syncCollection:A,supportedReportSet:m,isCollectionDirty:O,smartCollectionSync:D,fetchCalendars:S,fetchCalendarUserAddresses:R,fetchCalendarObjects:L,createCalendarObject:Q,updateCalendarObject:Z,deleteCalendarObject:ae,syncCalendars:se,fetchAddressBooks:Ve(B,{account:h,headers:d,fetch:n}),addressBookMultiGet:ce,makeAddressBook:ne,fetchVCards:Ve(P,{headers:d,fetch:n}),createVCard:Ve(M,{headers:d,fetch:n}),updateVCard:Ve(I,{headers:d,fetch:n}),deleteVCard:Ve(F,{headers:d,fetch:n}),todoQuery:Ve(ue,{headers:d,fetch:n}),todoMultiGet:Ve(fe,{headers:d,fetch:n}),fetchTodos:Ve(ve,{headers:d,fetch:n}),createTodo:Ve(Ae,{headers:d,fetch:n}),updateTodo:Ve(me,{headers:d,fetch:n}),deleteTodo:Ve(Oe,{headers:d,fetch:n})}};class Te{constructor(e){var t,r,a;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav",this.authFunction=e.authFunction,this.fetchOptions=null!==(a=e.fetchOptions)&&void 0!==a?a:{},this.fetchOverride=e.fetch}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=xe(this.credentials);break;case"Bearer":this.authHeaders=ge(this.credentials);break;case"Oauth":this.authHeaders=(await we(this.credentials,this.fetchOptions,this.fetchOverride)).headers;break;case"Digest":this.authHeaders={Authorization:`Digest ${this.credentials.digestString}`};break;case"Custom":this.authHeaders=await(null===(e=this.authFunction)||void 0===e?void 0:e.call(this,this.credentials));break;default:throw new Error("Invalid auth method")}this.account=this.accountType?await he({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride}):void 0}async davRequest(e){const{init:t,fetch:r,...a}=e,{headers:s,...o}=t;return y({...a,init:{...o,headers:{...this.authHeaders,...s}},fetchOptions:this.fetchOptions,fetch:null!=r?r:this.fetchOverride})}async createObject(...e){return Ve(x,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateObject(...e){return Ve(g,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteObject(...e){return Ve(C,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async propfind(...e){return Ve(V,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:a,loadObjects:s,fetchOptions:o,fetch:c}=e;return he({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:a,loadObjects:s,fetchOptions:null!=o?o:this.fetchOptions,fetch:null!=c?c:this.fetchOverride})}async collectionQuery(...e){return Ve(T,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCollection(...e){return Ve($,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCollection(...e){return Ve(_,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async supportedReportSet(...e){return Ve(E,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async isCollectionDirty(...e){return Ve(k,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async smartCollectionSync(...e){return Ve(U,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride,account:this.account})(e[0])}async calendarQuery(...e){return Ve(G,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCalendar(...e){return Ve(W,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async calendarMultiGet(...e){return Ve(J,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchCalendars(...e){return Ve(K,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return Ve(q,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return Ve(Y,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createCalendarObject(...e){return Ve(X,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateCalendarObject(...e){return Ve(ee,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteCalendarObject(...e){return Ve(te,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCalendars(...e){return Ve(re,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookQuery(...e){return Ve(j,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookMultiGet(...e){return Ve(H,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeAddressBook(...e){return Ve(z,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchAddressBooks(...e){return Ve(B,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchVCards(...e){return Ve(P,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createVCard(...e){return Ve(M,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateVCard(...e){return Ve(I,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteVCard(...e){return Ve(F,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async todoQuery(...e){return Ve(ue,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async todoMultiGet(...e){return Ve(fe,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchTodos(...e){return Ve(ve,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createTodo(...e){return Ve(Ae,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateTodo(...e){return Ve(me,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteTodo(...e){return Ve(Oe,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}}var $e=Object.freeze({__proto__:null,DAVClient:Te,createDAVClient:Se}),Ee={DAVNamespace:exports.DAVNamespace,DAVNamespaceShort:exports.DAVNamespaceShort,DAVAttributeMap:o,...$e,...b,...R,...ie,...Q,...se,...De,...Ne,...O};exports.DAVAttributeMap=o,exports.DAVClient=Te,exports.addressBookMultiGet=H,exports.addressBookQuery=j,exports.calendarMultiGet=J,exports.calendarQuery=G,exports.cleanupFalsy=u,exports.collectionQuery=T,exports.createAccount=he,exports.createCalendarObject=X,exports.createDAVClient=Se,exports.createObject=x,exports.createTodo=Ae,exports.createVCard=M,exports.davRequest=y,exports.default=Ee,exports.deleteCalendarObject=te,exports.deleteObject=C,exports.deleteTodo=Oe,exports.deleteVCard=F,exports.fetchAddressBooks=B,exports.fetchCalendarObjects=Y,exports.fetchCalendarUserAddresses=q,exports.fetchCalendars=K,exports.fetchOauthTokens=Ce,exports.fetchTodos=ve,exports.fetchVCards=P,exports.freeBusyQuery=ae,exports.getBasicAuthHeaders=xe,exports.getBearerAuthHeaders=ge,exports.getDAVAttribute=p,exports.getOauthHeaders=we,exports.isCollectionDirty=k,exports.makeAddressBook=z,exports.makeCalendar=W,exports.propfind=V,exports.refreshAccessToken=be,exports.smartCollectionSync=U,exports.supportedReportSet=E,exports.syncCalendars=re,exports.syncCollection=_,exports.todoMultiGet=fe,exports.todoQuery=ue,exports.updateCalendarObject=ee,exports.updateObject=g,exports.updateTodo=me,exports.updateVCard=I,exports.urlContains=l,exports.urlEquals=i; diff --git a/dist/tsdav.min.js b/dist/tsdav.min.js index 3a57b378..887b1d6d 100644 --- a/dist/tsdav.min.js +++ b/dist/tsdav.min.js @@ -1,2 +1,2 @@ var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function r(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){var r=!1;try{r=this instanceof e}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var n="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}var o=i,s=a;function c(e){if(o===setTimeout)return setTimeout(e,0);if((o===i||!o)&&setTimeout)return o=setTimeout,setTimeout(e,0);try{return o(e,0)}catch(t){try{return o.call(null,e,0)}catch(t){return o.call(this,e,0)}}}"function"==typeof n.setTimeout&&(o=setTimeout),"function"==typeof n.clearTimeout&&(s=clearTimeout);var u,l=[],h=!1,d=-1;function f(){h&&u&&(h=!1,u.length?l=u.concat(l):d=-1,l.length&&p())}function p(){if(!h){var e=c(f);h=!0;for(var t=l.length;t;){for(u=l,l=[];++d1)for(var r=1;r=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return x=function(s,c){c=c||{};var u=typeof s;if("string"===u&&s.length>0)return function(o){if((o=String(o)).length>100)return;var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!s)return;var c=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*a;case"weeks":case"week":case"w":return c*i;case"days":case"day":case"d":return c*n;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(s);if("number"===u&&isFinite(s))return c.long?function(i){var a=Math.abs(i);if(a>=n)return o(i,a,n,"day");if(a>=r)return o(i,a,r,"hour");if(a>=t)return o(i,a,t,"minute");if(a>=e)return o(i,a,e,"second");return i+" ms"}(s):function(i){var a=Math.abs(i);if(a>=n)return Math.round(i/n)+"d";if(a>=r)return Math.round(i/r)+"h";if(a>=t)return Math.round(i/t)+"m";if(a>=e)return Math.round(i/e)+"s";return i+"ms"}(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))}}var U,P=(N||(N=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))}),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&"env"in L&&(e=L.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=(S||(S=1,F=function(e){function t(e){let n,i,a,o=null;function s(...e){if(!s.enabled)return;const r=s,i=Number(new Date),a=i-(n||i);r.diff=a,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,i)=>{if("%%"===n)return"%";o++;const a=t.formatters[i];if("function"==typeof a){const t=e[o];n=a.call(r,t),e.splice(o,1),o--}return n}),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=r,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,a=t.enabled(e)),a),set:e=>{o=e}}),"function"==typeof t.init&&t.init(s),s}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e,t){let r=0,n=0,i=-1,a=0;for(;r"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(n(e,r))return!1;for(const r of t.names)if(n(e,r))return!0;return!1},t.humanize=I(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t>18&63]+$[e>>12&63]+$[e>>6&63]+$[63&e]}function G(e,t,r){for(var n,i=[],a=t;ac?c:s+o));return 1===n?(t=e[r-1],i+=$[t>>2],i+=$[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=$[t>>10],i+=$[t>>4&63],i+=$[t<<2&63],i+="="),a.push(i),a.join("")}function Q(e,t,r,n,i){var a,o,s=8*i-n-1,c=(1<>1,l=-7,h=r?i-1:0,d=r?-1:1,f=e[t+h];for(h+=d,a=f&(1<<-l)-1,f>>=-l,l+=s;l>0;a=256*a+e[t+h],h+=d,l-=8);for(o=a&(1<<-l)-1,a>>=-l,l+=n;l>0;o=256*o+e[t+h],h+=d,l-=8);if(0===a)a=1-u;else{if(a===c)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),a-=u}return(f?-1:1)*o*Math.pow(2,a-n)}function X(e,t,r,n,i,a){var o,s,c,u=8*a-i-1,l=(1<>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:a-1,p=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(o++,c/=2),o+h>=l?(s=0,o=l):o+h>=1?(s=(t*c-1)*Math.pow(2,i),o+=h):(s=t*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;e[r+f]=255&s,f+=p,s/=256,i-=8);for(o=o<0;e[r+f]=255&o,f+=p,o/=256,u-=8);e[r+f-p]|=128*y}var Z={}.toString,J=Array.isArray||function(e){return"[object Array]"==Z.call(e)};function ee(){return re.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function te(e,t){if(ee()=ee())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ee().toString(16)+" bytes");return 0|e}function ce(e){return!(null==e||!e._isBuffer)}function ue(e,t){if(ce(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Ue(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Pe(e).length;default:if(n)return Ue(e).length;t=(""+t).toLowerCase(),n=!0}}function le(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return _e(this,t,r);case"utf8":case"utf-8":return Ee(this,t,r);case"ascii":return Te(this,t,r);case"latin1":case"binary":return Oe(this,t,r);case"base64":return we(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ce(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function he(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function de(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=re.from(t,n)),ce(t))return 0===t.length?-1:fe(e,t,r,n,i);if("number"==typeof t)return t&=255,re.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):fe(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function fe(e,t,r,n,i){var a,o=1,s=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;o=2,s/=2,c/=2,r/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){var l=-1;for(a=r;as&&(r=s-c),a=r;a>=0;a--){for(var h=!0,d=0;di&&(n=i):n=i;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;o>8,i=r%256,a.push(i),a.push(n);return a}(t,e.length-r),e,r,n)}function we(e,t,r){return 0===t&&r===e.length?W(e):W(e.slice(t,r))}function Ee(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:u>223?3:u>191?2:1;if(i+h<=r)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(a=e[i+1]))&&(c=(31&u)<<6|63&a)>127&&(l=c);break;case 3:a=e[i+1],o=e[i+2],128==(192&a)&&128==(192&o)&&(c=(15&u)<<12|(63&a)<<6|63&o)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:a=e[i+1],o=e[i+2],s=e[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(c=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=h}return function(e){var t=e.length;if(t<=Ae)return String.fromCharCode.apply(String,e);var r="",n=0;for(;n0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},re.prototype.compare=function(e,t,r,n,i){if(!ce(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var a=(i>>>=0)-(n>>>=0),o=(r>>>=0)-(t>>>=0),s=Math.min(a,o),c=this.slice(n,i),u=e.slice(t,r),l=0;li)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return pe(this,e,t,r);case"utf8":case"utf-8":return ye(this,e,t,r);case"ascii":return ge(this,e,t,r);case"latin1":case"binary":return me(this,e,t,r);case"base64":return ve(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return be(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},re.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ae=4096;function Te(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",a=t;ar)throw new RangeError("Trying to access beyond buffer length")}function xe(e,t,r,n,i,a){if(!ce(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function Re(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function Fe(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function Se(e,t,r,n,i,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Ne(e,t,r,n,i){return i||Se(e,0,r,4),X(e,t,r,n,23,4),r+4}function Le(e,t,r,n,i){return i||Se(e,0,r,8),X(e,t,r,n,52,8),r+8}re.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},re.prototype.readUInt8=function(e,t){return t||De(e,1,this.length),this[e]},re.prototype.readUInt16LE=function(e,t){return t||De(e,2,this.length),this[e]|this[e+1]<<8},re.prototype.readUInt16BE=function(e,t){return t||De(e,2,this.length),this[e]<<8|this[e+1]},re.prototype.readUInt32LE=function(e,t){return t||De(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},re.prototype.readUInt32BE=function(e,t){return t||De(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},re.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||De(e,t,this.length);for(var n=this[e],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*t)),n},re.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||De(e,t,this.length);for(var n=t,i=1,a=this[e+--n];n>0&&(i*=256);)a+=this[e+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},re.prototype.readInt8=function(e,t){return t||De(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},re.prototype.readInt16LE=function(e,t){t||De(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},re.prototype.readInt16BE=function(e,t){t||De(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},re.prototype.readInt32LE=function(e,t){return t||De(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},re.prototype.readInt32BE=function(e,t){return t||De(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},re.prototype.readFloatLE=function(e,t){return t||De(e,4,this.length),Q(this,e,!0,23,4)},re.prototype.readFloatBE=function(e,t){return t||De(e,4,this.length),Q(this,e,!1,23,4)},re.prototype.readDoubleLE=function(e,t){return t||De(e,8,this.length),Q(this,e,!0,52,8)},re.prototype.readDoubleBE=function(e,t){return t||De(e,8,this.length),Q(this,e,!1,52,8)},re.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||xe(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+i]=e/a&255;return t+r},re.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,1,255,0),re.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},re.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,2,65535,0),re.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Re(this,e,t,!0),t+2},re.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,2,65535,0),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Re(this,e,t,!1),t+2},re.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,4,4294967295,0),re.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Fe(this,e,t,!0),t+4},re.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,4,4294967295,0),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Fe(this,e,t,!1),t+4},re.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);xe(this,e,t,r,i-1,-i)}var a=0,o=1,s=0;for(this[t]=255&e;++a=0&&(o*=256);)e<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(e/o|0)-s&255;return t+r},re.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,1,127,-128),re.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},re.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,2,32767,-32768),re.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Re(this,e,t,!0),t+2},re.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,2,32767,-32768),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Re(this,e,t,!1),t+2},re.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,4,2147483647,-2147483648),re.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Fe(this,e,t,!0),t+4},re.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||xe(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Fe(this,e,t,!1),t+4},re.prototype.writeFloatLE=function(e,t,r){return Ne(this,e,t,!0,r)},re.prototype.writeFloatBE=function(e,t,r){return Ne(this,e,t,!1,r)},re.prototype.writeDoubleLE=function(e,t,r){return Le(this,e,t,!0,r)},re.prototype.writeDoubleBE=function(e,t,r){return Le(this,e,t,!1,r)},re.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(a<1e3||!re.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function Pe(e){return function(e){var t,r,n,i,a,o;Y||z();var s=e.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===e[s-2]?2:"="===e[s-1]?1:0,o=new H(3*s/4-a),n=a>0?s-4:s;var c=0;for(t=0,r=0;t>16&255,o[c++]=i>>8&255,o[c++]=255&i;return 2===a?(i=K[e.charCodeAt(t)]<<2|K[e.charCodeAt(t+1)]>>4,o[c++]=255&i):1===a&&(i=K[e.charCodeAt(t)]<<10|K[e.charCodeAt(t+1)]<<4|K[e.charCodeAt(t+2)]>>2,o[c++]=i>>8&255,o[c++]=255&i),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(ke,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function je(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function Be(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}var Ve,Me,$e={};function Ke(){}function He(){He.init.call(this)}function Ye(e){return void 0===e._maxListeners?He.defaultMaxListeners:e._maxListeners}function ze(e,t,r,n){var i,a,o,s;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),o=a[t]):(a=e._events=new Ke,e._eventsCount=0),o){if("function"==typeof o?o=a[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=Ye(e))&&i>0&&o.length>i){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,s=c,"function"==typeof console.warn?console.warn(s):console.log(s)}}else o=a[t]=r,++e._eventsCount;return e}function qe(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function Ge(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function We(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Ke.prototype=Object.create(null),He.EventEmitter=He,He.usingDomains=!1,He.prototype.domain=void 0,He.prototype._events=void 0,He.prototype._maxListeners=void 0,He.defaultMaxListeners=10,He.init=function(){this.domain=null,He.usingDomains&&(!Ve.active||this instanceof Ve.Domain||(this.domain=Ve.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Ke,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},He.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},He.prototype.getMaxListeners=function(){return Ye(this)},He.prototype.emit=function(e){var t,r,n,i,a,o,s,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(s=this.domain,c){if(t=arguments[1],!s){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=s,t.domainThrown=!1,s.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,i=We(e,n),a=0;a0;)if(r[a]===t||r[a].listener&&r[a].listener===t){o=r[a].listener,i=a;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new Ke,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n0?Reflect.ownKeys(this._events):[]},Me="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e};var Qe=/%[sdj%]/g;function Xe(e){if(!ut(e)){for(var t=[],r=0;r=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),o=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),st(t)?r.showHidden=t:t&&function(e,t){if(!t||!dt(t))return e;var r=Object.keys(t),n=r.length;for(;n--;)e[r[n]]=t[r[n]]}(r,t),lt(r.showHidden)&&(r.showHidden=!1),lt(r.depth)&&(r.depth=2),lt(r.colors)&&(r.colors=!1),lt(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=rt),it(r,e,r.depth)}function rt(e,t){var r=tt.styles[t];return r?"["+tt.colors[r][0]+"m"+e+"["+tt.colors[r][1]+"m":e}function nt(e,t){return e}function it(e,t,r){if(e.customInspect&&t&&yt(t.inspect)&&t.inspect!==tt&&(!t.constructor||t.constructor.prototype!==t)){var n=t.inspect(r,e);return ut(n)||(n=it(e,n,r)),n}var i=function(e,t){if(lt(t))return e.stylize("undefined","undefined");if(ut(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(n=t,"number"==typeof n)return e.stylize(""+t,"number");var n;if(st(t))return e.stylize(""+t,"boolean");if(ct(t))return e.stylize("null","null")}(e,t);if(i)return i;var a=Object.keys(t),o=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),pt(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return at(t);if(0===a.length){if(yt(t)){var s=t.name?": "+t.name:"";return e.stylize("[Function"+s+"]","special")}if(ht(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(ft(t))return e.stylize(Date.prototype.toString.call(t),"date");if(pt(t))return at(t)}var c,u,l="",h=!1,d=["{","}"];(c=t,Array.isArray(c)&&(h=!0,d=["[","]"]),yt(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return ht(t)&&(l=" "+RegExp.prototype.toString.call(t)),ft(t)&&(l=" "+Date.prototype.toUTCString.call(t)),pt(t)&&(l=" "+at(t)),0!==a.length||h&&0!=t.length?r<0?ht(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=h?function(e,t,r,n,i){for(var a=[],o=0,s=t.length;o60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(u,l,d)):d[0]+l+d[1]}function at(e){return"["+Error.prototype.toString.call(e)+"]"}function ot(e,t,r,n,i,a){var o,s,c;if((c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(s=e.stylize("[Setter]","special")),mt(n,i)||(o="["+i+"]"),s||(e.seen.indexOf(c.value)<0?(s=ct(r)?it(e,c.value,null):it(e,c.value,r-1)).indexOf("\n")>-1&&(s=a?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),lt(o)){if(a&&i.match(/^\d+$/))return s;(o=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+s}function st(e){return"boolean"==typeof e}function ct(e){return null===e}function ut(e){return"string"==typeof e}function lt(e){return void 0===e}function ht(e){return dt(e)&&"[object RegExp]"===gt(e)}function dt(e){return"object"==typeof e&&null!==e}function ft(e){return dt(e)&&"[object Date]"===gt(e)}function pt(e){return dt(e)&&("[object Error]"===gt(e)||e instanceof Error)}function yt(e){return"function"==typeof e}function gt(e){return Object.prototype.toString.call(e)}function mt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vt(){this.head=null,this.tail=null,this.length=0}tt.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},tt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},vt.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},vt.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},vt.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},vt.prototype.clear=function(){this.head=this.tail=null,this.length=0},vt.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},vt.prototype.concat=function(e){if(0===this.length)return re.alloc(0);if(1===this.length)return this.head.data;for(var t=re.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t};var bt=re.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function wt(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),function(e){if(e&&!bt(e))throw new Error("Unknown encoding: "+e)}(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=At;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Tt;break;default:return void(this.write=Et)}this.charBuffer=new re(6),this.charReceived=0,this.charLength=0}function Et(e){return e.toString(this.encoding)}function At(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function Tt(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}wt.prototype.write=function(e){for(var t="";this.charLength;){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var n=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,n),n-=this.charReceived);var i;n=(t+=e.toString(this.encoding,0,n)).length-1;if((i=t.charCodeAt(n))>=55296&&i<=56319){var a=this.surrogateSize;return this.charLength+=a,this.charReceived+=a,this.charBuffer.copy(this.charBuffer,a,0,a),e.copy(this.charBuffer,0,0,a),t.substring(0,n)}return t},wt.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t},wt.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;t+=n.slice(0,r).toString(i)}return t},Ct.ReadableState=_t;var Ot=function(e){if(lt(Je)&&(Je=L.env.NODE_DEBUG||""),e=e.toUpperCase(),!et[e])if(new RegExp("\\b"+e+"\\b","i").test(Je)){et[e]=function(){var t=Xe.apply(null,arguments);console.error("%s %d: %s",e,0,t)}}else et[e]=function(){};return et[e]}("stream");function _t(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof er&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new vt,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(this.decoder=new wt(e.encoding),this.encoding=e.encoding)}function Ct(e){if(!(this instanceof Ct))return new Ct(e);this._readableState=new _t(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),He.call(this)}function Dt(e,t,r,n,i){var a=function(e,t){var r=null;re.isBuffer(t)||"string"==typeof t||null==t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(t,r);if(a)e.emit("error",a);else if(null===r)t.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,Ft(e)}(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!i){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var c;!t.decoder||i||n||(r=t.decoder.write(r),c=!t.objectMode&&0===r.length),i||(t.reading=!1),c||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&Ft(e))),function(e,t){t.readingMore||(t.readingMore=!0,y(Nt,e,t))}(e,t)}else i||(t.reading=!1);return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=xt?e=xt:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function Ft(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(Ot("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?y(St,e):St(e))}function St(e){Ot("emit readable"),e.emit("readable"),It(e)}function Nt(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;ea.length?a.length:e;if(o===a.length?i+=a:i+=a.slice(0,e),0===(e-=o)){o===a.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=a.slice(o));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=re.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var a=n.data,o=e>a.length?a.length:e;if(a.copy(r,r.length-e,0,o),0===(e-=o)){o===a.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=a.slice(o));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function Pt(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,y(jt,t,e))}function jt(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function Bt(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return Ot("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?Pt(this):Ft(this),null;if(0===(e=Rt(e,t))&&t.ended)return 0===t.length&&Pt(this),null;var n,i=t.needReadable;return Ot("need readable",i),(0===t.length||t.length-e0?Ut(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&Pt(this)),null!==n&&this.emit("data",n),n},Ct.prototype._read=function(e){this.emit("error",new Error("not implemented"))},Ct.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e)}n.pipesCount+=1,Ot("pipe count=%d opts=%j",n.pipesCount,t);var i=!t||!1!==t.end?o:u;function a(e){Ot("onunpipe"),e===r&&u()}function o(){Ot("onend"),e.end()}n.endEmitted?y(i):r.once("end",i),e.on("unpipe",a);var s=function(e){return function(){var t=e._readableState;Ot("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,It(e))}}(r);e.on("drain",s);var c=!1;function u(){Ot("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),e.removeListener("drain",s),e.removeListener("error",d),e.removeListener("unpipe",a),r.removeListener("end",o),r.removeListener("end",u),r.removeListener("data",h),c=!0,!n.awaitDrain||e._writableState&&!e._writableState.needDrain||s()}var l=!1;function h(t){Ot("ondata"),l=!1,!1!==e.write(t)||l||((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==Bt(n.pipes,e))&&!c&&(Ot("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function d(t){var r;Ot("onerror",t),g(),e.removeListener("error",d),0===(r="error",e.listeners(r).length)&&e.emit("error",t)}function f(){e.removeListener("finish",p),g()}function p(){Ot("onfinish"),e.removeListener("close",f),g()}function g(){Ot("unpipe"),r.unpipe(e)}return r.on("data",h),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",d),e.once("close",f),e.once("finish",p),e.emit("pipe",r),n.flowing||(Ot("pipe resume"),r.resume()),e},Ct.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this)),this;if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Kt.prototype._write=function(e,t,r){r(new Error("not implemented"))},Kt.prototype._writev=null,Kt.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,Wt(e,t),r&&(t.finished?y(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Me(er,Ct);for(var Xt=Object.keys(Kt.prototype),Zt=0;Zt"===a?(C(n,"onsgmldeclaration",n.sgmlDecl),n.sgmlDecl="",n.state=T.TEXT):g(a)?(n.state=T.SGML_DECL_QUOTED,n.sgmlDecl+=a):n.sgmlDecl+=a;continue;case T.SGML_DECL_QUOTED:a===n.q&&(n.state=T.SGML_DECL,n.q=""),n.sgmlDecl+=a;continue;case T.DOCTYPE:">"===a?(n.state=T.TEXT,C(n,"ondoctype",n.doctype),n.doctype=!0):(n.doctype+=a,"["===a?n.state=T.DOCTYPE_DTD:g(a)&&(n.state=T.DOCTYPE_QUOTED,n.q=a));continue;case T.DOCTYPE_QUOTED:n.doctype+=a,a===n.q&&(n.q="",n.state=T.DOCTYPE);continue;case T.DOCTYPE_DTD:"]"===a?(n.doctype+=a,n.state=T.DOCTYPE):"<"===a?(n.state=T.OPEN_WAKA,n.startTagPosition=n.position):g(a)?(n.doctype+=a,n.state=T.DOCTYPE_DTD_QUOTED,n.q=a):n.doctype+=a;continue;case T.DOCTYPE_DTD_QUOTED:n.doctype+=a,a===n.q&&(n.state=T.DOCTYPE_DTD,n.q="");continue;case T.COMMENT:"-"===a?n.state=T.COMMENT_ENDING:n.comment+=a;continue;case T.COMMENT_ENDING:"-"===a?(n.state=T.COMMENT_ENDED,n.comment=x(n.opt,n.comment),n.comment&&C(n,"oncomment",n.comment),n.comment=""):(n.comment+="-"+a,n.state=T.COMMENT);continue;case T.COMMENT_ENDED:">"!==a?(S(n,"Malformed comment"),n.comment+="--"+a,n.state=T.COMMENT):n.doctype&&!0!==n.doctype?n.state=T.DOCTYPE_DTD:n.state=T.TEXT;continue;case T.CDATA:for(c=i-1;a&&"]"!==a;)(a=B(t,i++))&&n.trackPosition&&(n.position++,"\n"===a?(n.line++,n.column=0):n.column++);n.cdata+=t.substring(c,i-1),"]"===a&&(n.state=T.CDATA_ENDING);continue;case T.CDATA_ENDING:"]"===a?n.state=T.CDATA_ENDING_2:(n.cdata+="]"+a,n.state=T.CDATA);continue;case T.CDATA_ENDING_2:">"===a?(n.cdata&&C(n,"oncdata",n.cdata),C(n,"onclosecdata"),n.cdata="",n.state=T.TEXT):"]"===a?n.cdata+="]":(n.cdata+="]]"+a,n.state=T.CDATA);continue;case T.PROC_INST:"?"===a?n.state=T.PROC_INST_ENDING:y(a)?n.state=T.PROC_INST_BODY:n.procInstName+=a;continue;case T.PROC_INST_BODY:if(!n.procInstBody&&y(a))continue;"?"===a?n.state=T.PROC_INST_ENDING:n.procInstBody+=a;continue;case T.PROC_INST_ENDING:">"===a?(C(n,"onprocessinginstruction",{name:n.procInstName,body:n.procInstBody}),n.procInstName=n.procInstBody="",n.state=T.TEXT):(n.procInstBody+="?"+a,n.state=T.PROC_INST_BODY);continue;case T.OPEN_TAG:v(d,a)?n.tagName+=a:(N(n),">"===a?I(n):"/"===a?n.state=T.OPEN_TAG_SLASH:(y(a)||S(n,"Invalid character in tag name"),n.state=T.ATTRIB));continue;case T.OPEN_TAG_SLASH:">"===a?(I(n,!0),U(n)):(S(n,"Forward-slash in opening tag not followed by >"),n.state=T.ATTRIB);continue;case T.ATTRIB:if(y(a))continue;">"===a?I(n):"/"===a?n.state=T.OPEN_TAG_SLASH:v(h,a)?(n.attribName=a,n.attribValue="",n.state=T.ATTRIB_NAME):S(n,"Invalid attribute name");continue;case T.ATTRIB_NAME:"="===a?n.state=T.ATTRIB_VALUE:">"===a?(S(n,"Attribute without value"),n.attribValue=n.attribName,k(n),I(n)):y(a)?n.state=T.ATTRIB_NAME_SAW_WHITE:v(d,a)?n.attribName+=a:S(n,"Invalid attribute name");continue;case T.ATTRIB_NAME_SAW_WHITE:if("="===a)n.state=T.ATTRIB_VALUE;else{if(y(a))continue;S(n,"Attribute without value"),n.tag.attributes[n.attribName]="",n.attribValue="",C(n,"onattribute",{name:n.attribName,value:""}),n.attribName="",">"===a?I(n):v(h,a)?(n.attribName=a,n.state=T.ATTRIB_NAME):(S(n,"Invalid attribute name"),n.state=T.ATTRIB)}continue;case T.ATTRIB_VALUE:if(y(a))continue;g(a)?(n.q=a,n.state=T.ATTRIB_VALUE_QUOTED):(n.opt.unquotedAttributeValues||R(n,"Unquoted attribute value"),n.state=T.ATTRIB_VALUE_UNQUOTED,n.attribValue=a);continue;case T.ATTRIB_VALUE_QUOTED:if(a!==n.q){"&"===a?n.state=T.ATTRIB_VALUE_ENTITY_Q:n.attribValue+=a;continue}k(n),n.q="",n.state=T.ATTRIB_VALUE_CLOSED;continue;case T.ATTRIB_VALUE_CLOSED:y(a)?n.state=T.ATTRIB:">"===a?I(n):"/"===a?n.state=T.OPEN_TAG_SLASH:v(h,a)?(S(n,"No whitespace between attributes"),n.attribName=a,n.attribValue="",n.state=T.ATTRIB_NAME):S(n,"Invalid attribute name");continue;case T.ATTRIB_VALUE_UNQUOTED:if(!m(a)){"&"===a?n.state=T.ATTRIB_VALUE_ENTITY_U:n.attribValue+=a;continue}k(n),">"===a?I(n):n.state=T.ATTRIB;continue;case T.CLOSE_TAG:if(n.tagName)">"===a?U(n):v(d,a)?n.tagName+=a:n.script?(n.script+=""===a?U(n):S(n,"Invalid characters in closing tag");continue;case T.TEXT_ENTITY:case T.ATTRIB_VALUE_ENTITY_Q:case T.ATTRIB_VALUE_ENTITY_U:var l,w;switch(n.state){case T.TEXT_ENTITY:l=T.TEXT,w="textNode";break;case T.ATTRIB_VALUE_ENTITY_Q:l=T.ATTRIB_VALUE_QUOTED,w="attribValue";break;case T.ATTRIB_VALUE_ENTITY_U:l=T.ATTRIB_VALUE_UNQUOTED,w="attribValue"}if(";"===a){var E=P(n);n.opt.unparsedEntities&&!Object.values(e.XML_ENTITIES).includes(E)?(n.entity="",n.state=l,n.write(E)):(n[w]+=E,n.entity="",n.state=l)}else v(n.entity.length?p:f,a)?n.entity+=a:(S(n,"Invalid character in entity name"),n[w]+="&"+n.entity+a,n.entity="",n.state=l);continue;default:throw new Error(n,"Unknown state: "+n.state)}return n.position>=n.bufferCheckPosition&&function(t){for(var n=Math.max(e.MAX_BUFFER_LENGTH,10),i=0,a=0,o=r.length;an)switch(r[a]){case"textNode":D(t);break;case"cdata":C(t,"oncdata",t.cdata),t.cdata="";break;case"script":C(t,"onscript",t.script),t.script="";break;default:R(t,"Max buffer length exceeded: "+r[a])}i=Math.max(i,s)}var c=e.MAX_BUFFER_LENGTH-i;t.bufferCheckPosition=c+t.position}(n),n} -/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){var e;D(e=this),""!==e.cdata&&(C(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(C(e,"onscript",e.script),e.script="")}};try{t=Tr.Stream}catch(e){t=function(){}}t||(t=function(){});var i=e.EVENTS.filter(function(e){return"error"!==e&&"end"!==e});function a(e,r){if(!(this instanceof a))return new a(e,r);t.apply(this),this._parser=new n(e,r),this.writable=!0,this.readable=!0;var o=this;this._parser.onend=function(){o.emit("end")},this._parser.onerror=function(e){o.emit("error",e),o._parser.error=null},this._decoder=null,i.forEach(function(e){Object.defineProperty(o,"on"+e,{get:function(){return o._parser["on"+e]},set:function(t){if(!t)return o.removeAllListeners(e),o._parser["on"+e]=t,t;o.on(e,t)},enumerable:!0,configurable:!1})})}a.prototype=Object.create(t.prototype,{constructor:{value:a}}),a.prototype.write=function(e){return"function"==typeof re.isBuffer&&re.isBuffer(e)&&(this._decoder||(this._decoder=new TextDecoder("utf8")),e=this._decoder.decode(e,{stream:!0})),this._parser.write(e.toString()),this.emit("data",e),!0},a.prototype.end=function(e){if(e&&e.length&&this.write(e),this._decoder){var t=this._decoder.decode();t&&(this._parser.write(t),this.emit("data",t))}return this._parser.end(),!0},a.prototype.on=function(e,r){var n=this;return n._parser["on"+e]||-1===i.indexOf(e)||(n._parser["on"+e]=function(){var t=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),n.emit.apply(n,t)}),t.prototype.on.call(n,e,r)};var o="[CDATA[",s="DOCTYPE",c="http://www.w3.org/XML/1998/namespace",u="http://www.w3.org/2000/xmlns/",l={xml:c,xmlns:u},h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,d=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,f=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,p=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function y(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function g(e){return'"'===e||"'"===e}function m(e){return">"===e||y(e)}function v(e,t){return e.test(t)}function b(e,t){return!v(e,t)}var w,E,A,T=0;for(var O in e.STATE={BEGIN:T++,BEGIN_WHITESPACE:T++,TEXT:T++,TEXT_ENTITY:T++,OPEN_WAKA:T++,SGML_DECL:T++,SGML_DECL_QUOTED:T++,DOCTYPE:T++,DOCTYPE_QUOTED:T++,DOCTYPE_DTD:T++,DOCTYPE_DTD_QUOTED:T++,COMMENT_STARTING:T++,COMMENT:T++,COMMENT_ENDING:T++,COMMENT_ENDED:T++,CDATA:T++,CDATA_ENDING:T++,CDATA_ENDING_2:T++,PROC_INST:T++,PROC_INST_BODY:T++,PROC_INST_ENDING:T++,OPEN_TAG:T++,OPEN_TAG_SLASH:T++,ATTRIB:T++,ATTRIB_NAME:T++,ATTRIB_NAME_SAW_WHITE:T++,ATTRIB_VALUE:T++,ATTRIB_VALUE_QUOTED:T++,ATTRIB_VALUE_CLOSED:T++,ATTRIB_VALUE_UNQUOTED:T++,ATTRIB_VALUE_ENTITY_Q:T++,ATTRIB_VALUE_ENTITY_U:T++,CLOSE_TAG:T++,CLOSE_TAG_SAW_WHITE:T++,SCRIPT:T++,SCRIPT_ENDING:T++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(t){var r=e.ENTITIES[t],n="number"==typeof r?String.fromCharCode(r):r;e.ENTITIES[t]=n}),e.STATE)e.STATE[e.STATE[O]]=O;function _(e,t,r){e[t]&&e[t](r)}function C(e,t,r){e.textNode&&D(e),_(e,t,r)}function D(e){e.textNode=x(e.opt,e.textNode),e.textNode&&_(e,"ontext",e.textNode),e.textNode=""}function x(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g," ")),t}function R(e,t){return D(e),e.trackPosition&&(t+="\nLine: "+e.line+"\nColumn: "+e.column+"\nChar: "+e.c),t=new Error(t),e.error=t,_(e,"onerror",t),e}function F(e){return e.sawRoot&&!e.closedRoot&&S(e,"Unclosed root tag"),e.state!==T.BEGIN&&e.state!==T.BEGIN_WHITESPACE&&e.state!==T.TEXT&&R(e,"Unexpected end"),D(e),e.c="",e.closed=!0,_(e,"onend"),n.call(e,e.strict,e.opt),e}function S(e,t){if("object"!=typeof e||!(e instanceof n))throw new Error("bad call to strictFail");e.strict&&R(e,t)}function N(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,r=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(r.ns=t.ns),e.attribList.length=0,C(e,"onopentagstart",r)}function L(e,t){var r=e.indexOf(":")<0?["",e]:e.split(":"),n=r[0],i=r[1];return t&&"xmlns"===e&&(n="xmlns",i=""),{prefix:n,local:i}}function k(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),-1!==e.attribList.indexOf(e.attribName)||e.tag.attributes.hasOwnProperty(e.attribName))e.attribName=e.attribValue="";else{if(e.opt.xmlns){var t=L(e.attribName,!0),r=t.prefix,n=t.local;if("xmlns"===r)if("xml"===n&&e.attribValue!==c)S(e,"xml: prefix must be bound to "+c+"\nActual: "+e.attribValue);else if("xmlns"===n&&e.attribValue!==u)S(e,"xmlns: prefix must be bound to "+u+"\nActual: "+e.attribValue);else{var i=e.tag,a=e.tags[e.tags.length-1]||e;i.ns===a.ns&&(i.ns=Object.create(a.ns)),i.ns[n]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,C(e,"onattribute",{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=""}}function I(e,t){if(e.opt.xmlns){var r=e.tag,n=L(e.tagName);r.prefix=n.prefix,r.local=n.local,r.uri=r.ns[n.prefix]||"",r.prefix&&!r.uri&&(S(e,"Unbound namespace prefix: "+JSON.stringify(e.tagName)),r.uri=n.prefix);var i=e.tags[e.tags.length-1]||e;r.ns&&i.ns!==r.ns&&Object.keys(r.ns).forEach(function(t){C(e,"onopennamespace",{prefix:t,uri:r.ns[t]})});for(var a=0,o=e.attribList.length;a",e.tagName="",void(e.state=T.SCRIPT);C(e,"onscript",e.script),e.script=""}var t=e.tags.length,r=e.tagName;e.strict||(r=r[e.looseCase]());for(var n=r;t--&&e.tags[t].name!==n;)S(e,"Unexpected close tag");if(t<0)return S(e,"Unmatched closing tag: "+e.tagName),e.textNode+="",void(e.state=T.TEXT);e.tagName=r;for(var i=e.tags.length;i-- >t;){var a=e.tag=e.tags.pop();e.tagName=e.tag.name,C(e,"onclosetag",e.tagName);var o={};for(var s in a.ns)o[s]=a.ns[s];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&a.ns!==c.ns&&Object.keys(a.ns).forEach(function(t){var r=a.ns[t];C(e,"onclosenamespace",{prefix:t,uri:r})})}0===t&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName="",e.attribList.length=0,e.state=T.TEXT}function P(e){var t,r=e.entity,n=r.toLowerCase(),i="";return e.ENTITIES[r]?e.ENTITIES[r]:e.ENTITIES[n]?e.ENTITIES[n]:("#"===(r=n).charAt(0)&&("x"===r.charAt(1)?(r=r.slice(2),i=(t=parseInt(r,16)).toString(16)):(r=r.slice(1),i=(t=parseInt(r,10)).toString(10))),r=r.replace(/^0+/,""),isNaN(t)||i.toLowerCase()!==r||t<0||t>1114111?(S(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function j(e,t){"<"===t?(e.state=T.OPEN_WAKA,e.startTagPosition=e.position):y(t)||(S(e,"Non-whitespace before first tag."),e.textNode=t,e.state=T.TEXT)}function B(e,t){var r="";return t1114111||E(o)!==o)throw RangeError("Invalid code point: "+o);o<=65535?r.push(o):(e=55296+((o-=65536)>>10),t=o%1024+56320,r.push(e,t)),(n+1===i||r.length>16384)&&(a+=w.apply(null,r),r.length=0)}return a},Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:A,configurable:!0,writable:!0}):String.fromCodePoint=A)}($e)),$e}function _r(){return lr?ur:(lr=1,ur={isArray:function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)}})}function Cr(){if(dr)return hr;dr=1;var e=_r().isArray;return hr={copyOptions:function(e){var t,r={};for(t in e)e.hasOwnProperty(t)&&(r[t]=e[t]);return r},ensureFlagExists:function(e,t){e in t&&"boolean"==typeof t[e]||(t[e]=!1)},ensureSpacesExists:function(e){(!("spaces"in e)||"number"!=typeof e.spaces&&"string"!=typeof e.spaces)&&(e.spaces=0)},ensureAlwaysArrayExists:function(t){"alwaysArray"in t&&("boolean"==typeof t.alwaysArray||e(t.alwaysArray))||(t.alwaysArray=!1)},ensureKeyExists:function(e,t){e+"Key"in t&&"string"==typeof t[e+"Key"]||(t[e+"Key"]=t.compact?"_"+e:e)},checkFnExists:function(e,t){return e+"Fn"in t}}}function Dr(){if(pr)return fr;pr=1;var e,t,r=Or(),n=Cr(),i=_r().isArray;function a(e){var t=Number(e);if(!isNaN(t))return t;var r=e.toLowerCase();return"true"===r||"false"!==r&&e}function o(r,n){var a;if(e.compact){if(!t[e[r+"Key"]]&&(i(e.alwaysArray)?-1!==e.alwaysArray.indexOf(e[r+"Key"]):e.alwaysArray)&&(t[e[r+"Key"]]=[]),t[e[r+"Key"]]&&!i(t[e[r+"Key"]])&&(t[e[r+"Key"]]=[t[e[r+"Key"]]]),r+"Fn"in e&&"string"==typeof n&&(n=e[r+"Fn"](n,t)),"instruction"===r&&("instructionFn"in e||"instructionNameFn"in e))for(a in n)if(n.hasOwnProperty(a))if("instructionFn"in e)n[a]=e.instructionFn(n[a],a,t);else{var o=n[a];delete n[a],n[e.instructionNameFn(a,o,t)]=o}i(t[e[r+"Key"]])?t[e[r+"Key"]].push(n):t[e[r+"Key"]]=n}else{t[e.elementsKey]||(t[e.elementsKey]=[]);var s={};if(s[e.typeKey]=r,"instruction"===r){for(a in n)if(n.hasOwnProperty(a))break;s[e.nameKey]="instructionNameFn"in e?e.instructionNameFn(a,n,t):a,e.instructionHasAttributes?(s[e.attributesKey]=n[a][e.attributesKey],"instructionFn"in e&&(s[e.attributesKey]=e.instructionFn(s[e.attributesKey],a,t))):("instructionFn"in e&&(n[a]=e.instructionFn(n[a],a,t)),s[e.instructionKey]=n[a])}else r+"Fn"in e&&(n=e[r+"Fn"](n,t)),s[e[r+"Key"]]=n;e.addParent&&(s[e.parentKey]=t),t[e.elementsKey].push(s)}}function s(r){var n;if("attributesFn"in e&&r&&(r=e.attributesFn(r,t)),(e.trim||"attributeValueFn"in e||"attributeNameFn"in e||e.nativeTypeAttributes)&&r)for(n in r)if(r.hasOwnProperty(n)&&(e.trim&&(r[n]=r[n].trim()),e.nativeTypeAttributes&&(r[n]=a(r[n])),"attributeValueFn"in e&&(r[n]=e.attributeValueFn(r[n],n,t)),"attributeNameFn"in e)){var i=r[n];delete r[n],r[e.attributeNameFn(n,r[n],t)]=i}return r}function c(r){var n={};if(r.body&&("xml"===r.name.toLowerCase()||e.instructionHasAttributes)){for(var i,a=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g;null!==(i=a.exec(r.body));)n[i[1]]=i[2]||i[3]||i[4];n=s(n)}if("xml"===r.name.toLowerCase()){if(e.ignoreDeclaration)return;t[e.declarationKey]={},Object.keys(n).length&&(t[e.declarationKey][e.attributesKey]=n),e.addParent&&(t[e.declarationKey][e.parentKey]=t)}else{if(e.ignoreInstruction)return;e.trim&&(r.body=r.body.trim());var c={};e.instructionHasAttributes&&Object.keys(n).length?(c[r.name]={},c[r.name][e.attributesKey]=n):c[r.name]=r.body,o("instruction",c)}}function u(r,n){var a;if("object"==typeof r&&(n=r.attributes,r=r.name),n=s(n),"elementNameFn"in e&&(r=e.elementNameFn(r,t)),e.compact){var o;if(a={},!e.ignoreAttributes&&n&&Object.keys(n).length)for(o in a[e.attributesKey]={},n)n.hasOwnProperty(o)&&(a[e.attributesKey][o]=n[o]);!(r in t)&&(i(e.alwaysArray)?-1!==e.alwaysArray.indexOf(r):e.alwaysArray)&&(t[r]=[]),t[r]&&!i(t[r])&&(t[r]=[t[r]]),i(t[r])?t[r].push(a):t[r]=a}else t[e.elementsKey]||(t[e.elementsKey]=[]),(a={})[e.typeKey]="element",a[e.nameKey]=r,!e.ignoreAttributes&&n&&Object.keys(n).length&&(a[e.attributesKey]=n),e.alwaysChildren&&(a[e.elementsKey]=[]),t[e.elementsKey].push(a);a[e.parentKey]=t,t=a}function l(t){e.ignoreText||(t.trim()||e.captureSpacesBetweenElements)&&(e.trim&&(t=t.trim()),e.nativeType&&(t=a(t)),e.sanitize&&(t=t.replace(/&/g,"&").replace(//g,">")),o("text",t))}function h(t){e.ignoreComment||(e.trim&&(t=t.trim()),o("comment",t))}function d(r){var n=t[e.parentKey];e.addParent||delete t[e.parentKey],t=n}function f(t){e.ignoreCdata||(e.trim&&(t=t.trim()),o("cdata",t))}function p(t){e.ignoreDoctype||(t=t.replace(/^ /,""),e.trim&&(t=t.trim()),o("doctype",t))}function y(e){e.note=e}return fr=function(i,a){var o=r.parser(!0,{}),s={};if(t=s,e=function(t){return e=n.copyOptions(t),n.ensureFlagExists("ignoreDeclaration",e),n.ensureFlagExists("ignoreInstruction",e),n.ensureFlagExists("ignoreAttributes",e),n.ensureFlagExists("ignoreText",e),n.ensureFlagExists("ignoreComment",e),n.ensureFlagExists("ignoreCdata",e),n.ensureFlagExists("ignoreDoctype",e),n.ensureFlagExists("compact",e),n.ensureFlagExists("alwaysChildren",e),n.ensureFlagExists("addParent",e),n.ensureFlagExists("trim",e),n.ensureFlagExists("nativeType",e),n.ensureFlagExists("nativeTypeAttributes",e),n.ensureFlagExists("sanitize",e),n.ensureFlagExists("instructionHasAttributes",e),n.ensureFlagExists("captureSpacesBetweenElements",e),n.ensureAlwaysArrayExists(e),n.ensureKeyExists("declaration",e),n.ensureKeyExists("instruction",e),n.ensureKeyExists("attributes",e),n.ensureKeyExists("text",e),n.ensureKeyExists("comment",e),n.ensureKeyExists("cdata",e),n.ensureKeyExists("doctype",e),n.ensureKeyExists("type",e),n.ensureKeyExists("name",e),n.ensureKeyExists("elements",e),n.ensureKeyExists("parent",e),n.checkFnExists("doctype",e),n.checkFnExists("instruction",e),n.checkFnExists("cdata",e),n.checkFnExists("comment",e),n.checkFnExists("text",e),n.checkFnExists("instructionName",e),n.checkFnExists("elementName",e),n.checkFnExists("attributeName",e),n.checkFnExists("attributeValue",e),n.checkFnExists("attributes",e),e}(a),o.opt={strictEntities:!0},o.onopentag=u,o.ontext=l,o.oncomment=h,o.onclosetag=d,o.onerror=y,o.oncdata=f,o.ondoctype=p,o.onprocessinginstruction=c,o.write(i).close(),s[e.elementsKey]){var g=s[e.elementsKey];delete s[e.elementsKey],s[e.elementsKey]=g,delete s.text}return s}}function xr(){if(gr)return yr;gr=1;var e=Cr(),t=Dr();return yr=function(r,n){var i,a,o,s;return i=function(t){var r=e.copyOptions(t);return e.ensureSpacesExists(r),r}(n),a=t(r,i),s="compact"in i&&i.compact?"_parent":"parent",o="addParent"in i&&i.addParent?JSON.stringify(a,function(e,t){return e===s?"_":t},i.spaces):JSON.stringify(a,null,i.spaces),o.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")},yr}function Rr(){if(vr)return mr;vr=1;var e,t,r=Cr(),n=_r().isArray;function i(e,t,r){return(!r&&e.spaces?"\n":"")+Array(t+1).join(e.spaces)}function a(r,n,a){if(n.ignoreAttributes)return"";"attributesFn"in n&&(r=n.attributesFn(r,t,e));var o,s,c,u,l=[];for(o in r)r.hasOwnProperty(o)&&null!==r[o]&&void 0!==r[o]&&(u=n.noQuotesForNativeAttributes&&"string"!=typeof r[o]?"":'"',s=(s=""+r[o]).replace(/"/g,"""),c="attributeNameFn"in n?n.attributeNameFn(o,s,t,e):o,l.push(n.spaces&&n.indentAttributes?i(n,a+1,!1):" "),l.push(c+"="+u+("attributeValueFn"in n?n.attributeValueFn(s,o,t,e):s)+u));return r&&Object.keys(r).length&&n.spaces&&n.indentAttributes&&l.push(i(n,a,!1)),l.join("")}function o(r,n,i){return e=r,t="xml",n.ignoreDeclaration?"":""}function s(r,n,i){if(n.ignoreInstruction)return"";var o;for(o in r)if(r.hasOwnProperty(o))break;var s="instructionNameFn"in n?n.instructionNameFn(o,r[o],t,e):o;if("object"==typeof r[o])return e=r,t=s,"";var c=r[o]?r[o]:"";return"instructionFn"in n&&(c=n.instructionFn(c,o,t,e)),""}function c(r,n){return n.ignoreComment?"":"\x3c!--"+("commentFn"in n?n.commentFn(r,t,e):r)+"--\x3e"}function u(r,n){return n.ignoreCdata?"":"","]]]]>"))+"]]>"}function l(r,n){return n.ignoreDoctype?"":""}function h(r,n){return n.ignoreText?"":(r=(r=(r=""+r).replace(/&/g,"&")).replace(/&/g,"&").replace(//g,">"),"textFn"in n?n.textFn(r,t,e):r)}function d(r,n,o,f){return r.reduce(function(r,p){var y=i(n,o,f&&!r);switch(p.type){case"element":return r+y+function(r,n,i){e=r,t=r.name;var o=[],s="elementNameFn"in n?n.elementNameFn(r.name,r):r.name;o.push("<"+s),r[n.attributesKey]&&o.push(a(r[n.attributesKey],n,i));var c=r[n.elementsKey]&&r[n.elementsKey].length||r[n.attributesKey]&&"preserve"===r[n.attributesKey]["xml:space"];return c||(c="fullTagEmptyElementFn"in n?n.fullTagEmptyElementFn(r.name,r):n.fullTagEmptyElement),c?(o.push(">"),r[n.elementsKey]&&r[n.elementsKey].length&&(o.push(d(r[n.elementsKey],n,i+1)),e=r,t=r.name),o.push(n.spaces&&function(e,t){var r;if(e.elements&&e.elements.length)for(r=0;r")):o.push("/>"),o.join("")}(p,n,o);case"comment":return r+y+c(p[n.commentKey],n);case"doctype":return r+y+l(p[n.doctypeKey],n);case"cdata":return r+(n.indentCdata?y:"")+u(p[n.cdataKey],n);case"text":return r+(n.indentText?y:"")+h(p[n.textKey],n);case"instruction":var g={};return g[p[n.nameKey]]=p[n.attributesKey]?p:p[n.instructionKey],r+(n.indentInstruction?y:"")+s(g,n,o)}},"")}function f(e,t,r){var n;for(n in e)if(e.hasOwnProperty(n))switch(n){case t.parentKey:case t.attributesKey:break;case t.textKey:if(t.indentText||r)return!0;break;case t.cdataKey:if(t.indentCdata||r)return!0;break;case t.instructionKey:if(t.indentInstruction||r)return!0;break;case t.doctypeKey:case t.commentKey:default:return!0}return!1}function p(r,n,o,s,c){e=r,t=n;var u="elementNameFn"in o?o.elementNameFn(n,r):n;if(null==r||""===r)return"fullTagEmptyElementFn"in o&&o.fullTagEmptyElementFn(n,r)||o.fullTagEmptyElement?"<"+u+">":"<"+u+"/>";var l=[];if(n){if(l.push("<"+u),"object"!=typeof r)return l.push(">"+h(r,o)+""),l.join("");r[o.attributesKey]&&l.push(a(r[o.attributesKey],o,s));var d=f(r,o,!0)||r[o.attributesKey]&&"preserve"===r[o.attributesKey]["xml:space"];if(d||(d="fullTagEmptyElementFn"in o?o.fullTagEmptyElementFn(n,r):o.fullTagEmptyElement),!d)return l.push("/>"),l.join("");l.push(">")}return l.push(y(r,o,s+1,!1)),e=r,t=n,n&&l.push((c?i(o,s,!1):"")+""),l.join("")}function y(e,t,r,a){var d,y,g,m=[];for(y in e)if(e.hasOwnProperty(y))for(g=n(e[y])?e[y]:[e[y]],d=0;d-1};function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function d(e){return"string"!=typeof e&&(e=String(e)),e}function f(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return a&&(t[Symbol.iterator]=function(){return t}),t}function p(e){this.map={},e instanceof p?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function y(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function g(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function m(e){var t=new FileReader,r=g(t);return t.readAsArrayBuffer(e),r}function v(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:o&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:s&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:i&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():c&&o&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=v(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c&&(ArrayBuffer.prototype.isPrototypeOf(e)||l(e))?this._bodyArrayBuffer=v(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):i&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var e=y(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var e=y(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}if(o)return this.blob().then(m);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,r,n,i,a=y(this);if(a)return a;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=g(t),n=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=n?n[1]:"utf-8",t.readAsText(e,i),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?t:e}(t.method||this.method||"GET"),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in n)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(r),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var i=/([?&])_=[^&]*/;i.test(this.url)?this.url=this.url.replace(i,"$1_="+(new Date).getTime()):this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}function A(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}}),t}function T(e,t){if(!(this instanceof T))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})},b.call(E.prototype),b.call(T.prototype),T.prototype.clone=function(){return new T(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},T.error=function(){var e=new T(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var O=[301,302,303,307,308];T.redirect=function(e,t){if(-1===O.indexOf(t))throw new RangeError("Invalid status code");return new T(null,{status:t,headers:{location:e}})},r.DOMException=n.DOMException;try{new r.DOMException}catch(e){r.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},r.DOMException.prototype=Object.create(Error.prototype),r.DOMException.prototype.constructor=r.DOMException}function _(e,t){return new Promise(function(i,a){var s=new E(e,t);if(s.signal&&s.signal.aborted)return a(new r.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function l(){u.abort()}if(u.onload=function(){var e,t,r={statusText:u.statusText,headers:(e=u.getAllResponseHeaders()||"",t=new p,e.replace(/\r?\n[\t ]+/g," ").split("\r").map(function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e}).forEach(function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();try{t.append(n,i)}catch(e){console.warn("Response "+e.message)}}}),t)};0===s.url.indexOf("file://")&&(u.status<200||u.status>599)?r.status=200:r.status=u.status,r.url="responseURL"in u?u.responseURL:r.headers.get("X-Request-URL");var n="response"in u?u.response:u.responseText;setTimeout(function(){i(new T(n,r))},0)},u.onerror=function(){setTimeout(function(){a(new TypeError("Network request failed"))},0)},u.ontimeout=function(){setTimeout(function(){a(new TypeError("Network request timed out"))},0)},u.onabort=function(){setTimeout(function(){a(new r.DOMException("Aborted","AbortError"))},0)},u.open(s.method,function(e){try{return""===e&&n.location.href?n.location.href:e}catch(t){return e}}(s.url),!0),"include"===s.credentials?u.withCredentials=!0:"omit"===s.credentials&&(u.withCredentials=!1),"responseType"in u&&(o?u.responseType="blob":c&&(u.responseType="arraybuffer")),t&&"object"==typeof t.headers&&!(t.headers instanceof p||n.Headers&&t.headers instanceof n.Headers)){var f=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){f.push(h(e)),u.setRequestHeader(e,d(t.headers[e]))}),s.headers.forEach(function(e,t){-1===f.indexOf(t)&&u.setRequestHeader(t,e)})}else s.headers.forEach(function(e,t){u.setRequestHeader(t,e)});s.signal&&(s.signal.addEventListener("abort",l),u.onreadystatechange=function(){4===u.readyState&&s.signal.removeEventListener("abort",l)}),u.send(void 0===s._bodyInit?null:s._bodyInit)})}_.polyfill=!0,n.fetch||(n.fetch=_,n.Headers=p,n.Request=E,n.Response=T),r.Headers=p,r.Request=E,r.Response=T,r.fetch=_}({})}(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var a=n.fetch?n:i;(r=a.fetch).default=a.fetch,r.fetch=a.fetch,r.Headers=a.Headers,r.Request=a.Request,r.Response=a.Response,t.exports=r}(kr,kr.exports)),kr.exports),Ur=t(Ir);const Pr="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):Ur,jr=e=>{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},Br=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),n=t.trim();if(Math.abs(r.length-n.length)>1)return!1;const i="/"===r.slice(-1)?r.slice(0,-1):r,a="/"===n.slice(-1)?n.slice(0,-1):n;return e.includes(a)||t.includes(i)},Vr=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),n=t.trim(),i="/"===r.slice(-1)?r.slice(0,-1):r,a="/"===n.slice(-1)?n.slice(0,-1):n;return e.includes(a)||t.includes(i)},Mr=e=>e.reduce((e,t)=>({...e,[B[t]]:t}),{}),$r=e=>Object.entries(e).reduce((e,[t,r])=>r?{...e,[t]:r}:e,{}),Kr=(e,t)=>t?{[e]:t}:{},Hr=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))):e:{},Yr=e=>Boolean(null==e?void 0:e.includes(".ics")),zr=(e,t)=>{const r=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,n=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(r.test(e)&&r.test(t)||n.test(e)&&n.test(t)))throw new Error("invalid timeRange format, not in ISO8601")};var qr=Object.freeze({__proto__:null,cleanupFalsy:$r,conditionalParam:Kr,defaultIcsFilter:Yr,excludeHeaders:Hr,getDAVAttribute:Mr,urlContains:Vr,urlEquals:Br,validateISO8601TimeRange:zr});const Gr=j("tsdav:request"),Wr=async e=>{var t;const{url:r,init:n,convertIncoming:i=!0,parseOutgoing:a=!0,fetchOptions:o={},fetch:s}=e,c=null!=s?s:Pr,{headers:u={},body:l,namespace:h,method:d,attributes:f}=n,p=i?Nr.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...l,_attributes:f},{compact:!0,spaces:2,elementNameFn:e=>h&&!/^.+:.+/.test(e)?`${h}:${e}`:e}):l,y={...o};delete y.headers;const g=await c(r,{headers:{"Content-Type":"text/xml;charset=UTF-8",...$r(u),...o.headers||{}},body:p,method:d,...y}),m=await g.text();if(!(g.ok&&(null===(t=g.headers.get("content-type"))||void 0===t?void 0:t.includes("xml"))&&a&&m))return[{href:g.url,ok:g.ok,status:g.status,statusText:g.statusText,raw:m}];const v=Nr.xml2js(m,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,n=Object.keys(r),i=n[n.length-1],a=r[i];if(a.length>0){a[a.length-1]=jr(e)}else r[i]=jr(e)}catch(e){Gr(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,e=>e[1].toUpperCase()),attributesFn:e=>{const t={...e};return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(v.multistatus.response)?v.multistatus.response:[v.multistatus.response]).map(e=>{var t,r;if(!e)return{status:g.status,statusText:g.statusText,ok:g.ok};const n=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:v,href:e.href,status:(null==n?void 0:n.groups)?Number.parseInt(null==n?void 0:n.groups.status,10):g.status,statusText:null!==(r=null===(t=null==n?void 0:n.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:g.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce((e,t)=>({...e,...null==t?void 0:t.prop}),{})}})},Qr=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Wr({url:t,init:{method:"PROPFIND",headers:Hr($r({depth:n,...i}),a),namespace:V.DAV,body:{propfind:{_attributes:Mr([U.CALDAV,U.CALDAV_APPLE,U.CALENDAR_SERVER,U.CARDDAV,U.DAV]),prop:r}}},fetchOptions:o,fetch:s})},Xr=async e=>{const{url:t,data:r,headers:n,headersToExclude:i,fetchOptions:a={},fetch:o}=e;return(null!=o?o:Pr)(t,{method:"PUT",body:r,headers:Hr(n,i),...a})},Zr=async e=>{const{url:t,data:r,etag:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return(null!=s?s:Pr)(t,{method:"PUT",body:r,headers:Hr($r({"If-Match":n,...i}),a),...o})},Jr=async e=>{const{url:t,headers:r,etag:n,headersToExclude:i,fetchOptions:a={},fetch:o}=e;return(null!=o?o:Pr)(t,{method:"DELETE",headers:Hr($r({"If-Match":n,...r}),i),...a})};var en=Object.freeze({__proto__:null,createObject:Xr,davRequest:Wr,deleteObject:Jr,propfind:Qr,updateObject:Zr});function tn(e,t){const r=e=>t.every(t=>e[t]);return Array.isArray(e)?e.every(e=>r(e)):r(e)}const rn=(e,t)=>t.reduce((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`,""),nn=j("tsdav:collection"),an=async e=>{const{url:t,body:r,depth:n,defaultNamespace:i=V.DAV,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e,u=await Wr({url:t,init:{method:"REPORT",headers:Hr($r({depth:n,...a}),o),namespace:i,body:r},fetchOptions:s,fetch:c}),l=u.find(e=>!e.ok||e.status&&e.status>=400);if(l)throw new Error(`Collection query failed: ${l.status} ${l.statusText}. ${l.raw?`Raw response: ${l.raw}`:""}`);return 1===u.length&&!u[0].raw&&u[0].status&&u[0].status<300?[]:u},on=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Wr({url:t,init:{method:"MKCOL",headers:Hr($r({depth:n,...i}),a),namespace:V.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:o,fetch:s})},sn=async e=>{var t,r,n,i,a;const{collection:o,headers:s,headersToExclude:c,fetchOptions:u={},fetch:l}=e;return null!==(a=null===(i=null===(n=null===(r=null===(t=(await Qr({url:o.url,props:{[`${V.DAV}:supported-report-set`]:{}},depth:"0",headers:Hr(s,c),fetchOptions:u,fetch:l}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===n?void 0:n.supportedReport)||void 0===i?void 0:i.map(e=>Object.keys(e.report)[0]))&&void 0!==a?a:[]},cn=async e=>{var t,r,n;const{collection:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e,u=(await Qr({url:i.url,props:{[`${V.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:Hr(a,o),fetchOptions:s,fetch:c})).filter(e=>Vr(i.url,e.href))[0];if(!u)throw new Error("Collection does not exist on server");return{isDirty:`${i.ctag}`!=`${null===(t=u.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(n=null===(r=u.props)||void 0===r?void 0:r.getctag)||void 0===n?void 0:n.toString()}},un=e=>{const{url:t,props:r,headers:n,syncLevel:i,syncToken:a,headersToExclude:o,fetchOptions:s,fetch:c}=e;return Wr({url:t,init:{method:"REPORT",namespace:V.DAV,headers:Hr({...n},o),body:{"sync-collection":{_attributes:Mr([U.CALDAV,U.CARDDAV,U.DAV]),"sync-level":i,"sync-token":a,[`${V.DAV}:prop`]:r}}},fetchOptions:s,fetch:c})},ln=async e=>{var t,r,n,i,a,o,s,c,u,l,h,d;const{collection:f,method:p,headers:y,headersToExclude:g,account:m,detailedResult:v,fetchOptions:b={},fetch:w}=e,E=["accountType","homeUrl"];if(!m||!tn(m,E)){if(!m)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${rn(m,E)} before smartCollectionSync`)}const A=null!=p?p:(null===(t=f.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(nn(`smart collection sync with type ${m.accountType} and method ${A}`),"webdav"===A){const e=await un({url:f.url,props:{[`${V.DAV}:getetag`]:{},[`${"caldav"===m.accountType?V.CALDAV:V.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{},[`${V.DAV}:displayname`]:{}},syncLevel:1,syncToken:f.syncToken,headers:Hr(y,g),fetchOptions:b,fetch:w}),t=e.filter(e=>{var t;const r="caldav"===m.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r}),u=t.filter(e=>404!==e.status).map(e=>e.href),l=t.filter(e=>404===e.status).map(e=>e.href),h=(u.length&&null!==(n=await(null===(r=null==f?void 0:f.objectMultiGet)||void 0===r?void 0:r.call(f,{url:f.url,props:{[`${V.DAV}:getetag`]:{},[`${"caldav"===m.accountType?V.CALDAV:V.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:u,depth:"1",headers:Hr(y,g),fetchOptions:b,fetch:w})))&&void 0!==n?n:[]).map(e=>{var t,r,n,i,a,o,s,c,u,l;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==m?void 0:m.accountType)?null!==(a=null===(i=null===(n=e.props)||void 0===n?void 0:n.calendarData)||void 0===i?void 0:i._cdata)&&void 0!==a?a:null===(o=e.props)||void 0===o?void 0:o.calendarData:null!==(u=null===(c=null===(s=e.props)||void 0===s?void 0:s.addressData)||void 0===c?void 0:c._cdata)&&void 0!==u?u:null===(l=e.props)||void 0===l?void 0:l.addressData}}),d=null!==(i=f.objects)&&void 0!==i?i:[],p=h.filter(e=>d.every(t=>!Vr(t.url,e.url))),E=d.reduce((e,t)=>{const r=h.find(e=>Vr(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),A=l.map(e=>({url:e,etag:""})),T=d.filter(e=>h.some(t=>Vr(e.url,t.url)&&t.etag===e.etag));return{...f,objects:v?{created:p,updated:E,deleted:A}:[...T,...p,...E],syncToken:null!==(c=null===(s=null===(o=null===(a=e[0])||void 0===a?void 0:a.raw)||void 0===o?void 0:o.multistatus)||void 0===s?void 0:s.syncToken)&&void 0!==c?c:f.syncToken}}if("basic"===A){const{isDirty:e,newCtag:t}=await cn({collection:f,headers:Hr(y,g),fetchOptions:b,fetch:w}),r=null!==(u=f.objects)&&void 0!==u?u:[],n=null!==(d=await(null===(h=(l=f).fetchObjects)||void 0===h?void 0:h.call(l,{collection:f,headers:Hr(y,g),fetchOptions:b,fetch:w})))&&void 0!==d?d:[],i=n.filter(e=>r.every(t=>!Vr(t.url,e.url))),a=r.reduce((e,t)=>{const r=n.find(e=>Vr(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),o=r.filter(e=>n.every(t=>!Vr(t.url,e.url))),s=r.filter(e=>n.some(t=>Vr(e.url,t.url)&&t.etag===e.etag));if(e)return{...f,objects:v?{created:i,updated:a,deleted:o}:[...s,...i,...a],ctag:t}}return v?{...f,objects:{created:[],updated:[],deleted:[]}}:f};var hn=Object.freeze({__proto__:null,collectionQuery:an,isCollectionDirty:cn,makeCollection:on,smartCollectionSync:ln,supportedReportSet:sn,syncCollection:un});const dn=j("tsdav:addressBook"),fn=async e=>{const{url:t,props:r,filters:n,depth:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e;return an({url:t,body:{"addressbook-query":$r({_attributes:Mr([U.CARDDAV,U.DAV]),[`${V.DAV}:prop`]:r,filter:null!=n?n:{"prop-filter":{_attributes:{name:"FN"}}}})},defaultNamespace:V.CARDDAV,depth:i,headers:Hr(a,o),fetchOptions:s,fetch:c})},pn=async e=>{const{url:t,props:r,objectUrls:n,depth:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e;return an({url:t,body:{"addressbook-multiget":$r({_attributes:Mr([U.DAV,U.CARDDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n})},defaultNamespace:V.CARDDAV,depth:i,headers:Hr(a,o),fetchOptions:s,fetch:c})},yn=async e=>{const{account:t,headers:r,props:n,headersToExclude:i,fetchOptions:a={},fetch:o}=null!=e?e:{},s=["homeUrl","rootUrl"];if(!t||!tn(t,s)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${rn(t,s)} before fetchAddressBooks`)}const c=await Qr({url:t.homeUrl,props:null!=n?n:{[`${V.DAV}:displayname`]:{},[`${V.CALENDAR_SERVER}:getctag`]:{},[`${V.DAV}:resourcetype`]:{},[`${V.DAV}:sync-token`]:{}},depth:"1",headers:Hr(r,i),fetchOptions:a,fetch:o});return Promise.all(c.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")}).map(e=>{var r,n,i,a,o,s,c,u,l;const h=null!==(i=null===(n=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===n?void 0:n._cdata)&&void 0!==i?i:null===(a=e.props)||void 0===a?void 0:a.displayname;return dn(`Found address book named ${"string"==typeof h?h:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(o=e.href)&&void 0!==o?o:"",null!==(s=t.rootUrl)&&void 0!==s?s:"").href,ctag:null===(c=e.props)||void 0===c?void 0:c.getctag,displayName:"string"==typeof h?h:"",resourcetype:Object.keys(null===(u=e.props)||void 0===u?void 0:u.resourcetype),syncToken:null===(l=e.props)||void 0===l?void 0:l.syncToken}}).map(async e=>({...e,reports:await sn({collection:e,headers:Hr(r,i),fetchOptions:a,fetch:o})})))},gn=async e=>{const{addressBook:t,headers:r,objectUrls:n,headersToExclude:i,urlFilter:a=e=>e,useMultiGet:o=!0,fetchOptions:s={},fetch:c}=e;dn(`Fetching vcards from ${null==t?void 0:t.url}`);const u=["url"];if(!t||!tn(t,u)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${rn(t,u)} before fetchVCards`)}const l=(null!=n?n:(await fn({url:t.url,props:{[`${V.DAV}:getetag`]:{}},depth:"1",headers:Hr(r,i),fetchOptions:s,fetch:c})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(e=>e&&!Br(e,t.url)).filter(a).map(e=>new URL(e).pathname);let h=[];return l.length>0&&(h=o?await pn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CARDDAV}:address-data`]:{}},objectUrls:l,depth:"1",headers:Hr(r,i),fetchOptions:s,fetch:c}):await fn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CARDDAV}:address-data`]:{}},depth:"1",headers:Hr(r,i),fetchOptions:s,fetch:c})),h.map(e=>{var r,n,i,a,o,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(n=e.props)||void 0===n?void 0:n.getetag,data:null!==(o=null===(a=null===(i=e.props)||void 0===i?void 0:i.addressData)||void 0===a?void 0:a._cdata)&&void 0!==o?o:null===(s=e.props)||void 0===s?void 0:s.addressData}})},mn=async e=>{const{addressBook:t,vCardString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Xr({url:new URL(n,t.url).href,data:r,headers:Hr({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o,fetch:s})},vn=async e=>{const{vCard:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;return Zr({url:t.url,data:t.data,etag:t.etag,headers:Hr({"content-type":"text/vcard; charset=utf-8",...r},n),fetchOptions:i,fetch:a})},bn=async e=>{const{vCard:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;return Jr({url:t.url,etag:t.etag,headers:Hr(r,n),fetchOptions:i,fetch:a})},wn=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Wr({url:t,init:{method:"MKCOL",headers:Hr($r({depth:n,...i}),a),namespace:V.DAV,body:r?{mkcol:{_attributes:Mr([U.DAV,U.CARDDAV]),set:{prop:r}}}:void 0},fetchOptions:o,fetch:s})};var En=Object.freeze({__proto__:null,addressBookMultiGet:pn,addressBookQuery:fn,createVCard:mn,deleteVCard:bn,fetchAddressBooks:yn,fetchVCards:gn,makeAddressBook:wn,updateVCard:vn});const An=j("tsdav:calendar"),Tn=async e=>{var t,r,n;const{account:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e,u=["principalUrl","rootUrl"];if(!tn(i,u))throw new Error(`account must have ${rn(i,u)} before fetchUserAddresses`);An(`Fetch user addresses from ${i.principalUrl}`);const l=(await Qr({url:i.principalUrl,props:{[`${V.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:Hr(a,o),fetchOptions:s,fetch:c})).find(e=>Vr(i.principalUrl,e.href));if(!l||!l.ok)throw new Error("cannot find calendarUserAddresses");const h=(null===(n=null===(r=null===(t=null==l?void 0:l.props)||void 0===t?void 0:t.calendarUserAddressSet)||void 0===r?void 0:r.href)||void 0===n?void 0:n.filter(Boolean))||[];return An(`Fetched calendar user addresses ${h}`),h},On=async e=>{const{url:t,props:r,filters:n,timezone:i,depth:a,headers:o,headersToExclude:s,fetchOptions:c={},fetch:u}=e;return an({url:t,body:{"calendar-query":$r({_attributes:Mr([U.CALDAV,U.CALENDAR_SERVER,U.CALDAV_APPLE,U.DAV]),[`${V.DAV}:prop`]:r,filter:n,timezone:i})},defaultNamespace:V.CALDAV,depth:a,headers:Hr(o,s),fetchOptions:c,fetch:u})},_n=async e=>{const{url:t,props:r,objectUrls:n,filters:i,timezone:a,depth:o,headers:s,headersToExclude:c,fetchOptions:u={},fetch:l}=e;return an({url:t,body:{"calendar-multiget":$r({_attributes:Mr([U.DAV,U.CALDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n,filter:i,timezone:a})},defaultNamespace:V.CALDAV,depth:o,headers:Hr(s,c),fetchOptions:u,fetch:l})},Cn=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Wr({url:t,init:{method:"MKCALENDAR",headers:Hr($r({depth:n,...i}),a),namespace:V.DAV,body:{[`${V.CALDAV}:mkcalendar`]:{_attributes:Mr([U.DAV,U.CALDAV,U.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:o,fetch:s})},Dn=async e=>{const{headers:t,account:r,props:n,projectedProps:i,headersToExclude:a,fetchOptions:o={},fetch:s}=null!=e?e:{},c=["homeUrl","rootUrl"];if(!r||!tn(r,c)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${rn(r,c)} before fetchCalendars`)}const u=await Qr({url:r.homeUrl,props:null!=n?n:{[`${V.CALDAV}:calendar-description`]:{},[`${V.CALDAV}:calendar-timezone`]:{},[`${V.DAV}:displayname`]:{},[`${V.CALDAV_APPLE}:calendar-color`]:{},[`${V.CALENDAR_SERVER}:getctag`]:{},[`${V.DAV}:resourcetype`]:{},[`${V.CALDAV}:supported-calendar-component-set`]:{},[`${V.DAV}:sync-token`]:{}},depth:"1",headers:Hr(t,a),fetchOptions:o,fetch:s});return Promise.all(u.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")}).filter(e=>{var t,r,n,i,a,o;return(Array.isArray(null===(r=null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet)||void 0===r?void 0:r.comp)?null===(n=e.props)||void 0===n?void 0:n.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(o=null===(a=null===(i=e.props)||void 0===i?void 0:i.supportedCalendarComponentSet)||void 0===a?void 0:a.comp)||void 0===o?void 0:o._attributes.name]).some(e=>Object.values(M).includes(e))}).map(e=>{var t,n,a,o,s,c,u,l,h,d,f,p,y,g,m,v;const b=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,w=null===(n=e.props)||void 0===n?void 0:n.calendarTimezone;return{description:"string"==typeof b?b:"",timezone:"string"==typeof w?w:"",url:new URL(null!==(a=e.href)&&void 0!==a?a:"",null!==(o=r.rootUrl)&&void 0!==o?o:"").href,ctag:null===(s=e.props)||void 0===s?void 0:s.getctag,calendarColor:null===(c=e.props)||void 0===c?void 0:c.calendarColor,displayName:null!==(l=null===(u=e.props)||void 0===u?void 0:u.displayname._cdata)&&void 0!==l?l:null===(h=e.props)||void 0===h?void 0:h.displayname,components:Array.isArray(null===(d=e.props)||void 0===d?void 0:d.supportedCalendarComponentSet.comp)?null===(f=e.props)||void 0===f?void 0:f.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(y=null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp)||void 0===y?void 0:y._attributes.name],resourcetype:Object.keys(null===(g=e.props)||void 0===g?void 0:g.resourcetype),syncToken:null===(m=e.props)||void 0===m?void 0:m.syncToken,...Kr("projectedProps",Object.fromEntries(Object.entries(null!==(v=e.props)&&void 0!==v?v:{}).filter(([e])=>null==i?void 0:i[e])))}}).map(async e=>({...e,reports:await sn({collection:e,headers:Hr(t,a),fetchOptions:o,fetch:s})})))},xn=async e=>{const{calendar:t,objectUrls:r,filters:n,timeRange:i,headers:a,expand:o,urlFilter:s=Yr,useMultiGet:c=!0,headersToExclude:u,fetchOptions:l={},fetch:h}=e;i&&zr(i.start,i.end),An(`Fetching calendar objects from ${null==t?void 0:t.url}`);const d=["url"];if(!t||!tn(t,d)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${rn(t,d)} before fetchCalendarObjects`)}const f=null!=n?n:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VEVENT"},...i?{"time-range":{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}];let p=[];const y=(null!=r?r:(p=await On({url:t.url,props:{[`${V.DAV}:getetag`]:{},...o&&i?{[`${V.CALDAV}:calendar-data`]:{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}}:{}},filters:f,depth:"1",headers:Hr(a,u),fetchOptions:l,fetch:h})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(s).map(e=>new URL(e).pathname);let g=[];return y.length>0&&(g=o&&!r?p.filter(e=>{var r,n;const i=(null!==(r=e.href)&&void 0!==r?r:"").startsWith("http")?e.href:new URL(null!==(n=e.href)&&void 0!==n?n:"",t.url).href;return s(null!=i?i:"")}):c?await _n({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:{...o&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},objectUrls:y,depth:"1",headers:Hr(a,u),fetchOptions:l,fetch:h}):await On({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:{...o&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},filters:f,depth:"1",headers:Hr(a,u),fetchOptions:l,fetch:h})),g.map(e=>{var r,n,i,a,o,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(n=e.props)||void 0===n?void 0:n.getetag}`,data:null!==(o=null===(a=null===(i=e.props)||void 0===i?void 0:i.calendarData)||void 0===a?void 0:a._cdata)&&void 0!==o?o:null===(s=e.props)||void 0===s?void 0:s.calendarData}})},Rn=async e=>{const{calendar:t,iCalString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Xr({url:new URL(n,t.url).href,data:r,headers:Hr({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o,fetch:s})},Fn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;return Zr({url:t.url,data:t.data,etag:t.etag,headers:Hr({"content-type":"text/calendar; charset=utf-8",...r},n),fetchOptions:i,fetch:a})},Sn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;return Jr({url:t.url,etag:t.etag,headers:Hr(r,n),fetchOptions:i,fetch:a})},Nn=async e=>{var t;const{oldCalendars:r,account:n,detailedResult:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e;if(!n)throw new Error("Must have account before syncCalendars");const u=null!==(t=null!=r?r:n.calendars)&&void 0!==t?t:[],l=await Dn({account:n,headers:Hr(a,o),fetchOptions:s,fetch:c}),h=l.filter(e=>u.every(t=>!Vr(t.url,e.url)));An(`new calendars: ${h.map(e=>e.displayName)}`);const d=u.reduce((e,t)=>{const r=l.find(e=>Vr(e.url,t.url));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e},[]);An(`updated calendars: ${d.map(e=>e.displayName)}`);const f=await Promise.all(d.map(async e=>await ln({collection:{...e,objectMultiGet:_n},method:"webdav",headers:Hr(a,o),account:n,fetchOptions:s,fetch:c}))),p=u.filter(e=>l.every(t=>!Vr(t.url,e.url)));An(`deleted calendars: ${p.map(e=>e.displayName)}`);const y=u.filter(e=>l.some(t=>Vr(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)));return i?{created:h,updated:d,deleted:p}:[...y,...h,...f]},Ln=async e=>{const{url:t,timeRange:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;if(!r)throw new Error("timeRange is required");zr(r.start,r.end);return(await an({url:t,body:{"free-busy-query":$r({_attributes:Mr([U.CALDAV]),[`${V.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:V.CALDAV,depth:n,headers:Hr(i,a),fetchOptions:o,fetch:s}))[0]};var kn=Object.freeze({__proto__:null,calendarMultiGet:_n,calendarQuery:On,createCalendarObject:Rn,deleteCalendarObject:Sn,fetchCalendarObjects:xn,fetchCalendarUserAddresses:Tn,fetchCalendars:Dn,freeBusyQuery:Ln,makeCalendar:Cn,syncCalendars:Nn,updateCalendarObject:Fn});const In=j("tsdav:account"),Un=async e=>{var t,r;In("Service discovery...");const{account:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e,c=null!=s?s:Pr,u=new URL(n.serverUrl),l=new URL(`/.well-known/${n.accountType}`,u);l.protocol=null!==(t=u.protocol)&&void 0!==t?t:"http";try{const e=await c(l.href,{headers:{...Hr(i,a),"Content-Type":"text/xml;charset=UTF-8"},method:"PROPFIND",body:'\n\n \n \n \n',redirect:"manual",...o});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){In(`Service discovery redirected to ${t}`);const e=new URL(t,u);return e.hostname===l.hostname&&l.port&&!e.port&&(e.port=l.port),e.protocol=null!==(r=u.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){In(`Service discovery failed: ${e.stack}`)}return u.href},Pn=async e=>{var t,r,n,i,a;const{account:o,headers:s,headersToExclude:c,fetchOptions:u={},fetch:l}=e,h=["rootUrl"];if(!tn(o,h))throw new Error(`account must have ${rn(o,h)} before fetchPrincipalUrl`);In(`Fetching principal url from path ${o.rootUrl}`);const[d]=await Qr({url:o.rootUrl,props:{[`${V.DAV}:current-user-principal`]:{}},depth:"0",headers:Hr(s,c),fetchOptions:u,fetch:l});if(!d.ok&&(In(`Fetch principal url failed: ${d.statusText}`),401===d.status))throw new Error("Invalid credentials");return In(`Fetched principal url ${null===(r=null===(t=d.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(a=null===(i=null===(n=d.props)||void 0===n?void 0:n.currentUserPrincipal)||void 0===i?void 0:i.href)&&void 0!==a?a:"",o.rootUrl).href},jn=async e=>{var t,r;const{account:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e,c=["principalUrl","rootUrl"];if(!tn(n,c))throw new Error(`account must have ${rn(n,c)} before fetchHomeUrl`);In(`Fetch home url from ${n.principalUrl}`);const u=await Qr({url:n.principalUrl,props:"caldav"===n.accountType?{[`${V.CALDAV}:calendar-home-set`]:{}}:{[`${V.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:Hr(i,a),fetchOptions:o,fetch:s}),l=u.find(e=>Vr(n.principalUrl,e.href));if(!l||!l.ok)throw In(`Fetch home url failed with status ${null==l?void 0:l.statusText} and error ${JSON.stringify(u.map(e=>e.error))}`),new Error("cannot find homeUrl");const h=new URL("caldav"===n.accountType?null===(t=null==l?void 0:l.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==l?void 0:l.props)||void 0===r?void 0:r.addressbookHomeSet.href,n.rootUrl).href;return In(`Fetched home url ${h}`),h},Bn=async e=>{const{account:t,headers:r,loadCollections:n=!1,loadObjects:i=!1,headersToExclude:a,fetchOptions:o={},fetch:s}=e,c={...t};return c.rootUrl=await Un({account:t,headers:Hr(r,a),fetchOptions:o,fetch:s}),c.principalUrl=await Pn({account:c,headers:Hr(r,a),fetchOptions:o,fetch:s}),c.homeUrl=await jn({account:c,headers:Hr(r,a),fetchOptions:o,fetch:s}),(n||i)&&("caldav"===t.accountType?c.calendars=await Dn({headers:Hr(r,a),account:c,fetchOptions:o,fetch:s}):"carddav"===t.accountType&&(c.addressBooks=await yn({headers:Hr(r,a),account:c,fetchOptions:o,fetch:s}))),i&&("caldav"===t.accountType&&c.calendars?c.calendars=await Promise.all(c.calendars.map(async e=>({...e,objects:await xn({calendar:e,headers:Hr(r,a),fetchOptions:o,fetch:s})}))):"carddav"===t.accountType&&c.addressBooks&&(c.addressBooks=await Promise.all(c.addressBooks.map(async e=>({...e,objects:await gn({addressBook:e,headers:Hr(r,a),fetchOptions:o,fetch:s})}))))),c};var Vn=Object.freeze({__proto__:null,createAccount:Bn,fetchHomeUrl:jn,fetchPrincipalUrl:Pn,serviceDiscovery:Un});const Mn=j("tsdav:todo"),$n=e=>({[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(e.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(e.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}),Kn=async e=>{const{url:t,props:r,filters:n,timezone:i,depth:a,headers:o,headersToExclude:s,fetchOptions:c={}}=e;return an({url:t,body:{"calendar-query":$r({_attributes:Mr([U.CALDAV,U.CALENDAR_SERVER,U.CALDAV_APPLE,U.DAV]),[`${V.DAV}:prop`]:r,filter:n,timezone:i})},defaultNamespace:V.CALDAV,depth:a,headers:Hr(o,s),fetchOptions:c})},Hn=async e=>{const{url:t,props:r,objectUrls:n,filters:i,timezone:a,depth:o,headers:s,headersToExclude:c,fetchOptions:u={}}=e;return an({url:t,body:{"calendar-multiget":$r({_attributes:Mr([U.DAV,U.CALDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n,filter:i,timezone:a})},defaultNamespace:V.CALDAV,depth:o,headers:Hr(s,c),fetchOptions:u})},Yn=async e=>{const{calendar:t,objectUrls:r,filters:n,timeRange:i,headers:a,expand:o,urlFilter:s=Yr,useMultiGet:c=!0,headersToExclude:u,fetchOptions:l={}}=e;i&&zr(i.start,i.end),Mn(`Fetching todo objects from ${null==t?void 0:t.url}`);const h=["url"];if(!t||!tn(t,h)){if(!t)throw new Error("cannot fetchTodos for undefined calendar");throw new Error(`calendar must have ${rn(t,h)} before fetchTodos`)}const d=null!=n?n:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VTODO"},...i?{"time-range":{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}],f=(null!=r?r:(await Kn({url:t.url,props:{[`${V.DAV}:getetag`]:{...o&&i?$n(i):{}}},filters:d,depth:"1",headers:Hr(a,u),fetchOptions:l})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(s).map(e=>new URL(e).pathname);let p=[];return f.length>0&&(p=!c||o?await Kn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:{...o&&i?$n(i):{}}},filters:d,depth:"1",headers:Hr(a,u),fetchOptions:l}):await Hn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:{...o&&i?$n(i):{}}},objectUrls:f,depth:"1",headers:Hr(a,u),fetchOptions:l})),p.map(e=>{var r,n,i,a,o,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(n=e.props)||void 0===n?void 0:n.getetag}`,data:null!==(o=null===(a=null===(i=e.props)||void 0===i?void 0:i.calendarData)||void 0===a?void 0:a._cdata)&&void 0!==o?o:null===(s=e.props)||void 0===s?void 0:s.calendarData}})},zn=async e=>{const{calendar:t,iCalString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={}}=e;if(!r.includes("UID:"))throw new Error("iCalString must contain a UID");return Xr({url:new URL(n,t.url).href,data:r,headers:Hr({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o})},qn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;if(!t.etag)throw new Error("calendarObject must have etag for update - fetch todo first");return Zr({url:t.url,data:t.data,etag:t.etag,headers:Hr({"content-type":"text/calendar; charset=utf-8",...r},n),fetchOptions:i})},Gn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={}}=e;return Jr({url:t.url,etag:t.etag,headers:Hr(r,n),fetchOptions:i})};var Wn,Qn=Object.freeze({__proto__:null,createTodo:zn,deleteTodo:Gn,fetchTodos:Yn,todoMultiGet:Hn,todoQuery:Kn,updateTodo:qn}),Xn={exports:{}};var Zn,Jn,ei=(Wn||(Wn=1,Zn=Xn,Jn=Xn.exports,function(t){var r=Jn,n=Zn&&Zn.exports==r&&Zn,i="object"==typeof e&&e;i.global!==i&&i.window!==i||(t=i);var a=function(e){this.message=e};(a.prototype=new Error).name="InvalidCharacterError";var o=function(e){throw new a(e)},s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=/[\t\n\f\r ]/g,u={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&o("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,i,a=e.length%3,c="",u=-1,l=e.length-a;++u>18&63)+s.charAt(i>>12&63)+s.charAt(i>>6&63)+s.charAt(63&i);return 2==a?(t=e.charCodeAt(u)<<8,r=e.charCodeAt(++u),c+=s.charAt((i=t+r)>>10)+s.charAt(i>>4&63)+s.charAt(i<<2&63)+"="):1==a&&(i=e.charCodeAt(u),c+=s.charAt(i>>2)+s.charAt(i<<4&63)+"=="),c},decode:function(e){var t=(e=String(e).replace(c,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&o("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,i=0,a="",u=-1;++u>(-2*i&6)));return a},version:"1.0.0"};if(r&&!r.nodeType)if(n)n.exports=u;else for(var l in u)u.hasOwnProperty(l)&&(r[l]=u[l]);else t.base64=u}(Xn.exports)),Xn.exports);const ti=j("tsdav:authHelper"),ri=(e,t)=>(...r)=>e({...t,...r[0]}),ni=e=>(ti(`Basic auth token generated: ${ei.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${ei.encode(`${e.username}:${e.password}`)}`}),ii=e=>({authorization:`Bearer ${e.accessToken}`}),ai=async(e,t,r)=>{const n=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!tn(e,n))throw new Error(`Oauth credentials missing: ${rn(e,n)}`);const i=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ti(e.tokenUrl),ti(i.toString());const a=null!=r?r:Pr,o=await a(e.tokenUrl,{method:"POST",body:i.toString(),headers:{"content-length":`${i.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(o.ok){return await o.json()}return ti(`Fetch Oauth tokens failed: ${await o.text()}`),{}},oi=async(e,t,r)=>{const n=["refreshToken","clientId","clientSecret","tokenUrl"];if(!tn(e,n))throw new Error(`Oauth credentials missing: ${rn(e,n)}`);const i=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),a=null!=r?r:Pr,o=await a(e.tokenUrl,{method:"POST",body:i.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(o.ok){return await o.json()}return ti(`Refresh access token failed: ${await o.text()}`),{}},si=async(e,t,r)=>{var n;ti("Fetching oauth headers");let i={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(n=e.expiration)&&void 0!==n?n:0))&&(i=await oi(e,t,r)):i=await ai(e,t,r),ti(`Oauth tokens fetched: ${i.access_token}`),{tokens:i,headers:{authorization:`Bearer ${i.access_token}`}}};var ci=Object.freeze({__proto__:null,defaultParam:ri,fetchOauthTokens:ai,getBasicAuthHeaders:ni,getBearerAuthHeaders:ii,getOauthHeaders:si,refreshAccessToken:oi});const ui=async e=>{var t;const{serverUrl:r,credentials:n,authMethod:i,defaultAccountType:a,authFunction:o,fetch:s}=e;let c={};switch(i){case"Basic":c=ni(n);break;case"Bearer":c=ii(n);break;case"Oauth":c=(await si(n,void 0,s)).headers;break;case"Digest":c={Authorization:`Digest ${n.digestString}`};break;case"Custom":c=null!==(t=await(null==o?void 0:o(n)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const u=a?await Bn({account:{serverUrl:r,credentials:n,accountType:a},headers:c,fetch:s}):void 0,l=ri(Xr,{url:r,headers:c,fetch:s}),h=ri(Zr,{headers:c,url:r,fetch:s}),d=ri(Jr,{headers:c,url:r,fetch:s}),f=ri(Qr,{headers:c,fetch:s}),p=ri(an,{headers:c,fetch:s}),y=ri(on,{headers:c,fetch:s}),g=ri(un,{headers:c,fetch:s}),m=ri(sn,{headers:c,fetch:s}),v=ri(cn,{headers:c,fetch:s}),b=ri(ln,{headers:c,account:u,fetch:s}),w=ri(On,{headers:c,fetch:s}),E=ri(_n,{headers:c,fetch:s}),A=ri(Cn,{headers:c,fetch:s}),T=ri(Dn,{headers:c,account:u,fetch:s}),O=ri(Tn,{headers:c,account:u,fetch:s}),_=ri(xn,{headers:c,fetch:s}),C=ri(Rn,{headers:c,fetch:s}),D=ri(Fn,{headers:c,fetch:s}),x=ri(Sn,{headers:c,fetch:s}),R=ri(Nn,{account:u,headers:c,fetch:s}),F=ri(fn,{headers:c,fetch:s}),S=ri(pn,{headers:c,fetch:s}),N=ri(wn,{headers:c,fetch:s});return{davRequest:async e=>{const{init:t,fetch:r,...n}=e,{headers:i,...a}=t;return Wr({...n,init:{...a,headers:{...c,...i}},fetch:null!=r?r:s})},propfind:f,createAccount:async e=>{const{account:t,headers:i,loadCollections:a,loadObjects:o,fetch:u}=e;return Bn({account:{serverUrl:r,credentials:n,...t},headers:{...c,...i},loadCollections:a,loadObjects:o,fetch:null!=u?u:s})},createObject:l,updateObject:h,deleteObject:d,calendarQuery:w,addressBookQuery:F,collectionQuery:p,makeCollection:y,calendarMultiGet:E,makeCalendar:A,syncCollection:g,supportedReportSet:m,isCollectionDirty:v,smartCollectionSync:b,fetchCalendars:T,fetchCalendarUserAddresses:O,fetchCalendarObjects:_,createCalendarObject:C,updateCalendarObject:D,deleteCalendarObject:x,syncCalendars:R,fetchAddressBooks:ri(yn,{account:u,headers:c,fetch:s}),addressBookMultiGet:S,makeAddressBook:N,fetchVCards:ri(gn,{headers:c,fetch:s}),createVCard:ri(mn,{headers:c,fetch:s}),updateVCard:ri(vn,{headers:c,fetch:s}),deleteVCard:ri(bn,{headers:c,fetch:s}),todoQuery:ri(Kn,{headers:c}),todoMultiGet:ri(Hn,{headers:c}),fetchTodos:ri(Yn,{headers:c}),createTodo:ri(zn,{headers:c}),updateTodo:ri(qn,{headers:c}),deleteTodo:ri(Gn,{headers:c})}};class li{constructor(e){var t,r,n;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav",this.authFunction=e.authFunction,this.fetchOptions=null!==(n=e.fetchOptions)&&void 0!==n?n:{},this.fetchOverride=e.fetch}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=ni(this.credentials);break;case"Bearer":this.authHeaders=ii(this.credentials);break;case"Oauth":this.authHeaders=(await si(this.credentials,this.fetchOptions,this.fetchOverride)).headers;break;case"Digest":this.authHeaders={Authorization:`Digest ${this.credentials.digestString}`};break;case"Custom":this.authHeaders=await(null===(e=this.authFunction)||void 0===e?void 0:e.call(this,this.credentials));break;default:throw new Error("Invalid auth method")}this.account=this.accountType?await Bn({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride}):void 0}async davRequest(e){const{init:t,fetch:r,...n}=e,{headers:i,...a}=t;return Wr({...n,init:{...a,headers:{...this.authHeaders,...i}},fetchOptions:this.fetchOptions,fetch:null!=r?r:this.fetchOverride})}async createObject(...e){return ri(Xr,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateObject(...e){return ri(Zr,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteObject(...e){return ri(Jr,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async propfind(...e){return ri(Qr,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:n,loadObjects:i,fetchOptions:a,fetch:o}=e;return Bn({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:n,loadObjects:i,fetchOptions:null!=a?a:this.fetchOptions,fetch:null!=o?o:this.fetchOverride})}async collectionQuery(...e){return ri(an,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCollection(...e){return ri(on,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCollection(...e){return ri(un,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async supportedReportSet(...e){return ri(sn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async isCollectionDirty(...e){return ri(cn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async smartCollectionSync(...e){return ri(ln,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride,account:this.account})(e[0])}async calendarQuery(...e){return ri(On,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCalendar(...e){return ri(Cn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async calendarMultiGet(...e){return ri(_n,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchCalendars(...e){return ri(Dn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return ri(Tn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return ri(xn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createCalendarObject(...e){return ri(Rn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateCalendarObject(...e){return ri(Fn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteCalendarObject(...e){return ri(Sn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCalendars(...e){return ri(Nn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookQuery(...e){return ri(fn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookMultiGet(...e){return ri(pn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeAddressBook(...e){return ri(wn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchAddressBooks(...e){return ri(yn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchVCards(...e){return ri(gn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createVCard(...e){return ri(mn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateVCard(...e){return ri(vn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteVCard(...e){return ri(bn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async todoQuery(...e){return ri(Kn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async todoMultiGet(...e){return ri(Hn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchTodos(...e){return ri(Yn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createTodo(...e){return ri(zn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateTodo(...e){return ri(qn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteTodo(...e){return ri(Gn,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}}var hi={DAVNamespace:U,DAVNamespaceShort:V,DAVAttributeMap:B,...Object.freeze({__proto__:null,DAVClient:li,createDAVClient:ui}),...en,...hn,...Vn,...En,...kn,...Qn,...ci,...qr};export{B as DAVAttributeMap,li as DAVClient,U as DAVNamespace,V as DAVNamespaceShort,pn as addressBookMultiGet,fn as addressBookQuery,_n as calendarMultiGet,On as calendarQuery,$r as cleanupFalsy,an as collectionQuery,Bn as createAccount,Rn as createCalendarObject,ui as createDAVClient,Xr as createObject,zn as createTodo,mn as createVCard,Wr as davRequest,hi as default,Sn as deleteCalendarObject,Jr as deleteObject,Gn as deleteTodo,bn as deleteVCard,yn as fetchAddressBooks,xn as fetchCalendarObjects,Tn as fetchCalendarUserAddresses,Dn as fetchCalendars,ai as fetchOauthTokens,Yn as fetchTodos,gn as fetchVCards,Ln as freeBusyQuery,ni as getBasicAuthHeaders,ii as getBearerAuthHeaders,Mr as getDAVAttribute,si as getOauthHeaders,cn as isCollectionDirty,wn as makeAddressBook,Cn as makeCalendar,Qr as propfind,oi as refreshAccessToken,ln as smartCollectionSync,sn as supportedReportSet,Nn as syncCalendars,un as syncCollection,Hn as todoMultiGet,Kn as todoQuery,Fn as updateCalendarObject,Zr as updateObject,qn as updateTodo,vn as updateVCard,Vr as urlContains,Br as urlEquals}; +/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){var e;D(e=this),""!==e.cdata&&(C(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(C(e,"onscript",e.script),e.script="")}};try{t=Tr.Stream}catch(e){t=function(){}}t||(t=function(){});var i=e.EVENTS.filter(function(e){return"error"!==e&&"end"!==e});function a(e,r){if(!(this instanceof a))return new a(e,r);t.apply(this),this._parser=new n(e,r),this.writable=!0,this.readable=!0;var o=this;this._parser.onend=function(){o.emit("end")},this._parser.onerror=function(e){o.emit("error",e),o._parser.error=null},this._decoder=null,i.forEach(function(e){Object.defineProperty(o,"on"+e,{get:function(){return o._parser["on"+e]},set:function(t){if(!t)return o.removeAllListeners(e),o._parser["on"+e]=t,t;o.on(e,t)},enumerable:!0,configurable:!1})})}a.prototype=Object.create(t.prototype,{constructor:{value:a}}),a.prototype.write=function(e){return"function"==typeof re.isBuffer&&re.isBuffer(e)&&(this._decoder||(this._decoder=new TextDecoder("utf8")),e=this._decoder.decode(e,{stream:!0})),this._parser.write(e.toString()),this.emit("data",e),!0},a.prototype.end=function(e){if(e&&e.length&&this.write(e),this._decoder){var t=this._decoder.decode();t&&(this._parser.write(t),this.emit("data",t))}return this._parser.end(),!0},a.prototype.on=function(e,r){var n=this;return n._parser["on"+e]||-1===i.indexOf(e)||(n._parser["on"+e]=function(){var t=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),n.emit.apply(n,t)}),t.prototype.on.call(n,e,r)};var o="[CDATA[",s="DOCTYPE",c="http://www.w3.org/XML/1998/namespace",u="http://www.w3.org/2000/xmlns/",l={xml:c,xmlns:u},h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,d=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,f=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,p=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function y(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function g(e){return'"'===e||"'"===e}function m(e){return">"===e||y(e)}function v(e,t){return e.test(t)}function b(e,t){return!v(e,t)}var w,E,A,T=0;for(var O in e.STATE={BEGIN:T++,BEGIN_WHITESPACE:T++,TEXT:T++,TEXT_ENTITY:T++,OPEN_WAKA:T++,SGML_DECL:T++,SGML_DECL_QUOTED:T++,DOCTYPE:T++,DOCTYPE_QUOTED:T++,DOCTYPE_DTD:T++,DOCTYPE_DTD_QUOTED:T++,COMMENT_STARTING:T++,COMMENT:T++,COMMENT_ENDING:T++,COMMENT_ENDED:T++,CDATA:T++,CDATA_ENDING:T++,CDATA_ENDING_2:T++,PROC_INST:T++,PROC_INST_BODY:T++,PROC_INST_ENDING:T++,OPEN_TAG:T++,OPEN_TAG_SLASH:T++,ATTRIB:T++,ATTRIB_NAME:T++,ATTRIB_NAME_SAW_WHITE:T++,ATTRIB_VALUE:T++,ATTRIB_VALUE_QUOTED:T++,ATTRIB_VALUE_CLOSED:T++,ATTRIB_VALUE_UNQUOTED:T++,ATTRIB_VALUE_ENTITY_Q:T++,ATTRIB_VALUE_ENTITY_U:T++,CLOSE_TAG:T++,CLOSE_TAG_SAW_WHITE:T++,SCRIPT:T++,SCRIPT_ENDING:T++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(t){var r=e.ENTITIES[t],n="number"==typeof r?String.fromCharCode(r):r;e.ENTITIES[t]=n}),e.STATE)e.STATE[e.STATE[O]]=O;function _(e,t,r){e[t]&&e[t](r)}function C(e,t,r){e.textNode&&D(e),_(e,t,r)}function D(e){e.textNode=x(e.opt,e.textNode),e.textNode&&_(e,"ontext",e.textNode),e.textNode=""}function x(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g," ")),t}function R(e,t){return D(e),e.trackPosition&&(t+="\nLine: "+e.line+"\nColumn: "+e.column+"\nChar: "+e.c),t=new Error(t),e.error=t,_(e,"onerror",t),e}function F(e){return e.sawRoot&&!e.closedRoot&&S(e,"Unclosed root tag"),e.state!==T.BEGIN&&e.state!==T.BEGIN_WHITESPACE&&e.state!==T.TEXT&&R(e,"Unexpected end"),D(e),e.c="",e.closed=!0,_(e,"onend"),n.call(e,e.strict,e.opt),e}function S(e,t){if("object"!=typeof e||!(e instanceof n))throw new Error("bad call to strictFail");e.strict&&R(e,t)}function N(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,r=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(r.ns=t.ns),e.attribList.length=0,C(e,"onopentagstart",r)}function L(e,t){var r=e.indexOf(":")<0?["",e]:e.split(":"),n=r[0],i=r[1];return t&&"xmlns"===e&&(n="xmlns",i=""),{prefix:n,local:i}}function k(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),-1!==e.attribList.indexOf(e.attribName)||e.tag.attributes.hasOwnProperty(e.attribName))e.attribName=e.attribValue="";else{if(e.opt.xmlns){var t=L(e.attribName,!0),r=t.prefix,n=t.local;if("xmlns"===r)if("xml"===n&&e.attribValue!==c)S(e,"xml: prefix must be bound to "+c+"\nActual: "+e.attribValue);else if("xmlns"===n&&e.attribValue!==u)S(e,"xmlns: prefix must be bound to "+u+"\nActual: "+e.attribValue);else{var i=e.tag,a=e.tags[e.tags.length-1]||e;i.ns===a.ns&&(i.ns=Object.create(a.ns)),i.ns[n]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,C(e,"onattribute",{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=""}}function I(e,t){if(e.opt.xmlns){var r=e.tag,n=L(e.tagName);r.prefix=n.prefix,r.local=n.local,r.uri=r.ns[n.prefix]||"",r.prefix&&!r.uri&&(S(e,"Unbound namespace prefix: "+JSON.stringify(e.tagName)),r.uri=n.prefix);var i=e.tags[e.tags.length-1]||e;r.ns&&i.ns!==r.ns&&Object.keys(r.ns).forEach(function(t){C(e,"onopennamespace",{prefix:t,uri:r.ns[t]})});for(var a=0,o=e.attribList.length;a",e.tagName="",void(e.state=T.SCRIPT);C(e,"onscript",e.script),e.script=""}var t=e.tags.length,r=e.tagName;e.strict||(r=r[e.looseCase]());for(var n=r;t--&&e.tags[t].name!==n;)S(e,"Unexpected close tag");if(t<0)return S(e,"Unmatched closing tag: "+e.tagName),e.textNode+="",void(e.state=T.TEXT);e.tagName=r;for(var i=e.tags.length;i-- >t;){var a=e.tag=e.tags.pop();e.tagName=e.tag.name,C(e,"onclosetag",e.tagName);var o={};for(var s in a.ns)o[s]=a.ns[s];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&a.ns!==c.ns&&Object.keys(a.ns).forEach(function(t){var r=a.ns[t];C(e,"onclosenamespace",{prefix:t,uri:r})})}0===t&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName="",e.attribList.length=0,e.state=T.TEXT}function P(e){var t,r=e.entity,n=r.toLowerCase(),i="";return e.ENTITIES[r]?e.ENTITIES[r]:e.ENTITIES[n]?e.ENTITIES[n]:("#"===(r=n).charAt(0)&&("x"===r.charAt(1)?(r=r.slice(2),i=(t=parseInt(r,16)).toString(16)):(r=r.slice(1),i=(t=parseInt(r,10)).toString(10))),r=r.replace(/^0+/,""),isNaN(t)||i.toLowerCase()!==r||t<0||t>1114111?(S(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function j(e,t){"<"===t?(e.state=T.OPEN_WAKA,e.startTagPosition=e.position):y(t)||(S(e,"Non-whitespace before first tag."),e.textNode=t,e.state=T.TEXT)}function B(e,t){var r="";return t1114111||E(o)!==o)throw RangeError("Invalid code point: "+o);o<=65535?r.push(o):(e=55296+((o-=65536)>>10),t=o%1024+56320,r.push(e,t)),(n+1===i||r.length>16384)&&(a+=w.apply(null,r),r.length=0)}return a},Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:A,configurable:!0,writable:!0}):String.fromCodePoint=A)}($e)),$e}function _r(){return lr?ur:(lr=1,ur={isArray:function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)}})}function Cr(){if(dr)return hr;dr=1;var e=_r().isArray;return hr={copyOptions:function(e){var t,r={};for(t in e)e.hasOwnProperty(t)&&(r[t]=e[t]);return r},ensureFlagExists:function(e,t){e in t&&"boolean"==typeof t[e]||(t[e]=!1)},ensureSpacesExists:function(e){(!("spaces"in e)||"number"!=typeof e.spaces&&"string"!=typeof e.spaces)&&(e.spaces=0)},ensureAlwaysArrayExists:function(t){"alwaysArray"in t&&("boolean"==typeof t.alwaysArray||e(t.alwaysArray))||(t.alwaysArray=!1)},ensureKeyExists:function(e,t){e+"Key"in t&&"string"==typeof t[e+"Key"]||(t[e+"Key"]=t.compact?"_"+e:e)},checkFnExists:function(e,t){return e+"Fn"in t}}}function Dr(){if(pr)return fr;pr=1;var e,t,r=Or(),n=Cr(),i=_r().isArray;function a(e){var t=Number(e);if(!isNaN(t))return t;var r=e.toLowerCase();return"true"===r||"false"!==r&&e}function o(r,n){var a;if(e.compact){if(!t[e[r+"Key"]]&&(i(e.alwaysArray)?-1!==e.alwaysArray.indexOf(e[r+"Key"]):e.alwaysArray)&&(t[e[r+"Key"]]=[]),t[e[r+"Key"]]&&!i(t[e[r+"Key"]])&&(t[e[r+"Key"]]=[t[e[r+"Key"]]]),r+"Fn"in e&&"string"==typeof n&&(n=e[r+"Fn"](n,t)),"instruction"===r&&("instructionFn"in e||"instructionNameFn"in e))for(a in n)if(n.hasOwnProperty(a))if("instructionFn"in e)n[a]=e.instructionFn(n[a],a,t);else{var o=n[a];delete n[a],n[e.instructionNameFn(a,o,t)]=o}i(t[e[r+"Key"]])?t[e[r+"Key"]].push(n):t[e[r+"Key"]]=n}else{t[e.elementsKey]||(t[e.elementsKey]=[]);var s={};if(s[e.typeKey]=r,"instruction"===r){for(a in n)if(n.hasOwnProperty(a))break;s[e.nameKey]="instructionNameFn"in e?e.instructionNameFn(a,n,t):a,e.instructionHasAttributes?(s[e.attributesKey]=n[a][e.attributesKey],"instructionFn"in e&&(s[e.attributesKey]=e.instructionFn(s[e.attributesKey],a,t))):("instructionFn"in e&&(n[a]=e.instructionFn(n[a],a,t)),s[e.instructionKey]=n[a])}else r+"Fn"in e&&(n=e[r+"Fn"](n,t)),s[e[r+"Key"]]=n;e.addParent&&(s[e.parentKey]=t),t[e.elementsKey].push(s)}}function s(r){var n;if("attributesFn"in e&&r&&(r=e.attributesFn(r,t)),(e.trim||"attributeValueFn"in e||"attributeNameFn"in e||e.nativeTypeAttributes)&&r)for(n in r)if(r.hasOwnProperty(n)&&(e.trim&&(r[n]=r[n].trim()),e.nativeTypeAttributes&&(r[n]=a(r[n])),"attributeValueFn"in e&&(r[n]=e.attributeValueFn(r[n],n,t)),"attributeNameFn"in e)){var i=r[n];delete r[n],r[e.attributeNameFn(n,r[n],t)]=i}return r}function c(r){var n={};if(r.body&&("xml"===r.name.toLowerCase()||e.instructionHasAttributes)){for(var i,a=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g;null!==(i=a.exec(r.body));)n[i[1]]=i[2]||i[3]||i[4];n=s(n)}if("xml"===r.name.toLowerCase()){if(e.ignoreDeclaration)return;t[e.declarationKey]={},Object.keys(n).length&&(t[e.declarationKey][e.attributesKey]=n),e.addParent&&(t[e.declarationKey][e.parentKey]=t)}else{if(e.ignoreInstruction)return;e.trim&&(r.body=r.body.trim());var c={};e.instructionHasAttributes&&Object.keys(n).length?(c[r.name]={},c[r.name][e.attributesKey]=n):c[r.name]=r.body,o("instruction",c)}}function u(r,n){var a;if("object"==typeof r&&(n=r.attributes,r=r.name),n=s(n),"elementNameFn"in e&&(r=e.elementNameFn(r,t)),e.compact){var o;if(a={},!e.ignoreAttributes&&n&&Object.keys(n).length)for(o in a[e.attributesKey]={},n)n.hasOwnProperty(o)&&(a[e.attributesKey][o]=n[o]);!(r in t)&&(i(e.alwaysArray)?-1!==e.alwaysArray.indexOf(r):e.alwaysArray)&&(t[r]=[]),t[r]&&!i(t[r])&&(t[r]=[t[r]]),i(t[r])?t[r].push(a):t[r]=a}else t[e.elementsKey]||(t[e.elementsKey]=[]),(a={})[e.typeKey]="element",a[e.nameKey]=r,!e.ignoreAttributes&&n&&Object.keys(n).length&&(a[e.attributesKey]=n),e.alwaysChildren&&(a[e.elementsKey]=[]),t[e.elementsKey].push(a);a[e.parentKey]=t,t=a}function l(t){e.ignoreText||(t.trim()||e.captureSpacesBetweenElements)&&(e.trim&&(t=t.trim()),e.nativeType&&(t=a(t)),e.sanitize&&(t=t.replace(/&/g,"&").replace(//g,">")),o("text",t))}function h(t){e.ignoreComment||(e.trim&&(t=t.trim()),o("comment",t))}function d(r){var n=t[e.parentKey];e.addParent||delete t[e.parentKey],t=n}function f(t){e.ignoreCdata||(e.trim&&(t=t.trim()),o("cdata",t))}function p(t){e.ignoreDoctype||(t=t.replace(/^ /,""),e.trim&&(t=t.trim()),o("doctype",t))}function y(e){e.note=e}return fr=function(i,a){var o=r.parser(!0,{}),s={};if(t=s,e=function(t){return e=n.copyOptions(t),n.ensureFlagExists("ignoreDeclaration",e),n.ensureFlagExists("ignoreInstruction",e),n.ensureFlagExists("ignoreAttributes",e),n.ensureFlagExists("ignoreText",e),n.ensureFlagExists("ignoreComment",e),n.ensureFlagExists("ignoreCdata",e),n.ensureFlagExists("ignoreDoctype",e),n.ensureFlagExists("compact",e),n.ensureFlagExists("alwaysChildren",e),n.ensureFlagExists("addParent",e),n.ensureFlagExists("trim",e),n.ensureFlagExists("nativeType",e),n.ensureFlagExists("nativeTypeAttributes",e),n.ensureFlagExists("sanitize",e),n.ensureFlagExists("instructionHasAttributes",e),n.ensureFlagExists("captureSpacesBetweenElements",e),n.ensureAlwaysArrayExists(e),n.ensureKeyExists("declaration",e),n.ensureKeyExists("instruction",e),n.ensureKeyExists("attributes",e),n.ensureKeyExists("text",e),n.ensureKeyExists("comment",e),n.ensureKeyExists("cdata",e),n.ensureKeyExists("doctype",e),n.ensureKeyExists("type",e),n.ensureKeyExists("name",e),n.ensureKeyExists("elements",e),n.ensureKeyExists("parent",e),n.checkFnExists("doctype",e),n.checkFnExists("instruction",e),n.checkFnExists("cdata",e),n.checkFnExists("comment",e),n.checkFnExists("text",e),n.checkFnExists("instructionName",e),n.checkFnExists("elementName",e),n.checkFnExists("attributeName",e),n.checkFnExists("attributeValue",e),n.checkFnExists("attributes",e),e}(a),o.opt={strictEntities:!0},o.onopentag=u,o.ontext=l,o.oncomment=h,o.onclosetag=d,o.onerror=y,o.oncdata=f,o.ondoctype=p,o.onprocessinginstruction=c,o.write(i).close(),s[e.elementsKey]){var g=s[e.elementsKey];delete s[e.elementsKey],s[e.elementsKey]=g,delete s.text}return s}}function xr(){if(gr)return yr;gr=1;var e=Cr(),t=Dr();return yr=function(r,n){var i,a,o,s;return i=function(t){var r=e.copyOptions(t);return e.ensureSpacesExists(r),r}(n),a=t(r,i),s="compact"in i&&i.compact?"_parent":"parent",o="addParent"in i&&i.addParent?JSON.stringify(a,function(e,t){return e===s?"_":t},i.spaces):JSON.stringify(a,null,i.spaces),o.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")},yr}function Rr(){if(vr)return mr;vr=1;var e,t,r=Cr(),n=_r().isArray;function i(e,t,r){return(!r&&e.spaces?"\n":"")+Array(t+1).join(e.spaces)}function a(r,n,a){if(n.ignoreAttributes)return"";"attributesFn"in n&&(r=n.attributesFn(r,t,e));var o,s,c,u,l=[];for(o in r)r.hasOwnProperty(o)&&null!==r[o]&&void 0!==r[o]&&(u=n.noQuotesForNativeAttributes&&"string"!=typeof r[o]?"":'"',s=(s=""+r[o]).replace(/"/g,"""),c="attributeNameFn"in n?n.attributeNameFn(o,s,t,e):o,l.push(n.spaces&&n.indentAttributes?i(n,a+1,!1):" "),l.push(c+"="+u+("attributeValueFn"in n?n.attributeValueFn(s,o,t,e):s)+u));return r&&Object.keys(r).length&&n.spaces&&n.indentAttributes&&l.push(i(n,a,!1)),l.join("")}function o(r,n,i){return e=r,t="xml",n.ignoreDeclaration?"":""}function s(r,n,i){if(n.ignoreInstruction)return"";var o;for(o in r)if(r.hasOwnProperty(o))break;var s="instructionNameFn"in n?n.instructionNameFn(o,r[o],t,e):o;if("object"==typeof r[o])return e=r,t=s,"";var c=r[o]?r[o]:"";return"instructionFn"in n&&(c=n.instructionFn(c,o,t,e)),""}function c(r,n){return n.ignoreComment?"":"\x3c!--"+("commentFn"in n?n.commentFn(r,t,e):r)+"--\x3e"}function u(r,n){return n.ignoreCdata?"":"","]]]]>"))+"]]>"}function l(r,n){return n.ignoreDoctype?"":""}function h(r,n){return n.ignoreText?"":(r=(r=(r=""+r).replace(/&/g,"&")).replace(/&/g,"&").replace(//g,">"),"textFn"in n?n.textFn(r,t,e):r)}function d(r,n,o,f){return r.reduce(function(r,p){var y=i(n,o,f&&!r);switch(p.type){case"element":return r+y+function(r,n,i){e=r,t=r.name;var o=[],s="elementNameFn"in n?n.elementNameFn(r.name,r):r.name;o.push("<"+s),r[n.attributesKey]&&o.push(a(r[n.attributesKey],n,i));var c=r[n.elementsKey]&&r[n.elementsKey].length||r[n.attributesKey]&&"preserve"===r[n.attributesKey]["xml:space"];return c||(c="fullTagEmptyElementFn"in n?n.fullTagEmptyElementFn(r.name,r):n.fullTagEmptyElement),c?(o.push(">"),r[n.elementsKey]&&r[n.elementsKey].length&&(o.push(d(r[n.elementsKey],n,i+1)),e=r,t=r.name),o.push(n.spaces&&function(e,t){var r;if(e.elements&&e.elements.length)for(r=0;r")):o.push("/>"),o.join("")}(p,n,o);case"comment":return r+y+c(p[n.commentKey],n);case"doctype":return r+y+l(p[n.doctypeKey],n);case"cdata":return r+(n.indentCdata?y:"")+u(p[n.cdataKey],n);case"text":return r+(n.indentText?y:"")+h(p[n.textKey],n);case"instruction":var g={};return g[p[n.nameKey]]=p[n.attributesKey]?p:p[n.instructionKey],r+(n.indentInstruction?y:"")+s(g,n,o)}},"")}function f(e,t,r){var n;for(n in e)if(e.hasOwnProperty(n))switch(n){case t.parentKey:case t.attributesKey:break;case t.textKey:if(t.indentText||r)return!0;break;case t.cdataKey:if(t.indentCdata||r)return!0;break;case t.instructionKey:if(t.indentInstruction||r)return!0;break;case t.doctypeKey:case t.commentKey:default:return!0}return!1}function p(r,n,o,s,c){e=r,t=n;var u="elementNameFn"in o?o.elementNameFn(n,r):n;if(null==r||""===r)return"fullTagEmptyElementFn"in o&&o.fullTagEmptyElementFn(n,r)||o.fullTagEmptyElement?"<"+u+">":"<"+u+"/>";var l=[];if(n){if(l.push("<"+u),"object"!=typeof r)return l.push(">"+h(r,o)+""),l.join("");r[o.attributesKey]&&l.push(a(r[o.attributesKey],o,s));var d=f(r,o,!0)||r[o.attributesKey]&&"preserve"===r[o.attributesKey]["xml:space"];if(d||(d="fullTagEmptyElementFn"in o?o.fullTagEmptyElementFn(n,r):o.fullTagEmptyElement),!d)return l.push("/>"),l.join("");l.push(">")}return l.push(y(r,o,s+1,!1)),e=r,t=n,n&&l.push((c?i(o,s,!1):"")+""),l.join("")}function y(e,t,r,a){var d,y,g,m=[];for(y in e)if(e.hasOwnProperty(y))for(g=n(e[y])?e[y]:[e[y]],d=0;d-1};function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||""===e)throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function d(e){return"string"!=typeof e&&(e=String(e)),e}function f(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return a&&(t[Symbol.iterator]=function(){return t}),t}function p(e){this.map={},e instanceof p?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(2!=e.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function y(e){if(!e._noBody)return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function g(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function m(e){var t=new FileReader,r=g(t);return t.readAsArrayBuffer(e),r}function v(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){var t;this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:o&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:s&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:i&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():c&&o&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=v(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c&&(ArrayBuffer.prototype.isPrototypeOf(e)||l(e))?this._bodyArrayBuffer=v(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):i&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var e=y(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var e=y(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}if(o)return this.blob().then(m);throw new Error("could not read as ArrayBuffer")},this.text=function(){var e,t,r,n,i,a=y(this);if(a)return a;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=g(t),n=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=n?n[1]:"utf-8",t.readAsText(e,i),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?t:e}(t.method||this.method||"GET"),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if("AbortController"in n)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(r),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==t.cache&&"no-cache"!==t.cache)){var i=/([?&])_=[^&]*/;i.test(this.url)?this.url=this.url.replace(i,"$1_="+(new Date).getTime()):this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}function A(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}}),t}function T(e,t){if(!(this instanceof T))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=void 0===t.statusText?"":""+t.statusText,this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})},b.call(E.prototype),b.call(T.prototype),T.prototype.clone=function(){return new T(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},T.error=function(){var e=new T(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var O=[301,302,303,307,308];T.redirect=function(e,t){if(-1===O.indexOf(t))throw new RangeError("Invalid status code");return new T(null,{status:t,headers:{location:e}})},r.DOMException=n.DOMException;try{new r.DOMException}catch(e){r.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},r.DOMException.prototype=Object.create(Error.prototype),r.DOMException.prototype.constructor=r.DOMException}function _(e,t){return new Promise(function(i,a){var s=new E(e,t);if(s.signal&&s.signal.aborted)return a(new r.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function l(){u.abort()}if(u.onload=function(){var e,t,r={statusText:u.statusText,headers:(e=u.getAllResponseHeaders()||"",t=new p,e.replace(/\r?\n[\t ]+/g," ").split("\r").map(function(e){return 0===e.indexOf("\n")?e.substr(1,e.length):e}).forEach(function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();try{t.append(n,i)}catch(e){console.warn("Response "+e.message)}}}),t)};0===s.url.indexOf("file://")&&(u.status<200||u.status>599)?r.status=200:r.status=u.status,r.url="responseURL"in u?u.responseURL:r.headers.get("X-Request-URL");var n="response"in u?u.response:u.responseText;setTimeout(function(){i(new T(n,r))},0)},u.onerror=function(){setTimeout(function(){a(new TypeError("Network request failed"))},0)},u.ontimeout=function(){setTimeout(function(){a(new TypeError("Network request timed out"))},0)},u.onabort=function(){setTimeout(function(){a(new r.DOMException("Aborted","AbortError"))},0)},u.open(s.method,function(e){try{return""===e&&n.location.href?n.location.href:e}catch(t){return e}}(s.url),!0),"include"===s.credentials?u.withCredentials=!0:"omit"===s.credentials&&(u.withCredentials=!1),"responseType"in u&&(o?u.responseType="blob":c&&(u.responseType="arraybuffer")),t&&"object"==typeof t.headers&&!(t.headers instanceof p||n.Headers&&t.headers instanceof n.Headers)){var f=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){f.push(h(e)),u.setRequestHeader(e,d(t.headers[e]))}),s.headers.forEach(function(e,t){-1===f.indexOf(t)&&u.setRequestHeader(t,e)})}else s.headers.forEach(function(e,t){u.setRequestHeader(t,e)});s.signal&&(s.signal.addEventListener("abort",l),u.onreadystatechange=function(){4===u.readyState&&s.signal.removeEventListener("abort",l)}),u.send(void 0===s._bodyInit?null:s._bodyInit)})}_.polyfill=!0,n.fetch||(n.fetch=_,n.Headers=p,n.Request=E,n.Response=T),r.Headers=p,r.Request=E,r.Response=T,r.fetch=_}({})}(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var a=n.fetch?n:i;(r=a.fetch).default=a.fetch,r.fetch=a.fetch,r.Headers=a.Headers,r.Request=a.Request,r.Response=a.Response,t.exports=r}(kr,kr.exports)),kr.exports),Ur=t(Ir);const Pr="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):Ur,jr=e=>{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},Br=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),n=t.trim();if(Math.abs(r.length-n.length)>1)return!1;const i="/"===r.slice(-1)?r.slice(0,-1):r,a="/"===n.slice(-1)?n.slice(0,-1):n;return e.includes(a)||t.includes(i)},Vr=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),n=t.trim(),i="/"===r.slice(-1)?r.slice(0,-1):r,a="/"===n.slice(-1)?n.slice(0,-1):n;return e.includes(a)||t.includes(i)},Mr=e=>e.reduce((e,t)=>({...e,[B[t]]:t}),{}),$r=e=>Object.entries(e).reduce((e,[t,r])=>r?{...e,[t]:r}:e,{}),Kr=(e,t)=>t?{[e]:t}:{},Hr=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))):e:{},Yr=e=>Boolean(null==e?void 0:e.includes(".ics")),zr=(e,t)=>{const r=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,n=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(r.test(e)&&r.test(t)||n.test(e)&&n.test(t)))throw new Error("invalid timeRange format, not in ISO8601")};var qr=Object.freeze({__proto__:null,cleanupFalsy:$r,conditionalParam:Kr,defaultIcsFilter:Yr,excludeHeaders:Hr,getDAVAttribute:Mr,urlContains:Vr,urlEquals:Br,validateISO8601TimeRange:zr});const Gr=j("tsdav:request"),Wr=async e=>{var t;const{url:r,init:n,convertIncoming:i=!0,parseOutgoing:a=!0,fetchOptions:o={},fetch:s}=e,c=null!=s?s:Pr,{headers:u={},body:l,namespace:h,method:d,attributes:f}=n,p=i?Nr.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...l,_attributes:f},{compact:!0,spaces:2,elementNameFn:e=>h&&!/^.+:.+/.test(e)?`${h}:${e}`:e}):l,y={...o};delete y.headers;const g=await c(r,{headers:{"Content-Type":"text/xml;charset=UTF-8",...$r(u),...o.headers||{}},body:p,method:d,...y}),m=await g.text();if(!(g.ok&&(null===(t=g.headers.get("content-type"))||void 0===t?void 0:t.includes("xml"))&&a&&m))return[{href:g.url,ok:g.ok,status:g.status,statusText:g.statusText,raw:m}];const v=Nr.xml2js(m,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,n=Object.keys(r),i=n[n.length-1],a=r[i];if(a.length>0){a[a.length-1]=jr(e)}else r[i]=jr(e)}catch(e){Gr(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,e=>e[1].toUpperCase()),attributesFn:e=>{const t={...e};return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(v.multistatus.response)?v.multistatus.response:[v.multistatus.response]).map(e=>{var t,r;if(!e)return{status:g.status,statusText:g.statusText,ok:g.ok};const n=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:v,href:e.href,status:(null==n?void 0:n.groups)?Number.parseInt(null==n?void 0:n.groups.status,10):g.status,statusText:null!==(r=null===(t=null==n?void 0:n.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:g.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce((e,t)=>({...e,...null==t?void 0:t.prop}),{})}})},Qr=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Wr({url:t,init:{method:"PROPFIND",headers:Hr($r({depth:n,...i}),a),namespace:V.DAV,body:{propfind:{_attributes:Mr([U.CALDAV,U.CALDAV_APPLE,U.CALENDAR_SERVER,U.CARDDAV,U.DAV]),prop:r}}},fetchOptions:o,fetch:s})},Xr=async e=>{const{url:t,data:r,headers:n,headersToExclude:i,fetchOptions:a={},fetch:o}=e;return(null!=o?o:Pr)(t,{method:"PUT",body:r,headers:Hr(n,i),...a})},Zr=async e=>{const{url:t,data:r,etag:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return(null!=s?s:Pr)(t,{method:"PUT",body:r,headers:Hr($r({"If-Match":n,...i}),a),...o})},Jr=async e=>{const{url:t,headers:r,etag:n,headersToExclude:i,fetchOptions:a={},fetch:o}=e;return(null!=o?o:Pr)(t,{method:"DELETE",headers:Hr($r({"If-Match":n,...r}),i),...a})};var en=Object.freeze({__proto__:null,createObject:Xr,davRequest:Wr,deleteObject:Jr,propfind:Qr,updateObject:Zr});function tn(e,t){const r=e=>t.every(t=>e[t]);return Array.isArray(e)?e.every(e=>r(e)):r(e)}const rn=(e,t)=>t.reduce((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`,""),nn=j("tsdav:collection"),an=async e=>{const{url:t,body:r,depth:n,defaultNamespace:i=V.DAV,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e,u=await Wr({url:t,init:{method:"REPORT",headers:Hr($r({depth:n,...a}),o),namespace:i,body:r},fetchOptions:s,fetch:c}),l=u.find(e=>!e.ok||e.status&&e.status>=400);if(l)throw new Error(`Collection query failed: ${l.status} ${l.statusText}. ${l.raw?`Raw response: ${l.raw}`:""}`);return 1===u.length&&!u[0].raw&&u[0].status&&u[0].status<300?[]:u},on=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Wr({url:t,init:{method:"MKCOL",headers:Hr($r({depth:n,...i}),a),namespace:V.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:o,fetch:s})},sn=async e=>{var t,r,n,i,a;const{collection:o,headers:s,headersToExclude:c,fetchOptions:u={},fetch:l}=e;return null!==(a=null===(i=null===(n=null===(r=null===(t=(await Qr({url:o.url,props:{[`${V.DAV}:supported-report-set`]:{}},depth:"0",headers:Hr(s,c),fetchOptions:u,fetch:l}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===n?void 0:n.supportedReport)||void 0===i?void 0:i.map(e=>Object.keys(e.report)[0]))&&void 0!==a?a:[]},cn=async e=>{var t,r,n;const{collection:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e,u=(await Qr({url:i.url,props:{[`${V.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:Hr(a,o),fetchOptions:s,fetch:c})).filter(e=>Vr(i.url,e.href))[0];if(!u)throw new Error("Collection does not exist on server");return{isDirty:`${i.ctag}`!=`${null===(t=u.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(n=null===(r=u.props)||void 0===r?void 0:r.getctag)||void 0===n?void 0:n.toString()}},un=e=>{const{url:t,props:r,headers:n,syncLevel:i,syncToken:a,headersToExclude:o,fetchOptions:s,fetch:c}=e;return Wr({url:t,init:{method:"REPORT",namespace:V.DAV,headers:Hr({...n},o),body:{"sync-collection":{_attributes:Mr([U.CALDAV,U.CARDDAV,U.DAV]),"sync-level":i,"sync-token":a,[`${V.DAV}:prop`]:r}}},fetchOptions:s,fetch:c})},ln=async e=>{var t,r,n,i,a,o,s,c,u,l,h,d;const{collection:f,method:p,headers:y,headersToExclude:g,account:m,detailedResult:v,fetchOptions:b={},fetch:w}=e,E=["accountType","homeUrl"];if(!m||!tn(m,E)){if(!m)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${rn(m,E)} before smartCollectionSync`)}const A=null!=p?p:(null===(t=f.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(nn(`smart collection sync with type ${m.accountType} and method ${A}`),"webdav"===A){const e=await un({url:f.url,props:{[`${V.DAV}:getetag`]:{},[`${"caldav"===m.accountType?V.CALDAV:V.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{},[`${V.DAV}:displayname`]:{}},syncLevel:1,syncToken:f.syncToken,headers:Hr(y,g),fetchOptions:b,fetch:w}),t=e.filter(e=>{var t;const r="caldav"===m.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r}),u=t.filter(e=>404!==e.status).map(e=>e.href),l=t.filter(e=>404===e.status).map(e=>e.href),h=(u.length&&null!==(n=await(null===(r=null==f?void 0:f.objectMultiGet)||void 0===r?void 0:r.call(f,{url:f.url,props:{[`${V.DAV}:getetag`]:{},[`${"caldav"===m.accountType?V.CALDAV:V.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:u,depth:"1",headers:Hr(y,g),fetchOptions:b,fetch:w})))&&void 0!==n?n:[]).map(e=>{var t,r,n,i,a,o,s,c,u,l;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==m?void 0:m.accountType)?null!==(a=null===(i=null===(n=e.props)||void 0===n?void 0:n.calendarData)||void 0===i?void 0:i._cdata)&&void 0!==a?a:null===(o=e.props)||void 0===o?void 0:o.calendarData:null!==(u=null===(c=null===(s=e.props)||void 0===s?void 0:s.addressData)||void 0===c?void 0:c._cdata)&&void 0!==u?u:null===(l=e.props)||void 0===l?void 0:l.addressData}}),d=null!==(i=f.objects)&&void 0!==i?i:[],p=h.filter(e=>d.every(t=>!Vr(t.url,e.url))),E=d.reduce((e,t)=>{const r=h.find(e=>Vr(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),A=l.map(e=>({url:e,etag:""})),T=d.filter(e=>h.some(t=>Vr(e.url,t.url)&&t.etag===e.etag));return{...f,objects:v?{created:p,updated:E,deleted:A}:[...T,...p,...E],syncToken:null!==(c=null===(s=null===(o=null===(a=e[0])||void 0===a?void 0:a.raw)||void 0===o?void 0:o.multistatus)||void 0===s?void 0:s.syncToken)&&void 0!==c?c:f.syncToken}}if("basic"===A){const{isDirty:e,newCtag:t}=await cn({collection:f,headers:Hr(y,g),fetchOptions:b,fetch:w}),r=null!==(u=f.objects)&&void 0!==u?u:[],n=null!==(d=await(null===(h=(l=f).fetchObjects)||void 0===h?void 0:h.call(l,{collection:f,headers:Hr(y,g),fetchOptions:b,fetch:w})))&&void 0!==d?d:[],i=n.filter(e=>r.every(t=>!Vr(t.url,e.url))),a=r.reduce((e,t)=>{const r=n.find(e=>Vr(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),o=r.filter(e=>n.every(t=>!Vr(t.url,e.url))),s=r.filter(e=>n.some(t=>Vr(e.url,t.url)&&t.etag===e.etag));if(e)return{...f,objects:v?{created:i,updated:a,deleted:o}:[...s,...i,...a],ctag:t}}return v?{...f,objects:{created:[],updated:[],deleted:[]}}:f};var hn=Object.freeze({__proto__:null,collectionQuery:an,isCollectionDirty:cn,makeCollection:on,smartCollectionSync:ln,supportedReportSet:sn,syncCollection:un});const dn=j("tsdav:addressBook"),fn=async e=>{const{url:t,props:r,filters:n,depth:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e;return an({url:t,body:{"addressbook-query":$r({_attributes:Mr([U.CARDDAV,U.DAV]),[`${V.DAV}:prop`]:r,filter:null!=n?n:{"prop-filter":{_attributes:{name:"FN"}}}})},defaultNamespace:V.CARDDAV,depth:i,headers:Hr(a,o),fetchOptions:s,fetch:c})},pn=async e=>{const{url:t,props:r,objectUrls:n,depth:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e;return an({url:t,body:{"addressbook-multiget":$r({_attributes:Mr([U.DAV,U.CARDDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n})},defaultNamespace:V.CARDDAV,depth:i,headers:Hr(a,o),fetchOptions:s,fetch:c})},yn=async e=>{const{account:t,headers:r,props:n,headersToExclude:i,fetchOptions:a={},fetch:o}=null!=e?e:{},s=["homeUrl","rootUrl"];if(!t||!tn(t,s)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${rn(t,s)} before fetchAddressBooks`)}const c=await Qr({url:t.homeUrl,props:null!=n?n:{[`${V.DAV}:displayname`]:{},[`${V.CALENDAR_SERVER}:getctag`]:{},[`${V.DAV}:resourcetype`]:{},[`${V.DAV}:sync-token`]:{}},depth:"1",headers:Hr(r,i),fetchOptions:a,fetch:o});return Promise.all(c.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")}).map(e=>{var r,n,i,a,o,s,c,u,l;const h=null!==(i=null===(n=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===n?void 0:n._cdata)&&void 0!==i?i:null===(a=e.props)||void 0===a?void 0:a.displayname;return dn(`Found address book named ${"string"==typeof h?h:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(o=e.href)&&void 0!==o?o:"",null!==(s=t.rootUrl)&&void 0!==s?s:"").href,ctag:null===(c=e.props)||void 0===c?void 0:c.getctag,displayName:"string"==typeof h?h:"",resourcetype:Object.keys(null===(u=e.props)||void 0===u?void 0:u.resourcetype),syncToken:null===(l=e.props)||void 0===l?void 0:l.syncToken}}).map(async e=>({...e,reports:await sn({collection:e,headers:Hr(r,i),fetchOptions:a,fetch:o})})))},gn=async e=>{const{addressBook:t,headers:r,objectUrls:n,headersToExclude:i,urlFilter:a=e=>e,useMultiGet:o=!0,fetchOptions:s={},fetch:c}=e;dn(`Fetching vcards from ${null==t?void 0:t.url}`);const u=["url"];if(!t||!tn(t,u)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${rn(t,u)} before fetchVCards`)}const l=(null!=n?n:(await fn({url:t.url,props:{[`${V.DAV}:getetag`]:{}},depth:"1",headers:Hr(r,i),fetchOptions:s,fetch:c})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(e=>e&&!Br(e,t.url)).filter(a).map(e=>new URL(e).pathname);let h=[];return l.length>0&&(h=o?await pn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CARDDAV}:address-data`]:{}},objectUrls:l,depth:"1",headers:Hr(r,i),fetchOptions:s,fetch:c}):await fn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CARDDAV}:address-data`]:{}},depth:"1",headers:Hr(r,i),fetchOptions:s,fetch:c})),h.map(e=>{var r,n,i,a,o,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(n=e.props)||void 0===n?void 0:n.getetag,data:null!==(o=null===(a=null===(i=e.props)||void 0===i?void 0:i.addressData)||void 0===a?void 0:a._cdata)&&void 0!==o?o:null===(s=e.props)||void 0===s?void 0:s.addressData}})},mn=async e=>{const{addressBook:t,vCardString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Xr({url:new URL(n,t.url).href,data:r,headers:Hr({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o,fetch:s})},vn=async e=>{const{vCard:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;return Zr({url:t.url,data:t.data,etag:t.etag,headers:Hr({"content-type":"text/vcard; charset=utf-8",...r},n),fetchOptions:i,fetch:a})},bn=async e=>{const{vCard:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;return Jr({url:t.url,etag:t.etag,headers:Hr(r,n),fetchOptions:i,fetch:a})},wn=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Wr({url:t,init:{method:"MKCOL",headers:Hr($r({depth:n,...i}),a),namespace:V.DAV,body:r?{mkcol:{_attributes:Mr([U.DAV,U.CARDDAV]),set:{prop:r}}}:void 0},fetchOptions:o,fetch:s})};var En=Object.freeze({__proto__:null,addressBookMultiGet:pn,addressBookQuery:fn,createVCard:mn,deleteVCard:bn,fetchAddressBooks:yn,fetchVCards:gn,makeAddressBook:wn,updateVCard:vn});const An=j("tsdav:calendar"),Tn=async e=>{var t,r,n;const{account:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e,u=["principalUrl","rootUrl"];if(!tn(i,u))throw new Error(`account must have ${rn(i,u)} before fetchUserAddresses`);An(`Fetch user addresses from ${i.principalUrl}`);const l=(await Qr({url:i.principalUrl,props:{[`${V.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:Hr(a,o),fetchOptions:s,fetch:c})).find(e=>Vr(i.principalUrl,e.href));if(!l||!l.ok)throw new Error("cannot find calendarUserAddresses");const h=(null===(n=null===(r=null===(t=null==l?void 0:l.props)||void 0===t?void 0:t.calendarUserAddressSet)||void 0===r?void 0:r.href)||void 0===n?void 0:n.filter(Boolean))||[];return An(`Fetched calendar user addresses ${h}`),h},On=async e=>{const{url:t,props:r,filters:n,timezone:i,depth:a,headers:o,headersToExclude:s,fetchOptions:c={},fetch:u}=e;return an({url:t,body:{"calendar-query":$r({_attributes:Mr([U.CALDAV,U.CALENDAR_SERVER,U.CALDAV_APPLE,U.DAV]),[`${V.DAV}:prop`]:r,filter:n,timezone:i})},defaultNamespace:V.CALDAV,depth:a,headers:Hr(o,s),fetchOptions:c,fetch:u})},_n=async e=>{const{url:t,props:r,objectUrls:n,filters:i,timezone:a,depth:o,headers:s,headersToExclude:c,fetchOptions:u={},fetch:l}=e;return an({url:t,body:{"calendar-multiget":$r({_attributes:Mr([U.DAV,U.CALDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n,filter:i,timezone:a})},defaultNamespace:V.CALDAV,depth:o,headers:Hr(s,c),fetchOptions:u,fetch:l})},Cn=async e=>{const{url:t,props:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Wr({url:t,init:{method:"MKCALENDAR",headers:Hr($r({depth:n,...i}),a),namespace:V.DAV,body:{[`${V.CALDAV}:mkcalendar`]:{_attributes:Mr([U.DAV,U.CALDAV,U.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:o,fetch:s})},Dn=async e=>{const{headers:t,account:r,props:n,projectedProps:i,headersToExclude:a,fetchOptions:o={},fetch:s}=null!=e?e:{},c=["homeUrl","rootUrl"];if(!r||!tn(r,c)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${rn(r,c)} before fetchCalendars`)}const u=await Qr({url:r.homeUrl,props:null!=n?n:{[`${V.CALDAV}:calendar-description`]:{},[`${V.CALDAV}:calendar-timezone`]:{},[`${V.DAV}:displayname`]:{},[`${V.CALDAV_APPLE}:calendar-color`]:{},[`${V.CALENDAR_SERVER}:getctag`]:{},[`${V.DAV}:resourcetype`]:{},[`${V.CALDAV}:supported-calendar-component-set`]:{},[`${V.DAV}:sync-token`]:{}},depth:"1",headers:Hr(t,a),fetchOptions:o,fetch:s});return Promise.all(u.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")}).filter(e=>{var t,r,n,i,a,o;return(Array.isArray(null===(r=null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet)||void 0===r?void 0:r.comp)?null===(n=e.props)||void 0===n?void 0:n.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(o=null===(a=null===(i=e.props)||void 0===i?void 0:i.supportedCalendarComponentSet)||void 0===a?void 0:a.comp)||void 0===o?void 0:o._attributes.name]).some(e=>Object.values(M).includes(e))}).map(e=>{var t,n,a,o,s,c,u,l,h,d,f,p,y,g,m,v;const b=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,w=null===(n=e.props)||void 0===n?void 0:n.calendarTimezone;return{description:"string"==typeof b?b:"",timezone:"string"==typeof w?w:"",url:new URL(null!==(a=e.href)&&void 0!==a?a:"",null!==(o=r.rootUrl)&&void 0!==o?o:"").href,ctag:null===(s=e.props)||void 0===s?void 0:s.getctag,calendarColor:null===(c=e.props)||void 0===c?void 0:c.calendarColor,displayName:null!==(l=null===(u=e.props)||void 0===u?void 0:u.displayname._cdata)&&void 0!==l?l:null===(h=e.props)||void 0===h?void 0:h.displayname,components:Array.isArray(null===(d=e.props)||void 0===d?void 0:d.supportedCalendarComponentSet.comp)?null===(f=e.props)||void 0===f?void 0:f.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(y=null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp)||void 0===y?void 0:y._attributes.name],resourcetype:Object.keys(null===(g=e.props)||void 0===g?void 0:g.resourcetype),syncToken:null===(m=e.props)||void 0===m?void 0:m.syncToken,...Kr("projectedProps",Object.fromEntries(Object.entries(null!==(v=e.props)&&void 0!==v?v:{}).filter(([e])=>null==i?void 0:i[e])))}}).map(async e=>({...e,reports:await sn({collection:e,headers:Hr(t,a),fetchOptions:o,fetch:s})})))},xn=async e=>{const{calendar:t,objectUrls:r,filters:n,timeRange:i,headers:a,expand:o,urlFilter:s=Yr,useMultiGet:c=!0,headersToExclude:u,fetchOptions:l={},fetch:h}=e;i&&zr(i.start,i.end),An(`Fetching calendar objects from ${null==t?void 0:t.url}`);const d=["url"];if(!t||!tn(t,d)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${rn(t,d)} before fetchCalendarObjects`)}const f=null!=n?n:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VEVENT"},...i?{"time-range":{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}];let p=[];const y=(null!=r?r:(p=await On({url:t.url,props:{[`${V.DAV}:getetag`]:{},...o&&i?{[`${V.CALDAV}:calendar-data`]:{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}}:{}},filters:f,depth:"1",headers:Hr(a,u),fetchOptions:l,fetch:h})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(s).map(e=>new URL(e).pathname);let g=[];return y.length>0&&(g=o&&!r?p.filter(e=>{var r,n;const i=(null!==(r=e.href)&&void 0!==r?r:"").startsWith("http")?e.href:new URL(null!==(n=e.href)&&void 0!==n?n:"",t.url).href;return s(null!=i?i:"")}):c?await _n({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:{...o&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},objectUrls:y,depth:"1",headers:Hr(a,u),fetchOptions:l,fetch:h}):await On({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:{...o&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},filters:f,depth:"1",headers:Hr(a,u),fetchOptions:l,fetch:h})),g.map(e=>{var r,n,i,a,o,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(n=e.props)||void 0===n?void 0:n.getetag}`,data:null!==(o=null===(a=null===(i=e.props)||void 0===i?void 0:i.calendarData)||void 0===a?void 0:a._cdata)&&void 0!==o?o:null===(s=e.props)||void 0===s?void 0:s.calendarData}})},Rn=async e=>{const{calendar:t,iCalString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;return Xr({url:new URL(n,t.url).href,data:r,headers:Hr({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o,fetch:s})},Fn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;return Zr({url:t.url,data:t.data,etag:t.etag,headers:Hr({"content-type":"text/calendar; charset=utf-8",...r},n),fetchOptions:i,fetch:a})},Sn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;return Jr({url:t.url,etag:t.etag,headers:Hr(r,n),fetchOptions:i,fetch:a})},Nn=async e=>{var t;const{oldCalendars:r,account:n,detailedResult:i,headers:a,headersToExclude:o,fetchOptions:s={},fetch:c}=e;if(!n)throw new Error("Must have account before syncCalendars");const u=null!==(t=null!=r?r:n.calendars)&&void 0!==t?t:[],l=await Dn({account:n,headers:Hr(a,o),fetchOptions:s,fetch:c}),h=l.filter(e=>u.every(t=>!Vr(t.url,e.url)));An(`new calendars: ${h.map(e=>e.displayName)}`);const d=u.reduce((e,t)=>{const r=l.find(e=>Vr(e.url,t.url));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e},[]);An(`updated calendars: ${d.map(e=>e.displayName)}`);const f=await Promise.all(d.map(async e=>await ln({collection:{...e,objectMultiGet:_n},method:"webdav",headers:Hr(a,o),account:n,fetchOptions:s,fetch:c}))),p=u.filter(e=>l.every(t=>!Vr(t.url,e.url)));An(`deleted calendars: ${p.map(e=>e.displayName)}`);const y=u.filter(e=>l.some(t=>Vr(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)));return i?{created:h,updated:d,deleted:p}:[...y,...h,...f]},Ln=async e=>{const{url:t,timeRange:r,depth:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;if(!r)throw new Error("timeRange is required");zr(r.start,r.end);return(await an({url:t,body:{"free-busy-query":$r({_attributes:Mr([U.CALDAV]),[`${V.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:V.CALDAV,depth:n,headers:Hr(i,a),fetchOptions:o,fetch:s}))[0]};var kn=Object.freeze({__proto__:null,calendarMultiGet:_n,calendarQuery:On,createCalendarObject:Rn,deleteCalendarObject:Sn,fetchCalendarObjects:xn,fetchCalendarUserAddresses:Tn,fetchCalendars:Dn,freeBusyQuery:Ln,makeCalendar:Cn,syncCalendars:Nn,updateCalendarObject:Fn});const In=j("tsdav:account"),Un=async e=>{var t,r;In("Service discovery...");const{account:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e,c=null!=s?s:Pr,u=new URL(n.serverUrl),l=new URL(`/.well-known/${n.accountType}`,u);l.protocol=null!==(t=u.protocol)&&void 0!==t?t:"http";try{const e=await c(l.href,{headers:{...Hr(i,a),"Content-Type":"text/xml;charset=UTF-8"},method:"PROPFIND",body:'\n\n \n \n \n',redirect:"manual",...o});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){In(`Service discovery redirected to ${t}`);const e=new URL(t,u);return e.hostname===l.hostname&&l.port&&!e.port&&(e.port=l.port),e.protocol=null!==(r=u.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){In(`Service discovery failed: ${e.stack}`)}return u.href},Pn=async e=>{var t,r,n,i,a;const{account:o,headers:s,headersToExclude:c,fetchOptions:u={},fetch:l}=e,h=["rootUrl"];if(!tn(o,h))throw new Error(`account must have ${rn(o,h)} before fetchPrincipalUrl`);In(`Fetching principal url from path ${o.rootUrl}`);const[d]=await Qr({url:o.rootUrl,props:{[`${V.DAV}:current-user-principal`]:{}},depth:"0",headers:Hr(s,c),fetchOptions:u,fetch:l});if(!d.ok&&(In(`Fetch principal url failed: ${d.statusText}`),401===d.status))throw new Error("Invalid credentials");return In(`Fetched principal url ${null===(r=null===(t=d.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(a=null===(i=null===(n=d.props)||void 0===n?void 0:n.currentUserPrincipal)||void 0===i?void 0:i.href)&&void 0!==a?a:"",o.rootUrl).href},jn=async e=>{var t,r;const{account:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e,c=["principalUrl","rootUrl"];if(!tn(n,c))throw new Error(`account must have ${rn(n,c)} before fetchHomeUrl`);In(`Fetch home url from ${n.principalUrl}`);const u=await Qr({url:n.principalUrl,props:"caldav"===n.accountType?{[`${V.CALDAV}:calendar-home-set`]:{}}:{[`${V.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:Hr(i,a),fetchOptions:o,fetch:s}),l=u.find(e=>Vr(n.principalUrl,e.href));if(!l||!l.ok)throw In(`Fetch home url failed with status ${null==l?void 0:l.statusText} and error ${JSON.stringify(u.map(e=>e.error))}`),new Error("cannot find homeUrl");const h=new URL("caldav"===n.accountType?null===(t=null==l?void 0:l.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==l?void 0:l.props)||void 0===r?void 0:r.addressbookHomeSet.href,n.rootUrl).href;return In(`Fetched home url ${h}`),h},Bn=async e=>{const{account:t,headers:r,loadCollections:n=!1,loadObjects:i=!1,headersToExclude:a,fetchOptions:o={},fetch:s}=e,c={...t};return c.rootUrl=await Un({account:t,headers:Hr(r,a),fetchOptions:o,fetch:s}),c.principalUrl=await Pn({account:c,headers:Hr(r,a),fetchOptions:o,fetch:s}),c.homeUrl=await jn({account:c,headers:Hr(r,a),fetchOptions:o,fetch:s}),(n||i)&&("caldav"===t.accountType?c.calendars=await Dn({headers:Hr(r,a),account:c,fetchOptions:o,fetch:s}):"carddav"===t.accountType&&(c.addressBooks=await yn({headers:Hr(r,a),account:c,fetchOptions:o,fetch:s}))),i&&("caldav"===t.accountType&&c.calendars?c.calendars=await Promise.all(c.calendars.map(async e=>({...e,objects:await xn({calendar:e,headers:Hr(r,a),fetchOptions:o,fetch:s})}))):"carddav"===t.accountType&&c.addressBooks&&(c.addressBooks=await Promise.all(c.addressBooks.map(async e=>({...e,objects:await gn({addressBook:e,headers:Hr(r,a),fetchOptions:o,fetch:s})}))))),c};var Vn=Object.freeze({__proto__:null,createAccount:Bn,fetchHomeUrl:jn,fetchPrincipalUrl:Pn,serviceDiscovery:Un});const Mn=j("tsdav:todo"),$n=e=>({[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(e.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(e.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}),Kn=async e=>{const{url:t,props:r,filters:n,timezone:i,depth:a,headers:o,headersToExclude:s,fetchOptions:c={},fetch:u}=e;return an({url:t,body:{"calendar-query":$r({_attributes:Mr([U.CALDAV,U.CALENDAR_SERVER,U.CALDAV_APPLE,U.DAV]),[`${V.DAV}:prop`]:r,filter:n,timezone:i})},defaultNamespace:V.CALDAV,depth:a,headers:Hr(o,s),fetchOptions:c,fetch:u})},Hn=async e=>{const{url:t,props:r,objectUrls:n,filters:i,timezone:a,depth:o,headers:s,headersToExclude:c,fetchOptions:u={},fetch:l}=e;return an({url:t,body:{"calendar-multiget":$r({_attributes:Mr([U.DAV,U.CALDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n,filter:i,timezone:a})},defaultNamespace:V.CALDAV,depth:o,headers:Hr(s,c),fetchOptions:u,fetch:l})},Yn=async e=>{const{calendar:t,objectUrls:r,filters:n,timeRange:i,headers:a,expand:o,urlFilter:s=Yr,useMultiGet:c=!0,headersToExclude:u,fetchOptions:l={},fetch:h}=e;i&&zr(i.start,i.end),Mn(`Fetching todo objects from ${null==t?void 0:t.url}`);const d=["url"];if(!t||!tn(t,d)){if(!t)throw new Error("cannot fetchTodos for undefined calendar");throw new Error(`calendar must have ${rn(t,d)} before fetchTodos`)}const f=null!=n?n:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VTODO"},...i?{"time-range":{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}],p=(null!=r?r:(await Kn({url:t.url,props:{[`${V.DAV}:getetag`]:{...o&&i?$n(i):{}}},filters:f,depth:"1",headers:Hr(a,u),fetchOptions:l,fetch:h})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(s).map(e=>new URL(e).pathname);let y=[];return p.length>0&&(y=!c||o?await Kn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:{...o&&i?$n(i):{}}},filters:f,depth:"1",headers:Hr(a,u),fetchOptions:l,fetch:h}):await Hn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:{...o&&i?$n(i):{}}},objectUrls:p,depth:"1",headers:Hr(a,u),fetchOptions:l,fetch:h})),y.map(e=>{var r,n,i,a,o,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(n=e.props)||void 0===n?void 0:n.getetag}`,data:null!==(o=null===(a=null===(i=e.props)||void 0===i?void 0:i.calendarData)||void 0===a?void 0:a._cdata)&&void 0!==o?o:null===(s=e.props)||void 0===s?void 0:s.calendarData}})},zn=async e=>{const{calendar:t,iCalString:r,filename:n,headers:i,headersToExclude:a,fetchOptions:o={},fetch:s}=e;if(!r.includes("UID:"))throw new Error("iCalString must contain a UID");return Xr({url:new URL(n,t.url).href,data:r,headers:Hr({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...i},a),fetchOptions:o,fetch:s})},qn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;if(!t.etag)throw new Error("calendarObject must have etag for update - fetch todo first");return Zr({url:t.url,data:t.data,etag:t.etag,headers:Hr({"content-type":"text/calendar; charset=utf-8",...r},n),fetchOptions:i,fetch:a})},Gn=async e=>{const{calendarObject:t,headers:r,headersToExclude:n,fetchOptions:i={},fetch:a}=e;return Jr({url:t.url,etag:t.etag,headers:Hr(r,n),fetchOptions:i,fetch:a})};var Wn,Qn=Object.freeze({__proto__:null,createTodo:zn,deleteTodo:Gn,fetchTodos:Yn,todoMultiGet:Hn,todoQuery:Kn,updateTodo:qn}),Xn={exports:{}};var Zn,Jn,ei=(Wn||(Wn=1,Zn=Xn,Jn=Xn.exports,function(t){var r=Jn,n=Zn&&Zn.exports==r&&Zn,i="object"==typeof e&&e;i.global!==i&&i.window!==i||(t=i);var a=function(e){this.message=e};(a.prototype=new Error).name="InvalidCharacterError";var o=function(e){throw new a(e)},s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=/[\t\n\f\r ]/g,u={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&o("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,i,a=e.length%3,c="",u=-1,l=e.length-a;++u>18&63)+s.charAt(i>>12&63)+s.charAt(i>>6&63)+s.charAt(63&i);return 2==a?(t=e.charCodeAt(u)<<8,r=e.charCodeAt(++u),c+=s.charAt((i=t+r)>>10)+s.charAt(i>>4&63)+s.charAt(i<<2&63)+"="):1==a&&(i=e.charCodeAt(u),c+=s.charAt(i>>2)+s.charAt(i<<4&63)+"=="),c},decode:function(e){var t=(e=String(e).replace(c,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&o("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,i=0,a="",u=-1;++u>(-2*i&6)));return a},version:"1.0.0"};if(r&&!r.nodeType)if(n)n.exports=u;else for(var l in u)u.hasOwnProperty(l)&&(r[l]=u[l]);else t.base64=u}(Xn.exports)),Xn.exports);const ti=j("tsdav:authHelper"),ri=(e,t)=>(...r)=>e({...t,...r[0]}),ni=e=>(ti(`Basic auth token generated: ${ei.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${ei.encode(`${e.username}:${e.password}`)}`}),ii=e=>({authorization:`Bearer ${e.accessToken}`}),ai=async(e,t,r)=>{const n=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!tn(e,n))throw new Error(`Oauth credentials missing: ${rn(e,n)}`);const i=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ti(e.tokenUrl),ti(i.toString());const a=null!=r?r:Pr,o=await a(e.tokenUrl,{method:"POST",body:i.toString(),headers:{"content-length":`${i.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(o.ok){return await o.json()}return ti(`Fetch Oauth tokens failed: ${await o.text()}`),{}},oi=async(e,t,r)=>{const n=["refreshToken","clientId","clientSecret","tokenUrl"];if(!tn(e,n))throw new Error(`Oauth credentials missing: ${rn(e,n)}`);const i=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),a=null!=r?r:Pr,o=await a(e.tokenUrl,{method:"POST",body:i.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(o.ok){return await o.json()}return ti(`Refresh access token failed: ${await o.text()}`),{}},si=async(e,t,r)=>{var n;ti("Fetching oauth headers");let i={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(n=e.expiration)&&void 0!==n?n:0))&&(i=await oi(e,t,r)):i=await ai(e,t,r),ti(`Oauth tokens fetched: ${i.access_token}`),{tokens:i,headers:{authorization:`Bearer ${i.access_token}`}}};var ci=Object.freeze({__proto__:null,defaultParam:ri,fetchOauthTokens:ai,getBasicAuthHeaders:ni,getBearerAuthHeaders:ii,getOauthHeaders:si,refreshAccessToken:oi});const ui=async e=>{var t;const{serverUrl:r,credentials:n,authMethod:i,defaultAccountType:a,authFunction:o,fetch:s}=e;let c={};switch(i){case"Basic":c=ni(n);break;case"Bearer":c=ii(n);break;case"Oauth":c=(await si(n,void 0,s)).headers;break;case"Digest":c={Authorization:`Digest ${n.digestString}`};break;case"Custom":c=null!==(t=await(null==o?void 0:o(n)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const u=a?await Bn({account:{serverUrl:r,credentials:n,accountType:a},headers:c,fetch:s}):void 0,l=ri(Xr,{url:r,headers:c,fetch:s}),h=ri(Zr,{headers:c,url:r,fetch:s}),d=ri(Jr,{headers:c,url:r,fetch:s}),f=ri(Qr,{headers:c,fetch:s}),p=ri(an,{headers:c,fetch:s}),y=ri(on,{headers:c,fetch:s}),g=ri(un,{headers:c,fetch:s}),m=ri(sn,{headers:c,fetch:s}),v=ri(cn,{headers:c,fetch:s}),b=ri(ln,{headers:c,account:u,fetch:s}),w=ri(On,{headers:c,fetch:s}),E=ri(_n,{headers:c,fetch:s}),A=ri(Cn,{headers:c,fetch:s}),T=ri(Dn,{headers:c,account:u,fetch:s}),O=ri(Tn,{headers:c,account:u,fetch:s}),_=ri(xn,{headers:c,fetch:s}),C=ri(Rn,{headers:c,fetch:s}),D=ri(Fn,{headers:c,fetch:s}),x=ri(Sn,{headers:c,fetch:s}),R=ri(Nn,{account:u,headers:c,fetch:s}),F=ri(fn,{headers:c,fetch:s}),S=ri(pn,{headers:c,fetch:s}),N=ri(wn,{headers:c,fetch:s});return{davRequest:async e=>{const{init:t,fetch:r,...n}=e,{headers:i,...a}=t;return Wr({...n,init:{...a,headers:{...c,...i}},fetch:null!=r?r:s})},propfind:f,createAccount:async e=>{const{account:t,headers:i,loadCollections:a,loadObjects:o,fetch:u}=e;return Bn({account:{serverUrl:r,credentials:n,...t},headers:{...c,...i},loadCollections:a,loadObjects:o,fetch:null!=u?u:s})},createObject:l,updateObject:h,deleteObject:d,calendarQuery:w,addressBookQuery:F,collectionQuery:p,makeCollection:y,calendarMultiGet:E,makeCalendar:A,syncCollection:g,supportedReportSet:m,isCollectionDirty:v,smartCollectionSync:b,fetchCalendars:T,fetchCalendarUserAddresses:O,fetchCalendarObjects:_,createCalendarObject:C,updateCalendarObject:D,deleteCalendarObject:x,syncCalendars:R,fetchAddressBooks:ri(yn,{account:u,headers:c,fetch:s}),addressBookMultiGet:S,makeAddressBook:N,fetchVCards:ri(gn,{headers:c,fetch:s}),createVCard:ri(mn,{headers:c,fetch:s}),updateVCard:ri(vn,{headers:c,fetch:s}),deleteVCard:ri(bn,{headers:c,fetch:s}),todoQuery:ri(Kn,{headers:c,fetch:s}),todoMultiGet:ri(Hn,{headers:c,fetch:s}),fetchTodos:ri(Yn,{headers:c,fetch:s}),createTodo:ri(zn,{headers:c,fetch:s}),updateTodo:ri(qn,{headers:c,fetch:s}),deleteTodo:ri(Gn,{headers:c,fetch:s})}};class li{constructor(e){var t,r,n;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav",this.authFunction=e.authFunction,this.fetchOptions=null!==(n=e.fetchOptions)&&void 0!==n?n:{},this.fetchOverride=e.fetch}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=ni(this.credentials);break;case"Bearer":this.authHeaders=ii(this.credentials);break;case"Oauth":this.authHeaders=(await si(this.credentials,this.fetchOptions,this.fetchOverride)).headers;break;case"Digest":this.authHeaders={Authorization:`Digest ${this.credentials.digestString}`};break;case"Custom":this.authHeaders=await(null===(e=this.authFunction)||void 0===e?void 0:e.call(this,this.credentials));break;default:throw new Error("Invalid auth method")}this.account=this.accountType?await Bn({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride}):void 0}async davRequest(e){const{init:t,fetch:r,...n}=e,{headers:i,...a}=t;return Wr({...n,init:{...a,headers:{...this.authHeaders,...i}},fetchOptions:this.fetchOptions,fetch:null!=r?r:this.fetchOverride})}async createObject(...e){return ri(Xr,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateObject(...e){return ri(Zr,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteObject(...e){return ri(Jr,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async propfind(...e){return ri(Qr,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:n,loadObjects:i,fetchOptions:a,fetch:o}=e;return Bn({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:n,loadObjects:i,fetchOptions:null!=a?a:this.fetchOptions,fetch:null!=o?o:this.fetchOverride})}async collectionQuery(...e){return ri(an,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCollection(...e){return ri(on,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCollection(...e){return ri(un,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async supportedReportSet(...e){return ri(sn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async isCollectionDirty(...e){return ri(cn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async smartCollectionSync(...e){return ri(ln,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride,account:this.account})(e[0])}async calendarQuery(...e){return ri(On,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCalendar(...e){return ri(Cn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async calendarMultiGet(...e){return ri(_n,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchCalendars(...e){return ri(Dn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return ri(Tn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return ri(xn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createCalendarObject(...e){return ri(Rn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateCalendarObject(...e){return ri(Fn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteCalendarObject(...e){return ri(Sn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCalendars(...e){return ri(Nn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookQuery(...e){return ri(fn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookMultiGet(...e){return ri(pn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeAddressBook(...e){return ri(wn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchAddressBooks(...e){return ri(yn,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchVCards(...e){return ri(gn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createVCard(...e){return ri(mn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateVCard(...e){return ri(vn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteVCard(...e){return ri(bn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async todoQuery(...e){return ri(Kn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async todoMultiGet(...e){return ri(Hn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchTodos(...e){return ri(Yn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createTodo(...e){return ri(zn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateTodo(...e){return ri(qn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteTodo(...e){return ri(Gn,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}}var hi={DAVNamespace:U,DAVNamespaceShort:V,DAVAttributeMap:B,...Object.freeze({__proto__:null,DAVClient:li,createDAVClient:ui}),...en,...hn,...Vn,...En,...kn,...Qn,...ci,...qr};export{B as DAVAttributeMap,li as DAVClient,U as DAVNamespace,V as DAVNamespaceShort,pn as addressBookMultiGet,fn as addressBookQuery,_n as calendarMultiGet,On as calendarQuery,$r as cleanupFalsy,an as collectionQuery,Bn as createAccount,Rn as createCalendarObject,ui as createDAVClient,Xr as createObject,zn as createTodo,mn as createVCard,Wr as davRequest,hi as default,Sn as deleteCalendarObject,Jr as deleteObject,Gn as deleteTodo,bn as deleteVCard,yn as fetchAddressBooks,xn as fetchCalendarObjects,Tn as fetchCalendarUserAddresses,Dn as fetchCalendars,ai as fetchOauthTokens,Yn as fetchTodos,gn as fetchVCards,Ln as freeBusyQuery,ni as getBasicAuthHeaders,ii as getBearerAuthHeaders,Mr as getDAVAttribute,si as getOauthHeaders,cn as isCollectionDirty,wn as makeAddressBook,Cn as makeCalendar,Qr as propfind,oi as refreshAccessToken,ln as smartCollectionSync,sn as supportedReportSet,Nn as syncCalendars,un as syncCollection,Hn as todoMultiGet,Kn as todoQuery,Fn as updateCalendarObject,Zr as updateObject,qn as updateTodo,vn as updateVCard,Vr as urlContains,Br as urlEquals}; diff --git a/dist/tsdav.min.mjs b/dist/tsdav.min.mjs index 5a2b9189..287c2b3b 100644 --- a/dist/tsdav.min.mjs +++ b/dist/tsdav.min.mjs @@ -1 +1 @@ -import e from"debug";import t from"xml-js";import r from"cross-fetch";import{encode as a}from"base-64";var s;!function(e){e.CALENDAR_SERVER="http://calendarserver.org/ns/",e.CALDAV_APPLE="http://apple.com/ns/ical/",e.CALDAV="urn:ietf:params:xml:ns:caldav",e.CARDDAV="urn:ietf:params:xml:ns:carddav",e.DAV="DAV:"}(s||(s={}));const o={[s.CALDAV]:"xmlns:c",[s.CARDDAV]:"xmlns:card",[s.CALENDAR_SERVER]:"xmlns:cs",[s.CALDAV_APPLE]:"xmlns:ca",[s.DAV]:"xmlns:d"};var n,c;!function(e){e.CALDAV="c",e.CARDDAV="card",e.CALENDAR_SERVER="cs",e.CALDAV_APPLE="ca",e.DAV="d"}(n||(n={})),function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(c||(c={}));const d="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):r,i=e=>{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},l=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),a=t.trim();if(Math.abs(r.length-a.length)>1)return!1;const s="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===a.slice(-1)?a.slice(0,-1):a;return e.includes(o)||t.includes(s)},h=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),a=t.trim(),s="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===a.slice(-1)?a.slice(0,-1):a;return e.includes(o)||t.includes(s)},u=e=>e.reduce((e,t)=>({...e,[o[t]]:t}),{}),p=e=>Object.entries(e).reduce((e,[t,r])=>r?{...e,[t]:r}:e,{}),f=(e,t)=>t?{[e]:t}:{},v=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))):e:{},O=e=>Boolean(null==e?void 0:e.includes(".ics")),y=(e,t)=>{const r=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,a=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(r.test(e)&&r.test(t)||a.test(e)&&a.test(t)))throw new Error("invalid timeRange format, not in ISO8601")};var m=Object.freeze({__proto__:null,cleanupFalsy:p,conditionalParam:f,defaultIcsFilter:O,excludeHeaders:v,getDAVAttribute:u,urlContains:h,urlEquals:l,validateISO8601TimeRange:y});const A=e("tsdav:request"),g=async e=>{var r;const{url:a,init:s,convertIncoming:o=!0,parseOutgoing:n=!0,fetchOptions:c={},fetch:l}=e,h=null!=l?l:d,{headers:u={},body:f,namespace:v,method:O,attributes:y}=s,m=o?t.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...f,_attributes:y},{compact:!0,spaces:2,elementNameFn:e=>v&&!/^.+:.+/.test(e)?`${v}:${e}`:e}):f,g={...c};delete g.headers;const D=await h(a,{headers:{"Content-Type":"text/xml;charset=UTF-8",...p(u),...c.headers||{}},body:m,method:O,...g}),w=await D.text();if(!(D.ok&&(null===(r=D.headers.get("content-type"))||void 0===r?void 0:r.includes("xml"))&&n&&w))return[{href:D.url,ok:D.ok,status:D.status,statusText:D.statusText,raw:w}];const b=t.xml2js(w,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,a=Object.keys(r),s=a[a.length-1],o=r[s];if(o.length>0){o[o.length-1]=i(e)}else r[s]=i(e)}catch(e){A(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,e=>e[1].toUpperCase()),attributesFn:e=>{const t={...e};return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(b.multistatus.response)?b.multistatus.response:[b.multistatus.response]).map(e=>{var t,r;if(!e)return{status:D.status,statusText:D.statusText,ok:D.ok};const a=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:b,href:e.href,status:(null==a?void 0:a.groups)?Number.parseInt(null==a?void 0:a.groups.status,10):D.status,statusText:null!==(r=null===(t=null==a?void 0:a.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:D.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce((e,t)=>({...e,...null==t?void 0:t.prop}),{})}})},D=async e=>{const{url:t,props:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e;return g({url:t,init:{method:"PROPFIND",headers:v(p({depth:a,...o}),c),namespace:n.DAV,body:{propfind:{_attributes:u([s.CALDAV,s.CALDAV_APPLE,s.CALENDAR_SERVER,s.CARDDAV,s.DAV]),prop:r}}},fetchOptions:d,fetch:i})},w=async e=>{const{url:t,data:r,headers:a,headersToExclude:s,fetchOptions:o={},fetch:n}=e;return(null!=n?n:d)(t,{method:"PUT",body:r,headers:v(a,s),...o})},b=async e=>{const{url:t,data:r,etag:a,headers:s,headersToExclude:o,fetchOptions:n={},fetch:c}=e;return(null!=c?c:d)(t,{method:"PUT",body:r,headers:v(p({"If-Match":a,...s}),o),...n})},C=async e=>{const{url:t,headers:r,etag:a,headersToExclude:s,fetchOptions:o={},fetch:n}=e;return(null!=n?n:d)(t,{method:"DELETE",headers:v(p({"If-Match":a,...r}),s),...o})};var V=Object.freeze({__proto__:null,createObject:w,davRequest:g,deleteObject:C,propfind:D,updateObject:b});function $(e,t){const r=e=>t.every(t=>e[t]);return Array.isArray(e)?e.every(e=>r(e)):r(e)}const T=(e,t)=>t.reduce((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`,""),E=e("tsdav:collection"),k=async e=>{const{url:t,body:r,depth:a,defaultNamespace:s=n.DAV,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e,l=await g({url:t,init:{method:"REPORT",headers:v(p({depth:a,...o}),c),namespace:s,body:r},fetchOptions:d,fetch:i}),h=l.find(e=>!e.ok||e.status&&e.status>=400);if(h)throw new Error(`Collection query failed: ${h.status} ${h.statusText}. ${h.raw?`Raw response: ${h.raw}`:""}`);return 1===l.length&&!l[0].raw&&l[0].status&&l[0].status<300?[]:l},_=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:d}=e;return g({url:t,init:{method:"MKCOL",headers:v(p({depth:a,...s}),o),namespace:n.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:c,fetch:d})},U=async e=>{var t,r,a,s,o;const{collection:c,headers:d,headersToExclude:i,fetchOptions:l={},fetch:h}=e;return null!==(o=null===(s=null===(a=null===(r=null===(t=(await D({url:c.url,props:{[`${n.DAV}:supported-report-set`]:{}},depth:"0",headers:v(d,i),fetchOptions:l,fetch:h}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===a?void 0:a.supportedReport)||void 0===s?void 0:s.map(e=>Object.keys(e.report)[0]))&&void 0!==o?o:[]},R=async e=>{var t,r,a;const{collection:s,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e,l=(await D({url:s.url,props:{[`${n.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:v(o,c),fetchOptions:d,fetch:i})).filter(e=>h(s.url,e.href))[0];if(!l)throw new Error("Collection does not exist on server");return{isDirty:`${s.ctag}`!=`${null===(t=l.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(a=null===(r=l.props)||void 0===r?void 0:r.getctag)||void 0===a?void 0:a.toString()}},L=e=>{const{url:t,props:r,headers:a,syncLevel:o,syncToken:c,headersToExclude:d,fetchOptions:i,fetch:l}=e;return g({url:t,init:{method:"REPORT",namespace:n.DAV,headers:v({...a},d),body:{"sync-collection":{_attributes:u([s.CALDAV,s.CARDDAV,s.DAV]),"sync-level":o,"sync-token":c,[`${n.DAV}:prop`]:r}}},fetchOptions:i,fetch:l})},x=async e=>{var t,r,a,s,o,c,d,i,l,u,p,f;const{collection:O,method:y,headers:m,headersToExclude:A,account:g,detailedResult:D,fetchOptions:w={},fetch:b}=e,C=["accountType","homeUrl"];if(!g||!$(g,C)){if(!g)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${T(g,C)} before smartCollectionSync`)}const V=null!=y?y:(null===(t=O.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(E(`smart collection sync with type ${g.accountType} and method ${V}`),"webdav"===V){const e=await L({url:O.url,props:{[`${n.DAV}:getetag`]:{},[`${"caldav"===g.accountType?n.CALDAV:n.CARDDAV}:${"caldav"===g.accountType?"calendar-data":"address-data"}`]:{},[`${n.DAV}:displayname`]:{}},syncLevel:1,syncToken:O.syncToken,headers:v(m,A),fetchOptions:w,fetch:b}),t=e.filter(e=>{var t;const r="caldav"===g.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r}),l=t.filter(e=>404!==e.status).map(e=>e.href),u=t.filter(e=>404===e.status).map(e=>e.href),p=(l.length&&null!==(a=await(null===(r=null==O?void 0:O.objectMultiGet)||void 0===r?void 0:r.call(O,{url:O.url,props:{[`${n.DAV}:getetag`]:{},[`${"caldav"===g.accountType?n.CALDAV:n.CARDDAV}:${"caldav"===g.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:l,depth:"1",headers:v(m,A),fetchOptions:w,fetch:b})))&&void 0!==a?a:[]).map(e=>{var t,r,a,s,o,n,c,d,i,l;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==g?void 0:g.accountType)?null!==(o=null===(s=null===(a=e.props)||void 0===a?void 0:a.calendarData)||void 0===s?void 0:s._cdata)&&void 0!==o?o:null===(n=e.props)||void 0===n?void 0:n.calendarData:null!==(i=null===(d=null===(c=e.props)||void 0===c?void 0:c.addressData)||void 0===d?void 0:d._cdata)&&void 0!==i?i:null===(l=e.props)||void 0===l?void 0:l.addressData}}),f=null!==(s=O.objects)&&void 0!==s?s:[],y=p.filter(e=>f.every(t=>!h(t.url,e.url))),C=f.reduce((e,t)=>{const r=p.find(e=>h(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),V=u.map(e=>({url:e,etag:""})),$=f.filter(e=>p.some(t=>h(e.url,t.url)&&t.etag===e.etag));return{...O,objects:D?{created:y,updated:C,deleted:V}:[...$,...y,...C],syncToken:null!==(i=null===(d=null===(c=null===(o=e[0])||void 0===o?void 0:o.raw)||void 0===c?void 0:c.multistatus)||void 0===d?void 0:d.syncToken)&&void 0!==i?i:O.syncToken}}if("basic"===V){const{isDirty:e,newCtag:t}=await R({collection:O,headers:v(m,A),fetchOptions:w,fetch:b}),r=null!==(l=O.objects)&&void 0!==l?l:[],a=null!==(f=await(null===(p=(u=O).fetchObjects)||void 0===p?void 0:p.call(u,{collection:O,headers:v(m,A),fetchOptions:w,fetch:b})))&&void 0!==f?f:[],s=a.filter(e=>r.every(t=>!h(t.url,e.url))),o=r.reduce((e,t)=>{const r=a.find(e=>h(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),n=r.filter(e=>a.every(t=>!h(t.url,e.url))),c=r.filter(e=>a.some(t=>h(e.url,t.url)&&t.etag===e.etag));if(e)return{...O,objects:D?{created:s,updated:o,deleted:n}:[...c,...s,...o],ctag:t}}return D?{...O,objects:{created:[],updated:[],deleted:[]}}:O};var S=Object.freeze({__proto__:null,collectionQuery:k,isCollectionDirty:R,makeCollection:_,smartCollectionSync:x,supportedReportSet:U,syncCollection:L});const j=e("tsdav:addressBook"),H=async e=>{const{url:t,props:r,filters:a,depth:o,headers:c,headersToExclude:d,fetchOptions:i={},fetch:l}=e;return k({url:t,body:{"addressbook-query":p({_attributes:u([s.CARDDAV,s.DAV]),[`${n.DAV}:prop`]:r,filter:null!=a?a:{"prop-filter":{_attributes:{name:"FN"}}}})},defaultNamespace:n.CARDDAV,depth:o,headers:v(c,d),fetchOptions:i,fetch:l})},N=async e=>{const{url:t,props:r,objectUrls:a,depth:o,headers:c,headersToExclude:d,fetchOptions:i={},fetch:l}=e;return k({url:t,body:{"addressbook-multiget":p({_attributes:u([s.DAV,s.CARDDAV]),[`${n.DAV}:prop`]:r,[`${n.DAV}:href`]:a})},defaultNamespace:n.CARDDAV,depth:o,headers:v(c,d),fetchOptions:i,fetch:l})},P=async e=>{const{account:t,headers:r,props:a,headersToExclude:s,fetchOptions:o={},fetch:c}=null!=e?e:{},d=["homeUrl","rootUrl"];if(!t||!$(t,d)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${T(t,d)} before fetchAddressBooks`)}const i=await D({url:t.homeUrl,props:null!=a?a:{[`${n.DAV}:displayname`]:{},[`${n.CALENDAR_SERVER}:getctag`]:{},[`${n.DAV}:resourcetype`]:{},[`${n.DAV}:sync-token`]:{}},depth:"1",headers:v(r,s),fetchOptions:o,fetch:c});return Promise.all(i.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")}).map(e=>{var r,a,s,o,n,c,d,i,l;const h=null!==(s=null===(a=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===a?void 0:a._cdata)&&void 0!==s?s:null===(o=e.props)||void 0===o?void 0:o.displayname;return j(`Found address book named ${"string"==typeof h?h:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(n=e.href)&&void 0!==n?n:"",null!==(c=t.rootUrl)&&void 0!==c?c:"").href,ctag:null===(d=e.props)||void 0===d?void 0:d.getctag,displayName:"string"==typeof h?h:"",resourcetype:Object.keys(null===(i=e.props)||void 0===i?void 0:i.resourcetype),syncToken:null===(l=e.props)||void 0===l?void 0:l.syncToken}}).map(async e=>({...e,reports:await U({collection:e,headers:v(r,s),fetchOptions:o,fetch:c})})))},B=async e=>{const{addressBook:t,headers:r,objectUrls:a,headersToExclude:s,urlFilter:o=e=>e,useMultiGet:c=!0,fetchOptions:d={},fetch:i}=e;j(`Fetching vcards from ${null==t?void 0:t.url}`);const h=["url"];if(!t||!$(t,h)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${T(t,h)} before fetchVCards`)}const u=(null!=a?a:(await H({url:t.url,props:{[`${n.DAV}:getetag`]:{}},depth:"1",headers:v(r,s),fetchOptions:d,fetch:i})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(e=>e&&!l(e,t.url)).filter(o).map(e=>new URL(e).pathname);let p=[];return u.length>0&&(p=c?await N({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CARDDAV}:address-data`]:{}},objectUrls:u,depth:"1",headers:v(r,s),fetchOptions:d,fetch:i}):await H({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CARDDAV}:address-data`]:{}},depth:"1",headers:v(r,s),fetchOptions:d,fetch:i})),p.map(e=>{var r,a,s,o,n,c;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(a=e.props)||void 0===a?void 0:a.getetag,data:null!==(n=null===(o=null===(s=e.props)||void 0===s?void 0:s.addressData)||void 0===o?void 0:o._cdata)&&void 0!==n?n:null===(c=e.props)||void 0===c?void 0:c.addressData}})},I=async e=>{const{addressBook:t,vCardString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={},fetch:c}=e;return w({url:new URL(a,t.url).href,data:r,headers:v({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n,fetch:c})},F=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return b({url:t.url,data:t.data,etag:t.etag,headers:v({"content-type":"text/vcard; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},M=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:v(r,a),fetchOptions:s,fetch:o})},z=async e=>{const{url:t,props:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e;return g({url:t,init:{method:"MKCOL",headers:v(p({depth:a,...o}),c),namespace:n.DAV,body:r?{mkcol:{_attributes:u([s.DAV,s.CARDDAV]),set:{prop:r}}}:void 0},fetchOptions:d,fetch:i})};var Z=Object.freeze({__proto__:null,addressBookMultiGet:N,addressBookQuery:H,createVCard:I,deleteVCard:M,fetchAddressBooks:P,fetchVCards:B,makeAddressBook:z,updateVCard:F});const G=e("tsdav:calendar"),Q=async e=>{var t,r,a;const{account:s,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e,l=["principalUrl","rootUrl"];if(!$(s,l))throw new Error(`account must have ${T(s,l)} before fetchUserAddresses`);G(`Fetch user addresses from ${s.principalUrl}`);const u=(await D({url:s.principalUrl,props:{[`${n.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:v(o,c),fetchOptions:d,fetch:i})).find(e=>h(s.principalUrl,e.href));if(!u||!u.ok)throw new Error("cannot find calendarUserAddresses");const p=(null===(a=null===(r=null===(t=null==u?void 0:u.props)||void 0===t?void 0:t.calendarUserAddressSet)||void 0===r?void 0:r.href)||void 0===a?void 0:a.filter(Boolean))||[];return G(`Fetched calendar user addresses ${p}`),p},q=async e=>{const{url:t,props:r,filters:a,timezone:o,depth:c,headers:d,headersToExclude:i,fetchOptions:l={},fetch:h}=e;return k({url:t,body:{"calendar-query":p({_attributes:u([s.CALDAV,s.CALENDAR_SERVER,s.CALDAV_APPLE,s.DAV]),[`${n.DAV}:prop`]:r,filter:a,timezone:o})},defaultNamespace:n.CALDAV,depth:c,headers:v(d,i),fetchOptions:l,fetch:h})},J=async e=>{const{url:t,props:r,objectUrls:a,filters:o,timezone:c,depth:d,headers:i,headersToExclude:l,fetchOptions:h={},fetch:f}=e;return k({url:t,body:{"calendar-multiget":p({_attributes:u([s.DAV,s.CALDAV]),[`${n.DAV}:prop`]:r,[`${n.DAV}:href`]:a,filter:o,timezone:c})},defaultNamespace:n.CALDAV,depth:d,headers:v(i,l),fetchOptions:h,fetch:f})},W=async e=>{const{url:t,props:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e;return g({url:t,init:{method:"MKCALENDAR",headers:v(p({depth:a,...o}),c),namespace:n.DAV,body:{[`${n.CALDAV}:mkcalendar`]:{_attributes:u([s.DAV,s.CALDAV,s.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:d,fetch:i})},K=async e=>{const{headers:t,account:r,props:a,projectedProps:s,headersToExclude:o,fetchOptions:d={},fetch:i}=null!=e?e:{},l=["homeUrl","rootUrl"];if(!r||!$(r,l)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${T(r,l)} before fetchCalendars`)}const h=await D({url:r.homeUrl,props:null!=a?a:{[`${n.CALDAV}:calendar-description`]:{},[`${n.CALDAV}:calendar-timezone`]:{},[`${n.DAV}:displayname`]:{},[`${n.CALDAV_APPLE}:calendar-color`]:{},[`${n.CALENDAR_SERVER}:getctag`]:{},[`${n.DAV}:resourcetype`]:{},[`${n.CALDAV}:supported-calendar-component-set`]:{},[`${n.DAV}:sync-token`]:{}},depth:"1",headers:v(t,o),fetchOptions:d,fetch:i});return Promise.all(h.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")}).filter(e=>{var t,r,a,s,o,n;return(Array.isArray(null===(r=null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet)||void 0===r?void 0:r.comp)?null===(a=e.props)||void 0===a?void 0:a.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(n=null===(o=null===(s=e.props)||void 0===s?void 0:s.supportedCalendarComponentSet)||void 0===o?void 0:o.comp)||void 0===n?void 0:n._attributes.name]).some(e=>Object.values(c).includes(e))}).map(e=>{var t,a,o,n,c,d,i,l,h,u,p,v,O,y,m,A;const g=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,D=null===(a=e.props)||void 0===a?void 0:a.calendarTimezone;return{description:"string"==typeof g?g:"",timezone:"string"==typeof D?D:"",url:new URL(null!==(o=e.href)&&void 0!==o?o:"",null!==(n=r.rootUrl)&&void 0!==n?n:"").href,ctag:null===(c=e.props)||void 0===c?void 0:c.getctag,calendarColor:null===(d=e.props)||void 0===d?void 0:d.calendarColor,displayName:null!==(l=null===(i=e.props)||void 0===i?void 0:i.displayname._cdata)&&void 0!==l?l:null===(h=e.props)||void 0===h?void 0:h.displayname,components:Array.isArray(null===(u=e.props)||void 0===u?void 0:u.supportedCalendarComponentSet.comp)?null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(O=null===(v=e.props)||void 0===v?void 0:v.supportedCalendarComponentSet.comp)||void 0===O?void 0:O._attributes.name],resourcetype:Object.keys(null===(y=e.props)||void 0===y?void 0:y.resourcetype),syncToken:null===(m=e.props)||void 0===m?void 0:m.syncToken,...f("projectedProps",Object.fromEntries(Object.entries(null!==(A=e.props)&&void 0!==A?A:{}).filter(([e])=>null==s?void 0:s[e])))}}).map(async e=>({...e,reports:await U({collection:e,headers:v(t,o),fetchOptions:d,fetch:i})})))},Y=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:c,urlFilter:d=O,useMultiGet:i=!0,headersToExclude:l,fetchOptions:h={},fetch:u}=e;s&&y(s.start,s.end),G(`Fetching calendar objects from ${null==t?void 0:t.url}`);const p=["url"];if(!t||!$(t,p)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${T(t,p)} before fetchCalendarObjects`)}const f=null!=a?a:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VEVENT"},...s?{"time-range":{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}];let m=[];const A=(null!=r?r:(m=await q({url:t.url,props:{[`${n.DAV}:getetag`]:{},...c&&s?{[`${n.CALDAV}:calendar-data`]:{[`${n.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}}:{}},filters:f,depth:"1",headers:v(o,l),fetchOptions:h,fetch:u})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(d).map(e=>new URL(e).pathname);let g=[];return A.length>0&&(g=c&&!r?m.filter(e=>{var r,a;const s=(null!==(r=e.href)&&void 0!==r?r:"").startsWith("http")?e.href:new URL(null!==(a=e.href)&&void 0!==a?a:"",t.url).href;return d(null!=s?s:"")}):i?await J({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CALDAV}:calendar-data`]:{...c&&s?{[`${n.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},objectUrls:A,depth:"1",headers:v(o,l),fetchOptions:h,fetch:u}):await q({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CALDAV}:calendar-data`]:{...c&&s?{[`${n.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},filters:f,depth:"1",headers:v(o,l),fetchOptions:h,fetch:u})),g.map(e=>{var r,a,s,o,n,c;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(a=e.props)||void 0===a?void 0:a.getetag}`,data:null!==(n=null===(o=null===(s=e.props)||void 0===s?void 0:s.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==n?n:null===(c=e.props)||void 0===c?void 0:c.calendarData}})},X=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={},fetch:c}=e;return w({url:new URL(a,t.url).href,data:r,headers:v({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n,fetch:c})},ee=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return b({url:t.url,data:t.data,etag:t.etag,headers:v({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},te=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:v(r,a),fetchOptions:s,fetch:o})},re=async e=>{var t;const{oldCalendars:r,account:a,detailedResult:s,headers:o,headersToExclude:n,fetchOptions:c={},fetch:d}=e;if(!a)throw new Error("Must have account before syncCalendars");const i=null!==(t=null!=r?r:a.calendars)&&void 0!==t?t:[],l=await K({account:a,headers:v(o,n),fetchOptions:c,fetch:d}),u=l.filter(e=>i.every(t=>!h(t.url,e.url)));G(`new calendars: ${u.map(e=>e.displayName)}`);const p=i.reduce((e,t)=>{const r=l.find(e=>h(e.url,t.url));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e},[]);G(`updated calendars: ${p.map(e=>e.displayName)}`);const f=await Promise.all(p.map(async e=>await x({collection:{...e,objectMultiGet:J},method:"webdav",headers:v(o,n),account:a,fetchOptions:c,fetch:d}))),O=i.filter(e=>l.every(t=>!h(t.url,e.url)));G(`deleted calendars: ${O.map(e=>e.displayName)}`);const y=i.filter(e=>l.some(t=>h(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)));return s?{created:u,updated:p,deleted:O}:[...y,...u,...f]},ae=async e=>{const{url:t,timeRange:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e;if(!r)throw new Error("timeRange is required");y(r.start,r.end);return(await k({url:t,body:{"free-busy-query":p({_attributes:u([s.CALDAV]),[`${n.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:n.CALDAV,depth:a,headers:v(o,c),fetchOptions:d,fetch:i}))[0]};var se=Object.freeze({__proto__:null,calendarMultiGet:J,calendarQuery:q,createCalendarObject:X,deleteCalendarObject:te,fetchCalendarObjects:Y,fetchCalendarUserAddresses:Q,fetchCalendars:K,freeBusyQuery:ae,makeCalendar:W,syncCalendars:re,updateCalendarObject:ee});const oe=e("tsdav:account"),ne=async e=>{var t,r;oe("Service discovery...");const{account:a,headers:s,headersToExclude:o,fetchOptions:n={},fetch:c}=e,i=null!=c?c:d,l=new URL(a.serverUrl),h=new URL(`/.well-known/${a.accountType}`,l);h.protocol=null!==(t=l.protocol)&&void 0!==t?t:"http";try{const e=await i(h.href,{headers:{...v(s,o),"Content-Type":"text/xml;charset=UTF-8"},method:"PROPFIND",body:'\n\n \n \n \n',redirect:"manual",...n});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){oe(`Service discovery redirected to ${t}`);const e=new URL(t,l);return e.hostname===h.hostname&&h.port&&!e.port&&(e.port=h.port),e.protocol=null!==(r=l.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){oe(`Service discovery failed: ${e.stack}`)}return l.href},ce=async e=>{var t,r,a,s,o;const{account:c,headers:d,headersToExclude:i,fetchOptions:l={},fetch:h}=e,u=["rootUrl"];if(!$(c,u))throw new Error(`account must have ${T(c,u)} before fetchPrincipalUrl`);oe(`Fetching principal url from path ${c.rootUrl}`);const[p]=await D({url:c.rootUrl,props:{[`${n.DAV}:current-user-principal`]:{}},depth:"0",headers:v(d,i),fetchOptions:l,fetch:h});if(!p.ok&&(oe(`Fetch principal url failed: ${p.statusText}`),401===p.status))throw new Error("Invalid credentials");return oe(`Fetched principal url ${null===(r=null===(t=p.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(o=null===(s=null===(a=p.props)||void 0===a?void 0:a.currentUserPrincipal)||void 0===s?void 0:s.href)&&void 0!==o?o:"",c.rootUrl).href},de=async e=>{var t,r;const{account:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:d}=e,i=["principalUrl","rootUrl"];if(!$(a,i))throw new Error(`account must have ${T(a,i)} before fetchHomeUrl`);oe(`Fetch home url from ${a.principalUrl}`);const l=await D({url:a.principalUrl,props:"caldav"===a.accountType?{[`${n.CALDAV}:calendar-home-set`]:{}}:{[`${n.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:v(s,o),fetchOptions:c,fetch:d}),u=l.find(e=>h(a.principalUrl,e.href));if(!u||!u.ok)throw oe(`Fetch home url failed with status ${null==u?void 0:u.statusText} and error ${JSON.stringify(l.map(e=>e.error))}`),new Error("cannot find homeUrl");const p=new URL("caldav"===a.accountType?null===(t=null==u?void 0:u.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==u?void 0:u.props)||void 0===r?void 0:r.addressbookHomeSet.href,a.rootUrl).href;return oe(`Fetched home url ${p}`),p},ie=async e=>{const{account:t,headers:r,loadCollections:a=!1,loadObjects:s=!1,headersToExclude:o,fetchOptions:n={},fetch:c}=e,d={...t};return d.rootUrl=await ne({account:t,headers:v(r,o),fetchOptions:n,fetch:c}),d.principalUrl=await ce({account:d,headers:v(r,o),fetchOptions:n,fetch:c}),d.homeUrl=await de({account:d,headers:v(r,o),fetchOptions:n,fetch:c}),(a||s)&&("caldav"===t.accountType?d.calendars=await K({headers:v(r,o),account:d,fetchOptions:n,fetch:c}):"carddav"===t.accountType&&(d.addressBooks=await P({headers:v(r,o),account:d,fetchOptions:n,fetch:c}))),s&&("caldav"===t.accountType&&d.calendars?d.calendars=await Promise.all(d.calendars.map(async e=>({...e,objects:await Y({calendar:e,headers:v(r,o),fetchOptions:n,fetch:c})}))):"carddav"===t.accountType&&d.addressBooks&&(d.addressBooks=await Promise.all(d.addressBooks.map(async e=>({...e,objects:await B({addressBook:e,headers:v(r,o),fetchOptions:n,fetch:c})}))))),d};var le=Object.freeze({__proto__:null,createAccount:ie,fetchHomeUrl:de,fetchPrincipalUrl:ce,serviceDiscovery:ne});const he=e("tsdav:todo"),ue=e=>({[`${n.CALDAV}:expand`]:{_attributes:{start:`${new Date(e.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(e.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}),pe=async e=>{const{url:t,props:r,filters:a,timezone:o,depth:c,headers:d,headersToExclude:i,fetchOptions:l={}}=e;return k({url:t,body:{"calendar-query":p({_attributes:u([s.CALDAV,s.CALENDAR_SERVER,s.CALDAV_APPLE,s.DAV]),[`${n.DAV}:prop`]:r,filter:a,timezone:o})},defaultNamespace:n.CALDAV,depth:c,headers:v(d,i),fetchOptions:l})},fe=async e=>{const{url:t,props:r,objectUrls:a,filters:o,timezone:c,depth:d,headers:i,headersToExclude:l,fetchOptions:h={}}=e;return k({url:t,body:{"calendar-multiget":p({_attributes:u([s.DAV,s.CALDAV]),[`${n.DAV}:prop`]:r,[`${n.DAV}:href`]:a,filter:o,timezone:c})},defaultNamespace:n.CALDAV,depth:d,headers:v(i,l),fetchOptions:h})},ve=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:c,urlFilter:d=O,useMultiGet:i=!0,headersToExclude:l,fetchOptions:h={}}=e;s&&y(s.start,s.end),he(`Fetching todo objects from ${null==t?void 0:t.url}`);const u=["url"];if(!t||!$(t,u)){if(!t)throw new Error("cannot fetchTodos for undefined calendar");throw new Error(`calendar must have ${T(t,u)} before fetchTodos`)}const p=null!=a?a:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VTODO"},...s?{"time-range":{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}],f=(null!=r?r:(await pe({url:t.url,props:{[`${n.DAV}:getetag`]:{...c&&s?ue(s):{}}},filters:p,depth:"1",headers:v(o,l),fetchOptions:h})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(d).map(e=>new URL(e).pathname);let m=[];return f.length>0&&(m=!i||c?await pe({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CALDAV}:calendar-data`]:{...c&&s?ue(s):{}}},filters:p,depth:"1",headers:v(o,l),fetchOptions:h}):await fe({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CALDAV}:calendar-data`]:{...c&&s?ue(s):{}}},objectUrls:f,depth:"1",headers:v(o,l),fetchOptions:h})),m.map(e=>{var r,a,s,o,n,c;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(a=e.props)||void 0===a?void 0:a.getetag}`,data:null!==(n=null===(o=null===(s=e.props)||void 0===s?void 0:s.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==n?n:null===(c=e.props)||void 0===c?void 0:c.calendarData}})},Oe=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={}}=e;if(!r.includes("UID:"))throw new Error("iCalString must contain a UID");return w({url:new URL(a,t.url).href,data:r,headers:v({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n})},ye=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;if(!t.etag)throw new Error("calendarObject must have etag for update - fetch todo first");return b({url:t.url,data:t.data,etag:t.etag,headers:v({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s})},me=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={}}=e;return C({url:t.url,etag:t.etag,headers:v(r,a),fetchOptions:s})};var Ae=Object.freeze({__proto__:null,createTodo:Oe,deleteTodo:me,fetchTodos:ve,todoMultiGet:fe,todoQuery:pe,updateTodo:ye});const ge=e("tsdav:authHelper"),De=(e,t)=>(...r)=>e({...t,...r[0]}),we=e=>(ge(`Basic auth token generated: ${a(`${e.username}:${e.password}`)}`),{authorization:`Basic ${a(`${e.username}:${e.password}`)}`}),be=e=>({authorization:`Bearer ${e.accessToken}`}),Ce=async(e,t,r)=>{const a=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!$(e,a))throw new Error(`Oauth credentials missing: ${T(e,a)}`);const s=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ge(e.tokenUrl),ge(s.toString());const o=null!=r?r:d,n=await o(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"content-length":`${s.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(n.ok){return await n.json()}return ge(`Fetch Oauth tokens failed: ${await n.text()}`),{}},Ve=async(e,t,r)=>{const a=["refreshToken","clientId","clientSecret","tokenUrl"];if(!$(e,a))throw new Error(`Oauth credentials missing: ${T(e,a)}`);const s=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),o=null!=r?r:d,n=await o(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(n.ok){return await n.json()}return ge(`Refresh access token failed: ${await n.text()}`),{}},$e=async(e,t,r)=>{var a;ge("Fetching oauth headers");let s={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(a=e.expiration)&&void 0!==a?a:0))&&(s=await Ve(e,t,r)):s=await Ce(e,t,r),ge(`Oauth tokens fetched: ${s.access_token}`),{tokens:s,headers:{authorization:`Bearer ${s.access_token}`}}};var Te=Object.freeze({__proto__:null,defaultParam:De,fetchOauthTokens:Ce,getBasicAuthHeaders:we,getBearerAuthHeaders:be,getOauthHeaders:$e,refreshAccessToken:Ve});const Ee=async e=>{var t;const{serverUrl:r,credentials:a,authMethod:s,defaultAccountType:o,authFunction:n,fetch:c}=e;let d={};switch(s){case"Basic":d=we(a);break;case"Bearer":d=be(a);break;case"Oauth":d=(await $e(a,void 0,c)).headers;break;case"Digest":d={Authorization:`Digest ${a.digestString}`};break;case"Custom":d=null!==(t=await(null==n?void 0:n(a)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const i=o?await ie({account:{serverUrl:r,credentials:a,accountType:o},headers:d,fetch:c}):void 0,l=De(w,{url:r,headers:d,fetch:c}),h=De(b,{headers:d,url:r,fetch:c}),u=De(C,{headers:d,url:r,fetch:c}),p=De(D,{headers:d,fetch:c}),f=De(k,{headers:d,fetch:c}),v=De(_,{headers:d,fetch:c}),O=De(L,{headers:d,fetch:c}),y=De(U,{headers:d,fetch:c}),m=De(R,{headers:d,fetch:c}),A=De(x,{headers:d,account:i,fetch:c}),V=De(q,{headers:d,fetch:c}),$=De(J,{headers:d,fetch:c}),T=De(W,{headers:d,fetch:c}),E=De(K,{headers:d,account:i,fetch:c}),S=De(Q,{headers:d,account:i,fetch:c}),j=De(Y,{headers:d,fetch:c}),Z=De(X,{headers:d,fetch:c}),G=De(ee,{headers:d,fetch:c}),ae=De(te,{headers:d,fetch:c}),se=De(re,{account:i,headers:d,fetch:c}),oe=De(H,{headers:d,fetch:c}),ne=De(N,{headers:d,fetch:c}),ce=De(z,{headers:d,fetch:c});return{davRequest:async e=>{const{init:t,fetch:r,...a}=e,{headers:s,...o}=t;return g({...a,init:{...o,headers:{...d,...s}},fetch:null!=r?r:c})},propfind:p,createAccount:async e=>{const{account:t,headers:s,loadCollections:o,loadObjects:n,fetch:i}=e;return ie({account:{serverUrl:r,credentials:a,...t},headers:{...d,...s},loadCollections:o,loadObjects:n,fetch:null!=i?i:c})},createObject:l,updateObject:h,deleteObject:u,calendarQuery:V,addressBookQuery:oe,collectionQuery:f,makeCollection:v,calendarMultiGet:$,makeCalendar:T,syncCollection:O,supportedReportSet:y,isCollectionDirty:m,smartCollectionSync:A,fetchCalendars:E,fetchCalendarUserAddresses:S,fetchCalendarObjects:j,createCalendarObject:Z,updateCalendarObject:G,deleteCalendarObject:ae,syncCalendars:se,fetchAddressBooks:De(P,{account:i,headers:d,fetch:c}),addressBookMultiGet:ne,makeAddressBook:ce,fetchVCards:De(B,{headers:d,fetch:c}),createVCard:De(I,{headers:d,fetch:c}),updateVCard:De(F,{headers:d,fetch:c}),deleteVCard:De(M,{headers:d,fetch:c}),todoQuery:De(pe,{headers:d}),todoMultiGet:De(fe,{headers:d}),fetchTodos:De(ve,{headers:d}),createTodo:De(Oe,{headers:d}),updateTodo:De(ye,{headers:d}),deleteTodo:De(me,{headers:d})}};class ke{constructor(e){var t,r,a;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav",this.authFunction=e.authFunction,this.fetchOptions=null!==(a=e.fetchOptions)&&void 0!==a?a:{},this.fetchOverride=e.fetch}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=we(this.credentials);break;case"Bearer":this.authHeaders=be(this.credentials);break;case"Oauth":this.authHeaders=(await $e(this.credentials,this.fetchOptions,this.fetchOverride)).headers;break;case"Digest":this.authHeaders={Authorization:`Digest ${this.credentials.digestString}`};break;case"Custom":this.authHeaders=await(null===(e=this.authFunction)||void 0===e?void 0:e.call(this,this.credentials));break;default:throw new Error("Invalid auth method")}this.account=this.accountType?await ie({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride}):void 0}async davRequest(e){const{init:t,fetch:r,...a}=e,{headers:s,...o}=t;return g({...a,init:{...o,headers:{...this.authHeaders,...s}},fetchOptions:this.fetchOptions,fetch:null!=r?r:this.fetchOverride})}async createObject(...e){return De(w,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateObject(...e){return De(b,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteObject(...e){return De(C,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async propfind(...e){return De(D,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:a,loadObjects:s,fetchOptions:o,fetch:n}=e;return ie({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:a,loadObjects:s,fetchOptions:null!=o?o:this.fetchOptions,fetch:null!=n?n:this.fetchOverride})}async collectionQuery(...e){return De(k,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCollection(...e){return De(_,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCollection(...e){return De(L,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async supportedReportSet(...e){return De(U,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async isCollectionDirty(...e){return De(R,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async smartCollectionSync(...e){return De(x,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride,account:this.account})(e[0])}async calendarQuery(...e){return De(q,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCalendar(...e){return De(W,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async calendarMultiGet(...e){return De(J,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchCalendars(...e){return De(K,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return De(Q,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return De(Y,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createCalendarObject(...e){return De(X,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateCalendarObject(...e){return De(ee,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteCalendarObject(...e){return De(te,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCalendars(...e){return De(re,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookQuery(...e){return De(H,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookMultiGet(...e){return De(N,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeAddressBook(...e){return De(z,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchAddressBooks(...e){return De(P,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchVCards(...e){return De(B,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createVCard(...e){return De(I,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateVCard(...e){return De(F,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteVCard(...e){return De(M,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async todoQuery(...e){return De(pe,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async todoMultiGet(...e){return De(fe,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async fetchTodos(...e){return De(ve,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async createTodo(...e){return De(Oe,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async updateTodo(...e){return De(ye,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}async deleteTodo(...e){return De(me,{headers:this.authHeaders,fetchOptions:this.fetchOptions})(e[0])}}var _e={DAVNamespace:s,DAVNamespaceShort:n,DAVAttributeMap:o,...Object.freeze({__proto__:null,DAVClient:ke,createDAVClient:Ee}),...V,...S,...le,...Z,...se,...Ae,...Te,...m};export{o as DAVAttributeMap,ke as DAVClient,s as DAVNamespace,n as DAVNamespaceShort,N as addressBookMultiGet,H as addressBookQuery,J as calendarMultiGet,q as calendarQuery,p as cleanupFalsy,k as collectionQuery,ie as createAccount,X as createCalendarObject,Ee as createDAVClient,w as createObject,Oe as createTodo,I as createVCard,g as davRequest,_e as default,te as deleteCalendarObject,C as deleteObject,me as deleteTodo,M as deleteVCard,P as fetchAddressBooks,Y as fetchCalendarObjects,Q as fetchCalendarUserAddresses,K as fetchCalendars,Ce as fetchOauthTokens,ve as fetchTodos,B as fetchVCards,ae as freeBusyQuery,we as getBasicAuthHeaders,be as getBearerAuthHeaders,u as getDAVAttribute,$e as getOauthHeaders,R as isCollectionDirty,z as makeAddressBook,W as makeCalendar,D as propfind,Ve as refreshAccessToken,x as smartCollectionSync,U as supportedReportSet,re as syncCalendars,L as syncCollection,fe as todoMultiGet,pe as todoQuery,ee as updateCalendarObject,b as updateObject,ye as updateTodo,F as updateVCard,h as urlContains,l as urlEquals}; +import e from"debug";import t from"xml-js";import r from"cross-fetch";import{encode as a}from"base-64";var s;!function(e){e.CALENDAR_SERVER="http://calendarserver.org/ns/",e.CALDAV_APPLE="http://apple.com/ns/ical/",e.CALDAV="urn:ietf:params:xml:ns:caldav",e.CARDDAV="urn:ietf:params:xml:ns:carddav",e.DAV="DAV:"}(s||(s={}));const o={[s.CALDAV]:"xmlns:c",[s.CARDDAV]:"xmlns:card",[s.CALENDAR_SERVER]:"xmlns:cs",[s.CALDAV_APPLE]:"xmlns:ca",[s.DAV]:"xmlns:d"};var n,c;!function(e){e.CALDAV="c",e.CARDDAV="card",e.CALENDAR_SERVER="cs",e.CALDAV_APPLE="ca",e.DAV="d"}(n||(n={})),function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(c||(c={}));const d="undefined"!=typeof globalThis&&"function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):r,i=e=>{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},h=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),a=t.trim();if(Math.abs(r.length-a.length)>1)return!1;const s="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===a.slice(-1)?a.slice(0,-1):a;return e.includes(o)||t.includes(s)},l=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),a=t.trim(),s="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===a.slice(-1)?a.slice(0,-1):a;return e.includes(o)||t.includes(s)},u=e=>e.reduce((e,t)=>({...e,[o[t]]:t}),{}),p=e=>Object.entries(e).reduce((e,[t,r])=>r?{...e,[t]:r}:e,{}),f=(e,t)=>t?{[e]:t}:{},v=(e,t)=>e?t&&0!==t.length?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))):e:{},O=e=>Boolean(null==e?void 0:e.includes(".ics")),y=(e,t)=>{const r=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,a=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(r.test(e)&&r.test(t)||a.test(e)&&a.test(t)))throw new Error("invalid timeRange format, not in ISO8601")};var m=Object.freeze({__proto__:null,cleanupFalsy:p,conditionalParam:f,defaultIcsFilter:O,excludeHeaders:v,getDAVAttribute:u,urlContains:l,urlEquals:h,validateISO8601TimeRange:y});const A=e("tsdav:request"),g=async e=>{var r;const{url:a,init:s,convertIncoming:o=!0,parseOutgoing:n=!0,fetchOptions:c={},fetch:h}=e,l=null!=h?h:d,{headers:u={},body:f,namespace:v,method:O,attributes:y}=s,m=o?t.js2xml({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}},...f,_attributes:y},{compact:!0,spaces:2,elementNameFn:e=>v&&!/^.+:.+/.test(e)?`${v}:${e}`:e}):f,g={...c};delete g.headers;const D=await l(a,{headers:{"Content-Type":"text/xml;charset=UTF-8",...p(u),...c.headers||{}},body:m,method:O,...g}),w=await D.text();if(!(D.ok&&(null===(r=D.headers.get("content-type"))||void 0===r?void 0:r.includes("xml"))&&n&&w))return[{href:D.url,ok:D.ok,status:D.status,statusText:D.statusText,raw:w}];const b=t.xml2js(w,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,a=Object.keys(r),s=a[a.length-1],o=r[s];if(o.length>0){o[o.length-1]=i(e)}else r[s]=i(e)}catch(e){A(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,e=>e[1].toUpperCase()),attributesFn:e=>{const t={...e};return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(b.multistatus.response)?b.multistatus.response:[b.multistatus.response]).map(e=>{var t,r;if(!e)return{status:D.status,statusText:D.statusText,ok:D.ok};const a=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:b,href:e.href,status:(null==a?void 0:a.groups)?Number.parseInt(null==a?void 0:a.groups.status,10):D.status,statusText:null!==(r=null===(t=null==a?void 0:a.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:D.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce((e,t)=>({...e,...null==t?void 0:t.prop}),{})}})},D=async e=>{const{url:t,props:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e;return g({url:t,init:{method:"PROPFIND",headers:v(p({depth:a,...o}),c),namespace:n.DAV,body:{propfind:{_attributes:u([s.CALDAV,s.CALDAV_APPLE,s.CALENDAR_SERVER,s.CARDDAV,s.DAV]),prop:r}}},fetchOptions:d,fetch:i})},w=async e=>{const{url:t,data:r,headers:a,headersToExclude:s,fetchOptions:o={},fetch:n}=e;return(null!=n?n:d)(t,{method:"PUT",body:r,headers:v(a,s),...o})},b=async e=>{const{url:t,data:r,etag:a,headers:s,headersToExclude:o,fetchOptions:n={},fetch:c}=e;return(null!=c?c:d)(t,{method:"PUT",body:r,headers:v(p({"If-Match":a,...s}),o),...n})},C=async e=>{const{url:t,headers:r,etag:a,headersToExclude:s,fetchOptions:o={},fetch:n}=e;return(null!=n?n:d)(t,{method:"DELETE",headers:v(p({"If-Match":a,...r}),s),...o})};var V=Object.freeze({__proto__:null,createObject:w,davRequest:g,deleteObject:C,propfind:D,updateObject:b});function $(e,t){const r=e=>t.every(t=>e[t]);return Array.isArray(e)?e.every(e=>r(e)):r(e)}const T=(e,t)=>t.reduce((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`,""),E=e("tsdav:collection"),k=async e=>{const{url:t,body:r,depth:a,defaultNamespace:s=n.DAV,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e,h=await g({url:t,init:{method:"REPORT",headers:v(p({depth:a,...o}),c),namespace:s,body:r},fetchOptions:d,fetch:i}),l=h.find(e=>!e.ok||e.status&&e.status>=400);if(l)throw new Error(`Collection query failed: ${l.status} ${l.statusText}. ${l.raw?`Raw response: ${l.raw}`:""}`);return 1===h.length&&!h[0].raw&&h[0].status&&h[0].status<300?[]:h},_=async e=>{const{url:t,props:r,depth:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:d}=e;return g({url:t,init:{method:"MKCOL",headers:v(p({depth:a,...s}),o),namespace:n.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0},fetchOptions:c,fetch:d})},U=async e=>{var t,r,a,s,o;const{collection:c,headers:d,headersToExclude:i,fetchOptions:h={},fetch:l}=e;return null!==(o=null===(s=null===(a=null===(r=null===(t=(await D({url:c.url,props:{[`${n.DAV}:supported-report-set`]:{}},depth:"0",headers:v(d,i),fetchOptions:h,fetch:l}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===a?void 0:a.supportedReport)||void 0===s?void 0:s.map(e=>Object.keys(e.report)[0]))&&void 0!==o?o:[]},R=async e=>{var t,r,a;const{collection:s,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e,h=(await D({url:s.url,props:{[`${n.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:v(o,c),fetchOptions:d,fetch:i})).filter(e=>l(s.url,e.href))[0];if(!h)throw new Error("Collection does not exist on server");return{isDirty:`${s.ctag}`!=`${null===(t=h.props)||void 0===t?void 0:t.getctag}`,newCtag:null===(a=null===(r=h.props)||void 0===r?void 0:r.getctag)||void 0===a?void 0:a.toString()}},L=e=>{const{url:t,props:r,headers:a,syncLevel:o,syncToken:c,headersToExclude:d,fetchOptions:i,fetch:h}=e;return g({url:t,init:{method:"REPORT",namespace:n.DAV,headers:v({...a},d),body:{"sync-collection":{_attributes:u([s.CALDAV,s.CARDDAV,s.DAV]),"sync-level":o,"sync-token":c,[`${n.DAV}:prop`]:r}}},fetchOptions:i,fetch:h})},x=async e=>{var t,r,a,s,o,c,d,i,h,u,p,f;const{collection:O,method:y,headers:m,headersToExclude:A,account:g,detailedResult:D,fetchOptions:w={},fetch:b}=e,C=["accountType","homeUrl"];if(!g||!$(g,C)){if(!g)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${T(g,C)} before smartCollectionSync`)}const V=null!=y?y:(null===(t=O.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(E(`smart collection sync with type ${g.accountType} and method ${V}`),"webdav"===V){const e=await L({url:O.url,props:{[`${n.DAV}:getetag`]:{},[`${"caldav"===g.accountType?n.CALDAV:n.CARDDAV}:${"caldav"===g.accountType?"calendar-data":"address-data"}`]:{},[`${n.DAV}:displayname`]:{}},syncLevel:1,syncToken:O.syncToken,headers:v(m,A),fetchOptions:w,fetch:b}),t=e.filter(e=>{var t;const r="caldav"===g.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r}),h=t.filter(e=>404!==e.status).map(e=>e.href),u=t.filter(e=>404===e.status).map(e=>e.href),p=(h.length&&null!==(a=await(null===(r=null==O?void 0:O.objectMultiGet)||void 0===r?void 0:r.call(O,{url:O.url,props:{[`${n.DAV}:getetag`]:{},[`${"caldav"===g.accountType?n.CALDAV:n.CARDDAV}:${"caldav"===g.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:h,depth:"1",headers:v(m,A),fetchOptions:w,fetch:b})))&&void 0!==a?a:[]).map(e=>{var t,r,a,s,o,n,c,d,i,h;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==g?void 0:g.accountType)?null!==(o=null===(s=null===(a=e.props)||void 0===a?void 0:a.calendarData)||void 0===s?void 0:s._cdata)&&void 0!==o?o:null===(n=e.props)||void 0===n?void 0:n.calendarData:null!==(i=null===(d=null===(c=e.props)||void 0===c?void 0:c.addressData)||void 0===d?void 0:d._cdata)&&void 0!==i?i:null===(h=e.props)||void 0===h?void 0:h.addressData}}),f=null!==(s=O.objects)&&void 0!==s?s:[],y=p.filter(e=>f.every(t=>!l(t.url,e.url))),C=f.reduce((e,t)=>{const r=p.find(e=>l(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),V=u.map(e=>({url:e,etag:""})),$=f.filter(e=>p.some(t=>l(e.url,t.url)&&t.etag===e.etag));return{...O,objects:D?{created:y,updated:C,deleted:V}:[...$,...y,...C],syncToken:null!==(i=null===(d=null===(c=null===(o=e[0])||void 0===o?void 0:o.raw)||void 0===c?void 0:c.multistatus)||void 0===d?void 0:d.syncToken)&&void 0!==i?i:O.syncToken}}if("basic"===V){const{isDirty:e,newCtag:t}=await R({collection:O,headers:v(m,A),fetchOptions:w,fetch:b}),r=null!==(h=O.objects)&&void 0!==h?h:[],a=null!==(f=await(null===(p=(u=O).fetchObjects)||void 0===p?void 0:p.call(u,{collection:O,headers:v(m,A),fetchOptions:w,fetch:b})))&&void 0!==f?f:[],s=a.filter(e=>r.every(t=>!l(t.url,e.url))),o=r.reduce((e,t)=>{const r=a.find(e=>l(e.url,t.url));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e},[]),n=r.filter(e=>a.every(t=>!l(t.url,e.url))),c=r.filter(e=>a.some(t=>l(e.url,t.url)&&t.etag===e.etag));if(e)return{...O,objects:D?{created:s,updated:o,deleted:n}:[...c,...s,...o],ctag:t}}return D?{...O,objects:{created:[],updated:[],deleted:[]}}:O};var S=Object.freeze({__proto__:null,collectionQuery:k,isCollectionDirty:R,makeCollection:_,smartCollectionSync:x,supportedReportSet:U,syncCollection:L});const j=e("tsdav:addressBook"),H=async e=>{const{url:t,props:r,filters:a,depth:o,headers:c,headersToExclude:d,fetchOptions:i={},fetch:h}=e;return k({url:t,body:{"addressbook-query":p({_attributes:u([s.CARDDAV,s.DAV]),[`${n.DAV}:prop`]:r,filter:null!=a?a:{"prop-filter":{_attributes:{name:"FN"}}}})},defaultNamespace:n.CARDDAV,depth:o,headers:v(c,d),fetchOptions:i,fetch:h})},N=async e=>{const{url:t,props:r,objectUrls:a,depth:o,headers:c,headersToExclude:d,fetchOptions:i={},fetch:h}=e;return k({url:t,body:{"addressbook-multiget":p({_attributes:u([s.DAV,s.CARDDAV]),[`${n.DAV}:prop`]:r,[`${n.DAV}:href`]:a})},defaultNamespace:n.CARDDAV,depth:o,headers:v(c,d),fetchOptions:i,fetch:h})},P=async e=>{const{account:t,headers:r,props:a,headersToExclude:s,fetchOptions:o={},fetch:c}=null!=e?e:{},d=["homeUrl","rootUrl"];if(!t||!$(t,d)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${T(t,d)} before fetchAddressBooks`)}const i=await D({url:t.homeUrl,props:null!=a?a:{[`${n.DAV}:displayname`]:{},[`${n.CALENDAR_SERVER}:getctag`]:{},[`${n.DAV}:resourcetype`]:{},[`${n.DAV}:sync-token`]:{}},depth:"1",headers:v(r,s),fetchOptions:o,fetch:c});return Promise.all(i.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")}).map(e=>{var r,a,s,o,n,c,d,i,h;const l=null!==(s=null===(a=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===a?void 0:a._cdata)&&void 0!==s?s:null===(o=e.props)||void 0===o?void 0:o.displayname;return j(`Found address book named ${"string"==typeof l?l:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(n=e.href)&&void 0!==n?n:"",null!==(c=t.rootUrl)&&void 0!==c?c:"").href,ctag:null===(d=e.props)||void 0===d?void 0:d.getctag,displayName:"string"==typeof l?l:"",resourcetype:Object.keys(null===(i=e.props)||void 0===i?void 0:i.resourcetype),syncToken:null===(h=e.props)||void 0===h?void 0:h.syncToken}}).map(async e=>({...e,reports:await U({collection:e,headers:v(r,s),fetchOptions:o,fetch:c})})))},B=async e=>{const{addressBook:t,headers:r,objectUrls:a,headersToExclude:s,urlFilter:o=e=>e,useMultiGet:c=!0,fetchOptions:d={},fetch:i}=e;j(`Fetching vcards from ${null==t?void 0:t.url}`);const l=["url"];if(!t||!$(t,l)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${T(t,l)} before fetchVCards`)}const u=(null!=a?a:(await H({url:t.url,props:{[`${n.DAV}:getetag`]:{}},depth:"1",headers:v(r,s),fetchOptions:d,fetch:i})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(e=>e&&!h(e,t.url)).filter(o).map(e=>new URL(e).pathname);let p=[];return u.length>0&&(p=c?await N({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CARDDAV}:address-data`]:{}},objectUrls:u,depth:"1",headers:v(r,s),fetchOptions:d,fetch:i}):await H({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CARDDAV}:address-data`]:{}},depth:"1",headers:v(r,s),fetchOptions:d,fetch:i})),p.map(e=>{var r,a,s,o,n,c;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(a=e.props)||void 0===a?void 0:a.getetag,data:null!==(n=null===(o=null===(s=e.props)||void 0===s?void 0:s.addressData)||void 0===o?void 0:o._cdata)&&void 0!==n?n:null===(c=e.props)||void 0===c?void 0:c.addressData}})},I=async e=>{const{addressBook:t,vCardString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={},fetch:c}=e;return w({url:new URL(a,t.url).href,data:r,headers:v({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n,fetch:c})},F=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return b({url:t.url,data:t.data,etag:t.etag,headers:v({"content-type":"text/vcard; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},M=async e=>{const{vCard:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:v(r,a),fetchOptions:s,fetch:o})},z=async e=>{const{url:t,props:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e;return g({url:t,init:{method:"MKCOL",headers:v(p({depth:a,...o}),c),namespace:n.DAV,body:r?{mkcol:{_attributes:u([s.DAV,s.CARDDAV]),set:{prop:r}}}:void 0},fetchOptions:d,fetch:i})};var Z=Object.freeze({__proto__:null,addressBookMultiGet:N,addressBookQuery:H,createVCard:I,deleteVCard:M,fetchAddressBooks:P,fetchVCards:B,makeAddressBook:z,updateVCard:F});const G=e("tsdav:calendar"),Q=async e=>{var t,r,a;const{account:s,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e,h=["principalUrl","rootUrl"];if(!$(s,h))throw new Error(`account must have ${T(s,h)} before fetchUserAddresses`);G(`Fetch user addresses from ${s.principalUrl}`);const u=(await D({url:s.principalUrl,props:{[`${n.CALDAV}:calendar-user-address-set`]:{}},depth:"0",headers:v(o,c),fetchOptions:d,fetch:i})).find(e=>l(s.principalUrl,e.href));if(!u||!u.ok)throw new Error("cannot find calendarUserAddresses");const p=(null===(a=null===(r=null===(t=null==u?void 0:u.props)||void 0===t?void 0:t.calendarUserAddressSet)||void 0===r?void 0:r.href)||void 0===a?void 0:a.filter(Boolean))||[];return G(`Fetched calendar user addresses ${p}`),p},q=async e=>{const{url:t,props:r,filters:a,timezone:o,depth:c,headers:d,headersToExclude:i,fetchOptions:h={},fetch:l}=e;return k({url:t,body:{"calendar-query":p({_attributes:u([s.CALDAV,s.CALENDAR_SERVER,s.CALDAV_APPLE,s.DAV]),[`${n.DAV}:prop`]:r,filter:a,timezone:o})},defaultNamespace:n.CALDAV,depth:c,headers:v(d,i),fetchOptions:h,fetch:l})},J=async e=>{const{url:t,props:r,objectUrls:a,filters:o,timezone:c,depth:d,headers:i,headersToExclude:h,fetchOptions:l={},fetch:f}=e;return k({url:t,body:{"calendar-multiget":p({_attributes:u([s.DAV,s.CALDAV]),[`${n.DAV}:prop`]:r,[`${n.DAV}:href`]:a,filter:o,timezone:c})},defaultNamespace:n.CALDAV,depth:d,headers:v(i,h),fetchOptions:l,fetch:f})},W=async e=>{const{url:t,props:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e;return g({url:t,init:{method:"MKCALENDAR",headers:v(p({depth:a,...o}),c),namespace:n.DAV,body:{[`${n.CALDAV}:mkcalendar`]:{_attributes:u([s.DAV,s.CALDAV,s.CALDAV_APPLE]),set:{prop:r}}}},fetchOptions:d,fetch:i})},K=async e=>{const{headers:t,account:r,props:a,projectedProps:s,headersToExclude:o,fetchOptions:d={},fetch:i}=null!=e?e:{},h=["homeUrl","rootUrl"];if(!r||!$(r,h)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${T(r,h)} before fetchCalendars`)}const l=await D({url:r.homeUrl,props:null!=a?a:{[`${n.CALDAV}:calendar-description`]:{},[`${n.CALDAV}:calendar-timezone`]:{},[`${n.DAV}:displayname`]:{},[`${n.CALDAV_APPLE}:calendar-color`]:{},[`${n.CALENDAR_SERVER}:getctag`]:{},[`${n.DAV}:resourcetype`]:{},[`${n.CALDAV}:supported-calendar-component-set`]:{},[`${n.DAV}:sync-token`]:{}},depth:"1",headers:v(t,o),fetchOptions:d,fetch:i});return Promise.all(l.filter(e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")}).filter(e=>{var t,r,a,s,o,n;return(Array.isArray(null===(r=null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet)||void 0===r?void 0:r.comp)?null===(a=e.props)||void 0===a?void 0:a.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(n=null===(o=null===(s=e.props)||void 0===s?void 0:s.supportedCalendarComponentSet)||void 0===o?void 0:o.comp)||void 0===n?void 0:n._attributes.name]).some(e=>Object.values(c).includes(e))}).map(e=>{var t,a,o,n,c,d,i,h,l,u,p,v,O,y,m,A;const g=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,D=null===(a=e.props)||void 0===a?void 0:a.calendarTimezone;return{description:"string"==typeof g?g:"",timezone:"string"==typeof D?D:"",url:new URL(null!==(o=e.href)&&void 0!==o?o:"",null!==(n=r.rootUrl)&&void 0!==n?n:"").href,ctag:null===(c=e.props)||void 0===c?void 0:c.getctag,calendarColor:null===(d=e.props)||void 0===d?void 0:d.calendarColor,displayName:null!==(h=null===(i=e.props)||void 0===i?void 0:i.displayname._cdata)&&void 0!==h?h:null===(l=e.props)||void 0===l?void 0:l.displayname,components:Array.isArray(null===(u=e.props)||void 0===u?void 0:u.supportedCalendarComponentSet.comp)?null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp.map(e=>e._attributes.name):[null===(O=null===(v=e.props)||void 0===v?void 0:v.supportedCalendarComponentSet.comp)||void 0===O?void 0:O._attributes.name],resourcetype:Object.keys(null===(y=e.props)||void 0===y?void 0:y.resourcetype),syncToken:null===(m=e.props)||void 0===m?void 0:m.syncToken,...f("projectedProps",Object.fromEntries(Object.entries(null!==(A=e.props)&&void 0!==A?A:{}).filter(([e])=>null==s?void 0:s[e])))}}).map(async e=>({...e,reports:await U({collection:e,headers:v(t,o),fetchOptions:d,fetch:i})})))},Y=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:c,urlFilter:d=O,useMultiGet:i=!0,headersToExclude:h,fetchOptions:l={},fetch:u}=e;s&&y(s.start,s.end),G(`Fetching calendar objects from ${null==t?void 0:t.url}`);const p=["url"];if(!t||!$(t,p)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${T(t,p)} before fetchCalendarObjects`)}const f=null!=a?a:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VEVENT"},...s?{"time-range":{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}];let m=[];const A=(null!=r?r:(m=await q({url:t.url,props:{[`${n.DAV}:getetag`]:{},...c&&s?{[`${n.CALDAV}:calendar-data`]:{[`${n.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}}:{}},filters:f,depth:"1",headers:v(o,h),fetchOptions:l,fetch:u})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(d).map(e=>new URL(e).pathname);let g=[];return A.length>0&&(g=c&&!r?m.filter(e=>{var r,a;const s=(null!==(r=e.href)&&void 0!==r?r:"").startsWith("http")?e.href:new URL(null!==(a=e.href)&&void 0!==a?a:"",t.url).href;return d(null!=s?s:"")}):i?await J({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CALDAV}:calendar-data`]:{...c&&s?{[`${n.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},objectUrls:A,depth:"1",headers:v(o,h),fetchOptions:l,fetch:u}):await q({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CALDAV}:calendar-data`]:{...c&&s?{[`${n.CALDAV}:expand`]:{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}},filters:f,depth:"1",headers:v(o,h),fetchOptions:l,fetch:u})),g.map(e=>{var r,a,s,o,n,c;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(a=e.props)||void 0===a?void 0:a.getetag}`,data:null!==(n=null===(o=null===(s=e.props)||void 0===s?void 0:s.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==n?n:null===(c=e.props)||void 0===c?void 0:c.calendarData}})},X=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={},fetch:c}=e;return w({url:new URL(a,t.url).href,data:r,headers:v({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n,fetch:c})},ee=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return b({url:t.url,data:t.data,etag:t.etag,headers:v({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},te=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:v(r,a),fetchOptions:s,fetch:o})},re=async e=>{var t;const{oldCalendars:r,account:a,detailedResult:s,headers:o,headersToExclude:n,fetchOptions:c={},fetch:d}=e;if(!a)throw new Error("Must have account before syncCalendars");const i=null!==(t=null!=r?r:a.calendars)&&void 0!==t?t:[],h=await K({account:a,headers:v(o,n),fetchOptions:c,fetch:d}),u=h.filter(e=>i.every(t=>!l(t.url,e.url)));G(`new calendars: ${u.map(e=>e.displayName)}`);const p=i.reduce((e,t)=>{const r=h.find(e=>l(e.url,t.url));return r&&(r.syncToken&&`${r.syncToken}`!=`${t.syncToken}`||r.ctag&&`${r.ctag}`!=`${t.ctag}`)?[...e,r]:e},[]);G(`updated calendars: ${p.map(e=>e.displayName)}`);const f=await Promise.all(p.map(async e=>await x({collection:{...e,objectMultiGet:J},method:"webdav",headers:v(o,n),account:a,fetchOptions:c,fetch:d}))),O=i.filter(e=>h.every(t=>!l(t.url,e.url)));G(`deleted calendars: ${O.map(e=>e.displayName)}`);const y=i.filter(e=>h.some(t=>l(t.url,e.url)&&(t.syncToken&&`${t.syncToken}`!=`${e.syncToken}`||t.ctag&&`${t.ctag}`!=`${e.ctag}`)));return s?{created:u,updated:p,deleted:O}:[...y,...u,...f]},ae=async e=>{const{url:t,timeRange:r,depth:a,headers:o,headersToExclude:c,fetchOptions:d={},fetch:i}=e;if(!r)throw new Error("timeRange is required");y(r.start,r.end);return(await k({url:t,body:{"free-busy-query":p({_attributes:u([s.CALDAV]),[`${n.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:n.CALDAV,depth:a,headers:v(o,c),fetchOptions:d,fetch:i}))[0]};var se=Object.freeze({__proto__:null,calendarMultiGet:J,calendarQuery:q,createCalendarObject:X,deleteCalendarObject:te,fetchCalendarObjects:Y,fetchCalendarUserAddresses:Q,fetchCalendars:K,freeBusyQuery:ae,makeCalendar:W,syncCalendars:re,updateCalendarObject:ee});const oe=e("tsdav:account"),ne=async e=>{var t,r;oe("Service discovery...");const{account:a,headers:s,headersToExclude:o,fetchOptions:n={},fetch:c}=e,i=null!=c?c:d,h=new URL(a.serverUrl),l=new URL(`/.well-known/${a.accountType}`,h);l.protocol=null!==(t=h.protocol)&&void 0!==t?t:"http";try{const e=await i(l.href,{headers:{...v(s,o),"Content-Type":"text/xml;charset=UTF-8"},method:"PROPFIND",body:'\n\n \n \n \n',redirect:"manual",...n});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){oe(`Service discovery redirected to ${t}`);const e=new URL(t,h);return e.hostname===l.hostname&&l.port&&!e.port&&(e.port=l.port),e.protocol=null!==(r=h.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){oe(`Service discovery failed: ${e.stack}`)}return h.href},ce=async e=>{var t,r,a,s,o;const{account:c,headers:d,headersToExclude:i,fetchOptions:h={},fetch:l}=e,u=["rootUrl"];if(!$(c,u))throw new Error(`account must have ${T(c,u)} before fetchPrincipalUrl`);oe(`Fetching principal url from path ${c.rootUrl}`);const[p]=await D({url:c.rootUrl,props:{[`${n.DAV}:current-user-principal`]:{}},depth:"0",headers:v(d,i),fetchOptions:h,fetch:l});if(!p.ok&&(oe(`Fetch principal url failed: ${p.statusText}`),401===p.status))throw new Error("Invalid credentials");return oe(`Fetched principal url ${null===(r=null===(t=p.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(o=null===(s=null===(a=p.props)||void 0===a?void 0:a.currentUserPrincipal)||void 0===s?void 0:s.href)&&void 0!==o?o:"",c.rootUrl).href},de=async e=>{var t,r;const{account:a,headers:s,headersToExclude:o,fetchOptions:c={},fetch:d}=e,i=["principalUrl","rootUrl"];if(!$(a,i))throw new Error(`account must have ${T(a,i)} before fetchHomeUrl`);oe(`Fetch home url from ${a.principalUrl}`);const h=await D({url:a.principalUrl,props:"caldav"===a.accountType?{[`${n.CALDAV}:calendar-home-set`]:{}}:{[`${n.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:v(s,o),fetchOptions:c,fetch:d}),u=h.find(e=>l(a.principalUrl,e.href));if(!u||!u.ok)throw oe(`Fetch home url failed with status ${null==u?void 0:u.statusText} and error ${JSON.stringify(h.map(e=>e.error))}`),new Error("cannot find homeUrl");const p=new URL("caldav"===a.accountType?null===(t=null==u?void 0:u.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==u?void 0:u.props)||void 0===r?void 0:r.addressbookHomeSet.href,a.rootUrl).href;return oe(`Fetched home url ${p}`),p},ie=async e=>{const{account:t,headers:r,loadCollections:a=!1,loadObjects:s=!1,headersToExclude:o,fetchOptions:n={},fetch:c}=e,d={...t};return d.rootUrl=await ne({account:t,headers:v(r,o),fetchOptions:n,fetch:c}),d.principalUrl=await ce({account:d,headers:v(r,o),fetchOptions:n,fetch:c}),d.homeUrl=await de({account:d,headers:v(r,o),fetchOptions:n,fetch:c}),(a||s)&&("caldav"===t.accountType?d.calendars=await K({headers:v(r,o),account:d,fetchOptions:n,fetch:c}):"carddav"===t.accountType&&(d.addressBooks=await P({headers:v(r,o),account:d,fetchOptions:n,fetch:c}))),s&&("caldav"===t.accountType&&d.calendars?d.calendars=await Promise.all(d.calendars.map(async e=>({...e,objects:await Y({calendar:e,headers:v(r,o),fetchOptions:n,fetch:c})}))):"carddav"===t.accountType&&d.addressBooks&&(d.addressBooks=await Promise.all(d.addressBooks.map(async e=>({...e,objects:await B({addressBook:e,headers:v(r,o),fetchOptions:n,fetch:c})}))))),d};var he=Object.freeze({__proto__:null,createAccount:ie,fetchHomeUrl:de,fetchPrincipalUrl:ce,serviceDiscovery:ne});const le=e("tsdav:todo"),ue=e=>({[`${n.CALDAV}:expand`]:{_attributes:{start:`${new Date(e.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(e.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}),pe=async e=>{const{url:t,props:r,filters:a,timezone:o,depth:c,headers:d,headersToExclude:i,fetchOptions:h={},fetch:l}=e;return k({url:t,body:{"calendar-query":p({_attributes:u([s.CALDAV,s.CALENDAR_SERVER,s.CALDAV_APPLE,s.DAV]),[`${n.DAV}:prop`]:r,filter:a,timezone:o})},defaultNamespace:n.CALDAV,depth:c,headers:v(d,i),fetchOptions:h,fetch:l})},fe=async e=>{const{url:t,props:r,objectUrls:a,filters:o,timezone:c,depth:d,headers:i,headersToExclude:h,fetchOptions:l={},fetch:f}=e;return k({url:t,body:{"calendar-multiget":p({_attributes:u([s.DAV,s.CALDAV]),[`${n.DAV}:prop`]:r,[`${n.DAV}:href`]:a,filter:o,timezone:c})},defaultNamespace:n.CALDAV,depth:d,headers:v(i,h),fetchOptions:l,fetch:f})},ve=async e=>{const{calendar:t,objectUrls:r,filters:a,timeRange:s,headers:o,expand:c,urlFilter:d=O,useMultiGet:i=!0,headersToExclude:h,fetchOptions:l={},fetch:u}=e;s&&y(s.start,s.end),le(`Fetching todo objects from ${null==t?void 0:t.url}`);const p=["url"];if(!t||!$(t,p)){if(!t)throw new Error("cannot fetchTodos for undefined calendar");throw new Error(`calendar must have ${T(t,p)} before fetchTodos`)}const f=null!=a?a:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":{_attributes:{name:"VTODO"},...s?{"time-range":{_attributes:{start:`${new Date(s.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(s.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{}}}}],m=(null!=r?r:(await pe({url:t.url,props:{[`${n.DAV}:getetag`]:{...c&&s?ue(s):{}}},filters:f,depth:"1",headers:v(o,h),fetchOptions:l,fetch:u})).map(e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""})).map(e=>e.startsWith("http")||!e?e:new URL(e,t.url).href).filter(d).map(e=>new URL(e).pathname);let A=[];return m.length>0&&(A=!i||c?await pe({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CALDAV}:calendar-data`]:{...c&&s?ue(s):{}}},filters:f,depth:"1",headers:v(o,h),fetchOptions:l,fetch:u}):await fe({url:t.url,props:{[`${n.DAV}:getetag`]:{},[`${n.CALDAV}:calendar-data`]:{...c&&s?ue(s):{}}},objectUrls:m,depth:"1",headers:v(o,h),fetchOptions:l,fetch:u})),A.map(e=>{var r,a,s,o,n,c;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(a=e.props)||void 0===a?void 0:a.getetag}`,data:null!==(n=null===(o=null===(s=e.props)||void 0===s?void 0:s.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==n?n:null===(c=e.props)||void 0===c?void 0:c.calendarData}})},Oe=async e=>{const{calendar:t,iCalString:r,filename:a,headers:s,headersToExclude:o,fetchOptions:n={},fetch:c}=e;if(!r.includes("UID:"))throw new Error("iCalString must contain a UID");return w({url:new URL(a,t.url).href,data:r,headers:v({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*",...s},o),fetchOptions:n,fetch:c})},ye=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;if(!t.etag)throw new Error("calendarObject must have etag for update - fetch todo first");return b({url:t.url,data:t.data,etag:t.etag,headers:v({"content-type":"text/calendar; charset=utf-8",...r},a),fetchOptions:s,fetch:o})},me=async e=>{const{calendarObject:t,headers:r,headersToExclude:a,fetchOptions:s={},fetch:o}=e;return C({url:t.url,etag:t.etag,headers:v(r,a),fetchOptions:s,fetch:o})};var Ae=Object.freeze({__proto__:null,createTodo:Oe,deleteTodo:me,fetchTodos:ve,todoMultiGet:fe,todoQuery:pe,updateTodo:ye});const ge=e("tsdav:authHelper"),De=(e,t)=>(...r)=>e({...t,...r[0]}),we=e=>(ge(`Basic auth token generated: ${a(`${e.username}:${e.password}`)}`),{authorization:`Basic ${a(`${e.username}:${e.password}`)}`}),be=e=>({authorization:`Bearer ${e.accessToken}`}),Ce=async(e,t,r)=>{const a=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!$(e,a))throw new Error(`Oauth credentials missing: ${T(e,a)}`);const s=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ge(e.tokenUrl),ge(s.toString());const o=null!=r?r:d,n=await o(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"content-length":`${s.toString().length}`,"content-type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(n.ok){return await n.json()}return ge(`Fetch Oauth tokens failed: ${await n.text()}`),{}},Ve=async(e,t,r)=>{const a=["refreshToken","clientId","clientSecret","tokenUrl"];if(!$(e,a))throw new Error(`Oauth credentials missing: ${T(e,a)}`);const s=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),o=null!=r?r:d,n=await o(e.tokenUrl,{method:"POST",body:s.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},...null!=t?t:{}});if(n.ok){return await n.json()}return ge(`Refresh access token failed: ${await n.text()}`),{}},$e=async(e,t,r)=>{var a;ge("Fetching oauth headers");let s={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(a=e.expiration)&&void 0!==a?a:0))&&(s=await Ve(e,t,r)):s=await Ce(e,t,r),ge(`Oauth tokens fetched: ${s.access_token}`),{tokens:s,headers:{authorization:`Bearer ${s.access_token}`}}};var Te=Object.freeze({__proto__:null,defaultParam:De,fetchOauthTokens:Ce,getBasicAuthHeaders:we,getBearerAuthHeaders:be,getOauthHeaders:$e,refreshAccessToken:Ve});const Ee=async e=>{var t;const{serverUrl:r,credentials:a,authMethod:s,defaultAccountType:o,authFunction:n,fetch:c}=e;let d={};switch(s){case"Basic":d=we(a);break;case"Bearer":d=be(a);break;case"Oauth":d=(await $e(a,void 0,c)).headers;break;case"Digest":d={Authorization:`Digest ${a.digestString}`};break;case"Custom":d=null!==(t=await(null==n?void 0:n(a)))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const i=o?await ie({account:{serverUrl:r,credentials:a,accountType:o},headers:d,fetch:c}):void 0,h=De(w,{url:r,headers:d,fetch:c}),l=De(b,{headers:d,url:r,fetch:c}),u=De(C,{headers:d,url:r,fetch:c}),p=De(D,{headers:d,fetch:c}),f=De(k,{headers:d,fetch:c}),v=De(_,{headers:d,fetch:c}),O=De(L,{headers:d,fetch:c}),y=De(U,{headers:d,fetch:c}),m=De(R,{headers:d,fetch:c}),A=De(x,{headers:d,account:i,fetch:c}),V=De(q,{headers:d,fetch:c}),$=De(J,{headers:d,fetch:c}),T=De(W,{headers:d,fetch:c}),E=De(K,{headers:d,account:i,fetch:c}),S=De(Q,{headers:d,account:i,fetch:c}),j=De(Y,{headers:d,fetch:c}),Z=De(X,{headers:d,fetch:c}),G=De(ee,{headers:d,fetch:c}),ae=De(te,{headers:d,fetch:c}),se=De(re,{account:i,headers:d,fetch:c}),oe=De(H,{headers:d,fetch:c}),ne=De(N,{headers:d,fetch:c}),ce=De(z,{headers:d,fetch:c});return{davRequest:async e=>{const{init:t,fetch:r,...a}=e,{headers:s,...o}=t;return g({...a,init:{...o,headers:{...d,...s}},fetch:null!=r?r:c})},propfind:p,createAccount:async e=>{const{account:t,headers:s,loadCollections:o,loadObjects:n,fetch:i}=e;return ie({account:{serverUrl:r,credentials:a,...t},headers:{...d,...s},loadCollections:o,loadObjects:n,fetch:null!=i?i:c})},createObject:h,updateObject:l,deleteObject:u,calendarQuery:V,addressBookQuery:oe,collectionQuery:f,makeCollection:v,calendarMultiGet:$,makeCalendar:T,syncCollection:O,supportedReportSet:y,isCollectionDirty:m,smartCollectionSync:A,fetchCalendars:E,fetchCalendarUserAddresses:S,fetchCalendarObjects:j,createCalendarObject:Z,updateCalendarObject:G,deleteCalendarObject:ae,syncCalendars:se,fetchAddressBooks:De(P,{account:i,headers:d,fetch:c}),addressBookMultiGet:ne,makeAddressBook:ce,fetchVCards:De(B,{headers:d,fetch:c}),createVCard:De(I,{headers:d,fetch:c}),updateVCard:De(F,{headers:d,fetch:c}),deleteVCard:De(M,{headers:d,fetch:c}),todoQuery:De(pe,{headers:d,fetch:c}),todoMultiGet:De(fe,{headers:d,fetch:c}),fetchTodos:De(ve,{headers:d,fetch:c}),createTodo:De(Oe,{headers:d,fetch:c}),updateTodo:De(ye,{headers:d,fetch:c}),deleteTodo:De(me,{headers:d,fetch:c})}};class ke{constructor(e){var t,r,a;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav",this.authFunction=e.authFunction,this.fetchOptions=null!==(a=e.fetchOptions)&&void 0!==a?a:{},this.fetchOverride=e.fetch}async login(){var e;switch(this.authMethod){case"Basic":this.authHeaders=we(this.credentials);break;case"Bearer":this.authHeaders=be(this.credentials);break;case"Oauth":this.authHeaders=(await $e(this.credentials,this.fetchOptions,this.fetchOverride)).headers;break;case"Digest":this.authHeaders={Authorization:`Digest ${this.credentials.digestString}`};break;case"Custom":this.authHeaders=await(null===(e=this.authFunction)||void 0===e?void 0:e.call(this,this.credentials));break;default:throw new Error("Invalid auth method")}this.account=this.accountType?await ie({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride}):void 0}async davRequest(e){const{init:t,fetch:r,...a}=e,{headers:s,...o}=t;return g({...a,init:{...o,headers:{...this.authHeaders,...s}},fetchOptions:this.fetchOptions,fetch:null!=r?r:this.fetchOverride})}async createObject(...e){return De(w,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateObject(...e){return De(b,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteObject(...e){return De(C,{url:this.serverUrl,headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async propfind(...e){return De(D,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createAccount(e){const{account:t,headers:r,loadCollections:a,loadObjects:s,fetchOptions:o,fetch:n}=e;return ie({account:{serverUrl:this.serverUrl,credentials:this.credentials,...t},headers:{...this.authHeaders,...r},loadCollections:a,loadObjects:s,fetchOptions:null!=o?o:this.fetchOptions,fetch:null!=n?n:this.fetchOverride})}async collectionQuery(...e){return De(k,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCollection(...e){return De(_,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCollection(...e){return De(L,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async supportedReportSet(...e){return De(U,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async isCollectionDirty(...e){return De(R,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async smartCollectionSync(...e){return De(x,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride,account:this.account})(e[0])}async calendarQuery(...e){return De(q,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeCalendar(...e){return De(W,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async calendarMultiGet(...e){return De(J,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchCalendars(...e){return De(K,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarUserAddresses(...e){return De(Q,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchCalendarObjects(...e){return De(Y,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createCalendarObject(...e){return De(X,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateCalendarObject(...e){return De(ee,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteCalendarObject(...e){return De(te,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async syncCalendars(...e){return De(re,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookQuery(...e){return De(H,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async addressBookMultiGet(...e){return De(N,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async makeAddressBook(...e){return De(z,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchAddressBooks(...e){return De(P,{headers:this.authHeaders,account:this.account,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(null==e?void 0:e[0])}async fetchVCards(...e){return De(B,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createVCard(...e){return De(I,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateVCard(...e){return De(F,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteVCard(...e){return De(M,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async todoQuery(...e){return De(pe,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async todoMultiGet(...e){return De(fe,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async fetchTodos(...e){return De(ve,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async createTodo(...e){return De(Oe,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async updateTodo(...e){return De(ye,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}async deleteTodo(...e){return De(me,{headers:this.authHeaders,fetchOptions:this.fetchOptions,fetch:this.fetchOverride})(e[0])}}var _e={DAVNamespace:s,DAVNamespaceShort:n,DAVAttributeMap:o,...Object.freeze({__proto__:null,DAVClient:ke,createDAVClient:Ee}),...V,...S,...he,...Z,...se,...Ae,...Te,...m};export{o as DAVAttributeMap,ke as DAVClient,s as DAVNamespace,n as DAVNamespaceShort,N as addressBookMultiGet,H as addressBookQuery,J as calendarMultiGet,q as calendarQuery,p as cleanupFalsy,k as collectionQuery,ie as createAccount,X as createCalendarObject,Ee as createDAVClient,w as createObject,Oe as createTodo,I as createVCard,g as davRequest,_e as default,te as deleteCalendarObject,C as deleteObject,me as deleteTodo,M as deleteVCard,P as fetchAddressBooks,Y as fetchCalendarObjects,Q as fetchCalendarUserAddresses,K as fetchCalendars,Ce as fetchOauthTokens,ve as fetchTodos,B as fetchVCards,ae as freeBusyQuery,we as getBasicAuthHeaders,be as getBearerAuthHeaders,u as getDAVAttribute,$e as getOauthHeaders,R as isCollectionDirty,z as makeAddressBook,W as makeCalendar,D as propfind,Ve as refreshAccessToken,x as smartCollectionSync,U as supportedReportSet,re as syncCalendars,L as syncCollection,fe as todoMultiGet,pe as todoQuery,ee as updateCalendarObject,b as updateObject,ye as updateTodo,F as updateVCard,l as urlContains,h as urlEquals}; diff --git a/dist/tsdav.mjs b/dist/tsdav.mjs index 60d7c359..fe4cb9e5 100644 --- a/dist/tsdav.mjs +++ b/dist/tsdav.mjs @@ -1508,10 +1508,11 @@ const buildExpandProp = (timeRange) => ({ * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoQuery = async (params) => { - const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -1531,6 +1532,7 @@ const todoQuery = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1545,10 +1547,11 @@ const todoQuery = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ const todoMultiGet = async (params) => { - const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, } = params; + const { url, props, objectUrls, filters, timezone, depth, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return collectionQuery({ url, body: { @@ -1564,6 +1567,7 @@ const todoMultiGet = async (params) => { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1579,11 +1583,12 @@ const todoMultiGet = async (params) => { * @param params.headersToExclude - Headers to exclude * @param params.useMultiGet - Whether to use multiget (default: true) * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of todo objects with url, etag, and iCalendar data * @throws Error if calendar URL is missing or timeRange format is invalid */ const fetchTodos = async (params) => { - const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, } = params; + const { calendar, objectUrls, filters: customFilters, timeRange, headers, expand, urlFilter = defaultIcsFilter, useMultiGet = true, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (timeRange) { validateISO8601TimeRange(timeRange.start, timeRange.end); } @@ -1640,6 +1645,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, })).map((res) => { var _a; return (_a = res.href) !== null && _a !== void 0 ? _a : ''; })) .map((url) => (url.startsWith('http') || !url ? url : new URL(url, calendar.url).href)) .filter(urlFilter) @@ -1659,6 +1665,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } else { @@ -1674,6 +1681,7 @@ const fetchTodos = async (params) => { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } } @@ -1695,11 +1703,12 @@ const fetchTodos = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if iCalString does not contain a UID */ const createTodo = async (params) => { - const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!iCalString.includes('UID:')) { throw new Error('iCalString must contain a UID'); } @@ -1712,6 +1721,7 @@ const createTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1721,11 +1731,12 @@ const createTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if calendarObject does not have an etag */ const updateTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; if (!calendarObject.etag) { throw new Error('calendarObject must have etag for update - fetch todo first'); } @@ -1738,6 +1749,7 @@ const updateTodo = async (params) => { ...headers, }, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; /** @@ -1747,15 +1759,17 @@ const updateTodo = async (params) => { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server */ const deleteTodo = async (params) => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { calendarObject, headers, headersToExclude, fetchOptions = {}, fetch: fetchOverride, } = params; return deleteObject({ url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; @@ -2073,12 +2087,30 @@ const createDAVClient = async (params) => { fetch: fetchOverride, }); // todo - const todoQuery$1 = defaultParam(todoQuery, { headers: authHeaders }); - const todoMultiGet$1 = defaultParam(todoMultiGet, { headers: authHeaders }); - const fetchTodos$1 = defaultParam(fetchTodos, { headers: authHeaders }); - const createTodo$1 = defaultParam(createTodo, { headers: authHeaders }); - const updateTodo$1 = defaultParam(updateTodo, { headers: authHeaders }); - const deleteTodo$1 = defaultParam(deleteTodo, { headers: authHeaders }); + const todoQuery$1 = defaultParam(todoQuery, { + headers: authHeaders, + fetch: fetchOverride, + }); + const todoMultiGet$1 = defaultParam(todoMultiGet, { + headers: authHeaders, + fetch: fetchOverride, + }); + const fetchTodos$1 = defaultParam(fetchTodos, { + headers: authHeaders, + fetch: fetchOverride, + }); + const createTodo$1 = defaultParam(createTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const updateTodo$1 = defaultParam(updateTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const deleteTodo$1 = defaultParam(deleteTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); return { davRequest: davRequest$1, propfind: propfind$1, @@ -2397,22 +2429,46 @@ class DAVClient { })(params[0]); } async todoQuery(...params) { - return defaultParam(todoQuery, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoQuery, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async todoMultiGet(...params) { - return defaultParam(todoMultiGet, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(todoMultiGet, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async fetchTodos(...params) { - return defaultParam(fetchTodos, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(fetchTodos, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async createTodo(...params) { - return defaultParam(createTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(createTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async updateTodo(...params) { - return defaultParam(updateTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(updateTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async deleteTodo(...params) { - return defaultParam(deleteTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(deleteTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } } diff --git a/package.json b/package.json index 06ef653f..8c867c3c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tsdav", - "version": "2.3.2", + "version": "2.3.3", "description": "WebDAV, CALDAV, and CARDDAV client for Nodejs and the Browser", "keywords": [ "dav", diff --git a/src/client.ts b/src/client.ts index 48a9bb01..6cec2299 100644 --- a/src/client.ts +++ b/src/client.ts @@ -290,12 +290,30 @@ export const createDAVClient = async (params: { }); // todo - const todoQuery = defaultParam(rawTodoQuery, { headers: authHeaders }); - const todoMultiGet = defaultParam(rawTodoMultiGet, { headers: authHeaders }); - const fetchTodos = defaultParam(rawFetchTodos, { headers: authHeaders }); - const createTodo = defaultParam(rawCreateTodo, { headers: authHeaders }); - const updateTodo = defaultParam(rawUpdateTodo, { headers: authHeaders }); - const deleteTodo = defaultParam(rawDeleteTodo, { headers: authHeaders }); + const todoQuery = defaultParam(rawTodoQuery, { + headers: authHeaders, + fetch: fetchOverride, + }); + const todoMultiGet = defaultParam(rawTodoMultiGet, { + headers: authHeaders, + fetch: fetchOverride, + }); + const fetchTodos = defaultParam(rawFetchTodos, { + headers: authHeaders, + fetch: fetchOverride, + }); + const createTodo = defaultParam(rawCreateTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const updateTodo = defaultParam(rawUpdateTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); + const deleteTodo = defaultParam(rawDeleteTodo, { + headers: authHeaders, + fetch: fetchOverride, + }); return { davRequest, @@ -742,26 +760,50 @@ export class DAVClient { } async todoQuery(...params: Parameters): Promise { - return defaultParam(rawTodoQuery, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(rawTodoQuery, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async todoMultiGet(...params: Parameters): Promise { - return defaultParam(rawTodoMultiGet, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(rawTodoMultiGet, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async fetchTodos(...params: Parameters): Promise { - return defaultParam(rawFetchTodos, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(rawFetchTodos, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async createTodo(...params: Parameters): Promise { - return defaultParam(rawCreateTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(rawCreateTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async updateTodo(...params: Parameters): Promise { - return defaultParam(rawUpdateTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(rawUpdateTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } async deleteTodo(...params: Parameters): Promise { - return defaultParam(rawDeleteTodo, { headers: this.authHeaders, fetchOptions: this.fetchOptions })(params[0]); + return defaultParam(rawDeleteTodo, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); } } diff --git a/src/todo.ts b/src/todo.ts index 226cbb6b..b1c9e418 100644 --- a/src/todo.ts +++ b/src/todo.ts @@ -41,6 +41,7 @@ const buildExpandProp = (timeRange: { start: string; end: string }): ElementComp * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ export const todoQuery = async (params: { @@ -52,6 +53,7 @@ export const todoQuery = async (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }): Promise => { const { url, @@ -62,6 +64,7 @@ export const todoQuery = async (params: { headers, headersToExclude, fetchOptions = {}, + fetch: fetchOverride, } = params; return collectionQuery({ url, @@ -82,6 +85,7 @@ export const todoQuery = async (params: { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; @@ -97,6 +101,7 @@ export const todoQuery = async (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of DAV responses */ export const todoMultiGet = async (params: { @@ -109,6 +114,7 @@ export const todoMultiGet = async (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }): Promise => { const { url, @@ -120,6 +126,7 @@ export const todoMultiGet = async (params: { headers, headersToExclude, fetchOptions = {}, + fetch: fetchOverride, } = params; return collectionQuery({ url, @@ -136,6 +143,7 @@ export const todoMultiGet = async (params: { depth, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; @@ -152,6 +160,7 @@ export const todoMultiGet = async (params: { * @param params.headersToExclude - Headers to exclude * @param params.useMultiGet - Whether to use multiget (default: true) * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Array of todo objects with url, etag, and iCalendar data * @throws Error if calendar URL is missing or timeRange format is invalid */ @@ -166,6 +175,7 @@ export const fetchTodos = async (params: { headersToExclude?: string[]; useMultiGet?: boolean; fetchOptions?: RequestInit; + fetch?: typeof fetch; }): Promise => { const { calendar, @@ -178,6 +188,7 @@ export const fetchTodos = async (params: { useMultiGet = true, headersToExclude, fetchOptions = {}, + fetch: fetchOverride, } = params; if (timeRange) { @@ -246,6 +257,7 @@ export const fetchTodos = async (params: { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }) ).map((res) => res.href ?? '') ) @@ -269,6 +281,7 @@ export const fetchTodos = async (params: { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } else { todoObjectResults = await todoMultiGet({ @@ -283,6 +296,7 @@ export const fetchTodos = async (params: { depth: '1', headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); } } @@ -303,6 +317,7 @@ export const fetchTodos = async (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if iCalString does not contain a UID */ @@ -313,8 +328,17 @@ export const createTodo = async (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }): Promise => { - const { calendar, iCalString, filename, headers, headersToExclude, fetchOptions = {} } = params; + const { + calendar, + iCalString, + filename, + headers, + headersToExclude, + fetchOptions = {}, + fetch: fetchOverride, + } = params; if (!iCalString.includes('UID:')) { throw new Error('iCalString must contain a UID'); @@ -332,6 +356,7 @@ export const createTodo = async (params: { headersToExclude, ), fetchOptions, + fetch: fetchOverride, }); }; @@ -342,6 +367,7 @@ export const createTodo = async (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server * @throws Error if calendarObject does not have an etag */ @@ -350,8 +376,15 @@ export const updateTodo = async (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }): Promise => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { + calendarObject, + headers, + headersToExclude, + fetchOptions = {}, + fetch: fetchOverride, + } = params; if (!calendarObject.etag) { throw new Error('calendarObject must have etag for update - fetch todo first'); @@ -369,6 +402,7 @@ export const updateTodo = async (params: { headersToExclude, ), fetchOptions, + fetch: fetchOverride, }); }; @@ -379,6 +413,7 @@ export const updateTodo = async (params: { * @param params.headers - Request headers * @param params.headersToExclude - Headers to exclude * @param params.fetchOptions - Fetch options + * @param params.fetch - Optional fetch implementation to use instead of the default * @returns Response from the server */ export const deleteTodo = async (params: { @@ -386,12 +421,20 @@ export const deleteTodo = async (params: { headers?: Record; headersToExclude?: string[]; fetchOptions?: RequestInit; + fetch?: typeof fetch; }): Promise => { - const { calendarObject, headers, headersToExclude, fetchOptions = {} } = params; + const { + calendarObject, + headers, + headersToExclude, + fetchOptions = {}, + fetch: fetchOverride, + } = params; return deleteObject({ url: calendarObject.url, etag: calendarObject.etag, headers: excludeHeaders(headers, headersToExclude), fetchOptions, + fetch: fetchOverride, }); }; From 10b5b3afd163b2ec47b1f7f704431ed82cefc821 Mon Sep 17 00:00:00 2001 From: PhilflowIO Date: Fri, 14 Aug 2026 21:43:54 +0200 Subject: [PATCH 2/2] test(caldav): cover todo fetch override Ten tests across three independently reverted halves. todo.test.ts follows calendar.test.ts: mock ./request only, let the real collectionQuery run through to davRequest, and assert each of the six functions forwards the override -- plus that it stays undefined when none is given. Reverting the todo.ts threading fails six of the seven. client.test.ts extends the existing fetch-override describe with fetchTodos and createTodo. Reverting the class wiring fails the two DAVClient cases while the createDAVClient one still passes; reverting the factory wiring fails only the createDAVClient one. --- src/__tests__/unit/client.test.ts | 66 ++++++++++++++++++++++ src/__tests__/unit/todo.test.ts | 93 +++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+) create mode 100644 src/__tests__/unit/todo.test.ts diff --git a/src/__tests__/unit/client.test.ts b/src/__tests__/unit/client.test.ts index 3a193259..32576728 100644 --- a/src/__tests__/unit/client.test.ts +++ b/src/__tests__/unit/client.test.ts @@ -101,4 +101,70 @@ describe('DAVClient fetch override', () => { expect(mockFetch).toHaveBeenCalled(); }); + + it('DAVClient should use fetch override in fetchTodos', async () => { + const mockFetch = jest.fn().mockResolvedValue({ + ok: true, + status: 200, + text: jest.fn().mockResolvedValue(''), + headers: new Map(), + }); + + const client = new DAVClient({ + serverUrl: 'http://example.com', + credentials: mockCredentials, + fetch: mockFetch, + }); + + await client.fetchTodos({ + calendar: { url: 'http://example.com/cal/' }, + }); + + expect(mockFetch).toHaveBeenCalled(); + }); + + it('createDAVClient should use fetch override in fetchTodos', async () => { + const mockFetch = jest.fn().mockResolvedValue({ + ok: true, + status: 200, + text: jest.fn().mockResolvedValue(''), + headers: new Map(), + }); + + const client = await createDAVClient({ + serverUrl: 'http://example.com', + credentials: mockCredentials, + authMethod: 'Basic', + fetch: mockFetch, + }); + + await client.fetchTodos({ + calendar: { url: 'http://example.com/cal/' }, + }); + + expect(mockFetch).toHaveBeenCalled(); + }); + + it('DAVClient should use fetch override in createTodo', async () => { + const mockFetch = jest.fn().mockResolvedValue({ + ok: true, + status: 200, + text: jest.fn().mockResolvedValue(''), + headers: new Map(), + }); + + const client = new DAVClient({ + serverUrl: 'http://example.com', + credentials: mockCredentials, + fetch: mockFetch, + }); + + await client.createTodo({ + calendar: { url: 'http://example.com/cal/' }, + iCalString: 'BEGIN:VCALENDAR\nBEGIN:VTODO\nUID:1\nEND:VTODO\nEND:VCALENDAR', + filename: '1.ics', + }); + + expect(mockFetch).toHaveBeenCalled(); + }); }); diff --git a/src/__tests__/unit/todo.test.ts b/src/__tests__/unit/todo.test.ts new file mode 100644 index 00000000..94a888c9 --- /dev/null +++ b/src/__tests__/unit/todo.test.ts @@ -0,0 +1,93 @@ +import * as request from '../../request'; +import { + createTodo, + deleteTodo, + fetchTodos, + todoMultiGet, + todoQuery, + updateTodo, +} from '../../todo'; + +jest.mock('../../request'); + +const mockedDavRequest = request.davRequest as jest.MockedFunction; +const mockedCreateObject = request.createObject as jest.MockedFunction; +const mockedUpdateObject = request.updateObject as jest.MockedFunction; +const mockedDeleteObject = request.deleteObject as jest.MockedFunction; + +describe('todo fetch override', () => { + const customFetch = jest.fn() as unknown as typeof fetch; + + beforeEach(() => { + jest.clearAllMocks(); + mockedDavRequest.mockResolvedValue([]); + }); + + it('todoQuery should forward a custom fetch to davRequest', async () => { + await todoQuery({ + url: 'http://example.com/cal/', + props: {}, + fetch: customFetch, + }); + + expect(mockedDavRequest.mock.calls[0][0].fetch).toBe(customFetch); + }); + + it('todoMultiGet should forward a custom fetch to davRequest', async () => { + await todoMultiGet({ + url: 'http://example.com/cal/', + props: {}, + depth: '1', + fetch: customFetch, + }); + + expect(mockedDavRequest.mock.calls[0][0].fetch).toBe(customFetch); + }); + + it('fetchTodos should forward a custom fetch through its internal query', async () => { + await fetchTodos({ + calendar: { url: 'http://example.com/cal/' }, + fetch: customFetch, + }); + + expect(mockedDavRequest).toHaveBeenCalled(); + mockedDavRequest.mock.calls.forEach((call) => { + expect(call[0].fetch).toBe(customFetch); + }); + }); + + it('createTodo should forward a custom fetch to createObject', async () => { + await createTodo({ + calendar: { url: 'http://example.com/cal/' }, + iCalString: 'BEGIN:VCALENDAR\nBEGIN:VTODO\nUID:1\nEND:VTODO\nEND:VCALENDAR', + filename: '1.ics', + fetch: customFetch, + }); + + expect(mockedCreateObject.mock.calls[0][0].fetch).toBe(customFetch); + }); + + it('updateTodo should forward a custom fetch to updateObject', async () => { + await updateTodo({ + calendarObject: { url: 'http://example.com/cal/1.ics', etag: '"1"', data: '' }, + fetch: customFetch, + }); + + expect(mockedUpdateObject.mock.calls[0][0].fetch).toBe(customFetch); + }); + + it('deleteTodo should forward a custom fetch to deleteObject', async () => { + await deleteTodo({ + calendarObject: { url: 'http://example.com/cal/1.ics', etag: '"1"', data: '' }, + fetch: customFetch, + }); + + expect(mockedDeleteObject.mock.calls[0][0].fetch).toBe(customFetch); + }); + + it('should leave fetch undefined when no override is given', async () => { + await todoQuery({ url: 'http://example.com/cal/', props: {} }); + + expect(mockedDavRequest.mock.calls[0][0].fetch).toBeUndefined(); + }); +});